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.

279620 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 int32 value)
  2046. : numValues (4),
  2047. highestBit (31),
  2048. negative (value < 0)
  2049. {
  2050. values.calloc (numValues + 1);
  2051. values[0] = abs (value);
  2052. highestBit = getHighestBit();
  2053. }
  2054. BigInteger::BigInteger (const uint32 value)
  2055. : numValues (4),
  2056. highestBit (31),
  2057. negative (false)
  2058. {
  2059. values.calloc (numValues + 1);
  2060. values[0] = value;
  2061. highestBit = getHighestBit();
  2062. }
  2063. BigInteger::BigInteger (int64 value)
  2064. : numValues (4),
  2065. highestBit (63),
  2066. negative (value < 0)
  2067. {
  2068. values.calloc (numValues + 1);
  2069. if (value < 0)
  2070. value = -value;
  2071. values[0] = (uint32) value;
  2072. values[1] = (uint32) (value >> 32);
  2073. highestBit = getHighestBit();
  2074. }
  2075. BigInteger::BigInteger (const BigInteger& other)
  2076. : numValues (jmax (4, bitToIndex (other.highestBit) + 1)),
  2077. highestBit (other.getHighestBit()),
  2078. negative (other.negative)
  2079. {
  2080. values.malloc (numValues + 1);
  2081. memcpy (values, other.values, sizeof (uint32) * (numValues + 1));
  2082. }
  2083. BigInteger::~BigInteger()
  2084. {
  2085. }
  2086. void BigInteger::swapWith (BigInteger& other) throw()
  2087. {
  2088. values.swapWith (other.values);
  2089. swapVariables (numValues, other.numValues);
  2090. swapVariables (highestBit, other.highestBit);
  2091. swapVariables (negative, other.negative);
  2092. }
  2093. BigInteger& BigInteger::operator= (const BigInteger& other)
  2094. {
  2095. if (this != &other)
  2096. {
  2097. highestBit = other.getHighestBit();
  2098. numValues = jmax (4, bitToIndex (highestBit) + 1);
  2099. negative = other.negative;
  2100. values.malloc (numValues + 1);
  2101. memcpy (values, other.values, sizeof (uint32) * (numValues + 1));
  2102. }
  2103. return *this;
  2104. }
  2105. void BigInteger::ensureSize (const int numVals)
  2106. {
  2107. if (numVals + 2 >= numValues)
  2108. {
  2109. int oldSize = numValues;
  2110. numValues = ((numVals + 2) * 3) / 2;
  2111. values.realloc (numValues + 1);
  2112. while (oldSize < numValues)
  2113. values [oldSize++] = 0;
  2114. }
  2115. }
  2116. bool BigInteger::operator[] (const int bit) const throw()
  2117. {
  2118. return bit <= highestBit && bit >= 0
  2119. && ((values [bitToIndex (bit)] & bitToMask (bit)) != 0);
  2120. }
  2121. int BigInteger::toInteger() const throw()
  2122. {
  2123. const int n = (int) (values[0] & 0x7fffffff);
  2124. return negative ? -n : n;
  2125. }
  2126. const BigInteger BigInteger::getBitRange (int startBit, int numBits) const
  2127. {
  2128. BigInteger r;
  2129. numBits = jmin (numBits, getHighestBit() + 1 - startBit);
  2130. r.ensureSize (bitToIndex (numBits));
  2131. r.highestBit = numBits;
  2132. int i = 0;
  2133. while (numBits > 0)
  2134. {
  2135. r.values[i++] = getBitRangeAsInt (startBit, jmin (32, numBits));
  2136. numBits -= 32;
  2137. startBit += 32;
  2138. }
  2139. r.highestBit = r.getHighestBit();
  2140. return r;
  2141. }
  2142. int BigInteger::getBitRangeAsInt (const int startBit, int numBits) const throw()
  2143. {
  2144. if (numBits > 32)
  2145. {
  2146. jassertfalse; // use getBitRange() if you need more than 32 bits..
  2147. numBits = 32;
  2148. }
  2149. numBits = jmin (numBits, highestBit + 1 - startBit);
  2150. if (numBits <= 0)
  2151. return 0;
  2152. const int pos = bitToIndex (startBit);
  2153. const int offset = startBit & 31;
  2154. const int endSpace = 32 - numBits;
  2155. uint32 n = ((uint32) values [pos]) >> offset;
  2156. if (offset > endSpace)
  2157. n |= ((uint32) values [pos + 1]) << (32 - offset);
  2158. return (int) (n & (((uint32) 0xffffffff) >> endSpace));
  2159. }
  2160. void BigInteger::setBitRangeAsInt (const int startBit, int numBits, uint32 valueToSet)
  2161. {
  2162. if (numBits > 32)
  2163. {
  2164. jassertfalse;
  2165. numBits = 32;
  2166. }
  2167. for (int i = 0; i < numBits; ++i)
  2168. {
  2169. setBit (startBit + i, (valueToSet & 1) != 0);
  2170. valueToSet >>= 1;
  2171. }
  2172. }
  2173. void BigInteger::clear()
  2174. {
  2175. if (numValues > 16)
  2176. {
  2177. numValues = 4;
  2178. values.calloc (numValues + 1);
  2179. }
  2180. else
  2181. {
  2182. zeromem (values, sizeof (uint32) * (numValues + 1));
  2183. }
  2184. highestBit = -1;
  2185. negative = false;
  2186. }
  2187. void BigInteger::setBit (const int bit)
  2188. {
  2189. if (bit >= 0)
  2190. {
  2191. if (bit > highestBit)
  2192. {
  2193. ensureSize (bitToIndex (bit));
  2194. highestBit = bit;
  2195. }
  2196. values [bitToIndex (bit)] |= bitToMask (bit);
  2197. }
  2198. }
  2199. void BigInteger::setBit (const int bit, const bool shouldBeSet)
  2200. {
  2201. if (shouldBeSet)
  2202. setBit (bit);
  2203. else
  2204. clearBit (bit);
  2205. }
  2206. void BigInteger::clearBit (const int bit) throw()
  2207. {
  2208. if (bit >= 0 && bit <= highestBit)
  2209. values [bitToIndex (bit)] &= ~bitToMask (bit);
  2210. }
  2211. void BigInteger::setRange (int startBit, int numBits, const bool shouldBeSet)
  2212. {
  2213. while (--numBits >= 0)
  2214. setBit (startBit++, shouldBeSet);
  2215. }
  2216. void BigInteger::insertBit (const int bit, const bool shouldBeSet)
  2217. {
  2218. if (bit >= 0)
  2219. shiftBits (1, bit);
  2220. setBit (bit, shouldBeSet);
  2221. }
  2222. bool BigInteger::isZero() const throw()
  2223. {
  2224. return getHighestBit() < 0;
  2225. }
  2226. bool BigInteger::isOne() const throw()
  2227. {
  2228. return getHighestBit() == 0 && ! negative;
  2229. }
  2230. bool BigInteger::isNegative() const throw()
  2231. {
  2232. return negative && ! isZero();
  2233. }
  2234. void BigInteger::setNegative (const bool neg) throw()
  2235. {
  2236. negative = neg;
  2237. }
  2238. void BigInteger::negate() throw()
  2239. {
  2240. negative = (! negative) && ! isZero();
  2241. }
  2242. int BigInteger::countNumberOfSetBits() const throw()
  2243. {
  2244. int total = 0;
  2245. for (int i = bitToIndex (highestBit) + 1; --i >= 0;)
  2246. {
  2247. uint32 n = values[i];
  2248. if (n == 0xffffffff)
  2249. {
  2250. total += 32;
  2251. }
  2252. else
  2253. {
  2254. while (n != 0)
  2255. {
  2256. total += (n & 1);
  2257. n >>= 1;
  2258. }
  2259. }
  2260. }
  2261. return total;
  2262. }
  2263. int BigInteger::getHighestBit() const throw()
  2264. {
  2265. for (int i = highestBit + 1; --i >= 0;)
  2266. if ((values [bitToIndex (i)] & bitToMask (i)) != 0)
  2267. return i;
  2268. return -1;
  2269. }
  2270. int BigInteger::findNextSetBit (int i) const throw()
  2271. {
  2272. for (; i <= highestBit; ++i)
  2273. if ((values [bitToIndex (i)] & bitToMask (i)) != 0)
  2274. return i;
  2275. return -1;
  2276. }
  2277. int BigInteger::findNextClearBit (int i) const throw()
  2278. {
  2279. for (; i <= highestBit; ++i)
  2280. if ((values [bitToIndex (i)] & bitToMask (i)) == 0)
  2281. break;
  2282. return i;
  2283. }
  2284. BigInteger& BigInteger::operator+= (const BigInteger& other)
  2285. {
  2286. if (other.isNegative())
  2287. return operator-= (-other);
  2288. if (isNegative())
  2289. {
  2290. if (compareAbsolute (other) < 0)
  2291. {
  2292. BigInteger temp (*this);
  2293. temp.negate();
  2294. *this = other;
  2295. operator-= (temp);
  2296. }
  2297. else
  2298. {
  2299. negate();
  2300. operator-= (other);
  2301. negate();
  2302. }
  2303. }
  2304. else
  2305. {
  2306. if (other.highestBit > highestBit)
  2307. highestBit = other.highestBit;
  2308. ++highestBit;
  2309. const int numInts = bitToIndex (highestBit) + 1;
  2310. ensureSize (numInts);
  2311. int64 remainder = 0;
  2312. for (int i = 0; i <= numInts; ++i)
  2313. {
  2314. if (i < numValues)
  2315. remainder += values[i];
  2316. if (i < other.numValues)
  2317. remainder += other.values[i];
  2318. values[i] = (uint32) remainder;
  2319. remainder >>= 32;
  2320. }
  2321. jassert (remainder == 0);
  2322. highestBit = getHighestBit();
  2323. }
  2324. return *this;
  2325. }
  2326. BigInteger& BigInteger::operator-= (const BigInteger& other)
  2327. {
  2328. if (other.isNegative())
  2329. return operator+= (-other);
  2330. if (! isNegative())
  2331. {
  2332. if (compareAbsolute (other) < 0)
  2333. {
  2334. BigInteger temp (other);
  2335. swapWith (temp);
  2336. operator-= (temp);
  2337. negate();
  2338. return *this;
  2339. }
  2340. }
  2341. else
  2342. {
  2343. negate();
  2344. operator+= (other);
  2345. negate();
  2346. return *this;
  2347. }
  2348. const int numInts = bitToIndex (highestBit) + 1;
  2349. const int maxOtherInts = bitToIndex (other.highestBit) + 1;
  2350. int64 amountToSubtract = 0;
  2351. for (int i = 0; i <= numInts; ++i)
  2352. {
  2353. if (i <= maxOtherInts)
  2354. amountToSubtract += (int64) other.values[i];
  2355. if (values[i] >= amountToSubtract)
  2356. {
  2357. values[i] = (uint32) (values[i] - amountToSubtract);
  2358. amountToSubtract = 0;
  2359. }
  2360. else
  2361. {
  2362. const int64 n = ((int64) values[i] + (((int64) 1) << 32)) - amountToSubtract;
  2363. values[i] = (uint32) n;
  2364. amountToSubtract = 1;
  2365. }
  2366. }
  2367. return *this;
  2368. }
  2369. BigInteger& BigInteger::operator*= (const BigInteger& other)
  2370. {
  2371. BigInteger total;
  2372. highestBit = getHighestBit();
  2373. const bool wasNegative = isNegative();
  2374. setNegative (false);
  2375. for (int i = 0; i <= highestBit; ++i)
  2376. {
  2377. if (operator[](i))
  2378. {
  2379. BigInteger n (other);
  2380. n.setNegative (false);
  2381. n <<= i;
  2382. total += n;
  2383. }
  2384. }
  2385. total.setNegative (wasNegative ^ other.isNegative());
  2386. swapWith (total);
  2387. return *this;
  2388. }
  2389. void BigInteger::divideBy (const BigInteger& divisor, BigInteger& remainder)
  2390. {
  2391. jassert (this != &remainder); // (can't handle passing itself in to get the remainder)
  2392. const int divHB = divisor.getHighestBit();
  2393. const int ourHB = getHighestBit();
  2394. if (divHB < 0 || ourHB < 0)
  2395. {
  2396. // division by zero
  2397. remainder.clear();
  2398. clear();
  2399. }
  2400. else
  2401. {
  2402. const bool wasNegative = isNegative();
  2403. swapWith (remainder);
  2404. remainder.setNegative (false);
  2405. clear();
  2406. BigInteger temp (divisor);
  2407. temp.setNegative (false);
  2408. int leftShift = ourHB - divHB;
  2409. temp <<= leftShift;
  2410. while (leftShift >= 0)
  2411. {
  2412. if (remainder.compareAbsolute (temp) >= 0)
  2413. {
  2414. remainder -= temp;
  2415. setBit (leftShift);
  2416. }
  2417. if (--leftShift >= 0)
  2418. temp >>= 1;
  2419. }
  2420. negative = wasNegative ^ divisor.isNegative();
  2421. remainder.setNegative (wasNegative);
  2422. }
  2423. }
  2424. BigInteger& BigInteger::operator/= (const BigInteger& other)
  2425. {
  2426. BigInteger remainder;
  2427. divideBy (other, remainder);
  2428. return *this;
  2429. }
  2430. BigInteger& BigInteger::operator|= (const BigInteger& other)
  2431. {
  2432. // this operation doesn't take into account negative values..
  2433. jassert (isNegative() == other.isNegative());
  2434. if (other.highestBit >= 0)
  2435. {
  2436. ensureSize (bitToIndex (other.highestBit));
  2437. int n = bitToIndex (other.highestBit) + 1;
  2438. while (--n >= 0)
  2439. values[n] |= other.values[n];
  2440. if (other.highestBit > highestBit)
  2441. highestBit = other.highestBit;
  2442. highestBit = getHighestBit();
  2443. }
  2444. return *this;
  2445. }
  2446. BigInteger& BigInteger::operator&= (const BigInteger& other)
  2447. {
  2448. // this operation doesn't take into account negative values..
  2449. jassert (isNegative() == other.isNegative());
  2450. int n = numValues;
  2451. while (n > other.numValues)
  2452. values[--n] = 0;
  2453. while (--n >= 0)
  2454. values[n] &= other.values[n];
  2455. if (other.highestBit < highestBit)
  2456. highestBit = other.highestBit;
  2457. highestBit = getHighestBit();
  2458. return *this;
  2459. }
  2460. BigInteger& BigInteger::operator^= (const BigInteger& other)
  2461. {
  2462. // this operation will only work with the absolute values
  2463. jassert (isNegative() == other.isNegative());
  2464. if (other.highestBit >= 0)
  2465. {
  2466. ensureSize (bitToIndex (other.highestBit));
  2467. int n = bitToIndex (other.highestBit) + 1;
  2468. while (--n >= 0)
  2469. values[n] ^= other.values[n];
  2470. if (other.highestBit > highestBit)
  2471. highestBit = other.highestBit;
  2472. highestBit = getHighestBit();
  2473. }
  2474. return *this;
  2475. }
  2476. BigInteger& BigInteger::operator%= (const BigInteger& divisor)
  2477. {
  2478. BigInteger remainder;
  2479. divideBy (divisor, remainder);
  2480. swapWith (remainder);
  2481. return *this;
  2482. }
  2483. BigInteger& BigInteger::operator<<= (int numBitsToShift)
  2484. {
  2485. shiftBits (numBitsToShift, 0);
  2486. return *this;
  2487. }
  2488. BigInteger& BigInteger::operator>>= (int numBitsToShift)
  2489. {
  2490. return operator<<= (-numBitsToShift);
  2491. }
  2492. BigInteger& BigInteger::operator++() { return operator+= (1); }
  2493. BigInteger& BigInteger::operator--() { return operator-= (1); }
  2494. const BigInteger BigInteger::operator++ (int) { const BigInteger old (*this); operator+= (1); return old; }
  2495. const BigInteger BigInteger::operator-- (int) { const BigInteger old (*this); operator-= (1); return old; }
  2496. const BigInteger BigInteger::operator+ (const BigInteger& other) const { BigInteger b (*this); return b += other; }
  2497. const BigInteger BigInteger::operator- (const BigInteger& other) const { BigInteger b (*this); return b -= other; }
  2498. const BigInteger BigInteger::operator* (const BigInteger& other) const { BigInteger b (*this); return b *= other; }
  2499. const BigInteger BigInteger::operator/ (const BigInteger& other) const { BigInteger b (*this); return b /= other; }
  2500. const BigInteger BigInteger::operator| (const BigInteger& other) const { BigInteger b (*this); return b |= other; }
  2501. const BigInteger BigInteger::operator& (const BigInteger& other) const { BigInteger b (*this); return b &= other; }
  2502. const BigInteger BigInteger::operator^ (const BigInteger& other) const { BigInteger b (*this); return b ^= other; }
  2503. const BigInteger BigInteger::operator% (const BigInteger& other) const { BigInteger b (*this); return b %= other; }
  2504. const BigInteger BigInteger::operator<< (const int numBits) const { BigInteger b (*this); return b <<= numBits; }
  2505. const BigInteger BigInteger::operator>> (const int numBits) const { BigInteger b (*this); return b >>= numBits; }
  2506. const BigInteger BigInteger::operator-() const { BigInteger b (*this); b.negate(); return b; }
  2507. int BigInteger::compare (const BigInteger& other) const throw()
  2508. {
  2509. if (isNegative() == other.isNegative())
  2510. {
  2511. const int absComp = compareAbsolute (other);
  2512. return isNegative() ? -absComp : absComp;
  2513. }
  2514. else
  2515. {
  2516. return isNegative() ? -1 : 1;
  2517. }
  2518. }
  2519. int BigInteger::compareAbsolute (const BigInteger& other) const throw()
  2520. {
  2521. const int h1 = getHighestBit();
  2522. const int h2 = other.getHighestBit();
  2523. if (h1 > h2)
  2524. return 1;
  2525. else if (h1 < h2)
  2526. return -1;
  2527. for (int i = bitToIndex (h1) + 1; --i >= 0;)
  2528. if (values[i] != other.values[i])
  2529. return (values[i] > other.values[i]) ? 1 : -1;
  2530. return 0;
  2531. }
  2532. bool BigInteger::operator== (const BigInteger& other) const throw() { return compare (other) == 0; }
  2533. bool BigInteger::operator!= (const BigInteger& other) const throw() { return compare (other) != 0; }
  2534. bool BigInteger::operator< (const BigInteger& other) const throw() { return compare (other) < 0; }
  2535. bool BigInteger::operator<= (const BigInteger& other) const throw() { return compare (other) <= 0; }
  2536. bool BigInteger::operator> (const BigInteger& other) const throw() { return compare (other) > 0; }
  2537. bool BigInteger::operator>= (const BigInteger& other) const throw() { return compare (other) >= 0; }
  2538. void BigInteger::shiftBits (int bits, const int startBit)
  2539. {
  2540. if (highestBit < 0)
  2541. return;
  2542. if (startBit > 0)
  2543. {
  2544. if (bits < 0)
  2545. {
  2546. // right shift
  2547. for (int i = startBit; i <= highestBit; ++i)
  2548. setBit (i, operator[] (i - bits));
  2549. highestBit = getHighestBit();
  2550. }
  2551. else if (bits > 0)
  2552. {
  2553. // left shift
  2554. for (int i = highestBit + 1; --i >= startBit;)
  2555. setBit (i + bits, operator[] (i));
  2556. while (--bits >= 0)
  2557. clearBit (bits + startBit);
  2558. }
  2559. }
  2560. else
  2561. {
  2562. if (bits < 0)
  2563. {
  2564. // right shift
  2565. bits = -bits;
  2566. if (bits > highestBit)
  2567. {
  2568. clear();
  2569. }
  2570. else
  2571. {
  2572. const int wordsToMove = bitToIndex (bits);
  2573. int top = 1 + bitToIndex (highestBit) - wordsToMove;
  2574. highestBit -= bits;
  2575. if (wordsToMove > 0)
  2576. {
  2577. int i;
  2578. for (i = 0; i < top; ++i)
  2579. values [i] = values [i + wordsToMove];
  2580. for (i = 0; i < wordsToMove; ++i)
  2581. values [top + i] = 0;
  2582. bits &= 31;
  2583. }
  2584. if (bits != 0)
  2585. {
  2586. const int invBits = 32 - bits;
  2587. --top;
  2588. for (int i = 0; i < top; ++i)
  2589. values[i] = (values[i] >> bits) | (values [i + 1] << invBits);
  2590. values[top] = (values[top] >> bits);
  2591. }
  2592. highestBit = getHighestBit();
  2593. }
  2594. }
  2595. else if (bits > 0)
  2596. {
  2597. // left shift
  2598. ensureSize (bitToIndex (highestBit + bits) + 1);
  2599. const int wordsToMove = bitToIndex (bits);
  2600. int top = 1 + bitToIndex (highestBit);
  2601. highestBit += bits;
  2602. if (wordsToMove > 0)
  2603. {
  2604. int i;
  2605. for (i = top; --i >= 0;)
  2606. values [i + wordsToMove] = values [i];
  2607. for (i = 0; i < wordsToMove; ++i)
  2608. values [i] = 0;
  2609. bits &= 31;
  2610. }
  2611. if (bits != 0)
  2612. {
  2613. const int invBits = 32 - bits;
  2614. for (int i = top + 1 + wordsToMove; --i > wordsToMove;)
  2615. values[i] = (values[i] << bits) | (values [i - 1] >> invBits);
  2616. values [wordsToMove] = values [wordsToMove] << bits;
  2617. }
  2618. highestBit = getHighestBit();
  2619. }
  2620. }
  2621. }
  2622. const BigInteger BigInteger::simpleGCD (BigInteger* m, BigInteger* n)
  2623. {
  2624. while (! m->isZero())
  2625. {
  2626. if (n->compareAbsolute (*m) > 0)
  2627. swapVariables (m, n);
  2628. *m -= *n;
  2629. }
  2630. return *n;
  2631. }
  2632. const BigInteger BigInteger::findGreatestCommonDivisor (BigInteger n) const
  2633. {
  2634. BigInteger m (*this);
  2635. while (! n.isZero())
  2636. {
  2637. if (abs (m.getHighestBit() - n.getHighestBit()) <= 16)
  2638. return simpleGCD (&m, &n);
  2639. BigInteger temp1 (m), temp2;
  2640. temp1.divideBy (n, temp2);
  2641. m = n;
  2642. n = temp2;
  2643. }
  2644. return m;
  2645. }
  2646. void BigInteger::exponentModulo (const BigInteger& exponent, const BigInteger& modulus)
  2647. {
  2648. BigInteger exp (exponent);
  2649. exp %= modulus;
  2650. BigInteger value (1);
  2651. swapWith (value);
  2652. value %= modulus;
  2653. while (! exp.isZero())
  2654. {
  2655. if (exp [0])
  2656. {
  2657. operator*= (value);
  2658. operator%= (modulus);
  2659. }
  2660. value *= value;
  2661. value %= modulus;
  2662. exp >>= 1;
  2663. }
  2664. }
  2665. void BigInteger::inverseModulo (const BigInteger& modulus)
  2666. {
  2667. if (modulus.isOne() || modulus.isNegative())
  2668. {
  2669. clear();
  2670. return;
  2671. }
  2672. if (isNegative() || compareAbsolute (modulus) >= 0)
  2673. operator%= (modulus);
  2674. if (isOne())
  2675. return;
  2676. if (! (*this)[0])
  2677. {
  2678. // not invertible
  2679. clear();
  2680. return;
  2681. }
  2682. BigInteger a1 (modulus);
  2683. BigInteger a2 (*this);
  2684. BigInteger b1 (modulus);
  2685. BigInteger b2 (1);
  2686. while (! a2.isOne())
  2687. {
  2688. BigInteger temp1, temp2, multiplier (a1);
  2689. multiplier.divideBy (a2, temp1);
  2690. temp1 = a2;
  2691. temp1 *= multiplier;
  2692. temp2 = a1;
  2693. temp2 -= temp1;
  2694. a1 = a2;
  2695. a2 = temp2;
  2696. temp1 = b2;
  2697. temp1 *= multiplier;
  2698. temp2 = b1;
  2699. temp2 -= temp1;
  2700. b1 = b2;
  2701. b2 = temp2;
  2702. }
  2703. while (b2.isNegative())
  2704. b2 += modulus;
  2705. b2 %= modulus;
  2706. swapWith (b2);
  2707. }
  2708. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const BigInteger& value)
  2709. {
  2710. return stream << value.toString (10);
  2711. }
  2712. const String BigInteger::toString (const int base, const int minimumNumCharacters) const
  2713. {
  2714. String s;
  2715. BigInteger v (*this);
  2716. if (base == 2 || base == 8 || base == 16)
  2717. {
  2718. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2719. static const char* const hexDigits = "0123456789abcdef";
  2720. for (;;)
  2721. {
  2722. const int remainder = v.getBitRangeAsInt (0, bits);
  2723. v >>= bits;
  2724. if (remainder == 0 && v.isZero())
  2725. break;
  2726. s = String::charToString (hexDigits [remainder]) + s;
  2727. }
  2728. }
  2729. else if (base == 10)
  2730. {
  2731. const BigInteger ten (10);
  2732. BigInteger remainder;
  2733. for (;;)
  2734. {
  2735. v.divideBy (ten, remainder);
  2736. if (remainder.isZero() && v.isZero())
  2737. break;
  2738. s = String (remainder.getBitRangeAsInt (0, 8)) + s;
  2739. }
  2740. }
  2741. else
  2742. {
  2743. jassertfalse; // can't do the specified base!
  2744. return String::empty;
  2745. }
  2746. s = s.paddedLeft ('0', minimumNumCharacters);
  2747. return isNegative() ? "-" + s : s;
  2748. }
  2749. void BigInteger::parseString (const String& text, const int base)
  2750. {
  2751. clear();
  2752. const juce_wchar* t = text;
  2753. if (base == 2 || base == 8 || base == 16)
  2754. {
  2755. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2756. for (;;)
  2757. {
  2758. const juce_wchar c = *t++;
  2759. const int digit = CharacterFunctions::getHexDigitValue (c);
  2760. if (((uint32) digit) < (uint32) base)
  2761. {
  2762. operator<<= (bits);
  2763. operator+= (digit);
  2764. }
  2765. else if (c == 0)
  2766. {
  2767. break;
  2768. }
  2769. }
  2770. }
  2771. else if (base == 10)
  2772. {
  2773. const BigInteger ten ((uint32) 10);
  2774. for (;;)
  2775. {
  2776. const juce_wchar c = *t++;
  2777. if (c >= '0' && c <= '9')
  2778. {
  2779. operator*= (ten);
  2780. operator+= ((int) (c - '0'));
  2781. }
  2782. else if (c == 0)
  2783. {
  2784. break;
  2785. }
  2786. }
  2787. }
  2788. setNegative (text.trimStart().startsWithChar ('-'));
  2789. }
  2790. const MemoryBlock BigInteger::toMemoryBlock() const
  2791. {
  2792. const int numBytes = (getHighestBit() + 8) >> 3;
  2793. MemoryBlock mb ((size_t) numBytes);
  2794. for (int i = 0; i < numBytes; ++i)
  2795. mb[i] = (uint8) getBitRangeAsInt (i << 3, 8);
  2796. return mb;
  2797. }
  2798. void BigInteger::loadFromMemoryBlock (const MemoryBlock& data)
  2799. {
  2800. clear();
  2801. for (int i = (int) data.getSize(); --i >= 0;)
  2802. this->setBitRangeAsInt ((int) (i << 3), 8, data [i]);
  2803. }
  2804. END_JUCE_NAMESPACE
  2805. /*** End of inlined file: juce_BigInteger.cpp ***/
  2806. /*** Start of inlined file: juce_MemoryBlock.cpp ***/
  2807. BEGIN_JUCE_NAMESPACE
  2808. MemoryBlock::MemoryBlock() throw()
  2809. : size (0)
  2810. {
  2811. }
  2812. MemoryBlock::MemoryBlock (const size_t initialSize, const bool initialiseToZero)
  2813. {
  2814. if (initialSize > 0)
  2815. {
  2816. size = initialSize;
  2817. data.allocate (initialSize, initialiseToZero);
  2818. }
  2819. else
  2820. {
  2821. size = 0;
  2822. }
  2823. }
  2824. MemoryBlock::MemoryBlock (const MemoryBlock& other)
  2825. : size (other.size)
  2826. {
  2827. if (size > 0)
  2828. {
  2829. jassert (other.data != 0);
  2830. data.malloc (size);
  2831. memcpy (data, other.data, size);
  2832. }
  2833. }
  2834. MemoryBlock::MemoryBlock (const void* const dataToInitialiseFrom, const size_t sizeInBytes)
  2835. : size (jmax ((size_t) 0, sizeInBytes))
  2836. {
  2837. jassert (sizeInBytes >= 0);
  2838. if (size > 0)
  2839. {
  2840. jassert (dataToInitialiseFrom != 0); // non-zero size, but a zero pointer passed-in?
  2841. data.malloc (size);
  2842. if (dataToInitialiseFrom != 0)
  2843. memcpy (data, dataToInitialiseFrom, size);
  2844. }
  2845. }
  2846. MemoryBlock::~MemoryBlock() throw()
  2847. {
  2848. jassert (size >= 0); // should never happen
  2849. jassert (size == 0 || data != 0); // non-zero size but no data allocated?
  2850. }
  2851. MemoryBlock& MemoryBlock::operator= (const MemoryBlock& other)
  2852. {
  2853. if (this != &other)
  2854. {
  2855. setSize (other.size, false);
  2856. memcpy (data, other.data, size);
  2857. }
  2858. return *this;
  2859. }
  2860. bool MemoryBlock::operator== (const MemoryBlock& other) const throw()
  2861. {
  2862. return matches (other.data, other.size);
  2863. }
  2864. bool MemoryBlock::operator!= (const MemoryBlock& other) const throw()
  2865. {
  2866. return ! operator== (other);
  2867. }
  2868. bool MemoryBlock::matches (const void* dataToCompare, size_t dataSize) const throw()
  2869. {
  2870. return size == dataSize
  2871. && memcmp (data, dataToCompare, size) == 0;
  2872. }
  2873. // this will resize the block to this size
  2874. void MemoryBlock::setSize (const size_t newSize, const bool initialiseToZero)
  2875. {
  2876. if (size != newSize)
  2877. {
  2878. if (newSize <= 0)
  2879. {
  2880. data.free();
  2881. size = 0;
  2882. }
  2883. else
  2884. {
  2885. if (data != 0)
  2886. {
  2887. data.realloc (newSize);
  2888. if (initialiseToZero && (newSize > size))
  2889. zeromem (data + size, newSize - size);
  2890. }
  2891. else
  2892. {
  2893. data.allocate (newSize, initialiseToZero);
  2894. }
  2895. size = newSize;
  2896. }
  2897. }
  2898. }
  2899. void MemoryBlock::ensureSize (const size_t minimumSize, const bool initialiseToZero)
  2900. {
  2901. if (size < minimumSize)
  2902. setSize (minimumSize, initialiseToZero);
  2903. }
  2904. void MemoryBlock::swapWith (MemoryBlock& other) throw()
  2905. {
  2906. swapVariables (size, other.size);
  2907. data.swapWith (other.data);
  2908. }
  2909. void MemoryBlock::fillWith (const uint8 value) throw()
  2910. {
  2911. memset (data, (int) value, size);
  2912. }
  2913. void MemoryBlock::append (const void* const srcData, const size_t numBytes)
  2914. {
  2915. if (numBytes > 0)
  2916. {
  2917. const size_t oldSize = size;
  2918. setSize (size + numBytes);
  2919. memcpy (data + oldSize, srcData, numBytes);
  2920. }
  2921. }
  2922. void MemoryBlock::copyFrom (const void* const src, int offset, size_t num) throw()
  2923. {
  2924. const char* d = static_cast<const char*> (src);
  2925. if (offset < 0)
  2926. {
  2927. d -= offset;
  2928. num -= offset;
  2929. offset = 0;
  2930. }
  2931. if (offset + num > size)
  2932. num = size - offset;
  2933. if (num > 0)
  2934. memcpy (data + offset, d, num);
  2935. }
  2936. void MemoryBlock::copyTo (void* const dst, int offset, size_t num) const throw()
  2937. {
  2938. char* d = static_cast<char*> (dst);
  2939. if (offset < 0)
  2940. {
  2941. zeromem (d, -offset);
  2942. d -= offset;
  2943. num += offset;
  2944. offset = 0;
  2945. }
  2946. if (offset + num > size)
  2947. {
  2948. const size_t newNum = size - offset;
  2949. zeromem (d + newNum, num - newNum);
  2950. num = newNum;
  2951. }
  2952. if (num > 0)
  2953. memcpy (d, data + offset, num);
  2954. }
  2955. void MemoryBlock::removeSection (size_t startByte, size_t numBytesToRemove)
  2956. {
  2957. if (startByte < 0)
  2958. {
  2959. numBytesToRemove += startByte;
  2960. startByte = 0;
  2961. }
  2962. if (startByte + numBytesToRemove >= size)
  2963. {
  2964. setSize (startByte);
  2965. }
  2966. else if (numBytesToRemove > 0)
  2967. {
  2968. memmove (data + startByte,
  2969. data + startByte + numBytesToRemove,
  2970. size - (startByte + numBytesToRemove));
  2971. setSize (size - numBytesToRemove);
  2972. }
  2973. }
  2974. const String MemoryBlock::toString() const
  2975. {
  2976. return String (static_cast <const char*> (getData()), size);
  2977. }
  2978. int MemoryBlock::getBitRange (const size_t bitRangeStart, size_t numBits) const throw()
  2979. {
  2980. int res = 0;
  2981. size_t byte = bitRangeStart >> 3;
  2982. int offsetInByte = (int) bitRangeStart & 7;
  2983. size_t bitsSoFar = 0;
  2984. while (numBits > 0 && (size_t) byte < size)
  2985. {
  2986. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  2987. const int mask = (0xff >> (8 - bitsThisTime)) << offsetInByte;
  2988. res |= (((data[byte] & mask) >> offsetInByte) << bitsSoFar);
  2989. bitsSoFar += bitsThisTime;
  2990. numBits -= bitsThisTime;
  2991. ++byte;
  2992. offsetInByte = 0;
  2993. }
  2994. return res;
  2995. }
  2996. void MemoryBlock::setBitRange (const size_t bitRangeStart, size_t numBits, int bitsToSet) throw()
  2997. {
  2998. size_t byte = bitRangeStart >> 3;
  2999. int offsetInByte = (int) bitRangeStart & 7;
  3000. unsigned int mask = ~((((unsigned int) 0xffffffff) << (32 - numBits)) >> (32 - numBits));
  3001. while (numBits > 0 && (size_t) byte < size)
  3002. {
  3003. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  3004. const unsigned int tempMask = (mask << offsetInByte) | ~((((unsigned int) 0xffffffff) >> offsetInByte) << offsetInByte);
  3005. const unsigned int tempBits = bitsToSet << offsetInByte;
  3006. data[byte] = (char) ((data[byte] & tempMask) | tempBits);
  3007. ++byte;
  3008. numBits -= bitsThisTime;
  3009. bitsToSet >>= bitsThisTime;
  3010. mask >>= bitsThisTime;
  3011. offsetInByte = 0;
  3012. }
  3013. }
  3014. void MemoryBlock::loadFromHexString (const String& hex)
  3015. {
  3016. ensureSize (hex.length() >> 1);
  3017. char* dest = data;
  3018. int i = 0;
  3019. for (;;)
  3020. {
  3021. int byte = 0;
  3022. for (int loop = 2; --loop >= 0;)
  3023. {
  3024. byte <<= 4;
  3025. for (;;)
  3026. {
  3027. const juce_wchar c = hex [i++];
  3028. if (c >= '0' && c <= '9')
  3029. {
  3030. byte |= c - '0';
  3031. break;
  3032. }
  3033. else if (c >= 'a' && c <= 'z')
  3034. {
  3035. byte |= c - ('a' - 10);
  3036. break;
  3037. }
  3038. else if (c >= 'A' && c <= 'Z')
  3039. {
  3040. byte |= c - ('A' - 10);
  3041. break;
  3042. }
  3043. else if (c == 0)
  3044. {
  3045. setSize (static_cast <size_t> (dest - data));
  3046. return;
  3047. }
  3048. }
  3049. }
  3050. *dest++ = (char) byte;
  3051. }
  3052. }
  3053. const char* const MemoryBlock::encodingTable = ".ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+";
  3054. const String MemoryBlock::toBase64Encoding() const
  3055. {
  3056. const size_t numChars = ((size << 3) + 5) / 6;
  3057. String destString ((unsigned int) size); // store the length, followed by a '.', and then the data.
  3058. const int initialLen = destString.length();
  3059. destString.preallocateStorage (initialLen + 2 + numChars);
  3060. juce_wchar* d = destString;
  3061. d += initialLen;
  3062. *d++ = '.';
  3063. for (size_t i = 0; i < numChars; ++i)
  3064. *d++ = encodingTable [getBitRange (i * 6, 6)];
  3065. *d++ = 0;
  3066. return destString;
  3067. }
  3068. bool MemoryBlock::fromBase64Encoding (const String& s)
  3069. {
  3070. const int startPos = s.indexOfChar ('.') + 1;
  3071. if (startPos <= 0)
  3072. return false;
  3073. const int numBytesNeeded = s.substring (0, startPos - 1).getIntValue();
  3074. setSize (numBytesNeeded, true);
  3075. const int numChars = s.length() - startPos;
  3076. const juce_wchar* srcChars = s;
  3077. srcChars += startPos;
  3078. int pos = 0;
  3079. for (int i = 0; i < numChars; ++i)
  3080. {
  3081. const char c = (char) srcChars[i];
  3082. for (int j = 0; j < 64; ++j)
  3083. {
  3084. if (encodingTable[j] == c)
  3085. {
  3086. setBitRange (pos, 6, j);
  3087. pos += 6;
  3088. break;
  3089. }
  3090. }
  3091. }
  3092. return true;
  3093. }
  3094. END_JUCE_NAMESPACE
  3095. /*** End of inlined file: juce_MemoryBlock.cpp ***/
  3096. /*** Start of inlined file: juce_PropertySet.cpp ***/
  3097. BEGIN_JUCE_NAMESPACE
  3098. PropertySet::PropertySet (const bool ignoreCaseOfKeyNames)
  3099. : properties (ignoreCaseOfKeyNames),
  3100. fallbackProperties (0),
  3101. ignoreCaseOfKeys (ignoreCaseOfKeyNames)
  3102. {
  3103. }
  3104. PropertySet::PropertySet (const PropertySet& other)
  3105. : properties (other.properties),
  3106. fallbackProperties (other.fallbackProperties),
  3107. ignoreCaseOfKeys (other.ignoreCaseOfKeys)
  3108. {
  3109. }
  3110. PropertySet& PropertySet::operator= (const PropertySet& other)
  3111. {
  3112. properties = other.properties;
  3113. fallbackProperties = other.fallbackProperties;
  3114. ignoreCaseOfKeys = other.ignoreCaseOfKeys;
  3115. propertyChanged();
  3116. return *this;
  3117. }
  3118. PropertySet::~PropertySet()
  3119. {
  3120. }
  3121. void PropertySet::clear()
  3122. {
  3123. const ScopedLock sl (lock);
  3124. if (properties.size() > 0)
  3125. {
  3126. properties.clear();
  3127. propertyChanged();
  3128. }
  3129. }
  3130. const String PropertySet::getValue (const String& keyName,
  3131. const String& defaultValue) const throw()
  3132. {
  3133. const ScopedLock sl (lock);
  3134. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3135. if (index >= 0)
  3136. return properties.getAllValues() [index];
  3137. return fallbackProperties != 0 ? fallbackProperties->getValue (keyName, defaultValue)
  3138. : defaultValue;
  3139. }
  3140. int PropertySet::getIntValue (const String& keyName,
  3141. const int defaultValue) const throw()
  3142. {
  3143. const ScopedLock sl (lock);
  3144. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3145. if (index >= 0)
  3146. return properties.getAllValues() [index].getIntValue();
  3147. return fallbackProperties != 0 ? fallbackProperties->getIntValue (keyName, defaultValue)
  3148. : defaultValue;
  3149. }
  3150. double PropertySet::getDoubleValue (const String& keyName,
  3151. const double defaultValue) const throw()
  3152. {
  3153. const ScopedLock sl (lock);
  3154. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3155. if (index >= 0)
  3156. return properties.getAllValues()[index].getDoubleValue();
  3157. return fallbackProperties != 0 ? fallbackProperties->getDoubleValue (keyName, defaultValue)
  3158. : defaultValue;
  3159. }
  3160. bool PropertySet::getBoolValue (const String& keyName,
  3161. const bool defaultValue) const throw()
  3162. {
  3163. const ScopedLock sl (lock);
  3164. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3165. if (index >= 0)
  3166. return properties.getAllValues() [index].getIntValue() != 0;
  3167. return fallbackProperties != 0 ? fallbackProperties->getBoolValue (keyName, defaultValue)
  3168. : defaultValue;
  3169. }
  3170. XmlElement* PropertySet::getXmlValue (const String& keyName) const
  3171. {
  3172. XmlDocument doc (getValue (keyName));
  3173. return doc.getDocumentElement();
  3174. }
  3175. void PropertySet::setValue (const String& keyName, const var& v)
  3176. {
  3177. jassert (keyName.isNotEmpty()); // shouldn't use an empty key name!
  3178. if (keyName.isNotEmpty())
  3179. {
  3180. const String value (v.toString());
  3181. const ScopedLock sl (lock);
  3182. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3183. if (index < 0 || properties.getAllValues() [index] != value)
  3184. {
  3185. properties.set (keyName, value);
  3186. propertyChanged();
  3187. }
  3188. }
  3189. }
  3190. void PropertySet::removeValue (const String& keyName)
  3191. {
  3192. if (keyName.isNotEmpty())
  3193. {
  3194. const ScopedLock sl (lock);
  3195. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3196. if (index >= 0)
  3197. {
  3198. properties.remove (keyName);
  3199. propertyChanged();
  3200. }
  3201. }
  3202. }
  3203. void PropertySet::setValue (const String& keyName, const XmlElement* const xml)
  3204. {
  3205. setValue (keyName, xml == 0 ? var::null
  3206. : var (xml->createDocument (String::empty, true)));
  3207. }
  3208. bool PropertySet::containsKey (const String& keyName) const throw()
  3209. {
  3210. const ScopedLock sl (lock);
  3211. return properties.getAllKeys().contains (keyName, ignoreCaseOfKeys);
  3212. }
  3213. void PropertySet::setFallbackPropertySet (PropertySet* fallbackProperties_) throw()
  3214. {
  3215. const ScopedLock sl (lock);
  3216. fallbackProperties = fallbackProperties_;
  3217. }
  3218. XmlElement* PropertySet::createXml (const String& nodeName) const
  3219. {
  3220. const ScopedLock sl (lock);
  3221. XmlElement* const xml = new XmlElement (nodeName);
  3222. for (int i = 0; i < properties.getAllKeys().size(); ++i)
  3223. {
  3224. XmlElement* const e = xml->createNewChildElement ("VALUE");
  3225. e->setAttribute ("name", properties.getAllKeys()[i]);
  3226. e->setAttribute ("val", properties.getAllValues()[i]);
  3227. }
  3228. return xml;
  3229. }
  3230. void PropertySet::restoreFromXml (const XmlElement& xml)
  3231. {
  3232. const ScopedLock sl (lock);
  3233. clear();
  3234. forEachXmlChildElementWithTagName (xml, e, "VALUE")
  3235. {
  3236. if (e->hasAttribute ("name")
  3237. && e->hasAttribute ("val"))
  3238. {
  3239. properties.set (e->getStringAttribute ("name"),
  3240. e->getStringAttribute ("val"));
  3241. }
  3242. }
  3243. if (properties.size() > 0)
  3244. propertyChanged();
  3245. }
  3246. void PropertySet::propertyChanged()
  3247. {
  3248. }
  3249. END_JUCE_NAMESPACE
  3250. /*** End of inlined file: juce_PropertySet.cpp ***/
  3251. /*** Start of inlined file: juce_Identifier.cpp ***/
  3252. BEGIN_JUCE_NAMESPACE
  3253. StringPool& Identifier::getPool()
  3254. {
  3255. static StringPool pool;
  3256. return pool;
  3257. }
  3258. Identifier::Identifier() throw()
  3259. : name (0)
  3260. {
  3261. }
  3262. Identifier::Identifier (const Identifier& other) throw()
  3263. : name (other.name)
  3264. {
  3265. }
  3266. Identifier& Identifier::operator= (const Identifier& other) throw()
  3267. {
  3268. name = other.name;
  3269. return *this;
  3270. }
  3271. Identifier::Identifier (const String& name_)
  3272. : name (Identifier::getPool().getPooledString (name_))
  3273. {
  3274. /* An Identifier string must be suitable for use as a script variable or XML
  3275. attribute, so it can only contain this limited set of characters.. */
  3276. jassert (name_.containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && name_.isNotEmpty());
  3277. }
  3278. Identifier::Identifier (const char* const name_)
  3279. : name (Identifier::getPool().getPooledString (name_))
  3280. {
  3281. /* An Identifier string must be suitable for use as a script variable or XML
  3282. attribute, so it can only contain this limited set of characters.. */
  3283. jassert (toString().containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && toString().isNotEmpty());
  3284. }
  3285. Identifier::~Identifier()
  3286. {
  3287. }
  3288. END_JUCE_NAMESPACE
  3289. /*** End of inlined file: juce_Identifier.cpp ***/
  3290. /*** Start of inlined file: juce_Variant.cpp ***/
  3291. BEGIN_JUCE_NAMESPACE
  3292. class var::VariantType
  3293. {
  3294. public:
  3295. VariantType() {}
  3296. virtual ~VariantType() {}
  3297. virtual int toInt (const ValueUnion&) const { return 0; }
  3298. virtual double toDouble (const ValueUnion&) const { return 0; }
  3299. virtual const String toString (const ValueUnion&) const { return String::empty; }
  3300. virtual bool toBool (const ValueUnion&) const { return false; }
  3301. virtual DynamicObject* toObject (const ValueUnion&) const { return 0; }
  3302. virtual bool isVoid() const throw() { return false; }
  3303. virtual bool isInt() const throw() { return false; }
  3304. virtual bool isBool() const throw() { return false; }
  3305. virtual bool isDouble() const throw() { return false; }
  3306. virtual bool isString() const throw() { return false; }
  3307. virtual bool isObject() const throw() { return false; }
  3308. virtual bool isMethod() const throw() { return false; }
  3309. virtual void cleanUp (ValueUnion&) const throw() {}
  3310. virtual void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest = source; }
  3311. virtual bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw() = 0;
  3312. virtual void writeToStream (const ValueUnion& data, OutputStream& output) const = 0;
  3313. };
  3314. class var::VariantType_Void : public var::VariantType
  3315. {
  3316. public:
  3317. VariantType_Void() {}
  3318. static const VariantType_Void* getInstance() { static const VariantType_Void i; return &i; }
  3319. bool isVoid() const throw() { return true; }
  3320. bool equals (const ValueUnion&, const ValueUnion&, const VariantType& otherType) const throw() { return otherType.isVoid(); }
  3321. void writeToStream (const ValueUnion&, OutputStream& output) const { output.writeCompressedInt (0); }
  3322. };
  3323. class var::VariantType_Int : public var::VariantType
  3324. {
  3325. public:
  3326. VariantType_Int() {}
  3327. static const VariantType_Int* getInstance() { static const VariantType_Int i; return &i; }
  3328. int toInt (const ValueUnion& data) const { return data.intValue; };
  3329. double toDouble (const ValueUnion& data) const { return (double) data.intValue; }
  3330. const String toString (const ValueUnion& data) const { return String (data.intValue); }
  3331. bool toBool (const ValueUnion& data) const { return data.intValue != 0; }
  3332. bool isInt() const throw() { return true; }
  3333. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3334. {
  3335. return otherType.toInt (otherData) == data.intValue;
  3336. }
  3337. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3338. {
  3339. output.writeCompressedInt (5);
  3340. output.writeByte (1);
  3341. output.writeInt (data.intValue);
  3342. }
  3343. };
  3344. class var::VariantType_Double : public var::VariantType
  3345. {
  3346. public:
  3347. VariantType_Double() {}
  3348. static const VariantType_Double* getInstance() { static const VariantType_Double i; return &i; }
  3349. int toInt (const ValueUnion& data) const { return (int) data.doubleValue; };
  3350. double toDouble (const ValueUnion& data) const { return data.doubleValue; }
  3351. const String toString (const ValueUnion& data) const { return String (data.doubleValue); }
  3352. bool toBool (const ValueUnion& data) const { return data.doubleValue != 0; }
  3353. bool isDouble() const throw() { return true; }
  3354. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3355. {
  3356. return otherType.toDouble (otherData) == data.doubleValue;
  3357. }
  3358. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3359. {
  3360. output.writeCompressedInt (9);
  3361. output.writeByte (4);
  3362. output.writeDouble (data.doubleValue);
  3363. }
  3364. };
  3365. class var::VariantType_Bool : public var::VariantType
  3366. {
  3367. public:
  3368. VariantType_Bool() {}
  3369. static const VariantType_Bool* getInstance() { static const VariantType_Bool i; return &i; }
  3370. int toInt (const ValueUnion& data) const { return data.boolValue ? 1 : 0; };
  3371. double toDouble (const ValueUnion& data) const { return data.boolValue ? 1.0 : 0.0; }
  3372. const String toString (const ValueUnion& data) const { return String::charToString (data.boolValue ? '1' : '0'); }
  3373. bool toBool (const ValueUnion& data) const { return data.boolValue; }
  3374. bool isBool() const throw() { return true; }
  3375. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3376. {
  3377. return otherType.toBool (otherData) == data.boolValue;
  3378. }
  3379. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3380. {
  3381. output.writeCompressedInt (1);
  3382. output.writeByte (data.boolValue ? 2 : 3);
  3383. }
  3384. };
  3385. class var::VariantType_String : public var::VariantType
  3386. {
  3387. public:
  3388. VariantType_String() {}
  3389. static const VariantType_String* getInstance() { static const VariantType_String i; return &i; }
  3390. void cleanUp (ValueUnion& data) const throw() { delete data.stringValue; }
  3391. void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest.stringValue = new String (*source.stringValue); }
  3392. int toInt (const ValueUnion& data) const { return data.stringValue->getIntValue(); };
  3393. double toDouble (const ValueUnion& data) const { return data.stringValue->getDoubleValue(); }
  3394. const String toString (const ValueUnion& data) const { return *data.stringValue; }
  3395. bool toBool (const ValueUnion& data) const { return data.stringValue->getIntValue() != 0
  3396. || data.stringValue->trim().equalsIgnoreCase ("true")
  3397. || data.stringValue->trim().equalsIgnoreCase ("yes"); }
  3398. bool isString() const throw() { return true; }
  3399. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3400. {
  3401. return otherType.toString (otherData) == *data.stringValue;
  3402. }
  3403. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3404. {
  3405. const int len = data.stringValue->getNumBytesAsUTF8() + 1;
  3406. output.writeCompressedInt (len + 1);
  3407. output.writeByte (5);
  3408. HeapBlock<char> temp (len);
  3409. data.stringValue->copyToUTF8 (temp, len);
  3410. output.write (temp, len);
  3411. }
  3412. };
  3413. class var::VariantType_Object : public var::VariantType
  3414. {
  3415. public:
  3416. VariantType_Object() {}
  3417. static const VariantType_Object* getInstance() { static const VariantType_Object i; return &i; }
  3418. void cleanUp (ValueUnion& data) const throw() { if (data.objectValue != 0) data.objectValue->decReferenceCount(); }
  3419. void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest.objectValue = source.objectValue; if (dest.objectValue != 0) dest.objectValue->incReferenceCount(); }
  3420. const String toString (const ValueUnion& data) const { return "Object 0x" + String::toHexString ((int) (pointer_sized_int) data.objectValue); }
  3421. bool toBool (const ValueUnion& data) const { return data.objectValue != 0; }
  3422. DynamicObject* toObject (const ValueUnion& data) const { return data.objectValue; }
  3423. bool isObject() const throw() { return true; }
  3424. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3425. {
  3426. return otherType.toObject (otherData) == data.objectValue;
  3427. }
  3428. void writeToStream (const ValueUnion&, OutputStream& output) const
  3429. {
  3430. jassertfalse; // Can't write an object to a stream!
  3431. output.writeCompressedInt (0);
  3432. }
  3433. };
  3434. class var::VariantType_Method : public var::VariantType
  3435. {
  3436. public:
  3437. VariantType_Method() {}
  3438. static const VariantType_Method* getInstance() { static const VariantType_Method i; return &i; }
  3439. const String toString (const ValueUnion&) const { return "Method"; }
  3440. bool toBool (const ValueUnion& data) const { return data.methodValue != 0; }
  3441. bool isMethod() const throw() { return true; }
  3442. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3443. {
  3444. return otherType.isMethod() && otherData.methodValue == data.methodValue;
  3445. }
  3446. void writeToStream (const ValueUnion&, OutputStream& output) const
  3447. {
  3448. jassertfalse; // Can't write a method to a stream!
  3449. output.writeCompressedInt (0);
  3450. }
  3451. };
  3452. var::var() throw()
  3453. : type (VariantType_Void::getInstance())
  3454. {
  3455. }
  3456. var::~var() throw()
  3457. {
  3458. type->cleanUp (value);
  3459. }
  3460. const var var::null;
  3461. var::var (const var& valueToCopy) : type (valueToCopy.type)
  3462. {
  3463. type->createCopy (value, valueToCopy.value);
  3464. }
  3465. var::var (const int value_) throw() : type (VariantType_Int::getInstance())
  3466. {
  3467. value.intValue = value_;
  3468. }
  3469. var::var (const bool value_) throw() : type (VariantType_Bool::getInstance())
  3470. {
  3471. value.boolValue = value_;
  3472. }
  3473. var::var (const double value_) throw() : type (VariantType_Double::getInstance())
  3474. {
  3475. value.doubleValue = value_;
  3476. }
  3477. var::var (const String& value_) : type (VariantType_String::getInstance())
  3478. {
  3479. value.stringValue = new String (value_);
  3480. }
  3481. var::var (const char* const value_) : type (VariantType_String::getInstance())
  3482. {
  3483. value.stringValue = new String (value_);
  3484. }
  3485. var::var (const juce_wchar* const value_) : type (VariantType_String::getInstance())
  3486. {
  3487. value.stringValue = new String (value_);
  3488. }
  3489. var::var (DynamicObject* const object) : type (VariantType_Object::getInstance())
  3490. {
  3491. value.objectValue = object;
  3492. if (object != 0)
  3493. object->incReferenceCount();
  3494. }
  3495. var::var (MethodFunction method_) throw() : type (VariantType_Method::getInstance())
  3496. {
  3497. value.methodValue = method_;
  3498. }
  3499. bool var::isVoid() const throw() { return type->isVoid(); }
  3500. bool var::isInt() const throw() { return type->isInt(); }
  3501. bool var::isBool() const throw() { return type->isBool(); }
  3502. bool var::isDouble() const throw() { return type->isDouble(); }
  3503. bool var::isString() const throw() { return type->isString(); }
  3504. bool var::isObject() const throw() { return type->isObject(); }
  3505. bool var::isMethod() const throw() { return type->isMethod(); }
  3506. var::operator int() const { return type->toInt (value); }
  3507. var::operator bool() const { return type->toBool (value); }
  3508. var::operator float() const { return (float) type->toDouble (value); }
  3509. var::operator double() const { return type->toDouble (value); }
  3510. const String var::toString() const { return type->toString (value); }
  3511. var::operator const String() const { return type->toString (value); }
  3512. DynamicObject* var::getObject() const { return type->toObject (value); }
  3513. void var::swapWith (var& other) throw()
  3514. {
  3515. swapVariables (type, other.type);
  3516. swapVariables (value, other.value);
  3517. }
  3518. var& var::operator= (const var& newValue) { type->cleanUp (value); type = newValue.type; type->createCopy (value, newValue.value); return *this; }
  3519. var& var::operator= (int newValue) { var v (newValue); swapWith (v); return *this; }
  3520. var& var::operator= (bool newValue) { var v (newValue); swapWith (v); return *this; }
  3521. var& var::operator= (double newValue) { var v (newValue); swapWith (v); return *this; }
  3522. var& var::operator= (const char* newValue) { var v (newValue); swapWith (v); return *this; }
  3523. var& var::operator= (const juce_wchar* newValue) { var v (newValue); swapWith (v); return *this; }
  3524. var& var::operator= (const String& newValue) { var v (newValue); swapWith (v); return *this; }
  3525. var& var::operator= (DynamicObject* newValue) { var v (newValue); swapWith (v); return *this; }
  3526. var& var::operator= (MethodFunction newValue) { var v (newValue); swapWith (v); return *this; }
  3527. bool var::equals (const var& other) const throw()
  3528. {
  3529. return type->equals (value, other.value, *other.type);
  3530. }
  3531. bool operator== (const var& v1, const var& v2) throw() { return v1.equals (v2); }
  3532. bool operator!= (const var& v1, const var& v2) throw() { return ! v1.equals (v2); }
  3533. bool operator== (const var& v1, const String& v2) throw() { return v1.toString() == v2; }
  3534. bool operator!= (const var& v1, const String& v2) throw() { return v1.toString() != v2; }
  3535. void var::writeToStream (OutputStream& output) const
  3536. {
  3537. type->writeToStream (value, output);
  3538. }
  3539. const var var::readFromStream (InputStream& input)
  3540. {
  3541. const int numBytes = input.readCompressedInt();
  3542. if (numBytes > 0)
  3543. {
  3544. switch (input.readByte())
  3545. {
  3546. case 1: return var (input.readInt());
  3547. case 2: return var (true);
  3548. case 3: return var (false);
  3549. case 4: return var (input.readDouble());
  3550. case 5:
  3551. {
  3552. MemoryOutputStream mo;
  3553. mo.writeFromInputStream (input, numBytes - 1);
  3554. return var (mo.toUTF8());
  3555. }
  3556. default: input.skipNextBytes (numBytes - 1); break;
  3557. }
  3558. }
  3559. return var::null;
  3560. }
  3561. const var var::operator[] (const Identifier& propertyName) const
  3562. {
  3563. DynamicObject* const o = getObject();
  3564. return o != 0 ? o->getProperty (propertyName) : var::null;
  3565. }
  3566. const var var::invoke (const Identifier& method, const var* arguments, int numArguments) const
  3567. {
  3568. DynamicObject* const o = getObject();
  3569. return o != 0 ? o->invokeMethod (method, arguments, numArguments) : var::null;
  3570. }
  3571. const var var::invoke (const var& targetObject, const var* arguments, int numArguments) const
  3572. {
  3573. if (isMethod())
  3574. {
  3575. DynamicObject* const target = targetObject.getObject();
  3576. if (target != 0)
  3577. return (target->*(value.methodValue)) (arguments, numArguments);
  3578. }
  3579. return var::null;
  3580. }
  3581. const var var::call (const Identifier& method) const
  3582. {
  3583. return invoke (method, 0, 0);
  3584. }
  3585. const var var::call (const Identifier& method, const var& arg1) const
  3586. {
  3587. return invoke (method, &arg1, 1);
  3588. }
  3589. const var var::call (const Identifier& method, const var& arg1, const var& arg2) const
  3590. {
  3591. var args[] = { arg1, arg2 };
  3592. return invoke (method, args, 2);
  3593. }
  3594. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3)
  3595. {
  3596. var args[] = { arg1, arg2, arg3 };
  3597. return invoke (method, args, 3);
  3598. }
  3599. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4) const
  3600. {
  3601. var args[] = { arg1, arg2, arg3, arg4 };
  3602. return invoke (method, args, 4);
  3603. }
  3604. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4, const var& arg5) const
  3605. {
  3606. var args[] = { arg1, arg2, arg3, arg4, arg5 };
  3607. return invoke (method, args, 5);
  3608. }
  3609. END_JUCE_NAMESPACE
  3610. /*** End of inlined file: juce_Variant.cpp ***/
  3611. /*** Start of inlined file: juce_NamedValueSet.cpp ***/
  3612. BEGIN_JUCE_NAMESPACE
  3613. NamedValueSet::NamedValue::NamedValue() throw()
  3614. {
  3615. }
  3616. inline NamedValueSet::NamedValue::NamedValue (const Identifier& name_, const var& value_)
  3617. : name (name_), value (value_)
  3618. {
  3619. }
  3620. bool NamedValueSet::NamedValue::operator== (const NamedValueSet::NamedValue& other) const throw()
  3621. {
  3622. return name == other.name && value == other.value;
  3623. }
  3624. NamedValueSet::NamedValueSet() throw()
  3625. {
  3626. }
  3627. NamedValueSet::NamedValueSet (const NamedValueSet& other)
  3628. : values (other.values)
  3629. {
  3630. }
  3631. NamedValueSet& NamedValueSet::operator= (const NamedValueSet& other)
  3632. {
  3633. values = other.values;
  3634. return *this;
  3635. }
  3636. NamedValueSet::~NamedValueSet()
  3637. {
  3638. }
  3639. bool NamedValueSet::operator== (const NamedValueSet& other) const
  3640. {
  3641. return values == other.values;
  3642. }
  3643. bool NamedValueSet::operator!= (const NamedValueSet& other) const
  3644. {
  3645. return ! operator== (other);
  3646. }
  3647. int NamedValueSet::size() const throw()
  3648. {
  3649. return values.size();
  3650. }
  3651. const var& NamedValueSet::operator[] (const Identifier& name) const
  3652. {
  3653. for (int i = values.size(); --i >= 0;)
  3654. {
  3655. const NamedValue& v = values.getReference(i);
  3656. if (v.name == name)
  3657. return v.value;
  3658. }
  3659. return var::null;
  3660. }
  3661. const var NamedValueSet::getWithDefault (const Identifier& name, const var& defaultReturnValue) const
  3662. {
  3663. const var* v = getItem (name);
  3664. return v != 0 ? *v : defaultReturnValue;
  3665. }
  3666. var* NamedValueSet::getItem (const Identifier& name) const
  3667. {
  3668. for (int i = values.size(); --i >= 0;)
  3669. {
  3670. NamedValue& v = values.getReference(i);
  3671. if (v.name == name)
  3672. return &(v.value);
  3673. }
  3674. return 0;
  3675. }
  3676. bool NamedValueSet::set (const Identifier& name, const var& newValue)
  3677. {
  3678. for (int i = values.size(); --i >= 0;)
  3679. {
  3680. NamedValue& v = values.getReference(i);
  3681. if (v.name == name)
  3682. {
  3683. if (v.value == newValue)
  3684. return false;
  3685. v.value = newValue;
  3686. return true;
  3687. }
  3688. }
  3689. values.add (NamedValue (name, newValue));
  3690. return true;
  3691. }
  3692. bool NamedValueSet::contains (const Identifier& name) const
  3693. {
  3694. return getItem (name) != 0;
  3695. }
  3696. bool NamedValueSet::remove (const Identifier& name)
  3697. {
  3698. for (int i = values.size(); --i >= 0;)
  3699. {
  3700. if (values.getReference(i).name == name)
  3701. {
  3702. values.remove (i);
  3703. return true;
  3704. }
  3705. }
  3706. return false;
  3707. }
  3708. const Identifier NamedValueSet::getName (const int index) const
  3709. {
  3710. jassert (((unsigned int) index) < (unsigned int) values.size());
  3711. return values [index].name;
  3712. }
  3713. const var NamedValueSet::getValueAt (const int index) const
  3714. {
  3715. jassert (((unsigned int) index) < (unsigned int) values.size());
  3716. return values [index].value;
  3717. }
  3718. void NamedValueSet::clear()
  3719. {
  3720. values.clear();
  3721. }
  3722. END_JUCE_NAMESPACE
  3723. /*** End of inlined file: juce_NamedValueSet.cpp ***/
  3724. /*** Start of inlined file: juce_DynamicObject.cpp ***/
  3725. BEGIN_JUCE_NAMESPACE
  3726. DynamicObject::DynamicObject()
  3727. {
  3728. }
  3729. DynamicObject::~DynamicObject()
  3730. {
  3731. }
  3732. bool DynamicObject::hasProperty (const Identifier& propertyName) const
  3733. {
  3734. var* const v = properties.getItem (propertyName);
  3735. return v != 0 && ! v->isMethod();
  3736. }
  3737. const var DynamicObject::getProperty (const Identifier& propertyName) const
  3738. {
  3739. return properties [propertyName];
  3740. }
  3741. void DynamicObject::setProperty (const Identifier& propertyName, const var& newValue)
  3742. {
  3743. properties.set (propertyName, newValue);
  3744. }
  3745. void DynamicObject::removeProperty (const Identifier& propertyName)
  3746. {
  3747. properties.remove (propertyName);
  3748. }
  3749. bool DynamicObject::hasMethod (const Identifier& methodName) const
  3750. {
  3751. return getProperty (methodName).isMethod();
  3752. }
  3753. const var DynamicObject::invokeMethod (const Identifier& methodName,
  3754. const var* parameters,
  3755. int numParameters)
  3756. {
  3757. return properties [methodName].invoke (var (this), parameters, numParameters);
  3758. }
  3759. void DynamicObject::setMethod (const Identifier& name,
  3760. var::MethodFunction methodFunction)
  3761. {
  3762. properties.set (name, var (methodFunction));
  3763. }
  3764. void DynamicObject::clear()
  3765. {
  3766. properties.clear();
  3767. }
  3768. END_JUCE_NAMESPACE
  3769. /*** End of inlined file: juce_DynamicObject.cpp ***/
  3770. /*** Start of inlined file: juce_Expression.cpp ***/
  3771. BEGIN_JUCE_NAMESPACE
  3772. class Expression::Helpers
  3773. {
  3774. public:
  3775. typedef ReferenceCountedObjectPtr<Term> TermPtr;
  3776. class Constant : public Term
  3777. {
  3778. public:
  3779. Constant (const double value_, bool isResolutionTarget_)
  3780. : value (value_), isResolutionTarget (isResolutionTarget_) {}
  3781. Type getType() const throw() { return constantType; }
  3782. Term* clone() const { return new Constant (value, isResolutionTarget); }
  3783. double evaluate (const EvaluationContext&, int) const { return value; }
  3784. int getNumInputs() const { return 0; }
  3785. Term* getInput (int) const { return 0; }
  3786. const TermPtr negated()
  3787. {
  3788. return new Constant (-value, isResolutionTarget);
  3789. }
  3790. const String toString() const
  3791. {
  3792. if (isResolutionTarget)
  3793. return "@" + String (value);
  3794. return String (value);
  3795. }
  3796. double value;
  3797. bool isResolutionTarget;
  3798. };
  3799. class Symbol : public Term
  3800. {
  3801. public:
  3802. explicit Symbol (const String& symbol_)
  3803. : mainSymbol (symbol_.upToFirstOccurrenceOf (".", false, false).trim()),
  3804. member (symbol_.fromFirstOccurrenceOf (".", false, false).trim())
  3805. {}
  3806. Symbol (const String& symbol_, const String& member_)
  3807. : mainSymbol (symbol_),
  3808. member (member_)
  3809. {}
  3810. double evaluate (const EvaluationContext& c, int recursionDepth) const
  3811. {
  3812. if (++recursionDepth > 256)
  3813. throw EvaluationError ("Recursive symbol references");
  3814. try
  3815. {
  3816. return c.getSymbolValue (mainSymbol, member).term->evaluate (c, recursionDepth);
  3817. }
  3818. catch (...)
  3819. {}
  3820. return 0;
  3821. }
  3822. Type getType() const throw() { return symbolType; }
  3823. Term* clone() const { return new Symbol (mainSymbol, member); }
  3824. int getNumInputs() const { return 0; }
  3825. Term* getInput (int) const { return 0; }
  3826. const String getSymbolName() const { return toString(); }
  3827. const String toString() const
  3828. {
  3829. return member.isEmpty() ? mainSymbol
  3830. : mainSymbol + "." + member;
  3831. }
  3832. bool referencesSymbol (const String& s, const EvaluationContext* c, int recursionDepth) const
  3833. {
  3834. if (s == mainSymbol)
  3835. return true;
  3836. if (++recursionDepth > 256)
  3837. throw EvaluationError ("Recursive symbol references");
  3838. try
  3839. {
  3840. return c != 0 && c->getSymbolValue (mainSymbol, member).term->referencesSymbol (s, c, recursionDepth);
  3841. }
  3842. catch (EvaluationError&)
  3843. {
  3844. return false;
  3845. }
  3846. }
  3847. String mainSymbol, member;
  3848. };
  3849. class Function : public Term
  3850. {
  3851. public:
  3852. Function (const String& functionName_, const ReferenceCountedArray<Term>& parameters_)
  3853. : functionName (functionName_), parameters (parameters_)
  3854. {}
  3855. Term* clone() const { return new Function (functionName, parameters); }
  3856. double evaluate (const EvaluationContext& c, int recursionDepth) const
  3857. {
  3858. HeapBlock <double> params (parameters.size());
  3859. for (int i = 0; i < parameters.size(); ++i)
  3860. params[i] = parameters.getUnchecked(i)->evaluate (c, recursionDepth);
  3861. return c.evaluateFunction (functionName, params, parameters.size());
  3862. }
  3863. Type getType() const throw() { return functionType; }
  3864. int getInputIndexFor (const Term* possibleInput) const { return parameters.indexOf (possibleInput); }
  3865. int getNumInputs() const { return parameters.size(); }
  3866. Term* getInput (int i) const { return parameters [i]; }
  3867. const String getFunctionName() const { return functionName; }
  3868. bool referencesSymbol (const String& s, const EvaluationContext* c, int recursionDepth) const
  3869. {
  3870. for (int i = 0; i < parameters.size(); ++i)
  3871. if (parameters.getUnchecked(i)->referencesSymbol (s, c, recursionDepth))
  3872. return true;
  3873. return false;
  3874. }
  3875. const String toString() const
  3876. {
  3877. if (parameters.size() == 0)
  3878. return functionName + "()";
  3879. String s (functionName + " (");
  3880. for (int i = 0; i < parameters.size(); ++i)
  3881. {
  3882. s << parameters.getUnchecked(i)->toString();
  3883. if (i < parameters.size() - 1)
  3884. s << ", ";
  3885. }
  3886. s << ')';
  3887. return s;
  3888. }
  3889. const String functionName;
  3890. ReferenceCountedArray<Term> parameters;
  3891. };
  3892. class Negate : public Term
  3893. {
  3894. public:
  3895. Negate (const TermPtr& input_) : input (input_)
  3896. {
  3897. jassert (input_ != 0);
  3898. }
  3899. Type getType() const throw() { return operatorType; }
  3900. int getInputIndexFor (const Term* possibleInput) const { return possibleInput == input ? 0 : -1; }
  3901. int getNumInputs() const { return 1; }
  3902. Term* getInput (int index) const { return index == 0 ? static_cast<Term*> (input) : 0; }
  3903. Term* clone() const { return new Negate (input->clone()); }
  3904. double evaluate (const EvaluationContext& c, int recursionDepth) const { return -input->evaluate (c, recursionDepth); }
  3905. const String getFunctionName() const { return "-"; }
  3906. const TermPtr negated()
  3907. {
  3908. return input;
  3909. }
  3910. const TermPtr createTermToEvaluateInput (const EvaluationContext& context, const Term* input_, double overallTarget, Term* topLevelTerm) const
  3911. {
  3912. (void) input_;
  3913. jassert (input_ == input);
  3914. const Term* const dest = findDestinationFor (topLevelTerm, this);
  3915. return new Negate (dest == 0 ? new Constant (overallTarget, false)
  3916. : dest->createTermToEvaluateInput (context, this, overallTarget, topLevelTerm));
  3917. }
  3918. const String toString() const
  3919. {
  3920. if (input->getOperatorPrecedence() > 0)
  3921. return "-(" + input->toString() + ")";
  3922. else
  3923. return "-" + input->toString();
  3924. }
  3925. bool referencesSymbol (const String& s, const EvaluationContext* c, int recursionDepth) const
  3926. {
  3927. return input->referencesSymbol (s, c, recursionDepth);
  3928. }
  3929. private:
  3930. const TermPtr input;
  3931. };
  3932. class BinaryTerm : public Term
  3933. {
  3934. public:
  3935. BinaryTerm (Term* const left_, Term* const right_) : left (left_), right (right_)
  3936. {
  3937. jassert (left_ != 0 && right_ != 0);
  3938. }
  3939. int getInputIndexFor (const Term* possibleInput) const
  3940. {
  3941. return possibleInput == left ? 0 : (possibleInput == right ? 1 : -1);
  3942. }
  3943. Type getType() const throw() { return operatorType; }
  3944. int getNumInputs() const { return 2; }
  3945. Term* getInput (int index) const { return index == 0 ? static_cast<Term*> (left) : (index == 1 ? static_cast<Term*> (right) : 0); }
  3946. bool referencesSymbol (const String& s, const EvaluationContext* c, int recursionDepth) const
  3947. {
  3948. return left->referencesSymbol (s, c, recursionDepth)
  3949. || right->referencesSymbol (s, c, recursionDepth);
  3950. }
  3951. const String toString() const
  3952. {
  3953. String s;
  3954. const int ourPrecendence = getOperatorPrecedence();
  3955. if (left->getOperatorPrecedence() > ourPrecendence)
  3956. s << '(' << left->toString() << ')';
  3957. else
  3958. s = left->toString();
  3959. s << ' ' << getFunctionName() << ' ';
  3960. if (right->getOperatorPrecedence() >= ourPrecendence)
  3961. s << '(' << right->toString() << ')';
  3962. else
  3963. s << right->toString();
  3964. return s;
  3965. }
  3966. protected:
  3967. const TermPtr left, right;
  3968. const TermPtr createDestinationTerm (const EvaluationContext& context, const Term* input, double overallTarget, Term* topLevelTerm) const
  3969. {
  3970. jassert (input == left || input == right);
  3971. if (input != left && input != right)
  3972. return 0;
  3973. const Term* const dest = findDestinationFor (topLevelTerm, this);
  3974. if (dest == 0)
  3975. return new Constant (overallTarget, false);
  3976. return dest->createTermToEvaluateInput (context, this, overallTarget, topLevelTerm);
  3977. }
  3978. };
  3979. class Add : public BinaryTerm
  3980. {
  3981. public:
  3982. Add (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  3983. Term* clone() const { return new Add (left->clone(), right->clone()); }
  3984. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) + right->evaluate (c, recursionDepth); }
  3985. int getOperatorPrecedence() const { return 2; }
  3986. const String getFunctionName() const { return "+"; }
  3987. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  3988. {
  3989. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  3990. if (newDest == 0)
  3991. return 0;
  3992. return new Subtract (newDest, (input == left ? right : left)->clone());
  3993. }
  3994. private:
  3995. Add (const Add&);
  3996. Add& operator= (const Add&);
  3997. };
  3998. class Subtract : public BinaryTerm
  3999. {
  4000. public:
  4001. Subtract (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  4002. Term* clone() const { return new Subtract (left->clone(), right->clone()); }
  4003. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) - right->evaluate (c, recursionDepth); }
  4004. int getOperatorPrecedence() const { return 2; }
  4005. const String getFunctionName() const { return "-"; }
  4006. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  4007. {
  4008. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  4009. if (newDest == 0)
  4010. return 0;
  4011. if (input == left)
  4012. return new Add (newDest, right->clone());
  4013. else
  4014. return new Subtract (left->clone(), newDest);
  4015. }
  4016. private:
  4017. Subtract (const Subtract&);
  4018. Subtract& operator= (const Subtract&);
  4019. };
  4020. class Multiply : public BinaryTerm
  4021. {
  4022. public:
  4023. Multiply (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  4024. Term* clone() const { return new Multiply (left->clone(), right->clone()); }
  4025. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) * right->evaluate (c, recursionDepth); }
  4026. const String getFunctionName() const { return "*"; }
  4027. int getOperatorPrecedence() const { return 1; }
  4028. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  4029. {
  4030. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  4031. if (newDest == 0)
  4032. return 0;
  4033. return new Divide (newDest, (input == left ? right : left)->clone());
  4034. }
  4035. private:
  4036. Multiply (const Multiply&);
  4037. Multiply& operator= (const Multiply&);
  4038. };
  4039. class Divide : public BinaryTerm
  4040. {
  4041. public:
  4042. Divide (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  4043. Term* clone() const { return new Divide (left->clone(), right->clone()); }
  4044. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) / right->evaluate (c, recursionDepth); }
  4045. const String getFunctionName() const { return "/"; }
  4046. int getOperatorPrecedence() const { return 1; }
  4047. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  4048. {
  4049. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  4050. if (newDest == 0)
  4051. return 0;
  4052. if (input == left)
  4053. return new Multiply (newDest, right->clone());
  4054. else
  4055. return new Divide (left->clone(), newDest);
  4056. }
  4057. private:
  4058. Divide (const Divide&);
  4059. Divide& operator= (const Divide&);
  4060. };
  4061. static Term* findDestinationFor (Term* const topLevel, const Term* const inputTerm)
  4062. {
  4063. const int inputIndex = topLevel->getInputIndexFor (inputTerm);
  4064. if (inputIndex >= 0)
  4065. return topLevel;
  4066. for (int i = topLevel->getNumInputs(); --i >= 0;)
  4067. {
  4068. Term* t = findDestinationFor (topLevel->getInput (i), inputTerm);
  4069. if (t != 0)
  4070. return t;
  4071. }
  4072. return 0;
  4073. }
  4074. static Constant* findTermToAdjust (Term* const term, const bool mustBeFlagged)
  4075. {
  4076. Constant* c = dynamic_cast<Constant*> (term);
  4077. if (c != 0 && (c->isResolutionTarget || ! mustBeFlagged))
  4078. return c;
  4079. if (dynamic_cast<Function*> (term) != 0)
  4080. return 0;
  4081. int i;
  4082. const int numIns = term->getNumInputs();
  4083. for (i = 0; i < numIns; ++i)
  4084. {
  4085. Constant* c = dynamic_cast<Constant*> (term->getInput (i));
  4086. if (c != 0 && (c->isResolutionTarget || ! mustBeFlagged))
  4087. return c;
  4088. }
  4089. for (i = 0; i < numIns; ++i)
  4090. {
  4091. Constant* c = findTermToAdjust (term->getInput (i), mustBeFlagged);
  4092. if (c != 0)
  4093. return c;
  4094. }
  4095. return 0;
  4096. }
  4097. static bool containsAnySymbols (const Term* const t)
  4098. {
  4099. if (dynamic_cast <const Symbol*> (t) != 0)
  4100. return true;
  4101. for (int i = t->getNumInputs(); --i >= 0;)
  4102. if (containsAnySymbols (t->getInput (i)))
  4103. return true;
  4104. return false;
  4105. }
  4106. static bool renameSymbol (Term* const t, const String& oldName, const String& newName)
  4107. {
  4108. Symbol* const sym = dynamic_cast <Symbol*> (t);
  4109. if (sym != 0 && sym->mainSymbol == oldName)
  4110. {
  4111. sym->mainSymbol = newName;
  4112. return true;
  4113. }
  4114. bool anyChanged = false;
  4115. for (int i = t->getNumInputs(); --i >= 0;)
  4116. if (renameSymbol (t->getInput (i), oldName, newName))
  4117. anyChanged = true;
  4118. return anyChanged;
  4119. }
  4120. class Parser
  4121. {
  4122. public:
  4123. Parser (const String& stringToParse, int& textIndex_)
  4124. : textString (stringToParse), textIndex (textIndex_)
  4125. {
  4126. text = textString;
  4127. }
  4128. const TermPtr readExpression()
  4129. {
  4130. TermPtr lhs (readMultiplyOrDivideExpression());
  4131. char opType;
  4132. while (lhs != 0 && readOperator ("+-", &opType))
  4133. {
  4134. TermPtr rhs (readMultiplyOrDivideExpression());
  4135. if (rhs == 0)
  4136. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4137. if (opType == '+')
  4138. lhs = new Add (lhs, rhs);
  4139. else
  4140. lhs = new Subtract (lhs, rhs);
  4141. }
  4142. return lhs;
  4143. }
  4144. private:
  4145. const String textString;
  4146. const juce_wchar* text;
  4147. int& textIndex;
  4148. static inline bool isDecimalDigit (const juce_wchar c) throw()
  4149. {
  4150. return c >= '0' && c <= '9';
  4151. }
  4152. void skipWhitespace (int& i)
  4153. {
  4154. while (CharacterFunctions::isWhitespace (text [i]))
  4155. ++i;
  4156. }
  4157. bool readChar (const juce_wchar required)
  4158. {
  4159. if (text[textIndex] == required)
  4160. {
  4161. ++textIndex;
  4162. return true;
  4163. }
  4164. return false;
  4165. }
  4166. bool readOperator (const char* ops, char* const opType = 0)
  4167. {
  4168. skipWhitespace (textIndex);
  4169. while (*ops != 0)
  4170. {
  4171. if (readChar (*ops))
  4172. {
  4173. if (opType != 0)
  4174. *opType = *ops;
  4175. return true;
  4176. }
  4177. ++ops;
  4178. }
  4179. return false;
  4180. }
  4181. bool readIdentifier (String& identifier)
  4182. {
  4183. skipWhitespace (textIndex);
  4184. int i = textIndex;
  4185. if (CharacterFunctions::isLetter (text[i]) || text[i] == '_')
  4186. {
  4187. ++i;
  4188. while (CharacterFunctions::isLetterOrDigit (text[i]) || text[i] == '_' || text[i] == '.')
  4189. ++i;
  4190. }
  4191. if (i > textIndex)
  4192. {
  4193. identifier = String (text + textIndex, i - textIndex);
  4194. textIndex = i;
  4195. return true;
  4196. }
  4197. return false;
  4198. }
  4199. Term* readNumber()
  4200. {
  4201. skipWhitespace (textIndex);
  4202. int i = textIndex;
  4203. const bool isResolutionTarget = (text[i] == '@');
  4204. if (isResolutionTarget)
  4205. {
  4206. ++i;
  4207. skipWhitespace (i);
  4208. textIndex = i;
  4209. }
  4210. if (text[i] == '-')
  4211. {
  4212. ++i;
  4213. skipWhitespace (i);
  4214. }
  4215. int numDigits = 0;
  4216. while (isDecimalDigit (text[i]))
  4217. {
  4218. ++i;
  4219. ++numDigits;
  4220. }
  4221. const bool hasPoint = (text[i] == '.');
  4222. if (hasPoint)
  4223. {
  4224. ++i;
  4225. while (isDecimalDigit (text[i]))
  4226. {
  4227. ++i;
  4228. ++numDigits;
  4229. }
  4230. }
  4231. if (numDigits == 0)
  4232. return 0;
  4233. juce_wchar c = text[i];
  4234. const bool hasExponent = (c == 'e' || c == 'E');
  4235. if (hasExponent)
  4236. {
  4237. ++i;
  4238. c = text[i];
  4239. if (c == '+' || c == '-')
  4240. ++i;
  4241. int numExpDigits = 0;
  4242. while (isDecimalDigit (text[i]))
  4243. {
  4244. ++i;
  4245. ++numExpDigits;
  4246. }
  4247. if (numExpDigits == 0)
  4248. return 0;
  4249. }
  4250. const int start = textIndex;
  4251. textIndex = i;
  4252. return new Constant (String (text + start, i - start).getDoubleValue(), isResolutionTarget);
  4253. }
  4254. const TermPtr readMultiplyOrDivideExpression()
  4255. {
  4256. TermPtr lhs (readUnaryExpression());
  4257. char opType;
  4258. while (lhs != 0 && readOperator ("*/", &opType))
  4259. {
  4260. TermPtr rhs (readUnaryExpression());
  4261. if (rhs == 0)
  4262. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4263. if (opType == '*')
  4264. lhs = new Multiply (lhs, rhs);
  4265. else
  4266. lhs = new Divide (lhs, rhs);
  4267. }
  4268. return lhs;
  4269. }
  4270. const TermPtr readUnaryExpression()
  4271. {
  4272. char opType;
  4273. if (readOperator ("+-", &opType))
  4274. {
  4275. TermPtr term (readUnaryExpression());
  4276. if (term == 0)
  4277. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4278. if (opType == '-')
  4279. term = term->negated();
  4280. return term;
  4281. }
  4282. return readPrimaryExpression();
  4283. }
  4284. const TermPtr readPrimaryExpression()
  4285. {
  4286. TermPtr e (readParenthesisedExpression());
  4287. if (e != 0)
  4288. return e;
  4289. e = readNumber();
  4290. if (e != 0)
  4291. return e;
  4292. String identifier;
  4293. if (readIdentifier (identifier))
  4294. {
  4295. if (readOperator ("(")) // method call...
  4296. {
  4297. Function* f = new Function (identifier, ReferenceCountedArray<Term>());
  4298. ScopedPointer<Term> func (f); // (can't use ScopedPointer<Function> in MSVC)
  4299. TermPtr param (readExpression());
  4300. if (param == 0)
  4301. {
  4302. if (readOperator (")"))
  4303. return func.release();
  4304. throw ParseError ("Expected parameters after \"" + identifier + " (\"");
  4305. }
  4306. f->parameters.add (param);
  4307. while (readOperator (","))
  4308. {
  4309. param = readExpression();
  4310. if (param == 0)
  4311. throw ParseError ("Expected expression after \",\"");
  4312. f->parameters.add (param);
  4313. }
  4314. if (readOperator (")"))
  4315. return func.release();
  4316. throw ParseError ("Expected \")\"");
  4317. }
  4318. else // just a symbol..
  4319. {
  4320. return new Symbol (identifier);
  4321. }
  4322. }
  4323. return 0;
  4324. }
  4325. const TermPtr readParenthesisedExpression()
  4326. {
  4327. if (! readOperator ("("))
  4328. return 0;
  4329. const TermPtr e (readExpression());
  4330. if (e == 0 || ! readOperator (")"))
  4331. return 0;
  4332. return e;
  4333. }
  4334. Parser (const Parser&);
  4335. Parser& operator= (const Parser&);
  4336. };
  4337. };
  4338. Expression::Expression()
  4339. : term (new Expression::Helpers::Constant (0, false))
  4340. {
  4341. }
  4342. Expression::~Expression()
  4343. {
  4344. }
  4345. Expression::Expression (Term* const term_)
  4346. : term (term_)
  4347. {
  4348. jassert (term != 0);
  4349. }
  4350. Expression::Expression (const double constant)
  4351. : term (new Expression::Helpers::Constant (constant, false))
  4352. {
  4353. }
  4354. Expression::Expression (const Expression& other)
  4355. : term (other.term)
  4356. {
  4357. }
  4358. Expression& Expression::operator= (const Expression& other)
  4359. {
  4360. term = other.term;
  4361. return *this;
  4362. }
  4363. Expression::Expression (const String& stringToParse)
  4364. {
  4365. int i = 0;
  4366. Helpers::Parser parser (stringToParse, i);
  4367. term = parser.readExpression();
  4368. if (term == 0)
  4369. term = new Helpers::Constant (0, false);
  4370. }
  4371. const Expression Expression::parse (const String& stringToParse, int& textIndexToStartFrom)
  4372. {
  4373. Helpers::Parser parser (stringToParse, textIndexToStartFrom);
  4374. const Helpers::TermPtr term (parser.readExpression());
  4375. if (term != 0)
  4376. return Expression (term);
  4377. return Expression();
  4378. }
  4379. double Expression::evaluate() const
  4380. {
  4381. return evaluate (Expression::EvaluationContext());
  4382. }
  4383. double Expression::evaluate (const Expression::EvaluationContext& context) const
  4384. {
  4385. return term->evaluate (context, 0);
  4386. }
  4387. const Expression Expression::operator+ (const Expression& other) const { return Expression (new Helpers::Add (term, other.term)); }
  4388. const Expression Expression::operator- (const Expression& other) const { return Expression (new Helpers::Subtract (term, other.term)); }
  4389. const Expression Expression::operator* (const Expression& other) const { return Expression (new Helpers::Multiply (term, other.term)); }
  4390. const Expression Expression::operator/ (const Expression& other) const { return Expression (new Helpers::Divide (term, other.term)); }
  4391. const Expression Expression::operator-() const { return Expression (term->negated()); }
  4392. const String Expression::toString() const
  4393. {
  4394. return term->toString();
  4395. }
  4396. const Expression Expression::symbol (const String& symbol)
  4397. {
  4398. return Expression (new Helpers::Symbol (symbol));
  4399. }
  4400. const Expression Expression::function (const String& functionName, const Array<Expression>& parameters)
  4401. {
  4402. ReferenceCountedArray<Term> params;
  4403. for (int i = 0; i < parameters.size(); ++i)
  4404. params.add (parameters.getReference(i).term);
  4405. return Expression (new Helpers::Function (functionName, params));
  4406. }
  4407. const Expression Expression::adjustedToGiveNewResult (const double targetValue,
  4408. const Expression::EvaluationContext& context) const
  4409. {
  4410. ScopedPointer<Term> newTerm (term->clone());
  4411. Helpers::Constant* termToAdjust = Helpers::findTermToAdjust (newTerm, true);
  4412. if (termToAdjust == 0)
  4413. termToAdjust = Helpers::findTermToAdjust (newTerm, false);
  4414. if (termToAdjust == 0)
  4415. {
  4416. newTerm = new Helpers::Add (newTerm.release(), new Helpers::Constant (0, false));
  4417. termToAdjust = Helpers::findTermToAdjust (newTerm, false);
  4418. }
  4419. jassert (termToAdjust != 0);
  4420. const Term* parent = Helpers::findDestinationFor (newTerm, termToAdjust);
  4421. if (parent == 0)
  4422. {
  4423. termToAdjust->value = targetValue;
  4424. }
  4425. else
  4426. {
  4427. const Helpers::TermPtr reverseTerm (parent->createTermToEvaluateInput (context, termToAdjust, targetValue, newTerm));
  4428. if (reverseTerm == 0)
  4429. return Expression (targetValue);
  4430. termToAdjust->value = reverseTerm->evaluate (context, 0);
  4431. }
  4432. return Expression (newTerm.release());
  4433. }
  4434. const Expression Expression::withRenamedSymbol (const String& oldSymbol, const String& newSymbol) const
  4435. {
  4436. jassert (newSymbol.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_"));
  4437. Expression newExpression (term->clone());
  4438. Helpers::renameSymbol (newExpression.term, oldSymbol, newSymbol);
  4439. return newExpression;
  4440. }
  4441. bool Expression::referencesSymbol (const String& symbol, const EvaluationContext* context) const
  4442. {
  4443. return term->referencesSymbol (symbol, context, 0);
  4444. }
  4445. bool Expression::usesAnySymbols() const
  4446. {
  4447. return Helpers::containsAnySymbols (term);
  4448. }
  4449. Expression::Type Expression::getType() const throw()
  4450. {
  4451. return term->getType();
  4452. }
  4453. const String Expression::getSymbol() const
  4454. {
  4455. return term->getSymbolName();
  4456. }
  4457. const String Expression::getFunction() const
  4458. {
  4459. return term->getFunctionName();
  4460. }
  4461. const String Expression::getOperator() const
  4462. {
  4463. return term->getFunctionName();
  4464. }
  4465. int Expression::getNumInputs() const
  4466. {
  4467. return term->getNumInputs();
  4468. }
  4469. const Expression Expression::getInput (int index) const
  4470. {
  4471. return Expression (term->getInput (index));
  4472. }
  4473. int Expression::Term::getOperatorPrecedence() const
  4474. {
  4475. return 0;
  4476. }
  4477. bool Expression::Term::referencesSymbol (const String&, const EvaluationContext*, int) const
  4478. {
  4479. return false;
  4480. }
  4481. int Expression::Term::getInputIndexFor (const Term*) const
  4482. {
  4483. return -1;
  4484. }
  4485. const ReferenceCountedObjectPtr<Expression::Term> Expression::Term::createTermToEvaluateInput (const EvaluationContext&, const Term*, double, Term*) const
  4486. {
  4487. jassertfalse;
  4488. return 0;
  4489. }
  4490. const ReferenceCountedObjectPtr<Expression::Term> Expression::Term::negated()
  4491. {
  4492. return new Helpers::Negate (this);
  4493. }
  4494. const String Expression::Term::getSymbolName() const
  4495. {
  4496. jassertfalse; // You should only call getSymbol() on an expression that's actually a symbol!
  4497. return String::empty;
  4498. }
  4499. const String Expression::Term::getFunctionName() const
  4500. {
  4501. jassertfalse; // You shouldn't call this for an expression that's not actually a function!
  4502. return String::empty;
  4503. }
  4504. Expression::ParseError::ParseError (const String& message)
  4505. : description (message)
  4506. {
  4507. DBG ("Expression::ParseError: " + message);
  4508. }
  4509. Expression::EvaluationError::EvaluationError (const String& message)
  4510. : description (message)
  4511. {
  4512. DBG ("Expression::EvaluationError: " + description);
  4513. }
  4514. Expression::EvaluationError::EvaluationError (const String& symbol, const String& member)
  4515. : description ("Unknown symbol: \"" + symbol + (member.isEmpty() ? "\"" : ("." + member + "\"")))
  4516. {
  4517. DBG ("Expression::EvaluationError: " + description);
  4518. }
  4519. Expression::EvaluationContext::EvaluationContext() {}
  4520. Expression::EvaluationContext::~EvaluationContext() {}
  4521. const Expression Expression::EvaluationContext::getSymbolValue (const String& symbol, const String& member) const
  4522. {
  4523. throw EvaluationError (symbol, member);
  4524. }
  4525. double Expression::EvaluationContext::evaluateFunction (const String& functionName, const double* parameters, int numParams) const
  4526. {
  4527. if (numParams > 0)
  4528. {
  4529. if (functionName == "min")
  4530. {
  4531. double v = parameters[0];
  4532. for (int i = 1; i < numParams; ++i)
  4533. v = jmin (v, parameters[i]);
  4534. return v;
  4535. }
  4536. else if (functionName == "max")
  4537. {
  4538. double v = parameters[0];
  4539. for (int i = 1; i < numParams; ++i)
  4540. v = jmax (v, parameters[i]);
  4541. return v;
  4542. }
  4543. else if (numParams == 1)
  4544. {
  4545. if (functionName == "sin") return sin (parameters[0]);
  4546. else if (functionName == "cos") return cos (parameters[0]);
  4547. else if (functionName == "tan") return tan (parameters[0]);
  4548. else if (functionName == "abs") return std::abs (parameters[0]);
  4549. }
  4550. }
  4551. throw EvaluationError ("Unknown function: \"" + functionName + "\"");
  4552. }
  4553. END_JUCE_NAMESPACE
  4554. /*** End of inlined file: juce_Expression.cpp ***/
  4555. /*** Start of inlined file: juce_BlowFish.cpp ***/
  4556. BEGIN_JUCE_NAMESPACE
  4557. BlowFish::BlowFish (const void* const keyData, const int keyBytes)
  4558. {
  4559. jassert (keyData != 0);
  4560. jassert (keyBytes > 0);
  4561. static const uint32 initialPValues [18] =
  4562. {
  4563. 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,
  4564. 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,
  4565. 0x9216d5d9, 0x8979fb1b
  4566. };
  4567. static const uint32 initialSValues [4 * 256] =
  4568. {
  4569. 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
  4570. 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
  4571. 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
  4572. 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,
  4573. 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
  4574. 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
  4575. 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,
  4576. 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
  4577. 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
  4578. 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
  4579. 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
  4580. 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
  4581. 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,
  4582. 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
  4583. 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
  4584. 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,
  4585. 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
  4586. 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
  4587. 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,
  4588. 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
  4589. 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
  4590. 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,
  4591. 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
  4592. 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
  4593. 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
  4594. 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
  4595. 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
  4596. 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,
  4597. 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
  4598. 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
  4599. 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,
  4600. 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a,
  4601. 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,
  4602. 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,
  4603. 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
  4604. 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
  4605. 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,
  4606. 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
  4607. 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
  4608. 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,
  4609. 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
  4610. 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,
  4611. 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,
  4612. 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
  4613. 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
  4614. 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,
  4615. 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
  4616. 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,
  4617. 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,
  4618. 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
  4619. 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
  4620. 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,
  4621. 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
  4622. 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,
  4623. 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,
  4624. 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
  4625. 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,
  4626. 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,
  4627. 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
  4628. 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
  4629. 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,
  4630. 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
  4631. 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,
  4632. 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7,
  4633. 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
  4634. 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
  4635. 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
  4636. 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,
  4637. 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,
  4638. 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
  4639. 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
  4640. 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,
  4641. 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
  4642. 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,
  4643. 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
  4644. 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
  4645. 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,
  4646. 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
  4647. 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
  4648. 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
  4649. 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
  4650. 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
  4651. 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,
  4652. 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,
  4653. 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
  4654. 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
  4655. 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,
  4656. 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
  4657. 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,
  4658. 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
  4659. 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
  4660. 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,
  4661. 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,
  4662. 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
  4663. 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
  4664. 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0,
  4665. 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,
  4666. 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,
  4667. 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
  4668. 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,
  4669. 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
  4670. 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
  4671. 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,
  4672. 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
  4673. 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
  4674. 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,
  4675. 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
  4676. 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
  4677. 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,
  4678. 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
  4679. 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
  4680. 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,
  4681. 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
  4682. 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
  4683. 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
  4684. 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
  4685. 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
  4686. 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,
  4687. 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
  4688. 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
  4689. 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,
  4690. 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
  4691. 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
  4692. 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,
  4693. 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
  4694. 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
  4695. 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,
  4696. 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6
  4697. };
  4698. memcpy (p, initialPValues, sizeof (p));
  4699. int i, j = 0;
  4700. for (i = 4; --i >= 0;)
  4701. {
  4702. s[i].malloc (256);
  4703. memcpy (s[i], initialSValues + i * 256, 256 * sizeof (uint32));
  4704. }
  4705. for (i = 0; i < 18; ++i)
  4706. {
  4707. uint32 d = 0;
  4708. for (int k = 0; k < 4; ++k)
  4709. {
  4710. d = (d << 8) | static_cast <const uint8*> (keyData)[j];
  4711. if (++j >= keyBytes)
  4712. j = 0;
  4713. }
  4714. p[i] = initialPValues[i] ^ d;
  4715. }
  4716. uint32 l = 0, r = 0;
  4717. for (i = 0; i < 18; i += 2)
  4718. {
  4719. encrypt (l, r);
  4720. p[i] = l;
  4721. p[i + 1] = r;
  4722. }
  4723. for (i = 0; i < 4; ++i)
  4724. {
  4725. for (j = 0; j < 256; j += 2)
  4726. {
  4727. encrypt (l, r);
  4728. s[i][j] = l;
  4729. s[i][j + 1] = r;
  4730. }
  4731. }
  4732. }
  4733. BlowFish::BlowFish (const BlowFish& other)
  4734. {
  4735. for (int i = 4; --i >= 0;)
  4736. s[i].malloc (256);
  4737. operator= (other);
  4738. }
  4739. BlowFish& BlowFish::operator= (const BlowFish& other)
  4740. {
  4741. memcpy (p, other.p, sizeof (p));
  4742. for (int i = 4; --i >= 0;)
  4743. memcpy (s[i], other.s[i], 256 * sizeof (uint32));
  4744. return *this;
  4745. }
  4746. BlowFish::~BlowFish()
  4747. {
  4748. }
  4749. uint32 BlowFish::F (const uint32 x) const throw()
  4750. {
  4751. return ((s[0][(x >> 24) & 0xff] + s[1][(x >> 16) & 0xff])
  4752. ^ s[2][(x >> 8) & 0xff]) + s[3][x & 0xff];
  4753. }
  4754. void BlowFish::encrypt (uint32& data1, uint32& data2) const throw()
  4755. {
  4756. uint32 l = data1;
  4757. uint32 r = data2;
  4758. for (int i = 0; i < 16; ++i)
  4759. {
  4760. l ^= p[i];
  4761. r ^= F(l);
  4762. swapVariables (l, r);
  4763. }
  4764. data1 = r ^ p[17];
  4765. data2 = l ^ p[16];
  4766. }
  4767. void BlowFish::decrypt (uint32& data1, uint32& data2) const throw()
  4768. {
  4769. uint32 l = data1;
  4770. uint32 r = data2;
  4771. for (int i = 17; i > 1; --i)
  4772. {
  4773. l ^= p[i];
  4774. r ^= F(l);
  4775. swapVariables (l, r);
  4776. }
  4777. data1 = r ^ p[0];
  4778. data2 = l ^ p[1];
  4779. }
  4780. END_JUCE_NAMESPACE
  4781. /*** End of inlined file: juce_BlowFish.cpp ***/
  4782. /*** Start of inlined file: juce_MD5.cpp ***/
  4783. BEGIN_JUCE_NAMESPACE
  4784. MD5::MD5()
  4785. {
  4786. zerostruct (result);
  4787. }
  4788. MD5::MD5 (const MD5& other)
  4789. {
  4790. memcpy (result, other.result, sizeof (result));
  4791. }
  4792. MD5& MD5::operator= (const MD5& other)
  4793. {
  4794. memcpy (result, other.result, sizeof (result));
  4795. return *this;
  4796. }
  4797. MD5::MD5 (const MemoryBlock& data)
  4798. {
  4799. ProcessContext context;
  4800. context.processBlock (data.getData(), data.getSize());
  4801. context.finish (result);
  4802. }
  4803. MD5::MD5 (const void* data, const size_t numBytes)
  4804. {
  4805. ProcessContext context;
  4806. context.processBlock (data, numBytes);
  4807. context.finish (result);
  4808. }
  4809. MD5::MD5 (const String& text)
  4810. {
  4811. ProcessContext context;
  4812. const int len = text.length();
  4813. const juce_wchar* const t = text;
  4814. for (int i = 0; i < len; ++i)
  4815. {
  4816. // force the string into integer-sized unicode characters, to try to make it
  4817. // get the same results on all platforms + compilers.
  4818. uint32 unicodeChar = ByteOrder::swapIfBigEndian ((uint32) t[i]);
  4819. context.processBlock (&unicodeChar, sizeof (unicodeChar));
  4820. }
  4821. context.finish (result);
  4822. }
  4823. void MD5::processStream (InputStream& input, int64 numBytesToRead)
  4824. {
  4825. ProcessContext context;
  4826. if (numBytesToRead < 0)
  4827. numBytesToRead = std::numeric_limits<int64>::max();
  4828. while (numBytesToRead > 0)
  4829. {
  4830. uint8 tempBuffer [512];
  4831. const int bytesRead = input.read (tempBuffer, (int) jmin (numBytesToRead, (int64) sizeof (tempBuffer)));
  4832. if (bytesRead <= 0)
  4833. break;
  4834. numBytesToRead -= bytesRead;
  4835. context.processBlock (tempBuffer, bytesRead);
  4836. }
  4837. context.finish (result);
  4838. }
  4839. MD5::MD5 (InputStream& input, int64 numBytesToRead)
  4840. {
  4841. processStream (input, numBytesToRead);
  4842. }
  4843. MD5::MD5 (const File& file)
  4844. {
  4845. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  4846. if (fin != 0)
  4847. processStream (*fin, -1);
  4848. else
  4849. zerostruct (result);
  4850. }
  4851. MD5::~MD5()
  4852. {
  4853. }
  4854. namespace MD5Functions
  4855. {
  4856. static void encode (void* const output, const void* const input, const int numBytes) throw()
  4857. {
  4858. for (int i = 0; i < (numBytes >> 2); ++i)
  4859. static_cast<uint32*> (output)[i] = ByteOrder::swapIfBigEndian (static_cast<const uint32*> (input) [i]);
  4860. }
  4861. static inline uint32 F (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & y) | (~x & z); }
  4862. static inline uint32 G (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & z) | (y & ~z); }
  4863. static inline uint32 H (const uint32 x, const uint32 y, const uint32 z) throw() { return x ^ y ^ z; }
  4864. static inline uint32 I (const uint32 x, const uint32 y, const uint32 z) throw() { return y ^ (x | ~z); }
  4865. static inline uint32 rotateLeft (const uint32 x, const uint32 n) throw() { return (x << n) | (x >> (32 - n)); }
  4866. static void FF (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4867. {
  4868. a += F (b, c, d) + x + ac;
  4869. a = rotateLeft (a, s) + b;
  4870. }
  4871. static void GG (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4872. {
  4873. a += G (b, c, d) + x + ac;
  4874. a = rotateLeft (a, s) + b;
  4875. }
  4876. static void HH (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4877. {
  4878. a += H (b, c, d) + x + ac;
  4879. a = rotateLeft (a, s) + b;
  4880. }
  4881. static void II (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4882. {
  4883. a += I (b, c, d) + x + ac;
  4884. a = rotateLeft (a, s) + b;
  4885. }
  4886. }
  4887. MD5::ProcessContext::ProcessContext()
  4888. {
  4889. state[0] = 0x67452301;
  4890. state[1] = 0xefcdab89;
  4891. state[2] = 0x98badcfe;
  4892. state[3] = 0x10325476;
  4893. count[0] = 0;
  4894. count[1] = 0;
  4895. }
  4896. void MD5::ProcessContext::processBlock (const void* const data, const size_t dataSize)
  4897. {
  4898. int bufferPos = ((count[0] >> 3) & 0x3F);
  4899. count[0] += (uint32) (dataSize << 3);
  4900. if (count[0] < ((uint32) dataSize << 3))
  4901. count[1]++;
  4902. count[1] += (uint32) (dataSize >> 29);
  4903. const size_t spaceLeft = 64 - bufferPos;
  4904. size_t i = 0;
  4905. if (dataSize >= spaceLeft)
  4906. {
  4907. memcpy (buffer + bufferPos, data, spaceLeft);
  4908. transform (buffer);
  4909. for (i = spaceLeft; i + 64 <= dataSize; i += 64)
  4910. transform (static_cast <const char*> (data) + i);
  4911. bufferPos = 0;
  4912. }
  4913. memcpy (buffer + bufferPos, static_cast <const char*> (data) + i, dataSize - i);
  4914. }
  4915. void MD5::ProcessContext::finish (void* const result)
  4916. {
  4917. unsigned char encodedLength[8];
  4918. MD5Functions::encode (encodedLength, count, 8);
  4919. // Pad out to 56 mod 64.
  4920. const int index = (uint32) ((count[0] >> 3) & 0x3f);
  4921. const int paddingLength = (index < 56) ? (56 - index)
  4922. : (120 - index);
  4923. uint8 paddingBuffer [64];
  4924. zeromem (paddingBuffer, paddingLength);
  4925. paddingBuffer [0] = 0x80;
  4926. processBlock (paddingBuffer, paddingLength);
  4927. processBlock (encodedLength, 8);
  4928. MD5Functions::encode (result, state, 16);
  4929. zerostruct (buffer);
  4930. }
  4931. void MD5::ProcessContext::transform (const void* const bufferToTransform)
  4932. {
  4933. using namespace MD5Functions;
  4934. uint32 a = state[0];
  4935. uint32 b = state[1];
  4936. uint32 c = state[2];
  4937. uint32 d = state[3];
  4938. uint32 x[16];
  4939. encode (x, bufferToTransform, 64);
  4940. enum Constants
  4941. {
  4942. S11 = 7, S12 = 12, S13 = 17, S14 = 22, S21 = 5, S22 = 9, S23 = 14, S24 = 20,
  4943. S31 = 4, S32 = 11, S33 = 16, S34 = 23, S41 = 6, S42 = 10, S43 = 15, S44 = 21
  4944. };
  4945. FF (a, b, c, d, x[ 0], S11, 0xd76aa478); FF (d, a, b, c, x[ 1], S12, 0xe8c7b756);
  4946. FF (c, d, a, b, x[ 2], S13, 0x242070db); FF (b, c, d, a, x[ 3], S14, 0xc1bdceee);
  4947. FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); FF (d, a, b, c, x[ 5], S12, 0x4787c62a);
  4948. FF (c, d, a, b, x[ 6], S13, 0xa8304613); FF (b, c, d, a, x[ 7], S14, 0xfd469501);
  4949. FF (a, b, c, d, x[ 8], S11, 0x698098d8); FF (d, a, b, c, x[ 9], S12, 0x8b44f7af);
  4950. FF (c, d, a, b, x[10], S13, 0xffff5bb1); FF (b, c, d, a, x[11], S14, 0x895cd7be);
  4951. FF (a, b, c, d, x[12], S11, 0x6b901122); FF (d, a, b, c, x[13], S12, 0xfd987193);
  4952. FF (c, d, a, b, x[14], S13, 0xa679438e); FF (b, c, d, a, x[15], S14, 0x49b40821);
  4953. GG (a, b, c, d, x[ 1], S21, 0xf61e2562); GG (d, a, b, c, x[ 6], S22, 0xc040b340);
  4954. GG (c, d, a, b, x[11], S23, 0x265e5a51); GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa);
  4955. GG (a, b, c, d, x[ 5], S21, 0xd62f105d); GG (d, a, b, c, x[10], S22, 0x02441453);
  4956. GG (c, d, a, b, x[15], S23, 0xd8a1e681); GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8);
  4957. GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); GG (d, a, b, c, x[14], S22, 0xc33707d6);
  4958. GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); GG (b, c, d, a, x[ 8], S24, 0x455a14ed);
  4959. GG (a, b, c, d, x[13], S21, 0xa9e3e905); GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8);
  4960. GG (c, d, a, b, x[ 7], S23, 0x676f02d9); GG (b, c, d, a, x[12], S24, 0x8d2a4c8a);
  4961. HH (a, b, c, d, x[ 5], S31, 0xfffa3942); HH (d, a, b, c, x[ 8], S32, 0x8771f681);
  4962. HH (c, d, a, b, x[11], S33, 0x6d9d6122); HH (b, c, d, a, x[14], S34, 0xfde5380c);
  4963. HH (a, b, c, d, x[ 1], S31, 0xa4beea44); HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9);
  4964. HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); HH (b, c, d, a, x[10], S34, 0xbebfbc70);
  4965. HH (a, b, c, d, x[13], S31, 0x289b7ec6); HH (d, a, b, c, x[ 0], S32, 0xeaa127fa);
  4966. HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); HH (b, c, d, a, x[ 6], S34, 0x04881d05);
  4967. HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); HH (d, a, b, c, x[12], S32, 0xe6db99e5);
  4968. HH (c, d, a, b, x[15], S33, 0x1fa27cf8); HH (b, c, d, a, x[ 2], S34, 0xc4ac5665);
  4969. II (a, b, c, d, x[ 0], S41, 0xf4292244); II (d, a, b, c, x[ 7], S42, 0x432aff97);
  4970. II (c, d, a, b, x[14], S43, 0xab9423a7); II (b, c, d, a, x[ 5], S44, 0xfc93a039);
  4971. II (a, b, c, d, x[12], S41, 0x655b59c3); II (d, a, b, c, x[ 3], S42, 0x8f0ccc92);
  4972. II (c, d, a, b, x[10], S43, 0xffeff47d); II (b, c, d, a, x[ 1], S44, 0x85845dd1);
  4973. II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); II (d, a, b, c, x[15], S42, 0xfe2ce6e0);
  4974. II (c, d, a, b, x[ 6], S43, 0xa3014314); II (b, c, d, a, x[13], S44, 0x4e0811a1);
  4975. II (a, b, c, d, x[ 4], S41, 0xf7537e82); II (d, a, b, c, x[11], S42, 0xbd3af235);
  4976. II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); II (b, c, d, a, x[ 9], S44, 0xeb86d391);
  4977. state[0] += a;
  4978. state[1] += b;
  4979. state[2] += c;
  4980. state[3] += d;
  4981. zerostruct (x);
  4982. }
  4983. const MemoryBlock MD5::getRawChecksumData() const
  4984. {
  4985. return MemoryBlock (result, sizeof (result));
  4986. }
  4987. const String MD5::toHexString() const
  4988. {
  4989. return String::toHexString (result, sizeof (result), 0);
  4990. }
  4991. bool MD5::operator== (const MD5& other) const
  4992. {
  4993. return memcmp (result, other.result, sizeof (result)) == 0;
  4994. }
  4995. bool MD5::operator!= (const MD5& other) const
  4996. {
  4997. return ! operator== (other);
  4998. }
  4999. END_JUCE_NAMESPACE
  5000. /*** End of inlined file: juce_MD5.cpp ***/
  5001. /*** Start of inlined file: juce_Primes.cpp ***/
  5002. BEGIN_JUCE_NAMESPACE
  5003. namespace PrimesHelpers
  5004. {
  5005. static void createSmallSieve (const int numBits, BigInteger& result)
  5006. {
  5007. result.setBit (numBits);
  5008. result.clearBit (numBits); // to enlarge the array
  5009. result.setBit (0);
  5010. int n = 2;
  5011. do
  5012. {
  5013. for (int i = n + n; i < numBits; i += n)
  5014. result.setBit (i);
  5015. n = result.findNextClearBit (n + 1);
  5016. }
  5017. while (n <= (numBits >> 1));
  5018. }
  5019. static void bigSieve (const BigInteger& base, const int numBits, BigInteger& result,
  5020. const BigInteger& smallSieve, const int smallSieveSize)
  5021. {
  5022. jassert (! base[0]); // must be even!
  5023. result.setBit (numBits);
  5024. result.clearBit (numBits); // to enlarge the array
  5025. int index = smallSieve.findNextClearBit (0);
  5026. do
  5027. {
  5028. const int prime = (index << 1) + 1;
  5029. BigInteger r (base), remainder;
  5030. r.divideBy (prime, remainder);
  5031. int i = prime - remainder.getBitRangeAsInt (0, 32);
  5032. if (r.isZero())
  5033. i += prime;
  5034. if ((i & 1) == 0)
  5035. i += prime;
  5036. i = (i - 1) >> 1;
  5037. while (i < numBits)
  5038. {
  5039. result.setBit (i);
  5040. i += prime;
  5041. }
  5042. index = smallSieve.findNextClearBit (index + 1);
  5043. }
  5044. while (index < smallSieveSize);
  5045. }
  5046. static bool findCandidate (const BigInteger& base, const BigInteger& sieve,
  5047. const int numBits, BigInteger& result, const int certainty)
  5048. {
  5049. for (int i = 0; i < numBits; ++i)
  5050. {
  5051. if (! sieve[i])
  5052. {
  5053. result = base + (unsigned int) ((i << 1) + 1);
  5054. if (Primes::isProbablyPrime (result, certainty))
  5055. return true;
  5056. }
  5057. }
  5058. return false;
  5059. }
  5060. static bool passesMillerRabin (const BigInteger& n, int iterations)
  5061. {
  5062. const BigInteger one (1), two (2);
  5063. const BigInteger nMinusOne (n - one);
  5064. BigInteger d (nMinusOne);
  5065. const int s = d.findNextSetBit (0);
  5066. d >>= s;
  5067. BigInteger smallPrimes;
  5068. int numBitsInSmallPrimes = 0;
  5069. for (;;)
  5070. {
  5071. numBitsInSmallPrimes += 256;
  5072. createSmallSieve (numBitsInSmallPrimes, smallPrimes);
  5073. const int numPrimesFound = numBitsInSmallPrimes - smallPrimes.countNumberOfSetBits();
  5074. if (numPrimesFound > iterations + 1)
  5075. break;
  5076. }
  5077. int smallPrime = 2;
  5078. while (--iterations >= 0)
  5079. {
  5080. smallPrime = smallPrimes.findNextClearBit (smallPrime + 1);
  5081. BigInteger r (smallPrime);
  5082. r.exponentModulo (d, n);
  5083. if (r != one && r != nMinusOne)
  5084. {
  5085. for (int j = 0; j < s; ++j)
  5086. {
  5087. r.exponentModulo (two, n);
  5088. if (r == nMinusOne)
  5089. break;
  5090. }
  5091. if (r != nMinusOne)
  5092. return false;
  5093. }
  5094. }
  5095. return true;
  5096. }
  5097. }
  5098. const BigInteger Primes::createProbablePrime (const int bitLength,
  5099. const int certainty,
  5100. const int* randomSeeds,
  5101. int numRandomSeeds)
  5102. {
  5103. using namespace PrimesHelpers;
  5104. int defaultSeeds [16];
  5105. if (numRandomSeeds <= 0)
  5106. {
  5107. randomSeeds = defaultSeeds;
  5108. numRandomSeeds = numElementsInArray (defaultSeeds);
  5109. Random r (0);
  5110. for (int j = 10; --j >= 0;)
  5111. {
  5112. r.setSeedRandomly();
  5113. for (int i = numRandomSeeds; --i >= 0;)
  5114. defaultSeeds[i] ^= r.nextInt() ^ Random::getSystemRandom().nextInt();
  5115. }
  5116. }
  5117. BigInteger smallSieve;
  5118. const int smallSieveSize = 15000;
  5119. createSmallSieve (smallSieveSize, smallSieve);
  5120. BigInteger p;
  5121. for (int i = numRandomSeeds; --i >= 0;)
  5122. {
  5123. BigInteger p2;
  5124. Random r (randomSeeds[i]);
  5125. r.fillBitsRandomly (p2, 0, bitLength);
  5126. p ^= p2;
  5127. }
  5128. p.setBit (bitLength - 1);
  5129. p.clearBit (0);
  5130. const int searchLen = jmax (1024, (bitLength / 20) * 64);
  5131. while (p.getHighestBit() < bitLength)
  5132. {
  5133. p += 2 * searchLen;
  5134. BigInteger sieve;
  5135. bigSieve (p, searchLen, sieve,
  5136. smallSieve, smallSieveSize);
  5137. BigInteger candidate;
  5138. if (findCandidate (p, sieve, searchLen, candidate, certainty))
  5139. return candidate;
  5140. }
  5141. jassertfalse;
  5142. return BigInteger();
  5143. }
  5144. bool Primes::isProbablyPrime (const BigInteger& number, const int certainty)
  5145. {
  5146. using namespace PrimesHelpers;
  5147. if (! number[0])
  5148. return false;
  5149. if (number.getHighestBit() <= 10)
  5150. {
  5151. const int num = number.getBitRangeAsInt (0, 10);
  5152. for (int i = num / 2; --i > 1;)
  5153. if (num % i == 0)
  5154. return false;
  5155. return true;
  5156. }
  5157. else
  5158. {
  5159. if (number.findGreatestCommonDivisor (2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23) != 1)
  5160. return false;
  5161. return passesMillerRabin (number, certainty);
  5162. }
  5163. }
  5164. END_JUCE_NAMESPACE
  5165. /*** End of inlined file: juce_Primes.cpp ***/
  5166. /*** Start of inlined file: juce_RSAKey.cpp ***/
  5167. BEGIN_JUCE_NAMESPACE
  5168. RSAKey::RSAKey()
  5169. {
  5170. }
  5171. RSAKey::RSAKey (const String& s)
  5172. {
  5173. if (s.containsChar (','))
  5174. {
  5175. part1.parseString (s.upToFirstOccurrenceOf (",", false, false), 16);
  5176. part2.parseString (s.fromFirstOccurrenceOf (",", false, false), 16);
  5177. }
  5178. else
  5179. {
  5180. // the string needs to be two hex numbers, comma-separated..
  5181. jassertfalse;
  5182. }
  5183. }
  5184. RSAKey::~RSAKey()
  5185. {
  5186. }
  5187. bool RSAKey::operator== (const RSAKey& other) const throw()
  5188. {
  5189. return part1 == other.part1 && part2 == other.part2;
  5190. }
  5191. bool RSAKey::operator!= (const RSAKey& other) const throw()
  5192. {
  5193. return ! operator== (other);
  5194. }
  5195. const String RSAKey::toString() const
  5196. {
  5197. return part1.toString (16) + "," + part2.toString (16);
  5198. }
  5199. bool RSAKey::applyToValue (BigInteger& value) const
  5200. {
  5201. if (part1.isZero() || part2.isZero() || value <= 0)
  5202. {
  5203. jassertfalse; // using an uninitialised key
  5204. value.clear();
  5205. return false;
  5206. }
  5207. BigInteger result;
  5208. while (! value.isZero())
  5209. {
  5210. result *= part2;
  5211. BigInteger remainder;
  5212. value.divideBy (part2, remainder);
  5213. remainder.exponentModulo (part1, part2);
  5214. result += remainder;
  5215. }
  5216. value.swapWith (result);
  5217. return true;
  5218. }
  5219. const BigInteger RSAKey::findBestCommonDivisor (const BigInteger& p, const BigInteger& q)
  5220. {
  5221. // try 3, 5, 9, 17, etc first because these only contain 2 bits and so
  5222. // are fast to divide + multiply
  5223. for (int i = 2; i <= 65536; i *= 2)
  5224. {
  5225. const BigInteger e (1 + i);
  5226. if (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne())
  5227. return e;
  5228. }
  5229. BigInteger e (4);
  5230. while (! (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne()))
  5231. ++e;
  5232. return e;
  5233. }
  5234. void RSAKey::createKeyPair (RSAKey& publicKey, RSAKey& privateKey,
  5235. const int numBits, const int* randomSeeds, const int numRandomSeeds)
  5236. {
  5237. jassert (numBits > 16); // not much point using less than this..
  5238. jassert (numRandomSeeds == 0 || numRandomSeeds >= 2); // you need to provide plenty of seeds here!
  5239. BigInteger p (Primes::createProbablePrime (numBits / 2, 30, randomSeeds, numRandomSeeds / 2));
  5240. BigInteger q (Primes::createProbablePrime (numBits - numBits / 2, 30, randomSeeds == 0 ? 0 : (randomSeeds + numRandomSeeds / 2), numRandomSeeds - numRandomSeeds / 2));
  5241. const BigInteger n (p * q);
  5242. const BigInteger m (--p * --q);
  5243. const BigInteger e (findBestCommonDivisor (p, q));
  5244. BigInteger d (e);
  5245. d.inverseModulo (m);
  5246. publicKey.part1 = e;
  5247. publicKey.part2 = n;
  5248. privateKey.part1 = d;
  5249. privateKey.part2 = n;
  5250. }
  5251. END_JUCE_NAMESPACE
  5252. /*** End of inlined file: juce_RSAKey.cpp ***/
  5253. /*** Start of inlined file: juce_InputStream.cpp ***/
  5254. BEGIN_JUCE_NAMESPACE
  5255. char InputStream::readByte()
  5256. {
  5257. char temp = 0;
  5258. read (&temp, 1);
  5259. return temp;
  5260. }
  5261. bool InputStream::readBool()
  5262. {
  5263. return readByte() != 0;
  5264. }
  5265. short InputStream::readShort()
  5266. {
  5267. char temp[2];
  5268. if (read (temp, 2) == 2)
  5269. return (short) ByteOrder::littleEndianShort (temp);
  5270. return 0;
  5271. }
  5272. short InputStream::readShortBigEndian()
  5273. {
  5274. char temp[2];
  5275. if (read (temp, 2) == 2)
  5276. return (short) ByteOrder::bigEndianShort (temp);
  5277. return 0;
  5278. }
  5279. int InputStream::readInt()
  5280. {
  5281. char temp[4];
  5282. if (read (temp, 4) == 4)
  5283. return (int) ByteOrder::littleEndianInt (temp);
  5284. return 0;
  5285. }
  5286. int InputStream::readIntBigEndian()
  5287. {
  5288. char temp[4];
  5289. if (read (temp, 4) == 4)
  5290. return (int) ByteOrder::bigEndianInt (temp);
  5291. return 0;
  5292. }
  5293. int InputStream::readCompressedInt()
  5294. {
  5295. const unsigned char sizeByte = readByte();
  5296. if (sizeByte == 0)
  5297. return 0;
  5298. const int numBytes = (sizeByte & 0x7f);
  5299. if (numBytes > 4)
  5300. {
  5301. jassertfalse; // trying to read corrupt data - this method must only be used
  5302. // to read data that was written by OutputStream::writeCompressedInt()
  5303. return 0;
  5304. }
  5305. char bytes[4] = { 0, 0, 0, 0 };
  5306. if (read (bytes, numBytes) != numBytes)
  5307. return 0;
  5308. const int num = (int) ByteOrder::littleEndianInt (bytes);
  5309. return (sizeByte >> 7) ? -num : num;
  5310. }
  5311. int64 InputStream::readInt64()
  5312. {
  5313. union { uint8 asBytes[8]; uint64 asInt64; } n;
  5314. if (read (n.asBytes, 8) == 8)
  5315. return (int64) ByteOrder::swapIfBigEndian (n.asInt64);
  5316. return 0;
  5317. }
  5318. int64 InputStream::readInt64BigEndian()
  5319. {
  5320. union { uint8 asBytes[8]; uint64 asInt64; } n;
  5321. if (read (n.asBytes, 8) == 8)
  5322. return (int64) ByteOrder::swapIfLittleEndian (n.asInt64);
  5323. return 0;
  5324. }
  5325. float InputStream::readFloat()
  5326. {
  5327. // the union below relies on these types being the same size...
  5328. static_jassert (sizeof (int32) == sizeof (float));
  5329. union { int32 asInt; float asFloat; } n;
  5330. n.asInt = (int32) readInt();
  5331. return n.asFloat;
  5332. }
  5333. float InputStream::readFloatBigEndian()
  5334. {
  5335. union { int32 asInt; float asFloat; } n;
  5336. n.asInt = (int32) readIntBigEndian();
  5337. return n.asFloat;
  5338. }
  5339. double InputStream::readDouble()
  5340. {
  5341. union { int64 asInt; double asDouble; } n;
  5342. n.asInt = readInt64();
  5343. return n.asDouble;
  5344. }
  5345. double InputStream::readDoubleBigEndian()
  5346. {
  5347. union { int64 asInt; double asDouble; } n;
  5348. n.asInt = readInt64BigEndian();
  5349. return n.asDouble;
  5350. }
  5351. const String InputStream::readString()
  5352. {
  5353. MemoryBlock buffer (256);
  5354. char* data = static_cast<char*> (buffer.getData());
  5355. size_t i = 0;
  5356. while ((data[i] = readByte()) != 0)
  5357. {
  5358. if (++i >= buffer.getSize())
  5359. {
  5360. buffer.setSize (buffer.getSize() + 512);
  5361. data = static_cast<char*> (buffer.getData());
  5362. }
  5363. }
  5364. return String::fromUTF8 (data, (int) i);
  5365. }
  5366. const String InputStream::readNextLine()
  5367. {
  5368. MemoryBlock buffer (256);
  5369. char* data = static_cast<char*> (buffer.getData());
  5370. size_t i = 0;
  5371. while ((data[i] = readByte()) != 0)
  5372. {
  5373. if (data[i] == '\n')
  5374. break;
  5375. if (data[i] == '\r')
  5376. {
  5377. const int64 lastPos = getPosition();
  5378. if (readByte() != '\n')
  5379. setPosition (lastPos);
  5380. break;
  5381. }
  5382. if (++i >= buffer.getSize())
  5383. {
  5384. buffer.setSize (buffer.getSize() + 512);
  5385. data = static_cast<char*> (buffer.getData());
  5386. }
  5387. }
  5388. return String::fromUTF8 (data, (int) i);
  5389. }
  5390. int InputStream::readIntoMemoryBlock (MemoryBlock& block, int numBytes)
  5391. {
  5392. MemoryOutputStream mo (block, true);
  5393. return mo.writeFromInputStream (*this, numBytes);
  5394. }
  5395. const String InputStream::readEntireStreamAsString()
  5396. {
  5397. MemoryOutputStream mo;
  5398. mo.writeFromInputStream (*this, -1);
  5399. return mo.toString();
  5400. }
  5401. void InputStream::skipNextBytes (int64 numBytesToSkip)
  5402. {
  5403. if (numBytesToSkip > 0)
  5404. {
  5405. const int skipBufferSize = (int) jmin (numBytesToSkip, (int64) 16384);
  5406. HeapBlock<char> temp (skipBufferSize);
  5407. while (numBytesToSkip > 0 && ! isExhausted())
  5408. numBytesToSkip -= read (temp, (int) jmin (numBytesToSkip, (int64) skipBufferSize));
  5409. }
  5410. }
  5411. END_JUCE_NAMESPACE
  5412. /*** End of inlined file: juce_InputStream.cpp ***/
  5413. /*** Start of inlined file: juce_OutputStream.cpp ***/
  5414. BEGIN_JUCE_NAMESPACE
  5415. #if JUCE_DEBUG
  5416. static Array<void*, CriticalSection> activeStreams;
  5417. void juce_CheckForDanglingStreams()
  5418. {
  5419. /*
  5420. It's always a bad idea to leak any object, but if you're leaking output
  5421. streams, then there's a good chance that you're failing to flush a file
  5422. to disk properly, which could result in corrupted data and other similar
  5423. nastiness..
  5424. */
  5425. jassert (activeStreams.size() == 0);
  5426. };
  5427. #endif
  5428. OutputStream::OutputStream()
  5429. {
  5430. #if JUCE_DEBUG
  5431. activeStreams.add (this);
  5432. #endif
  5433. }
  5434. OutputStream::~OutputStream()
  5435. {
  5436. #if JUCE_DEBUG
  5437. activeStreams.removeValue (this);
  5438. #endif
  5439. }
  5440. void OutputStream::writeBool (const bool b)
  5441. {
  5442. writeByte (b ? (char) 1
  5443. : (char) 0);
  5444. }
  5445. void OutputStream::writeByte (char byte)
  5446. {
  5447. write (&byte, 1);
  5448. }
  5449. void OutputStream::writeShort (short value)
  5450. {
  5451. const unsigned short v = ByteOrder::swapIfBigEndian ((unsigned short) value);
  5452. write (&v, 2);
  5453. }
  5454. void OutputStream::writeShortBigEndian (short value)
  5455. {
  5456. const unsigned short v = ByteOrder::swapIfLittleEndian ((unsigned short) value);
  5457. write (&v, 2);
  5458. }
  5459. void OutputStream::writeInt (int value)
  5460. {
  5461. const unsigned int v = ByteOrder::swapIfBigEndian ((unsigned int) value);
  5462. write (&v, 4);
  5463. }
  5464. void OutputStream::writeIntBigEndian (int value)
  5465. {
  5466. const unsigned int v = ByteOrder::swapIfLittleEndian ((unsigned int) value);
  5467. write (&v, 4);
  5468. }
  5469. void OutputStream::writeCompressedInt (int value)
  5470. {
  5471. unsigned int un = (value < 0) ? (unsigned int) -value
  5472. : (unsigned int) value;
  5473. uint8 data[5];
  5474. int num = 0;
  5475. while (un > 0)
  5476. {
  5477. data[++num] = (uint8) un;
  5478. un >>= 8;
  5479. }
  5480. data[0] = (uint8) num;
  5481. if (value < 0)
  5482. data[0] |= 0x80;
  5483. write (data, num + 1);
  5484. }
  5485. void OutputStream::writeInt64 (int64 value)
  5486. {
  5487. const uint64 v = ByteOrder::swapIfBigEndian ((uint64) value);
  5488. write (&v, 8);
  5489. }
  5490. void OutputStream::writeInt64BigEndian (int64 value)
  5491. {
  5492. const uint64 v = ByteOrder::swapIfLittleEndian ((uint64) value);
  5493. write (&v, 8);
  5494. }
  5495. void OutputStream::writeFloat (float value)
  5496. {
  5497. union { int asInt; float asFloat; } n;
  5498. n.asFloat = value;
  5499. writeInt (n.asInt);
  5500. }
  5501. void OutputStream::writeFloatBigEndian (float value)
  5502. {
  5503. union { int asInt; float asFloat; } n;
  5504. n.asFloat = value;
  5505. writeIntBigEndian (n.asInt);
  5506. }
  5507. void OutputStream::writeDouble (double value)
  5508. {
  5509. union { int64 asInt; double asDouble; } n;
  5510. n.asDouble = value;
  5511. writeInt64 (n.asInt);
  5512. }
  5513. void OutputStream::writeDoubleBigEndian (double value)
  5514. {
  5515. union { int64 asInt; double asDouble; } n;
  5516. n.asDouble = value;
  5517. writeInt64BigEndian (n.asInt);
  5518. }
  5519. void OutputStream::writeString (const String& text)
  5520. {
  5521. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  5522. // if lots of large, persistent strings were to be written to streams).
  5523. const int numBytes = text.getNumBytesAsUTF8() + 1;
  5524. HeapBlock<char> temp (numBytes);
  5525. text.copyToUTF8 (temp, numBytes);
  5526. write (temp, numBytes);
  5527. }
  5528. void OutputStream::writeText (const String& text, const bool asUnicode,
  5529. const bool writeUnicodeHeaderBytes)
  5530. {
  5531. if (asUnicode)
  5532. {
  5533. if (writeUnicodeHeaderBytes)
  5534. write ("\x0ff\x0fe", 2);
  5535. const juce_wchar* src = text;
  5536. bool lastCharWasReturn = false;
  5537. while (*src != 0)
  5538. {
  5539. if (*src == L'\n' && ! lastCharWasReturn)
  5540. writeShort ((short) L'\r');
  5541. lastCharWasReturn = (*src == L'\r');
  5542. writeShort ((short) *src++);
  5543. }
  5544. }
  5545. else
  5546. {
  5547. const char* src = text.toUTF8();
  5548. const char* t = src;
  5549. for (;;)
  5550. {
  5551. if (*t == '\n')
  5552. {
  5553. if (t > src)
  5554. write (src, (int) (t - src));
  5555. write ("\r\n", 2);
  5556. src = t + 1;
  5557. }
  5558. else if (*t == '\r')
  5559. {
  5560. if (t[1] == '\n')
  5561. ++t;
  5562. }
  5563. else if (*t == 0)
  5564. {
  5565. if (t > src)
  5566. write (src, (int) (t - src));
  5567. break;
  5568. }
  5569. ++t;
  5570. }
  5571. }
  5572. }
  5573. int OutputStream::writeFromInputStream (InputStream& source, int64 numBytesToWrite)
  5574. {
  5575. if (numBytesToWrite < 0)
  5576. numBytesToWrite = std::numeric_limits<int64>::max();
  5577. int numWritten = 0;
  5578. while (numBytesToWrite > 0 && ! source.isExhausted())
  5579. {
  5580. char buffer [8192];
  5581. const int num = source.read (buffer, (int) jmin (numBytesToWrite, (int64) sizeof (buffer)));
  5582. if (num <= 0)
  5583. break;
  5584. write (buffer, num);
  5585. numBytesToWrite -= num;
  5586. numWritten += num;
  5587. }
  5588. return numWritten;
  5589. }
  5590. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const int number)
  5591. {
  5592. return stream << String (number);
  5593. }
  5594. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const double number)
  5595. {
  5596. return stream << String (number);
  5597. }
  5598. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char character)
  5599. {
  5600. stream.writeByte (character);
  5601. return stream;
  5602. }
  5603. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char* const text)
  5604. {
  5605. stream.write (text, (int) strlen (text));
  5606. return stream;
  5607. }
  5608. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryBlock& data)
  5609. {
  5610. stream.write (data.getData(), (int) data.getSize());
  5611. return stream;
  5612. }
  5613. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const File& fileToRead)
  5614. {
  5615. const ScopedPointer<FileInputStream> in (fileToRead.createInputStream());
  5616. if (in != 0)
  5617. stream.writeFromInputStream (*in, -1);
  5618. return stream;
  5619. }
  5620. END_JUCE_NAMESPACE
  5621. /*** End of inlined file: juce_OutputStream.cpp ***/
  5622. /*** Start of inlined file: juce_DirectoryIterator.cpp ***/
  5623. BEGIN_JUCE_NAMESPACE
  5624. DirectoryIterator::DirectoryIterator (const File& directory,
  5625. bool isRecursive_,
  5626. const String& wildCard_,
  5627. const int whatToLookFor_)
  5628. : fileFinder (directory, isRecursive_ ? "*" : wildCard_),
  5629. wildCard (wildCard_),
  5630. path (File::addTrailingSeparator (directory.getFullPathName())),
  5631. index (-1),
  5632. totalNumFiles (-1),
  5633. whatToLookFor (whatToLookFor_),
  5634. isRecursive (isRecursive_),
  5635. hasBeenAdvanced (false)
  5636. {
  5637. // you have to specify the type of files you're looking for!
  5638. jassert ((whatToLookFor_ & (File::findFiles | File::findDirectories)) != 0);
  5639. jassert (whatToLookFor_ > 0 && whatToLookFor_ <= 7);
  5640. }
  5641. DirectoryIterator::~DirectoryIterator()
  5642. {
  5643. }
  5644. bool DirectoryIterator::next()
  5645. {
  5646. return next (0, 0, 0, 0, 0, 0);
  5647. }
  5648. bool DirectoryIterator::next (bool* const isDirResult, bool* const isHiddenResult, int64* const fileSize,
  5649. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  5650. {
  5651. hasBeenAdvanced = true;
  5652. if (subIterator != 0)
  5653. {
  5654. if (subIterator->next (isDirResult, isHiddenResult, fileSize, modTime, creationTime, isReadOnly))
  5655. return true;
  5656. subIterator = 0;
  5657. }
  5658. String filename;
  5659. bool isDirectory, isHidden;
  5660. while (fileFinder.next (filename, &isDirectory, &isHidden, fileSize, modTime, creationTime, isReadOnly))
  5661. {
  5662. ++index;
  5663. if (! filename.containsOnly ("."))
  5664. {
  5665. const File fileFound (path + filename, 0);
  5666. bool matches = false;
  5667. if (isDirectory)
  5668. {
  5669. if (isRecursive && ((whatToLookFor & File::ignoreHiddenFiles) == 0 || ! isHidden))
  5670. subIterator = new DirectoryIterator (fileFound, true, wildCard, whatToLookFor);
  5671. matches = (whatToLookFor & File::findDirectories) != 0;
  5672. }
  5673. else
  5674. {
  5675. matches = (whatToLookFor & File::findFiles) != 0;
  5676. }
  5677. // if recursive, we're not relying on the OS iterator to do the wildcard match, so do it now..
  5678. if (matches && isRecursive)
  5679. matches = filename.matchesWildcard (wildCard, ! File::areFileNamesCaseSensitive());
  5680. if (matches && (whatToLookFor & File::ignoreHiddenFiles) != 0)
  5681. matches = ! isHidden;
  5682. if (matches)
  5683. {
  5684. currentFile = fileFound;
  5685. if (isHiddenResult != 0) *isHiddenResult = isHidden;
  5686. if (isDirResult != 0) *isDirResult = isDirectory;
  5687. return true;
  5688. }
  5689. else if (subIterator != 0)
  5690. {
  5691. return next();
  5692. }
  5693. }
  5694. }
  5695. return false;
  5696. }
  5697. const File DirectoryIterator::getFile() const
  5698. {
  5699. if (subIterator != 0 && subIterator->hasBeenAdvanced)
  5700. return subIterator->getFile();
  5701. // You need to call DirectoryIterator::next() before asking it for the file that it found!
  5702. jassert (hasBeenAdvanced);
  5703. return currentFile;
  5704. }
  5705. float DirectoryIterator::getEstimatedProgress() const
  5706. {
  5707. if (totalNumFiles < 0)
  5708. totalNumFiles = File (path).getNumberOfChildFiles (File::findFilesAndDirectories);
  5709. if (totalNumFiles <= 0)
  5710. return 0.0f;
  5711. const float detailedIndex = (subIterator != 0) ? index + subIterator->getEstimatedProgress()
  5712. : (float) index;
  5713. return detailedIndex / totalNumFiles;
  5714. }
  5715. END_JUCE_NAMESPACE
  5716. /*** End of inlined file: juce_DirectoryIterator.cpp ***/
  5717. /*** Start of inlined file: juce_File.cpp ***/
  5718. #if ! JUCE_WINDOWS
  5719. #include <pwd.h>
  5720. #endif
  5721. BEGIN_JUCE_NAMESPACE
  5722. File::File (const String& fullPathName)
  5723. : fullPath (parseAbsolutePath (fullPathName))
  5724. {
  5725. }
  5726. File::File (const String& path, int)
  5727. : fullPath (path)
  5728. {
  5729. }
  5730. const File File::createFileWithoutCheckingPath (const String& path)
  5731. {
  5732. return File (path, 0);
  5733. }
  5734. File::File (const File& other)
  5735. : fullPath (other.fullPath)
  5736. {
  5737. }
  5738. File& File::operator= (const String& newPath)
  5739. {
  5740. fullPath = parseAbsolutePath (newPath);
  5741. return *this;
  5742. }
  5743. File& File::operator= (const File& other)
  5744. {
  5745. fullPath = other.fullPath;
  5746. return *this;
  5747. }
  5748. const File File::nonexistent;
  5749. const String File::parseAbsolutePath (const String& p)
  5750. {
  5751. if (p.isEmpty())
  5752. return String::empty;
  5753. #if JUCE_WINDOWS
  5754. // Windows..
  5755. String path (p.replaceCharacter ('/', '\\'));
  5756. if (path.startsWithChar (File::separator))
  5757. {
  5758. if (path[1] != File::separator)
  5759. {
  5760. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  5761. If you're trying to parse a string that may be either a relative path or an absolute path,
  5762. you MUST provide a context against which the partial path can be evaluated - you can do
  5763. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  5764. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  5765. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  5766. */
  5767. jassertfalse;
  5768. path = File::getCurrentWorkingDirectory().getFullPathName().substring (0, 2) + path;
  5769. }
  5770. }
  5771. else if (! path.containsChar (':'))
  5772. {
  5773. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  5774. If you're trying to parse a string that may be either a relative path or an absolute path,
  5775. you MUST provide a context against which the partial path can be evaluated - you can do
  5776. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  5777. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  5778. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  5779. */
  5780. jassertfalse;
  5781. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  5782. }
  5783. #else
  5784. // Mac or Linux..
  5785. String path (p.replaceCharacter ('\\', '/'));
  5786. if (path.startsWithChar ('~'))
  5787. {
  5788. if (path[1] == File::separator || path[1] == 0)
  5789. {
  5790. // expand a name of the form "~/abc"
  5791. path = File::getSpecialLocation (File::userHomeDirectory).getFullPathName()
  5792. + path.substring (1);
  5793. }
  5794. else
  5795. {
  5796. // expand a name of type "~dave/abc"
  5797. const String userName (path.substring (1).upToFirstOccurrenceOf ("/", false, false));
  5798. struct passwd* const pw = getpwnam (userName.toUTF8());
  5799. if (pw != 0)
  5800. path = addTrailingSeparator (pw->pw_dir) + path.fromFirstOccurrenceOf ("/", false, false);
  5801. }
  5802. }
  5803. else if (! path.startsWithChar (File::separator))
  5804. {
  5805. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  5806. If you're trying to parse a string that may be either a relative path or an absolute path,
  5807. you MUST provide a context against which the partial path can be evaluated - you can do
  5808. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  5809. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  5810. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  5811. */
  5812. jassert (path.startsWith ("./") || path.startsWith ("../")); // (assume that a path "./xyz" is deliberately intended to be relative to the CWD)
  5813. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  5814. }
  5815. #endif
  5816. while (path.endsWithChar (separator) && path != separatorString) // careful not to turn a single "/" into an empty string.
  5817. path = path.dropLastCharacters (1);
  5818. return path;
  5819. }
  5820. const String File::addTrailingSeparator (const String& path)
  5821. {
  5822. return path.endsWithChar (File::separator) ? path
  5823. : path + File::separator;
  5824. }
  5825. #if JUCE_LINUX
  5826. #define NAMES_ARE_CASE_SENSITIVE 1
  5827. #endif
  5828. bool File::areFileNamesCaseSensitive()
  5829. {
  5830. #if NAMES_ARE_CASE_SENSITIVE
  5831. return true;
  5832. #else
  5833. return false;
  5834. #endif
  5835. }
  5836. bool File::operator== (const File& other) const
  5837. {
  5838. #if NAMES_ARE_CASE_SENSITIVE
  5839. return fullPath == other.fullPath;
  5840. #else
  5841. return fullPath.equalsIgnoreCase (other.fullPath);
  5842. #endif
  5843. }
  5844. bool File::operator!= (const File& other) const
  5845. {
  5846. return ! operator== (other);
  5847. }
  5848. bool File::operator< (const File& other) const
  5849. {
  5850. #if NAMES_ARE_CASE_SENSITIVE
  5851. return fullPath < other.fullPath;
  5852. #else
  5853. return fullPath.compareIgnoreCase (other.fullPath) < 0;
  5854. #endif
  5855. }
  5856. bool File::operator> (const File& other) const
  5857. {
  5858. #if NAMES_ARE_CASE_SENSITIVE
  5859. return fullPath > other.fullPath;
  5860. #else
  5861. return fullPath.compareIgnoreCase (other.fullPath) > 0;
  5862. #endif
  5863. }
  5864. bool File::setReadOnly (const bool shouldBeReadOnly,
  5865. const bool applyRecursively) const
  5866. {
  5867. bool worked = true;
  5868. if (applyRecursively && isDirectory())
  5869. {
  5870. Array <File> subFiles;
  5871. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  5872. for (int i = subFiles.size(); --i >= 0;)
  5873. worked = subFiles.getReference(i).setReadOnly (shouldBeReadOnly, true) && worked;
  5874. }
  5875. return setFileReadOnlyInternal (shouldBeReadOnly) && worked;
  5876. }
  5877. bool File::deleteRecursively() const
  5878. {
  5879. bool worked = true;
  5880. if (isDirectory())
  5881. {
  5882. Array<File> subFiles;
  5883. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  5884. for (int i = subFiles.size(); --i >= 0;)
  5885. worked = subFiles.getReference(i).deleteRecursively() && worked;
  5886. }
  5887. return deleteFile() && worked;
  5888. }
  5889. bool File::moveFileTo (const File& newFile) const
  5890. {
  5891. if (newFile.fullPath == fullPath)
  5892. return true;
  5893. #if ! NAMES_ARE_CASE_SENSITIVE
  5894. if (*this != newFile)
  5895. #endif
  5896. if (! newFile.deleteFile())
  5897. return false;
  5898. return moveInternal (newFile);
  5899. }
  5900. bool File::copyFileTo (const File& newFile) const
  5901. {
  5902. return (*this == newFile)
  5903. || (exists() && newFile.deleteFile() && copyInternal (newFile));
  5904. }
  5905. bool File::copyDirectoryTo (const File& newDirectory) const
  5906. {
  5907. if (isDirectory() && newDirectory.createDirectory())
  5908. {
  5909. Array<File> subFiles;
  5910. findChildFiles (subFiles, File::findFiles, false);
  5911. int i;
  5912. for (i = 0; i < subFiles.size(); ++i)
  5913. if (! subFiles.getReference(i).copyFileTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  5914. return false;
  5915. subFiles.clear();
  5916. findChildFiles (subFiles, File::findDirectories, false);
  5917. for (i = 0; i < subFiles.size(); ++i)
  5918. if (! subFiles.getReference(i).copyDirectoryTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  5919. return false;
  5920. return true;
  5921. }
  5922. return false;
  5923. }
  5924. const String File::getPathUpToLastSlash() const
  5925. {
  5926. const int lastSlash = fullPath.lastIndexOfChar (separator);
  5927. if (lastSlash > 0)
  5928. return fullPath.substring (0, lastSlash);
  5929. else if (lastSlash == 0)
  5930. return separatorString;
  5931. else
  5932. return fullPath;
  5933. }
  5934. const File File::getParentDirectory() const
  5935. {
  5936. return File (getPathUpToLastSlash(), (int) 0);
  5937. }
  5938. const String File::getFileName() const
  5939. {
  5940. return fullPath.substring (fullPath.lastIndexOfChar (separator) + 1);
  5941. }
  5942. int File::hashCode() const
  5943. {
  5944. return fullPath.hashCode();
  5945. }
  5946. int64 File::hashCode64() const
  5947. {
  5948. return fullPath.hashCode64();
  5949. }
  5950. const String File::getFileNameWithoutExtension() const
  5951. {
  5952. const int lastSlash = fullPath.lastIndexOfChar (separator) + 1;
  5953. const int lastDot = fullPath.lastIndexOfChar ('.');
  5954. if (lastDot > lastSlash)
  5955. return fullPath.substring (lastSlash, lastDot);
  5956. else
  5957. return fullPath.substring (lastSlash);
  5958. }
  5959. bool File::isAChildOf (const File& potentialParent) const
  5960. {
  5961. if (potentialParent == File::nonexistent)
  5962. return false;
  5963. const String ourPath (getPathUpToLastSlash());
  5964. #if NAMES_ARE_CASE_SENSITIVE
  5965. if (potentialParent.fullPath == ourPath)
  5966. #else
  5967. if (potentialParent.fullPath.equalsIgnoreCase (ourPath))
  5968. #endif
  5969. {
  5970. return true;
  5971. }
  5972. else if (potentialParent.fullPath.length() >= ourPath.length())
  5973. {
  5974. return false;
  5975. }
  5976. else
  5977. {
  5978. return getParentDirectory().isAChildOf (potentialParent);
  5979. }
  5980. }
  5981. bool File::isAbsolutePath (const String& path)
  5982. {
  5983. return path.startsWithChar ('/') || path.startsWithChar ('\\')
  5984. #if JUCE_WINDOWS
  5985. || (path.isNotEmpty() && path[1] == ':');
  5986. #else
  5987. || path.startsWithChar ('~');
  5988. #endif
  5989. }
  5990. const File File::getChildFile (String relativePath) const
  5991. {
  5992. if (isAbsolutePath (relativePath))
  5993. {
  5994. // the path is really absolute..
  5995. return File (relativePath);
  5996. }
  5997. else
  5998. {
  5999. // it's relative, so remove any ../ or ./ bits at the start.
  6000. String path (fullPath);
  6001. if (relativePath[0] == '.')
  6002. {
  6003. #if JUCE_WINDOWS
  6004. relativePath = relativePath.replaceCharacter ('/', '\\').trimStart();
  6005. #else
  6006. relativePath = relativePath.replaceCharacter ('\\', '/').trimStart();
  6007. #endif
  6008. while (relativePath[0] == '.')
  6009. {
  6010. if (relativePath[1] == '.')
  6011. {
  6012. if (relativePath [2] == 0 || relativePath[2] == separator)
  6013. {
  6014. const int lastSlash = path.lastIndexOfChar (separator);
  6015. if (lastSlash >= 0)
  6016. path = path.substring (0, lastSlash);
  6017. relativePath = relativePath.substring (3);
  6018. }
  6019. else
  6020. {
  6021. break;
  6022. }
  6023. }
  6024. else if (relativePath[1] == separator)
  6025. {
  6026. relativePath = relativePath.substring (2);
  6027. }
  6028. else
  6029. {
  6030. break;
  6031. }
  6032. }
  6033. }
  6034. return File (addTrailingSeparator (path) + relativePath);
  6035. }
  6036. }
  6037. const File File::getSiblingFile (const String& fileName) const
  6038. {
  6039. return getParentDirectory().getChildFile (fileName);
  6040. }
  6041. const String File::descriptionOfSizeInBytes (const int64 bytes)
  6042. {
  6043. if (bytes == 1)
  6044. {
  6045. return "1 byte";
  6046. }
  6047. else if (bytes < 1024)
  6048. {
  6049. return String ((int) bytes) + " bytes";
  6050. }
  6051. else if (bytes < 1024 * 1024)
  6052. {
  6053. return String (bytes / 1024.0, 1) + " KB";
  6054. }
  6055. else if (bytes < 1024 * 1024 * 1024)
  6056. {
  6057. return String (bytes / (1024.0 * 1024.0), 1) + " MB";
  6058. }
  6059. else
  6060. {
  6061. return String (bytes / (1024.0 * 1024.0 * 1024.0), 1) + " GB";
  6062. }
  6063. }
  6064. bool File::create() const
  6065. {
  6066. if (exists())
  6067. return true;
  6068. {
  6069. const File parentDir (getParentDirectory());
  6070. if (parentDir == *this || ! parentDir.createDirectory())
  6071. return false;
  6072. FileOutputStream fo (*this, 8);
  6073. }
  6074. return exists();
  6075. }
  6076. bool File::createDirectory() const
  6077. {
  6078. if (! isDirectory())
  6079. {
  6080. const File parentDir (getParentDirectory());
  6081. if (parentDir == *this || ! parentDir.createDirectory())
  6082. return false;
  6083. createDirectoryInternal (fullPath.trimCharactersAtEnd (separatorString));
  6084. return isDirectory();
  6085. }
  6086. return true;
  6087. }
  6088. const Time File::getCreationTime() const
  6089. {
  6090. int64 m, a, c;
  6091. getFileTimesInternal (m, a, c);
  6092. return Time (c);
  6093. }
  6094. const Time File::getLastModificationTime() const
  6095. {
  6096. int64 m, a, c;
  6097. getFileTimesInternal (m, a, c);
  6098. return Time (m);
  6099. }
  6100. const Time File::getLastAccessTime() const
  6101. {
  6102. int64 m, a, c;
  6103. getFileTimesInternal (m, a, c);
  6104. return Time (a);
  6105. }
  6106. bool File::setLastModificationTime (const Time& t) const { return setFileTimesInternal (t.toMilliseconds(), 0, 0); }
  6107. bool File::setLastAccessTime (const Time& t) const { return setFileTimesInternal (0, t.toMilliseconds(), 0); }
  6108. bool File::setCreationTime (const Time& t) const { return setFileTimesInternal (0, 0, t.toMilliseconds()); }
  6109. bool File::loadFileAsData (MemoryBlock& destBlock) const
  6110. {
  6111. if (! existsAsFile())
  6112. return false;
  6113. FileInputStream in (*this);
  6114. return getSize() == in.readIntoMemoryBlock (destBlock);
  6115. }
  6116. const String File::loadFileAsString() const
  6117. {
  6118. if (! existsAsFile())
  6119. return String::empty;
  6120. FileInputStream in (*this);
  6121. return in.readEntireStreamAsString();
  6122. }
  6123. int File::findChildFiles (Array<File>& results,
  6124. const int whatToLookFor,
  6125. const bool searchRecursively,
  6126. const String& wildCardPattern) const
  6127. {
  6128. DirectoryIterator di (*this, searchRecursively, wildCardPattern, whatToLookFor);
  6129. int total = 0;
  6130. while (di.next())
  6131. {
  6132. results.add (di.getFile());
  6133. ++total;
  6134. }
  6135. return total;
  6136. }
  6137. int File::getNumberOfChildFiles (const int whatToLookFor, const String& wildCardPattern) const
  6138. {
  6139. DirectoryIterator di (*this, false, wildCardPattern, whatToLookFor);
  6140. int total = 0;
  6141. while (di.next())
  6142. ++total;
  6143. return total;
  6144. }
  6145. bool File::containsSubDirectories() const
  6146. {
  6147. if (isDirectory())
  6148. {
  6149. DirectoryIterator di (*this, false, "*", findDirectories);
  6150. return di.next();
  6151. }
  6152. return false;
  6153. }
  6154. const File File::getNonexistentChildFile (const String& prefix_,
  6155. const String& suffix,
  6156. bool putNumbersInBrackets) const
  6157. {
  6158. File f (getChildFile (prefix_ + suffix));
  6159. if (f.exists())
  6160. {
  6161. int num = 2;
  6162. String prefix (prefix_);
  6163. // remove any bracketed numbers that may already be on the end..
  6164. if (prefix.trim().endsWithChar (')'))
  6165. {
  6166. putNumbersInBrackets = true;
  6167. const int openBracks = prefix.lastIndexOfChar ('(');
  6168. const int closeBracks = prefix.lastIndexOfChar (')');
  6169. if (openBracks > 0
  6170. && closeBracks > openBracks
  6171. && prefix.substring (openBracks + 1, closeBracks).containsOnly ("0123456789"))
  6172. {
  6173. num = prefix.substring (openBracks + 1, closeBracks).getIntValue() + 1;
  6174. prefix = prefix.substring (0, openBracks);
  6175. }
  6176. }
  6177. // also use brackets if it ends in a digit.
  6178. putNumbersInBrackets = putNumbersInBrackets
  6179. || CharacterFunctions::isDigit (prefix.getLastCharacter());
  6180. do
  6181. {
  6182. if (putNumbersInBrackets)
  6183. f = getChildFile (prefix + '(' + String (num++) + ')' + suffix);
  6184. else
  6185. f = getChildFile (prefix + String (num++) + suffix);
  6186. } while (f.exists());
  6187. }
  6188. return f;
  6189. }
  6190. const File File::getNonexistentSibling (const bool putNumbersInBrackets) const
  6191. {
  6192. if (exists())
  6193. {
  6194. return getParentDirectory()
  6195. .getNonexistentChildFile (getFileNameWithoutExtension(),
  6196. getFileExtension(),
  6197. putNumbersInBrackets);
  6198. }
  6199. else
  6200. {
  6201. return *this;
  6202. }
  6203. }
  6204. const String File::getFileExtension() const
  6205. {
  6206. String ext;
  6207. if (! isDirectory())
  6208. {
  6209. const int indexOfDot = fullPath.lastIndexOfChar ('.');
  6210. if (indexOfDot > fullPath.lastIndexOfChar (separator))
  6211. ext = fullPath.substring (indexOfDot);
  6212. }
  6213. return ext;
  6214. }
  6215. bool File::hasFileExtension (const String& possibleSuffix) const
  6216. {
  6217. if (possibleSuffix.isEmpty())
  6218. return fullPath.lastIndexOfChar ('.') <= fullPath.lastIndexOfChar (separator);
  6219. const int semicolon = possibleSuffix.indexOfChar (0, ';');
  6220. if (semicolon >= 0)
  6221. {
  6222. return hasFileExtension (possibleSuffix.substring (0, semicolon).trimEnd())
  6223. || hasFileExtension (possibleSuffix.substring (semicolon + 1).trimStart());
  6224. }
  6225. else
  6226. {
  6227. if (fullPath.endsWithIgnoreCase (possibleSuffix))
  6228. {
  6229. if (possibleSuffix.startsWithChar ('.'))
  6230. return true;
  6231. const int dotPos = fullPath.length() - possibleSuffix.length() - 1;
  6232. if (dotPos >= 0)
  6233. return fullPath [dotPos] == '.';
  6234. }
  6235. }
  6236. return false;
  6237. }
  6238. const File File::withFileExtension (const String& newExtension) const
  6239. {
  6240. if (fullPath.isEmpty())
  6241. return File::nonexistent;
  6242. String filePart (getFileName());
  6243. int i = filePart.lastIndexOfChar ('.');
  6244. if (i >= 0)
  6245. filePart = filePart.substring (0, i);
  6246. if (newExtension.isNotEmpty() && ! newExtension.startsWithChar ('.'))
  6247. filePart << '.';
  6248. return getSiblingFile (filePart + newExtension);
  6249. }
  6250. bool File::startAsProcess (const String& parameters) const
  6251. {
  6252. return exists() && PlatformUtilities::openDocument (fullPath, parameters);
  6253. }
  6254. FileInputStream* File::createInputStream() const
  6255. {
  6256. if (existsAsFile())
  6257. return new FileInputStream (*this);
  6258. return 0;
  6259. }
  6260. FileOutputStream* File::createOutputStream (const int bufferSize) const
  6261. {
  6262. ScopedPointer <FileOutputStream> out (new FileOutputStream (*this, bufferSize));
  6263. if (out->failedToOpen())
  6264. return 0;
  6265. return out.release();
  6266. }
  6267. bool File::appendData (const void* const dataToAppend,
  6268. const int numberOfBytes) const
  6269. {
  6270. if (numberOfBytes > 0)
  6271. {
  6272. const ScopedPointer <FileOutputStream> out (createOutputStream());
  6273. if (out == 0)
  6274. return false;
  6275. out->write (dataToAppend, numberOfBytes);
  6276. }
  6277. return true;
  6278. }
  6279. bool File::replaceWithData (const void* const dataToWrite,
  6280. const int numberOfBytes) const
  6281. {
  6282. jassert (numberOfBytes >= 0); // a negative number of bytes??
  6283. if (numberOfBytes <= 0)
  6284. return deleteFile();
  6285. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  6286. tempFile.getFile().appendData (dataToWrite, numberOfBytes);
  6287. return tempFile.overwriteTargetFileWithTemporary();
  6288. }
  6289. bool File::appendText (const String& text,
  6290. const bool asUnicode,
  6291. const bool writeUnicodeHeaderBytes) const
  6292. {
  6293. const ScopedPointer <FileOutputStream> out (createOutputStream());
  6294. if (out != 0)
  6295. {
  6296. out->writeText (text, asUnicode, writeUnicodeHeaderBytes);
  6297. return true;
  6298. }
  6299. return false;
  6300. }
  6301. bool File::replaceWithText (const String& textToWrite,
  6302. const bool asUnicode,
  6303. const bool writeUnicodeHeaderBytes) const
  6304. {
  6305. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  6306. tempFile.getFile().appendText (textToWrite, asUnicode, writeUnicodeHeaderBytes);
  6307. return tempFile.overwriteTargetFileWithTemporary();
  6308. }
  6309. bool File::hasIdenticalContentTo (const File& other) const
  6310. {
  6311. if (other == *this)
  6312. return true;
  6313. if (getSize() == other.getSize() && existsAsFile() && other.existsAsFile())
  6314. {
  6315. FileInputStream in1 (*this), in2 (other);
  6316. const int bufferSize = 4096;
  6317. HeapBlock <char> buffer1, buffer2;
  6318. buffer1.malloc (bufferSize);
  6319. buffer2.malloc (bufferSize);
  6320. for (;;)
  6321. {
  6322. const int num1 = in1.read (buffer1, bufferSize);
  6323. const int num2 = in2.read (buffer2, bufferSize);
  6324. if (num1 != num2)
  6325. break;
  6326. if (num1 <= 0)
  6327. return true;
  6328. if (memcmp (buffer1, buffer2, num1) != 0)
  6329. break;
  6330. }
  6331. }
  6332. return false;
  6333. }
  6334. const String File::createLegalPathName (const String& original)
  6335. {
  6336. String s (original);
  6337. String start;
  6338. if (s[1] == ':')
  6339. {
  6340. start = s.substring (0, 2);
  6341. s = s.substring (2);
  6342. }
  6343. return start + s.removeCharacters ("\"#@,;:<>*^|?")
  6344. .substring (0, 1024);
  6345. }
  6346. const String File::createLegalFileName (const String& original)
  6347. {
  6348. String s (original.removeCharacters ("\"#@,;:<>*^|?\\/"));
  6349. const int maxLength = 128; // only the length of the filename, not the whole path
  6350. const int len = s.length();
  6351. if (len > maxLength)
  6352. {
  6353. const int lastDot = s.lastIndexOfChar ('.');
  6354. if (lastDot > jmax (0, len - 12))
  6355. {
  6356. s = s.substring (0, maxLength - (len - lastDot))
  6357. + s.substring (lastDot);
  6358. }
  6359. else
  6360. {
  6361. s = s.substring (0, maxLength);
  6362. }
  6363. }
  6364. return s;
  6365. }
  6366. const String File::getRelativePathFrom (const File& dir) const
  6367. {
  6368. String thisPath (fullPath);
  6369. {
  6370. int len = thisPath.length();
  6371. while (--len >= 0 && thisPath [len] == File::separator)
  6372. thisPath [len] = 0;
  6373. }
  6374. String dirPath (addTrailingSeparator (dir.existsAsFile() ? dir.getParentDirectory().getFullPathName()
  6375. : dir.fullPath));
  6376. const int len = jmin (thisPath.length(), dirPath.length());
  6377. int commonBitLength = 0;
  6378. for (int i = 0; i < len; ++i)
  6379. {
  6380. #if NAMES_ARE_CASE_SENSITIVE
  6381. if (thisPath[i] != dirPath[i])
  6382. #else
  6383. if (CharacterFunctions::toLowerCase (thisPath[i])
  6384. != CharacterFunctions::toLowerCase (dirPath[i]))
  6385. #endif
  6386. {
  6387. break;
  6388. }
  6389. ++commonBitLength;
  6390. }
  6391. while (commonBitLength > 0 && thisPath [commonBitLength - 1] != File::separator)
  6392. --commonBitLength;
  6393. // if the only common bit is the root, then just return the full path..
  6394. if (commonBitLength <= 0
  6395. || (commonBitLength == 1 && thisPath [1] == File::separator))
  6396. return fullPath;
  6397. thisPath = thisPath.substring (commonBitLength);
  6398. dirPath = dirPath.substring (commonBitLength);
  6399. while (dirPath.isNotEmpty())
  6400. {
  6401. #if JUCE_WINDOWS
  6402. thisPath = "..\\" + thisPath;
  6403. #else
  6404. thisPath = "../" + thisPath;
  6405. #endif
  6406. const int sep = dirPath.indexOfChar (separator);
  6407. if (sep >= 0)
  6408. dirPath = dirPath.substring (sep + 1);
  6409. else
  6410. dirPath = String::empty;
  6411. }
  6412. return thisPath;
  6413. }
  6414. const File File::createTempFile (const String& fileNameEnding)
  6415. {
  6416. const File tempFile (getSpecialLocation (tempDirectory)
  6417. .getChildFile ("temp_" + String (Random::getSystemRandom().nextInt()))
  6418. .withFileExtension (fileNameEnding));
  6419. if (tempFile.exists())
  6420. return createTempFile (fileNameEnding);
  6421. else
  6422. return tempFile;
  6423. }
  6424. #if JUCE_UNIT_TESTS
  6425. class FileTests : public UnitTest
  6426. {
  6427. public:
  6428. FileTests() : UnitTest ("Files") {}
  6429. void runTest()
  6430. {
  6431. beginTest ("Reading");
  6432. const File home (File::getSpecialLocation (File::userHomeDirectory));
  6433. const File temp (File::getSpecialLocation (File::tempDirectory));
  6434. expect (! File::nonexistent.exists());
  6435. expect (home.isDirectory());
  6436. expect (home.exists());
  6437. expect (! home.existsAsFile());
  6438. expect (File::getSpecialLocation (File::userDocumentsDirectory).isDirectory());
  6439. expect (File::getSpecialLocation (File::userApplicationDataDirectory).isDirectory());
  6440. expect (File::getSpecialLocation (File::currentExecutableFile).exists());
  6441. expect (File::getSpecialLocation (File::currentApplicationFile).exists());
  6442. expect (File::getSpecialLocation (File::invokedExecutableFile).exists());
  6443. expect (home.getVolumeTotalSize() > 1024 * 1024);
  6444. expect (home.getBytesFreeOnVolume() > 0);
  6445. expect (! home.isHidden());
  6446. expect (home.isOnHardDisk());
  6447. expect (! home.isOnCDRomDrive());
  6448. expect (File::getCurrentWorkingDirectory().exists());
  6449. expect (home.setAsCurrentWorkingDirectory());
  6450. expect (File::getCurrentWorkingDirectory() == home);
  6451. {
  6452. Array<File> roots;
  6453. File::findFileSystemRoots (roots);
  6454. expect (roots.size() > 0);
  6455. int numRootsExisting = 0;
  6456. for (int i = 0; i < roots.size(); ++i)
  6457. if (roots[i].exists())
  6458. ++numRootsExisting;
  6459. // (on windows, some of the drives may not contain media, so as long as at least one is ok..)
  6460. expect (numRootsExisting > 0);
  6461. }
  6462. beginTest ("Writing");
  6463. File demoFolder (temp.getChildFile ("Juce UnitTests Temp Folder.folder"));
  6464. expect (demoFolder.deleteRecursively());
  6465. expect (demoFolder.createDirectory());
  6466. expect (demoFolder.isDirectory());
  6467. expect (demoFolder.getParentDirectory() == temp);
  6468. expect (temp.isDirectory());
  6469. {
  6470. Array<File> files;
  6471. temp.findChildFiles (files, File::findFilesAndDirectories, false, "*");
  6472. expect (files.contains (demoFolder));
  6473. }
  6474. {
  6475. Array<File> files;
  6476. temp.findChildFiles (files, File::findDirectories, true, "*.folder");
  6477. expect (files.contains (demoFolder));
  6478. }
  6479. File tempFile (demoFolder.getNonexistentChildFile ("test", ".txt", false));
  6480. expect (tempFile.getFileExtension() == ".txt");
  6481. expect (tempFile.hasFileExtension (".txt"));
  6482. expect (tempFile.hasFileExtension ("txt"));
  6483. expect (tempFile.withFileExtension ("xyz").hasFileExtension (".xyz"));
  6484. expect (tempFile.getSiblingFile ("foo").isAChildOf (temp));
  6485. expect (tempFile.hasWriteAccess());
  6486. {
  6487. FileOutputStream fo (tempFile);
  6488. fo.write ("0123456789", 10);
  6489. }
  6490. expect (tempFile.exists());
  6491. expect (tempFile.getSize() == 10);
  6492. expect (std::abs ((int) (tempFile.getLastModificationTime().toMilliseconds() - Time::getCurrentTime().toMilliseconds())) < 3000);
  6493. expect (tempFile.loadFileAsString() == "0123456789");
  6494. expect (! demoFolder.containsSubDirectories());
  6495. expect (demoFolder.getNumberOfChildFiles (File::findFiles) == 1);
  6496. expect (demoFolder.getNumberOfChildFiles (File::findFilesAndDirectories) == 1);
  6497. expect (demoFolder.getNumberOfChildFiles (File::findDirectories) == 0);
  6498. demoFolder.getNonexistentChildFile ("tempFolder", "", false).createDirectory();
  6499. expect (demoFolder.getNumberOfChildFiles (File::findDirectories) == 1);
  6500. expect (demoFolder.getNumberOfChildFiles (File::findFilesAndDirectories) == 2);
  6501. expect (demoFolder.containsSubDirectories());
  6502. expect (tempFile.hasWriteAccess());
  6503. tempFile.setReadOnly (true);
  6504. expect (! tempFile.hasWriteAccess());
  6505. tempFile.setReadOnly (false);
  6506. expect (tempFile.hasWriteAccess());
  6507. Time t (Time::getCurrentTime());
  6508. tempFile.setLastModificationTime (t);
  6509. Time t2 = tempFile.getLastModificationTime();
  6510. expect (std::abs ((int) (t2.toMilliseconds() - t.toMilliseconds())) <= 1000);
  6511. {
  6512. MemoryBlock mb;
  6513. tempFile.loadFileAsData (mb);
  6514. expect (mb.getSize() == 10);
  6515. expect (mb[0] == '0');
  6516. }
  6517. expect (tempFile.appendData ("abcdefghij", 10));
  6518. expect (tempFile.getSize() == 20);
  6519. expect (tempFile.replaceWithData ("abcdefghij", 10));
  6520. expect (tempFile.getSize() == 10);
  6521. File tempFile2 (tempFile.getNonexistentSibling (false));
  6522. expect (tempFile.copyFileTo (tempFile2));
  6523. expect (tempFile2.exists());
  6524. expect (tempFile2.hasIdenticalContentTo (tempFile));
  6525. expect (tempFile.deleteFile());
  6526. expect (! tempFile.exists());
  6527. expect (tempFile2.moveFileTo (tempFile));
  6528. expect (tempFile.exists());
  6529. expect (! tempFile2.exists());
  6530. expect (demoFolder.deleteRecursively());
  6531. expect (! demoFolder.exists());
  6532. }
  6533. };
  6534. static FileTests fileUnitTests;
  6535. #endif
  6536. END_JUCE_NAMESPACE
  6537. /*** End of inlined file: juce_File.cpp ***/
  6538. /*** Start of inlined file: juce_FileInputStream.cpp ***/
  6539. BEGIN_JUCE_NAMESPACE
  6540. int64 juce_fileSetPosition (void* handle, int64 pos);
  6541. FileInputStream::FileInputStream (const File& f)
  6542. : file (f),
  6543. fileHandle (0),
  6544. currentPosition (0),
  6545. totalSize (0),
  6546. needToSeek (true)
  6547. {
  6548. openHandle();
  6549. }
  6550. FileInputStream::~FileInputStream()
  6551. {
  6552. closeHandle();
  6553. }
  6554. int64 FileInputStream::getTotalLength()
  6555. {
  6556. return totalSize;
  6557. }
  6558. int FileInputStream::read (void* buffer, int bytesToRead)
  6559. {
  6560. int num = 0;
  6561. if (needToSeek)
  6562. {
  6563. if (juce_fileSetPosition (fileHandle, currentPosition) < 0)
  6564. return 0;
  6565. needToSeek = false;
  6566. }
  6567. num = readInternal (buffer, bytesToRead);
  6568. currentPosition += num;
  6569. return num;
  6570. }
  6571. bool FileInputStream::isExhausted()
  6572. {
  6573. return currentPosition >= totalSize;
  6574. }
  6575. int64 FileInputStream::getPosition()
  6576. {
  6577. return currentPosition;
  6578. }
  6579. bool FileInputStream::setPosition (int64 pos)
  6580. {
  6581. pos = jlimit ((int64) 0, totalSize, pos);
  6582. needToSeek |= (currentPosition != pos);
  6583. currentPosition = pos;
  6584. return true;
  6585. }
  6586. END_JUCE_NAMESPACE
  6587. /*** End of inlined file: juce_FileInputStream.cpp ***/
  6588. /*** Start of inlined file: juce_FileOutputStream.cpp ***/
  6589. BEGIN_JUCE_NAMESPACE
  6590. int64 juce_fileSetPosition (void* handle, int64 pos);
  6591. FileOutputStream::FileOutputStream (const File& f, const int bufferSize_)
  6592. : file (f),
  6593. fileHandle (0),
  6594. currentPosition (0),
  6595. bufferSize (bufferSize_),
  6596. bytesInBuffer (0),
  6597. buffer (jmax (bufferSize_, 16))
  6598. {
  6599. openHandle();
  6600. }
  6601. FileOutputStream::~FileOutputStream()
  6602. {
  6603. flush();
  6604. closeHandle();
  6605. }
  6606. int64 FileOutputStream::getPosition()
  6607. {
  6608. return currentPosition;
  6609. }
  6610. bool FileOutputStream::setPosition (int64 newPosition)
  6611. {
  6612. if (newPosition != currentPosition)
  6613. {
  6614. flush();
  6615. currentPosition = juce_fileSetPosition (fileHandle, newPosition);
  6616. }
  6617. return newPosition == currentPosition;
  6618. }
  6619. void FileOutputStream::flush()
  6620. {
  6621. if (bytesInBuffer > 0)
  6622. {
  6623. writeInternal (buffer, bytesInBuffer);
  6624. bytesInBuffer = 0;
  6625. }
  6626. flushInternal();
  6627. }
  6628. bool FileOutputStream::write (const void* const src, const int numBytes)
  6629. {
  6630. if (bytesInBuffer + numBytes < bufferSize)
  6631. {
  6632. memcpy (buffer + bytesInBuffer, src, numBytes);
  6633. bytesInBuffer += numBytes;
  6634. currentPosition += numBytes;
  6635. }
  6636. else
  6637. {
  6638. if (bytesInBuffer > 0)
  6639. {
  6640. // flush the reservoir
  6641. const bool wroteOk = (writeInternal (buffer, bytesInBuffer) == bytesInBuffer);
  6642. bytesInBuffer = 0;
  6643. if (! wroteOk)
  6644. return false;
  6645. }
  6646. if (numBytes < bufferSize)
  6647. {
  6648. memcpy (buffer + bytesInBuffer, src, numBytes);
  6649. bytesInBuffer += numBytes;
  6650. currentPosition += numBytes;
  6651. }
  6652. else
  6653. {
  6654. const int bytesWritten = writeInternal (src, numBytes);
  6655. if (bytesWritten < 0)
  6656. return false;
  6657. currentPosition += bytesWritten;
  6658. return bytesWritten == numBytes;
  6659. }
  6660. }
  6661. return true;
  6662. }
  6663. END_JUCE_NAMESPACE
  6664. /*** End of inlined file: juce_FileOutputStream.cpp ***/
  6665. /*** Start of inlined file: juce_FileSearchPath.cpp ***/
  6666. BEGIN_JUCE_NAMESPACE
  6667. FileSearchPath::FileSearchPath()
  6668. {
  6669. }
  6670. FileSearchPath::FileSearchPath (const String& path)
  6671. {
  6672. init (path);
  6673. }
  6674. FileSearchPath::FileSearchPath (const FileSearchPath& other)
  6675. : directories (other.directories)
  6676. {
  6677. }
  6678. FileSearchPath::~FileSearchPath()
  6679. {
  6680. }
  6681. FileSearchPath& FileSearchPath::operator= (const String& path)
  6682. {
  6683. init (path);
  6684. return *this;
  6685. }
  6686. void FileSearchPath::init (const String& path)
  6687. {
  6688. directories.clear();
  6689. directories.addTokens (path, ";", "\"");
  6690. directories.trim();
  6691. directories.removeEmptyStrings();
  6692. for (int i = directories.size(); --i >= 0;)
  6693. directories.set (i, directories[i].unquoted());
  6694. }
  6695. int FileSearchPath::getNumPaths() const
  6696. {
  6697. return directories.size();
  6698. }
  6699. const File FileSearchPath::operator[] (const int index) const
  6700. {
  6701. return File (directories [index]);
  6702. }
  6703. const String FileSearchPath::toString() const
  6704. {
  6705. StringArray directories2 (directories);
  6706. for (int i = directories2.size(); --i >= 0;)
  6707. if (directories2[i].containsChar (';'))
  6708. directories2.set (i, directories2[i].quoted());
  6709. return directories2.joinIntoString (";");
  6710. }
  6711. void FileSearchPath::add (const File& dir, const int insertIndex)
  6712. {
  6713. directories.insert (insertIndex, dir.getFullPathName());
  6714. }
  6715. void FileSearchPath::addIfNotAlreadyThere (const File& dir)
  6716. {
  6717. for (int i = 0; i < directories.size(); ++i)
  6718. if (File (directories[i]) == dir)
  6719. return;
  6720. add (dir);
  6721. }
  6722. void FileSearchPath::remove (const int index)
  6723. {
  6724. directories.remove (index);
  6725. }
  6726. void FileSearchPath::addPath (const FileSearchPath& other)
  6727. {
  6728. for (int i = 0; i < other.getNumPaths(); ++i)
  6729. addIfNotAlreadyThere (other[i]);
  6730. }
  6731. void FileSearchPath::removeRedundantPaths()
  6732. {
  6733. for (int i = directories.size(); --i >= 0;)
  6734. {
  6735. const File d1 (directories[i]);
  6736. for (int j = directories.size(); --j >= 0;)
  6737. {
  6738. const File d2 (directories[j]);
  6739. if ((i != j) && (d1.isAChildOf (d2) || d1 == d2))
  6740. {
  6741. directories.remove (i);
  6742. break;
  6743. }
  6744. }
  6745. }
  6746. }
  6747. void FileSearchPath::removeNonExistentPaths()
  6748. {
  6749. for (int i = directories.size(); --i >= 0;)
  6750. if (! File (directories[i]).isDirectory())
  6751. directories.remove (i);
  6752. }
  6753. int FileSearchPath::findChildFiles (Array<File>& results,
  6754. const int whatToLookFor,
  6755. const bool searchRecursively,
  6756. const String& wildCardPattern) const
  6757. {
  6758. int total = 0;
  6759. for (int i = 0; i < directories.size(); ++i)
  6760. total += operator[] (i).findChildFiles (results,
  6761. whatToLookFor,
  6762. searchRecursively,
  6763. wildCardPattern);
  6764. return total;
  6765. }
  6766. bool FileSearchPath::isFileInPath (const File& fileToCheck,
  6767. const bool checkRecursively) const
  6768. {
  6769. for (int i = directories.size(); --i >= 0;)
  6770. {
  6771. const File d (directories[i]);
  6772. if (checkRecursively)
  6773. {
  6774. if (fileToCheck.isAChildOf (d))
  6775. return true;
  6776. }
  6777. else
  6778. {
  6779. if (fileToCheck.getParentDirectory() == d)
  6780. return true;
  6781. }
  6782. }
  6783. return false;
  6784. }
  6785. END_JUCE_NAMESPACE
  6786. /*** End of inlined file: juce_FileSearchPath.cpp ***/
  6787. /*** Start of inlined file: juce_NamedPipe.cpp ***/
  6788. BEGIN_JUCE_NAMESPACE
  6789. NamedPipe::NamedPipe()
  6790. : internal (0)
  6791. {
  6792. }
  6793. NamedPipe::~NamedPipe()
  6794. {
  6795. close();
  6796. }
  6797. bool NamedPipe::openExisting (const String& pipeName)
  6798. {
  6799. currentPipeName = pipeName;
  6800. return openInternal (pipeName, false);
  6801. }
  6802. bool NamedPipe::createNewPipe (const String& pipeName)
  6803. {
  6804. currentPipeName = pipeName;
  6805. return openInternal (pipeName, true);
  6806. }
  6807. bool NamedPipe::isOpen() const
  6808. {
  6809. return internal != 0;
  6810. }
  6811. const String NamedPipe::getName() const
  6812. {
  6813. return currentPipeName;
  6814. }
  6815. // other methods for this class are implemented in the platform-specific files
  6816. END_JUCE_NAMESPACE
  6817. /*** End of inlined file: juce_NamedPipe.cpp ***/
  6818. /*** Start of inlined file: juce_TemporaryFile.cpp ***/
  6819. BEGIN_JUCE_NAMESPACE
  6820. TemporaryFile::TemporaryFile (const String& suffix, const int optionFlags)
  6821. {
  6822. createTempFile (File::getSpecialLocation (File::tempDirectory),
  6823. "temp_" + String (Random::getSystemRandom().nextInt()),
  6824. suffix,
  6825. optionFlags);
  6826. }
  6827. TemporaryFile::TemporaryFile (const File& targetFile_, const int optionFlags)
  6828. : targetFile (targetFile_)
  6829. {
  6830. // If you use this constructor, you need to give it a valid target file!
  6831. jassert (targetFile != File::nonexistent);
  6832. createTempFile (targetFile.getParentDirectory(),
  6833. targetFile.getFileNameWithoutExtension() + "_temp" + String (Random::getSystemRandom().nextInt()),
  6834. targetFile.getFileExtension(),
  6835. optionFlags);
  6836. }
  6837. void TemporaryFile::createTempFile (const File& parentDirectory, String name,
  6838. const String& suffix, const int optionFlags)
  6839. {
  6840. if ((optionFlags & useHiddenFile) != 0)
  6841. name = "." + name;
  6842. temporaryFile = parentDirectory.getNonexistentChildFile (name, suffix, (optionFlags & putNumbersInBrackets) != 0);
  6843. }
  6844. TemporaryFile::~TemporaryFile()
  6845. {
  6846. if (! deleteTemporaryFile())
  6847. {
  6848. /* Failed to delete our temporary file! The most likely reason for this would be
  6849. that you've not closed an output stream that was being used to write to file.
  6850. If you find that something beyond your control is changing permissions on
  6851. your temporary files and preventing them from being deleted, you may want to
  6852. call TemporaryFile::deleteTemporaryFile() to detect those error cases and
  6853. handle them appropriately.
  6854. */
  6855. jassertfalse;
  6856. }
  6857. }
  6858. bool TemporaryFile::overwriteTargetFileWithTemporary() const
  6859. {
  6860. // This method only works if you created this object with the constructor
  6861. // that takes a target file!
  6862. jassert (targetFile != File::nonexistent);
  6863. if (temporaryFile.exists())
  6864. {
  6865. // Have a few attempts at overwriting the file before giving up..
  6866. for (int i = 5; --i >= 0;)
  6867. {
  6868. if (temporaryFile.moveFileTo (targetFile))
  6869. return true;
  6870. Thread::sleep (100);
  6871. }
  6872. }
  6873. else
  6874. {
  6875. // There's no temporary file to use. If your write failed, you should
  6876. // probably check, and not bother calling this method.
  6877. jassertfalse;
  6878. }
  6879. return false;
  6880. }
  6881. bool TemporaryFile::deleteTemporaryFile() const
  6882. {
  6883. // Have a few attempts at deleting the file before giving up..
  6884. for (int i = 5; --i >= 0;)
  6885. {
  6886. if (temporaryFile.deleteFile())
  6887. return true;
  6888. Thread::sleep (50);
  6889. }
  6890. return false;
  6891. }
  6892. END_JUCE_NAMESPACE
  6893. /*** End of inlined file: juce_TemporaryFile.cpp ***/
  6894. /*** Start of inlined file: juce_Socket.cpp ***/
  6895. #if JUCE_WINDOWS
  6896. #include <winsock2.h>
  6897. #if JUCE_MSVC
  6898. #pragma warning (push)
  6899. #pragma warning (disable : 4127 4389 4018)
  6900. #endif
  6901. #else
  6902. #if JUCE_LINUX
  6903. #include <sys/types.h>
  6904. #include <sys/socket.h>
  6905. #include <sys/errno.h>
  6906. #include <unistd.h>
  6907. #include <netinet/in.h>
  6908. #elif (MACOSX_DEPLOYMENT_TARGET <= MAC_OS_X_VERSION_10_4) && ! JUCE_IOS
  6909. #include <CoreServices/CoreServices.h>
  6910. #endif
  6911. #include <fcntl.h>
  6912. #include <netdb.h>
  6913. #include <arpa/inet.h>
  6914. #include <netinet/tcp.h>
  6915. #endif
  6916. BEGIN_JUCE_NAMESPACE
  6917. #if defined (JUCE_LINUX) || defined (JUCE_MAC) || defined (JUCE_IOS)
  6918. typedef socklen_t juce_socklen_t;
  6919. #else
  6920. typedef int juce_socklen_t;
  6921. #endif
  6922. #if JUCE_WINDOWS
  6923. namespace SocketHelpers
  6924. {
  6925. typedef int (__stdcall juce_CloseWin32SocketLibCall) (void);
  6926. static juce_CloseWin32SocketLibCall* juce_CloseWin32SocketLib = 0;
  6927. }
  6928. static void initWin32Sockets()
  6929. {
  6930. static CriticalSection lock;
  6931. const ScopedLock sl (lock);
  6932. if (SocketHelpers::juce_CloseWin32SocketLib == 0)
  6933. {
  6934. WSADATA wsaData;
  6935. const WORD wVersionRequested = MAKEWORD (1, 1);
  6936. WSAStartup (wVersionRequested, &wsaData);
  6937. SocketHelpers::juce_CloseWin32SocketLib = &WSACleanup;
  6938. }
  6939. }
  6940. void juce_shutdownWin32Sockets()
  6941. {
  6942. if (SocketHelpers::juce_CloseWin32SocketLib != 0)
  6943. (*SocketHelpers::juce_CloseWin32SocketLib)();
  6944. }
  6945. #endif
  6946. namespace SocketHelpers
  6947. {
  6948. static bool resetSocketOptions (const int handle, const bool isDatagram, const bool allowBroadcast) throw()
  6949. {
  6950. const int sndBufSize = 65536;
  6951. const int rcvBufSize = 65536;
  6952. const int one = 1;
  6953. return handle > 0
  6954. && setsockopt (handle, SOL_SOCKET, SO_RCVBUF, (const char*) &rcvBufSize, sizeof (rcvBufSize)) == 0
  6955. && setsockopt (handle, SOL_SOCKET, SO_SNDBUF, (const char*) &sndBufSize, sizeof (sndBufSize)) == 0
  6956. && (isDatagram ? ((! allowBroadcast) || setsockopt (handle, SOL_SOCKET, SO_BROADCAST, (const char*) &one, sizeof (one)) == 0)
  6957. : (setsockopt (handle, IPPROTO_TCP, TCP_NODELAY, (const char*) &one, sizeof (one)) == 0));
  6958. }
  6959. static bool bindSocketToPort (const int handle, const int port) throw()
  6960. {
  6961. if (handle <= 0 || port <= 0)
  6962. return false;
  6963. struct sockaddr_in servTmpAddr;
  6964. zerostruct (servTmpAddr);
  6965. servTmpAddr.sin_family = PF_INET;
  6966. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  6967. servTmpAddr.sin_port = htons ((uint16) port);
  6968. return bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) >= 0;
  6969. }
  6970. static int readSocket (const int handle,
  6971. void* const destBuffer, const int maxBytesToRead,
  6972. bool volatile& connected,
  6973. const bool blockUntilSpecifiedAmountHasArrived) throw()
  6974. {
  6975. int bytesRead = 0;
  6976. while (bytesRead < maxBytesToRead)
  6977. {
  6978. int bytesThisTime;
  6979. #if JUCE_WINDOWS
  6980. bytesThisTime = recv (handle, static_cast<char*> (destBuffer) + bytesRead, maxBytesToRead - bytesRead, 0);
  6981. #else
  6982. while ((bytesThisTime = (int) ::read (handle, addBytesToPointer (destBuffer, bytesRead), maxBytesToRead - bytesRead)) < 0
  6983. && errno == EINTR
  6984. && connected)
  6985. {
  6986. }
  6987. #endif
  6988. if (bytesThisTime <= 0 || ! connected)
  6989. {
  6990. if (bytesRead == 0)
  6991. bytesRead = -1;
  6992. break;
  6993. }
  6994. bytesRead += bytesThisTime;
  6995. if (! blockUntilSpecifiedAmountHasArrived)
  6996. break;
  6997. }
  6998. return bytesRead;
  6999. }
  7000. static int waitForReadiness (const int handle, const bool forReading,
  7001. const int timeoutMsecs) throw()
  7002. {
  7003. struct timeval timeout;
  7004. struct timeval* timeoutp;
  7005. if (timeoutMsecs >= 0)
  7006. {
  7007. timeout.tv_sec = timeoutMsecs / 1000;
  7008. timeout.tv_usec = (timeoutMsecs % 1000) * 1000;
  7009. timeoutp = &timeout;
  7010. }
  7011. else
  7012. {
  7013. timeoutp = 0;
  7014. }
  7015. fd_set rset, wset;
  7016. FD_ZERO (&rset);
  7017. FD_SET (handle, &rset);
  7018. FD_ZERO (&wset);
  7019. FD_SET (handle, &wset);
  7020. fd_set* const prset = forReading ? &rset : 0;
  7021. fd_set* const pwset = forReading ? 0 : &wset;
  7022. #if JUCE_WINDOWS
  7023. if (select (handle + 1, prset, pwset, 0, timeoutp) < 0)
  7024. return -1;
  7025. #else
  7026. {
  7027. int result;
  7028. while ((result = select (handle + 1, prset, pwset, 0, timeoutp)) < 0
  7029. && errno == EINTR)
  7030. {
  7031. }
  7032. if (result < 0)
  7033. return -1;
  7034. }
  7035. #endif
  7036. {
  7037. int opt;
  7038. juce_socklen_t len = sizeof (opt);
  7039. if (getsockopt (handle, SOL_SOCKET, SO_ERROR, (char*) &opt, &len) < 0
  7040. || opt != 0)
  7041. return -1;
  7042. }
  7043. if ((forReading && FD_ISSET (handle, &rset))
  7044. || ((! forReading) && FD_ISSET (handle, &wset)))
  7045. return 1;
  7046. return 0;
  7047. }
  7048. static bool setSocketBlockingState (const int handle, const bool shouldBlock) throw()
  7049. {
  7050. #if JUCE_WINDOWS
  7051. u_long nonBlocking = shouldBlock ? 0 : 1;
  7052. if (ioctlsocket (handle, FIONBIO, &nonBlocking) != 0)
  7053. return false;
  7054. #else
  7055. int socketFlags = fcntl (handle, F_GETFL, 0);
  7056. if (socketFlags == -1)
  7057. return false;
  7058. if (shouldBlock)
  7059. socketFlags &= ~O_NONBLOCK;
  7060. else
  7061. socketFlags |= O_NONBLOCK;
  7062. if (fcntl (handle, F_SETFL, socketFlags) != 0)
  7063. return false;
  7064. #endif
  7065. return true;
  7066. }
  7067. static bool connectSocket (int volatile& handle,
  7068. const bool isDatagram,
  7069. void** serverAddress,
  7070. const String& hostName,
  7071. const int portNumber,
  7072. const int timeOutMillisecs) throw()
  7073. {
  7074. struct hostent* const hostEnt = gethostbyname (hostName.toUTF8());
  7075. if (hostEnt == 0)
  7076. return false;
  7077. struct in_addr targetAddress;
  7078. memcpy (&targetAddress.s_addr,
  7079. *(hostEnt->h_addr_list),
  7080. sizeof (targetAddress.s_addr));
  7081. struct sockaddr_in servTmpAddr;
  7082. zerostruct (servTmpAddr);
  7083. servTmpAddr.sin_family = PF_INET;
  7084. servTmpAddr.sin_addr = targetAddress;
  7085. servTmpAddr.sin_port = htons ((uint16) portNumber);
  7086. if (handle < 0)
  7087. handle = (int) socket (AF_INET, isDatagram ? SOCK_DGRAM : SOCK_STREAM, 0);
  7088. if (handle < 0)
  7089. return false;
  7090. if (isDatagram)
  7091. {
  7092. *serverAddress = new struct sockaddr_in();
  7093. *((struct sockaddr_in*) *serverAddress) = servTmpAddr;
  7094. return true;
  7095. }
  7096. setSocketBlockingState (handle, false);
  7097. const int result = ::connect (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in));
  7098. if (result < 0)
  7099. {
  7100. #if JUCE_WINDOWS
  7101. if (result == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
  7102. #else
  7103. if (errno == EINPROGRESS)
  7104. #endif
  7105. {
  7106. if (waitForReadiness (handle, false, timeOutMillisecs) != 1)
  7107. {
  7108. setSocketBlockingState (handle, true);
  7109. return false;
  7110. }
  7111. }
  7112. }
  7113. setSocketBlockingState (handle, true);
  7114. resetSocketOptions (handle, false, false);
  7115. return true;
  7116. }
  7117. }
  7118. StreamingSocket::StreamingSocket()
  7119. : portNumber (0),
  7120. handle (-1),
  7121. connected (false),
  7122. isListener (false)
  7123. {
  7124. #if JUCE_WINDOWS
  7125. initWin32Sockets();
  7126. #endif
  7127. }
  7128. StreamingSocket::StreamingSocket (const String& hostName_,
  7129. const int portNumber_,
  7130. const int handle_)
  7131. : hostName (hostName_),
  7132. portNumber (portNumber_),
  7133. handle (handle_),
  7134. connected (true),
  7135. isListener (false)
  7136. {
  7137. #if JUCE_WINDOWS
  7138. initWin32Sockets();
  7139. #endif
  7140. SocketHelpers::resetSocketOptions (handle_, false, false);
  7141. }
  7142. StreamingSocket::~StreamingSocket()
  7143. {
  7144. close();
  7145. }
  7146. int StreamingSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  7147. {
  7148. return (connected && ! isListener) ? SocketHelpers::readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  7149. : -1;
  7150. }
  7151. int StreamingSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  7152. {
  7153. if (isListener || ! connected)
  7154. return -1;
  7155. #if JUCE_WINDOWS
  7156. return send (handle, (const char*) sourceBuffer, numBytesToWrite, 0);
  7157. #else
  7158. int result;
  7159. while ((result = (int) ::write (handle, sourceBuffer, numBytesToWrite)) < 0
  7160. && errno == EINTR)
  7161. {
  7162. }
  7163. return result;
  7164. #endif
  7165. }
  7166. int StreamingSocket::waitUntilReady (const bool readyForReading,
  7167. const int timeoutMsecs) const
  7168. {
  7169. return connected ? SocketHelpers::waitForReadiness (handle, readyForReading, timeoutMsecs)
  7170. : -1;
  7171. }
  7172. bool StreamingSocket::bindToPort (const int port)
  7173. {
  7174. return SocketHelpers::bindSocketToPort (handle, port);
  7175. }
  7176. bool StreamingSocket::connect (const String& remoteHostName,
  7177. const int remotePortNumber,
  7178. const int timeOutMillisecs)
  7179. {
  7180. if (isListener)
  7181. {
  7182. jassertfalse; // a listener socket can't connect to another one!
  7183. return false;
  7184. }
  7185. if (connected)
  7186. close();
  7187. hostName = remoteHostName;
  7188. portNumber = remotePortNumber;
  7189. isListener = false;
  7190. connected = SocketHelpers::connectSocket (handle, false, 0, remoteHostName,
  7191. remotePortNumber, timeOutMillisecs);
  7192. if (! (connected && SocketHelpers::resetSocketOptions (handle, false, false)))
  7193. {
  7194. close();
  7195. return false;
  7196. }
  7197. return true;
  7198. }
  7199. void StreamingSocket::close()
  7200. {
  7201. #if JUCE_WINDOWS
  7202. if (handle != SOCKET_ERROR || connected)
  7203. closesocket (handle);
  7204. connected = false;
  7205. #else
  7206. if (connected)
  7207. {
  7208. connected = false;
  7209. if (isListener)
  7210. {
  7211. // need to do this to interrupt the accept() function..
  7212. StreamingSocket temp;
  7213. temp.connect ("localhost", portNumber, 1000);
  7214. }
  7215. }
  7216. if (handle != -1)
  7217. ::close (handle);
  7218. #endif
  7219. hostName = String::empty;
  7220. portNumber = 0;
  7221. handle = -1;
  7222. isListener = false;
  7223. }
  7224. bool StreamingSocket::createListener (const int newPortNumber, const String& localHostName)
  7225. {
  7226. if (connected)
  7227. close();
  7228. hostName = "listener";
  7229. portNumber = newPortNumber;
  7230. isListener = true;
  7231. struct sockaddr_in servTmpAddr;
  7232. zerostruct (servTmpAddr);
  7233. servTmpAddr.sin_family = PF_INET;
  7234. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  7235. if (localHostName.isNotEmpty())
  7236. servTmpAddr.sin_addr.s_addr = ::inet_addr (localHostName.toUTF8());
  7237. servTmpAddr.sin_port = htons ((uint16) portNumber);
  7238. handle = (int) socket (AF_INET, SOCK_STREAM, 0);
  7239. if (handle < 0)
  7240. return false;
  7241. const int reuse = 1;
  7242. setsockopt (handle, SOL_SOCKET, SO_REUSEADDR, (const char*) &reuse, sizeof (reuse));
  7243. if (bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) < 0
  7244. || listen (handle, SOMAXCONN) < 0)
  7245. {
  7246. close();
  7247. return false;
  7248. }
  7249. connected = true;
  7250. return true;
  7251. }
  7252. StreamingSocket* StreamingSocket::waitForNextConnection() const
  7253. {
  7254. jassert (isListener || ! connected); // to call this method, you first have to use createListener() to
  7255. // prepare this socket as a listener.
  7256. if (connected && isListener)
  7257. {
  7258. struct sockaddr address;
  7259. juce_socklen_t len = sizeof (sockaddr);
  7260. const int newSocket = (int) accept (handle, &address, &len);
  7261. if (newSocket >= 0 && connected)
  7262. return new StreamingSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  7263. portNumber, newSocket);
  7264. }
  7265. return 0;
  7266. }
  7267. bool StreamingSocket::isLocal() const throw()
  7268. {
  7269. return hostName == "127.0.0.1";
  7270. }
  7271. DatagramSocket::DatagramSocket (const int localPortNumber, const bool allowBroadcast_)
  7272. : portNumber (0),
  7273. handle (-1),
  7274. connected (true),
  7275. allowBroadcast (allowBroadcast_),
  7276. serverAddress (0)
  7277. {
  7278. #if JUCE_WINDOWS
  7279. initWin32Sockets();
  7280. #endif
  7281. handle = (int) socket (AF_INET, SOCK_DGRAM, 0);
  7282. bindToPort (localPortNumber);
  7283. }
  7284. DatagramSocket::DatagramSocket (const String& hostName_, const int portNumber_,
  7285. const int handle_, const int localPortNumber)
  7286. : hostName (hostName_),
  7287. portNumber (portNumber_),
  7288. handle (handle_),
  7289. connected (true),
  7290. allowBroadcast (false),
  7291. serverAddress (0)
  7292. {
  7293. #if JUCE_WINDOWS
  7294. initWin32Sockets();
  7295. #endif
  7296. SocketHelpers::resetSocketOptions (handle_, true, allowBroadcast);
  7297. bindToPort (localPortNumber);
  7298. }
  7299. DatagramSocket::~DatagramSocket()
  7300. {
  7301. close();
  7302. delete static_cast <struct sockaddr_in*> (serverAddress);
  7303. serverAddress = 0;
  7304. }
  7305. void DatagramSocket::close()
  7306. {
  7307. #if JUCE_WINDOWS
  7308. closesocket (handle);
  7309. connected = false;
  7310. #else
  7311. connected = false;
  7312. ::close (handle);
  7313. #endif
  7314. hostName = String::empty;
  7315. portNumber = 0;
  7316. handle = -1;
  7317. }
  7318. bool DatagramSocket::bindToPort (const int port)
  7319. {
  7320. return SocketHelpers::bindSocketToPort (handle, port);
  7321. }
  7322. bool DatagramSocket::connect (const String& remoteHostName,
  7323. const int remotePortNumber,
  7324. const int timeOutMillisecs)
  7325. {
  7326. if (connected)
  7327. close();
  7328. hostName = remoteHostName;
  7329. portNumber = remotePortNumber;
  7330. connected = SocketHelpers::connectSocket (handle, true, &serverAddress,
  7331. remoteHostName, remotePortNumber,
  7332. timeOutMillisecs);
  7333. if (! (connected && SocketHelpers::resetSocketOptions (handle, true, allowBroadcast)))
  7334. {
  7335. close();
  7336. return false;
  7337. }
  7338. return true;
  7339. }
  7340. DatagramSocket* DatagramSocket::waitForNextConnection() const
  7341. {
  7342. struct sockaddr address;
  7343. juce_socklen_t len = sizeof (sockaddr);
  7344. while (waitUntilReady (true, -1) == 1)
  7345. {
  7346. char buf[1];
  7347. if (recvfrom (handle, buf, 0, 0, &address, &len) > 0)
  7348. {
  7349. return new DatagramSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  7350. ntohs (((struct sockaddr_in*) &address)->sin_port),
  7351. -1, -1);
  7352. }
  7353. }
  7354. return 0;
  7355. }
  7356. int DatagramSocket::waitUntilReady (const bool readyForReading,
  7357. const int timeoutMsecs) const
  7358. {
  7359. return connected ? SocketHelpers::waitForReadiness (handle, readyForReading, timeoutMsecs)
  7360. : -1;
  7361. }
  7362. int DatagramSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  7363. {
  7364. return connected ? SocketHelpers::readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  7365. : -1;
  7366. }
  7367. int DatagramSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  7368. {
  7369. // You need to call connect() first to set the server address..
  7370. jassert (serverAddress != 0 && connected);
  7371. return connected ? (int) sendto (handle, (const char*) sourceBuffer,
  7372. numBytesToWrite, 0,
  7373. (const struct sockaddr*) serverAddress,
  7374. sizeof (struct sockaddr_in))
  7375. : -1;
  7376. }
  7377. bool DatagramSocket::isLocal() const throw()
  7378. {
  7379. return hostName == "127.0.0.1";
  7380. }
  7381. #if JUCE_MSVC
  7382. #pragma warning (pop)
  7383. #endif
  7384. END_JUCE_NAMESPACE
  7385. /*** End of inlined file: juce_Socket.cpp ***/
  7386. /*** Start of inlined file: juce_URL.cpp ***/
  7387. BEGIN_JUCE_NAMESPACE
  7388. URL::URL()
  7389. {
  7390. }
  7391. URL::URL (const String& url_)
  7392. : url (url_)
  7393. {
  7394. int i = url.indexOfChar ('?');
  7395. if (i >= 0)
  7396. {
  7397. do
  7398. {
  7399. const int nextAmp = url.indexOfChar (i + 1, '&');
  7400. const int equalsPos = url.indexOfChar (i + 1, '=');
  7401. if (equalsPos > i + 1)
  7402. {
  7403. if (nextAmp < 0)
  7404. {
  7405. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  7406. removeEscapeChars (url.substring (equalsPos + 1)));
  7407. }
  7408. else if (nextAmp > 0 && equalsPos < nextAmp)
  7409. {
  7410. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  7411. removeEscapeChars (url.substring (equalsPos + 1, nextAmp)));
  7412. }
  7413. }
  7414. i = nextAmp;
  7415. }
  7416. while (i >= 0);
  7417. url = url.upToFirstOccurrenceOf ("?", false, false);
  7418. }
  7419. }
  7420. URL::URL (const URL& other)
  7421. : url (other.url),
  7422. postData (other.postData),
  7423. parameters (other.parameters),
  7424. filesToUpload (other.filesToUpload),
  7425. mimeTypes (other.mimeTypes)
  7426. {
  7427. }
  7428. URL& URL::operator= (const URL& other)
  7429. {
  7430. url = other.url;
  7431. postData = other.postData;
  7432. parameters = other.parameters;
  7433. filesToUpload = other.filesToUpload;
  7434. mimeTypes = other.mimeTypes;
  7435. return *this;
  7436. }
  7437. URL::~URL()
  7438. {
  7439. }
  7440. static const String getMangledParameters (const StringPairArray& parameters)
  7441. {
  7442. String p;
  7443. for (int i = 0; i < parameters.size(); ++i)
  7444. {
  7445. if (i > 0)
  7446. p << '&';
  7447. p << URL::addEscapeChars (parameters.getAllKeys() [i], true)
  7448. << '='
  7449. << URL::addEscapeChars (parameters.getAllValues() [i], true);
  7450. }
  7451. return p;
  7452. }
  7453. const String URL::toString (const bool includeGetParameters) const
  7454. {
  7455. if (includeGetParameters && parameters.size() > 0)
  7456. return url + "?" + getMangledParameters (parameters);
  7457. else
  7458. return url;
  7459. }
  7460. bool URL::isWellFormed() const
  7461. {
  7462. //xxx TODO
  7463. return url.isNotEmpty();
  7464. }
  7465. static int findStartOfDomain (const String& url)
  7466. {
  7467. int i = 0;
  7468. while (CharacterFunctions::isLetterOrDigit (url[i])
  7469. || CharacterFunctions::indexOfChar (L"+-.", url[i], false) >= 0)
  7470. ++i;
  7471. return url[i] == ':' ? i + 1 : 0;
  7472. }
  7473. const String URL::getDomain() const
  7474. {
  7475. int start = findStartOfDomain (url);
  7476. while (url[start] == '/')
  7477. ++start;
  7478. const int end1 = url.indexOfChar (start, '/');
  7479. const int end2 = url.indexOfChar (start, ':');
  7480. const int end = (end1 < 0 || end2 < 0) ? jmax (end1, end2)
  7481. : jmin (end1, end2);
  7482. return url.substring (start, end);
  7483. }
  7484. const String URL::getSubPath() const
  7485. {
  7486. int start = findStartOfDomain (url);
  7487. while (url[start] == '/')
  7488. ++start;
  7489. const int startOfPath = url.indexOfChar (start, '/') + 1;
  7490. return startOfPath <= 0 ? String::empty
  7491. : url.substring (startOfPath);
  7492. }
  7493. const String URL::getScheme() const
  7494. {
  7495. return url.substring (0, findStartOfDomain (url) - 1);
  7496. }
  7497. const URL URL::withNewSubPath (const String& newPath) const
  7498. {
  7499. int start = findStartOfDomain (url);
  7500. while (url[start] == '/')
  7501. ++start;
  7502. const int startOfPath = url.indexOfChar (start, '/') + 1;
  7503. URL u (*this);
  7504. if (startOfPath > 0)
  7505. u.url = url.substring (0, startOfPath);
  7506. if (! u.url.endsWithChar ('/'))
  7507. u.url << '/';
  7508. if (newPath.startsWithChar ('/'))
  7509. u.url << newPath.substring (1);
  7510. else
  7511. u.url << newPath;
  7512. return u;
  7513. }
  7514. bool URL::isProbablyAWebsiteURL (const String& possibleURL)
  7515. {
  7516. if (possibleURL.startsWithIgnoreCase ("http:")
  7517. || possibleURL.startsWithIgnoreCase ("ftp:"))
  7518. return true;
  7519. if (possibleURL.startsWithIgnoreCase ("file:")
  7520. || possibleURL.containsChar ('@')
  7521. || possibleURL.endsWithChar ('.')
  7522. || (! possibleURL.containsChar ('.')))
  7523. return false;
  7524. if (possibleURL.startsWithIgnoreCase ("www.")
  7525. && possibleURL.substring (5).containsChar ('.'))
  7526. return true;
  7527. const char* commonTLDs[] = { "com", "net", "org", "uk", "de", "fr", "jp" };
  7528. for (int i = 0; i < numElementsInArray (commonTLDs); ++i)
  7529. if ((possibleURL + "/").containsIgnoreCase ("." + String (commonTLDs[i]) + "/"))
  7530. return true;
  7531. return false;
  7532. }
  7533. bool URL::isProbablyAnEmailAddress (const String& possibleEmailAddress)
  7534. {
  7535. const int atSign = possibleEmailAddress.indexOfChar ('@');
  7536. return atSign > 0
  7537. && possibleEmailAddress.lastIndexOfChar ('.') > (atSign + 1)
  7538. && (! possibleEmailAddress.endsWithChar ('.'));
  7539. }
  7540. void* juce_openInternetFile (const String& url,
  7541. const String& headers,
  7542. const MemoryBlock& optionalPostData,
  7543. const bool isPost,
  7544. URL::OpenStreamProgressCallback* callback,
  7545. void* callbackContext,
  7546. int timeOutMs);
  7547. void juce_closeInternetFile (void* handle);
  7548. int juce_readFromInternetFile (void* handle, void* dest, int bytesToRead);
  7549. int juce_seekInInternetFile (void* handle, int newPosition);
  7550. int64 juce_getInternetFileContentLength (void* handle);
  7551. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers);
  7552. class WebInputStream : public InputStream
  7553. {
  7554. public:
  7555. WebInputStream (const URL& url,
  7556. const bool isPost_,
  7557. URL::OpenStreamProgressCallback* const progressCallback_,
  7558. void* const progressCallbackContext_,
  7559. const String& extraHeaders,
  7560. const int timeOutMs_,
  7561. StringPairArray* const responseHeaders)
  7562. : position (0),
  7563. finished (false),
  7564. isPost (isPost_),
  7565. progressCallback (progressCallback_),
  7566. progressCallbackContext (progressCallbackContext_),
  7567. timeOutMs (timeOutMs_)
  7568. {
  7569. server = url.toString (! isPost);
  7570. if (isPost_)
  7571. createHeadersAndPostData (url);
  7572. headers += extraHeaders;
  7573. if (! headers.endsWithChar ('\n'))
  7574. headers << "\r\n";
  7575. handle = juce_openInternetFile (server, headers, postData, isPost,
  7576. progressCallback_, progressCallbackContext_,
  7577. timeOutMs);
  7578. if (responseHeaders != 0)
  7579. juce_getInternetFileHeaders (handle, *responseHeaders);
  7580. }
  7581. ~WebInputStream()
  7582. {
  7583. juce_closeInternetFile (handle);
  7584. }
  7585. bool isError() const { return handle == 0; }
  7586. int64 getTotalLength() { return juce_getInternetFileContentLength (handle); }
  7587. bool isExhausted() { return finished; }
  7588. int64 getPosition() { return position; }
  7589. int read (void* dest, int bytes)
  7590. {
  7591. if (finished || isError())
  7592. {
  7593. return 0;
  7594. }
  7595. else
  7596. {
  7597. const int bytesRead = juce_readFromInternetFile (handle, dest, bytes);
  7598. position += bytesRead;
  7599. if (bytesRead == 0)
  7600. finished = true;
  7601. return bytesRead;
  7602. }
  7603. }
  7604. bool setPosition (int64 wantedPos)
  7605. {
  7606. if (wantedPos != position)
  7607. {
  7608. finished = false;
  7609. const int actualPos = juce_seekInInternetFile (handle, (int) wantedPos);
  7610. if (actualPos == wantedPos)
  7611. {
  7612. position = wantedPos;
  7613. }
  7614. else
  7615. {
  7616. if (wantedPos < position)
  7617. {
  7618. juce_closeInternetFile (handle);
  7619. position = 0;
  7620. finished = false;
  7621. handle = juce_openInternetFile (server, headers, postData, isPost,
  7622. progressCallback, progressCallbackContext,
  7623. timeOutMs);
  7624. }
  7625. skipNextBytes (wantedPos - position);
  7626. }
  7627. }
  7628. return true;
  7629. }
  7630. juce_UseDebuggingNewOperator
  7631. private:
  7632. String server, headers;
  7633. MemoryBlock postData;
  7634. int64 position;
  7635. bool finished;
  7636. const bool isPost;
  7637. void* handle;
  7638. URL::OpenStreamProgressCallback* const progressCallback;
  7639. void* const progressCallbackContext;
  7640. const int timeOutMs;
  7641. void createHeadersAndPostData (const URL& url)
  7642. {
  7643. MemoryOutputStream data (postData, false);
  7644. if (url.getFilesToUpload().size() > 0)
  7645. {
  7646. // need to upload some files, so do it as multi-part...
  7647. const String boundary (String::toHexString (Random::getSystemRandom().nextInt64()));
  7648. headers << "Content-Type: multipart/form-data; boundary=" << boundary << "\r\n";
  7649. data << "--" << boundary;
  7650. int i;
  7651. for (i = 0; i < url.getParameters().size(); ++i)
  7652. {
  7653. data << "\r\nContent-Disposition: form-data; name=\""
  7654. << url.getParameters().getAllKeys() [i]
  7655. << "\"\r\n\r\n"
  7656. << url.getParameters().getAllValues() [i]
  7657. << "\r\n--"
  7658. << boundary;
  7659. }
  7660. for (i = 0; i < url.getFilesToUpload().size(); ++i)
  7661. {
  7662. const File file (url.getFilesToUpload().getAllValues() [i]);
  7663. const String paramName (url.getFilesToUpload().getAllKeys() [i]);
  7664. data << "\r\nContent-Disposition: form-data; name=\"" << paramName
  7665. << "\"; filename=\"" << file.getFileName() << "\"\r\n";
  7666. const String mimeType (url.getMimeTypesOfUploadFiles()
  7667. .getValue (paramName, String::empty));
  7668. if (mimeType.isNotEmpty())
  7669. data << "Content-Type: " << mimeType << "\r\n";
  7670. data << "Content-Transfer-Encoding: binary\r\n\r\n"
  7671. << file << "\r\n--" << boundary;
  7672. }
  7673. data << "--\r\n";
  7674. data.flush();
  7675. }
  7676. else
  7677. {
  7678. data << getMangledParameters (url.getParameters())
  7679. << url.getPostData();
  7680. data.flush();
  7681. // just a short text attachment, so use simple url encoding..
  7682. headers = "Content-Type: application/x-www-form-urlencoded\r\nContent-length: "
  7683. + String ((unsigned int) postData.getSize())
  7684. + "\r\n";
  7685. }
  7686. }
  7687. WebInputStream (const WebInputStream&);
  7688. WebInputStream& operator= (const WebInputStream&);
  7689. };
  7690. InputStream* URL::createInputStream (const bool usePostCommand,
  7691. OpenStreamProgressCallback* const progressCallback,
  7692. void* const progressCallbackContext,
  7693. const String& extraHeaders,
  7694. const int timeOutMs,
  7695. StringPairArray* const responseHeaders) const
  7696. {
  7697. ScopedPointer <WebInputStream> wi (new WebInputStream (*this, usePostCommand,
  7698. progressCallback, progressCallbackContext,
  7699. extraHeaders, timeOutMs, responseHeaders));
  7700. return wi->isError() ? 0 : wi.release();
  7701. }
  7702. bool URL::readEntireBinaryStream (MemoryBlock& destData,
  7703. const bool usePostCommand) const
  7704. {
  7705. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  7706. if (in != 0)
  7707. {
  7708. in->readIntoMemoryBlock (destData);
  7709. return true;
  7710. }
  7711. return false;
  7712. }
  7713. const String URL::readEntireTextStream (const bool usePostCommand) const
  7714. {
  7715. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  7716. if (in != 0)
  7717. return in->readEntireStreamAsString();
  7718. return String::empty;
  7719. }
  7720. XmlElement* URL::readEntireXmlStream (const bool usePostCommand) const
  7721. {
  7722. XmlDocument doc (readEntireTextStream (usePostCommand));
  7723. return doc.getDocumentElement();
  7724. }
  7725. const URL URL::withParameter (const String& parameterName,
  7726. const String& parameterValue) const
  7727. {
  7728. URL u (*this);
  7729. u.parameters.set (parameterName, parameterValue);
  7730. return u;
  7731. }
  7732. const URL URL::withFileToUpload (const String& parameterName,
  7733. const File& fileToUpload,
  7734. const String& mimeType) const
  7735. {
  7736. jassert (mimeType.isNotEmpty()); // You need to supply a mime type!
  7737. URL u (*this);
  7738. u.filesToUpload.set (parameterName, fileToUpload.getFullPathName());
  7739. u.mimeTypes.set (parameterName, mimeType);
  7740. return u;
  7741. }
  7742. const URL URL::withPOSTData (const String& postData_) const
  7743. {
  7744. URL u (*this);
  7745. u.postData = postData_;
  7746. return u;
  7747. }
  7748. const StringPairArray& URL::getParameters() const
  7749. {
  7750. return parameters;
  7751. }
  7752. const StringPairArray& URL::getFilesToUpload() const
  7753. {
  7754. return filesToUpload;
  7755. }
  7756. const StringPairArray& URL::getMimeTypesOfUploadFiles() const
  7757. {
  7758. return mimeTypes;
  7759. }
  7760. const String URL::removeEscapeChars (const String& s)
  7761. {
  7762. String result (s.replaceCharacter ('+', ' '));
  7763. if (! result.containsChar ('%'))
  7764. return result;
  7765. // We need to operate on the string as raw UTF8 chars, and then recombine them into unicode
  7766. // after all the replacements have been made, so that multi-byte chars are handled.
  7767. Array<char> utf8 (result.toUTF8(), result.getNumBytesAsUTF8());
  7768. for (int i = 0; i < utf8.size(); ++i)
  7769. {
  7770. if (utf8.getUnchecked(i) == '%')
  7771. {
  7772. const int hexDigit1 = CharacterFunctions::getHexDigitValue (utf8 [i + 1]);
  7773. const int hexDigit2 = CharacterFunctions::getHexDigitValue (utf8 [i + 2]);
  7774. if (hexDigit1 >= 0 && hexDigit2 >= 0)
  7775. {
  7776. utf8.set (i, (char) ((hexDigit1 << 4) + hexDigit2));
  7777. utf8.removeRange (i + 1, 2);
  7778. }
  7779. }
  7780. }
  7781. return String::fromUTF8 (utf8.getRawDataPointer(), utf8.size());
  7782. }
  7783. const String URL::addEscapeChars (const String& s, const bool isParameter)
  7784. {
  7785. const char* const legalChars = isParameter ? "_-.*!'()"
  7786. : ",$_-.*!'()";
  7787. Array<char> utf8 (s.toUTF8(), s.getNumBytesAsUTF8());
  7788. for (int i = 0; i < utf8.size(); ++i)
  7789. {
  7790. const char c = utf8.getUnchecked(i);
  7791. if (! (CharacterFunctions::isLetterOrDigit (c)
  7792. || CharacterFunctions::indexOfChar (legalChars, c, false) >= 0))
  7793. {
  7794. if (c == ' ')
  7795. {
  7796. utf8.set (i, '+');
  7797. }
  7798. else
  7799. {
  7800. static const char* const hexDigits = "0123456789abcdef";
  7801. utf8.set (i, '%');
  7802. utf8.insert (++i, hexDigits [((uint8) c) >> 4]);
  7803. utf8.insert (++i, hexDigits [c & 15]);
  7804. }
  7805. }
  7806. }
  7807. return String::fromUTF8 (utf8.getRawDataPointer(), utf8.size());
  7808. }
  7809. bool URL::launchInDefaultBrowser() const
  7810. {
  7811. String u (toString (true));
  7812. if (u.containsChar ('@') && ! u.containsChar (':'))
  7813. u = "mailto:" + u;
  7814. return PlatformUtilities::openDocument (u, String::empty);
  7815. }
  7816. END_JUCE_NAMESPACE
  7817. /*** End of inlined file: juce_URL.cpp ***/
  7818. /*** Start of inlined file: juce_BufferedInputStream.cpp ***/
  7819. BEGIN_JUCE_NAMESPACE
  7820. BufferedInputStream::BufferedInputStream (InputStream* const source_,
  7821. const int bufferSize_,
  7822. const bool deleteSourceWhenDestroyed)
  7823. : source (source_),
  7824. sourceToDelete (deleteSourceWhenDestroyed ? source_ : 0),
  7825. bufferSize (jmax (256, bufferSize_)),
  7826. position (source_->getPosition()),
  7827. lastReadPos (0),
  7828. bufferOverlap (128)
  7829. {
  7830. const int sourceSize = (int) source_->getTotalLength();
  7831. if (sourceSize >= 0)
  7832. bufferSize = jmin (jmax (32, sourceSize), bufferSize);
  7833. bufferStart = position;
  7834. buffer.malloc (bufferSize);
  7835. }
  7836. BufferedInputStream::~BufferedInputStream()
  7837. {
  7838. }
  7839. int64 BufferedInputStream::getTotalLength()
  7840. {
  7841. return source->getTotalLength();
  7842. }
  7843. int64 BufferedInputStream::getPosition()
  7844. {
  7845. return position;
  7846. }
  7847. bool BufferedInputStream::setPosition (int64 newPosition)
  7848. {
  7849. position = jmax ((int64) 0, newPosition);
  7850. return true;
  7851. }
  7852. bool BufferedInputStream::isExhausted()
  7853. {
  7854. return (position >= lastReadPos)
  7855. && source->isExhausted();
  7856. }
  7857. void BufferedInputStream::ensureBuffered()
  7858. {
  7859. const int64 bufferEndOverlap = lastReadPos - bufferOverlap;
  7860. if (position < bufferStart || position >= bufferEndOverlap)
  7861. {
  7862. int bytesRead;
  7863. if (position < lastReadPos
  7864. && position >= bufferEndOverlap
  7865. && position >= bufferStart)
  7866. {
  7867. const int bytesToKeep = (int) (lastReadPos - position);
  7868. memmove (buffer, buffer + (int) (position - bufferStart), bytesToKeep);
  7869. bufferStart = position;
  7870. bytesRead = source->read (buffer + bytesToKeep,
  7871. bufferSize - bytesToKeep);
  7872. lastReadPos += bytesRead;
  7873. bytesRead += bytesToKeep;
  7874. }
  7875. else
  7876. {
  7877. bufferStart = position;
  7878. source->setPosition (bufferStart);
  7879. bytesRead = source->read (buffer, bufferSize);
  7880. lastReadPos = bufferStart + bytesRead;
  7881. }
  7882. while (bytesRead < bufferSize)
  7883. buffer [bytesRead++] = 0;
  7884. }
  7885. }
  7886. int BufferedInputStream::read (void* destBuffer, int maxBytesToRead)
  7887. {
  7888. if (position >= bufferStart
  7889. && position + maxBytesToRead <= lastReadPos)
  7890. {
  7891. memcpy (destBuffer, buffer + (int) (position - bufferStart), maxBytesToRead);
  7892. position += maxBytesToRead;
  7893. return maxBytesToRead;
  7894. }
  7895. else
  7896. {
  7897. if (position < bufferStart || position >= lastReadPos)
  7898. ensureBuffered();
  7899. int bytesRead = 0;
  7900. while (maxBytesToRead > 0)
  7901. {
  7902. const int bytesAvailable = jmin (maxBytesToRead, (int) (lastReadPos - position));
  7903. if (bytesAvailable > 0)
  7904. {
  7905. memcpy (destBuffer, buffer + (int) (position - bufferStart), bytesAvailable);
  7906. maxBytesToRead -= bytesAvailable;
  7907. bytesRead += bytesAvailable;
  7908. position += bytesAvailable;
  7909. destBuffer = static_cast <char*> (destBuffer) + bytesAvailable;
  7910. }
  7911. const int64 oldLastReadPos = lastReadPos;
  7912. ensureBuffered();
  7913. if (oldLastReadPos == lastReadPos)
  7914. break; // if ensureBuffered() failed to read any more data, bail out
  7915. if (isExhausted())
  7916. break;
  7917. }
  7918. return bytesRead;
  7919. }
  7920. }
  7921. const String BufferedInputStream::readString()
  7922. {
  7923. if (position >= bufferStart
  7924. && position < lastReadPos)
  7925. {
  7926. const int maxChars = (int) (lastReadPos - position);
  7927. const char* const src = buffer + (int) (position - bufferStart);
  7928. for (int i = 0; i < maxChars; ++i)
  7929. {
  7930. if (src[i] == 0)
  7931. {
  7932. position += i + 1;
  7933. return String::fromUTF8 (src, i);
  7934. }
  7935. }
  7936. }
  7937. return InputStream::readString();
  7938. }
  7939. END_JUCE_NAMESPACE
  7940. /*** End of inlined file: juce_BufferedInputStream.cpp ***/
  7941. /*** Start of inlined file: juce_FileInputSource.cpp ***/
  7942. BEGIN_JUCE_NAMESPACE
  7943. FileInputSource::FileInputSource (const File& file_)
  7944. : file (file_)
  7945. {
  7946. }
  7947. FileInputSource::~FileInputSource()
  7948. {
  7949. }
  7950. InputStream* FileInputSource::createInputStream()
  7951. {
  7952. return file.createInputStream();
  7953. }
  7954. InputStream* FileInputSource::createInputStreamFor (const String& relatedItemPath)
  7955. {
  7956. return file.getSiblingFile (relatedItemPath).createInputStream();
  7957. }
  7958. int64 FileInputSource::hashCode() const
  7959. {
  7960. return file.hashCode();
  7961. }
  7962. END_JUCE_NAMESPACE
  7963. /*** End of inlined file: juce_FileInputSource.cpp ***/
  7964. /*** Start of inlined file: juce_MemoryInputStream.cpp ***/
  7965. BEGIN_JUCE_NAMESPACE
  7966. MemoryInputStream::MemoryInputStream (const void* const sourceData,
  7967. const size_t sourceDataSize,
  7968. const bool keepInternalCopy)
  7969. : data (static_cast <const char*> (sourceData)),
  7970. dataSize (sourceDataSize),
  7971. position (0)
  7972. {
  7973. if (keepInternalCopy)
  7974. {
  7975. internalCopy.append (data, sourceDataSize);
  7976. data = static_cast <const char*> (internalCopy.getData());
  7977. }
  7978. }
  7979. MemoryInputStream::MemoryInputStream (const MemoryBlock& sourceData,
  7980. const bool keepInternalCopy)
  7981. : data (static_cast <const char*> (sourceData.getData())),
  7982. dataSize (sourceData.getSize()),
  7983. position (0)
  7984. {
  7985. if (keepInternalCopy)
  7986. {
  7987. internalCopy = sourceData;
  7988. data = static_cast <const char*> (internalCopy.getData());
  7989. }
  7990. }
  7991. MemoryInputStream::~MemoryInputStream()
  7992. {
  7993. }
  7994. int64 MemoryInputStream::getTotalLength()
  7995. {
  7996. return dataSize;
  7997. }
  7998. int MemoryInputStream::read (void* const buffer, const int howMany)
  7999. {
  8000. jassert (howMany >= 0);
  8001. const int num = jmin (howMany, (int) (dataSize - position));
  8002. memcpy (buffer, data + position, num);
  8003. position += num;
  8004. return (int) num;
  8005. }
  8006. bool MemoryInputStream::isExhausted()
  8007. {
  8008. return (position >= dataSize);
  8009. }
  8010. bool MemoryInputStream::setPosition (const int64 pos)
  8011. {
  8012. position = (int) jlimit ((int64) 0, (int64) dataSize, pos);
  8013. return true;
  8014. }
  8015. int64 MemoryInputStream::getPosition()
  8016. {
  8017. return position;
  8018. }
  8019. #if JUCE_UNIT_TESTS
  8020. class MemoryStreamTests : public UnitTest
  8021. {
  8022. public:
  8023. MemoryStreamTests() : UnitTest ("MemoryInputStream & MemoryOutputStream") {}
  8024. void runTest()
  8025. {
  8026. beginTest ("Basics");
  8027. int randomInt = Random::getSystemRandom().nextInt();
  8028. int64 randomInt64 = Random::getSystemRandom().nextInt64();
  8029. double randomDouble = Random::getSystemRandom().nextDouble();
  8030. String randomString;
  8031. for (int i = 50; --i >= 0;)
  8032. randomString << (juce_wchar) (Random::getSystemRandom().nextInt() & 0xffff);
  8033. MemoryOutputStream mo;
  8034. mo.writeInt (randomInt);
  8035. mo.writeIntBigEndian (randomInt);
  8036. mo.writeCompressedInt (randomInt);
  8037. mo.writeString (randomString);
  8038. mo.writeInt64 (randomInt64);
  8039. mo.writeInt64BigEndian (randomInt64);
  8040. mo.writeDouble (randomDouble);
  8041. mo.writeDoubleBigEndian (randomDouble);
  8042. MemoryInputStream mi (mo.getData(), mo.getDataSize(), false);
  8043. expect (mi.readInt() == randomInt);
  8044. expect (mi.readIntBigEndian() == randomInt);
  8045. expect (mi.readCompressedInt() == randomInt);
  8046. expect (mi.readString() == randomString);
  8047. expect (mi.readInt64() == randomInt64);
  8048. expect (mi.readInt64BigEndian() == randomInt64);
  8049. expect (mi.readDouble() == randomDouble);
  8050. expect (mi.readDoubleBigEndian() == randomDouble);
  8051. }
  8052. };
  8053. static MemoryStreamTests memoryInputStreamUnitTests;
  8054. #endif
  8055. END_JUCE_NAMESPACE
  8056. /*** End of inlined file: juce_MemoryInputStream.cpp ***/
  8057. /*** Start of inlined file: juce_MemoryOutputStream.cpp ***/
  8058. BEGIN_JUCE_NAMESPACE
  8059. MemoryOutputStream::MemoryOutputStream (const size_t initialSize)
  8060. : data (internalBlock),
  8061. position (0),
  8062. size (0)
  8063. {
  8064. internalBlock.setSize (initialSize, false);
  8065. }
  8066. MemoryOutputStream::MemoryOutputStream (MemoryBlock& memoryBlockToWriteTo,
  8067. const bool appendToExistingBlockContent)
  8068. : data (memoryBlockToWriteTo),
  8069. position (0),
  8070. size (0)
  8071. {
  8072. if (appendToExistingBlockContent)
  8073. position = size = memoryBlockToWriteTo.getSize();
  8074. }
  8075. MemoryOutputStream::~MemoryOutputStream()
  8076. {
  8077. flush();
  8078. }
  8079. void MemoryOutputStream::flush()
  8080. {
  8081. if (&data != &internalBlock)
  8082. data.setSize (size, false);
  8083. }
  8084. void MemoryOutputStream::preallocate (const size_t bytesToPreallocate)
  8085. {
  8086. data.ensureSize (bytesToPreallocate + 1);
  8087. }
  8088. void MemoryOutputStream::reset() throw()
  8089. {
  8090. position = 0;
  8091. size = 0;
  8092. }
  8093. bool MemoryOutputStream::write (const void* const buffer, int howMany)
  8094. {
  8095. if (howMany > 0)
  8096. {
  8097. const size_t storageNeeded = position + howMany;
  8098. if (storageNeeded >= data.getSize())
  8099. data.ensureSize ((storageNeeded + jmin (storageNeeded / 2, (size_t) (1024 * 1024)) + 32) & ~31);
  8100. memcpy (static_cast<char*> (data.getData()) + position, buffer, howMany);
  8101. position += howMany;
  8102. size = jmax (size, position);
  8103. }
  8104. return true;
  8105. }
  8106. const void* MemoryOutputStream::getData() const throw()
  8107. {
  8108. void* const d = data.getData();
  8109. if (data.getSize() > size)
  8110. static_cast <char*> (d) [size] = 0;
  8111. return d;
  8112. }
  8113. bool MemoryOutputStream::setPosition (int64 newPosition)
  8114. {
  8115. if (newPosition <= (int64) size)
  8116. {
  8117. // ok to seek backwards
  8118. position = jlimit ((size_t) 0, size, (size_t) newPosition);
  8119. return true;
  8120. }
  8121. else
  8122. {
  8123. // trying to make it bigger isn't a good thing to do..
  8124. return false;
  8125. }
  8126. }
  8127. int MemoryOutputStream::writeFromInputStream (InputStream& source, int64 maxNumBytesToWrite)
  8128. {
  8129. // before writing from an input, see if we can preallocate to make it more efficient..
  8130. int64 availableData = source.getTotalLength() - source.getPosition();
  8131. if (availableData > 0)
  8132. {
  8133. if (maxNumBytesToWrite > 0 && maxNumBytesToWrite < availableData)
  8134. availableData = maxNumBytesToWrite;
  8135. preallocate (data.getSize() + (size_t) maxNumBytesToWrite);
  8136. }
  8137. return OutputStream::writeFromInputStream (source, maxNumBytesToWrite);
  8138. }
  8139. const String MemoryOutputStream::toUTF8() const
  8140. {
  8141. return String (static_cast <const char*> (getData()), getDataSize());
  8142. }
  8143. const String MemoryOutputStream::toString() const
  8144. {
  8145. return String::createStringFromData (getData(), getDataSize());
  8146. }
  8147. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryOutputStream& streamToRead)
  8148. {
  8149. stream.write (streamToRead.getData(), streamToRead.getDataSize());
  8150. return stream;
  8151. }
  8152. END_JUCE_NAMESPACE
  8153. /*** End of inlined file: juce_MemoryOutputStream.cpp ***/
  8154. /*** Start of inlined file: juce_SubregionStream.cpp ***/
  8155. BEGIN_JUCE_NAMESPACE
  8156. SubregionStream::SubregionStream (InputStream* const sourceStream,
  8157. const int64 startPositionInSourceStream_,
  8158. const int64 lengthOfSourceStream_,
  8159. const bool deleteSourceWhenDestroyed)
  8160. : source (sourceStream),
  8161. startPositionInSourceStream (startPositionInSourceStream_),
  8162. lengthOfSourceStream (lengthOfSourceStream_)
  8163. {
  8164. if (deleteSourceWhenDestroyed)
  8165. sourceToDelete = source;
  8166. setPosition (0);
  8167. }
  8168. SubregionStream::~SubregionStream()
  8169. {
  8170. }
  8171. int64 SubregionStream::getTotalLength()
  8172. {
  8173. const int64 srcLen = source->getTotalLength() - startPositionInSourceStream;
  8174. return (lengthOfSourceStream >= 0) ? jmin (lengthOfSourceStream, srcLen)
  8175. : srcLen;
  8176. }
  8177. int64 SubregionStream::getPosition()
  8178. {
  8179. return source->getPosition() - startPositionInSourceStream;
  8180. }
  8181. bool SubregionStream::setPosition (int64 newPosition)
  8182. {
  8183. return source->setPosition (jmax ((int64) 0, newPosition + startPositionInSourceStream));
  8184. }
  8185. int SubregionStream::read (void* destBuffer, int maxBytesToRead)
  8186. {
  8187. if (lengthOfSourceStream < 0)
  8188. {
  8189. return source->read (destBuffer, maxBytesToRead);
  8190. }
  8191. else
  8192. {
  8193. maxBytesToRead = (int) jmin ((int64) maxBytesToRead, lengthOfSourceStream - getPosition());
  8194. if (maxBytesToRead <= 0)
  8195. return 0;
  8196. return source->read (destBuffer, maxBytesToRead);
  8197. }
  8198. }
  8199. bool SubregionStream::isExhausted()
  8200. {
  8201. if (lengthOfSourceStream >= 0)
  8202. return (getPosition() >= lengthOfSourceStream) || source->isExhausted();
  8203. else
  8204. return source->isExhausted();
  8205. }
  8206. END_JUCE_NAMESPACE
  8207. /*** End of inlined file: juce_SubregionStream.cpp ***/
  8208. /*** Start of inlined file: juce_PerformanceCounter.cpp ***/
  8209. BEGIN_JUCE_NAMESPACE
  8210. PerformanceCounter::PerformanceCounter (const String& name_,
  8211. int runsPerPrintout,
  8212. const File& loggingFile)
  8213. : name (name_),
  8214. numRuns (0),
  8215. runsPerPrint (runsPerPrintout),
  8216. totalTime (0),
  8217. outputFile (loggingFile)
  8218. {
  8219. if (outputFile != File::nonexistent)
  8220. {
  8221. String s ("**** Counter for \"");
  8222. s << name_ << "\" started at: "
  8223. << Time::getCurrentTime().toString (true, true)
  8224. << "\r\n";
  8225. outputFile.appendText (s, false, false);
  8226. }
  8227. }
  8228. PerformanceCounter::~PerformanceCounter()
  8229. {
  8230. printStatistics();
  8231. }
  8232. void PerformanceCounter::start()
  8233. {
  8234. started = Time::getHighResolutionTicks();
  8235. }
  8236. void PerformanceCounter::stop()
  8237. {
  8238. const int64 now = Time::getHighResolutionTicks();
  8239. totalTime += 1000.0 * Time::highResolutionTicksToSeconds (now - started);
  8240. if (++numRuns == runsPerPrint)
  8241. printStatistics();
  8242. }
  8243. void PerformanceCounter::printStatistics()
  8244. {
  8245. if (numRuns > 0)
  8246. {
  8247. String s ("Performance count for \"");
  8248. s << name << "\" - average over " << numRuns << " run(s) = ";
  8249. const int micros = (int) (totalTime * (1000.0 / numRuns));
  8250. if (micros > 10000)
  8251. s << (micros/1000) << " millisecs";
  8252. else
  8253. s << micros << " microsecs";
  8254. s << ", total = " << String (totalTime / 1000, 5) << " seconds";
  8255. Logger::outputDebugString (s);
  8256. s << "\r\n";
  8257. if (outputFile != File::nonexistent)
  8258. outputFile.appendText (s, false, false);
  8259. numRuns = 0;
  8260. totalTime = 0;
  8261. }
  8262. }
  8263. END_JUCE_NAMESPACE
  8264. /*** End of inlined file: juce_PerformanceCounter.cpp ***/
  8265. /*** Start of inlined file: juce_Uuid.cpp ***/
  8266. BEGIN_JUCE_NAMESPACE
  8267. Uuid::Uuid()
  8268. {
  8269. // Mix up any available MAC addresses with some time-based pseudo-random numbers
  8270. // to make it very very unlikely that two UUIDs will ever be the same..
  8271. static int64 macAddresses[2];
  8272. static bool hasCheckedMacAddresses = false;
  8273. if (! hasCheckedMacAddresses)
  8274. {
  8275. hasCheckedMacAddresses = true;
  8276. SystemStats::getMACAddresses (macAddresses, 2);
  8277. }
  8278. value.asInt64[0] = macAddresses[0];
  8279. value.asInt64[1] = macAddresses[1];
  8280. // We'll use both a local RNG that is re-seeded, plus the shared RNG,
  8281. // whose seed will carry over between calls to this method.
  8282. Random r (macAddresses[0] ^ macAddresses[1]
  8283. ^ Random::getSystemRandom().nextInt64());
  8284. for (int i = 4; --i >= 0;)
  8285. {
  8286. r.setSeedRandomly(); // calling this repeatedly improves randomness
  8287. value.asInt[i] ^= r.nextInt();
  8288. value.asInt[i] ^= Random::getSystemRandom().nextInt();
  8289. }
  8290. }
  8291. Uuid::~Uuid() throw()
  8292. {
  8293. }
  8294. Uuid::Uuid (const Uuid& other)
  8295. : value (other.value)
  8296. {
  8297. }
  8298. Uuid& Uuid::operator= (const Uuid& other)
  8299. {
  8300. value = other.value;
  8301. return *this;
  8302. }
  8303. bool Uuid::operator== (const Uuid& other) const
  8304. {
  8305. return value.asInt64[0] == other.value.asInt64[0]
  8306. && value.asInt64[1] == other.value.asInt64[1];
  8307. }
  8308. bool Uuid::operator!= (const Uuid& other) const
  8309. {
  8310. return ! operator== (other);
  8311. }
  8312. bool Uuid::isNull() const throw()
  8313. {
  8314. return (value.asInt64 [0] == 0) && (value.asInt64 [1] == 0);
  8315. }
  8316. const String Uuid::toString() const
  8317. {
  8318. return String::toHexString (value.asBytes, sizeof (value.asBytes), 0);
  8319. }
  8320. Uuid::Uuid (const String& uuidString)
  8321. {
  8322. operator= (uuidString);
  8323. }
  8324. Uuid& Uuid::operator= (const String& uuidString)
  8325. {
  8326. MemoryBlock mb;
  8327. mb.loadFromHexString (uuidString);
  8328. mb.ensureSize (sizeof (value.asBytes), true);
  8329. mb.copyTo (value.asBytes, 0, sizeof (value.asBytes));
  8330. return *this;
  8331. }
  8332. Uuid::Uuid (const uint8* const rawData)
  8333. {
  8334. operator= (rawData);
  8335. }
  8336. Uuid& Uuid::operator= (const uint8* const rawData)
  8337. {
  8338. if (rawData != 0)
  8339. memcpy (value.asBytes, rawData, sizeof (value.asBytes));
  8340. else
  8341. zeromem (value.asBytes, sizeof (value.asBytes));
  8342. return *this;
  8343. }
  8344. END_JUCE_NAMESPACE
  8345. /*** End of inlined file: juce_Uuid.cpp ***/
  8346. /*** Start of inlined file: juce_ZipFile.cpp ***/
  8347. BEGIN_JUCE_NAMESPACE
  8348. class ZipFile::ZipEntryInfo
  8349. {
  8350. public:
  8351. ZipFile::ZipEntry entry;
  8352. int streamOffset;
  8353. int compressedSize;
  8354. bool compressed;
  8355. };
  8356. class ZipFile::ZipInputStream : public InputStream
  8357. {
  8358. public:
  8359. ZipInputStream (ZipFile& file_, ZipFile::ZipEntryInfo& zei)
  8360. : file (file_),
  8361. zipEntryInfo (zei),
  8362. pos (0),
  8363. headerSize (0),
  8364. inputStream (0)
  8365. {
  8366. inputStream = file_.inputStream;
  8367. if (file_.inputSource != 0)
  8368. {
  8369. inputStream = file.inputSource->createInputStream();
  8370. }
  8371. else
  8372. {
  8373. #if JUCE_DEBUG
  8374. file_.numOpenStreams++;
  8375. #endif
  8376. }
  8377. char buffer [30];
  8378. if (inputStream != 0
  8379. && inputStream->setPosition (zei.streamOffset)
  8380. && inputStream->read (buffer, 30) == 30
  8381. && ByteOrder::littleEndianInt (buffer) == 0x04034b50)
  8382. {
  8383. headerSize = 30 + ByteOrder::littleEndianShort (buffer + 26)
  8384. + ByteOrder::littleEndianShort (buffer + 28);
  8385. }
  8386. }
  8387. ~ZipInputStream()
  8388. {
  8389. #if JUCE_DEBUG
  8390. if (inputStream != 0 && inputStream == file.inputStream)
  8391. file.numOpenStreams--;
  8392. #endif
  8393. if (inputStream != file.inputStream)
  8394. delete inputStream;
  8395. }
  8396. int64 getTotalLength()
  8397. {
  8398. return zipEntryInfo.compressedSize;
  8399. }
  8400. int read (void* buffer, int howMany)
  8401. {
  8402. if (headerSize <= 0)
  8403. return 0;
  8404. howMany = (int) jmin ((int64) howMany, zipEntryInfo.compressedSize - pos);
  8405. if (inputStream == 0)
  8406. return 0;
  8407. int num;
  8408. if (inputStream == file.inputStream)
  8409. {
  8410. const ScopedLock sl (file.lock);
  8411. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  8412. num = inputStream->read (buffer, howMany);
  8413. }
  8414. else
  8415. {
  8416. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  8417. num = inputStream->read (buffer, howMany);
  8418. }
  8419. pos += num;
  8420. return num;
  8421. }
  8422. bool isExhausted()
  8423. {
  8424. return headerSize <= 0 || pos >= zipEntryInfo.compressedSize;
  8425. }
  8426. int64 getPosition()
  8427. {
  8428. return pos;
  8429. }
  8430. bool setPosition (int64 newPos)
  8431. {
  8432. pos = jlimit ((int64) 0, (int64) zipEntryInfo.compressedSize, newPos);
  8433. return true;
  8434. }
  8435. private:
  8436. ZipFile& file;
  8437. ZipEntryInfo zipEntryInfo;
  8438. int64 pos;
  8439. int headerSize;
  8440. InputStream* inputStream;
  8441. ZipInputStream (const ZipInputStream&);
  8442. ZipInputStream& operator= (const ZipInputStream&);
  8443. };
  8444. ZipFile::ZipFile (InputStream* const source_, const bool deleteStreamWhenDestroyed)
  8445. : inputStream (source_)
  8446. #if JUCE_DEBUG
  8447. , numOpenStreams (0)
  8448. #endif
  8449. {
  8450. if (deleteStreamWhenDestroyed)
  8451. streamToDelete = inputStream;
  8452. init();
  8453. }
  8454. ZipFile::ZipFile (const File& file)
  8455. : inputStream (0)
  8456. #if JUCE_DEBUG
  8457. , numOpenStreams (0)
  8458. #endif
  8459. {
  8460. inputSource = new FileInputSource (file);
  8461. init();
  8462. }
  8463. ZipFile::ZipFile (InputSource* const inputSource_)
  8464. : inputStream (0),
  8465. inputSource (inputSource_)
  8466. #if JUCE_DEBUG
  8467. , numOpenStreams (0)
  8468. #endif
  8469. {
  8470. init();
  8471. }
  8472. ZipFile::~ZipFile()
  8473. {
  8474. #if JUCE_DEBUG
  8475. entries.clear();
  8476. // If you hit this assertion, it means you've created a stream to read
  8477. // one of the items in the zipfile, but you've forgotten to delete that
  8478. // stream object before deleting the file.. Streams can't be kept open
  8479. // after the file is deleted because they need to share the input
  8480. // stream that the file uses to read itself.
  8481. jassert (numOpenStreams == 0);
  8482. #endif
  8483. }
  8484. int ZipFile::getNumEntries() const throw()
  8485. {
  8486. return entries.size();
  8487. }
  8488. const ZipFile::ZipEntry* ZipFile::getEntry (const int index) const throw()
  8489. {
  8490. ZipEntryInfo* const zei = entries [index];
  8491. return zei != 0 ? &(zei->entry) : 0;
  8492. }
  8493. int ZipFile::getIndexOfFileName (const String& fileName) const throw()
  8494. {
  8495. for (int i = 0; i < entries.size(); ++i)
  8496. if (entries.getUnchecked (i)->entry.filename == fileName)
  8497. return i;
  8498. return -1;
  8499. }
  8500. const ZipFile::ZipEntry* ZipFile::getEntry (const String& fileName) const throw()
  8501. {
  8502. return getEntry (getIndexOfFileName (fileName));
  8503. }
  8504. InputStream* ZipFile::createStreamForEntry (const int index)
  8505. {
  8506. ZipEntryInfo* const zei = entries[index];
  8507. InputStream* stream = 0;
  8508. if (zei != 0)
  8509. {
  8510. stream = new ZipInputStream (*this, *zei);
  8511. if (zei->compressed)
  8512. {
  8513. stream = new GZIPDecompressorInputStream (stream, true, true,
  8514. zei->entry.uncompressedSize);
  8515. // (much faster to unzip in big blocks using a buffer..)
  8516. stream = new BufferedInputStream (stream, 32768, true);
  8517. }
  8518. }
  8519. return stream;
  8520. }
  8521. class ZipFile::ZipFilenameComparator
  8522. {
  8523. public:
  8524. int compareElements (const ZipFile::ZipEntryInfo* first, const ZipFile::ZipEntryInfo* second)
  8525. {
  8526. return first->entry.filename.compare (second->entry.filename);
  8527. }
  8528. };
  8529. void ZipFile::sortEntriesByFilename()
  8530. {
  8531. ZipFilenameComparator sorter;
  8532. entries.sort (sorter);
  8533. }
  8534. void ZipFile::init()
  8535. {
  8536. ScopedPointer <InputStream> toDelete;
  8537. InputStream* in = inputStream;
  8538. if (inputSource != 0)
  8539. {
  8540. in = inputSource->createInputStream();
  8541. toDelete = in;
  8542. }
  8543. if (in != 0)
  8544. {
  8545. int numEntries = 0;
  8546. int pos = findEndOfZipEntryTable (in, numEntries);
  8547. if (pos >= 0 && pos < in->getTotalLength())
  8548. {
  8549. const int size = (int) (in->getTotalLength() - pos);
  8550. in->setPosition (pos);
  8551. MemoryBlock headerData;
  8552. if (in->readIntoMemoryBlock (headerData, size) == size)
  8553. {
  8554. pos = 0;
  8555. for (int i = 0; i < numEntries; ++i)
  8556. {
  8557. if (pos + 46 > size)
  8558. break;
  8559. const char* const buffer = static_cast <const char*> (headerData.getData()) + pos;
  8560. const int fileNameLen = ByteOrder::littleEndianShort (buffer + 28);
  8561. if (pos + 46 + fileNameLen > size)
  8562. break;
  8563. ZipEntryInfo* const zei = new ZipEntryInfo();
  8564. zei->entry.filename = String::fromUTF8 (buffer + 46, fileNameLen);
  8565. const int time = ByteOrder::littleEndianShort (buffer + 12);
  8566. const int date = ByteOrder::littleEndianShort (buffer + 14);
  8567. const int year = 1980 + (date >> 9);
  8568. const int month = ((date >> 5) & 15) - 1;
  8569. const int day = date & 31;
  8570. const int hours = time >> 11;
  8571. const int minutes = (time >> 5) & 63;
  8572. const int seconds = (time & 31) << 1;
  8573. zei->entry.fileTime = Time (year, month, day, hours, minutes, seconds);
  8574. zei->compressed = ByteOrder::littleEndianShort (buffer + 10) != 0;
  8575. zei->compressedSize = ByteOrder::littleEndianInt (buffer + 20);
  8576. zei->entry.uncompressedSize = ByteOrder::littleEndianInt (buffer + 24);
  8577. zei->streamOffset = ByteOrder::littleEndianInt (buffer + 42);
  8578. entries.add (zei);
  8579. pos += 46 + fileNameLen
  8580. + ByteOrder::littleEndianShort (buffer + 30)
  8581. + ByteOrder::littleEndianShort (buffer + 32);
  8582. }
  8583. }
  8584. }
  8585. }
  8586. }
  8587. int ZipFile::findEndOfZipEntryTable (InputStream* input, int& numEntries)
  8588. {
  8589. BufferedInputStream in (input, 8192, false);
  8590. in.setPosition (in.getTotalLength());
  8591. int64 pos = in.getPosition();
  8592. const int64 lowestPos = jmax ((int64) 0, pos - 1024);
  8593. char buffer [32];
  8594. zeromem (buffer, sizeof (buffer));
  8595. while (pos > lowestPos)
  8596. {
  8597. in.setPosition (pos - 22);
  8598. pos = in.getPosition();
  8599. memcpy (buffer + 22, buffer, 4);
  8600. if (in.read (buffer, 22) != 22)
  8601. return 0;
  8602. for (int i = 0; i < 22; ++i)
  8603. {
  8604. if (ByteOrder::littleEndianInt (buffer + i) == 0x06054b50)
  8605. {
  8606. in.setPosition (pos + i);
  8607. in.read (buffer, 22);
  8608. numEntries = ByteOrder::littleEndianShort (buffer + 10);
  8609. return ByteOrder::littleEndianInt (buffer + 16);
  8610. }
  8611. }
  8612. }
  8613. return 0;
  8614. }
  8615. bool ZipFile::uncompressTo (const File& targetDirectory,
  8616. const bool shouldOverwriteFiles)
  8617. {
  8618. for (int i = 0; i < entries.size(); ++i)
  8619. if (! uncompressEntry (i, targetDirectory, shouldOverwriteFiles))
  8620. return false;
  8621. return true;
  8622. }
  8623. bool ZipFile::uncompressEntry (const int index,
  8624. const File& targetDirectory,
  8625. bool shouldOverwriteFiles)
  8626. {
  8627. const ZipEntryInfo* zei = entries [index];
  8628. if (zei != 0)
  8629. {
  8630. const File targetFile (targetDirectory.getChildFile (zei->entry.filename));
  8631. if (zei->entry.filename.endsWithChar ('/'))
  8632. {
  8633. return targetFile.createDirectory(); // (entry is a directory, not a file)
  8634. }
  8635. else
  8636. {
  8637. ScopedPointer<InputStream> in (createStreamForEntry (index));
  8638. if (in != 0)
  8639. {
  8640. if (shouldOverwriteFiles && ! targetFile.deleteFile())
  8641. return false;
  8642. if ((! targetFile.exists()) && targetFile.getParentDirectory().createDirectory())
  8643. {
  8644. ScopedPointer<FileOutputStream> out (targetFile.createOutputStream());
  8645. if (out != 0)
  8646. {
  8647. out->writeFromInputStream (*in, -1);
  8648. out = 0;
  8649. targetFile.setCreationTime (zei->entry.fileTime);
  8650. targetFile.setLastModificationTime (zei->entry.fileTime);
  8651. targetFile.setLastAccessTime (zei->entry.fileTime);
  8652. return true;
  8653. }
  8654. }
  8655. }
  8656. }
  8657. }
  8658. return false;
  8659. }
  8660. END_JUCE_NAMESPACE
  8661. /*** End of inlined file: juce_ZipFile.cpp ***/
  8662. /*** Start of inlined file: juce_CharacterFunctions.cpp ***/
  8663. #if JUCE_MSVC
  8664. #pragma warning (push)
  8665. #pragma warning (disable: 4514 4996)
  8666. #endif
  8667. #include <cwctype>
  8668. #include <cctype>
  8669. #include <ctime>
  8670. BEGIN_JUCE_NAMESPACE
  8671. int CharacterFunctions::length (const char* const s) throw()
  8672. {
  8673. return (int) strlen (s);
  8674. }
  8675. int CharacterFunctions::length (const juce_wchar* const s) throw()
  8676. {
  8677. return (int) wcslen (s);
  8678. }
  8679. void CharacterFunctions::copy (char* dest, const char* src, const int maxChars) throw()
  8680. {
  8681. strncpy (dest, src, maxChars);
  8682. }
  8683. void CharacterFunctions::copy (juce_wchar* dest, const juce_wchar* src, int maxChars) throw()
  8684. {
  8685. wcsncpy (dest, src, maxChars);
  8686. }
  8687. void CharacterFunctions::copy (juce_wchar* dest, const char* src, const int maxChars) throw()
  8688. {
  8689. mbstowcs (dest, src, maxChars);
  8690. }
  8691. void CharacterFunctions::copy (char* dest, const juce_wchar* src, const int maxChars) throw()
  8692. {
  8693. wcstombs (dest, src, maxChars);
  8694. }
  8695. int CharacterFunctions::bytesRequiredForCopy (const juce_wchar* src) throw()
  8696. {
  8697. return (int) wcstombs (0, src, 0);
  8698. }
  8699. void CharacterFunctions::append (char* dest, const char* src) throw()
  8700. {
  8701. strcat (dest, src);
  8702. }
  8703. void CharacterFunctions::append (juce_wchar* dest, const juce_wchar* src) throw()
  8704. {
  8705. wcscat (dest, src);
  8706. }
  8707. int CharacterFunctions::compare (const char* const s1, const char* const s2) throw()
  8708. {
  8709. return strcmp (s1, s2);
  8710. }
  8711. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2) throw()
  8712. {
  8713. jassert (s1 != 0 && s2 != 0);
  8714. return wcscmp (s1, s2);
  8715. }
  8716. int CharacterFunctions::compare (const char* const s1, const char* const s2, const int maxChars) throw()
  8717. {
  8718. jassert (s1 != 0 && s2 != 0);
  8719. return strncmp (s1, s2, maxChars);
  8720. }
  8721. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  8722. {
  8723. jassert (s1 != 0 && s2 != 0);
  8724. return wcsncmp (s1, s2, maxChars);
  8725. }
  8726. int CharacterFunctions::compare (const juce_wchar* s1, const char* s2) throw()
  8727. {
  8728. jassert (s1 != 0 && s2 != 0);
  8729. for (;;)
  8730. {
  8731. const int diff = (int) (*s1 - (juce_wchar) (unsigned char) *s2);
  8732. if (diff != 0)
  8733. return diff;
  8734. else if (*s1 == 0)
  8735. break;
  8736. ++s1;
  8737. ++s2;
  8738. }
  8739. return 0;
  8740. }
  8741. int CharacterFunctions::compare (const char* s1, const juce_wchar* s2) throw()
  8742. {
  8743. return -compare (s2, s1);
  8744. }
  8745. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2) throw()
  8746. {
  8747. jassert (s1 != 0 && s2 != 0);
  8748. #if JUCE_WINDOWS
  8749. return stricmp (s1, s2);
  8750. #else
  8751. return strcasecmp (s1, s2);
  8752. #endif
  8753. }
  8754. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2) throw()
  8755. {
  8756. jassert (s1 != 0 && s2 != 0);
  8757. #if JUCE_WINDOWS
  8758. return _wcsicmp (s1, s2);
  8759. #else
  8760. for (;;)
  8761. {
  8762. if (*s1 != *s2)
  8763. {
  8764. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  8765. if (diff != 0)
  8766. return diff < 0 ? -1 : 1;
  8767. }
  8768. else if (*s1 == 0)
  8769. break;
  8770. ++s1;
  8771. ++s2;
  8772. }
  8773. return 0;
  8774. #endif
  8775. }
  8776. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const char* s2) throw()
  8777. {
  8778. jassert (s1 != 0 && s2 != 0);
  8779. for (;;)
  8780. {
  8781. if (*s1 != *s2)
  8782. {
  8783. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  8784. if (diff != 0)
  8785. return diff < 0 ? -1 : 1;
  8786. }
  8787. else if (*s1 == 0)
  8788. break;
  8789. ++s1;
  8790. ++s2;
  8791. }
  8792. return 0;
  8793. }
  8794. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2, const int maxChars) throw()
  8795. {
  8796. jassert (s1 != 0 && s2 != 0);
  8797. #if JUCE_WINDOWS
  8798. return strnicmp (s1, s2, maxChars);
  8799. #else
  8800. return strncasecmp (s1, s2, maxChars);
  8801. #endif
  8802. }
  8803. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  8804. {
  8805. jassert (s1 != 0 && s2 != 0);
  8806. #if JUCE_WINDOWS
  8807. return _wcsnicmp (s1, s2, maxChars);
  8808. #else
  8809. while (--maxChars >= 0)
  8810. {
  8811. if (*s1 != *s2)
  8812. {
  8813. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  8814. if (diff != 0)
  8815. return diff < 0 ? -1 : 1;
  8816. }
  8817. else if (*s1 == 0)
  8818. break;
  8819. ++s1;
  8820. ++s2;
  8821. }
  8822. return 0;
  8823. #endif
  8824. }
  8825. const char* CharacterFunctions::find (const char* const haystack, const char* const needle) throw()
  8826. {
  8827. return strstr (haystack, needle);
  8828. }
  8829. const juce_wchar* CharacterFunctions::find (const juce_wchar* haystack, const juce_wchar* const needle) throw()
  8830. {
  8831. return wcsstr (haystack, needle);
  8832. }
  8833. int CharacterFunctions::indexOfChar (const char* const haystack, const char needle, const bool ignoreCase) throw()
  8834. {
  8835. if (haystack != 0)
  8836. {
  8837. int i = 0;
  8838. if (ignoreCase)
  8839. {
  8840. const char n1 = toLowerCase (needle);
  8841. const char n2 = toUpperCase (needle);
  8842. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  8843. {
  8844. while (haystack[i] != 0)
  8845. {
  8846. if (haystack[i] == n1 || haystack[i] == n2)
  8847. return i;
  8848. ++i;
  8849. }
  8850. return -1;
  8851. }
  8852. jassert (n1 == needle);
  8853. }
  8854. while (haystack[i] != 0)
  8855. {
  8856. if (haystack[i] == needle)
  8857. return i;
  8858. ++i;
  8859. }
  8860. }
  8861. return -1;
  8862. }
  8863. int CharacterFunctions::indexOfChar (const juce_wchar* const haystack, const juce_wchar needle, const bool ignoreCase) throw()
  8864. {
  8865. if (haystack != 0)
  8866. {
  8867. int i = 0;
  8868. if (ignoreCase)
  8869. {
  8870. const juce_wchar n1 = toLowerCase (needle);
  8871. const juce_wchar n2 = toUpperCase (needle);
  8872. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  8873. {
  8874. while (haystack[i] != 0)
  8875. {
  8876. if (haystack[i] == n1 || haystack[i] == n2)
  8877. return i;
  8878. ++i;
  8879. }
  8880. return -1;
  8881. }
  8882. jassert (n1 == needle);
  8883. }
  8884. while (haystack[i] != 0)
  8885. {
  8886. if (haystack[i] == needle)
  8887. return i;
  8888. ++i;
  8889. }
  8890. }
  8891. return -1;
  8892. }
  8893. int CharacterFunctions::indexOfCharFast (const char* const haystack, const char needle) throw()
  8894. {
  8895. jassert (haystack != 0);
  8896. int i = 0;
  8897. while (haystack[i] != 0)
  8898. {
  8899. if (haystack[i] == needle)
  8900. return i;
  8901. ++i;
  8902. }
  8903. return -1;
  8904. }
  8905. int CharacterFunctions::indexOfCharFast (const juce_wchar* const haystack, const juce_wchar needle) throw()
  8906. {
  8907. jassert (haystack != 0);
  8908. int i = 0;
  8909. while (haystack[i] != 0)
  8910. {
  8911. if (haystack[i] == needle)
  8912. return i;
  8913. ++i;
  8914. }
  8915. return -1;
  8916. }
  8917. int CharacterFunctions::getIntialSectionContainingOnly (const char* const text, const char* const allowedChars) throw()
  8918. {
  8919. return allowedChars == 0 ? 0 : (int) strspn (text, allowedChars);
  8920. }
  8921. int CharacterFunctions::getIntialSectionContainingOnly (const juce_wchar* const text, const juce_wchar* const allowedChars) throw()
  8922. {
  8923. if (allowedChars == 0)
  8924. return 0;
  8925. int i = 0;
  8926. for (;;)
  8927. {
  8928. if (indexOfCharFast (allowedChars, text[i]) < 0)
  8929. break;
  8930. ++i;
  8931. }
  8932. return i;
  8933. }
  8934. int CharacterFunctions::ftime (char* const dest, const int maxChars, const char* const format, const struct tm* const tm) throw()
  8935. {
  8936. return (int) strftime (dest, maxChars, format, tm);
  8937. }
  8938. int CharacterFunctions::ftime (juce_wchar* const dest, const int maxChars, const juce_wchar* const format, const struct tm* const tm) throw()
  8939. {
  8940. return (int) wcsftime (dest, maxChars, format, tm);
  8941. }
  8942. int CharacterFunctions::getIntValue (const char* const s) throw()
  8943. {
  8944. return atoi (s);
  8945. }
  8946. int CharacterFunctions::getIntValue (const juce_wchar* s) throw()
  8947. {
  8948. #if JUCE_WINDOWS
  8949. return _wtoi (s);
  8950. #else
  8951. int v = 0;
  8952. while (isWhitespace (*s))
  8953. ++s;
  8954. const bool isNeg = *s == '-';
  8955. if (isNeg)
  8956. ++s;
  8957. for (;;)
  8958. {
  8959. const wchar_t c = *s++;
  8960. if (c >= '0' && c <= '9')
  8961. v = v * 10 + (int) (c - '0');
  8962. else
  8963. break;
  8964. }
  8965. return isNeg ? -v : v;
  8966. #endif
  8967. }
  8968. int64 CharacterFunctions::getInt64Value (const char* s) throw()
  8969. {
  8970. #if JUCE_LINUX
  8971. return atoll (s);
  8972. #elif JUCE_WINDOWS
  8973. return _atoi64 (s);
  8974. #else
  8975. int64 v = 0;
  8976. while (isWhitespace (*s))
  8977. ++s;
  8978. const bool isNeg = *s == '-';
  8979. if (isNeg)
  8980. ++s;
  8981. for (;;)
  8982. {
  8983. const char c = *s++;
  8984. if (c >= '0' && c <= '9')
  8985. v = v * 10 + (int64) (c - '0');
  8986. else
  8987. break;
  8988. }
  8989. return isNeg ? -v : v;
  8990. #endif
  8991. }
  8992. int64 CharacterFunctions::getInt64Value (const juce_wchar* s) throw()
  8993. {
  8994. #if JUCE_WINDOWS
  8995. return _wtoi64 (s);
  8996. #else
  8997. int64 v = 0;
  8998. while (isWhitespace (*s))
  8999. ++s;
  9000. const bool isNeg = *s == '-';
  9001. if (isNeg)
  9002. ++s;
  9003. for (;;)
  9004. {
  9005. const juce_wchar c = *s++;
  9006. if (c >= '0' && c <= '9')
  9007. v = v * 10 + (int64) (c - '0');
  9008. else
  9009. break;
  9010. }
  9011. return isNeg ? -v : v;
  9012. #endif
  9013. }
  9014. static double juce_mulexp10 (const double value, int exponent) throw()
  9015. {
  9016. if (exponent == 0)
  9017. return value;
  9018. if (value == 0)
  9019. return 0;
  9020. const bool negative = (exponent < 0);
  9021. if (negative)
  9022. exponent = -exponent;
  9023. double result = 1.0, power = 10.0;
  9024. for (int bit = 1; exponent != 0; bit <<= 1)
  9025. {
  9026. if ((exponent & bit) != 0)
  9027. {
  9028. exponent ^= bit;
  9029. result *= power;
  9030. if (exponent == 0)
  9031. break;
  9032. }
  9033. power *= power;
  9034. }
  9035. return negative ? (value / result) : (value * result);
  9036. }
  9037. template <class CharType>
  9038. double juce_atof (const CharType* const original) throw()
  9039. {
  9040. double result[3] = { 0, 0, 0 }, accumulator[2] = { 0, 0 };
  9041. int exponentAdjustment[2] = { 0, 0 }, exponentAccumulator[2] = { -1, -1 };
  9042. int exponent = 0, decPointIndex = 0, digit = 0;
  9043. int lastDigit = 0, numSignificantDigits = 0;
  9044. bool isNegative = false, digitsFound = false;
  9045. const int maxSignificantDigits = 15 + 2;
  9046. const CharType* s = original;
  9047. while (CharacterFunctions::isWhitespace (*s))
  9048. ++s;
  9049. switch (*s)
  9050. {
  9051. case '-': isNegative = true; // fall-through..
  9052. case '+': ++s;
  9053. }
  9054. if (*s == 'n' || *s == 'N' || *s == 'i' || *s == 'I')
  9055. return atof (String (original).toUTF8()); // Let the c library deal with NAN and INF
  9056. for (;;)
  9057. {
  9058. if (CharacterFunctions::isDigit (*s))
  9059. {
  9060. lastDigit = digit;
  9061. digit = *s++ - '0';
  9062. digitsFound = true;
  9063. if (decPointIndex != 0)
  9064. exponentAdjustment[1]++;
  9065. if (numSignificantDigits == 0 && digit == 0)
  9066. continue;
  9067. if (++numSignificantDigits > maxSignificantDigits)
  9068. {
  9069. if (digit > 5)
  9070. ++accumulator [decPointIndex];
  9071. else if (digit == 5 && (lastDigit & 1) != 0)
  9072. ++accumulator [decPointIndex];
  9073. if (decPointIndex > 0)
  9074. exponentAdjustment[1]--;
  9075. else
  9076. exponentAdjustment[0]++;
  9077. while (CharacterFunctions::isDigit (*s))
  9078. {
  9079. ++s;
  9080. if (decPointIndex == 0)
  9081. exponentAdjustment[0]++;
  9082. }
  9083. }
  9084. else
  9085. {
  9086. const double maxAccumulatorValue = (double) ((std::numeric_limits<unsigned int>::max() - 9) / 10);
  9087. if (accumulator [decPointIndex] > maxAccumulatorValue)
  9088. {
  9089. result [decPointIndex] = juce_mulexp10 (result [decPointIndex], exponentAccumulator [decPointIndex])
  9090. + accumulator [decPointIndex];
  9091. accumulator [decPointIndex] = 0;
  9092. exponentAccumulator [decPointIndex] = 0;
  9093. }
  9094. accumulator [decPointIndex] = accumulator[decPointIndex] * 10 + digit;
  9095. exponentAccumulator [decPointIndex]++;
  9096. }
  9097. }
  9098. else if (decPointIndex == 0 && *s == '.')
  9099. {
  9100. ++s;
  9101. decPointIndex = 1;
  9102. if (numSignificantDigits > maxSignificantDigits)
  9103. {
  9104. while (CharacterFunctions::isDigit (*s))
  9105. ++s;
  9106. break;
  9107. }
  9108. }
  9109. else
  9110. {
  9111. break;
  9112. }
  9113. }
  9114. result[0] = juce_mulexp10 (result[0], exponentAccumulator[0]) + accumulator[0];
  9115. if (decPointIndex != 0)
  9116. result[1] = juce_mulexp10 (result[1], exponentAccumulator[1]) + accumulator[1];
  9117. if ((*s == 'e' || *s == 'E') && digitsFound)
  9118. {
  9119. bool negativeExponent = false;
  9120. switch (*++s)
  9121. {
  9122. case '-': negativeExponent = true; // fall-through..
  9123. case '+': ++s;
  9124. }
  9125. while (CharacterFunctions::isDigit (*s))
  9126. exponent = (exponent * 10) + (*s++ - '0');
  9127. if (negativeExponent)
  9128. exponent = -exponent;
  9129. }
  9130. double r = juce_mulexp10 (result[0], exponent + exponentAdjustment[0]);
  9131. if (decPointIndex != 0)
  9132. r += juce_mulexp10 (result[1], exponent - exponentAdjustment[1]);
  9133. return isNegative ? -r : r;
  9134. }
  9135. double CharacterFunctions::getDoubleValue (const char* const s) throw()
  9136. {
  9137. return juce_atof <char> (s);
  9138. }
  9139. double CharacterFunctions::getDoubleValue (const juce_wchar* const s) throw()
  9140. {
  9141. return juce_atof <juce_wchar> (s);
  9142. }
  9143. char CharacterFunctions::toUpperCase (const char character) throw()
  9144. {
  9145. return (char) toupper (character);
  9146. }
  9147. juce_wchar CharacterFunctions::toUpperCase (const juce_wchar character) throw()
  9148. {
  9149. return towupper (character);
  9150. }
  9151. void CharacterFunctions::toUpperCase (char* s) throw()
  9152. {
  9153. #if JUCE_WINDOWS
  9154. strupr (s);
  9155. #else
  9156. while (*s != 0)
  9157. {
  9158. *s = toUpperCase (*s);
  9159. ++s;
  9160. }
  9161. #endif
  9162. }
  9163. void CharacterFunctions::toUpperCase (juce_wchar* s) throw()
  9164. {
  9165. #if JUCE_WINDOWS
  9166. _wcsupr (s);
  9167. #else
  9168. while (*s != 0)
  9169. {
  9170. *s = toUpperCase (*s);
  9171. ++s;
  9172. }
  9173. #endif
  9174. }
  9175. bool CharacterFunctions::isUpperCase (const char character) throw()
  9176. {
  9177. return isupper (character) != 0;
  9178. }
  9179. bool CharacterFunctions::isUpperCase (const juce_wchar character) throw()
  9180. {
  9181. #if JUCE_WINDOWS
  9182. return iswupper (character) != 0;
  9183. #else
  9184. return toLowerCase (character) != character;
  9185. #endif
  9186. }
  9187. char CharacterFunctions::toLowerCase (const char character) throw()
  9188. {
  9189. return (char) tolower (character);
  9190. }
  9191. juce_wchar CharacterFunctions::toLowerCase (const juce_wchar character) throw()
  9192. {
  9193. return towlower (character);
  9194. }
  9195. void CharacterFunctions::toLowerCase (char* s) throw()
  9196. {
  9197. #if JUCE_WINDOWS
  9198. strlwr (s);
  9199. #else
  9200. while (*s != 0)
  9201. {
  9202. *s = toLowerCase (*s);
  9203. ++s;
  9204. }
  9205. #endif
  9206. }
  9207. void CharacterFunctions::toLowerCase (juce_wchar* s) throw()
  9208. {
  9209. #if JUCE_WINDOWS
  9210. _wcslwr (s);
  9211. #else
  9212. while (*s != 0)
  9213. {
  9214. *s = toLowerCase (*s);
  9215. ++s;
  9216. }
  9217. #endif
  9218. }
  9219. bool CharacterFunctions::isLowerCase (const char character) throw()
  9220. {
  9221. return islower (character) != 0;
  9222. }
  9223. bool CharacterFunctions::isLowerCase (const juce_wchar character) throw()
  9224. {
  9225. #if JUCE_WINDOWS
  9226. return iswlower (character) != 0;
  9227. #else
  9228. return toUpperCase (character) != character;
  9229. #endif
  9230. }
  9231. bool CharacterFunctions::isWhitespace (const char character) throw()
  9232. {
  9233. return character == ' ' || (character <= 13 && character >= 9);
  9234. }
  9235. bool CharacterFunctions::isWhitespace (const juce_wchar character) throw()
  9236. {
  9237. return iswspace (character) != 0;
  9238. }
  9239. bool CharacterFunctions::isDigit (const char character) throw()
  9240. {
  9241. return (character >= '0' && character <= '9');
  9242. }
  9243. bool CharacterFunctions::isDigit (const juce_wchar character) throw()
  9244. {
  9245. return iswdigit (character) != 0;
  9246. }
  9247. bool CharacterFunctions::isLetter (const char character) throw()
  9248. {
  9249. return (character >= 'a' && character <= 'z')
  9250. || (character >= 'A' && character <= 'Z');
  9251. }
  9252. bool CharacterFunctions::isLetter (const juce_wchar character) throw()
  9253. {
  9254. return iswalpha (character) != 0;
  9255. }
  9256. bool CharacterFunctions::isLetterOrDigit (const char character) throw()
  9257. {
  9258. return (character >= 'a' && character <= 'z')
  9259. || (character >= 'A' && character <= 'Z')
  9260. || (character >= '0' && character <= '9');
  9261. }
  9262. bool CharacterFunctions::isLetterOrDigit (const juce_wchar character) throw()
  9263. {
  9264. return iswalnum (character) != 0;
  9265. }
  9266. int CharacterFunctions::getHexDigitValue (const juce_wchar digit) throw()
  9267. {
  9268. unsigned int d = digit - '0';
  9269. if (d < (unsigned int) 10)
  9270. return (int) d;
  9271. d += (unsigned int) ('0' - 'a');
  9272. if (d < (unsigned int) 6)
  9273. return (int) d + 10;
  9274. d += (unsigned int) ('a' - 'A');
  9275. if (d < (unsigned int) 6)
  9276. return (int) d + 10;
  9277. return -1;
  9278. }
  9279. #if JUCE_MSVC
  9280. #pragma warning (pop)
  9281. #endif
  9282. END_JUCE_NAMESPACE
  9283. /*** End of inlined file: juce_CharacterFunctions.cpp ***/
  9284. /*** Start of inlined file: juce_LocalisedStrings.cpp ***/
  9285. BEGIN_JUCE_NAMESPACE
  9286. LocalisedStrings::LocalisedStrings (const String& fileContents)
  9287. {
  9288. loadFromText (fileContents);
  9289. }
  9290. LocalisedStrings::LocalisedStrings (const File& fileToLoad)
  9291. {
  9292. loadFromText (fileToLoad.loadFileAsString());
  9293. }
  9294. LocalisedStrings::~LocalisedStrings()
  9295. {
  9296. }
  9297. const String LocalisedStrings::translate (const String& text) const
  9298. {
  9299. return translations.getValue (text, text);
  9300. }
  9301. static int findCloseQuote (const String& text, int startPos)
  9302. {
  9303. juce_wchar lastChar = 0;
  9304. for (;;)
  9305. {
  9306. const juce_wchar c = text [startPos];
  9307. if (c == 0 || (c == '"' && lastChar != '\\'))
  9308. break;
  9309. lastChar = c;
  9310. ++startPos;
  9311. }
  9312. return startPos;
  9313. }
  9314. static const String unescapeString (const String& s)
  9315. {
  9316. return s.replace ("\\\"", "\"")
  9317. .replace ("\\\'", "\'")
  9318. .replace ("\\t", "\t")
  9319. .replace ("\\r", "\r")
  9320. .replace ("\\n", "\n");
  9321. }
  9322. void LocalisedStrings::loadFromText (const String& fileContents)
  9323. {
  9324. StringArray lines;
  9325. lines.addLines (fileContents);
  9326. for (int i = 0; i < lines.size(); ++i)
  9327. {
  9328. String line (lines[i].trim());
  9329. if (line.startsWithChar ('"'))
  9330. {
  9331. int closeQuote = findCloseQuote (line, 1);
  9332. const String originalText (unescapeString (line.substring (1, closeQuote)));
  9333. if (originalText.isNotEmpty())
  9334. {
  9335. const int openingQuote = findCloseQuote (line, closeQuote + 1);
  9336. closeQuote = findCloseQuote (line, openingQuote + 1);
  9337. const String newText (unescapeString (line.substring (openingQuote + 1, closeQuote)));
  9338. if (newText.isNotEmpty())
  9339. translations.set (originalText, newText);
  9340. }
  9341. }
  9342. else if (line.startsWithIgnoreCase ("language:"))
  9343. {
  9344. languageName = line.substring (9).trim();
  9345. }
  9346. else if (line.startsWithIgnoreCase ("countries:"))
  9347. {
  9348. countryCodes.addTokens (line.substring (10).trim(), true);
  9349. countryCodes.trim();
  9350. countryCodes.removeEmptyStrings();
  9351. }
  9352. }
  9353. }
  9354. void LocalisedStrings::setIgnoresCase (const bool shouldIgnoreCase)
  9355. {
  9356. translations.setIgnoresCase (shouldIgnoreCase);
  9357. }
  9358. static CriticalSection currentMappingsLock;
  9359. static LocalisedStrings* currentMappings = 0;
  9360. void LocalisedStrings::setCurrentMappings (LocalisedStrings* newTranslations)
  9361. {
  9362. const ScopedLock sl (currentMappingsLock);
  9363. delete currentMappings;
  9364. currentMappings = newTranslations;
  9365. }
  9366. LocalisedStrings* LocalisedStrings::getCurrentMappings()
  9367. {
  9368. return currentMappings;
  9369. }
  9370. const String LocalisedStrings::translateWithCurrentMappings (const String& text)
  9371. {
  9372. const ScopedLock sl (currentMappingsLock);
  9373. if (currentMappings != 0)
  9374. return currentMappings->translate (text);
  9375. return text;
  9376. }
  9377. const String LocalisedStrings::translateWithCurrentMappings (const char* text)
  9378. {
  9379. return translateWithCurrentMappings (String (text));
  9380. }
  9381. END_JUCE_NAMESPACE
  9382. /*** End of inlined file: juce_LocalisedStrings.cpp ***/
  9383. /*** Start of inlined file: juce_String.cpp ***/
  9384. #if JUCE_MSVC
  9385. #pragma warning (push)
  9386. #pragma warning (disable: 4514)
  9387. #endif
  9388. #include <locale>
  9389. BEGIN_JUCE_NAMESPACE
  9390. #if JUCE_MSVC
  9391. #pragma warning (pop)
  9392. #endif
  9393. #if defined (JUCE_STRINGS_ARE_UNICODE) && ! JUCE_STRINGS_ARE_UNICODE
  9394. #error "JUCE_STRINGS_ARE_UNICODE is deprecated! All strings are now unicode by default."
  9395. #endif
  9396. class StringHolder
  9397. {
  9398. public:
  9399. StringHolder()
  9400. : refCount (0x3fffffff), allocatedNumChars (0)
  9401. {
  9402. text[0] = 0;
  9403. }
  9404. static juce_wchar* createUninitialised (const size_t numChars)
  9405. {
  9406. StringHolder* const s = reinterpret_cast <StringHolder*> (new char [sizeof (StringHolder) + numChars * sizeof (juce_wchar)]);
  9407. s->refCount.value = 0;
  9408. s->allocatedNumChars = numChars;
  9409. return &(s->text[0]);
  9410. }
  9411. static juce_wchar* createCopy (const juce_wchar* const src, const size_t numChars)
  9412. {
  9413. juce_wchar* const dest = createUninitialised (numChars);
  9414. copyChars (dest, src, numChars);
  9415. return dest;
  9416. }
  9417. static juce_wchar* createCopy (const char* const src, const size_t numChars)
  9418. {
  9419. juce_wchar* const dest = createUninitialised (numChars);
  9420. CharacterFunctions::copy (dest, src, (int) numChars);
  9421. dest [numChars] = 0;
  9422. return dest;
  9423. }
  9424. static inline juce_wchar* getEmpty() throw()
  9425. {
  9426. return &(empty.text[0]);
  9427. }
  9428. static void retain (juce_wchar* const text) throw()
  9429. {
  9430. ++(bufferFromText (text)->refCount);
  9431. }
  9432. static inline void release (StringHolder* const b) throw()
  9433. {
  9434. if (--(b->refCount) == -1 && b != &empty)
  9435. delete[] reinterpret_cast <char*> (b);
  9436. }
  9437. static void release (juce_wchar* const text) throw()
  9438. {
  9439. release (bufferFromText (text));
  9440. }
  9441. static juce_wchar* makeUnique (juce_wchar* const text)
  9442. {
  9443. StringHolder* const b = bufferFromText (text);
  9444. if (b->refCount.get() <= 0)
  9445. return text;
  9446. juce_wchar* const newText = createCopy (text, b->allocatedNumChars);
  9447. release (b);
  9448. return newText;
  9449. }
  9450. static juce_wchar* makeUniqueWithSize (juce_wchar* const text, size_t numChars)
  9451. {
  9452. StringHolder* const b = bufferFromText (text);
  9453. if (b->refCount.get() <= 0 && b->allocatedNumChars >= numChars)
  9454. return text;
  9455. juce_wchar* const newText = createUninitialised (jmax (b->allocatedNumChars, numChars));
  9456. copyChars (newText, text, b->allocatedNumChars);
  9457. release (b);
  9458. return newText;
  9459. }
  9460. static size_t getAllocatedNumChars (juce_wchar* const text) throw()
  9461. {
  9462. return bufferFromText (text)->allocatedNumChars;
  9463. }
  9464. static void copyChars (juce_wchar* const dest, const juce_wchar* const src, const size_t numChars) throw()
  9465. {
  9466. jassert (src != 0 && dest != 0);
  9467. memcpy (dest, src, numChars * sizeof (juce_wchar));
  9468. dest [numChars] = 0;
  9469. }
  9470. Atomic<int> refCount;
  9471. size_t allocatedNumChars;
  9472. juce_wchar text[1];
  9473. static StringHolder empty;
  9474. private:
  9475. static inline StringHolder* bufferFromText (void* const text) throw()
  9476. {
  9477. // (Can't use offsetof() here because of warnings about this not being a POD)
  9478. return reinterpret_cast <StringHolder*> (static_cast <char*> (text)
  9479. - (reinterpret_cast <size_t> (reinterpret_cast <StringHolder*> (1)->text) - 1));
  9480. }
  9481. };
  9482. StringHolder StringHolder::empty;
  9483. const String String::empty;
  9484. void String::createInternal (const juce_wchar* const t, const size_t numChars)
  9485. {
  9486. jassert (t[numChars] == 0); // must have a null terminator
  9487. text = StringHolder::createCopy (t, numChars);
  9488. }
  9489. void String::appendInternal (const juce_wchar* const newText, const int numExtraChars)
  9490. {
  9491. if (numExtraChars > 0)
  9492. {
  9493. const int oldLen = length();
  9494. const int newTotalLen = oldLen + numExtraChars;
  9495. text = StringHolder::makeUniqueWithSize (text, newTotalLen);
  9496. StringHolder::copyChars (text + oldLen, newText, numExtraChars);
  9497. }
  9498. }
  9499. void String::preallocateStorage (const size_t numChars)
  9500. {
  9501. text = StringHolder::makeUniqueWithSize (text, numChars);
  9502. }
  9503. String::String() throw()
  9504. : text (StringHolder::getEmpty())
  9505. {
  9506. }
  9507. String::~String() throw()
  9508. {
  9509. StringHolder::release (text);
  9510. }
  9511. String::String (const String& other) throw()
  9512. : text (other.text)
  9513. {
  9514. StringHolder::retain (text);
  9515. }
  9516. void String::swapWith (String& other) throw()
  9517. {
  9518. swapVariables (text, other.text);
  9519. }
  9520. String& String::operator= (const String& other) throw()
  9521. {
  9522. juce_wchar* const newText = other.text;
  9523. StringHolder::retain (newText);
  9524. StringHolder::release (reinterpret_cast <Atomic<juce_wchar*>*> (&text)->exchange (newText));
  9525. return *this;
  9526. }
  9527. String::String (const size_t numChars, const int /*dummyVariable*/)
  9528. : text (StringHolder::createUninitialised (numChars))
  9529. {
  9530. }
  9531. String::String (const String& stringToCopy, const size_t charsToAllocate)
  9532. {
  9533. const size_t otherSize = StringHolder::getAllocatedNumChars (stringToCopy.text);
  9534. text = StringHolder::createUninitialised (jmax (charsToAllocate, otherSize));
  9535. StringHolder::copyChars (text, stringToCopy.text, otherSize);
  9536. }
  9537. String::String (const char* const t)
  9538. {
  9539. if (t != 0 && *t != 0)
  9540. text = StringHolder::createCopy (t, CharacterFunctions::length (t));
  9541. else
  9542. text = StringHolder::getEmpty();
  9543. }
  9544. String::String (const juce_wchar* const t)
  9545. {
  9546. if (t != 0 && *t != 0)
  9547. text = StringHolder::createCopy (t, CharacterFunctions::length (t));
  9548. else
  9549. text = StringHolder::getEmpty();
  9550. }
  9551. String::String (const char* const t, const size_t maxChars)
  9552. {
  9553. int i;
  9554. for (i = 0; (size_t) i < maxChars; ++i)
  9555. if (t[i] == 0)
  9556. break;
  9557. if (i > 0)
  9558. text = StringHolder::createCopy (t, i);
  9559. else
  9560. text = StringHolder::getEmpty();
  9561. }
  9562. String::String (const juce_wchar* const t, const size_t maxChars)
  9563. {
  9564. int i;
  9565. for (i = 0; (size_t) i < maxChars; ++i)
  9566. if (t[i] == 0)
  9567. break;
  9568. if (i > 0)
  9569. text = StringHolder::createCopy (t, i);
  9570. else
  9571. text = StringHolder::getEmpty();
  9572. }
  9573. const String String::charToString (const juce_wchar character)
  9574. {
  9575. String result ((size_t) 1, (int) 0);
  9576. result.text[0] = character;
  9577. result.text[1] = 0;
  9578. return result;
  9579. }
  9580. namespace NumberToStringConverters
  9581. {
  9582. // pass in a pointer to the END of a buffer..
  9583. static juce_wchar* int64ToString (juce_wchar* t, const int64 n) throw()
  9584. {
  9585. *--t = 0;
  9586. int64 v = (n >= 0) ? n : -n;
  9587. do
  9588. {
  9589. *--t = (juce_wchar) ('0' + (int) (v % 10));
  9590. v /= 10;
  9591. } while (v > 0);
  9592. if (n < 0)
  9593. *--t = '-';
  9594. return t;
  9595. }
  9596. static juce_wchar* uint64ToString (juce_wchar* t, int64 v) throw()
  9597. {
  9598. *--t = 0;
  9599. do
  9600. {
  9601. *--t = (juce_wchar) ('0' + (int) (v % 10));
  9602. v /= 10;
  9603. } while (v > 0);
  9604. return t;
  9605. }
  9606. static juce_wchar* intToString (juce_wchar* t, const int n) throw()
  9607. {
  9608. if (n == (int) 0x80000000) // (would cause an overflow)
  9609. return int64ToString (t, n);
  9610. *--t = 0;
  9611. int v = abs (n);
  9612. do
  9613. {
  9614. *--t = (juce_wchar) ('0' + (v % 10));
  9615. v /= 10;
  9616. } while (v > 0);
  9617. if (n < 0)
  9618. *--t = '-';
  9619. return t;
  9620. }
  9621. static juce_wchar* uintToString (juce_wchar* t, unsigned int v) throw()
  9622. {
  9623. *--t = 0;
  9624. do
  9625. {
  9626. *--t = (juce_wchar) ('0' + (v % 10));
  9627. v /= 10;
  9628. } while (v > 0);
  9629. return t;
  9630. }
  9631. static juce_wchar getDecimalPoint()
  9632. {
  9633. #if JUCE_MSVC && _MSC_VER < 1400
  9634. static juce_wchar dp = std::_USE (std::locale(), std::numpunct <wchar_t>).decimal_point();
  9635. #else
  9636. static juce_wchar dp = std::use_facet <std::numpunct <wchar_t> > (std::locale()).decimal_point();
  9637. #endif
  9638. return dp;
  9639. }
  9640. static juce_wchar* doubleToString (juce_wchar* buffer, int numChars, double n, int numDecPlaces, size_t& len) throw()
  9641. {
  9642. if (numDecPlaces > 0 && n > -1.0e20 && n < 1.0e20)
  9643. {
  9644. juce_wchar* const end = buffer + numChars;
  9645. juce_wchar* t = end;
  9646. int64 v = (int64) (pow (10.0, numDecPlaces) * std::abs (n) + 0.5);
  9647. *--t = (juce_wchar) 0;
  9648. while (numDecPlaces >= 0 || v > 0)
  9649. {
  9650. if (numDecPlaces == 0)
  9651. *--t = getDecimalPoint();
  9652. *--t = (juce_wchar) ('0' + (v % 10));
  9653. v /= 10;
  9654. --numDecPlaces;
  9655. }
  9656. if (n < 0)
  9657. *--t = '-';
  9658. len = end - t - 1;
  9659. return t;
  9660. }
  9661. else
  9662. {
  9663. #if JUCE_WINDOWS
  9664. #if JUCE_MSVC && _MSC_VER <= 1400
  9665. len = _snwprintf (buffer, numChars, L"%.9g", n);
  9666. #else
  9667. len = _snwprintf_s (buffer, numChars, _TRUNCATE, L"%.9g", n);
  9668. #endif
  9669. #else
  9670. len = swprintf (buffer, numChars, L"%.9g", n);
  9671. #endif
  9672. return buffer;
  9673. }
  9674. }
  9675. }
  9676. String::String (const int number)
  9677. {
  9678. juce_wchar buffer [16];
  9679. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9680. juce_wchar* const start = NumberToStringConverters::intToString (end, number);
  9681. createInternal (start, end - start - 1);
  9682. }
  9683. String::String (const unsigned int number)
  9684. {
  9685. juce_wchar buffer [16];
  9686. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9687. juce_wchar* const start = NumberToStringConverters::uintToString (end, number);
  9688. createInternal (start, end - start - 1);
  9689. }
  9690. String::String (const short number)
  9691. {
  9692. juce_wchar buffer [16];
  9693. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9694. juce_wchar* const start = NumberToStringConverters::intToString (end, (int) number);
  9695. createInternal (start, end - start - 1);
  9696. }
  9697. String::String (const unsigned short number)
  9698. {
  9699. juce_wchar buffer [16];
  9700. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9701. juce_wchar* const start = NumberToStringConverters::uintToString (end, (unsigned int) number);
  9702. createInternal (start, end - start - 1);
  9703. }
  9704. String::String (const int64 number)
  9705. {
  9706. juce_wchar buffer [32];
  9707. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9708. juce_wchar* const start = NumberToStringConverters::int64ToString (end, number);
  9709. createInternal (start, end - start - 1);
  9710. }
  9711. String::String (const uint64 number)
  9712. {
  9713. juce_wchar buffer [32];
  9714. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9715. juce_wchar* const start = NumberToStringConverters::uint64ToString (end, number);
  9716. createInternal (start, end - start - 1);
  9717. }
  9718. String::String (const float number, const int numberOfDecimalPlaces)
  9719. {
  9720. juce_wchar buffer [48];
  9721. size_t len;
  9722. juce_wchar* start = NumberToStringConverters::doubleToString (buffer, numElementsInArray (buffer), (double) number, numberOfDecimalPlaces, len);
  9723. createInternal (start, len);
  9724. }
  9725. String::String (const double number, const int numberOfDecimalPlaces)
  9726. {
  9727. juce_wchar buffer [48];
  9728. size_t len;
  9729. juce_wchar* start = NumberToStringConverters::doubleToString (buffer, numElementsInArray (buffer), number, numberOfDecimalPlaces, len);
  9730. createInternal (start, len);
  9731. }
  9732. int String::length() const throw()
  9733. {
  9734. return CharacterFunctions::length (text);
  9735. }
  9736. int String::hashCode() const throw()
  9737. {
  9738. const juce_wchar* t = text;
  9739. int result = 0;
  9740. while (*t != (juce_wchar) 0)
  9741. result = 31 * result + *t++;
  9742. return result;
  9743. }
  9744. int64 String::hashCode64() const throw()
  9745. {
  9746. const juce_wchar* t = text;
  9747. int64 result = 0;
  9748. while (*t != (juce_wchar) 0)
  9749. result = 101 * result + *t++;
  9750. return result;
  9751. }
  9752. 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::initialise() {}
  14207. void UnitTest::shutdown() {}
  14208. void UnitTest::performTest (UnitTestRunner* const runner_)
  14209. {
  14210. jassert (runner_ != 0);
  14211. runner = runner_;
  14212. initialise();
  14213. runTest();
  14214. shutdown();
  14215. }
  14216. void UnitTest::logMessage (const String& message)
  14217. {
  14218. runner->logMessage (message);
  14219. }
  14220. void UnitTest::beginTest (const String& testName)
  14221. {
  14222. runner->beginNewTest (this, testName);
  14223. }
  14224. void UnitTest::expect (const bool result, const String& failureMessage)
  14225. {
  14226. if (result)
  14227. runner->addPass();
  14228. else
  14229. runner->addFail (failureMessage);
  14230. }
  14231. UnitTestRunner::UnitTestRunner()
  14232. : currentTest (0), assertOnFailure (false)
  14233. {
  14234. }
  14235. UnitTestRunner::~UnitTestRunner()
  14236. {
  14237. }
  14238. int UnitTestRunner::getNumResults() const throw()
  14239. {
  14240. return results.size();
  14241. }
  14242. const UnitTestRunner::TestResult* UnitTestRunner::getResult (int index) const throw()
  14243. {
  14244. return results [index];
  14245. }
  14246. void UnitTestRunner::resultsUpdated()
  14247. {
  14248. }
  14249. void UnitTestRunner::runTests (const Array<UnitTest*>& tests, const bool assertOnFailure_)
  14250. {
  14251. results.clear();
  14252. assertOnFailure = assertOnFailure_;
  14253. resultsUpdated();
  14254. for (int i = 0; i < tests.size(); ++i)
  14255. {
  14256. try
  14257. {
  14258. tests.getUnchecked(i)->performTest (this);
  14259. }
  14260. catch (...)
  14261. {
  14262. addFail ("An unhandled exception was thrown!");
  14263. }
  14264. }
  14265. endTest();
  14266. }
  14267. void UnitTestRunner::runAllTests (const bool assertOnFailure_)
  14268. {
  14269. runTests (UnitTest::getAllTests(), assertOnFailure_);
  14270. }
  14271. void UnitTestRunner::logMessage (const String& message)
  14272. {
  14273. Logger::writeToLog (message);
  14274. }
  14275. void UnitTestRunner::beginNewTest (UnitTest* const test, const String& subCategory)
  14276. {
  14277. endTest();
  14278. currentTest = test;
  14279. TestResult* const r = new TestResult();
  14280. r->unitTestName = test->getName();
  14281. r->subcategoryName = subCategory;
  14282. r->passes = 0;
  14283. r->failures = 0;
  14284. results.add (r);
  14285. logMessage ("-----------------------------------------------------------------");
  14286. logMessage ("Starting test: " + r->unitTestName + " / " + subCategory + "...");
  14287. resultsUpdated();
  14288. }
  14289. void UnitTestRunner::endTest()
  14290. {
  14291. if (results.size() > 0)
  14292. {
  14293. TestResult* const r = results.getLast();
  14294. if (r->failures > 0)
  14295. {
  14296. String m ("FAILED!!");
  14297. m << r->failures << (r->failures == 1 ? "test" : "tests")
  14298. << " failed, out of a total of " << (r->passes + r->failures);
  14299. logMessage (String::empty);
  14300. logMessage (m);
  14301. logMessage (String::empty);
  14302. }
  14303. else
  14304. {
  14305. logMessage ("All tests completed successfully");
  14306. }
  14307. }
  14308. }
  14309. void UnitTestRunner::addPass()
  14310. {
  14311. {
  14312. const ScopedLock sl (results.getLock());
  14313. TestResult* const r = results.getLast();
  14314. jassert (r != 0); // You need to call UnitTest::beginTest() before performing any tests!
  14315. r->passes++;
  14316. String message ("Test ");
  14317. message << (r->failures + r->passes) << " passed";
  14318. logMessage (message);
  14319. }
  14320. resultsUpdated();
  14321. }
  14322. void UnitTestRunner::addFail (const String& failureMessage)
  14323. {
  14324. {
  14325. const ScopedLock sl (results.getLock());
  14326. TestResult* const r = results.getLast();
  14327. jassert (r != 0); // You need to call UnitTest::beginTest() before performing any tests!
  14328. r->failures++;
  14329. String message ("!!! Test ");
  14330. message << (r->failures + r->passes) << " failed";
  14331. if (failureMessage.isNotEmpty())
  14332. message << ": " << failureMessage;
  14333. r->messages.add (message);
  14334. logMessage (message);
  14335. }
  14336. resultsUpdated();
  14337. if (assertOnFailure) { jassertfalse }
  14338. }
  14339. END_JUCE_NAMESPACE
  14340. /*** End of inlined file: juce_UnitTest.cpp ***/
  14341. #endif
  14342. #if JUCE_BUILD_MISC
  14343. /*** Start of inlined file: juce_ValueTree.cpp ***/
  14344. BEGIN_JUCE_NAMESPACE
  14345. class ValueTree::SetPropertyAction : public UndoableAction
  14346. {
  14347. public:
  14348. SetPropertyAction (const SharedObjectPtr& target_, const Identifier& name_,
  14349. const var& newValue_, const var& oldValue_,
  14350. const bool isAddingNewProperty_, const bool isDeletingProperty_)
  14351. : target (target_), name (name_), newValue (newValue_), oldValue (oldValue_),
  14352. isAddingNewProperty (isAddingNewProperty_), isDeletingProperty (isDeletingProperty_)
  14353. {
  14354. }
  14355. ~SetPropertyAction() {}
  14356. bool perform()
  14357. {
  14358. jassert (! (isAddingNewProperty && target->hasProperty (name)));
  14359. if (isDeletingProperty)
  14360. target->removeProperty (name, 0);
  14361. else
  14362. target->setProperty (name, newValue, 0);
  14363. return true;
  14364. }
  14365. bool undo()
  14366. {
  14367. if (isAddingNewProperty)
  14368. target->removeProperty (name, 0);
  14369. else
  14370. target->setProperty (name, oldValue, 0);
  14371. return true;
  14372. }
  14373. int getSizeInUnits()
  14374. {
  14375. return (int) sizeof (*this); //xxx should be more accurate
  14376. }
  14377. UndoableAction* createCoalescedAction (UndoableAction* nextAction)
  14378. {
  14379. if (! (isAddingNewProperty || isDeletingProperty))
  14380. {
  14381. SetPropertyAction* next = dynamic_cast <SetPropertyAction*> (nextAction);
  14382. if (next != 0 && next->target == target && next->name == name
  14383. && ! (next->isAddingNewProperty || next->isDeletingProperty))
  14384. {
  14385. return new SetPropertyAction (target, name, next->newValue, oldValue, false, false);
  14386. }
  14387. }
  14388. return 0;
  14389. }
  14390. private:
  14391. const SharedObjectPtr target;
  14392. const Identifier name;
  14393. const var newValue;
  14394. var oldValue;
  14395. const bool isAddingNewProperty : 1, isDeletingProperty : 1;
  14396. SetPropertyAction (const SetPropertyAction&);
  14397. SetPropertyAction& operator= (const SetPropertyAction&);
  14398. };
  14399. class ValueTree::AddOrRemoveChildAction : public UndoableAction
  14400. {
  14401. public:
  14402. AddOrRemoveChildAction (const SharedObjectPtr& target_, const int childIndex_,
  14403. const SharedObjectPtr& newChild_)
  14404. : target (target_),
  14405. child (newChild_ != 0 ? newChild_ : target_->children [childIndex_]),
  14406. childIndex (childIndex_),
  14407. isDeleting (newChild_ == 0)
  14408. {
  14409. jassert (child != 0);
  14410. }
  14411. ~AddOrRemoveChildAction() {}
  14412. bool perform()
  14413. {
  14414. if (isDeleting)
  14415. target->removeChild (childIndex, 0);
  14416. else
  14417. target->addChild (child, childIndex, 0);
  14418. return true;
  14419. }
  14420. bool undo()
  14421. {
  14422. if (isDeleting)
  14423. {
  14424. target->addChild (child, childIndex, 0);
  14425. }
  14426. else
  14427. {
  14428. // If you hit this, it seems that your object's state is getting confused - probably
  14429. // because you've interleaved some undoable and non-undoable operations?
  14430. jassert (childIndex < target->children.size());
  14431. target->removeChild (childIndex, 0);
  14432. }
  14433. return true;
  14434. }
  14435. int getSizeInUnits()
  14436. {
  14437. return (int) sizeof (*this); //xxx should be more accurate
  14438. }
  14439. private:
  14440. const SharedObjectPtr target, child;
  14441. const int childIndex;
  14442. const bool isDeleting;
  14443. AddOrRemoveChildAction (const AddOrRemoveChildAction&);
  14444. AddOrRemoveChildAction& operator= (const AddOrRemoveChildAction&);
  14445. };
  14446. class ValueTree::MoveChildAction : public UndoableAction
  14447. {
  14448. public:
  14449. MoveChildAction (const SharedObjectPtr& parent_,
  14450. const int startIndex_, const int endIndex_)
  14451. : parent (parent_),
  14452. startIndex (startIndex_),
  14453. endIndex (endIndex_)
  14454. {
  14455. }
  14456. ~MoveChildAction() {}
  14457. bool perform()
  14458. {
  14459. parent->moveChild (startIndex, endIndex, 0);
  14460. return true;
  14461. }
  14462. bool undo()
  14463. {
  14464. parent->moveChild (endIndex, startIndex, 0);
  14465. return true;
  14466. }
  14467. int getSizeInUnits()
  14468. {
  14469. return (int) sizeof (*this); //xxx should be more accurate
  14470. }
  14471. UndoableAction* createCoalescedAction (UndoableAction* nextAction)
  14472. {
  14473. MoveChildAction* next = dynamic_cast <MoveChildAction*> (nextAction);
  14474. if (next != 0 && next->parent == parent && next->startIndex == endIndex)
  14475. return new MoveChildAction (parent, startIndex, next->endIndex);
  14476. return 0;
  14477. }
  14478. private:
  14479. const SharedObjectPtr parent;
  14480. const int startIndex, endIndex;
  14481. MoveChildAction (const MoveChildAction&);
  14482. MoveChildAction& operator= (const MoveChildAction&);
  14483. };
  14484. ValueTree::SharedObject::SharedObject (const Identifier& type_)
  14485. : type (type_), parent (0)
  14486. {
  14487. }
  14488. ValueTree::SharedObject::SharedObject (const SharedObject& other)
  14489. : type (other.type), properties (other.properties), parent (0)
  14490. {
  14491. for (int i = 0; i < other.children.size(); ++i)
  14492. {
  14493. SharedObject* const child = new SharedObject (*other.children.getUnchecked(i));
  14494. child->parent = this;
  14495. children.add (child);
  14496. }
  14497. }
  14498. ValueTree::SharedObject::~SharedObject()
  14499. {
  14500. jassert (parent == 0); // this should never happen unless something isn't obeying the ref-counting!
  14501. for (int i = children.size(); --i >= 0;)
  14502. {
  14503. const SharedObjectPtr c (children.getUnchecked(i));
  14504. c->parent = 0;
  14505. children.remove (i);
  14506. c->sendParentChangeMessage();
  14507. }
  14508. }
  14509. void ValueTree::SharedObject::sendPropertyChangeMessage (ValueTree& tree, const Identifier& property)
  14510. {
  14511. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  14512. {
  14513. ValueTree* const v = valueTreesWithListeners[i];
  14514. if (v != 0)
  14515. v->listeners.call (&ValueTree::Listener::valueTreePropertyChanged, tree, property);
  14516. }
  14517. }
  14518. void ValueTree::SharedObject::sendPropertyChangeMessage (const Identifier& property)
  14519. {
  14520. ValueTree tree (this);
  14521. ValueTree::SharedObject* t = this;
  14522. while (t != 0)
  14523. {
  14524. t->sendPropertyChangeMessage (tree, property);
  14525. t = t->parent;
  14526. }
  14527. }
  14528. void ValueTree::SharedObject::sendChildChangeMessage (ValueTree& tree)
  14529. {
  14530. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  14531. {
  14532. ValueTree* const v = valueTreesWithListeners[i];
  14533. if (v != 0)
  14534. v->listeners.call (&ValueTree::Listener::valueTreeChildrenChanged, tree);
  14535. }
  14536. }
  14537. void ValueTree::SharedObject::sendChildChangeMessage()
  14538. {
  14539. ValueTree tree (this);
  14540. ValueTree::SharedObject* t = this;
  14541. while (t != 0)
  14542. {
  14543. t->sendChildChangeMessage (tree);
  14544. t = t->parent;
  14545. }
  14546. }
  14547. void ValueTree::SharedObject::sendParentChangeMessage()
  14548. {
  14549. ValueTree tree (this);
  14550. int i;
  14551. for (i = children.size(); --i >= 0;)
  14552. {
  14553. SharedObject* const t = children[i];
  14554. if (t != 0)
  14555. t->sendParentChangeMessage();
  14556. }
  14557. for (i = valueTreesWithListeners.size(); --i >= 0;)
  14558. {
  14559. ValueTree* const v = valueTreesWithListeners[i];
  14560. if (v != 0)
  14561. v->listeners.call (&ValueTree::Listener::valueTreeParentChanged, tree);
  14562. }
  14563. }
  14564. const var& ValueTree::SharedObject::getProperty (const Identifier& name) const
  14565. {
  14566. return properties [name];
  14567. }
  14568. const var ValueTree::SharedObject::getProperty (const Identifier& name, const var& defaultReturnValue) const
  14569. {
  14570. return properties.getWithDefault (name, defaultReturnValue);
  14571. }
  14572. void ValueTree::SharedObject::setProperty (const Identifier& name, const var& newValue, UndoManager* const undoManager)
  14573. {
  14574. if (undoManager == 0)
  14575. {
  14576. if (properties.set (name, newValue))
  14577. sendPropertyChangeMessage (name);
  14578. }
  14579. else
  14580. {
  14581. var* const existingValue = properties.getItem (name);
  14582. if (existingValue != 0)
  14583. {
  14584. if (*existingValue != newValue)
  14585. undoManager->perform (new SetPropertyAction (this, name, newValue, properties [name], false, false));
  14586. }
  14587. else
  14588. {
  14589. undoManager->perform (new SetPropertyAction (this, name, newValue, var::null, true, false));
  14590. }
  14591. }
  14592. }
  14593. bool ValueTree::SharedObject::hasProperty (const Identifier& name) const
  14594. {
  14595. return properties.contains (name);
  14596. }
  14597. void ValueTree::SharedObject::removeProperty (const Identifier& name, UndoManager* const undoManager)
  14598. {
  14599. if (undoManager == 0)
  14600. {
  14601. if (properties.remove (name))
  14602. sendPropertyChangeMessage (name);
  14603. }
  14604. else
  14605. {
  14606. if (properties.contains (name))
  14607. undoManager->perform (new SetPropertyAction (this, name, var::null, properties [name], false, true));
  14608. }
  14609. }
  14610. void ValueTree::SharedObject::removeAllProperties (UndoManager* const undoManager)
  14611. {
  14612. if (undoManager == 0)
  14613. {
  14614. while (properties.size() > 0)
  14615. {
  14616. const Identifier name (properties.getName (properties.size() - 1));
  14617. properties.remove (name);
  14618. sendPropertyChangeMessage (name);
  14619. }
  14620. }
  14621. else
  14622. {
  14623. for (int i = properties.size(); --i >= 0;)
  14624. undoManager->perform (new SetPropertyAction (this, properties.getName(i), var::null, properties.getValueAt(i), false, true));
  14625. }
  14626. }
  14627. ValueTree ValueTree::SharedObject::getChildWithName (const Identifier& typeToMatch) const
  14628. {
  14629. for (int i = 0; i < children.size(); ++i)
  14630. if (children.getUnchecked(i)->type == typeToMatch)
  14631. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  14632. return ValueTree::invalid;
  14633. }
  14634. ValueTree ValueTree::SharedObject::getOrCreateChildWithName (const Identifier& typeToMatch, UndoManager* undoManager)
  14635. {
  14636. for (int i = 0; i < children.size(); ++i)
  14637. if (children.getUnchecked(i)->type == typeToMatch)
  14638. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  14639. SharedObject* const newObject = new SharedObject (typeToMatch);
  14640. addChild (newObject, -1, undoManager);
  14641. return ValueTree (newObject);
  14642. }
  14643. ValueTree ValueTree::SharedObject::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  14644. {
  14645. for (int i = 0; i < children.size(); ++i)
  14646. if (children.getUnchecked(i)->getProperty (propertyName) == propertyValue)
  14647. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  14648. return ValueTree::invalid;
  14649. }
  14650. bool ValueTree::SharedObject::isAChildOf (const SharedObject* const possibleParent) const
  14651. {
  14652. const SharedObject* p = parent;
  14653. while (p != 0)
  14654. {
  14655. if (p == possibleParent)
  14656. return true;
  14657. p = p->parent;
  14658. }
  14659. return false;
  14660. }
  14661. int ValueTree::SharedObject::indexOf (const ValueTree& child) const
  14662. {
  14663. return children.indexOf (child.object);
  14664. }
  14665. void ValueTree::SharedObject::addChild (SharedObject* child, int index, UndoManager* const undoManager)
  14666. {
  14667. if (child != 0 && child->parent != this)
  14668. {
  14669. if (child != this && ! isAChildOf (child))
  14670. {
  14671. // You should always make sure that a child is removed from its previous parent before
  14672. // adding it somewhere else - otherwise, it's ambiguous as to whether a different
  14673. // undomanager should be used when removing it from its current parent..
  14674. jassert (child->parent == 0);
  14675. if (child->parent != 0)
  14676. {
  14677. jassert (child->parent->children.indexOf (child) >= 0);
  14678. child->parent->removeChild (child->parent->children.indexOf (child), undoManager);
  14679. }
  14680. if (undoManager == 0)
  14681. {
  14682. children.insert (index, child);
  14683. child->parent = this;
  14684. sendChildChangeMessage();
  14685. child->sendParentChangeMessage();
  14686. }
  14687. else
  14688. {
  14689. if (index < 0)
  14690. index = children.size();
  14691. undoManager->perform (new AddOrRemoveChildAction (this, index, child));
  14692. }
  14693. }
  14694. else
  14695. {
  14696. // You're attempting to create a recursive loop! A node
  14697. // can't be a child of one of its own children!
  14698. jassertfalse;
  14699. }
  14700. }
  14701. }
  14702. void ValueTree::SharedObject::removeChild (const int childIndex, UndoManager* const undoManager)
  14703. {
  14704. const SharedObjectPtr child (children [childIndex]);
  14705. if (child != 0)
  14706. {
  14707. if (undoManager == 0)
  14708. {
  14709. children.remove (childIndex);
  14710. child->parent = 0;
  14711. sendChildChangeMessage();
  14712. child->sendParentChangeMessage();
  14713. }
  14714. else
  14715. {
  14716. undoManager->perform (new AddOrRemoveChildAction (this, childIndex, 0));
  14717. }
  14718. }
  14719. }
  14720. void ValueTree::SharedObject::removeAllChildren (UndoManager* const undoManager)
  14721. {
  14722. while (children.size() > 0)
  14723. removeChild (children.size() - 1, undoManager);
  14724. }
  14725. void ValueTree::SharedObject::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  14726. {
  14727. // The source index must be a valid index!
  14728. jassert (((unsigned int) currentIndex) < (unsigned int) children.size());
  14729. if (currentIndex != newIndex
  14730. && ((unsigned int) currentIndex) < (unsigned int) children.size())
  14731. {
  14732. if (undoManager == 0)
  14733. {
  14734. children.move (currentIndex, newIndex);
  14735. sendChildChangeMessage();
  14736. }
  14737. else
  14738. {
  14739. if (((unsigned int) newIndex) >= (unsigned int) children.size())
  14740. newIndex = children.size() - 1;
  14741. undoManager->perform (new MoveChildAction (this, currentIndex, newIndex));
  14742. }
  14743. }
  14744. }
  14745. void ValueTree::SharedObject::reorderChildren (const ReferenceCountedArray <SharedObject>& newOrder, UndoManager* undoManager)
  14746. {
  14747. jassert (newOrder.size() == children.size());
  14748. if (undoManager == 0)
  14749. {
  14750. children = newOrder;
  14751. sendChildChangeMessage();
  14752. }
  14753. else
  14754. {
  14755. for (int i = 0; i < children.size(); ++i)
  14756. {
  14757. if (children.getUnchecked(i) != newOrder.getUnchecked(i))
  14758. {
  14759. jassert (children.contains (newOrder.getUnchecked(i)));
  14760. moveChild (children.indexOf (newOrder.getUnchecked(i)), i, undoManager);
  14761. }
  14762. }
  14763. }
  14764. }
  14765. bool ValueTree::SharedObject::isEquivalentTo (const SharedObject& other) const
  14766. {
  14767. if (type != other.type
  14768. || properties.size() != other.properties.size()
  14769. || children.size() != other.children.size()
  14770. || properties != other.properties)
  14771. return false;
  14772. for (int i = 0; i < children.size(); ++i)
  14773. if (! children.getUnchecked(i)->isEquivalentTo (*other.children.getUnchecked(i)))
  14774. return false;
  14775. return true;
  14776. }
  14777. ValueTree::ValueTree() throw()
  14778. : object (0)
  14779. {
  14780. }
  14781. const ValueTree ValueTree::invalid;
  14782. ValueTree::ValueTree (const Identifier& type_)
  14783. : object (new ValueTree::SharedObject (type_))
  14784. {
  14785. jassert (type_.toString().isNotEmpty()); // All objects should be given a sensible type name!
  14786. }
  14787. ValueTree::ValueTree (SharedObject* const object_)
  14788. : object (object_)
  14789. {
  14790. }
  14791. ValueTree::ValueTree (const ValueTree& other)
  14792. : object (other.object)
  14793. {
  14794. }
  14795. ValueTree& ValueTree::operator= (const ValueTree& other)
  14796. {
  14797. if (listeners.size() > 0)
  14798. {
  14799. if (object != 0)
  14800. object->valueTreesWithListeners.removeValue (this);
  14801. if (other.object != 0)
  14802. other.object->valueTreesWithListeners.add (this);
  14803. }
  14804. object = other.object;
  14805. return *this;
  14806. }
  14807. ValueTree::~ValueTree()
  14808. {
  14809. if (listeners.size() > 0 && object != 0)
  14810. object->valueTreesWithListeners.removeValue (this);
  14811. }
  14812. bool ValueTree::operator== (const ValueTree& other) const throw()
  14813. {
  14814. return object == other.object;
  14815. }
  14816. bool ValueTree::operator!= (const ValueTree& other) const throw()
  14817. {
  14818. return object != other.object;
  14819. }
  14820. bool ValueTree::isEquivalentTo (const ValueTree& other) const
  14821. {
  14822. return object == other.object
  14823. || (object != 0 && other.object != 0 && object->isEquivalentTo (*other.object));
  14824. }
  14825. ValueTree ValueTree::createCopy() const
  14826. {
  14827. return ValueTree (object != 0 ? new SharedObject (*object) : 0);
  14828. }
  14829. bool ValueTree::hasType (const Identifier& typeName) const
  14830. {
  14831. return object != 0 && object->type == typeName;
  14832. }
  14833. const Identifier ValueTree::getType() const
  14834. {
  14835. return object != 0 ? object->type : Identifier();
  14836. }
  14837. ValueTree ValueTree::getParent() const
  14838. {
  14839. return ValueTree (object != 0 ? object->parent : (SharedObject*) 0);
  14840. }
  14841. ValueTree ValueTree::getSibling (const int delta) const
  14842. {
  14843. if (object == 0 || object->parent == 0)
  14844. return invalid;
  14845. const int index = object->parent->indexOf (*this) + delta;
  14846. return ValueTree (static_cast <SharedObject*> (object->parent->children [index]));
  14847. }
  14848. const var& ValueTree::operator[] (const Identifier& name) const
  14849. {
  14850. return object == 0 ? var::null : object->getProperty (name);
  14851. }
  14852. const var& ValueTree::getProperty (const Identifier& name) const
  14853. {
  14854. return object == 0 ? var::null : object->getProperty (name);
  14855. }
  14856. const var ValueTree::getProperty (const Identifier& name, const var& defaultReturnValue) const
  14857. {
  14858. return object == 0 ? defaultReturnValue : object->getProperty (name, defaultReturnValue);
  14859. }
  14860. void ValueTree::setProperty (const Identifier& name, const var& newValue, UndoManager* const undoManager)
  14861. {
  14862. jassert (name.toString().isNotEmpty());
  14863. if (object != 0 && name.toString().isNotEmpty())
  14864. object->setProperty (name, newValue, undoManager);
  14865. }
  14866. bool ValueTree::hasProperty (const Identifier& name) const
  14867. {
  14868. return object != 0 && object->hasProperty (name);
  14869. }
  14870. void ValueTree::removeProperty (const Identifier& name, UndoManager* const undoManager)
  14871. {
  14872. if (object != 0)
  14873. object->removeProperty (name, undoManager);
  14874. }
  14875. void ValueTree::removeAllProperties (UndoManager* const undoManager)
  14876. {
  14877. if (object != 0)
  14878. object->removeAllProperties (undoManager);
  14879. }
  14880. int ValueTree::getNumProperties() const
  14881. {
  14882. return object == 0 ? 0 : object->properties.size();
  14883. }
  14884. const Identifier ValueTree::getPropertyName (const int index) const
  14885. {
  14886. return object == 0 ? Identifier()
  14887. : object->properties.getName (index);
  14888. }
  14889. class ValueTreePropertyValueSource : public Value::ValueSource,
  14890. public ValueTree::Listener
  14891. {
  14892. public:
  14893. ValueTreePropertyValueSource (const ValueTree& tree_,
  14894. const Identifier& property_,
  14895. UndoManager* const undoManager_)
  14896. : tree (tree_),
  14897. property (property_),
  14898. undoManager (undoManager_)
  14899. {
  14900. tree.addListener (this);
  14901. }
  14902. ~ValueTreePropertyValueSource()
  14903. {
  14904. tree.removeListener (this);
  14905. }
  14906. const var getValue() const
  14907. {
  14908. return tree [property];
  14909. }
  14910. void setValue (const var& newValue)
  14911. {
  14912. tree.setProperty (property, newValue, undoManager);
  14913. }
  14914. void valueTreePropertyChanged (ValueTree& treeWhosePropertyHasChanged, const Identifier& changedProperty)
  14915. {
  14916. if (tree == treeWhosePropertyHasChanged && property == changedProperty)
  14917. sendChangeMessage (false);
  14918. }
  14919. void valueTreeChildrenChanged (ValueTree&) {}
  14920. void valueTreeParentChanged (ValueTree&) {}
  14921. private:
  14922. ValueTree tree;
  14923. const Identifier property;
  14924. UndoManager* const undoManager;
  14925. ValueTreePropertyValueSource& operator= (const ValueTreePropertyValueSource&);
  14926. };
  14927. Value ValueTree::getPropertyAsValue (const Identifier& name, UndoManager* const undoManager) const
  14928. {
  14929. return Value (new ValueTreePropertyValueSource (*this, name, undoManager));
  14930. }
  14931. int ValueTree::getNumChildren() const
  14932. {
  14933. return object == 0 ? 0 : object->children.size();
  14934. }
  14935. ValueTree ValueTree::getChild (int index) const
  14936. {
  14937. return ValueTree (object != 0 ? (SharedObject*) object->children [index] : (SharedObject*) 0);
  14938. }
  14939. ValueTree ValueTree::getChildWithName (const Identifier& type) const
  14940. {
  14941. return object != 0 ? object->getChildWithName (type) : ValueTree::invalid;
  14942. }
  14943. ValueTree ValueTree::getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager)
  14944. {
  14945. return object != 0 ? object->getOrCreateChildWithName (type, undoManager) : ValueTree::invalid;
  14946. }
  14947. ValueTree ValueTree::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  14948. {
  14949. return object != 0 ? object->getChildWithProperty (propertyName, propertyValue) : ValueTree::invalid;
  14950. }
  14951. bool ValueTree::isAChildOf (const ValueTree& possibleParent) const
  14952. {
  14953. return object != 0 && object->isAChildOf (possibleParent.object);
  14954. }
  14955. int ValueTree::indexOf (const ValueTree& child) const
  14956. {
  14957. return object != 0 ? object->indexOf (child) : -1;
  14958. }
  14959. void ValueTree::addChild (const ValueTree& child, int index, UndoManager* const undoManager)
  14960. {
  14961. if (object != 0)
  14962. object->addChild (child.object, index, undoManager);
  14963. }
  14964. void ValueTree::removeChild (const int childIndex, UndoManager* const undoManager)
  14965. {
  14966. if (object != 0)
  14967. object->removeChild (childIndex, undoManager);
  14968. }
  14969. void ValueTree::removeChild (const ValueTree& child, UndoManager* const undoManager)
  14970. {
  14971. if (object != 0)
  14972. object->removeChild (object->children.indexOf (child.object), undoManager);
  14973. }
  14974. void ValueTree::removeAllChildren (UndoManager* const undoManager)
  14975. {
  14976. if (object != 0)
  14977. object->removeAllChildren (undoManager);
  14978. }
  14979. void ValueTree::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  14980. {
  14981. if (object != 0)
  14982. object->moveChild (currentIndex, newIndex, undoManager);
  14983. }
  14984. void ValueTree::addListener (Listener* listener)
  14985. {
  14986. if (listener != 0)
  14987. {
  14988. if (listeners.size() == 0 && object != 0)
  14989. object->valueTreesWithListeners.add (this);
  14990. listeners.add (listener);
  14991. }
  14992. }
  14993. void ValueTree::removeListener (Listener* listener)
  14994. {
  14995. listeners.remove (listener);
  14996. if (listeners.size() == 0 && object != 0)
  14997. object->valueTreesWithListeners.removeValue (this);
  14998. }
  14999. XmlElement* ValueTree::SharedObject::createXml() const
  15000. {
  15001. XmlElement* xml = new XmlElement (type.toString());
  15002. int i;
  15003. for (i = 0; i < properties.size(); ++i)
  15004. {
  15005. Identifier name (properties.getName(i));
  15006. const var& v = properties [name];
  15007. jassert (! v.isObject()); // DynamicObjects can't be stored as XML!
  15008. xml->setAttribute (name.toString(), v.toString());
  15009. }
  15010. for (i = 0; i < children.size(); ++i)
  15011. xml->addChildElement (children.getUnchecked(i)->createXml());
  15012. return xml;
  15013. }
  15014. XmlElement* ValueTree::createXml() const
  15015. {
  15016. return object != 0 ? object->createXml() : 0;
  15017. }
  15018. ValueTree ValueTree::fromXml (const XmlElement& xml)
  15019. {
  15020. ValueTree v (xml.getTagName());
  15021. const int numAtts = xml.getNumAttributes(); // xxx inefficient - should write an att iterator..
  15022. for (int i = 0; i < numAtts; ++i)
  15023. v.setProperty (xml.getAttributeName (i), var (xml.getAttributeValue (i)), 0);
  15024. forEachXmlChildElement (xml, e)
  15025. {
  15026. v.addChild (fromXml (*e), -1, 0);
  15027. }
  15028. return v;
  15029. }
  15030. void ValueTree::writeToStream (OutputStream& output)
  15031. {
  15032. output.writeString (getType().toString());
  15033. const int numProps = getNumProperties();
  15034. output.writeCompressedInt (numProps);
  15035. int i;
  15036. for (i = 0; i < numProps; ++i)
  15037. {
  15038. const Identifier name (getPropertyName(i));
  15039. output.writeString (name.toString());
  15040. getProperty(name).writeToStream (output);
  15041. }
  15042. const int numChildren = getNumChildren();
  15043. output.writeCompressedInt (numChildren);
  15044. for (i = 0; i < numChildren; ++i)
  15045. getChild (i).writeToStream (output);
  15046. }
  15047. ValueTree ValueTree::readFromStream (InputStream& input)
  15048. {
  15049. const String type (input.readString());
  15050. if (type.isEmpty())
  15051. return ValueTree::invalid;
  15052. ValueTree v (type);
  15053. const int numProps = input.readCompressedInt();
  15054. if (numProps < 0)
  15055. {
  15056. jassertfalse; // trying to read corrupted data!
  15057. return v;
  15058. }
  15059. int i;
  15060. for (i = 0; i < numProps; ++i)
  15061. {
  15062. const String name (input.readString());
  15063. jassert (name.isNotEmpty());
  15064. const var value (var::readFromStream (input));
  15065. v.setProperty (name, value, 0);
  15066. }
  15067. const int numChildren = input.readCompressedInt();
  15068. for (i = 0; i < numChildren; ++i)
  15069. v.addChild (readFromStream (input), -1, 0);
  15070. return v;
  15071. }
  15072. ValueTree ValueTree::readFromData (const void* const data, const size_t numBytes)
  15073. {
  15074. MemoryInputStream in (data, numBytes, false);
  15075. return readFromStream (in);
  15076. }
  15077. END_JUCE_NAMESPACE
  15078. /*** End of inlined file: juce_ValueTree.cpp ***/
  15079. /*** Start of inlined file: juce_Value.cpp ***/
  15080. BEGIN_JUCE_NAMESPACE
  15081. Value::ValueSource::ValueSource()
  15082. {
  15083. }
  15084. Value::ValueSource::~ValueSource()
  15085. {
  15086. }
  15087. void Value::ValueSource::sendChangeMessage (const bool synchronous)
  15088. {
  15089. if (synchronous)
  15090. {
  15091. for (int i = valuesWithListeners.size(); --i >= 0;)
  15092. {
  15093. Value* const v = valuesWithListeners[i];
  15094. if (v != 0)
  15095. v->callListeners();
  15096. }
  15097. }
  15098. else
  15099. {
  15100. triggerAsyncUpdate();
  15101. }
  15102. }
  15103. void Value::ValueSource::handleAsyncUpdate()
  15104. {
  15105. sendChangeMessage (true);
  15106. }
  15107. class SimpleValueSource : public Value::ValueSource
  15108. {
  15109. public:
  15110. SimpleValueSource()
  15111. {
  15112. }
  15113. SimpleValueSource (const var& initialValue)
  15114. : value (initialValue)
  15115. {
  15116. }
  15117. ~SimpleValueSource()
  15118. {
  15119. }
  15120. const var getValue() const
  15121. {
  15122. return value;
  15123. }
  15124. void setValue (const var& newValue)
  15125. {
  15126. if (newValue != value)
  15127. {
  15128. value = newValue;
  15129. sendChangeMessage (false);
  15130. }
  15131. }
  15132. private:
  15133. var value;
  15134. SimpleValueSource (const SimpleValueSource&);
  15135. SimpleValueSource& operator= (const SimpleValueSource&);
  15136. };
  15137. Value::Value()
  15138. : value (new SimpleValueSource())
  15139. {
  15140. }
  15141. Value::Value (ValueSource* const value_)
  15142. : value (value_)
  15143. {
  15144. jassert (value_ != 0);
  15145. }
  15146. Value::Value (const var& initialValue)
  15147. : value (new SimpleValueSource (initialValue))
  15148. {
  15149. }
  15150. Value::Value (const Value& other)
  15151. : value (other.value)
  15152. {
  15153. }
  15154. Value& Value::operator= (const Value& other)
  15155. {
  15156. value = other.value;
  15157. return *this;
  15158. }
  15159. Value::~Value()
  15160. {
  15161. if (listeners.size() > 0)
  15162. value->valuesWithListeners.removeValue (this);
  15163. }
  15164. const var Value::getValue() const
  15165. {
  15166. return value->getValue();
  15167. }
  15168. Value::operator const var() const
  15169. {
  15170. return getValue();
  15171. }
  15172. void Value::setValue (const var& newValue)
  15173. {
  15174. value->setValue (newValue);
  15175. }
  15176. const String Value::toString() const
  15177. {
  15178. return value->getValue().toString();
  15179. }
  15180. Value& Value::operator= (const var& newValue)
  15181. {
  15182. value->setValue (newValue);
  15183. return *this;
  15184. }
  15185. void Value::referTo (const Value& valueToReferTo)
  15186. {
  15187. if (valueToReferTo.value != value)
  15188. {
  15189. if (listeners.size() > 0)
  15190. {
  15191. value->valuesWithListeners.removeValue (this);
  15192. valueToReferTo.value->valuesWithListeners.add (this);
  15193. }
  15194. value = valueToReferTo.value;
  15195. callListeners();
  15196. }
  15197. }
  15198. bool Value::refersToSameSourceAs (const Value& other) const
  15199. {
  15200. return value == other.value;
  15201. }
  15202. bool Value::operator== (const Value& other) const
  15203. {
  15204. return value == other.value || value->getValue() == other.getValue();
  15205. }
  15206. bool Value::operator!= (const Value& other) const
  15207. {
  15208. return value != other.value && value->getValue() != other.getValue();
  15209. }
  15210. void Value::addListener (Listener* const listener)
  15211. {
  15212. if (listener != 0)
  15213. {
  15214. if (listeners.size() == 0)
  15215. value->valuesWithListeners.add (this);
  15216. listeners.add (listener);
  15217. }
  15218. }
  15219. void Value::removeListener (Listener* const listener)
  15220. {
  15221. listeners.remove (listener);
  15222. if (listeners.size() == 0)
  15223. value->valuesWithListeners.removeValue (this);
  15224. }
  15225. void Value::callListeners()
  15226. {
  15227. Value v (*this); // (create a copy in case this gets deleted by a callback)
  15228. listeners.call (&Value::Listener::valueChanged, v);
  15229. }
  15230. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const Value& value)
  15231. {
  15232. return stream << value.toString();
  15233. }
  15234. END_JUCE_NAMESPACE
  15235. /*** End of inlined file: juce_Value.cpp ***/
  15236. /*** Start of inlined file: juce_Application.cpp ***/
  15237. BEGIN_JUCE_NAMESPACE
  15238. #if JUCE_MAC
  15239. extern void juce_initialiseMacMainMenu();
  15240. #endif
  15241. JUCEApplication::JUCEApplication()
  15242. : appReturnValue (0),
  15243. stillInitialising (true)
  15244. {
  15245. jassert (isStandaloneApp() && appInstance == 0);
  15246. appInstance = this;
  15247. }
  15248. JUCEApplication::~JUCEApplication()
  15249. {
  15250. if (appLock != 0)
  15251. {
  15252. appLock->exit();
  15253. appLock = 0;
  15254. }
  15255. jassert (appInstance == this);
  15256. appInstance = 0;
  15257. }
  15258. JUCEApplication::CreateInstanceFunction JUCEApplication::createInstance = 0;
  15259. JUCEApplication* JUCEApplication::appInstance = 0;
  15260. bool JUCEApplication::moreThanOneInstanceAllowed()
  15261. {
  15262. return true;
  15263. }
  15264. void JUCEApplication::anotherInstanceStarted (const String&)
  15265. {
  15266. }
  15267. void JUCEApplication::systemRequestedQuit()
  15268. {
  15269. quit();
  15270. }
  15271. void JUCEApplication::quit()
  15272. {
  15273. MessageManager::getInstance()->stopDispatchLoop();
  15274. }
  15275. void JUCEApplication::setApplicationReturnValue (const int newReturnValue) throw()
  15276. {
  15277. appReturnValue = newReturnValue;
  15278. }
  15279. void JUCEApplication::actionListenerCallback (const String& message)
  15280. {
  15281. if (message.startsWith (getApplicationName() + "/"))
  15282. anotherInstanceStarted (message.substring (getApplicationName().length() + 1));
  15283. }
  15284. void JUCEApplication::unhandledException (const std::exception*,
  15285. const String&,
  15286. const int)
  15287. {
  15288. jassertfalse;
  15289. }
  15290. void JUCEApplication::sendUnhandledException (const std::exception* const e,
  15291. const char* const sourceFile,
  15292. const int lineNumber)
  15293. {
  15294. if (appInstance != 0)
  15295. appInstance->unhandledException (e, sourceFile, lineNumber);
  15296. }
  15297. ApplicationCommandTarget* JUCEApplication::getNextCommandTarget()
  15298. {
  15299. return 0;
  15300. }
  15301. void JUCEApplication::getAllCommands (Array <CommandID>& commands)
  15302. {
  15303. commands.add (StandardApplicationCommandIDs::quit);
  15304. }
  15305. void JUCEApplication::getCommandInfo (const CommandID commandID, ApplicationCommandInfo& result)
  15306. {
  15307. if (commandID == StandardApplicationCommandIDs::quit)
  15308. {
  15309. result.setInfo (TRANS("Quit"),
  15310. TRANS("Quits the application"),
  15311. "Application",
  15312. 0);
  15313. result.defaultKeypresses.add (KeyPress ('q', ModifierKeys::commandModifier, 0));
  15314. }
  15315. }
  15316. bool JUCEApplication::perform (const InvocationInfo& info)
  15317. {
  15318. if (info.commandID == StandardApplicationCommandIDs::quit)
  15319. {
  15320. systemRequestedQuit();
  15321. return true;
  15322. }
  15323. return false;
  15324. }
  15325. bool JUCEApplication::initialiseApp (const String& commandLine)
  15326. {
  15327. commandLineParameters = commandLine.trim();
  15328. #if ! JUCE_IOS
  15329. jassert (appLock == 0); // initialiseApp must only be called once!
  15330. if (! moreThanOneInstanceAllowed())
  15331. {
  15332. appLock = new InterProcessLock ("juceAppLock_" + getApplicationName());
  15333. if (! appLock->enter(0))
  15334. {
  15335. appLock = 0;
  15336. MessageManager::broadcastMessage (getApplicationName() + "/" + commandLineParameters);
  15337. DBG ("Another instance is running - quitting...");
  15338. return false;
  15339. }
  15340. }
  15341. #endif
  15342. // let the app do its setting-up..
  15343. initialise (commandLineParameters);
  15344. #if JUCE_MAC
  15345. juce_initialiseMacMainMenu(); // needs to be called after the app object has created, to get its name
  15346. #endif
  15347. // register for broadcast new app messages
  15348. MessageManager::getInstance()->registerBroadcastListener (this);
  15349. stillInitialising = false;
  15350. return true;
  15351. }
  15352. int JUCEApplication::shutdownApp()
  15353. {
  15354. jassert (appInstance == this);
  15355. MessageManager::getInstance()->deregisterBroadcastListener (this);
  15356. JUCE_TRY
  15357. {
  15358. // give the app a chance to clean up..
  15359. shutdown();
  15360. }
  15361. JUCE_CATCH_EXCEPTION
  15362. return getApplicationReturnValue();
  15363. }
  15364. // This is called on the Mac and iOS where the OS doesn't allow the stack to unwind on shutdown..
  15365. void JUCEApplication::appWillTerminateByForce()
  15366. {
  15367. {
  15368. const ScopedPointer<JUCEApplication> app (JUCEApplication::getInstance());
  15369. if (app != 0)
  15370. app->shutdownApp();
  15371. }
  15372. shutdownJuce_GUI();
  15373. }
  15374. int JUCEApplication::main (const String& commandLine)
  15375. {
  15376. ScopedJuceInitialiser_GUI libraryInitialiser;
  15377. jassert (createInstance != 0);
  15378. int returnCode = 0;
  15379. {
  15380. const ScopedPointer<JUCEApplication> app (createInstance());
  15381. if (! app->initialiseApp (commandLine))
  15382. return 0;
  15383. JUCE_TRY
  15384. {
  15385. // loop until a quit message is received..
  15386. MessageManager::getInstance()->runDispatchLoop();
  15387. }
  15388. JUCE_CATCH_EXCEPTION
  15389. returnCode = app->shutdownApp();
  15390. }
  15391. return returnCode;
  15392. }
  15393. #if JUCE_IOS
  15394. extern int juce_iOSMain (int argc, const char* argv[]);
  15395. #endif
  15396. #if ! JUCE_WINDOWS
  15397. extern const char* juce_Argv0;
  15398. #endif
  15399. int JUCEApplication::main (int argc, const char* argv[])
  15400. {
  15401. JUCE_AUTORELEASEPOOL
  15402. #if ! JUCE_WINDOWS
  15403. jassert (createInstance != 0);
  15404. juce_Argv0 = argv[0];
  15405. #endif
  15406. #if JUCE_IOS
  15407. return juce_iOSMain (argc, argv);
  15408. #else
  15409. String cmd;
  15410. for (int i = 1; i < argc; ++i)
  15411. cmd << argv[i] << ' ';
  15412. return JUCEApplication::main (cmd);
  15413. #endif
  15414. }
  15415. END_JUCE_NAMESPACE
  15416. /*** End of inlined file: juce_Application.cpp ***/
  15417. /*** Start of inlined file: juce_ApplicationCommandInfo.cpp ***/
  15418. BEGIN_JUCE_NAMESPACE
  15419. ApplicationCommandInfo::ApplicationCommandInfo (const CommandID commandID_) throw()
  15420. : commandID (commandID_),
  15421. flags (0)
  15422. {
  15423. }
  15424. void ApplicationCommandInfo::setInfo (const String& shortName_,
  15425. const String& description_,
  15426. const String& categoryName_,
  15427. const int flags_) throw()
  15428. {
  15429. shortName = shortName_;
  15430. description = description_;
  15431. categoryName = categoryName_;
  15432. flags = flags_;
  15433. }
  15434. void ApplicationCommandInfo::setActive (const bool b) throw()
  15435. {
  15436. if (b)
  15437. flags &= ~isDisabled;
  15438. else
  15439. flags |= isDisabled;
  15440. }
  15441. void ApplicationCommandInfo::setTicked (const bool b) throw()
  15442. {
  15443. if (b)
  15444. flags |= isTicked;
  15445. else
  15446. flags &= ~isTicked;
  15447. }
  15448. void ApplicationCommandInfo::addDefaultKeypress (const int keyCode, const ModifierKeys& modifiers) throw()
  15449. {
  15450. defaultKeypresses.add (KeyPress (keyCode, modifiers, 0));
  15451. }
  15452. END_JUCE_NAMESPACE
  15453. /*** End of inlined file: juce_ApplicationCommandInfo.cpp ***/
  15454. /*** Start of inlined file: juce_ApplicationCommandManager.cpp ***/
  15455. BEGIN_JUCE_NAMESPACE
  15456. ApplicationCommandManager::ApplicationCommandManager()
  15457. : firstTarget (0)
  15458. {
  15459. keyMappings = new KeyPressMappingSet (this);
  15460. Desktop::getInstance().addFocusChangeListener (this);
  15461. }
  15462. ApplicationCommandManager::~ApplicationCommandManager()
  15463. {
  15464. Desktop::getInstance().removeFocusChangeListener (this);
  15465. keyMappings = 0;
  15466. }
  15467. void ApplicationCommandManager::clearCommands()
  15468. {
  15469. commands.clear();
  15470. keyMappings->clearAllKeyPresses();
  15471. triggerAsyncUpdate();
  15472. }
  15473. void ApplicationCommandManager::registerCommand (const ApplicationCommandInfo& newCommand)
  15474. {
  15475. // zero isn't a valid command ID!
  15476. jassert (newCommand.commandID != 0);
  15477. // the name isn't optional!
  15478. jassert (newCommand.shortName.isNotEmpty());
  15479. if (getCommandForID (newCommand.commandID) == 0)
  15480. {
  15481. ApplicationCommandInfo* const newInfo = new ApplicationCommandInfo (newCommand);
  15482. newInfo->flags &= ~ApplicationCommandInfo::isTicked;
  15483. commands.add (newInfo);
  15484. keyMappings->resetToDefaultMapping (newCommand.commandID);
  15485. triggerAsyncUpdate();
  15486. }
  15487. else
  15488. {
  15489. // trying to re-register the same command with different parameters?
  15490. jassert (newCommand.shortName == getCommandForID (newCommand.commandID)->shortName
  15491. && (newCommand.description == getCommandForID (newCommand.commandID)->description || newCommand.description.isEmpty())
  15492. && newCommand.categoryName == getCommandForID (newCommand.commandID)->categoryName
  15493. && newCommand.defaultKeypresses == getCommandForID (newCommand.commandID)->defaultKeypresses
  15494. && (newCommand.flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor))
  15495. == (getCommandForID (newCommand.commandID)->flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor)));
  15496. }
  15497. }
  15498. void ApplicationCommandManager::registerAllCommandsForTarget (ApplicationCommandTarget* target)
  15499. {
  15500. if (target != 0)
  15501. {
  15502. Array <CommandID> commandIDs;
  15503. target->getAllCommands (commandIDs);
  15504. for (int i = 0; i < commandIDs.size(); ++i)
  15505. {
  15506. ApplicationCommandInfo info (commandIDs.getUnchecked(i));
  15507. target->getCommandInfo (info.commandID, info);
  15508. registerCommand (info);
  15509. }
  15510. }
  15511. }
  15512. void ApplicationCommandManager::removeCommand (const CommandID commandID)
  15513. {
  15514. for (int i = commands.size(); --i >= 0;)
  15515. {
  15516. if (commands.getUnchecked (i)->commandID == commandID)
  15517. {
  15518. commands.remove (i);
  15519. triggerAsyncUpdate();
  15520. const Array <KeyPress> keys (keyMappings->getKeyPressesAssignedToCommand (commandID));
  15521. for (int j = keys.size(); --j >= 0;)
  15522. keyMappings->removeKeyPress (keys.getReference (j));
  15523. }
  15524. }
  15525. }
  15526. void ApplicationCommandManager::commandStatusChanged()
  15527. {
  15528. triggerAsyncUpdate();
  15529. }
  15530. const ApplicationCommandInfo* ApplicationCommandManager::getCommandForID (const CommandID commandID) const throw()
  15531. {
  15532. for (int i = commands.size(); --i >= 0;)
  15533. if (commands.getUnchecked(i)->commandID == commandID)
  15534. return commands.getUnchecked(i);
  15535. return 0;
  15536. }
  15537. const String ApplicationCommandManager::getNameOfCommand (const CommandID commandID) const throw()
  15538. {
  15539. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  15540. return (ci != 0) ? ci->shortName : String::empty;
  15541. }
  15542. const String ApplicationCommandManager::getDescriptionOfCommand (const CommandID commandID) const throw()
  15543. {
  15544. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  15545. return (ci != 0) ? (ci->description.isNotEmpty() ? ci->description : ci->shortName)
  15546. : String::empty;
  15547. }
  15548. const StringArray ApplicationCommandManager::getCommandCategories() const
  15549. {
  15550. StringArray s;
  15551. for (int i = 0; i < commands.size(); ++i)
  15552. s.addIfNotAlreadyThere (commands.getUnchecked(i)->categoryName, false);
  15553. return s;
  15554. }
  15555. const Array <CommandID> ApplicationCommandManager::getCommandsInCategory (const String& categoryName) const
  15556. {
  15557. Array <CommandID> results;
  15558. for (int i = 0; i < commands.size(); ++i)
  15559. if (commands.getUnchecked(i)->categoryName == categoryName)
  15560. results.add (commands.getUnchecked(i)->commandID);
  15561. return results;
  15562. }
  15563. bool ApplicationCommandManager::invokeDirectly (const CommandID commandID, const bool asynchronously)
  15564. {
  15565. ApplicationCommandTarget::InvocationInfo info (commandID);
  15566. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  15567. return invoke (info, asynchronously);
  15568. }
  15569. bool ApplicationCommandManager::invoke (const ApplicationCommandTarget::InvocationInfo& info_, const bool asynchronously)
  15570. {
  15571. // This call isn't thread-safe for use from a non-UI thread without locking the message
  15572. // manager first..
  15573. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  15574. ApplicationCommandTarget* const target = getFirstCommandTarget (info_.commandID);
  15575. if (target == 0)
  15576. return false;
  15577. ApplicationCommandInfo commandInfo (0);
  15578. target->getCommandInfo (info_.commandID, commandInfo);
  15579. ApplicationCommandTarget::InvocationInfo info (info_);
  15580. info.commandFlags = commandInfo.flags;
  15581. sendListenerInvokeCallback (info);
  15582. const bool ok = target->invoke (info, asynchronously);
  15583. commandStatusChanged();
  15584. return ok;
  15585. }
  15586. ApplicationCommandTarget* ApplicationCommandManager::getFirstCommandTarget (const CommandID)
  15587. {
  15588. return firstTarget != 0 ? firstTarget
  15589. : findDefaultComponentTarget();
  15590. }
  15591. void ApplicationCommandManager::setFirstCommandTarget (ApplicationCommandTarget* const newTarget) throw()
  15592. {
  15593. firstTarget = newTarget;
  15594. }
  15595. ApplicationCommandTarget* ApplicationCommandManager::getTargetForCommand (const CommandID commandID,
  15596. ApplicationCommandInfo& upToDateInfo)
  15597. {
  15598. ApplicationCommandTarget* target = getFirstCommandTarget (commandID);
  15599. if (target == 0)
  15600. target = JUCEApplication::getInstance();
  15601. if (target != 0)
  15602. target = target->getTargetForCommand (commandID);
  15603. if (target != 0)
  15604. target->getCommandInfo (commandID, upToDateInfo);
  15605. return target;
  15606. }
  15607. ApplicationCommandTarget* ApplicationCommandManager::findTargetForComponent (Component* c)
  15608. {
  15609. ApplicationCommandTarget* target = dynamic_cast <ApplicationCommandTarget*> (c);
  15610. if (target == 0 && c != 0)
  15611. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  15612. target = c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  15613. return target;
  15614. }
  15615. ApplicationCommandTarget* ApplicationCommandManager::findDefaultComponentTarget()
  15616. {
  15617. Component* c = Component::getCurrentlyFocusedComponent();
  15618. if (c == 0)
  15619. {
  15620. TopLevelWindow* const activeWindow = TopLevelWindow::getActiveTopLevelWindow();
  15621. if (activeWindow != 0)
  15622. {
  15623. c = activeWindow->getPeer()->getLastFocusedSubcomponent();
  15624. if (c == 0)
  15625. c = activeWindow;
  15626. }
  15627. }
  15628. if (c == 0 && Process::isForegroundProcess())
  15629. {
  15630. // getting a bit desperate now - try all desktop comps..
  15631. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  15632. {
  15633. ApplicationCommandTarget* const target
  15634. = findTargetForComponent (Desktop::getInstance().getComponent (i)
  15635. ->getPeer()->getLastFocusedSubcomponent());
  15636. if (target != 0)
  15637. return target;
  15638. }
  15639. }
  15640. if (c != 0)
  15641. {
  15642. ResizableWindow* const resizableWindow = dynamic_cast <ResizableWindow*> (c);
  15643. // if we're focused on a ResizableWindow, chances are that it's the content
  15644. // component that really should get the event. And if not, the event will
  15645. // still be passed up to the top level window anyway, so let's send it to the
  15646. // content comp.
  15647. if (resizableWindow != 0 && resizableWindow->getContentComponent() != 0)
  15648. c = resizableWindow->getContentComponent();
  15649. ApplicationCommandTarget* const target = findTargetForComponent (c);
  15650. if (target != 0)
  15651. return target;
  15652. }
  15653. return JUCEApplication::getInstance();
  15654. }
  15655. void ApplicationCommandManager::addListener (ApplicationCommandManagerListener* const listener)
  15656. {
  15657. listeners.add (listener);
  15658. }
  15659. void ApplicationCommandManager::removeListener (ApplicationCommandManagerListener* const listener)
  15660. {
  15661. listeners.remove (listener);
  15662. }
  15663. void ApplicationCommandManager::sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info)
  15664. {
  15665. listeners.call (&ApplicationCommandManagerListener::applicationCommandInvoked, info);
  15666. }
  15667. void ApplicationCommandManager::handleAsyncUpdate()
  15668. {
  15669. listeners.call (&ApplicationCommandManagerListener::applicationCommandListChanged);
  15670. }
  15671. void ApplicationCommandManager::globalFocusChanged (Component*)
  15672. {
  15673. commandStatusChanged();
  15674. }
  15675. END_JUCE_NAMESPACE
  15676. /*** End of inlined file: juce_ApplicationCommandManager.cpp ***/
  15677. /*** Start of inlined file: juce_ApplicationCommandTarget.cpp ***/
  15678. BEGIN_JUCE_NAMESPACE
  15679. ApplicationCommandTarget::ApplicationCommandTarget()
  15680. {
  15681. }
  15682. ApplicationCommandTarget::~ApplicationCommandTarget()
  15683. {
  15684. messageInvoker = 0;
  15685. }
  15686. bool ApplicationCommandTarget::tryToInvoke (const InvocationInfo& info, const bool async)
  15687. {
  15688. if (isCommandActive (info.commandID))
  15689. {
  15690. if (async)
  15691. {
  15692. if (messageInvoker == 0)
  15693. messageInvoker = new CommandTargetMessageInvoker (this);
  15694. messageInvoker->postMessage (new Message (0, 0, 0, new ApplicationCommandTarget::InvocationInfo (info)));
  15695. return true;
  15696. }
  15697. else
  15698. {
  15699. const bool success = perform (info);
  15700. jassert (success); // hmm - your target should have been able to perform this command. If it can't
  15701. // do it at the moment for some reason, it should clear the 'isActive' flag when it
  15702. // returns the command's info.
  15703. return success;
  15704. }
  15705. }
  15706. return false;
  15707. }
  15708. ApplicationCommandTarget* ApplicationCommandTarget::findFirstTargetParentComponent()
  15709. {
  15710. Component* c = dynamic_cast <Component*> (this);
  15711. if (c != 0)
  15712. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  15713. return c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  15714. return 0;
  15715. }
  15716. ApplicationCommandTarget* ApplicationCommandTarget::getTargetForCommand (const CommandID commandID)
  15717. {
  15718. ApplicationCommandTarget* target = this;
  15719. int depth = 0;
  15720. while (target != 0)
  15721. {
  15722. Array <CommandID> commandIDs;
  15723. target->getAllCommands (commandIDs);
  15724. if (commandIDs.contains (commandID))
  15725. return target;
  15726. target = target->getNextCommandTarget();
  15727. ++depth;
  15728. jassert (depth < 100); // could be a recursive command chain??
  15729. jassert (target != this); // definitely a recursive command chain!
  15730. if (depth > 100 || target == this)
  15731. break;
  15732. }
  15733. if (target == 0)
  15734. {
  15735. target = JUCEApplication::getInstance();
  15736. if (target != 0)
  15737. {
  15738. Array <CommandID> commandIDs;
  15739. target->getAllCommands (commandIDs);
  15740. if (commandIDs.contains (commandID))
  15741. return target;
  15742. }
  15743. }
  15744. return 0;
  15745. }
  15746. bool ApplicationCommandTarget::isCommandActive (const CommandID commandID)
  15747. {
  15748. ApplicationCommandInfo info (commandID);
  15749. info.flags = ApplicationCommandInfo::isDisabled;
  15750. getCommandInfo (commandID, info);
  15751. return (info.flags & ApplicationCommandInfo::isDisabled) == 0;
  15752. }
  15753. bool ApplicationCommandTarget::invoke (const InvocationInfo& info, const bool async)
  15754. {
  15755. ApplicationCommandTarget* target = this;
  15756. int depth = 0;
  15757. while (target != 0)
  15758. {
  15759. if (target->tryToInvoke (info, async))
  15760. return true;
  15761. target = target->getNextCommandTarget();
  15762. ++depth;
  15763. jassert (depth < 100); // could be a recursive command chain??
  15764. jassert (target != this); // definitely a recursive command chain!
  15765. if (depth > 100 || target == this)
  15766. break;
  15767. }
  15768. if (target == 0)
  15769. {
  15770. target = JUCEApplication::getInstance();
  15771. if (target != 0)
  15772. return target->tryToInvoke (info, async);
  15773. }
  15774. return false;
  15775. }
  15776. bool ApplicationCommandTarget::invokeDirectly (const CommandID commandID, const bool asynchronously)
  15777. {
  15778. ApplicationCommandTarget::InvocationInfo info (commandID);
  15779. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  15780. return invoke (info, asynchronously);
  15781. }
  15782. ApplicationCommandTarget::InvocationInfo::InvocationInfo (const CommandID commandID_)
  15783. : commandID (commandID_),
  15784. commandFlags (0),
  15785. invocationMethod (direct),
  15786. originatingComponent (0),
  15787. isKeyDown (false),
  15788. millisecsSinceKeyPressed (0)
  15789. {
  15790. }
  15791. ApplicationCommandTarget::CommandTargetMessageInvoker::CommandTargetMessageInvoker (ApplicationCommandTarget* const owner_)
  15792. : owner (owner_)
  15793. {
  15794. }
  15795. ApplicationCommandTarget::CommandTargetMessageInvoker::~CommandTargetMessageInvoker()
  15796. {
  15797. }
  15798. void ApplicationCommandTarget::CommandTargetMessageInvoker::handleMessage (const Message& message)
  15799. {
  15800. const ScopedPointer <InvocationInfo> info (static_cast <InvocationInfo*> (message.pointerParameter));
  15801. owner->tryToInvoke (*info, false);
  15802. }
  15803. END_JUCE_NAMESPACE
  15804. /*** End of inlined file: juce_ApplicationCommandTarget.cpp ***/
  15805. /*** Start of inlined file: juce_ApplicationProperties.cpp ***/
  15806. BEGIN_JUCE_NAMESPACE
  15807. juce_ImplementSingleton (ApplicationProperties)
  15808. ApplicationProperties::ApplicationProperties()
  15809. : msBeforeSaving (3000),
  15810. options (PropertiesFile::storeAsBinary),
  15811. commonSettingsAreReadOnly (0),
  15812. processLock (0)
  15813. {
  15814. }
  15815. ApplicationProperties::~ApplicationProperties()
  15816. {
  15817. closeFiles();
  15818. clearSingletonInstance();
  15819. }
  15820. void ApplicationProperties::setStorageParameters (const String& applicationName,
  15821. const String& fileNameSuffix,
  15822. const String& folderName_,
  15823. const int millisecondsBeforeSaving,
  15824. const int propertiesFileOptions,
  15825. InterProcessLock* processLock_)
  15826. {
  15827. appName = applicationName;
  15828. fileSuffix = fileNameSuffix;
  15829. folderName = folderName_;
  15830. msBeforeSaving = millisecondsBeforeSaving;
  15831. options = propertiesFileOptions;
  15832. processLock = processLock_;
  15833. }
  15834. bool ApplicationProperties::testWriteAccess (const bool testUserSettings,
  15835. const bool testCommonSettings,
  15836. const bool showWarningDialogOnFailure)
  15837. {
  15838. const bool userOk = (! testUserSettings) || getUserSettings()->save();
  15839. const bool commonOk = (! testCommonSettings) || getCommonSettings (false)->save();
  15840. if (! (userOk && commonOk))
  15841. {
  15842. if (showWarningDialogOnFailure)
  15843. {
  15844. String filenames;
  15845. if (userProps != 0 && ! userOk)
  15846. filenames << '\n' << userProps->getFile().getFullPathName();
  15847. if (commonProps != 0 && ! commonOk)
  15848. filenames << '\n' << commonProps->getFile().getFullPathName();
  15849. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  15850. appName + TRANS(" - Unable to save settings"),
  15851. TRANS("An error occurred when trying to save the application's settings file...\n\nIn order to save and restore its settings, ")
  15852. + appName + TRANS(" needs to be able to write to the following files:\n")
  15853. + filenames
  15854. + TRANS("\n\nMake sure that these files aren't read-only, and that the disk isn't full."));
  15855. }
  15856. return false;
  15857. }
  15858. return true;
  15859. }
  15860. void ApplicationProperties::openFiles()
  15861. {
  15862. // You need to call setStorageParameters() before trying to get hold of the
  15863. // properties!
  15864. jassert (appName.isNotEmpty());
  15865. if (appName.isNotEmpty())
  15866. {
  15867. if (userProps == 0)
  15868. userProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  15869. false, msBeforeSaving, options, processLock);
  15870. if (commonProps == 0)
  15871. commonProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  15872. true, msBeforeSaving, options, processLock);
  15873. userProps->setFallbackPropertySet (commonProps);
  15874. }
  15875. }
  15876. PropertiesFile* ApplicationProperties::getUserSettings()
  15877. {
  15878. if (userProps == 0)
  15879. openFiles();
  15880. return userProps;
  15881. }
  15882. PropertiesFile* ApplicationProperties::getCommonSettings (const bool returnUserPropsIfReadOnly)
  15883. {
  15884. if (commonProps == 0)
  15885. openFiles();
  15886. if (returnUserPropsIfReadOnly)
  15887. {
  15888. if (commonSettingsAreReadOnly == 0)
  15889. commonSettingsAreReadOnly = commonProps->save() ? -1 : 1;
  15890. if (commonSettingsAreReadOnly > 0)
  15891. return userProps;
  15892. }
  15893. return commonProps;
  15894. }
  15895. bool ApplicationProperties::saveIfNeeded()
  15896. {
  15897. return (userProps == 0 || userProps->saveIfNeeded())
  15898. && (commonProps == 0 || commonProps->saveIfNeeded());
  15899. }
  15900. void ApplicationProperties::closeFiles()
  15901. {
  15902. userProps = 0;
  15903. commonProps = 0;
  15904. }
  15905. END_JUCE_NAMESPACE
  15906. /*** End of inlined file: juce_ApplicationProperties.cpp ***/
  15907. /*** Start of inlined file: juce_PropertiesFile.cpp ***/
  15908. BEGIN_JUCE_NAMESPACE
  15909. namespace PropertyFileConstants
  15910. {
  15911. static const int magicNumber = (int) ByteOrder::littleEndianInt ("PROP");
  15912. static const int magicNumberCompressed = (int) ByteOrder::littleEndianInt ("CPRP");
  15913. static const char* const fileTag = "PROPERTIES";
  15914. static const char* const valueTag = "VALUE";
  15915. static const char* const nameAttribute = "name";
  15916. static const char* const valueAttribute = "val";
  15917. }
  15918. PropertiesFile::PropertiesFile (const File& f, const int millisecondsBeforeSaving,
  15919. const int options_, InterProcessLock* const processLock_)
  15920. : PropertySet (ignoreCaseOfKeyNames),
  15921. file (f),
  15922. timerInterval (millisecondsBeforeSaving),
  15923. options (options_),
  15924. loadedOk (false),
  15925. needsWriting (false),
  15926. processLock (processLock_)
  15927. {
  15928. // You need to correctly specify just one storage format for the file
  15929. jassert ((options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsBinary
  15930. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsCompressedBinary
  15931. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsXML);
  15932. ProcessScopedLock pl (createProcessLock());
  15933. if (pl != 0 && ! pl->isLocked())
  15934. return; // locking failure..
  15935. ScopedPointer<InputStream> fileStream (f.createInputStream());
  15936. if (fileStream != 0)
  15937. {
  15938. int magicNumber = fileStream->readInt();
  15939. if (magicNumber == PropertyFileConstants::magicNumberCompressed)
  15940. {
  15941. fileStream = new GZIPDecompressorInputStream (new SubregionStream (fileStream.release(), 4, -1, true), true);
  15942. magicNumber = PropertyFileConstants::magicNumber;
  15943. }
  15944. if (magicNumber == PropertyFileConstants::magicNumber)
  15945. {
  15946. loadedOk = true;
  15947. BufferedInputStream in (fileStream.release(), 2048, true);
  15948. int numValues = in.readInt();
  15949. while (--numValues >= 0 && ! in.isExhausted())
  15950. {
  15951. const String key (in.readString());
  15952. const String value (in.readString());
  15953. jassert (key.isNotEmpty());
  15954. if (key.isNotEmpty())
  15955. getAllProperties().set (key, value);
  15956. }
  15957. }
  15958. else
  15959. {
  15960. // Not a binary props file - let's see if it's XML..
  15961. fileStream = 0;
  15962. XmlDocument parser (f);
  15963. ScopedPointer<XmlElement> doc (parser.getDocumentElement (true));
  15964. if (doc != 0 && doc->hasTagName (PropertyFileConstants::fileTag))
  15965. {
  15966. doc = parser.getDocumentElement();
  15967. if (doc != 0)
  15968. {
  15969. loadedOk = true;
  15970. forEachXmlChildElementWithTagName (*doc, e, PropertyFileConstants::valueTag)
  15971. {
  15972. const String name (e->getStringAttribute (PropertyFileConstants::nameAttribute));
  15973. if (name.isNotEmpty())
  15974. {
  15975. getAllProperties().set (name,
  15976. e->getFirstChildElement() != 0
  15977. ? e->getFirstChildElement()->createDocument (String::empty, true)
  15978. : e->getStringAttribute (PropertyFileConstants::valueAttribute));
  15979. }
  15980. }
  15981. }
  15982. else
  15983. {
  15984. // must be a pretty broken XML file we're trying to parse here,
  15985. // or a sign that this object needs an InterProcessLock,
  15986. // or just a failure reading the file. This last reason is why
  15987. // we don't jassertfalse here.
  15988. }
  15989. }
  15990. }
  15991. }
  15992. else
  15993. {
  15994. loadedOk = ! f.exists();
  15995. }
  15996. }
  15997. PropertiesFile::~PropertiesFile()
  15998. {
  15999. if (! saveIfNeeded())
  16000. jassertfalse;
  16001. }
  16002. InterProcessLock::ScopedLockType* PropertiesFile::createProcessLock() const
  16003. {
  16004. return processLock != 0 ? new InterProcessLock::ScopedLockType (*processLock) : 0;
  16005. }
  16006. bool PropertiesFile::saveIfNeeded()
  16007. {
  16008. const ScopedLock sl (getLock());
  16009. return (! needsWriting) || save();
  16010. }
  16011. bool PropertiesFile::needsToBeSaved() const
  16012. {
  16013. const ScopedLock sl (getLock());
  16014. return needsWriting;
  16015. }
  16016. void PropertiesFile::setNeedsToBeSaved (const bool needsToBeSaved_)
  16017. {
  16018. const ScopedLock sl (getLock());
  16019. needsWriting = needsToBeSaved_;
  16020. }
  16021. bool PropertiesFile::save()
  16022. {
  16023. const ScopedLock sl (getLock());
  16024. stopTimer();
  16025. if (file == File::nonexistent
  16026. || file.isDirectory()
  16027. || ! file.getParentDirectory().createDirectory())
  16028. return false;
  16029. if ((options & storeAsXML) != 0)
  16030. {
  16031. XmlElement doc (PropertyFileConstants::fileTag);
  16032. for (int i = 0; i < getAllProperties().size(); ++i)
  16033. {
  16034. XmlElement* const e = doc.createNewChildElement (PropertyFileConstants::valueTag);
  16035. e->setAttribute (PropertyFileConstants::nameAttribute, getAllProperties().getAllKeys() [i]);
  16036. // if the value seems to contain xml, store it as such..
  16037. XmlDocument xmlContent (getAllProperties().getAllValues() [i]);
  16038. XmlElement* const childElement = xmlContent.getDocumentElement();
  16039. if (childElement != 0)
  16040. e->addChildElement (childElement);
  16041. else
  16042. e->setAttribute (PropertyFileConstants::valueAttribute,
  16043. getAllProperties().getAllValues() [i]);
  16044. }
  16045. ProcessScopedLock pl (createProcessLock());
  16046. if (pl != 0 && ! pl->isLocked())
  16047. return false; // locking failure..
  16048. if (doc.writeToFile (file, String::empty))
  16049. {
  16050. needsWriting = false;
  16051. return true;
  16052. }
  16053. }
  16054. else
  16055. {
  16056. ProcessScopedLock pl (createProcessLock());
  16057. if (pl != 0 && ! pl->isLocked())
  16058. return false; // locking failure..
  16059. TemporaryFile tempFile (file);
  16060. ScopedPointer <OutputStream> out (tempFile.getFile().createOutputStream());
  16061. if (out != 0)
  16062. {
  16063. if ((options & storeAsCompressedBinary) != 0)
  16064. {
  16065. out->writeInt (PropertyFileConstants::magicNumberCompressed);
  16066. out->flush();
  16067. out = new GZIPCompressorOutputStream (out.release(), 9, true);
  16068. }
  16069. else
  16070. {
  16071. // have you set up the storage option flags correctly?
  16072. jassert ((options & storeAsBinary) != 0);
  16073. out->writeInt (PropertyFileConstants::magicNumber);
  16074. }
  16075. const int numProperties = getAllProperties().size();
  16076. out->writeInt (numProperties);
  16077. for (int i = 0; i < numProperties; ++i)
  16078. {
  16079. out->writeString (getAllProperties().getAllKeys() [i]);
  16080. out->writeString (getAllProperties().getAllValues() [i]);
  16081. }
  16082. out = 0;
  16083. if (tempFile.overwriteTargetFileWithTemporary())
  16084. {
  16085. needsWriting = false;
  16086. return true;
  16087. }
  16088. }
  16089. }
  16090. return false;
  16091. }
  16092. void PropertiesFile::timerCallback()
  16093. {
  16094. saveIfNeeded();
  16095. }
  16096. void PropertiesFile::propertyChanged()
  16097. {
  16098. sendChangeMessage (this);
  16099. needsWriting = true;
  16100. if (timerInterval > 0)
  16101. startTimer (timerInterval);
  16102. else if (timerInterval == 0)
  16103. saveIfNeeded();
  16104. }
  16105. const File PropertiesFile::getDefaultAppSettingsFile (const String& applicationName,
  16106. const String& fileNameSuffix,
  16107. const String& folderName,
  16108. const bool commonToAllUsers)
  16109. {
  16110. // mustn't have illegal characters in this name..
  16111. jassert (applicationName == File::createLegalFileName (applicationName));
  16112. #if JUCE_MAC || JUCE_IOS
  16113. File dir (commonToAllUsers ? "/Library/Preferences"
  16114. : "~/Library/Preferences");
  16115. if (folderName.isNotEmpty())
  16116. dir = dir.getChildFile (folderName);
  16117. #endif
  16118. #ifdef JUCE_LINUX
  16119. const File dir ((commonToAllUsers ? "/var/" : "~/")
  16120. + (folderName.isNotEmpty() ? folderName
  16121. : ("." + applicationName)));
  16122. #endif
  16123. #if JUCE_WINDOWS
  16124. File dir (File::getSpecialLocation (commonToAllUsers ? File::commonApplicationDataDirectory
  16125. : File::userApplicationDataDirectory));
  16126. if (dir == File::nonexistent)
  16127. return File::nonexistent;
  16128. dir = dir.getChildFile (folderName.isNotEmpty() ? folderName
  16129. : applicationName);
  16130. #endif
  16131. return dir.getChildFile (applicationName)
  16132. .withFileExtension (fileNameSuffix);
  16133. }
  16134. PropertiesFile* PropertiesFile::createDefaultAppPropertiesFile (const String& applicationName,
  16135. const String& fileNameSuffix,
  16136. const String& folderName,
  16137. const bool commonToAllUsers,
  16138. const int millisecondsBeforeSaving,
  16139. const int propertiesFileOptions,
  16140. InterProcessLock* processLock_)
  16141. {
  16142. const File file (getDefaultAppSettingsFile (applicationName,
  16143. fileNameSuffix,
  16144. folderName,
  16145. commonToAllUsers));
  16146. jassert (file != File::nonexistent);
  16147. if (file == File::nonexistent)
  16148. return 0;
  16149. return new PropertiesFile (file, millisecondsBeforeSaving, propertiesFileOptions,processLock_);
  16150. }
  16151. END_JUCE_NAMESPACE
  16152. /*** End of inlined file: juce_PropertiesFile.cpp ***/
  16153. /*** Start of inlined file: juce_FileBasedDocument.cpp ***/
  16154. BEGIN_JUCE_NAMESPACE
  16155. FileBasedDocument::FileBasedDocument (const String& fileExtension_,
  16156. const String& fileWildcard_,
  16157. const String& openFileDialogTitle_,
  16158. const String& saveFileDialogTitle_)
  16159. : changedSinceSave (false),
  16160. fileExtension (fileExtension_),
  16161. fileWildcard (fileWildcard_),
  16162. openFileDialogTitle (openFileDialogTitle_),
  16163. saveFileDialogTitle (saveFileDialogTitle_)
  16164. {
  16165. }
  16166. FileBasedDocument::~FileBasedDocument()
  16167. {
  16168. }
  16169. void FileBasedDocument::setChangedFlag (const bool hasChanged)
  16170. {
  16171. if (changedSinceSave != hasChanged)
  16172. {
  16173. changedSinceSave = hasChanged;
  16174. sendChangeMessage (this);
  16175. }
  16176. }
  16177. void FileBasedDocument::changed()
  16178. {
  16179. changedSinceSave = true;
  16180. sendChangeMessage (this);
  16181. }
  16182. void FileBasedDocument::setFile (const File& newFile)
  16183. {
  16184. if (documentFile != newFile)
  16185. {
  16186. documentFile = newFile;
  16187. changed();
  16188. }
  16189. }
  16190. bool FileBasedDocument::loadFrom (const File& newFile,
  16191. const bool showMessageOnFailure)
  16192. {
  16193. MouseCursor::showWaitCursor();
  16194. const File oldFile (documentFile);
  16195. documentFile = newFile;
  16196. String error;
  16197. if (newFile.existsAsFile())
  16198. {
  16199. error = loadDocument (newFile);
  16200. if (error.isEmpty())
  16201. {
  16202. setChangedFlag (false);
  16203. MouseCursor::hideWaitCursor();
  16204. setLastDocumentOpened (newFile);
  16205. return true;
  16206. }
  16207. }
  16208. else
  16209. {
  16210. error = "The file doesn't exist";
  16211. }
  16212. documentFile = oldFile;
  16213. MouseCursor::hideWaitCursor();
  16214. if (showMessageOnFailure)
  16215. {
  16216. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  16217. TRANS("Failed to open file..."),
  16218. TRANS("There was an error while trying to load the file:\n\n")
  16219. + newFile.getFullPathName()
  16220. + "\n\n"
  16221. + error);
  16222. }
  16223. return false;
  16224. }
  16225. bool FileBasedDocument::loadFromUserSpecifiedFile (const bool showMessageOnFailure)
  16226. {
  16227. FileChooser fc (openFileDialogTitle,
  16228. getLastDocumentOpened(),
  16229. fileWildcard);
  16230. if (fc.browseForFileToOpen())
  16231. return loadFrom (fc.getResult(), showMessageOnFailure);
  16232. return false;
  16233. }
  16234. FileBasedDocument::SaveResult FileBasedDocument::save (const bool askUserForFileIfNotSpecified,
  16235. const bool showMessageOnFailure)
  16236. {
  16237. return saveAs (documentFile,
  16238. false,
  16239. askUserForFileIfNotSpecified,
  16240. showMessageOnFailure);
  16241. }
  16242. FileBasedDocument::SaveResult FileBasedDocument::saveAs (const File& newFile,
  16243. const bool warnAboutOverwritingExistingFiles,
  16244. const bool askUserForFileIfNotSpecified,
  16245. const bool showMessageOnFailure)
  16246. {
  16247. if (newFile == File::nonexistent)
  16248. {
  16249. if (askUserForFileIfNotSpecified)
  16250. {
  16251. return saveAsInteractive (true);
  16252. }
  16253. else
  16254. {
  16255. // can't save to an unspecified file
  16256. jassertfalse;
  16257. return failedToWriteToFile;
  16258. }
  16259. }
  16260. if (warnAboutOverwritingExistingFiles && newFile.exists())
  16261. {
  16262. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  16263. TRANS("File already exists"),
  16264. TRANS("There's already a file called:\n\n")
  16265. + newFile.getFullPathName()
  16266. + TRANS("\n\nAre you sure you want to overwrite it?"),
  16267. TRANS("overwrite"),
  16268. TRANS("cancel")))
  16269. {
  16270. return userCancelledSave;
  16271. }
  16272. }
  16273. MouseCursor::showWaitCursor();
  16274. const File oldFile (documentFile);
  16275. documentFile = newFile;
  16276. String error (saveDocument (newFile));
  16277. if (error.isEmpty())
  16278. {
  16279. setChangedFlag (false);
  16280. MouseCursor::hideWaitCursor();
  16281. return savedOk;
  16282. }
  16283. documentFile = oldFile;
  16284. MouseCursor::hideWaitCursor();
  16285. if (showMessageOnFailure)
  16286. {
  16287. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  16288. TRANS("Error writing to file..."),
  16289. TRANS("An error occurred while trying to save \"")
  16290. + getDocumentTitle()
  16291. + TRANS("\" to the file:\n\n")
  16292. + newFile.getFullPathName()
  16293. + "\n\n"
  16294. + error);
  16295. }
  16296. return failedToWriteToFile;
  16297. }
  16298. FileBasedDocument::SaveResult FileBasedDocument::saveIfNeededAndUserAgrees()
  16299. {
  16300. if (! hasChangedSinceSaved())
  16301. return savedOk;
  16302. const int r = AlertWindow::showYesNoCancelBox (AlertWindow::QuestionIcon,
  16303. TRANS("Closing document..."),
  16304. TRANS("Do you want to save the changes to \"")
  16305. + getDocumentTitle() + "\"?",
  16306. TRANS("save"),
  16307. TRANS("discard changes"),
  16308. TRANS("cancel"));
  16309. if (r == 1)
  16310. {
  16311. // save changes
  16312. return save (true, true);
  16313. }
  16314. else if (r == 2)
  16315. {
  16316. // discard changes
  16317. return savedOk;
  16318. }
  16319. return userCancelledSave;
  16320. }
  16321. FileBasedDocument::SaveResult FileBasedDocument::saveAsInteractive (const bool warnAboutOverwritingExistingFiles)
  16322. {
  16323. File f;
  16324. if (documentFile.existsAsFile())
  16325. f = documentFile;
  16326. else
  16327. f = getLastDocumentOpened();
  16328. String legalFilename (File::createLegalFileName (getDocumentTitle()));
  16329. if (legalFilename.isEmpty())
  16330. legalFilename = "unnamed";
  16331. if (f.existsAsFile() || f.getParentDirectory().isDirectory())
  16332. f = f.getSiblingFile (legalFilename);
  16333. else
  16334. f = File::getSpecialLocation (File::userDocumentsDirectory).getChildFile (legalFilename);
  16335. f = f.withFileExtension (fileExtension)
  16336. .getNonexistentSibling (true);
  16337. FileChooser fc (saveFileDialogTitle, f, fileWildcard);
  16338. if (fc.browseForFileToSave (warnAboutOverwritingExistingFiles))
  16339. {
  16340. File chosen (fc.getResult());
  16341. if (chosen.getFileExtension().isEmpty())
  16342. {
  16343. chosen = chosen.withFileExtension (fileExtension);
  16344. if (chosen.exists())
  16345. {
  16346. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  16347. TRANS("File already exists"),
  16348. TRANS("There's already a file called:")
  16349. + "\n\n" + chosen.getFullPathName()
  16350. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  16351. TRANS("overwrite"),
  16352. TRANS("cancel")))
  16353. {
  16354. return userCancelledSave;
  16355. }
  16356. }
  16357. }
  16358. setLastDocumentOpened (chosen);
  16359. return saveAs (chosen, false, false, true);
  16360. }
  16361. return userCancelledSave;
  16362. }
  16363. END_JUCE_NAMESPACE
  16364. /*** End of inlined file: juce_FileBasedDocument.cpp ***/
  16365. /*** Start of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  16366. BEGIN_JUCE_NAMESPACE
  16367. RecentlyOpenedFilesList::RecentlyOpenedFilesList()
  16368. : maxNumberOfItems (10)
  16369. {
  16370. }
  16371. RecentlyOpenedFilesList::~RecentlyOpenedFilesList()
  16372. {
  16373. }
  16374. void RecentlyOpenedFilesList::setMaxNumberOfItems (const int newMaxNumber)
  16375. {
  16376. maxNumberOfItems = jmax (1, newMaxNumber);
  16377. while (getNumFiles() > maxNumberOfItems)
  16378. files.remove (getNumFiles() - 1);
  16379. }
  16380. int RecentlyOpenedFilesList::getNumFiles() const
  16381. {
  16382. return files.size();
  16383. }
  16384. const File RecentlyOpenedFilesList::getFile (const int index) const
  16385. {
  16386. return File (files [index]);
  16387. }
  16388. void RecentlyOpenedFilesList::clear()
  16389. {
  16390. files.clear();
  16391. }
  16392. void RecentlyOpenedFilesList::addFile (const File& file)
  16393. {
  16394. const String path (file.getFullPathName());
  16395. files.removeString (path, true);
  16396. files.insert (0, path);
  16397. setMaxNumberOfItems (maxNumberOfItems);
  16398. }
  16399. void RecentlyOpenedFilesList::removeNonExistentFiles()
  16400. {
  16401. for (int i = getNumFiles(); --i >= 0;)
  16402. if (! getFile(i).exists())
  16403. files.remove (i);
  16404. }
  16405. int RecentlyOpenedFilesList::createPopupMenuItems (PopupMenu& menuToAddTo,
  16406. const int baseItemId,
  16407. const bool showFullPaths,
  16408. const bool dontAddNonExistentFiles,
  16409. const File** filesToAvoid)
  16410. {
  16411. int num = 0;
  16412. for (int i = 0; i < getNumFiles(); ++i)
  16413. {
  16414. const File f (getFile(i));
  16415. if ((! dontAddNonExistentFiles) || f.exists())
  16416. {
  16417. bool needsAvoiding = false;
  16418. if (filesToAvoid != 0)
  16419. {
  16420. const File** avoid = filesToAvoid;
  16421. while (*avoid != 0)
  16422. {
  16423. if (f == **avoid)
  16424. {
  16425. needsAvoiding = true;
  16426. break;
  16427. }
  16428. ++avoid;
  16429. }
  16430. }
  16431. if (! needsAvoiding)
  16432. {
  16433. menuToAddTo.addItem (baseItemId + i,
  16434. showFullPaths ? f.getFullPathName()
  16435. : f.getFileName());
  16436. ++num;
  16437. }
  16438. }
  16439. }
  16440. return num;
  16441. }
  16442. const String RecentlyOpenedFilesList::toString() const
  16443. {
  16444. return files.joinIntoString ("\n");
  16445. }
  16446. void RecentlyOpenedFilesList::restoreFromString (const String& stringifiedVersion)
  16447. {
  16448. clear();
  16449. files.addLines (stringifiedVersion);
  16450. setMaxNumberOfItems (maxNumberOfItems);
  16451. }
  16452. END_JUCE_NAMESPACE
  16453. /*** End of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  16454. /*** Start of inlined file: juce_UndoManager.cpp ***/
  16455. BEGIN_JUCE_NAMESPACE
  16456. UndoManager::UndoManager (const int maxNumberOfUnitsToKeep,
  16457. const int minimumTransactions)
  16458. : totalUnitsStored (0),
  16459. nextIndex (0),
  16460. newTransaction (true),
  16461. reentrancyCheck (false)
  16462. {
  16463. setMaxNumberOfStoredUnits (maxNumberOfUnitsToKeep,
  16464. minimumTransactions);
  16465. }
  16466. UndoManager::~UndoManager()
  16467. {
  16468. clearUndoHistory();
  16469. }
  16470. void UndoManager::clearUndoHistory()
  16471. {
  16472. transactions.clear();
  16473. transactionNames.clear();
  16474. totalUnitsStored = 0;
  16475. nextIndex = 0;
  16476. sendChangeMessage (this);
  16477. }
  16478. int UndoManager::getNumberOfUnitsTakenUpByStoredCommands() const
  16479. {
  16480. return totalUnitsStored;
  16481. }
  16482. void UndoManager::setMaxNumberOfStoredUnits (const int maxNumberOfUnitsToKeep,
  16483. const int minimumTransactions)
  16484. {
  16485. maxNumUnitsToKeep = jmax (1, maxNumberOfUnitsToKeep);
  16486. minimumTransactionsToKeep = jmax (1, minimumTransactions);
  16487. }
  16488. bool UndoManager::perform (UndoableAction* const command_, const String& actionName)
  16489. {
  16490. if (command_ != 0)
  16491. {
  16492. ScopedPointer<UndoableAction> command (command_);
  16493. if (actionName.isNotEmpty())
  16494. currentTransactionName = actionName;
  16495. if (reentrancyCheck)
  16496. {
  16497. jassertfalse; // don't call perform() recursively from the UndoableAction::perform() or
  16498. // undo() methods, or else these actions won't actually get done.
  16499. return false;
  16500. }
  16501. else if (command->perform())
  16502. {
  16503. OwnedArray<UndoableAction>* commandSet = transactions [nextIndex - 1];
  16504. if (commandSet != 0 && ! newTransaction)
  16505. {
  16506. UndoableAction* lastAction = commandSet->getLast();
  16507. if (lastAction != 0)
  16508. {
  16509. UndoableAction* coalescedAction = lastAction->createCoalescedAction (command);
  16510. if (coalescedAction != 0)
  16511. {
  16512. command = coalescedAction;
  16513. totalUnitsStored -= lastAction->getSizeInUnits();
  16514. commandSet->removeLast();
  16515. }
  16516. }
  16517. }
  16518. else
  16519. {
  16520. commandSet = new OwnedArray<UndoableAction>();
  16521. transactions.insert (nextIndex, commandSet);
  16522. transactionNames.insert (nextIndex, currentTransactionName);
  16523. ++nextIndex;
  16524. }
  16525. totalUnitsStored += command->getSizeInUnits();
  16526. commandSet->add (command.release());
  16527. newTransaction = false;
  16528. while (nextIndex < transactions.size())
  16529. {
  16530. const OwnedArray <UndoableAction>* const lastSet = transactions.getLast();
  16531. for (int i = lastSet->size(); --i >= 0;)
  16532. totalUnitsStored -= lastSet->getUnchecked (i)->getSizeInUnits();
  16533. transactions.removeLast();
  16534. transactionNames.remove (transactionNames.size() - 1);
  16535. }
  16536. while (nextIndex > 0
  16537. && totalUnitsStored > maxNumUnitsToKeep
  16538. && transactions.size() > minimumTransactionsToKeep)
  16539. {
  16540. const OwnedArray <UndoableAction>* const firstSet = transactions.getFirst();
  16541. for (int i = firstSet->size(); --i >= 0;)
  16542. totalUnitsStored -= firstSet->getUnchecked (i)->getSizeInUnits();
  16543. jassert (totalUnitsStored >= 0); // something fishy going on if this fails!
  16544. transactions.remove (0);
  16545. transactionNames.remove (0);
  16546. --nextIndex;
  16547. }
  16548. sendChangeMessage (this);
  16549. return true;
  16550. }
  16551. }
  16552. return false;
  16553. }
  16554. void UndoManager::beginNewTransaction (const String& actionName)
  16555. {
  16556. newTransaction = true;
  16557. currentTransactionName = actionName;
  16558. }
  16559. void UndoManager::setCurrentTransactionName (const String& newName)
  16560. {
  16561. currentTransactionName = newName;
  16562. }
  16563. bool UndoManager::canUndo() const
  16564. {
  16565. return nextIndex > 0;
  16566. }
  16567. bool UndoManager::canRedo() const
  16568. {
  16569. return nextIndex < transactions.size();
  16570. }
  16571. const String UndoManager::getUndoDescription() const
  16572. {
  16573. return transactionNames [nextIndex - 1];
  16574. }
  16575. const String UndoManager::getRedoDescription() const
  16576. {
  16577. return transactionNames [nextIndex];
  16578. }
  16579. bool UndoManager::undo()
  16580. {
  16581. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16582. if (commandSet == 0)
  16583. return false;
  16584. reentrancyCheck = true;
  16585. bool failed = false;
  16586. for (int i = commandSet->size(); --i >= 0;)
  16587. {
  16588. if (! commandSet->getUnchecked(i)->undo())
  16589. {
  16590. jassertfalse;
  16591. failed = true;
  16592. break;
  16593. }
  16594. }
  16595. reentrancyCheck = false;
  16596. if (failed)
  16597. clearUndoHistory();
  16598. else
  16599. --nextIndex;
  16600. beginNewTransaction();
  16601. sendChangeMessage (this);
  16602. return true;
  16603. }
  16604. bool UndoManager::redo()
  16605. {
  16606. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex];
  16607. if (commandSet == 0)
  16608. return false;
  16609. reentrancyCheck = true;
  16610. bool failed = false;
  16611. for (int i = 0; i < commandSet->size(); ++i)
  16612. {
  16613. if (! commandSet->getUnchecked(i)->perform())
  16614. {
  16615. jassertfalse;
  16616. failed = true;
  16617. break;
  16618. }
  16619. }
  16620. reentrancyCheck = false;
  16621. if (failed)
  16622. clearUndoHistory();
  16623. else
  16624. ++nextIndex;
  16625. beginNewTransaction();
  16626. sendChangeMessage (this);
  16627. return true;
  16628. }
  16629. bool UndoManager::undoCurrentTransactionOnly()
  16630. {
  16631. return newTransaction ? false : undo();
  16632. }
  16633. void UndoManager::getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const
  16634. {
  16635. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16636. if (commandSet != 0 && ! newTransaction)
  16637. {
  16638. for (int i = 0; i < commandSet->size(); ++i)
  16639. actionsFound.add (commandSet->getUnchecked(i));
  16640. }
  16641. }
  16642. int UndoManager::getNumActionsInCurrentTransaction() const
  16643. {
  16644. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16645. if (commandSet != 0 && ! newTransaction)
  16646. return commandSet->size();
  16647. return 0;
  16648. }
  16649. END_JUCE_NAMESPACE
  16650. /*** End of inlined file: juce_UndoManager.cpp ***/
  16651. /*** Start of inlined file: juce_AiffAudioFormat.cpp ***/
  16652. BEGIN_JUCE_NAMESPACE
  16653. static const char* const aiffFormatName = "AIFF file";
  16654. static const char* const aiffExtensions[] = { ".aiff", ".aif", 0 };
  16655. class AiffAudioFormatReader : public AudioFormatReader
  16656. {
  16657. public:
  16658. int bytesPerFrame;
  16659. int64 dataChunkStart;
  16660. bool littleEndian;
  16661. AiffAudioFormatReader (InputStream* in)
  16662. : AudioFormatReader (in, TRANS (aiffFormatName))
  16663. {
  16664. if (input->readInt() == chunkName ("FORM"))
  16665. {
  16666. const int len = input->readIntBigEndian();
  16667. const int64 end = input->getPosition() + len;
  16668. const int nextType = input->readInt();
  16669. if (nextType == chunkName ("AIFF") || nextType == chunkName ("AIFC"))
  16670. {
  16671. bool hasGotVer = false;
  16672. bool hasGotData = false;
  16673. bool hasGotType = false;
  16674. while (input->getPosition() < end)
  16675. {
  16676. const int type = input->readInt();
  16677. const uint32 length = (uint32) input->readIntBigEndian();
  16678. const int64 chunkEnd = input->getPosition() + length;
  16679. if (type == chunkName ("FVER"))
  16680. {
  16681. hasGotVer = true;
  16682. const int ver = input->readIntBigEndian();
  16683. if (ver != 0 && ver != (int) 0xa2805140)
  16684. break;
  16685. }
  16686. else if (type == chunkName ("COMM"))
  16687. {
  16688. hasGotType = true;
  16689. numChannels = (unsigned int) input->readShortBigEndian();
  16690. lengthInSamples = input->readIntBigEndian();
  16691. bitsPerSample = input->readShortBigEndian();
  16692. bytesPerFrame = (numChannels * bitsPerSample) >> 3;
  16693. unsigned char sampleRateBytes[10];
  16694. input->read (sampleRateBytes, 10);
  16695. const int byte0 = sampleRateBytes[0];
  16696. if ((byte0 & 0x80) != 0
  16697. || byte0 <= 0x3F || byte0 > 0x40
  16698. || (byte0 == 0x40 && sampleRateBytes[1] > 0x1C))
  16699. break;
  16700. unsigned int sampRate = ByteOrder::bigEndianInt (sampleRateBytes + 2);
  16701. sampRate >>= (16414 - ByteOrder::bigEndianShort (sampleRateBytes));
  16702. sampleRate = (int) sampRate;
  16703. if (length <= 18)
  16704. {
  16705. // some types don't have a chunk large enough to include a compression
  16706. // type, so assume it's just big-endian pcm
  16707. littleEndian = false;
  16708. }
  16709. else
  16710. {
  16711. const int compType = input->readInt();
  16712. if (compType == chunkName ("NONE") || compType == chunkName ("twos"))
  16713. {
  16714. littleEndian = false;
  16715. }
  16716. else if (compType == chunkName ("sowt"))
  16717. {
  16718. littleEndian = true;
  16719. }
  16720. else
  16721. {
  16722. sampleRate = 0;
  16723. break;
  16724. }
  16725. }
  16726. }
  16727. else if (type == chunkName ("SSND"))
  16728. {
  16729. hasGotData = true;
  16730. const int offset = input->readIntBigEndian();
  16731. dataChunkStart = input->getPosition() + 4 + offset;
  16732. lengthInSamples = (bytesPerFrame > 0) ? jmin (lengthInSamples, (int64) (length / bytesPerFrame)) : 0;
  16733. }
  16734. else if ((hasGotVer && hasGotData && hasGotType)
  16735. || chunkEnd < input->getPosition()
  16736. || input->isExhausted())
  16737. {
  16738. break;
  16739. }
  16740. input->setPosition (chunkEnd);
  16741. }
  16742. }
  16743. }
  16744. }
  16745. ~AiffAudioFormatReader()
  16746. {
  16747. }
  16748. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  16749. int64 startSampleInFile, int numSamples)
  16750. {
  16751. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  16752. if (samplesAvailable < numSamples)
  16753. {
  16754. for (int i = numDestChannels; --i >= 0;)
  16755. if (destSamples[i] != 0)
  16756. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  16757. numSamples = (int) samplesAvailable;
  16758. }
  16759. if (numSamples <= 0)
  16760. return true;
  16761. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  16762. while (numSamples > 0)
  16763. {
  16764. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  16765. char tempBuffer [tempBufSize];
  16766. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  16767. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  16768. if (bytesRead < numThisTime * bytesPerFrame)
  16769. {
  16770. jassert (bytesRead >= 0);
  16771. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  16772. }
  16773. jassert (! usesFloatingPointData); // (would need to add support for this if it's possible)
  16774. if (littleEndian)
  16775. {
  16776. switch (bitsPerSample)
  16777. {
  16778. case 8: ReadHelper<AudioData::Int32, AudioData::Int8, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16779. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16780. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16781. case 32: ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16782. default: jassertfalse; break;
  16783. }
  16784. }
  16785. else
  16786. {
  16787. switch (bitsPerSample)
  16788. {
  16789. case 8: ReadHelper<AudioData::Int32, AudioData::Int8, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16790. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16791. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16792. case 32: ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16793. default: jassertfalse; break;
  16794. }
  16795. }
  16796. startOffsetInDestBuffer += numThisTime;
  16797. numSamples -= numThisTime;
  16798. }
  16799. return true;
  16800. }
  16801. juce_UseDebuggingNewOperator
  16802. private:
  16803. AiffAudioFormatReader (const AiffAudioFormatReader&);
  16804. AiffAudioFormatReader& operator= (const AiffAudioFormatReader&);
  16805. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  16806. };
  16807. class AiffAudioFormatWriter : public AudioFormatWriter
  16808. {
  16809. public:
  16810. AiffAudioFormatWriter (OutputStream* out, double sampleRate_, unsigned int numChans, int bits)
  16811. : AudioFormatWriter (out, TRANS (aiffFormatName), sampleRate_, numChans, bits),
  16812. lengthInSamples (0),
  16813. bytesWritten (0),
  16814. writeFailed (false)
  16815. {
  16816. headerPosition = out->getPosition();
  16817. writeHeader();
  16818. }
  16819. ~AiffAudioFormatWriter()
  16820. {
  16821. if ((bytesWritten & 1) != 0)
  16822. output->writeByte (0);
  16823. writeHeader();
  16824. }
  16825. bool write (const int** data, int numSamples)
  16826. {
  16827. jassert (data != 0 && *data != 0); // the input must contain at least one channel!
  16828. if (writeFailed)
  16829. return false;
  16830. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  16831. tempBlock.ensureSize (bytes, false);
  16832. switch (bitsPerSample)
  16833. {
  16834. case 8: WriteHelper<AudioData::Int8, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16835. case 16: WriteHelper<AudioData::Int16, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16836. case 24: WriteHelper<AudioData::Int24, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16837. case 32: WriteHelper<AudioData::Int32, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16838. default: jassertfalse; break;
  16839. }
  16840. if (bytesWritten + bytes >= (uint32) 0xfff00000
  16841. || ! output->write (tempBlock.getData(), bytes))
  16842. {
  16843. // failed to write to disk, so let's try writing the header.
  16844. // If it's just run out of disk space, then if it does manage
  16845. // to write the header, we'll still have a useable file..
  16846. writeHeader();
  16847. writeFailed = true;
  16848. return false;
  16849. }
  16850. else
  16851. {
  16852. bytesWritten += bytes;
  16853. lengthInSamples += numSamples;
  16854. return true;
  16855. }
  16856. }
  16857. juce_UseDebuggingNewOperator
  16858. private:
  16859. MemoryBlock tempBlock;
  16860. uint32 lengthInSamples, bytesWritten;
  16861. int64 headerPosition;
  16862. bool writeFailed;
  16863. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  16864. AiffAudioFormatWriter (const AiffAudioFormatWriter&);
  16865. AiffAudioFormatWriter& operator= (const AiffAudioFormatWriter&);
  16866. void writeHeader()
  16867. {
  16868. const bool couldSeekOk = output->setPosition (headerPosition);
  16869. (void) couldSeekOk;
  16870. // if this fails, you've given it an output stream that can't seek! It needs
  16871. // to be able to seek back to write the header
  16872. jassert (couldSeekOk);
  16873. const int headerLen = 54;
  16874. int audioBytes = lengthInSamples * ((bitsPerSample * numChannels) / 8);
  16875. audioBytes += (audioBytes & 1);
  16876. output->writeInt (chunkName ("FORM"));
  16877. output->writeIntBigEndian (headerLen + audioBytes - 8);
  16878. output->writeInt (chunkName ("AIFF"));
  16879. output->writeInt (chunkName ("COMM"));
  16880. output->writeIntBigEndian (18);
  16881. output->writeShortBigEndian ((short) numChannels);
  16882. output->writeIntBigEndian (lengthInSamples);
  16883. output->writeShortBigEndian ((short) bitsPerSample);
  16884. uint8 sampleRateBytes[10];
  16885. zeromem (sampleRateBytes, 10);
  16886. if (sampleRate <= 1)
  16887. {
  16888. sampleRateBytes[0] = 0x3f;
  16889. sampleRateBytes[1] = 0xff;
  16890. sampleRateBytes[2] = 0x80;
  16891. }
  16892. else
  16893. {
  16894. int mask = 0x40000000;
  16895. sampleRateBytes[0] = 0x40;
  16896. if (sampleRate >= mask)
  16897. {
  16898. jassertfalse;
  16899. sampleRateBytes[1] = 0x1d;
  16900. }
  16901. else
  16902. {
  16903. int n = (int) sampleRate;
  16904. int i;
  16905. for (i = 0; i <= 32 ; ++i)
  16906. {
  16907. if ((n & mask) != 0)
  16908. break;
  16909. mask >>= 1;
  16910. }
  16911. n = n << (i + 1);
  16912. sampleRateBytes[1] = (uint8) (29 - i);
  16913. sampleRateBytes[2] = (uint8) ((n >> 24) & 0xff);
  16914. sampleRateBytes[3] = (uint8) ((n >> 16) & 0xff);
  16915. sampleRateBytes[4] = (uint8) ((n >> 8) & 0xff);
  16916. sampleRateBytes[5] = (uint8) (n & 0xff);
  16917. }
  16918. }
  16919. output->write (sampleRateBytes, 10);
  16920. output->writeInt (chunkName ("SSND"));
  16921. output->writeIntBigEndian (audioBytes + 8);
  16922. output->writeInt (0);
  16923. output->writeInt (0);
  16924. jassert (output->getPosition() == headerLen);
  16925. }
  16926. };
  16927. AiffAudioFormat::AiffAudioFormat()
  16928. : AudioFormat (TRANS (aiffFormatName), StringArray (aiffExtensions))
  16929. {
  16930. }
  16931. AiffAudioFormat::~AiffAudioFormat()
  16932. {
  16933. }
  16934. const Array <int> AiffAudioFormat::getPossibleSampleRates()
  16935. {
  16936. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  16937. return Array <int> (rates);
  16938. }
  16939. const Array <int> AiffAudioFormat::getPossibleBitDepths()
  16940. {
  16941. const int depths[] = { 8, 16, 24, 0 };
  16942. return Array <int> (depths);
  16943. }
  16944. bool AiffAudioFormat::canDoStereo() { return true; }
  16945. bool AiffAudioFormat::canDoMono() { return true; }
  16946. #if JUCE_MAC
  16947. bool AiffAudioFormat::canHandleFile (const File& f)
  16948. {
  16949. if (AudioFormat::canHandleFile (f))
  16950. return true;
  16951. const OSType type = PlatformUtilities::getTypeOfFile (f.getFullPathName());
  16952. return type == 'AIFF' || type == 'AIFC'
  16953. || type == 'aiff' || type == 'aifc';
  16954. }
  16955. #endif
  16956. AudioFormatReader* AiffAudioFormat::createReaderFor (InputStream* sourceStream, const bool deleteStreamIfOpeningFails)
  16957. {
  16958. ScopedPointer <AiffAudioFormatReader> w (new AiffAudioFormatReader (sourceStream));
  16959. if (w->sampleRate != 0)
  16960. return w.release();
  16961. if (! deleteStreamIfOpeningFails)
  16962. w->input = 0;
  16963. return 0;
  16964. }
  16965. AudioFormatWriter* AiffAudioFormat::createWriterFor (OutputStream* out,
  16966. double sampleRate,
  16967. unsigned int numberOfChannels,
  16968. int bitsPerSample,
  16969. const StringPairArray& /*metadataValues*/,
  16970. int /*qualityOptionIndex*/)
  16971. {
  16972. if (getPossibleBitDepths().contains (bitsPerSample))
  16973. return new AiffAudioFormatWriter (out, sampleRate, numberOfChannels, bitsPerSample);
  16974. return 0;
  16975. }
  16976. END_JUCE_NAMESPACE
  16977. /*** End of inlined file: juce_AiffAudioFormat.cpp ***/
  16978. /*** Start of inlined file: juce_AudioFormat.cpp ***/
  16979. BEGIN_JUCE_NAMESPACE
  16980. AudioFormat::AudioFormat (const String& name, const StringArray& extensions)
  16981. : formatName (name),
  16982. fileExtensions (extensions)
  16983. {
  16984. }
  16985. AudioFormat::~AudioFormat()
  16986. {
  16987. }
  16988. bool AudioFormat::canHandleFile (const File& f)
  16989. {
  16990. for (int i = 0; i < fileExtensions.size(); ++i)
  16991. if (f.hasFileExtension (fileExtensions[i]))
  16992. return true;
  16993. return false;
  16994. }
  16995. const String& AudioFormat::getFormatName() const { return formatName; }
  16996. const StringArray& AudioFormat::getFileExtensions() const { return fileExtensions; }
  16997. bool AudioFormat::isCompressed() { return false; }
  16998. const StringArray AudioFormat::getQualityOptions() { return StringArray(); }
  16999. END_JUCE_NAMESPACE
  17000. /*** End of inlined file: juce_AudioFormat.cpp ***/
  17001. /*** Start of inlined file: juce_AudioFormatReader.cpp ***/
  17002. BEGIN_JUCE_NAMESPACE
  17003. AudioFormatReader::AudioFormatReader (InputStream* const in,
  17004. const String& formatName_)
  17005. : sampleRate (0),
  17006. bitsPerSample (0),
  17007. lengthInSamples (0),
  17008. numChannels (0),
  17009. usesFloatingPointData (false),
  17010. input (in),
  17011. formatName (formatName_)
  17012. {
  17013. }
  17014. AudioFormatReader::~AudioFormatReader()
  17015. {
  17016. delete input;
  17017. }
  17018. bool AudioFormatReader::read (int* const* destSamples,
  17019. int numDestChannels,
  17020. int64 startSampleInSource,
  17021. int numSamplesToRead,
  17022. const bool fillLeftoverChannelsWithCopies)
  17023. {
  17024. jassert (numDestChannels > 0); // you have to actually give this some channels to work with!
  17025. int startOffsetInDestBuffer = 0;
  17026. if (startSampleInSource < 0)
  17027. {
  17028. const int silence = (int) jmin (-startSampleInSource, (int64) numSamplesToRead);
  17029. for (int i = numDestChannels; --i >= 0;)
  17030. if (destSamples[i] != 0)
  17031. zeromem (destSamples[i], sizeof (int) * silence);
  17032. startOffsetInDestBuffer += silence;
  17033. numSamplesToRead -= silence;
  17034. startSampleInSource = 0;
  17035. }
  17036. if (numSamplesToRead <= 0)
  17037. return true;
  17038. if (! readSamples (const_cast<int**> (destSamples),
  17039. jmin ((int) numChannels, numDestChannels), startOffsetInDestBuffer,
  17040. startSampleInSource, numSamplesToRead))
  17041. return false;
  17042. if (numDestChannels > (int) numChannels)
  17043. {
  17044. if (fillLeftoverChannelsWithCopies)
  17045. {
  17046. int* lastFullChannel = destSamples[0];
  17047. for (int i = (int) numChannels; --i > 0;)
  17048. {
  17049. if (destSamples[i] != 0)
  17050. {
  17051. lastFullChannel = destSamples[i];
  17052. break;
  17053. }
  17054. }
  17055. if (lastFullChannel != 0)
  17056. for (int i = numChannels; i < numDestChannels; ++i)
  17057. if (destSamples[i] != 0)
  17058. memcpy (destSamples[i], lastFullChannel, sizeof (int) * numSamplesToRead);
  17059. }
  17060. else
  17061. {
  17062. for (int i = numChannels; i < numDestChannels; ++i)
  17063. if (destSamples[i] != 0)
  17064. zeromem (destSamples[i], sizeof (int) * numSamplesToRead);
  17065. }
  17066. }
  17067. return true;
  17068. }
  17069. static void findAudioBufferMaxMin (const float* const buffer, const int num, float& maxVal, float& minVal) throw()
  17070. {
  17071. float mn = buffer[0];
  17072. float mx = mn;
  17073. for (int i = 1; i < num; ++i)
  17074. {
  17075. const float s = buffer[i];
  17076. if (s > mx) mx = s;
  17077. if (s < mn) mn = s;
  17078. }
  17079. maxVal = mx;
  17080. minVal = mn;
  17081. }
  17082. void AudioFormatReader::readMaxLevels (int64 startSampleInFile,
  17083. int64 numSamples,
  17084. float& lowestLeft, float& highestLeft,
  17085. float& lowestRight, float& highestRight)
  17086. {
  17087. if (numSamples <= 0)
  17088. {
  17089. lowestLeft = 0;
  17090. lowestRight = 0;
  17091. highestLeft = 0;
  17092. highestRight = 0;
  17093. return;
  17094. }
  17095. const int bufferSize = (int) jmin (numSamples, (int64) 4096);
  17096. HeapBlock<int> tempSpace (bufferSize * 2 + 64);
  17097. int* tempBuffer[3];
  17098. tempBuffer[0] = tempSpace.getData();
  17099. tempBuffer[1] = tempSpace.getData() + bufferSize;
  17100. tempBuffer[2] = 0;
  17101. if (usesFloatingPointData)
  17102. {
  17103. float lmin = 1.0e6f;
  17104. float lmax = -lmin;
  17105. float rmin = lmin;
  17106. float rmax = lmax;
  17107. while (numSamples > 0)
  17108. {
  17109. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  17110. read (tempBuffer, 2, startSampleInFile, numToDo, false);
  17111. numSamples -= numToDo;
  17112. startSampleInFile += numToDo;
  17113. float bufmin, bufmax;
  17114. findAudioBufferMaxMin (reinterpret_cast<float*> (tempBuffer[0]), numToDo, bufmax, bufmin);
  17115. lmin = jmin (lmin, bufmin);
  17116. lmax = jmax (lmax, bufmax);
  17117. if (numChannels > 1)
  17118. {
  17119. findAudioBufferMaxMin (reinterpret_cast<float*> (tempBuffer[1]), numToDo, bufmax, bufmin);
  17120. rmin = jmin (rmin, bufmin);
  17121. rmax = jmax (rmax, bufmax);
  17122. }
  17123. }
  17124. if (numChannels <= 1)
  17125. {
  17126. rmax = lmax;
  17127. rmin = lmin;
  17128. }
  17129. lowestLeft = lmin;
  17130. highestLeft = lmax;
  17131. lowestRight = rmin;
  17132. highestRight = rmax;
  17133. }
  17134. else
  17135. {
  17136. int lmax = std::numeric_limits<int>::min();
  17137. int lmin = std::numeric_limits<int>::max();
  17138. int rmax = std::numeric_limits<int>::min();
  17139. int rmin = std::numeric_limits<int>::max();
  17140. while (numSamples > 0)
  17141. {
  17142. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  17143. read (tempBuffer, 2, startSampleInFile, numToDo, false);
  17144. numSamples -= numToDo;
  17145. startSampleInFile += numToDo;
  17146. for (int j = numChannels; --j >= 0;)
  17147. {
  17148. int bufMax = std::numeric_limits<int>::min();
  17149. int bufMin = std::numeric_limits<int>::max();
  17150. const int* const b = tempBuffer[j];
  17151. for (int i = 0; i < numToDo; ++i)
  17152. {
  17153. const int samp = b[i];
  17154. if (samp < bufMin)
  17155. bufMin = samp;
  17156. if (samp > bufMax)
  17157. bufMax = samp;
  17158. }
  17159. if (j == 0)
  17160. {
  17161. lmax = jmax (lmax, bufMax);
  17162. lmin = jmin (lmin, bufMin);
  17163. }
  17164. else
  17165. {
  17166. rmax = jmax (rmax, bufMax);
  17167. rmin = jmin (rmin, bufMin);
  17168. }
  17169. }
  17170. }
  17171. if (numChannels <= 1)
  17172. {
  17173. rmax = lmax;
  17174. rmin = lmin;
  17175. }
  17176. lowestLeft = lmin / (float) std::numeric_limits<int>::max();
  17177. highestLeft = lmax / (float) std::numeric_limits<int>::max();
  17178. lowestRight = rmin / (float) std::numeric_limits<int>::max();
  17179. highestRight = rmax / (float) std::numeric_limits<int>::max();
  17180. }
  17181. }
  17182. int64 AudioFormatReader::searchForLevel (int64 startSample,
  17183. int64 numSamplesToSearch,
  17184. const double magnitudeRangeMinimum,
  17185. const double magnitudeRangeMaximum,
  17186. const int minimumConsecutiveSamples)
  17187. {
  17188. if (numSamplesToSearch == 0)
  17189. return -1;
  17190. const int bufferSize = 4096;
  17191. HeapBlock<int> tempSpace (bufferSize * 2 + 64);
  17192. int* tempBuffer[3];
  17193. tempBuffer[0] = tempSpace.getData();
  17194. tempBuffer[1] = tempSpace.getData() + bufferSize;
  17195. tempBuffer[2] = 0;
  17196. int consecutive = 0;
  17197. int64 firstMatchPos = -1;
  17198. jassert (magnitudeRangeMaximum > magnitudeRangeMinimum);
  17199. const double doubleMin = jlimit (0.0, (double) std::numeric_limits<int>::max(), magnitudeRangeMinimum * std::numeric_limits<int>::max());
  17200. const double doubleMax = jlimit (doubleMin, (double) std::numeric_limits<int>::max(), magnitudeRangeMaximum * std::numeric_limits<int>::max());
  17201. const int intMagnitudeRangeMinimum = roundToInt (doubleMin);
  17202. const int intMagnitudeRangeMaximum = roundToInt (doubleMax);
  17203. while (numSamplesToSearch != 0)
  17204. {
  17205. const int numThisTime = (int) jmin (abs64 (numSamplesToSearch), (int64) bufferSize);
  17206. int64 bufferStart = startSample;
  17207. if (numSamplesToSearch < 0)
  17208. bufferStart -= numThisTime;
  17209. if (bufferStart >= (int) lengthInSamples)
  17210. break;
  17211. read (tempBuffer, 2, bufferStart, numThisTime, false);
  17212. int num = numThisTime;
  17213. while (--num >= 0)
  17214. {
  17215. if (numSamplesToSearch < 0)
  17216. --startSample;
  17217. bool matches = false;
  17218. const int index = (int) (startSample - bufferStart);
  17219. if (usesFloatingPointData)
  17220. {
  17221. const float sample1 = std::abs (((float*) tempBuffer[0]) [index]);
  17222. if (sample1 >= magnitudeRangeMinimum
  17223. && sample1 <= magnitudeRangeMaximum)
  17224. {
  17225. matches = true;
  17226. }
  17227. else if (numChannels > 1)
  17228. {
  17229. const float sample2 = std::abs (((float*) tempBuffer[1]) [index]);
  17230. matches = (sample2 >= magnitudeRangeMinimum
  17231. && sample2 <= magnitudeRangeMaximum);
  17232. }
  17233. }
  17234. else
  17235. {
  17236. const int sample1 = abs (tempBuffer[0] [index]);
  17237. if (sample1 >= intMagnitudeRangeMinimum
  17238. && sample1 <= intMagnitudeRangeMaximum)
  17239. {
  17240. matches = true;
  17241. }
  17242. else if (numChannels > 1)
  17243. {
  17244. const int sample2 = abs (tempBuffer[1][index]);
  17245. matches = (sample2 >= intMagnitudeRangeMinimum
  17246. && sample2 <= intMagnitudeRangeMaximum);
  17247. }
  17248. }
  17249. if (matches)
  17250. {
  17251. if (firstMatchPos < 0)
  17252. firstMatchPos = startSample;
  17253. if (++consecutive >= minimumConsecutiveSamples)
  17254. {
  17255. if (firstMatchPos < 0 || firstMatchPos >= lengthInSamples)
  17256. return -1;
  17257. return firstMatchPos;
  17258. }
  17259. }
  17260. else
  17261. {
  17262. consecutive = 0;
  17263. firstMatchPos = -1;
  17264. }
  17265. if (numSamplesToSearch > 0)
  17266. ++startSample;
  17267. }
  17268. if (numSamplesToSearch > 0)
  17269. numSamplesToSearch -= numThisTime;
  17270. else
  17271. numSamplesToSearch += numThisTime;
  17272. }
  17273. return -1;
  17274. }
  17275. END_JUCE_NAMESPACE
  17276. /*** End of inlined file: juce_AudioFormatReader.cpp ***/
  17277. /*** Start of inlined file: juce_AudioFormatWriter.cpp ***/
  17278. BEGIN_JUCE_NAMESPACE
  17279. AudioFormatWriter::AudioFormatWriter (OutputStream* const out,
  17280. const String& formatName_,
  17281. const double rate,
  17282. const unsigned int numChannels_,
  17283. const unsigned int bitsPerSample_)
  17284. : sampleRate (rate),
  17285. numChannels (numChannels_),
  17286. bitsPerSample (bitsPerSample_),
  17287. usesFloatingPointData (false),
  17288. output (out),
  17289. formatName (formatName_)
  17290. {
  17291. }
  17292. AudioFormatWriter::~AudioFormatWriter()
  17293. {
  17294. delete output;
  17295. }
  17296. bool AudioFormatWriter::writeFromAudioReader (AudioFormatReader& reader,
  17297. int64 startSample,
  17298. int64 numSamplesToRead)
  17299. {
  17300. const int bufferSize = 16384;
  17301. AudioSampleBuffer tempBuffer (numChannels, bufferSize);
  17302. int* buffers [128];
  17303. zerostruct (buffers);
  17304. for (int i = tempBuffer.getNumChannels(); --i >= 0;)
  17305. buffers[i] = reinterpret_cast<int*> (tempBuffer.getSampleData (i, 0));
  17306. if (numSamplesToRead < 0)
  17307. numSamplesToRead = reader.lengthInSamples;
  17308. while (numSamplesToRead > 0)
  17309. {
  17310. const int numToDo = (int) jmin (numSamplesToRead, (int64) bufferSize);
  17311. if (! reader.read (buffers, numChannels, startSample, numToDo, false))
  17312. return false;
  17313. if (reader.usesFloatingPointData != isFloatingPoint())
  17314. {
  17315. int** bufferChan = buffers;
  17316. while (*bufferChan != 0)
  17317. {
  17318. int* b = *bufferChan++;
  17319. if (isFloatingPoint())
  17320. {
  17321. // int -> float
  17322. const double factor = 1.0 / std::numeric_limits<int>::max();
  17323. for (int i = 0; i < numToDo; ++i)
  17324. ((float*) b)[i] = (float) (factor * b[i]);
  17325. }
  17326. else
  17327. {
  17328. // float -> int
  17329. for (int i = 0; i < numToDo; ++i)
  17330. {
  17331. const double samp = *(const float*) b;
  17332. if (samp <= -1.0)
  17333. *b++ = std::numeric_limits<int>::min();
  17334. else if (samp >= 1.0)
  17335. *b++ = std::numeric_limits<int>::max();
  17336. else
  17337. *b++ = roundToInt (std::numeric_limits<int>::max() * samp);
  17338. }
  17339. }
  17340. }
  17341. }
  17342. if (! write (const_cast<const int**> (buffers), numToDo))
  17343. return false;
  17344. numSamplesToRead -= numToDo;
  17345. startSample += numToDo;
  17346. }
  17347. return true;
  17348. }
  17349. bool AudioFormatWriter::writeFromAudioSource (AudioSource& source, int numSamplesToRead, const int samplesPerBlock)
  17350. {
  17351. AudioSampleBuffer tempBuffer (getNumChannels(), samplesPerBlock);
  17352. while (numSamplesToRead > 0)
  17353. {
  17354. const int numToDo = jmin (numSamplesToRead, samplesPerBlock);
  17355. AudioSourceChannelInfo info;
  17356. info.buffer = &tempBuffer;
  17357. info.startSample = 0;
  17358. info.numSamples = numToDo;
  17359. info.clearActiveBufferRegion();
  17360. source.getNextAudioBlock (info);
  17361. if (! writeFromAudioSampleBuffer (tempBuffer, 0, numToDo))
  17362. return false;
  17363. numSamplesToRead -= numToDo;
  17364. }
  17365. return true;
  17366. }
  17367. bool AudioFormatWriter::writeFromAudioSampleBuffer (const AudioSampleBuffer& source, int startSample, int numSamples)
  17368. {
  17369. jassert (startSample >= 0 && startSample + numSamples <= source.getNumSamples() && source.getNumChannels() > 0);
  17370. if (numSamples <= 0)
  17371. return true;
  17372. HeapBlock<int> tempBuffer;
  17373. HeapBlock<int*> chans (numChannels + 1);
  17374. chans [numChannels] = 0;
  17375. if (isFloatingPoint())
  17376. {
  17377. for (int i = numChannels; --i >= 0;)
  17378. chans[i] = reinterpret_cast<int*> (source.getSampleData (i, startSample));
  17379. }
  17380. else
  17381. {
  17382. tempBuffer.malloc (numSamples * numChannels);
  17383. for (unsigned int i = 0; i < numChannels; ++i)
  17384. {
  17385. typedef AudioData::Pointer <AudioData::Int32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> DestSampleType;
  17386. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> SourceSampleType;
  17387. DestSampleType destData (chans[i] = tempBuffer + i * numSamples);
  17388. SourceSampleType sourceData (source.getSampleData (i, startSample));
  17389. destData.convertSamples (sourceData, numSamples);
  17390. }
  17391. }
  17392. return write ((const int**) chans.getData(), numSamples);
  17393. }
  17394. class AudioFormatWriter::ThreadedWriter::Buffer : public TimeSliceClient,
  17395. public AbstractFifo
  17396. {
  17397. public:
  17398. Buffer (TimeSliceThread& timeSliceThread_, AudioFormatWriter* writer_, int numChannels, int bufferSize)
  17399. : AbstractFifo (bufferSize),
  17400. buffer (numChannels, bufferSize),
  17401. timeSliceThread (timeSliceThread_),
  17402. writer (writer_), isRunning (true)
  17403. {
  17404. timeSliceThread.addTimeSliceClient (this);
  17405. }
  17406. ~Buffer()
  17407. {
  17408. isRunning = false;
  17409. timeSliceThread.removeTimeSliceClient (this);
  17410. while (useTimeSlice())
  17411. {}
  17412. }
  17413. bool write (const float** data, int numSamples)
  17414. {
  17415. if (numSamples <= 0 || ! isRunning)
  17416. return true;
  17417. jassert (timeSliceThread.isThreadRunning()); // you need to get your thread running before pumping data into this!
  17418. int start1, size1, start2, size2;
  17419. prepareToWrite (numSamples, start1, size1, start2, size2);
  17420. if (size1 + size2 < numSamples)
  17421. return false;
  17422. for (int i = buffer.getNumChannels(); --i >= 0;)
  17423. {
  17424. buffer.copyFrom (i, start1, data[i], size1);
  17425. buffer.copyFrom (i, start2, data[i] + size1, size2);
  17426. }
  17427. finishedWrite (size1 + size2);
  17428. timeSliceThread.notify();
  17429. return true;
  17430. }
  17431. bool useTimeSlice()
  17432. {
  17433. const int numToDo = getTotalSize() / 4;
  17434. int start1, size1, start2, size2;
  17435. prepareToRead (numToDo, start1, size1, start2, size2);
  17436. if (size1 <= 0)
  17437. return false;
  17438. writer->writeFromAudioSampleBuffer (buffer, start1, size1);
  17439. if (size2 > 0)
  17440. writer->writeFromAudioSampleBuffer (buffer, start2, size2);
  17441. finishedRead (size1 + size2);
  17442. return true;
  17443. }
  17444. private:
  17445. AudioSampleBuffer buffer;
  17446. TimeSliceThread& timeSliceThread;
  17447. ScopedPointer<AudioFormatWriter> writer;
  17448. volatile bool isRunning;
  17449. Buffer (const Buffer&);
  17450. Buffer& operator= (const Buffer&);
  17451. };
  17452. AudioFormatWriter::ThreadedWriter::ThreadedWriter (AudioFormatWriter* writer, TimeSliceThread& backgroundThread, int numSamplesToBuffer)
  17453. : buffer (new AudioFormatWriter::ThreadedWriter::Buffer (backgroundThread, writer, writer->numChannels, numSamplesToBuffer))
  17454. {
  17455. }
  17456. AudioFormatWriter::ThreadedWriter::~ThreadedWriter()
  17457. {
  17458. }
  17459. bool AudioFormatWriter::ThreadedWriter::write (const float** data, int numSamples)
  17460. {
  17461. return buffer->write (data, numSamples);
  17462. }
  17463. END_JUCE_NAMESPACE
  17464. /*** End of inlined file: juce_AudioFormatWriter.cpp ***/
  17465. /*** Start of inlined file: juce_AudioFormatManager.cpp ***/
  17466. BEGIN_JUCE_NAMESPACE
  17467. AudioFormatManager::AudioFormatManager()
  17468. : defaultFormatIndex (0)
  17469. {
  17470. }
  17471. AudioFormatManager::~AudioFormatManager()
  17472. {
  17473. clearFormats();
  17474. clearSingletonInstance();
  17475. }
  17476. juce_ImplementSingleton (AudioFormatManager);
  17477. void AudioFormatManager::registerFormat (AudioFormat* newFormat,
  17478. const bool makeThisTheDefaultFormat)
  17479. {
  17480. jassert (newFormat != 0);
  17481. if (newFormat != 0)
  17482. {
  17483. #if JUCE_DEBUG
  17484. for (int i = getNumKnownFormats(); --i >= 0;)
  17485. {
  17486. if (getKnownFormat (i)->getFormatName() == newFormat->getFormatName())
  17487. {
  17488. jassertfalse; // trying to add the same format twice!
  17489. }
  17490. }
  17491. #endif
  17492. if (makeThisTheDefaultFormat)
  17493. defaultFormatIndex = getNumKnownFormats();
  17494. knownFormats.add (newFormat);
  17495. }
  17496. }
  17497. void AudioFormatManager::registerBasicFormats()
  17498. {
  17499. #if JUCE_MAC
  17500. registerFormat (new AiffAudioFormat(), true);
  17501. registerFormat (new WavAudioFormat(), false);
  17502. #else
  17503. registerFormat (new WavAudioFormat(), true);
  17504. registerFormat (new AiffAudioFormat(), false);
  17505. #endif
  17506. #if JUCE_USE_FLAC
  17507. registerFormat (new FlacAudioFormat(), false);
  17508. #endif
  17509. #if JUCE_USE_OGGVORBIS
  17510. registerFormat (new OggVorbisAudioFormat(), false);
  17511. #endif
  17512. }
  17513. void AudioFormatManager::clearFormats()
  17514. {
  17515. knownFormats.clear();
  17516. defaultFormatIndex = 0;
  17517. }
  17518. int AudioFormatManager::getNumKnownFormats() const
  17519. {
  17520. return knownFormats.size();
  17521. }
  17522. AudioFormat* AudioFormatManager::getKnownFormat (const int index) const
  17523. {
  17524. return knownFormats [index];
  17525. }
  17526. AudioFormat* AudioFormatManager::getDefaultFormat() const
  17527. {
  17528. return getKnownFormat (defaultFormatIndex);
  17529. }
  17530. AudioFormat* AudioFormatManager::findFormatForFileExtension (const String& fileExtension) const
  17531. {
  17532. String e (fileExtension);
  17533. if (! e.startsWithChar ('.'))
  17534. e = "." + e;
  17535. for (int i = 0; i < getNumKnownFormats(); ++i)
  17536. if (getKnownFormat(i)->getFileExtensions().contains (e, true))
  17537. return getKnownFormat(i);
  17538. return 0;
  17539. }
  17540. const String AudioFormatManager::getWildcardForAllFormats() const
  17541. {
  17542. StringArray allExtensions;
  17543. int i;
  17544. for (i = 0; i < getNumKnownFormats(); ++i)
  17545. allExtensions.addArray (getKnownFormat (i)->getFileExtensions());
  17546. allExtensions.trim();
  17547. allExtensions.removeEmptyStrings();
  17548. String s;
  17549. for (i = 0; i < allExtensions.size(); ++i)
  17550. {
  17551. s << '*';
  17552. if (! allExtensions[i].startsWithChar ('.'))
  17553. s << '.';
  17554. s << allExtensions[i];
  17555. if (i < allExtensions.size() - 1)
  17556. s << ';';
  17557. }
  17558. return s;
  17559. }
  17560. AudioFormatReader* AudioFormatManager::createReaderFor (const File& file)
  17561. {
  17562. // you need to actually register some formats before the manager can
  17563. // use them to open a file!
  17564. jassert (getNumKnownFormats() > 0);
  17565. for (int i = 0; i < getNumKnownFormats(); ++i)
  17566. {
  17567. AudioFormat* const af = getKnownFormat(i);
  17568. if (af->canHandleFile (file))
  17569. {
  17570. InputStream* const in = file.createInputStream();
  17571. if (in != 0)
  17572. {
  17573. AudioFormatReader* const r = af->createReaderFor (in, true);
  17574. if (r != 0)
  17575. return r;
  17576. }
  17577. }
  17578. }
  17579. return 0;
  17580. }
  17581. AudioFormatReader* AudioFormatManager::createReaderFor (InputStream* audioFileStream)
  17582. {
  17583. // you need to actually register some formats before the manager can
  17584. // use them to open a file!
  17585. jassert (getNumKnownFormats() > 0);
  17586. ScopedPointer <InputStream> in (audioFileStream);
  17587. if (in != 0)
  17588. {
  17589. const int64 originalStreamPos = in->getPosition();
  17590. for (int i = 0; i < getNumKnownFormats(); ++i)
  17591. {
  17592. AudioFormatReader* const r = getKnownFormat(i)->createReaderFor (in, false);
  17593. if (r != 0)
  17594. {
  17595. in.release();
  17596. return r;
  17597. }
  17598. in->setPosition (originalStreamPos);
  17599. // the stream that is passed-in must be capable of being repositioned so
  17600. // that all the formats can have a go at opening it.
  17601. jassert (in->getPosition() == originalStreamPos);
  17602. }
  17603. }
  17604. return 0;
  17605. }
  17606. END_JUCE_NAMESPACE
  17607. /*** End of inlined file: juce_AudioFormatManager.cpp ***/
  17608. /*** Start of inlined file: juce_AudioSubsectionReader.cpp ***/
  17609. BEGIN_JUCE_NAMESPACE
  17610. AudioSubsectionReader::AudioSubsectionReader (AudioFormatReader* const source_,
  17611. const int64 startSample_,
  17612. const int64 length_,
  17613. const bool deleteSourceWhenDeleted_)
  17614. : AudioFormatReader (0, source_->getFormatName()),
  17615. source (source_),
  17616. startSample (startSample_),
  17617. deleteSourceWhenDeleted (deleteSourceWhenDeleted_)
  17618. {
  17619. length = jmin (jmax ((int64) 0, source->lengthInSamples - startSample), length_);
  17620. sampleRate = source->sampleRate;
  17621. bitsPerSample = source->bitsPerSample;
  17622. lengthInSamples = length;
  17623. numChannels = source->numChannels;
  17624. usesFloatingPointData = source->usesFloatingPointData;
  17625. }
  17626. AudioSubsectionReader::~AudioSubsectionReader()
  17627. {
  17628. if (deleteSourceWhenDeleted)
  17629. delete source;
  17630. }
  17631. bool AudioSubsectionReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  17632. int64 startSampleInFile, int numSamples)
  17633. {
  17634. if (startSampleInFile + numSamples > length)
  17635. {
  17636. for (int i = numDestChannels; --i >= 0;)
  17637. if (destSamples[i] != 0)
  17638. zeromem (destSamples[i], sizeof (int) * numSamples);
  17639. numSamples = jmin (numSamples, (int) (length - startSampleInFile));
  17640. if (numSamples <= 0)
  17641. return true;
  17642. }
  17643. return source->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer,
  17644. startSampleInFile + startSample, numSamples);
  17645. }
  17646. void AudioSubsectionReader::readMaxLevels (int64 startSampleInFile,
  17647. int64 numSamples,
  17648. float& lowestLeft,
  17649. float& highestLeft,
  17650. float& lowestRight,
  17651. float& highestRight)
  17652. {
  17653. startSampleInFile = jmax ((int64) 0, startSampleInFile);
  17654. numSamples = jmax ((int64) 0, jmin (numSamples, length - startSampleInFile));
  17655. source->readMaxLevels (startSampleInFile + startSample,
  17656. numSamples,
  17657. lowestLeft,
  17658. highestLeft,
  17659. lowestRight,
  17660. highestRight);
  17661. }
  17662. END_JUCE_NAMESPACE
  17663. /*** End of inlined file: juce_AudioSubsectionReader.cpp ***/
  17664. /*** Start of inlined file: juce_AudioThumbnail.cpp ***/
  17665. BEGIN_JUCE_NAMESPACE
  17666. AudioThumbnail::AudioThumbnail (const int orginalSamplesPerThumbnailSample_,
  17667. AudioFormatManager& formatManagerToUse_,
  17668. AudioThumbnailCache& cacheToUse)
  17669. : formatManagerToUse (formatManagerToUse_),
  17670. cache (cacheToUse),
  17671. orginalSamplesPerThumbnailSample (orginalSamplesPerThumbnailSample_),
  17672. timeBeforeDeletingReader (2000)
  17673. {
  17674. clear();
  17675. }
  17676. AudioThumbnail::~AudioThumbnail()
  17677. {
  17678. cache.removeThumbnail (this);
  17679. const ScopedLock sl (readerLock);
  17680. reader = 0;
  17681. }
  17682. AudioThumbnail::DataFormat* AudioThumbnail::getData() const throw()
  17683. {
  17684. jassert (data.getData() != 0);
  17685. return static_cast <DataFormat*> (data.getData());
  17686. }
  17687. void AudioThumbnail::setSource (InputSource* const newSource)
  17688. {
  17689. cache.removeThumbnail (this);
  17690. timerCallback(); // stops the timer and deletes the reader
  17691. source = newSource;
  17692. clear();
  17693. if (newSource != 0
  17694. && ! (cache.loadThumb (*this, newSource->hashCode())
  17695. && isFullyLoaded()))
  17696. {
  17697. {
  17698. const ScopedLock sl (readerLock);
  17699. reader = createReader();
  17700. }
  17701. if (reader != 0)
  17702. {
  17703. initialiseFromAudioFile (*reader);
  17704. cache.addThumbnail (this);
  17705. }
  17706. }
  17707. sendChangeMessage (this);
  17708. }
  17709. bool AudioThumbnail::useTimeSlice()
  17710. {
  17711. const ScopedLock sl (readerLock);
  17712. if (isFullyLoaded())
  17713. {
  17714. if (reader != 0)
  17715. startTimer (timeBeforeDeletingReader);
  17716. cache.removeThumbnail (this);
  17717. return false;
  17718. }
  17719. if (reader == 0)
  17720. reader = createReader();
  17721. if (reader != 0)
  17722. {
  17723. readNextBlockFromAudioFile (*reader);
  17724. stopTimer();
  17725. sendChangeMessage (this);
  17726. const bool justFinished = isFullyLoaded();
  17727. if (justFinished)
  17728. cache.storeThumb (*this, source->hashCode());
  17729. return ! justFinished;
  17730. }
  17731. return false;
  17732. }
  17733. AudioFormatReader* AudioThumbnail::createReader() const
  17734. {
  17735. if (source != 0)
  17736. {
  17737. InputStream* const audioFileStream = source->createInputStream();
  17738. if (audioFileStream != 0)
  17739. return formatManagerToUse.createReaderFor (audioFileStream);
  17740. }
  17741. return 0;
  17742. }
  17743. void AudioThumbnail::timerCallback()
  17744. {
  17745. stopTimer();
  17746. const ScopedLock sl (readerLock);
  17747. reader = 0;
  17748. }
  17749. void AudioThumbnail::clear()
  17750. {
  17751. data.setSize (sizeof (DataFormat) + 3);
  17752. DataFormat* const d = getData();
  17753. d->thumbnailMagic[0] = 'j';
  17754. d->thumbnailMagic[1] = 'a';
  17755. d->thumbnailMagic[2] = 't';
  17756. d->thumbnailMagic[3] = 'm';
  17757. d->samplesPerThumbSample = orginalSamplesPerThumbnailSample;
  17758. d->totalSamples = 0;
  17759. d->numFinishedSamples = 0;
  17760. d->numThumbnailSamples = 0;
  17761. d->numChannels = 0;
  17762. d->sampleRate = 0;
  17763. numSamplesCached = 0;
  17764. cacheNeedsRefilling = true;
  17765. }
  17766. void AudioThumbnail::loadFrom (InputStream& input)
  17767. {
  17768. const ScopedLock sl (readerLock);
  17769. data.setSize (0);
  17770. input.readIntoMemoryBlock (data);
  17771. DataFormat* const d = getData();
  17772. d->flipEndiannessIfBigEndian();
  17773. if (! (d->thumbnailMagic[0] == 'j'
  17774. && d->thumbnailMagic[1] == 'a'
  17775. && d->thumbnailMagic[2] == 't'
  17776. && d->thumbnailMagic[3] == 'm'))
  17777. {
  17778. clear();
  17779. }
  17780. numSamplesCached = 0;
  17781. cacheNeedsRefilling = true;
  17782. }
  17783. void AudioThumbnail::saveTo (OutputStream& output) const
  17784. {
  17785. const ScopedLock sl (readerLock);
  17786. DataFormat* const d = getData();
  17787. d->flipEndiannessIfBigEndian();
  17788. output.write (d, (int) data.getSize());
  17789. d->flipEndiannessIfBigEndian();
  17790. }
  17791. bool AudioThumbnail::initialiseFromAudioFile (AudioFormatReader& fileReader)
  17792. {
  17793. DataFormat* d = getData();
  17794. d->totalSamples = fileReader.lengthInSamples;
  17795. d->numChannels = jmin ((uint32) 2, fileReader.numChannels);
  17796. d->numFinishedSamples = 0;
  17797. d->sampleRate = roundToInt (fileReader.sampleRate);
  17798. d->numThumbnailSamples = (int) (d->totalSamples / d->samplesPerThumbSample) + 1;
  17799. data.setSize (sizeof (DataFormat) + 3 + d->numThumbnailSamples * d->numChannels * 2);
  17800. d = getData();
  17801. zeromem (d->data, d->numThumbnailSamples * d->numChannels * 2);
  17802. return d->totalSamples > 0;
  17803. }
  17804. bool AudioThumbnail::readNextBlockFromAudioFile (AudioFormatReader& fileReader)
  17805. {
  17806. DataFormat* const d = getData();
  17807. if (d->numFinishedSamples < d->totalSamples)
  17808. {
  17809. const int numToDo = (int) jmin ((int64) 65536, d->totalSamples - d->numFinishedSamples);
  17810. generateSection (fileReader,
  17811. d->numFinishedSamples,
  17812. numToDo);
  17813. d->numFinishedSamples += numToDo;
  17814. }
  17815. cacheNeedsRefilling = true;
  17816. return d->numFinishedSamples < d->totalSamples;
  17817. }
  17818. int AudioThumbnail::getNumChannels() const throw()
  17819. {
  17820. return getData()->numChannels;
  17821. }
  17822. double AudioThumbnail::getTotalLength() const throw()
  17823. {
  17824. const DataFormat* const d = getData();
  17825. if (d->sampleRate > 0)
  17826. return d->totalSamples / (double) d->sampleRate;
  17827. else
  17828. return 0.0;
  17829. }
  17830. void AudioThumbnail::generateSection (AudioFormatReader& fileReader,
  17831. int64 startSample,
  17832. int numSamples)
  17833. {
  17834. DataFormat* const d = getData();
  17835. const int firstDataPos = (int) (startSample / d->samplesPerThumbSample);
  17836. const int lastDataPos = (int) ((startSample + numSamples) / d->samplesPerThumbSample);
  17837. char* const l = getChannelData (0);
  17838. char* const r = getChannelData (1);
  17839. for (int i = firstDataPos; i < lastDataPos; ++i)
  17840. {
  17841. const int sourceStart = i * d->samplesPerThumbSample;
  17842. const int sourceEnd = sourceStart + d->samplesPerThumbSample;
  17843. float lowestLeft, highestLeft, lowestRight, highestRight;
  17844. fileReader.readMaxLevels (sourceStart,
  17845. sourceEnd - sourceStart,
  17846. lowestLeft,
  17847. highestLeft,
  17848. lowestRight,
  17849. highestRight);
  17850. int n = i * 2;
  17851. if (r != 0)
  17852. {
  17853. l [n] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  17854. r [n++] = (char) jlimit (-128.0f, 127.0f, lowestRight * 127.0f);
  17855. l [n] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  17856. r [n++] = (char) jlimit (-128.0f, 127.0f, highestRight * 127.0f);
  17857. }
  17858. else
  17859. {
  17860. l [n++] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  17861. l [n++] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  17862. }
  17863. }
  17864. }
  17865. char* AudioThumbnail::getChannelData (int channel) const
  17866. {
  17867. DataFormat* const d = getData();
  17868. if (channel >= 0 && channel < d->numChannels)
  17869. return d->data + (channel * 2 * d->numThumbnailSamples);
  17870. return 0;
  17871. }
  17872. bool AudioThumbnail::isFullyLoaded() const throw()
  17873. {
  17874. const DataFormat* const d = getData();
  17875. return d->numFinishedSamples >= d->totalSamples;
  17876. }
  17877. void AudioThumbnail::refillCache (const int numSamples,
  17878. double startTime,
  17879. const double timePerPixel)
  17880. {
  17881. const DataFormat* const d = getData();
  17882. if (numSamples <= 0
  17883. || timePerPixel <= 0.0
  17884. || d->sampleRate <= 0)
  17885. {
  17886. numSamplesCached = 0;
  17887. cacheNeedsRefilling = true;
  17888. return;
  17889. }
  17890. if (numSamples == numSamplesCached
  17891. && numChannelsCached == d->numChannels
  17892. && startTime == cachedStart
  17893. && timePerPixel == cachedTimePerPixel
  17894. && ! cacheNeedsRefilling)
  17895. {
  17896. return;
  17897. }
  17898. numSamplesCached = numSamples;
  17899. numChannelsCached = d->numChannels;
  17900. cachedStart = startTime;
  17901. cachedTimePerPixel = timePerPixel;
  17902. cachedLevels.ensureSize (2 * numChannelsCached * numSamples);
  17903. const bool needExtraDetail = (timePerPixel * d->sampleRate <= d->samplesPerThumbSample);
  17904. const ScopedLock sl (readerLock);
  17905. cacheNeedsRefilling = false;
  17906. if (needExtraDetail && reader == 0)
  17907. reader = createReader();
  17908. if (reader != 0 && timePerPixel * d->sampleRate <= d->samplesPerThumbSample)
  17909. {
  17910. startTimer (timeBeforeDeletingReader);
  17911. char* cacheData = static_cast <char*> (cachedLevels.getData());
  17912. int sample = roundToInt (startTime * d->sampleRate);
  17913. for (int i = numSamples; --i >= 0;)
  17914. {
  17915. const int nextSample = roundToInt ((startTime + timePerPixel) * d->sampleRate);
  17916. if (sample >= 0)
  17917. {
  17918. if (sample >= reader->lengthInSamples)
  17919. break;
  17920. float lmin, lmax, rmin, rmax;
  17921. reader->readMaxLevels (sample,
  17922. jmax (1, nextSample - sample),
  17923. lmin, lmax, rmin, rmax);
  17924. cacheData[0] = (char) jlimit (-128, 127, roundFloatToInt (lmin * 127.0f));
  17925. cacheData[1] = (char) jlimit (-128, 127, roundFloatToInt (lmax * 127.0f));
  17926. if (numChannelsCached > 1)
  17927. {
  17928. cacheData[2] = (char) jlimit (-128, 127, roundFloatToInt (rmin * 127.0f));
  17929. cacheData[3] = (char) jlimit (-128, 127, roundFloatToInt (rmax * 127.0f));
  17930. }
  17931. cacheData += 2 * numChannelsCached;
  17932. }
  17933. startTime += timePerPixel;
  17934. sample = nextSample;
  17935. }
  17936. }
  17937. else
  17938. {
  17939. for (int channelNum = 0; channelNum < numChannelsCached; ++channelNum)
  17940. {
  17941. char* const channelData = getChannelData (channelNum);
  17942. char* cacheData = static_cast <char*> (cachedLevels.getData()) + channelNum * 2;
  17943. const double timeToThumbSampleFactor = d->sampleRate / (double) d->samplesPerThumbSample;
  17944. startTime = cachedStart;
  17945. int sample = roundToInt (startTime * timeToThumbSampleFactor);
  17946. const int numFinished = (int) (d->numFinishedSamples / d->samplesPerThumbSample);
  17947. for (int i = numSamples; --i >= 0;)
  17948. {
  17949. const int nextSample = roundToInt ((startTime + timePerPixel) * timeToThumbSampleFactor);
  17950. if (sample >= 0 && channelData != 0)
  17951. {
  17952. char mx = -128;
  17953. char mn = 127;
  17954. while (sample <= nextSample)
  17955. {
  17956. if (sample >= numFinished)
  17957. break;
  17958. const int n = sample << 1;
  17959. const char sampMin = channelData [n];
  17960. const char sampMax = channelData [n + 1];
  17961. if (sampMin < mn)
  17962. mn = sampMin;
  17963. if (sampMax > mx)
  17964. mx = sampMax;
  17965. ++sample;
  17966. }
  17967. if (mn <= mx)
  17968. {
  17969. cacheData[0] = mn;
  17970. cacheData[1] = mx;
  17971. }
  17972. else
  17973. {
  17974. cacheData[0] = 1;
  17975. cacheData[1] = 0;
  17976. }
  17977. }
  17978. else
  17979. {
  17980. cacheData[0] = 1;
  17981. cacheData[1] = 0;
  17982. }
  17983. cacheData += numChannelsCached * 2;
  17984. startTime += timePerPixel;
  17985. sample = nextSample;
  17986. }
  17987. }
  17988. }
  17989. }
  17990. void AudioThumbnail::drawChannel (Graphics& g,
  17991. int x, int y, int w, int h,
  17992. double startTime,
  17993. double endTime,
  17994. int channelNum,
  17995. const float verticalZoomFactor)
  17996. {
  17997. refillCache (w, startTime, (endTime - startTime) / w);
  17998. if (numSamplesCached >= w
  17999. && channelNum >= 0
  18000. && channelNum < numChannelsCached)
  18001. {
  18002. const float topY = (float) y;
  18003. const float bottomY = topY + h;
  18004. const float midY = topY + h * 0.5f;
  18005. const float vscale = verticalZoomFactor * h / 256.0f;
  18006. const Rectangle<int> clip (g.getClipBounds());
  18007. const int skipLeft = jlimit (0, w, clip.getX() - x);
  18008. w -= skipLeft;
  18009. x += skipLeft;
  18010. const char* cacheData = static_cast <const char*> (cachedLevels.getData())
  18011. + (channelNum << 1)
  18012. + skipLeft * (numChannelsCached << 1);
  18013. while (--w >= 0)
  18014. {
  18015. const char mn = cacheData[0];
  18016. const char mx = cacheData[1];
  18017. cacheData += numChannelsCached << 1;
  18018. if (mn <= mx) // if the wrong way round, signifies that the sample's not yet known
  18019. g.drawVerticalLine (x, jmax (midY - mx * vscale - 0.3f, topY),
  18020. jmin (midY - mn * vscale + 0.3f, bottomY));
  18021. if (++x >= clip.getRight())
  18022. break;
  18023. }
  18024. }
  18025. }
  18026. void AudioThumbnail::DataFormat::flipEndiannessIfBigEndian() throw()
  18027. {
  18028. #if JUCE_BIG_ENDIAN
  18029. struct Flipper
  18030. {
  18031. static void flip (int32& n) { n = (int32) ByteOrder::swap ((uint32) n); }
  18032. static void flip (int64& n) { n = (int64) ByteOrder::swap ((uint64) n); }
  18033. };
  18034. Flipper::flip (samplesPerThumbSample);
  18035. Flipper::flip (totalSamples);
  18036. Flipper::flip (numFinishedSamples);
  18037. Flipper::flip (numThumbnailSamples);
  18038. Flipper::flip (numChannels);
  18039. Flipper::flip (sampleRate);
  18040. #endif
  18041. }
  18042. END_JUCE_NAMESPACE
  18043. /*** End of inlined file: juce_AudioThumbnail.cpp ***/
  18044. /*** Start of inlined file: juce_AudioThumbnailCache.cpp ***/
  18045. BEGIN_JUCE_NAMESPACE
  18046. struct ThumbnailCacheEntry
  18047. {
  18048. int64 hash;
  18049. uint32 lastUsed;
  18050. MemoryBlock data;
  18051. juce_UseDebuggingNewOperator
  18052. };
  18053. AudioThumbnailCache::AudioThumbnailCache (const int maxNumThumbsToStore_)
  18054. : TimeSliceThread ("thumb cache"),
  18055. maxNumThumbsToStore (maxNumThumbsToStore_)
  18056. {
  18057. startThread (2);
  18058. }
  18059. AudioThumbnailCache::~AudioThumbnailCache()
  18060. {
  18061. }
  18062. bool AudioThumbnailCache::loadThumb (AudioThumbnail& thumb, const int64 hashCode)
  18063. {
  18064. for (int i = thumbs.size(); --i >= 0;)
  18065. {
  18066. if (thumbs[i]->hash == hashCode)
  18067. {
  18068. MemoryInputStream in (thumbs[i]->data, false);
  18069. thumb.loadFrom (in);
  18070. thumbs[i]->lastUsed = Time::getMillisecondCounter();
  18071. return true;
  18072. }
  18073. }
  18074. return false;
  18075. }
  18076. void AudioThumbnailCache::storeThumb (const AudioThumbnail& thumb,
  18077. const int64 hashCode)
  18078. {
  18079. MemoryOutputStream out;
  18080. thumb.saveTo (out);
  18081. ThumbnailCacheEntry* te = 0;
  18082. for (int i = thumbs.size(); --i >= 0;)
  18083. {
  18084. if (thumbs[i]->hash == hashCode)
  18085. {
  18086. te = thumbs[i];
  18087. break;
  18088. }
  18089. }
  18090. if (te == 0)
  18091. {
  18092. te = new ThumbnailCacheEntry();
  18093. te->hash = hashCode;
  18094. if (thumbs.size() < maxNumThumbsToStore)
  18095. {
  18096. thumbs.add (te);
  18097. }
  18098. else
  18099. {
  18100. int oldest = 0;
  18101. unsigned int oldestTime = Time::getMillisecondCounter() + 1;
  18102. int i;
  18103. for (i = thumbs.size(); --i >= 0;)
  18104. if (thumbs[i]->lastUsed < oldestTime)
  18105. oldest = i;
  18106. thumbs.set (i, te);
  18107. }
  18108. }
  18109. te->lastUsed = Time::getMillisecondCounter();
  18110. te->data.setSize (0);
  18111. te->data.append (out.getData(), out.getDataSize());
  18112. }
  18113. void AudioThumbnailCache::clear()
  18114. {
  18115. thumbs.clear();
  18116. }
  18117. void AudioThumbnailCache::addThumbnail (AudioThumbnail* const thumb)
  18118. {
  18119. addTimeSliceClient (thumb);
  18120. }
  18121. void AudioThumbnailCache::removeThumbnail (AudioThumbnail* const thumb)
  18122. {
  18123. removeTimeSliceClient (thumb);
  18124. }
  18125. END_JUCE_NAMESPACE
  18126. /*** End of inlined file: juce_AudioThumbnailCache.cpp ***/
  18127. /*** Start of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  18128. #if JUCE_QUICKTIME && ! (JUCE_64BIT || JUCE_IOS)
  18129. #if ! JUCE_WINDOWS
  18130. #include <QuickTime/Movies.h>
  18131. #include <QuickTime/QTML.h>
  18132. #include <QuickTime/QuickTimeComponents.h>
  18133. #include <QuickTime/MediaHandlers.h>
  18134. #include <QuickTime/ImageCodec.h>
  18135. #else
  18136. #if JUCE_MSVC
  18137. #pragma warning (push)
  18138. #pragma warning (disable : 4100)
  18139. #endif
  18140. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  18141. add its header directory to your include path.
  18142. Alternatively, if you don't need any QuickTime services, just turn off the JUCE_QUICKTIME
  18143. flag in juce_Config.h
  18144. */
  18145. #include <Movies.h>
  18146. #include <QTML.h>
  18147. #include <QuickTimeComponents.h>
  18148. #include <MediaHandlers.h>
  18149. #include <ImageCodec.h>
  18150. #if JUCE_MSVC
  18151. #pragma warning (pop)
  18152. #endif
  18153. #endif
  18154. BEGIN_JUCE_NAMESPACE
  18155. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  18156. static const char* const quickTimeFormatName = "QuickTime file";
  18157. static const char* const quickTimeExtensions[] = { ".mov", ".mp3", ".mp4", ".m4a", 0 };
  18158. class QTAudioReader : public AudioFormatReader
  18159. {
  18160. public:
  18161. QTAudioReader (InputStream* const input_, const int trackNum_)
  18162. : AudioFormatReader (input_, TRANS (quickTimeFormatName)),
  18163. ok (false),
  18164. movie (0),
  18165. trackNum (trackNum_),
  18166. lastSampleRead (0),
  18167. lastThreadId (0),
  18168. extractor (0),
  18169. dataHandle (0)
  18170. {
  18171. JUCE_AUTORELEASEPOOL
  18172. bufferList.calloc (256, 1);
  18173. #if JUCE_WINDOWS
  18174. if (InitializeQTML (0) != noErr)
  18175. return;
  18176. #endif
  18177. if (EnterMovies() != noErr)
  18178. return;
  18179. bool opened = juce_OpenQuickTimeMovieFromStream (input_, movie, dataHandle);
  18180. if (! opened)
  18181. return;
  18182. {
  18183. const int numTracks = GetMovieTrackCount (movie);
  18184. int trackCount = 0;
  18185. for (int i = 1; i <= numTracks; ++i)
  18186. {
  18187. track = GetMovieIndTrack (movie, i);
  18188. media = GetTrackMedia (track);
  18189. OSType mediaType;
  18190. GetMediaHandlerDescription (media, &mediaType, 0, 0);
  18191. if (mediaType == SoundMediaType
  18192. && trackCount++ == trackNum_)
  18193. {
  18194. ok = true;
  18195. break;
  18196. }
  18197. }
  18198. }
  18199. if (! ok)
  18200. return;
  18201. ok = false;
  18202. lengthInSamples = GetMediaDecodeDuration (media);
  18203. usesFloatingPointData = false;
  18204. samplesPerFrame = (int) (GetMediaDecodeDuration (media) / GetMediaSampleCount (media));
  18205. trackUnitsPerFrame = GetMovieTimeScale (movie) * samplesPerFrame
  18206. / GetMediaTimeScale (media);
  18207. OSStatus err = MovieAudioExtractionBegin (movie, 0, &extractor);
  18208. unsigned long output_layout_size;
  18209. err = MovieAudioExtractionGetPropertyInfo (extractor,
  18210. kQTPropertyClass_MovieAudioExtraction_Audio,
  18211. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  18212. 0, &output_layout_size, 0);
  18213. if (err != noErr)
  18214. return;
  18215. HeapBlock <AudioChannelLayout> qt_audio_channel_layout;
  18216. qt_audio_channel_layout.calloc (output_layout_size, 1);
  18217. err = MovieAudioExtractionGetProperty (extractor,
  18218. kQTPropertyClass_MovieAudioExtraction_Audio,
  18219. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  18220. output_layout_size, qt_audio_channel_layout, 0);
  18221. qt_audio_channel_layout[0].mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  18222. err = MovieAudioExtractionSetProperty (extractor,
  18223. kQTPropertyClass_MovieAudioExtraction_Audio,
  18224. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  18225. output_layout_size,
  18226. qt_audio_channel_layout);
  18227. err = MovieAudioExtractionGetProperty (extractor,
  18228. kQTPropertyClass_MovieAudioExtraction_Audio,
  18229. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  18230. sizeof (inputStreamDesc),
  18231. &inputStreamDesc, 0);
  18232. if (err != noErr)
  18233. return;
  18234. inputStreamDesc.mFormatFlags = kAudioFormatFlagIsSignedInteger
  18235. | kAudioFormatFlagIsPacked
  18236. | kAudioFormatFlagsNativeEndian;
  18237. inputStreamDesc.mBitsPerChannel = sizeof (SInt16) * 8;
  18238. inputStreamDesc.mChannelsPerFrame = jmin ((UInt32) 2, inputStreamDesc.mChannelsPerFrame);
  18239. inputStreamDesc.mBytesPerFrame = sizeof (SInt16) * inputStreamDesc.mChannelsPerFrame;
  18240. inputStreamDesc.mBytesPerPacket = inputStreamDesc.mBytesPerFrame;
  18241. err = MovieAudioExtractionSetProperty (extractor,
  18242. kQTPropertyClass_MovieAudioExtraction_Audio,
  18243. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  18244. sizeof (inputStreamDesc),
  18245. &inputStreamDesc);
  18246. if (err != noErr)
  18247. return;
  18248. Boolean allChannelsDiscrete = false;
  18249. err = MovieAudioExtractionSetProperty (extractor,
  18250. kQTPropertyClass_MovieAudioExtraction_Movie,
  18251. kQTMovieAudioExtractionMoviePropertyID_AllChannelsDiscrete,
  18252. sizeof (allChannelsDiscrete),
  18253. &allChannelsDiscrete);
  18254. if (err != noErr)
  18255. return;
  18256. bufferList->mNumberBuffers = 1;
  18257. bufferList->mBuffers[0].mNumberChannels = inputStreamDesc.mChannelsPerFrame;
  18258. bufferList->mBuffers[0].mDataByteSize = jmax ((UInt32) 4096, (UInt32) (samplesPerFrame * inputStreamDesc.mBytesPerFrame) + 16);
  18259. dataBuffer.malloc (bufferList->mBuffers[0].mDataByteSize);
  18260. bufferList->mBuffers[0].mData = dataBuffer;
  18261. sampleRate = inputStreamDesc.mSampleRate;
  18262. bitsPerSample = 16;
  18263. numChannels = inputStreamDesc.mChannelsPerFrame;
  18264. detachThread();
  18265. ok = true;
  18266. }
  18267. ~QTAudioReader()
  18268. {
  18269. JUCE_AUTORELEASEPOOL
  18270. checkThreadIsAttached();
  18271. if (dataHandle != 0)
  18272. DisposeHandle (dataHandle);
  18273. if (extractor != 0)
  18274. {
  18275. MovieAudioExtractionEnd (extractor);
  18276. extractor = 0;
  18277. }
  18278. DisposeMovie (movie);
  18279. #if JUCE_MAC
  18280. ExitMoviesOnThread ();
  18281. #endif
  18282. }
  18283. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  18284. int64 startSampleInFile, int numSamples)
  18285. {
  18286. JUCE_AUTORELEASEPOOL
  18287. checkThreadIsAttached();
  18288. bool ok = true;
  18289. while (numSamples > 0)
  18290. {
  18291. if (lastSampleRead != startSampleInFile)
  18292. {
  18293. TimeRecord time;
  18294. time.scale = (TimeScale) inputStreamDesc.mSampleRate;
  18295. time.base = 0;
  18296. time.value.hi = 0;
  18297. time.value.lo = (UInt32) startSampleInFile;
  18298. OSStatus err = MovieAudioExtractionSetProperty (extractor,
  18299. kQTPropertyClass_MovieAudioExtraction_Movie,
  18300. kQTMovieAudioExtractionMoviePropertyID_CurrentTime,
  18301. sizeof (time), &time);
  18302. if (err != noErr)
  18303. {
  18304. ok = false;
  18305. break;
  18306. }
  18307. }
  18308. int framesToDo = jmin (numSamples, (int) (bufferList->mBuffers[0].mDataByteSize / inputStreamDesc.mBytesPerFrame));
  18309. bufferList->mBuffers[0].mDataByteSize = inputStreamDesc.mBytesPerFrame * framesToDo;
  18310. UInt32 outFlags = 0;
  18311. UInt32 actualNumFrames = framesToDo;
  18312. OSStatus err = MovieAudioExtractionFillBuffer (extractor, &actualNumFrames, bufferList, &outFlags);
  18313. if (err != noErr)
  18314. {
  18315. ok = false;
  18316. break;
  18317. }
  18318. lastSampleRead = startSampleInFile + actualNumFrames;
  18319. const int samplesReceived = actualNumFrames;
  18320. for (int j = numDestChannels; --j >= 0;)
  18321. {
  18322. if (destSamples[j] != 0)
  18323. {
  18324. const short* const src = ((const short*) bufferList->mBuffers[0].mData) + j;
  18325. for (int i = 0; i < samplesReceived; ++i)
  18326. destSamples[j][startOffsetInDestBuffer + i] = src [i << 1] << 16;
  18327. }
  18328. }
  18329. startOffsetInDestBuffer += samplesReceived;
  18330. startSampleInFile += samplesReceived;
  18331. numSamples -= samplesReceived;
  18332. if ((outFlags & kQTMovieAudioExtractionComplete) != 0 && numSamples > 0)
  18333. {
  18334. for (int j = numDestChannels; --j >= 0;)
  18335. if (destSamples[j] != 0)
  18336. zeromem (destSamples[j] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  18337. break;
  18338. }
  18339. }
  18340. detachThread();
  18341. return ok;
  18342. }
  18343. juce_UseDebuggingNewOperator
  18344. bool ok;
  18345. private:
  18346. Movie movie;
  18347. Media media;
  18348. Track track;
  18349. const int trackNum;
  18350. double trackUnitsPerFrame;
  18351. int samplesPerFrame;
  18352. int64 lastSampleRead;
  18353. Thread::ThreadID lastThreadId;
  18354. MovieAudioExtractionRef extractor;
  18355. AudioStreamBasicDescription inputStreamDesc;
  18356. HeapBlock <AudioBufferList> bufferList;
  18357. HeapBlock <char> dataBuffer;
  18358. Handle dataHandle;
  18359. void checkThreadIsAttached()
  18360. {
  18361. #if JUCE_MAC
  18362. if (Thread::getCurrentThreadId() != lastThreadId)
  18363. EnterMoviesOnThread (0);
  18364. AttachMovieToCurrentThread (movie);
  18365. #endif
  18366. }
  18367. void detachThread()
  18368. {
  18369. #if JUCE_MAC
  18370. DetachMovieFromCurrentThread (movie);
  18371. #endif
  18372. }
  18373. QTAudioReader (const QTAudioReader&);
  18374. QTAudioReader& operator= (const QTAudioReader&);
  18375. };
  18376. QuickTimeAudioFormat::QuickTimeAudioFormat()
  18377. : AudioFormat (TRANS (quickTimeFormatName), StringArray (quickTimeExtensions))
  18378. {
  18379. }
  18380. QuickTimeAudioFormat::~QuickTimeAudioFormat()
  18381. {
  18382. }
  18383. const Array <int> QuickTimeAudioFormat::getPossibleSampleRates() { return Array<int>(); }
  18384. const Array <int> QuickTimeAudioFormat::getPossibleBitDepths() { return Array<int>(); }
  18385. bool QuickTimeAudioFormat::canDoStereo() { return true; }
  18386. bool QuickTimeAudioFormat::canDoMono() { return true; }
  18387. AudioFormatReader* QuickTimeAudioFormat::createReaderFor (InputStream* sourceStream,
  18388. const bool deleteStreamIfOpeningFails)
  18389. {
  18390. ScopedPointer <QTAudioReader> r (new QTAudioReader (sourceStream, 0));
  18391. if (r->ok)
  18392. return r.release();
  18393. if (! deleteStreamIfOpeningFails)
  18394. r->input = 0;
  18395. return 0;
  18396. }
  18397. AudioFormatWriter* QuickTimeAudioFormat::createWriterFor (OutputStream* /*streamToWriteTo*/,
  18398. double /*sampleRateToUse*/,
  18399. unsigned int /*numberOfChannels*/,
  18400. int /*bitsPerSample*/,
  18401. const StringPairArray& /*metadataValues*/,
  18402. int /*qualityOptionIndex*/)
  18403. {
  18404. jassertfalse; // not yet implemented!
  18405. return 0;
  18406. }
  18407. END_JUCE_NAMESPACE
  18408. #endif
  18409. /*** End of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  18410. /*** Start of inlined file: juce_WavAudioFormat.cpp ***/
  18411. BEGIN_JUCE_NAMESPACE
  18412. static const char* const wavFormatName = "WAV file";
  18413. static const char* const wavExtensions[] = { ".wav", ".bwf", 0 };
  18414. const char* const WavAudioFormat::bwavDescription = "bwav description";
  18415. const char* const WavAudioFormat::bwavOriginator = "bwav originator";
  18416. const char* const WavAudioFormat::bwavOriginatorRef = "bwav originator ref";
  18417. const char* const WavAudioFormat::bwavOriginationDate = "bwav origination date";
  18418. const char* const WavAudioFormat::bwavOriginationTime = "bwav origination time";
  18419. const char* const WavAudioFormat::bwavTimeReference = "bwav time reference";
  18420. const char* const WavAudioFormat::bwavCodingHistory = "bwav coding history";
  18421. const StringPairArray WavAudioFormat::createBWAVMetadata (const String& description,
  18422. const String& originator,
  18423. const String& originatorRef,
  18424. const Time& date,
  18425. const int64 timeReferenceSamples,
  18426. const String& codingHistory)
  18427. {
  18428. StringPairArray m;
  18429. m.set (bwavDescription, description);
  18430. m.set (bwavOriginator, originator);
  18431. m.set (bwavOriginatorRef, originatorRef);
  18432. m.set (bwavOriginationDate, date.formatted ("%Y-%m-%d"));
  18433. m.set (bwavOriginationTime, date.formatted ("%H:%M:%S"));
  18434. m.set (bwavTimeReference, String (timeReferenceSamples));
  18435. m.set (bwavCodingHistory, codingHistory);
  18436. return m;
  18437. }
  18438. #if JUCE_MSVC
  18439. #pragma pack (push, 1)
  18440. #define PACKED
  18441. #elif JUCE_GCC
  18442. #define PACKED __attribute__((packed))
  18443. #else
  18444. #define PACKED
  18445. #endif
  18446. struct BWAVChunk
  18447. {
  18448. char description [256];
  18449. char originator [32];
  18450. char originatorRef [32];
  18451. char originationDate [10];
  18452. char originationTime [8];
  18453. uint32 timeRefLow;
  18454. uint32 timeRefHigh;
  18455. uint16 version;
  18456. uint8 umid[64];
  18457. uint8 reserved[190];
  18458. char codingHistory[1];
  18459. void copyTo (StringPairArray& values) const
  18460. {
  18461. values.set (WavAudioFormat::bwavDescription, String::fromUTF8 (description, 256));
  18462. values.set (WavAudioFormat::bwavOriginator, String::fromUTF8 (originator, 32));
  18463. values.set (WavAudioFormat::bwavOriginatorRef, String::fromUTF8 (originatorRef, 32));
  18464. values.set (WavAudioFormat::bwavOriginationDate, String::fromUTF8 (originationDate, 10));
  18465. values.set (WavAudioFormat::bwavOriginationTime, String::fromUTF8 (originationTime, 8));
  18466. const uint32 timeLow = ByteOrder::swapIfBigEndian (timeRefLow);
  18467. const uint32 timeHigh = ByteOrder::swapIfBigEndian (timeRefHigh);
  18468. const int64 time = (((int64)timeHigh) << 32) + timeLow;
  18469. values.set (WavAudioFormat::bwavTimeReference, String (time));
  18470. values.set (WavAudioFormat::bwavCodingHistory, String::fromUTF8 (codingHistory));
  18471. }
  18472. static MemoryBlock createFrom (const StringPairArray& values)
  18473. {
  18474. const size_t sizeNeeded = sizeof (BWAVChunk) + values [WavAudioFormat::bwavCodingHistory].getNumBytesAsUTF8();
  18475. MemoryBlock data ((sizeNeeded + 3) & ~3);
  18476. data.fillWith (0);
  18477. BWAVChunk* b = (BWAVChunk*) data.getData();
  18478. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  18479. // as they get called in the right order..
  18480. values [WavAudioFormat::bwavDescription].copyToUTF8 (b->description, 257);
  18481. values [WavAudioFormat::bwavOriginator].copyToUTF8 (b->originator, 33);
  18482. values [WavAudioFormat::bwavOriginatorRef].copyToUTF8 (b->originatorRef, 33);
  18483. values [WavAudioFormat::bwavOriginationDate].copyToUTF8 (b->originationDate, 11);
  18484. values [WavAudioFormat::bwavOriginationTime].copyToUTF8 (b->originationTime, 9);
  18485. const int64 time = values [WavAudioFormat::bwavTimeReference].getLargeIntValue();
  18486. b->timeRefLow = ByteOrder::swapIfBigEndian ((uint32) (time & 0xffffffff));
  18487. b->timeRefHigh = ByteOrder::swapIfBigEndian ((uint32) (time >> 32));
  18488. values [WavAudioFormat::bwavCodingHistory].copyToUTF8 (b->codingHistory, 0x7fffffff);
  18489. if (b->description[0] != 0
  18490. || b->originator[0] != 0
  18491. || b->originationDate[0] != 0
  18492. || b->originationTime[0] != 0
  18493. || b->codingHistory[0] != 0
  18494. || time != 0)
  18495. {
  18496. return data;
  18497. }
  18498. return MemoryBlock();
  18499. }
  18500. } PACKED;
  18501. struct SMPLChunk
  18502. {
  18503. struct SampleLoop
  18504. {
  18505. uint32 identifier;
  18506. uint32 type;
  18507. uint32 start;
  18508. uint32 end;
  18509. uint32 fraction;
  18510. uint32 playCount;
  18511. } PACKED;
  18512. uint32 manufacturer;
  18513. uint32 product;
  18514. uint32 samplePeriod;
  18515. uint32 midiUnityNote;
  18516. uint32 midiPitchFraction;
  18517. uint32 smpteFormat;
  18518. uint32 smpteOffset;
  18519. uint32 numSampleLoops;
  18520. uint32 samplerData;
  18521. SampleLoop loops[1];
  18522. void copyTo (StringPairArray& values, const int totalSize) const
  18523. {
  18524. values.set ("Manufacturer", String (ByteOrder::swapIfBigEndian (manufacturer)));
  18525. values.set ("Product", String (ByteOrder::swapIfBigEndian (product)));
  18526. values.set ("SamplePeriod", String (ByteOrder::swapIfBigEndian (samplePeriod)));
  18527. values.set ("MidiUnityNote", String (ByteOrder::swapIfBigEndian (midiUnityNote)));
  18528. values.set ("MidiPitchFraction", String (ByteOrder::swapIfBigEndian (midiPitchFraction)));
  18529. values.set ("SmpteFormat", String (ByteOrder::swapIfBigEndian (smpteFormat)));
  18530. values.set ("SmpteOffset", String (ByteOrder::swapIfBigEndian (smpteOffset)));
  18531. values.set ("NumSampleLoops", String (ByteOrder::swapIfBigEndian (numSampleLoops)));
  18532. values.set ("SamplerData", String (ByteOrder::swapIfBigEndian (samplerData)));
  18533. for (uint32 i = 0; i < numSampleLoops; ++i)
  18534. {
  18535. if ((uint8*) (loops + (i + 1)) > ((uint8*) this) + totalSize)
  18536. break;
  18537. const String prefix ("Loop" + String(i));
  18538. values.set (prefix + "Identifier", String (ByteOrder::swapIfBigEndian (loops[i].identifier)));
  18539. values.set (prefix + "Type", String (ByteOrder::swapIfBigEndian (loops[i].type)));
  18540. values.set (prefix + "Start", String (ByteOrder::swapIfBigEndian (loops[i].start)));
  18541. values.set (prefix + "End", String (ByteOrder::swapIfBigEndian (loops[i].end)));
  18542. values.set (prefix + "Fraction", String (ByteOrder::swapIfBigEndian (loops[i].fraction)));
  18543. values.set (prefix + "PlayCount", String (ByteOrder::swapIfBigEndian (loops[i].playCount)));
  18544. }
  18545. }
  18546. static MemoryBlock createFrom (const StringPairArray& values)
  18547. {
  18548. const int numLoops = jmin (64, values.getValue ("NumSampleLoops", "0").getIntValue());
  18549. if (numLoops <= 0)
  18550. return MemoryBlock();
  18551. const size_t sizeNeeded = sizeof (SMPLChunk) + (numLoops - 1) * sizeof (SampleLoop);
  18552. MemoryBlock data ((sizeNeeded + 3) & ~3);
  18553. data.fillWith (0);
  18554. SMPLChunk* s = (SMPLChunk*) data.getData();
  18555. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  18556. // as they get called in the right order..
  18557. s->manufacturer = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Manufacturer", "0").getIntValue());
  18558. s->product = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Product", "0").getIntValue());
  18559. s->samplePeriod = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplePeriod", "0").getIntValue());
  18560. s->midiUnityNote = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiUnityNote", "60").getIntValue());
  18561. s->midiPitchFraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiPitchFraction", "0").getIntValue());
  18562. s->smpteFormat = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteFormat", "0").getIntValue());
  18563. s->smpteOffset = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteOffset", "0").getIntValue());
  18564. s->numSampleLoops = ByteOrder::swapIfBigEndian ((uint32) numLoops);
  18565. s->samplerData = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplerData", "0").getIntValue());
  18566. for (int i = 0; i < numLoops; ++i)
  18567. {
  18568. const String prefix ("Loop" + String(i));
  18569. s->loops[i].identifier = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Identifier", "0").getIntValue());
  18570. s->loops[i].type = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Type", "0").getIntValue());
  18571. s->loops[i].start = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Start", "0").getIntValue());
  18572. s->loops[i].end = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "End", "0").getIntValue());
  18573. s->loops[i].fraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Fraction", "0").getIntValue());
  18574. s->loops[i].playCount = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "PlayCount", "0").getIntValue());
  18575. }
  18576. return data;
  18577. }
  18578. } PACKED;
  18579. struct ExtensibleWavSubFormat
  18580. {
  18581. uint32 data1;
  18582. uint16 data2;
  18583. uint16 data3;
  18584. uint8 data4[8];
  18585. } PACKED;
  18586. #if JUCE_MSVC
  18587. #pragma pack (pop)
  18588. #endif
  18589. #undef PACKED
  18590. class WavAudioFormatReader : public AudioFormatReader
  18591. {
  18592. public:
  18593. WavAudioFormatReader (InputStream* const in)
  18594. : AudioFormatReader (in, TRANS (wavFormatName)),
  18595. bwavChunkStart (0),
  18596. bwavSize (0),
  18597. dataLength (0)
  18598. {
  18599. if (input->readInt() == chunkName ("RIFF"))
  18600. {
  18601. const uint32 len = (uint32) input->readInt();
  18602. const int64 end = input->getPosition() + len;
  18603. bool hasGotType = false;
  18604. bool hasGotData = false;
  18605. if (input->readInt() == chunkName ("WAVE"))
  18606. {
  18607. while (input->getPosition() < end
  18608. && ! input->isExhausted())
  18609. {
  18610. const int chunkType = input->readInt();
  18611. uint32 length = (uint32) input->readInt();
  18612. const int64 chunkEnd = input->getPosition() + length + (length & 1);
  18613. if (chunkType == chunkName ("fmt "))
  18614. {
  18615. // read the format chunk
  18616. const unsigned short format = input->readShort();
  18617. const short numChans = input->readShort();
  18618. sampleRate = input->readInt();
  18619. const int bytesPerSec = input->readInt();
  18620. numChannels = numChans;
  18621. bytesPerFrame = bytesPerSec / (int)sampleRate;
  18622. bitsPerSample = 8 * bytesPerFrame / numChans;
  18623. if (format == 3)
  18624. {
  18625. usesFloatingPointData = true;
  18626. }
  18627. else if (format == 0xfffe /*WAVE_FORMAT_EXTENSIBLE*/)
  18628. {
  18629. if (length < 40) // too short
  18630. {
  18631. bytesPerFrame = 0;
  18632. }
  18633. else
  18634. {
  18635. input->skipNextBytes (12); // skip over blockAlign, bitsPerSample and speakerPosition mask
  18636. ExtensibleWavSubFormat subFormat;
  18637. subFormat.data1 = input->readInt();
  18638. subFormat.data2 = input->readShort();
  18639. subFormat.data3 = input->readShort();
  18640. input->read (subFormat.data4, sizeof (subFormat.data4));
  18641. const ExtensibleWavSubFormat pcmFormat
  18642. = { 0x00000001, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  18643. if (memcmp (&subFormat, &pcmFormat, sizeof (subFormat)) != 0)
  18644. {
  18645. const ExtensibleWavSubFormat ambisonicFormat
  18646. = { 0x00000001, 0x0721, 0x11d3, { 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00 } };
  18647. if (memcmp (&subFormat, &ambisonicFormat, sizeof (subFormat)) != 0)
  18648. bytesPerFrame = 0;
  18649. }
  18650. }
  18651. }
  18652. else if (format != 1)
  18653. {
  18654. bytesPerFrame = 0;
  18655. }
  18656. hasGotType = true;
  18657. }
  18658. else if (chunkType == chunkName ("data"))
  18659. {
  18660. // get the data chunk's position
  18661. dataLength = length;
  18662. dataChunkStart = input->getPosition();
  18663. lengthInSamples = (bytesPerFrame > 0) ? (dataLength / bytesPerFrame) : 0;
  18664. hasGotData = true;
  18665. }
  18666. else if (chunkType == chunkName ("bext"))
  18667. {
  18668. bwavChunkStart = input->getPosition();
  18669. bwavSize = length;
  18670. // Broadcast-wav extension chunk..
  18671. HeapBlock <BWAVChunk> bwav;
  18672. bwav.calloc (jmax ((size_t) length + 1, sizeof (BWAVChunk)), 1);
  18673. input->read (bwav, length);
  18674. bwav->copyTo (metadataValues);
  18675. }
  18676. else if (chunkType == chunkName ("smpl"))
  18677. {
  18678. HeapBlock <SMPLChunk> smpl;
  18679. smpl.calloc (jmax ((size_t) length + 1, sizeof (SMPLChunk)), 1);
  18680. input->read (smpl, length);
  18681. smpl->copyTo (metadataValues, length);
  18682. }
  18683. else if (chunkEnd <= input->getPosition())
  18684. {
  18685. break;
  18686. }
  18687. input->setPosition (chunkEnd);
  18688. }
  18689. }
  18690. }
  18691. }
  18692. ~WavAudioFormatReader()
  18693. {
  18694. }
  18695. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  18696. int64 startSampleInFile, int numSamples)
  18697. {
  18698. jassert (destSamples != 0);
  18699. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  18700. if (samplesAvailable < numSamples)
  18701. {
  18702. for (int i = numDestChannels; --i >= 0;)
  18703. if (destSamples[i] != 0)
  18704. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  18705. numSamples = (int) samplesAvailable;
  18706. }
  18707. if (numSamples <= 0)
  18708. return true;
  18709. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  18710. while (numSamples > 0)
  18711. {
  18712. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  18713. char tempBuffer [tempBufSize];
  18714. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  18715. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  18716. if (bytesRead < numThisTime * bytesPerFrame)
  18717. {
  18718. jassert (bytesRead >= 0);
  18719. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  18720. }
  18721. switch (bitsPerSample)
  18722. {
  18723. case 8: ReadHelper<AudioData::Int32, AudioData::UInt8, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18724. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18725. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18726. case 32: if (usesFloatingPointData) ReadHelper<AudioData::Float32, AudioData::Float32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime);
  18727. else ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18728. default: jassertfalse; break;
  18729. }
  18730. startOffsetInDestBuffer += numThisTime;
  18731. numSamples -= numThisTime;
  18732. }
  18733. return true;
  18734. }
  18735. int64 bwavChunkStart, bwavSize;
  18736. juce_UseDebuggingNewOperator
  18737. private:
  18738. ScopedPointer<AudioData::Converter> converter;
  18739. int bytesPerFrame;
  18740. int64 dataChunkStart, dataLength;
  18741. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  18742. WavAudioFormatReader (const WavAudioFormatReader&);
  18743. WavAudioFormatReader& operator= (const WavAudioFormatReader&);
  18744. };
  18745. class WavAudioFormatWriter : public AudioFormatWriter
  18746. {
  18747. public:
  18748. WavAudioFormatWriter (OutputStream* const out,
  18749. const double sampleRate_,
  18750. const unsigned int numChannels_,
  18751. const int bits,
  18752. const StringPairArray& metadataValues)
  18753. : AudioFormatWriter (out,
  18754. TRANS (wavFormatName),
  18755. sampleRate_,
  18756. numChannels_,
  18757. bits),
  18758. lengthInSamples (0),
  18759. bytesWritten (0),
  18760. writeFailed (false)
  18761. {
  18762. if (metadataValues.size() > 0)
  18763. {
  18764. bwavChunk = BWAVChunk::createFrom (metadataValues);
  18765. smplChunk = SMPLChunk::createFrom (metadataValues);
  18766. }
  18767. headerPosition = out->getPosition();
  18768. writeHeader();
  18769. }
  18770. ~WavAudioFormatWriter()
  18771. {
  18772. writeHeader();
  18773. }
  18774. bool write (const int** data, int numSamples)
  18775. {
  18776. jassert (data != 0 && *data != 0); // the input must contain at least one channel!
  18777. if (writeFailed)
  18778. return false;
  18779. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  18780. tempBlock.ensureSize (bytes, false);
  18781. switch (bitsPerSample)
  18782. {
  18783. case 8: WriteHelper<AudioData::UInt8, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18784. case 16: WriteHelper<AudioData::Int16, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18785. case 24: WriteHelper<AudioData::Int24, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18786. case 32: WriteHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18787. default: jassertfalse; break;
  18788. }
  18789. if (bytesWritten + bytes >= (uint32) 0xfff00000
  18790. || ! output->write (tempBlock.getData(), bytes))
  18791. {
  18792. // failed to write to disk, so let's try writing the header.
  18793. // If it's just run out of disk space, then if it does manage
  18794. // to write the header, we'll still have a useable file..
  18795. writeHeader();
  18796. writeFailed = true;
  18797. return false;
  18798. }
  18799. else
  18800. {
  18801. bytesWritten += bytes;
  18802. lengthInSamples += numSamples;
  18803. return true;
  18804. }
  18805. }
  18806. juce_UseDebuggingNewOperator
  18807. private:
  18808. ScopedPointer<AudioData::Converter> converter;
  18809. MemoryBlock tempBlock, bwavChunk, smplChunk;
  18810. uint32 lengthInSamples, bytesWritten;
  18811. int64 headerPosition;
  18812. bool writeFailed;
  18813. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  18814. void writeHeader()
  18815. {
  18816. const bool seekedOk = output->setPosition (headerPosition);
  18817. (void) seekedOk;
  18818. // if this fails, you've given it an output stream that can't seek! It needs
  18819. // to be able to seek back to write the header
  18820. jassert (seekedOk);
  18821. const int bytesPerFrame = numChannels * bitsPerSample / 8;
  18822. output->writeInt (chunkName ("RIFF"));
  18823. output->writeInt ((int) (lengthInSamples * bytesPerFrame
  18824. + ((bwavChunk.getSize() > 0) ? (44 + bwavChunk.getSize()) : 36)));
  18825. output->writeInt (chunkName ("WAVE"));
  18826. output->writeInt (chunkName ("fmt "));
  18827. output->writeInt (16);
  18828. output->writeShort ((bitsPerSample < 32) ? (short) 1 /*WAVE_FORMAT_PCM*/
  18829. : (short) 3 /*WAVE_FORMAT_IEEE_FLOAT*/);
  18830. output->writeShort ((short) numChannels);
  18831. output->writeInt ((int) sampleRate);
  18832. output->writeInt (bytesPerFrame * (int) sampleRate);
  18833. output->writeShort ((short) bytesPerFrame);
  18834. output->writeShort ((short) bitsPerSample);
  18835. if (bwavChunk.getSize() > 0)
  18836. {
  18837. output->writeInt (chunkName ("bext"));
  18838. output->writeInt ((int) bwavChunk.getSize());
  18839. output->write (bwavChunk.getData(), (int) bwavChunk.getSize());
  18840. }
  18841. if (smplChunk.getSize() > 0)
  18842. {
  18843. output->writeInt (chunkName ("smpl"));
  18844. output->writeInt ((int) smplChunk.getSize());
  18845. output->write (smplChunk.getData(), (int) smplChunk.getSize());
  18846. }
  18847. output->writeInt (chunkName ("data"));
  18848. output->writeInt (lengthInSamples * bytesPerFrame);
  18849. usesFloatingPointData = (bitsPerSample == 32);
  18850. }
  18851. WavAudioFormatWriter (const WavAudioFormatWriter&);
  18852. WavAudioFormatWriter& operator= (const WavAudioFormatWriter&);
  18853. };
  18854. WavAudioFormat::WavAudioFormat()
  18855. : AudioFormat (TRANS (wavFormatName), StringArray (wavExtensions))
  18856. {
  18857. }
  18858. WavAudioFormat::~WavAudioFormat()
  18859. {
  18860. }
  18861. const Array <int> WavAudioFormat::getPossibleSampleRates()
  18862. {
  18863. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  18864. return Array <int> (rates);
  18865. }
  18866. const Array <int> WavAudioFormat::getPossibleBitDepths()
  18867. {
  18868. const int depths[] = { 8, 16, 24, 32, 0 };
  18869. return Array <int> (depths);
  18870. }
  18871. bool WavAudioFormat::canDoStereo() { return true; }
  18872. bool WavAudioFormat::canDoMono() { return true; }
  18873. AudioFormatReader* WavAudioFormat::createReaderFor (InputStream* sourceStream,
  18874. const bool deleteStreamIfOpeningFails)
  18875. {
  18876. ScopedPointer <WavAudioFormatReader> r (new WavAudioFormatReader (sourceStream));
  18877. if (r->sampleRate != 0)
  18878. return r.release();
  18879. if (! deleteStreamIfOpeningFails)
  18880. r->input = 0;
  18881. return 0;
  18882. }
  18883. AudioFormatWriter* WavAudioFormat::createWriterFor (OutputStream* out,
  18884. double sampleRate,
  18885. unsigned int numChannels,
  18886. int bitsPerSample,
  18887. const StringPairArray& metadataValues,
  18888. int /*qualityOptionIndex*/)
  18889. {
  18890. if (getPossibleBitDepths().contains (bitsPerSample))
  18891. {
  18892. return new WavAudioFormatWriter (out,
  18893. sampleRate,
  18894. numChannels,
  18895. bitsPerSample,
  18896. metadataValues);
  18897. }
  18898. return 0;
  18899. }
  18900. static bool juce_slowCopyOfWavFileWithNewMetadata (const File& file, const StringPairArray& metadata)
  18901. {
  18902. TemporaryFile tempFile (file);
  18903. WavAudioFormat wav;
  18904. ScopedPointer <AudioFormatReader> reader (wav.createReaderFor (file.createInputStream(), true));
  18905. if (reader != 0)
  18906. {
  18907. ScopedPointer <OutputStream> outStream (tempFile.getFile().createOutputStream());
  18908. if (outStream != 0)
  18909. {
  18910. ScopedPointer <AudioFormatWriter> writer (wav.createWriterFor (outStream, reader->sampleRate,
  18911. reader->numChannels, reader->bitsPerSample,
  18912. metadata, 0));
  18913. if (writer != 0)
  18914. {
  18915. outStream.release();
  18916. bool ok = writer->writeFromAudioReader (*reader, 0, -1);
  18917. writer = 0;
  18918. reader = 0;
  18919. return ok && tempFile.overwriteTargetFileWithTemporary();
  18920. }
  18921. }
  18922. }
  18923. return false;
  18924. }
  18925. bool WavAudioFormat::replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata)
  18926. {
  18927. ScopedPointer <WavAudioFormatReader> reader ((WavAudioFormatReader*) createReaderFor (wavFile.createInputStream(), true));
  18928. if (reader != 0)
  18929. {
  18930. const int64 bwavPos = reader->bwavChunkStart;
  18931. const int64 bwavSize = reader->bwavSize;
  18932. reader = 0;
  18933. if (bwavSize > 0)
  18934. {
  18935. MemoryBlock chunk = BWAVChunk::createFrom (newMetadata);
  18936. if (chunk.getSize() <= (size_t) bwavSize)
  18937. {
  18938. // the new one will fit in the space available, so write it directly..
  18939. const int64 oldSize = wavFile.getSize();
  18940. {
  18941. ScopedPointer <FileOutputStream> out (wavFile.createOutputStream());
  18942. out->setPosition (bwavPos);
  18943. out->write (chunk.getData(), (int) chunk.getSize());
  18944. out->setPosition (oldSize);
  18945. }
  18946. jassert (wavFile.getSize() == oldSize);
  18947. return true;
  18948. }
  18949. }
  18950. }
  18951. return juce_slowCopyOfWavFileWithNewMetadata (wavFile, newMetadata);
  18952. }
  18953. END_JUCE_NAMESPACE
  18954. /*** End of inlined file: juce_WavAudioFormat.cpp ***/
  18955. /*** Start of inlined file: juce_AudioCDReader.cpp ***/
  18956. #if JUCE_USE_CDREADER
  18957. BEGIN_JUCE_NAMESPACE
  18958. int AudioCDReader::getNumTracks() const
  18959. {
  18960. return trackStartSamples.size() - 1;
  18961. }
  18962. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  18963. {
  18964. return trackStartSamples [trackNum];
  18965. }
  18966. const Array<int>& AudioCDReader::getTrackOffsets() const
  18967. {
  18968. return trackStartSamples;
  18969. }
  18970. int AudioCDReader::getCDDBId()
  18971. {
  18972. int checksum = 0;
  18973. const int numTracks = getNumTracks();
  18974. for (int i = 0; i < numTracks; ++i)
  18975. for (int offset = (trackStartSamples.getUnchecked(i) + 88200) / 44100; offset > 0; offset /= 10)
  18976. checksum += offset % 10;
  18977. const int length = (trackStartSamples.getLast() - trackStartSamples.getFirst()) / 44100;
  18978. // CCLLLLTT: checksum, length, tracks
  18979. return ((checksum & 0xff) << 24) | (length << 8) | numTracks;
  18980. }
  18981. END_JUCE_NAMESPACE
  18982. #endif
  18983. /*** End of inlined file: juce_AudioCDReader.cpp ***/
  18984. /*** Start of inlined file: juce_AudioFormatReaderSource.cpp ***/
  18985. BEGIN_JUCE_NAMESPACE
  18986. AudioFormatReaderSource::AudioFormatReaderSource (AudioFormatReader* const reader_,
  18987. const bool deleteReaderWhenThisIsDeleted)
  18988. : reader (reader_),
  18989. deleteReader (deleteReaderWhenThisIsDeleted),
  18990. nextPlayPos (0),
  18991. looping (false)
  18992. {
  18993. jassert (reader != 0);
  18994. }
  18995. AudioFormatReaderSource::~AudioFormatReaderSource()
  18996. {
  18997. releaseResources();
  18998. if (deleteReader)
  18999. delete reader;
  19000. }
  19001. void AudioFormatReaderSource::setNextReadPosition (int newPosition)
  19002. {
  19003. nextPlayPos = newPosition;
  19004. }
  19005. void AudioFormatReaderSource::setLooping (bool shouldLoop)
  19006. {
  19007. looping = shouldLoop;
  19008. }
  19009. int AudioFormatReaderSource::getNextReadPosition() const
  19010. {
  19011. return (looping) ? (nextPlayPos % (int) reader->lengthInSamples)
  19012. : nextPlayPos;
  19013. }
  19014. int AudioFormatReaderSource::getTotalLength() const
  19015. {
  19016. return (int) reader->lengthInSamples;
  19017. }
  19018. void AudioFormatReaderSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  19019. double /*sampleRate*/)
  19020. {
  19021. }
  19022. void AudioFormatReaderSource::releaseResources()
  19023. {
  19024. }
  19025. void AudioFormatReaderSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19026. {
  19027. if (info.numSamples > 0)
  19028. {
  19029. const int start = nextPlayPos;
  19030. if (looping)
  19031. {
  19032. const int newStart = start % (int) reader->lengthInSamples;
  19033. const int newEnd = (start + info.numSamples) % (int) reader->lengthInSamples;
  19034. if (newEnd > newStart)
  19035. {
  19036. info.buffer->readFromAudioReader (reader,
  19037. info.startSample,
  19038. newEnd - newStart,
  19039. newStart,
  19040. true, true);
  19041. }
  19042. else
  19043. {
  19044. const int endSamps = (int) reader->lengthInSamples - newStart;
  19045. info.buffer->readFromAudioReader (reader,
  19046. info.startSample,
  19047. endSamps,
  19048. newStart,
  19049. true, true);
  19050. info.buffer->readFromAudioReader (reader,
  19051. info.startSample + endSamps,
  19052. newEnd,
  19053. 0,
  19054. true, true);
  19055. }
  19056. nextPlayPos = newEnd;
  19057. }
  19058. else
  19059. {
  19060. info.buffer->readFromAudioReader (reader,
  19061. info.startSample,
  19062. info.numSamples,
  19063. start,
  19064. true, true);
  19065. nextPlayPos += info.numSamples;
  19066. }
  19067. }
  19068. }
  19069. END_JUCE_NAMESPACE
  19070. /*** End of inlined file: juce_AudioFormatReaderSource.cpp ***/
  19071. /*** Start of inlined file: juce_AudioSourcePlayer.cpp ***/
  19072. BEGIN_JUCE_NAMESPACE
  19073. AudioSourcePlayer::AudioSourcePlayer()
  19074. : source (0),
  19075. sampleRate (0),
  19076. bufferSize (0),
  19077. tempBuffer (2, 8),
  19078. lastGain (1.0f),
  19079. gain (1.0f)
  19080. {
  19081. }
  19082. AudioSourcePlayer::~AudioSourcePlayer()
  19083. {
  19084. setSource (0);
  19085. }
  19086. void AudioSourcePlayer::setSource (AudioSource* newSource)
  19087. {
  19088. if (source != newSource)
  19089. {
  19090. AudioSource* const oldSource = source;
  19091. if (newSource != 0 && bufferSize > 0 && sampleRate > 0)
  19092. newSource->prepareToPlay (bufferSize, sampleRate);
  19093. {
  19094. const ScopedLock sl (readLock);
  19095. source = newSource;
  19096. }
  19097. if (oldSource != 0)
  19098. oldSource->releaseResources();
  19099. }
  19100. }
  19101. void AudioSourcePlayer::setGain (const float newGain) throw()
  19102. {
  19103. gain = newGain;
  19104. }
  19105. void AudioSourcePlayer::audioDeviceIOCallback (const float** inputChannelData,
  19106. int totalNumInputChannels,
  19107. float** outputChannelData,
  19108. int totalNumOutputChannels,
  19109. int numSamples)
  19110. {
  19111. // these should have been prepared by audioDeviceAboutToStart()...
  19112. jassert (sampleRate > 0 && bufferSize > 0);
  19113. const ScopedLock sl (readLock);
  19114. if (source != 0)
  19115. {
  19116. AudioSourceChannelInfo info;
  19117. int i, numActiveChans = 0, numInputs = 0, numOutputs = 0;
  19118. // messy stuff needed to compact the channels down into an array
  19119. // of non-zero pointers..
  19120. for (i = 0; i < totalNumInputChannels; ++i)
  19121. {
  19122. if (inputChannelData[i] != 0)
  19123. {
  19124. inputChans [numInputs++] = inputChannelData[i];
  19125. if (numInputs >= numElementsInArray (inputChans))
  19126. break;
  19127. }
  19128. }
  19129. for (i = 0; i < totalNumOutputChannels; ++i)
  19130. {
  19131. if (outputChannelData[i] != 0)
  19132. {
  19133. outputChans [numOutputs++] = outputChannelData[i];
  19134. if (numOutputs >= numElementsInArray (outputChans))
  19135. break;
  19136. }
  19137. }
  19138. if (numInputs > numOutputs)
  19139. {
  19140. // if there aren't enough output channels for the number of
  19141. // inputs, we need to create some temporary extra ones (can't
  19142. // use the input data in case it gets written to)
  19143. tempBuffer.setSize (numInputs - numOutputs, numSamples,
  19144. false, false, true);
  19145. for (i = 0; i < numOutputs; ++i)
  19146. {
  19147. channels[numActiveChans] = outputChans[i];
  19148. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  19149. ++numActiveChans;
  19150. }
  19151. for (i = numOutputs; i < numInputs; ++i)
  19152. {
  19153. channels[numActiveChans] = tempBuffer.getSampleData (i - numOutputs, 0);
  19154. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  19155. ++numActiveChans;
  19156. }
  19157. }
  19158. else
  19159. {
  19160. for (i = 0; i < numInputs; ++i)
  19161. {
  19162. channels[numActiveChans] = outputChans[i];
  19163. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  19164. ++numActiveChans;
  19165. }
  19166. for (i = numInputs; i < numOutputs; ++i)
  19167. {
  19168. channels[numActiveChans] = outputChans[i];
  19169. zeromem (channels[numActiveChans], sizeof (float) * numSamples);
  19170. ++numActiveChans;
  19171. }
  19172. }
  19173. AudioSampleBuffer buffer (channels, numActiveChans, numSamples);
  19174. info.buffer = &buffer;
  19175. info.startSample = 0;
  19176. info.numSamples = numSamples;
  19177. source->getNextAudioBlock (info);
  19178. for (i = info.buffer->getNumChannels(); --i >= 0;)
  19179. info.buffer->applyGainRamp (i, info.startSample, info.numSamples, lastGain, gain);
  19180. lastGain = gain;
  19181. }
  19182. else
  19183. {
  19184. for (int i = 0; i < totalNumOutputChannels; ++i)
  19185. if (outputChannelData[i] != 0)
  19186. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  19187. }
  19188. }
  19189. void AudioSourcePlayer::audioDeviceAboutToStart (AudioIODevice* device)
  19190. {
  19191. sampleRate = device->getCurrentSampleRate();
  19192. bufferSize = device->getCurrentBufferSizeSamples();
  19193. zeromem (channels, sizeof (channels));
  19194. if (source != 0)
  19195. source->prepareToPlay (bufferSize, sampleRate);
  19196. }
  19197. void AudioSourcePlayer::audioDeviceStopped()
  19198. {
  19199. if (source != 0)
  19200. source->releaseResources();
  19201. sampleRate = 0.0;
  19202. bufferSize = 0;
  19203. tempBuffer.setSize (2, 8);
  19204. }
  19205. END_JUCE_NAMESPACE
  19206. /*** End of inlined file: juce_AudioSourcePlayer.cpp ***/
  19207. /*** Start of inlined file: juce_AudioTransportSource.cpp ***/
  19208. BEGIN_JUCE_NAMESPACE
  19209. AudioTransportSource::AudioTransportSource()
  19210. : source (0),
  19211. resamplerSource (0),
  19212. bufferingSource (0),
  19213. positionableSource (0),
  19214. masterSource (0),
  19215. gain (1.0f),
  19216. lastGain (1.0f),
  19217. playing (false),
  19218. stopped (true),
  19219. sampleRate (44100.0),
  19220. sourceSampleRate (0.0),
  19221. blockSize (128),
  19222. readAheadBufferSize (0),
  19223. isPrepared (false),
  19224. inputStreamEOF (false)
  19225. {
  19226. }
  19227. AudioTransportSource::~AudioTransportSource()
  19228. {
  19229. setSource (0);
  19230. releaseResources();
  19231. }
  19232. void AudioTransportSource::setSource (PositionableAudioSource* const newSource,
  19233. int readAheadBufferSize_,
  19234. double sourceSampleRateToCorrectFor)
  19235. {
  19236. if (source == newSource)
  19237. {
  19238. if (source == 0)
  19239. return;
  19240. setSource (0, 0, 0); // deselect and reselect to avoid releasing resources wrongly
  19241. }
  19242. readAheadBufferSize = readAheadBufferSize_;
  19243. sourceSampleRate = sourceSampleRateToCorrectFor;
  19244. ResamplingAudioSource* newResamplerSource = 0;
  19245. BufferingAudioSource* newBufferingSource = 0;
  19246. PositionableAudioSource* newPositionableSource = 0;
  19247. AudioSource* newMasterSource = 0;
  19248. ScopedPointer <ResamplingAudioSource> oldResamplerSource (resamplerSource);
  19249. ScopedPointer <BufferingAudioSource> oldBufferingSource (bufferingSource);
  19250. AudioSource* oldMasterSource = masterSource;
  19251. if (newSource != 0)
  19252. {
  19253. newPositionableSource = newSource;
  19254. if (readAheadBufferSize_ > 0)
  19255. newPositionableSource = newBufferingSource
  19256. = new BufferingAudioSource (newPositionableSource, false, readAheadBufferSize_);
  19257. newPositionableSource->setNextReadPosition (0);
  19258. if (sourceSampleRateToCorrectFor != 0)
  19259. newMasterSource = newResamplerSource
  19260. = new ResamplingAudioSource (newPositionableSource, false);
  19261. else
  19262. newMasterSource = newPositionableSource;
  19263. if (isPrepared)
  19264. {
  19265. if (newResamplerSource != 0 && sourceSampleRate > 0 && sampleRate > 0)
  19266. newResamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  19267. newMasterSource->prepareToPlay (blockSize, sampleRate);
  19268. }
  19269. }
  19270. {
  19271. const ScopedLock sl (callbackLock);
  19272. source = newSource;
  19273. resamplerSource = newResamplerSource;
  19274. bufferingSource = newBufferingSource;
  19275. masterSource = newMasterSource;
  19276. positionableSource = newPositionableSource;
  19277. playing = false;
  19278. }
  19279. if (oldMasterSource != 0)
  19280. oldMasterSource->releaseResources();
  19281. }
  19282. void AudioTransportSource::start()
  19283. {
  19284. if ((! playing) && masterSource != 0)
  19285. {
  19286. {
  19287. const ScopedLock sl (callbackLock);
  19288. playing = true;
  19289. stopped = false;
  19290. inputStreamEOF = false;
  19291. }
  19292. sendChangeMessage (this);
  19293. }
  19294. }
  19295. void AudioTransportSource::stop()
  19296. {
  19297. if (playing)
  19298. {
  19299. {
  19300. const ScopedLock sl (callbackLock);
  19301. playing = false;
  19302. }
  19303. int n = 500;
  19304. while (--n >= 0 && ! stopped)
  19305. Thread::sleep (2);
  19306. sendChangeMessage (this);
  19307. }
  19308. }
  19309. void AudioTransportSource::setPosition (double newPosition)
  19310. {
  19311. if (sampleRate > 0.0)
  19312. setNextReadPosition (roundToInt (newPosition * sampleRate));
  19313. }
  19314. double AudioTransportSource::getCurrentPosition() const
  19315. {
  19316. if (sampleRate > 0.0)
  19317. return getNextReadPosition() / sampleRate;
  19318. else
  19319. return 0.0;
  19320. }
  19321. void AudioTransportSource::setNextReadPosition (int newPosition)
  19322. {
  19323. if (positionableSource != 0)
  19324. {
  19325. if (sampleRate > 0 && sourceSampleRate > 0)
  19326. newPosition = roundToInt (newPosition * sourceSampleRate / sampleRate);
  19327. positionableSource->setNextReadPosition (newPosition);
  19328. }
  19329. }
  19330. int AudioTransportSource::getNextReadPosition() const
  19331. {
  19332. if (positionableSource != 0)
  19333. {
  19334. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  19335. return roundToInt (positionableSource->getNextReadPosition() * ratio);
  19336. }
  19337. return 0;
  19338. }
  19339. int AudioTransportSource::getTotalLength() const
  19340. {
  19341. const ScopedLock sl (callbackLock);
  19342. if (positionableSource != 0)
  19343. {
  19344. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  19345. return roundToInt (positionableSource->getTotalLength() * ratio);
  19346. }
  19347. return 0;
  19348. }
  19349. bool AudioTransportSource::isLooping() const
  19350. {
  19351. const ScopedLock sl (callbackLock);
  19352. return positionableSource != 0
  19353. && positionableSource->isLooping();
  19354. }
  19355. void AudioTransportSource::setGain (const float newGain) throw()
  19356. {
  19357. gain = newGain;
  19358. }
  19359. void AudioTransportSource::prepareToPlay (int samplesPerBlockExpected,
  19360. double sampleRate_)
  19361. {
  19362. const ScopedLock sl (callbackLock);
  19363. sampleRate = sampleRate_;
  19364. blockSize = samplesPerBlockExpected;
  19365. if (masterSource != 0)
  19366. masterSource->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19367. if (resamplerSource != 0 && sourceSampleRate != 0)
  19368. resamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  19369. isPrepared = true;
  19370. }
  19371. void AudioTransportSource::releaseResources()
  19372. {
  19373. const ScopedLock sl (callbackLock);
  19374. if (masterSource != 0)
  19375. masterSource->releaseResources();
  19376. isPrepared = false;
  19377. }
  19378. void AudioTransportSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19379. {
  19380. const ScopedLock sl (callbackLock);
  19381. inputStreamEOF = false;
  19382. if (masterSource != 0 && ! stopped)
  19383. {
  19384. masterSource->getNextAudioBlock (info);
  19385. if (! playing)
  19386. {
  19387. // just stopped playing, so fade out the last block..
  19388. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  19389. info.buffer->applyGainRamp (i, info.startSample, jmin (256, info.numSamples), 1.0f, 0.0f);
  19390. if (info.numSamples > 256)
  19391. info.buffer->clear (info.startSample + 256, info.numSamples - 256);
  19392. }
  19393. if (positionableSource->getNextReadPosition() > positionableSource->getTotalLength() + 1
  19394. && ! positionableSource->isLooping())
  19395. {
  19396. playing = false;
  19397. inputStreamEOF = true;
  19398. sendChangeMessage (this);
  19399. }
  19400. stopped = ! playing;
  19401. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  19402. {
  19403. info.buffer->applyGainRamp (i, info.startSample, info.numSamples,
  19404. lastGain, gain);
  19405. }
  19406. }
  19407. else
  19408. {
  19409. info.clearActiveBufferRegion();
  19410. stopped = true;
  19411. }
  19412. lastGain = gain;
  19413. }
  19414. END_JUCE_NAMESPACE
  19415. /*** End of inlined file: juce_AudioTransportSource.cpp ***/
  19416. /*** Start of inlined file: juce_BufferingAudioSource.cpp ***/
  19417. BEGIN_JUCE_NAMESPACE
  19418. class SharedBufferingAudioSourceThread : public DeletedAtShutdown,
  19419. public Thread,
  19420. private Timer
  19421. {
  19422. public:
  19423. SharedBufferingAudioSourceThread()
  19424. : Thread ("Audio Buffer")
  19425. {
  19426. }
  19427. ~SharedBufferingAudioSourceThread()
  19428. {
  19429. stopThread (10000);
  19430. clearSingletonInstance();
  19431. }
  19432. juce_DeclareSingleton (SharedBufferingAudioSourceThread, false)
  19433. void addSource (BufferingAudioSource* source)
  19434. {
  19435. const ScopedLock sl (lock);
  19436. if (! sources.contains (source))
  19437. {
  19438. sources.add (source);
  19439. startThread();
  19440. stopTimer();
  19441. }
  19442. notify();
  19443. }
  19444. void removeSource (BufferingAudioSource* source)
  19445. {
  19446. const ScopedLock sl (lock);
  19447. sources.removeValue (source);
  19448. if (sources.size() == 0)
  19449. startTimer (5000);
  19450. }
  19451. private:
  19452. Array <BufferingAudioSource*> sources;
  19453. CriticalSection lock;
  19454. void run()
  19455. {
  19456. while (! threadShouldExit())
  19457. {
  19458. bool busy = false;
  19459. for (int i = sources.size(); --i >= 0;)
  19460. {
  19461. if (threadShouldExit())
  19462. return;
  19463. const ScopedLock sl (lock);
  19464. BufferingAudioSource* const b = sources[i];
  19465. if (b != 0 && b->readNextBufferChunk())
  19466. busy = true;
  19467. }
  19468. if (! busy)
  19469. wait (500);
  19470. }
  19471. }
  19472. void timerCallback()
  19473. {
  19474. stopTimer();
  19475. if (sources.size() == 0)
  19476. deleteInstance();
  19477. }
  19478. SharedBufferingAudioSourceThread (const SharedBufferingAudioSourceThread&);
  19479. SharedBufferingAudioSourceThread& operator= (const SharedBufferingAudioSourceThread&);
  19480. };
  19481. juce_ImplementSingleton (SharedBufferingAudioSourceThread)
  19482. BufferingAudioSource::BufferingAudioSource (PositionableAudioSource* source_,
  19483. const bool deleteSourceWhenDeleted_,
  19484. int numberOfSamplesToBuffer_)
  19485. : source (source_),
  19486. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  19487. numberOfSamplesToBuffer (jmax (1024, numberOfSamplesToBuffer_)),
  19488. buffer (2, 0),
  19489. bufferValidStart (0),
  19490. bufferValidEnd (0),
  19491. nextPlayPos (0),
  19492. wasSourceLooping (false)
  19493. {
  19494. jassert (source_ != 0);
  19495. jassert (numberOfSamplesToBuffer_ > 1024); // not much point using this class if you're
  19496. // not using a larger buffer..
  19497. }
  19498. BufferingAudioSource::~BufferingAudioSource()
  19499. {
  19500. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19501. if (thread != 0)
  19502. thread->removeSource (this);
  19503. if (deleteSourceWhenDeleted)
  19504. delete source;
  19505. }
  19506. void BufferingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate_)
  19507. {
  19508. source->prepareToPlay (samplesPerBlockExpected, sampleRate_);
  19509. sampleRate = sampleRate_;
  19510. buffer.setSize (2, jmax (samplesPerBlockExpected * 2, numberOfSamplesToBuffer));
  19511. buffer.clear();
  19512. bufferValidStart = 0;
  19513. bufferValidEnd = 0;
  19514. SharedBufferingAudioSourceThread::getInstance()->addSource (this);
  19515. while (bufferValidEnd - bufferValidStart < jmin (((int) sampleRate_) / 4,
  19516. buffer.getNumSamples() / 2))
  19517. {
  19518. SharedBufferingAudioSourceThread::getInstance()->notify();
  19519. Thread::sleep (5);
  19520. }
  19521. }
  19522. void BufferingAudioSource::releaseResources()
  19523. {
  19524. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19525. if (thread != 0)
  19526. thread->removeSource (this);
  19527. buffer.setSize (2, 0);
  19528. source->releaseResources();
  19529. }
  19530. void BufferingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19531. {
  19532. const ScopedLock sl (bufferStartPosLock);
  19533. const int validStart = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos) - nextPlayPos;
  19534. const int validEnd = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos + info.numSamples) - nextPlayPos;
  19535. if (validStart == validEnd)
  19536. {
  19537. // total cache miss
  19538. info.clearActiveBufferRegion();
  19539. }
  19540. else
  19541. {
  19542. if (validStart > 0)
  19543. info.buffer->clear (info.startSample, validStart); // partial cache miss at start
  19544. if (validEnd < info.numSamples)
  19545. info.buffer->clear (info.startSample + validEnd,
  19546. info.numSamples - validEnd); // partial cache miss at end
  19547. if (validStart < validEnd)
  19548. {
  19549. for (int chan = jmin (2, info.buffer->getNumChannels()); --chan >= 0;)
  19550. {
  19551. const int startBufferIndex = (validStart + nextPlayPos) % buffer.getNumSamples();
  19552. const int endBufferIndex = (validEnd + nextPlayPos) % buffer.getNumSamples();
  19553. if (startBufferIndex < endBufferIndex)
  19554. {
  19555. info.buffer->copyFrom (chan, info.startSample + validStart,
  19556. buffer,
  19557. chan, startBufferIndex,
  19558. validEnd - validStart);
  19559. }
  19560. else
  19561. {
  19562. const int initialSize = buffer.getNumSamples() - startBufferIndex;
  19563. info.buffer->copyFrom (chan, info.startSample + validStart,
  19564. buffer,
  19565. chan, startBufferIndex,
  19566. initialSize);
  19567. info.buffer->copyFrom (chan, info.startSample + validStart + initialSize,
  19568. buffer,
  19569. chan, 0,
  19570. (validEnd - validStart) - initialSize);
  19571. }
  19572. }
  19573. }
  19574. nextPlayPos += info.numSamples;
  19575. if (source->isLooping() && nextPlayPos > 0)
  19576. nextPlayPos %= source->getTotalLength();
  19577. }
  19578. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19579. if (thread != 0)
  19580. thread->notify();
  19581. }
  19582. int BufferingAudioSource::getNextReadPosition() const
  19583. {
  19584. return (source->isLooping() && nextPlayPos > 0)
  19585. ? nextPlayPos % source->getTotalLength()
  19586. : nextPlayPos;
  19587. }
  19588. void BufferingAudioSource::setNextReadPosition (int newPosition)
  19589. {
  19590. const ScopedLock sl (bufferStartPosLock);
  19591. nextPlayPos = newPosition;
  19592. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19593. if (thread != 0)
  19594. thread->notify();
  19595. }
  19596. bool BufferingAudioSource::readNextBufferChunk()
  19597. {
  19598. int newBVS, newBVE, sectionToReadStart, sectionToReadEnd;
  19599. {
  19600. const ScopedLock sl (bufferStartPosLock);
  19601. if (wasSourceLooping != isLooping())
  19602. {
  19603. wasSourceLooping = isLooping();
  19604. bufferValidStart = 0;
  19605. bufferValidEnd = 0;
  19606. }
  19607. newBVS = jmax (0, nextPlayPos);
  19608. newBVE = newBVS + buffer.getNumSamples() - 4;
  19609. sectionToReadStart = 0;
  19610. sectionToReadEnd = 0;
  19611. const int maxChunkSize = 2048;
  19612. if (newBVS < bufferValidStart || newBVS >= bufferValidEnd)
  19613. {
  19614. newBVE = jmin (newBVE, newBVS + maxChunkSize);
  19615. sectionToReadStart = newBVS;
  19616. sectionToReadEnd = newBVE;
  19617. bufferValidStart = 0;
  19618. bufferValidEnd = 0;
  19619. }
  19620. else if (abs (newBVS - bufferValidStart) > 512
  19621. || abs (newBVE - bufferValidEnd) > 512)
  19622. {
  19623. newBVE = jmin (newBVE, bufferValidEnd + maxChunkSize);
  19624. sectionToReadStart = bufferValidEnd;
  19625. sectionToReadEnd = newBVE;
  19626. bufferValidStart = newBVS;
  19627. bufferValidEnd = jmin (bufferValidEnd, newBVE);
  19628. }
  19629. }
  19630. if (sectionToReadStart != sectionToReadEnd)
  19631. {
  19632. const int bufferIndexStart = sectionToReadStart % buffer.getNumSamples();
  19633. const int bufferIndexEnd = sectionToReadEnd % buffer.getNumSamples();
  19634. if (bufferIndexStart < bufferIndexEnd)
  19635. {
  19636. readBufferSection (sectionToReadStart,
  19637. sectionToReadEnd - sectionToReadStart,
  19638. bufferIndexStart);
  19639. }
  19640. else
  19641. {
  19642. const int initialSize = buffer.getNumSamples() - bufferIndexStart;
  19643. readBufferSection (sectionToReadStart,
  19644. initialSize,
  19645. bufferIndexStart);
  19646. readBufferSection (sectionToReadStart + initialSize,
  19647. (sectionToReadEnd - sectionToReadStart) - initialSize,
  19648. 0);
  19649. }
  19650. const ScopedLock sl2 (bufferStartPosLock);
  19651. bufferValidStart = newBVS;
  19652. bufferValidEnd = newBVE;
  19653. return true;
  19654. }
  19655. else
  19656. {
  19657. return false;
  19658. }
  19659. }
  19660. void BufferingAudioSource::readBufferSection (int start, int length, int bufferOffset)
  19661. {
  19662. if (source->getNextReadPosition() != start)
  19663. source->setNextReadPosition (start);
  19664. AudioSourceChannelInfo info;
  19665. info.buffer = &buffer;
  19666. info.startSample = bufferOffset;
  19667. info.numSamples = length;
  19668. source->getNextAudioBlock (info);
  19669. }
  19670. END_JUCE_NAMESPACE
  19671. /*** End of inlined file: juce_BufferingAudioSource.cpp ***/
  19672. /*** Start of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  19673. BEGIN_JUCE_NAMESPACE
  19674. ChannelRemappingAudioSource::ChannelRemappingAudioSource (AudioSource* const source_,
  19675. const bool deleteSourceWhenDeleted_)
  19676. : requiredNumberOfChannels (2),
  19677. source (source_),
  19678. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  19679. buffer (2, 16)
  19680. {
  19681. remappedInfo.buffer = &buffer;
  19682. remappedInfo.startSample = 0;
  19683. }
  19684. ChannelRemappingAudioSource::~ChannelRemappingAudioSource()
  19685. {
  19686. if (deleteSourceWhenDeleted)
  19687. delete source;
  19688. }
  19689. void ChannelRemappingAudioSource::setNumberOfChannelsToProduce (const int requiredNumberOfChannels_)
  19690. {
  19691. const ScopedLock sl (lock);
  19692. requiredNumberOfChannels = requiredNumberOfChannels_;
  19693. }
  19694. void ChannelRemappingAudioSource::clearAllMappings()
  19695. {
  19696. const ScopedLock sl (lock);
  19697. remappedInputs.clear();
  19698. remappedOutputs.clear();
  19699. }
  19700. void ChannelRemappingAudioSource::setInputChannelMapping (const int destIndex, const int sourceIndex)
  19701. {
  19702. const ScopedLock sl (lock);
  19703. while (remappedInputs.size() < destIndex)
  19704. remappedInputs.add (-1);
  19705. remappedInputs.set (destIndex, sourceIndex);
  19706. }
  19707. void ChannelRemappingAudioSource::setOutputChannelMapping (const int sourceIndex, const int destIndex)
  19708. {
  19709. const ScopedLock sl (lock);
  19710. while (remappedOutputs.size() < sourceIndex)
  19711. remappedOutputs.add (-1);
  19712. remappedOutputs.set (sourceIndex, destIndex);
  19713. }
  19714. int ChannelRemappingAudioSource::getRemappedInputChannel (const int inputChannelIndex) const
  19715. {
  19716. const ScopedLock sl (lock);
  19717. if (inputChannelIndex >= 0 && inputChannelIndex < remappedInputs.size())
  19718. return remappedInputs.getUnchecked (inputChannelIndex);
  19719. return -1;
  19720. }
  19721. int ChannelRemappingAudioSource::getRemappedOutputChannel (const int outputChannelIndex) const
  19722. {
  19723. const ScopedLock sl (lock);
  19724. if (outputChannelIndex >= 0 && outputChannelIndex < remappedOutputs.size())
  19725. return remappedOutputs .getUnchecked (outputChannelIndex);
  19726. return -1;
  19727. }
  19728. void ChannelRemappingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19729. {
  19730. source->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19731. }
  19732. void ChannelRemappingAudioSource::releaseResources()
  19733. {
  19734. source->releaseResources();
  19735. }
  19736. void ChannelRemappingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  19737. {
  19738. const ScopedLock sl (lock);
  19739. buffer.setSize (requiredNumberOfChannels, bufferToFill.numSamples, false, false, true);
  19740. const int numChans = bufferToFill.buffer->getNumChannels();
  19741. int i;
  19742. for (i = 0; i < buffer.getNumChannels(); ++i)
  19743. {
  19744. const int remappedChan = getRemappedInputChannel (i);
  19745. if (remappedChan >= 0 && remappedChan < numChans)
  19746. {
  19747. buffer.copyFrom (i, 0, *bufferToFill.buffer,
  19748. remappedChan,
  19749. bufferToFill.startSample,
  19750. bufferToFill.numSamples);
  19751. }
  19752. else
  19753. {
  19754. buffer.clear (i, 0, bufferToFill.numSamples);
  19755. }
  19756. }
  19757. remappedInfo.numSamples = bufferToFill.numSamples;
  19758. source->getNextAudioBlock (remappedInfo);
  19759. bufferToFill.clearActiveBufferRegion();
  19760. for (i = 0; i < requiredNumberOfChannels; ++i)
  19761. {
  19762. const int remappedChan = getRemappedOutputChannel (i);
  19763. if (remappedChan >= 0 && remappedChan < numChans)
  19764. {
  19765. bufferToFill.buffer->addFrom (remappedChan, bufferToFill.startSample,
  19766. buffer, i, 0, bufferToFill.numSamples);
  19767. }
  19768. }
  19769. }
  19770. XmlElement* ChannelRemappingAudioSource::createXml() const
  19771. {
  19772. XmlElement* e = new XmlElement ("MAPPINGS");
  19773. String ins, outs;
  19774. int i;
  19775. const ScopedLock sl (lock);
  19776. for (i = 0; i < remappedInputs.size(); ++i)
  19777. ins << remappedInputs.getUnchecked(i) << ' ';
  19778. for (i = 0; i < remappedOutputs.size(); ++i)
  19779. outs << remappedOutputs.getUnchecked(i) << ' ';
  19780. e->setAttribute ("inputs", ins.trimEnd());
  19781. e->setAttribute ("outputs", outs.trimEnd());
  19782. return e;
  19783. }
  19784. void ChannelRemappingAudioSource::restoreFromXml (const XmlElement& e)
  19785. {
  19786. if (e.hasTagName ("MAPPINGS"))
  19787. {
  19788. const ScopedLock sl (lock);
  19789. clearAllMappings();
  19790. StringArray ins, outs;
  19791. ins.addTokens (e.getStringAttribute ("inputs"), false);
  19792. outs.addTokens (e.getStringAttribute ("outputs"), false);
  19793. int i;
  19794. for (i = 0; i < ins.size(); ++i)
  19795. remappedInputs.add (ins[i].getIntValue());
  19796. for (i = 0; i < outs.size(); ++i)
  19797. remappedOutputs.add (outs[i].getIntValue());
  19798. }
  19799. }
  19800. END_JUCE_NAMESPACE
  19801. /*** End of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  19802. /*** Start of inlined file: juce_IIRFilterAudioSource.cpp ***/
  19803. BEGIN_JUCE_NAMESPACE
  19804. IIRFilterAudioSource::IIRFilterAudioSource (AudioSource* const inputSource,
  19805. const bool deleteInputWhenDeleted_)
  19806. : input (inputSource),
  19807. deleteInputWhenDeleted (deleteInputWhenDeleted_)
  19808. {
  19809. jassert (inputSource != 0);
  19810. for (int i = 2; --i >= 0;)
  19811. iirFilters.add (new IIRFilter());
  19812. }
  19813. IIRFilterAudioSource::~IIRFilterAudioSource()
  19814. {
  19815. if (deleteInputWhenDeleted)
  19816. delete input;
  19817. }
  19818. void IIRFilterAudioSource::setFilterParameters (const IIRFilter& newSettings)
  19819. {
  19820. for (int i = iirFilters.size(); --i >= 0;)
  19821. iirFilters.getUnchecked(i)->copyCoefficientsFrom (newSettings);
  19822. }
  19823. void IIRFilterAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19824. {
  19825. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19826. for (int i = iirFilters.size(); --i >= 0;)
  19827. iirFilters.getUnchecked(i)->reset();
  19828. }
  19829. void IIRFilterAudioSource::releaseResources()
  19830. {
  19831. input->releaseResources();
  19832. }
  19833. void IIRFilterAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  19834. {
  19835. input->getNextAudioBlock (bufferToFill);
  19836. const int numChannels = bufferToFill.buffer->getNumChannels();
  19837. while (numChannels > iirFilters.size())
  19838. iirFilters.add (new IIRFilter (*iirFilters.getUnchecked (0)));
  19839. for (int i = 0; i < numChannels; ++i)
  19840. iirFilters.getUnchecked(i)
  19841. ->processSamples (bufferToFill.buffer->getSampleData (i, bufferToFill.startSample),
  19842. bufferToFill.numSamples);
  19843. }
  19844. END_JUCE_NAMESPACE
  19845. /*** End of inlined file: juce_IIRFilterAudioSource.cpp ***/
  19846. /*** Start of inlined file: juce_MixerAudioSource.cpp ***/
  19847. BEGIN_JUCE_NAMESPACE
  19848. MixerAudioSource::MixerAudioSource()
  19849. : tempBuffer (2, 0),
  19850. currentSampleRate (0.0),
  19851. bufferSizeExpected (0)
  19852. {
  19853. }
  19854. MixerAudioSource::~MixerAudioSource()
  19855. {
  19856. removeAllInputs();
  19857. }
  19858. void MixerAudioSource::addInputSource (AudioSource* input, const bool deleteWhenRemoved)
  19859. {
  19860. if (input != 0 && ! inputs.contains (input))
  19861. {
  19862. double localRate;
  19863. int localBufferSize;
  19864. {
  19865. const ScopedLock sl (lock);
  19866. localRate = currentSampleRate;
  19867. localBufferSize = bufferSizeExpected;
  19868. }
  19869. if (localRate != 0.0)
  19870. input->prepareToPlay (localBufferSize, localRate);
  19871. const ScopedLock sl (lock);
  19872. inputsToDelete.setBit (inputs.size(), deleteWhenRemoved);
  19873. inputs.add (input);
  19874. }
  19875. }
  19876. void MixerAudioSource::removeInputSource (AudioSource* input, const bool deleteInput)
  19877. {
  19878. if (input != 0)
  19879. {
  19880. int index;
  19881. {
  19882. const ScopedLock sl (lock);
  19883. index = inputs.indexOf (input);
  19884. if (index >= 0)
  19885. {
  19886. inputsToDelete.shiftBits (index, 1);
  19887. inputs.remove (index);
  19888. }
  19889. }
  19890. if (index >= 0)
  19891. {
  19892. input->releaseResources();
  19893. if (deleteInput)
  19894. delete input;
  19895. }
  19896. }
  19897. }
  19898. void MixerAudioSource::removeAllInputs()
  19899. {
  19900. OwnedArray<AudioSource> toDelete;
  19901. {
  19902. const ScopedLock sl (lock);
  19903. for (int i = inputs.size(); --i >= 0;)
  19904. if (inputsToDelete[i])
  19905. toDelete.add (inputs.getUnchecked(i));
  19906. }
  19907. }
  19908. void MixerAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19909. {
  19910. tempBuffer.setSize (2, samplesPerBlockExpected);
  19911. const ScopedLock sl (lock);
  19912. currentSampleRate = sampleRate;
  19913. bufferSizeExpected = samplesPerBlockExpected;
  19914. for (int i = inputs.size(); --i >= 0;)
  19915. inputs.getUnchecked(i)->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19916. }
  19917. void MixerAudioSource::releaseResources()
  19918. {
  19919. const ScopedLock sl (lock);
  19920. for (int i = inputs.size(); --i >= 0;)
  19921. inputs.getUnchecked(i)->releaseResources();
  19922. tempBuffer.setSize (2, 0);
  19923. currentSampleRate = 0;
  19924. bufferSizeExpected = 0;
  19925. }
  19926. void MixerAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19927. {
  19928. const ScopedLock sl (lock);
  19929. if (inputs.size() > 0)
  19930. {
  19931. inputs.getUnchecked(0)->getNextAudioBlock (info);
  19932. if (inputs.size() > 1)
  19933. {
  19934. tempBuffer.setSize (jmax (1, info.buffer->getNumChannels()),
  19935. info.buffer->getNumSamples());
  19936. AudioSourceChannelInfo info2;
  19937. info2.buffer = &tempBuffer;
  19938. info2.numSamples = info.numSamples;
  19939. info2.startSample = 0;
  19940. for (int i = 1; i < inputs.size(); ++i)
  19941. {
  19942. inputs.getUnchecked(i)->getNextAudioBlock (info2);
  19943. for (int chan = 0; chan < info.buffer->getNumChannels(); ++chan)
  19944. info.buffer->addFrom (chan, info.startSample, tempBuffer, chan, 0, info.numSamples);
  19945. }
  19946. }
  19947. }
  19948. else
  19949. {
  19950. info.clearActiveBufferRegion();
  19951. }
  19952. }
  19953. END_JUCE_NAMESPACE
  19954. /*** End of inlined file: juce_MixerAudioSource.cpp ***/
  19955. /*** Start of inlined file: juce_ResamplingAudioSource.cpp ***/
  19956. BEGIN_JUCE_NAMESPACE
  19957. ResamplingAudioSource::ResamplingAudioSource (AudioSource* const inputSource,
  19958. const bool deleteInputWhenDeleted_,
  19959. const int numChannels_)
  19960. : input (inputSource),
  19961. deleteInputWhenDeleted (deleteInputWhenDeleted_),
  19962. ratio (1.0),
  19963. lastRatio (1.0),
  19964. buffer (numChannels_, 0),
  19965. sampsInBuffer (0),
  19966. numChannels (numChannels_)
  19967. {
  19968. jassert (input != 0);
  19969. }
  19970. ResamplingAudioSource::~ResamplingAudioSource()
  19971. {
  19972. if (deleteInputWhenDeleted)
  19973. delete input;
  19974. }
  19975. void ResamplingAudioSource::setResamplingRatio (const double samplesInPerOutputSample)
  19976. {
  19977. jassert (samplesInPerOutputSample > 0);
  19978. const ScopedLock sl (ratioLock);
  19979. ratio = jmax (0.0, samplesInPerOutputSample);
  19980. }
  19981. void ResamplingAudioSource::prepareToPlay (int samplesPerBlockExpected,
  19982. double sampleRate)
  19983. {
  19984. const ScopedLock sl (ratioLock);
  19985. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19986. buffer.setSize (numChannels, roundToInt (samplesPerBlockExpected * ratio) + 32);
  19987. buffer.clear();
  19988. sampsInBuffer = 0;
  19989. bufferPos = 0;
  19990. subSampleOffset = 0.0;
  19991. filterStates.calloc (numChannels);
  19992. srcBuffers.calloc (numChannels);
  19993. destBuffers.calloc (numChannels);
  19994. createLowPass (ratio);
  19995. resetFilters();
  19996. }
  19997. void ResamplingAudioSource::releaseResources()
  19998. {
  19999. input->releaseResources();
  20000. buffer.setSize (numChannels, 0);
  20001. }
  20002. void ResamplingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  20003. {
  20004. const ScopedLock sl (ratioLock);
  20005. if (lastRatio != ratio)
  20006. {
  20007. createLowPass (ratio);
  20008. lastRatio = ratio;
  20009. }
  20010. const int sampsNeeded = roundToInt (info.numSamples * ratio) + 2;
  20011. int bufferSize = buffer.getNumSamples();
  20012. if (bufferSize < sampsNeeded + 8)
  20013. {
  20014. bufferPos %= bufferSize;
  20015. bufferSize = sampsNeeded + 32;
  20016. buffer.setSize (buffer.getNumChannels(), bufferSize, true, true);
  20017. }
  20018. bufferPos %= bufferSize;
  20019. int endOfBufferPos = bufferPos + sampsInBuffer;
  20020. const int channelsToProcess = jmin (numChannels, info.buffer->getNumChannels());
  20021. while (sampsNeeded > sampsInBuffer)
  20022. {
  20023. endOfBufferPos %= bufferSize;
  20024. int numToDo = jmin (sampsNeeded - sampsInBuffer,
  20025. bufferSize - endOfBufferPos);
  20026. AudioSourceChannelInfo readInfo;
  20027. readInfo.buffer = &buffer;
  20028. readInfo.numSamples = numToDo;
  20029. readInfo.startSample = endOfBufferPos;
  20030. input->getNextAudioBlock (readInfo);
  20031. if (ratio > 1.0001)
  20032. {
  20033. // for down-sampling, pre-apply the filter..
  20034. for (int i = channelsToProcess; --i >= 0;)
  20035. applyFilter (buffer.getSampleData (i, endOfBufferPos), numToDo, filterStates[i]);
  20036. }
  20037. sampsInBuffer += numToDo;
  20038. endOfBufferPos += numToDo;
  20039. }
  20040. for (int channel = 0; channel < channelsToProcess; ++channel)
  20041. {
  20042. destBuffers[channel] = info.buffer->getSampleData (channel, info.startSample);
  20043. srcBuffers[channel] = buffer.getSampleData (channel, 0);
  20044. }
  20045. int nextPos = (bufferPos + 1) % bufferSize;
  20046. for (int m = info.numSamples; --m >= 0;)
  20047. {
  20048. const float alpha = (float) subSampleOffset;
  20049. const float invAlpha = 1.0f - alpha;
  20050. for (int channel = 0; channel < channelsToProcess; ++channel)
  20051. *destBuffers[channel]++ = srcBuffers[channel][bufferPos] * invAlpha + srcBuffers[channel][nextPos] * alpha;
  20052. subSampleOffset += ratio;
  20053. jassert (sampsInBuffer > 0);
  20054. while (subSampleOffset >= 1.0)
  20055. {
  20056. if (++bufferPos >= bufferSize)
  20057. bufferPos = 0;
  20058. --sampsInBuffer;
  20059. nextPos = (bufferPos + 1) % bufferSize;
  20060. subSampleOffset -= 1.0;
  20061. }
  20062. }
  20063. if (ratio < 0.9999)
  20064. {
  20065. // for up-sampling, apply the filter after transposing..
  20066. for (int i = channelsToProcess; --i >= 0;)
  20067. applyFilter (info.buffer->getSampleData (i, info.startSample), info.numSamples, filterStates[i]);
  20068. }
  20069. else if (ratio <= 1.0001)
  20070. {
  20071. // if the filter's not currently being applied, keep it stoked with the last couple of samples to avoid discontinuities
  20072. for (int i = channelsToProcess; --i >= 0;)
  20073. {
  20074. const float* const endOfBuffer = info.buffer->getSampleData (i, info.startSample + info.numSamples - 1);
  20075. FilterState& fs = filterStates[i];
  20076. if (info.numSamples > 1)
  20077. {
  20078. fs.y2 = fs.x2 = *(endOfBuffer - 1);
  20079. }
  20080. else
  20081. {
  20082. fs.y2 = fs.y1;
  20083. fs.x2 = fs.x1;
  20084. }
  20085. fs.y1 = fs.x1 = *endOfBuffer;
  20086. }
  20087. }
  20088. jassert (sampsInBuffer >= 0);
  20089. }
  20090. void ResamplingAudioSource::createLowPass (const double frequencyRatio)
  20091. {
  20092. const double proportionalRate = (frequencyRatio > 1.0) ? 0.5 / frequencyRatio
  20093. : 0.5 * frequencyRatio;
  20094. const double n = 1.0 / tan (double_Pi * jmax (0.001, proportionalRate));
  20095. const double nSquared = n * n;
  20096. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  20097. setFilterCoefficients (c1,
  20098. c1 * 2.0f,
  20099. c1,
  20100. 1.0,
  20101. c1 * 2.0 * (1.0 - nSquared),
  20102. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  20103. }
  20104. void ResamplingAudioSource::setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6)
  20105. {
  20106. const double a = 1.0 / c4;
  20107. c1 *= a;
  20108. c2 *= a;
  20109. c3 *= a;
  20110. c5 *= a;
  20111. c6 *= a;
  20112. coefficients[0] = c1;
  20113. coefficients[1] = c2;
  20114. coefficients[2] = c3;
  20115. coefficients[3] = c4;
  20116. coefficients[4] = c5;
  20117. coefficients[5] = c6;
  20118. }
  20119. void ResamplingAudioSource::resetFilters()
  20120. {
  20121. zeromem (filterStates, sizeof (FilterState) * numChannels);
  20122. }
  20123. void ResamplingAudioSource::applyFilter (float* samples, int num, FilterState& fs)
  20124. {
  20125. while (--num >= 0)
  20126. {
  20127. const double in = *samples;
  20128. double out = coefficients[0] * in
  20129. + coefficients[1] * fs.x1
  20130. + coefficients[2] * fs.x2
  20131. - coefficients[4] * fs.y1
  20132. - coefficients[5] * fs.y2;
  20133. #if JUCE_INTEL
  20134. if (! (out < -1.0e-8 || out > 1.0e-8))
  20135. out = 0;
  20136. #endif
  20137. fs.x2 = fs.x1;
  20138. fs.x1 = in;
  20139. fs.y2 = fs.y1;
  20140. fs.y1 = out;
  20141. *samples++ = (float) out;
  20142. }
  20143. }
  20144. END_JUCE_NAMESPACE
  20145. /*** End of inlined file: juce_ResamplingAudioSource.cpp ***/
  20146. /*** Start of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  20147. BEGIN_JUCE_NAMESPACE
  20148. ToneGeneratorAudioSource::ToneGeneratorAudioSource()
  20149. : frequency (1000.0),
  20150. sampleRate (44100.0),
  20151. currentPhase (0.0),
  20152. phasePerSample (0.0),
  20153. amplitude (0.5f)
  20154. {
  20155. }
  20156. ToneGeneratorAudioSource::~ToneGeneratorAudioSource()
  20157. {
  20158. }
  20159. void ToneGeneratorAudioSource::setAmplitude (const float newAmplitude)
  20160. {
  20161. amplitude = newAmplitude;
  20162. }
  20163. void ToneGeneratorAudioSource::setFrequency (const double newFrequencyHz)
  20164. {
  20165. frequency = newFrequencyHz;
  20166. phasePerSample = 0.0;
  20167. }
  20168. void ToneGeneratorAudioSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  20169. double sampleRate_)
  20170. {
  20171. currentPhase = 0.0;
  20172. phasePerSample = 0.0;
  20173. sampleRate = sampleRate_;
  20174. }
  20175. void ToneGeneratorAudioSource::releaseResources()
  20176. {
  20177. }
  20178. void ToneGeneratorAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  20179. {
  20180. if (phasePerSample == 0.0)
  20181. phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  20182. for (int i = 0; i < info.numSamples; ++i)
  20183. {
  20184. const float sample = amplitude * (float) std::sin (currentPhase);
  20185. currentPhase += phasePerSample;
  20186. for (int j = info.buffer->getNumChannels(); --j >= 0;)
  20187. *info.buffer->getSampleData (j, info.startSample + i) = sample;
  20188. }
  20189. }
  20190. END_JUCE_NAMESPACE
  20191. /*** End of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  20192. /*** Start of inlined file: juce_AudioDeviceManager.cpp ***/
  20193. BEGIN_JUCE_NAMESPACE
  20194. AudioDeviceManager::AudioDeviceSetup::AudioDeviceSetup()
  20195. : sampleRate (0),
  20196. bufferSize (0),
  20197. useDefaultInputChannels (true),
  20198. useDefaultOutputChannels (true)
  20199. {
  20200. }
  20201. bool AudioDeviceManager::AudioDeviceSetup::operator== (const AudioDeviceManager::AudioDeviceSetup& other) const
  20202. {
  20203. return outputDeviceName == other.outputDeviceName
  20204. && inputDeviceName == other.inputDeviceName
  20205. && sampleRate == other.sampleRate
  20206. && bufferSize == other.bufferSize
  20207. && inputChannels == other.inputChannels
  20208. && useDefaultInputChannels == other.useDefaultInputChannels
  20209. && outputChannels == other.outputChannels
  20210. && useDefaultOutputChannels == other.useDefaultOutputChannels;
  20211. }
  20212. AudioDeviceManager::AudioDeviceManager()
  20213. : currentAudioDevice (0),
  20214. numInputChansNeeded (0),
  20215. numOutputChansNeeded (2),
  20216. listNeedsScanning (true),
  20217. useInputNames (false),
  20218. inputLevelMeasurementEnabledCount (0),
  20219. inputLevel (0),
  20220. tempBuffer (2, 2),
  20221. defaultMidiOutput (0),
  20222. cpuUsageMs (0),
  20223. timeToCpuScale (0)
  20224. {
  20225. callbackHandler.owner = this;
  20226. }
  20227. AudioDeviceManager::~AudioDeviceManager()
  20228. {
  20229. currentAudioDevice = 0;
  20230. defaultMidiOutput = 0;
  20231. }
  20232. void AudioDeviceManager::createDeviceTypesIfNeeded()
  20233. {
  20234. if (availableDeviceTypes.size() == 0)
  20235. {
  20236. createAudioDeviceTypes (availableDeviceTypes);
  20237. while (lastDeviceTypeConfigs.size() < availableDeviceTypes.size())
  20238. lastDeviceTypeConfigs.add (new AudioDeviceSetup());
  20239. if (availableDeviceTypes.size() > 0)
  20240. currentDeviceType = availableDeviceTypes.getUnchecked(0)->getTypeName();
  20241. }
  20242. }
  20243. const OwnedArray <AudioIODeviceType>& AudioDeviceManager::getAvailableDeviceTypes()
  20244. {
  20245. scanDevicesIfNeeded();
  20246. return availableDeviceTypes;
  20247. }
  20248. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio();
  20249. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio();
  20250. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI();
  20251. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound();
  20252. AudioIODeviceType* juce_createAudioIODeviceType_ASIO();
  20253. AudioIODeviceType* juce_createAudioIODeviceType_ALSA();
  20254. AudioIODeviceType* juce_createAudioIODeviceType_JACK();
  20255. void AudioDeviceManager::createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& list)
  20256. {
  20257. (void) list; // (to avoid 'unused param' warnings)
  20258. #if JUCE_WINDOWS
  20259. #if JUCE_WASAPI
  20260. if (SystemStats::getOperatingSystemType() >= SystemStats::WinVista)
  20261. list.add (juce_createAudioIODeviceType_WASAPI());
  20262. #endif
  20263. #if JUCE_DIRECTSOUND
  20264. list.add (juce_createAudioIODeviceType_DirectSound());
  20265. #endif
  20266. #if JUCE_ASIO
  20267. list.add (juce_createAudioIODeviceType_ASIO());
  20268. #endif
  20269. #endif
  20270. #if JUCE_MAC
  20271. list.add (juce_createAudioIODeviceType_CoreAudio());
  20272. #endif
  20273. #if JUCE_IOS
  20274. list.add (juce_createAudioIODeviceType_iPhoneAudio());
  20275. #endif
  20276. #if JUCE_LINUX && JUCE_ALSA
  20277. list.add (juce_createAudioIODeviceType_ALSA());
  20278. #endif
  20279. #if JUCE_LINUX && JUCE_JACK
  20280. list.add (juce_createAudioIODeviceType_JACK());
  20281. #endif
  20282. }
  20283. const String AudioDeviceManager::initialise (const int numInputChannelsNeeded,
  20284. const int numOutputChannelsNeeded,
  20285. const XmlElement* const e,
  20286. const bool selectDefaultDeviceOnFailure,
  20287. const String& preferredDefaultDeviceName,
  20288. const AudioDeviceSetup* preferredSetupOptions)
  20289. {
  20290. scanDevicesIfNeeded();
  20291. numInputChansNeeded = numInputChannelsNeeded;
  20292. numOutputChansNeeded = numOutputChannelsNeeded;
  20293. if (e != 0 && e->hasTagName ("DEVICESETUP"))
  20294. {
  20295. lastExplicitSettings = new XmlElement (*e);
  20296. String error;
  20297. AudioDeviceSetup setup;
  20298. if (preferredSetupOptions != 0)
  20299. setup = *preferredSetupOptions;
  20300. if (e->getStringAttribute ("audioDeviceName").isNotEmpty())
  20301. {
  20302. setup.inputDeviceName = setup.outputDeviceName
  20303. = e->getStringAttribute ("audioDeviceName");
  20304. }
  20305. else
  20306. {
  20307. setup.inputDeviceName = e->getStringAttribute ("audioInputDeviceName");
  20308. setup.outputDeviceName = e->getStringAttribute ("audioOutputDeviceName");
  20309. }
  20310. currentDeviceType = e->getStringAttribute ("deviceType");
  20311. if (currentDeviceType.isEmpty())
  20312. {
  20313. AudioIODeviceType* const type = findType (setup.inputDeviceName, setup.outputDeviceName);
  20314. if (type != 0)
  20315. currentDeviceType = type->getTypeName();
  20316. else if (availableDeviceTypes.size() > 0)
  20317. currentDeviceType = availableDeviceTypes[0]->getTypeName();
  20318. }
  20319. setup.bufferSize = e->getIntAttribute ("audioDeviceBufferSize");
  20320. setup.sampleRate = e->getDoubleAttribute ("audioDeviceRate");
  20321. setup.inputChannels.parseString (e->getStringAttribute ("audioDeviceInChans", "11"), 2);
  20322. setup.outputChannels.parseString (e->getStringAttribute ("audioDeviceOutChans", "11"), 2);
  20323. setup.useDefaultInputChannels = ! e->hasAttribute ("audioDeviceInChans");
  20324. setup.useDefaultOutputChannels = ! e->hasAttribute ("audioDeviceOutChans");
  20325. error = setAudioDeviceSetup (setup, true);
  20326. midiInsFromXml.clear();
  20327. forEachXmlChildElementWithTagName (*e, c, "MIDIINPUT")
  20328. midiInsFromXml.add (c->getStringAttribute ("name"));
  20329. const StringArray allMidiIns (MidiInput::getDevices());
  20330. for (int i = allMidiIns.size(); --i >= 0;)
  20331. setMidiInputEnabled (allMidiIns[i], midiInsFromXml.contains (allMidiIns[i]));
  20332. if (error.isNotEmpty() && selectDefaultDeviceOnFailure)
  20333. error = initialise (numInputChannelsNeeded, numOutputChannelsNeeded, 0,
  20334. false, preferredDefaultDeviceName);
  20335. setDefaultMidiOutput (e->getStringAttribute ("defaultMidiOutput"));
  20336. return error;
  20337. }
  20338. else
  20339. {
  20340. AudioDeviceSetup setup;
  20341. if (preferredSetupOptions != 0)
  20342. {
  20343. setup = *preferredSetupOptions;
  20344. }
  20345. else if (preferredDefaultDeviceName.isNotEmpty())
  20346. {
  20347. for (int j = availableDeviceTypes.size(); --j >= 0;)
  20348. {
  20349. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(j);
  20350. StringArray outs (type->getDeviceNames (false));
  20351. int i;
  20352. for (i = 0; i < outs.size(); ++i)
  20353. {
  20354. if (outs[i].matchesWildcard (preferredDefaultDeviceName, true))
  20355. {
  20356. setup.outputDeviceName = outs[i];
  20357. break;
  20358. }
  20359. }
  20360. StringArray ins (type->getDeviceNames (true));
  20361. for (i = 0; i < ins.size(); ++i)
  20362. {
  20363. if (ins[i].matchesWildcard (preferredDefaultDeviceName, true))
  20364. {
  20365. setup.inputDeviceName = ins[i];
  20366. break;
  20367. }
  20368. }
  20369. }
  20370. }
  20371. insertDefaultDeviceNames (setup);
  20372. return setAudioDeviceSetup (setup, false);
  20373. }
  20374. }
  20375. void AudioDeviceManager::insertDefaultDeviceNames (AudioDeviceSetup& setup) const
  20376. {
  20377. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  20378. if (type != 0)
  20379. {
  20380. if (setup.outputDeviceName.isEmpty())
  20381. setup.outputDeviceName = type->getDeviceNames (false) [type->getDefaultDeviceIndex (false)];
  20382. if (setup.inputDeviceName.isEmpty())
  20383. setup.inputDeviceName = type->getDeviceNames (true) [type->getDefaultDeviceIndex (true)];
  20384. }
  20385. }
  20386. XmlElement* AudioDeviceManager::createStateXml() const
  20387. {
  20388. return lastExplicitSettings != 0 ? new XmlElement (*lastExplicitSettings) : 0;
  20389. }
  20390. void AudioDeviceManager::scanDevicesIfNeeded()
  20391. {
  20392. if (listNeedsScanning)
  20393. {
  20394. listNeedsScanning = false;
  20395. createDeviceTypesIfNeeded();
  20396. for (int i = availableDeviceTypes.size(); --i >= 0;)
  20397. availableDeviceTypes.getUnchecked(i)->scanForDevices();
  20398. }
  20399. }
  20400. AudioIODeviceType* AudioDeviceManager::findType (const String& inputName, const String& outputName)
  20401. {
  20402. scanDevicesIfNeeded();
  20403. for (int i = availableDeviceTypes.size(); --i >= 0;)
  20404. {
  20405. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(i);
  20406. if ((inputName.isNotEmpty() && type->getDeviceNames (true).contains (inputName, true))
  20407. || (outputName.isNotEmpty() && type->getDeviceNames (false).contains (outputName, true)))
  20408. {
  20409. return type;
  20410. }
  20411. }
  20412. return 0;
  20413. }
  20414. void AudioDeviceManager::getAudioDeviceSetup (AudioDeviceSetup& setup)
  20415. {
  20416. setup = currentSetup;
  20417. }
  20418. void AudioDeviceManager::deleteCurrentDevice()
  20419. {
  20420. currentAudioDevice = 0;
  20421. currentSetup.inputDeviceName = String::empty;
  20422. currentSetup.outputDeviceName = String::empty;
  20423. }
  20424. void AudioDeviceManager::setCurrentAudioDeviceType (const String& type,
  20425. const bool treatAsChosenDevice)
  20426. {
  20427. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20428. {
  20429. if (availableDeviceTypes.getUnchecked(i)->getTypeName() == type
  20430. && currentDeviceType != type)
  20431. {
  20432. currentDeviceType = type;
  20433. AudioDeviceSetup s (*lastDeviceTypeConfigs.getUnchecked(i));
  20434. insertDefaultDeviceNames (s);
  20435. setAudioDeviceSetup (s, treatAsChosenDevice);
  20436. sendChangeMessage (this);
  20437. break;
  20438. }
  20439. }
  20440. }
  20441. AudioIODeviceType* AudioDeviceManager::getCurrentDeviceTypeObject() const
  20442. {
  20443. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20444. if (availableDeviceTypes[i]->getTypeName() == currentDeviceType)
  20445. return availableDeviceTypes[i];
  20446. return availableDeviceTypes[0];
  20447. }
  20448. const String AudioDeviceManager::setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  20449. const bool treatAsChosenDevice)
  20450. {
  20451. jassert (&newSetup != &currentSetup); // this will have no effect
  20452. if (newSetup == currentSetup && currentAudioDevice != 0)
  20453. return String::empty;
  20454. if (! (newSetup == currentSetup))
  20455. sendChangeMessage (this);
  20456. stopDevice();
  20457. const String newInputDeviceName (numInputChansNeeded == 0 ? String::empty : newSetup.inputDeviceName);
  20458. const String newOutputDeviceName (numOutputChansNeeded == 0 ? String::empty : newSetup.outputDeviceName);
  20459. String error;
  20460. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  20461. if (type == 0 || (newInputDeviceName.isEmpty() && newOutputDeviceName.isEmpty()))
  20462. {
  20463. deleteCurrentDevice();
  20464. if (treatAsChosenDevice)
  20465. updateXml();
  20466. return String::empty;
  20467. }
  20468. if (currentSetup.inputDeviceName != newInputDeviceName
  20469. || currentSetup.outputDeviceName != newOutputDeviceName
  20470. || currentAudioDevice == 0)
  20471. {
  20472. deleteCurrentDevice();
  20473. scanDevicesIfNeeded();
  20474. if (newOutputDeviceName.isNotEmpty()
  20475. && ! type->getDeviceNames (false).contains (newOutputDeviceName))
  20476. {
  20477. return "No such device: " + newOutputDeviceName;
  20478. }
  20479. if (newInputDeviceName.isNotEmpty()
  20480. && ! type->getDeviceNames (true).contains (newInputDeviceName))
  20481. {
  20482. return "No such device: " + newInputDeviceName;
  20483. }
  20484. currentAudioDevice = type->createDevice (newOutputDeviceName, newInputDeviceName);
  20485. if (currentAudioDevice == 0)
  20486. 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!";
  20487. else
  20488. error = currentAudioDevice->getLastError();
  20489. if (error.isNotEmpty())
  20490. {
  20491. deleteCurrentDevice();
  20492. return error;
  20493. }
  20494. if (newSetup.useDefaultInputChannels)
  20495. {
  20496. inputChannels.clear();
  20497. inputChannels.setRange (0, numInputChansNeeded, true);
  20498. }
  20499. if (newSetup.useDefaultOutputChannels)
  20500. {
  20501. outputChannels.clear();
  20502. outputChannels.setRange (0, numOutputChansNeeded, true);
  20503. }
  20504. if (newInputDeviceName.isEmpty())
  20505. inputChannels.clear();
  20506. if (newOutputDeviceName.isEmpty())
  20507. outputChannels.clear();
  20508. }
  20509. if (! newSetup.useDefaultInputChannels)
  20510. inputChannels = newSetup.inputChannels;
  20511. if (! newSetup.useDefaultOutputChannels)
  20512. outputChannels = newSetup.outputChannels;
  20513. currentSetup = newSetup;
  20514. currentSetup.sampleRate = chooseBestSampleRate (newSetup.sampleRate);
  20515. error = currentAudioDevice->open (inputChannels,
  20516. outputChannels,
  20517. currentSetup.sampleRate,
  20518. currentSetup.bufferSize);
  20519. if (error.isEmpty())
  20520. {
  20521. currentDeviceType = currentAudioDevice->getTypeName();
  20522. currentAudioDevice->start (&callbackHandler);
  20523. currentSetup.sampleRate = currentAudioDevice->getCurrentSampleRate();
  20524. currentSetup.bufferSize = currentAudioDevice->getCurrentBufferSizeSamples();
  20525. currentSetup.inputChannels = currentAudioDevice->getActiveInputChannels();
  20526. currentSetup.outputChannels = currentAudioDevice->getActiveOutputChannels();
  20527. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20528. if (availableDeviceTypes.getUnchecked (i)->getTypeName() == currentDeviceType)
  20529. *(lastDeviceTypeConfigs.getUnchecked (i)) = currentSetup;
  20530. if (treatAsChosenDevice)
  20531. updateXml();
  20532. }
  20533. else
  20534. {
  20535. deleteCurrentDevice();
  20536. }
  20537. return error;
  20538. }
  20539. double AudioDeviceManager::chooseBestSampleRate (double rate) const
  20540. {
  20541. jassert (currentAudioDevice != 0);
  20542. if (rate > 0)
  20543. {
  20544. bool ok = false;
  20545. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  20546. {
  20547. const double sr = currentAudioDevice->getSampleRate (i);
  20548. if (sr == rate)
  20549. ok = true;
  20550. }
  20551. if (! ok)
  20552. rate = 0;
  20553. }
  20554. if (rate == 0)
  20555. {
  20556. double lowestAbove44 = 0.0;
  20557. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  20558. {
  20559. const double sr = currentAudioDevice->getSampleRate (i);
  20560. if (sr >= 44100.0 && (lowestAbove44 == 0 || sr < lowestAbove44))
  20561. lowestAbove44 = sr;
  20562. }
  20563. if (lowestAbove44 == 0.0)
  20564. rate = currentAudioDevice->getSampleRate (0);
  20565. else
  20566. rate = lowestAbove44;
  20567. }
  20568. return rate;
  20569. }
  20570. void AudioDeviceManager::stopDevice()
  20571. {
  20572. if (currentAudioDevice != 0)
  20573. currentAudioDevice->stop();
  20574. testSound = 0;
  20575. }
  20576. void AudioDeviceManager::closeAudioDevice()
  20577. {
  20578. stopDevice();
  20579. currentAudioDevice = 0;
  20580. }
  20581. void AudioDeviceManager::restartLastAudioDevice()
  20582. {
  20583. if (currentAudioDevice == 0)
  20584. {
  20585. if (currentSetup.inputDeviceName.isEmpty()
  20586. && currentSetup.outputDeviceName.isEmpty())
  20587. {
  20588. // This method will only reload the last device that was running
  20589. // before closeAudioDevice() was called - you need to actually open
  20590. // one first, with setAudioDevice().
  20591. jassertfalse;
  20592. return;
  20593. }
  20594. AudioDeviceSetup s (currentSetup);
  20595. setAudioDeviceSetup (s, false);
  20596. }
  20597. }
  20598. void AudioDeviceManager::updateXml()
  20599. {
  20600. lastExplicitSettings = new XmlElement ("DEVICESETUP");
  20601. lastExplicitSettings->setAttribute ("deviceType", currentDeviceType);
  20602. lastExplicitSettings->setAttribute ("audioOutputDeviceName", currentSetup.outputDeviceName);
  20603. lastExplicitSettings->setAttribute ("audioInputDeviceName", currentSetup.inputDeviceName);
  20604. if (currentAudioDevice != 0)
  20605. {
  20606. lastExplicitSettings->setAttribute ("audioDeviceRate", currentAudioDevice->getCurrentSampleRate());
  20607. if (currentAudioDevice->getDefaultBufferSize() != currentAudioDevice->getCurrentBufferSizeSamples())
  20608. lastExplicitSettings->setAttribute ("audioDeviceBufferSize", currentAudioDevice->getCurrentBufferSizeSamples());
  20609. if (! currentSetup.useDefaultInputChannels)
  20610. lastExplicitSettings->setAttribute ("audioDeviceInChans", currentSetup.inputChannels.toString (2));
  20611. if (! currentSetup.useDefaultOutputChannels)
  20612. lastExplicitSettings->setAttribute ("audioDeviceOutChans", currentSetup.outputChannels.toString (2));
  20613. }
  20614. for (int i = 0; i < enabledMidiInputs.size(); ++i)
  20615. {
  20616. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  20617. m->setAttribute ("name", enabledMidiInputs[i]->getName());
  20618. }
  20619. if (midiInsFromXml.size() > 0)
  20620. {
  20621. // Add any midi devices that have been enabled before, but which aren't currently
  20622. // open because the device has been disconnected.
  20623. const StringArray availableMidiDevices (MidiInput::getDevices());
  20624. for (int i = 0; i < midiInsFromXml.size(); ++i)
  20625. {
  20626. if (! availableMidiDevices.contains (midiInsFromXml[i], true))
  20627. {
  20628. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  20629. m->setAttribute ("name", midiInsFromXml[i]);
  20630. }
  20631. }
  20632. }
  20633. if (defaultMidiOutputName.isNotEmpty())
  20634. lastExplicitSettings->setAttribute ("defaultMidiOutput", defaultMidiOutputName);
  20635. }
  20636. void AudioDeviceManager::addAudioCallback (AudioIODeviceCallback* newCallback)
  20637. {
  20638. {
  20639. const ScopedLock sl (audioCallbackLock);
  20640. if (callbacks.contains (newCallback))
  20641. return;
  20642. }
  20643. if (currentAudioDevice != 0 && newCallback != 0)
  20644. newCallback->audioDeviceAboutToStart (currentAudioDevice);
  20645. const ScopedLock sl (audioCallbackLock);
  20646. callbacks.add (newCallback);
  20647. }
  20648. void AudioDeviceManager::removeAudioCallback (AudioIODeviceCallback* callback)
  20649. {
  20650. if (callback != 0)
  20651. {
  20652. bool needsDeinitialising = currentAudioDevice != 0;
  20653. {
  20654. const ScopedLock sl (audioCallbackLock);
  20655. needsDeinitialising = needsDeinitialising && callbacks.contains (callback);
  20656. callbacks.removeValue (callback);
  20657. }
  20658. if (needsDeinitialising)
  20659. callback->audioDeviceStopped();
  20660. }
  20661. }
  20662. void AudioDeviceManager::audioDeviceIOCallbackInt (const float** inputChannelData,
  20663. int numInputChannels,
  20664. float** outputChannelData,
  20665. int numOutputChannels,
  20666. int numSamples)
  20667. {
  20668. const ScopedLock sl (audioCallbackLock);
  20669. if (inputLevelMeasurementEnabledCount > 0)
  20670. {
  20671. for (int j = 0; j < numSamples; ++j)
  20672. {
  20673. float s = 0;
  20674. for (int i = 0; i < numInputChannels; ++i)
  20675. s += std::abs (inputChannelData[i][j]);
  20676. s /= numInputChannels;
  20677. const double decayFactor = 0.99992;
  20678. if (s > inputLevel)
  20679. inputLevel = s;
  20680. else if (inputLevel > 0.001f)
  20681. inputLevel *= decayFactor;
  20682. else
  20683. inputLevel = 0;
  20684. }
  20685. }
  20686. if (callbacks.size() > 0)
  20687. {
  20688. const double callbackStartTime = Time::getMillisecondCounterHiRes();
  20689. tempBuffer.setSize (jmax (1, numOutputChannels), jmax (1, numSamples), false, false, true);
  20690. callbacks.getUnchecked(0)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  20691. outputChannelData, numOutputChannels, numSamples);
  20692. float** const tempChans = tempBuffer.getArrayOfChannels();
  20693. for (int i = callbacks.size(); --i > 0;)
  20694. {
  20695. callbacks.getUnchecked(i)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  20696. tempChans, numOutputChannels, numSamples);
  20697. for (int chan = 0; chan < numOutputChannels; ++chan)
  20698. {
  20699. const float* const src = tempChans [chan];
  20700. float* const dst = outputChannelData [chan];
  20701. if (src != 0 && dst != 0)
  20702. for (int j = 0; j < numSamples; ++j)
  20703. dst[j] += src[j];
  20704. }
  20705. }
  20706. const double msTaken = Time::getMillisecondCounterHiRes() - callbackStartTime;
  20707. const double filterAmount = 0.2;
  20708. cpuUsageMs += filterAmount * (msTaken - cpuUsageMs);
  20709. }
  20710. else
  20711. {
  20712. for (int i = 0; i < numOutputChannels; ++i)
  20713. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  20714. }
  20715. if (testSound != 0)
  20716. {
  20717. const int numSamps = jmin (numSamples, testSound->getNumSamples() - testSoundPosition);
  20718. const float* const src = testSound->getSampleData (0, testSoundPosition);
  20719. for (int i = 0; i < numOutputChannels; ++i)
  20720. for (int j = 0; j < numSamps; ++j)
  20721. outputChannelData [i][j] += src[j];
  20722. testSoundPosition += numSamps;
  20723. if (testSoundPosition >= testSound->getNumSamples())
  20724. testSound = 0;
  20725. }
  20726. }
  20727. void AudioDeviceManager::audioDeviceAboutToStartInt (AudioIODevice* const device)
  20728. {
  20729. cpuUsageMs = 0;
  20730. const double sampleRate = device->getCurrentSampleRate();
  20731. const int blockSize = device->getCurrentBufferSizeSamples();
  20732. if (sampleRate > 0.0 && blockSize > 0)
  20733. {
  20734. const double msPerBlock = 1000.0 * blockSize / sampleRate;
  20735. timeToCpuScale = (msPerBlock > 0.0) ? (1.0 / msPerBlock) : 0.0;
  20736. }
  20737. {
  20738. const ScopedLock sl (audioCallbackLock);
  20739. for (int i = callbacks.size(); --i >= 0;)
  20740. callbacks.getUnchecked(i)->audioDeviceAboutToStart (device);
  20741. }
  20742. sendChangeMessage (this);
  20743. }
  20744. void AudioDeviceManager::audioDeviceStoppedInt()
  20745. {
  20746. cpuUsageMs = 0;
  20747. timeToCpuScale = 0;
  20748. sendChangeMessage (this);
  20749. const ScopedLock sl (audioCallbackLock);
  20750. for (int i = callbacks.size(); --i >= 0;)
  20751. callbacks.getUnchecked(i)->audioDeviceStopped();
  20752. }
  20753. double AudioDeviceManager::getCpuUsage() const
  20754. {
  20755. return jlimit (0.0, 1.0, timeToCpuScale * cpuUsageMs);
  20756. }
  20757. void AudioDeviceManager::setMidiInputEnabled (const String& name,
  20758. const bool enabled)
  20759. {
  20760. if (enabled != isMidiInputEnabled (name))
  20761. {
  20762. if (enabled)
  20763. {
  20764. const int index = MidiInput::getDevices().indexOf (name);
  20765. if (index >= 0)
  20766. {
  20767. MidiInput* const min = MidiInput::openDevice (index, &callbackHandler);
  20768. if (min != 0)
  20769. {
  20770. enabledMidiInputs.add (min);
  20771. min->start();
  20772. }
  20773. }
  20774. }
  20775. else
  20776. {
  20777. for (int i = enabledMidiInputs.size(); --i >= 0;)
  20778. if (enabledMidiInputs[i]->getName() == name)
  20779. enabledMidiInputs.remove (i);
  20780. }
  20781. updateXml();
  20782. sendChangeMessage (this);
  20783. }
  20784. }
  20785. bool AudioDeviceManager::isMidiInputEnabled (const String& name) const
  20786. {
  20787. for (int i = enabledMidiInputs.size(); --i >= 0;)
  20788. if (enabledMidiInputs[i]->getName() == name)
  20789. return true;
  20790. return false;
  20791. }
  20792. void AudioDeviceManager::addMidiInputCallback (const String& name,
  20793. MidiInputCallback* callback)
  20794. {
  20795. removeMidiInputCallback (name, callback);
  20796. if (name.isEmpty())
  20797. {
  20798. midiCallbacks.add (callback);
  20799. midiCallbackDevices.add (0);
  20800. }
  20801. else
  20802. {
  20803. for (int i = enabledMidiInputs.size(); --i >= 0;)
  20804. {
  20805. if (enabledMidiInputs[i]->getName() == name)
  20806. {
  20807. const ScopedLock sl (midiCallbackLock);
  20808. midiCallbacks.add (callback);
  20809. midiCallbackDevices.add (enabledMidiInputs[i]);
  20810. break;
  20811. }
  20812. }
  20813. }
  20814. }
  20815. void AudioDeviceManager::removeMidiInputCallback (const String& name,
  20816. MidiInputCallback* /*callback*/)
  20817. {
  20818. const ScopedLock sl (midiCallbackLock);
  20819. for (int i = midiCallbacks.size(); --i >= 0;)
  20820. {
  20821. String devName;
  20822. if (midiCallbackDevices.getUnchecked(i) != 0)
  20823. devName = midiCallbackDevices.getUnchecked(i)->getName();
  20824. if (devName == name)
  20825. {
  20826. midiCallbacks.remove (i);
  20827. midiCallbackDevices.remove (i);
  20828. }
  20829. }
  20830. }
  20831. void AudioDeviceManager::handleIncomingMidiMessageInt (MidiInput* source,
  20832. const MidiMessage& message)
  20833. {
  20834. if (! message.isActiveSense())
  20835. {
  20836. const bool isDefaultSource = (source == 0 || source == enabledMidiInputs.getFirst());
  20837. const ScopedLock sl (midiCallbackLock);
  20838. for (int i = midiCallbackDevices.size(); --i >= 0;)
  20839. {
  20840. MidiInput* const md = midiCallbackDevices.getUnchecked(i);
  20841. if (md == source || (md == 0 && isDefaultSource))
  20842. midiCallbacks.getUnchecked(i)->handleIncomingMidiMessage (source, message);
  20843. }
  20844. }
  20845. }
  20846. void AudioDeviceManager::setDefaultMidiOutput (const String& deviceName)
  20847. {
  20848. if (defaultMidiOutputName != deviceName)
  20849. {
  20850. SortedSet <AudioIODeviceCallback*> oldCallbacks;
  20851. {
  20852. const ScopedLock sl (audioCallbackLock);
  20853. oldCallbacks = callbacks;
  20854. callbacks.clear();
  20855. }
  20856. if (currentAudioDevice != 0)
  20857. for (int i = oldCallbacks.size(); --i >= 0;)
  20858. oldCallbacks.getUnchecked(i)->audioDeviceStopped();
  20859. defaultMidiOutput = 0;
  20860. defaultMidiOutputName = deviceName;
  20861. if (deviceName.isNotEmpty())
  20862. defaultMidiOutput = MidiOutput::openDevice (MidiOutput::getDevices().indexOf (deviceName));
  20863. if (currentAudioDevice != 0)
  20864. for (int i = oldCallbacks.size(); --i >= 0;)
  20865. oldCallbacks.getUnchecked(i)->audioDeviceAboutToStart (currentAudioDevice);
  20866. {
  20867. const ScopedLock sl (audioCallbackLock);
  20868. callbacks = oldCallbacks;
  20869. }
  20870. updateXml();
  20871. sendChangeMessage (this);
  20872. }
  20873. }
  20874. void AudioDeviceManager::CallbackHandler::audioDeviceIOCallback (const float** inputChannelData,
  20875. int numInputChannels,
  20876. float** outputChannelData,
  20877. int numOutputChannels,
  20878. int numSamples)
  20879. {
  20880. owner->audioDeviceIOCallbackInt (inputChannelData, numInputChannels, outputChannelData, numOutputChannels, numSamples);
  20881. }
  20882. void AudioDeviceManager::CallbackHandler::audioDeviceAboutToStart (AudioIODevice* device)
  20883. {
  20884. owner->audioDeviceAboutToStartInt (device);
  20885. }
  20886. void AudioDeviceManager::CallbackHandler::audioDeviceStopped()
  20887. {
  20888. owner->audioDeviceStoppedInt();
  20889. }
  20890. void AudioDeviceManager::CallbackHandler::handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message)
  20891. {
  20892. owner->handleIncomingMidiMessageInt (source, message);
  20893. }
  20894. void AudioDeviceManager::playTestSound()
  20895. {
  20896. { // cunningly nested to swap, unlock and delete in that order.
  20897. ScopedPointer <AudioSampleBuffer> oldSound;
  20898. {
  20899. const ScopedLock sl (audioCallbackLock);
  20900. oldSound = testSound;
  20901. }
  20902. }
  20903. testSoundPosition = 0;
  20904. if (currentAudioDevice != 0)
  20905. {
  20906. const double sampleRate = currentAudioDevice->getCurrentSampleRate();
  20907. const int soundLength = (int) sampleRate;
  20908. AudioSampleBuffer* const newSound = new AudioSampleBuffer (1, soundLength);
  20909. float* samples = newSound->getSampleData (0);
  20910. const double frequency = MidiMessage::getMidiNoteInHertz (80);
  20911. const float amplitude = 0.5f;
  20912. const double phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  20913. for (int i = 0; i < soundLength; ++i)
  20914. samples[i] = amplitude * (float) std::sin (i * phasePerSample);
  20915. newSound->applyGainRamp (0, 0, soundLength / 10, 0.0f, 1.0f);
  20916. newSound->applyGainRamp (0, soundLength - soundLength / 4, soundLength / 4, 1.0f, 0.0f);
  20917. const ScopedLock sl (audioCallbackLock);
  20918. testSound = newSound;
  20919. }
  20920. }
  20921. void AudioDeviceManager::enableInputLevelMeasurement (const bool enableMeasurement)
  20922. {
  20923. const ScopedLock sl (audioCallbackLock);
  20924. if (enableMeasurement)
  20925. ++inputLevelMeasurementEnabledCount;
  20926. else
  20927. --inputLevelMeasurementEnabledCount;
  20928. inputLevel = 0;
  20929. }
  20930. double AudioDeviceManager::getCurrentInputLevel() const
  20931. {
  20932. jassert (inputLevelMeasurementEnabledCount > 0); // you need to call enableInputLevelMeasurement() before using this!
  20933. return inputLevel;
  20934. }
  20935. END_JUCE_NAMESPACE
  20936. /*** End of inlined file: juce_AudioDeviceManager.cpp ***/
  20937. /*** Start of inlined file: juce_AudioIODevice.cpp ***/
  20938. BEGIN_JUCE_NAMESPACE
  20939. AudioIODevice::AudioIODevice (const String& deviceName, const String& typeName_)
  20940. : name (deviceName),
  20941. typeName (typeName_)
  20942. {
  20943. }
  20944. AudioIODevice::~AudioIODevice()
  20945. {
  20946. }
  20947. bool AudioIODevice::hasControlPanel() const
  20948. {
  20949. return false;
  20950. }
  20951. bool AudioIODevice::showControlPanel()
  20952. {
  20953. jassertfalse; // this should only be called for devices which return true from
  20954. // their hasControlPanel() method.
  20955. return false;
  20956. }
  20957. END_JUCE_NAMESPACE
  20958. /*** End of inlined file: juce_AudioIODevice.cpp ***/
  20959. /*** Start of inlined file: juce_AudioIODeviceType.cpp ***/
  20960. BEGIN_JUCE_NAMESPACE
  20961. AudioIODeviceType::AudioIODeviceType (const String& name)
  20962. : typeName (name)
  20963. {
  20964. }
  20965. AudioIODeviceType::~AudioIODeviceType()
  20966. {
  20967. }
  20968. END_JUCE_NAMESPACE
  20969. /*** End of inlined file: juce_AudioIODeviceType.cpp ***/
  20970. /*** Start of inlined file: juce_MidiOutput.cpp ***/
  20971. BEGIN_JUCE_NAMESPACE
  20972. MidiOutput::MidiOutput()
  20973. : Thread ("midi out"),
  20974. internal (0),
  20975. firstMessage (0)
  20976. {
  20977. }
  20978. MidiOutput::PendingMessage::PendingMessage (const uint8* const data, const int len,
  20979. const double sampleNumber)
  20980. : message (data, len, sampleNumber)
  20981. {
  20982. }
  20983. void MidiOutput::sendBlockOfMessages (const MidiBuffer& buffer,
  20984. const double millisecondCounterToStartAt,
  20985. double samplesPerSecondForBuffer)
  20986. {
  20987. // You've got to call startBackgroundThread() for this to actually work..
  20988. jassert (isThreadRunning());
  20989. // this needs to be a value in the future - RTFM for this method!
  20990. jassert (millisecondCounterToStartAt > 0);
  20991. const double timeScaleFactor = 1000.0 / samplesPerSecondForBuffer;
  20992. MidiBuffer::Iterator i (buffer);
  20993. const uint8* data;
  20994. int len, time;
  20995. while (i.getNextEvent (data, len, time))
  20996. {
  20997. const double eventTime = millisecondCounterToStartAt + timeScaleFactor * time;
  20998. PendingMessage* const m
  20999. = new PendingMessage (data, len, eventTime);
  21000. const ScopedLock sl (lock);
  21001. if (firstMessage == 0 || firstMessage->message.getTimeStamp() > eventTime)
  21002. {
  21003. m->next = firstMessage;
  21004. firstMessage = m;
  21005. }
  21006. else
  21007. {
  21008. PendingMessage* mm = firstMessage;
  21009. while (mm->next != 0 && mm->next->message.getTimeStamp() <= eventTime)
  21010. mm = mm->next;
  21011. m->next = mm->next;
  21012. mm->next = m;
  21013. }
  21014. }
  21015. notify();
  21016. }
  21017. void MidiOutput::clearAllPendingMessages()
  21018. {
  21019. const ScopedLock sl (lock);
  21020. while (firstMessage != 0)
  21021. {
  21022. PendingMessage* const m = firstMessage;
  21023. firstMessage = firstMessage->next;
  21024. delete m;
  21025. }
  21026. }
  21027. void MidiOutput::startBackgroundThread()
  21028. {
  21029. startThread (9);
  21030. }
  21031. void MidiOutput::stopBackgroundThread()
  21032. {
  21033. stopThread (5000);
  21034. }
  21035. void MidiOutput::run()
  21036. {
  21037. while (! threadShouldExit())
  21038. {
  21039. uint32 now = Time::getMillisecondCounter();
  21040. uint32 eventTime = 0;
  21041. uint32 timeToWait = 500;
  21042. PendingMessage* message;
  21043. {
  21044. const ScopedLock sl (lock);
  21045. message = firstMessage;
  21046. if (message != 0)
  21047. {
  21048. eventTime = roundToInt (message->message.getTimeStamp());
  21049. if (eventTime > now + 20)
  21050. {
  21051. timeToWait = eventTime - (now + 20);
  21052. message = 0;
  21053. }
  21054. else
  21055. {
  21056. firstMessage = message->next;
  21057. }
  21058. }
  21059. }
  21060. if (message != 0)
  21061. {
  21062. if (eventTime > now)
  21063. {
  21064. Time::waitForMillisecondCounter (eventTime);
  21065. if (threadShouldExit())
  21066. break;
  21067. }
  21068. if (eventTime > now - 200)
  21069. sendMessageNow (message->message);
  21070. delete message;
  21071. }
  21072. else
  21073. {
  21074. jassert (timeToWait < 1000 * 30);
  21075. wait (timeToWait);
  21076. }
  21077. }
  21078. clearAllPendingMessages();
  21079. }
  21080. END_JUCE_NAMESPACE
  21081. /*** End of inlined file: juce_MidiOutput.cpp ***/
  21082. /*** Start of inlined file: juce_AudioDataConverters.cpp ***/
  21083. BEGIN_JUCE_NAMESPACE
  21084. void AudioDataConverters::convertFloatToInt16LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21085. {
  21086. const double maxVal = (double) 0x7fff;
  21087. char* intData = static_cast <char*> (dest);
  21088. if (dest != (void*) source || destBytesPerSample <= 4)
  21089. {
  21090. for (int i = 0; i < numSamples; ++i)
  21091. {
  21092. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21093. intData += destBytesPerSample;
  21094. }
  21095. }
  21096. else
  21097. {
  21098. intData += destBytesPerSample * numSamples;
  21099. for (int i = numSamples; --i >= 0;)
  21100. {
  21101. intData -= destBytesPerSample;
  21102. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21103. }
  21104. }
  21105. }
  21106. void AudioDataConverters::convertFloatToInt16BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21107. {
  21108. const double maxVal = (double) 0x7fff;
  21109. char* intData = static_cast <char*> (dest);
  21110. if (dest != (void*) source || destBytesPerSample <= 4)
  21111. {
  21112. for (int i = 0; i < numSamples; ++i)
  21113. {
  21114. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21115. intData += destBytesPerSample;
  21116. }
  21117. }
  21118. else
  21119. {
  21120. intData += destBytesPerSample * numSamples;
  21121. for (int i = numSamples; --i >= 0;)
  21122. {
  21123. intData -= destBytesPerSample;
  21124. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21125. }
  21126. }
  21127. }
  21128. void AudioDataConverters::convertFloatToInt24LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21129. {
  21130. const double maxVal = (double) 0x7fffff;
  21131. char* intData = static_cast <char*> (dest);
  21132. if (dest != (void*) source || destBytesPerSample <= 4)
  21133. {
  21134. for (int i = 0; i < numSamples; ++i)
  21135. {
  21136. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21137. intData += destBytesPerSample;
  21138. }
  21139. }
  21140. else
  21141. {
  21142. intData += destBytesPerSample * numSamples;
  21143. for (int i = numSamples; --i >= 0;)
  21144. {
  21145. intData -= destBytesPerSample;
  21146. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21147. }
  21148. }
  21149. }
  21150. void AudioDataConverters::convertFloatToInt24BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21151. {
  21152. const double maxVal = (double) 0x7fffff;
  21153. char* intData = static_cast <char*> (dest);
  21154. if (dest != (void*) source || destBytesPerSample <= 4)
  21155. {
  21156. for (int i = 0; i < numSamples; ++i)
  21157. {
  21158. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21159. intData += destBytesPerSample;
  21160. }
  21161. }
  21162. else
  21163. {
  21164. intData += destBytesPerSample * numSamples;
  21165. for (int i = numSamples; --i >= 0;)
  21166. {
  21167. intData -= destBytesPerSample;
  21168. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21169. }
  21170. }
  21171. }
  21172. void AudioDataConverters::convertFloatToInt32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21173. {
  21174. const double maxVal = (double) 0x7fffffff;
  21175. char* intData = static_cast <char*> (dest);
  21176. if (dest != (void*) source || destBytesPerSample <= 4)
  21177. {
  21178. for (int i = 0; i < numSamples; ++i)
  21179. {
  21180. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21181. intData += destBytesPerSample;
  21182. }
  21183. }
  21184. else
  21185. {
  21186. intData += destBytesPerSample * numSamples;
  21187. for (int i = numSamples; --i >= 0;)
  21188. {
  21189. intData -= destBytesPerSample;
  21190. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21191. }
  21192. }
  21193. }
  21194. void AudioDataConverters::convertFloatToInt32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21195. {
  21196. const double maxVal = (double) 0x7fffffff;
  21197. char* intData = static_cast <char*> (dest);
  21198. if (dest != (void*) source || destBytesPerSample <= 4)
  21199. {
  21200. for (int i = 0; i < numSamples; ++i)
  21201. {
  21202. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21203. intData += destBytesPerSample;
  21204. }
  21205. }
  21206. else
  21207. {
  21208. intData += destBytesPerSample * numSamples;
  21209. for (int i = numSamples; --i >= 0;)
  21210. {
  21211. intData -= destBytesPerSample;
  21212. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21213. }
  21214. }
  21215. }
  21216. void AudioDataConverters::convertFloatToFloat32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21217. {
  21218. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  21219. char* d = static_cast <char*> (dest);
  21220. for (int i = 0; i < numSamples; ++i)
  21221. {
  21222. *(float*) d = source[i];
  21223. #if JUCE_BIG_ENDIAN
  21224. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  21225. #endif
  21226. d += destBytesPerSample;
  21227. }
  21228. }
  21229. void AudioDataConverters::convertFloatToFloat32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21230. {
  21231. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  21232. char* d = static_cast <char*> (dest);
  21233. for (int i = 0; i < numSamples; ++i)
  21234. {
  21235. *(float*) d = source[i];
  21236. #if JUCE_LITTLE_ENDIAN
  21237. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  21238. #endif
  21239. d += destBytesPerSample;
  21240. }
  21241. }
  21242. void AudioDataConverters::convertInt16LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21243. {
  21244. const float scale = 1.0f / 0x7fff;
  21245. const char* intData = static_cast <const char*> (source);
  21246. if (source != (void*) dest || srcBytesPerSample >= 4)
  21247. {
  21248. for (int i = 0; i < numSamples; ++i)
  21249. {
  21250. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  21251. intData += srcBytesPerSample;
  21252. }
  21253. }
  21254. else
  21255. {
  21256. intData += srcBytesPerSample * numSamples;
  21257. for (int i = numSamples; --i >= 0;)
  21258. {
  21259. intData -= srcBytesPerSample;
  21260. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  21261. }
  21262. }
  21263. }
  21264. void AudioDataConverters::convertInt16BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21265. {
  21266. const float scale = 1.0f / 0x7fff;
  21267. const char* intData = static_cast <const char*> (source);
  21268. if (source != (void*) dest || srcBytesPerSample >= 4)
  21269. {
  21270. for (int i = 0; i < numSamples; ++i)
  21271. {
  21272. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  21273. intData += srcBytesPerSample;
  21274. }
  21275. }
  21276. else
  21277. {
  21278. intData += srcBytesPerSample * numSamples;
  21279. for (int i = numSamples; --i >= 0;)
  21280. {
  21281. intData -= srcBytesPerSample;
  21282. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  21283. }
  21284. }
  21285. }
  21286. void AudioDataConverters::convertInt24LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21287. {
  21288. const float scale = 1.0f / 0x7fffff;
  21289. const char* intData = static_cast <const char*> (source);
  21290. if (source != (void*) dest || srcBytesPerSample >= 4)
  21291. {
  21292. for (int i = 0; i < numSamples; ++i)
  21293. {
  21294. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  21295. intData += srcBytesPerSample;
  21296. }
  21297. }
  21298. else
  21299. {
  21300. intData += srcBytesPerSample * numSamples;
  21301. for (int i = numSamples; --i >= 0;)
  21302. {
  21303. intData -= srcBytesPerSample;
  21304. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  21305. }
  21306. }
  21307. }
  21308. void AudioDataConverters::convertInt24BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21309. {
  21310. const float scale = 1.0f / 0x7fffff;
  21311. const char* intData = static_cast <const char*> (source);
  21312. if (source != (void*) dest || srcBytesPerSample >= 4)
  21313. {
  21314. for (int i = 0; i < numSamples; ++i)
  21315. {
  21316. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  21317. intData += srcBytesPerSample;
  21318. }
  21319. }
  21320. else
  21321. {
  21322. intData += srcBytesPerSample * numSamples;
  21323. for (int i = numSamples; --i >= 0;)
  21324. {
  21325. intData -= srcBytesPerSample;
  21326. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  21327. }
  21328. }
  21329. }
  21330. void AudioDataConverters::convertInt32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21331. {
  21332. const float scale = 1.0f / 0x7fffffff;
  21333. const char* intData = static_cast <const char*> (source);
  21334. if (source != (void*) dest || srcBytesPerSample >= 4)
  21335. {
  21336. for (int i = 0; i < numSamples; ++i)
  21337. {
  21338. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  21339. intData += srcBytesPerSample;
  21340. }
  21341. }
  21342. else
  21343. {
  21344. intData += srcBytesPerSample * numSamples;
  21345. for (int i = numSamples; --i >= 0;)
  21346. {
  21347. intData -= srcBytesPerSample;
  21348. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  21349. }
  21350. }
  21351. }
  21352. void AudioDataConverters::convertInt32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21353. {
  21354. const float scale = 1.0f / 0x7fffffff;
  21355. const char* intData = static_cast <const char*> (source);
  21356. if (source != (void*) dest || srcBytesPerSample >= 4)
  21357. {
  21358. for (int i = 0; i < numSamples; ++i)
  21359. {
  21360. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  21361. intData += srcBytesPerSample;
  21362. }
  21363. }
  21364. else
  21365. {
  21366. intData += srcBytesPerSample * numSamples;
  21367. for (int i = numSamples; --i >= 0;)
  21368. {
  21369. intData -= srcBytesPerSample;
  21370. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  21371. }
  21372. }
  21373. }
  21374. void AudioDataConverters::convertFloat32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21375. {
  21376. const char* s = static_cast <const char*> (source);
  21377. for (int i = 0; i < numSamples; ++i)
  21378. {
  21379. dest[i] = *(float*)s;
  21380. #if JUCE_BIG_ENDIAN
  21381. uint32* const d = (uint32*) (dest + i);
  21382. *d = ByteOrder::swap (*d);
  21383. #endif
  21384. s += srcBytesPerSample;
  21385. }
  21386. }
  21387. void AudioDataConverters::convertFloat32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21388. {
  21389. const char* s = static_cast <const char*> (source);
  21390. for (int i = 0; i < numSamples; ++i)
  21391. {
  21392. dest[i] = *(float*)s;
  21393. #if JUCE_LITTLE_ENDIAN
  21394. uint32* const d = (uint32*) (dest + i);
  21395. *d = ByteOrder::swap (*d);
  21396. #endif
  21397. s += srcBytesPerSample;
  21398. }
  21399. }
  21400. void AudioDataConverters::convertFloatToFormat (const DataFormat destFormat,
  21401. const float* const source,
  21402. void* const dest,
  21403. const int numSamples)
  21404. {
  21405. switch (destFormat)
  21406. {
  21407. case int16LE:
  21408. convertFloatToInt16LE (source, dest, numSamples);
  21409. break;
  21410. case int16BE:
  21411. convertFloatToInt16BE (source, dest, numSamples);
  21412. break;
  21413. case int24LE:
  21414. convertFloatToInt24LE (source, dest, numSamples);
  21415. break;
  21416. case int24BE:
  21417. convertFloatToInt24BE (source, dest, numSamples);
  21418. break;
  21419. case int32LE:
  21420. convertFloatToInt32LE (source, dest, numSamples);
  21421. break;
  21422. case int32BE:
  21423. convertFloatToInt32BE (source, dest, numSamples);
  21424. break;
  21425. case float32LE:
  21426. convertFloatToFloat32LE (source, dest, numSamples);
  21427. break;
  21428. case float32BE:
  21429. convertFloatToFloat32BE (source, dest, numSamples);
  21430. break;
  21431. default:
  21432. jassertfalse;
  21433. break;
  21434. }
  21435. }
  21436. void AudioDataConverters::convertFormatToFloat (const DataFormat sourceFormat,
  21437. const void* const source,
  21438. float* const dest,
  21439. const int numSamples)
  21440. {
  21441. switch (sourceFormat)
  21442. {
  21443. case int16LE:
  21444. convertInt16LEToFloat (source, dest, numSamples);
  21445. break;
  21446. case int16BE:
  21447. convertInt16BEToFloat (source, dest, numSamples);
  21448. break;
  21449. case int24LE:
  21450. convertInt24LEToFloat (source, dest, numSamples);
  21451. break;
  21452. case int24BE:
  21453. convertInt24BEToFloat (source, dest, numSamples);
  21454. break;
  21455. case int32LE:
  21456. convertInt32LEToFloat (source, dest, numSamples);
  21457. break;
  21458. case int32BE:
  21459. convertInt32BEToFloat (source, dest, numSamples);
  21460. break;
  21461. case float32LE:
  21462. convertFloat32LEToFloat (source, dest, numSamples);
  21463. break;
  21464. case float32BE:
  21465. convertFloat32BEToFloat (source, dest, numSamples);
  21466. break;
  21467. default:
  21468. jassertfalse;
  21469. break;
  21470. }
  21471. }
  21472. void AudioDataConverters::interleaveSamples (const float** const source,
  21473. float* const dest,
  21474. const int numSamples,
  21475. const int numChannels)
  21476. {
  21477. for (int chan = 0; chan < numChannels; ++chan)
  21478. {
  21479. int i = chan;
  21480. const float* src = source [chan];
  21481. for (int j = 0; j < numSamples; ++j)
  21482. {
  21483. dest [i] = src [j];
  21484. i += numChannels;
  21485. }
  21486. }
  21487. }
  21488. void AudioDataConverters::deinterleaveSamples (const float* const source,
  21489. float** const dest,
  21490. const int numSamples,
  21491. const int numChannels)
  21492. {
  21493. for (int chan = 0; chan < numChannels; ++chan)
  21494. {
  21495. int i = chan;
  21496. float* dst = dest [chan];
  21497. for (int j = 0; j < numSamples; ++j)
  21498. {
  21499. dst [j] = source [i];
  21500. i += numChannels;
  21501. }
  21502. }
  21503. }
  21504. #if JUCE_UNIT_TESTS
  21505. class AudioConversionTests : public UnitTest
  21506. {
  21507. public:
  21508. AudioConversionTests() : UnitTest ("Audio data conversion") {}
  21509. template <class F1, class E1, class F2, class E2>
  21510. struct Test5
  21511. {
  21512. static void test (UnitTest& unitTest)
  21513. {
  21514. test (unitTest, false);
  21515. test (unitTest, true);
  21516. }
  21517. static void test (UnitTest& unitTest, bool inPlace)
  21518. {
  21519. const int numSamples = 2048;
  21520. int32 original [numSamples], converted [numSamples], reversed [numSamples];
  21521. {
  21522. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::NonConst> d (original);
  21523. bool clippingFailed = false;
  21524. for (int i = 0; i < numSamples / 2; ++i)
  21525. {
  21526. d.setAsFloat (Random::getSystemRandom().nextFloat() * 2.2f - 1.1f);
  21527. if (! d.isFloatingPoint())
  21528. clippingFailed = d.getAsFloat() > 1.0f || d.getAsFloat() < -1.0f || clippingFailed;
  21529. ++d;
  21530. d.setAsInt32 (Random::getSystemRandom().nextInt());
  21531. ++d;
  21532. }
  21533. unitTest.expect (! clippingFailed);
  21534. }
  21535. // convert data from the source to dest format..
  21536. ScopedPointer<AudioData::Converter> conv (new AudioData::ConverterInstance <AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const>,
  21537. AudioData::Pointer<F2, E2, AudioData::NonInterleaved, AudioData::NonConst> >());
  21538. conv->convertSamples (inPlace ? reversed : converted, original, numSamples);
  21539. // ..and back again..
  21540. conv = new AudioData::ConverterInstance <AudioData::Pointer<F2, E2, AudioData::NonInterleaved, AudioData::Const>,
  21541. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::NonConst> >();
  21542. if (! inPlace)
  21543. zerostruct (reversed);
  21544. conv->convertSamples (reversed, inPlace ? reversed : converted, numSamples);
  21545. {
  21546. int biggestDiff = 0;
  21547. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const> d1 (original);
  21548. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const> d2 (reversed);
  21549. const int errorMargin = 2 * AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const>::get32BitResolution()
  21550. + AudioData::Pointer<F2, E2, AudioData::NonInterleaved, AudioData::Const>::get32BitResolution();
  21551. for (int i = 0; i < numSamples; ++i)
  21552. {
  21553. biggestDiff = jmax (biggestDiff, std::abs (d1.getAsInt32() - d2.getAsInt32()));
  21554. ++d1;
  21555. ++d2;
  21556. }
  21557. unitTest.expect (biggestDiff <= errorMargin);
  21558. }
  21559. }
  21560. };
  21561. template <class F1, class E1, class FormatType>
  21562. struct Test3
  21563. {
  21564. static void test (UnitTest& unitTest)
  21565. {
  21566. Test5 <F1, E1, FormatType, AudioData::BigEndian>::test (unitTest);
  21567. Test5 <F1, E1, FormatType, AudioData::LittleEndian>::test (unitTest);
  21568. }
  21569. };
  21570. template <class FormatType, class Endianness>
  21571. struct Test2
  21572. {
  21573. static void test (UnitTest& unitTest)
  21574. {
  21575. Test3 <FormatType, Endianness, AudioData::Int8>::test (unitTest);
  21576. Test3 <FormatType, Endianness, AudioData::UInt8>::test (unitTest);
  21577. Test3 <FormatType, Endianness, AudioData::Int16>::test (unitTest);
  21578. Test3 <FormatType, Endianness, AudioData::Int24>::test (unitTest);
  21579. Test3 <FormatType, Endianness, AudioData::Int32>::test (unitTest);
  21580. Test3 <FormatType, Endianness, AudioData::Float32>::test (unitTest);
  21581. }
  21582. };
  21583. template <class FormatType>
  21584. struct Test1
  21585. {
  21586. static void test (UnitTest& unitTest)
  21587. {
  21588. Test2 <FormatType, AudioData::BigEndian>::test (unitTest);
  21589. Test2 <FormatType, AudioData::LittleEndian>::test (unitTest);
  21590. }
  21591. };
  21592. void runTest()
  21593. {
  21594. beginTest ("Round-trip conversion");
  21595. Test1 <AudioData::Int8>::test (*this);
  21596. Test1 <AudioData::Int16>::test (*this);
  21597. Test1 <AudioData::Int24>::test (*this);
  21598. Test1 <AudioData::Int32>::test (*this);
  21599. Test1 <AudioData::Float32>::test (*this);
  21600. }
  21601. };
  21602. static AudioConversionTests audioConversionUnitTests;
  21603. #endif
  21604. END_JUCE_NAMESPACE
  21605. /*** End of inlined file: juce_AudioDataConverters.cpp ***/
  21606. /*** Start of inlined file: juce_AudioSampleBuffer.cpp ***/
  21607. BEGIN_JUCE_NAMESPACE
  21608. AudioSampleBuffer::AudioSampleBuffer (const int numChannels_,
  21609. const int numSamples) throw()
  21610. : numChannels (numChannels_),
  21611. size (numSamples)
  21612. {
  21613. jassert (numSamples >= 0);
  21614. jassert (numChannels_ > 0);
  21615. allocateData();
  21616. }
  21617. AudioSampleBuffer::AudioSampleBuffer (const AudioSampleBuffer& other) throw()
  21618. : numChannels (other.numChannels),
  21619. size (other.size)
  21620. {
  21621. allocateData();
  21622. const size_t numBytes = size * sizeof (float);
  21623. for (int i = 0; i < numChannels; ++i)
  21624. memcpy (channels[i], other.channels[i], numBytes);
  21625. }
  21626. void AudioSampleBuffer::allocateData()
  21627. {
  21628. const size_t channelListSize = (numChannels + 1) * sizeof (float*);
  21629. allocatedBytes = (int) (numChannels * size * sizeof (float) + channelListSize + 32);
  21630. allocatedData.malloc (allocatedBytes);
  21631. channels = reinterpret_cast <float**> (allocatedData.getData());
  21632. float* chan = (float*) (allocatedData + channelListSize);
  21633. for (int i = 0; i < numChannels; ++i)
  21634. {
  21635. channels[i] = chan;
  21636. chan += size;
  21637. }
  21638. channels [numChannels] = 0;
  21639. }
  21640. AudioSampleBuffer::AudioSampleBuffer (float** dataToReferTo,
  21641. const int numChannels_,
  21642. const int numSamples) throw()
  21643. : numChannels (numChannels_),
  21644. size (numSamples),
  21645. allocatedBytes (0)
  21646. {
  21647. jassert (numChannels_ > 0);
  21648. allocateChannels (dataToReferTo);
  21649. }
  21650. void AudioSampleBuffer::setDataToReferTo (float** dataToReferTo,
  21651. const int newNumChannels,
  21652. const int newNumSamples) throw()
  21653. {
  21654. jassert (newNumChannels > 0);
  21655. allocatedBytes = 0;
  21656. allocatedData.free();
  21657. numChannels = newNumChannels;
  21658. size = newNumSamples;
  21659. allocateChannels (dataToReferTo);
  21660. }
  21661. void AudioSampleBuffer::allocateChannels (float** const dataToReferTo)
  21662. {
  21663. // (try to avoid doing a malloc here, as that'll blow up things like Pro-Tools)
  21664. if (numChannels < numElementsInArray (preallocatedChannelSpace))
  21665. {
  21666. channels = static_cast <float**> (preallocatedChannelSpace);
  21667. }
  21668. else
  21669. {
  21670. allocatedData.malloc (numChannels + 1, sizeof (float*));
  21671. channels = reinterpret_cast <float**> (allocatedData.getData());
  21672. }
  21673. for (int i = 0; i < numChannels; ++i)
  21674. {
  21675. // you have to pass in the same number of valid pointers as numChannels
  21676. jassert (dataToReferTo[i] != 0);
  21677. channels[i] = dataToReferTo[i];
  21678. }
  21679. channels [numChannels] = 0;
  21680. }
  21681. AudioSampleBuffer& AudioSampleBuffer::operator= (const AudioSampleBuffer& other) throw()
  21682. {
  21683. if (this != &other)
  21684. {
  21685. setSize (other.getNumChannels(), other.getNumSamples(), false, false, false);
  21686. const size_t numBytes = size * sizeof (float);
  21687. for (int i = 0; i < numChannels; ++i)
  21688. memcpy (channels[i], other.channels[i], numBytes);
  21689. }
  21690. return *this;
  21691. }
  21692. AudioSampleBuffer::~AudioSampleBuffer() throw()
  21693. {
  21694. }
  21695. void AudioSampleBuffer::setSize (const int newNumChannels,
  21696. const int newNumSamples,
  21697. const bool keepExistingContent,
  21698. const bool clearExtraSpace,
  21699. const bool avoidReallocating) throw()
  21700. {
  21701. jassert (newNumChannels > 0);
  21702. if (newNumSamples != size || newNumChannels != numChannels)
  21703. {
  21704. const size_t channelListSize = (newNumChannels + 1) * sizeof (float*);
  21705. const size_t newTotalBytes = (newNumChannels * newNumSamples * sizeof (float)) + channelListSize + 32;
  21706. if (keepExistingContent)
  21707. {
  21708. HeapBlock <char> newData;
  21709. newData.allocate (newTotalBytes, clearExtraSpace);
  21710. const int numChansToCopy = jmin (numChannels, newNumChannels);
  21711. const size_t numBytesToCopy = sizeof (float) * jmin (newNumSamples, size);
  21712. float** const newChannels = reinterpret_cast <float**> (newData.getData());
  21713. float* newChan = reinterpret_cast <float*> (newData + channelListSize);
  21714. for (int i = 0; i < numChansToCopy; ++i)
  21715. {
  21716. memcpy (newChan, channels[i], numBytesToCopy);
  21717. newChannels[i] = newChan;
  21718. newChan += newNumSamples;
  21719. }
  21720. allocatedData.swapWith (newData);
  21721. allocatedBytes = (int) newTotalBytes;
  21722. channels = newChannels;
  21723. }
  21724. else
  21725. {
  21726. if (avoidReallocating && allocatedBytes >= newTotalBytes)
  21727. {
  21728. if (clearExtraSpace)
  21729. zeromem (allocatedData, newTotalBytes);
  21730. }
  21731. else
  21732. {
  21733. allocatedBytes = newTotalBytes;
  21734. allocatedData.allocate (newTotalBytes, clearExtraSpace);
  21735. channels = reinterpret_cast <float**> (allocatedData.getData());
  21736. }
  21737. float* chan = reinterpret_cast <float*> (allocatedData + channelListSize);
  21738. for (int i = 0; i < newNumChannels; ++i)
  21739. {
  21740. channels[i] = chan;
  21741. chan += newNumSamples;
  21742. }
  21743. }
  21744. channels [newNumChannels] = 0;
  21745. size = newNumSamples;
  21746. numChannels = newNumChannels;
  21747. }
  21748. }
  21749. void AudioSampleBuffer::clear() throw()
  21750. {
  21751. for (int i = 0; i < numChannels; ++i)
  21752. zeromem (channels[i], size * sizeof (float));
  21753. }
  21754. void AudioSampleBuffer::clear (const int startSample,
  21755. const int numSamples) throw()
  21756. {
  21757. jassert (startSample >= 0 && startSample + numSamples <= size);
  21758. for (int i = 0; i < numChannels; ++i)
  21759. zeromem (channels [i] + startSample, numSamples * sizeof (float));
  21760. }
  21761. void AudioSampleBuffer::clear (const int channel,
  21762. const int startSample,
  21763. const int numSamples) throw()
  21764. {
  21765. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21766. jassert (startSample >= 0 && startSample + numSamples <= size);
  21767. zeromem (channels [channel] + startSample, numSamples * sizeof (float));
  21768. }
  21769. void AudioSampleBuffer::applyGain (const int channel,
  21770. const int startSample,
  21771. int numSamples,
  21772. const float gain) throw()
  21773. {
  21774. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21775. jassert (startSample >= 0 && startSample + numSamples <= size);
  21776. if (gain != 1.0f)
  21777. {
  21778. float* d = channels [channel] + startSample;
  21779. if (gain == 0.0f)
  21780. {
  21781. zeromem (d, sizeof (float) * numSamples);
  21782. }
  21783. else
  21784. {
  21785. while (--numSamples >= 0)
  21786. *d++ *= gain;
  21787. }
  21788. }
  21789. }
  21790. void AudioSampleBuffer::applyGainRamp (const int channel,
  21791. const int startSample,
  21792. int numSamples,
  21793. float startGain,
  21794. float endGain) throw()
  21795. {
  21796. if (startGain == endGain)
  21797. {
  21798. applyGain (channel, startSample, numSamples, startGain);
  21799. }
  21800. else
  21801. {
  21802. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21803. jassert (startSample >= 0 && startSample + numSamples <= size);
  21804. const float increment = (endGain - startGain) / numSamples;
  21805. float* d = channels [channel] + startSample;
  21806. while (--numSamples >= 0)
  21807. {
  21808. *d++ *= startGain;
  21809. startGain += increment;
  21810. }
  21811. }
  21812. }
  21813. void AudioSampleBuffer::applyGain (const int startSample,
  21814. const int numSamples,
  21815. const float gain) throw()
  21816. {
  21817. for (int i = 0; i < numChannels; ++i)
  21818. applyGain (i, startSample, numSamples, gain);
  21819. }
  21820. void AudioSampleBuffer::addFrom (const int destChannel,
  21821. const int destStartSample,
  21822. const AudioSampleBuffer& source,
  21823. const int sourceChannel,
  21824. const int sourceStartSample,
  21825. int numSamples,
  21826. const float gain) throw()
  21827. {
  21828. jassert (&source != this || sourceChannel != destChannel);
  21829. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21830. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21831. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  21832. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  21833. if (gain != 0.0f && numSamples > 0)
  21834. {
  21835. float* d = channels [destChannel] + destStartSample;
  21836. const float* s = source.channels [sourceChannel] + sourceStartSample;
  21837. if (gain != 1.0f)
  21838. {
  21839. while (--numSamples >= 0)
  21840. *d++ += gain * *s++;
  21841. }
  21842. else
  21843. {
  21844. while (--numSamples >= 0)
  21845. *d++ += *s++;
  21846. }
  21847. }
  21848. }
  21849. void AudioSampleBuffer::addFrom (const int destChannel,
  21850. const int destStartSample,
  21851. const float* source,
  21852. int numSamples,
  21853. const float gain) throw()
  21854. {
  21855. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21856. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21857. jassert (source != 0);
  21858. if (gain != 0.0f && numSamples > 0)
  21859. {
  21860. float* d = channels [destChannel] + destStartSample;
  21861. if (gain != 1.0f)
  21862. {
  21863. while (--numSamples >= 0)
  21864. *d++ += gain * *source++;
  21865. }
  21866. else
  21867. {
  21868. while (--numSamples >= 0)
  21869. *d++ += *source++;
  21870. }
  21871. }
  21872. }
  21873. void AudioSampleBuffer::addFromWithRamp (const int destChannel,
  21874. const int destStartSample,
  21875. const float* source,
  21876. int numSamples,
  21877. float startGain,
  21878. const float endGain) throw()
  21879. {
  21880. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21881. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21882. jassert (source != 0);
  21883. if (startGain == endGain)
  21884. {
  21885. addFrom (destChannel,
  21886. destStartSample,
  21887. source,
  21888. numSamples,
  21889. startGain);
  21890. }
  21891. else
  21892. {
  21893. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  21894. {
  21895. const float increment = (endGain - startGain) / numSamples;
  21896. float* d = channels [destChannel] + destStartSample;
  21897. while (--numSamples >= 0)
  21898. {
  21899. *d++ += startGain * *source++;
  21900. startGain += increment;
  21901. }
  21902. }
  21903. }
  21904. }
  21905. void AudioSampleBuffer::copyFrom (const int destChannel,
  21906. const int destStartSample,
  21907. const AudioSampleBuffer& source,
  21908. const int sourceChannel,
  21909. const int sourceStartSample,
  21910. int numSamples) throw()
  21911. {
  21912. jassert (&source != this || sourceChannel != destChannel);
  21913. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21914. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21915. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  21916. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  21917. if (numSamples > 0)
  21918. {
  21919. memcpy (channels [destChannel] + destStartSample,
  21920. source.channels [sourceChannel] + sourceStartSample,
  21921. sizeof (float) * numSamples);
  21922. }
  21923. }
  21924. void AudioSampleBuffer::copyFrom (const int destChannel,
  21925. const int destStartSample,
  21926. const float* source,
  21927. int numSamples) throw()
  21928. {
  21929. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21930. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21931. jassert (source != 0);
  21932. if (numSamples > 0)
  21933. {
  21934. memcpy (channels [destChannel] + destStartSample,
  21935. source,
  21936. sizeof (float) * numSamples);
  21937. }
  21938. }
  21939. void AudioSampleBuffer::copyFrom (const int destChannel,
  21940. const int destStartSample,
  21941. const float* source,
  21942. int numSamples,
  21943. const float gain) throw()
  21944. {
  21945. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21946. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21947. jassert (source != 0);
  21948. if (numSamples > 0)
  21949. {
  21950. float* d = channels [destChannel] + destStartSample;
  21951. if (gain != 1.0f)
  21952. {
  21953. if (gain == 0)
  21954. {
  21955. zeromem (d, sizeof (float) * numSamples);
  21956. }
  21957. else
  21958. {
  21959. while (--numSamples >= 0)
  21960. *d++ = gain * *source++;
  21961. }
  21962. }
  21963. else
  21964. {
  21965. memcpy (d, source, sizeof (float) * numSamples);
  21966. }
  21967. }
  21968. }
  21969. void AudioSampleBuffer::copyFromWithRamp (const int destChannel,
  21970. const int destStartSample,
  21971. const float* source,
  21972. int numSamples,
  21973. float startGain,
  21974. float endGain) throw()
  21975. {
  21976. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21977. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21978. jassert (source != 0);
  21979. if (startGain == endGain)
  21980. {
  21981. copyFrom (destChannel,
  21982. destStartSample,
  21983. source,
  21984. numSamples,
  21985. startGain);
  21986. }
  21987. else
  21988. {
  21989. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  21990. {
  21991. const float increment = (endGain - startGain) / numSamples;
  21992. float* d = channels [destChannel] + destStartSample;
  21993. while (--numSamples >= 0)
  21994. {
  21995. *d++ = startGain * *source++;
  21996. startGain += increment;
  21997. }
  21998. }
  21999. }
  22000. }
  22001. void AudioSampleBuffer::findMinMax (const int channel,
  22002. const int startSample,
  22003. int numSamples,
  22004. float& minVal,
  22005. float& maxVal) const throw()
  22006. {
  22007. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  22008. jassert (startSample >= 0 && startSample + numSamples <= size);
  22009. if (numSamples <= 0)
  22010. {
  22011. minVal = 0.0f;
  22012. maxVal = 0.0f;
  22013. }
  22014. else
  22015. {
  22016. const float* d = channels [channel] + startSample;
  22017. float mn = *d++;
  22018. float mx = mn;
  22019. while (--numSamples > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  22020. {
  22021. const float samp = *d++;
  22022. if (samp > mx)
  22023. mx = samp;
  22024. if (samp < mn)
  22025. mn = samp;
  22026. }
  22027. maxVal = mx;
  22028. minVal = mn;
  22029. }
  22030. }
  22031. float AudioSampleBuffer::getMagnitude (const int channel,
  22032. const int startSample,
  22033. const int numSamples) const throw()
  22034. {
  22035. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  22036. jassert (startSample >= 0 && startSample + numSamples <= size);
  22037. float mn, mx;
  22038. findMinMax (channel, startSample, numSamples, mn, mx);
  22039. return jmax (mn, -mn, mx, -mx);
  22040. }
  22041. float AudioSampleBuffer::getMagnitude (const int startSample,
  22042. const int numSamples) const throw()
  22043. {
  22044. float mag = 0.0f;
  22045. for (int i = 0; i < numChannels; ++i)
  22046. mag = jmax (mag, getMagnitude (i, startSample, numSamples));
  22047. return mag;
  22048. }
  22049. float AudioSampleBuffer::getRMSLevel (const int channel,
  22050. const int startSample,
  22051. const int numSamples) const throw()
  22052. {
  22053. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  22054. jassert (startSample >= 0 && startSample + numSamples <= size);
  22055. if (numSamples <= 0 || channel < 0 || channel >= numChannels)
  22056. return 0.0f;
  22057. const float* const data = channels [channel] + startSample;
  22058. double sum = 0.0;
  22059. for (int i = 0; i < numSamples; ++i)
  22060. {
  22061. const float sample = data [i];
  22062. sum += sample * sample;
  22063. }
  22064. return (float) std::sqrt (sum / numSamples);
  22065. }
  22066. void AudioSampleBuffer::readFromAudioReader (AudioFormatReader* reader,
  22067. const int startSample,
  22068. const int numSamples,
  22069. const int readerStartSample,
  22070. const bool useLeftChan,
  22071. const bool useRightChan)
  22072. {
  22073. jassert (reader != 0);
  22074. jassert (startSample >= 0 && startSample + numSamples <= size);
  22075. if (numSamples > 0)
  22076. {
  22077. int* chans[3];
  22078. if (useLeftChan == useRightChan)
  22079. {
  22080. chans[0] = reinterpret_cast<int*> (getSampleData (0, startSample));
  22081. chans[1] = (reader->numChannels > 1 && getNumChannels() > 1) ? reinterpret_cast<int*> (getSampleData (1, startSample)) : 0;
  22082. }
  22083. else if (useLeftChan || (reader->numChannels == 1))
  22084. {
  22085. chans[0] = reinterpret_cast<int*> (getSampleData (0, startSample));
  22086. chans[1] = 0;
  22087. }
  22088. else if (useRightChan)
  22089. {
  22090. chans[0] = 0;
  22091. chans[1] = reinterpret_cast<int*> (getSampleData (0, startSample));
  22092. }
  22093. chans[2] = 0;
  22094. reader->read (chans, 2, readerStartSample, numSamples, true);
  22095. if (! reader->usesFloatingPointData)
  22096. {
  22097. for (int j = 0; j < 2; ++j)
  22098. {
  22099. float* const d = reinterpret_cast <float*> (chans[j]);
  22100. if (d != 0)
  22101. {
  22102. const float multiplier = 1.0f / 0x7fffffff;
  22103. for (int i = 0; i < numSamples; ++i)
  22104. d[i] = *reinterpret_cast<int*> (d + i) * multiplier;
  22105. }
  22106. }
  22107. }
  22108. if (numChannels > 1 && (chans[0] == 0 || chans[1] == 0))
  22109. {
  22110. // if this is a stereo buffer and the source was mono, dupe the first channel..
  22111. memcpy (getSampleData (1, startSample),
  22112. getSampleData (0, startSample),
  22113. sizeof (float) * numSamples);
  22114. }
  22115. }
  22116. }
  22117. void AudioSampleBuffer::writeToAudioWriter (AudioFormatWriter* writer,
  22118. const int startSample,
  22119. const int numSamples) const
  22120. {
  22121. jassert (writer != 0);
  22122. writer->writeFromAudioSampleBuffer (*this, startSample, numSamples);
  22123. }
  22124. END_JUCE_NAMESPACE
  22125. /*** End of inlined file: juce_AudioSampleBuffer.cpp ***/
  22126. /*** Start of inlined file: juce_IIRFilter.cpp ***/
  22127. BEGIN_JUCE_NAMESPACE
  22128. IIRFilter::IIRFilter()
  22129. : active (false)
  22130. {
  22131. reset();
  22132. }
  22133. IIRFilter::IIRFilter (const IIRFilter& other)
  22134. : active (other.active)
  22135. {
  22136. const ScopedLock sl (other.processLock);
  22137. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  22138. reset();
  22139. }
  22140. IIRFilter::~IIRFilter()
  22141. {
  22142. }
  22143. void IIRFilter::reset() throw()
  22144. {
  22145. const ScopedLock sl (processLock);
  22146. x1 = 0;
  22147. x2 = 0;
  22148. y1 = 0;
  22149. y2 = 0;
  22150. }
  22151. float IIRFilter::processSingleSampleRaw (const float in) throw()
  22152. {
  22153. float out = coefficients[0] * in
  22154. + coefficients[1] * x1
  22155. + coefficients[2] * x2
  22156. - coefficients[4] * y1
  22157. - coefficients[5] * y2;
  22158. #if JUCE_INTEL
  22159. if (! (out < -1.0e-8 || out > 1.0e-8))
  22160. out = 0;
  22161. #endif
  22162. x2 = x1;
  22163. x1 = in;
  22164. y2 = y1;
  22165. y1 = out;
  22166. return out;
  22167. }
  22168. void IIRFilter::processSamples (float* const samples,
  22169. const int numSamples) throw()
  22170. {
  22171. const ScopedLock sl (processLock);
  22172. if (active)
  22173. {
  22174. for (int i = 0; i < numSamples; ++i)
  22175. {
  22176. const float in = samples[i];
  22177. float out = coefficients[0] * in
  22178. + coefficients[1] * x1
  22179. + coefficients[2] * x2
  22180. - coefficients[4] * y1
  22181. - coefficients[5] * y2;
  22182. #if JUCE_INTEL
  22183. if (! (out < -1.0e-8 || out > 1.0e-8))
  22184. out = 0;
  22185. #endif
  22186. x2 = x1;
  22187. x1 = in;
  22188. y2 = y1;
  22189. y1 = out;
  22190. samples[i] = out;
  22191. }
  22192. }
  22193. }
  22194. void IIRFilter::makeLowPass (const double sampleRate,
  22195. const double frequency) throw()
  22196. {
  22197. jassert (sampleRate > 0);
  22198. const double n = 1.0 / tan (double_Pi * frequency / sampleRate);
  22199. const double nSquared = n * n;
  22200. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  22201. setCoefficients (c1,
  22202. c1 * 2.0f,
  22203. c1,
  22204. 1.0,
  22205. c1 * 2.0 * (1.0 - nSquared),
  22206. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  22207. }
  22208. void IIRFilter::makeHighPass (const double sampleRate,
  22209. const double frequency) throw()
  22210. {
  22211. const double n = tan (double_Pi * frequency / sampleRate);
  22212. const double nSquared = n * n;
  22213. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  22214. setCoefficients (c1,
  22215. c1 * -2.0f,
  22216. c1,
  22217. 1.0,
  22218. c1 * 2.0 * (nSquared - 1.0),
  22219. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  22220. }
  22221. void IIRFilter::makeLowShelf (const double sampleRate,
  22222. const double cutOffFrequency,
  22223. const double Q,
  22224. const float gainFactor) throw()
  22225. {
  22226. jassert (sampleRate > 0);
  22227. jassert (Q > 0);
  22228. const double A = jmax (0.0f, gainFactor);
  22229. const double aminus1 = A - 1.0;
  22230. const double aplus1 = A + 1.0;
  22231. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  22232. const double coso = std::cos (omega);
  22233. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  22234. const double aminus1TimesCoso = aminus1 * coso;
  22235. setCoefficients (A * (aplus1 - aminus1TimesCoso + beta),
  22236. A * 2.0 * (aminus1 - aplus1 * coso),
  22237. A * (aplus1 - aminus1TimesCoso - beta),
  22238. aplus1 + aminus1TimesCoso + beta,
  22239. -2.0 * (aminus1 + aplus1 * coso),
  22240. aplus1 + aminus1TimesCoso - beta);
  22241. }
  22242. void IIRFilter::makeHighShelf (const double sampleRate,
  22243. const double cutOffFrequency,
  22244. const double Q,
  22245. const float gainFactor) throw()
  22246. {
  22247. jassert (sampleRate > 0);
  22248. jassert (Q > 0);
  22249. const double A = jmax (0.0f, gainFactor);
  22250. const double aminus1 = A - 1.0;
  22251. const double aplus1 = A + 1.0;
  22252. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  22253. const double coso = std::cos (omega);
  22254. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  22255. const double aminus1TimesCoso = aminus1 * coso;
  22256. setCoefficients (A * (aplus1 + aminus1TimesCoso + beta),
  22257. A * -2.0 * (aminus1 + aplus1 * coso),
  22258. A * (aplus1 + aminus1TimesCoso - beta),
  22259. aplus1 - aminus1TimesCoso + beta,
  22260. 2.0 * (aminus1 - aplus1 * coso),
  22261. aplus1 - aminus1TimesCoso - beta);
  22262. }
  22263. void IIRFilter::makeBandPass (const double sampleRate,
  22264. const double centreFrequency,
  22265. const double Q,
  22266. const float gainFactor) throw()
  22267. {
  22268. jassert (sampleRate > 0);
  22269. jassert (Q > 0);
  22270. const double A = jmax (0.0f, gainFactor);
  22271. const double omega = (double_Pi * 2.0 * jmax (centreFrequency, 2.0)) / sampleRate;
  22272. const double alpha = 0.5 * std::sin (omega) / Q;
  22273. const double c2 = -2.0 * std::cos (omega);
  22274. const double alphaTimesA = alpha * A;
  22275. const double alphaOverA = alpha / A;
  22276. setCoefficients (1.0 + alphaTimesA,
  22277. c2,
  22278. 1.0 - alphaTimesA,
  22279. 1.0 + alphaOverA,
  22280. c2,
  22281. 1.0 - alphaOverA);
  22282. }
  22283. void IIRFilter::makeInactive() throw()
  22284. {
  22285. const ScopedLock sl (processLock);
  22286. active = false;
  22287. }
  22288. void IIRFilter::copyCoefficientsFrom (const IIRFilter& other) throw()
  22289. {
  22290. const ScopedLock sl (processLock);
  22291. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  22292. active = other.active;
  22293. }
  22294. void IIRFilter::setCoefficients (double c1,
  22295. double c2,
  22296. double c3,
  22297. double c4,
  22298. double c5,
  22299. double c6) throw()
  22300. {
  22301. const double a = 1.0 / c4;
  22302. c1 *= a;
  22303. c2 *= a;
  22304. c3 *= a;
  22305. c5 *= a;
  22306. c6 *= a;
  22307. const ScopedLock sl (processLock);
  22308. coefficients[0] = (float) c1;
  22309. coefficients[1] = (float) c2;
  22310. coefficients[2] = (float) c3;
  22311. coefficients[3] = (float) c4;
  22312. coefficients[4] = (float) c5;
  22313. coefficients[5] = (float) c6;
  22314. active = true;
  22315. }
  22316. END_JUCE_NAMESPACE
  22317. /*** End of inlined file: juce_IIRFilter.cpp ***/
  22318. /*** Start of inlined file: juce_MidiBuffer.cpp ***/
  22319. BEGIN_JUCE_NAMESPACE
  22320. MidiBuffer::MidiBuffer() throw()
  22321. : bytesUsed (0)
  22322. {
  22323. }
  22324. MidiBuffer::MidiBuffer (const MidiMessage& message) throw()
  22325. : bytesUsed (0)
  22326. {
  22327. addEvent (message, 0);
  22328. }
  22329. MidiBuffer::MidiBuffer (const MidiBuffer& other) throw()
  22330. : data (other.data),
  22331. bytesUsed (other.bytesUsed)
  22332. {
  22333. }
  22334. MidiBuffer& MidiBuffer::operator= (const MidiBuffer& other) throw()
  22335. {
  22336. bytesUsed = other.bytesUsed;
  22337. data = other.data;
  22338. return *this;
  22339. }
  22340. void MidiBuffer::swapWith (MidiBuffer& other) throw()
  22341. {
  22342. data.swapWith (other.data);
  22343. swapVariables <int> (bytesUsed, other.bytesUsed);
  22344. }
  22345. MidiBuffer::~MidiBuffer()
  22346. {
  22347. }
  22348. inline uint8* MidiBuffer::getData() const throw()
  22349. {
  22350. return static_cast <uint8*> (data.getData());
  22351. }
  22352. inline int MidiBuffer::getEventTime (const void* const d) throw()
  22353. {
  22354. return *static_cast <const int*> (d);
  22355. }
  22356. inline uint16 MidiBuffer::getEventDataSize (const void* const d) throw()
  22357. {
  22358. return *reinterpret_cast <const uint16*> (static_cast <const char*> (d) + sizeof (int));
  22359. }
  22360. inline uint16 MidiBuffer::getEventTotalSize (const void* const d) throw()
  22361. {
  22362. return getEventDataSize (d) + sizeof (int) + sizeof (uint16);
  22363. }
  22364. void MidiBuffer::clear() throw()
  22365. {
  22366. bytesUsed = 0;
  22367. }
  22368. void MidiBuffer::clear (const int startSample, const int numSamples)
  22369. {
  22370. uint8* const start = findEventAfter (getData(), startSample - 1);
  22371. uint8* const end = findEventAfter (start, startSample + numSamples - 1);
  22372. if (end > start)
  22373. {
  22374. const int bytesToMove = bytesUsed - (int) (end - getData());
  22375. if (bytesToMove > 0)
  22376. memmove (start, end, bytesToMove);
  22377. bytesUsed -= (int) (end - start);
  22378. }
  22379. }
  22380. void MidiBuffer::addEvent (const MidiMessage& m, const int sampleNumber)
  22381. {
  22382. addEvent (m.getRawData(), m.getRawDataSize(), sampleNumber);
  22383. }
  22384. static int findActualEventLength (const uint8* const data, const int maxBytes) throw()
  22385. {
  22386. unsigned int byte = (unsigned int) *data;
  22387. int size = 0;
  22388. if (byte == 0xf0 || byte == 0xf7)
  22389. {
  22390. const uint8* d = data + 1;
  22391. while (d < data + maxBytes)
  22392. if (*d++ == 0xf7)
  22393. break;
  22394. size = (int) (d - data);
  22395. }
  22396. else if (byte == 0xff)
  22397. {
  22398. int n;
  22399. const int bytesLeft = MidiMessage::readVariableLengthVal (data + 1, n);
  22400. size = jmin (maxBytes, n + 2 + bytesLeft);
  22401. }
  22402. else if (byte >= 0x80)
  22403. {
  22404. size = jmin (maxBytes, MidiMessage::getMessageLengthFromFirstByte ((uint8) byte));
  22405. }
  22406. return size;
  22407. }
  22408. void MidiBuffer::addEvent (const void* const newData, const int maxBytes, const int sampleNumber)
  22409. {
  22410. const int numBytes = findActualEventLength (static_cast <const uint8*> (newData), maxBytes);
  22411. if (numBytes > 0)
  22412. {
  22413. int spaceNeeded = bytesUsed + numBytes + sizeof (int) + sizeof (uint16);
  22414. data.ensureSize ((spaceNeeded + spaceNeeded / 2 + 8) & ~7);
  22415. uint8* d = findEventAfter (getData(), sampleNumber);
  22416. const int bytesToMove = bytesUsed - (int) (d - getData());
  22417. if (bytesToMove > 0)
  22418. memmove (d + numBytes + sizeof (int) + sizeof (uint16), d, bytesToMove);
  22419. *reinterpret_cast <int*> (d) = sampleNumber;
  22420. d += sizeof (int);
  22421. *reinterpret_cast <uint16*> (d) = (uint16) numBytes;
  22422. d += sizeof (uint16);
  22423. memcpy (d, newData, numBytes);
  22424. bytesUsed += numBytes + sizeof (int) + sizeof (uint16);
  22425. }
  22426. }
  22427. void MidiBuffer::addEvents (const MidiBuffer& otherBuffer,
  22428. const int startSample,
  22429. const int numSamples,
  22430. const int sampleDeltaToAdd)
  22431. {
  22432. Iterator i (otherBuffer);
  22433. i.setNextSamplePosition (startSample);
  22434. const uint8* eventData;
  22435. int eventSize, position;
  22436. while (i.getNextEvent (eventData, eventSize, position)
  22437. && (position < startSample + numSamples || numSamples < 0))
  22438. {
  22439. addEvent (eventData, eventSize, position + sampleDeltaToAdd);
  22440. }
  22441. }
  22442. void MidiBuffer::ensureSize (size_t minimumNumBytes)
  22443. {
  22444. data.ensureSize (minimumNumBytes);
  22445. }
  22446. bool MidiBuffer::isEmpty() const throw()
  22447. {
  22448. return bytesUsed == 0;
  22449. }
  22450. int MidiBuffer::getNumEvents() const throw()
  22451. {
  22452. int n = 0;
  22453. const uint8* d = getData();
  22454. const uint8* const end = d + bytesUsed;
  22455. while (d < end)
  22456. {
  22457. d += getEventTotalSize (d);
  22458. ++n;
  22459. }
  22460. return n;
  22461. }
  22462. int MidiBuffer::getFirstEventTime() const throw()
  22463. {
  22464. return bytesUsed > 0 ? getEventTime (data.getData()) : 0;
  22465. }
  22466. int MidiBuffer::getLastEventTime() const throw()
  22467. {
  22468. if (bytesUsed == 0)
  22469. return 0;
  22470. const uint8* d = getData();
  22471. const uint8* const endData = d + bytesUsed;
  22472. for (;;)
  22473. {
  22474. const uint8* const nextOne = d + getEventTotalSize (d);
  22475. if (nextOne >= endData)
  22476. return getEventTime (d);
  22477. d = nextOne;
  22478. }
  22479. }
  22480. uint8* MidiBuffer::findEventAfter (uint8* d, const int samplePosition) const throw()
  22481. {
  22482. const uint8* const endData = getData() + bytesUsed;
  22483. while (d < endData && getEventTime (d) <= samplePosition)
  22484. d += getEventTotalSize (d);
  22485. return d;
  22486. }
  22487. MidiBuffer::Iterator::Iterator (const MidiBuffer& buffer_) throw()
  22488. : buffer (buffer_),
  22489. data (buffer_.getData())
  22490. {
  22491. }
  22492. MidiBuffer::Iterator::~Iterator() throw()
  22493. {
  22494. }
  22495. void MidiBuffer::Iterator::setNextSamplePosition (const int samplePosition) throw()
  22496. {
  22497. data = buffer.getData();
  22498. const uint8* dataEnd = data + buffer.bytesUsed;
  22499. while (data < dataEnd && getEventTime (data) < samplePosition)
  22500. data += getEventTotalSize (data);
  22501. }
  22502. bool MidiBuffer::Iterator::getNextEvent (const uint8* &midiData, int& numBytes, int& samplePosition) throw()
  22503. {
  22504. if (data >= buffer.getData() + buffer.bytesUsed)
  22505. return false;
  22506. samplePosition = getEventTime (data);
  22507. numBytes = getEventDataSize (data);
  22508. data += sizeof (int) + sizeof (uint16);
  22509. midiData = data;
  22510. data += numBytes;
  22511. return true;
  22512. }
  22513. bool MidiBuffer::Iterator::getNextEvent (MidiMessage& result, int& samplePosition) throw()
  22514. {
  22515. if (data >= buffer.getData() + buffer.bytesUsed)
  22516. return false;
  22517. samplePosition = getEventTime (data);
  22518. const int numBytes = getEventDataSize (data);
  22519. data += sizeof (int) + sizeof (uint16);
  22520. result = MidiMessage (data, numBytes, samplePosition);
  22521. data += numBytes;
  22522. return true;
  22523. }
  22524. END_JUCE_NAMESPACE
  22525. /*** End of inlined file: juce_MidiBuffer.cpp ***/
  22526. /*** Start of inlined file: juce_MidiFile.cpp ***/
  22527. BEGIN_JUCE_NAMESPACE
  22528. namespace MidiFileHelpers
  22529. {
  22530. static void writeVariableLengthInt (OutputStream& out, unsigned int v)
  22531. {
  22532. unsigned int buffer = v & 0x7F;
  22533. while ((v >>= 7) != 0)
  22534. {
  22535. buffer <<= 8;
  22536. buffer |= ((v & 0x7F) | 0x80);
  22537. }
  22538. for (;;)
  22539. {
  22540. out.writeByte ((char) buffer);
  22541. if (buffer & 0x80)
  22542. buffer >>= 8;
  22543. else
  22544. break;
  22545. }
  22546. }
  22547. static bool parseMidiHeader (const uint8* &data, short& timeFormat, short& fileType, short& numberOfTracks) throw()
  22548. {
  22549. unsigned int ch = (int) ByteOrder::bigEndianInt (data);
  22550. data += 4;
  22551. if (ch != ByteOrder::bigEndianInt ("MThd"))
  22552. {
  22553. bool ok = false;
  22554. if (ch == ByteOrder::bigEndianInt ("RIFF"))
  22555. {
  22556. for (int i = 0; i < 8; ++i)
  22557. {
  22558. ch = ByteOrder::bigEndianInt (data);
  22559. data += 4;
  22560. if (ch == ByteOrder::bigEndianInt ("MThd"))
  22561. {
  22562. ok = true;
  22563. break;
  22564. }
  22565. }
  22566. }
  22567. if (! ok)
  22568. return false;
  22569. }
  22570. unsigned int bytesRemaining = ByteOrder::bigEndianInt (data);
  22571. data += 4;
  22572. fileType = (short) ByteOrder::bigEndianShort (data);
  22573. data += 2;
  22574. numberOfTracks = (short) ByteOrder::bigEndianShort (data);
  22575. data += 2;
  22576. timeFormat = (short) ByteOrder::bigEndianShort (data);
  22577. data += 2;
  22578. bytesRemaining -= 6;
  22579. data += bytesRemaining;
  22580. return true;
  22581. }
  22582. static double convertTicksToSeconds (const double time,
  22583. const MidiMessageSequence& tempoEvents,
  22584. const int timeFormat)
  22585. {
  22586. if (timeFormat > 0)
  22587. {
  22588. int numer = 4, denom = 4;
  22589. double tempoTime = 0.0, correctedTempoTime = 0.0;
  22590. const double tickLen = 1.0 / (timeFormat & 0x7fff);
  22591. double secsPerTick = 0.5 * tickLen;
  22592. const int numEvents = tempoEvents.getNumEvents();
  22593. for (int i = 0; i < numEvents; ++i)
  22594. {
  22595. const MidiMessage& m = tempoEvents.getEventPointer(i)->message;
  22596. if (time <= m.getTimeStamp())
  22597. break;
  22598. if (timeFormat > 0)
  22599. {
  22600. correctedTempoTime = correctedTempoTime
  22601. + (m.getTimeStamp() - tempoTime) * secsPerTick;
  22602. }
  22603. else
  22604. {
  22605. correctedTempoTime = tickLen * m.getTimeStamp() / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  22606. }
  22607. tempoTime = m.getTimeStamp();
  22608. if (m.isTempoMetaEvent())
  22609. secsPerTick = tickLen * m.getTempoSecondsPerQuarterNote();
  22610. else if (m.isTimeSignatureMetaEvent())
  22611. m.getTimeSignatureInfo (numer, denom);
  22612. while (i + 1 < numEvents)
  22613. {
  22614. const MidiMessage& m2 = tempoEvents.getEventPointer(i + 1)->message;
  22615. if (m2.getTimeStamp() == tempoTime)
  22616. {
  22617. ++i;
  22618. if (m2.isTempoMetaEvent())
  22619. secsPerTick = tickLen * m2.getTempoSecondsPerQuarterNote();
  22620. else if (m2.isTimeSignatureMetaEvent())
  22621. m2.getTimeSignatureInfo (numer, denom);
  22622. }
  22623. else
  22624. {
  22625. break;
  22626. }
  22627. }
  22628. }
  22629. return correctedTempoTime + (time - tempoTime) * secsPerTick;
  22630. }
  22631. else
  22632. {
  22633. return time / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  22634. }
  22635. }
  22636. // a comparator that puts all the note-offs before note-ons that have the same time
  22637. struct Sorter
  22638. {
  22639. static int compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  22640. const MidiMessageSequence::MidiEventHolder* const second) throw()
  22641. {
  22642. const double diff = (first->message.getTimeStamp() - second->message.getTimeStamp());
  22643. if (diff == 0)
  22644. {
  22645. if (first->message.isNoteOff() && second->message.isNoteOn())
  22646. return -1;
  22647. else if (first->message.isNoteOn() && second->message.isNoteOff())
  22648. return 1;
  22649. else
  22650. return 0;
  22651. }
  22652. else
  22653. {
  22654. return (diff > 0) ? 1 : -1;
  22655. }
  22656. }
  22657. };
  22658. }
  22659. MidiFile::MidiFile()
  22660. : timeFormat ((short) (unsigned short) 0xe728)
  22661. {
  22662. }
  22663. MidiFile::~MidiFile()
  22664. {
  22665. clear();
  22666. }
  22667. void MidiFile::clear()
  22668. {
  22669. tracks.clear();
  22670. }
  22671. int MidiFile::getNumTracks() const throw()
  22672. {
  22673. return tracks.size();
  22674. }
  22675. const MidiMessageSequence* MidiFile::getTrack (const int index) const throw()
  22676. {
  22677. return tracks [index];
  22678. }
  22679. void MidiFile::addTrack (const MidiMessageSequence& trackSequence)
  22680. {
  22681. tracks.add (new MidiMessageSequence (trackSequence));
  22682. }
  22683. short MidiFile::getTimeFormat() const throw()
  22684. {
  22685. return timeFormat;
  22686. }
  22687. void MidiFile::setTicksPerQuarterNote (const int ticks) throw()
  22688. {
  22689. timeFormat = (short) ticks;
  22690. }
  22691. void MidiFile::setSmpteTimeFormat (const int framesPerSecond,
  22692. const int subframeResolution) throw()
  22693. {
  22694. timeFormat = (short) (((-framesPerSecond) << 8) | subframeResolution);
  22695. }
  22696. void MidiFile::findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const
  22697. {
  22698. for (int i = tracks.size(); --i >= 0;)
  22699. {
  22700. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  22701. for (int j = 0; j < numEvents; ++j)
  22702. {
  22703. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  22704. if (m.isTempoMetaEvent())
  22705. tempoChangeEvents.addEvent (m);
  22706. }
  22707. }
  22708. }
  22709. void MidiFile::findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const
  22710. {
  22711. for (int i = tracks.size(); --i >= 0;)
  22712. {
  22713. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  22714. for (int j = 0; j < numEvents; ++j)
  22715. {
  22716. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  22717. if (m.isTimeSignatureMetaEvent())
  22718. timeSigEvents.addEvent (m);
  22719. }
  22720. }
  22721. }
  22722. double MidiFile::getLastTimestamp() const
  22723. {
  22724. double t = 0.0;
  22725. for (int i = tracks.size(); --i >= 0;)
  22726. t = jmax (t, tracks.getUnchecked(i)->getEndTime());
  22727. return t;
  22728. }
  22729. bool MidiFile::readFrom (InputStream& sourceStream)
  22730. {
  22731. clear();
  22732. MemoryBlock data;
  22733. const int maxSensibleMidiFileSize = 2 * 1024 * 1024;
  22734. // (put a sanity-check on the file size, as midi files are generally small)
  22735. if (sourceStream.readIntoMemoryBlock (data, maxSensibleMidiFileSize))
  22736. {
  22737. size_t size = data.getSize();
  22738. const uint8* d = static_cast <const uint8*> (data.getData());
  22739. short fileType, expectedTracks;
  22740. if (size > 16 && MidiFileHelpers::parseMidiHeader (d, timeFormat, fileType, expectedTracks))
  22741. {
  22742. size -= (int) (d - static_cast <const uint8*> (data.getData()));
  22743. int track = 0;
  22744. while (size > 0 && track < expectedTracks)
  22745. {
  22746. const int chunkType = (int) ByteOrder::bigEndianInt (d);
  22747. d += 4;
  22748. const int chunkSize = (int) ByteOrder::bigEndianInt (d);
  22749. d += 4;
  22750. if (chunkSize <= 0)
  22751. break;
  22752. if (size < 0)
  22753. return false;
  22754. if (chunkType == (int) ByteOrder::bigEndianInt ("MTrk"))
  22755. {
  22756. readNextTrack (d, chunkSize);
  22757. }
  22758. size -= chunkSize + 8;
  22759. d += chunkSize;
  22760. ++track;
  22761. }
  22762. return true;
  22763. }
  22764. }
  22765. return false;
  22766. }
  22767. void MidiFile::readNextTrack (const uint8* data, int size)
  22768. {
  22769. double time = 0;
  22770. char lastStatusByte = 0;
  22771. MidiMessageSequence result;
  22772. while (size > 0)
  22773. {
  22774. int bytesUsed;
  22775. const int delay = MidiMessage::readVariableLengthVal (data, bytesUsed);
  22776. data += bytesUsed;
  22777. size -= bytesUsed;
  22778. time += delay;
  22779. int messSize = 0;
  22780. const MidiMessage mm (data, size, messSize, lastStatusByte, time);
  22781. if (messSize <= 0)
  22782. break;
  22783. size -= messSize;
  22784. data += messSize;
  22785. result.addEvent (mm);
  22786. const char firstByte = *(mm.getRawData());
  22787. if ((firstByte & 0xf0) != 0xf0)
  22788. lastStatusByte = firstByte;
  22789. }
  22790. // use a sort that puts all the note-offs before note-ons that have the same time
  22791. MidiFileHelpers::Sorter sorter;
  22792. result.list.sort (sorter, true);
  22793. result.updateMatchedPairs();
  22794. addTrack (result);
  22795. }
  22796. void MidiFile::convertTimestampTicksToSeconds()
  22797. {
  22798. MidiMessageSequence tempoEvents;
  22799. findAllTempoEvents (tempoEvents);
  22800. findAllTimeSigEvents (tempoEvents);
  22801. for (int i = 0; i < tracks.size(); ++i)
  22802. {
  22803. MidiMessageSequence& ms = *tracks.getUnchecked(i);
  22804. for (int j = ms.getNumEvents(); --j >= 0;)
  22805. {
  22806. MidiMessage& m = ms.getEventPointer(j)->message;
  22807. m.setTimeStamp (MidiFileHelpers::convertTicksToSeconds (m.getTimeStamp(),
  22808. tempoEvents,
  22809. timeFormat));
  22810. }
  22811. }
  22812. }
  22813. bool MidiFile::writeTo (OutputStream& out)
  22814. {
  22815. out.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MThd"));
  22816. out.writeIntBigEndian (6);
  22817. out.writeShortBigEndian (1); // type
  22818. out.writeShortBigEndian ((short) tracks.size());
  22819. out.writeShortBigEndian (timeFormat);
  22820. for (int i = 0; i < tracks.size(); ++i)
  22821. writeTrack (out, i);
  22822. out.flush();
  22823. return true;
  22824. }
  22825. void MidiFile::writeTrack (OutputStream& mainOut,
  22826. const int trackNum)
  22827. {
  22828. MemoryOutputStream out;
  22829. const MidiMessageSequence& ms = *tracks[trackNum];
  22830. int lastTick = 0;
  22831. char lastStatusByte = 0;
  22832. for (int i = 0; i < ms.getNumEvents(); ++i)
  22833. {
  22834. const MidiMessage& mm = ms.getEventPointer(i)->message;
  22835. const int tick = roundToInt (mm.getTimeStamp());
  22836. const int delta = jmax (0, tick - lastTick);
  22837. MidiFileHelpers::writeVariableLengthInt (out, delta);
  22838. lastTick = tick;
  22839. const char statusByte = *(mm.getRawData());
  22840. if ((statusByte == lastStatusByte)
  22841. && ((statusByte & 0xf0) != 0xf0)
  22842. && i > 0
  22843. && mm.getRawDataSize() > 1)
  22844. {
  22845. out.write (mm.getRawData() + 1, mm.getRawDataSize() - 1);
  22846. }
  22847. else
  22848. {
  22849. out.write (mm.getRawData(), mm.getRawDataSize());
  22850. }
  22851. lastStatusByte = statusByte;
  22852. }
  22853. out.writeByte (0);
  22854. const MidiMessage m (MidiMessage::endOfTrack());
  22855. out.write (m.getRawData(),
  22856. m.getRawDataSize());
  22857. mainOut.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MTrk"));
  22858. mainOut.writeIntBigEndian ((int) out.getDataSize());
  22859. mainOut.write (out.getData(), (int) out.getDataSize());
  22860. }
  22861. END_JUCE_NAMESPACE
  22862. /*** End of inlined file: juce_MidiFile.cpp ***/
  22863. /*** Start of inlined file: juce_MidiKeyboardState.cpp ***/
  22864. BEGIN_JUCE_NAMESPACE
  22865. MidiKeyboardState::MidiKeyboardState()
  22866. {
  22867. zerostruct (noteStates);
  22868. }
  22869. MidiKeyboardState::~MidiKeyboardState()
  22870. {
  22871. }
  22872. void MidiKeyboardState::reset()
  22873. {
  22874. const ScopedLock sl (lock);
  22875. zerostruct (noteStates);
  22876. eventsToAdd.clear();
  22877. }
  22878. bool MidiKeyboardState::isNoteOn (const int midiChannel, const int n) const throw()
  22879. {
  22880. jassert (midiChannel >= 0 && midiChannel <= 16);
  22881. return ((unsigned int) n) < 128
  22882. && (noteStates[n] & (1 << (midiChannel - 1))) != 0;
  22883. }
  22884. bool MidiKeyboardState::isNoteOnForChannels (const int midiChannelMask, const int n) const throw()
  22885. {
  22886. return ((unsigned int) n) < 128
  22887. && (noteStates[n] & midiChannelMask) != 0;
  22888. }
  22889. void MidiKeyboardState::noteOn (const int midiChannel, const int midiNoteNumber, const float velocity)
  22890. {
  22891. jassert (midiChannel >= 0 && midiChannel <= 16);
  22892. jassert (((unsigned int) midiNoteNumber) < 128);
  22893. const ScopedLock sl (lock);
  22894. if (((unsigned int) midiNoteNumber) < 128)
  22895. {
  22896. const int timeNow = (int) Time::getMillisecondCounter();
  22897. eventsToAdd.addEvent (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity), timeNow);
  22898. eventsToAdd.clear (0, timeNow - 500);
  22899. noteOnInternal (midiChannel, midiNoteNumber, velocity);
  22900. }
  22901. }
  22902. void MidiKeyboardState::noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity)
  22903. {
  22904. if (((unsigned int) midiNoteNumber) < 128)
  22905. {
  22906. noteStates [midiNoteNumber] |= (1 << (midiChannel - 1));
  22907. for (int i = listeners.size(); --i >= 0;)
  22908. listeners.getUnchecked(i)->handleNoteOn (this, midiChannel, midiNoteNumber, velocity);
  22909. }
  22910. }
  22911. void MidiKeyboardState::noteOff (const int midiChannel, const int midiNoteNumber)
  22912. {
  22913. const ScopedLock sl (lock);
  22914. if (isNoteOn (midiChannel, midiNoteNumber))
  22915. {
  22916. const int timeNow = (int) Time::getMillisecondCounter();
  22917. eventsToAdd.addEvent (MidiMessage::noteOff (midiChannel, midiNoteNumber), timeNow);
  22918. eventsToAdd.clear (0, timeNow - 500);
  22919. noteOffInternal (midiChannel, midiNoteNumber);
  22920. }
  22921. }
  22922. void MidiKeyboardState::noteOffInternal (const int midiChannel, const int midiNoteNumber)
  22923. {
  22924. if (isNoteOn (midiChannel, midiNoteNumber))
  22925. {
  22926. noteStates [midiNoteNumber] &= ~(1 << (midiChannel - 1));
  22927. for (int i = listeners.size(); --i >= 0;)
  22928. listeners.getUnchecked(i)->handleNoteOff (this, midiChannel, midiNoteNumber);
  22929. }
  22930. }
  22931. void MidiKeyboardState::allNotesOff (const int midiChannel)
  22932. {
  22933. const ScopedLock sl (lock);
  22934. if (midiChannel <= 0)
  22935. {
  22936. for (int i = 1; i <= 16; ++i)
  22937. allNotesOff (i);
  22938. }
  22939. else
  22940. {
  22941. for (int i = 0; i < 128; ++i)
  22942. noteOff (midiChannel, i);
  22943. }
  22944. }
  22945. void MidiKeyboardState::processNextMidiEvent (const MidiMessage& message)
  22946. {
  22947. if (message.isNoteOn())
  22948. {
  22949. noteOnInternal (message.getChannel(), message.getNoteNumber(), message.getFloatVelocity());
  22950. }
  22951. else if (message.isNoteOff())
  22952. {
  22953. noteOffInternal (message.getChannel(), message.getNoteNumber());
  22954. }
  22955. else if (message.isAllNotesOff())
  22956. {
  22957. for (int i = 0; i < 128; ++i)
  22958. noteOffInternal (message.getChannel(), i);
  22959. }
  22960. }
  22961. void MidiKeyboardState::processNextMidiBuffer (MidiBuffer& buffer,
  22962. const int startSample,
  22963. const int numSamples,
  22964. const bool injectIndirectEvents)
  22965. {
  22966. MidiBuffer::Iterator i (buffer);
  22967. MidiMessage message (0xf4, 0.0);
  22968. int time;
  22969. const ScopedLock sl (lock);
  22970. while (i.getNextEvent (message, time))
  22971. processNextMidiEvent (message);
  22972. if (injectIndirectEvents)
  22973. {
  22974. MidiBuffer::Iterator i2 (eventsToAdd);
  22975. const int firstEventToAdd = eventsToAdd.getFirstEventTime();
  22976. const double scaleFactor = numSamples / (double) (eventsToAdd.getLastEventTime() + 1 - firstEventToAdd);
  22977. while (i2.getNextEvent (message, time))
  22978. {
  22979. const int pos = jlimit (0, numSamples - 1, roundToInt ((time - firstEventToAdd) * scaleFactor));
  22980. buffer.addEvent (message, startSample + pos);
  22981. }
  22982. }
  22983. eventsToAdd.clear();
  22984. }
  22985. void MidiKeyboardState::addListener (MidiKeyboardStateListener* const listener)
  22986. {
  22987. const ScopedLock sl (lock);
  22988. listeners.addIfNotAlreadyThere (listener);
  22989. }
  22990. void MidiKeyboardState::removeListener (MidiKeyboardStateListener* const listener)
  22991. {
  22992. const ScopedLock sl (lock);
  22993. listeners.removeValue (listener);
  22994. }
  22995. END_JUCE_NAMESPACE
  22996. /*** End of inlined file: juce_MidiKeyboardState.cpp ***/
  22997. /*** Start of inlined file: juce_MidiMessage.cpp ***/
  22998. BEGIN_JUCE_NAMESPACE
  22999. int MidiMessage::readVariableLengthVal (const uint8* data, int& numBytesUsed) throw()
  23000. {
  23001. numBytesUsed = 0;
  23002. int v = 0;
  23003. int i;
  23004. do
  23005. {
  23006. i = (int) *data++;
  23007. if (++numBytesUsed > 6)
  23008. break;
  23009. v = (v << 7) + (i & 0x7f);
  23010. } while (i & 0x80);
  23011. return v;
  23012. }
  23013. int MidiMessage::getMessageLengthFromFirstByte (const uint8 firstByte) throw()
  23014. {
  23015. // this method only works for valid starting bytes of a short midi message
  23016. jassert (firstByte >= 0x80
  23017. && firstByte != 0xf0
  23018. && firstByte != 0xf7);
  23019. static const char messageLengths[] =
  23020. {
  23021. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  23022. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  23023. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  23024. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  23025. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  23026. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  23027. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  23028. 1, 2, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
  23029. };
  23030. return messageLengths [firstByte & 0x7f];
  23031. }
  23032. MidiMessage::MidiMessage (const void* const d, const int dataSize, const double t)
  23033. : timeStamp (t),
  23034. size (dataSize)
  23035. {
  23036. jassert (dataSize > 0);
  23037. if (dataSize <= 4)
  23038. data = static_cast<uint8*> (preallocatedData.asBytes);
  23039. else
  23040. data = new uint8 [dataSize];
  23041. memcpy (data, d, dataSize);
  23042. // check that the length matches the data..
  23043. jassert (size > 3 || data[0] >= 0xf0 || getMessageLengthFromFirstByte (data[0]) == size);
  23044. }
  23045. MidiMessage::MidiMessage (const int byte1, const double t) throw()
  23046. : timeStamp (t),
  23047. data (static_cast<uint8*> (preallocatedData.asBytes)),
  23048. size (1)
  23049. {
  23050. data[0] = (uint8) byte1;
  23051. // check that the length matches the data..
  23052. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 1);
  23053. }
  23054. MidiMessage::MidiMessage (const int byte1, const int byte2, const double t) throw()
  23055. : timeStamp (t),
  23056. data (static_cast<uint8*> (preallocatedData.asBytes)),
  23057. size (2)
  23058. {
  23059. data[0] = (uint8) byte1;
  23060. data[1] = (uint8) byte2;
  23061. // check that the length matches the data..
  23062. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 2);
  23063. }
  23064. MidiMessage::MidiMessage (const int byte1, const int byte2, const int byte3, const double t) throw()
  23065. : timeStamp (t),
  23066. data (static_cast<uint8*> (preallocatedData.asBytes)),
  23067. size (3)
  23068. {
  23069. data[0] = (uint8) byte1;
  23070. data[1] = (uint8) byte2;
  23071. data[2] = (uint8) byte3;
  23072. // check that the length matches the data..
  23073. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 3);
  23074. }
  23075. MidiMessage::MidiMessage (const MidiMessage& other)
  23076. : timeStamp (other.timeStamp),
  23077. size (other.size)
  23078. {
  23079. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  23080. {
  23081. data = new uint8 [size];
  23082. memcpy (data, other.data, size);
  23083. }
  23084. else
  23085. {
  23086. data = static_cast<uint8*> (preallocatedData.asBytes);
  23087. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  23088. }
  23089. }
  23090. MidiMessage::MidiMessage (const MidiMessage& other, const double newTimeStamp)
  23091. : timeStamp (newTimeStamp),
  23092. size (other.size)
  23093. {
  23094. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  23095. {
  23096. data = new uint8 [size];
  23097. memcpy (data, other.data, size);
  23098. }
  23099. else
  23100. {
  23101. data = static_cast<uint8*> (preallocatedData.asBytes);
  23102. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  23103. }
  23104. }
  23105. MidiMessage::MidiMessage (const void* src_, int sz, int& numBytesUsed, const uint8 lastStatusByte, double t)
  23106. : timeStamp (t),
  23107. data (static_cast<uint8*> (preallocatedData.asBytes))
  23108. {
  23109. const uint8* src = static_cast <const uint8*> (src_);
  23110. unsigned int byte = (unsigned int) *src;
  23111. if (byte < 0x80)
  23112. {
  23113. byte = (unsigned int) (uint8) lastStatusByte;
  23114. numBytesUsed = -1;
  23115. }
  23116. else
  23117. {
  23118. numBytesUsed = 0;
  23119. --sz;
  23120. ++src;
  23121. }
  23122. if (byte >= 0x80)
  23123. {
  23124. if (byte == 0xf0)
  23125. {
  23126. const uint8* d = src;
  23127. while (d < src + sz)
  23128. {
  23129. if (*d >= 0x80) // stop if we hit a status byte, and don't include it in this message
  23130. {
  23131. if (*d == 0xf7) // include an 0xf7 if we hit one
  23132. ++d;
  23133. break;
  23134. }
  23135. ++d;
  23136. }
  23137. size = 1 + (int) (d - src);
  23138. data = new uint8 [size];
  23139. *data = (uint8) byte;
  23140. memcpy (data + 1, src, size - 1);
  23141. }
  23142. else if (byte == 0xff)
  23143. {
  23144. int n;
  23145. const int bytesLeft = readVariableLengthVal (src + 1, n);
  23146. size = jmin (sz + 1, n + 2 + bytesLeft);
  23147. data = new uint8 [size];
  23148. *data = (uint8) byte;
  23149. memcpy (data + 1, src, size - 1);
  23150. }
  23151. else
  23152. {
  23153. preallocatedData.asInt32 = 0;
  23154. size = getMessageLengthFromFirstByte ((uint8) byte);
  23155. data[0] = (uint8) byte;
  23156. if (size > 1)
  23157. {
  23158. data[1] = src[0];
  23159. if (size > 2)
  23160. data[2] = src[1];
  23161. }
  23162. }
  23163. numBytesUsed += size;
  23164. }
  23165. else
  23166. {
  23167. preallocatedData.asInt32 = 0;
  23168. size = 0;
  23169. }
  23170. }
  23171. MidiMessage& MidiMessage::operator= (const MidiMessage& other)
  23172. {
  23173. if (this != &other)
  23174. {
  23175. timeStamp = other.timeStamp;
  23176. size = other.size;
  23177. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  23178. delete[] data;
  23179. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  23180. {
  23181. data = new uint8 [size];
  23182. memcpy (data, other.data, size);
  23183. }
  23184. else
  23185. {
  23186. data = static_cast<uint8*> (preallocatedData.asBytes);
  23187. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  23188. }
  23189. }
  23190. return *this;
  23191. }
  23192. MidiMessage::~MidiMessage()
  23193. {
  23194. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  23195. delete[] data;
  23196. }
  23197. int MidiMessage::getChannel() const throw()
  23198. {
  23199. if ((data[0] & 0xf0) != 0xf0)
  23200. return (data[0] & 0xf) + 1;
  23201. else
  23202. return 0;
  23203. }
  23204. bool MidiMessage::isForChannel (const int channel) const throw()
  23205. {
  23206. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23207. return ((data[0] & 0xf) == channel - 1)
  23208. && ((data[0] & 0xf0) != 0xf0);
  23209. }
  23210. void MidiMessage::setChannel (const int channel) throw()
  23211. {
  23212. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23213. if ((data[0] & 0xf0) != (uint8) 0xf0)
  23214. data[0] = (uint8) ((data[0] & (uint8)0xf0)
  23215. | (uint8)(channel - 1));
  23216. }
  23217. bool MidiMessage::isNoteOn (const bool returnTrueForVelocity0) const throw()
  23218. {
  23219. return ((data[0] & 0xf0) == 0x90)
  23220. && (returnTrueForVelocity0 || data[2] != 0);
  23221. }
  23222. bool MidiMessage::isNoteOff (const bool returnTrueForNoteOnVelocity0) const throw()
  23223. {
  23224. return ((data[0] & 0xf0) == 0x80)
  23225. || (returnTrueForNoteOnVelocity0 && (data[2] == 0) && ((data[0] & 0xf0) == 0x90));
  23226. }
  23227. bool MidiMessage::isNoteOnOrOff() const throw()
  23228. {
  23229. const int d = data[0] & 0xf0;
  23230. return (d == 0x90) || (d == 0x80);
  23231. }
  23232. int MidiMessage::getNoteNumber() const throw()
  23233. {
  23234. return data[1];
  23235. }
  23236. void MidiMessage::setNoteNumber (const int newNoteNumber) throw()
  23237. {
  23238. if (isNoteOnOrOff())
  23239. data[1] = (uint8) jlimit (0, 127, newNoteNumber);
  23240. }
  23241. uint8 MidiMessage::getVelocity() const throw()
  23242. {
  23243. if (isNoteOnOrOff())
  23244. return data[2];
  23245. else
  23246. return 0;
  23247. }
  23248. float MidiMessage::getFloatVelocity() const throw()
  23249. {
  23250. return getVelocity() * (1.0f / 127.0f);
  23251. }
  23252. void MidiMessage::setVelocity (const float newVelocity) throw()
  23253. {
  23254. if (isNoteOnOrOff())
  23255. data[2] = (uint8) jlimit (0, 0x7f, roundToInt (newVelocity * 127.0f));
  23256. }
  23257. void MidiMessage::multiplyVelocity (const float scaleFactor) throw()
  23258. {
  23259. if (isNoteOnOrOff())
  23260. data[2] = (uint8) jlimit (0, 0x7f, roundToInt (scaleFactor * data[2]));
  23261. }
  23262. bool MidiMessage::isAftertouch() const throw()
  23263. {
  23264. return (data[0] & 0xf0) == 0xa0;
  23265. }
  23266. int MidiMessage::getAfterTouchValue() const throw()
  23267. {
  23268. return data[2];
  23269. }
  23270. const MidiMessage MidiMessage::aftertouchChange (const int channel,
  23271. const int noteNum,
  23272. const int aftertouchValue) throw()
  23273. {
  23274. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23275. jassert (((unsigned int) noteNum) <= 127);
  23276. jassert (((unsigned int) aftertouchValue) <= 127);
  23277. return MidiMessage (0xa0 | jlimit (0, 15, channel - 1),
  23278. noteNum & 0x7f,
  23279. aftertouchValue & 0x7f);
  23280. }
  23281. bool MidiMessage::isChannelPressure() const throw()
  23282. {
  23283. return (data[0] & 0xf0) == 0xd0;
  23284. }
  23285. int MidiMessage::getChannelPressureValue() const throw()
  23286. {
  23287. jassert (isChannelPressure());
  23288. return data[1];
  23289. }
  23290. const MidiMessage MidiMessage::channelPressureChange (const int channel,
  23291. const int pressure) throw()
  23292. {
  23293. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23294. jassert (((unsigned int) pressure) <= 127);
  23295. return MidiMessage (0xd0 | jlimit (0, 15, channel - 1),
  23296. pressure & 0x7f);
  23297. }
  23298. bool MidiMessage::isProgramChange() const throw()
  23299. {
  23300. return (data[0] & 0xf0) == 0xc0;
  23301. }
  23302. int MidiMessage::getProgramChangeNumber() const throw()
  23303. {
  23304. return data[1];
  23305. }
  23306. const MidiMessage MidiMessage::programChange (const int channel,
  23307. const int programNumber) throw()
  23308. {
  23309. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23310. return MidiMessage (0xc0 | jlimit (0, 15, channel - 1),
  23311. programNumber & 0x7f);
  23312. }
  23313. bool MidiMessage::isPitchWheel() const throw()
  23314. {
  23315. return (data[0] & 0xf0) == 0xe0;
  23316. }
  23317. int MidiMessage::getPitchWheelValue() const throw()
  23318. {
  23319. return data[1] | (data[2] << 7);
  23320. }
  23321. const MidiMessage MidiMessage::pitchWheel (const int channel,
  23322. const int position) throw()
  23323. {
  23324. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23325. jassert (((unsigned int) position) <= 0x3fff);
  23326. return MidiMessage (0xe0 | jlimit (0, 15, channel - 1),
  23327. position & 127,
  23328. (position >> 7) & 127);
  23329. }
  23330. bool MidiMessage::isController() const throw()
  23331. {
  23332. return (data[0] & 0xf0) == 0xb0;
  23333. }
  23334. int MidiMessage::getControllerNumber() const throw()
  23335. {
  23336. jassert (isController());
  23337. return data[1];
  23338. }
  23339. int MidiMessage::getControllerValue() const throw()
  23340. {
  23341. jassert (isController());
  23342. return data[2];
  23343. }
  23344. const MidiMessage MidiMessage::controllerEvent (const int channel,
  23345. const int controllerType,
  23346. const int value) throw()
  23347. {
  23348. // the channel must be between 1 and 16 inclusive
  23349. jassert (channel > 0 && channel <= 16);
  23350. return MidiMessage (0xb0 | jlimit (0, 15, channel - 1),
  23351. controllerType & 127,
  23352. value & 127);
  23353. }
  23354. const MidiMessage MidiMessage::noteOn (const int channel,
  23355. const int noteNumber,
  23356. const float velocity) throw()
  23357. {
  23358. return noteOn (channel, noteNumber, (uint8)(velocity * 127.0f));
  23359. }
  23360. const MidiMessage MidiMessage::noteOn (const int channel,
  23361. const int noteNumber,
  23362. const uint8 velocity) throw()
  23363. {
  23364. jassert (channel > 0 && channel <= 16);
  23365. jassert (((unsigned int) noteNumber) <= 127);
  23366. return MidiMessage (0x90 | jlimit (0, 15, channel - 1),
  23367. noteNumber & 127,
  23368. jlimit (0, 127, roundToInt (velocity)));
  23369. }
  23370. const MidiMessage MidiMessage::noteOff (const int channel,
  23371. const int noteNumber) throw()
  23372. {
  23373. jassert (channel > 0 && channel <= 16);
  23374. jassert (((unsigned int) noteNumber) <= 127);
  23375. return MidiMessage (0x80 | jlimit (0, 15, channel - 1), noteNumber & 127, 0);
  23376. }
  23377. const MidiMessage MidiMessage::allNotesOff (const int channel) throw()
  23378. {
  23379. return controllerEvent (channel, 123, 0);
  23380. }
  23381. bool MidiMessage::isAllNotesOff() const throw()
  23382. {
  23383. return (data[0] & 0xf0) == 0xb0
  23384. && data[1] == 123;
  23385. }
  23386. const MidiMessage MidiMessage::allSoundOff (const int channel) throw()
  23387. {
  23388. return controllerEvent (channel, 120, 0);
  23389. }
  23390. bool MidiMessage::isAllSoundOff() const throw()
  23391. {
  23392. return (data[0] & 0xf0) == 0xb0
  23393. && data[1] == 120;
  23394. }
  23395. const MidiMessage MidiMessage::allControllersOff (const int channel) throw()
  23396. {
  23397. return controllerEvent (channel, 121, 0);
  23398. }
  23399. const MidiMessage MidiMessage::masterVolume (const float volume)
  23400. {
  23401. const int vol = jlimit (0, 0x3fff, roundToInt (volume * 0x4000));
  23402. uint8 buf[8];
  23403. buf[0] = 0xf0;
  23404. buf[1] = 0x7f;
  23405. buf[2] = 0x7f;
  23406. buf[3] = 0x04;
  23407. buf[4] = 0x01;
  23408. buf[5] = (uint8) (vol & 0x7f);
  23409. buf[6] = (uint8) (vol >> 7);
  23410. buf[7] = 0xf7;
  23411. return MidiMessage (buf, 8);
  23412. }
  23413. bool MidiMessage::isSysEx() const throw()
  23414. {
  23415. return *data == 0xf0;
  23416. }
  23417. const MidiMessage MidiMessage::createSysExMessage (const uint8* sysexData, const int dataSize)
  23418. {
  23419. MemoryBlock mm (dataSize + 2);
  23420. uint8* const m = static_cast <uint8*> (mm.getData());
  23421. m[0] = 0xf0;
  23422. memcpy (m + 1, sysexData, dataSize);
  23423. m[dataSize + 1] = 0xf7;
  23424. return MidiMessage (m, dataSize + 2);
  23425. }
  23426. const uint8* MidiMessage::getSysExData() const throw()
  23427. {
  23428. return (isSysEx()) ? getRawData() + 1 : 0;
  23429. }
  23430. int MidiMessage::getSysExDataSize() const throw()
  23431. {
  23432. return (isSysEx()) ? size - 2 : 0;
  23433. }
  23434. bool MidiMessage::isMetaEvent() const throw()
  23435. {
  23436. return *data == 0xff;
  23437. }
  23438. bool MidiMessage::isActiveSense() const throw()
  23439. {
  23440. return *data == 0xfe;
  23441. }
  23442. int MidiMessage::getMetaEventType() const throw()
  23443. {
  23444. if (*data != 0xff)
  23445. return -1;
  23446. else
  23447. return data[1];
  23448. }
  23449. int MidiMessage::getMetaEventLength() const throw()
  23450. {
  23451. if (*data == 0xff)
  23452. {
  23453. int n;
  23454. return jmin (size - 2, readVariableLengthVal (data + 2, n));
  23455. }
  23456. return 0;
  23457. }
  23458. const uint8* MidiMessage::getMetaEventData() const throw()
  23459. {
  23460. int n;
  23461. const uint8* d = data + 2;
  23462. readVariableLengthVal (d, n);
  23463. return d + n;
  23464. }
  23465. bool MidiMessage::isTrackMetaEvent() const throw()
  23466. {
  23467. return getMetaEventType() == 0;
  23468. }
  23469. bool MidiMessage::isEndOfTrackMetaEvent() const throw()
  23470. {
  23471. return getMetaEventType() == 47;
  23472. }
  23473. bool MidiMessage::isTextMetaEvent() const throw()
  23474. {
  23475. const int t = getMetaEventType();
  23476. return t > 0 && t < 16;
  23477. }
  23478. const String MidiMessage::getTextFromTextMetaEvent() const
  23479. {
  23480. return String (reinterpret_cast <const char*> (getMetaEventData()), getMetaEventLength());
  23481. }
  23482. bool MidiMessage::isTrackNameEvent() const throw()
  23483. {
  23484. return (data[1] == 3)
  23485. && (*data == 0xff);
  23486. }
  23487. bool MidiMessage::isTempoMetaEvent() const throw()
  23488. {
  23489. return (data[1] == 81)
  23490. && (*data == 0xff);
  23491. }
  23492. bool MidiMessage::isMidiChannelMetaEvent() const throw()
  23493. {
  23494. return (data[1] == 0x20)
  23495. && (*data == 0xff)
  23496. && (data[2] == 1);
  23497. }
  23498. int MidiMessage::getMidiChannelMetaEventChannel() const throw()
  23499. {
  23500. return data[3] + 1;
  23501. }
  23502. double MidiMessage::getTempoSecondsPerQuarterNote() const throw()
  23503. {
  23504. if (! isTempoMetaEvent())
  23505. return 0.0;
  23506. const uint8* const d = getMetaEventData();
  23507. return (((unsigned int) d[0] << 16)
  23508. | ((unsigned int) d[1] << 8)
  23509. | d[2])
  23510. / 1000000.0;
  23511. }
  23512. double MidiMessage::getTempoMetaEventTickLength (const short timeFormat) const throw()
  23513. {
  23514. if (timeFormat > 0)
  23515. {
  23516. if (! isTempoMetaEvent())
  23517. return 0.5 / timeFormat;
  23518. return getTempoSecondsPerQuarterNote() / timeFormat;
  23519. }
  23520. else
  23521. {
  23522. const int frameCode = (-timeFormat) >> 8;
  23523. double framesPerSecond;
  23524. switch (frameCode)
  23525. {
  23526. case 24: framesPerSecond = 24.0; break;
  23527. case 25: framesPerSecond = 25.0; break;
  23528. case 29: framesPerSecond = 29.97; break;
  23529. case 30: framesPerSecond = 30.0; break;
  23530. default: framesPerSecond = 30.0; break;
  23531. }
  23532. return (1.0 / framesPerSecond) / (timeFormat & 0xff);
  23533. }
  23534. }
  23535. const MidiMessage MidiMessage::tempoMetaEvent (int microsecondsPerQuarterNote) throw()
  23536. {
  23537. uint8 d[8];
  23538. d[0] = 0xff;
  23539. d[1] = 81;
  23540. d[2] = 3;
  23541. d[3] = (uint8) (microsecondsPerQuarterNote >> 16);
  23542. d[4] = (uint8) ((microsecondsPerQuarterNote >> 8) & 0xff);
  23543. d[5] = (uint8) (microsecondsPerQuarterNote & 0xff);
  23544. return MidiMessage (d, 6, 0.0);
  23545. }
  23546. bool MidiMessage::isTimeSignatureMetaEvent() const throw()
  23547. {
  23548. return (data[1] == 0x58)
  23549. && (*data == (uint8) 0xff);
  23550. }
  23551. void MidiMessage::getTimeSignatureInfo (int& numerator, int& denominator) const throw()
  23552. {
  23553. if (isTimeSignatureMetaEvent())
  23554. {
  23555. const uint8* const d = getMetaEventData();
  23556. numerator = d[0];
  23557. denominator = 1 << d[1];
  23558. }
  23559. else
  23560. {
  23561. numerator = 4;
  23562. denominator = 4;
  23563. }
  23564. }
  23565. const MidiMessage MidiMessage::timeSignatureMetaEvent (const int numerator, const int denominator)
  23566. {
  23567. uint8 d[8];
  23568. d[0] = 0xff;
  23569. d[1] = 0x58;
  23570. d[2] = 0x04;
  23571. d[3] = (uint8) numerator;
  23572. int n = 1;
  23573. int powerOfTwo = 0;
  23574. while (n < denominator)
  23575. {
  23576. n <<= 1;
  23577. ++powerOfTwo;
  23578. }
  23579. d[4] = (uint8) powerOfTwo;
  23580. d[5] = 0x01;
  23581. d[6] = 96;
  23582. return MidiMessage (d, 7, 0.0);
  23583. }
  23584. const MidiMessage MidiMessage::midiChannelMetaEvent (const int channel) throw()
  23585. {
  23586. uint8 d[8];
  23587. d[0] = 0xff;
  23588. d[1] = 0x20;
  23589. d[2] = 0x01;
  23590. d[3] = (uint8) jlimit (0, 0xff, channel - 1);
  23591. return MidiMessage (d, 4, 0.0);
  23592. }
  23593. bool MidiMessage::isKeySignatureMetaEvent() const throw()
  23594. {
  23595. return getMetaEventType() == 89;
  23596. }
  23597. int MidiMessage::getKeySignatureNumberOfSharpsOrFlats() const throw()
  23598. {
  23599. return (int) *getMetaEventData();
  23600. }
  23601. const MidiMessage MidiMessage::endOfTrack() throw()
  23602. {
  23603. return MidiMessage (0xff, 0x2f, 0, 0.0);
  23604. }
  23605. bool MidiMessage::isSongPositionPointer() const throw()
  23606. {
  23607. return *data == 0xf2;
  23608. }
  23609. int MidiMessage::getSongPositionPointerMidiBeat() const throw()
  23610. {
  23611. return data[1] | (data[2] << 7);
  23612. }
  23613. const MidiMessage MidiMessage::songPositionPointer (const int positionInMidiBeats) throw()
  23614. {
  23615. return MidiMessage (0xf2,
  23616. positionInMidiBeats & 127,
  23617. (positionInMidiBeats >> 7) & 127);
  23618. }
  23619. bool MidiMessage::isMidiStart() const throw()
  23620. {
  23621. return *data == 0xfa;
  23622. }
  23623. const MidiMessage MidiMessage::midiStart() throw()
  23624. {
  23625. return MidiMessage (0xfa);
  23626. }
  23627. bool MidiMessage::isMidiContinue() const throw()
  23628. {
  23629. return *data == 0xfb;
  23630. }
  23631. const MidiMessage MidiMessage::midiContinue() throw()
  23632. {
  23633. return MidiMessage (0xfb);
  23634. }
  23635. bool MidiMessage::isMidiStop() const throw()
  23636. {
  23637. return *data == 0xfc;
  23638. }
  23639. const MidiMessage MidiMessage::midiStop() throw()
  23640. {
  23641. return MidiMessage (0xfc);
  23642. }
  23643. bool MidiMessage::isMidiClock() const throw()
  23644. {
  23645. return *data == 0xf8;
  23646. }
  23647. const MidiMessage MidiMessage::midiClock() throw()
  23648. {
  23649. return MidiMessage (0xf8);
  23650. }
  23651. bool MidiMessage::isQuarterFrame() const throw()
  23652. {
  23653. return *data == 0xf1;
  23654. }
  23655. int MidiMessage::getQuarterFrameSequenceNumber() const throw()
  23656. {
  23657. return ((int) data[1]) >> 4;
  23658. }
  23659. int MidiMessage::getQuarterFrameValue() const throw()
  23660. {
  23661. return ((int) data[1]) & 0x0f;
  23662. }
  23663. const MidiMessage MidiMessage::quarterFrame (const int sequenceNumber,
  23664. const int value) throw()
  23665. {
  23666. return MidiMessage (0xf1, (sequenceNumber << 4) | value);
  23667. }
  23668. bool MidiMessage::isFullFrame() const throw()
  23669. {
  23670. return data[0] == 0xf0
  23671. && data[1] == 0x7f
  23672. && size >= 10
  23673. && data[3] == 0x01
  23674. && data[4] == 0x01;
  23675. }
  23676. void MidiMessage::getFullFrameParameters (int& hours,
  23677. int& minutes,
  23678. int& seconds,
  23679. int& frames,
  23680. MidiMessage::SmpteTimecodeType& timecodeType) const throw()
  23681. {
  23682. jassert (isFullFrame());
  23683. timecodeType = (SmpteTimecodeType) (data[5] >> 5);
  23684. hours = data[5] & 0x1f;
  23685. minutes = data[6];
  23686. seconds = data[7];
  23687. frames = data[8];
  23688. }
  23689. const MidiMessage MidiMessage::fullFrame (const int hours,
  23690. const int minutes,
  23691. const int seconds,
  23692. const int frames,
  23693. MidiMessage::SmpteTimecodeType timecodeType)
  23694. {
  23695. uint8 d[10];
  23696. d[0] = 0xf0;
  23697. d[1] = 0x7f;
  23698. d[2] = 0x7f;
  23699. d[3] = 0x01;
  23700. d[4] = 0x01;
  23701. d[5] = (uint8) ((hours & 0x01f) | (timecodeType << 5));
  23702. d[6] = (uint8) minutes;
  23703. d[7] = (uint8) seconds;
  23704. d[8] = (uint8) frames;
  23705. d[9] = 0xf7;
  23706. return MidiMessage (d, 10, 0.0);
  23707. }
  23708. bool MidiMessage::isMidiMachineControlMessage() const throw()
  23709. {
  23710. return data[0] == 0xf0
  23711. && data[1] == 0x7f
  23712. && data[3] == 0x06
  23713. && size > 5;
  23714. }
  23715. MidiMessage::MidiMachineControlCommand MidiMessage::getMidiMachineControlCommand() const throw()
  23716. {
  23717. jassert (isMidiMachineControlMessage());
  23718. return (MidiMachineControlCommand) data[4];
  23719. }
  23720. const MidiMessage MidiMessage::midiMachineControlCommand (MidiMessage::MidiMachineControlCommand command)
  23721. {
  23722. uint8 d[6];
  23723. d[0] = 0xf0;
  23724. d[1] = 0x7f;
  23725. d[2] = 0x00;
  23726. d[3] = 0x06;
  23727. d[4] = (uint8) command;
  23728. d[5] = 0xf7;
  23729. return MidiMessage (d, 6, 0.0);
  23730. }
  23731. bool MidiMessage::isMidiMachineControlGoto (int& hours,
  23732. int& minutes,
  23733. int& seconds,
  23734. int& frames) const throw()
  23735. {
  23736. if (size >= 12
  23737. && data[0] == 0xf0
  23738. && data[1] == 0x7f
  23739. && data[3] == 0x06
  23740. && data[4] == 0x44
  23741. && data[5] == 0x06
  23742. && data[6] == 0x01)
  23743. {
  23744. hours = data[7] % 24; // (that some machines send out hours > 24)
  23745. minutes = data[8];
  23746. seconds = data[9];
  23747. frames = data[10];
  23748. return true;
  23749. }
  23750. return false;
  23751. }
  23752. const MidiMessage MidiMessage::midiMachineControlGoto (int hours,
  23753. int minutes,
  23754. int seconds,
  23755. int frames)
  23756. {
  23757. uint8 d[12];
  23758. d[0] = 0xf0;
  23759. d[1] = 0x7f;
  23760. d[2] = 0x00;
  23761. d[3] = 0x06;
  23762. d[4] = 0x44;
  23763. d[5] = 0x06;
  23764. d[6] = 0x01;
  23765. d[7] = (uint8) hours;
  23766. d[8] = (uint8) minutes;
  23767. d[9] = (uint8) seconds;
  23768. d[10] = (uint8) frames;
  23769. d[11] = 0xf7;
  23770. return MidiMessage (d, 12, 0.0);
  23771. }
  23772. const String MidiMessage::getMidiNoteName (int note, bool useSharps, bool includeOctaveNumber, int octaveNumForMiddleC)
  23773. {
  23774. static const char* const sharpNoteNames[] = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };
  23775. static const char* const flatNoteNames[] = { "C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab", "A", "Bb", "B" };
  23776. if (((unsigned int) note) < 128)
  23777. {
  23778. String s (useSharps ? sharpNoteNames [note % 12]
  23779. : flatNoteNames [note % 12]);
  23780. if (includeOctaveNumber)
  23781. s << (note / 12 + (octaveNumForMiddleC - 5));
  23782. return s;
  23783. }
  23784. return String::empty;
  23785. }
  23786. const double MidiMessage::getMidiNoteInHertz (int noteNumber, const double frequencyOfA) throw()
  23787. {
  23788. noteNumber -= 12 * 6 + 9; // now 0 = A
  23789. return frequencyOfA * pow (2.0, noteNumber / 12.0);
  23790. }
  23791. const String MidiMessage::getGMInstrumentName (const int n)
  23792. {
  23793. const char* names[] =
  23794. {
  23795. "Acoustic Grand Piano", "Bright Acoustic Piano", "Electric Grand Piano", "Honky-tonk Piano",
  23796. "Electric Piano 1", "Electric Piano 2", "Harpsichord", "Clavinet", "Celesta", "Glockenspiel",
  23797. "Music Box", "Vibraphone", "Marimba", "Xylophone", "Tubular Bells", "Dulcimer", "Drawbar Organ",
  23798. "Percussive Organ", "Rock Organ", "Church Organ", "Reed Organ", "Accordion", "Harmonica",
  23799. "Tango Accordion", "Acoustic Guitar (nylon)", "Acoustic Guitar (steel)", "Electric Guitar (jazz)",
  23800. "Electric Guitar (clean)", "Electric Guitar (mute)", "Overdriven Guitar", "Distortion Guitar",
  23801. "Guitar Harmonics", "Acoustic Bass", "Electric Bass (finger)", "Electric Bass (pick)",
  23802. "Fretless Bass", "Slap Bass 1", "Slap Bass 2", "Synth Bass 1", "Synth Bass 2", "Violin",
  23803. "Viola", "Cello", "Contrabass", "Tremolo Strings", "Pizzicato Strings", "Orchestral Harp",
  23804. "Timpani", "String Ensemble 1", "String Ensemble 2", "SynthStrings 1", "SynthStrings 2",
  23805. "Choir Aahs", "Voice Oohs", "Synth Voice", "Orchestra Hit", "Trumpet", "Trombone", "Tuba",
  23806. "Muted Trumpet", "French Horn", "Brass Section", "SynthBrass 1", "SynthBrass 2", "Soprano Sax",
  23807. "Alto Sax", "Tenor Sax", "Baritone Sax", "Oboe", "English Horn", "Bassoon", "Clarinet",
  23808. "Piccolo", "Flute", "Recorder", "Pan Flute", "Blown Bottle", "Shakuhachi", "Whistle",
  23809. "Ocarina", "Lead 1 (square)", "Lead 2 (sawtooth)", "Lead 3 (calliope)", "Lead 4 (chiff)",
  23810. "Lead 5 (charang)", "Lead 6 (voice)", "Lead 7 (fifths)", "Lead 8 (bass+lead)", "Pad 1 (new age)",
  23811. "Pad 2 (warm)", "Pad 3 (polysynth)", "Pad 4 (choir)", "Pad 5 (bowed)", "Pad 6 (metallic)",
  23812. "Pad 7 (halo)", "Pad 8 (sweep)", "FX 1 (rain)", "FX 2 (soundtrack)", "FX 3 (crystal)",
  23813. "FX 4 (atmosphere)", "FX 5 (brightness)", "FX 6 (goblins)", "FX 7 (echoes)", "FX 8 (sci-fi)",
  23814. "Sitar", "Banjo", "Shamisen", "Koto", "Kalimba", "Bag pipe", "Fiddle", "Shanai", "Tinkle Bell",
  23815. "Agogo", "Steel Drums", "Woodblock", "Taiko Drum", "Melodic Tom", "Synth Drum", "Reverse Cymbal",
  23816. "Guitar Fret Noise", "Breath Noise", "Seashore", "Bird Tweet", "Telephone Ring", "Helicopter",
  23817. "Applause", "Gunshot"
  23818. };
  23819. return (((unsigned int) n) < 128) ? names[n] : (const char*) 0;
  23820. }
  23821. const String MidiMessage::getGMInstrumentBankName (const int n)
  23822. {
  23823. const char* names[] =
  23824. {
  23825. "Piano", "Chromatic Percussion", "Organ", "Guitar",
  23826. "Bass", "Strings", "Ensemble", "Brass",
  23827. "Reed", "Pipe", "Synth Lead", "Synth Pad",
  23828. "Synth Effects", "Ethnic", "Percussive", "Sound Effects"
  23829. };
  23830. return (((unsigned int) n) <= 15) ? names[n] : (const char*) 0;
  23831. }
  23832. const String MidiMessage::getRhythmInstrumentName (const int n)
  23833. {
  23834. const char* names[] =
  23835. {
  23836. "Acoustic Bass Drum", "Bass Drum 1", "Side Stick", "Acoustic Snare",
  23837. "Hand Clap", "Electric Snare", "Low Floor Tom", "Closed Hi-Hat", "High Floor Tom",
  23838. "Pedal Hi-Hat", "Low Tom", "Open Hi-Hat", "Low-Mid Tom", "Hi-Mid Tom", "Crash Cymbal 1",
  23839. "High Tom", "Ride Cymbal 1", "Chinese Cymbal", "Ride Bell", "Tambourine", "Splash Cymbal",
  23840. "Cowbell", "Crash Cymbal 2", "Vibraslap", "Ride Cymbal 2", "Hi Bongo", "Low Bongo",
  23841. "Mute Hi Conga", "Open Hi Conga", "Low Conga", "High Timbale", "Low Timbale", "High Agogo",
  23842. "Low Agogo", "Cabasa", "Maracas", "Short Whistle", "Long Whistle", "Short Guiro",
  23843. "Long Guiro", "Claves", "Hi Wood Block", "Low Wood Block", "Mute Cuica", "Open Cuica",
  23844. "Mute Triangle", "Open Triangle"
  23845. };
  23846. return (n >= 35 && n <= 81) ? names [n - 35] : (const char*) 0;
  23847. }
  23848. const String MidiMessage::getControllerName (const int n)
  23849. {
  23850. const char* names[] =
  23851. {
  23852. "Bank Select", "Modulation Wheel (coarse)", "Breath controller (coarse)",
  23853. 0, "Foot Pedal (coarse)", "Portamento Time (coarse)",
  23854. "Data Entry (coarse)", "Volume (coarse)", "Balance (coarse)",
  23855. 0, "Pan position (coarse)", "Expression (coarse)", "Effect Control 1 (coarse)",
  23856. "Effect Control 2 (coarse)", 0, 0, "General Purpose Slider 1", "General Purpose Slider 2",
  23857. "General Purpose Slider 3", "General Purpose Slider 4", 0, 0, 0, 0, 0, 0, 0, 0,
  23858. 0, 0, 0, 0, "Bank Select (fine)", "Modulation Wheel (fine)", "Breath controller (fine)",
  23859. 0, "Foot Pedal (fine)", "Portamento Time (fine)", "Data Entry (fine)", "Volume (fine)",
  23860. "Balance (fine)", 0, "Pan position (fine)", "Expression (fine)", "Effect Control 1 (fine)",
  23861. "Effect Control 2 (fine)", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  23862. "Hold Pedal (on/off)", "Portamento (on/off)", "Sustenuto Pedal (on/off)", "Soft Pedal (on/off)",
  23863. "Legato Pedal (on/off)", "Hold 2 Pedal (on/off)", "Sound Variation", "Sound Timbre",
  23864. "Sound Release Time", "Sound Attack Time", "Sound Brightness", "Sound Control 6",
  23865. "Sound Control 7", "Sound Control 8", "Sound Control 9", "Sound Control 10",
  23866. "General Purpose Button 1 (on/off)", "General Purpose Button 2 (on/off)",
  23867. "General Purpose Button 3 (on/off)", "General Purpose Button 4 (on/off)",
  23868. 0, 0, 0, 0, 0, 0, 0, "Reverb Level", "Tremolo Level", "Chorus Level", "Celeste Level",
  23869. "Phaser Level", "Data Button increment", "Data Button decrement", "Non-registered Parameter (fine)",
  23870. "Non-registered Parameter (coarse)", "Registered Parameter (fine)", "Registered Parameter (coarse)",
  23871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "All Sound Off", "All Controllers Off",
  23872. "Local Keyboard (on/off)", "All Notes Off", "Omni Mode Off", "Omni Mode On", "Mono Operation",
  23873. "Poly Operation"
  23874. };
  23875. return (((unsigned int) n) < 128) ? names[n] : (const char*) 0;
  23876. }
  23877. END_JUCE_NAMESPACE
  23878. /*** End of inlined file: juce_MidiMessage.cpp ***/
  23879. /*** Start of inlined file: juce_MidiMessageCollector.cpp ***/
  23880. BEGIN_JUCE_NAMESPACE
  23881. MidiMessageCollector::MidiMessageCollector()
  23882. : lastCallbackTime (0),
  23883. sampleRate (44100.0001)
  23884. {
  23885. }
  23886. MidiMessageCollector::~MidiMessageCollector()
  23887. {
  23888. }
  23889. void MidiMessageCollector::reset (const double sampleRate_)
  23890. {
  23891. jassert (sampleRate_ > 0);
  23892. const ScopedLock sl (midiCallbackLock);
  23893. sampleRate = sampleRate_;
  23894. incomingMessages.clear();
  23895. lastCallbackTime = Time::getMillisecondCounterHiRes();
  23896. }
  23897. void MidiMessageCollector::addMessageToQueue (const MidiMessage& message)
  23898. {
  23899. // you need to call reset() to set the correct sample rate before using this object
  23900. jassert (sampleRate != 44100.0001);
  23901. // the messages that come in here need to be time-stamped correctly - see MidiInput
  23902. // for details of what the number should be.
  23903. jassert (message.getTimeStamp() != 0);
  23904. const ScopedLock sl (midiCallbackLock);
  23905. const int sampleNumber
  23906. = (int) ((message.getTimeStamp() - 0.001 * lastCallbackTime) * sampleRate);
  23907. incomingMessages.addEvent (message, sampleNumber);
  23908. // if the messages don't get used for over a second, we'd better
  23909. // get rid of any old ones to avoid the queue getting too big
  23910. if (sampleNumber > sampleRate)
  23911. incomingMessages.clear (0, sampleNumber - (int) sampleRate);
  23912. }
  23913. void MidiMessageCollector::removeNextBlockOfMessages (MidiBuffer& destBuffer,
  23914. const int numSamples)
  23915. {
  23916. // you need to call reset() to set the correct sample rate before using this object
  23917. jassert (sampleRate != 44100.0001);
  23918. const double timeNow = Time::getMillisecondCounterHiRes();
  23919. const double msElapsed = timeNow - lastCallbackTime;
  23920. const ScopedLock sl (midiCallbackLock);
  23921. lastCallbackTime = timeNow;
  23922. if (! incomingMessages.isEmpty())
  23923. {
  23924. int numSourceSamples = jmax (1, roundToInt (msElapsed * 0.001 * sampleRate));
  23925. int startSample = 0;
  23926. int scale = 1 << 16;
  23927. const uint8* midiData;
  23928. int numBytes, samplePosition;
  23929. MidiBuffer::Iterator iter (incomingMessages);
  23930. if (numSourceSamples > numSamples)
  23931. {
  23932. // if our list of events is longer than the buffer we're being
  23933. // asked for, scale them down to squeeze them all in..
  23934. const int maxBlockLengthToUse = numSamples << 5;
  23935. if (numSourceSamples > maxBlockLengthToUse)
  23936. {
  23937. startSample = numSourceSamples - maxBlockLengthToUse;
  23938. numSourceSamples = maxBlockLengthToUse;
  23939. iter.setNextSamplePosition (startSample);
  23940. }
  23941. scale = (numSamples << 10) / numSourceSamples;
  23942. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  23943. {
  23944. samplePosition = ((samplePosition - startSample) * scale) >> 10;
  23945. destBuffer.addEvent (midiData, numBytes,
  23946. jlimit (0, numSamples - 1, samplePosition));
  23947. }
  23948. }
  23949. else
  23950. {
  23951. // if our event list is shorter than the number we need, put them
  23952. // towards the end of the buffer
  23953. startSample = numSamples - numSourceSamples;
  23954. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  23955. {
  23956. destBuffer.addEvent (midiData, numBytes,
  23957. jlimit (0, numSamples - 1, samplePosition + startSample));
  23958. }
  23959. }
  23960. incomingMessages.clear();
  23961. }
  23962. }
  23963. void MidiMessageCollector::handleNoteOn (MidiKeyboardState*, int midiChannel, int midiNoteNumber, float velocity)
  23964. {
  23965. MidiMessage m (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity));
  23966. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  23967. addMessageToQueue (m);
  23968. }
  23969. void MidiMessageCollector::handleNoteOff (MidiKeyboardState*, int midiChannel, int midiNoteNumber)
  23970. {
  23971. MidiMessage m (MidiMessage::noteOff (midiChannel, midiNoteNumber));
  23972. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  23973. addMessageToQueue (m);
  23974. }
  23975. void MidiMessageCollector::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  23976. {
  23977. addMessageToQueue (message);
  23978. }
  23979. END_JUCE_NAMESPACE
  23980. /*** End of inlined file: juce_MidiMessageCollector.cpp ***/
  23981. /*** Start of inlined file: juce_MidiMessageSequence.cpp ***/
  23982. BEGIN_JUCE_NAMESPACE
  23983. MidiMessageSequence::MidiMessageSequence()
  23984. {
  23985. }
  23986. MidiMessageSequence::MidiMessageSequence (const MidiMessageSequence& other)
  23987. {
  23988. list.ensureStorageAllocated (other.list.size());
  23989. for (int i = 0; i < other.list.size(); ++i)
  23990. list.add (new MidiEventHolder (other.list.getUnchecked(i)->message));
  23991. }
  23992. MidiMessageSequence& MidiMessageSequence::operator= (const MidiMessageSequence& other)
  23993. {
  23994. MidiMessageSequence otherCopy (other);
  23995. swapWith (otherCopy);
  23996. return *this;
  23997. }
  23998. void MidiMessageSequence::swapWith (MidiMessageSequence& other) throw()
  23999. {
  24000. list.swapWithArray (other.list);
  24001. }
  24002. MidiMessageSequence::~MidiMessageSequence()
  24003. {
  24004. }
  24005. void MidiMessageSequence::clear()
  24006. {
  24007. list.clear();
  24008. }
  24009. int MidiMessageSequence::getNumEvents() const
  24010. {
  24011. return list.size();
  24012. }
  24013. MidiMessageSequence::MidiEventHolder* MidiMessageSequence::getEventPointer (const int index) const
  24014. {
  24015. return list [index];
  24016. }
  24017. double MidiMessageSequence::getTimeOfMatchingKeyUp (const int index) const
  24018. {
  24019. const MidiEventHolder* const meh = list [index];
  24020. if (meh != 0 && meh->noteOffObject != 0)
  24021. return meh->noteOffObject->message.getTimeStamp();
  24022. else
  24023. return 0.0;
  24024. }
  24025. int MidiMessageSequence::getIndexOfMatchingKeyUp (const int index) const
  24026. {
  24027. const MidiEventHolder* const meh = list [index];
  24028. return (meh != 0) ? list.indexOf (meh->noteOffObject) : -1;
  24029. }
  24030. int MidiMessageSequence::getIndexOf (MidiEventHolder* const event) const
  24031. {
  24032. return list.indexOf (event);
  24033. }
  24034. int MidiMessageSequence::getNextIndexAtTime (const double timeStamp) const
  24035. {
  24036. const int numEvents = list.size();
  24037. int i;
  24038. for (i = 0; i < numEvents; ++i)
  24039. if (list.getUnchecked(i)->message.getTimeStamp() >= timeStamp)
  24040. break;
  24041. return i;
  24042. }
  24043. double MidiMessageSequence::getStartTime() const
  24044. {
  24045. if (list.size() > 0)
  24046. return list.getUnchecked(0)->message.getTimeStamp();
  24047. else
  24048. return 0;
  24049. }
  24050. double MidiMessageSequence::getEndTime() const
  24051. {
  24052. if (list.size() > 0)
  24053. return list.getLast()->message.getTimeStamp();
  24054. else
  24055. return 0;
  24056. }
  24057. double MidiMessageSequence::getEventTime (const int index) const
  24058. {
  24059. if (((unsigned int) index) < (unsigned int) list.size())
  24060. return list.getUnchecked (index)->message.getTimeStamp();
  24061. return 0.0;
  24062. }
  24063. void MidiMessageSequence::addEvent (const MidiMessage& newMessage,
  24064. double timeAdjustment)
  24065. {
  24066. MidiEventHolder* const newOne = new MidiEventHolder (newMessage);
  24067. timeAdjustment += newMessage.getTimeStamp();
  24068. newOne->message.setTimeStamp (timeAdjustment);
  24069. int i;
  24070. for (i = list.size(); --i >= 0;)
  24071. if (list.getUnchecked(i)->message.getTimeStamp() <= timeAdjustment)
  24072. break;
  24073. list.insert (i + 1, newOne);
  24074. }
  24075. void MidiMessageSequence::deleteEvent (const int index,
  24076. const bool deleteMatchingNoteUp)
  24077. {
  24078. if (((unsigned int) index) < (unsigned int) list.size())
  24079. {
  24080. if (deleteMatchingNoteUp)
  24081. deleteEvent (getIndexOfMatchingKeyUp (index), false);
  24082. list.remove (index);
  24083. }
  24084. }
  24085. void MidiMessageSequence::addSequence (const MidiMessageSequence& other,
  24086. double timeAdjustment,
  24087. double firstAllowableTime,
  24088. double endOfAllowableDestTimes)
  24089. {
  24090. firstAllowableTime -= timeAdjustment;
  24091. endOfAllowableDestTimes -= timeAdjustment;
  24092. for (int i = 0; i < other.list.size(); ++i)
  24093. {
  24094. const MidiMessage& m = other.list.getUnchecked(i)->message;
  24095. const double t = m.getTimeStamp();
  24096. if (t >= firstAllowableTime && t < endOfAllowableDestTimes)
  24097. {
  24098. MidiEventHolder* const newOne = new MidiEventHolder (m);
  24099. newOne->message.setTimeStamp (timeAdjustment + t);
  24100. list.add (newOne);
  24101. }
  24102. }
  24103. sort();
  24104. }
  24105. int MidiMessageSequence::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  24106. const MidiMessageSequence::MidiEventHolder* const second) throw()
  24107. {
  24108. const double diff = first->message.getTimeStamp()
  24109. - second->message.getTimeStamp();
  24110. return (diff > 0) - (diff < 0);
  24111. }
  24112. void MidiMessageSequence::sort()
  24113. {
  24114. list.sort (*this, true);
  24115. }
  24116. void MidiMessageSequence::updateMatchedPairs()
  24117. {
  24118. for (int i = 0; i < list.size(); ++i)
  24119. {
  24120. const MidiMessage& m1 = list.getUnchecked(i)->message;
  24121. if (m1.isNoteOn())
  24122. {
  24123. list.getUnchecked(i)->noteOffObject = 0;
  24124. const int note = m1.getNoteNumber();
  24125. const int chan = m1.getChannel();
  24126. const int len = list.size();
  24127. for (int j = i + 1; j < len; ++j)
  24128. {
  24129. const MidiMessage& m = list.getUnchecked(j)->message;
  24130. if (m.getNoteNumber() == note && m.getChannel() == chan)
  24131. {
  24132. if (m.isNoteOff())
  24133. {
  24134. list.getUnchecked(i)->noteOffObject = list[j];
  24135. break;
  24136. }
  24137. else if (m.isNoteOn())
  24138. {
  24139. list.insert (j, new MidiEventHolder (MidiMessage::noteOff (chan, note)));
  24140. list.getUnchecked(j)->message.setTimeStamp (m.getTimeStamp());
  24141. list.getUnchecked(i)->noteOffObject = list[j];
  24142. break;
  24143. }
  24144. }
  24145. }
  24146. }
  24147. }
  24148. }
  24149. void MidiMessageSequence::addTimeToMessages (const double delta)
  24150. {
  24151. for (int i = list.size(); --i >= 0;)
  24152. list.getUnchecked (i)->message.setTimeStamp (list.getUnchecked (i)->message.getTimeStamp()
  24153. + delta);
  24154. }
  24155. void MidiMessageSequence::extractMidiChannelMessages (const int channelNumberToExtract,
  24156. MidiMessageSequence& destSequence,
  24157. const bool alsoIncludeMetaEvents) const
  24158. {
  24159. for (int i = 0; i < list.size(); ++i)
  24160. {
  24161. const MidiMessage& mm = list.getUnchecked(i)->message;
  24162. if (mm.isForChannel (channelNumberToExtract)
  24163. || (alsoIncludeMetaEvents && mm.isMetaEvent()))
  24164. {
  24165. destSequence.addEvent (mm);
  24166. }
  24167. }
  24168. }
  24169. void MidiMessageSequence::extractSysExMessages (MidiMessageSequence& destSequence) const
  24170. {
  24171. for (int i = 0; i < list.size(); ++i)
  24172. {
  24173. const MidiMessage& mm = list.getUnchecked(i)->message;
  24174. if (mm.isSysEx())
  24175. destSequence.addEvent (mm);
  24176. }
  24177. }
  24178. void MidiMessageSequence::deleteMidiChannelMessages (const int channelNumberToRemove)
  24179. {
  24180. for (int i = list.size(); --i >= 0;)
  24181. if (list.getUnchecked(i)->message.isForChannel (channelNumberToRemove))
  24182. list.remove(i);
  24183. }
  24184. void MidiMessageSequence::deleteSysExMessages()
  24185. {
  24186. for (int i = list.size(); --i >= 0;)
  24187. if (list.getUnchecked(i)->message.isSysEx())
  24188. list.remove(i);
  24189. }
  24190. void MidiMessageSequence::createControllerUpdatesForTime (const int channelNumber,
  24191. const double time,
  24192. OwnedArray<MidiMessage>& dest)
  24193. {
  24194. bool doneProg = false;
  24195. bool donePitchWheel = false;
  24196. Array <int> doneControllers;
  24197. doneControllers.ensureStorageAllocated (32);
  24198. for (int i = list.size(); --i >= 0;)
  24199. {
  24200. const MidiMessage& mm = list.getUnchecked(i)->message;
  24201. if (mm.isForChannel (channelNumber)
  24202. && mm.getTimeStamp() <= time)
  24203. {
  24204. if (mm.isProgramChange())
  24205. {
  24206. if (! doneProg)
  24207. {
  24208. dest.add (new MidiMessage (mm, 0.0));
  24209. doneProg = true;
  24210. }
  24211. }
  24212. else if (mm.isController())
  24213. {
  24214. if (! doneControllers.contains (mm.getControllerNumber()))
  24215. {
  24216. dest.add (new MidiMessage (mm, 0.0));
  24217. doneControllers.add (mm.getControllerNumber());
  24218. }
  24219. }
  24220. else if (mm.isPitchWheel())
  24221. {
  24222. if (! donePitchWheel)
  24223. {
  24224. dest.add (new MidiMessage (mm, 0.0));
  24225. donePitchWheel = true;
  24226. }
  24227. }
  24228. }
  24229. }
  24230. }
  24231. MidiMessageSequence::MidiEventHolder::MidiEventHolder (const MidiMessage& message_)
  24232. : message (message_),
  24233. noteOffObject (0)
  24234. {
  24235. }
  24236. MidiMessageSequence::MidiEventHolder::~MidiEventHolder()
  24237. {
  24238. }
  24239. END_JUCE_NAMESPACE
  24240. /*** End of inlined file: juce_MidiMessageSequence.cpp ***/
  24241. /*** Start of inlined file: juce_AudioPluginFormat.cpp ***/
  24242. BEGIN_JUCE_NAMESPACE
  24243. AudioPluginFormat::AudioPluginFormat() throw()
  24244. {
  24245. }
  24246. AudioPluginFormat::~AudioPluginFormat()
  24247. {
  24248. }
  24249. END_JUCE_NAMESPACE
  24250. /*** End of inlined file: juce_AudioPluginFormat.cpp ***/
  24251. /*** Start of inlined file: juce_AudioPluginFormatManager.cpp ***/
  24252. BEGIN_JUCE_NAMESPACE
  24253. AudioPluginFormatManager::AudioPluginFormatManager()
  24254. {
  24255. }
  24256. AudioPluginFormatManager::~AudioPluginFormatManager()
  24257. {
  24258. clearSingletonInstance();
  24259. }
  24260. juce_ImplementSingleton_SingleThreaded (AudioPluginFormatManager);
  24261. void AudioPluginFormatManager::addDefaultFormats()
  24262. {
  24263. #if JUCE_DEBUG
  24264. // you should only call this method once!
  24265. for (int i = formats.size(); --i >= 0;)
  24266. {
  24267. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  24268. jassert (dynamic_cast <VSTPluginFormat*> (formats[i]) == 0);
  24269. #endif
  24270. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  24271. jassert (dynamic_cast <AudioUnitPluginFormat*> (formats[i]) == 0);
  24272. #endif
  24273. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  24274. jassert (dynamic_cast <DirectXPluginFormat*> (formats[i]) == 0);
  24275. #endif
  24276. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  24277. jassert (dynamic_cast <LADSPAPluginFormat*> (formats[i]) == 0);
  24278. #endif
  24279. }
  24280. #endif
  24281. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  24282. formats.add (new AudioUnitPluginFormat());
  24283. #endif
  24284. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  24285. formats.add (new VSTPluginFormat());
  24286. #endif
  24287. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  24288. formats.add (new DirectXPluginFormat());
  24289. #endif
  24290. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  24291. formats.add (new LADSPAPluginFormat());
  24292. #endif
  24293. }
  24294. int AudioPluginFormatManager::getNumFormats()
  24295. {
  24296. return formats.size();
  24297. }
  24298. AudioPluginFormat* AudioPluginFormatManager::getFormat (const int index)
  24299. {
  24300. return formats [index];
  24301. }
  24302. void AudioPluginFormatManager::addFormat (AudioPluginFormat* const format)
  24303. {
  24304. formats.add (format);
  24305. }
  24306. AudioPluginInstance* AudioPluginFormatManager::createPluginInstance (const PluginDescription& description,
  24307. String& errorMessage) const
  24308. {
  24309. AudioPluginInstance* result = 0;
  24310. for (int i = 0; i < formats.size(); ++i)
  24311. {
  24312. result = formats.getUnchecked(i)->createInstanceFromDescription (description);
  24313. if (result != 0)
  24314. break;
  24315. }
  24316. if (result == 0)
  24317. {
  24318. if (! doesPluginStillExist (description))
  24319. errorMessage = TRANS ("This plug-in file no longer exists");
  24320. else
  24321. errorMessage = TRANS ("This plug-in failed to load correctly");
  24322. }
  24323. return result;
  24324. }
  24325. bool AudioPluginFormatManager::doesPluginStillExist (const PluginDescription& description) const
  24326. {
  24327. for (int i = 0; i < formats.size(); ++i)
  24328. if (formats.getUnchecked(i)->getName() == description.pluginFormatName)
  24329. return formats.getUnchecked(i)->doesPluginStillExist (description);
  24330. return false;
  24331. }
  24332. END_JUCE_NAMESPACE
  24333. /*** End of inlined file: juce_AudioPluginFormatManager.cpp ***/
  24334. /*** Start of inlined file: juce_AudioPluginInstance.cpp ***/
  24335. #define JUCE_PLUGIN_HOST 1
  24336. BEGIN_JUCE_NAMESPACE
  24337. AudioPluginInstance::AudioPluginInstance()
  24338. {
  24339. }
  24340. AudioPluginInstance::~AudioPluginInstance()
  24341. {
  24342. }
  24343. END_JUCE_NAMESPACE
  24344. /*** End of inlined file: juce_AudioPluginInstance.cpp ***/
  24345. /*** Start of inlined file: juce_KnownPluginList.cpp ***/
  24346. BEGIN_JUCE_NAMESPACE
  24347. KnownPluginList::KnownPluginList()
  24348. {
  24349. }
  24350. KnownPluginList::~KnownPluginList()
  24351. {
  24352. }
  24353. void KnownPluginList::clear()
  24354. {
  24355. if (types.size() > 0)
  24356. {
  24357. types.clear();
  24358. sendChangeMessage (this);
  24359. }
  24360. }
  24361. PluginDescription* KnownPluginList::getTypeForFile (const String& fileOrIdentifier) const
  24362. {
  24363. for (int i = 0; i < types.size(); ++i)
  24364. if (types.getUnchecked(i)->fileOrIdentifier == fileOrIdentifier)
  24365. return types.getUnchecked(i);
  24366. return 0;
  24367. }
  24368. PluginDescription* KnownPluginList::getTypeForIdentifierString (const String& identifierString) const
  24369. {
  24370. for (int i = 0; i < types.size(); ++i)
  24371. if (types.getUnchecked(i)->createIdentifierString() == identifierString)
  24372. return types.getUnchecked(i);
  24373. return 0;
  24374. }
  24375. bool KnownPluginList::addType (const PluginDescription& type)
  24376. {
  24377. for (int i = types.size(); --i >= 0;)
  24378. {
  24379. if (types.getUnchecked(i)->isDuplicateOf (type))
  24380. {
  24381. // strange - found a duplicate plugin with different info..
  24382. jassert (types.getUnchecked(i)->name == type.name);
  24383. jassert (types.getUnchecked(i)->isInstrument == type.isInstrument);
  24384. *types.getUnchecked(i) = type;
  24385. return false;
  24386. }
  24387. }
  24388. types.add (new PluginDescription (type));
  24389. sendChangeMessage (this);
  24390. return true;
  24391. }
  24392. void KnownPluginList::removeType (const int index)
  24393. {
  24394. types.remove (index);
  24395. sendChangeMessage (this);
  24396. }
  24397. static const Time getPluginFileModTime (const String& fileOrIdentifier)
  24398. {
  24399. if (fileOrIdentifier.startsWithChar ('/') || fileOrIdentifier[1] == ':')
  24400. return File (fileOrIdentifier).getLastModificationTime();
  24401. return Time (0);
  24402. }
  24403. static bool timesAreDifferent (const Time& t1, const Time& t2) throw()
  24404. {
  24405. return t1 != t2 || t1 == Time (0);
  24406. }
  24407. bool KnownPluginList::isListingUpToDate (const String& fileOrIdentifier) const
  24408. {
  24409. if (getTypeForFile (fileOrIdentifier) == 0)
  24410. return false;
  24411. for (int i = types.size(); --i >= 0;)
  24412. {
  24413. const PluginDescription* const d = types.getUnchecked(i);
  24414. if (d->fileOrIdentifier == fileOrIdentifier
  24415. && timesAreDifferent (d->lastFileModTime, getPluginFileModTime (fileOrIdentifier)))
  24416. {
  24417. return false;
  24418. }
  24419. }
  24420. return true;
  24421. }
  24422. bool KnownPluginList::scanAndAddFile (const String& fileOrIdentifier,
  24423. const bool dontRescanIfAlreadyInList,
  24424. OwnedArray <PluginDescription>& typesFound,
  24425. AudioPluginFormat& format)
  24426. {
  24427. bool addedOne = false;
  24428. if (dontRescanIfAlreadyInList
  24429. && getTypeForFile (fileOrIdentifier) != 0)
  24430. {
  24431. bool needsRescanning = false;
  24432. for (int i = types.size(); --i >= 0;)
  24433. {
  24434. const PluginDescription* const d = types.getUnchecked(i);
  24435. if (d->fileOrIdentifier == fileOrIdentifier)
  24436. {
  24437. if (timesAreDifferent (d->lastFileModTime, getPluginFileModTime (fileOrIdentifier)))
  24438. needsRescanning = true;
  24439. else
  24440. typesFound.add (new PluginDescription (*d));
  24441. }
  24442. }
  24443. if (! needsRescanning)
  24444. return false;
  24445. }
  24446. OwnedArray <PluginDescription> found;
  24447. format.findAllTypesForFile (found, fileOrIdentifier);
  24448. for (int i = 0; i < found.size(); ++i)
  24449. {
  24450. PluginDescription* const desc = found.getUnchecked(i);
  24451. jassert (desc != 0);
  24452. if (addType (*desc))
  24453. addedOne = true;
  24454. typesFound.add (new PluginDescription (*desc));
  24455. }
  24456. return addedOne;
  24457. }
  24458. void KnownPluginList::scanAndAddDragAndDroppedFiles (const StringArray& files,
  24459. OwnedArray <PluginDescription>& typesFound)
  24460. {
  24461. for (int i = 0; i < files.size(); ++i)
  24462. {
  24463. bool loaded = false;
  24464. for (int j = 0; j < AudioPluginFormatManager::getInstance()->getNumFormats(); ++j)
  24465. {
  24466. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (j);
  24467. if (scanAndAddFile (files[i], true, typesFound, *format))
  24468. loaded = true;
  24469. }
  24470. if (! loaded)
  24471. {
  24472. const File f (files[i]);
  24473. if (f.isDirectory())
  24474. {
  24475. StringArray s;
  24476. {
  24477. Array<File> subFiles;
  24478. f.findChildFiles (subFiles, File::findFilesAndDirectories, false);
  24479. for (int j = 0; j < subFiles.size(); ++j)
  24480. s.add (subFiles.getReference(j).getFullPathName());
  24481. }
  24482. scanAndAddDragAndDroppedFiles (s, typesFound);
  24483. }
  24484. }
  24485. }
  24486. }
  24487. class PluginSorter
  24488. {
  24489. public:
  24490. KnownPluginList::SortMethod method;
  24491. PluginSorter() throw() {}
  24492. int compareElements (const PluginDescription* const first,
  24493. const PluginDescription* const second) const
  24494. {
  24495. int diff = 0;
  24496. if (method == KnownPluginList::sortByCategory)
  24497. diff = first->category.compareLexicographically (second->category);
  24498. else if (method == KnownPluginList::sortByManufacturer)
  24499. diff = first->manufacturerName.compareLexicographically (second->manufacturerName);
  24500. else if (method == KnownPluginList::sortByFileSystemLocation)
  24501. diff = first->fileOrIdentifier.replaceCharacter ('\\', '/')
  24502. .upToLastOccurrenceOf ("/", false, false)
  24503. .compare (second->fileOrIdentifier.replaceCharacter ('\\', '/')
  24504. .upToLastOccurrenceOf ("/", false, false));
  24505. if (diff == 0)
  24506. diff = first->name.compareLexicographically (second->name);
  24507. return diff;
  24508. }
  24509. };
  24510. void KnownPluginList::sort (const SortMethod method)
  24511. {
  24512. if (method != defaultOrder)
  24513. {
  24514. PluginSorter sorter;
  24515. sorter.method = method;
  24516. types.sort (sorter, true);
  24517. sendChangeMessage (this);
  24518. }
  24519. }
  24520. XmlElement* KnownPluginList::createXml() const
  24521. {
  24522. XmlElement* const e = new XmlElement ("KNOWNPLUGINS");
  24523. for (int i = 0; i < types.size(); ++i)
  24524. e->addChildElement (types.getUnchecked(i)->createXml());
  24525. return e;
  24526. }
  24527. void KnownPluginList::recreateFromXml (const XmlElement& xml)
  24528. {
  24529. clear();
  24530. if (xml.hasTagName ("KNOWNPLUGINS"))
  24531. {
  24532. forEachXmlChildElement (xml, e)
  24533. {
  24534. PluginDescription info;
  24535. if (info.loadFromXml (*e))
  24536. addType (info);
  24537. }
  24538. }
  24539. }
  24540. const int menuIdBase = 0x324503f4;
  24541. // This is used to turn a bunch of paths into a nested menu structure.
  24542. struct PluginFilesystemTree
  24543. {
  24544. private:
  24545. String folder;
  24546. OwnedArray <PluginFilesystemTree> subFolders;
  24547. Array <PluginDescription*> plugins;
  24548. void addPlugin (PluginDescription* const pd, const String& path)
  24549. {
  24550. if (path.isEmpty())
  24551. {
  24552. plugins.add (pd);
  24553. }
  24554. else
  24555. {
  24556. const String firstSubFolder (path.upToFirstOccurrenceOf ("/", false, false));
  24557. const String remainingPath (path.fromFirstOccurrenceOf ("/", false, false));
  24558. for (int i = subFolders.size(); --i >= 0;)
  24559. {
  24560. if (subFolders.getUnchecked(i)->folder.equalsIgnoreCase (firstSubFolder))
  24561. {
  24562. subFolders.getUnchecked(i)->addPlugin (pd, remainingPath);
  24563. return;
  24564. }
  24565. }
  24566. PluginFilesystemTree* const newFolder = new PluginFilesystemTree();
  24567. newFolder->folder = firstSubFolder;
  24568. subFolders.add (newFolder);
  24569. newFolder->addPlugin (pd, remainingPath);
  24570. }
  24571. }
  24572. // removes any deeply nested folders that don't contain any actual plugins
  24573. void optimise()
  24574. {
  24575. for (int i = subFolders.size(); --i >= 0;)
  24576. {
  24577. PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  24578. sub->optimise();
  24579. if (sub->plugins.size() == 0)
  24580. {
  24581. for (int j = 0; j < sub->subFolders.size(); ++j)
  24582. subFolders.add (sub->subFolders.getUnchecked(j));
  24583. sub->subFolders.clear (false);
  24584. subFolders.remove (i);
  24585. }
  24586. }
  24587. }
  24588. public:
  24589. void buildTree (const Array <PluginDescription*>& allPlugins)
  24590. {
  24591. for (int i = 0; i < allPlugins.size(); ++i)
  24592. {
  24593. String path (allPlugins.getUnchecked(i)
  24594. ->fileOrIdentifier.replaceCharacter ('\\', '/')
  24595. .upToLastOccurrenceOf ("/", false, false));
  24596. if (path.substring (1, 2) == ":")
  24597. path = path.substring (2);
  24598. addPlugin (allPlugins.getUnchecked(i), path);
  24599. }
  24600. optimise();
  24601. }
  24602. void addToMenu (PopupMenu& m, const OwnedArray <PluginDescription>& allPlugins) const
  24603. {
  24604. int i;
  24605. for (i = 0; i < subFolders.size(); ++i)
  24606. {
  24607. const PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  24608. PopupMenu subMenu;
  24609. sub->addToMenu (subMenu, allPlugins);
  24610. #if JUCE_MAC
  24611. // avoid the special AU formatting nonsense on Mac..
  24612. m.addSubMenu (sub->folder.fromFirstOccurrenceOf (":", false, false), subMenu);
  24613. #else
  24614. m.addSubMenu (sub->folder, subMenu);
  24615. #endif
  24616. }
  24617. for (i = 0; i < plugins.size(); ++i)
  24618. {
  24619. PluginDescription* const plugin = plugins.getUnchecked(i);
  24620. m.addItem (allPlugins.indexOf (plugin) + menuIdBase,
  24621. plugin->name, true, false);
  24622. }
  24623. }
  24624. };
  24625. void KnownPluginList::addToMenu (PopupMenu& menu, const SortMethod sortMethod) const
  24626. {
  24627. Array <PluginDescription*> sorted;
  24628. {
  24629. PluginSorter sorter;
  24630. sorter.method = sortMethod;
  24631. for (int i = 0; i < types.size(); ++i)
  24632. sorted.addSorted (sorter, types.getUnchecked(i));
  24633. }
  24634. if (sortMethod == sortByCategory
  24635. || sortMethod == sortByManufacturer)
  24636. {
  24637. String lastSubMenuName;
  24638. PopupMenu sub;
  24639. for (int i = 0; i < sorted.size(); ++i)
  24640. {
  24641. const PluginDescription* const pd = sorted.getUnchecked(i);
  24642. String thisSubMenuName (sortMethod == sortByCategory ? pd->category
  24643. : pd->manufacturerName);
  24644. if (! thisSubMenuName.containsNonWhitespaceChars())
  24645. thisSubMenuName = "Other";
  24646. if (thisSubMenuName != lastSubMenuName)
  24647. {
  24648. if (sub.getNumItems() > 0)
  24649. {
  24650. menu.addSubMenu (lastSubMenuName, sub);
  24651. sub.clear();
  24652. }
  24653. lastSubMenuName = thisSubMenuName;
  24654. }
  24655. sub.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  24656. }
  24657. if (sub.getNumItems() > 0)
  24658. menu.addSubMenu (lastSubMenuName, sub);
  24659. }
  24660. else if (sortMethod == sortByFileSystemLocation)
  24661. {
  24662. PluginFilesystemTree root;
  24663. root.buildTree (sorted);
  24664. root.addToMenu (menu, types);
  24665. }
  24666. else
  24667. {
  24668. for (int i = 0; i < sorted.size(); ++i)
  24669. {
  24670. const PluginDescription* const pd = sorted.getUnchecked(i);
  24671. menu.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  24672. }
  24673. }
  24674. }
  24675. int KnownPluginList::getIndexChosenByMenu (const int menuResultCode) const
  24676. {
  24677. const int i = menuResultCode - menuIdBase;
  24678. return (((unsigned int) i) < (unsigned int) types.size()) ? i : -1;
  24679. }
  24680. END_JUCE_NAMESPACE
  24681. /*** End of inlined file: juce_KnownPluginList.cpp ***/
  24682. /*** Start of inlined file: juce_PluginDescription.cpp ***/
  24683. BEGIN_JUCE_NAMESPACE
  24684. PluginDescription::PluginDescription()
  24685. : uid (0),
  24686. isInstrument (false),
  24687. numInputChannels (0),
  24688. numOutputChannels (0)
  24689. {
  24690. }
  24691. PluginDescription::~PluginDescription()
  24692. {
  24693. }
  24694. PluginDescription::PluginDescription (const PluginDescription& other)
  24695. : name (other.name),
  24696. pluginFormatName (other.pluginFormatName),
  24697. category (other.category),
  24698. manufacturerName (other.manufacturerName),
  24699. version (other.version),
  24700. fileOrIdentifier (other.fileOrIdentifier),
  24701. lastFileModTime (other.lastFileModTime),
  24702. uid (other.uid),
  24703. isInstrument (other.isInstrument),
  24704. numInputChannels (other.numInputChannels),
  24705. numOutputChannels (other.numOutputChannels)
  24706. {
  24707. }
  24708. PluginDescription& PluginDescription::operator= (const PluginDescription& other)
  24709. {
  24710. name = other.name;
  24711. pluginFormatName = other.pluginFormatName;
  24712. category = other.category;
  24713. manufacturerName = other.manufacturerName;
  24714. version = other.version;
  24715. fileOrIdentifier = other.fileOrIdentifier;
  24716. uid = other.uid;
  24717. isInstrument = other.isInstrument;
  24718. lastFileModTime = other.lastFileModTime;
  24719. numInputChannels = other.numInputChannels;
  24720. numOutputChannels = other.numOutputChannels;
  24721. return *this;
  24722. }
  24723. bool PluginDescription::isDuplicateOf (const PluginDescription& other) const
  24724. {
  24725. return fileOrIdentifier == other.fileOrIdentifier
  24726. && uid == other.uid;
  24727. }
  24728. const String PluginDescription::createIdentifierString() const
  24729. {
  24730. return pluginFormatName
  24731. + "-" + name
  24732. + "-" + String::toHexString (fileOrIdentifier.hashCode())
  24733. + "-" + String::toHexString (uid);
  24734. }
  24735. XmlElement* PluginDescription::createXml() const
  24736. {
  24737. XmlElement* const e = new XmlElement ("PLUGIN");
  24738. e->setAttribute ("name", name);
  24739. e->setAttribute ("format", pluginFormatName);
  24740. e->setAttribute ("category", category);
  24741. e->setAttribute ("manufacturer", manufacturerName);
  24742. e->setAttribute ("version", version);
  24743. e->setAttribute ("file", fileOrIdentifier);
  24744. e->setAttribute ("uid", String::toHexString (uid));
  24745. e->setAttribute ("isInstrument", isInstrument);
  24746. e->setAttribute ("fileTime", String::toHexString (lastFileModTime.toMilliseconds()));
  24747. e->setAttribute ("numInputs", numInputChannels);
  24748. e->setAttribute ("numOutputs", numOutputChannels);
  24749. return e;
  24750. }
  24751. bool PluginDescription::loadFromXml (const XmlElement& xml)
  24752. {
  24753. if (xml.hasTagName ("PLUGIN"))
  24754. {
  24755. name = xml.getStringAttribute ("name");
  24756. pluginFormatName = xml.getStringAttribute ("format");
  24757. category = xml.getStringAttribute ("category");
  24758. manufacturerName = xml.getStringAttribute ("manufacturer");
  24759. version = xml.getStringAttribute ("version");
  24760. fileOrIdentifier = xml.getStringAttribute ("file");
  24761. uid = xml.getStringAttribute ("uid").getHexValue32();
  24762. isInstrument = xml.getBoolAttribute ("isInstrument", false);
  24763. lastFileModTime = Time (xml.getStringAttribute ("fileTime").getHexValue64());
  24764. numInputChannels = xml.getIntAttribute ("numInputs");
  24765. numOutputChannels = xml.getIntAttribute ("numOutputs");
  24766. return true;
  24767. }
  24768. return false;
  24769. }
  24770. END_JUCE_NAMESPACE
  24771. /*** End of inlined file: juce_PluginDescription.cpp ***/
  24772. /*** Start of inlined file: juce_PluginDirectoryScanner.cpp ***/
  24773. BEGIN_JUCE_NAMESPACE
  24774. PluginDirectoryScanner::PluginDirectoryScanner (KnownPluginList& listToAddTo,
  24775. AudioPluginFormat& formatToLookFor,
  24776. FileSearchPath directoriesToSearch,
  24777. const bool recursive,
  24778. const File& deadMansPedalFile_)
  24779. : list (listToAddTo),
  24780. format (formatToLookFor),
  24781. deadMansPedalFile (deadMansPedalFile_),
  24782. nextIndex (0),
  24783. progress (0)
  24784. {
  24785. directoriesToSearch.removeRedundantPaths();
  24786. filesOrIdentifiersToScan = format.searchPathsForPlugins (directoriesToSearch, recursive);
  24787. // If any plugins have crashed recently when being loaded, move them to the
  24788. // end of the list to give the others a chance to load correctly..
  24789. const StringArray crashedPlugins (getDeadMansPedalFile());
  24790. for (int i = 0; i < crashedPlugins.size(); ++i)
  24791. {
  24792. const String f = crashedPlugins[i];
  24793. for (int j = filesOrIdentifiersToScan.size(); --j >= 0;)
  24794. if (f == filesOrIdentifiersToScan[j])
  24795. filesOrIdentifiersToScan.move (j, -1);
  24796. }
  24797. }
  24798. PluginDirectoryScanner::~PluginDirectoryScanner()
  24799. {
  24800. }
  24801. const String PluginDirectoryScanner::getNextPluginFileThatWillBeScanned() const
  24802. {
  24803. return format.getNameOfPluginFromIdentifier (filesOrIdentifiersToScan [nextIndex]);
  24804. }
  24805. bool PluginDirectoryScanner::scanNextFile (const bool dontRescanIfAlreadyInList)
  24806. {
  24807. String file (filesOrIdentifiersToScan [nextIndex]);
  24808. if (file.isNotEmpty())
  24809. {
  24810. if (! list.isListingUpToDate (file))
  24811. {
  24812. OwnedArray <PluginDescription> typesFound;
  24813. // Add this plugin to the end of the dead-man's pedal list in case it crashes...
  24814. StringArray crashedPlugins (getDeadMansPedalFile());
  24815. crashedPlugins.removeString (file);
  24816. crashedPlugins.add (file);
  24817. setDeadMansPedalFile (crashedPlugins);
  24818. list.scanAndAddFile (file,
  24819. dontRescanIfAlreadyInList,
  24820. typesFound,
  24821. format);
  24822. // Managed to load without crashing, so remove it from the dead-man's-pedal..
  24823. crashedPlugins.removeString (file);
  24824. setDeadMansPedalFile (crashedPlugins);
  24825. if (typesFound.size() == 0)
  24826. failedFiles.add (file);
  24827. }
  24828. ++nextIndex;
  24829. progress = nextIndex / (float) filesOrIdentifiersToScan.size();
  24830. }
  24831. return nextIndex < filesOrIdentifiersToScan.size();
  24832. }
  24833. const StringArray PluginDirectoryScanner::getDeadMansPedalFile()
  24834. {
  24835. StringArray lines;
  24836. if (deadMansPedalFile != File::nonexistent)
  24837. {
  24838. lines.addLines (deadMansPedalFile.loadFileAsString());
  24839. lines.removeEmptyStrings();
  24840. }
  24841. return lines;
  24842. }
  24843. void PluginDirectoryScanner::setDeadMansPedalFile (const StringArray& newContents)
  24844. {
  24845. if (deadMansPedalFile != File::nonexistent)
  24846. deadMansPedalFile.replaceWithText (newContents.joinIntoString ("\n"), true, true);
  24847. }
  24848. END_JUCE_NAMESPACE
  24849. /*** End of inlined file: juce_PluginDirectoryScanner.cpp ***/
  24850. /*** Start of inlined file: juce_PluginListComponent.cpp ***/
  24851. BEGIN_JUCE_NAMESPACE
  24852. PluginListComponent::PluginListComponent (KnownPluginList& listToEdit,
  24853. const File& deadMansPedalFile_,
  24854. PropertiesFile* const propertiesToUse_)
  24855. : list (listToEdit),
  24856. deadMansPedalFile (deadMansPedalFile_),
  24857. propertiesToUse (propertiesToUse_)
  24858. {
  24859. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  24860. addAndMakeVisible (optionsButton = new TextButton ("Options..."));
  24861. optionsButton->addButtonListener (this);
  24862. optionsButton->setTriggeredOnMouseDown (true);
  24863. setSize (400, 600);
  24864. list.addChangeListener (this);
  24865. changeListenerCallback (0);
  24866. }
  24867. PluginListComponent::~PluginListComponent()
  24868. {
  24869. list.removeChangeListener (this);
  24870. deleteAllChildren();
  24871. }
  24872. void PluginListComponent::resized()
  24873. {
  24874. listBox->setBounds (0, 0, getWidth(), getHeight() - 30);
  24875. optionsButton->changeWidthToFitText (24);
  24876. optionsButton->setTopLeftPosition (8, getHeight() - 28);
  24877. }
  24878. void PluginListComponent::changeListenerCallback (void*)
  24879. {
  24880. listBox->updateContent();
  24881. listBox->repaint();
  24882. }
  24883. int PluginListComponent::getNumRows()
  24884. {
  24885. return list.getNumTypes();
  24886. }
  24887. void PluginListComponent::paintListBoxItem (int row,
  24888. Graphics& g,
  24889. int width, int height,
  24890. bool rowIsSelected)
  24891. {
  24892. if (rowIsSelected)
  24893. g.fillAll (findColour (TextEditor::highlightColourId));
  24894. const PluginDescription* const pd = list.getType (row);
  24895. if (pd != 0)
  24896. {
  24897. GlyphArrangement ga;
  24898. ga.addCurtailedLineOfText (Font (height * 0.7f, Font::bold), pd->name, 8.0f, height * 0.8f, width - 10.0f, true);
  24899. g.setColour (Colours::black);
  24900. ga.draw (g);
  24901. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  24902. String desc;
  24903. desc << pd->pluginFormatName
  24904. << (pd->isInstrument ? " instrument" : " effect")
  24905. << " - "
  24906. << pd->numInputChannels << (pd->numInputChannels == 1 ? " in" : " ins")
  24907. << " / "
  24908. << pd->numOutputChannels << (pd->numOutputChannels == 1 ? " out" : " outs");
  24909. if (pd->manufacturerName.isNotEmpty())
  24910. desc << " - " << pd->manufacturerName;
  24911. if (pd->version.isNotEmpty())
  24912. desc << " - " << pd->version;
  24913. if (pd->category.isNotEmpty())
  24914. desc << " - category: '" << pd->category << '\'';
  24915. g.setColour (Colours::grey);
  24916. ga.clear();
  24917. ga.addCurtailedLineOfText (Font (height * 0.6f), desc, bb.getRight() + 10.0f, height * 0.8f, width - bb.getRight() - 12.0f, true);
  24918. ga.draw (g);
  24919. }
  24920. }
  24921. void PluginListComponent::deleteKeyPressed (int lastRowSelected)
  24922. {
  24923. list.removeType (lastRowSelected);
  24924. }
  24925. void PluginListComponent::buttonClicked (Button* b)
  24926. {
  24927. if (optionsButton == b)
  24928. {
  24929. PopupMenu menu;
  24930. menu.addItem (1, TRANS("Clear list"));
  24931. menu.addItem (5, TRANS("Remove selected plugin from list"), listBox->getNumSelectedRows() > 0);
  24932. menu.addItem (6, TRANS("Show folder containing selected plugin"), listBox->getNumSelectedRows() > 0);
  24933. menu.addItem (7, TRANS("Remove any plugins whose files no longer exist"));
  24934. menu.addSeparator();
  24935. menu.addItem (2, TRANS("Sort alphabetically"));
  24936. menu.addItem (3, TRANS("Sort by category"));
  24937. menu.addItem (4, TRANS("Sort by manufacturer"));
  24938. menu.addSeparator();
  24939. for (int i = 0; i < AudioPluginFormatManager::getInstance()->getNumFormats(); ++i)
  24940. {
  24941. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (i);
  24942. if (format->getDefaultLocationsToSearch().getNumPaths() > 0)
  24943. menu.addItem (10 + i, "Scan for new or updated " + format->getName() + " plugins...");
  24944. }
  24945. const int r = menu.showAt (optionsButton);
  24946. if (r == 1)
  24947. {
  24948. list.clear();
  24949. }
  24950. else if (r == 2)
  24951. {
  24952. list.sort (KnownPluginList::sortAlphabetically);
  24953. }
  24954. else if (r == 3)
  24955. {
  24956. list.sort (KnownPluginList::sortByCategory);
  24957. }
  24958. else if (r == 4)
  24959. {
  24960. list.sort (KnownPluginList::sortByManufacturer);
  24961. }
  24962. else if (r == 5)
  24963. {
  24964. const SparseSet <int> selected (listBox->getSelectedRows());
  24965. for (int i = list.getNumTypes(); --i >= 0;)
  24966. if (selected.contains (i))
  24967. list.removeType (i);
  24968. }
  24969. else if (r == 6)
  24970. {
  24971. const PluginDescription* const desc = list.getType (listBox->getSelectedRow());
  24972. if (desc != 0)
  24973. {
  24974. if (File (desc->fileOrIdentifier).existsAsFile())
  24975. File (desc->fileOrIdentifier).getParentDirectory().startAsProcess();
  24976. }
  24977. }
  24978. else if (r == 7)
  24979. {
  24980. for (int i = list.getNumTypes(); --i >= 0;)
  24981. {
  24982. if (! AudioPluginFormatManager::getInstance()->doesPluginStillExist (*list.getType (i)))
  24983. {
  24984. list.removeType (i);
  24985. }
  24986. }
  24987. }
  24988. else if (r != 0)
  24989. {
  24990. typeToScan = r - 10;
  24991. startTimer (1);
  24992. }
  24993. }
  24994. }
  24995. void PluginListComponent::timerCallback()
  24996. {
  24997. stopTimer();
  24998. scanFor (AudioPluginFormatManager::getInstance()->getFormat (typeToScan));
  24999. }
  25000. bool PluginListComponent::isInterestedInFileDrag (const StringArray& /*files*/)
  25001. {
  25002. return true;
  25003. }
  25004. void PluginListComponent::filesDropped (const StringArray& files, int, int)
  25005. {
  25006. OwnedArray <PluginDescription> typesFound;
  25007. list.scanAndAddDragAndDroppedFiles (files, typesFound);
  25008. }
  25009. void PluginListComponent::scanFor (AudioPluginFormat* format)
  25010. {
  25011. if (format == 0)
  25012. return;
  25013. FileSearchPath path (format->getDefaultLocationsToSearch());
  25014. if (propertiesToUse != 0)
  25015. path = propertiesToUse->getValue ("lastPluginScanPath_" + format->getName(), path.toString());
  25016. {
  25017. AlertWindow aw (TRANS("Select folders to scan..."), String::empty, AlertWindow::NoIcon);
  25018. FileSearchPathListComponent pathList;
  25019. pathList.setSize (500, 300);
  25020. pathList.setPath (path);
  25021. aw.addCustomComponent (&pathList);
  25022. aw.addButton (TRANS("Scan"), 1, KeyPress::returnKey);
  25023. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  25024. if (aw.runModalLoop() == 0)
  25025. return;
  25026. path = pathList.getPath();
  25027. }
  25028. if (propertiesToUse != 0)
  25029. {
  25030. propertiesToUse->setValue ("lastPluginScanPath_" + format->getName(), path.toString());
  25031. propertiesToUse->saveIfNeeded();
  25032. }
  25033. double progress = 0.0;
  25034. AlertWindow aw (TRANS("Scanning for plugins..."),
  25035. TRANS("Searching for all possible plugin files..."), AlertWindow::NoIcon);
  25036. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  25037. aw.addProgressBarComponent (progress);
  25038. aw.enterModalState();
  25039. MessageManager::getInstance()->runDispatchLoopUntil (300);
  25040. PluginDirectoryScanner scanner (list, *format, path, true, deadMansPedalFile);
  25041. for (;;)
  25042. {
  25043. aw.setMessage (TRANS("Testing:\n\n")
  25044. + scanner.getNextPluginFileThatWillBeScanned());
  25045. MessageManager::getInstance()->runDispatchLoopUntil (20);
  25046. if (! scanner.scanNextFile (true))
  25047. break;
  25048. if (! aw.isCurrentlyModal())
  25049. break;
  25050. progress = scanner.getProgress();
  25051. }
  25052. if (scanner.getFailedFiles().size() > 0)
  25053. {
  25054. StringArray shortNames;
  25055. for (int i = 0; i < scanner.getFailedFiles().size(); ++i)
  25056. shortNames.add (File (scanner.getFailedFiles()[i]).getFileName());
  25057. AlertWindow::showMessageBox (AlertWindow::InfoIcon,
  25058. TRANS("Scan complete"),
  25059. TRANS("Note that the following files appeared to be plugin files, but failed to load correctly:\n\n")
  25060. + shortNames.joinIntoString (", "));
  25061. }
  25062. }
  25063. END_JUCE_NAMESPACE
  25064. /*** End of inlined file: juce_PluginListComponent.cpp ***/
  25065. /*** Start of inlined file: juce_AudioUnitPluginFormat.mm ***/
  25066. #if JUCE_PLUGINHOST_AU && ! (JUCE_LINUX || JUCE_WINDOWS)
  25067. #include <AudioUnit/AudioUnit.h>
  25068. #include <AudioUnit/AUCocoaUIView.h>
  25069. #include <CoreAudioKit/AUGenericView.h>
  25070. #if JUCE_SUPPORT_CARBON
  25071. #include <AudioToolbox/AudioUnitUtilities.h>
  25072. #include <AudioUnit/AudioUnitCarbonView.h>
  25073. #endif
  25074. BEGIN_JUCE_NAMESPACE
  25075. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  25076. #endif
  25077. #if JUCE_MAC
  25078. // Change this to disable logging of various activities
  25079. #ifndef AU_LOGGING
  25080. #define AU_LOGGING 1
  25081. #endif
  25082. #if AU_LOGGING
  25083. #define log(a) Logger::writeToLog(a);
  25084. #else
  25085. #define log(a)
  25086. #endif
  25087. namespace AudioUnitFormatHelpers
  25088. {
  25089. static int insideCallback = 0;
  25090. static const String osTypeToString (OSType type)
  25091. {
  25092. char s[4];
  25093. s[0] = (char) (((uint32) type) >> 24);
  25094. s[1] = (char) (((uint32) type) >> 16);
  25095. s[2] = (char) (((uint32) type) >> 8);
  25096. s[3] = (char) ((uint32) type);
  25097. return String (s, 4);
  25098. }
  25099. static OSType stringToOSType (const String& s1)
  25100. {
  25101. const String s (s1 + " ");
  25102. return (((OSType) (unsigned char) s[0]) << 24)
  25103. | (((OSType) (unsigned char) s[1]) << 16)
  25104. | (((OSType) (unsigned char) s[2]) << 8)
  25105. | ((OSType) (unsigned char) s[3]);
  25106. }
  25107. static const char* auIdentifierPrefix = "AudioUnit:";
  25108. static const String createAUPluginIdentifier (const ComponentDescription& desc)
  25109. {
  25110. jassert (osTypeToString ('abcd') == "abcd"); // agh, must have got the endianness wrong..
  25111. jassert (stringToOSType ("abcd") == (OSType) 'abcd'); // ditto
  25112. String s (auIdentifierPrefix);
  25113. if (desc.componentType == kAudioUnitType_MusicDevice)
  25114. s << "Synths/";
  25115. else if (desc.componentType == kAudioUnitType_MusicEffect
  25116. || desc.componentType == kAudioUnitType_Effect)
  25117. s << "Effects/";
  25118. else if (desc.componentType == kAudioUnitType_Generator)
  25119. s << "Generators/";
  25120. else if (desc.componentType == kAudioUnitType_Panner)
  25121. s << "Panners/";
  25122. s << osTypeToString (desc.componentType) << ","
  25123. << osTypeToString (desc.componentSubType) << ","
  25124. << osTypeToString (desc.componentManufacturer);
  25125. return s;
  25126. }
  25127. static void getAUDetails (ComponentRecord* comp, String& name, String& manufacturer)
  25128. {
  25129. Handle componentNameHandle = NewHandle (sizeof (void*));
  25130. Handle componentInfoHandle = NewHandle (sizeof (void*));
  25131. if (componentNameHandle != 0 && componentInfoHandle != 0)
  25132. {
  25133. ComponentDescription desc;
  25134. if (GetComponentInfo (comp, &desc, componentNameHandle, componentInfoHandle, 0) == noErr)
  25135. {
  25136. ConstStr255Param nameString = (ConstStr255Param) (*componentNameHandle);
  25137. ConstStr255Param infoString = (ConstStr255Param) (*componentInfoHandle);
  25138. if (nameString != 0 && nameString[0] != 0)
  25139. {
  25140. const String all ((const char*) nameString + 1, nameString[0]);
  25141. DBG ("name: "+ all);
  25142. manufacturer = all.upToFirstOccurrenceOf (":", false, false).trim();
  25143. name = all.fromFirstOccurrenceOf (":", false, false).trim();
  25144. }
  25145. if (infoString != 0 && infoString[0] != 0)
  25146. {
  25147. DBG ("info: " + String ((const char*) infoString + 1, infoString[0]));
  25148. }
  25149. if (name.isEmpty())
  25150. name = "<Unknown>";
  25151. }
  25152. DisposeHandle (componentNameHandle);
  25153. DisposeHandle (componentInfoHandle);
  25154. }
  25155. }
  25156. static bool getComponentDescFromIdentifier (const String& fileOrIdentifier, ComponentDescription& desc,
  25157. String& name, String& version, String& manufacturer)
  25158. {
  25159. zerostruct (desc);
  25160. if (fileOrIdentifier.startsWithIgnoreCase (auIdentifierPrefix))
  25161. {
  25162. String s (fileOrIdentifier.substring (jmax (fileOrIdentifier.lastIndexOfChar (':'),
  25163. fileOrIdentifier.lastIndexOfChar ('/')) + 1));
  25164. StringArray tokens;
  25165. tokens.addTokens (s, ",", String::empty);
  25166. tokens.trim();
  25167. tokens.removeEmptyStrings();
  25168. if (tokens.size() == 3)
  25169. {
  25170. desc.componentType = stringToOSType (tokens[0]);
  25171. desc.componentSubType = stringToOSType (tokens[1]);
  25172. desc.componentManufacturer = stringToOSType (tokens[2]);
  25173. ComponentRecord* comp = FindNextComponent (0, &desc);
  25174. if (comp != 0)
  25175. {
  25176. getAUDetails (comp, name, manufacturer);
  25177. return true;
  25178. }
  25179. }
  25180. }
  25181. return false;
  25182. }
  25183. }
  25184. class AudioUnitPluginWindowCarbon;
  25185. class AudioUnitPluginWindowCocoa;
  25186. class AudioUnitPluginInstance : public AudioPluginInstance
  25187. {
  25188. public:
  25189. ~AudioUnitPluginInstance();
  25190. void initialise();
  25191. // AudioPluginInstance methods:
  25192. void fillInPluginDescription (PluginDescription& desc) const
  25193. {
  25194. desc.name = pluginName;
  25195. desc.fileOrIdentifier = AudioUnitFormatHelpers::createAUPluginIdentifier (componentDesc);
  25196. desc.uid = ((int) componentDesc.componentType)
  25197. ^ ((int) componentDesc.componentSubType)
  25198. ^ ((int) componentDesc.componentManufacturer);
  25199. desc.lastFileModTime = 0;
  25200. desc.pluginFormatName = "AudioUnit";
  25201. desc.category = getCategory();
  25202. desc.manufacturerName = manufacturer;
  25203. desc.version = version;
  25204. desc.numInputChannels = getNumInputChannels();
  25205. desc.numOutputChannels = getNumOutputChannels();
  25206. desc.isInstrument = (componentDesc.componentType == kAudioUnitType_MusicDevice);
  25207. }
  25208. const String getName() const { return pluginName; }
  25209. bool acceptsMidi() const { return wantsMidiMessages; }
  25210. bool producesMidi() const { return false; }
  25211. // AudioProcessor methods:
  25212. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  25213. void releaseResources();
  25214. void processBlock (AudioSampleBuffer& buffer,
  25215. MidiBuffer& midiMessages);
  25216. bool hasEditor() const;
  25217. AudioProcessorEditor* createEditor();
  25218. const String getInputChannelName (int index) const;
  25219. bool isInputChannelStereoPair (int index) const;
  25220. const String getOutputChannelName (int index) const;
  25221. bool isOutputChannelStereoPair (int index) const;
  25222. int getNumParameters();
  25223. float getParameter (int index);
  25224. void setParameter (int index, float newValue);
  25225. const String getParameterName (int index);
  25226. const String getParameterText (int index);
  25227. bool isParameterAutomatable (int index) const;
  25228. int getNumPrograms();
  25229. int getCurrentProgram();
  25230. void setCurrentProgram (int index);
  25231. const String getProgramName (int index);
  25232. void changeProgramName (int index, const String& newName);
  25233. void getStateInformation (MemoryBlock& destData);
  25234. void getCurrentProgramStateInformation (MemoryBlock& destData);
  25235. void setStateInformation (const void* data, int sizeInBytes);
  25236. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  25237. juce_UseDebuggingNewOperator
  25238. private:
  25239. friend class AudioUnitPluginWindowCarbon;
  25240. friend class AudioUnitPluginWindowCocoa;
  25241. friend class AudioUnitPluginFormat;
  25242. ComponentDescription componentDesc;
  25243. String pluginName, manufacturer, version;
  25244. String fileOrIdentifier;
  25245. CriticalSection lock;
  25246. bool wantsMidiMessages, wasPlaying, prepared;
  25247. HeapBlock <AudioBufferList> outputBufferList;
  25248. AudioTimeStamp timeStamp;
  25249. AudioSampleBuffer* currentBuffer;
  25250. AudioUnit audioUnit;
  25251. Array <int> parameterIds;
  25252. bool getComponentDescFromFile (const String& fileOrIdentifier);
  25253. void setPluginCallbacks();
  25254. void getParameterListFromPlugin();
  25255. OSStatus renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  25256. const AudioTimeStamp* inTimeStamp,
  25257. UInt32 inBusNumber,
  25258. UInt32 inNumberFrames,
  25259. AudioBufferList* ioData) const;
  25260. static OSStatus renderGetInputCallback (void* inRefCon,
  25261. AudioUnitRenderActionFlags* ioActionFlags,
  25262. const AudioTimeStamp* inTimeStamp,
  25263. UInt32 inBusNumber,
  25264. UInt32 inNumberFrames,
  25265. AudioBufferList* ioData)
  25266. {
  25267. return ((AudioUnitPluginInstance*) inRefCon)
  25268. ->renderGetInput (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  25269. }
  25270. OSStatus getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const;
  25271. OSStatus getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat, Float32* outTimeSig_Numerator,
  25272. UInt32* outTimeSig_Denominator, Float64* outCurrentMeasureDownBeat) const;
  25273. OSStatus getTransportState (Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  25274. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  25275. Float64* outCycleStartBeat, Float64* outCycleEndBeat);
  25276. static OSStatus getBeatAndTempoCallback (void* inHostUserData, Float64* outCurrentBeat, Float64* outCurrentTempo)
  25277. {
  25278. return ((AudioUnitPluginInstance*) inHostUserData)->getBeatAndTempo (outCurrentBeat, outCurrentTempo);
  25279. }
  25280. static OSStatus getMusicalTimeLocationCallback (void* inHostUserData, UInt32* outDeltaSampleOffsetToNextBeat,
  25281. Float32* outTimeSig_Numerator, UInt32* outTimeSig_Denominator,
  25282. Float64* outCurrentMeasureDownBeat)
  25283. {
  25284. return ((AudioUnitPluginInstance*) inHostUserData)
  25285. ->getMusicalTimeLocation (outDeltaSampleOffsetToNextBeat, outTimeSig_Numerator,
  25286. outTimeSig_Denominator, outCurrentMeasureDownBeat);
  25287. }
  25288. static OSStatus getTransportStateCallback (void* inHostUserData, Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  25289. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  25290. Float64* outCycleStartBeat, Float64* outCycleEndBeat)
  25291. {
  25292. return ((AudioUnitPluginInstance*) inHostUserData)
  25293. ->getTransportState (outIsPlaying, outTransportStateChanged,
  25294. outCurrentSampleInTimeLine, outIsCycling,
  25295. outCycleStartBeat, outCycleEndBeat);
  25296. }
  25297. void getNumChannels (int& numIns, int& numOuts)
  25298. {
  25299. numIns = 0;
  25300. numOuts = 0;
  25301. AUChannelInfo supportedChannels [128];
  25302. UInt32 supportedChannelsSize = sizeof (supportedChannels);
  25303. if (AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SupportedNumChannels, kAudioUnitScope_Global,
  25304. 0, supportedChannels, &supportedChannelsSize) == noErr
  25305. && supportedChannelsSize > 0)
  25306. {
  25307. int explicitNumIns = 0;
  25308. int explicitNumOuts = 0;
  25309. int maximumNumIns = 0;
  25310. int maximumNumOuts = 0;
  25311. for (int i = 0; i < supportedChannelsSize / sizeof (AUChannelInfo); ++i)
  25312. {
  25313. const int inChannels = (int) supportedChannels[i].inChannels;
  25314. const int outChannels = (int) supportedChannels[i].outChannels;
  25315. if (inChannels < 0)
  25316. maximumNumIns = jmin (maximumNumIns, inChannels);
  25317. else
  25318. explicitNumIns = jmax (explicitNumIns, inChannels);
  25319. if (outChannels < 0)
  25320. maximumNumOuts = jmin (maximumNumOuts, outChannels);
  25321. else
  25322. explicitNumOuts = jmax (explicitNumOuts, outChannels);
  25323. }
  25324. if ((maximumNumIns == -1 && maximumNumOuts == -1) // (special meaning: any number of ins/outs, as long as they match)
  25325. || (maximumNumIns == -2 && maximumNumOuts == -1) // (special meaning: any number of ins/outs, even if they don't match)
  25326. || (maximumNumIns == -1 && maximumNumOuts == -2))
  25327. {
  25328. numIns = numOuts = 2;
  25329. }
  25330. else
  25331. {
  25332. numIns = explicitNumIns;
  25333. numOuts = explicitNumOuts;
  25334. if (maximumNumIns == -1 || (maximumNumIns < 0 && explicitNumIns <= -maximumNumIns))
  25335. numIns = 2;
  25336. if (maximumNumOuts == -1 || (maximumNumOuts < 0 && explicitNumOuts <= -maximumNumOuts))
  25337. numOuts = 2;
  25338. }
  25339. }
  25340. else
  25341. {
  25342. // (this really means the plugin will take any number of ins/outs as long
  25343. // as they are the same)
  25344. numIns = numOuts = 2;
  25345. }
  25346. }
  25347. const String getCategory() const;
  25348. AudioUnitPluginInstance (const String& fileOrIdentifier);
  25349. };
  25350. AudioUnitPluginInstance::AudioUnitPluginInstance (const String& fileOrIdentifier)
  25351. : fileOrIdentifier (fileOrIdentifier),
  25352. wantsMidiMessages (false), wasPlaying (false), prepared (false),
  25353. audioUnit (0),
  25354. currentBuffer (0)
  25355. {
  25356. using namespace AudioUnitFormatHelpers;
  25357. try
  25358. {
  25359. ++insideCallback;
  25360. log ("Opening AU: " + fileOrIdentifier);
  25361. if (getComponentDescFromFile (fileOrIdentifier))
  25362. {
  25363. ComponentRecord* const comp = FindNextComponent (0, &componentDesc);
  25364. if (comp != 0)
  25365. {
  25366. audioUnit = (AudioUnit) OpenComponent (comp);
  25367. wantsMidiMessages = componentDesc.componentType == kAudioUnitType_MusicDevice
  25368. || componentDesc.componentType == kAudioUnitType_MusicEffect;
  25369. }
  25370. }
  25371. --insideCallback;
  25372. }
  25373. catch (...)
  25374. {
  25375. --insideCallback;
  25376. }
  25377. }
  25378. AudioUnitPluginInstance::~AudioUnitPluginInstance()
  25379. {
  25380. const ScopedLock sl (lock);
  25381. jassert (AudioUnitFormatHelpers::insideCallback == 0);
  25382. if (audioUnit != 0)
  25383. {
  25384. AudioUnitUninitialize (audioUnit);
  25385. CloseComponent (audioUnit);
  25386. audioUnit = 0;
  25387. }
  25388. }
  25389. bool AudioUnitPluginInstance::getComponentDescFromFile (const String& fileOrIdentifier)
  25390. {
  25391. zerostruct (componentDesc);
  25392. if (AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, componentDesc, pluginName, version, manufacturer))
  25393. return true;
  25394. const File file (fileOrIdentifier);
  25395. if (! file.hasFileExtension (".component"))
  25396. return false;
  25397. const char* const utf8 = fileOrIdentifier.toUTF8();
  25398. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  25399. strlen (utf8), file.isDirectory());
  25400. if (url != 0)
  25401. {
  25402. CFBundleRef bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  25403. CFRelease (url);
  25404. if (bundleRef != 0)
  25405. {
  25406. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  25407. if (name != 0 && CFGetTypeID (name) == CFStringGetTypeID())
  25408. pluginName = PlatformUtilities::cfStringToJuceString ((CFStringRef) name);
  25409. if (pluginName.isEmpty())
  25410. pluginName = file.getFileNameWithoutExtension();
  25411. CFTypeRef versionString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleVersion"));
  25412. if (versionString != 0 && CFGetTypeID (versionString) == CFStringGetTypeID())
  25413. version = PlatformUtilities::cfStringToJuceString ((CFStringRef) versionString);
  25414. CFTypeRef manuString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleGetInfoString"));
  25415. if (manuString != 0 && CFGetTypeID (manuString) == CFStringGetTypeID())
  25416. manufacturer = PlatformUtilities::cfStringToJuceString ((CFStringRef) manuString);
  25417. short resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  25418. UseResFile (resFileId);
  25419. for (int i = 1; i <= Count1Resources ('thng'); ++i)
  25420. {
  25421. Handle h = Get1IndResource ('thng', i);
  25422. if (h != 0)
  25423. {
  25424. HLock (h);
  25425. const uint32* const types = (const uint32*) *h;
  25426. if (types[0] == kAudioUnitType_MusicDevice
  25427. || types[0] == kAudioUnitType_MusicEffect
  25428. || types[0] == kAudioUnitType_Effect
  25429. || types[0] == kAudioUnitType_Generator
  25430. || types[0] == kAudioUnitType_Panner)
  25431. {
  25432. componentDesc.componentType = types[0];
  25433. componentDesc.componentSubType = types[1];
  25434. componentDesc.componentManufacturer = types[2];
  25435. break;
  25436. }
  25437. HUnlock (h);
  25438. ReleaseResource (h);
  25439. }
  25440. }
  25441. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  25442. CFRelease (bundleRef);
  25443. }
  25444. }
  25445. return componentDesc.componentType != 0 && componentDesc.componentSubType != 0;
  25446. }
  25447. void AudioUnitPluginInstance::initialise()
  25448. {
  25449. getParameterListFromPlugin();
  25450. setPluginCallbacks();
  25451. int numIns, numOuts;
  25452. getNumChannels (numIns, numOuts);
  25453. setPlayConfigDetails (numIns, numOuts, 0, 0);
  25454. setLatencySamples (0);
  25455. }
  25456. void AudioUnitPluginInstance::getParameterListFromPlugin()
  25457. {
  25458. parameterIds.clear();
  25459. if (audioUnit != 0)
  25460. {
  25461. UInt32 paramListSize = 0;
  25462. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  25463. 0, 0, &paramListSize);
  25464. if (paramListSize > 0)
  25465. {
  25466. parameterIds.insertMultiple (0, 0, paramListSize / sizeof (int));
  25467. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  25468. 0, &parameterIds.getReference(0), &paramListSize);
  25469. }
  25470. }
  25471. }
  25472. void AudioUnitPluginInstance::setPluginCallbacks()
  25473. {
  25474. if (audioUnit != 0)
  25475. {
  25476. {
  25477. AURenderCallbackStruct info;
  25478. zerostruct (info);
  25479. info.inputProcRefCon = this;
  25480. info.inputProc = renderGetInputCallback;
  25481. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
  25482. 0, &info, sizeof (info));
  25483. }
  25484. {
  25485. HostCallbackInfo info;
  25486. zerostruct (info);
  25487. info.hostUserData = this;
  25488. info.beatAndTempoProc = getBeatAndTempoCallback;
  25489. info.musicalTimeLocationProc = getMusicalTimeLocationCallback;
  25490. info.transportStateProc = getTransportStateCallback;
  25491. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_HostCallbacks, kAudioUnitScope_Global,
  25492. 0, &info, sizeof (info));
  25493. }
  25494. }
  25495. }
  25496. void AudioUnitPluginInstance::prepareToPlay (double sampleRate_,
  25497. int samplesPerBlockExpected)
  25498. {
  25499. if (audioUnit != 0)
  25500. {
  25501. releaseResources();
  25502. Float64 sampleRateIn = 0, sampleRateOut = 0;
  25503. UInt32 sampleRateSize = sizeof (sampleRateIn);
  25504. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sampleRateIn, &sampleRateSize);
  25505. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sampleRateOut, &sampleRateSize);
  25506. if (sampleRateIn != sampleRate_ || sampleRateOut != sampleRate_)
  25507. {
  25508. Float64 sr = sampleRate_;
  25509. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sr, sizeof (Float64));
  25510. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sr, sizeof (Float64));
  25511. }
  25512. int numIns, numOuts;
  25513. getNumChannels (numIns, numOuts);
  25514. setPlayConfigDetails (numIns, numOuts, sampleRate_, samplesPerBlockExpected);
  25515. Float64 latencySecs = 0.0;
  25516. UInt32 latencySize = sizeof (latencySecs);
  25517. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_Latency, kAudioUnitScope_Global,
  25518. 0, &latencySecs, &latencySize);
  25519. setLatencySamples (roundToInt (latencySecs * sampleRate_));
  25520. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  25521. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  25522. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  25523. {
  25524. AudioStreamBasicDescription stream;
  25525. zerostruct (stream);
  25526. stream.mSampleRate = sampleRate_;
  25527. stream.mFormatID = kAudioFormatLinearPCM;
  25528. stream.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved;
  25529. stream.mFramesPerPacket = 1;
  25530. stream.mBytesPerPacket = 4;
  25531. stream.mBytesPerFrame = 4;
  25532. stream.mBitsPerChannel = 32;
  25533. stream.mChannelsPerFrame = numIns;
  25534. OSStatus err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input,
  25535. 0, &stream, sizeof (stream));
  25536. stream.mChannelsPerFrame = numOuts;
  25537. err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output,
  25538. 0, &stream, sizeof (stream));
  25539. }
  25540. outputBufferList.calloc (sizeof (AudioBufferList) + sizeof (AudioBuffer) * (numOuts + 1), 1);
  25541. outputBufferList->mNumberBuffers = numOuts;
  25542. for (int i = numOuts; --i >= 0;)
  25543. outputBufferList->mBuffers[i].mNumberChannels = 1;
  25544. zerostruct (timeStamp);
  25545. timeStamp.mSampleTime = 0;
  25546. timeStamp.mHostTime = AudioGetCurrentHostTime();
  25547. timeStamp.mFlags = kAudioTimeStampSampleTimeValid | kAudioTimeStampHostTimeValid;
  25548. currentBuffer = 0;
  25549. wasPlaying = false;
  25550. prepared = (AudioUnitInitialize (audioUnit) == noErr);
  25551. }
  25552. }
  25553. void AudioUnitPluginInstance::releaseResources()
  25554. {
  25555. if (prepared)
  25556. {
  25557. AudioUnitUninitialize (audioUnit);
  25558. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  25559. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  25560. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  25561. outputBufferList.free();
  25562. currentBuffer = 0;
  25563. prepared = false;
  25564. }
  25565. }
  25566. OSStatus AudioUnitPluginInstance::renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  25567. const AudioTimeStamp* inTimeStamp,
  25568. UInt32 inBusNumber,
  25569. UInt32 inNumberFrames,
  25570. AudioBufferList* ioData) const
  25571. {
  25572. if (inBusNumber == 0
  25573. && currentBuffer != 0)
  25574. {
  25575. jassert (inNumberFrames == currentBuffer->getNumSamples()); // if this ever happens, might need to add extra handling
  25576. for (int i = 0; i < ioData->mNumberBuffers; ++i)
  25577. {
  25578. if (i < currentBuffer->getNumChannels())
  25579. {
  25580. memcpy (ioData->mBuffers[i].mData,
  25581. currentBuffer->getSampleData (i, 0),
  25582. sizeof (float) * inNumberFrames);
  25583. }
  25584. else
  25585. {
  25586. zeromem (ioData->mBuffers[i].mData, sizeof (float) * inNumberFrames);
  25587. }
  25588. }
  25589. }
  25590. return noErr;
  25591. }
  25592. void AudioUnitPluginInstance::processBlock (AudioSampleBuffer& buffer,
  25593. MidiBuffer& midiMessages)
  25594. {
  25595. const int numSamples = buffer.getNumSamples();
  25596. if (prepared)
  25597. {
  25598. AudioUnitRenderActionFlags flags = 0;
  25599. timeStamp.mHostTime = AudioGetCurrentHostTime();
  25600. for (int i = getNumOutputChannels(); --i >= 0;)
  25601. {
  25602. outputBufferList->mBuffers[i].mDataByteSize = sizeof (float) * numSamples;
  25603. outputBufferList->mBuffers[i].mData = buffer.getSampleData (i, 0);
  25604. }
  25605. currentBuffer = &buffer;
  25606. if (wantsMidiMessages)
  25607. {
  25608. const uint8* midiEventData;
  25609. int midiEventSize, midiEventPosition;
  25610. MidiBuffer::Iterator i (midiMessages);
  25611. while (i.getNextEvent (midiEventData, midiEventSize, midiEventPosition))
  25612. {
  25613. if (midiEventSize <= 3)
  25614. MusicDeviceMIDIEvent (audioUnit,
  25615. midiEventData[0], midiEventData[1], midiEventData[2],
  25616. midiEventPosition);
  25617. else
  25618. MusicDeviceSysEx (audioUnit, midiEventData, midiEventSize);
  25619. }
  25620. midiMessages.clear();
  25621. }
  25622. AudioUnitRender (audioUnit, &flags, &timeStamp,
  25623. 0, numSamples, outputBufferList);
  25624. timeStamp.mSampleTime += numSamples;
  25625. }
  25626. else
  25627. {
  25628. // Plugin not working correctly, so just bypass..
  25629. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  25630. buffer.clear (i, 0, buffer.getNumSamples());
  25631. }
  25632. }
  25633. OSStatus AudioUnitPluginInstance::getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const
  25634. {
  25635. AudioPlayHead* const ph = getPlayHead();
  25636. AudioPlayHead::CurrentPositionInfo result;
  25637. if (ph != 0 && ph->getCurrentPosition (result))
  25638. {
  25639. if (outCurrentBeat != 0)
  25640. *outCurrentBeat = result.ppqPosition;
  25641. if (outCurrentTempo != 0)
  25642. *outCurrentTempo = result.bpm;
  25643. }
  25644. else
  25645. {
  25646. if (outCurrentBeat != 0)
  25647. *outCurrentBeat = 0;
  25648. if (outCurrentTempo != 0)
  25649. *outCurrentTempo = 120.0;
  25650. }
  25651. return noErr;
  25652. }
  25653. OSStatus AudioUnitPluginInstance::getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat,
  25654. Float32* outTimeSig_Numerator,
  25655. UInt32* outTimeSig_Denominator,
  25656. Float64* outCurrentMeasureDownBeat) const
  25657. {
  25658. AudioPlayHead* const ph = getPlayHead();
  25659. AudioPlayHead::CurrentPositionInfo result;
  25660. if (ph != 0 && ph->getCurrentPosition (result))
  25661. {
  25662. if (outTimeSig_Numerator != 0)
  25663. *outTimeSig_Numerator = result.timeSigNumerator;
  25664. if (outTimeSig_Denominator != 0)
  25665. *outTimeSig_Denominator = result.timeSigDenominator;
  25666. if (outDeltaSampleOffsetToNextBeat != 0)
  25667. *outDeltaSampleOffsetToNextBeat = 0; //xxx
  25668. if (outCurrentMeasureDownBeat != 0)
  25669. *outCurrentMeasureDownBeat = result.ppqPositionOfLastBarStart; //xxx wrong
  25670. }
  25671. else
  25672. {
  25673. if (outDeltaSampleOffsetToNextBeat != 0)
  25674. *outDeltaSampleOffsetToNextBeat = 0;
  25675. if (outTimeSig_Numerator != 0)
  25676. *outTimeSig_Numerator = 4;
  25677. if (outTimeSig_Denominator != 0)
  25678. *outTimeSig_Denominator = 4;
  25679. if (outCurrentMeasureDownBeat != 0)
  25680. *outCurrentMeasureDownBeat = 0;
  25681. }
  25682. return noErr;
  25683. }
  25684. OSStatus AudioUnitPluginInstance::getTransportState (Boolean* outIsPlaying,
  25685. Boolean* outTransportStateChanged,
  25686. Float64* outCurrentSampleInTimeLine,
  25687. Boolean* outIsCycling,
  25688. Float64* outCycleStartBeat,
  25689. Float64* outCycleEndBeat)
  25690. {
  25691. AudioPlayHead* const ph = getPlayHead();
  25692. AudioPlayHead::CurrentPositionInfo result;
  25693. if (ph != 0 && ph->getCurrentPosition (result))
  25694. {
  25695. if (outIsPlaying != 0)
  25696. *outIsPlaying = result.isPlaying;
  25697. if (outTransportStateChanged != 0)
  25698. {
  25699. *outTransportStateChanged = result.isPlaying != wasPlaying;
  25700. wasPlaying = result.isPlaying;
  25701. }
  25702. if (outCurrentSampleInTimeLine != 0)
  25703. *outCurrentSampleInTimeLine = roundToInt (result.timeInSeconds * getSampleRate());
  25704. if (outIsCycling != 0)
  25705. *outIsCycling = false;
  25706. if (outCycleStartBeat != 0)
  25707. *outCycleStartBeat = 0;
  25708. if (outCycleEndBeat != 0)
  25709. *outCycleEndBeat = 0;
  25710. }
  25711. else
  25712. {
  25713. if (outIsPlaying != 0)
  25714. *outIsPlaying = false;
  25715. if (outTransportStateChanged != 0)
  25716. *outTransportStateChanged = false;
  25717. if (outCurrentSampleInTimeLine != 0)
  25718. *outCurrentSampleInTimeLine = 0;
  25719. if (outIsCycling != 0)
  25720. *outIsCycling = false;
  25721. if (outCycleStartBeat != 0)
  25722. *outCycleStartBeat = 0;
  25723. if (outCycleEndBeat != 0)
  25724. *outCycleEndBeat = 0;
  25725. }
  25726. return noErr;
  25727. }
  25728. class AudioUnitPluginWindowCocoa : public AudioProcessorEditor,
  25729. public Timer
  25730. {
  25731. public:
  25732. AudioUnitPluginWindowCocoa (AudioUnitPluginInstance& plugin_, const bool createGenericViewIfNeeded)
  25733. : AudioProcessorEditor (&plugin_),
  25734. plugin (plugin_)
  25735. {
  25736. addAndMakeVisible (&wrapper);
  25737. setOpaque (true);
  25738. setVisible (true);
  25739. setSize (100, 100);
  25740. createView (createGenericViewIfNeeded);
  25741. }
  25742. ~AudioUnitPluginWindowCocoa()
  25743. {
  25744. const bool wasValid = isValid();
  25745. wrapper.setView (0);
  25746. if (wasValid)
  25747. plugin.editorBeingDeleted (this);
  25748. }
  25749. bool isValid() const { return wrapper.getView() != 0; }
  25750. void paint (Graphics& g)
  25751. {
  25752. g.fillAll (Colours::white);
  25753. }
  25754. void resized()
  25755. {
  25756. wrapper.setSize (getWidth(), getHeight());
  25757. }
  25758. void timerCallback()
  25759. {
  25760. wrapper.resizeToFitView();
  25761. startTimer (jmin (713, getTimerInterval() + 51));
  25762. }
  25763. void childBoundsChanged (Component* child)
  25764. {
  25765. setSize (wrapper.getWidth(), wrapper.getHeight());
  25766. startTimer (70);
  25767. }
  25768. private:
  25769. AudioUnitPluginInstance& plugin;
  25770. NSViewComponent wrapper;
  25771. bool createView (const bool createGenericViewIfNeeded)
  25772. {
  25773. NSView* pluginView = 0;
  25774. UInt32 dataSize = 0;
  25775. Boolean isWritable = false;
  25776. AudioUnitInitialize (plugin.audioUnit);
  25777. if (AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25778. 0, &dataSize, &isWritable) == noErr
  25779. && dataSize != 0
  25780. && AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25781. 0, &dataSize, &isWritable) == noErr)
  25782. {
  25783. HeapBlock <AudioUnitCocoaViewInfo> info;
  25784. info.calloc (dataSize, 1);
  25785. if (AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25786. 0, info, &dataSize) == noErr)
  25787. {
  25788. NSString* viewClassName = (NSString*) (info->mCocoaAUViewClass[0]);
  25789. NSString* path = (NSString*) CFURLCopyPath (info->mCocoaAUViewBundleLocation);
  25790. NSBundle* viewBundle = [NSBundle bundleWithPath: [path autorelease]];
  25791. Class viewClass = [viewBundle classNamed: viewClassName];
  25792. if ([viewClass conformsToProtocol: @protocol (AUCocoaUIBase)]
  25793. && [viewClass instancesRespondToSelector: @selector (interfaceVersion)]
  25794. && [viewClass instancesRespondToSelector: @selector (uiViewForAudioUnit: withSize:)])
  25795. {
  25796. id factory = [[[viewClass alloc] init] autorelease];
  25797. pluginView = [factory uiViewForAudioUnit: plugin.audioUnit
  25798. withSize: NSMakeSize (getWidth(), getHeight())];
  25799. }
  25800. for (int i = (dataSize - sizeof (CFURLRef)) / sizeof (CFStringRef); --i >= 0;)
  25801. CFRelease (info->mCocoaAUViewClass[i]);
  25802. CFRelease (info->mCocoaAUViewBundleLocation);
  25803. }
  25804. }
  25805. if (createGenericViewIfNeeded && (pluginView == 0))
  25806. pluginView = [[AUGenericView alloc] initWithAudioUnit: plugin.audioUnit];
  25807. wrapper.setView (pluginView);
  25808. if (pluginView != 0)
  25809. {
  25810. timerCallback();
  25811. startTimer (70);
  25812. }
  25813. return pluginView != 0;
  25814. }
  25815. };
  25816. #if JUCE_SUPPORT_CARBON
  25817. class AudioUnitPluginWindowCarbon : public AudioProcessorEditor
  25818. {
  25819. public:
  25820. AudioUnitPluginWindowCarbon (AudioUnitPluginInstance& plugin_)
  25821. : AudioProcessorEditor (&plugin_),
  25822. plugin (plugin_),
  25823. viewComponent (0)
  25824. {
  25825. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  25826. setOpaque (true);
  25827. setVisible (true);
  25828. setSize (400, 300);
  25829. ComponentDescription viewList [16];
  25830. UInt32 viewListSize = sizeof (viewList);
  25831. AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global,
  25832. 0, &viewList, &viewListSize);
  25833. componentRecord = FindNextComponent (0, &viewList[0]);
  25834. }
  25835. ~AudioUnitPluginWindowCarbon()
  25836. {
  25837. innerWrapper = 0;
  25838. if (isValid())
  25839. plugin.editorBeingDeleted (this);
  25840. }
  25841. bool isValid() const throw() { return componentRecord != 0; }
  25842. void paint (Graphics& g)
  25843. {
  25844. g.fillAll (Colours::black);
  25845. }
  25846. void resized()
  25847. {
  25848. innerWrapper->setSize (getWidth(), getHeight());
  25849. }
  25850. bool keyStateChanged (bool)
  25851. {
  25852. return false;
  25853. }
  25854. bool keyPressed (const KeyPress&)
  25855. {
  25856. return false;
  25857. }
  25858. AudioUnit getAudioUnit() const { return plugin.audioUnit; }
  25859. AudioUnitCarbonView getViewComponent()
  25860. {
  25861. if (viewComponent == 0 && componentRecord != 0)
  25862. viewComponent = (AudioUnitCarbonView) OpenComponent (componentRecord);
  25863. return viewComponent;
  25864. }
  25865. void closeViewComponent()
  25866. {
  25867. if (viewComponent != 0)
  25868. {
  25869. log ("Closing AU GUI: " + plugin.getName());
  25870. CloseComponent (viewComponent);
  25871. viewComponent = 0;
  25872. }
  25873. }
  25874. juce_UseDebuggingNewOperator
  25875. private:
  25876. AudioUnitPluginInstance& plugin;
  25877. ComponentRecord* componentRecord;
  25878. AudioUnitCarbonView viewComponent;
  25879. class InnerWrapperComponent : public CarbonViewWrapperComponent
  25880. {
  25881. public:
  25882. InnerWrapperComponent (AudioUnitPluginWindowCarbon* const owner_)
  25883. : owner (owner_)
  25884. {
  25885. }
  25886. ~InnerWrapperComponent()
  25887. {
  25888. deleteWindow();
  25889. }
  25890. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  25891. {
  25892. log ("Opening AU GUI: " + owner->plugin.getName());
  25893. AudioUnitCarbonView viewComponent = owner->getViewComponent();
  25894. if (viewComponent == 0)
  25895. return 0;
  25896. Float32Point pos = { 0, 0 };
  25897. Float32Point size = { 250, 200 };
  25898. HIViewRef pluginView = 0;
  25899. AudioUnitCarbonViewCreate (viewComponent,
  25900. owner->getAudioUnit(),
  25901. windowRef,
  25902. rootView,
  25903. &pos,
  25904. &size,
  25905. (ControlRef*) &pluginView);
  25906. return pluginView;
  25907. }
  25908. void removeView (HIViewRef)
  25909. {
  25910. owner->closeViewComponent();
  25911. }
  25912. private:
  25913. AudioUnitPluginWindowCarbon* const owner;
  25914. };
  25915. friend class InnerWrapperComponent;
  25916. ScopedPointer<InnerWrapperComponent> innerWrapper;
  25917. };
  25918. #endif
  25919. bool AudioUnitPluginInstance::hasEditor() const
  25920. {
  25921. return true;
  25922. }
  25923. AudioProcessorEditor* AudioUnitPluginInstance::createEditor()
  25924. {
  25925. ScopedPointer<AudioProcessorEditor> w (new AudioUnitPluginWindowCocoa (*this, false));
  25926. if (! static_cast <AudioUnitPluginWindowCocoa*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  25927. w = 0;
  25928. #if JUCE_SUPPORT_CARBON
  25929. if (w == 0)
  25930. {
  25931. w = new AudioUnitPluginWindowCarbon (*this);
  25932. if (! static_cast <AudioUnitPluginWindowCarbon*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  25933. w = 0;
  25934. }
  25935. #endif
  25936. if (w == 0)
  25937. w = new AudioUnitPluginWindowCocoa (*this, true); // use AUGenericView as a fallback
  25938. return w.release();
  25939. }
  25940. const String AudioUnitPluginInstance::getCategory() const
  25941. {
  25942. const char* result = 0;
  25943. switch (componentDesc.componentType)
  25944. {
  25945. case kAudioUnitType_Effect:
  25946. case kAudioUnitType_MusicEffect:
  25947. result = "Effect";
  25948. break;
  25949. case kAudioUnitType_MusicDevice:
  25950. result = "Synth";
  25951. break;
  25952. case kAudioUnitType_Generator:
  25953. result = "Generator";
  25954. break;
  25955. case kAudioUnitType_Panner:
  25956. result = "Panner";
  25957. break;
  25958. default:
  25959. break;
  25960. }
  25961. return result;
  25962. }
  25963. int AudioUnitPluginInstance::getNumParameters()
  25964. {
  25965. return parameterIds.size();
  25966. }
  25967. float AudioUnitPluginInstance::getParameter (int index)
  25968. {
  25969. const ScopedLock sl (lock);
  25970. Float32 value = 0.0f;
  25971. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  25972. {
  25973. AudioUnitGetParameter (audioUnit,
  25974. (UInt32) parameterIds.getUnchecked (index),
  25975. kAudioUnitScope_Global, 0,
  25976. &value);
  25977. }
  25978. return value;
  25979. }
  25980. void AudioUnitPluginInstance::setParameter (int index, float newValue)
  25981. {
  25982. const ScopedLock sl (lock);
  25983. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  25984. {
  25985. AudioUnitSetParameter (audioUnit,
  25986. (UInt32) parameterIds.getUnchecked (index),
  25987. kAudioUnitScope_Global, 0,
  25988. newValue, 0);
  25989. }
  25990. }
  25991. const String AudioUnitPluginInstance::getParameterName (int index)
  25992. {
  25993. AudioUnitParameterInfo info;
  25994. zerostruct (info);
  25995. UInt32 sz = sizeof (info);
  25996. String name;
  25997. if (AudioUnitGetProperty (audioUnit,
  25998. kAudioUnitProperty_ParameterInfo,
  25999. kAudioUnitScope_Global,
  26000. parameterIds [index], &info, &sz) == noErr)
  26001. {
  26002. if ((info.flags & kAudioUnitParameterFlag_HasCFNameString) != 0)
  26003. name = PlatformUtilities::cfStringToJuceString (info.cfNameString);
  26004. else
  26005. name = String (info.name, sizeof (info.name));
  26006. }
  26007. return name;
  26008. }
  26009. const String AudioUnitPluginInstance::getParameterText (int index)
  26010. {
  26011. return String (getParameter (index));
  26012. }
  26013. bool AudioUnitPluginInstance::isParameterAutomatable (int index) const
  26014. {
  26015. AudioUnitParameterInfo info;
  26016. UInt32 sz = sizeof (info);
  26017. if (AudioUnitGetProperty (audioUnit,
  26018. kAudioUnitProperty_ParameterInfo,
  26019. kAudioUnitScope_Global,
  26020. parameterIds [index], &info, &sz) == noErr)
  26021. {
  26022. return (info.flags & kAudioUnitParameterFlag_NonRealTime) == 0;
  26023. }
  26024. return true;
  26025. }
  26026. int AudioUnitPluginInstance::getNumPrograms()
  26027. {
  26028. CFArrayRef presets;
  26029. UInt32 sz = sizeof (CFArrayRef);
  26030. int num = 0;
  26031. if (AudioUnitGetProperty (audioUnit,
  26032. kAudioUnitProperty_FactoryPresets,
  26033. kAudioUnitScope_Global,
  26034. 0, &presets, &sz) == noErr)
  26035. {
  26036. num = (int) CFArrayGetCount (presets);
  26037. CFRelease (presets);
  26038. }
  26039. return num;
  26040. }
  26041. int AudioUnitPluginInstance::getCurrentProgram()
  26042. {
  26043. AUPreset current;
  26044. current.presetNumber = 0;
  26045. UInt32 sz = sizeof (AUPreset);
  26046. AudioUnitGetProperty (audioUnit,
  26047. kAudioUnitProperty_FactoryPresets,
  26048. kAudioUnitScope_Global,
  26049. 0, &current, &sz);
  26050. return current.presetNumber;
  26051. }
  26052. void AudioUnitPluginInstance::setCurrentProgram (int newIndex)
  26053. {
  26054. AUPreset current;
  26055. current.presetNumber = newIndex;
  26056. current.presetName = 0;
  26057. AudioUnitSetProperty (audioUnit,
  26058. kAudioUnitProperty_FactoryPresets,
  26059. kAudioUnitScope_Global,
  26060. 0, &current, sizeof (AUPreset));
  26061. }
  26062. const String AudioUnitPluginInstance::getProgramName (int index)
  26063. {
  26064. String s;
  26065. CFArrayRef presets;
  26066. UInt32 sz = sizeof (CFArrayRef);
  26067. if (AudioUnitGetProperty (audioUnit,
  26068. kAudioUnitProperty_FactoryPresets,
  26069. kAudioUnitScope_Global,
  26070. 0, &presets, &sz) == noErr)
  26071. {
  26072. for (CFIndex i = 0; i < CFArrayGetCount (presets); ++i)
  26073. {
  26074. const AUPreset* p = (const AUPreset*) CFArrayGetValueAtIndex (presets, i);
  26075. if (p != 0 && p->presetNumber == index)
  26076. {
  26077. s = PlatformUtilities::cfStringToJuceString (p->presetName);
  26078. break;
  26079. }
  26080. }
  26081. CFRelease (presets);
  26082. }
  26083. return s;
  26084. }
  26085. void AudioUnitPluginInstance::changeProgramName (int index, const String& newName)
  26086. {
  26087. jassertfalse; // xxx not implemented!
  26088. }
  26089. const String AudioUnitPluginInstance::getInputChannelName (int index) const
  26090. {
  26091. if (((unsigned int) index) < (unsigned int) getNumInputChannels())
  26092. return "Input " + String (index + 1);
  26093. return String::empty;
  26094. }
  26095. bool AudioUnitPluginInstance::isInputChannelStereoPair (int index) const
  26096. {
  26097. if (((unsigned int) index) >= (unsigned int) getNumInputChannels())
  26098. return false;
  26099. return true;
  26100. }
  26101. const String AudioUnitPluginInstance::getOutputChannelName (int index) const
  26102. {
  26103. if (((unsigned int) index) < (unsigned int) getNumOutputChannels())
  26104. return "Output " + String (index + 1);
  26105. return String::empty;
  26106. }
  26107. bool AudioUnitPluginInstance::isOutputChannelStereoPair (int index) const
  26108. {
  26109. if (((unsigned int) index) >= (unsigned int) getNumOutputChannels())
  26110. return false;
  26111. return true;
  26112. }
  26113. void AudioUnitPluginInstance::getStateInformation (MemoryBlock& destData)
  26114. {
  26115. getCurrentProgramStateInformation (destData);
  26116. }
  26117. void AudioUnitPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  26118. {
  26119. CFPropertyListRef propertyList = 0;
  26120. UInt32 sz = sizeof (CFPropertyListRef);
  26121. if (AudioUnitGetProperty (audioUnit,
  26122. kAudioUnitProperty_ClassInfo,
  26123. kAudioUnitScope_Global,
  26124. 0, &propertyList, &sz) == noErr)
  26125. {
  26126. CFWriteStreamRef stream = CFWriteStreamCreateWithAllocatedBuffers (kCFAllocatorDefault, kCFAllocatorDefault);
  26127. CFWriteStreamOpen (stream);
  26128. CFIndex bytesWritten = CFPropertyListWriteToStream (propertyList, stream, kCFPropertyListBinaryFormat_v1_0, 0);
  26129. CFWriteStreamClose (stream);
  26130. CFDataRef data = (CFDataRef) CFWriteStreamCopyProperty (stream, kCFStreamPropertyDataWritten);
  26131. destData.setSize (bytesWritten);
  26132. destData.copyFrom (CFDataGetBytePtr (data), 0, destData.getSize());
  26133. CFRelease (data);
  26134. CFRelease (stream);
  26135. CFRelease (propertyList);
  26136. }
  26137. }
  26138. void AudioUnitPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  26139. {
  26140. setCurrentProgramStateInformation (data, sizeInBytes);
  26141. }
  26142. void AudioUnitPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  26143. {
  26144. CFReadStreamRef stream = CFReadStreamCreateWithBytesNoCopy (kCFAllocatorDefault,
  26145. (const UInt8*) data,
  26146. sizeInBytes,
  26147. kCFAllocatorNull);
  26148. CFReadStreamOpen (stream);
  26149. CFPropertyListFormat format = kCFPropertyListBinaryFormat_v1_0;
  26150. CFPropertyListRef propertyList = CFPropertyListCreateFromStream (kCFAllocatorDefault,
  26151. stream,
  26152. 0,
  26153. kCFPropertyListImmutable,
  26154. &format,
  26155. 0);
  26156. CFRelease (stream);
  26157. if (propertyList != 0)
  26158. AudioUnitSetProperty (audioUnit,
  26159. kAudioUnitProperty_ClassInfo,
  26160. kAudioUnitScope_Global,
  26161. 0, &propertyList, sizeof (propertyList));
  26162. }
  26163. AudioUnitPluginFormat::AudioUnitPluginFormat()
  26164. {
  26165. }
  26166. AudioUnitPluginFormat::~AudioUnitPluginFormat()
  26167. {
  26168. }
  26169. void AudioUnitPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  26170. const String& fileOrIdentifier)
  26171. {
  26172. if (! fileMightContainThisPluginType (fileOrIdentifier))
  26173. return;
  26174. PluginDescription desc;
  26175. desc.fileOrIdentifier = fileOrIdentifier;
  26176. desc.uid = 0;
  26177. try
  26178. {
  26179. ScopedPointer <AudioPluginInstance> createdInstance (createInstanceFromDescription (desc));
  26180. AudioUnitPluginInstance* const auInstance = dynamic_cast <AudioUnitPluginInstance*> ((AudioPluginInstance*) createdInstance);
  26181. if (auInstance != 0)
  26182. {
  26183. auInstance->fillInPluginDescription (desc);
  26184. results.add (new PluginDescription (desc));
  26185. }
  26186. }
  26187. catch (...)
  26188. {
  26189. // crashed while loading...
  26190. }
  26191. }
  26192. AudioPluginInstance* AudioUnitPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  26193. {
  26194. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  26195. {
  26196. ScopedPointer <AudioUnitPluginInstance> result (new AudioUnitPluginInstance (desc.fileOrIdentifier));
  26197. if (result->audioUnit != 0)
  26198. {
  26199. result->initialise();
  26200. return result.release();
  26201. }
  26202. }
  26203. return 0;
  26204. }
  26205. const StringArray AudioUnitPluginFormat::searchPathsForPlugins (const FileSearchPath& /*directoriesToSearch*/,
  26206. const bool /*recursive*/)
  26207. {
  26208. StringArray result;
  26209. ComponentRecord* comp = 0;
  26210. ComponentDescription desc;
  26211. zerostruct (desc);
  26212. for (;;)
  26213. {
  26214. zerostruct (desc);
  26215. comp = FindNextComponent (comp, &desc);
  26216. if (comp == 0)
  26217. break;
  26218. GetComponentInfo (comp, &desc, 0, 0, 0);
  26219. if (desc.componentType == kAudioUnitType_MusicDevice
  26220. || desc.componentType == kAudioUnitType_MusicEffect
  26221. || desc.componentType == kAudioUnitType_Effect
  26222. || desc.componentType == kAudioUnitType_Generator
  26223. || desc.componentType == kAudioUnitType_Panner)
  26224. {
  26225. const String s (AudioUnitFormatHelpers::createAUPluginIdentifier (desc));
  26226. DBG (s);
  26227. result.add (s);
  26228. }
  26229. }
  26230. return result;
  26231. }
  26232. bool AudioUnitPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  26233. {
  26234. ComponentDescription desc;
  26235. String name, version, manufacturer;
  26236. if (AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer))
  26237. return FindNextComponent (0, &desc) != 0;
  26238. const File f (fileOrIdentifier);
  26239. return f.hasFileExtension (".component")
  26240. && f.isDirectory();
  26241. }
  26242. const String AudioUnitPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  26243. {
  26244. ComponentDescription desc;
  26245. String name, version, manufacturer;
  26246. AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer);
  26247. if (name.isEmpty())
  26248. name = fileOrIdentifier;
  26249. return name;
  26250. }
  26251. bool AudioUnitPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  26252. {
  26253. if (desc.fileOrIdentifier.startsWithIgnoreCase (AudioUnitFormatHelpers::auIdentifierPrefix))
  26254. return fileMightContainThisPluginType (desc.fileOrIdentifier);
  26255. else
  26256. return File (desc.fileOrIdentifier).exists();
  26257. }
  26258. const FileSearchPath AudioUnitPluginFormat::getDefaultLocationsToSearch()
  26259. {
  26260. return FileSearchPath ("/(Default AudioUnit locations)");
  26261. }
  26262. #endif
  26263. END_JUCE_NAMESPACE
  26264. #undef log
  26265. #endif
  26266. /*** End of inlined file: juce_AudioUnitPluginFormat.mm ***/
  26267. /*** Start of inlined file: juce_VSTPluginFormat.mm ***/
  26268. // This file just wraps juce_VSTPluginFormat.cpp in an objective-C wrapper
  26269. #define JUCE_MAC_VST_INCLUDED 1
  26270. /*** Start of inlined file: juce_VSTPluginFormat.cpp ***/
  26271. #if JUCE_PLUGINHOST_VST && (JUCE_MAC_VST_INCLUDED || ! JUCE_MAC)
  26272. #if JUCE_WINDOWS
  26273. #undef _WIN32_WINNT
  26274. #define _WIN32_WINNT 0x500
  26275. #undef STRICT
  26276. #define STRICT
  26277. #include <windows.h>
  26278. #include <float.h>
  26279. #pragma warning (disable : 4312 4355)
  26280. #elif JUCE_LINUX
  26281. #include <float.h>
  26282. #include <sys/time.h>
  26283. #include <X11/Xlib.h>
  26284. #include <X11/Xutil.h>
  26285. #include <X11/Xatom.h>
  26286. #undef Font
  26287. #undef KeyPress
  26288. #undef Drawable
  26289. #undef Time
  26290. #else
  26291. #include <Cocoa/Cocoa.h>
  26292. #include <Carbon/Carbon.h>
  26293. #endif
  26294. #if ! (JUCE_MAC && JUCE_64BIT)
  26295. BEGIN_JUCE_NAMESPACE
  26296. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  26297. #endif
  26298. #undef PRAGMA_ALIGN_SUPPORTED
  26299. #define VST_FORCE_DEPRECATED 0
  26300. #if JUCE_MSVC
  26301. #pragma warning (push)
  26302. #pragma warning (disable: 4996)
  26303. #endif
  26304. /* Obviously you're going to need the Steinberg vstsdk2.4 folder in
  26305. your include path if you want to add VST support.
  26306. If you're not interested in VSTs, you can disable them by changing the
  26307. JUCE_PLUGINHOST_VST flag in juce_Config.h
  26308. */
  26309. #include "pluginterfaces/vst2.x/aeffectx.h"
  26310. #if JUCE_MSVC
  26311. #pragma warning (pop)
  26312. #endif
  26313. #if JUCE_LINUX
  26314. #define Font JUCE_NAMESPACE::Font
  26315. #define KeyPress JUCE_NAMESPACE::KeyPress
  26316. #define Drawable JUCE_NAMESPACE::Drawable
  26317. #define Time JUCE_NAMESPACE::Time
  26318. #endif
  26319. /*** Start of inlined file: juce_VSTMidiEventList.h ***/
  26320. #ifdef __aeffect__
  26321. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26322. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26323. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  26324. events to the list.
  26325. This is used by both the VST hosting code and the plugin wrapper.
  26326. */
  26327. class VSTMidiEventList
  26328. {
  26329. public:
  26330. VSTMidiEventList()
  26331. : numEventsUsed (0), numEventsAllocated (0)
  26332. {
  26333. }
  26334. ~VSTMidiEventList()
  26335. {
  26336. freeEvents();
  26337. }
  26338. void clear()
  26339. {
  26340. numEventsUsed = 0;
  26341. if (events != 0)
  26342. events->numEvents = 0;
  26343. }
  26344. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  26345. {
  26346. ensureSize (numEventsUsed + 1);
  26347. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  26348. events->numEvents = ++numEventsUsed;
  26349. if (numBytes <= 4)
  26350. {
  26351. if (e->type == kVstSysExType)
  26352. {
  26353. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  26354. e->type = kVstMidiType;
  26355. e->byteSize = sizeof (VstMidiEvent);
  26356. e->noteLength = 0;
  26357. e->noteOffset = 0;
  26358. e->detune = 0;
  26359. e->noteOffVelocity = 0;
  26360. }
  26361. e->deltaFrames = frameOffset;
  26362. memcpy (e->midiData, midiData, numBytes);
  26363. }
  26364. else
  26365. {
  26366. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  26367. if (se->type == kVstSysExType)
  26368. se->sysexDump = (char*) juce_realloc (se->sysexDump, numBytes);
  26369. else
  26370. se->sysexDump = (char*) juce_malloc (numBytes);
  26371. memcpy (se->sysexDump, midiData, numBytes);
  26372. se->type = kVstSysExType;
  26373. se->byteSize = sizeof (VstMidiSysexEvent);
  26374. se->deltaFrames = frameOffset;
  26375. se->flags = 0;
  26376. se->dumpBytes = numBytes;
  26377. se->resvd1 = 0;
  26378. se->resvd2 = 0;
  26379. }
  26380. }
  26381. // Handy method to pull the events out of an event buffer supplied by the host
  26382. // or plugin.
  26383. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  26384. {
  26385. for (int i = 0; i < events->numEvents; ++i)
  26386. {
  26387. const VstEvent* const e = events->events[i];
  26388. if (e != 0)
  26389. {
  26390. if (e->type == kVstMidiType)
  26391. {
  26392. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  26393. 4, e->deltaFrames);
  26394. }
  26395. else if (e->type == kVstSysExType)
  26396. {
  26397. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  26398. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  26399. e->deltaFrames);
  26400. }
  26401. }
  26402. }
  26403. }
  26404. void ensureSize (int numEventsNeeded)
  26405. {
  26406. if (numEventsNeeded > numEventsAllocated)
  26407. {
  26408. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  26409. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  26410. if (events == 0)
  26411. events.calloc (size, 1);
  26412. else
  26413. events.realloc (size, 1);
  26414. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  26415. {
  26416. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (jmax ((int) sizeof (VstMidiEvent),
  26417. (int) sizeof (VstMidiSysexEvent)));
  26418. e->type = kVstMidiType;
  26419. e->byteSize = sizeof (VstMidiEvent);
  26420. events->events[i] = (VstEvent*) e;
  26421. }
  26422. numEventsAllocated = numEventsNeeded;
  26423. }
  26424. }
  26425. void freeEvents()
  26426. {
  26427. if (events != 0)
  26428. {
  26429. for (int i = numEventsAllocated; --i >= 0;)
  26430. {
  26431. VstMidiEvent* const e = (VstMidiEvent*) (events->events[i]);
  26432. if (e->type == kVstSysExType)
  26433. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  26434. juce_free (e);
  26435. }
  26436. events.free();
  26437. numEventsUsed = 0;
  26438. numEventsAllocated = 0;
  26439. }
  26440. }
  26441. HeapBlock <VstEvents> events;
  26442. private:
  26443. int numEventsUsed, numEventsAllocated;
  26444. };
  26445. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26446. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26447. /*** End of inlined file: juce_VSTMidiEventList.h ***/
  26448. #if ! JUCE_WINDOWS
  26449. static void _fpreset() {}
  26450. static void _clearfp() {}
  26451. #endif
  26452. extern void juce_callAnyTimersSynchronously();
  26453. const int fxbVersionNum = 1;
  26454. struct fxProgram
  26455. {
  26456. long chunkMagic; // 'CcnK'
  26457. long byteSize; // of this chunk, excl. magic + byteSize
  26458. long fxMagic; // 'FxCk'
  26459. long version;
  26460. long fxID; // fx unique id
  26461. long fxVersion;
  26462. long numParams;
  26463. char prgName[28];
  26464. float params[1]; // variable no. of parameters
  26465. };
  26466. struct fxSet
  26467. {
  26468. long chunkMagic; // 'CcnK'
  26469. long byteSize; // of this chunk, excl. magic + byteSize
  26470. long fxMagic; // 'FxBk'
  26471. long version;
  26472. long fxID; // fx unique id
  26473. long fxVersion;
  26474. long numPrograms;
  26475. char future[128];
  26476. fxProgram programs[1]; // variable no. of programs
  26477. };
  26478. struct fxChunkSet
  26479. {
  26480. long chunkMagic; // 'CcnK'
  26481. long byteSize; // of this chunk, excl. magic + byteSize
  26482. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  26483. long version;
  26484. long fxID; // fx unique id
  26485. long fxVersion;
  26486. long numPrograms;
  26487. char future[128];
  26488. long chunkSize;
  26489. char chunk[8]; // variable
  26490. };
  26491. struct fxProgramSet
  26492. {
  26493. long chunkMagic; // 'CcnK'
  26494. long byteSize; // of this chunk, excl. magic + byteSize
  26495. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  26496. long version;
  26497. long fxID; // fx unique id
  26498. long fxVersion;
  26499. long numPrograms;
  26500. char name[28];
  26501. long chunkSize;
  26502. char chunk[8]; // variable
  26503. };
  26504. static long vst_swap (const long x) throw()
  26505. {
  26506. #ifdef JUCE_LITTLE_ENDIAN
  26507. return (long) ByteOrder::swap ((uint32) x);
  26508. #else
  26509. return x;
  26510. #endif
  26511. }
  26512. static float vst_swapFloat (const float x) throw()
  26513. {
  26514. #ifdef JUCE_LITTLE_ENDIAN
  26515. union { uint32 asInt; float asFloat; } n;
  26516. n.asFloat = x;
  26517. n.asInt = ByteOrder::swap (n.asInt);
  26518. return n.asFloat;
  26519. #else
  26520. return x;
  26521. #endif
  26522. }
  26523. static double getVSTHostTimeNanoseconds()
  26524. {
  26525. #if JUCE_WINDOWS
  26526. return timeGetTime() * 1000000.0;
  26527. #elif JUCE_LINUX
  26528. timeval micro;
  26529. gettimeofday (&micro, 0);
  26530. return micro.tv_usec * 1000.0;
  26531. #elif JUCE_MAC
  26532. UnsignedWide micro;
  26533. Microseconds (&micro);
  26534. return micro.lo * 1000.0;
  26535. #endif
  26536. }
  26537. typedef AEffect* (*MainCall) (audioMasterCallback);
  26538. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt);
  26539. static int shellUIDToCreate = 0;
  26540. static int insideVSTCallback = 0;
  26541. class VSTPluginWindow;
  26542. // Change this to disable logging of various VST activities
  26543. #ifndef VST_LOGGING
  26544. #define VST_LOGGING 1
  26545. #endif
  26546. #if VST_LOGGING
  26547. #define log(a) Logger::writeToLog(a);
  26548. #else
  26549. #define log(a)
  26550. #endif
  26551. #if JUCE_MAC && JUCE_PPC
  26552. static void* NewCFMFromMachO (void* const machofp) throw()
  26553. {
  26554. void* result = juce_malloc (8);
  26555. ((void**) result)[0] = machofp;
  26556. ((void**) result)[1] = result;
  26557. return result;
  26558. }
  26559. #endif
  26560. #if JUCE_LINUX
  26561. extern Display* display;
  26562. extern XContext windowHandleXContext;
  26563. typedef void (*EventProcPtr) (XEvent* ev);
  26564. static bool xErrorTriggered;
  26565. static int temporaryErrorHandler (Display*, XErrorEvent*)
  26566. {
  26567. xErrorTriggered = true;
  26568. return 0;
  26569. }
  26570. static int getPropertyFromXWindow (Window handle, Atom atom)
  26571. {
  26572. XErrorHandler oldErrorHandler = XSetErrorHandler (temporaryErrorHandler);
  26573. xErrorTriggered = false;
  26574. int userSize;
  26575. unsigned long bytes, userCount;
  26576. unsigned char* data;
  26577. Atom userType;
  26578. XGetWindowProperty (display, handle, atom, 0, 1, false, AnyPropertyType,
  26579. &userType, &userSize, &userCount, &bytes, &data);
  26580. XSetErrorHandler (oldErrorHandler);
  26581. return (userCount == 1 && ! xErrorTriggered) ? *reinterpret_cast<int*> (data)
  26582. : 0;
  26583. }
  26584. static Window getChildWindow (Window windowToCheck)
  26585. {
  26586. Window rootWindow, parentWindow;
  26587. Window* childWindows;
  26588. unsigned int numChildren;
  26589. XQueryTree (display,
  26590. windowToCheck,
  26591. &rootWindow,
  26592. &parentWindow,
  26593. &childWindows,
  26594. &numChildren);
  26595. if (numChildren > 0)
  26596. return childWindows [0];
  26597. return 0;
  26598. }
  26599. static void translateJuceToXButtonModifiers (const MouseEvent& e, XEvent& ev) throw()
  26600. {
  26601. if (e.mods.isLeftButtonDown())
  26602. {
  26603. ev.xbutton.button = Button1;
  26604. ev.xbutton.state |= Button1Mask;
  26605. }
  26606. else if (e.mods.isRightButtonDown())
  26607. {
  26608. ev.xbutton.button = Button3;
  26609. ev.xbutton.state |= Button3Mask;
  26610. }
  26611. else if (e.mods.isMiddleButtonDown())
  26612. {
  26613. ev.xbutton.button = Button2;
  26614. ev.xbutton.state |= Button2Mask;
  26615. }
  26616. }
  26617. static void translateJuceToXMotionModifiers (const MouseEvent& e, XEvent& ev) throw()
  26618. {
  26619. if (e.mods.isLeftButtonDown()) ev.xmotion.state |= Button1Mask;
  26620. else if (e.mods.isRightButtonDown()) ev.xmotion.state |= Button3Mask;
  26621. else if (e.mods.isMiddleButtonDown()) ev.xmotion.state |= Button2Mask;
  26622. }
  26623. static void translateJuceToXCrossingModifiers (const MouseEvent& e, XEvent& ev) throw()
  26624. {
  26625. if (e.mods.isLeftButtonDown()) ev.xcrossing.state |= Button1Mask;
  26626. else if (e.mods.isRightButtonDown()) ev.xcrossing.state |= Button3Mask;
  26627. else if (e.mods.isMiddleButtonDown()) ev.xcrossing.state |= Button2Mask;
  26628. }
  26629. static void translateJuceToXMouseWheelModifiers (const MouseEvent& e, const float increment, XEvent& ev) throw()
  26630. {
  26631. if (increment < 0)
  26632. {
  26633. ev.xbutton.button = Button5;
  26634. ev.xbutton.state |= Button5Mask;
  26635. }
  26636. else if (increment > 0)
  26637. {
  26638. ev.xbutton.button = Button4;
  26639. ev.xbutton.state |= Button4Mask;
  26640. }
  26641. }
  26642. #endif
  26643. class ModuleHandle : public ReferenceCountedObject
  26644. {
  26645. public:
  26646. File file;
  26647. MainCall moduleMain;
  26648. String pluginName;
  26649. static Array <ModuleHandle*>& getActiveModules()
  26650. {
  26651. static Array <ModuleHandle*> activeModules;
  26652. return activeModules;
  26653. }
  26654. static ModuleHandle* findOrCreateModule (const File& file)
  26655. {
  26656. for (int i = getActiveModules().size(); --i >= 0;)
  26657. {
  26658. ModuleHandle* const module = getActiveModules().getUnchecked(i);
  26659. if (module->file == file)
  26660. return module;
  26661. }
  26662. _fpreset(); // (doesn't do any harm)
  26663. ++insideVSTCallback;
  26664. shellUIDToCreate = 0;
  26665. log ("Attempting to load VST: " + file.getFullPathName());
  26666. ScopedPointer <ModuleHandle> m (new ModuleHandle (file));
  26667. if (! m->open())
  26668. m = 0;
  26669. --insideVSTCallback;
  26670. _fpreset(); // (doesn't do any harm)
  26671. return m.release();
  26672. }
  26673. ModuleHandle (const File& file_)
  26674. : file (file_),
  26675. moduleMain (0),
  26676. #if JUCE_WINDOWS || JUCE_LINUX
  26677. hModule (0)
  26678. #elif JUCE_MAC
  26679. fragId (0),
  26680. resHandle (0),
  26681. bundleRef (0),
  26682. resFileId (0)
  26683. #endif
  26684. {
  26685. getActiveModules().add (this);
  26686. #if JUCE_WINDOWS || JUCE_LINUX
  26687. fullParentDirectoryPathName = file_.getParentDirectory().getFullPathName();
  26688. #elif JUCE_MAC
  26689. FSRef ref;
  26690. PlatformUtilities::makeFSRefFromPath (&ref, file_.getParentDirectory().getFullPathName());
  26691. FSGetCatalogInfo (&ref, kFSCatInfoNone, 0, 0, &parentDirFSSpec, 0);
  26692. #endif
  26693. }
  26694. ~ModuleHandle()
  26695. {
  26696. getActiveModules().removeValue (this);
  26697. close();
  26698. }
  26699. juce_UseDebuggingNewOperator
  26700. #if JUCE_WINDOWS || JUCE_LINUX
  26701. void* hModule;
  26702. String fullParentDirectoryPathName;
  26703. bool open()
  26704. {
  26705. #if JUCE_WINDOWS
  26706. static bool timePeriodSet = false;
  26707. if (! timePeriodSet)
  26708. {
  26709. timePeriodSet = true;
  26710. timeBeginPeriod (2);
  26711. }
  26712. #endif
  26713. pluginName = file.getFileNameWithoutExtension();
  26714. hModule = PlatformUtilities::loadDynamicLibrary (file.getFullPathName());
  26715. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "VSTPluginMain");
  26716. if (moduleMain == 0)
  26717. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "main");
  26718. return moduleMain != 0;
  26719. }
  26720. void close()
  26721. {
  26722. _fpreset(); // (doesn't do any harm)
  26723. PlatformUtilities::freeDynamicLibrary (hModule);
  26724. }
  26725. void closeEffect (AEffect* eff)
  26726. {
  26727. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26728. }
  26729. #else
  26730. CFragConnectionID fragId;
  26731. Handle resHandle;
  26732. CFBundleRef bundleRef;
  26733. FSSpec parentDirFSSpec;
  26734. short resFileId;
  26735. bool open()
  26736. {
  26737. bool ok = false;
  26738. const String filename (file.getFullPathName());
  26739. if (file.hasFileExtension (".vst"))
  26740. {
  26741. const char* const utf8 = filename.toUTF8();
  26742. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  26743. strlen (utf8), file.isDirectory());
  26744. if (url != 0)
  26745. {
  26746. bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  26747. CFRelease (url);
  26748. if (bundleRef != 0)
  26749. {
  26750. if (CFBundleLoadExecutable (bundleRef))
  26751. {
  26752. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("main_macho"));
  26753. if (moduleMain == 0)
  26754. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("VSTPluginMain"));
  26755. if (moduleMain != 0)
  26756. {
  26757. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  26758. if (name != 0)
  26759. {
  26760. if (CFGetTypeID (name) == CFStringGetTypeID())
  26761. {
  26762. char buffer[1024];
  26763. if (CFStringGetCString ((CFStringRef) name, buffer, sizeof (buffer), CFStringGetSystemEncoding()))
  26764. pluginName = buffer;
  26765. }
  26766. }
  26767. if (pluginName.isEmpty())
  26768. pluginName = file.getFileNameWithoutExtension();
  26769. resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  26770. ok = true;
  26771. }
  26772. }
  26773. if (! ok)
  26774. {
  26775. CFBundleUnloadExecutable (bundleRef);
  26776. CFRelease (bundleRef);
  26777. bundleRef = 0;
  26778. }
  26779. }
  26780. }
  26781. }
  26782. #if JUCE_PPC
  26783. else
  26784. {
  26785. FSRef fn;
  26786. if (FSPathMakeRef ((UInt8*) filename.toUTF8(), &fn, 0) == noErr)
  26787. {
  26788. resFileId = FSOpenResFile (&fn, fsRdPerm);
  26789. if (resFileId != -1)
  26790. {
  26791. const int numEffs = Count1Resources ('aEff');
  26792. for (int i = 0; i < numEffs; ++i)
  26793. {
  26794. resHandle = Get1IndResource ('aEff', i + 1);
  26795. if (resHandle != 0)
  26796. {
  26797. OSType type;
  26798. Str255 name;
  26799. SInt16 id;
  26800. GetResInfo (resHandle, &id, &type, name);
  26801. pluginName = String ((const char*) name + 1, name[0]);
  26802. DetachResource (resHandle);
  26803. HLock (resHandle);
  26804. Ptr ptr;
  26805. Str255 errorText;
  26806. OSErr err = GetMemFragment (*resHandle, GetHandleSize (resHandle),
  26807. name, kPrivateCFragCopy,
  26808. &fragId, &ptr, errorText);
  26809. if (err == noErr)
  26810. {
  26811. moduleMain = (MainCall) newMachOFromCFM (ptr);
  26812. ok = true;
  26813. }
  26814. else
  26815. {
  26816. HUnlock (resHandle);
  26817. }
  26818. break;
  26819. }
  26820. }
  26821. if (! ok)
  26822. CloseResFile (resFileId);
  26823. }
  26824. }
  26825. }
  26826. #endif
  26827. return ok;
  26828. }
  26829. void close()
  26830. {
  26831. #if JUCE_PPC
  26832. if (fragId != 0)
  26833. {
  26834. if (moduleMain != 0)
  26835. disposeMachOFromCFM ((void*) moduleMain);
  26836. CloseConnection (&fragId);
  26837. HUnlock (resHandle);
  26838. if (resFileId != 0)
  26839. CloseResFile (resFileId);
  26840. }
  26841. else
  26842. #endif
  26843. if (bundleRef != 0)
  26844. {
  26845. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  26846. if (CFGetRetainCount (bundleRef) == 1)
  26847. CFBundleUnloadExecutable (bundleRef);
  26848. if (CFGetRetainCount (bundleRef) > 0)
  26849. CFRelease (bundleRef);
  26850. }
  26851. }
  26852. void closeEffect (AEffect* eff)
  26853. {
  26854. #if JUCE_PPC
  26855. if (fragId != 0)
  26856. {
  26857. Array<void*> thingsToDelete;
  26858. thingsToDelete.add ((void*) eff->dispatcher);
  26859. thingsToDelete.add ((void*) eff->process);
  26860. thingsToDelete.add ((void*) eff->setParameter);
  26861. thingsToDelete.add ((void*) eff->getParameter);
  26862. thingsToDelete.add ((void*) eff->processReplacing);
  26863. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26864. for (int i = thingsToDelete.size(); --i >= 0;)
  26865. disposeMachOFromCFM (thingsToDelete[i]);
  26866. }
  26867. else
  26868. #endif
  26869. {
  26870. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26871. }
  26872. }
  26873. #if JUCE_PPC
  26874. static void* newMachOFromCFM (void* cfmfp)
  26875. {
  26876. if (cfmfp == 0)
  26877. return 0;
  26878. UInt32* const mfp = new UInt32[6];
  26879. mfp[0] = 0x3d800000 | ((UInt32) cfmfp >> 16);
  26880. mfp[1] = 0x618c0000 | ((UInt32) cfmfp & 0xffff);
  26881. mfp[2] = 0x800c0000;
  26882. mfp[3] = 0x804c0004;
  26883. mfp[4] = 0x7c0903a6;
  26884. mfp[5] = 0x4e800420;
  26885. MakeDataExecutable (mfp, sizeof (UInt32) * 6);
  26886. return mfp;
  26887. }
  26888. static void disposeMachOFromCFM (void* ptr)
  26889. {
  26890. delete[] static_cast <UInt32*> (ptr);
  26891. }
  26892. void coerceAEffectFunctionCalls (AEffect* eff)
  26893. {
  26894. if (fragId != 0)
  26895. {
  26896. eff->dispatcher = (AEffectDispatcherProc) newMachOFromCFM ((void*) eff->dispatcher);
  26897. eff->process = (AEffectProcessProc) newMachOFromCFM ((void*) eff->process);
  26898. eff->setParameter = (AEffectSetParameterProc) newMachOFromCFM ((void*) eff->setParameter);
  26899. eff->getParameter = (AEffectGetParameterProc) newMachOFromCFM ((void*) eff->getParameter);
  26900. eff->processReplacing = (AEffectProcessProc) newMachOFromCFM ((void*) eff->processReplacing);
  26901. }
  26902. }
  26903. #endif
  26904. #endif
  26905. };
  26906. /**
  26907. An instance of a plugin, created by a VSTPluginFormat.
  26908. */
  26909. class VSTPluginInstance : public AudioPluginInstance,
  26910. private Timer,
  26911. private AsyncUpdater
  26912. {
  26913. public:
  26914. ~VSTPluginInstance();
  26915. // AudioPluginInstance methods:
  26916. void fillInPluginDescription (PluginDescription& desc) const
  26917. {
  26918. desc.name = name;
  26919. desc.fileOrIdentifier = module->file.getFullPathName();
  26920. desc.uid = getUID();
  26921. desc.lastFileModTime = module->file.getLastModificationTime();
  26922. desc.pluginFormatName = "VST";
  26923. desc.category = getCategory();
  26924. {
  26925. char buffer [kVstMaxVendorStrLen + 8];
  26926. zerostruct (buffer);
  26927. dispatch (effGetVendorString, 0, 0, buffer, 0);
  26928. desc.manufacturerName = buffer;
  26929. }
  26930. desc.version = getVersion();
  26931. desc.numInputChannels = getNumInputChannels();
  26932. desc.numOutputChannels = getNumOutputChannels();
  26933. desc.isInstrument = (effect != 0 && (effect->flags & effFlagsIsSynth) != 0);
  26934. }
  26935. const String getName() const { return name; }
  26936. int getUID() const;
  26937. bool acceptsMidi() const { return wantsMidiMessages; }
  26938. bool producesMidi() const { return dispatch (effCanDo, 0, 0, (void*) "sendVstMidiEvent", 0) > 0; }
  26939. // AudioProcessor methods:
  26940. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  26941. void releaseResources();
  26942. void processBlock (AudioSampleBuffer& buffer,
  26943. MidiBuffer& midiMessages);
  26944. bool hasEditor() const { return effect != 0 && (effect->flags & effFlagsHasEditor) != 0; }
  26945. AudioProcessorEditor* createEditor();
  26946. const String getInputChannelName (int index) const;
  26947. bool isInputChannelStereoPair (int index) const;
  26948. const String getOutputChannelName (int index) const;
  26949. bool isOutputChannelStereoPair (int index) const;
  26950. int getNumParameters() { return effect != 0 ? effect->numParams : 0; }
  26951. float getParameter (int index);
  26952. void setParameter (int index, float newValue);
  26953. const String getParameterName (int index);
  26954. const String getParameterText (int index);
  26955. bool isParameterAutomatable (int index) const;
  26956. int getNumPrograms() { return effect != 0 ? effect->numPrograms : 0; }
  26957. int getCurrentProgram() { return dispatch (effGetProgram, 0, 0, 0, 0); }
  26958. void setCurrentProgram (int index);
  26959. const String getProgramName (int index);
  26960. void changeProgramName (int index, const String& newName);
  26961. void getStateInformation (MemoryBlock& destData);
  26962. void getCurrentProgramStateInformation (MemoryBlock& destData);
  26963. void setStateInformation (const void* data, int sizeInBytes);
  26964. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  26965. void timerCallback();
  26966. void handleAsyncUpdate();
  26967. VstIntPtr handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt);
  26968. juce_UseDebuggingNewOperator
  26969. private:
  26970. friend class VSTPluginWindow;
  26971. friend class VSTPluginFormat;
  26972. AEffect* effect;
  26973. String name;
  26974. CriticalSection lock;
  26975. bool wantsMidiMessages, initialised, isPowerOn;
  26976. mutable StringArray programNames;
  26977. AudioSampleBuffer tempBuffer;
  26978. CriticalSection midiInLock;
  26979. MidiBuffer incomingMidi;
  26980. VSTMidiEventList midiEventsToSend;
  26981. VstTimeInfo vstHostTime;
  26982. ReferenceCountedObjectPtr <ModuleHandle> module;
  26983. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const;
  26984. bool restoreProgramSettings (const fxProgram* const prog);
  26985. const String getCurrentProgramName();
  26986. void setParamsInProgramBlock (fxProgram* const prog);
  26987. void updateStoredProgramNames();
  26988. void initialise();
  26989. void handleMidiFromPlugin (const VstEvents* const events);
  26990. void createTempParameterStore (MemoryBlock& dest);
  26991. void restoreFromTempParameterStore (const MemoryBlock& mb);
  26992. const String getParameterLabel (int index) const;
  26993. bool usesChunks() const throw() { return effect != 0 && (effect->flags & effFlagsProgramChunks) != 0; }
  26994. void getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const;
  26995. void setChunkData (const char* data, int size, bool isPreset);
  26996. bool loadFromFXBFile (const void* data, int numBytes);
  26997. bool saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB);
  26998. int getVersionNumber() const throw() { return effect != 0 ? effect->version : 0; }
  26999. const String getVersion() const;
  27000. const String getCategory() const;
  27001. void setPower (const bool on);
  27002. VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module);
  27003. };
  27004. VSTPluginInstance::VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module_)
  27005. : effect (0),
  27006. wantsMidiMessages (false),
  27007. initialised (false),
  27008. isPowerOn (false),
  27009. tempBuffer (1, 1),
  27010. module (module_)
  27011. {
  27012. try
  27013. {
  27014. _fpreset();
  27015. ++insideVSTCallback;
  27016. name = module->pluginName;
  27017. log ("Creating VST instance: " + name);
  27018. #if JUCE_MAC
  27019. if (module->resFileId != 0)
  27020. UseResFile (module->resFileId);
  27021. #if JUCE_PPC
  27022. if (module->fragId != 0)
  27023. {
  27024. static void* audioMasterCoerced = 0;
  27025. if (audioMasterCoerced == 0)
  27026. audioMasterCoerced = NewCFMFromMachO ((void*) &audioMaster);
  27027. effect = module->moduleMain ((audioMasterCallback) audioMasterCoerced);
  27028. }
  27029. else
  27030. #endif
  27031. #endif
  27032. {
  27033. effect = module->moduleMain (&audioMaster);
  27034. }
  27035. --insideVSTCallback;
  27036. if (effect != 0 && effect->magic == kEffectMagic)
  27037. {
  27038. #if JUCE_PPC
  27039. module->coerceAEffectFunctionCalls (effect);
  27040. #endif
  27041. jassert (effect->resvd2 == 0);
  27042. jassert (effect->object != 0);
  27043. _fpreset(); // some dodgy plugs fuck around with this
  27044. }
  27045. else
  27046. {
  27047. effect = 0;
  27048. }
  27049. }
  27050. catch (...)
  27051. {
  27052. --insideVSTCallback;
  27053. }
  27054. }
  27055. VSTPluginInstance::~VSTPluginInstance()
  27056. {
  27057. const ScopedLock sl (lock);
  27058. jassert (insideVSTCallback == 0);
  27059. if (effect != 0 && effect->magic == kEffectMagic)
  27060. {
  27061. try
  27062. {
  27063. #if JUCE_MAC
  27064. if (module->resFileId != 0)
  27065. UseResFile (module->resFileId);
  27066. #endif
  27067. // Must delete any editors before deleting the plugin instance!
  27068. jassert (getActiveEditor() == 0);
  27069. _fpreset(); // some dodgy plugs fuck around with this
  27070. module->closeEffect (effect);
  27071. }
  27072. catch (...)
  27073. {}
  27074. }
  27075. module = 0;
  27076. effect = 0;
  27077. }
  27078. void VSTPluginInstance::initialise()
  27079. {
  27080. if (initialised || effect == 0)
  27081. return;
  27082. log ("Initialising VST: " + module->pluginName);
  27083. initialised = true;
  27084. dispatch (effIdentify, 0, 0, 0, 0);
  27085. // this code would ask the plugin for its name, but so few plugins
  27086. // actually bother implementing this correctly, that it's better to
  27087. // just ignore it and use the file name instead.
  27088. /* {
  27089. char buffer [256];
  27090. zerostruct (buffer);
  27091. dispatch (effGetEffectName, 0, 0, buffer, 0);
  27092. name = String (buffer).trim();
  27093. if (name.isEmpty())
  27094. name = module->pluginName;
  27095. }
  27096. */
  27097. if (getSampleRate() > 0)
  27098. dispatch (effSetSampleRate, 0, 0, 0, (float) getSampleRate());
  27099. if (getBlockSize() > 0)
  27100. dispatch (effSetBlockSize, 0, jmax (32, getBlockSize()), 0, 0);
  27101. dispatch (effOpen, 0, 0, 0, 0);
  27102. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  27103. getSampleRate(), getBlockSize());
  27104. if (getNumPrograms() > 1)
  27105. setCurrentProgram (0);
  27106. else
  27107. dispatch (effSetProgram, 0, 0, 0, 0);
  27108. int i;
  27109. for (i = effect->numInputs; --i >= 0;)
  27110. dispatch (effConnectInput, i, 1, 0, 0);
  27111. for (i = effect->numOutputs; --i >= 0;)
  27112. dispatch (effConnectOutput, i, 1, 0, 0);
  27113. updateStoredProgramNames();
  27114. wantsMidiMessages = dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0;
  27115. setLatencySamples (effect->initialDelay);
  27116. }
  27117. void VSTPluginInstance::prepareToPlay (double sampleRate_,
  27118. int samplesPerBlockExpected)
  27119. {
  27120. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  27121. sampleRate_, samplesPerBlockExpected);
  27122. setLatencySamples (effect->initialDelay);
  27123. vstHostTime.tempo = 120.0;
  27124. vstHostTime.timeSigNumerator = 4;
  27125. vstHostTime.timeSigDenominator = 4;
  27126. vstHostTime.sampleRate = sampleRate_;
  27127. vstHostTime.samplePos = 0;
  27128. vstHostTime.flags = kVstNanosValid; /*| kVstTransportPlaying | kVstTempoValid | kVstTimeSigValid*/;
  27129. initialise();
  27130. if (initialised)
  27131. {
  27132. wantsMidiMessages = wantsMidiMessages
  27133. || (dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0);
  27134. if (wantsMidiMessages)
  27135. midiEventsToSend.ensureSize (256);
  27136. else
  27137. midiEventsToSend.freeEvents();
  27138. incomingMidi.clear();
  27139. dispatch (effSetSampleRate, 0, 0, 0, (float) sampleRate_);
  27140. dispatch (effSetBlockSize, 0, jmax (16, samplesPerBlockExpected), 0, 0);
  27141. tempBuffer.setSize (jmax (1, effect->numOutputs), samplesPerBlockExpected);
  27142. if (! isPowerOn)
  27143. setPower (true);
  27144. // dodgy hack to force some plugins to initialise the sample rate..
  27145. if ((! hasEditor()) && getNumParameters() > 0)
  27146. {
  27147. const float old = getParameter (0);
  27148. setParameter (0, (old < 0.5f) ? 1.0f : 0.0f);
  27149. setParameter (0, old);
  27150. }
  27151. dispatch (effStartProcess, 0, 0, 0, 0);
  27152. }
  27153. }
  27154. void VSTPluginInstance::releaseResources()
  27155. {
  27156. if (initialised)
  27157. {
  27158. dispatch (effStopProcess, 0, 0, 0, 0);
  27159. setPower (false);
  27160. }
  27161. tempBuffer.setSize (1, 1);
  27162. incomingMidi.clear();
  27163. midiEventsToSend.freeEvents();
  27164. }
  27165. void VSTPluginInstance::processBlock (AudioSampleBuffer& buffer,
  27166. MidiBuffer& midiMessages)
  27167. {
  27168. const int numSamples = buffer.getNumSamples();
  27169. if (initialised)
  27170. {
  27171. AudioPlayHead* playHead = getPlayHead();
  27172. if (playHead != 0)
  27173. {
  27174. AudioPlayHead::CurrentPositionInfo position;
  27175. playHead->getCurrentPosition (position);
  27176. vstHostTime.tempo = position.bpm;
  27177. vstHostTime.timeSigNumerator = position.timeSigNumerator;
  27178. vstHostTime.timeSigDenominator = position.timeSigDenominator;
  27179. vstHostTime.ppqPos = position.ppqPosition;
  27180. vstHostTime.barStartPos = position.ppqPositionOfLastBarStart;
  27181. vstHostTime.flags |= kVstTempoValid | kVstTimeSigValid | kVstPpqPosValid | kVstBarsValid;
  27182. if (position.isPlaying)
  27183. vstHostTime.flags |= kVstTransportPlaying;
  27184. else
  27185. vstHostTime.flags &= ~kVstTransportPlaying;
  27186. }
  27187. vstHostTime.nanoSeconds = getVSTHostTimeNanoseconds();
  27188. if (wantsMidiMessages)
  27189. {
  27190. midiEventsToSend.clear();
  27191. midiEventsToSend.ensureSize (1);
  27192. MidiBuffer::Iterator iter (midiMessages);
  27193. const uint8* midiData;
  27194. int numBytesOfMidiData, samplePosition;
  27195. while (iter.getNextEvent (midiData, numBytesOfMidiData, samplePosition))
  27196. {
  27197. midiEventsToSend.addEvent (midiData, numBytesOfMidiData,
  27198. jlimit (0, numSamples - 1, samplePosition));
  27199. }
  27200. try
  27201. {
  27202. effect->dispatcher (effect, effProcessEvents, 0, 0, midiEventsToSend.events, 0);
  27203. }
  27204. catch (...)
  27205. {}
  27206. }
  27207. _clearfp();
  27208. if ((effect->flags & effFlagsCanReplacing) != 0)
  27209. {
  27210. try
  27211. {
  27212. effect->processReplacing (effect, buffer.getArrayOfChannels(), buffer.getArrayOfChannels(), numSamples);
  27213. }
  27214. catch (...)
  27215. {}
  27216. }
  27217. else
  27218. {
  27219. tempBuffer.setSize (effect->numOutputs, numSamples);
  27220. tempBuffer.clear();
  27221. try
  27222. {
  27223. effect->process (effect, buffer.getArrayOfChannels(), tempBuffer.getArrayOfChannels(), numSamples);
  27224. }
  27225. catch (...)
  27226. {}
  27227. for (int i = effect->numOutputs; --i >= 0;)
  27228. buffer.copyFrom (i, 0, tempBuffer.getSampleData (i), numSamples);
  27229. }
  27230. }
  27231. else
  27232. {
  27233. // Not initialised, so just bypass..
  27234. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  27235. buffer.clear (i, 0, buffer.getNumSamples());
  27236. }
  27237. {
  27238. // copy any incoming midi..
  27239. const ScopedLock sl (midiInLock);
  27240. midiMessages.swapWith (incomingMidi);
  27241. incomingMidi.clear();
  27242. }
  27243. }
  27244. void VSTPluginInstance::handleMidiFromPlugin (const VstEvents* const events)
  27245. {
  27246. if (events != 0)
  27247. {
  27248. const ScopedLock sl (midiInLock);
  27249. VSTMidiEventList::addEventsToMidiBuffer (events, incomingMidi);
  27250. }
  27251. }
  27252. static Array <VSTPluginWindow*> activeVSTWindows;
  27253. class VSTPluginWindow : public AudioProcessorEditor,
  27254. #if ! JUCE_MAC
  27255. public ComponentMovementWatcher,
  27256. #endif
  27257. public Timer
  27258. {
  27259. public:
  27260. VSTPluginWindow (VSTPluginInstance& plugin_)
  27261. : AudioProcessorEditor (&plugin_),
  27262. #if ! JUCE_MAC
  27263. ComponentMovementWatcher (this),
  27264. #endif
  27265. plugin (plugin_),
  27266. isOpen (false),
  27267. wasShowing (false),
  27268. pluginRefusesToResize (false),
  27269. pluginWantsKeys (false),
  27270. alreadyInside (false),
  27271. recursiveResize (false)
  27272. {
  27273. #if JUCE_WINDOWS
  27274. sizeCheckCount = 0;
  27275. pluginHWND = 0;
  27276. #elif JUCE_LINUX
  27277. pluginWindow = None;
  27278. pluginProc = None;
  27279. #else
  27280. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  27281. #endif
  27282. activeVSTWindows.add (this);
  27283. setSize (1, 1);
  27284. setOpaque (true);
  27285. setVisible (true);
  27286. }
  27287. ~VSTPluginWindow()
  27288. {
  27289. #if JUCE_MAC
  27290. innerWrapper = 0;
  27291. #else
  27292. closePluginWindow();
  27293. #endif
  27294. activeVSTWindows.removeValue (this);
  27295. plugin.editorBeingDeleted (this);
  27296. }
  27297. #if ! JUCE_MAC
  27298. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  27299. {
  27300. if (recursiveResize)
  27301. return;
  27302. Component* const topComp = getTopLevelComponent();
  27303. if (topComp->getPeer() != 0)
  27304. {
  27305. const Point<int> pos (relativePositionToOtherComponent (topComp, Point<int>()));
  27306. recursiveResize = true;
  27307. #if JUCE_WINDOWS
  27308. if (pluginHWND != 0)
  27309. MoveWindow (pluginHWND, pos.getX(), pos.getY(), getWidth(), getHeight(), TRUE);
  27310. #elif JUCE_LINUX
  27311. if (pluginWindow != 0)
  27312. {
  27313. XResizeWindow (display, pluginWindow, getWidth(), getHeight());
  27314. XMoveWindow (display, pluginWindow, pos.getX(), pos.getY());
  27315. XMapRaised (display, pluginWindow);
  27316. }
  27317. #endif
  27318. recursiveResize = false;
  27319. }
  27320. }
  27321. void componentVisibilityChanged (Component&)
  27322. {
  27323. const bool isShowingNow = isShowing();
  27324. if (wasShowing != isShowingNow)
  27325. {
  27326. wasShowing = isShowingNow;
  27327. if (isShowingNow)
  27328. openPluginWindow();
  27329. else
  27330. closePluginWindow();
  27331. }
  27332. componentMovedOrResized (true, true);
  27333. }
  27334. void componentPeerChanged()
  27335. {
  27336. closePluginWindow();
  27337. openPluginWindow();
  27338. }
  27339. #endif
  27340. bool keyStateChanged (bool)
  27341. {
  27342. return pluginWantsKeys;
  27343. }
  27344. bool keyPressed (const KeyPress&)
  27345. {
  27346. return pluginWantsKeys;
  27347. }
  27348. #if JUCE_MAC
  27349. void paint (Graphics& g)
  27350. {
  27351. g.fillAll (Colours::black);
  27352. }
  27353. #else
  27354. void paint (Graphics& g)
  27355. {
  27356. if (isOpen)
  27357. {
  27358. ComponentPeer* const peer = getPeer();
  27359. if (peer != 0)
  27360. {
  27361. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  27362. peer->addMaskedRegion (pos.getX(), pos.getY(), getWidth(), getHeight());
  27363. #if JUCE_LINUX
  27364. if (pluginWindow != 0)
  27365. {
  27366. const Rectangle<int> clip (g.getClipBounds());
  27367. XEvent ev;
  27368. zerostruct (ev);
  27369. ev.xexpose.type = Expose;
  27370. ev.xexpose.display = display;
  27371. ev.xexpose.window = pluginWindow;
  27372. ev.xexpose.x = clip.getX();
  27373. ev.xexpose.y = clip.getY();
  27374. ev.xexpose.width = clip.getWidth();
  27375. ev.xexpose.height = clip.getHeight();
  27376. sendEventToChild (&ev);
  27377. }
  27378. #endif
  27379. }
  27380. }
  27381. else
  27382. {
  27383. g.fillAll (Colours::black);
  27384. }
  27385. }
  27386. #endif
  27387. void timerCallback()
  27388. {
  27389. #if JUCE_WINDOWS
  27390. if (--sizeCheckCount <= 0)
  27391. {
  27392. sizeCheckCount = 10;
  27393. checkPluginWindowSize();
  27394. }
  27395. #endif
  27396. try
  27397. {
  27398. static bool reentrant = false;
  27399. if (! reentrant)
  27400. {
  27401. reentrant = true;
  27402. plugin.dispatch (effEditIdle, 0, 0, 0, 0);
  27403. reentrant = false;
  27404. }
  27405. }
  27406. catch (...)
  27407. {}
  27408. }
  27409. void mouseDown (const MouseEvent& e)
  27410. {
  27411. #if JUCE_LINUX
  27412. if (pluginWindow == 0)
  27413. return;
  27414. toFront (true);
  27415. XEvent ev;
  27416. zerostruct (ev);
  27417. ev.xbutton.display = display;
  27418. ev.xbutton.type = ButtonPress;
  27419. ev.xbutton.window = pluginWindow;
  27420. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27421. ev.xbutton.time = CurrentTime;
  27422. ev.xbutton.x = e.x;
  27423. ev.xbutton.y = e.y;
  27424. ev.xbutton.x_root = e.getScreenX();
  27425. ev.xbutton.y_root = e.getScreenY();
  27426. translateJuceToXButtonModifiers (e, ev);
  27427. sendEventToChild (&ev);
  27428. #elif JUCE_WINDOWS
  27429. (void) e;
  27430. toFront (true);
  27431. #endif
  27432. }
  27433. void broughtToFront()
  27434. {
  27435. activeVSTWindows.removeValue (this);
  27436. activeVSTWindows.add (this);
  27437. #if JUCE_MAC
  27438. dispatch (effEditTop, 0, 0, 0, 0);
  27439. #endif
  27440. }
  27441. juce_UseDebuggingNewOperator
  27442. private:
  27443. VSTPluginInstance& plugin;
  27444. bool isOpen, wasShowing, recursiveResize;
  27445. bool pluginWantsKeys, pluginRefusesToResize, alreadyInside;
  27446. #if JUCE_WINDOWS
  27447. HWND pluginHWND;
  27448. void* originalWndProc;
  27449. int sizeCheckCount;
  27450. #elif JUCE_LINUX
  27451. Window pluginWindow;
  27452. EventProcPtr pluginProc;
  27453. #endif
  27454. #if JUCE_MAC
  27455. void openPluginWindow (WindowRef parentWindow)
  27456. {
  27457. if (isOpen || parentWindow == 0)
  27458. return;
  27459. isOpen = true;
  27460. ERect* rect = 0;
  27461. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27462. dispatch (effEditOpen, 0, 0, parentWindow, 0);
  27463. // do this before and after like in the steinberg example
  27464. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27465. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  27466. // Install keyboard hooks
  27467. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  27468. // double-check it's not too tiny
  27469. int w = 250, h = 150;
  27470. if (rect != 0)
  27471. {
  27472. w = rect->right - rect->left;
  27473. h = rect->bottom - rect->top;
  27474. if (w == 0 || h == 0)
  27475. {
  27476. w = 250;
  27477. h = 150;
  27478. }
  27479. }
  27480. w = jmax (w, 32);
  27481. h = jmax (h, 32);
  27482. setSize (w, h);
  27483. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  27484. repaint();
  27485. }
  27486. #else
  27487. void openPluginWindow()
  27488. {
  27489. if (isOpen || getWindowHandle() == 0)
  27490. return;
  27491. log ("Opening VST UI: " + plugin.name);
  27492. isOpen = true;
  27493. ERect* rect = 0;
  27494. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27495. dispatch (effEditOpen, 0, 0, getWindowHandle(), 0);
  27496. // do this before and after like in the steinberg example
  27497. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27498. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  27499. // Install keyboard hooks
  27500. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  27501. #if JUCE_WINDOWS
  27502. originalWndProc = 0;
  27503. pluginHWND = GetWindow ((HWND) getWindowHandle(), GW_CHILD);
  27504. if (pluginHWND == 0)
  27505. {
  27506. isOpen = false;
  27507. setSize (300, 150);
  27508. return;
  27509. }
  27510. #pragma warning (push)
  27511. #pragma warning (disable: 4244)
  27512. originalWndProc = (void*) GetWindowLongPtr (pluginHWND, GWLP_WNDPROC);
  27513. if (! pluginWantsKeys)
  27514. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) vstHookWndProc);
  27515. #pragma warning (pop)
  27516. int w, h;
  27517. RECT r;
  27518. GetWindowRect (pluginHWND, &r);
  27519. w = r.right - r.left;
  27520. h = r.bottom - r.top;
  27521. if (rect != 0)
  27522. {
  27523. const int rw = rect->right - rect->left;
  27524. const int rh = rect->bottom - rect->top;
  27525. if ((rw > 50 && rh > 50 && rw < 2000 && rh < 2000 && rw != w && rh != h)
  27526. || ((w == 0 && rw > 0) || (h == 0 && rh > 0)))
  27527. {
  27528. // very dodgy logic to decide which size is right.
  27529. if (abs (rw - w) > 350 || abs (rh - h) > 350)
  27530. {
  27531. SetWindowPos (pluginHWND, 0,
  27532. 0, 0, rw, rh,
  27533. SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  27534. GetWindowRect (pluginHWND, &r);
  27535. w = r.right - r.left;
  27536. h = r.bottom - r.top;
  27537. pluginRefusesToResize = (w != rw) || (h != rh);
  27538. w = rw;
  27539. h = rh;
  27540. }
  27541. }
  27542. }
  27543. #elif JUCE_LINUX
  27544. pluginWindow = getChildWindow ((Window) getWindowHandle());
  27545. if (pluginWindow != 0)
  27546. pluginProc = (EventProcPtr) getPropertyFromXWindow (pluginWindow,
  27547. XInternAtom (display, "_XEventProc", False));
  27548. int w = 250, h = 150;
  27549. if (rect != 0)
  27550. {
  27551. w = rect->right - rect->left;
  27552. h = rect->bottom - rect->top;
  27553. if (w == 0 || h == 0)
  27554. {
  27555. w = 250;
  27556. h = 150;
  27557. }
  27558. }
  27559. if (pluginWindow != 0)
  27560. XMapRaised (display, pluginWindow);
  27561. #endif
  27562. // double-check it's not too tiny
  27563. w = jmax (w, 32);
  27564. h = jmax (h, 32);
  27565. setSize (w, h);
  27566. #if JUCE_WINDOWS
  27567. checkPluginWindowSize();
  27568. #endif
  27569. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  27570. repaint();
  27571. }
  27572. #endif
  27573. #if ! JUCE_MAC
  27574. void closePluginWindow()
  27575. {
  27576. if (isOpen)
  27577. {
  27578. log ("Closing VST UI: " + plugin.getName());
  27579. isOpen = false;
  27580. dispatch (effEditClose, 0, 0, 0, 0);
  27581. #if JUCE_WINDOWS
  27582. #pragma warning (push)
  27583. #pragma warning (disable: 4244)
  27584. if (pluginHWND != 0 && IsWindow (pluginHWND))
  27585. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) originalWndProc);
  27586. #pragma warning (pop)
  27587. stopTimer();
  27588. if (pluginHWND != 0 && IsWindow (pluginHWND))
  27589. DestroyWindow (pluginHWND);
  27590. pluginHWND = 0;
  27591. #elif JUCE_LINUX
  27592. stopTimer();
  27593. pluginWindow = 0;
  27594. pluginProc = 0;
  27595. #endif
  27596. }
  27597. }
  27598. #endif
  27599. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt)
  27600. {
  27601. return plugin.dispatch (opcode, index, value, ptr, opt);
  27602. }
  27603. #if JUCE_WINDOWS
  27604. void checkPluginWindowSize()
  27605. {
  27606. RECT r;
  27607. GetWindowRect (pluginHWND, &r);
  27608. const int w = r.right - r.left;
  27609. const int h = r.bottom - r.top;
  27610. if (isShowing() && w > 0 && h > 0
  27611. && (w != getWidth() || h != getHeight())
  27612. && ! pluginRefusesToResize)
  27613. {
  27614. setSize (w, h);
  27615. sizeCheckCount = 0;
  27616. }
  27617. }
  27618. // hooks to get keyboard events from VST windows..
  27619. static LRESULT CALLBACK vstHookWndProc (HWND hW, UINT message, WPARAM wParam, LPARAM lParam)
  27620. {
  27621. for (int i = activeVSTWindows.size(); --i >= 0;)
  27622. {
  27623. const VSTPluginWindow* const w = activeVSTWindows.getUnchecked (i);
  27624. if (w->pluginHWND == hW)
  27625. {
  27626. if (message == WM_CHAR
  27627. || message == WM_KEYDOWN
  27628. || message == WM_SYSKEYDOWN
  27629. || message == WM_KEYUP
  27630. || message == WM_SYSKEYUP
  27631. || message == WM_APPCOMMAND)
  27632. {
  27633. SendMessage ((HWND) w->getTopLevelComponent()->getWindowHandle(),
  27634. message, wParam, lParam);
  27635. }
  27636. return CallWindowProc ((WNDPROC) (w->originalWndProc),
  27637. (HWND) w->pluginHWND,
  27638. message,
  27639. wParam,
  27640. lParam);
  27641. }
  27642. }
  27643. return DefWindowProc (hW, message, wParam, lParam);
  27644. }
  27645. #endif
  27646. #if JUCE_LINUX
  27647. // overload mouse/keyboard events to forward them to the plugin's inner window..
  27648. void sendEventToChild (XEvent* event)
  27649. {
  27650. if (pluginProc != 0)
  27651. {
  27652. // if the plugin publishes an event procedure, pass the event directly..
  27653. pluginProc (event);
  27654. }
  27655. else if (pluginWindow != 0)
  27656. {
  27657. // if the plugin has a window, then send the event to the window so that
  27658. // its message thread will pick it up..
  27659. XSendEvent (display, pluginWindow, False, 0L, event);
  27660. XFlush (display);
  27661. }
  27662. }
  27663. void mouseEnter (const MouseEvent& e)
  27664. {
  27665. if (pluginWindow != 0)
  27666. {
  27667. XEvent ev;
  27668. zerostruct (ev);
  27669. ev.xcrossing.display = display;
  27670. ev.xcrossing.type = EnterNotify;
  27671. ev.xcrossing.window = pluginWindow;
  27672. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  27673. ev.xcrossing.time = CurrentTime;
  27674. ev.xcrossing.x = e.x;
  27675. ev.xcrossing.y = e.y;
  27676. ev.xcrossing.x_root = e.getScreenX();
  27677. ev.xcrossing.y_root = e.getScreenY();
  27678. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  27679. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  27680. translateJuceToXCrossingModifiers (e, ev);
  27681. sendEventToChild (&ev);
  27682. }
  27683. }
  27684. void mouseExit (const MouseEvent& e)
  27685. {
  27686. if (pluginWindow != 0)
  27687. {
  27688. XEvent ev;
  27689. zerostruct (ev);
  27690. ev.xcrossing.display = display;
  27691. ev.xcrossing.type = LeaveNotify;
  27692. ev.xcrossing.window = pluginWindow;
  27693. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  27694. ev.xcrossing.time = CurrentTime;
  27695. ev.xcrossing.x = e.x;
  27696. ev.xcrossing.y = e.y;
  27697. ev.xcrossing.x_root = e.getScreenX();
  27698. ev.xcrossing.y_root = e.getScreenY();
  27699. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  27700. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  27701. ev.xcrossing.focus = hasKeyboardFocus (true); // TODO - yes ?
  27702. translateJuceToXCrossingModifiers (e, ev);
  27703. sendEventToChild (&ev);
  27704. }
  27705. }
  27706. void mouseMove (const MouseEvent& e)
  27707. {
  27708. if (pluginWindow != 0)
  27709. {
  27710. XEvent ev;
  27711. zerostruct (ev);
  27712. ev.xmotion.display = display;
  27713. ev.xmotion.type = MotionNotify;
  27714. ev.xmotion.window = pluginWindow;
  27715. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  27716. ev.xmotion.time = CurrentTime;
  27717. ev.xmotion.is_hint = NotifyNormal;
  27718. ev.xmotion.x = e.x;
  27719. ev.xmotion.y = e.y;
  27720. ev.xmotion.x_root = e.getScreenX();
  27721. ev.xmotion.y_root = e.getScreenY();
  27722. sendEventToChild (&ev);
  27723. }
  27724. }
  27725. void mouseDrag (const MouseEvent& e)
  27726. {
  27727. if (pluginWindow != 0)
  27728. {
  27729. XEvent ev;
  27730. zerostruct (ev);
  27731. ev.xmotion.display = display;
  27732. ev.xmotion.type = MotionNotify;
  27733. ev.xmotion.window = pluginWindow;
  27734. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  27735. ev.xmotion.time = CurrentTime;
  27736. ev.xmotion.x = e.x ;
  27737. ev.xmotion.y = e.y;
  27738. ev.xmotion.x_root = e.getScreenX();
  27739. ev.xmotion.y_root = e.getScreenY();
  27740. ev.xmotion.is_hint = NotifyNormal;
  27741. translateJuceToXMotionModifiers (e, ev);
  27742. sendEventToChild (&ev);
  27743. }
  27744. }
  27745. void mouseUp (const MouseEvent& e)
  27746. {
  27747. if (pluginWindow != 0)
  27748. {
  27749. XEvent ev;
  27750. zerostruct (ev);
  27751. ev.xbutton.display = display;
  27752. ev.xbutton.type = ButtonRelease;
  27753. ev.xbutton.window = pluginWindow;
  27754. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27755. ev.xbutton.time = CurrentTime;
  27756. ev.xbutton.x = e.x;
  27757. ev.xbutton.y = e.y;
  27758. ev.xbutton.x_root = e.getScreenX();
  27759. ev.xbutton.y_root = e.getScreenY();
  27760. translateJuceToXButtonModifiers (e, ev);
  27761. sendEventToChild (&ev);
  27762. }
  27763. }
  27764. void mouseWheelMove (const MouseEvent& e,
  27765. float incrementX,
  27766. float incrementY)
  27767. {
  27768. if (pluginWindow != 0)
  27769. {
  27770. XEvent ev;
  27771. zerostruct (ev);
  27772. ev.xbutton.display = display;
  27773. ev.xbutton.type = ButtonPress;
  27774. ev.xbutton.window = pluginWindow;
  27775. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27776. ev.xbutton.time = CurrentTime;
  27777. ev.xbutton.x = e.x;
  27778. ev.xbutton.y = e.y;
  27779. ev.xbutton.x_root = e.getScreenX();
  27780. ev.xbutton.y_root = e.getScreenY();
  27781. translateJuceToXMouseWheelModifiers (e, incrementY, ev);
  27782. sendEventToChild (&ev);
  27783. // TODO - put a usleep here ?
  27784. ev.xbutton.type = ButtonRelease;
  27785. sendEventToChild (&ev);
  27786. }
  27787. }
  27788. #endif
  27789. #if JUCE_MAC
  27790. #if ! JUCE_SUPPORT_CARBON
  27791. #error "To build VSTs, you need to enable the JUCE_SUPPORT_CARBON flag in your config!"
  27792. #endif
  27793. class InnerWrapperComponent : public CarbonViewWrapperComponent
  27794. {
  27795. public:
  27796. InnerWrapperComponent (VSTPluginWindow* const owner_)
  27797. : owner (owner_),
  27798. alreadyInside (false)
  27799. {
  27800. }
  27801. ~InnerWrapperComponent()
  27802. {
  27803. deleteWindow();
  27804. }
  27805. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  27806. {
  27807. owner->openPluginWindow (windowRef);
  27808. return 0;
  27809. }
  27810. void removeView (HIViewRef)
  27811. {
  27812. owner->dispatch (effEditClose, 0, 0, 0, 0);
  27813. owner->dispatch (effEditSleep, 0, 0, 0, 0);
  27814. }
  27815. bool getEmbeddedViewSize (int& w, int& h)
  27816. {
  27817. ERect* rect = 0;
  27818. owner->dispatch (effEditGetRect, 0, 0, &rect, 0);
  27819. w = rect->right - rect->left;
  27820. h = rect->bottom - rect->top;
  27821. return true;
  27822. }
  27823. void mouseDown (int x, int y)
  27824. {
  27825. if (! alreadyInside)
  27826. {
  27827. alreadyInside = true;
  27828. getTopLevelComponent()->toFront (true);
  27829. owner->dispatch (effEditMouse, x, y, 0, 0);
  27830. alreadyInside = false;
  27831. }
  27832. else
  27833. {
  27834. PostEvent (::mouseDown, 0);
  27835. }
  27836. }
  27837. void paint()
  27838. {
  27839. ComponentPeer* const peer = getPeer();
  27840. if (peer != 0)
  27841. {
  27842. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  27843. ERect r;
  27844. r.left = pos.getX();
  27845. r.right = r.left + getWidth();
  27846. r.top = pos.getY();
  27847. r.bottom = r.top + getHeight();
  27848. owner->dispatch (effEditDraw, 0, 0, &r, 0);
  27849. }
  27850. }
  27851. private:
  27852. VSTPluginWindow* const owner;
  27853. bool alreadyInside;
  27854. };
  27855. friend class InnerWrapperComponent;
  27856. ScopedPointer <InnerWrapperComponent> innerWrapper;
  27857. void resized()
  27858. {
  27859. innerWrapper->setSize (getWidth(), getHeight());
  27860. }
  27861. #endif
  27862. };
  27863. AudioProcessorEditor* VSTPluginInstance::createEditor()
  27864. {
  27865. if (hasEditor())
  27866. return new VSTPluginWindow (*this);
  27867. return 0;
  27868. }
  27869. void VSTPluginInstance::handleAsyncUpdate()
  27870. {
  27871. // indicates that something about the plugin has changed..
  27872. updateHostDisplay();
  27873. }
  27874. bool VSTPluginInstance::restoreProgramSettings (const fxProgram* const prog)
  27875. {
  27876. if (vst_swap (prog->chunkMagic) == 'CcnK' && vst_swap (prog->fxMagic) == 'FxCk')
  27877. {
  27878. changeProgramName (getCurrentProgram(), prog->prgName);
  27879. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  27880. setParameter (i, vst_swapFloat (prog->params[i]));
  27881. return true;
  27882. }
  27883. return false;
  27884. }
  27885. bool VSTPluginInstance::loadFromFXBFile (const void* const data,
  27886. const int dataSize)
  27887. {
  27888. if (dataSize < 28)
  27889. return false;
  27890. const fxSet* const set = (const fxSet*) data;
  27891. if ((vst_swap (set->chunkMagic) != 'CcnK' && vst_swap (set->chunkMagic) != 'KncC')
  27892. || vst_swap (set->version) > fxbVersionNum)
  27893. return false;
  27894. if (vst_swap (set->fxMagic) == 'FxBk')
  27895. {
  27896. // bank of programs
  27897. if (vst_swap (set->numPrograms) >= 0)
  27898. {
  27899. const int oldProg = getCurrentProgram();
  27900. const int numParams = vst_swap (((const fxProgram*) (set->programs))->numParams);
  27901. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27902. for (int i = 0; i < vst_swap (set->numPrograms); ++i)
  27903. {
  27904. if (i != oldProg)
  27905. {
  27906. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + i * progLen);
  27907. if (((const char*) prog) - ((const char*) set) >= dataSize)
  27908. return false;
  27909. if (vst_swap (set->numPrograms) > 0)
  27910. setCurrentProgram (i);
  27911. if (! restoreProgramSettings (prog))
  27912. return false;
  27913. }
  27914. }
  27915. if (vst_swap (set->numPrograms) > 0)
  27916. setCurrentProgram (oldProg);
  27917. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + oldProg * progLen);
  27918. if (((const char*) prog) - ((const char*) set) >= dataSize)
  27919. return false;
  27920. if (! restoreProgramSettings (prog))
  27921. return false;
  27922. }
  27923. }
  27924. else if (vst_swap (set->fxMagic) == 'FxCk')
  27925. {
  27926. // single program
  27927. const fxProgram* const prog = (const fxProgram*) data;
  27928. if (vst_swap (prog->chunkMagic) != 'CcnK')
  27929. return false;
  27930. changeProgramName (getCurrentProgram(), prog->prgName);
  27931. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  27932. setParameter (i, vst_swapFloat (prog->params[i]));
  27933. }
  27934. else if (vst_swap (set->fxMagic) == 'FBCh' || vst_swap (set->fxMagic) == 'hCBF')
  27935. {
  27936. // non-preset chunk
  27937. const fxChunkSet* const cset = (const fxChunkSet*) data;
  27938. if (vst_swap (cset->chunkSize) + sizeof (fxChunkSet) - 8 > (unsigned int) dataSize)
  27939. return false;
  27940. setChunkData (cset->chunk, vst_swap (cset->chunkSize), false);
  27941. }
  27942. else if (vst_swap (set->fxMagic) == 'FPCh' || vst_swap (set->fxMagic) == 'hCPF')
  27943. {
  27944. // preset chunk
  27945. const fxProgramSet* const cset = (const fxProgramSet*) data;
  27946. if (vst_swap (cset->chunkSize) + sizeof (fxProgramSet) - 8 > (unsigned int) dataSize)
  27947. return false;
  27948. setChunkData (cset->chunk, vst_swap (cset->chunkSize), true);
  27949. changeProgramName (getCurrentProgram(), cset->name);
  27950. }
  27951. else
  27952. {
  27953. return false;
  27954. }
  27955. return true;
  27956. }
  27957. void VSTPluginInstance::setParamsInProgramBlock (fxProgram* const prog)
  27958. {
  27959. const int numParams = getNumParameters();
  27960. prog->chunkMagic = vst_swap ('CcnK');
  27961. prog->byteSize = 0;
  27962. prog->fxMagic = vst_swap ('FxCk');
  27963. prog->version = vst_swap (fxbVersionNum);
  27964. prog->fxID = vst_swap (getUID());
  27965. prog->fxVersion = vst_swap (getVersionNumber());
  27966. prog->numParams = vst_swap (numParams);
  27967. getCurrentProgramName().copyToCString (prog->prgName, sizeof (prog->prgName) - 1);
  27968. for (int i = 0; i < numParams; ++i)
  27969. prog->params[i] = vst_swapFloat (getParameter (i));
  27970. }
  27971. bool VSTPluginInstance::saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB)
  27972. {
  27973. const int numPrograms = getNumPrograms();
  27974. const int numParams = getNumParameters();
  27975. if (usesChunks())
  27976. {
  27977. if (isFXB)
  27978. {
  27979. MemoryBlock chunk;
  27980. getChunkData (chunk, false, maxSizeMB);
  27981. const size_t totalLen = sizeof (fxChunkSet) + chunk.getSize() - 8;
  27982. dest.setSize (totalLen, true);
  27983. fxChunkSet* const set = (fxChunkSet*) dest.getData();
  27984. set->chunkMagic = vst_swap ('CcnK');
  27985. set->byteSize = 0;
  27986. set->fxMagic = vst_swap ('FBCh');
  27987. set->version = vst_swap (fxbVersionNum);
  27988. set->fxID = vst_swap (getUID());
  27989. set->fxVersion = vst_swap (getVersionNumber());
  27990. set->numPrograms = vst_swap (numPrograms);
  27991. set->chunkSize = vst_swap ((long) chunk.getSize());
  27992. chunk.copyTo (set->chunk, 0, chunk.getSize());
  27993. }
  27994. else
  27995. {
  27996. MemoryBlock chunk;
  27997. getChunkData (chunk, true, maxSizeMB);
  27998. const size_t totalLen = sizeof (fxProgramSet) + chunk.getSize() - 8;
  27999. dest.setSize (totalLen, true);
  28000. fxProgramSet* const set = (fxProgramSet*) dest.getData();
  28001. set->chunkMagic = vst_swap ('CcnK');
  28002. set->byteSize = 0;
  28003. set->fxMagic = vst_swap ('FPCh');
  28004. set->version = vst_swap (fxbVersionNum);
  28005. set->fxID = vst_swap (getUID());
  28006. set->fxVersion = vst_swap (getVersionNumber());
  28007. set->numPrograms = vst_swap (numPrograms);
  28008. set->chunkSize = vst_swap ((long) chunk.getSize());
  28009. getCurrentProgramName().copyToCString (set->name, sizeof (set->name) - 1);
  28010. chunk.copyTo (set->chunk, 0, chunk.getSize());
  28011. }
  28012. }
  28013. else
  28014. {
  28015. if (isFXB)
  28016. {
  28017. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  28018. const int len = (sizeof (fxSet) - sizeof (fxProgram)) + progLen * jmax (1, numPrograms);
  28019. dest.setSize (len, true);
  28020. fxSet* const set = (fxSet*) dest.getData();
  28021. set->chunkMagic = vst_swap ('CcnK');
  28022. set->byteSize = 0;
  28023. set->fxMagic = vst_swap ('FxBk');
  28024. set->version = vst_swap (fxbVersionNum);
  28025. set->fxID = vst_swap (getUID());
  28026. set->fxVersion = vst_swap (getVersionNumber());
  28027. set->numPrograms = vst_swap (numPrograms);
  28028. const int oldProgram = getCurrentProgram();
  28029. MemoryBlock oldSettings;
  28030. createTempParameterStore (oldSettings);
  28031. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + oldProgram * progLen));
  28032. for (int i = 0; i < numPrograms; ++i)
  28033. {
  28034. if (i != oldProgram)
  28035. {
  28036. setCurrentProgram (i);
  28037. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + i * progLen));
  28038. }
  28039. }
  28040. setCurrentProgram (oldProgram);
  28041. restoreFromTempParameterStore (oldSettings);
  28042. }
  28043. else
  28044. {
  28045. const int totalLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  28046. dest.setSize (totalLen, true);
  28047. setParamsInProgramBlock ((fxProgram*) dest.getData());
  28048. }
  28049. }
  28050. return true;
  28051. }
  28052. void VSTPluginInstance::getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const
  28053. {
  28054. if (usesChunks())
  28055. {
  28056. void* data = 0;
  28057. const int bytes = dispatch (effGetChunk, isPreset ? 1 : 0, 0, &data, 0.0f);
  28058. if (data != 0 && bytes <= maxSizeMB * 1024 * 1024)
  28059. {
  28060. mb.setSize (bytes);
  28061. mb.copyFrom (data, 0, bytes);
  28062. }
  28063. }
  28064. }
  28065. void VSTPluginInstance::setChunkData (const char* data, int size, bool isPreset)
  28066. {
  28067. if (size > 0 && usesChunks())
  28068. {
  28069. dispatch (effSetChunk, isPreset ? 1 : 0, size, (void*) data, 0.0f);
  28070. if (! isPreset)
  28071. updateStoredProgramNames();
  28072. }
  28073. }
  28074. void VSTPluginInstance::timerCallback()
  28075. {
  28076. if (dispatch (effIdle, 0, 0, 0, 0) == 0)
  28077. stopTimer();
  28078. }
  28079. int VSTPluginInstance::dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const
  28080. {
  28081. const ScopedLock sl (lock);
  28082. ++insideVSTCallback;
  28083. int result = 0;
  28084. try
  28085. {
  28086. if (effect != 0)
  28087. {
  28088. #if JUCE_MAC
  28089. if (module->resFileId != 0)
  28090. UseResFile (module->resFileId);
  28091. #endif
  28092. result = effect->dispatcher (effect, opcode, index, value, ptr, opt);
  28093. #if JUCE_MAC
  28094. module->resFileId = CurResFile();
  28095. #endif
  28096. --insideVSTCallback;
  28097. return result;
  28098. }
  28099. }
  28100. catch (...)
  28101. {
  28102. }
  28103. --insideVSTCallback;
  28104. return result;
  28105. }
  28106. // handles non plugin-specific callbacks..
  28107. static const int defaultVSTSampleRateValue = 16384;
  28108. static const int defaultVSTBlockSizeValue = 512;
  28109. static VstIntPtr handleGeneralCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  28110. {
  28111. (void) index;
  28112. (void) value;
  28113. (void) opt;
  28114. switch (opcode)
  28115. {
  28116. case audioMasterCanDo:
  28117. {
  28118. static const char* canDos[] = { "supplyIdle",
  28119. "sendVstEvents",
  28120. "sendVstMidiEvent",
  28121. "sendVstTimeInfo",
  28122. "receiveVstEvents",
  28123. "receiveVstMidiEvent",
  28124. "supportShell",
  28125. "shellCategory" };
  28126. for (int i = 0; i < numElementsInArray (canDos); ++i)
  28127. if (strcmp (canDos[i], (const char*) ptr) == 0)
  28128. return 1;
  28129. return 0;
  28130. }
  28131. case audioMasterVersion: return 0x2400;
  28132. case audioMasterCurrentId: return shellUIDToCreate;
  28133. case audioMasterGetNumAutomatableParameters: return 0;
  28134. case audioMasterGetAutomationState: return 1;
  28135. case audioMasterGetVendorVersion: return 0x0101;
  28136. case audioMasterGetVendorString:
  28137. case audioMasterGetProductString:
  28138. {
  28139. String hostName ("Juce VST Host");
  28140. if (JUCEApplication::getInstance() != 0)
  28141. hostName = JUCEApplication::getInstance()->getApplicationName();
  28142. hostName.copyToCString ((char*) ptr, jmin (kVstMaxVendorStrLen, kVstMaxProductStrLen) - 1);
  28143. break;
  28144. }
  28145. case audioMasterGetSampleRate: return (VstIntPtr) defaultVSTSampleRateValue;
  28146. case audioMasterGetBlockSize: return (VstIntPtr) defaultVSTBlockSizeValue;
  28147. case audioMasterSetOutputSampleRate: return 0;
  28148. default:
  28149. DBG ("*** Unhandled VST Callback: " + String ((int) opcode));
  28150. break;
  28151. }
  28152. return 0;
  28153. }
  28154. // handles callbacks for a specific plugin
  28155. VstIntPtr VSTPluginInstance::handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  28156. {
  28157. switch (opcode)
  28158. {
  28159. case audioMasterAutomate:
  28160. sendParamChangeMessageToListeners (index, opt);
  28161. break;
  28162. case audioMasterProcessEvents:
  28163. handleMidiFromPlugin ((const VstEvents*) ptr);
  28164. break;
  28165. case audioMasterGetTime:
  28166. #if JUCE_MSVC
  28167. #pragma warning (push)
  28168. #pragma warning (disable: 4311)
  28169. #endif
  28170. return (VstIntPtr) &vstHostTime;
  28171. #if JUCE_MSVC
  28172. #pragma warning (pop)
  28173. #endif
  28174. break;
  28175. case audioMasterIdle:
  28176. if (insideVSTCallback == 0 && MessageManager::getInstance()->isThisTheMessageThread())
  28177. {
  28178. ++insideVSTCallback;
  28179. #if JUCE_MAC
  28180. if (getActiveEditor() != 0)
  28181. dispatch (effEditIdle, 0, 0, 0, 0);
  28182. #endif
  28183. juce_callAnyTimersSynchronously();
  28184. handleUpdateNowIfNeeded();
  28185. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  28186. ComponentPeer::getPeer (i)->performAnyPendingRepaintsNow();
  28187. --insideVSTCallback;
  28188. }
  28189. break;
  28190. case audioMasterUpdateDisplay:
  28191. triggerAsyncUpdate();
  28192. break;
  28193. case audioMasterTempoAt:
  28194. // returns (10000 * bpm)
  28195. break;
  28196. case audioMasterNeedIdle:
  28197. startTimer (50);
  28198. break;
  28199. case audioMasterSizeWindow:
  28200. if (getActiveEditor() != 0)
  28201. getActiveEditor()->setSize (index, value);
  28202. return 1;
  28203. case audioMasterGetSampleRate:
  28204. return (VstIntPtr) (getSampleRate() > 0 ? getSampleRate() : defaultVSTSampleRateValue);
  28205. case audioMasterGetBlockSize:
  28206. return (VstIntPtr) (getBlockSize() > 0 ? getBlockSize() : defaultVSTBlockSizeValue);
  28207. case audioMasterWantMidi:
  28208. wantsMidiMessages = true;
  28209. break;
  28210. case audioMasterGetDirectory:
  28211. #if JUCE_MAC
  28212. return (VstIntPtr) (void*) &module->parentDirFSSpec;
  28213. #else
  28214. return (VstIntPtr) (pointer_sized_uint) module->fullParentDirectoryPathName.toUTF8();
  28215. #endif
  28216. case audioMasterGetAutomationState:
  28217. // returns 0: not supported, 1: off, 2:read, 3:write, 4:read/write
  28218. break;
  28219. // none of these are handled (yet)..
  28220. case audioMasterBeginEdit:
  28221. case audioMasterEndEdit:
  28222. case audioMasterSetTime:
  28223. case audioMasterPinConnected:
  28224. case audioMasterGetParameterQuantization:
  28225. case audioMasterIOChanged:
  28226. case audioMasterGetInputLatency:
  28227. case audioMasterGetOutputLatency:
  28228. case audioMasterGetPreviousPlug:
  28229. case audioMasterGetNextPlug:
  28230. case audioMasterWillReplaceOrAccumulate:
  28231. case audioMasterGetCurrentProcessLevel:
  28232. case audioMasterOfflineStart:
  28233. case audioMasterOfflineRead:
  28234. case audioMasterOfflineWrite:
  28235. case audioMasterOfflineGetCurrentPass:
  28236. case audioMasterOfflineGetCurrentMetaPass:
  28237. case audioMasterVendorSpecific:
  28238. case audioMasterSetIcon:
  28239. case audioMasterGetLanguage:
  28240. case audioMasterOpenWindow:
  28241. case audioMasterCloseWindow:
  28242. break;
  28243. default:
  28244. return handleGeneralCallback (opcode, index, value, ptr, opt);
  28245. }
  28246. return 0;
  28247. }
  28248. // entry point for all callbacks from the plugin
  28249. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt)
  28250. {
  28251. try
  28252. {
  28253. if (effect != 0 && effect->resvd2 != 0)
  28254. {
  28255. return ((VSTPluginInstance*)(effect->resvd2))
  28256. ->handleCallback (opcode, index, value, ptr, opt);
  28257. }
  28258. return handleGeneralCallback (opcode, index, value, ptr, opt);
  28259. }
  28260. catch (...)
  28261. {
  28262. return 0;
  28263. }
  28264. }
  28265. const String VSTPluginInstance::getVersion() const
  28266. {
  28267. unsigned int v = dispatch (effGetVendorVersion, 0, 0, 0, 0);
  28268. String s;
  28269. if (v == 0 || v == -1)
  28270. v = getVersionNumber();
  28271. if (v != 0)
  28272. {
  28273. int versionBits[4];
  28274. int n = 0;
  28275. while (v != 0)
  28276. {
  28277. versionBits [n++] = (v & 0xff);
  28278. v >>= 8;
  28279. }
  28280. s << 'V';
  28281. while (n > 0)
  28282. {
  28283. s << versionBits [--n];
  28284. if (n > 0)
  28285. s << '.';
  28286. }
  28287. }
  28288. return s;
  28289. }
  28290. int VSTPluginInstance::getUID() const
  28291. {
  28292. int uid = effect != 0 ? effect->uniqueID : 0;
  28293. if (uid == 0)
  28294. uid = module->file.hashCode();
  28295. return uid;
  28296. }
  28297. const String VSTPluginInstance::getCategory() const
  28298. {
  28299. const char* result = 0;
  28300. switch (dispatch (effGetPlugCategory, 0, 0, 0, 0))
  28301. {
  28302. case kPlugCategEffect: result = "Effect"; break;
  28303. case kPlugCategSynth: result = "Synth"; break;
  28304. case kPlugCategAnalysis: result = "Anaylsis"; break;
  28305. case kPlugCategMastering: result = "Mastering"; break;
  28306. case kPlugCategSpacializer: result = "Spacial"; break;
  28307. case kPlugCategRoomFx: result = "Reverb"; break;
  28308. case kPlugSurroundFx: result = "Surround"; break;
  28309. case kPlugCategRestoration: result = "Restoration"; break;
  28310. case kPlugCategGenerator: result = "Tone generation"; break;
  28311. default: break;
  28312. }
  28313. return result;
  28314. }
  28315. float VSTPluginInstance::getParameter (int index)
  28316. {
  28317. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  28318. {
  28319. try
  28320. {
  28321. const ScopedLock sl (lock);
  28322. return effect->getParameter (effect, index);
  28323. }
  28324. catch (...)
  28325. {
  28326. }
  28327. }
  28328. return 0.0f;
  28329. }
  28330. void VSTPluginInstance::setParameter (int index, float newValue)
  28331. {
  28332. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  28333. {
  28334. try
  28335. {
  28336. const ScopedLock sl (lock);
  28337. if (effect->getParameter (effect, index) != newValue)
  28338. effect->setParameter (effect, index, newValue);
  28339. }
  28340. catch (...)
  28341. {
  28342. }
  28343. }
  28344. }
  28345. const String VSTPluginInstance::getParameterName (int index)
  28346. {
  28347. if (effect != 0)
  28348. {
  28349. jassert (index >= 0 && index < effect->numParams);
  28350. char nm [256];
  28351. zerostruct (nm);
  28352. dispatch (effGetParamName, index, 0, nm, 0);
  28353. return String (nm).trim();
  28354. }
  28355. return String::empty;
  28356. }
  28357. const String VSTPluginInstance::getParameterLabel (int index) const
  28358. {
  28359. if (effect != 0)
  28360. {
  28361. jassert (index >= 0 && index < effect->numParams);
  28362. char nm [256];
  28363. zerostruct (nm);
  28364. dispatch (effGetParamLabel, index, 0, nm, 0);
  28365. return String (nm).trim();
  28366. }
  28367. return String::empty;
  28368. }
  28369. const String VSTPluginInstance::getParameterText (int index)
  28370. {
  28371. if (effect != 0)
  28372. {
  28373. jassert (index >= 0 && index < effect->numParams);
  28374. char nm [256];
  28375. zerostruct (nm);
  28376. dispatch (effGetParamDisplay, index, 0, nm, 0);
  28377. return String (nm).trim();
  28378. }
  28379. return String::empty;
  28380. }
  28381. bool VSTPluginInstance::isParameterAutomatable (int index) const
  28382. {
  28383. if (effect != 0)
  28384. {
  28385. jassert (index >= 0 && index < effect->numParams);
  28386. return dispatch (effCanBeAutomated, index, 0, 0, 0) != 0;
  28387. }
  28388. return false;
  28389. }
  28390. void VSTPluginInstance::createTempParameterStore (MemoryBlock& dest)
  28391. {
  28392. dest.setSize (64 + 4 * getNumParameters());
  28393. dest.fillWith (0);
  28394. getCurrentProgramName().copyToCString ((char*) dest.getData(), 63);
  28395. float* const p = (float*) (((char*) dest.getData()) + 64);
  28396. for (int i = 0; i < getNumParameters(); ++i)
  28397. p[i] = getParameter(i);
  28398. }
  28399. void VSTPluginInstance::restoreFromTempParameterStore (const MemoryBlock& m)
  28400. {
  28401. changeProgramName (getCurrentProgram(), (const char*) m.getData());
  28402. float* p = (float*) (((char*) m.getData()) + 64);
  28403. for (int i = 0; i < getNumParameters(); ++i)
  28404. setParameter (i, p[i]);
  28405. }
  28406. void VSTPluginInstance::setCurrentProgram (int newIndex)
  28407. {
  28408. if (getNumPrograms() > 0 && newIndex != getCurrentProgram())
  28409. dispatch (effSetProgram, 0, jlimit (0, getNumPrograms() - 1, newIndex), 0, 0);
  28410. }
  28411. const String VSTPluginInstance::getProgramName (int index)
  28412. {
  28413. if (index == getCurrentProgram())
  28414. {
  28415. return getCurrentProgramName();
  28416. }
  28417. else if (effect != 0)
  28418. {
  28419. char nm [256];
  28420. zerostruct (nm);
  28421. if (dispatch (effGetProgramNameIndexed,
  28422. jlimit (0, getNumPrograms(), index),
  28423. -1, nm, 0) != 0)
  28424. {
  28425. return String (nm).trim();
  28426. }
  28427. }
  28428. return programNames [index];
  28429. }
  28430. void VSTPluginInstance::changeProgramName (int index, const String& newName)
  28431. {
  28432. if (index == getCurrentProgram())
  28433. {
  28434. if (getNumPrograms() > 0 && newName != getCurrentProgramName())
  28435. dispatch (effSetProgramName, 0, 0, (void*) newName.substring (0, 24).toCString(), 0.0f);
  28436. }
  28437. else
  28438. {
  28439. jassertfalse; // xxx not implemented!
  28440. }
  28441. }
  28442. void VSTPluginInstance::updateStoredProgramNames()
  28443. {
  28444. if (effect != 0 && getNumPrograms() > 0)
  28445. {
  28446. char nm [256];
  28447. zerostruct (nm);
  28448. // only do this if the plugin can't use indexed names..
  28449. if (dispatch (effGetProgramNameIndexed, 0, -1, nm, 0) == 0)
  28450. {
  28451. const int oldProgram = getCurrentProgram();
  28452. MemoryBlock oldSettings;
  28453. createTempParameterStore (oldSettings);
  28454. for (int i = 0; i < getNumPrograms(); ++i)
  28455. {
  28456. setCurrentProgram (i);
  28457. getCurrentProgramName(); // (this updates the list)
  28458. }
  28459. setCurrentProgram (oldProgram);
  28460. restoreFromTempParameterStore (oldSettings);
  28461. }
  28462. }
  28463. }
  28464. const String VSTPluginInstance::getCurrentProgramName()
  28465. {
  28466. if (effect != 0)
  28467. {
  28468. char nm [256];
  28469. zerostruct (nm);
  28470. dispatch (effGetProgramName, 0, 0, nm, 0);
  28471. const int index = getCurrentProgram();
  28472. if (programNames[index].isEmpty())
  28473. {
  28474. while (programNames.size() < index)
  28475. programNames.add (String::empty);
  28476. programNames.set (index, String (nm).trim());
  28477. }
  28478. return String (nm).trim();
  28479. }
  28480. return String::empty;
  28481. }
  28482. const String VSTPluginInstance::getInputChannelName (int index) const
  28483. {
  28484. if (index >= 0 && index < getNumInputChannels())
  28485. {
  28486. VstPinProperties pinProps;
  28487. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  28488. return String (pinProps.label, sizeof (pinProps.label));
  28489. }
  28490. return String::empty;
  28491. }
  28492. bool VSTPluginInstance::isInputChannelStereoPair (int index) const
  28493. {
  28494. if (index < 0 || index >= getNumInputChannels())
  28495. return false;
  28496. VstPinProperties pinProps;
  28497. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  28498. return (pinProps.flags & kVstPinIsStereo) != 0;
  28499. return true;
  28500. }
  28501. const String VSTPluginInstance::getOutputChannelName (int index) const
  28502. {
  28503. if (index >= 0 && index < getNumOutputChannels())
  28504. {
  28505. VstPinProperties pinProps;
  28506. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  28507. return String (pinProps.label, sizeof (pinProps.label));
  28508. }
  28509. return String::empty;
  28510. }
  28511. bool VSTPluginInstance::isOutputChannelStereoPair (int index) const
  28512. {
  28513. if (index < 0 || index >= getNumOutputChannels())
  28514. return false;
  28515. VstPinProperties pinProps;
  28516. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  28517. return (pinProps.flags & kVstPinIsStereo) != 0;
  28518. return true;
  28519. }
  28520. void VSTPluginInstance::setPower (const bool on)
  28521. {
  28522. dispatch (effMainsChanged, 0, on ? 1 : 0, 0, 0);
  28523. isPowerOn = on;
  28524. }
  28525. const int defaultMaxSizeMB = 64;
  28526. void VSTPluginInstance::getStateInformation (MemoryBlock& destData)
  28527. {
  28528. saveToFXBFile (destData, true, defaultMaxSizeMB);
  28529. }
  28530. void VSTPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  28531. {
  28532. saveToFXBFile (destData, false, defaultMaxSizeMB);
  28533. }
  28534. void VSTPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  28535. {
  28536. loadFromFXBFile (data, sizeInBytes);
  28537. }
  28538. void VSTPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  28539. {
  28540. loadFromFXBFile (data, sizeInBytes);
  28541. }
  28542. VSTPluginFormat::VSTPluginFormat()
  28543. {
  28544. }
  28545. VSTPluginFormat::~VSTPluginFormat()
  28546. {
  28547. }
  28548. void VSTPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  28549. const String& fileOrIdentifier)
  28550. {
  28551. if (! fileMightContainThisPluginType (fileOrIdentifier))
  28552. return;
  28553. PluginDescription desc;
  28554. desc.fileOrIdentifier = fileOrIdentifier;
  28555. desc.uid = 0;
  28556. ScopedPointer <VSTPluginInstance> instance (dynamic_cast <VSTPluginInstance*> (createInstanceFromDescription (desc)));
  28557. if (instance == 0)
  28558. return;
  28559. try
  28560. {
  28561. #if JUCE_MAC
  28562. if (instance->module->resFileId != 0)
  28563. UseResFile (instance->module->resFileId);
  28564. #endif
  28565. instance->fillInPluginDescription (desc);
  28566. VstPlugCategory category = (VstPlugCategory) instance->dispatch (effGetPlugCategory, 0, 0, 0, 0);
  28567. if (category != kPlugCategShell)
  28568. {
  28569. // Normal plugin...
  28570. results.add (new PluginDescription (desc));
  28571. ++insideVSTCallback;
  28572. instance->dispatch (effOpen, 0, 0, 0, 0);
  28573. --insideVSTCallback;
  28574. }
  28575. else
  28576. {
  28577. // It's a shell plugin, so iterate all the subtypes...
  28578. char shellEffectName [64];
  28579. for (;;)
  28580. {
  28581. zerostruct (shellEffectName);
  28582. const int uid = instance->dispatch (effShellGetNextPlugin, 0, 0, shellEffectName, 0);
  28583. if (uid == 0)
  28584. {
  28585. break;
  28586. }
  28587. else
  28588. {
  28589. desc.uid = uid;
  28590. desc.name = shellEffectName;
  28591. bool alreadyThere = false;
  28592. for (int i = results.size(); --i >= 0;)
  28593. {
  28594. PluginDescription* const d = results.getUnchecked(i);
  28595. if (d->isDuplicateOf (desc))
  28596. {
  28597. alreadyThere = true;
  28598. break;
  28599. }
  28600. }
  28601. if (! alreadyThere)
  28602. results.add (new PluginDescription (desc));
  28603. }
  28604. }
  28605. }
  28606. }
  28607. catch (...)
  28608. {
  28609. // crashed while loading...
  28610. }
  28611. }
  28612. AudioPluginInstance* VSTPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  28613. {
  28614. ScopedPointer <VSTPluginInstance> result;
  28615. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  28616. {
  28617. File file (desc.fileOrIdentifier);
  28618. const File previousWorkingDirectory (File::getCurrentWorkingDirectory());
  28619. file.getParentDirectory().setAsCurrentWorkingDirectory();
  28620. const ReferenceCountedObjectPtr <ModuleHandle> module (ModuleHandle::findOrCreateModule (file));
  28621. if (module != 0)
  28622. {
  28623. shellUIDToCreate = desc.uid;
  28624. result = new VSTPluginInstance (module);
  28625. if (result->effect != 0)
  28626. {
  28627. result->effect->resvd2 = (VstIntPtr) (pointer_sized_int) (VSTPluginInstance*) result;
  28628. result->initialise();
  28629. }
  28630. else
  28631. {
  28632. result = 0;
  28633. }
  28634. }
  28635. previousWorkingDirectory.setAsCurrentWorkingDirectory();
  28636. }
  28637. return result.release();
  28638. }
  28639. bool VSTPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  28640. {
  28641. const File f (fileOrIdentifier);
  28642. #if JUCE_MAC
  28643. if (f.isDirectory() && f.hasFileExtension (".vst"))
  28644. return true;
  28645. #if JUCE_PPC
  28646. FSRef fileRef;
  28647. if (PlatformUtilities::makeFSRefFromPath (&fileRef, f.getFullPathName()))
  28648. {
  28649. const short resFileId = FSOpenResFile (&fileRef, fsRdPerm);
  28650. if (resFileId != -1)
  28651. {
  28652. const int numEffects = Count1Resources ('aEff');
  28653. CloseResFile (resFileId);
  28654. if (numEffects > 0)
  28655. return true;
  28656. }
  28657. }
  28658. #endif
  28659. return false;
  28660. #elif JUCE_WINDOWS
  28661. return f.existsAsFile() && f.hasFileExtension (".dll");
  28662. #elif JUCE_LINUX
  28663. return f.existsAsFile() && f.hasFileExtension (".so");
  28664. #endif
  28665. }
  28666. const String VSTPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  28667. {
  28668. return fileOrIdentifier;
  28669. }
  28670. bool VSTPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  28671. {
  28672. return File (desc.fileOrIdentifier).exists();
  28673. }
  28674. const StringArray VSTPluginFormat::searchPathsForPlugins (const FileSearchPath& directoriesToSearch, const bool recursive)
  28675. {
  28676. StringArray results;
  28677. for (int j = 0; j < directoriesToSearch.getNumPaths(); ++j)
  28678. recursiveFileSearch (results, directoriesToSearch [j], recursive);
  28679. return results;
  28680. }
  28681. void VSTPluginFormat::recursiveFileSearch (StringArray& results, const File& dir, const bool recursive)
  28682. {
  28683. // avoid allowing the dir iterator to be recursive, because we want to avoid letting it delve inside
  28684. // .component or .vst directories.
  28685. DirectoryIterator iter (dir, false, "*", File::findFilesAndDirectories);
  28686. while (iter.next())
  28687. {
  28688. const File f (iter.getFile());
  28689. bool isPlugin = false;
  28690. if (fileMightContainThisPluginType (f.getFullPathName()))
  28691. {
  28692. isPlugin = true;
  28693. results.add (f.getFullPathName());
  28694. }
  28695. if (recursive && (! isPlugin) && f.isDirectory())
  28696. recursiveFileSearch (results, f, true);
  28697. }
  28698. }
  28699. const FileSearchPath VSTPluginFormat::getDefaultLocationsToSearch()
  28700. {
  28701. #if JUCE_MAC
  28702. return FileSearchPath ("~/Library/Audio/Plug-Ins/VST;/Library/Audio/Plug-Ins/VST");
  28703. #elif JUCE_WINDOWS
  28704. const String programFiles (File::getSpecialLocation (File::globalApplicationsDirectory).getFullPathName());
  28705. return FileSearchPath (programFiles + "\\Steinberg\\VstPlugins");
  28706. #elif JUCE_LINUX
  28707. return FileSearchPath ("/usr/lib/vst");
  28708. #endif
  28709. }
  28710. END_JUCE_NAMESPACE
  28711. #endif
  28712. #undef log
  28713. #endif
  28714. /*** End of inlined file: juce_VSTPluginFormat.cpp ***/
  28715. /*** End of inlined file: juce_VSTPluginFormat.mm ***/
  28716. /*** Start of inlined file: juce_AudioProcessor.cpp ***/
  28717. BEGIN_JUCE_NAMESPACE
  28718. AudioProcessor::AudioProcessor()
  28719. : playHead (0),
  28720. activeEditor (0),
  28721. sampleRate (0),
  28722. blockSize (0),
  28723. numInputChannels (0),
  28724. numOutputChannels (0),
  28725. latencySamples (0),
  28726. suspended (false),
  28727. nonRealtime (false)
  28728. {
  28729. }
  28730. AudioProcessor::~AudioProcessor()
  28731. {
  28732. // ooh, nasty - the editor should have been deleted before the filter
  28733. // that it refers to is deleted..
  28734. jassert (activeEditor == 0);
  28735. #if JUCE_DEBUG
  28736. // This will fail if you've called beginParameterChangeGesture() for one
  28737. // or more parameters without having made a corresponding call to endParameterChangeGesture...
  28738. jassert (changingParams.countNumberOfSetBits() == 0);
  28739. #endif
  28740. }
  28741. void AudioProcessor::setPlayHead (AudioPlayHead* const newPlayHead) throw()
  28742. {
  28743. playHead = newPlayHead;
  28744. }
  28745. void AudioProcessor::addListener (AudioProcessorListener* const newListener)
  28746. {
  28747. const ScopedLock sl (listenerLock);
  28748. listeners.addIfNotAlreadyThere (newListener);
  28749. }
  28750. void AudioProcessor::removeListener (AudioProcessorListener* const listenerToRemove)
  28751. {
  28752. const ScopedLock sl (listenerLock);
  28753. listeners.removeValue (listenerToRemove);
  28754. }
  28755. void AudioProcessor::setPlayConfigDetails (const int numIns,
  28756. const int numOuts,
  28757. const double sampleRate_,
  28758. const int blockSize_) throw()
  28759. {
  28760. numInputChannels = numIns;
  28761. numOutputChannels = numOuts;
  28762. sampleRate = sampleRate_;
  28763. blockSize = blockSize_;
  28764. }
  28765. void AudioProcessor::setNonRealtime (const bool nonRealtime_) throw()
  28766. {
  28767. nonRealtime = nonRealtime_;
  28768. }
  28769. void AudioProcessor::setLatencySamples (const int newLatency)
  28770. {
  28771. if (latencySamples != newLatency)
  28772. {
  28773. latencySamples = newLatency;
  28774. updateHostDisplay();
  28775. }
  28776. }
  28777. void AudioProcessor::setParameterNotifyingHost (const int parameterIndex,
  28778. const float newValue)
  28779. {
  28780. setParameter (parameterIndex, newValue);
  28781. sendParamChangeMessageToListeners (parameterIndex, newValue);
  28782. }
  28783. void AudioProcessor::sendParamChangeMessageToListeners (const int parameterIndex, const float newValue)
  28784. {
  28785. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  28786. for (int i = listeners.size(); --i >= 0;)
  28787. {
  28788. AudioProcessorListener* l;
  28789. {
  28790. const ScopedLock sl (listenerLock);
  28791. l = listeners [i];
  28792. }
  28793. if (l != 0)
  28794. l->audioProcessorParameterChanged (this, parameterIndex, newValue);
  28795. }
  28796. }
  28797. void AudioProcessor::beginParameterChangeGesture (int parameterIndex)
  28798. {
  28799. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  28800. #if JUCE_DEBUG
  28801. // This means you've called beginParameterChangeGesture twice in succession without a matching
  28802. // call to endParameterChangeGesture. That might be fine in most hosts, but better to avoid doing it.
  28803. jassert (! changingParams [parameterIndex]);
  28804. changingParams.setBit (parameterIndex);
  28805. #endif
  28806. for (int i = listeners.size(); --i >= 0;)
  28807. {
  28808. AudioProcessorListener* l;
  28809. {
  28810. const ScopedLock sl (listenerLock);
  28811. l = listeners [i];
  28812. }
  28813. if (l != 0)
  28814. l->audioProcessorParameterChangeGestureBegin (this, parameterIndex);
  28815. }
  28816. }
  28817. void AudioProcessor::endParameterChangeGesture (int parameterIndex)
  28818. {
  28819. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  28820. #if JUCE_DEBUG
  28821. // This means you've called endParameterChangeGesture without having previously called
  28822. // endParameterChangeGesture. That might be fine in most hosts, but better to keep the
  28823. // calls matched correctly.
  28824. jassert (changingParams [parameterIndex]);
  28825. changingParams.clearBit (parameterIndex);
  28826. #endif
  28827. for (int i = listeners.size(); --i >= 0;)
  28828. {
  28829. AudioProcessorListener* l;
  28830. {
  28831. const ScopedLock sl (listenerLock);
  28832. l = listeners [i];
  28833. }
  28834. if (l != 0)
  28835. l->audioProcessorParameterChangeGestureEnd (this, parameterIndex);
  28836. }
  28837. }
  28838. void AudioProcessor::updateHostDisplay()
  28839. {
  28840. for (int i = listeners.size(); --i >= 0;)
  28841. {
  28842. AudioProcessorListener* l;
  28843. {
  28844. const ScopedLock sl (listenerLock);
  28845. l = listeners [i];
  28846. }
  28847. if (l != 0)
  28848. l->audioProcessorChanged (this);
  28849. }
  28850. }
  28851. bool AudioProcessor::isParameterAutomatable (int /*parameterIndex*/) const
  28852. {
  28853. return true;
  28854. }
  28855. bool AudioProcessor::isMetaParameter (int /*parameterIndex*/) const
  28856. {
  28857. return false;
  28858. }
  28859. void AudioProcessor::suspendProcessing (const bool shouldBeSuspended)
  28860. {
  28861. const ScopedLock sl (callbackLock);
  28862. suspended = shouldBeSuspended;
  28863. }
  28864. void AudioProcessor::reset()
  28865. {
  28866. }
  28867. void AudioProcessor::editorBeingDeleted (AudioProcessorEditor* const editor) throw()
  28868. {
  28869. const ScopedLock sl (callbackLock);
  28870. jassert (activeEditor == editor);
  28871. if (activeEditor == editor)
  28872. activeEditor = 0;
  28873. }
  28874. AudioProcessorEditor* AudioProcessor::createEditorIfNeeded()
  28875. {
  28876. if (activeEditor != 0)
  28877. return activeEditor;
  28878. AudioProcessorEditor* const ed = createEditor();
  28879. // You must make your hasEditor() method return a consistent result!
  28880. jassert (hasEditor() == (ed != 0));
  28881. if (ed != 0)
  28882. {
  28883. // you must give your editor comp a size before returning it..
  28884. jassert (ed->getWidth() > 0 && ed->getHeight() > 0);
  28885. const ScopedLock sl (callbackLock);
  28886. activeEditor = ed;
  28887. }
  28888. return ed;
  28889. }
  28890. void AudioProcessor::getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData)
  28891. {
  28892. getStateInformation (destData);
  28893. }
  28894. void AudioProcessor::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  28895. {
  28896. setStateInformation (data, sizeInBytes);
  28897. }
  28898. // magic number to identify memory blocks that we've stored as XML
  28899. const uint32 magicXmlNumber = 0x21324356;
  28900. void AudioProcessor::copyXmlToBinary (const XmlElement& xml,
  28901. JUCE_NAMESPACE::MemoryBlock& destData)
  28902. {
  28903. const String xmlString (xml.createDocument (String::empty, true, false));
  28904. const int stringLength = xmlString.getNumBytesAsUTF8();
  28905. destData.setSize (stringLength + 10);
  28906. char* const d = static_cast<char*> (destData.getData());
  28907. *(uint32*) d = ByteOrder::swapIfBigEndian ((const uint32) magicXmlNumber);
  28908. *(uint32*) (d + 4) = ByteOrder::swapIfBigEndian ((const uint32) stringLength);
  28909. xmlString.copyToUTF8 (d + 8, stringLength + 1);
  28910. }
  28911. XmlElement* AudioProcessor::getXmlFromBinary (const void* data,
  28912. const int sizeInBytes)
  28913. {
  28914. if (sizeInBytes > 8
  28915. && ByteOrder::littleEndianInt (data) == magicXmlNumber)
  28916. {
  28917. const int stringLength = (int) ByteOrder::littleEndianInt (addBytesToPointer (data, 4));
  28918. if (stringLength > 0)
  28919. {
  28920. XmlDocument doc (String::fromUTF8 (static_cast<const char*> (data) + 8,
  28921. jmin ((sizeInBytes - 8), stringLength)));
  28922. return doc.getDocumentElement();
  28923. }
  28924. }
  28925. return 0;
  28926. }
  28927. void AudioProcessorListener::audioProcessorParameterChangeGestureBegin (AudioProcessor*, int) {}
  28928. void AudioProcessorListener::audioProcessorParameterChangeGestureEnd (AudioProcessor*, int) {}
  28929. bool AudioPlayHead::CurrentPositionInfo::operator== (const CurrentPositionInfo& other) const throw()
  28930. {
  28931. return timeInSeconds == other.timeInSeconds
  28932. && ppqPosition == other.ppqPosition
  28933. && editOriginTime == other.editOriginTime
  28934. && ppqPositionOfLastBarStart == other.ppqPositionOfLastBarStart
  28935. && frameRate == other.frameRate
  28936. && isPlaying == other.isPlaying
  28937. && isRecording == other.isRecording
  28938. && bpm == other.bpm
  28939. && timeSigNumerator == other.timeSigNumerator
  28940. && timeSigDenominator == other.timeSigDenominator;
  28941. }
  28942. bool AudioPlayHead::CurrentPositionInfo::operator!= (const CurrentPositionInfo& other) const throw()
  28943. {
  28944. return ! operator== (other);
  28945. }
  28946. void AudioPlayHead::CurrentPositionInfo::resetToDefault()
  28947. {
  28948. zerostruct (*this);
  28949. timeSigNumerator = 4;
  28950. timeSigDenominator = 4;
  28951. bpm = 120;
  28952. }
  28953. END_JUCE_NAMESPACE
  28954. /*** End of inlined file: juce_AudioProcessor.cpp ***/
  28955. /*** Start of inlined file: juce_AudioProcessorEditor.cpp ***/
  28956. BEGIN_JUCE_NAMESPACE
  28957. AudioProcessorEditor::AudioProcessorEditor (AudioProcessor* const owner_)
  28958. : owner (owner_)
  28959. {
  28960. // the filter must be valid..
  28961. jassert (owner != 0);
  28962. }
  28963. AudioProcessorEditor::~AudioProcessorEditor()
  28964. {
  28965. // if this fails, then the wrapper hasn't called editorBeingDeleted() on the
  28966. // filter for some reason..
  28967. jassert (owner->getActiveEditor() != this);
  28968. }
  28969. END_JUCE_NAMESPACE
  28970. /*** End of inlined file: juce_AudioProcessorEditor.cpp ***/
  28971. /*** Start of inlined file: juce_AudioProcessorGraph.cpp ***/
  28972. BEGIN_JUCE_NAMESPACE
  28973. const int AudioProcessorGraph::midiChannelIndex = 0x1000;
  28974. AudioProcessorGraph::Node::Node (const uint32 id_, AudioProcessor* const processor_)
  28975. : id (id_),
  28976. processor (processor_),
  28977. isPrepared (false)
  28978. {
  28979. jassert (processor_ != 0);
  28980. }
  28981. AudioProcessorGraph::Node::~Node()
  28982. {
  28983. }
  28984. void AudioProcessorGraph::Node::prepare (const double sampleRate, const int blockSize,
  28985. AudioProcessorGraph* const graph)
  28986. {
  28987. if (! isPrepared)
  28988. {
  28989. isPrepared = true;
  28990. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28991. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (processor));
  28992. if (ioProc != 0)
  28993. ioProc->setParentGraph (graph);
  28994. processor->setPlayConfigDetails (processor->getNumInputChannels(),
  28995. processor->getNumOutputChannels(),
  28996. sampleRate, blockSize);
  28997. processor->prepareToPlay (sampleRate, blockSize);
  28998. }
  28999. }
  29000. void AudioProcessorGraph::Node::unprepare()
  29001. {
  29002. if (isPrepared)
  29003. {
  29004. isPrepared = false;
  29005. processor->releaseResources();
  29006. }
  29007. }
  29008. AudioProcessorGraph::AudioProcessorGraph()
  29009. : lastNodeId (0),
  29010. renderingBuffers (1, 1),
  29011. currentAudioOutputBuffer (1, 1)
  29012. {
  29013. }
  29014. AudioProcessorGraph::~AudioProcessorGraph()
  29015. {
  29016. clearRenderingSequence();
  29017. clear();
  29018. }
  29019. const String AudioProcessorGraph::getName() const
  29020. {
  29021. return "Audio Graph";
  29022. }
  29023. void AudioProcessorGraph::clear()
  29024. {
  29025. nodes.clear();
  29026. connections.clear();
  29027. triggerAsyncUpdate();
  29028. }
  29029. AudioProcessorGraph::Node* AudioProcessorGraph::getNodeForId (const uint32 nodeId) const
  29030. {
  29031. for (int i = nodes.size(); --i >= 0;)
  29032. if (nodes.getUnchecked(i)->id == nodeId)
  29033. return nodes.getUnchecked(i);
  29034. return 0;
  29035. }
  29036. AudioProcessorGraph::Node* AudioProcessorGraph::addNode (AudioProcessor* const newProcessor,
  29037. uint32 nodeId)
  29038. {
  29039. if (newProcessor == 0)
  29040. {
  29041. jassertfalse;
  29042. return 0;
  29043. }
  29044. if (nodeId == 0)
  29045. {
  29046. nodeId = ++lastNodeId;
  29047. }
  29048. else
  29049. {
  29050. // you can't add a node with an id that already exists in the graph..
  29051. jassert (getNodeForId (nodeId) == 0);
  29052. removeNode (nodeId);
  29053. }
  29054. lastNodeId = nodeId;
  29055. Node* const n = new Node (nodeId, newProcessor);
  29056. nodes.add (n);
  29057. triggerAsyncUpdate();
  29058. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  29059. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (n->processor));
  29060. if (ioProc != 0)
  29061. ioProc->setParentGraph (this);
  29062. return n;
  29063. }
  29064. bool AudioProcessorGraph::removeNode (const uint32 nodeId)
  29065. {
  29066. disconnectNode (nodeId);
  29067. for (int i = nodes.size(); --i >= 0;)
  29068. {
  29069. if (nodes.getUnchecked(i)->id == nodeId)
  29070. {
  29071. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  29072. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (nodes.getUnchecked(i)->processor));
  29073. if (ioProc != 0)
  29074. ioProc->setParentGraph (0);
  29075. nodes.remove (i);
  29076. triggerAsyncUpdate();
  29077. return true;
  29078. }
  29079. }
  29080. return false;
  29081. }
  29082. const AudioProcessorGraph::Connection* AudioProcessorGraph::getConnectionBetween (const uint32 sourceNodeId,
  29083. const int sourceChannelIndex,
  29084. const uint32 destNodeId,
  29085. const int destChannelIndex) const
  29086. {
  29087. for (int i = connections.size(); --i >= 0;)
  29088. {
  29089. const Connection* const c = connections.getUnchecked(i);
  29090. if (c->sourceNodeId == sourceNodeId
  29091. && c->destNodeId == destNodeId
  29092. && c->sourceChannelIndex == sourceChannelIndex
  29093. && c->destChannelIndex == destChannelIndex)
  29094. {
  29095. return c;
  29096. }
  29097. }
  29098. return 0;
  29099. }
  29100. bool AudioProcessorGraph::isConnected (const uint32 possibleSourceNodeId,
  29101. const uint32 possibleDestNodeId) const
  29102. {
  29103. for (int i = connections.size(); --i >= 0;)
  29104. {
  29105. const Connection* const c = connections.getUnchecked(i);
  29106. if (c->sourceNodeId == possibleSourceNodeId
  29107. && c->destNodeId == possibleDestNodeId)
  29108. {
  29109. return true;
  29110. }
  29111. }
  29112. return false;
  29113. }
  29114. bool AudioProcessorGraph::canConnect (const uint32 sourceNodeId,
  29115. const int sourceChannelIndex,
  29116. const uint32 destNodeId,
  29117. const int destChannelIndex) const
  29118. {
  29119. if (sourceChannelIndex < 0
  29120. || destChannelIndex < 0
  29121. || sourceNodeId == destNodeId
  29122. || (destChannelIndex == midiChannelIndex) != (sourceChannelIndex == midiChannelIndex))
  29123. return false;
  29124. const Node* const source = getNodeForId (sourceNodeId);
  29125. if (source == 0
  29126. || (sourceChannelIndex != midiChannelIndex && sourceChannelIndex >= source->processor->getNumOutputChannels())
  29127. || (sourceChannelIndex == midiChannelIndex && ! source->processor->producesMidi()))
  29128. return false;
  29129. const Node* const dest = getNodeForId (destNodeId);
  29130. if (dest == 0
  29131. || (destChannelIndex != midiChannelIndex && destChannelIndex >= dest->processor->getNumInputChannels())
  29132. || (destChannelIndex == midiChannelIndex && ! dest->processor->acceptsMidi()))
  29133. return false;
  29134. return getConnectionBetween (sourceNodeId, sourceChannelIndex,
  29135. destNodeId, destChannelIndex) == 0;
  29136. }
  29137. bool AudioProcessorGraph::addConnection (const uint32 sourceNodeId,
  29138. const int sourceChannelIndex,
  29139. const uint32 destNodeId,
  29140. const int destChannelIndex)
  29141. {
  29142. if (! canConnect (sourceNodeId, sourceChannelIndex, destNodeId, destChannelIndex))
  29143. return false;
  29144. Connection* const c = new Connection();
  29145. c->sourceNodeId = sourceNodeId;
  29146. c->sourceChannelIndex = sourceChannelIndex;
  29147. c->destNodeId = destNodeId;
  29148. c->destChannelIndex = destChannelIndex;
  29149. connections.add (c);
  29150. triggerAsyncUpdate();
  29151. return true;
  29152. }
  29153. void AudioProcessorGraph::removeConnection (const int index)
  29154. {
  29155. connections.remove (index);
  29156. triggerAsyncUpdate();
  29157. }
  29158. bool AudioProcessorGraph::removeConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  29159. const uint32 destNodeId, const int destChannelIndex)
  29160. {
  29161. bool doneAnything = false;
  29162. for (int i = connections.size(); --i >= 0;)
  29163. {
  29164. const Connection* const c = connections.getUnchecked(i);
  29165. if (c->sourceNodeId == sourceNodeId
  29166. && c->destNodeId == destNodeId
  29167. && c->sourceChannelIndex == sourceChannelIndex
  29168. && c->destChannelIndex == destChannelIndex)
  29169. {
  29170. removeConnection (i);
  29171. doneAnything = true;
  29172. triggerAsyncUpdate();
  29173. }
  29174. }
  29175. return doneAnything;
  29176. }
  29177. bool AudioProcessorGraph::disconnectNode (const uint32 nodeId)
  29178. {
  29179. bool doneAnything = false;
  29180. for (int i = connections.size(); --i >= 0;)
  29181. {
  29182. const Connection* const c = connections.getUnchecked(i);
  29183. if (c->sourceNodeId == nodeId || c->destNodeId == nodeId)
  29184. {
  29185. removeConnection (i);
  29186. doneAnything = true;
  29187. triggerAsyncUpdate();
  29188. }
  29189. }
  29190. return doneAnything;
  29191. }
  29192. bool AudioProcessorGraph::removeIllegalConnections()
  29193. {
  29194. bool doneAnything = false;
  29195. for (int i = connections.size(); --i >= 0;)
  29196. {
  29197. const Connection* const c = connections.getUnchecked(i);
  29198. const Node* const source = getNodeForId (c->sourceNodeId);
  29199. const Node* const dest = getNodeForId (c->destNodeId);
  29200. if (source == 0 || dest == 0
  29201. || (c->sourceChannelIndex != midiChannelIndex
  29202. && (((unsigned int) c->sourceChannelIndex) >= (unsigned int) source->processor->getNumOutputChannels()))
  29203. || (c->sourceChannelIndex == midiChannelIndex
  29204. && ! source->processor->producesMidi())
  29205. || (c->destChannelIndex != midiChannelIndex
  29206. && (((unsigned int) c->destChannelIndex) >= (unsigned int) dest->processor->getNumInputChannels()))
  29207. || (c->destChannelIndex == midiChannelIndex
  29208. && ! dest->processor->acceptsMidi()))
  29209. {
  29210. removeConnection (i);
  29211. doneAnything = true;
  29212. triggerAsyncUpdate();
  29213. }
  29214. }
  29215. return doneAnything;
  29216. }
  29217. namespace GraphRenderingOps
  29218. {
  29219. class AudioGraphRenderingOp
  29220. {
  29221. public:
  29222. AudioGraphRenderingOp() {}
  29223. virtual ~AudioGraphRenderingOp() {}
  29224. virtual void perform (AudioSampleBuffer& sharedBufferChans,
  29225. const OwnedArray <MidiBuffer>& sharedMidiBuffers,
  29226. const int numSamples) = 0;
  29227. juce_UseDebuggingNewOperator
  29228. };
  29229. class ClearChannelOp : public AudioGraphRenderingOp
  29230. {
  29231. public:
  29232. ClearChannelOp (const int channelNum_)
  29233. : channelNum (channelNum_)
  29234. {}
  29235. ~ClearChannelOp() {}
  29236. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29237. {
  29238. sharedBufferChans.clear (channelNum, 0, numSamples);
  29239. }
  29240. private:
  29241. const int channelNum;
  29242. ClearChannelOp (const ClearChannelOp&);
  29243. ClearChannelOp& operator= (const ClearChannelOp&);
  29244. };
  29245. class CopyChannelOp : public AudioGraphRenderingOp
  29246. {
  29247. public:
  29248. CopyChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  29249. : srcChannelNum (srcChannelNum_),
  29250. dstChannelNum (dstChannelNum_)
  29251. {}
  29252. ~CopyChannelOp() {}
  29253. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29254. {
  29255. sharedBufferChans.copyFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  29256. }
  29257. private:
  29258. const int srcChannelNum, dstChannelNum;
  29259. CopyChannelOp (const CopyChannelOp&);
  29260. CopyChannelOp& operator= (const CopyChannelOp&);
  29261. };
  29262. class AddChannelOp : public AudioGraphRenderingOp
  29263. {
  29264. public:
  29265. AddChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  29266. : srcChannelNum (srcChannelNum_),
  29267. dstChannelNum (dstChannelNum_)
  29268. {}
  29269. ~AddChannelOp() {}
  29270. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29271. {
  29272. sharedBufferChans.addFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  29273. }
  29274. private:
  29275. const int srcChannelNum, dstChannelNum;
  29276. AddChannelOp (const AddChannelOp&);
  29277. AddChannelOp& operator= (const AddChannelOp&);
  29278. };
  29279. class ClearMidiBufferOp : public AudioGraphRenderingOp
  29280. {
  29281. public:
  29282. ClearMidiBufferOp (const int bufferNum_)
  29283. : bufferNum (bufferNum_)
  29284. {}
  29285. ~ClearMidiBufferOp() {}
  29286. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  29287. {
  29288. sharedMidiBuffers.getUnchecked (bufferNum)->clear();
  29289. }
  29290. private:
  29291. const int bufferNum;
  29292. ClearMidiBufferOp (const ClearMidiBufferOp&);
  29293. ClearMidiBufferOp& operator= (const ClearMidiBufferOp&);
  29294. };
  29295. class CopyMidiBufferOp : public AudioGraphRenderingOp
  29296. {
  29297. public:
  29298. CopyMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  29299. : srcBufferNum (srcBufferNum_),
  29300. dstBufferNum (dstBufferNum_)
  29301. {}
  29302. ~CopyMidiBufferOp() {}
  29303. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  29304. {
  29305. *sharedMidiBuffers.getUnchecked (dstBufferNum) = *sharedMidiBuffers.getUnchecked (srcBufferNum);
  29306. }
  29307. private:
  29308. const int srcBufferNum, dstBufferNum;
  29309. CopyMidiBufferOp (const CopyMidiBufferOp&);
  29310. CopyMidiBufferOp& operator= (const CopyMidiBufferOp&);
  29311. };
  29312. class AddMidiBufferOp : public AudioGraphRenderingOp
  29313. {
  29314. public:
  29315. AddMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  29316. : srcBufferNum (srcBufferNum_),
  29317. dstBufferNum (dstBufferNum_)
  29318. {}
  29319. ~AddMidiBufferOp() {}
  29320. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  29321. {
  29322. sharedMidiBuffers.getUnchecked (dstBufferNum)
  29323. ->addEvents (*sharedMidiBuffers.getUnchecked (srcBufferNum), 0, numSamples, 0);
  29324. }
  29325. private:
  29326. const int srcBufferNum, dstBufferNum;
  29327. AddMidiBufferOp (const AddMidiBufferOp&);
  29328. AddMidiBufferOp& operator= (const AddMidiBufferOp&);
  29329. };
  29330. class ProcessBufferOp : public AudioGraphRenderingOp
  29331. {
  29332. public:
  29333. ProcessBufferOp (const AudioProcessorGraph::Node::Ptr& node_,
  29334. const Array <int>& audioChannelsToUse_,
  29335. const int totalChans_,
  29336. const int midiBufferToUse_)
  29337. : node (node_),
  29338. processor (node_->getProcessor()),
  29339. audioChannelsToUse (audioChannelsToUse_),
  29340. totalChans (jmax (1, totalChans_)),
  29341. midiBufferToUse (midiBufferToUse_)
  29342. {
  29343. channels.calloc (totalChans);
  29344. while (audioChannelsToUse.size() < totalChans)
  29345. audioChannelsToUse.add (0);
  29346. }
  29347. ~ProcessBufferOp()
  29348. {
  29349. }
  29350. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  29351. {
  29352. for (int i = totalChans; --i >= 0;)
  29353. channels[i] = sharedBufferChans.getSampleData (audioChannelsToUse.getUnchecked (i), 0);
  29354. AudioSampleBuffer buffer (channels, totalChans, numSamples);
  29355. processor->processBlock (buffer, *sharedMidiBuffers.getUnchecked (midiBufferToUse));
  29356. }
  29357. const AudioProcessorGraph::Node::Ptr node;
  29358. AudioProcessor* const processor;
  29359. private:
  29360. Array <int> audioChannelsToUse;
  29361. HeapBlock <float*> channels;
  29362. int totalChans;
  29363. int midiBufferToUse;
  29364. ProcessBufferOp (const ProcessBufferOp&);
  29365. ProcessBufferOp& operator= (const ProcessBufferOp&);
  29366. };
  29367. /** Used to calculate the correct sequence of rendering ops needed, based on
  29368. the best re-use of shared buffers at each stage.
  29369. */
  29370. class RenderingOpSequenceCalculator
  29371. {
  29372. public:
  29373. RenderingOpSequenceCalculator (AudioProcessorGraph& graph_,
  29374. const Array<void*>& orderedNodes_,
  29375. Array<void*>& renderingOps)
  29376. : graph (graph_),
  29377. orderedNodes (orderedNodes_)
  29378. {
  29379. nodeIds.add (-2); // first buffer is read-only zeros
  29380. channels.add (0);
  29381. midiNodeIds.add (-2);
  29382. for (int i = 0; i < orderedNodes.size(); ++i)
  29383. {
  29384. createRenderingOpsForNode ((AudioProcessorGraph::Node*) orderedNodes.getUnchecked(i),
  29385. renderingOps, i);
  29386. markAnyUnusedBuffersAsFree (i);
  29387. }
  29388. }
  29389. int getNumBuffersNeeded() const { return nodeIds.size(); }
  29390. int getNumMidiBuffersNeeded() const { return midiNodeIds.size(); }
  29391. juce_UseDebuggingNewOperator
  29392. private:
  29393. AudioProcessorGraph& graph;
  29394. const Array<void*>& orderedNodes;
  29395. Array <int> nodeIds, channels, midiNodeIds;
  29396. void createRenderingOpsForNode (AudioProcessorGraph::Node* const node,
  29397. Array<void*>& renderingOps,
  29398. const int ourRenderingIndex)
  29399. {
  29400. const int numIns = node->getProcessor()->getNumInputChannels();
  29401. const int numOuts = node->getProcessor()->getNumOutputChannels();
  29402. const int totalChans = jmax (numIns, numOuts);
  29403. Array <int> audioChannelsToUse;
  29404. int midiBufferToUse = -1;
  29405. for (int inputChan = 0; inputChan < numIns; ++inputChan)
  29406. {
  29407. // get a list of all the inputs to this node
  29408. Array <int> sourceNodes, sourceOutputChans;
  29409. for (int i = graph.getNumConnections(); --i >= 0;)
  29410. {
  29411. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  29412. if (c->destNodeId == node->id && c->destChannelIndex == inputChan)
  29413. {
  29414. sourceNodes.add (c->sourceNodeId);
  29415. sourceOutputChans.add (c->sourceChannelIndex);
  29416. }
  29417. }
  29418. int bufIndex = -1;
  29419. if (sourceNodes.size() == 0)
  29420. {
  29421. // unconnected input channel
  29422. if (inputChan >= numOuts)
  29423. {
  29424. bufIndex = getReadOnlyEmptyBuffer();
  29425. jassert (bufIndex >= 0);
  29426. }
  29427. else
  29428. {
  29429. bufIndex = getFreeBuffer (false);
  29430. renderingOps.add (new ClearChannelOp (bufIndex));
  29431. }
  29432. }
  29433. else if (sourceNodes.size() == 1)
  29434. {
  29435. // channel with a straightforward single input..
  29436. const int srcNode = sourceNodes.getUnchecked(0);
  29437. const int srcChan = sourceOutputChans.getUnchecked(0);
  29438. bufIndex = getBufferContaining (srcNode, srcChan);
  29439. if (bufIndex < 0)
  29440. {
  29441. // if not found, this is probably a feedback loop
  29442. bufIndex = getReadOnlyEmptyBuffer();
  29443. jassert (bufIndex >= 0);
  29444. }
  29445. if (inputChan < numOuts
  29446. && isBufferNeededLater (ourRenderingIndex,
  29447. inputChan,
  29448. srcNode, srcChan))
  29449. {
  29450. // can't mess up this channel because it's needed later by another node, so we
  29451. // need to use a copy of it..
  29452. const int newFreeBuffer = getFreeBuffer (false);
  29453. renderingOps.add (new CopyChannelOp (bufIndex, newFreeBuffer));
  29454. bufIndex = newFreeBuffer;
  29455. }
  29456. }
  29457. else
  29458. {
  29459. // channel with a mix of several inputs..
  29460. // try to find a re-usable channel from our inputs..
  29461. int reusableInputIndex = -1;
  29462. for (int i = 0; i < sourceNodes.size(); ++i)
  29463. {
  29464. const int sourceBufIndex = getBufferContaining (sourceNodes.getUnchecked(i),
  29465. sourceOutputChans.getUnchecked(i));
  29466. if (sourceBufIndex >= 0
  29467. && ! isBufferNeededLater (ourRenderingIndex,
  29468. inputChan,
  29469. sourceNodes.getUnchecked(i),
  29470. sourceOutputChans.getUnchecked(i)))
  29471. {
  29472. // we've found one of our input chans that can be re-used..
  29473. reusableInputIndex = i;
  29474. bufIndex = sourceBufIndex;
  29475. break;
  29476. }
  29477. }
  29478. if (reusableInputIndex < 0)
  29479. {
  29480. // can't re-use any of our input chans, so get a new one and copy everything into it..
  29481. bufIndex = getFreeBuffer (false);
  29482. jassert (bufIndex != 0);
  29483. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked (0),
  29484. sourceOutputChans.getUnchecked (0));
  29485. if (srcIndex < 0)
  29486. {
  29487. // if not found, this is probably a feedback loop
  29488. renderingOps.add (new ClearChannelOp (bufIndex));
  29489. }
  29490. else
  29491. {
  29492. renderingOps.add (new CopyChannelOp (srcIndex, bufIndex));
  29493. }
  29494. reusableInputIndex = 0;
  29495. }
  29496. for (int j = 0; j < sourceNodes.size(); ++j)
  29497. {
  29498. if (j != reusableInputIndex)
  29499. {
  29500. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked(j),
  29501. sourceOutputChans.getUnchecked(j));
  29502. if (srcIndex >= 0)
  29503. renderingOps.add (new AddChannelOp (srcIndex, bufIndex));
  29504. }
  29505. }
  29506. }
  29507. jassert (bufIndex >= 0);
  29508. audioChannelsToUse.add (bufIndex);
  29509. if (inputChan < numOuts)
  29510. markBufferAsContaining (bufIndex, node->id, inputChan);
  29511. }
  29512. for (int outputChan = numIns; outputChan < numOuts; ++outputChan)
  29513. {
  29514. const int bufIndex = getFreeBuffer (false);
  29515. jassert (bufIndex != 0);
  29516. audioChannelsToUse.add (bufIndex);
  29517. markBufferAsContaining (bufIndex, node->id, outputChan);
  29518. }
  29519. // Now the same thing for midi..
  29520. Array <int> midiSourceNodes;
  29521. for (int i = graph.getNumConnections(); --i >= 0;)
  29522. {
  29523. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  29524. if (c->destNodeId == node->id && c->destChannelIndex == AudioProcessorGraph::midiChannelIndex)
  29525. midiSourceNodes.add (c->sourceNodeId);
  29526. }
  29527. if (midiSourceNodes.size() == 0)
  29528. {
  29529. // No midi inputs..
  29530. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  29531. if (node->getProcessor()->acceptsMidi() || node->getProcessor()->producesMidi())
  29532. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  29533. }
  29534. else if (midiSourceNodes.size() == 1)
  29535. {
  29536. // One midi input..
  29537. midiBufferToUse = getBufferContaining (midiSourceNodes.getUnchecked(0),
  29538. AudioProcessorGraph::midiChannelIndex);
  29539. if (midiBufferToUse >= 0)
  29540. {
  29541. if (isBufferNeededLater (ourRenderingIndex,
  29542. AudioProcessorGraph::midiChannelIndex,
  29543. midiSourceNodes.getUnchecked(0),
  29544. AudioProcessorGraph::midiChannelIndex))
  29545. {
  29546. // can't mess up this channel because it's needed later by another node, so we
  29547. // need to use a copy of it..
  29548. const int newFreeBuffer = getFreeBuffer (true);
  29549. renderingOps.add (new CopyMidiBufferOp (midiBufferToUse, newFreeBuffer));
  29550. midiBufferToUse = newFreeBuffer;
  29551. }
  29552. }
  29553. else
  29554. {
  29555. // probably a feedback loop, so just use an empty one..
  29556. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  29557. }
  29558. }
  29559. else
  29560. {
  29561. // More than one midi input being mixed..
  29562. int reusableInputIndex = -1;
  29563. for (int i = 0; i < midiSourceNodes.size(); ++i)
  29564. {
  29565. const int sourceBufIndex = getBufferContaining (midiSourceNodes.getUnchecked(i),
  29566. AudioProcessorGraph::midiChannelIndex);
  29567. if (sourceBufIndex >= 0
  29568. && ! isBufferNeededLater (ourRenderingIndex,
  29569. AudioProcessorGraph::midiChannelIndex,
  29570. midiSourceNodes.getUnchecked(i),
  29571. AudioProcessorGraph::midiChannelIndex))
  29572. {
  29573. // we've found one of our input buffers that can be re-used..
  29574. reusableInputIndex = i;
  29575. midiBufferToUse = sourceBufIndex;
  29576. break;
  29577. }
  29578. }
  29579. if (reusableInputIndex < 0)
  29580. {
  29581. // can't re-use any of our input buffers, so get a new one and copy everything into it..
  29582. midiBufferToUse = getFreeBuffer (true);
  29583. jassert (midiBufferToUse >= 0);
  29584. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(0),
  29585. AudioProcessorGraph::midiChannelIndex);
  29586. if (srcIndex >= 0)
  29587. renderingOps.add (new CopyMidiBufferOp (srcIndex, midiBufferToUse));
  29588. else
  29589. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  29590. reusableInputIndex = 0;
  29591. }
  29592. for (int j = 0; j < midiSourceNodes.size(); ++j)
  29593. {
  29594. if (j != reusableInputIndex)
  29595. {
  29596. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(j),
  29597. AudioProcessorGraph::midiChannelIndex);
  29598. if (srcIndex >= 0)
  29599. renderingOps.add (new AddMidiBufferOp (srcIndex, midiBufferToUse));
  29600. }
  29601. }
  29602. }
  29603. if (node->getProcessor()->producesMidi())
  29604. markBufferAsContaining (midiBufferToUse, node->id,
  29605. AudioProcessorGraph::midiChannelIndex);
  29606. renderingOps.add (new ProcessBufferOp (node, audioChannelsToUse,
  29607. totalChans, midiBufferToUse));
  29608. }
  29609. int getFreeBuffer (const bool forMidi)
  29610. {
  29611. if (forMidi)
  29612. {
  29613. for (int i = 1; i < midiNodeIds.size(); ++i)
  29614. if (midiNodeIds.getUnchecked(i) < 0)
  29615. return i;
  29616. midiNodeIds.add (-1);
  29617. return midiNodeIds.size() - 1;
  29618. }
  29619. else
  29620. {
  29621. for (int i = 1; i < nodeIds.size(); ++i)
  29622. if (nodeIds.getUnchecked(i) < 0)
  29623. return i;
  29624. nodeIds.add (-1);
  29625. channels.add (0);
  29626. return nodeIds.size() - 1;
  29627. }
  29628. }
  29629. int getReadOnlyEmptyBuffer() const
  29630. {
  29631. return 0;
  29632. }
  29633. int getBufferContaining (const int nodeId, const int outputChannel) const
  29634. {
  29635. if (outputChannel == AudioProcessorGraph::midiChannelIndex)
  29636. {
  29637. for (int i = midiNodeIds.size(); --i >= 0;)
  29638. if (midiNodeIds.getUnchecked(i) == nodeId)
  29639. return i;
  29640. }
  29641. else
  29642. {
  29643. for (int i = nodeIds.size(); --i >= 0;)
  29644. if (nodeIds.getUnchecked(i) == nodeId
  29645. && channels.getUnchecked(i) == outputChannel)
  29646. return i;
  29647. }
  29648. return -1;
  29649. }
  29650. void markAnyUnusedBuffersAsFree (const int stepIndex)
  29651. {
  29652. int i;
  29653. for (i = 0; i < nodeIds.size(); ++i)
  29654. {
  29655. if (nodeIds.getUnchecked(i) >= 0
  29656. && ! isBufferNeededLater (stepIndex, -1,
  29657. nodeIds.getUnchecked(i),
  29658. channels.getUnchecked(i)))
  29659. {
  29660. nodeIds.set (i, -1);
  29661. }
  29662. }
  29663. for (i = 0; i < midiNodeIds.size(); ++i)
  29664. {
  29665. if (midiNodeIds.getUnchecked(i) >= 0
  29666. && ! isBufferNeededLater (stepIndex, -1,
  29667. midiNodeIds.getUnchecked(i),
  29668. AudioProcessorGraph::midiChannelIndex))
  29669. {
  29670. midiNodeIds.set (i, -1);
  29671. }
  29672. }
  29673. }
  29674. bool isBufferNeededLater (int stepIndexToSearchFrom,
  29675. int inputChannelOfIndexToIgnore,
  29676. const int nodeId,
  29677. const int outputChanIndex) const
  29678. {
  29679. while (stepIndexToSearchFrom < orderedNodes.size())
  29680. {
  29681. const AudioProcessorGraph::Node* const node = (const AudioProcessorGraph::Node*) orderedNodes.getUnchecked (stepIndexToSearchFrom);
  29682. if (outputChanIndex == AudioProcessorGraph::midiChannelIndex)
  29683. {
  29684. if (inputChannelOfIndexToIgnore != AudioProcessorGraph::midiChannelIndex
  29685. && graph.getConnectionBetween (nodeId, AudioProcessorGraph::midiChannelIndex,
  29686. node->id, AudioProcessorGraph::midiChannelIndex) != 0)
  29687. return true;
  29688. }
  29689. else
  29690. {
  29691. for (int i = 0; i < node->getProcessor()->getNumInputChannels(); ++i)
  29692. if (i != inputChannelOfIndexToIgnore
  29693. && graph.getConnectionBetween (nodeId, outputChanIndex,
  29694. node->id, i) != 0)
  29695. return true;
  29696. }
  29697. inputChannelOfIndexToIgnore = -1;
  29698. ++stepIndexToSearchFrom;
  29699. }
  29700. return false;
  29701. }
  29702. void markBufferAsContaining (int bufferNum, int nodeId, int outputIndex)
  29703. {
  29704. if (outputIndex == AudioProcessorGraph::midiChannelIndex)
  29705. {
  29706. jassert (bufferNum > 0 && bufferNum < midiNodeIds.size());
  29707. midiNodeIds.set (bufferNum, nodeId);
  29708. }
  29709. else
  29710. {
  29711. jassert (bufferNum >= 0 && bufferNum < nodeIds.size());
  29712. nodeIds.set (bufferNum, nodeId);
  29713. channels.set (bufferNum, outputIndex);
  29714. }
  29715. }
  29716. RenderingOpSequenceCalculator (const RenderingOpSequenceCalculator&);
  29717. RenderingOpSequenceCalculator& operator= (const RenderingOpSequenceCalculator&);
  29718. };
  29719. }
  29720. void AudioProcessorGraph::clearRenderingSequence()
  29721. {
  29722. const ScopedLock sl (renderLock);
  29723. for (int i = renderingOps.size(); --i >= 0;)
  29724. {
  29725. GraphRenderingOps::AudioGraphRenderingOp* const r
  29726. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  29727. renderingOps.remove (i);
  29728. delete r;
  29729. }
  29730. }
  29731. bool AudioProcessorGraph::isAnInputTo (const uint32 possibleInputId,
  29732. const uint32 possibleDestinationId,
  29733. const int recursionCheck) const
  29734. {
  29735. if (recursionCheck > 0)
  29736. {
  29737. for (int i = connections.size(); --i >= 0;)
  29738. {
  29739. const AudioProcessorGraph::Connection* const c = connections.getUnchecked (i);
  29740. if (c->destNodeId == possibleDestinationId
  29741. && (c->sourceNodeId == possibleInputId
  29742. || isAnInputTo (possibleInputId, c->sourceNodeId, recursionCheck - 1)))
  29743. return true;
  29744. }
  29745. }
  29746. return false;
  29747. }
  29748. void AudioProcessorGraph::buildRenderingSequence()
  29749. {
  29750. Array<void*> newRenderingOps;
  29751. int numRenderingBuffersNeeded = 2;
  29752. int numMidiBuffersNeeded = 1;
  29753. {
  29754. MessageManagerLock mml;
  29755. Array<void*> orderedNodes;
  29756. int i;
  29757. for (i = 0; i < nodes.size(); ++i)
  29758. {
  29759. Node* const node = nodes.getUnchecked(i);
  29760. node->prepare (getSampleRate(), getBlockSize(), this);
  29761. int j = 0;
  29762. for (; j < orderedNodes.size(); ++j)
  29763. if (isAnInputTo (node->id,
  29764. ((Node*) orderedNodes.getUnchecked (j))->id,
  29765. nodes.size() + 1))
  29766. break;
  29767. orderedNodes.insert (j, node);
  29768. }
  29769. GraphRenderingOps::RenderingOpSequenceCalculator calculator (*this, orderedNodes, newRenderingOps);
  29770. numRenderingBuffersNeeded = calculator.getNumBuffersNeeded();
  29771. numMidiBuffersNeeded = calculator.getNumMidiBuffersNeeded();
  29772. }
  29773. Array<void*> oldRenderingOps (renderingOps);
  29774. {
  29775. // swap over to the new rendering sequence..
  29776. const ScopedLock sl (renderLock);
  29777. renderingBuffers.setSize (numRenderingBuffersNeeded, getBlockSize());
  29778. renderingBuffers.clear();
  29779. for (int i = midiBuffers.size(); --i >= 0;)
  29780. midiBuffers.getUnchecked(i)->clear();
  29781. while (midiBuffers.size() < numMidiBuffersNeeded)
  29782. midiBuffers.add (new MidiBuffer());
  29783. renderingOps = newRenderingOps;
  29784. }
  29785. for (int i = oldRenderingOps.size(); --i >= 0;)
  29786. delete (GraphRenderingOps::AudioGraphRenderingOp*) oldRenderingOps.getUnchecked(i);
  29787. }
  29788. void AudioProcessorGraph::handleAsyncUpdate()
  29789. {
  29790. buildRenderingSequence();
  29791. }
  29792. void AudioProcessorGraph::prepareToPlay (double /*sampleRate*/, int estimatedSamplesPerBlock)
  29793. {
  29794. currentAudioInputBuffer = 0;
  29795. currentAudioOutputBuffer.setSize (jmax (1, getNumOutputChannels()), estimatedSamplesPerBlock);
  29796. currentMidiInputBuffer = 0;
  29797. currentMidiOutputBuffer.clear();
  29798. clearRenderingSequence();
  29799. buildRenderingSequence();
  29800. }
  29801. void AudioProcessorGraph::releaseResources()
  29802. {
  29803. for (int i = 0; i < nodes.size(); ++i)
  29804. nodes.getUnchecked(i)->unprepare();
  29805. renderingBuffers.setSize (1, 1);
  29806. midiBuffers.clear();
  29807. currentAudioInputBuffer = 0;
  29808. currentAudioOutputBuffer.setSize (1, 1);
  29809. currentMidiInputBuffer = 0;
  29810. currentMidiOutputBuffer.clear();
  29811. }
  29812. void AudioProcessorGraph::processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages)
  29813. {
  29814. const int numSamples = buffer.getNumSamples();
  29815. const ScopedLock sl (renderLock);
  29816. currentAudioInputBuffer = &buffer;
  29817. currentAudioOutputBuffer.setSize (jmax (1, buffer.getNumChannels()), numSamples);
  29818. currentAudioOutputBuffer.clear();
  29819. currentMidiInputBuffer = &midiMessages;
  29820. currentMidiOutputBuffer.clear();
  29821. int i;
  29822. for (i = 0; i < renderingOps.size(); ++i)
  29823. {
  29824. GraphRenderingOps::AudioGraphRenderingOp* const op
  29825. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  29826. op->perform (renderingBuffers, midiBuffers, numSamples);
  29827. }
  29828. for (i = 0; i < buffer.getNumChannels(); ++i)
  29829. buffer.copyFrom (i, 0, currentAudioOutputBuffer, i, 0, numSamples);
  29830. midiMessages.clear();
  29831. midiMessages.addEvents (currentMidiOutputBuffer, 0, buffer.getNumSamples(), 0);
  29832. }
  29833. const String AudioProcessorGraph::getInputChannelName (int channelIndex) const
  29834. {
  29835. return "Input " + String (channelIndex + 1);
  29836. }
  29837. const String AudioProcessorGraph::getOutputChannelName (int channelIndex) const
  29838. {
  29839. return "Output " + String (channelIndex + 1);
  29840. }
  29841. bool AudioProcessorGraph::isInputChannelStereoPair (int /*index*/) const { return true; }
  29842. bool AudioProcessorGraph::isOutputChannelStereoPair (int /*index*/) const { return true; }
  29843. bool AudioProcessorGraph::acceptsMidi() const { return true; }
  29844. bool AudioProcessorGraph::producesMidi() const { return true; }
  29845. void AudioProcessorGraph::getStateInformation (JUCE_NAMESPACE::MemoryBlock& /*destData*/) {}
  29846. void AudioProcessorGraph::setStateInformation (const void* /*data*/, int /*sizeInBytes*/) {}
  29847. AudioProcessorGraph::AudioGraphIOProcessor::AudioGraphIOProcessor (const IODeviceType type_)
  29848. : type (type_),
  29849. graph (0)
  29850. {
  29851. }
  29852. AudioProcessorGraph::AudioGraphIOProcessor::~AudioGraphIOProcessor()
  29853. {
  29854. }
  29855. const String AudioProcessorGraph::AudioGraphIOProcessor::getName() const
  29856. {
  29857. switch (type)
  29858. {
  29859. case audioOutputNode: return "Audio Output";
  29860. case audioInputNode: return "Audio Input";
  29861. case midiOutputNode: return "Midi Output";
  29862. case midiInputNode: return "Midi Input";
  29863. default: break;
  29864. }
  29865. return String::empty;
  29866. }
  29867. void AudioProcessorGraph::AudioGraphIOProcessor::fillInPluginDescription (PluginDescription& d) const
  29868. {
  29869. d.name = getName();
  29870. d.uid = d.name.hashCode();
  29871. d.category = "I/O devices";
  29872. d.pluginFormatName = "Internal";
  29873. d.manufacturerName = "Raw Material Software";
  29874. d.version = "1.0";
  29875. d.isInstrument = false;
  29876. d.numInputChannels = getNumInputChannels();
  29877. if (type == audioOutputNode && graph != 0)
  29878. d.numInputChannels = graph->getNumInputChannels();
  29879. d.numOutputChannels = getNumOutputChannels();
  29880. if (type == audioInputNode && graph != 0)
  29881. d.numOutputChannels = graph->getNumOutputChannels();
  29882. }
  29883. void AudioProcessorGraph::AudioGraphIOProcessor::prepareToPlay (double, int)
  29884. {
  29885. jassert (graph != 0);
  29886. }
  29887. void AudioProcessorGraph::AudioGraphIOProcessor::releaseResources()
  29888. {
  29889. }
  29890. void AudioProcessorGraph::AudioGraphIOProcessor::processBlock (AudioSampleBuffer& buffer,
  29891. MidiBuffer& midiMessages)
  29892. {
  29893. jassert (graph != 0);
  29894. switch (type)
  29895. {
  29896. case audioOutputNode:
  29897. {
  29898. for (int i = jmin (graph->currentAudioOutputBuffer.getNumChannels(),
  29899. buffer.getNumChannels()); --i >= 0;)
  29900. {
  29901. graph->currentAudioOutputBuffer.addFrom (i, 0, buffer, i, 0, buffer.getNumSamples());
  29902. }
  29903. break;
  29904. }
  29905. case audioInputNode:
  29906. {
  29907. for (int i = jmin (graph->currentAudioInputBuffer->getNumChannels(),
  29908. buffer.getNumChannels()); --i >= 0;)
  29909. {
  29910. buffer.copyFrom (i, 0, *graph->currentAudioInputBuffer, i, 0, buffer.getNumSamples());
  29911. }
  29912. break;
  29913. }
  29914. case midiOutputNode:
  29915. graph->currentMidiOutputBuffer.addEvents (midiMessages, 0, buffer.getNumSamples(), 0);
  29916. break;
  29917. case midiInputNode:
  29918. midiMessages.addEvents (*graph->currentMidiInputBuffer, 0, buffer.getNumSamples(), 0);
  29919. break;
  29920. default:
  29921. break;
  29922. }
  29923. }
  29924. bool AudioProcessorGraph::AudioGraphIOProcessor::acceptsMidi() const
  29925. {
  29926. return type == midiOutputNode;
  29927. }
  29928. bool AudioProcessorGraph::AudioGraphIOProcessor::producesMidi() const
  29929. {
  29930. return type == midiInputNode;
  29931. }
  29932. const String AudioProcessorGraph::AudioGraphIOProcessor::getInputChannelName (int channelIndex) const
  29933. {
  29934. switch (type)
  29935. {
  29936. case audioOutputNode: return "Output " + String (channelIndex + 1);
  29937. case midiOutputNode: return "Midi Output";
  29938. default: break;
  29939. }
  29940. return String::empty;
  29941. }
  29942. const String AudioProcessorGraph::AudioGraphIOProcessor::getOutputChannelName (int channelIndex) const
  29943. {
  29944. switch (type)
  29945. {
  29946. case audioInputNode: return "Input " + String (channelIndex + 1);
  29947. case midiInputNode: return "Midi Input";
  29948. default: break;
  29949. }
  29950. return String::empty;
  29951. }
  29952. bool AudioProcessorGraph::AudioGraphIOProcessor::isInputChannelStereoPair (int /*index*/) const
  29953. {
  29954. return type == audioInputNode || type == audioOutputNode;
  29955. }
  29956. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutputChannelStereoPair (int index) const
  29957. {
  29958. return isInputChannelStereoPair (index);
  29959. }
  29960. bool AudioProcessorGraph::AudioGraphIOProcessor::isInput() const
  29961. {
  29962. return type == audioInputNode || type == midiInputNode;
  29963. }
  29964. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutput() const
  29965. {
  29966. return type == audioOutputNode || type == midiOutputNode;
  29967. }
  29968. bool AudioProcessorGraph::AudioGraphIOProcessor::hasEditor() const { return false; }
  29969. AudioProcessorEditor* AudioProcessorGraph::AudioGraphIOProcessor::createEditor() { return 0; }
  29970. int AudioProcessorGraph::AudioGraphIOProcessor::getNumParameters() { return 0; }
  29971. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterName (int) { return String::empty; }
  29972. float AudioProcessorGraph::AudioGraphIOProcessor::getParameter (int) { return 0.0f; }
  29973. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterText (int) { return String::empty; }
  29974. void AudioProcessorGraph::AudioGraphIOProcessor::setParameter (int, float) { }
  29975. int AudioProcessorGraph::AudioGraphIOProcessor::getNumPrograms() { return 0; }
  29976. int AudioProcessorGraph::AudioGraphIOProcessor::getCurrentProgram() { return 0; }
  29977. void AudioProcessorGraph::AudioGraphIOProcessor::setCurrentProgram (int) { }
  29978. const String AudioProcessorGraph::AudioGraphIOProcessor::getProgramName (int) { return String::empty; }
  29979. void AudioProcessorGraph::AudioGraphIOProcessor::changeProgramName (int, const String&) { }
  29980. void AudioProcessorGraph::AudioGraphIOProcessor::getStateInformation (JUCE_NAMESPACE::MemoryBlock&)
  29981. {
  29982. }
  29983. void AudioProcessorGraph::AudioGraphIOProcessor::setStateInformation (const void*, int)
  29984. {
  29985. }
  29986. void AudioProcessorGraph::AudioGraphIOProcessor::setParentGraph (AudioProcessorGraph* const newGraph)
  29987. {
  29988. graph = newGraph;
  29989. if (graph != 0)
  29990. {
  29991. setPlayConfigDetails (type == audioOutputNode ? graph->getNumOutputChannels() : 0,
  29992. type == audioInputNode ? graph->getNumInputChannels() : 0,
  29993. getSampleRate(),
  29994. getBlockSize());
  29995. updateHostDisplay();
  29996. }
  29997. }
  29998. END_JUCE_NAMESPACE
  29999. /*** End of inlined file: juce_AudioProcessorGraph.cpp ***/
  30000. /*** Start of inlined file: juce_AudioProcessorPlayer.cpp ***/
  30001. BEGIN_JUCE_NAMESPACE
  30002. AudioProcessorPlayer::AudioProcessorPlayer()
  30003. : processor (0),
  30004. sampleRate (0),
  30005. blockSize (0),
  30006. isPrepared (false),
  30007. numInputChans (0),
  30008. numOutputChans (0),
  30009. tempBuffer (1, 1)
  30010. {
  30011. }
  30012. AudioProcessorPlayer::~AudioProcessorPlayer()
  30013. {
  30014. setProcessor (0);
  30015. }
  30016. void AudioProcessorPlayer::setProcessor (AudioProcessor* const processorToPlay)
  30017. {
  30018. if (processor != processorToPlay)
  30019. {
  30020. if (processorToPlay != 0 && sampleRate > 0 && blockSize > 0)
  30021. {
  30022. processorToPlay->setPlayConfigDetails (numInputChans, numOutputChans,
  30023. sampleRate, blockSize);
  30024. processorToPlay->prepareToPlay (sampleRate, blockSize);
  30025. }
  30026. AudioProcessor* oldOne;
  30027. {
  30028. const ScopedLock sl (lock);
  30029. oldOne = isPrepared ? processor : 0;
  30030. processor = processorToPlay;
  30031. isPrepared = true;
  30032. }
  30033. if (oldOne != 0)
  30034. oldOne->releaseResources();
  30035. }
  30036. }
  30037. void AudioProcessorPlayer::audioDeviceIOCallback (const float** const inputChannelData,
  30038. const int numInputChannels,
  30039. float** const outputChannelData,
  30040. const int numOutputChannels,
  30041. const int numSamples)
  30042. {
  30043. // these should have been prepared by audioDeviceAboutToStart()...
  30044. jassert (sampleRate > 0 && blockSize > 0);
  30045. incomingMidi.clear();
  30046. messageCollector.removeNextBlockOfMessages (incomingMidi, numSamples);
  30047. int i, totalNumChans = 0;
  30048. if (numInputChannels > numOutputChannels)
  30049. {
  30050. // if there aren't enough output channels for the number of
  30051. // inputs, we need to create some temporary extra ones (can't
  30052. // use the input data in case it gets written to)
  30053. tempBuffer.setSize (numInputChannels - numOutputChannels, numSamples,
  30054. false, false, true);
  30055. for (i = 0; i < numOutputChannels; ++i)
  30056. {
  30057. channels[totalNumChans] = outputChannelData[i];
  30058. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  30059. ++totalNumChans;
  30060. }
  30061. for (i = numOutputChannels; i < numInputChannels; ++i)
  30062. {
  30063. channels[totalNumChans] = tempBuffer.getSampleData (i - numOutputChannels, 0);
  30064. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  30065. ++totalNumChans;
  30066. }
  30067. }
  30068. else
  30069. {
  30070. for (i = 0; i < numInputChannels; ++i)
  30071. {
  30072. channels[totalNumChans] = outputChannelData[i];
  30073. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  30074. ++totalNumChans;
  30075. }
  30076. for (i = numInputChannels; i < numOutputChannels; ++i)
  30077. {
  30078. channels[totalNumChans] = outputChannelData[i];
  30079. zeromem (channels[totalNumChans], sizeof (float) * numSamples);
  30080. ++totalNumChans;
  30081. }
  30082. }
  30083. AudioSampleBuffer buffer (channels, totalNumChans, numSamples);
  30084. const ScopedLock sl (lock);
  30085. if (processor != 0)
  30086. {
  30087. const ScopedLock sl (processor->getCallbackLock());
  30088. if (processor->isSuspended())
  30089. {
  30090. for (i = 0; i < numOutputChannels; ++i)
  30091. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  30092. }
  30093. else
  30094. {
  30095. processor->processBlock (buffer, incomingMidi);
  30096. }
  30097. }
  30098. }
  30099. void AudioProcessorPlayer::audioDeviceAboutToStart (AudioIODevice* device)
  30100. {
  30101. const ScopedLock sl (lock);
  30102. sampleRate = device->getCurrentSampleRate();
  30103. blockSize = device->getCurrentBufferSizeSamples();
  30104. numInputChans = device->getActiveInputChannels().countNumberOfSetBits();
  30105. numOutputChans = device->getActiveOutputChannels().countNumberOfSetBits();
  30106. messageCollector.reset (sampleRate);
  30107. zeromem (channels, sizeof (channels));
  30108. if (processor != 0)
  30109. {
  30110. if (isPrepared)
  30111. processor->releaseResources();
  30112. AudioProcessor* const oldProcessor = processor;
  30113. setProcessor (0);
  30114. setProcessor (oldProcessor);
  30115. }
  30116. }
  30117. void AudioProcessorPlayer::audioDeviceStopped()
  30118. {
  30119. const ScopedLock sl (lock);
  30120. if (processor != 0 && isPrepared)
  30121. processor->releaseResources();
  30122. sampleRate = 0.0;
  30123. blockSize = 0;
  30124. isPrepared = false;
  30125. tempBuffer.setSize (1, 1);
  30126. }
  30127. void AudioProcessorPlayer::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  30128. {
  30129. messageCollector.addMessageToQueue (message);
  30130. }
  30131. END_JUCE_NAMESPACE
  30132. /*** End of inlined file: juce_AudioProcessorPlayer.cpp ***/
  30133. /*** Start of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  30134. BEGIN_JUCE_NAMESPACE
  30135. class ProcessorParameterPropertyComp : public PropertyComponent,
  30136. public AudioProcessorListener,
  30137. public AsyncUpdater
  30138. {
  30139. public:
  30140. ProcessorParameterPropertyComp (const String& name, AudioProcessor& owner_, int index_)
  30141. : PropertyComponent (name),
  30142. owner (owner_),
  30143. index (index_),
  30144. slider (owner_, index_)
  30145. {
  30146. addAndMakeVisible (&slider);
  30147. owner_.addListener (this);
  30148. }
  30149. ~ProcessorParameterPropertyComp()
  30150. {
  30151. owner.removeListener (this);
  30152. }
  30153. void refresh()
  30154. {
  30155. slider.setValue (owner.getParameter (index), false);
  30156. }
  30157. void audioProcessorChanged (AudioProcessor*) {}
  30158. void audioProcessorParameterChanged (AudioProcessor*, int parameterIndex, float)
  30159. {
  30160. if (parameterIndex == index)
  30161. triggerAsyncUpdate();
  30162. }
  30163. void handleAsyncUpdate()
  30164. {
  30165. refresh();
  30166. }
  30167. juce_UseDebuggingNewOperator
  30168. private:
  30169. class ParamSlider : public Slider
  30170. {
  30171. public:
  30172. ParamSlider (AudioProcessor& owner_, const int index_)
  30173. : Slider (String::empty),
  30174. owner (owner_),
  30175. index (index_)
  30176. {
  30177. setRange (0.0, 1.0, 0.0);
  30178. setSliderStyle (Slider::LinearBar);
  30179. setTextBoxIsEditable (false);
  30180. setScrollWheelEnabled (false);
  30181. }
  30182. ~ParamSlider()
  30183. {
  30184. }
  30185. void valueChanged()
  30186. {
  30187. const float newVal = (float) getValue();
  30188. if (owner.getParameter (index) != newVal)
  30189. owner.setParameter (index, newVal);
  30190. }
  30191. const String getTextFromValue (double /*value*/)
  30192. {
  30193. return owner.getParameterText (index);
  30194. }
  30195. juce_UseDebuggingNewOperator
  30196. private:
  30197. AudioProcessor& owner;
  30198. const int index;
  30199. ParamSlider (const ParamSlider&);
  30200. ParamSlider& operator= (const ParamSlider&);
  30201. };
  30202. AudioProcessor& owner;
  30203. const int index;
  30204. ParamSlider slider;
  30205. ProcessorParameterPropertyComp (const ProcessorParameterPropertyComp&);
  30206. ProcessorParameterPropertyComp& operator= (const ProcessorParameterPropertyComp&);
  30207. };
  30208. GenericAudioProcessorEditor::GenericAudioProcessorEditor (AudioProcessor* const owner_)
  30209. : AudioProcessorEditor (owner_)
  30210. {
  30211. jassert (owner_ != 0);
  30212. setOpaque (true);
  30213. addAndMakeVisible (panel = new PropertyPanel());
  30214. Array <PropertyComponent*> params;
  30215. const int numParams = owner_->getNumParameters();
  30216. int totalHeight = 0;
  30217. for (int i = 0; i < numParams; ++i)
  30218. {
  30219. String name (owner_->getParameterName (i));
  30220. if (name.trim().isEmpty())
  30221. name = "Unnamed";
  30222. ProcessorParameterPropertyComp* const pc = new ProcessorParameterPropertyComp (name, *owner_, i);
  30223. params.add (pc);
  30224. totalHeight += pc->getPreferredHeight();
  30225. }
  30226. panel->addProperties (params);
  30227. setSize (400, jlimit (25, 400, totalHeight));
  30228. }
  30229. GenericAudioProcessorEditor::~GenericAudioProcessorEditor()
  30230. {
  30231. deleteAllChildren();
  30232. }
  30233. void GenericAudioProcessorEditor::paint (Graphics& g)
  30234. {
  30235. g.fillAll (Colours::white);
  30236. }
  30237. void GenericAudioProcessorEditor::resized()
  30238. {
  30239. panel->setSize (getWidth(), getHeight());
  30240. }
  30241. END_JUCE_NAMESPACE
  30242. /*** End of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  30243. /*** Start of inlined file: juce_Sampler.cpp ***/
  30244. BEGIN_JUCE_NAMESPACE
  30245. SamplerSound::SamplerSound (const String& name_,
  30246. AudioFormatReader& source,
  30247. const BigInteger& midiNotes_,
  30248. const int midiNoteForNormalPitch,
  30249. const double attackTimeSecs,
  30250. const double releaseTimeSecs,
  30251. const double maxSampleLengthSeconds)
  30252. : name (name_),
  30253. midiNotes (midiNotes_),
  30254. midiRootNote (midiNoteForNormalPitch)
  30255. {
  30256. sourceSampleRate = source.sampleRate;
  30257. if (sourceSampleRate <= 0 || source.lengthInSamples <= 0)
  30258. {
  30259. length = 0;
  30260. attackSamples = 0;
  30261. releaseSamples = 0;
  30262. }
  30263. else
  30264. {
  30265. length = jmin ((int) source.lengthInSamples,
  30266. (int) (maxSampleLengthSeconds * sourceSampleRate));
  30267. data = new AudioSampleBuffer (jmin (2, (int) source.numChannels), length + 4);
  30268. data->readFromAudioReader (&source, 0, length + 4, 0, true, true);
  30269. attackSamples = roundToInt (attackTimeSecs * sourceSampleRate);
  30270. releaseSamples = roundToInt (releaseTimeSecs * sourceSampleRate);
  30271. }
  30272. }
  30273. SamplerSound::~SamplerSound()
  30274. {
  30275. }
  30276. bool SamplerSound::appliesToNote (const int midiNoteNumber)
  30277. {
  30278. return midiNotes [midiNoteNumber];
  30279. }
  30280. bool SamplerSound::appliesToChannel (const int /*midiChannel*/)
  30281. {
  30282. return true;
  30283. }
  30284. SamplerVoice::SamplerVoice()
  30285. : pitchRatio (0.0),
  30286. sourceSamplePosition (0.0),
  30287. lgain (0.0f),
  30288. rgain (0.0f),
  30289. isInAttack (false),
  30290. isInRelease (false)
  30291. {
  30292. }
  30293. SamplerVoice::~SamplerVoice()
  30294. {
  30295. }
  30296. bool SamplerVoice::canPlaySound (SynthesiserSound* sound)
  30297. {
  30298. return dynamic_cast <const SamplerSound*> (sound) != 0;
  30299. }
  30300. void SamplerVoice::startNote (const int midiNoteNumber,
  30301. const float velocity,
  30302. SynthesiserSound* s,
  30303. const int /*currentPitchWheelPosition*/)
  30304. {
  30305. const SamplerSound* const sound = dynamic_cast <const SamplerSound*> (s);
  30306. jassert (sound != 0); // this object can only play SamplerSounds!
  30307. if (sound != 0)
  30308. {
  30309. const double targetFreq = MidiMessage::getMidiNoteInHertz (midiNoteNumber);
  30310. const double naturalFreq = MidiMessage::getMidiNoteInHertz (sound->midiRootNote);
  30311. pitchRatio = (targetFreq * sound->sourceSampleRate) / (naturalFreq * getSampleRate());
  30312. sourceSamplePosition = 0.0;
  30313. lgain = velocity;
  30314. rgain = velocity;
  30315. isInAttack = (sound->attackSamples > 0);
  30316. isInRelease = false;
  30317. if (isInAttack)
  30318. {
  30319. attackReleaseLevel = 0.0f;
  30320. attackDelta = (float) (pitchRatio / sound->attackSamples);
  30321. }
  30322. else
  30323. {
  30324. attackReleaseLevel = 1.0f;
  30325. attackDelta = 0.0f;
  30326. }
  30327. if (sound->releaseSamples > 0)
  30328. {
  30329. releaseDelta = (float) (-pitchRatio / sound->releaseSamples);
  30330. }
  30331. else
  30332. {
  30333. releaseDelta = 0.0f;
  30334. }
  30335. }
  30336. }
  30337. void SamplerVoice::stopNote (const bool allowTailOff)
  30338. {
  30339. if (allowTailOff)
  30340. {
  30341. isInAttack = false;
  30342. isInRelease = true;
  30343. }
  30344. else
  30345. {
  30346. clearCurrentNote();
  30347. }
  30348. }
  30349. void SamplerVoice::pitchWheelMoved (const int /*newValue*/)
  30350. {
  30351. }
  30352. void SamplerVoice::controllerMoved (const int /*controllerNumber*/,
  30353. const int /*newValue*/)
  30354. {
  30355. }
  30356. void SamplerVoice::renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples)
  30357. {
  30358. const SamplerSound* const playingSound = static_cast <SamplerSound*> (getCurrentlyPlayingSound().getObject());
  30359. if (playingSound != 0)
  30360. {
  30361. const float* const inL = playingSound->data->getSampleData (0, 0);
  30362. const float* const inR = playingSound->data->getNumChannels() > 1
  30363. ? playingSound->data->getSampleData (1, 0) : 0;
  30364. float* outL = outputBuffer.getSampleData (0, startSample);
  30365. float* outR = outputBuffer.getNumChannels() > 1 ? outputBuffer.getSampleData (1, startSample) : 0;
  30366. while (--numSamples >= 0)
  30367. {
  30368. const int pos = (int) sourceSamplePosition;
  30369. const float alpha = (float) (sourceSamplePosition - pos);
  30370. const float invAlpha = 1.0f - alpha;
  30371. // just using a very simple linear interpolation here..
  30372. float l = (inL [pos] * invAlpha + inL [pos + 1] * alpha);
  30373. float r = (inR != 0) ? (inR [pos] * invAlpha + inR [pos + 1] * alpha)
  30374. : l;
  30375. l *= lgain;
  30376. r *= rgain;
  30377. if (isInAttack)
  30378. {
  30379. l *= attackReleaseLevel;
  30380. r *= attackReleaseLevel;
  30381. attackReleaseLevel += attackDelta;
  30382. if (attackReleaseLevel >= 1.0f)
  30383. {
  30384. attackReleaseLevel = 1.0f;
  30385. isInAttack = false;
  30386. }
  30387. }
  30388. else if (isInRelease)
  30389. {
  30390. l *= attackReleaseLevel;
  30391. r *= attackReleaseLevel;
  30392. attackReleaseLevel += releaseDelta;
  30393. if (attackReleaseLevel <= 0.0f)
  30394. {
  30395. stopNote (false);
  30396. break;
  30397. }
  30398. }
  30399. if (outR != 0)
  30400. {
  30401. *outL++ += l;
  30402. *outR++ += r;
  30403. }
  30404. else
  30405. {
  30406. *outL++ += (l + r) * 0.5f;
  30407. }
  30408. sourceSamplePosition += pitchRatio;
  30409. if (sourceSamplePosition > playingSound->length)
  30410. {
  30411. stopNote (false);
  30412. break;
  30413. }
  30414. }
  30415. }
  30416. }
  30417. END_JUCE_NAMESPACE
  30418. /*** End of inlined file: juce_Sampler.cpp ***/
  30419. /*** Start of inlined file: juce_Synthesiser.cpp ***/
  30420. BEGIN_JUCE_NAMESPACE
  30421. SynthesiserSound::SynthesiserSound()
  30422. {
  30423. }
  30424. SynthesiserSound::~SynthesiserSound()
  30425. {
  30426. }
  30427. SynthesiserVoice::SynthesiserVoice()
  30428. : currentSampleRate (44100.0),
  30429. currentlyPlayingNote (-1),
  30430. noteOnTime (0),
  30431. currentlyPlayingSound (0)
  30432. {
  30433. }
  30434. SynthesiserVoice::~SynthesiserVoice()
  30435. {
  30436. }
  30437. bool SynthesiserVoice::isPlayingChannel (const int midiChannel) const
  30438. {
  30439. return currentlyPlayingSound != 0
  30440. && currentlyPlayingSound->appliesToChannel (midiChannel);
  30441. }
  30442. void SynthesiserVoice::setCurrentPlaybackSampleRate (const double newRate)
  30443. {
  30444. currentSampleRate = newRate;
  30445. }
  30446. void SynthesiserVoice::clearCurrentNote()
  30447. {
  30448. currentlyPlayingNote = -1;
  30449. currentlyPlayingSound = 0;
  30450. }
  30451. Synthesiser::Synthesiser()
  30452. : sampleRate (0),
  30453. lastNoteOnCounter (0),
  30454. shouldStealNotes (true)
  30455. {
  30456. for (int i = 0; i < numElementsInArray (lastPitchWheelValues); ++i)
  30457. lastPitchWheelValues[i] = 0x2000;
  30458. }
  30459. Synthesiser::~Synthesiser()
  30460. {
  30461. }
  30462. SynthesiserVoice* Synthesiser::getVoice (const int index) const
  30463. {
  30464. const ScopedLock sl (lock);
  30465. return voices [index];
  30466. }
  30467. void Synthesiser::clearVoices()
  30468. {
  30469. const ScopedLock sl (lock);
  30470. voices.clear();
  30471. }
  30472. void Synthesiser::addVoice (SynthesiserVoice* const newVoice)
  30473. {
  30474. const ScopedLock sl (lock);
  30475. voices.add (newVoice);
  30476. }
  30477. void Synthesiser::removeVoice (const int index)
  30478. {
  30479. const ScopedLock sl (lock);
  30480. voices.remove (index);
  30481. }
  30482. void Synthesiser::clearSounds()
  30483. {
  30484. const ScopedLock sl (lock);
  30485. sounds.clear();
  30486. }
  30487. void Synthesiser::addSound (const SynthesiserSound::Ptr& newSound)
  30488. {
  30489. const ScopedLock sl (lock);
  30490. sounds.add (newSound);
  30491. }
  30492. void Synthesiser::removeSound (const int index)
  30493. {
  30494. const ScopedLock sl (lock);
  30495. sounds.remove (index);
  30496. }
  30497. void Synthesiser::setNoteStealingEnabled (const bool shouldStealNotes_)
  30498. {
  30499. shouldStealNotes = shouldStealNotes_;
  30500. }
  30501. void Synthesiser::setCurrentPlaybackSampleRate (const double newRate)
  30502. {
  30503. if (sampleRate != newRate)
  30504. {
  30505. const ScopedLock sl (lock);
  30506. allNotesOff (0, false);
  30507. sampleRate = newRate;
  30508. for (int i = voices.size(); --i >= 0;)
  30509. voices.getUnchecked (i)->setCurrentPlaybackSampleRate (newRate);
  30510. }
  30511. }
  30512. void Synthesiser::renderNextBlock (AudioSampleBuffer& outputBuffer,
  30513. const MidiBuffer& midiData,
  30514. int startSample,
  30515. int numSamples)
  30516. {
  30517. // must set the sample rate before using this!
  30518. jassert (sampleRate != 0);
  30519. const ScopedLock sl (lock);
  30520. MidiBuffer::Iterator midiIterator (midiData);
  30521. midiIterator.setNextSamplePosition (startSample);
  30522. MidiMessage m (0xf4, 0.0);
  30523. while (numSamples > 0)
  30524. {
  30525. int midiEventPos;
  30526. const bool useEvent = midiIterator.getNextEvent (m, midiEventPos)
  30527. && midiEventPos < startSample + numSamples;
  30528. const int numThisTime = useEvent ? midiEventPos - startSample
  30529. : numSamples;
  30530. if (numThisTime > 0)
  30531. {
  30532. for (int i = voices.size(); --i >= 0;)
  30533. voices.getUnchecked (i)->renderNextBlock (outputBuffer, startSample, numThisTime);
  30534. }
  30535. if (useEvent)
  30536. {
  30537. if (m.isNoteOn())
  30538. {
  30539. const int channel = m.getChannel();
  30540. noteOn (channel,
  30541. m.getNoteNumber(),
  30542. m.getFloatVelocity());
  30543. }
  30544. else if (m.isNoteOff())
  30545. {
  30546. noteOff (m.getChannel(),
  30547. m.getNoteNumber(),
  30548. true);
  30549. }
  30550. else if (m.isAllNotesOff() || m.isAllSoundOff())
  30551. {
  30552. allNotesOff (m.getChannel(), true);
  30553. }
  30554. else if (m.isPitchWheel())
  30555. {
  30556. const int channel = m.getChannel();
  30557. const int wheelPos = m.getPitchWheelValue();
  30558. lastPitchWheelValues [channel - 1] = wheelPos;
  30559. handlePitchWheel (channel, wheelPos);
  30560. }
  30561. else if (m.isController())
  30562. {
  30563. handleController (m.getChannel(),
  30564. m.getControllerNumber(),
  30565. m.getControllerValue());
  30566. }
  30567. }
  30568. startSample += numThisTime;
  30569. numSamples -= numThisTime;
  30570. }
  30571. }
  30572. void Synthesiser::noteOn (const int midiChannel,
  30573. const int midiNoteNumber,
  30574. const float velocity)
  30575. {
  30576. const ScopedLock sl (lock);
  30577. for (int i = sounds.size(); --i >= 0;)
  30578. {
  30579. SynthesiserSound* const sound = sounds.getUnchecked(i);
  30580. if (sound->appliesToNote (midiNoteNumber)
  30581. && sound->appliesToChannel (midiChannel))
  30582. {
  30583. startVoice (findFreeVoice (sound, shouldStealNotes),
  30584. sound, midiChannel, midiNoteNumber, velocity);
  30585. }
  30586. }
  30587. }
  30588. void Synthesiser::startVoice (SynthesiserVoice* const voice,
  30589. SynthesiserSound* const sound,
  30590. const int midiChannel,
  30591. const int midiNoteNumber,
  30592. const float velocity)
  30593. {
  30594. if (voice != 0 && sound != 0)
  30595. {
  30596. if (voice->currentlyPlayingSound != 0)
  30597. voice->stopNote (false);
  30598. voice->startNote (midiNoteNumber,
  30599. velocity,
  30600. sound,
  30601. lastPitchWheelValues [midiChannel - 1]);
  30602. voice->currentlyPlayingNote = midiNoteNumber;
  30603. voice->noteOnTime = ++lastNoteOnCounter;
  30604. voice->currentlyPlayingSound = sound;
  30605. }
  30606. }
  30607. void Synthesiser::noteOff (const int midiChannel,
  30608. const int midiNoteNumber,
  30609. const bool allowTailOff)
  30610. {
  30611. const ScopedLock sl (lock);
  30612. for (int i = voices.size(); --i >= 0;)
  30613. {
  30614. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30615. if (voice->getCurrentlyPlayingNote() == midiNoteNumber)
  30616. {
  30617. SynthesiserSound* const sound = voice->getCurrentlyPlayingSound();
  30618. if (sound != 0
  30619. && sound->appliesToNote (midiNoteNumber)
  30620. && sound->appliesToChannel (midiChannel))
  30621. {
  30622. voice->stopNote (allowTailOff);
  30623. // the subclass MUST call clearCurrentNote() if it's not tailing off! RTFM for stopNote()!
  30624. jassert (allowTailOff || (voice->getCurrentlyPlayingNote() < 0 && voice->getCurrentlyPlayingSound() == 0));
  30625. }
  30626. }
  30627. }
  30628. }
  30629. void Synthesiser::allNotesOff (const int midiChannel,
  30630. const bool allowTailOff)
  30631. {
  30632. const ScopedLock sl (lock);
  30633. for (int i = voices.size(); --i >= 0;)
  30634. {
  30635. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30636. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30637. voice->stopNote (allowTailOff);
  30638. }
  30639. }
  30640. void Synthesiser::handlePitchWheel (const int midiChannel,
  30641. const int wheelValue)
  30642. {
  30643. const ScopedLock sl (lock);
  30644. for (int i = voices.size(); --i >= 0;)
  30645. {
  30646. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30647. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30648. {
  30649. voice->pitchWheelMoved (wheelValue);
  30650. }
  30651. }
  30652. }
  30653. void Synthesiser::handleController (const int midiChannel,
  30654. const int controllerNumber,
  30655. const int controllerValue)
  30656. {
  30657. const ScopedLock sl (lock);
  30658. for (int i = voices.size(); --i >= 0;)
  30659. {
  30660. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30661. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30662. voice->controllerMoved (controllerNumber, controllerValue);
  30663. }
  30664. }
  30665. SynthesiserVoice* Synthesiser::findFreeVoice (SynthesiserSound* soundToPlay,
  30666. const bool stealIfNoneAvailable) const
  30667. {
  30668. const ScopedLock sl (lock);
  30669. for (int i = voices.size(); --i >= 0;)
  30670. if (voices.getUnchecked (i)->getCurrentlyPlayingNote() < 0
  30671. && voices.getUnchecked (i)->canPlaySound (soundToPlay))
  30672. return voices.getUnchecked (i);
  30673. if (stealIfNoneAvailable)
  30674. {
  30675. // currently this just steals the one that's been playing the longest, but could be made a bit smarter..
  30676. SynthesiserVoice* oldest = 0;
  30677. for (int i = voices.size(); --i >= 0;)
  30678. {
  30679. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30680. if (voice->canPlaySound (soundToPlay)
  30681. && (oldest == 0 || oldest->noteOnTime > voice->noteOnTime))
  30682. oldest = voice;
  30683. }
  30684. jassert (oldest != 0);
  30685. return oldest;
  30686. }
  30687. return 0;
  30688. }
  30689. END_JUCE_NAMESPACE
  30690. /*** End of inlined file: juce_Synthesiser.cpp ***/
  30691. /*** Start of inlined file: juce_ActionBroadcaster.cpp ***/
  30692. BEGIN_JUCE_NAMESPACE
  30693. ActionBroadcaster::ActionBroadcaster() throw()
  30694. {
  30695. // are you trying to create this object before or after juce has been intialised??
  30696. jassert (MessageManager::instance != 0);
  30697. }
  30698. ActionBroadcaster::~ActionBroadcaster()
  30699. {
  30700. // all event-based objects must be deleted BEFORE juce is shut down!
  30701. jassert (MessageManager::instance != 0);
  30702. }
  30703. void ActionBroadcaster::addActionListener (ActionListener* const listener)
  30704. {
  30705. actionListenerList.addActionListener (listener);
  30706. }
  30707. void ActionBroadcaster::removeActionListener (ActionListener* const listener)
  30708. {
  30709. jassert (actionListenerList.isValidMessageListener());
  30710. if (actionListenerList.isValidMessageListener())
  30711. actionListenerList.removeActionListener (listener);
  30712. }
  30713. void ActionBroadcaster::removeAllActionListeners()
  30714. {
  30715. actionListenerList.removeAllActionListeners();
  30716. }
  30717. void ActionBroadcaster::sendActionMessage (const String& message) const
  30718. {
  30719. actionListenerList.sendActionMessage (message);
  30720. }
  30721. END_JUCE_NAMESPACE
  30722. /*** End of inlined file: juce_ActionBroadcaster.cpp ***/
  30723. /*** Start of inlined file: juce_ActionListenerList.cpp ***/
  30724. BEGIN_JUCE_NAMESPACE
  30725. // special message of our own with a string in it
  30726. class ActionMessage : public Message
  30727. {
  30728. public:
  30729. const String message;
  30730. ActionMessage (const String& messageText, void* const listener_) throw()
  30731. : message (messageText)
  30732. {
  30733. pointerParameter = listener_;
  30734. }
  30735. ~ActionMessage() throw()
  30736. {
  30737. }
  30738. private:
  30739. ActionMessage (const ActionMessage&);
  30740. ActionMessage& operator= (const ActionMessage&);
  30741. };
  30742. ActionListenerList::ActionListenerList()
  30743. {
  30744. }
  30745. ActionListenerList::~ActionListenerList()
  30746. {
  30747. }
  30748. void ActionListenerList::addActionListener (ActionListener* const listener)
  30749. {
  30750. const ScopedLock sl (actionListenerLock_);
  30751. jassert (listener != 0);
  30752. jassert (! actionListeners_.contains (listener)); // trying to add a listener to the list twice!
  30753. if (listener != 0)
  30754. actionListeners_.add (listener);
  30755. }
  30756. void ActionListenerList::removeActionListener (ActionListener* const listener)
  30757. {
  30758. const ScopedLock sl (actionListenerLock_);
  30759. jassert (actionListeners_.contains (listener)); // trying to remove a listener that isn't on the list!
  30760. actionListeners_.removeValue (listener);
  30761. }
  30762. void ActionListenerList::removeAllActionListeners()
  30763. {
  30764. const ScopedLock sl (actionListenerLock_);
  30765. actionListeners_.clear();
  30766. }
  30767. void ActionListenerList::sendActionMessage (const String& message) const
  30768. {
  30769. const ScopedLock sl (actionListenerLock_);
  30770. for (int i = actionListeners_.size(); --i >= 0;)
  30771. postMessage (new ActionMessage (message, static_cast <ActionListener*> (actionListeners_.getUnchecked(i))));
  30772. }
  30773. void ActionListenerList::handleMessage (const Message& message)
  30774. {
  30775. const ActionMessage& am = (const ActionMessage&) message;
  30776. if (actionListeners_.contains (am.pointerParameter))
  30777. static_cast <ActionListener*> (am.pointerParameter)->actionListenerCallback (am.message);
  30778. }
  30779. END_JUCE_NAMESPACE
  30780. /*** End of inlined file: juce_ActionListenerList.cpp ***/
  30781. /*** Start of inlined file: juce_AsyncUpdater.cpp ***/
  30782. BEGIN_JUCE_NAMESPACE
  30783. AsyncUpdater::AsyncUpdater() throw()
  30784. : asyncMessagePending (false)
  30785. {
  30786. internalAsyncHandler.owner = this;
  30787. }
  30788. AsyncUpdater::~AsyncUpdater()
  30789. {
  30790. }
  30791. void AsyncUpdater::triggerAsyncUpdate()
  30792. {
  30793. if (! asyncMessagePending)
  30794. {
  30795. asyncMessagePending = true;
  30796. internalAsyncHandler.postMessage (new Message());
  30797. }
  30798. }
  30799. void AsyncUpdater::cancelPendingUpdate() throw()
  30800. {
  30801. asyncMessagePending = false;
  30802. }
  30803. void AsyncUpdater::handleUpdateNowIfNeeded()
  30804. {
  30805. if (asyncMessagePending)
  30806. {
  30807. asyncMessagePending = false;
  30808. handleAsyncUpdate();
  30809. }
  30810. }
  30811. void AsyncUpdater::AsyncUpdaterInternal::handleMessage (const Message&)
  30812. {
  30813. owner->handleUpdateNowIfNeeded();
  30814. }
  30815. END_JUCE_NAMESPACE
  30816. /*** End of inlined file: juce_AsyncUpdater.cpp ***/
  30817. /*** Start of inlined file: juce_ChangeBroadcaster.cpp ***/
  30818. BEGIN_JUCE_NAMESPACE
  30819. ChangeBroadcaster::ChangeBroadcaster() throw()
  30820. {
  30821. // are you trying to create this object before or after juce has been intialised??
  30822. jassert (MessageManager::instance != 0);
  30823. }
  30824. ChangeBroadcaster::~ChangeBroadcaster()
  30825. {
  30826. // all event-based objects must be deleted BEFORE juce is shut down!
  30827. jassert (MessageManager::instance != 0);
  30828. }
  30829. void ChangeBroadcaster::addChangeListener (ChangeListener* const listener)
  30830. {
  30831. changeListenerList.addChangeListener (listener);
  30832. }
  30833. void ChangeBroadcaster::removeChangeListener (ChangeListener* const listener)
  30834. {
  30835. jassert (changeListenerList.isValidMessageListener());
  30836. if (changeListenerList.isValidMessageListener())
  30837. changeListenerList.removeChangeListener (listener);
  30838. }
  30839. void ChangeBroadcaster::removeAllChangeListeners()
  30840. {
  30841. changeListenerList.removeAllChangeListeners();
  30842. }
  30843. void ChangeBroadcaster::sendChangeMessage (void* objectThatHasChanged)
  30844. {
  30845. changeListenerList.sendChangeMessage (objectThatHasChanged);
  30846. }
  30847. void ChangeBroadcaster::sendSynchronousChangeMessage (void* objectThatHasChanged)
  30848. {
  30849. changeListenerList.sendSynchronousChangeMessage (objectThatHasChanged);
  30850. }
  30851. void ChangeBroadcaster::dispatchPendingMessages()
  30852. {
  30853. changeListenerList.dispatchPendingMessages();
  30854. }
  30855. END_JUCE_NAMESPACE
  30856. /*** End of inlined file: juce_ChangeBroadcaster.cpp ***/
  30857. /*** Start of inlined file: juce_ChangeListenerList.cpp ***/
  30858. BEGIN_JUCE_NAMESPACE
  30859. ChangeListenerList::ChangeListenerList()
  30860. : lastChangedObject (0),
  30861. messagePending (false)
  30862. {
  30863. }
  30864. ChangeListenerList::~ChangeListenerList()
  30865. {
  30866. }
  30867. void ChangeListenerList::addChangeListener (ChangeListener* const listener)
  30868. {
  30869. const ScopedLock sl (lock);
  30870. jassert (listener != 0);
  30871. if (listener != 0)
  30872. listeners.add (listener);
  30873. }
  30874. void ChangeListenerList::removeChangeListener (ChangeListener* const listener)
  30875. {
  30876. const ScopedLock sl (lock);
  30877. listeners.removeValue (listener);
  30878. }
  30879. void ChangeListenerList::removeAllChangeListeners()
  30880. {
  30881. const ScopedLock sl (lock);
  30882. listeners.clear();
  30883. }
  30884. void ChangeListenerList::sendChangeMessage (void* const objectThatHasChanged)
  30885. {
  30886. const ScopedLock sl (lock);
  30887. if ((! messagePending) && (listeners.size() > 0))
  30888. {
  30889. lastChangedObject = objectThatHasChanged;
  30890. postMessage (new Message (0, 0, 0, objectThatHasChanged));
  30891. messagePending = true;
  30892. }
  30893. }
  30894. void ChangeListenerList::handleMessage (const Message& message)
  30895. {
  30896. sendSynchronousChangeMessage (message.pointerParameter);
  30897. }
  30898. void ChangeListenerList::sendSynchronousChangeMessage (void* const objectThatHasChanged)
  30899. {
  30900. const ScopedLock sl (lock);
  30901. messagePending = false;
  30902. for (int i = listeners.size(); --i >= 0;)
  30903. {
  30904. ChangeListener* const l = static_cast <ChangeListener*> (listeners.getUnchecked (i));
  30905. {
  30906. const ScopedUnlock tempUnlocker (lock);
  30907. l->changeListenerCallback (objectThatHasChanged);
  30908. }
  30909. i = jmin (i, listeners.size());
  30910. }
  30911. }
  30912. void ChangeListenerList::dispatchPendingMessages()
  30913. {
  30914. if (messagePending)
  30915. sendSynchronousChangeMessage (lastChangedObject);
  30916. }
  30917. END_JUCE_NAMESPACE
  30918. /*** End of inlined file: juce_ChangeListenerList.cpp ***/
  30919. /*** Start of inlined file: juce_InterprocessConnection.cpp ***/
  30920. BEGIN_JUCE_NAMESPACE
  30921. InterprocessConnection::InterprocessConnection (const bool callbacksOnMessageThread,
  30922. const uint32 magicMessageHeaderNumber)
  30923. : Thread ("Juce IPC connection"),
  30924. callbackConnectionState (false),
  30925. useMessageThread (callbacksOnMessageThread),
  30926. magicMessageHeader (magicMessageHeaderNumber),
  30927. pipeReceiveMessageTimeout (-1)
  30928. {
  30929. }
  30930. InterprocessConnection::~InterprocessConnection()
  30931. {
  30932. callbackConnectionState = false;
  30933. disconnect();
  30934. }
  30935. bool InterprocessConnection::connectToSocket (const String& hostName,
  30936. const int portNumber,
  30937. const int timeOutMillisecs)
  30938. {
  30939. disconnect();
  30940. const ScopedLock sl (pipeAndSocketLock);
  30941. socket = new StreamingSocket();
  30942. if (socket->connect (hostName, portNumber, timeOutMillisecs))
  30943. {
  30944. connectionMadeInt();
  30945. startThread();
  30946. return true;
  30947. }
  30948. else
  30949. {
  30950. socket = 0;
  30951. return false;
  30952. }
  30953. }
  30954. bool InterprocessConnection::connectToPipe (const String& pipeName,
  30955. const int pipeReceiveMessageTimeoutMs)
  30956. {
  30957. disconnect();
  30958. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  30959. if (newPipe->openExisting (pipeName))
  30960. {
  30961. const ScopedLock sl (pipeAndSocketLock);
  30962. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  30963. initialiseWithPipe (newPipe.release());
  30964. return true;
  30965. }
  30966. return false;
  30967. }
  30968. bool InterprocessConnection::createPipe (const String& pipeName,
  30969. const int pipeReceiveMessageTimeoutMs)
  30970. {
  30971. disconnect();
  30972. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  30973. if (newPipe->createNewPipe (pipeName))
  30974. {
  30975. const ScopedLock sl (pipeAndSocketLock);
  30976. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  30977. initialiseWithPipe (newPipe.release());
  30978. return true;
  30979. }
  30980. return false;
  30981. }
  30982. void InterprocessConnection::disconnect()
  30983. {
  30984. if (socket != 0)
  30985. socket->close();
  30986. if (pipe != 0)
  30987. {
  30988. pipe->cancelPendingReads();
  30989. pipe->close();
  30990. }
  30991. stopThread (4000);
  30992. {
  30993. const ScopedLock sl (pipeAndSocketLock);
  30994. socket = 0;
  30995. pipe = 0;
  30996. }
  30997. connectionLostInt();
  30998. }
  30999. bool InterprocessConnection::isConnected() const
  31000. {
  31001. const ScopedLock sl (pipeAndSocketLock);
  31002. return ((socket != 0 && socket->isConnected())
  31003. || (pipe != 0 && pipe->isOpen()))
  31004. && isThreadRunning();
  31005. }
  31006. const String InterprocessConnection::getConnectedHostName() const
  31007. {
  31008. if (pipe != 0)
  31009. {
  31010. return "localhost";
  31011. }
  31012. else if (socket != 0)
  31013. {
  31014. if (! socket->isLocal())
  31015. return socket->getHostName();
  31016. return "localhost";
  31017. }
  31018. return String::empty;
  31019. }
  31020. bool InterprocessConnection::sendMessage (const MemoryBlock& message)
  31021. {
  31022. uint32 messageHeader[2];
  31023. messageHeader [0] = ByteOrder::swapIfBigEndian (magicMessageHeader);
  31024. messageHeader [1] = ByteOrder::swapIfBigEndian ((uint32) message.getSize());
  31025. MemoryBlock messageData (sizeof (messageHeader) + message.getSize());
  31026. messageData.copyFrom (messageHeader, 0, sizeof (messageHeader));
  31027. messageData.copyFrom (message.getData(), sizeof (messageHeader), message.getSize());
  31028. size_t bytesWritten = 0;
  31029. const ScopedLock sl (pipeAndSocketLock);
  31030. if (socket != 0)
  31031. {
  31032. bytesWritten = socket->write (messageData.getData(), (int) messageData.getSize());
  31033. }
  31034. else if (pipe != 0)
  31035. {
  31036. bytesWritten = pipe->write (messageData.getData(), (int) messageData.getSize());
  31037. }
  31038. if (bytesWritten < 0)
  31039. {
  31040. // error..
  31041. return false;
  31042. }
  31043. return (bytesWritten == messageData.getSize());
  31044. }
  31045. void InterprocessConnection::initialiseWithSocket (StreamingSocket* const socket_)
  31046. {
  31047. jassert (socket == 0);
  31048. socket = socket_;
  31049. connectionMadeInt();
  31050. startThread();
  31051. }
  31052. void InterprocessConnection::initialiseWithPipe (NamedPipe* const pipe_)
  31053. {
  31054. jassert (pipe == 0);
  31055. pipe = pipe_;
  31056. connectionMadeInt();
  31057. startThread();
  31058. }
  31059. const int messageMagicNumber = 0xb734128b;
  31060. void InterprocessConnection::handleMessage (const Message& message)
  31061. {
  31062. if (message.intParameter1 == messageMagicNumber)
  31063. {
  31064. switch (message.intParameter2)
  31065. {
  31066. case 0:
  31067. {
  31068. ScopedPointer <MemoryBlock> data (static_cast <MemoryBlock*> (message.pointerParameter));
  31069. messageReceived (*data);
  31070. break;
  31071. }
  31072. case 1:
  31073. connectionMade();
  31074. break;
  31075. case 2:
  31076. connectionLost();
  31077. break;
  31078. }
  31079. }
  31080. }
  31081. void InterprocessConnection::connectionMadeInt()
  31082. {
  31083. if (! callbackConnectionState)
  31084. {
  31085. callbackConnectionState = true;
  31086. if (useMessageThread)
  31087. postMessage (new Message (messageMagicNumber, 1, 0, 0));
  31088. else
  31089. connectionMade();
  31090. }
  31091. }
  31092. void InterprocessConnection::connectionLostInt()
  31093. {
  31094. if (callbackConnectionState)
  31095. {
  31096. callbackConnectionState = false;
  31097. if (useMessageThread)
  31098. postMessage (new Message (messageMagicNumber, 2, 0, 0));
  31099. else
  31100. connectionLost();
  31101. }
  31102. }
  31103. void InterprocessConnection::deliverDataInt (const MemoryBlock& data)
  31104. {
  31105. jassert (callbackConnectionState);
  31106. if (useMessageThread)
  31107. postMessage (new Message (messageMagicNumber, 0, 0, new MemoryBlock (data)));
  31108. else
  31109. messageReceived (data);
  31110. }
  31111. bool InterprocessConnection::readNextMessageInt()
  31112. {
  31113. const int maximumMessageSize = 1024 * 1024 * 10; // sanity check
  31114. uint32 messageHeader[2];
  31115. const int bytes = (socket != 0) ? socket->read (messageHeader, sizeof (messageHeader), true)
  31116. : pipe->read (messageHeader, sizeof (messageHeader), pipeReceiveMessageTimeout);
  31117. if (bytes == sizeof (messageHeader)
  31118. && ByteOrder::swapIfBigEndian (messageHeader[0]) == magicMessageHeader)
  31119. {
  31120. int bytesInMessage = (int) ByteOrder::swapIfBigEndian (messageHeader[1]);
  31121. if (bytesInMessage > 0 && bytesInMessage < maximumMessageSize)
  31122. {
  31123. MemoryBlock messageData (bytesInMessage, true);
  31124. int bytesRead = 0;
  31125. while (bytesInMessage > 0)
  31126. {
  31127. if (threadShouldExit())
  31128. return false;
  31129. const int numThisTime = jmin (bytesInMessage, 65536);
  31130. const int bytesIn = (socket != 0) ? socket->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, true)
  31131. : pipe->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, pipeReceiveMessageTimeout);
  31132. if (bytesIn <= 0)
  31133. break;
  31134. bytesRead += bytesIn;
  31135. bytesInMessage -= bytesIn;
  31136. }
  31137. if (bytesRead >= 0)
  31138. deliverDataInt (messageData);
  31139. }
  31140. }
  31141. else if (bytes < 0)
  31142. {
  31143. {
  31144. const ScopedLock sl (pipeAndSocketLock);
  31145. socket = 0;
  31146. }
  31147. connectionLostInt();
  31148. return false;
  31149. }
  31150. return true;
  31151. }
  31152. void InterprocessConnection::run()
  31153. {
  31154. while (! threadShouldExit())
  31155. {
  31156. if (socket != 0)
  31157. {
  31158. const int ready = socket->waitUntilReady (true, 0);
  31159. if (ready < 0)
  31160. {
  31161. {
  31162. const ScopedLock sl (pipeAndSocketLock);
  31163. socket = 0;
  31164. }
  31165. connectionLostInt();
  31166. break;
  31167. }
  31168. else if (ready > 0)
  31169. {
  31170. if (! readNextMessageInt())
  31171. break;
  31172. }
  31173. else
  31174. {
  31175. Thread::sleep (2);
  31176. }
  31177. }
  31178. else if (pipe != 0)
  31179. {
  31180. if (! pipe->isOpen())
  31181. {
  31182. {
  31183. const ScopedLock sl (pipeAndSocketLock);
  31184. pipe = 0;
  31185. }
  31186. connectionLostInt();
  31187. break;
  31188. }
  31189. else
  31190. {
  31191. if (! readNextMessageInt())
  31192. break;
  31193. }
  31194. }
  31195. else
  31196. {
  31197. break;
  31198. }
  31199. }
  31200. }
  31201. END_JUCE_NAMESPACE
  31202. /*** End of inlined file: juce_InterprocessConnection.cpp ***/
  31203. /*** Start of inlined file: juce_InterprocessConnectionServer.cpp ***/
  31204. BEGIN_JUCE_NAMESPACE
  31205. InterprocessConnectionServer::InterprocessConnectionServer()
  31206. : Thread ("Juce IPC server")
  31207. {
  31208. }
  31209. InterprocessConnectionServer::~InterprocessConnectionServer()
  31210. {
  31211. stop();
  31212. }
  31213. bool InterprocessConnectionServer::beginWaitingForSocket (const int portNumber)
  31214. {
  31215. stop();
  31216. socket = new StreamingSocket();
  31217. if (socket->createListener (portNumber))
  31218. {
  31219. startThread();
  31220. return true;
  31221. }
  31222. socket = 0;
  31223. return false;
  31224. }
  31225. void InterprocessConnectionServer::stop()
  31226. {
  31227. signalThreadShouldExit();
  31228. if (socket != 0)
  31229. socket->close();
  31230. stopThread (4000);
  31231. socket = 0;
  31232. }
  31233. void InterprocessConnectionServer::run()
  31234. {
  31235. while ((! threadShouldExit()) && socket != 0)
  31236. {
  31237. ScopedPointer <StreamingSocket> clientSocket (socket->waitForNextConnection());
  31238. if (clientSocket != 0)
  31239. {
  31240. InterprocessConnection* newConnection = createConnectionObject();
  31241. if (newConnection != 0)
  31242. newConnection->initialiseWithSocket (clientSocket.release());
  31243. }
  31244. }
  31245. }
  31246. END_JUCE_NAMESPACE
  31247. /*** End of inlined file: juce_InterprocessConnectionServer.cpp ***/
  31248. /*** Start of inlined file: juce_Message.cpp ***/
  31249. BEGIN_JUCE_NAMESPACE
  31250. Message::Message() throw()
  31251. : intParameter1 (0),
  31252. intParameter2 (0),
  31253. intParameter3 (0),
  31254. pointerParameter (0)
  31255. {
  31256. }
  31257. Message::Message (const int intParameter1_,
  31258. const int intParameter2_,
  31259. const int intParameter3_,
  31260. void* const pointerParameter_) throw()
  31261. : intParameter1 (intParameter1_),
  31262. intParameter2 (intParameter2_),
  31263. intParameter3 (intParameter3_),
  31264. pointerParameter (pointerParameter_)
  31265. {
  31266. }
  31267. Message::~Message() throw()
  31268. {
  31269. }
  31270. END_JUCE_NAMESPACE
  31271. /*** End of inlined file: juce_Message.cpp ***/
  31272. /*** Start of inlined file: juce_MessageListener.cpp ***/
  31273. BEGIN_JUCE_NAMESPACE
  31274. MessageListener::MessageListener() throw()
  31275. {
  31276. // are you trying to create a messagelistener before or after juce has been intialised??
  31277. jassert (MessageManager::instance != 0);
  31278. if (MessageManager::instance != 0)
  31279. MessageManager::instance->messageListeners.add (this);
  31280. }
  31281. MessageListener::~MessageListener()
  31282. {
  31283. if (MessageManager::instance != 0)
  31284. MessageManager::instance->messageListeners.removeValue (this);
  31285. }
  31286. void MessageListener::postMessage (Message* const message) const throw()
  31287. {
  31288. message->messageRecipient = const_cast <MessageListener*> (this);
  31289. if (MessageManager::instance == 0)
  31290. MessageManager::getInstance();
  31291. MessageManager::instance->postMessageToQueue (message);
  31292. }
  31293. bool MessageListener::isValidMessageListener() const throw()
  31294. {
  31295. return (MessageManager::instance != 0)
  31296. && MessageManager::instance->messageListeners.contains (this);
  31297. }
  31298. END_JUCE_NAMESPACE
  31299. /*** End of inlined file: juce_MessageListener.cpp ***/
  31300. /*** Start of inlined file: juce_MessageManager.cpp ***/
  31301. BEGIN_JUCE_NAMESPACE
  31302. // platform-specific functions..
  31303. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
  31304. bool juce_postMessageToSystemQueue (Message* message);
  31305. MessageManager* MessageManager::instance = 0;
  31306. static const int quitMessageId = 0xfffff321;
  31307. MessageManager::MessageManager() throw()
  31308. : quitMessagePosted (false),
  31309. quitMessageReceived (false),
  31310. threadWithLock (0)
  31311. {
  31312. messageThreadId = Thread::getCurrentThreadId();
  31313. }
  31314. MessageManager::~MessageManager() throw()
  31315. {
  31316. broadcastListeners = 0;
  31317. doPlatformSpecificShutdown();
  31318. // If you hit this assertion, then you've probably leaked a Component or some other
  31319. // kind of MessageListener object...
  31320. jassert (messageListeners.size() == 0);
  31321. jassert (instance == this);
  31322. instance = 0; // do this last in case this instance is still needed by doPlatformSpecificShutdown()
  31323. }
  31324. MessageManager* MessageManager::getInstance() throw()
  31325. {
  31326. if (instance == 0)
  31327. {
  31328. instance = new MessageManager();
  31329. doPlatformSpecificInitialisation();
  31330. }
  31331. return instance;
  31332. }
  31333. void MessageManager::postMessageToQueue (Message* const message)
  31334. {
  31335. if (quitMessagePosted || ! juce_postMessageToSystemQueue (message))
  31336. delete message;
  31337. }
  31338. CallbackMessage::CallbackMessage() throw() {}
  31339. CallbackMessage::~CallbackMessage() throw() {}
  31340. void CallbackMessage::post()
  31341. {
  31342. if (MessageManager::instance != 0)
  31343. MessageManager::instance->postCallbackMessage (this);
  31344. }
  31345. void MessageManager::postCallbackMessage (Message* const message)
  31346. {
  31347. message->messageRecipient = 0;
  31348. postMessageToQueue (message);
  31349. }
  31350. // not for public use..
  31351. void MessageManager::deliverMessage (Message* const message)
  31352. {
  31353. const ScopedPointer <Message> messageDeleter (message);
  31354. MessageListener* const recipient = message->messageRecipient;
  31355. JUCE_TRY
  31356. {
  31357. if (messageListeners.contains (recipient))
  31358. {
  31359. recipient->handleMessage (*message);
  31360. }
  31361. else if (recipient == 0)
  31362. {
  31363. if (message->intParameter1 == quitMessageId)
  31364. {
  31365. quitMessageReceived = true;
  31366. }
  31367. else
  31368. {
  31369. CallbackMessage* const cm = dynamic_cast <CallbackMessage*> (message);
  31370. if (cm != 0)
  31371. cm->messageCallback();
  31372. }
  31373. }
  31374. }
  31375. JUCE_CATCH_EXCEPTION
  31376. }
  31377. #if ! (JUCE_MAC || JUCE_IOS)
  31378. void MessageManager::runDispatchLoop()
  31379. {
  31380. jassert (isThisTheMessageThread()); // must only be called by the message thread
  31381. runDispatchLoopUntil (-1);
  31382. }
  31383. void MessageManager::stopDispatchLoop()
  31384. {
  31385. Message* const m = new Message (quitMessageId, 0, 0, 0);
  31386. m->messageRecipient = 0;
  31387. postMessageToQueue (m);
  31388. quitMessagePosted = true;
  31389. }
  31390. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  31391. {
  31392. jassert (isThisTheMessageThread()); // must only be called by the message thread
  31393. const int64 endTime = Time::currentTimeMillis() + millisecondsToRunFor;
  31394. while ((millisecondsToRunFor < 0 || endTime > Time::currentTimeMillis())
  31395. && ! quitMessageReceived)
  31396. {
  31397. JUCE_TRY
  31398. {
  31399. if (! juce_dispatchNextMessageOnSystemQueue (millisecondsToRunFor >= 0))
  31400. {
  31401. const int msToWait = (int) (endTime - Time::currentTimeMillis());
  31402. if (msToWait > 0)
  31403. Thread::sleep (jmin (5, msToWait));
  31404. }
  31405. }
  31406. JUCE_CATCH_EXCEPTION
  31407. }
  31408. return ! quitMessageReceived;
  31409. }
  31410. #endif
  31411. void MessageManager::deliverBroadcastMessage (const String& value)
  31412. {
  31413. if (broadcastListeners != 0)
  31414. broadcastListeners->sendActionMessage (value);
  31415. }
  31416. void MessageManager::registerBroadcastListener (ActionListener* const listener)
  31417. {
  31418. if (broadcastListeners == 0)
  31419. broadcastListeners = new ActionListenerList();
  31420. broadcastListeners->addActionListener (listener);
  31421. }
  31422. void MessageManager::deregisterBroadcastListener (ActionListener* const listener)
  31423. {
  31424. if (broadcastListeners != 0)
  31425. broadcastListeners->removeActionListener (listener);
  31426. }
  31427. bool MessageManager::isThisTheMessageThread() const throw()
  31428. {
  31429. return Thread::getCurrentThreadId() == messageThreadId;
  31430. }
  31431. void MessageManager::setCurrentThreadAsMessageThread()
  31432. {
  31433. if (messageThreadId != Thread::getCurrentThreadId())
  31434. {
  31435. messageThreadId = Thread::getCurrentThreadId();
  31436. // This is needed on windows to make sure the message window is created by this thread
  31437. doPlatformSpecificShutdown();
  31438. doPlatformSpecificInitialisation();
  31439. }
  31440. }
  31441. bool MessageManager::currentThreadHasLockedMessageManager() const throw()
  31442. {
  31443. const Thread::ThreadID thisThread = Thread::getCurrentThreadId();
  31444. return thisThread == messageThreadId || thisThread == threadWithLock;
  31445. }
  31446. /* The only safe way to lock the message thread while another thread does
  31447. some work is by posting a special message, whose purpose is to tie up the event
  31448. loop until the other thread has finished its business.
  31449. Any other approach can get horribly deadlocked if the OS uses its own hidden locks which
  31450. get locked before making an event callback, because if the same OS lock gets indirectly
  31451. accessed from another thread inside a MM lock, you're screwed. (this is exactly what happens
  31452. in Cocoa).
  31453. */
  31454. class MessageManagerLock::SharedEvents : public ReferenceCountedObject
  31455. {
  31456. public:
  31457. SharedEvents() {}
  31458. ~SharedEvents() {}
  31459. /* This class just holds a couple of events to communicate between the BlockingMessage
  31460. and the MessageManagerLock. Because both of these objects may be deleted at any time,
  31461. this shared data must be kept in a separate, ref-counted container. */
  31462. WaitableEvent lockedEvent, releaseEvent;
  31463. private:
  31464. SharedEvents (const SharedEvents&);
  31465. SharedEvents& operator= (const SharedEvents&);
  31466. };
  31467. class MessageManagerLock::BlockingMessage : public CallbackMessage
  31468. {
  31469. public:
  31470. BlockingMessage (MessageManagerLock::SharedEvents* const events_) : events (events_) {}
  31471. ~BlockingMessage() throw() {}
  31472. void messageCallback()
  31473. {
  31474. events->lockedEvent.signal();
  31475. events->releaseEvent.wait();
  31476. }
  31477. juce_UseDebuggingNewOperator
  31478. private:
  31479. ReferenceCountedObjectPtr <MessageManagerLock::SharedEvents> events;
  31480. BlockingMessage (const BlockingMessage&);
  31481. BlockingMessage& operator= (const BlockingMessage&);
  31482. };
  31483. MessageManagerLock::MessageManagerLock (Thread* const threadToCheck)
  31484. : sharedEvents (0),
  31485. locked (false)
  31486. {
  31487. init (threadToCheck, 0);
  31488. }
  31489. MessageManagerLock::MessageManagerLock (ThreadPoolJob* const jobToCheckForExitSignal)
  31490. : sharedEvents (0),
  31491. locked (false)
  31492. {
  31493. init (0, jobToCheckForExitSignal);
  31494. }
  31495. void MessageManagerLock::init (Thread* const threadToCheck, ThreadPoolJob* const job)
  31496. {
  31497. if (MessageManager::instance != 0)
  31498. {
  31499. if (MessageManager::instance->currentThreadHasLockedMessageManager())
  31500. {
  31501. locked = true; // either we're on the message thread, or this is a re-entrant call.
  31502. }
  31503. else
  31504. {
  31505. if (threadToCheck == 0 && job == 0)
  31506. {
  31507. MessageManager::instance->lockingLock.enter();
  31508. }
  31509. else
  31510. {
  31511. while (! MessageManager::instance->lockingLock.tryEnter())
  31512. {
  31513. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  31514. || (job != 0 && job->shouldExit()))
  31515. return;
  31516. Thread::sleep (1);
  31517. }
  31518. }
  31519. sharedEvents = new SharedEvents();
  31520. sharedEvents->incReferenceCount();
  31521. (new BlockingMessage (sharedEvents))->post();
  31522. while (! sharedEvents->lockedEvent.wait (50))
  31523. {
  31524. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  31525. || (job != 0 && job->shouldExit()))
  31526. {
  31527. sharedEvents->releaseEvent.signal();
  31528. sharedEvents->decReferenceCount();
  31529. sharedEvents = 0;
  31530. MessageManager::instance->lockingLock.exit();
  31531. return;
  31532. }
  31533. }
  31534. jassert (MessageManager::instance->threadWithLock == 0);
  31535. MessageManager::instance->threadWithLock = Thread::getCurrentThreadId();
  31536. locked = true;
  31537. }
  31538. }
  31539. }
  31540. MessageManagerLock::~MessageManagerLock() throw()
  31541. {
  31542. if (sharedEvents != 0)
  31543. {
  31544. jassert (MessageManager::instance == 0 || MessageManager::instance->currentThreadHasLockedMessageManager());
  31545. sharedEvents->releaseEvent.signal();
  31546. sharedEvents->decReferenceCount();
  31547. if (MessageManager::instance != 0)
  31548. {
  31549. MessageManager::instance->threadWithLock = 0;
  31550. MessageManager::instance->lockingLock.exit();
  31551. }
  31552. }
  31553. }
  31554. END_JUCE_NAMESPACE
  31555. /*** End of inlined file: juce_MessageManager.cpp ***/
  31556. /*** Start of inlined file: juce_MultiTimer.cpp ***/
  31557. BEGIN_JUCE_NAMESPACE
  31558. class MultiTimer::MultiTimerCallback : public Timer
  31559. {
  31560. public:
  31561. MultiTimerCallback (const int timerId_, MultiTimer& owner_)
  31562. : timerId (timerId_),
  31563. owner (owner_)
  31564. {
  31565. }
  31566. ~MultiTimerCallback()
  31567. {
  31568. }
  31569. void timerCallback()
  31570. {
  31571. owner.timerCallback (timerId);
  31572. }
  31573. const int timerId;
  31574. private:
  31575. MultiTimer& owner;
  31576. };
  31577. MultiTimer::MultiTimer() throw()
  31578. {
  31579. }
  31580. MultiTimer::MultiTimer (const MultiTimer&) throw()
  31581. {
  31582. }
  31583. MultiTimer::~MultiTimer()
  31584. {
  31585. const ScopedLock sl (timerListLock);
  31586. timers.clear();
  31587. }
  31588. void MultiTimer::startTimer (const int timerId, const int intervalInMilliseconds) throw()
  31589. {
  31590. const ScopedLock sl (timerListLock);
  31591. for (int i = timers.size(); --i >= 0;)
  31592. {
  31593. MultiTimerCallback* const t = timers.getUnchecked(i);
  31594. if (t->timerId == timerId)
  31595. {
  31596. t->startTimer (intervalInMilliseconds);
  31597. return;
  31598. }
  31599. }
  31600. MultiTimerCallback* const newTimer = new MultiTimerCallback (timerId, *this);
  31601. timers.add (newTimer);
  31602. newTimer->startTimer (intervalInMilliseconds);
  31603. }
  31604. void MultiTimer::stopTimer (const int timerId) throw()
  31605. {
  31606. const ScopedLock sl (timerListLock);
  31607. for (int i = timers.size(); --i >= 0;)
  31608. {
  31609. MultiTimerCallback* const t = timers.getUnchecked(i);
  31610. if (t->timerId == timerId)
  31611. t->stopTimer();
  31612. }
  31613. }
  31614. bool MultiTimer::isTimerRunning (const int timerId) const throw()
  31615. {
  31616. const ScopedLock sl (timerListLock);
  31617. for (int i = timers.size(); --i >= 0;)
  31618. {
  31619. const MultiTimerCallback* const t = timers.getUnchecked(i);
  31620. if (t->timerId == timerId)
  31621. return t->isTimerRunning();
  31622. }
  31623. return false;
  31624. }
  31625. int MultiTimer::getTimerInterval (const int timerId) const throw()
  31626. {
  31627. const ScopedLock sl (timerListLock);
  31628. for (int i = timers.size(); --i >= 0;)
  31629. {
  31630. const MultiTimerCallback* const t = timers.getUnchecked(i);
  31631. if (t->timerId == timerId)
  31632. return t->getTimerInterval();
  31633. }
  31634. return 0;
  31635. }
  31636. END_JUCE_NAMESPACE
  31637. /*** End of inlined file: juce_MultiTimer.cpp ***/
  31638. /*** Start of inlined file: juce_Timer.cpp ***/
  31639. BEGIN_JUCE_NAMESPACE
  31640. class InternalTimerThread : private Thread,
  31641. private MessageListener,
  31642. private DeletedAtShutdown,
  31643. private AsyncUpdater
  31644. {
  31645. public:
  31646. InternalTimerThread()
  31647. : Thread ("Juce Timer"),
  31648. firstTimer (0),
  31649. callbackNeeded (0)
  31650. {
  31651. triggerAsyncUpdate();
  31652. }
  31653. ~InternalTimerThread() throw()
  31654. {
  31655. stopThread (4000);
  31656. jassert (instance == this || instance == 0);
  31657. if (instance == this)
  31658. instance = 0;
  31659. }
  31660. void run()
  31661. {
  31662. uint32 lastTime = Time::getMillisecondCounter();
  31663. while (! threadShouldExit())
  31664. {
  31665. const uint32 now = Time::getMillisecondCounter();
  31666. if (now <= lastTime)
  31667. {
  31668. wait (2);
  31669. continue;
  31670. }
  31671. const int elapsed = now - lastTime;
  31672. lastTime = now;
  31673. int timeUntilFirstTimer = 1000;
  31674. {
  31675. const ScopedLock sl (lock);
  31676. decrementAllCounters (elapsed);
  31677. if (firstTimer != 0)
  31678. timeUntilFirstTimer = firstTimer->countdownMs;
  31679. }
  31680. if (timeUntilFirstTimer <= 0)
  31681. {
  31682. /* If we managed to set the atomic boolean to true then send a message, this is needed
  31683. as a memory barrier so the message won't be sent before callbackNeeded is set to true,
  31684. but if it fails it means the message-thread changed the value from under us so at least
  31685. some processing is happenening and we can just loop around and try again
  31686. */
  31687. if (callbackNeeded.compareAndSetBool (1, 0))
  31688. {
  31689. postMessage (new Message());
  31690. /* Sometimes our message can get discarded by the OS (e.g. when running as an RTAS
  31691. when the app has a modal loop), so this is how long to wait before assuming the
  31692. message has been lost and trying again.
  31693. */
  31694. const uint32 messageDeliveryTimeout = now + 2000;
  31695. while (callbackNeeded.get() != 0)
  31696. {
  31697. wait (4);
  31698. if (threadShouldExit())
  31699. return;
  31700. if (Time::getMillisecondCounter() > messageDeliveryTimeout)
  31701. break;
  31702. }
  31703. }
  31704. }
  31705. else
  31706. {
  31707. // don't wait for too long because running this loop also helps keep the
  31708. // Time::getApproximateMillisecondTimer value stay up-to-date
  31709. wait (jlimit (1, 50, timeUntilFirstTimer));
  31710. }
  31711. }
  31712. }
  31713. void callTimers()
  31714. {
  31715. const ScopedLock sl (lock);
  31716. while (firstTimer != 0 && firstTimer->countdownMs <= 0)
  31717. {
  31718. Timer* const t = firstTimer;
  31719. t->countdownMs = t->periodMs;
  31720. removeTimer (t);
  31721. addTimer (t);
  31722. const ScopedUnlock ul (lock);
  31723. JUCE_TRY
  31724. {
  31725. t->timerCallback();
  31726. }
  31727. JUCE_CATCH_EXCEPTION
  31728. }
  31729. /* This is needed as a memory barrier to make sure all processing of current timers is done
  31730. before the boolean is set. This set should never fail since if it was false in the first place,
  31731. we wouldn't get a message (so it can't be changed from false to true from under us), and if we
  31732. get a message then the value is true and the other thread can only set it to true again and
  31733. we will get another callback to set it to false.
  31734. */
  31735. callbackNeeded.set (0);
  31736. }
  31737. void handleMessage (const Message&)
  31738. {
  31739. callTimers();
  31740. }
  31741. void callTimersSynchronously()
  31742. {
  31743. if (! isThreadRunning())
  31744. {
  31745. // (This is relied on by some plugins in cases where the MM has
  31746. // had to restart and the async callback never started)
  31747. cancelPendingUpdate();
  31748. triggerAsyncUpdate();
  31749. }
  31750. callTimers();
  31751. }
  31752. static void callAnyTimersSynchronously()
  31753. {
  31754. if (InternalTimerThread::instance != 0)
  31755. InternalTimerThread::instance->callTimersSynchronously();
  31756. }
  31757. static inline void add (Timer* const tim) throw()
  31758. {
  31759. if (instance == 0)
  31760. instance = new InternalTimerThread();
  31761. const ScopedLock sl (instance->lock);
  31762. instance->addTimer (tim);
  31763. }
  31764. static inline void remove (Timer* const tim) throw()
  31765. {
  31766. if (instance != 0)
  31767. {
  31768. const ScopedLock sl (instance->lock);
  31769. instance->removeTimer (tim);
  31770. }
  31771. }
  31772. static inline void resetCounter (Timer* const tim,
  31773. const int newCounter) throw()
  31774. {
  31775. if (instance != 0)
  31776. {
  31777. tim->countdownMs = newCounter;
  31778. tim->periodMs = newCounter;
  31779. if ((tim->next != 0 && tim->next->countdownMs < tim->countdownMs)
  31780. || (tim->previous != 0 && tim->previous->countdownMs > tim->countdownMs))
  31781. {
  31782. const ScopedLock sl (instance->lock);
  31783. instance->removeTimer (tim);
  31784. instance->addTimer (tim);
  31785. }
  31786. }
  31787. }
  31788. private:
  31789. friend class Timer;
  31790. static InternalTimerThread* instance;
  31791. static CriticalSection lock;
  31792. Timer* volatile firstTimer;
  31793. Atomic <int> callbackNeeded;
  31794. void addTimer (Timer* const t) throw()
  31795. {
  31796. #if JUCE_DEBUG
  31797. Timer* tt = firstTimer;
  31798. while (tt != 0)
  31799. {
  31800. // trying to add a timer that's already here - shouldn't get to this point,
  31801. // so if you get this assertion, let me know!
  31802. jassert (tt != t);
  31803. tt = tt->next;
  31804. }
  31805. jassert (t->previous == 0 && t->next == 0);
  31806. #endif
  31807. Timer* i = firstTimer;
  31808. if (i == 0 || i->countdownMs > t->countdownMs)
  31809. {
  31810. t->next = firstTimer;
  31811. firstTimer = t;
  31812. }
  31813. else
  31814. {
  31815. while (i->next != 0 && i->next->countdownMs <= t->countdownMs)
  31816. i = i->next;
  31817. jassert (i != 0);
  31818. t->next = i->next;
  31819. t->previous = i;
  31820. i->next = t;
  31821. }
  31822. if (t->next != 0)
  31823. t->next->previous = t;
  31824. jassert ((t->next == 0 || t->next->countdownMs >= t->countdownMs)
  31825. && (t->previous == 0 || t->previous->countdownMs <= t->countdownMs));
  31826. notify();
  31827. }
  31828. void removeTimer (Timer* const t) throw()
  31829. {
  31830. #if JUCE_DEBUG
  31831. Timer* tt = firstTimer;
  31832. bool found = false;
  31833. while (tt != 0)
  31834. {
  31835. if (tt == t)
  31836. {
  31837. found = true;
  31838. break;
  31839. }
  31840. tt = tt->next;
  31841. }
  31842. // trying to remove a timer that's not here - shouldn't get to this point,
  31843. // so if you get this assertion, let me know!
  31844. jassert (found);
  31845. #endif
  31846. if (t->previous != 0)
  31847. {
  31848. jassert (firstTimer != t);
  31849. t->previous->next = t->next;
  31850. }
  31851. else
  31852. {
  31853. jassert (firstTimer == t);
  31854. firstTimer = t->next;
  31855. }
  31856. if (t->next != 0)
  31857. t->next->previous = t->previous;
  31858. t->next = 0;
  31859. t->previous = 0;
  31860. }
  31861. void decrementAllCounters (const int numMillisecs) const
  31862. {
  31863. Timer* t = firstTimer;
  31864. while (t != 0)
  31865. {
  31866. t->countdownMs -= numMillisecs;
  31867. t = t->next;
  31868. }
  31869. }
  31870. void handleAsyncUpdate()
  31871. {
  31872. startThread (7);
  31873. }
  31874. InternalTimerThread (const InternalTimerThread&);
  31875. InternalTimerThread& operator= (const InternalTimerThread&);
  31876. };
  31877. InternalTimerThread* InternalTimerThread::instance = 0;
  31878. CriticalSection InternalTimerThread::lock;
  31879. void juce_callAnyTimersSynchronously()
  31880. {
  31881. InternalTimerThread::callAnyTimersSynchronously();
  31882. }
  31883. #if JUCE_DEBUG
  31884. static SortedSet <Timer*> activeTimers;
  31885. #endif
  31886. Timer::Timer() throw()
  31887. : countdownMs (0),
  31888. periodMs (0),
  31889. previous (0),
  31890. next (0)
  31891. {
  31892. #if JUCE_DEBUG
  31893. activeTimers.add (this);
  31894. #endif
  31895. }
  31896. Timer::Timer (const Timer&) throw()
  31897. : countdownMs (0),
  31898. periodMs (0),
  31899. previous (0),
  31900. next (0)
  31901. {
  31902. #if JUCE_DEBUG
  31903. activeTimers.add (this);
  31904. #endif
  31905. }
  31906. Timer::~Timer()
  31907. {
  31908. stopTimer();
  31909. #if JUCE_DEBUG
  31910. activeTimers.removeValue (this);
  31911. #endif
  31912. }
  31913. void Timer::startTimer (const int interval) throw()
  31914. {
  31915. const ScopedLock sl (InternalTimerThread::lock);
  31916. #if JUCE_DEBUG
  31917. // this isn't a valid object! Your timer might be a dangling pointer or something..
  31918. jassert (activeTimers.contains (this));
  31919. #endif
  31920. if (periodMs == 0)
  31921. {
  31922. countdownMs = interval;
  31923. periodMs = jmax (1, interval);
  31924. InternalTimerThread::add (this);
  31925. }
  31926. else
  31927. {
  31928. InternalTimerThread::resetCounter (this, interval);
  31929. }
  31930. }
  31931. void Timer::stopTimer() throw()
  31932. {
  31933. const ScopedLock sl (InternalTimerThread::lock);
  31934. #if JUCE_DEBUG
  31935. // this isn't a valid object! Your timer might be a dangling pointer or something..
  31936. jassert (activeTimers.contains (this));
  31937. #endif
  31938. if (periodMs > 0)
  31939. {
  31940. InternalTimerThread::remove (this);
  31941. periodMs = 0;
  31942. }
  31943. }
  31944. END_JUCE_NAMESPACE
  31945. /*** End of inlined file: juce_Timer.cpp ***/
  31946. #endif
  31947. #if JUCE_BUILD_GUI
  31948. /*** Start of inlined file: juce_Component.cpp ***/
  31949. BEGIN_JUCE_NAMESPACE
  31950. #define checkMessageManagerIsLocked jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  31951. enum ComponentMessageNumbers
  31952. {
  31953. customCommandMessage = 0x7fff0001,
  31954. exitModalStateMessage = 0x7fff0002
  31955. };
  31956. static uint32 nextComponentUID = 0;
  31957. Component* Component::currentlyFocusedComponent = 0;
  31958. Component::Component()
  31959. : parentComponent_ (0),
  31960. componentUID (++nextComponentUID),
  31961. numDeepMouseListeners (0),
  31962. lookAndFeel_ (0),
  31963. effect_ (0),
  31964. bufferedImage_ (0),
  31965. mouseListeners_ (0),
  31966. keyListeners_ (0),
  31967. componentFlags_ (0)
  31968. {
  31969. }
  31970. Component::Component (const String& name)
  31971. : componentName_ (name),
  31972. parentComponent_ (0),
  31973. componentUID (++nextComponentUID),
  31974. numDeepMouseListeners (0),
  31975. lookAndFeel_ (0),
  31976. effect_ (0),
  31977. bufferedImage_ (0),
  31978. mouseListeners_ (0),
  31979. keyListeners_ (0),
  31980. componentFlags_ (0)
  31981. {
  31982. }
  31983. Component::~Component()
  31984. {
  31985. componentListeners.call (&ComponentListener::componentBeingDeleted, *this);
  31986. if (parentComponent_ != 0)
  31987. {
  31988. parentComponent_->removeChildComponent (this);
  31989. }
  31990. else if ((currentlyFocusedComponent == this)
  31991. || isParentOf (currentlyFocusedComponent))
  31992. {
  31993. giveAwayFocus();
  31994. }
  31995. if (flags.hasHeavyweightPeerFlag)
  31996. removeFromDesktop();
  31997. for (int i = childComponentList_.size(); --i >= 0;)
  31998. childComponentList_.getUnchecked(i)->parentComponent_ = 0;
  31999. delete mouseListeners_;
  32000. delete keyListeners_;
  32001. }
  32002. void Component::setName (const String& name)
  32003. {
  32004. // if component methods are being called from threads other than the message
  32005. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32006. checkMessageManagerIsLocked
  32007. if (componentName_ != name)
  32008. {
  32009. componentName_ = name;
  32010. if (flags.hasHeavyweightPeerFlag)
  32011. {
  32012. ComponentPeer* const peer = getPeer();
  32013. jassert (peer != 0);
  32014. if (peer != 0)
  32015. peer->setTitle (name);
  32016. }
  32017. BailOutChecker checker (this);
  32018. componentListeners.callChecked (checker, &ComponentListener::componentNameChanged, *this);
  32019. }
  32020. }
  32021. void Component::setVisible (bool shouldBeVisible)
  32022. {
  32023. if (flags.visibleFlag != shouldBeVisible)
  32024. {
  32025. // if component methods are being called from threads other than the message
  32026. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32027. checkMessageManagerIsLocked
  32028. SafePointer<Component> safePointer (this);
  32029. flags.visibleFlag = shouldBeVisible;
  32030. internalRepaint (0, 0, getWidth(), getHeight());
  32031. sendFakeMouseMove();
  32032. if (! shouldBeVisible)
  32033. {
  32034. if (currentlyFocusedComponent == this
  32035. || isParentOf (currentlyFocusedComponent))
  32036. {
  32037. if (parentComponent_ != 0)
  32038. parentComponent_->grabKeyboardFocus();
  32039. else
  32040. giveAwayFocus();
  32041. }
  32042. }
  32043. if (safePointer != 0)
  32044. {
  32045. sendVisibilityChangeMessage();
  32046. if (safePointer != 0 && flags.hasHeavyweightPeerFlag)
  32047. {
  32048. ComponentPeer* const peer = getPeer();
  32049. jassert (peer != 0);
  32050. if (peer != 0)
  32051. {
  32052. peer->setVisible (shouldBeVisible);
  32053. internalHierarchyChanged();
  32054. }
  32055. }
  32056. }
  32057. }
  32058. }
  32059. void Component::visibilityChanged()
  32060. {
  32061. }
  32062. void Component::sendVisibilityChangeMessage()
  32063. {
  32064. BailOutChecker checker (this);
  32065. visibilityChanged();
  32066. if (! checker.shouldBailOut())
  32067. componentListeners.callChecked (checker, &ComponentListener::componentVisibilityChanged, *this);
  32068. }
  32069. bool Component::isShowing() const
  32070. {
  32071. if (flags.visibleFlag)
  32072. {
  32073. if (parentComponent_ != 0)
  32074. {
  32075. return parentComponent_->isShowing();
  32076. }
  32077. else
  32078. {
  32079. const ComponentPeer* const peer = getPeer();
  32080. return peer != 0 && ! peer->isMinimised();
  32081. }
  32082. }
  32083. return false;
  32084. }
  32085. class FadeOutProxyComponent : public Component,
  32086. public Timer
  32087. {
  32088. public:
  32089. FadeOutProxyComponent (Component* comp,
  32090. const int fadeLengthMs,
  32091. const int deltaXToMove,
  32092. const int deltaYToMove,
  32093. const float scaleFactorAtEnd)
  32094. : lastTime (0),
  32095. alpha (1.0f),
  32096. scale (1.0f)
  32097. {
  32098. image = comp->createComponentSnapshot (comp->getLocalBounds());
  32099. setBounds (comp->getBounds());
  32100. comp->getParentComponent()->addAndMakeVisible (this);
  32101. toBehind (comp);
  32102. alphaChangePerMs = -1.0f / (float)fadeLengthMs;
  32103. centreX = comp->getX() + comp->getWidth() * 0.5f;
  32104. xChangePerMs = deltaXToMove / (float)fadeLengthMs;
  32105. centreY = comp->getY() + comp->getHeight() * 0.5f;
  32106. yChangePerMs = deltaYToMove / (float)fadeLengthMs;
  32107. scaleChangePerMs = (scaleFactorAtEnd - 1.0f) / (float)fadeLengthMs;
  32108. setInterceptsMouseClicks (false, false);
  32109. // 30 fps is enough for a fade, but we need a higher rate if it's moving as well..
  32110. startTimer (1000 / ((deltaXToMove == 0 && deltaYToMove == 0) ? 30 : 50));
  32111. }
  32112. ~FadeOutProxyComponent()
  32113. {
  32114. }
  32115. void paint (Graphics& g)
  32116. {
  32117. g.setOpacity (alpha);
  32118. g.drawImage (image,
  32119. 0, 0, getWidth(), getHeight(),
  32120. 0, 0, image.getWidth(), image.getHeight());
  32121. }
  32122. void timerCallback()
  32123. {
  32124. const uint32 now = Time::getMillisecondCounter();
  32125. if (lastTime == 0)
  32126. lastTime = now;
  32127. const int msPassed = (now > lastTime) ? now - lastTime : 0;
  32128. lastTime = now;
  32129. alpha += alphaChangePerMs * msPassed;
  32130. if (alpha > 0)
  32131. {
  32132. if (xChangePerMs != 0.0f || yChangePerMs != 0.0f || scaleChangePerMs != 0.0f)
  32133. {
  32134. centreX += xChangePerMs * msPassed;
  32135. centreY += yChangePerMs * msPassed;
  32136. scale += scaleChangePerMs * msPassed;
  32137. const int w = roundToInt (image.getWidth() * scale);
  32138. const int h = roundToInt (image.getHeight() * scale);
  32139. setBounds (roundToInt (centreX) - w / 2,
  32140. roundToInt (centreY) - h / 2,
  32141. w, h);
  32142. }
  32143. repaint();
  32144. }
  32145. else
  32146. {
  32147. delete this;
  32148. }
  32149. }
  32150. juce_UseDebuggingNewOperator
  32151. private:
  32152. Image image;
  32153. uint32 lastTime;
  32154. float alpha, alphaChangePerMs;
  32155. float centreX, xChangePerMs;
  32156. float centreY, yChangePerMs;
  32157. float scale, scaleChangePerMs;
  32158. FadeOutProxyComponent (const FadeOutProxyComponent&);
  32159. FadeOutProxyComponent& operator= (const FadeOutProxyComponent&);
  32160. };
  32161. void Component::fadeOutComponent (const int millisecondsToFade,
  32162. const int deltaXToMove,
  32163. const int deltaYToMove,
  32164. const float scaleFactorAtEnd)
  32165. {
  32166. //xxx won't work for comps without parents
  32167. if (isShowing() && millisecondsToFade > 0)
  32168. new FadeOutProxyComponent (this, millisecondsToFade,
  32169. deltaXToMove, deltaYToMove, scaleFactorAtEnd);
  32170. setVisible (false);
  32171. }
  32172. bool Component::isValidComponent() const
  32173. {
  32174. return (this != 0) && isValidMessageListener();
  32175. }
  32176. void* Component::getWindowHandle() const
  32177. {
  32178. const ComponentPeer* const peer = getPeer();
  32179. if (peer != 0)
  32180. return peer->getNativeHandle();
  32181. return 0;
  32182. }
  32183. void Component::addToDesktop (int styleWanted, void* nativeWindowToAttachTo)
  32184. {
  32185. // if component methods are being called from threads other than the message
  32186. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32187. checkMessageManagerIsLocked
  32188. if (isOpaque())
  32189. styleWanted &= ~ComponentPeer::windowIsSemiTransparent;
  32190. else
  32191. styleWanted |= ComponentPeer::windowIsSemiTransparent;
  32192. int currentStyleFlags = 0;
  32193. // don't use getPeer(), so that we only get the peer that's specifically
  32194. // for this comp, and not for one of its parents.
  32195. ComponentPeer* peer = ComponentPeer::getPeerFor (this);
  32196. if (peer != 0)
  32197. currentStyleFlags = peer->getStyleFlags();
  32198. if (styleWanted != currentStyleFlags || ! flags.hasHeavyweightPeerFlag)
  32199. {
  32200. SafePointer<Component> safePointer (this);
  32201. #if JUCE_LINUX
  32202. // it's wise to give the component a non-zero size before
  32203. // putting it on the desktop, as X windows get confused by this, and
  32204. // a (1, 1) minimum size is enforced here.
  32205. setSize (jmax (1, getWidth()),
  32206. jmax (1, getHeight()));
  32207. #endif
  32208. const Point<int> topLeft (relativePositionToGlobal (Point<int> (0, 0)));
  32209. bool wasFullscreen = false;
  32210. bool wasMinimised = false;
  32211. ComponentBoundsConstrainer* currentConstainer = 0;
  32212. Rectangle<int> oldNonFullScreenBounds;
  32213. if (peer != 0)
  32214. {
  32215. wasFullscreen = peer->isFullScreen();
  32216. wasMinimised = peer->isMinimised();
  32217. currentConstainer = peer->getConstrainer();
  32218. oldNonFullScreenBounds = peer->getNonFullScreenBounds();
  32219. removeFromDesktop();
  32220. setTopLeftPosition (topLeft.getX(), topLeft.getY());
  32221. }
  32222. if (parentComponent_ != 0)
  32223. parentComponent_->removeChildComponent (this);
  32224. if (safePointer != 0)
  32225. {
  32226. flags.hasHeavyweightPeerFlag = true;
  32227. peer = createNewPeer (styleWanted, nativeWindowToAttachTo);
  32228. Desktop::getInstance().addDesktopComponent (this);
  32229. bounds_.setPosition (topLeft);
  32230. peer->setBounds (topLeft.getX(), topLeft.getY(), getWidth(), getHeight(), false);
  32231. peer->setVisible (isVisible());
  32232. if (wasFullscreen)
  32233. {
  32234. peer->setFullScreen (true);
  32235. peer->setNonFullScreenBounds (oldNonFullScreenBounds);
  32236. }
  32237. if (wasMinimised)
  32238. peer->setMinimised (true);
  32239. if (isAlwaysOnTop())
  32240. peer->setAlwaysOnTop (true);
  32241. peer->setConstrainer (currentConstainer);
  32242. repaint();
  32243. }
  32244. internalHierarchyChanged();
  32245. }
  32246. }
  32247. void Component::removeFromDesktop()
  32248. {
  32249. // if component methods are being called from threads other than the message
  32250. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32251. checkMessageManagerIsLocked
  32252. if (flags.hasHeavyweightPeerFlag)
  32253. {
  32254. ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  32255. flags.hasHeavyweightPeerFlag = false;
  32256. jassert (peer != 0);
  32257. delete peer;
  32258. Desktop::getInstance().removeDesktopComponent (this);
  32259. }
  32260. }
  32261. bool Component::isOnDesktop() const throw()
  32262. {
  32263. return flags.hasHeavyweightPeerFlag;
  32264. }
  32265. void Component::userTriedToCloseWindow()
  32266. {
  32267. /* This means that the user's trying to get rid of your window with the 'close window' system
  32268. menu option (on windows) or possibly the task manager - you should really handle this
  32269. and delete or hide your component in an appropriate way.
  32270. If you want to ignore the event and don't want to trigger this assertion, just override
  32271. this method and do nothing.
  32272. */
  32273. jassertfalse;
  32274. }
  32275. void Component::minimisationStateChanged (bool)
  32276. {
  32277. }
  32278. void Component::setOpaque (const bool shouldBeOpaque)
  32279. {
  32280. if (shouldBeOpaque != flags.opaqueFlag)
  32281. {
  32282. flags.opaqueFlag = shouldBeOpaque;
  32283. if (flags.hasHeavyweightPeerFlag)
  32284. {
  32285. const ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  32286. if (peer != 0)
  32287. {
  32288. // to make it recreate the heavyweight window
  32289. addToDesktop (peer->getStyleFlags());
  32290. }
  32291. }
  32292. repaint();
  32293. }
  32294. }
  32295. bool Component::isOpaque() const throw()
  32296. {
  32297. return flags.opaqueFlag;
  32298. }
  32299. void Component::setBufferedToImage (const bool shouldBeBuffered)
  32300. {
  32301. if (shouldBeBuffered != flags.bufferToImageFlag)
  32302. {
  32303. bufferedImage_ = Image::null;
  32304. flags.bufferToImageFlag = shouldBeBuffered;
  32305. }
  32306. }
  32307. void Component::toFront (const bool setAsForeground)
  32308. {
  32309. // if component methods are being called from threads other than the message
  32310. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32311. checkMessageManagerIsLocked
  32312. if (flags.hasHeavyweightPeerFlag)
  32313. {
  32314. ComponentPeer* const peer = getPeer();
  32315. if (peer != 0)
  32316. {
  32317. peer->toFront (setAsForeground);
  32318. if (setAsForeground && ! hasKeyboardFocus (true))
  32319. grabKeyboardFocus();
  32320. }
  32321. }
  32322. else if (parentComponent_ != 0)
  32323. {
  32324. Array<Component*>& childList = parentComponent_->childComponentList_;
  32325. if (childList.getLast() != this)
  32326. {
  32327. const int index = childList.indexOf (this);
  32328. if (index >= 0)
  32329. {
  32330. int insertIndex = -1;
  32331. if (! flags.alwaysOnTopFlag)
  32332. {
  32333. insertIndex = childList.size() - 1;
  32334. while (insertIndex > 0 && childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  32335. --insertIndex;
  32336. }
  32337. if (index != insertIndex)
  32338. {
  32339. childList.move (index, insertIndex);
  32340. sendFakeMouseMove();
  32341. repaintParent();
  32342. }
  32343. }
  32344. }
  32345. if (setAsForeground)
  32346. {
  32347. internalBroughtToFront();
  32348. grabKeyboardFocus();
  32349. }
  32350. }
  32351. }
  32352. void Component::toBehind (Component* const other)
  32353. {
  32354. if (other != 0 && other != this)
  32355. {
  32356. // the two components must belong to the same parent..
  32357. jassert (parentComponent_ == other->parentComponent_);
  32358. if (parentComponent_ != 0)
  32359. {
  32360. Array<Component*>& childList = parentComponent_->childComponentList_;
  32361. const int index = childList.indexOf (this);
  32362. if (index >= 0 && childList [index + 1] != other)
  32363. {
  32364. int otherIndex = childList.indexOf (other);
  32365. if (otherIndex >= 0)
  32366. {
  32367. if (index < otherIndex)
  32368. --otherIndex;
  32369. childList.move (index, otherIndex);
  32370. sendFakeMouseMove();
  32371. repaintParent();
  32372. }
  32373. }
  32374. }
  32375. else if (isOnDesktop())
  32376. {
  32377. jassert (other->isOnDesktop());
  32378. if (other->isOnDesktop())
  32379. {
  32380. ComponentPeer* const us = getPeer();
  32381. ComponentPeer* const them = other->getPeer();
  32382. jassert (us != 0 && them != 0);
  32383. if (us != 0 && them != 0)
  32384. us->toBehind (them);
  32385. }
  32386. }
  32387. }
  32388. }
  32389. void Component::toBack()
  32390. {
  32391. Array<Component*>& childList = parentComponent_->childComponentList_;
  32392. if (isOnDesktop())
  32393. {
  32394. jassertfalse; //xxx need to add this to native window
  32395. }
  32396. else if (parentComponent_ != 0 && childList.getFirst() != this)
  32397. {
  32398. const int index = childList.indexOf (this);
  32399. if (index > 0)
  32400. {
  32401. int insertIndex = 0;
  32402. if (flags.alwaysOnTopFlag)
  32403. {
  32404. while (insertIndex < childList.size()
  32405. && ! childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  32406. {
  32407. ++insertIndex;
  32408. }
  32409. }
  32410. if (index != insertIndex)
  32411. {
  32412. childList.move (index, insertIndex);
  32413. sendFakeMouseMove();
  32414. repaintParent();
  32415. }
  32416. }
  32417. }
  32418. }
  32419. void Component::setAlwaysOnTop (const bool shouldStayOnTop)
  32420. {
  32421. if (shouldStayOnTop != flags.alwaysOnTopFlag)
  32422. {
  32423. flags.alwaysOnTopFlag = shouldStayOnTop;
  32424. if (isOnDesktop())
  32425. {
  32426. ComponentPeer* const peer = getPeer();
  32427. jassert (peer != 0);
  32428. if (peer != 0)
  32429. {
  32430. if (! peer->setAlwaysOnTop (shouldStayOnTop))
  32431. {
  32432. // some kinds of peer can't change their always-on-top status, so
  32433. // for these, we'll need to create a new window
  32434. const int oldFlags = peer->getStyleFlags();
  32435. removeFromDesktop();
  32436. addToDesktop (oldFlags);
  32437. }
  32438. }
  32439. }
  32440. if (shouldStayOnTop)
  32441. toFront (false);
  32442. internalHierarchyChanged();
  32443. }
  32444. }
  32445. bool Component::isAlwaysOnTop() const throw()
  32446. {
  32447. return flags.alwaysOnTopFlag;
  32448. }
  32449. int Component::proportionOfWidth (const float proportion) const throw()
  32450. {
  32451. return roundToInt (proportion * bounds_.getWidth());
  32452. }
  32453. int Component::proportionOfHeight (const float proportion) const throw()
  32454. {
  32455. return roundToInt (proportion * bounds_.getHeight());
  32456. }
  32457. int Component::getParentWidth() const throw()
  32458. {
  32459. return (parentComponent_ != 0) ? parentComponent_->getWidth()
  32460. : getParentMonitorArea().getWidth();
  32461. }
  32462. int Component::getParentHeight() const throw()
  32463. {
  32464. return (parentComponent_ != 0) ? parentComponent_->getHeight()
  32465. : getParentMonitorArea().getHeight();
  32466. }
  32467. int Component::getScreenX() const
  32468. {
  32469. return getScreenPosition().getX();
  32470. }
  32471. int Component::getScreenY() const
  32472. {
  32473. return getScreenPosition().getY();
  32474. }
  32475. const Point<int> Component::getScreenPosition() const
  32476. {
  32477. return (parentComponent_ != 0) ? parentComponent_->getScreenPosition() + getPosition()
  32478. : (flags.hasHeavyweightPeerFlag ? getPeer()->getScreenPosition()
  32479. : getPosition());
  32480. }
  32481. const Rectangle<int> Component::getScreenBounds() const
  32482. {
  32483. return bounds_.withPosition (getScreenPosition());
  32484. }
  32485. const Point<int> Component::relativePositionToGlobal (const Point<int>& relativePosition) const
  32486. {
  32487. const Component* c = this;
  32488. Point<int> p (relativePosition);
  32489. do
  32490. {
  32491. if (c->flags.hasHeavyweightPeerFlag)
  32492. return c->getPeer()->relativePositionToGlobal (p);
  32493. p += c->getPosition();
  32494. c = c->parentComponent_;
  32495. }
  32496. while (c != 0);
  32497. return p;
  32498. }
  32499. const Point<int> Component::globalPositionToRelative (const Point<int>& screenPosition) const
  32500. {
  32501. if (flags.hasHeavyweightPeerFlag)
  32502. {
  32503. return getPeer()->globalPositionToRelative (screenPosition);
  32504. }
  32505. else
  32506. {
  32507. if (parentComponent_ != 0)
  32508. return parentComponent_->globalPositionToRelative (screenPosition) - getPosition();
  32509. return screenPosition - getPosition();
  32510. }
  32511. }
  32512. const Point<int> Component::relativePositionToOtherComponent (const Component* const targetComponent, const Point<int>& positionRelativeToThis) const
  32513. {
  32514. Point<int> p (positionRelativeToThis);
  32515. if (targetComponent != 0)
  32516. {
  32517. const Component* c = this;
  32518. do
  32519. {
  32520. if (c == targetComponent)
  32521. return p;
  32522. if (c->flags.hasHeavyweightPeerFlag)
  32523. {
  32524. p = c->getPeer()->relativePositionToGlobal (p);
  32525. break;
  32526. }
  32527. p += c->getPosition();
  32528. c = c->parentComponent_;
  32529. }
  32530. while (c != 0);
  32531. p = targetComponent->globalPositionToRelative (p);
  32532. }
  32533. return p;
  32534. }
  32535. void Component::setBounds (const int x, const int y, int w, int h)
  32536. {
  32537. // if component methods are being called from threads other than the message
  32538. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32539. checkMessageManagerIsLocked
  32540. if (w < 0) w = 0;
  32541. if (h < 0) h = 0;
  32542. const bool wasResized = (getWidth() != w || getHeight() != h);
  32543. const bool wasMoved = (getX() != x || getY() != y);
  32544. #if JUCE_DEBUG
  32545. // It's a very bad idea to try to resize a window during its paint() method!
  32546. jassert (! (flags.isInsidePaintCall && wasResized && isOnDesktop()));
  32547. #endif
  32548. if (wasMoved || wasResized)
  32549. {
  32550. if (flags.visibleFlag)
  32551. {
  32552. // send a fake mouse move to trigger enter/exit messages if needed..
  32553. sendFakeMouseMove();
  32554. if (! flags.hasHeavyweightPeerFlag)
  32555. repaintParent();
  32556. }
  32557. bounds_.setBounds (x, y, w, h);
  32558. if (wasResized)
  32559. repaint();
  32560. else if (! flags.hasHeavyweightPeerFlag)
  32561. repaintParent();
  32562. if (flags.hasHeavyweightPeerFlag)
  32563. {
  32564. ComponentPeer* const peer = getPeer();
  32565. if (peer != 0)
  32566. {
  32567. if (wasMoved && wasResized)
  32568. peer->setBounds (getX(), getY(), getWidth(), getHeight(), false);
  32569. else if (wasMoved)
  32570. peer->setPosition (getX(), getY());
  32571. else if (wasResized)
  32572. peer->setSize (getWidth(), getHeight());
  32573. }
  32574. }
  32575. sendMovedResizedMessages (wasMoved, wasResized);
  32576. }
  32577. }
  32578. void Component::sendMovedResizedMessages (const bool wasMoved, const bool wasResized)
  32579. {
  32580. JUCE_TRY
  32581. {
  32582. if (wasMoved)
  32583. moved();
  32584. if (wasResized)
  32585. {
  32586. resized();
  32587. for (int i = childComponentList_.size(); --i >= 0;)
  32588. {
  32589. childComponentList_.getUnchecked(i)->parentSizeChanged();
  32590. i = jmin (i, childComponentList_.size());
  32591. }
  32592. }
  32593. BailOutChecker checker (this);
  32594. if (parentComponent_ != 0)
  32595. parentComponent_->childBoundsChanged (this);
  32596. if (! checker.shouldBailOut())
  32597. componentListeners.callChecked (checker, &ComponentListener::componentMovedOrResized,
  32598. *this, wasMoved, wasResized);
  32599. }
  32600. JUCE_CATCH_EXCEPTION
  32601. }
  32602. void Component::setSize (const int w, const int h)
  32603. {
  32604. setBounds (getX(), getY(), w, h);
  32605. }
  32606. void Component::setTopLeftPosition (const int x, const int y)
  32607. {
  32608. setBounds (x, y, getWidth(), getHeight());
  32609. }
  32610. void Component::setTopRightPosition (const int x, const int y)
  32611. {
  32612. setTopLeftPosition (x - getWidth(), y);
  32613. }
  32614. void Component::setBounds (const Rectangle<int>& r)
  32615. {
  32616. setBounds (r.getX(),
  32617. r.getY(),
  32618. r.getWidth(),
  32619. r.getHeight());
  32620. }
  32621. void Component::setBoundsRelative (const float x, const float y,
  32622. const float w, const float h)
  32623. {
  32624. const int pw = getParentWidth();
  32625. const int ph = getParentHeight();
  32626. setBounds (roundToInt (x * pw),
  32627. roundToInt (y * ph),
  32628. roundToInt (w * pw),
  32629. roundToInt (h * ph));
  32630. }
  32631. void Component::setCentrePosition (const int x, const int y)
  32632. {
  32633. setTopLeftPosition (x - getWidth() / 2,
  32634. y - getHeight() / 2);
  32635. }
  32636. void Component::setCentreRelative (const float x, const float y)
  32637. {
  32638. setCentrePosition (roundToInt (getParentWidth() * x),
  32639. roundToInt (getParentHeight() * y));
  32640. }
  32641. void Component::centreWithSize (const int width, const int height)
  32642. {
  32643. const Rectangle<int> parentArea (getParentOrMainMonitorBounds());
  32644. setBounds (parentArea.getCentreX() - width / 2,
  32645. parentArea.getCentreY() - height / 2,
  32646. width, height);
  32647. }
  32648. void Component::setBoundsInset (const BorderSize& borders)
  32649. {
  32650. setBounds (borders.subtractedFrom (getParentOrMainMonitorBounds()));
  32651. }
  32652. void Component::setBoundsToFit (int x, int y, int width, int height,
  32653. const Justification& justification,
  32654. const bool onlyReduceInSize)
  32655. {
  32656. // it's no good calling this method unless both the component and
  32657. // target rectangle have a finite size.
  32658. jassert (getWidth() > 0 && getHeight() > 0 && width > 0 && height > 0);
  32659. if (getWidth() > 0 && getHeight() > 0
  32660. && width > 0 && height > 0)
  32661. {
  32662. int newW, newH;
  32663. if (onlyReduceInSize && getWidth() <= width && getHeight() <= height)
  32664. {
  32665. newW = getWidth();
  32666. newH = getHeight();
  32667. }
  32668. else
  32669. {
  32670. const double imageRatio = getHeight() / (double) getWidth();
  32671. const double targetRatio = height / (double) width;
  32672. if (imageRatio <= targetRatio)
  32673. {
  32674. newW = width;
  32675. newH = jmin (height, roundToInt (newW * imageRatio));
  32676. }
  32677. else
  32678. {
  32679. newH = height;
  32680. newW = jmin (width, roundToInt (newH / imageRatio));
  32681. }
  32682. }
  32683. if (newW > 0 && newH > 0)
  32684. {
  32685. int newX, newY;
  32686. justification.applyToRectangle (newX, newY, newW, newH,
  32687. x, y, width, height);
  32688. setBounds (newX, newY, newW, newH);
  32689. }
  32690. }
  32691. }
  32692. bool Component::hitTest (int x, int y)
  32693. {
  32694. if (! flags.ignoresMouseClicksFlag)
  32695. return true;
  32696. if (flags.allowChildMouseClicksFlag)
  32697. {
  32698. for (int i = getNumChildComponents(); --i >= 0;)
  32699. {
  32700. Component* const c = getChildComponent (i);
  32701. if (c->isVisible()
  32702. && c->bounds_.contains (x, y)
  32703. && c->hitTest (x - c->getX(),
  32704. y - c->getY()))
  32705. {
  32706. return true;
  32707. }
  32708. }
  32709. }
  32710. return false;
  32711. }
  32712. void Component::setInterceptsMouseClicks (const bool allowClicks,
  32713. const bool allowClicksOnChildComponents) throw()
  32714. {
  32715. flags.ignoresMouseClicksFlag = ! allowClicks;
  32716. flags.allowChildMouseClicksFlag = allowClicksOnChildComponents;
  32717. }
  32718. void Component::getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  32719. bool& allowsClicksOnChildComponents) const throw()
  32720. {
  32721. allowsClicksOnThisComponent = ! flags.ignoresMouseClicksFlag;
  32722. allowsClicksOnChildComponents = flags.allowChildMouseClicksFlag;
  32723. }
  32724. bool Component::contains (const int x, const int y)
  32725. {
  32726. if (((unsigned int) x) < (unsigned int) getWidth()
  32727. && ((unsigned int) y) < (unsigned int) getHeight()
  32728. && hitTest (x, y))
  32729. {
  32730. if (parentComponent_ != 0)
  32731. {
  32732. return parentComponent_->contains (x + getX(),
  32733. y + getY());
  32734. }
  32735. else if (flags.hasHeavyweightPeerFlag)
  32736. {
  32737. const ComponentPeer* const peer = getPeer();
  32738. if (peer != 0)
  32739. return peer->contains (Point<int> (x, y), true);
  32740. }
  32741. }
  32742. return false;
  32743. }
  32744. bool Component::reallyContains (int x, int y, const bool returnTrueIfWithinAChild)
  32745. {
  32746. if (! contains (x, y))
  32747. return false;
  32748. Component* p = this;
  32749. while (p->parentComponent_ != 0)
  32750. {
  32751. x += p->getX();
  32752. y += p->getY();
  32753. p = p->parentComponent_;
  32754. }
  32755. const Component* const c = p->getComponentAt (x, y);
  32756. return (c == this) || (returnTrueIfWithinAChild && isParentOf (c));
  32757. }
  32758. Component* Component::getComponentAt (const Point<int>& position)
  32759. {
  32760. return getComponentAt (position.getX(), position.getY());
  32761. }
  32762. Component* Component::getComponentAt (const int x, const int y)
  32763. {
  32764. if (flags.visibleFlag
  32765. && ((unsigned int) x) < (unsigned int) getWidth()
  32766. && ((unsigned int) y) < (unsigned int) getHeight()
  32767. && hitTest (x, y))
  32768. {
  32769. for (int i = childComponentList_.size(); --i >= 0;)
  32770. {
  32771. Component* const child = childComponentList_.getUnchecked(i);
  32772. Component* const c = child->getComponentAt (x - child->getX(),
  32773. y - child->getY());
  32774. if (c != 0)
  32775. return c;
  32776. }
  32777. return this;
  32778. }
  32779. return 0;
  32780. }
  32781. void Component::addChildComponent (Component* const child, int zOrder)
  32782. {
  32783. // if component methods are being called from threads other than the message
  32784. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32785. checkMessageManagerIsLocked
  32786. if (child != 0 && child->parentComponent_ != this)
  32787. {
  32788. if (child->parentComponent_ != 0)
  32789. child->parentComponent_->removeChildComponent (child);
  32790. else
  32791. child->removeFromDesktop();
  32792. child->parentComponent_ = this;
  32793. if (child->isVisible())
  32794. child->repaintParent();
  32795. if (! child->isAlwaysOnTop())
  32796. {
  32797. if (zOrder < 0 || zOrder > childComponentList_.size())
  32798. zOrder = childComponentList_.size();
  32799. while (zOrder > 0)
  32800. {
  32801. if (! childComponentList_.getUnchecked (zOrder - 1)->isAlwaysOnTop())
  32802. break;
  32803. --zOrder;
  32804. }
  32805. }
  32806. childComponentList_.insert (zOrder, child);
  32807. child->internalHierarchyChanged();
  32808. internalChildrenChanged();
  32809. }
  32810. }
  32811. void Component::addAndMakeVisible (Component* const child, int zOrder)
  32812. {
  32813. if (child != 0)
  32814. {
  32815. child->setVisible (true);
  32816. addChildComponent (child, zOrder);
  32817. }
  32818. }
  32819. void Component::removeChildComponent (Component* const child)
  32820. {
  32821. removeChildComponent (childComponentList_.indexOf (child));
  32822. }
  32823. Component* Component::removeChildComponent (const int index)
  32824. {
  32825. // if component methods are being called from threads other than the message
  32826. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32827. checkMessageManagerIsLocked
  32828. Component* const child = childComponentList_ [index];
  32829. if (child != 0)
  32830. {
  32831. sendFakeMouseMove();
  32832. child->repaintParent();
  32833. childComponentList_.remove (index);
  32834. child->parentComponent_ = 0;
  32835. JUCE_TRY
  32836. {
  32837. if ((currentlyFocusedComponent == child)
  32838. || child->isParentOf (currentlyFocusedComponent))
  32839. {
  32840. // get rid first to force the grabKeyboardFocus to change to us.
  32841. giveAwayFocus();
  32842. grabKeyboardFocus();
  32843. }
  32844. }
  32845. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  32846. catch (const std::exception& e)
  32847. {
  32848. currentlyFocusedComponent = 0;
  32849. Desktop::getInstance().triggerFocusCallback();
  32850. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  32851. }
  32852. catch (...)
  32853. {
  32854. currentlyFocusedComponent = 0;
  32855. Desktop::getInstance().triggerFocusCallback();
  32856. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  32857. }
  32858. #endif
  32859. child->internalHierarchyChanged();
  32860. internalChildrenChanged();
  32861. }
  32862. return child;
  32863. }
  32864. void Component::removeAllChildren()
  32865. {
  32866. while (childComponentList_.size() > 0)
  32867. removeChildComponent (childComponentList_.size() - 1);
  32868. }
  32869. void Component::deleteAllChildren()
  32870. {
  32871. while (childComponentList_.size() > 0)
  32872. delete (removeChildComponent (childComponentList_.size() - 1));
  32873. }
  32874. int Component::getNumChildComponents() const throw()
  32875. {
  32876. return childComponentList_.size();
  32877. }
  32878. Component* Component::getChildComponent (const int index) const throw()
  32879. {
  32880. return childComponentList_ [index];
  32881. }
  32882. int Component::getIndexOfChildComponent (const Component* const child) const throw()
  32883. {
  32884. return childComponentList_.indexOf (const_cast <Component*> (child));
  32885. }
  32886. Component* Component::getTopLevelComponent() const throw()
  32887. {
  32888. const Component* comp = this;
  32889. while (comp->parentComponent_ != 0)
  32890. comp = comp->parentComponent_;
  32891. return const_cast <Component*> (comp);
  32892. }
  32893. bool Component::isParentOf (const Component* possibleChild) const throw()
  32894. {
  32895. if (! possibleChild->isValidComponent())
  32896. {
  32897. jassert (possibleChild == 0);
  32898. return false;
  32899. }
  32900. while (possibleChild != 0)
  32901. {
  32902. possibleChild = possibleChild->parentComponent_;
  32903. if (possibleChild == this)
  32904. return true;
  32905. }
  32906. return false;
  32907. }
  32908. void Component::parentHierarchyChanged()
  32909. {
  32910. }
  32911. void Component::childrenChanged()
  32912. {
  32913. }
  32914. void Component::internalChildrenChanged()
  32915. {
  32916. if (componentListeners.isEmpty())
  32917. {
  32918. childrenChanged();
  32919. }
  32920. else
  32921. {
  32922. BailOutChecker checker (this);
  32923. childrenChanged();
  32924. if (! checker.shouldBailOut())
  32925. componentListeners.callChecked (checker, &ComponentListener::componentChildrenChanged, *this);
  32926. }
  32927. }
  32928. void Component::internalHierarchyChanged()
  32929. {
  32930. BailOutChecker checker (this);
  32931. parentHierarchyChanged();
  32932. if (checker.shouldBailOut())
  32933. return;
  32934. componentListeners.callChecked (checker, &ComponentListener::componentParentHierarchyChanged, *this);
  32935. if (checker.shouldBailOut())
  32936. return;
  32937. for (int i = childComponentList_.size(); --i >= 0;)
  32938. {
  32939. childComponentList_.getUnchecked (i)->internalHierarchyChanged();
  32940. if (checker.shouldBailOut())
  32941. {
  32942. // you really shouldn't delete the parent component during a callback telling you
  32943. // that it's changed..
  32944. jassertfalse;
  32945. return;
  32946. }
  32947. i = jmin (i, childComponentList_.size());
  32948. }
  32949. }
  32950. void* Component::runModalLoopCallback (void* userData)
  32951. {
  32952. return (void*) (pointer_sized_int) static_cast <Component*> (userData)->runModalLoop();
  32953. }
  32954. int Component::runModalLoop()
  32955. {
  32956. if (! MessageManager::getInstance()->isThisTheMessageThread())
  32957. {
  32958. // use a callback so this can be called from non-gui threads
  32959. return (int) (pointer_sized_int) MessageManager::getInstance()
  32960. ->callFunctionOnMessageThread (&runModalLoopCallback, this);
  32961. }
  32962. if (! isCurrentlyModal())
  32963. enterModalState (true);
  32964. return ModalComponentManager::getInstance()->runEventLoopForCurrentComponent();
  32965. }
  32966. void Component::enterModalState (const bool takeKeyboardFocus_, ModalComponentManager::Callback* const callback)
  32967. {
  32968. // if component methods are being called from threads other than the message
  32969. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32970. checkMessageManagerIsLocked
  32971. // Check for an attempt to make a component modal when it already is!
  32972. // This can cause nasty problems..
  32973. jassert (! flags.currentlyModalFlag);
  32974. if (! isCurrentlyModal())
  32975. {
  32976. ModalComponentManager::getInstance()->startModal (this, callback);
  32977. flags.currentlyModalFlag = true;
  32978. setVisible (true);
  32979. if (takeKeyboardFocus_)
  32980. grabKeyboardFocus();
  32981. }
  32982. }
  32983. void Component::exitModalState (const int returnValue)
  32984. {
  32985. if (isCurrentlyModal())
  32986. {
  32987. if (MessageManager::getInstance()->isThisTheMessageThread())
  32988. {
  32989. ModalComponentManager::getInstance()->endModal (this, returnValue);
  32990. flags.currentlyModalFlag = false;
  32991. bringModalComponentToFront();
  32992. }
  32993. else
  32994. {
  32995. postMessage (new Message (exitModalStateMessage, returnValue, 0, 0));
  32996. }
  32997. }
  32998. }
  32999. bool Component::isCurrentlyModal() const throw()
  33000. {
  33001. return flags.currentlyModalFlag
  33002. && getCurrentlyModalComponent() == this;
  33003. }
  33004. bool Component::isCurrentlyBlockedByAnotherModalComponent() const
  33005. {
  33006. Component* const mc = getCurrentlyModalComponent();
  33007. return mc != 0
  33008. && mc != this
  33009. && (! mc->isParentOf (this))
  33010. && ! mc->canModalEventBeSentToComponent (this);
  33011. }
  33012. int JUCE_CALLTYPE Component::getNumCurrentlyModalComponents() throw()
  33013. {
  33014. return ModalComponentManager::getInstance()->getNumModalComponents();
  33015. }
  33016. Component* JUCE_CALLTYPE Component::getCurrentlyModalComponent (int index) throw()
  33017. {
  33018. return ModalComponentManager::getInstance()->getModalComponent (index);
  33019. }
  33020. void Component::bringModalComponentToFront()
  33021. {
  33022. ComponentPeer* lastOne = 0;
  33023. for (int i = 0; i < getNumCurrentlyModalComponents(); ++i)
  33024. {
  33025. Component* const c = getCurrentlyModalComponent (i);
  33026. if (c == 0)
  33027. break;
  33028. ComponentPeer* peer = c->getPeer();
  33029. if (peer != 0 && peer != lastOne)
  33030. {
  33031. if (lastOne == 0)
  33032. {
  33033. peer->toFront (true);
  33034. peer->grabFocus();
  33035. }
  33036. else
  33037. peer->toBehind (lastOne);
  33038. lastOne = peer;
  33039. }
  33040. }
  33041. }
  33042. void Component::setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) throw()
  33043. {
  33044. flags.bringToFrontOnClickFlag = shouldBeBroughtToFront;
  33045. }
  33046. bool Component::isBroughtToFrontOnMouseClick() const throw()
  33047. {
  33048. return flags.bringToFrontOnClickFlag;
  33049. }
  33050. void Component::setMouseCursor (const MouseCursor& cursor)
  33051. {
  33052. if (cursor_ != cursor)
  33053. {
  33054. cursor_ = cursor;
  33055. if (flags.visibleFlag)
  33056. updateMouseCursor();
  33057. }
  33058. }
  33059. const MouseCursor Component::getMouseCursor()
  33060. {
  33061. return cursor_;
  33062. }
  33063. void Component::updateMouseCursor() const
  33064. {
  33065. sendFakeMouseMove();
  33066. }
  33067. void Component::setRepaintsOnMouseActivity (const bool shouldRepaint) throw()
  33068. {
  33069. flags.repaintOnMouseActivityFlag = shouldRepaint;
  33070. }
  33071. void Component::repaintParent()
  33072. {
  33073. if (flags.visibleFlag)
  33074. internalRepaint (0, 0, getWidth(), getHeight());
  33075. }
  33076. void Component::repaint()
  33077. {
  33078. repaint (0, 0, getWidth(), getHeight());
  33079. }
  33080. void Component::repaint (const int x, const int y,
  33081. const int w, const int h)
  33082. {
  33083. bufferedImage_ = Image::null;
  33084. if (flags.visibleFlag)
  33085. internalRepaint (x, y, w, h);
  33086. }
  33087. void Component::repaint (const Rectangle<int>& area)
  33088. {
  33089. repaint (area.getX(), area.getY(), area.getWidth(), area.getHeight());
  33090. }
  33091. void Component::internalRepaint (int x, int y, int w, int h)
  33092. {
  33093. // if component methods are being called from threads other than the message
  33094. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33095. checkMessageManagerIsLocked
  33096. if (x < 0)
  33097. {
  33098. w += x;
  33099. x = 0;
  33100. }
  33101. if (x + w > getWidth())
  33102. w = getWidth() - x;
  33103. if (w > 0)
  33104. {
  33105. if (y < 0)
  33106. {
  33107. h += y;
  33108. y = 0;
  33109. }
  33110. if (y + h > getHeight())
  33111. h = getHeight() - y;
  33112. if (h > 0)
  33113. {
  33114. if (parentComponent_ != 0)
  33115. {
  33116. x += getX();
  33117. y += getY();
  33118. if (parentComponent_->flags.visibleFlag)
  33119. parentComponent_->internalRepaint (x, y, w, h);
  33120. }
  33121. else if (flags.hasHeavyweightPeerFlag)
  33122. {
  33123. ComponentPeer* const peer = getPeer();
  33124. if (peer != 0)
  33125. peer->repaint (Rectangle<int> (x, y, w, h));
  33126. }
  33127. }
  33128. }
  33129. }
  33130. void Component::renderComponent (Graphics& g)
  33131. {
  33132. const Rectangle<int> clipBounds (g.getClipBounds());
  33133. g.saveState();
  33134. clipObscuredRegions (g, clipBounds, 0, 0);
  33135. if (! g.isClipEmpty())
  33136. {
  33137. if (flags.bufferToImageFlag)
  33138. {
  33139. if (bufferedImage_.isNull())
  33140. {
  33141. bufferedImage_ = Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33142. getWidth(), getHeight(), ! flags.opaqueFlag, Image::NativeImage);
  33143. Graphics imG (bufferedImage_);
  33144. paint (imG);
  33145. }
  33146. g.setColour (Colours::black);
  33147. g.drawImageAt (bufferedImage_, 0, 0);
  33148. }
  33149. else
  33150. {
  33151. paint (g);
  33152. }
  33153. }
  33154. g.restoreState();
  33155. for (int i = 0; i < childComponentList_.size(); ++i)
  33156. {
  33157. Component* const child = childComponentList_.getUnchecked (i);
  33158. if (child->isVisible() && clipBounds.intersects (child->getBounds()))
  33159. {
  33160. g.saveState();
  33161. if (g.reduceClipRegion (child->getX(), child->getY(),
  33162. child->getWidth(), child->getHeight()))
  33163. {
  33164. for (int j = i + 1; j < childComponentList_.size(); ++j)
  33165. {
  33166. const Component* const sibling = childComponentList_.getUnchecked (j);
  33167. if (sibling->flags.opaqueFlag && sibling->isVisible())
  33168. g.excludeClipRegion (sibling->getBounds());
  33169. }
  33170. if (! g.isClipEmpty())
  33171. {
  33172. g.setOrigin (child->getX(), child->getY());
  33173. child->paintEntireComponent (g);
  33174. }
  33175. }
  33176. g.restoreState();
  33177. }
  33178. }
  33179. g.saveState();
  33180. paintOverChildren (g);
  33181. g.restoreState();
  33182. }
  33183. void Component::paintEntireComponent (Graphics& g)
  33184. {
  33185. jassert (! g.isClipEmpty());
  33186. #if JUCE_DEBUG
  33187. flags.isInsidePaintCall = true;
  33188. #endif
  33189. if (effect_ != 0)
  33190. {
  33191. Image effectImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33192. getWidth(), getHeight(),
  33193. ! flags.opaqueFlag, Image::NativeImage);
  33194. {
  33195. Graphics g2 (effectImage);
  33196. renderComponent (g2);
  33197. }
  33198. effect_->applyEffect (effectImage, g);
  33199. }
  33200. else
  33201. {
  33202. renderComponent (g);
  33203. }
  33204. #if JUCE_DEBUG
  33205. flags.isInsidePaintCall = false;
  33206. #endif
  33207. }
  33208. const Image Component::createComponentSnapshot (const Rectangle<int>& areaToGrab,
  33209. const bool clipImageToComponentBounds)
  33210. {
  33211. Rectangle<int> r (areaToGrab);
  33212. if (clipImageToComponentBounds)
  33213. r = r.getIntersection (getLocalBounds());
  33214. Image componentImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33215. jmax (1, r.getWidth()),
  33216. jmax (1, r.getHeight()),
  33217. true);
  33218. Graphics imageContext (componentImage);
  33219. imageContext.setOrigin (-r.getX(), -r.getY());
  33220. paintEntireComponent (imageContext);
  33221. return componentImage;
  33222. }
  33223. void Component::setComponentEffect (ImageEffectFilter* const effect)
  33224. {
  33225. if (effect_ != effect)
  33226. {
  33227. effect_ = effect;
  33228. repaint();
  33229. }
  33230. }
  33231. LookAndFeel& Component::getLookAndFeel() const throw()
  33232. {
  33233. const Component* c = this;
  33234. do
  33235. {
  33236. if (c->lookAndFeel_ != 0)
  33237. return *(c->lookAndFeel_);
  33238. c = c->parentComponent_;
  33239. }
  33240. while (c != 0);
  33241. return LookAndFeel::getDefaultLookAndFeel();
  33242. }
  33243. void Component::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  33244. {
  33245. if (lookAndFeel_ != newLookAndFeel)
  33246. {
  33247. lookAndFeel_ = newLookAndFeel;
  33248. sendLookAndFeelChange();
  33249. }
  33250. }
  33251. void Component::lookAndFeelChanged()
  33252. {
  33253. }
  33254. void Component::sendLookAndFeelChange()
  33255. {
  33256. repaint();
  33257. lookAndFeelChanged();
  33258. // (it's not a great idea to do anything that would delete this component
  33259. // during the lookAndFeelChanged() callback)
  33260. jassert (isValidComponent());
  33261. SafePointer<Component> safePointer (this);
  33262. for (int i = childComponentList_.size(); --i >= 0;)
  33263. {
  33264. childComponentList_.getUnchecked (i)->sendLookAndFeelChange();
  33265. if (safePointer == 0)
  33266. return;
  33267. i = jmin (i, childComponentList_.size());
  33268. }
  33269. }
  33270. static const Identifier getColourPropertyId (const int colourId)
  33271. {
  33272. String s;
  33273. s.preallocateStorage (18);
  33274. s << "jcclr_" << String::toHexString (colourId);
  33275. return s;
  33276. }
  33277. const Colour Component::findColour (const int colourId, const bool inheritFromParent) const
  33278. {
  33279. var* v = properties.getItem (getColourPropertyId (colourId));
  33280. if (v != 0)
  33281. return Colour ((int) *v);
  33282. if (inheritFromParent && parentComponent_ != 0)
  33283. return parentComponent_->findColour (colourId, true);
  33284. return getLookAndFeel().findColour (colourId);
  33285. }
  33286. bool Component::isColourSpecified (const int colourId) const
  33287. {
  33288. return properties.contains (getColourPropertyId (colourId));
  33289. }
  33290. void Component::removeColour (const int colourId)
  33291. {
  33292. if (properties.remove (getColourPropertyId (colourId)))
  33293. colourChanged();
  33294. }
  33295. void Component::setColour (const int colourId, const Colour& colour)
  33296. {
  33297. if (properties.set (getColourPropertyId (colourId), (int) colour.getARGB()))
  33298. colourChanged();
  33299. }
  33300. void Component::copyAllExplicitColoursTo (Component& target) const
  33301. {
  33302. bool changed = false;
  33303. for (int i = properties.size(); --i >= 0;)
  33304. {
  33305. const Identifier name (properties.getName(i));
  33306. if (name.toString().startsWith ("jcclr_"))
  33307. if (target.properties.set (name, properties [name]))
  33308. changed = true;
  33309. }
  33310. if (changed)
  33311. target.colourChanged();
  33312. }
  33313. void Component::colourChanged()
  33314. {
  33315. }
  33316. const Rectangle<int> Component::getLocalBounds() const throw()
  33317. {
  33318. return Rectangle<int> (getWidth(), getHeight());
  33319. }
  33320. const Rectangle<int> Component::getParentOrMainMonitorBounds() const
  33321. {
  33322. return parentComponent_ != 0 ? parentComponent_->getLocalBounds()
  33323. : Desktop::getInstance().getMainMonitorArea();
  33324. }
  33325. const Rectangle<int> Component::getUnclippedArea() const
  33326. {
  33327. int x = 0, y = 0, w = getWidth(), h = getHeight();
  33328. Component* p = parentComponent_;
  33329. int px = getX();
  33330. int py = getY();
  33331. while (p != 0)
  33332. {
  33333. if (! Rectangle<int>::intersectRectangles (x, y, w, h, -px, -py, p->getWidth(), p->getHeight()))
  33334. return Rectangle<int>();
  33335. px += p->getX();
  33336. py += p->getY();
  33337. p = p->parentComponent_;
  33338. }
  33339. return Rectangle<int> (x, y, w, h);
  33340. }
  33341. void Component::clipObscuredRegions (Graphics& g, const Rectangle<int>& clipRect,
  33342. const int deltaX, const int deltaY) const
  33343. {
  33344. for (int i = childComponentList_.size(); --i >= 0;)
  33345. {
  33346. const Component* const c = childComponentList_.getUnchecked(i);
  33347. if (c->isVisible())
  33348. {
  33349. const Rectangle<int> newClip (clipRect.getIntersection (c->bounds_));
  33350. if (! newClip.isEmpty())
  33351. {
  33352. if (c->isOpaque())
  33353. {
  33354. g.excludeClipRegion (newClip.translated (deltaX, deltaY));
  33355. }
  33356. else
  33357. {
  33358. c->clipObscuredRegions (g, newClip.translated (-c->getX(), -c->getY()),
  33359. c->getX() + deltaX,
  33360. c->getY() + deltaY);
  33361. }
  33362. }
  33363. }
  33364. }
  33365. }
  33366. void Component::getVisibleArea (RectangleList& result, const bool includeSiblings) const
  33367. {
  33368. result.clear();
  33369. const Rectangle<int> unclipped (getUnclippedArea());
  33370. if (! unclipped.isEmpty())
  33371. {
  33372. result.add (unclipped);
  33373. if (includeSiblings)
  33374. {
  33375. const Component* const c = getTopLevelComponent();
  33376. c->subtractObscuredRegions (result, c->relativePositionToOtherComponent (this, Point<int>()),
  33377. c->getLocalBounds(), this);
  33378. }
  33379. subtractObscuredRegions (result, Point<int>(), unclipped, 0);
  33380. result.consolidate();
  33381. }
  33382. }
  33383. void Component::subtractObscuredRegions (RectangleList& result,
  33384. const Point<int>& delta,
  33385. const Rectangle<int>& clipRect,
  33386. const Component* const compToAvoid) const
  33387. {
  33388. for (int i = childComponentList_.size(); --i >= 0;)
  33389. {
  33390. const Component* const c = childComponentList_.getUnchecked(i);
  33391. if (c != compToAvoid && c->isVisible())
  33392. {
  33393. if (c->isOpaque())
  33394. {
  33395. Rectangle<int> childBounds (c->bounds_.getIntersection (clipRect));
  33396. childBounds.translate (delta.getX(), delta.getY());
  33397. result.subtract (childBounds);
  33398. }
  33399. else
  33400. {
  33401. Rectangle<int> newClip (clipRect.getIntersection (c->bounds_));
  33402. newClip.translate (-c->getX(), -c->getY());
  33403. c->subtractObscuredRegions (result, c->getPosition() + delta,
  33404. newClip, compToAvoid);
  33405. }
  33406. }
  33407. }
  33408. }
  33409. void Component::mouseEnter (const MouseEvent&)
  33410. {
  33411. // base class does nothing
  33412. }
  33413. void Component::mouseExit (const MouseEvent&)
  33414. {
  33415. // base class does nothing
  33416. }
  33417. void Component::mouseDown (const MouseEvent&)
  33418. {
  33419. // base class does nothing
  33420. }
  33421. void Component::mouseUp (const MouseEvent&)
  33422. {
  33423. // base class does nothing
  33424. }
  33425. void Component::mouseDrag (const MouseEvent&)
  33426. {
  33427. // base class does nothing
  33428. }
  33429. void Component::mouseMove (const MouseEvent&)
  33430. {
  33431. // base class does nothing
  33432. }
  33433. void Component::mouseDoubleClick (const MouseEvent&)
  33434. {
  33435. // base class does nothing
  33436. }
  33437. void Component::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  33438. {
  33439. // the base class just passes this event up to its parent..
  33440. if (parentComponent_ != 0)
  33441. parentComponent_->mouseWheelMove (e.getEventRelativeTo (parentComponent_),
  33442. wheelIncrementX, wheelIncrementY);
  33443. }
  33444. void Component::resized()
  33445. {
  33446. // base class does nothing
  33447. }
  33448. void Component::moved()
  33449. {
  33450. // base class does nothing
  33451. }
  33452. void Component::childBoundsChanged (Component*)
  33453. {
  33454. // base class does nothing
  33455. }
  33456. void Component::parentSizeChanged()
  33457. {
  33458. // base class does nothing
  33459. }
  33460. void Component::addComponentListener (ComponentListener* const newListener)
  33461. {
  33462. jassert (isValidComponent());
  33463. componentListeners.add (newListener);
  33464. }
  33465. void Component::removeComponentListener (ComponentListener* const listenerToRemove)
  33466. {
  33467. jassert (isValidComponent());
  33468. componentListeners.remove (listenerToRemove);
  33469. }
  33470. void Component::inputAttemptWhenModal()
  33471. {
  33472. bringModalComponentToFront();
  33473. getLookAndFeel().playAlertSound();
  33474. }
  33475. bool Component::canModalEventBeSentToComponent (const Component*)
  33476. {
  33477. return false;
  33478. }
  33479. void Component::internalModalInputAttempt()
  33480. {
  33481. Component* const current = getCurrentlyModalComponent();
  33482. if (current != 0)
  33483. current->inputAttemptWhenModal();
  33484. }
  33485. void Component::paint (Graphics&)
  33486. {
  33487. // all painting is done in the subclasses
  33488. jassert (! isOpaque()); // if your component's opaque, you've gotta paint it!
  33489. }
  33490. void Component::paintOverChildren (Graphics&)
  33491. {
  33492. // all painting is done in the subclasses
  33493. }
  33494. void Component::handleMessage (const Message& message)
  33495. {
  33496. if (message.intParameter1 == exitModalStateMessage)
  33497. {
  33498. exitModalState (message.intParameter2);
  33499. }
  33500. else if (message.intParameter1 == customCommandMessage)
  33501. {
  33502. handleCommandMessage (message.intParameter2);
  33503. }
  33504. }
  33505. void Component::postCommandMessage (const int commandId)
  33506. {
  33507. postMessage (new Message (customCommandMessage, commandId, 0, 0));
  33508. }
  33509. void Component::handleCommandMessage (int)
  33510. {
  33511. // used by subclasses
  33512. }
  33513. void Component::addMouseListener (MouseListener* const newListener,
  33514. const bool wantsEventsForAllNestedChildComponents)
  33515. {
  33516. // if component methods are being called from threads other than the message
  33517. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33518. checkMessageManagerIsLocked
  33519. // If you register a component as a mouselistener for itself, it'll receive all the events
  33520. // twice - once via the direct callback that all components get anyway, and then again as a listener!
  33521. jassert ((newListener != this) || wantsEventsForAllNestedChildComponents);
  33522. if (mouseListeners_ == 0)
  33523. mouseListeners_ = new Array<MouseListener*>();
  33524. if (! mouseListeners_->contains (newListener))
  33525. {
  33526. if (wantsEventsForAllNestedChildComponents)
  33527. {
  33528. mouseListeners_->insert (0, newListener);
  33529. ++numDeepMouseListeners;
  33530. }
  33531. else
  33532. {
  33533. mouseListeners_->add (newListener);
  33534. }
  33535. }
  33536. }
  33537. void Component::removeMouseListener (MouseListener* const listenerToRemove)
  33538. {
  33539. // if component methods are being called from threads other than the message
  33540. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33541. checkMessageManagerIsLocked
  33542. if (mouseListeners_ != 0)
  33543. {
  33544. const int index = mouseListeners_->indexOf (listenerToRemove);
  33545. if (index >= 0)
  33546. {
  33547. if (index < numDeepMouseListeners)
  33548. --numDeepMouseListeners;
  33549. mouseListeners_->remove (index);
  33550. }
  33551. }
  33552. }
  33553. void Component::internalMouseEnter (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33554. {
  33555. if (isCurrentlyBlockedByAnotherModalComponent())
  33556. {
  33557. // if something else is modal, always just show a normal mouse cursor
  33558. source.showMouseCursor (MouseCursor::NormalCursor);
  33559. return;
  33560. }
  33561. if (! flags.mouseInsideFlag)
  33562. {
  33563. flags.mouseInsideFlag = true;
  33564. flags.mouseOverFlag = true;
  33565. flags.draggingFlag = false;
  33566. BailOutChecker checker (this);
  33567. if (flags.repaintOnMouseActivityFlag)
  33568. repaint();
  33569. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33570. this, this, time, relativePos,
  33571. time, 0, false);
  33572. mouseEnter (me);
  33573. if (checker.shouldBailOut())
  33574. return;
  33575. Desktop::getInstance().resetTimer();
  33576. Desktop::getInstance().mouseListeners.callChecked (checker, &MouseListener::mouseEnter, me);
  33577. if (checker.shouldBailOut())
  33578. return;
  33579. if (mouseListeners_ != 0)
  33580. {
  33581. for (int i = mouseListeners_->size(); --i >= 0;)
  33582. {
  33583. mouseListeners_->getUnchecked(i)->mouseEnter (me);
  33584. if (checker.shouldBailOut())
  33585. return;
  33586. i = jmin (i, mouseListeners_->size());
  33587. }
  33588. }
  33589. Component* p = parentComponent_;
  33590. while (p != 0)
  33591. {
  33592. if (p->numDeepMouseListeners > 0)
  33593. {
  33594. BailOutChecker checker2 (this, p);
  33595. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33596. {
  33597. p->mouseListeners_->getUnchecked(i)->mouseEnter (me);
  33598. if (checker2.shouldBailOut())
  33599. return;
  33600. i = jmin (i, p->numDeepMouseListeners);
  33601. }
  33602. }
  33603. p = p->parentComponent_;
  33604. }
  33605. }
  33606. }
  33607. void Component::internalMouseExit (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33608. {
  33609. BailOutChecker checker (this);
  33610. if (flags.draggingFlag)
  33611. {
  33612. internalMouseUp (source, relativePos, time, source.getCurrentModifiers().getRawFlags());
  33613. if (checker.shouldBailOut())
  33614. return;
  33615. }
  33616. if (flags.mouseInsideFlag || flags.mouseOverFlag)
  33617. {
  33618. flags.mouseInsideFlag = false;
  33619. flags.mouseOverFlag = false;
  33620. flags.draggingFlag = false;
  33621. if (flags.repaintOnMouseActivityFlag)
  33622. repaint();
  33623. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33624. this, this, time, relativePos,
  33625. time, 0, false);
  33626. mouseExit (me);
  33627. if (checker.shouldBailOut())
  33628. return;
  33629. Desktop::getInstance().resetTimer();
  33630. Desktop::getInstance().mouseListeners.callChecked (checker, &MouseListener::mouseExit, me);
  33631. if (checker.shouldBailOut())
  33632. return;
  33633. if (mouseListeners_ != 0)
  33634. {
  33635. for (int i = mouseListeners_->size(); --i >= 0;)
  33636. {
  33637. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseExit (me);
  33638. if (checker.shouldBailOut())
  33639. return;
  33640. i = jmin (i, mouseListeners_->size());
  33641. }
  33642. }
  33643. Component* p = parentComponent_;
  33644. while (p != 0)
  33645. {
  33646. if (p->numDeepMouseListeners > 0)
  33647. {
  33648. BailOutChecker checker2 (this, p);
  33649. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33650. {
  33651. p->mouseListeners_->getUnchecked (i)->mouseExit (me);
  33652. if (checker2.shouldBailOut())
  33653. return;
  33654. i = jmin (i, p->numDeepMouseListeners);
  33655. }
  33656. }
  33657. p = p->parentComponent_;
  33658. }
  33659. }
  33660. }
  33661. class InternalDragRepeater : public Timer
  33662. {
  33663. public:
  33664. InternalDragRepeater()
  33665. {}
  33666. ~InternalDragRepeater()
  33667. {
  33668. clearSingletonInstance();
  33669. }
  33670. juce_DeclareSingleton_SingleThreaded_Minimal (InternalDragRepeater)
  33671. void timerCallback()
  33672. {
  33673. Desktop& desktop = Desktop::getInstance();
  33674. int numMiceDown = 0;
  33675. for (int i = desktop.getNumMouseSources(); --i >= 0;)
  33676. {
  33677. MouseInputSource* const source = desktop.getMouseSource(i);
  33678. if (source->isDragging())
  33679. {
  33680. source->triggerFakeMove();
  33681. ++numMiceDown;
  33682. }
  33683. }
  33684. if (numMiceDown == 0)
  33685. deleteInstance();
  33686. }
  33687. juce_UseDebuggingNewOperator
  33688. private:
  33689. InternalDragRepeater (const InternalDragRepeater&);
  33690. InternalDragRepeater& operator= (const InternalDragRepeater&);
  33691. };
  33692. juce_ImplementSingleton_SingleThreaded (InternalDragRepeater)
  33693. void Component::beginDragAutoRepeat (const int interval)
  33694. {
  33695. if (interval > 0)
  33696. {
  33697. if (InternalDragRepeater::getInstance()->getTimerInterval() != interval)
  33698. InternalDragRepeater::getInstance()->startTimer (interval);
  33699. }
  33700. else
  33701. {
  33702. InternalDragRepeater::deleteInstance();
  33703. }
  33704. }
  33705. void Component::internalMouseDown (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33706. {
  33707. Desktop& desktop = Desktop::getInstance();
  33708. BailOutChecker checker (this);
  33709. if (isCurrentlyBlockedByAnotherModalComponent())
  33710. {
  33711. internalModalInputAttempt();
  33712. if (checker.shouldBailOut())
  33713. return;
  33714. // If processing the input attempt has exited the modal loop, we'll allow the event
  33715. // to be delivered..
  33716. if (isCurrentlyBlockedByAnotherModalComponent())
  33717. {
  33718. // allow blocked mouse-events to go to global listeners..
  33719. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33720. this, this, time, relativePos, time,
  33721. source.getNumberOfMultipleClicks(), false);
  33722. desktop.resetTimer();
  33723. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  33724. return;
  33725. }
  33726. }
  33727. {
  33728. Component* c = this;
  33729. while (c != 0)
  33730. {
  33731. if (c->isBroughtToFrontOnMouseClick())
  33732. {
  33733. c->toFront (true);
  33734. if (checker.shouldBailOut())
  33735. return;
  33736. }
  33737. c = c->parentComponent_;
  33738. }
  33739. }
  33740. if (! flags.dontFocusOnMouseClickFlag)
  33741. {
  33742. grabFocusInternal (focusChangedByMouseClick);
  33743. if (checker.shouldBailOut())
  33744. return;
  33745. }
  33746. flags.draggingFlag = true;
  33747. flags.mouseOverFlag = true;
  33748. if (flags.repaintOnMouseActivityFlag)
  33749. repaint();
  33750. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33751. this, this, time, relativePos, time,
  33752. source.getNumberOfMultipleClicks(), false);
  33753. mouseDown (me);
  33754. if (checker.shouldBailOut())
  33755. return;
  33756. desktop.resetTimer();
  33757. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  33758. if (checker.shouldBailOut())
  33759. return;
  33760. if (mouseListeners_ != 0)
  33761. {
  33762. for (int i = mouseListeners_->size(); --i >= 0;)
  33763. {
  33764. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDown (me);
  33765. if (checker.shouldBailOut())
  33766. return;
  33767. i = jmin (i, mouseListeners_->size());
  33768. }
  33769. }
  33770. Component* p = parentComponent_;
  33771. while (p != 0)
  33772. {
  33773. if (p->numDeepMouseListeners > 0)
  33774. {
  33775. BailOutChecker checker2 (this, p);
  33776. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33777. {
  33778. p->mouseListeners_->getUnchecked (i)->mouseDown (me);
  33779. if (checker2.shouldBailOut())
  33780. return;
  33781. i = jmin (i, p->numDeepMouseListeners);
  33782. }
  33783. }
  33784. p = p->parentComponent_;
  33785. }
  33786. }
  33787. void Component::internalMouseUp (MouseInputSource& source, const Point<int>& relativePos, const Time& time, const ModifierKeys& oldModifiers)
  33788. {
  33789. if (flags.draggingFlag)
  33790. {
  33791. Desktop& desktop = Desktop::getInstance();
  33792. flags.draggingFlag = false;
  33793. BailOutChecker checker (this);
  33794. if (flags.repaintOnMouseActivityFlag)
  33795. repaint();
  33796. const MouseEvent me (source, relativePos,
  33797. oldModifiers, this, this, time,
  33798. globalPositionToRelative (source.getLastMouseDownPosition()),
  33799. source.getLastMouseDownTime(),
  33800. source.getNumberOfMultipleClicks(),
  33801. source.hasMouseMovedSignificantlySincePressed());
  33802. mouseUp (me);
  33803. if (checker.shouldBailOut())
  33804. return;
  33805. desktop.resetTimer();
  33806. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseUp, me);
  33807. if (checker.shouldBailOut())
  33808. return;
  33809. if (mouseListeners_ != 0)
  33810. {
  33811. for (int i = mouseListeners_->size(); --i >= 0;)
  33812. {
  33813. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseUp (me);
  33814. if (checker.shouldBailOut())
  33815. return;
  33816. i = jmin (i, mouseListeners_->size());
  33817. }
  33818. }
  33819. {
  33820. Component* p = parentComponent_;
  33821. while (p != 0)
  33822. {
  33823. if (p->numDeepMouseListeners > 0)
  33824. {
  33825. BailOutChecker checker2 (this, p);
  33826. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33827. {
  33828. p->mouseListeners_->getUnchecked (i)->mouseUp (me);
  33829. if (checker2.shouldBailOut())
  33830. return;
  33831. i = jmin (i, p->numDeepMouseListeners);
  33832. }
  33833. }
  33834. p = p->parentComponent_;
  33835. }
  33836. }
  33837. // check for double-click
  33838. if (me.getNumberOfClicks() >= 2)
  33839. {
  33840. const int numListeners = (mouseListeners_ != 0) ? mouseListeners_->size() : 0;
  33841. mouseDoubleClick (me);
  33842. if (checker.shouldBailOut())
  33843. return;
  33844. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDoubleClick, me);
  33845. if (checker.shouldBailOut())
  33846. return;
  33847. for (int i = numListeners; --i >= 0;)
  33848. {
  33849. if (checker.shouldBailOut())
  33850. return;
  33851. MouseListener* const ml = (MouseListener*)((*mouseListeners_)[i]);
  33852. if (ml != 0)
  33853. ml->mouseDoubleClick (me);
  33854. }
  33855. if (checker.shouldBailOut())
  33856. return;
  33857. Component* p = parentComponent_;
  33858. while (p != 0)
  33859. {
  33860. if (p->numDeepMouseListeners > 0)
  33861. {
  33862. BailOutChecker checker2 (this, p);
  33863. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33864. {
  33865. p->mouseListeners_->getUnchecked (i)->mouseDoubleClick (me);
  33866. if (checker2.shouldBailOut())
  33867. return;
  33868. i = jmin (i, p->numDeepMouseListeners);
  33869. }
  33870. }
  33871. p = p->parentComponent_;
  33872. }
  33873. }
  33874. }
  33875. }
  33876. void Component::internalMouseDrag (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33877. {
  33878. if (flags.draggingFlag)
  33879. {
  33880. Desktop& desktop = Desktop::getInstance();
  33881. flags.mouseOverFlag = reallyContains (relativePos.getX(), relativePos.getY(), false);
  33882. BailOutChecker checker (this);
  33883. const MouseEvent me (source, relativePos,
  33884. source.getCurrentModifiers(), this, this, time,
  33885. globalPositionToRelative (source.getLastMouseDownPosition()),
  33886. source.getLastMouseDownTime(),
  33887. source.getNumberOfMultipleClicks(),
  33888. source.hasMouseMovedSignificantlySincePressed());
  33889. mouseDrag (me);
  33890. if (checker.shouldBailOut())
  33891. return;
  33892. desktop.resetTimer();
  33893. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  33894. if (checker.shouldBailOut())
  33895. return;
  33896. if (mouseListeners_ != 0)
  33897. {
  33898. for (int i = mouseListeners_->size(); --i >= 0;)
  33899. {
  33900. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDrag (me);
  33901. if (checker.shouldBailOut())
  33902. return;
  33903. i = jmin (i, mouseListeners_->size());
  33904. }
  33905. }
  33906. Component* p = parentComponent_;
  33907. while (p != 0)
  33908. {
  33909. if (p->numDeepMouseListeners > 0)
  33910. {
  33911. BailOutChecker checker2 (this, p);
  33912. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33913. {
  33914. p->mouseListeners_->getUnchecked (i)->mouseDrag (me);
  33915. if (checker2.shouldBailOut())
  33916. return;
  33917. i = jmin (i, p->numDeepMouseListeners);
  33918. }
  33919. }
  33920. p = p->parentComponent_;
  33921. }
  33922. }
  33923. }
  33924. void Component::internalMouseMove (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33925. {
  33926. Desktop& desktop = Desktop::getInstance();
  33927. BailOutChecker checker (this);
  33928. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33929. this, this, time, relativePos,
  33930. time, 0, false);
  33931. if (isCurrentlyBlockedByAnotherModalComponent())
  33932. {
  33933. // allow blocked mouse-events to go to global listeners..
  33934. desktop.sendMouseMove();
  33935. }
  33936. else
  33937. {
  33938. flags.mouseOverFlag = true;
  33939. mouseMove (me);
  33940. if (checker.shouldBailOut())
  33941. return;
  33942. desktop.resetTimer();
  33943. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  33944. if (checker.shouldBailOut())
  33945. return;
  33946. if (mouseListeners_ != 0)
  33947. {
  33948. for (int i = mouseListeners_->size(); --i >= 0;)
  33949. {
  33950. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseMove (me);
  33951. if (checker.shouldBailOut())
  33952. return;
  33953. i = jmin (i, mouseListeners_->size());
  33954. }
  33955. }
  33956. Component* p = parentComponent_;
  33957. while (p != 0)
  33958. {
  33959. if (p->numDeepMouseListeners > 0)
  33960. {
  33961. BailOutChecker checker2 (this, p);
  33962. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33963. {
  33964. p->mouseListeners_->getUnchecked (i)->mouseMove (me);
  33965. if (checker2.shouldBailOut())
  33966. return;
  33967. i = jmin (i, p->numDeepMouseListeners);
  33968. }
  33969. }
  33970. p = p->parentComponent_;
  33971. }
  33972. }
  33973. }
  33974. void Component::internalMouseWheel (MouseInputSource& source, const Point<int>& relativePos,
  33975. const Time& time, const float amountX, const float amountY)
  33976. {
  33977. Desktop& desktop = Desktop::getInstance();
  33978. BailOutChecker checker (this);
  33979. const float wheelIncrementX = amountX / 256.0f;
  33980. const float wheelIncrementY = amountY / 256.0f;
  33981. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33982. this, this, time, relativePos, time, 0, false);
  33983. if (isCurrentlyBlockedByAnotherModalComponent())
  33984. {
  33985. // allow blocked mouse-events to go to global listeners..
  33986. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  33987. }
  33988. else
  33989. {
  33990. mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  33991. if (checker.shouldBailOut())
  33992. return;
  33993. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  33994. if (checker.shouldBailOut())
  33995. return;
  33996. if (mouseListeners_ != 0)
  33997. {
  33998. for (int i = mouseListeners_->size(); --i >= 0;)
  33999. {
  34000. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  34001. if (checker.shouldBailOut())
  34002. return;
  34003. i = jmin (i, mouseListeners_->size());
  34004. }
  34005. }
  34006. Component* p = parentComponent_;
  34007. while (p != 0)
  34008. {
  34009. if (p->numDeepMouseListeners > 0)
  34010. {
  34011. BailOutChecker checker2 (this, p);
  34012. for (int i = p->numDeepMouseListeners; --i >= 0;)
  34013. {
  34014. p->mouseListeners_->getUnchecked (i)->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  34015. if (checker2.shouldBailOut())
  34016. return;
  34017. i = jmin (i, p->numDeepMouseListeners);
  34018. }
  34019. }
  34020. p = p->parentComponent_;
  34021. }
  34022. }
  34023. }
  34024. void Component::sendFakeMouseMove() const
  34025. {
  34026. Desktop::getInstance().getMainMouseSource().triggerFakeMove();
  34027. }
  34028. void Component::broughtToFront()
  34029. {
  34030. }
  34031. void Component::internalBroughtToFront()
  34032. {
  34033. if (! isValidComponent())
  34034. return;
  34035. if (flags.hasHeavyweightPeerFlag)
  34036. Desktop::getInstance().componentBroughtToFront (this);
  34037. BailOutChecker checker (this);
  34038. broughtToFront();
  34039. if (checker.shouldBailOut())
  34040. return;
  34041. componentListeners.callChecked (checker, &ComponentListener::componentBroughtToFront, *this);
  34042. if (checker.shouldBailOut())
  34043. return;
  34044. // When brought to the front and there's a modal component blocking this one,
  34045. // we need to bring the modal one to the front instead..
  34046. Component* const cm = getCurrentlyModalComponent();
  34047. if (cm != 0 && cm->getTopLevelComponent() != getTopLevelComponent())
  34048. bringModalComponentToFront();
  34049. }
  34050. void Component::focusGained (FocusChangeType)
  34051. {
  34052. // base class does nothing
  34053. }
  34054. void Component::internalFocusGain (const FocusChangeType cause)
  34055. {
  34056. SafePointer<Component> safePointer (this);
  34057. focusGained (cause);
  34058. if (safePointer != 0)
  34059. internalChildFocusChange (cause);
  34060. }
  34061. void Component::focusLost (FocusChangeType)
  34062. {
  34063. // base class does nothing
  34064. }
  34065. void Component::internalFocusLoss (const FocusChangeType cause)
  34066. {
  34067. SafePointer<Component> safePointer (this);
  34068. focusLost (focusChangedDirectly);
  34069. if (safePointer != 0)
  34070. internalChildFocusChange (cause);
  34071. }
  34072. void Component::focusOfChildComponentChanged (FocusChangeType /*cause*/)
  34073. {
  34074. // base class does nothing
  34075. }
  34076. void Component::internalChildFocusChange (FocusChangeType cause)
  34077. {
  34078. const bool childIsNowFocused = hasKeyboardFocus (true);
  34079. if (flags.childCompFocusedFlag != childIsNowFocused)
  34080. {
  34081. flags.childCompFocusedFlag = childIsNowFocused;
  34082. SafePointer<Component> safePointer (this);
  34083. focusOfChildComponentChanged (cause);
  34084. if (safePointer == 0)
  34085. return;
  34086. }
  34087. if (parentComponent_ != 0)
  34088. parentComponent_->internalChildFocusChange (cause);
  34089. }
  34090. bool Component::isEnabled() const throw()
  34091. {
  34092. return (! flags.isDisabledFlag)
  34093. && (parentComponent_ == 0 || parentComponent_->isEnabled());
  34094. }
  34095. void Component::setEnabled (const bool shouldBeEnabled)
  34096. {
  34097. if (flags.isDisabledFlag == shouldBeEnabled)
  34098. {
  34099. flags.isDisabledFlag = ! shouldBeEnabled;
  34100. // if any parent components are disabled, setting our flag won't make a difference,
  34101. // so no need to send a change message
  34102. if (parentComponent_ == 0 || parentComponent_->isEnabled())
  34103. sendEnablementChangeMessage();
  34104. }
  34105. }
  34106. void Component::sendEnablementChangeMessage()
  34107. {
  34108. SafePointer<Component> safePointer (this);
  34109. enablementChanged();
  34110. if (safePointer == 0)
  34111. return;
  34112. for (int i = getNumChildComponents(); --i >= 0;)
  34113. {
  34114. Component* const c = getChildComponent (i);
  34115. if (c != 0)
  34116. {
  34117. c->sendEnablementChangeMessage();
  34118. if (safePointer == 0)
  34119. return;
  34120. }
  34121. }
  34122. }
  34123. void Component::enablementChanged()
  34124. {
  34125. }
  34126. void Component::setWantsKeyboardFocus (const bool wantsFocus) throw()
  34127. {
  34128. flags.wantsFocusFlag = wantsFocus;
  34129. }
  34130. void Component::setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus)
  34131. {
  34132. flags.dontFocusOnMouseClickFlag = ! shouldGrabFocus;
  34133. }
  34134. bool Component::getMouseClickGrabsKeyboardFocus() const throw()
  34135. {
  34136. return ! flags.dontFocusOnMouseClickFlag;
  34137. }
  34138. bool Component::getWantsKeyboardFocus() const throw()
  34139. {
  34140. return flags.wantsFocusFlag && ! flags.isDisabledFlag;
  34141. }
  34142. void Component::setFocusContainer (const bool shouldBeFocusContainer) throw()
  34143. {
  34144. flags.isFocusContainerFlag = shouldBeFocusContainer;
  34145. }
  34146. bool Component::isFocusContainer() const throw()
  34147. {
  34148. return flags.isFocusContainerFlag;
  34149. }
  34150. static const Identifier juce_explicitFocusOrderId ("_jexfo");
  34151. int Component::getExplicitFocusOrder() const
  34152. {
  34153. return properties [juce_explicitFocusOrderId];
  34154. }
  34155. void Component::setExplicitFocusOrder (const int newFocusOrderIndex)
  34156. {
  34157. properties.set (juce_explicitFocusOrderId, newFocusOrderIndex);
  34158. }
  34159. KeyboardFocusTraverser* Component::createFocusTraverser()
  34160. {
  34161. if (flags.isFocusContainerFlag || parentComponent_ == 0)
  34162. return new KeyboardFocusTraverser();
  34163. return parentComponent_->createFocusTraverser();
  34164. }
  34165. void Component::takeKeyboardFocus (const FocusChangeType cause)
  34166. {
  34167. // give the focus to this component
  34168. if (currentlyFocusedComponent != this)
  34169. {
  34170. JUCE_TRY
  34171. {
  34172. // get the focus onto our desktop window
  34173. ComponentPeer* const peer = getPeer();
  34174. if (peer != 0)
  34175. {
  34176. SafePointer<Component> safePointer (this);
  34177. peer->grabFocus();
  34178. if (peer->isFocused() && currentlyFocusedComponent != this)
  34179. {
  34180. SafePointer<Component> componentLosingFocus (currentlyFocusedComponent);
  34181. currentlyFocusedComponent = this;
  34182. Desktop::getInstance().triggerFocusCallback();
  34183. // call this after setting currentlyFocusedComponent so that the one that's
  34184. // losing it has a chance to see where focus is going
  34185. if (componentLosingFocus != 0)
  34186. componentLosingFocus->internalFocusLoss (cause);
  34187. if (currentlyFocusedComponent == this)
  34188. {
  34189. focusGained (cause);
  34190. if (safePointer != 0)
  34191. internalChildFocusChange (cause);
  34192. }
  34193. }
  34194. }
  34195. }
  34196. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  34197. catch (const std::exception& e)
  34198. {
  34199. currentlyFocusedComponent = 0;
  34200. Desktop::getInstance().triggerFocusCallback();
  34201. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  34202. }
  34203. catch (...)
  34204. {
  34205. currentlyFocusedComponent = 0;
  34206. Desktop::getInstance().triggerFocusCallback();
  34207. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  34208. }
  34209. #endif
  34210. }
  34211. }
  34212. void Component::grabFocusInternal (const FocusChangeType cause, const bool canTryParent)
  34213. {
  34214. if (isShowing())
  34215. {
  34216. if (flags.wantsFocusFlag && (isEnabled() || parentComponent_ == 0))
  34217. {
  34218. takeKeyboardFocus (cause);
  34219. }
  34220. else
  34221. {
  34222. if (isParentOf (currentlyFocusedComponent)
  34223. && currentlyFocusedComponent->isShowing())
  34224. {
  34225. // do nothing if the focused component is actually a child of ours..
  34226. }
  34227. else
  34228. {
  34229. // find the default child component..
  34230. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  34231. if (traverser != 0)
  34232. {
  34233. Component* const defaultComp = traverser->getDefaultComponent (this);
  34234. traverser = 0;
  34235. if (defaultComp != 0)
  34236. {
  34237. defaultComp->grabFocusInternal (cause, false);
  34238. return;
  34239. }
  34240. }
  34241. if (canTryParent && parentComponent_ != 0)
  34242. {
  34243. // if no children want it and we're allowed to try our parent comp,
  34244. // then pass up to parent, which will try our siblings.
  34245. parentComponent_->grabFocusInternal (cause, true);
  34246. }
  34247. }
  34248. }
  34249. }
  34250. }
  34251. void Component::grabKeyboardFocus()
  34252. {
  34253. // if component methods are being called from threads other than the message
  34254. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  34255. checkMessageManagerIsLocked
  34256. grabFocusInternal (focusChangedDirectly);
  34257. }
  34258. void Component::moveKeyboardFocusToSibling (const bool moveToNext)
  34259. {
  34260. // if component methods are being called from threads other than the message
  34261. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  34262. checkMessageManagerIsLocked
  34263. if (parentComponent_ != 0)
  34264. {
  34265. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  34266. if (traverser != 0)
  34267. {
  34268. Component* const nextComp = moveToNext ? traverser->getNextComponent (this)
  34269. : traverser->getPreviousComponent (this);
  34270. traverser = 0;
  34271. if (nextComp != 0)
  34272. {
  34273. if (nextComp->isCurrentlyBlockedByAnotherModalComponent())
  34274. {
  34275. SafePointer<Component> nextCompPointer (nextComp);
  34276. internalModalInputAttempt();
  34277. if (nextCompPointer == 0 || nextComp->isCurrentlyBlockedByAnotherModalComponent())
  34278. return;
  34279. }
  34280. nextComp->grabFocusInternal (focusChangedByTabKey);
  34281. return;
  34282. }
  34283. }
  34284. parentComponent_->moveKeyboardFocusToSibling (moveToNext);
  34285. }
  34286. }
  34287. bool Component::hasKeyboardFocus (const bool trueIfChildIsFocused) const
  34288. {
  34289. return (currentlyFocusedComponent == this)
  34290. || (trueIfChildIsFocused && isParentOf (currentlyFocusedComponent));
  34291. }
  34292. Component* JUCE_CALLTYPE Component::getCurrentlyFocusedComponent() throw()
  34293. {
  34294. return currentlyFocusedComponent;
  34295. }
  34296. void Component::giveAwayFocus()
  34297. {
  34298. // use a copy so we can clear the value before the call
  34299. SafePointer<Component> componentLosingFocus (currentlyFocusedComponent);
  34300. currentlyFocusedComponent = 0;
  34301. Desktop::getInstance().triggerFocusCallback();
  34302. if (componentLosingFocus != 0)
  34303. componentLosingFocus->internalFocusLoss (focusChangedDirectly);
  34304. }
  34305. bool Component::isMouseOver() const throw()
  34306. {
  34307. return flags.mouseOverFlag;
  34308. }
  34309. bool Component::isMouseButtonDown() const throw()
  34310. {
  34311. return flags.draggingFlag;
  34312. }
  34313. bool Component::isMouseOverOrDragging() const throw()
  34314. {
  34315. return flags.mouseOverFlag || flags.draggingFlag;
  34316. }
  34317. bool JUCE_CALLTYPE Component::isMouseButtonDownAnywhere() throw()
  34318. {
  34319. return ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown();
  34320. }
  34321. const Point<int> Component::getMouseXYRelative() const
  34322. {
  34323. return globalPositionToRelative (Desktop::getMousePosition());
  34324. }
  34325. const Rectangle<int> Component::getParentMonitorArea() const
  34326. {
  34327. return Desktop::getInstance()
  34328. .getMonitorAreaContaining (relativePositionToGlobal (getLocalBounds().getCentre()));
  34329. }
  34330. void Component::addKeyListener (KeyListener* const newListener)
  34331. {
  34332. if (keyListeners_ == 0)
  34333. keyListeners_ = new Array <KeyListener*>();
  34334. keyListeners_->addIfNotAlreadyThere (newListener);
  34335. }
  34336. void Component::removeKeyListener (KeyListener* const listenerToRemove)
  34337. {
  34338. if (keyListeners_ != 0)
  34339. keyListeners_->removeValue (listenerToRemove);
  34340. }
  34341. bool Component::keyPressed (const KeyPress&)
  34342. {
  34343. return false;
  34344. }
  34345. bool Component::keyStateChanged (const bool /*isKeyDown*/)
  34346. {
  34347. return false;
  34348. }
  34349. void Component::modifierKeysChanged (const ModifierKeys& modifiers)
  34350. {
  34351. if (parentComponent_ != 0)
  34352. parentComponent_->modifierKeysChanged (modifiers);
  34353. }
  34354. void Component::internalModifierKeysChanged()
  34355. {
  34356. sendFakeMouseMove();
  34357. modifierKeysChanged (ModifierKeys::getCurrentModifiers());
  34358. }
  34359. ComponentPeer* Component::getPeer() const
  34360. {
  34361. if (flags.hasHeavyweightPeerFlag)
  34362. return ComponentPeer::getPeerFor (this);
  34363. else if (parentComponent_ != 0)
  34364. return parentComponent_->getPeer();
  34365. else
  34366. return 0;
  34367. }
  34368. Component::BailOutChecker::BailOutChecker (Component* const component1, Component* const component2_)
  34369. : safePointer1 (component1), safePointer2 (component2_), component2 (component2_)
  34370. {
  34371. jassert (component1 != 0);
  34372. }
  34373. bool Component::BailOutChecker::shouldBailOut() const throw()
  34374. {
  34375. return safePointer1 == 0 || safePointer2.getComponent() != component2;
  34376. }
  34377. END_JUCE_NAMESPACE
  34378. /*** End of inlined file: juce_Component.cpp ***/
  34379. /*** Start of inlined file: juce_ComponentListener.cpp ***/
  34380. BEGIN_JUCE_NAMESPACE
  34381. void ComponentListener::componentMovedOrResized (Component&, bool, bool) {}
  34382. void ComponentListener::componentBroughtToFront (Component&) {}
  34383. void ComponentListener::componentVisibilityChanged (Component&) {}
  34384. void ComponentListener::componentChildrenChanged (Component&) {}
  34385. void ComponentListener::componentParentHierarchyChanged (Component&) {}
  34386. void ComponentListener::componentNameChanged (Component&) {}
  34387. void ComponentListener::componentBeingDeleted (Component&) {}
  34388. END_JUCE_NAMESPACE
  34389. /*** End of inlined file: juce_ComponentListener.cpp ***/
  34390. /*** Start of inlined file: juce_Desktop.cpp ***/
  34391. BEGIN_JUCE_NAMESPACE
  34392. Desktop::Desktop()
  34393. : mouseClickCounter (0),
  34394. kioskModeComponent (0),
  34395. allowedOrientations (allOrientations)
  34396. {
  34397. createMouseInputSources();
  34398. refreshMonitorSizes();
  34399. }
  34400. Desktop::~Desktop()
  34401. {
  34402. jassert (instance == this);
  34403. instance = 0;
  34404. // doh! If you don't delete all your windows before exiting, you're going to
  34405. // be leaking memory!
  34406. jassert (desktopComponents.size() == 0);
  34407. }
  34408. Desktop& JUCE_CALLTYPE Desktop::getInstance()
  34409. {
  34410. if (instance == 0)
  34411. instance = new Desktop();
  34412. return *instance;
  34413. }
  34414. Desktop* Desktop::instance = 0;
  34415. extern void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords,
  34416. const bool clipToWorkArea);
  34417. void Desktop::refreshMonitorSizes()
  34418. {
  34419. const Array <Rectangle<int> > oldClipped (monitorCoordsClipped);
  34420. const Array <Rectangle<int> > oldUnclipped (monitorCoordsUnclipped);
  34421. monitorCoordsClipped.clear();
  34422. monitorCoordsUnclipped.clear();
  34423. juce_updateMultiMonitorInfo (monitorCoordsClipped, true);
  34424. juce_updateMultiMonitorInfo (monitorCoordsUnclipped, false);
  34425. jassert (monitorCoordsClipped.size() == monitorCoordsUnclipped.size());
  34426. if (oldClipped != monitorCoordsClipped
  34427. || oldUnclipped != monitorCoordsUnclipped)
  34428. {
  34429. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  34430. {
  34431. ComponentPeer* const p = ComponentPeer::getPeer (i);
  34432. if (p != 0)
  34433. p->handleScreenSizeChange();
  34434. }
  34435. }
  34436. }
  34437. int Desktop::getNumDisplayMonitors() const throw()
  34438. {
  34439. return monitorCoordsClipped.size();
  34440. }
  34441. const Rectangle<int> Desktop::getDisplayMonitorCoordinates (const int index, const bool clippedToWorkArea) const throw()
  34442. {
  34443. return clippedToWorkArea ? monitorCoordsClipped [index]
  34444. : monitorCoordsUnclipped [index];
  34445. }
  34446. const RectangleList Desktop::getAllMonitorDisplayAreas (const bool clippedToWorkArea) const throw()
  34447. {
  34448. RectangleList rl;
  34449. for (int i = 0; i < getNumDisplayMonitors(); ++i)
  34450. rl.addWithoutMerging (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  34451. return rl;
  34452. }
  34453. const Rectangle<int> Desktop::getMainMonitorArea (const bool clippedToWorkArea) const throw()
  34454. {
  34455. return getDisplayMonitorCoordinates (0, clippedToWorkArea);
  34456. }
  34457. const Rectangle<int> Desktop::getMonitorAreaContaining (const Point<int>& position, const bool clippedToWorkArea) const
  34458. {
  34459. Rectangle<int> best (getMainMonitorArea (clippedToWorkArea));
  34460. double bestDistance = 1.0e10;
  34461. for (int i = getNumDisplayMonitors(); --i >= 0;)
  34462. {
  34463. const Rectangle<int> rect (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  34464. if (rect.contains (position))
  34465. return rect;
  34466. const double distance = rect.getCentre().getDistanceFrom (position);
  34467. if (distance < bestDistance)
  34468. {
  34469. bestDistance = distance;
  34470. best = rect;
  34471. }
  34472. }
  34473. return best;
  34474. }
  34475. int Desktop::getNumComponents() const throw()
  34476. {
  34477. return desktopComponents.size();
  34478. }
  34479. Component* Desktop::getComponent (const int index) const throw()
  34480. {
  34481. return desktopComponents [index];
  34482. }
  34483. Component* Desktop::findComponentAt (const Point<int>& screenPosition) const
  34484. {
  34485. for (int i = desktopComponents.size(); --i >= 0;)
  34486. {
  34487. Component* const c = desktopComponents.getUnchecked(i);
  34488. const Point<int> relative (c->globalPositionToRelative (screenPosition));
  34489. if (c->contains (relative.getX(), relative.getY()))
  34490. return c->getComponentAt (relative.getX(), relative.getY());
  34491. }
  34492. return 0;
  34493. }
  34494. void Desktop::addDesktopComponent (Component* const c)
  34495. {
  34496. jassert (c != 0);
  34497. jassert (! desktopComponents.contains (c));
  34498. desktopComponents.addIfNotAlreadyThere (c);
  34499. }
  34500. void Desktop::removeDesktopComponent (Component* const c)
  34501. {
  34502. desktopComponents.removeValue (c);
  34503. }
  34504. void Desktop::componentBroughtToFront (Component* const c)
  34505. {
  34506. const int index = desktopComponents.indexOf (c);
  34507. jassert (index >= 0);
  34508. if (index >= 0)
  34509. {
  34510. int newIndex = -1;
  34511. if (! c->isAlwaysOnTop())
  34512. {
  34513. newIndex = desktopComponents.size();
  34514. while (newIndex > 0 && desktopComponents.getUnchecked (newIndex - 1)->isAlwaysOnTop())
  34515. --newIndex;
  34516. --newIndex;
  34517. }
  34518. desktopComponents.move (index, newIndex);
  34519. }
  34520. }
  34521. const Point<int> Desktop::getLastMouseDownPosition() throw()
  34522. {
  34523. return getInstance().getMainMouseSource().getLastMouseDownPosition();
  34524. }
  34525. int Desktop::getMouseButtonClickCounter() throw()
  34526. {
  34527. return getInstance().mouseClickCounter;
  34528. }
  34529. void Desktop::incrementMouseClickCounter() throw()
  34530. {
  34531. ++mouseClickCounter;
  34532. }
  34533. int Desktop::getNumDraggingMouseSources() const throw()
  34534. {
  34535. int num = 0;
  34536. for (int i = mouseSources.size(); --i >= 0;)
  34537. if (mouseSources.getUnchecked(i)->isDragging())
  34538. ++num;
  34539. return num;
  34540. }
  34541. MouseInputSource* Desktop::getDraggingMouseSource (int index) const throw()
  34542. {
  34543. int num = 0;
  34544. for (int i = mouseSources.size(); --i >= 0;)
  34545. {
  34546. MouseInputSource* const mi = mouseSources.getUnchecked(i);
  34547. if (mi->isDragging())
  34548. {
  34549. if (index == num)
  34550. return mi;
  34551. ++num;
  34552. }
  34553. }
  34554. return 0;
  34555. }
  34556. void Desktop::addFocusChangeListener (FocusChangeListener* const listener)
  34557. {
  34558. focusListeners.add (listener);
  34559. }
  34560. void Desktop::removeFocusChangeListener (FocusChangeListener* const listener)
  34561. {
  34562. focusListeners.remove (listener);
  34563. }
  34564. void Desktop::triggerFocusCallback()
  34565. {
  34566. triggerAsyncUpdate();
  34567. }
  34568. void Desktop::handleAsyncUpdate()
  34569. {
  34570. Component* currentFocus = Component::getCurrentlyFocusedComponent();
  34571. focusListeners.call (&FocusChangeListener::globalFocusChanged, currentFocus);
  34572. }
  34573. void Desktop::addGlobalMouseListener (MouseListener* const listener)
  34574. {
  34575. mouseListeners.add (listener);
  34576. resetTimer();
  34577. }
  34578. void Desktop::removeGlobalMouseListener (MouseListener* const listener)
  34579. {
  34580. mouseListeners.remove (listener);
  34581. resetTimer();
  34582. }
  34583. void Desktop::timerCallback()
  34584. {
  34585. if (lastFakeMouseMove != getMousePosition())
  34586. sendMouseMove();
  34587. }
  34588. void Desktop::sendMouseMove()
  34589. {
  34590. if (! mouseListeners.isEmpty())
  34591. {
  34592. startTimer (20);
  34593. lastFakeMouseMove = getMousePosition();
  34594. Component* const target = findComponentAt (lastFakeMouseMove);
  34595. if (target != 0)
  34596. {
  34597. Component::BailOutChecker checker (target);
  34598. const Point<int> pos (target->globalPositionToRelative (lastFakeMouseMove));
  34599. const Time now (Time::getCurrentTime());
  34600. const MouseEvent me (getMainMouseSource(), pos, ModifierKeys::getCurrentModifiers(),
  34601. target, target, now, pos, now, 0, false);
  34602. if (me.mods.isAnyMouseButtonDown())
  34603. mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  34604. else
  34605. mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  34606. }
  34607. }
  34608. }
  34609. void Desktop::resetTimer()
  34610. {
  34611. if (mouseListeners.size() == 0)
  34612. stopTimer();
  34613. else
  34614. startTimer (100);
  34615. lastFakeMouseMove = getMousePosition();
  34616. }
  34617. extern void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars);
  34618. void Desktop::setKioskModeComponent (Component* componentToUse, const bool allowMenusAndBars)
  34619. {
  34620. if (kioskModeComponent != componentToUse)
  34621. {
  34622. // agh! Don't delete a component without first stopping it being the kiosk comp
  34623. jassert (kioskModeComponent == 0 || kioskModeComponent->isValidComponent());
  34624. // agh! Don't remove a component from the desktop if it's the kiosk comp!
  34625. jassert (kioskModeComponent == 0 || kioskModeComponent->isOnDesktop());
  34626. if (kioskModeComponent->isValidComponent())
  34627. {
  34628. juce_setKioskComponent (kioskModeComponent, false, allowMenusAndBars);
  34629. kioskModeComponent->setBounds (kioskComponentOriginalBounds);
  34630. }
  34631. kioskModeComponent = componentToUse;
  34632. if (kioskModeComponent != 0)
  34633. {
  34634. jassert (kioskModeComponent->isValidComponent());
  34635. // Only components that are already on the desktop can be put into kiosk mode!
  34636. jassert (kioskModeComponent->isOnDesktop());
  34637. kioskComponentOriginalBounds = kioskModeComponent->getBounds();
  34638. juce_setKioskComponent (kioskModeComponent, true, allowMenusAndBars);
  34639. }
  34640. }
  34641. }
  34642. void Desktop::setOrientationsEnabled (const int newOrientations)
  34643. {
  34644. // Dodgy set of flags being passed here! Make sure you specify at least one permitted orientation.
  34645. jassert (newOrientations != 0 && (newOrientations & ~allOrientations) == 0);
  34646. allowedOrientations = newOrientations;
  34647. }
  34648. bool Desktop::isOrientationEnabled (const DisplayOrientation orientation) const throw()
  34649. {
  34650. // Make sure you only pass one valid flag in here...
  34651. jassert (orientation == upright || orientation == upsideDown || orientation == rotatedClockwise || orientation == rotatedAntiClockwise);
  34652. return (allowedOrientations & orientation) != 0;
  34653. }
  34654. END_JUCE_NAMESPACE
  34655. /*** End of inlined file: juce_Desktop.cpp ***/
  34656. /*** Start of inlined file: juce_ModalComponentManager.cpp ***/
  34657. BEGIN_JUCE_NAMESPACE
  34658. class ModalComponentManager::ModalItem : public ComponentListener
  34659. {
  34660. public:
  34661. ModalItem (Component* const comp, Callback* const callback)
  34662. : component (comp), returnValue (0), isActive (true), isDeleted (false)
  34663. {
  34664. if (callback != 0)
  34665. callbacks.add (callback);
  34666. jassert (comp != 0);
  34667. component->addComponentListener (this);
  34668. }
  34669. ~ModalItem()
  34670. {
  34671. if (! isDeleted)
  34672. component->removeComponentListener (this);
  34673. }
  34674. void componentBeingDeleted (Component&)
  34675. {
  34676. isDeleted = true;
  34677. cancel();
  34678. }
  34679. void componentVisibilityChanged (Component&)
  34680. {
  34681. if (! component->isShowing())
  34682. cancel();
  34683. }
  34684. void componentParentHierarchyChanged (Component&)
  34685. {
  34686. if (! component->isShowing())
  34687. cancel();
  34688. }
  34689. void cancel()
  34690. {
  34691. if (isActive)
  34692. {
  34693. isActive = false;
  34694. ModalComponentManager::getInstance()->triggerAsyncUpdate();
  34695. }
  34696. }
  34697. Component* component;
  34698. OwnedArray<Callback> callbacks;
  34699. int returnValue;
  34700. bool isActive, isDeleted;
  34701. private:
  34702. ModalItem (const ModalItem&);
  34703. ModalItem& operator= (const ModalItem&);
  34704. };
  34705. ModalComponentManager::ModalComponentManager()
  34706. {
  34707. }
  34708. ModalComponentManager::~ModalComponentManager()
  34709. {
  34710. clearSingletonInstance();
  34711. }
  34712. juce_ImplementSingleton_SingleThreaded (ModalComponentManager);
  34713. void ModalComponentManager::startModal (Component* component, Callback* callback)
  34714. {
  34715. if (component != 0)
  34716. stack.add (new ModalItem (component, callback));
  34717. }
  34718. void ModalComponentManager::attachCallback (Component* component, Callback* callback)
  34719. {
  34720. if (callback != 0)
  34721. {
  34722. ScopedPointer<Callback> callbackDeleter (callback);
  34723. for (int i = stack.size(); --i >= 0;)
  34724. {
  34725. ModalItem* const item = stack.getUnchecked(i);
  34726. if (item->component == component)
  34727. {
  34728. item->callbacks.add (callback);
  34729. callbackDeleter.release();
  34730. break;
  34731. }
  34732. }
  34733. }
  34734. }
  34735. void ModalComponentManager::endModal (Component* component)
  34736. {
  34737. for (int i = stack.size(); --i >= 0;)
  34738. {
  34739. ModalItem* const item = stack.getUnchecked(i);
  34740. if (item->component == component)
  34741. item->cancel();
  34742. }
  34743. }
  34744. void ModalComponentManager::endModal (Component* component, int returnValue)
  34745. {
  34746. for (int i = stack.size(); --i >= 0;)
  34747. {
  34748. ModalItem* const item = stack.getUnchecked(i);
  34749. if (item->component == component)
  34750. {
  34751. item->returnValue = returnValue;
  34752. item->cancel();
  34753. }
  34754. }
  34755. }
  34756. int ModalComponentManager::getNumModalComponents() const
  34757. {
  34758. int n = 0;
  34759. for (int i = 0; i < stack.size(); ++i)
  34760. if (stack.getUnchecked(i)->isActive)
  34761. ++n;
  34762. return n;
  34763. }
  34764. Component* ModalComponentManager::getModalComponent (const int index) const
  34765. {
  34766. int n = 0;
  34767. for (int i = stack.size(); --i >= 0;)
  34768. {
  34769. const ModalItem* const item = stack.getUnchecked(i);
  34770. if (item->isActive)
  34771. if (n++ == index)
  34772. return item->component;
  34773. }
  34774. return 0;
  34775. }
  34776. bool ModalComponentManager::isModal (Component* const comp) const
  34777. {
  34778. for (int i = stack.size(); --i >= 0;)
  34779. {
  34780. const ModalItem* const item = stack.getUnchecked(i);
  34781. if (item->isActive && item->component == comp)
  34782. return true;
  34783. }
  34784. return false;
  34785. }
  34786. bool ModalComponentManager::isFrontModalComponent (Component* const comp) const
  34787. {
  34788. return comp == getModalComponent (0);
  34789. }
  34790. void ModalComponentManager::handleAsyncUpdate()
  34791. {
  34792. for (int i = stack.size(); --i >= 0;)
  34793. {
  34794. const ModalItem* const item = stack.getUnchecked(i);
  34795. if (! item->isActive)
  34796. {
  34797. for (int j = item->callbacks.size(); --j >= 0;)
  34798. item->callbacks.getUnchecked(j)->modalStateFinished (item->returnValue);
  34799. stack.remove (i);
  34800. }
  34801. }
  34802. }
  34803. class ModalComponentManager::ReturnValueRetriever : public ModalComponentManager::Callback
  34804. {
  34805. public:
  34806. ReturnValueRetriever (int& value_, bool& finished_) : value (value_), finished (finished_) {}
  34807. ~ReturnValueRetriever() {}
  34808. void modalStateFinished (int returnValue)
  34809. {
  34810. finished = true;
  34811. value = returnValue;
  34812. }
  34813. private:
  34814. int& value;
  34815. bool& finished;
  34816. ReturnValueRetriever (const ReturnValueRetriever&);
  34817. ReturnValueRetriever& operator= (const ReturnValueRetriever&);
  34818. };
  34819. int ModalComponentManager::runEventLoopForCurrentComponent()
  34820. {
  34821. // This can only be run from the message thread!
  34822. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  34823. Component* currentlyModal = getModalComponent (0);
  34824. if (currentlyModal == 0)
  34825. return 0;
  34826. Component::SafePointer<Component> prevFocused (Component::getCurrentlyFocusedComponent());
  34827. int returnValue = 0;
  34828. bool finished = false;
  34829. attachCallback (currentlyModal, new ReturnValueRetriever (returnValue, finished));
  34830. JUCE_TRY
  34831. {
  34832. while (! finished)
  34833. {
  34834. if (! MessageManager::getInstance()->runDispatchLoopUntil (20))
  34835. break;
  34836. }
  34837. }
  34838. JUCE_CATCH_EXCEPTION
  34839. if (prevFocused != 0)
  34840. prevFocused->grabKeyboardFocus();
  34841. return returnValue;
  34842. }
  34843. END_JUCE_NAMESPACE
  34844. /*** End of inlined file: juce_ModalComponentManager.cpp ***/
  34845. /*** Start of inlined file: juce_ArrowButton.cpp ***/
  34846. BEGIN_JUCE_NAMESPACE
  34847. ArrowButton::ArrowButton (const String& name,
  34848. float arrowDirectionInRadians,
  34849. const Colour& arrowColour)
  34850. : Button (name),
  34851. colour (arrowColour)
  34852. {
  34853. path.lineTo (0.0f, 1.0f);
  34854. path.lineTo (1.0f, 0.5f);
  34855. path.closeSubPath();
  34856. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * arrowDirectionInRadians,
  34857. 0.5f, 0.5f));
  34858. setComponentEffect (&shadow);
  34859. buttonStateChanged();
  34860. }
  34861. ArrowButton::~ArrowButton()
  34862. {
  34863. }
  34864. void ArrowButton::paintButton (Graphics& g,
  34865. bool /*isMouseOverButton*/,
  34866. bool /*isButtonDown*/)
  34867. {
  34868. g.setColour (colour);
  34869. g.fillPath (path, path.getTransformToScaleToFit ((float) offset,
  34870. (float) offset,
  34871. (float) (getWidth() - 3),
  34872. (float) (getHeight() - 3),
  34873. false));
  34874. }
  34875. void ArrowButton::buttonStateChanged()
  34876. {
  34877. offset = (isDown()) ? 1 : 0;
  34878. shadow.setShadowProperties ((isDown()) ? 1.2f : 3.0f,
  34879. 0.3f, -1, 0);
  34880. }
  34881. END_JUCE_NAMESPACE
  34882. /*** End of inlined file: juce_ArrowButton.cpp ***/
  34883. /*** Start of inlined file: juce_Button.cpp ***/
  34884. BEGIN_JUCE_NAMESPACE
  34885. class Button::RepeatTimer : public Timer
  34886. {
  34887. public:
  34888. RepeatTimer (Button& owner_) : owner (owner_) {}
  34889. void timerCallback() { owner.repeatTimerCallback(); }
  34890. juce_UseDebuggingNewOperator
  34891. private:
  34892. Button& owner;
  34893. RepeatTimer (const RepeatTimer&);
  34894. RepeatTimer& operator= (const RepeatTimer&);
  34895. };
  34896. Button::Button (const String& name)
  34897. : Component (name),
  34898. text (name),
  34899. buttonPressTime (0),
  34900. lastTimeCallbackTime (0),
  34901. commandManagerToUse (0),
  34902. autoRepeatDelay (-1),
  34903. autoRepeatSpeed (0),
  34904. autoRepeatMinimumDelay (-1),
  34905. radioGroupId (0),
  34906. commandID (0),
  34907. connectedEdgeFlags (0),
  34908. buttonState (buttonNormal),
  34909. lastToggleState (false),
  34910. clickTogglesState (false),
  34911. needsToRelease (false),
  34912. needsRepainting (false),
  34913. isKeyDown (false),
  34914. triggerOnMouseDown (false),
  34915. generateTooltip (false)
  34916. {
  34917. setWantsKeyboardFocus (true);
  34918. isOn.addListener (this);
  34919. }
  34920. Button::~Button()
  34921. {
  34922. isOn.removeListener (this);
  34923. if (commandManagerToUse != 0)
  34924. commandManagerToUse->removeListener (this);
  34925. repeatTimer = 0;
  34926. clearShortcuts();
  34927. }
  34928. void Button::setButtonText (const String& newText)
  34929. {
  34930. if (text != newText)
  34931. {
  34932. text = newText;
  34933. repaint();
  34934. }
  34935. }
  34936. void Button::setTooltip (const String& newTooltip)
  34937. {
  34938. SettableTooltipClient::setTooltip (newTooltip);
  34939. generateTooltip = false;
  34940. }
  34941. const String Button::getTooltip()
  34942. {
  34943. if (generateTooltip && commandManagerToUse != 0 && commandID != 0)
  34944. {
  34945. String tt (commandManagerToUse->getDescriptionOfCommand (commandID));
  34946. Array <KeyPress> keyPresses (commandManagerToUse->getKeyMappings()->getKeyPressesAssignedToCommand (commandID));
  34947. for (int i = 0; i < keyPresses.size(); ++i)
  34948. {
  34949. const String key (keyPresses.getReference(i).getTextDescription());
  34950. tt << " [";
  34951. if (key.length() == 1)
  34952. tt << TRANS("shortcut") << ": '" << key << "']";
  34953. else
  34954. tt << key << ']';
  34955. }
  34956. return tt;
  34957. }
  34958. return SettableTooltipClient::getTooltip();
  34959. }
  34960. void Button::setConnectedEdges (const int connectedEdgeFlags_)
  34961. {
  34962. if (connectedEdgeFlags != connectedEdgeFlags_)
  34963. {
  34964. connectedEdgeFlags = connectedEdgeFlags_;
  34965. repaint();
  34966. }
  34967. }
  34968. void Button::setToggleState (const bool shouldBeOn,
  34969. const bool sendChangeNotification)
  34970. {
  34971. if (shouldBeOn != lastToggleState)
  34972. {
  34973. if (isOn != shouldBeOn) // this test means that if the value is void rather than explicitly set to
  34974. isOn = shouldBeOn; // false, it won't be changed unless the required value is true.
  34975. lastToggleState = shouldBeOn;
  34976. repaint();
  34977. if (sendChangeNotification)
  34978. {
  34979. Component::SafePointer<Component> deletionWatcher (this);
  34980. sendClickMessage (ModifierKeys());
  34981. if (deletionWatcher == 0)
  34982. return;
  34983. }
  34984. if (lastToggleState)
  34985. turnOffOtherButtonsInGroup (sendChangeNotification);
  34986. }
  34987. }
  34988. void Button::setClickingTogglesState (const bool shouldToggle) throw()
  34989. {
  34990. clickTogglesState = shouldToggle;
  34991. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  34992. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  34993. // it is that this button represents, and the button will update its state to reflect this
  34994. // in the applicationCommandListChanged() method.
  34995. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  34996. }
  34997. bool Button::getClickingTogglesState() const throw()
  34998. {
  34999. return clickTogglesState;
  35000. }
  35001. void Button::valueChanged (Value& value)
  35002. {
  35003. if (value.refersToSameSourceAs (isOn))
  35004. setToggleState (isOn.getValue(), true);
  35005. }
  35006. void Button::setRadioGroupId (const int newGroupId)
  35007. {
  35008. if (radioGroupId != newGroupId)
  35009. {
  35010. radioGroupId = newGroupId;
  35011. if (lastToggleState)
  35012. turnOffOtherButtonsInGroup (true);
  35013. }
  35014. }
  35015. void Button::turnOffOtherButtonsInGroup (const bool sendChangeNotification)
  35016. {
  35017. Component* const p = getParentComponent();
  35018. if (p != 0 && radioGroupId != 0)
  35019. {
  35020. Component::SafePointer<Component> deletionWatcher (this);
  35021. for (int i = p->getNumChildComponents(); --i >= 0;)
  35022. {
  35023. Component* const c = p->getChildComponent (i);
  35024. if (c != this)
  35025. {
  35026. Button* const b = dynamic_cast <Button*> (c);
  35027. if (b != 0 && b->getRadioGroupId() == radioGroupId)
  35028. {
  35029. b->setToggleState (false, sendChangeNotification);
  35030. if (deletionWatcher == 0)
  35031. return;
  35032. }
  35033. }
  35034. }
  35035. }
  35036. }
  35037. void Button::enablementChanged()
  35038. {
  35039. updateState (0);
  35040. repaint();
  35041. }
  35042. Button::ButtonState Button::updateState (const MouseEvent* const e)
  35043. {
  35044. ButtonState state = buttonNormal;
  35045. if (isEnabled() && isVisible() && ! isCurrentlyBlockedByAnotherModalComponent())
  35046. {
  35047. Point<int> mousePos;
  35048. if (e == 0)
  35049. mousePos = getMouseXYRelative();
  35050. else
  35051. mousePos = e->getEventRelativeTo (this).getPosition();
  35052. const bool over = reallyContains (mousePos.getX(), mousePos.getY(), true);
  35053. const bool down = isMouseButtonDown();
  35054. if ((down && (over || (triggerOnMouseDown && buttonState == buttonDown))) || isKeyDown)
  35055. state = buttonDown;
  35056. else if (over)
  35057. state = buttonOver;
  35058. }
  35059. setState (state);
  35060. return state;
  35061. }
  35062. void Button::setState (const ButtonState newState)
  35063. {
  35064. if (buttonState != newState)
  35065. {
  35066. buttonState = newState;
  35067. repaint();
  35068. if (buttonState == buttonDown)
  35069. {
  35070. buttonPressTime = Time::getApproximateMillisecondCounter();
  35071. lastTimeCallbackTime = buttonPressTime;
  35072. }
  35073. sendStateMessage();
  35074. }
  35075. }
  35076. bool Button::isDown() const throw()
  35077. {
  35078. return buttonState == buttonDown;
  35079. }
  35080. bool Button::isOver() const throw()
  35081. {
  35082. return buttonState != buttonNormal;
  35083. }
  35084. void Button::buttonStateChanged()
  35085. {
  35086. }
  35087. uint32 Button::getMillisecondsSinceButtonDown() const throw()
  35088. {
  35089. const uint32 now = Time::getApproximateMillisecondCounter();
  35090. return now > buttonPressTime ? now - buttonPressTime : 0;
  35091. }
  35092. void Button::setTriggeredOnMouseDown (const bool isTriggeredOnMouseDown) throw()
  35093. {
  35094. triggerOnMouseDown = isTriggeredOnMouseDown;
  35095. }
  35096. void Button::clicked()
  35097. {
  35098. }
  35099. void Button::clicked (const ModifierKeys& /*modifiers*/)
  35100. {
  35101. clicked();
  35102. }
  35103. static const int clickMessageId = 0x2f3f4f99;
  35104. void Button::triggerClick()
  35105. {
  35106. postCommandMessage (clickMessageId);
  35107. }
  35108. void Button::internalClickCallback (const ModifierKeys& modifiers)
  35109. {
  35110. if (clickTogglesState)
  35111. setToggleState ((radioGroupId != 0) || ! lastToggleState, false);
  35112. sendClickMessage (modifiers);
  35113. }
  35114. void Button::flashButtonState()
  35115. {
  35116. if (isEnabled())
  35117. {
  35118. needsToRelease = true;
  35119. setState (buttonDown);
  35120. getRepeatTimer().startTimer (100);
  35121. }
  35122. }
  35123. void Button::handleCommandMessage (int commandId)
  35124. {
  35125. if (commandId == clickMessageId)
  35126. {
  35127. if (isEnabled())
  35128. {
  35129. flashButtonState();
  35130. internalClickCallback (ModifierKeys::getCurrentModifiers());
  35131. }
  35132. }
  35133. else
  35134. {
  35135. Component::handleCommandMessage (commandId);
  35136. }
  35137. }
  35138. void Button::addButtonListener (Listener* const newListener)
  35139. {
  35140. buttonListeners.add (newListener);
  35141. }
  35142. void Button::removeButtonListener (Listener* const listener)
  35143. {
  35144. buttonListeners.remove (listener);
  35145. }
  35146. void Button::sendClickMessage (const ModifierKeys& modifiers)
  35147. {
  35148. Component::BailOutChecker checker (this);
  35149. if (commandManagerToUse != 0 && commandID != 0)
  35150. {
  35151. ApplicationCommandTarget::InvocationInfo info (commandID);
  35152. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromButton;
  35153. info.originatingComponent = this;
  35154. commandManagerToUse->invoke (info, true);
  35155. }
  35156. clicked (modifiers);
  35157. if (! checker.shouldBailOut())
  35158. buttonListeners.callChecked (checker, &ButtonListener::buttonClicked, this); // (can't use Button::Listener due to idiotic VC2005 bug)
  35159. }
  35160. void Button::sendStateMessage()
  35161. {
  35162. Component::BailOutChecker checker (this);
  35163. buttonStateChanged();
  35164. if (! checker.shouldBailOut())
  35165. buttonListeners.callChecked (checker, &ButtonListener::buttonStateChanged, this);
  35166. }
  35167. void Button::paint (Graphics& g)
  35168. {
  35169. if (needsToRelease && isEnabled())
  35170. {
  35171. needsToRelease = false;
  35172. needsRepainting = true;
  35173. }
  35174. paintButton (g, isOver(), isDown());
  35175. }
  35176. void Button::mouseEnter (const MouseEvent& e)
  35177. {
  35178. updateState (&e);
  35179. }
  35180. void Button::mouseExit (const MouseEvent& e)
  35181. {
  35182. updateState (&e);
  35183. }
  35184. void Button::mouseDown (const MouseEvent& e)
  35185. {
  35186. updateState (&e);
  35187. if (isDown())
  35188. {
  35189. if (autoRepeatDelay >= 0)
  35190. getRepeatTimer().startTimer (autoRepeatDelay);
  35191. if (triggerOnMouseDown)
  35192. internalClickCallback (e.mods);
  35193. }
  35194. }
  35195. void Button::mouseUp (const MouseEvent& e)
  35196. {
  35197. const bool wasDown = isDown();
  35198. updateState (&e);
  35199. if (wasDown && isOver() && ! triggerOnMouseDown)
  35200. internalClickCallback (e.mods);
  35201. }
  35202. void Button::mouseDrag (const MouseEvent& e)
  35203. {
  35204. const ButtonState oldState = buttonState;
  35205. updateState (&e);
  35206. if (autoRepeatDelay >= 0 && buttonState != oldState && isDown())
  35207. getRepeatTimer().startTimer (autoRepeatSpeed);
  35208. }
  35209. void Button::focusGained (FocusChangeType)
  35210. {
  35211. updateState (0);
  35212. repaint();
  35213. }
  35214. void Button::focusLost (FocusChangeType)
  35215. {
  35216. updateState (0);
  35217. repaint();
  35218. }
  35219. void Button::setVisible (bool shouldBeVisible)
  35220. {
  35221. if (shouldBeVisible != isVisible())
  35222. {
  35223. Component::setVisible (shouldBeVisible);
  35224. if (! shouldBeVisible)
  35225. needsToRelease = false;
  35226. updateState (0);
  35227. }
  35228. else
  35229. {
  35230. Component::setVisible (shouldBeVisible);
  35231. }
  35232. }
  35233. void Button::parentHierarchyChanged()
  35234. {
  35235. Component* const newKeySource = (shortcuts.size() == 0) ? 0 : getTopLevelComponent();
  35236. if (newKeySource != keySource.getComponent())
  35237. {
  35238. if (keySource != 0)
  35239. keySource->removeKeyListener (this);
  35240. keySource = newKeySource;
  35241. if (keySource != 0)
  35242. keySource->addKeyListener (this);
  35243. }
  35244. }
  35245. void Button::setCommandToTrigger (ApplicationCommandManager* const commandManagerToUse_,
  35246. const int commandID_,
  35247. const bool generateTooltip_)
  35248. {
  35249. commandID = commandID_;
  35250. generateTooltip = generateTooltip_;
  35251. if (commandManagerToUse != commandManagerToUse_)
  35252. {
  35253. if (commandManagerToUse != 0)
  35254. commandManagerToUse->removeListener (this);
  35255. commandManagerToUse = commandManagerToUse_;
  35256. if (commandManagerToUse != 0)
  35257. commandManagerToUse->addListener (this);
  35258. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  35259. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  35260. // it is that this button represents, and the button will update its state to reflect this
  35261. // in the applicationCommandListChanged() method.
  35262. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  35263. }
  35264. if (commandManagerToUse != 0)
  35265. applicationCommandListChanged();
  35266. else
  35267. setEnabled (true);
  35268. }
  35269. void Button::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  35270. {
  35271. if (info.commandID == commandID
  35272. && (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) == 0)
  35273. {
  35274. flashButtonState();
  35275. }
  35276. }
  35277. void Button::applicationCommandListChanged()
  35278. {
  35279. if (commandManagerToUse != 0)
  35280. {
  35281. ApplicationCommandInfo info (0);
  35282. ApplicationCommandTarget* const target = commandManagerToUse->getTargetForCommand (commandID, info);
  35283. setEnabled (target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0);
  35284. if (target != 0)
  35285. setToggleState ((info.flags & ApplicationCommandInfo::isTicked) != 0, false);
  35286. }
  35287. }
  35288. void Button::addShortcut (const KeyPress& key)
  35289. {
  35290. if (key.isValid())
  35291. {
  35292. jassert (! isRegisteredForShortcut (key)); // already registered!
  35293. shortcuts.add (key);
  35294. parentHierarchyChanged();
  35295. }
  35296. }
  35297. void Button::clearShortcuts()
  35298. {
  35299. shortcuts.clear();
  35300. parentHierarchyChanged();
  35301. }
  35302. bool Button::isShortcutPressed() const
  35303. {
  35304. if (! isCurrentlyBlockedByAnotherModalComponent())
  35305. {
  35306. for (int i = shortcuts.size(); --i >= 0;)
  35307. if (shortcuts.getReference(i).isCurrentlyDown())
  35308. return true;
  35309. }
  35310. return false;
  35311. }
  35312. bool Button::isRegisteredForShortcut (const KeyPress& key) const
  35313. {
  35314. for (int i = shortcuts.size(); --i >= 0;)
  35315. if (key == shortcuts.getReference(i))
  35316. return true;
  35317. return false;
  35318. }
  35319. bool Button::keyStateChanged (const bool, Component*)
  35320. {
  35321. if (! isEnabled())
  35322. return false;
  35323. const bool wasDown = isKeyDown;
  35324. isKeyDown = isShortcutPressed();
  35325. if (autoRepeatDelay >= 0 && (isKeyDown && ! wasDown))
  35326. getRepeatTimer().startTimer (autoRepeatDelay);
  35327. updateState (0);
  35328. if (isEnabled() && wasDown && ! isKeyDown)
  35329. {
  35330. internalClickCallback (ModifierKeys::getCurrentModifiers());
  35331. // (return immediately - this button may now have been deleted)
  35332. return true;
  35333. }
  35334. return wasDown || isKeyDown;
  35335. }
  35336. bool Button::keyPressed (const KeyPress&, Component*)
  35337. {
  35338. // returning true will avoid forwarding events for keys that we're using as shortcuts
  35339. return isShortcutPressed();
  35340. }
  35341. bool Button::keyPressed (const KeyPress& key)
  35342. {
  35343. if (isEnabled() && key.isKeyCode (KeyPress::returnKey))
  35344. {
  35345. triggerClick();
  35346. return true;
  35347. }
  35348. return false;
  35349. }
  35350. void Button::setRepeatSpeed (const int initialDelayMillisecs,
  35351. const int repeatMillisecs,
  35352. const int minimumDelayInMillisecs) throw()
  35353. {
  35354. autoRepeatDelay = initialDelayMillisecs;
  35355. autoRepeatSpeed = repeatMillisecs;
  35356. autoRepeatMinimumDelay = jmin (autoRepeatSpeed, minimumDelayInMillisecs);
  35357. }
  35358. void Button::repeatTimerCallback()
  35359. {
  35360. if (needsRepainting)
  35361. {
  35362. getRepeatTimer().stopTimer();
  35363. updateState (0);
  35364. needsRepainting = false;
  35365. }
  35366. else if (autoRepeatSpeed > 0 && (isKeyDown || (updateState (0) == buttonDown)))
  35367. {
  35368. int repeatSpeed = autoRepeatSpeed;
  35369. if (autoRepeatMinimumDelay >= 0)
  35370. {
  35371. double timeHeldDown = jmin (1.0, getMillisecondsSinceButtonDown() / 4000.0);
  35372. timeHeldDown *= timeHeldDown;
  35373. repeatSpeed = repeatSpeed + (int) (timeHeldDown * (autoRepeatMinimumDelay - repeatSpeed));
  35374. }
  35375. repeatSpeed = jmax (1, repeatSpeed);
  35376. getRepeatTimer().startTimer (repeatSpeed);
  35377. const uint32 now = Time::getApproximateMillisecondCounter();
  35378. const int numTimesToCallback = (now > lastTimeCallbackTime) ? jmax (1, (int) (now - lastTimeCallbackTime) / repeatSpeed) : 1;
  35379. lastTimeCallbackTime = now;
  35380. Component::SafePointer<Component> deletionWatcher (this);
  35381. for (int i = numTimesToCallback; --i >= 0;)
  35382. {
  35383. internalClickCallback (ModifierKeys::getCurrentModifiers());
  35384. if (deletionWatcher == 0 || ! isDown())
  35385. return;
  35386. }
  35387. }
  35388. else if (! needsToRelease)
  35389. {
  35390. getRepeatTimer().stopTimer();
  35391. }
  35392. }
  35393. Button::RepeatTimer& Button::getRepeatTimer()
  35394. {
  35395. if (repeatTimer == 0)
  35396. repeatTimer = new RepeatTimer (*this);
  35397. return *repeatTimer;
  35398. }
  35399. END_JUCE_NAMESPACE
  35400. /*** End of inlined file: juce_Button.cpp ***/
  35401. /*** Start of inlined file: juce_DrawableButton.cpp ***/
  35402. BEGIN_JUCE_NAMESPACE
  35403. DrawableButton::DrawableButton (const String& name,
  35404. const DrawableButton::ButtonStyle buttonStyle)
  35405. : Button (name),
  35406. style (buttonStyle),
  35407. edgeIndent (3)
  35408. {
  35409. if (buttonStyle == ImageOnButtonBackground)
  35410. {
  35411. backgroundOff = Colour (0xffbbbbff);
  35412. backgroundOn = Colour (0xff3333ff);
  35413. }
  35414. else
  35415. {
  35416. backgroundOff = Colours::transparentBlack;
  35417. backgroundOn = Colour (0xaabbbbff);
  35418. }
  35419. }
  35420. DrawableButton::~DrawableButton()
  35421. {
  35422. deleteImages();
  35423. }
  35424. void DrawableButton::deleteImages()
  35425. {
  35426. }
  35427. void DrawableButton::setImages (const Drawable* normal,
  35428. const Drawable* over,
  35429. const Drawable* down,
  35430. const Drawable* disabled,
  35431. const Drawable* normalOn,
  35432. const Drawable* overOn,
  35433. const Drawable* downOn,
  35434. const Drawable* disabledOn)
  35435. {
  35436. deleteImages();
  35437. jassert (normal != 0); // you really need to give it at least a normal image..
  35438. if (normal != 0)
  35439. normalImage = normal->createCopy();
  35440. if (over != 0)
  35441. overImage = over->createCopy();
  35442. if (down != 0)
  35443. downImage = down->createCopy();
  35444. if (disabled != 0)
  35445. disabledImage = disabled->createCopy();
  35446. if (normalOn != 0)
  35447. normalImageOn = normalOn->createCopy();
  35448. if (overOn != 0)
  35449. overImageOn = overOn->createCopy();
  35450. if (downOn != 0)
  35451. downImageOn = downOn->createCopy();
  35452. if (disabledOn != 0)
  35453. disabledImageOn = disabledOn->createCopy();
  35454. repaint();
  35455. }
  35456. void DrawableButton::setButtonStyle (const DrawableButton::ButtonStyle newStyle)
  35457. {
  35458. if (style != newStyle)
  35459. {
  35460. style = newStyle;
  35461. repaint();
  35462. }
  35463. }
  35464. void DrawableButton::setBackgroundColours (const Colour& toggledOffColour,
  35465. const Colour& toggledOnColour)
  35466. {
  35467. if (backgroundOff != toggledOffColour
  35468. || backgroundOn != toggledOnColour)
  35469. {
  35470. backgroundOff = toggledOffColour;
  35471. backgroundOn = toggledOnColour;
  35472. repaint();
  35473. }
  35474. }
  35475. const Colour& DrawableButton::getBackgroundColour() const throw()
  35476. {
  35477. return getToggleState() ? backgroundOn
  35478. : backgroundOff;
  35479. }
  35480. void DrawableButton::setEdgeIndent (const int numPixelsIndent)
  35481. {
  35482. edgeIndent = numPixelsIndent;
  35483. repaint();
  35484. }
  35485. void DrawableButton::paintButton (Graphics& g,
  35486. bool isMouseOverButton,
  35487. bool isButtonDown)
  35488. {
  35489. Rectangle<int> imageSpace;
  35490. if (style == ImageOnButtonBackground)
  35491. {
  35492. const int insetX = getWidth() / 4;
  35493. const int insetY = getHeight() / 4;
  35494. imageSpace.setBounds (insetX, insetY, getWidth() - insetX * 2, getHeight() - insetY * 2);
  35495. getLookAndFeel().drawButtonBackground (g, *this,
  35496. getBackgroundColour(),
  35497. isMouseOverButton,
  35498. isButtonDown);
  35499. }
  35500. else
  35501. {
  35502. g.fillAll (getBackgroundColour());
  35503. const int textH = (style == ImageAboveTextLabel)
  35504. ? jmin (16, proportionOfHeight (0.25f))
  35505. : 0;
  35506. const int indentX = jmin (edgeIndent, proportionOfWidth (0.3f));
  35507. const int indentY = jmin (edgeIndent, proportionOfHeight (0.3f));
  35508. imageSpace.setBounds (indentX, indentY,
  35509. getWidth() - indentX * 2,
  35510. getHeight() - indentY * 2 - textH);
  35511. if (textH > 0)
  35512. {
  35513. g.setFont ((float) textH);
  35514. g.setColour (findColour (DrawableButton::textColourId)
  35515. .withMultipliedAlpha (isEnabled() ? 1.0f : 0.4f));
  35516. g.drawFittedText (getButtonText(),
  35517. 2, getHeight() - textH - 1,
  35518. getWidth() - 4, textH,
  35519. Justification::centred, 1);
  35520. }
  35521. }
  35522. g.setImageResamplingQuality (Graphics::mediumResamplingQuality);
  35523. g.setOpacity (1.0f);
  35524. const Drawable* imageToDraw = 0;
  35525. if (isEnabled())
  35526. {
  35527. imageToDraw = getCurrentImage();
  35528. }
  35529. else
  35530. {
  35531. imageToDraw = getToggleState() ? disabledImageOn
  35532. : disabledImage;
  35533. if (imageToDraw == 0)
  35534. {
  35535. g.setOpacity (0.4f);
  35536. imageToDraw = getNormalImage();
  35537. }
  35538. }
  35539. if (imageToDraw != 0)
  35540. {
  35541. if (style == ImageRaw)
  35542. imageToDraw->draw (g, 1.0f);
  35543. else
  35544. imageToDraw->drawWithin (g, imageSpace.toFloat(), RectanglePlacement::centred, 1.0f);
  35545. }
  35546. }
  35547. const Drawable* DrawableButton::getCurrentImage() const throw()
  35548. {
  35549. if (isDown())
  35550. return getDownImage();
  35551. if (isOver())
  35552. return getOverImage();
  35553. return getNormalImage();
  35554. }
  35555. const Drawable* DrawableButton::getNormalImage() const throw()
  35556. {
  35557. return (getToggleState() && normalImageOn != 0) ? normalImageOn
  35558. : normalImage;
  35559. }
  35560. const Drawable* DrawableButton::getOverImage() const throw()
  35561. {
  35562. const Drawable* d = normalImage;
  35563. if (getToggleState())
  35564. {
  35565. if (overImageOn != 0)
  35566. d = overImageOn;
  35567. else if (normalImageOn != 0)
  35568. d = normalImageOn;
  35569. else if (overImage != 0)
  35570. d = overImage;
  35571. }
  35572. else
  35573. {
  35574. if (overImage != 0)
  35575. d = overImage;
  35576. }
  35577. return d;
  35578. }
  35579. const Drawable* DrawableButton::getDownImage() const throw()
  35580. {
  35581. const Drawable* d = normalImage;
  35582. if (getToggleState())
  35583. {
  35584. if (downImageOn != 0)
  35585. d = downImageOn;
  35586. else if (overImageOn != 0)
  35587. d = overImageOn;
  35588. else if (normalImageOn != 0)
  35589. d = normalImageOn;
  35590. else if (downImage != 0)
  35591. d = downImage;
  35592. else
  35593. d = getOverImage();
  35594. }
  35595. else
  35596. {
  35597. if (downImage != 0)
  35598. d = downImage;
  35599. else
  35600. d = getOverImage();
  35601. }
  35602. return d;
  35603. }
  35604. END_JUCE_NAMESPACE
  35605. /*** End of inlined file: juce_DrawableButton.cpp ***/
  35606. /*** Start of inlined file: juce_HyperlinkButton.cpp ***/
  35607. BEGIN_JUCE_NAMESPACE
  35608. HyperlinkButton::HyperlinkButton (const String& linkText,
  35609. const URL& linkURL)
  35610. : Button (linkText),
  35611. url (linkURL),
  35612. font (14.0f, Font::underlined),
  35613. resizeFont (true),
  35614. justification (Justification::centred)
  35615. {
  35616. setMouseCursor (MouseCursor::PointingHandCursor);
  35617. setTooltip (linkURL.toString (false));
  35618. }
  35619. HyperlinkButton::~HyperlinkButton()
  35620. {
  35621. }
  35622. void HyperlinkButton::setFont (const Font& newFont,
  35623. const bool resizeToMatchComponentHeight,
  35624. const Justification& justificationType)
  35625. {
  35626. font = newFont;
  35627. resizeFont = resizeToMatchComponentHeight;
  35628. justification = justificationType;
  35629. repaint();
  35630. }
  35631. void HyperlinkButton::setURL (const URL& newURL) throw()
  35632. {
  35633. url = newURL;
  35634. setTooltip (newURL.toString (false));
  35635. }
  35636. const Font HyperlinkButton::getFontToUse() const
  35637. {
  35638. Font f (font);
  35639. if (resizeFont)
  35640. f.setHeight (getHeight() * 0.7f);
  35641. return f;
  35642. }
  35643. void HyperlinkButton::changeWidthToFitText()
  35644. {
  35645. setSize (getFontToUse().getStringWidth (getName()) + 6, getHeight());
  35646. }
  35647. void HyperlinkButton::colourChanged()
  35648. {
  35649. repaint();
  35650. }
  35651. void HyperlinkButton::clicked()
  35652. {
  35653. if (url.isWellFormed())
  35654. url.launchInDefaultBrowser();
  35655. }
  35656. void HyperlinkButton::paintButton (Graphics& g,
  35657. bool isMouseOverButton,
  35658. bool isButtonDown)
  35659. {
  35660. const Colour textColour (findColour (textColourId));
  35661. if (isEnabled())
  35662. g.setColour ((isMouseOverButton) ? textColour.darker ((isButtonDown) ? 1.3f : 0.4f)
  35663. : textColour);
  35664. else
  35665. g.setColour (textColour.withMultipliedAlpha (0.4f));
  35666. g.setFont (getFontToUse());
  35667. g.drawText (getButtonText(),
  35668. 2, 0, getWidth() - 2, getHeight(),
  35669. justification.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  35670. true);
  35671. }
  35672. END_JUCE_NAMESPACE
  35673. /*** End of inlined file: juce_HyperlinkButton.cpp ***/
  35674. /*** Start of inlined file: juce_ImageButton.cpp ***/
  35675. BEGIN_JUCE_NAMESPACE
  35676. ImageButton::ImageButton (const String& text_)
  35677. : Button (text_),
  35678. scaleImageToFit (true),
  35679. preserveProportions (true),
  35680. alphaThreshold (0),
  35681. imageX (0),
  35682. imageY (0),
  35683. imageW (0),
  35684. imageH (0),
  35685. normalImage (0),
  35686. overImage (0),
  35687. downImage (0)
  35688. {
  35689. }
  35690. ImageButton::~ImageButton()
  35691. {
  35692. }
  35693. void ImageButton::setImages (const bool resizeButtonNowToFitThisImage,
  35694. const bool rescaleImagesWhenButtonSizeChanges,
  35695. const bool preserveImageProportions,
  35696. const Image& normalImage_,
  35697. const float imageOpacityWhenNormal,
  35698. const Colour& overlayColourWhenNormal,
  35699. const Image& overImage_,
  35700. const float imageOpacityWhenOver,
  35701. const Colour& overlayColourWhenOver,
  35702. const Image& downImage_,
  35703. const float imageOpacityWhenDown,
  35704. const Colour& overlayColourWhenDown,
  35705. const float hitTestAlphaThreshold)
  35706. {
  35707. normalImage = normalImage_;
  35708. overImage = overImage_;
  35709. downImage = downImage_;
  35710. if (resizeButtonNowToFitThisImage && normalImage.isValid())
  35711. {
  35712. imageW = normalImage.getWidth();
  35713. imageH = normalImage.getHeight();
  35714. setSize (imageW, imageH);
  35715. }
  35716. scaleImageToFit = rescaleImagesWhenButtonSizeChanges;
  35717. preserveProportions = preserveImageProportions;
  35718. normalOpacity = imageOpacityWhenNormal;
  35719. normalOverlay = overlayColourWhenNormal;
  35720. overOpacity = imageOpacityWhenOver;
  35721. overOverlay = overlayColourWhenOver;
  35722. downOpacity = imageOpacityWhenDown;
  35723. downOverlay = overlayColourWhenDown;
  35724. alphaThreshold = (unsigned char) jlimit (0, 0xff, roundToInt (255.0f * hitTestAlphaThreshold));
  35725. repaint();
  35726. }
  35727. const Image ImageButton::getCurrentImage() const
  35728. {
  35729. if (isDown() || getToggleState())
  35730. return getDownImage();
  35731. if (isOver())
  35732. return getOverImage();
  35733. return getNormalImage();
  35734. }
  35735. const Image ImageButton::getNormalImage() const
  35736. {
  35737. return normalImage;
  35738. }
  35739. const Image ImageButton::getOverImage() const
  35740. {
  35741. return overImage.isValid() ? overImage
  35742. : normalImage;
  35743. }
  35744. const Image ImageButton::getDownImage() const
  35745. {
  35746. return downImage.isValid() ? downImage
  35747. : getOverImage();
  35748. }
  35749. void ImageButton::paintButton (Graphics& g,
  35750. bool isMouseOverButton,
  35751. bool isButtonDown)
  35752. {
  35753. if (! isEnabled())
  35754. {
  35755. isMouseOverButton = false;
  35756. isButtonDown = false;
  35757. }
  35758. Image im (getCurrentImage());
  35759. if (im.isValid())
  35760. {
  35761. const int iw = im.getWidth();
  35762. const int ih = im.getHeight();
  35763. imageW = getWidth();
  35764. imageH = getHeight();
  35765. imageX = (imageW - iw) >> 1;
  35766. imageY = (imageH - ih) >> 1;
  35767. if (scaleImageToFit)
  35768. {
  35769. if (preserveProportions)
  35770. {
  35771. int newW, newH;
  35772. const float imRatio = ih / (float)iw;
  35773. const float destRatio = imageH / (float)imageW;
  35774. if (imRatio > destRatio)
  35775. {
  35776. newW = roundToInt (imageH / imRatio);
  35777. newH = imageH;
  35778. }
  35779. else
  35780. {
  35781. newW = imageW;
  35782. newH = roundToInt (imageW * imRatio);
  35783. }
  35784. imageX = (imageW - newW) / 2;
  35785. imageY = (imageH - newH) / 2;
  35786. imageW = newW;
  35787. imageH = newH;
  35788. }
  35789. else
  35790. {
  35791. imageX = 0;
  35792. imageY = 0;
  35793. }
  35794. }
  35795. if (! scaleImageToFit)
  35796. {
  35797. imageW = iw;
  35798. imageH = ih;
  35799. }
  35800. getLookAndFeel().drawImageButton (g, &im, imageX, imageY, imageW, imageH,
  35801. isButtonDown ? downOverlay
  35802. : (isMouseOverButton ? overOverlay
  35803. : normalOverlay),
  35804. isButtonDown ? downOpacity
  35805. : (isMouseOverButton ? overOpacity
  35806. : normalOpacity),
  35807. *this);
  35808. }
  35809. }
  35810. bool ImageButton::hitTest (int x, int y)
  35811. {
  35812. if (alphaThreshold == 0)
  35813. return true;
  35814. Image im (getCurrentImage());
  35815. return im.isNull() || (imageW > 0 && imageH > 0
  35816. && alphaThreshold < im.getPixelAt (((x - imageX) * im.getWidth()) / imageW,
  35817. ((y - imageY) * im.getHeight()) / imageH).getAlpha());
  35818. }
  35819. END_JUCE_NAMESPACE
  35820. /*** End of inlined file: juce_ImageButton.cpp ***/
  35821. /*** Start of inlined file: juce_ShapeButton.cpp ***/
  35822. BEGIN_JUCE_NAMESPACE
  35823. ShapeButton::ShapeButton (const String& text_,
  35824. const Colour& normalColour_,
  35825. const Colour& overColour_,
  35826. const Colour& downColour_)
  35827. : Button (text_),
  35828. normalColour (normalColour_),
  35829. overColour (overColour_),
  35830. downColour (downColour_),
  35831. maintainShapeProportions (false),
  35832. outlineWidth (0.0f)
  35833. {
  35834. }
  35835. ShapeButton::~ShapeButton()
  35836. {
  35837. }
  35838. void ShapeButton::setColours (const Colour& newNormalColour,
  35839. const Colour& newOverColour,
  35840. const Colour& newDownColour)
  35841. {
  35842. normalColour = newNormalColour;
  35843. overColour = newOverColour;
  35844. downColour = newDownColour;
  35845. }
  35846. void ShapeButton::setOutline (const Colour& newOutlineColour,
  35847. const float newOutlineWidth)
  35848. {
  35849. outlineColour = newOutlineColour;
  35850. outlineWidth = newOutlineWidth;
  35851. }
  35852. void ShapeButton::setShape (const Path& newShape,
  35853. const bool resizeNowToFitThisShape,
  35854. const bool maintainShapeProportions_,
  35855. const bool hasShadow)
  35856. {
  35857. shape = newShape;
  35858. maintainShapeProportions = maintainShapeProportions_;
  35859. shadow.setShadowProperties (3.0f, 0.5f, 0, 0);
  35860. setComponentEffect ((hasShadow) ? &shadow : 0);
  35861. if (resizeNowToFitThisShape)
  35862. {
  35863. Rectangle<float> bounds (shape.getBounds());
  35864. if (hasShadow)
  35865. bounds.expand (4.0f, 4.0f);
  35866. shape.applyTransform (AffineTransform::translation (-bounds.getX(), -bounds.getY()));
  35867. setSize (1 + (int) (bounds.getWidth() + outlineWidth),
  35868. 1 + (int) (bounds.getHeight() + outlineWidth));
  35869. }
  35870. }
  35871. void ShapeButton::paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  35872. {
  35873. if (! isEnabled())
  35874. {
  35875. isMouseOverButton = false;
  35876. isButtonDown = false;
  35877. }
  35878. g.setColour ((isButtonDown) ? downColour
  35879. : (isMouseOverButton) ? overColour
  35880. : normalColour);
  35881. int w = getWidth();
  35882. int h = getHeight();
  35883. if (getComponentEffect() != 0)
  35884. {
  35885. w -= 4;
  35886. h -= 4;
  35887. }
  35888. const float offset = (outlineWidth * 0.5f) + (isButtonDown ? 1.5f : 0.0f);
  35889. const AffineTransform trans (shape.getTransformToScaleToFit (offset, offset,
  35890. w - offset - outlineWidth,
  35891. h - offset - outlineWidth,
  35892. maintainShapeProportions));
  35893. g.fillPath (shape, trans);
  35894. if (outlineWidth > 0.0f)
  35895. {
  35896. g.setColour (outlineColour);
  35897. g.strokePath (shape, PathStrokeType (outlineWidth), trans);
  35898. }
  35899. }
  35900. END_JUCE_NAMESPACE
  35901. /*** End of inlined file: juce_ShapeButton.cpp ***/
  35902. /*** Start of inlined file: juce_TextButton.cpp ***/
  35903. BEGIN_JUCE_NAMESPACE
  35904. TextButton::TextButton (const String& name,
  35905. const String& toolTip)
  35906. : Button (name)
  35907. {
  35908. setTooltip (toolTip);
  35909. }
  35910. TextButton::~TextButton()
  35911. {
  35912. }
  35913. void TextButton::paintButton (Graphics& g,
  35914. bool isMouseOverButton,
  35915. bool isButtonDown)
  35916. {
  35917. getLookAndFeel().drawButtonBackground (g, *this,
  35918. findColour (getToggleState() ? buttonOnColourId
  35919. : buttonColourId),
  35920. isMouseOverButton,
  35921. isButtonDown);
  35922. getLookAndFeel().drawButtonText (g, *this,
  35923. isMouseOverButton,
  35924. isButtonDown);
  35925. }
  35926. void TextButton::colourChanged()
  35927. {
  35928. repaint();
  35929. }
  35930. const Font TextButton::getFont()
  35931. {
  35932. return Font (jmin (15.0f, getHeight() * 0.6f));
  35933. }
  35934. void TextButton::changeWidthToFitText (const int newHeight)
  35935. {
  35936. if (newHeight >= 0)
  35937. setSize (jmax (1, getWidth()), newHeight);
  35938. setSize (getFont().getStringWidth (getButtonText()) + getHeight(),
  35939. getHeight());
  35940. }
  35941. END_JUCE_NAMESPACE
  35942. /*** End of inlined file: juce_TextButton.cpp ***/
  35943. /*** Start of inlined file: juce_ToggleButton.cpp ***/
  35944. BEGIN_JUCE_NAMESPACE
  35945. ToggleButton::ToggleButton (const String& buttonText)
  35946. : Button (buttonText)
  35947. {
  35948. setClickingTogglesState (true);
  35949. }
  35950. ToggleButton::~ToggleButton()
  35951. {
  35952. }
  35953. void ToggleButton::paintButton (Graphics& g,
  35954. bool isMouseOverButton,
  35955. bool isButtonDown)
  35956. {
  35957. getLookAndFeel().drawToggleButton (g, *this,
  35958. isMouseOverButton,
  35959. isButtonDown);
  35960. }
  35961. void ToggleButton::changeWidthToFitText()
  35962. {
  35963. getLookAndFeel().changeToggleButtonWidthToFitText (*this);
  35964. }
  35965. void ToggleButton::colourChanged()
  35966. {
  35967. repaint();
  35968. }
  35969. END_JUCE_NAMESPACE
  35970. /*** End of inlined file: juce_ToggleButton.cpp ***/
  35971. /*** Start of inlined file: juce_ToolbarButton.cpp ***/
  35972. BEGIN_JUCE_NAMESPACE
  35973. ToolbarButton::ToolbarButton (const int itemId_,
  35974. const String& buttonText,
  35975. Drawable* const normalImage_,
  35976. Drawable* const toggledOnImage_)
  35977. : ToolbarItemComponent (itemId_, buttonText, true),
  35978. normalImage (normalImage_),
  35979. toggledOnImage (toggledOnImage_)
  35980. {
  35981. jassert (normalImage_ != 0);
  35982. }
  35983. ToolbarButton::~ToolbarButton()
  35984. {
  35985. }
  35986. bool ToolbarButton::getToolbarItemSizes (int toolbarDepth,
  35987. bool /*isToolbarVertical*/,
  35988. int& preferredSize,
  35989. int& minSize, int& maxSize)
  35990. {
  35991. preferredSize = minSize = maxSize = toolbarDepth;
  35992. return true;
  35993. }
  35994. void ToolbarButton::paintButtonArea (Graphics& g,
  35995. int width, int height,
  35996. bool /*isMouseOver*/,
  35997. bool /*isMouseDown*/)
  35998. {
  35999. Drawable* d = normalImage;
  36000. if (getToggleState() && toggledOnImage != 0)
  36001. d = toggledOnImage;
  36002. const Rectangle<float> area (0.0f, 0.0f, (float) width, (float) height);
  36003. if (! isEnabled())
  36004. {
  36005. Image im (Image::ARGB, width, height, true);
  36006. {
  36007. Graphics g2 (im);
  36008. d->drawWithin (g2, area, RectanglePlacement::centred, 1.0f);
  36009. }
  36010. im.desaturate();
  36011. g.drawImageAt (im, 0, 0);
  36012. }
  36013. else
  36014. {
  36015. d->drawWithin (g, area, RectanglePlacement::centred, 1.0f);
  36016. }
  36017. }
  36018. void ToolbarButton::contentAreaChanged (const Rectangle<int>&)
  36019. {
  36020. }
  36021. END_JUCE_NAMESPACE
  36022. /*** End of inlined file: juce_ToolbarButton.cpp ***/
  36023. /*** Start of inlined file: juce_CodeDocument.cpp ***/
  36024. BEGIN_JUCE_NAMESPACE
  36025. class CodeDocumentLine
  36026. {
  36027. public:
  36028. CodeDocumentLine (const juce_wchar* const line_,
  36029. const int lineLength_,
  36030. const int numNewLineChars,
  36031. const int lineStartInFile_)
  36032. : line (line_, lineLength_),
  36033. lineStartInFile (lineStartInFile_),
  36034. lineLength (lineLength_),
  36035. lineLengthWithoutNewLines (lineLength_ - numNewLineChars)
  36036. {
  36037. }
  36038. ~CodeDocumentLine()
  36039. {
  36040. }
  36041. static void createLines (Array <CodeDocumentLine*>& newLines, const String& text)
  36042. {
  36043. const juce_wchar* const t = text;
  36044. int pos = 0;
  36045. while (t [pos] != 0)
  36046. {
  36047. const int startOfLine = pos;
  36048. int numNewLineChars = 0;
  36049. while (t[pos] != 0)
  36050. {
  36051. if (t[pos] == '\r')
  36052. {
  36053. ++numNewLineChars;
  36054. ++pos;
  36055. if (t[pos] == '\n')
  36056. {
  36057. ++numNewLineChars;
  36058. ++pos;
  36059. }
  36060. break;
  36061. }
  36062. if (t[pos] == '\n')
  36063. {
  36064. ++numNewLineChars;
  36065. ++pos;
  36066. break;
  36067. }
  36068. ++pos;
  36069. }
  36070. newLines.add (new CodeDocumentLine (t + startOfLine, pos - startOfLine,
  36071. numNewLineChars, startOfLine));
  36072. }
  36073. jassert (pos == text.length());
  36074. }
  36075. bool endsWithLineBreak() const throw()
  36076. {
  36077. return lineLengthWithoutNewLines != lineLength;
  36078. }
  36079. void updateLength() throw()
  36080. {
  36081. lineLengthWithoutNewLines = lineLength = line.length();
  36082. while (lineLengthWithoutNewLines > 0
  36083. && (line [lineLengthWithoutNewLines - 1] == '\n'
  36084. || line [lineLengthWithoutNewLines - 1] == '\r'))
  36085. {
  36086. --lineLengthWithoutNewLines;
  36087. }
  36088. }
  36089. String line;
  36090. int lineStartInFile, lineLength, lineLengthWithoutNewLines;
  36091. };
  36092. CodeDocument::Iterator::Iterator (CodeDocument* const document_)
  36093. : document (document_),
  36094. currentLine (document_->lines[0]),
  36095. line (0),
  36096. position (0)
  36097. {
  36098. }
  36099. CodeDocument::Iterator::Iterator (const CodeDocument::Iterator& other)
  36100. : document (other.document),
  36101. currentLine (other.currentLine),
  36102. line (other.line),
  36103. position (other.position)
  36104. {
  36105. }
  36106. CodeDocument::Iterator& CodeDocument::Iterator::operator= (const CodeDocument::Iterator& other) throw()
  36107. {
  36108. document = other.document;
  36109. currentLine = other.currentLine;
  36110. line = other.line;
  36111. position = other.position;
  36112. return *this;
  36113. }
  36114. CodeDocument::Iterator::~Iterator() throw()
  36115. {
  36116. }
  36117. juce_wchar CodeDocument::Iterator::nextChar()
  36118. {
  36119. if (currentLine == 0)
  36120. return 0;
  36121. jassert (currentLine == document->lines.getUnchecked (line));
  36122. const juce_wchar result = currentLine->line [position - currentLine->lineStartInFile];
  36123. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  36124. {
  36125. ++line;
  36126. currentLine = document->lines [line];
  36127. }
  36128. return result;
  36129. }
  36130. void CodeDocument::Iterator::skip()
  36131. {
  36132. if (currentLine != 0)
  36133. {
  36134. jassert (currentLine == document->lines.getUnchecked (line));
  36135. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  36136. {
  36137. ++line;
  36138. currentLine = document->lines [line];
  36139. }
  36140. }
  36141. }
  36142. void CodeDocument::Iterator::skipToEndOfLine()
  36143. {
  36144. if (currentLine != 0)
  36145. {
  36146. jassert (currentLine == document->lines.getUnchecked (line));
  36147. ++line;
  36148. currentLine = document->lines [line];
  36149. if (currentLine != 0)
  36150. position = currentLine->lineStartInFile;
  36151. else
  36152. position = document->getNumCharacters();
  36153. }
  36154. }
  36155. juce_wchar CodeDocument::Iterator::peekNextChar() const
  36156. {
  36157. if (currentLine == 0)
  36158. return 0;
  36159. jassert (currentLine == document->lines.getUnchecked (line));
  36160. return const_cast <const String&> (currentLine->line) [position - currentLine->lineStartInFile];
  36161. }
  36162. void CodeDocument::Iterator::skipWhitespace()
  36163. {
  36164. while (CharacterFunctions::isWhitespace (peekNextChar()))
  36165. skip();
  36166. }
  36167. bool CodeDocument::Iterator::isEOF() const throw()
  36168. {
  36169. return currentLine == 0;
  36170. }
  36171. CodeDocument::Position::Position() throw()
  36172. : owner (0), characterPos (0), line (0),
  36173. indexInLine (0), positionMaintained (false)
  36174. {
  36175. }
  36176. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  36177. const int line_, const int indexInLine_) throw()
  36178. : owner (const_cast <CodeDocument*> (ownerDocument)),
  36179. characterPos (0), line (line_),
  36180. indexInLine (indexInLine_), positionMaintained (false)
  36181. {
  36182. setLineAndIndex (line_, indexInLine_);
  36183. }
  36184. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  36185. const int characterPos_) throw()
  36186. : owner (const_cast <CodeDocument*> (ownerDocument)),
  36187. positionMaintained (false)
  36188. {
  36189. setPosition (characterPos_);
  36190. }
  36191. CodeDocument::Position::Position (const Position& other) throw()
  36192. : owner (other.owner), characterPos (other.characterPos), line (other.line),
  36193. indexInLine (other.indexInLine), positionMaintained (false)
  36194. {
  36195. jassert (*this == other);
  36196. }
  36197. CodeDocument::Position::~Position()
  36198. {
  36199. setPositionMaintained (false);
  36200. }
  36201. CodeDocument::Position& CodeDocument::Position::operator= (const Position& other)
  36202. {
  36203. if (this != &other)
  36204. {
  36205. const bool wasPositionMaintained = positionMaintained;
  36206. if (owner != other.owner)
  36207. setPositionMaintained (false);
  36208. owner = other.owner;
  36209. line = other.line;
  36210. indexInLine = other.indexInLine;
  36211. characterPos = other.characterPos;
  36212. setPositionMaintained (wasPositionMaintained);
  36213. jassert (*this == other);
  36214. }
  36215. return *this;
  36216. }
  36217. bool CodeDocument::Position::operator== (const Position& other) const throw()
  36218. {
  36219. jassert ((characterPos == other.characterPos)
  36220. == (line == other.line && indexInLine == other.indexInLine));
  36221. return characterPos == other.characterPos
  36222. && line == other.line
  36223. && indexInLine == other.indexInLine
  36224. && owner == other.owner;
  36225. }
  36226. bool CodeDocument::Position::operator!= (const Position& other) const throw()
  36227. {
  36228. return ! operator== (other);
  36229. }
  36230. void CodeDocument::Position::setLineAndIndex (const int newLine, const int newIndexInLine)
  36231. {
  36232. jassert (owner != 0);
  36233. if (owner->lines.size() == 0)
  36234. {
  36235. line = 0;
  36236. indexInLine = 0;
  36237. characterPos = 0;
  36238. }
  36239. else
  36240. {
  36241. if (newLine >= owner->lines.size())
  36242. {
  36243. line = owner->lines.size() - 1;
  36244. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  36245. jassert (l != 0);
  36246. indexInLine = l->lineLengthWithoutNewLines;
  36247. characterPos = l->lineStartInFile + indexInLine;
  36248. }
  36249. else
  36250. {
  36251. line = jmax (0, newLine);
  36252. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  36253. jassert (l != 0);
  36254. if (l->lineLengthWithoutNewLines > 0)
  36255. indexInLine = jlimit (0, l->lineLengthWithoutNewLines, newIndexInLine);
  36256. else
  36257. indexInLine = 0;
  36258. characterPos = l->lineStartInFile + indexInLine;
  36259. }
  36260. }
  36261. }
  36262. void CodeDocument::Position::setPosition (const int newPosition)
  36263. {
  36264. jassert (owner != 0);
  36265. line = 0;
  36266. indexInLine = 0;
  36267. characterPos = 0;
  36268. if (newPosition > 0)
  36269. {
  36270. int lineStart = 0;
  36271. int lineEnd = owner->lines.size();
  36272. for (;;)
  36273. {
  36274. if (lineEnd - lineStart < 4)
  36275. {
  36276. for (int i = lineStart; i < lineEnd; ++i)
  36277. {
  36278. CodeDocumentLine* const l = owner->lines.getUnchecked (i);
  36279. int index = newPosition - l->lineStartInFile;
  36280. if (index >= 0 && (index < l->lineLength || i == lineEnd - 1))
  36281. {
  36282. line = i;
  36283. indexInLine = jmin (l->lineLengthWithoutNewLines, index);
  36284. characterPos = l->lineStartInFile + indexInLine;
  36285. }
  36286. }
  36287. break;
  36288. }
  36289. else
  36290. {
  36291. const int midIndex = (lineStart + lineEnd + 1) / 2;
  36292. CodeDocumentLine* const mid = owner->lines.getUnchecked (midIndex);
  36293. if (newPosition >= mid->lineStartInFile)
  36294. lineStart = midIndex;
  36295. else
  36296. lineEnd = midIndex;
  36297. }
  36298. }
  36299. }
  36300. }
  36301. void CodeDocument::Position::moveBy (int characterDelta)
  36302. {
  36303. jassert (owner != 0);
  36304. if (characterDelta == 1)
  36305. {
  36306. setPosition (getPosition());
  36307. // If moving right, make sure we don't get stuck between the \r and \n characters..
  36308. if (line < owner->lines.size())
  36309. {
  36310. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  36311. if (indexInLine + characterDelta < l->lineLength
  36312. && indexInLine + characterDelta >= l->lineLengthWithoutNewLines + 1)
  36313. ++characterDelta;
  36314. }
  36315. }
  36316. setPosition (characterPos + characterDelta);
  36317. }
  36318. const CodeDocument::Position CodeDocument::Position::movedBy (const int characterDelta) const
  36319. {
  36320. CodeDocument::Position p (*this);
  36321. p.moveBy (characterDelta);
  36322. return p;
  36323. }
  36324. const CodeDocument::Position CodeDocument::Position::movedByLines (const int deltaLines) const
  36325. {
  36326. CodeDocument::Position p (*this);
  36327. p.setLineAndIndex (getLineNumber() + deltaLines, getIndexInLine());
  36328. return p;
  36329. }
  36330. const juce_wchar CodeDocument::Position::getCharacter() const
  36331. {
  36332. const CodeDocumentLine* const l = owner->lines [line];
  36333. return l == 0 ? 0 : l->line [getIndexInLine()];
  36334. }
  36335. const String CodeDocument::Position::getLineText() const
  36336. {
  36337. const CodeDocumentLine* const l = owner->lines [line];
  36338. return l == 0 ? String::empty : l->line;
  36339. }
  36340. void CodeDocument::Position::setPositionMaintained (const bool isMaintained)
  36341. {
  36342. if (isMaintained != positionMaintained)
  36343. {
  36344. positionMaintained = isMaintained;
  36345. if (owner != 0)
  36346. {
  36347. if (isMaintained)
  36348. {
  36349. jassert (! owner->positionsToMaintain.contains (this));
  36350. owner->positionsToMaintain.add (this);
  36351. }
  36352. else
  36353. {
  36354. // If this happens, you may have deleted the document while there are Position objects that are still using it...
  36355. jassert (owner->positionsToMaintain.contains (this));
  36356. owner->positionsToMaintain.removeValue (this);
  36357. }
  36358. }
  36359. }
  36360. }
  36361. CodeDocument::CodeDocument()
  36362. : undoManager (std::numeric_limits<int>::max(), 10000),
  36363. currentActionIndex (0),
  36364. indexOfSavedState (-1),
  36365. maximumLineLength (-1),
  36366. newLineChars ("\r\n")
  36367. {
  36368. }
  36369. CodeDocument::~CodeDocument()
  36370. {
  36371. }
  36372. const String CodeDocument::getAllContent() const
  36373. {
  36374. return getTextBetween (Position (this, 0),
  36375. Position (this, lines.size(), 0));
  36376. }
  36377. const String CodeDocument::getTextBetween (const Position& start, const Position& end) const
  36378. {
  36379. if (end.getPosition() <= start.getPosition())
  36380. return String::empty;
  36381. const int startLine = start.getLineNumber();
  36382. const int endLine = end.getLineNumber();
  36383. if (startLine == endLine)
  36384. {
  36385. CodeDocumentLine* const line = lines [startLine];
  36386. return (line == 0) ? String::empty : line->line.substring (start.getIndexInLine(), end.getIndexInLine());
  36387. }
  36388. String result;
  36389. result.preallocateStorage (end.getPosition() - start.getPosition() + 4);
  36390. String::Concatenator concatenator (result);
  36391. const int maxLine = jmin (lines.size() - 1, endLine);
  36392. for (int i = jmax (0, startLine); i <= maxLine; ++i)
  36393. {
  36394. const CodeDocumentLine* line = lines.getUnchecked(i);
  36395. int len = line->lineLength;
  36396. if (i == startLine)
  36397. {
  36398. const int index = start.getIndexInLine();
  36399. concatenator.append (line->line.substring (index, len));
  36400. }
  36401. else if (i == endLine)
  36402. {
  36403. len = end.getIndexInLine();
  36404. concatenator.append (line->line.substring (0, len));
  36405. }
  36406. else
  36407. {
  36408. concatenator.append (line->line);
  36409. }
  36410. }
  36411. return result;
  36412. }
  36413. int CodeDocument::getNumCharacters() const throw()
  36414. {
  36415. const CodeDocumentLine* const lastLine = lines.getLast();
  36416. return (lastLine == 0) ? 0 : lastLine->lineStartInFile + lastLine->lineLength;
  36417. }
  36418. const String CodeDocument::getLine (const int lineIndex) const throw()
  36419. {
  36420. const CodeDocumentLine* const line = lines [lineIndex];
  36421. return (line == 0) ? String::empty : line->line;
  36422. }
  36423. int CodeDocument::getMaximumLineLength() throw()
  36424. {
  36425. if (maximumLineLength < 0)
  36426. {
  36427. maximumLineLength = 0;
  36428. for (int i = lines.size(); --i >= 0;)
  36429. maximumLineLength = jmax (maximumLineLength, lines.getUnchecked(i)->lineLength);
  36430. }
  36431. return maximumLineLength;
  36432. }
  36433. void CodeDocument::deleteSection (const Position& startPosition, const Position& endPosition)
  36434. {
  36435. remove (startPosition.getPosition(), endPosition.getPosition(), true);
  36436. }
  36437. void CodeDocument::insertText (const Position& position, const String& text)
  36438. {
  36439. insert (text, position.getPosition(), true);
  36440. }
  36441. void CodeDocument::replaceAllContent (const String& newContent)
  36442. {
  36443. remove (0, getNumCharacters(), true);
  36444. insert (newContent, 0, true);
  36445. }
  36446. bool CodeDocument::loadFromStream (InputStream& stream)
  36447. {
  36448. replaceAllContent (stream.readEntireStreamAsString());
  36449. setSavePoint();
  36450. clearUndoHistory();
  36451. return true;
  36452. }
  36453. bool CodeDocument::writeToStream (OutputStream& stream)
  36454. {
  36455. for (int i = 0; i < lines.size(); ++i)
  36456. {
  36457. String temp (lines.getUnchecked(i)->line); // use a copy to avoid bloating the memory footprint of the stored string.
  36458. const char* utf8 = temp.toUTF8();
  36459. if (! stream.write (utf8, (int) strlen (utf8)))
  36460. return false;
  36461. }
  36462. return true;
  36463. }
  36464. void CodeDocument::setNewLineCharacters (const String& newLine) throw()
  36465. {
  36466. jassert (newLine == "\r\n" || newLine == "\n" || newLine == "\r");
  36467. newLineChars = newLine;
  36468. }
  36469. void CodeDocument::newTransaction()
  36470. {
  36471. undoManager.beginNewTransaction (String::empty);
  36472. }
  36473. void CodeDocument::undo()
  36474. {
  36475. newTransaction();
  36476. undoManager.undo();
  36477. }
  36478. void CodeDocument::redo()
  36479. {
  36480. undoManager.redo();
  36481. }
  36482. void CodeDocument::clearUndoHistory()
  36483. {
  36484. undoManager.clearUndoHistory();
  36485. }
  36486. void CodeDocument::setSavePoint() throw()
  36487. {
  36488. indexOfSavedState = currentActionIndex;
  36489. }
  36490. bool CodeDocument::hasChangedSinceSavePoint() const throw()
  36491. {
  36492. return currentActionIndex != indexOfSavedState;
  36493. }
  36494. static int getCodeCharacterCategory (const juce_wchar character) throw()
  36495. {
  36496. return (CharacterFunctions::isLetterOrDigit (character) || character == '_')
  36497. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  36498. }
  36499. const CodeDocument::Position CodeDocument::findWordBreakAfter (const Position& position) const throw()
  36500. {
  36501. Position p (position);
  36502. const int maxDistance = 256;
  36503. int i = 0;
  36504. while (i < maxDistance
  36505. && CharacterFunctions::isWhitespace (p.getCharacter())
  36506. && (i == 0 || (p.getCharacter() != '\n'
  36507. && p.getCharacter() != '\r')))
  36508. {
  36509. ++i;
  36510. p.moveBy (1);
  36511. }
  36512. if (i == 0)
  36513. {
  36514. const int type = getCodeCharacterCategory (p.getCharacter());
  36515. while (i < maxDistance && type == getCodeCharacterCategory (p.getCharacter()))
  36516. {
  36517. ++i;
  36518. p.moveBy (1);
  36519. }
  36520. while (i < maxDistance
  36521. && CharacterFunctions::isWhitespace (p.getCharacter())
  36522. && (i == 0 || (p.getCharacter() != '\n'
  36523. && p.getCharacter() != '\r')))
  36524. {
  36525. ++i;
  36526. p.moveBy (1);
  36527. }
  36528. }
  36529. return p;
  36530. }
  36531. const CodeDocument::Position CodeDocument::findWordBreakBefore (const Position& position) const throw()
  36532. {
  36533. Position p (position);
  36534. const int maxDistance = 256;
  36535. int i = 0;
  36536. bool stoppedAtLineStart = false;
  36537. while (i < maxDistance)
  36538. {
  36539. const juce_wchar c = p.movedBy (-1).getCharacter();
  36540. if (c == '\r' || c == '\n')
  36541. {
  36542. stoppedAtLineStart = true;
  36543. if (i > 0)
  36544. break;
  36545. }
  36546. if (! CharacterFunctions::isWhitespace (c))
  36547. break;
  36548. p.moveBy (-1);
  36549. ++i;
  36550. }
  36551. if (i < maxDistance && ! stoppedAtLineStart)
  36552. {
  36553. const int type = getCodeCharacterCategory (p.movedBy (-1).getCharacter());
  36554. while (i < maxDistance && type == getCodeCharacterCategory (p.movedBy (-1).getCharacter()))
  36555. {
  36556. p.moveBy (-1);
  36557. ++i;
  36558. }
  36559. }
  36560. return p;
  36561. }
  36562. void CodeDocument::checkLastLineStatus()
  36563. {
  36564. while (lines.size() > 0
  36565. && lines.getLast()->lineLength == 0
  36566. && (lines.size() == 1 || ! lines.getUnchecked (lines.size() - 2)->endsWithLineBreak()))
  36567. {
  36568. // remove any empty lines at the end if the preceding line doesn't end in a newline.
  36569. lines.removeLast();
  36570. }
  36571. const CodeDocumentLine* const lastLine = lines.getLast();
  36572. if (lastLine != 0 && lastLine->endsWithLineBreak())
  36573. {
  36574. // check that there's an empty line at the end if the preceding one ends in a newline..
  36575. lines.add (new CodeDocumentLine (String::empty, 0, 0, lastLine->lineStartInFile + lastLine->lineLength));
  36576. }
  36577. }
  36578. void CodeDocument::addListener (CodeDocument::Listener* const listener) throw()
  36579. {
  36580. listeners.add (listener);
  36581. }
  36582. void CodeDocument::removeListener (CodeDocument::Listener* const listener) throw()
  36583. {
  36584. listeners.remove (listener);
  36585. }
  36586. void CodeDocument::sendListenerChangeMessage (const int startLine, const int endLine)
  36587. {
  36588. Position startPos (this, startLine, 0);
  36589. Position endPos (this, endLine, 0);
  36590. listeners.call (&CodeDocument::Listener::codeDocumentChanged, startPos, endPos);
  36591. }
  36592. class CodeDocumentInsertAction : public UndoableAction
  36593. {
  36594. CodeDocument& owner;
  36595. const String text;
  36596. int insertPos;
  36597. CodeDocumentInsertAction (const CodeDocumentInsertAction&);
  36598. CodeDocumentInsertAction& operator= (const CodeDocumentInsertAction&);
  36599. public:
  36600. CodeDocumentInsertAction (CodeDocument& owner_, const String& text_, const int insertPos_) throw()
  36601. : owner (owner_),
  36602. text (text_),
  36603. insertPos (insertPos_)
  36604. {
  36605. }
  36606. ~CodeDocumentInsertAction() {}
  36607. bool perform()
  36608. {
  36609. owner.currentActionIndex++;
  36610. owner.insert (text, insertPos, false);
  36611. return true;
  36612. }
  36613. bool undo()
  36614. {
  36615. owner.currentActionIndex--;
  36616. owner.remove (insertPos, insertPos + text.length(), false);
  36617. return true;
  36618. }
  36619. int getSizeInUnits() { return text.length() + 32; }
  36620. };
  36621. void CodeDocument::insert (const String& text, const int insertPos, const bool undoable)
  36622. {
  36623. if (text.isEmpty())
  36624. return;
  36625. if (undoable)
  36626. {
  36627. undoManager.perform (new CodeDocumentInsertAction (*this, text, insertPos));
  36628. }
  36629. else
  36630. {
  36631. Position pos (this, insertPos);
  36632. const int firstAffectedLine = pos.getLineNumber();
  36633. int lastAffectedLine = firstAffectedLine + 1;
  36634. CodeDocumentLine* const firstLine = lines [firstAffectedLine];
  36635. String textInsideOriginalLine (text);
  36636. if (firstLine != 0)
  36637. {
  36638. const int index = pos.getIndexInLine();
  36639. textInsideOriginalLine = firstLine->line.substring (0, index)
  36640. + textInsideOriginalLine
  36641. + firstLine->line.substring (index);
  36642. }
  36643. maximumLineLength = -1;
  36644. Array <CodeDocumentLine*> newLines;
  36645. CodeDocumentLine::createLines (newLines, textInsideOriginalLine);
  36646. jassert (newLines.size() > 0);
  36647. CodeDocumentLine* const newFirstLine = newLines.getUnchecked (0);
  36648. newFirstLine->lineStartInFile = firstLine != 0 ? firstLine->lineStartInFile : 0;
  36649. lines.set (firstAffectedLine, newFirstLine);
  36650. if (newLines.size() > 1)
  36651. {
  36652. for (int i = 1; i < newLines.size(); ++i)
  36653. {
  36654. CodeDocumentLine* const l = newLines.getUnchecked (i);
  36655. lines.insert (firstAffectedLine + i, l);
  36656. }
  36657. lastAffectedLine = lines.size();
  36658. }
  36659. int i, lineStart = newFirstLine->lineStartInFile;
  36660. for (i = firstAffectedLine; i < lines.size(); ++i)
  36661. {
  36662. CodeDocumentLine* const l = lines.getUnchecked (i);
  36663. l->lineStartInFile = lineStart;
  36664. lineStart += l->lineLength;
  36665. }
  36666. checkLastLineStatus();
  36667. const int newTextLength = text.length();
  36668. for (i = 0; i < positionsToMaintain.size(); ++i)
  36669. {
  36670. CodeDocument::Position* const p = positionsToMaintain.getUnchecked(i);
  36671. if (p->getPosition() >= insertPos)
  36672. p->setPosition (p->getPosition() + newTextLength);
  36673. }
  36674. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  36675. }
  36676. }
  36677. class CodeDocumentDeleteAction : public UndoableAction
  36678. {
  36679. CodeDocument& owner;
  36680. int startPos, endPos;
  36681. String removedText;
  36682. CodeDocumentDeleteAction (const CodeDocumentDeleteAction&);
  36683. CodeDocumentDeleteAction& operator= (const CodeDocumentDeleteAction&);
  36684. public:
  36685. CodeDocumentDeleteAction (CodeDocument& owner_, const int startPos_, const int endPos_) throw()
  36686. : owner (owner_),
  36687. startPos (startPos_),
  36688. endPos (endPos_)
  36689. {
  36690. removedText = owner.getTextBetween (CodeDocument::Position (&owner, startPos),
  36691. CodeDocument::Position (&owner, endPos));
  36692. }
  36693. ~CodeDocumentDeleteAction() {}
  36694. bool perform()
  36695. {
  36696. owner.currentActionIndex++;
  36697. owner.remove (startPos, endPos, false);
  36698. return true;
  36699. }
  36700. bool undo()
  36701. {
  36702. owner.currentActionIndex--;
  36703. owner.insert (removedText, startPos, false);
  36704. return true;
  36705. }
  36706. int getSizeInUnits() { return removedText.length() + 32; }
  36707. };
  36708. void CodeDocument::remove (const int startPos, const int endPos, const bool undoable)
  36709. {
  36710. if (endPos <= startPos)
  36711. return;
  36712. if (undoable)
  36713. {
  36714. undoManager.perform (new CodeDocumentDeleteAction (*this, startPos, endPos));
  36715. }
  36716. else
  36717. {
  36718. Position startPosition (this, startPos);
  36719. Position endPosition (this, endPos);
  36720. maximumLineLength = -1;
  36721. const int firstAffectedLine = startPosition.getLineNumber();
  36722. const int endLine = endPosition.getLineNumber();
  36723. int lastAffectedLine = firstAffectedLine + 1;
  36724. CodeDocumentLine* const firstLine = lines.getUnchecked (firstAffectedLine);
  36725. if (firstAffectedLine == endLine)
  36726. {
  36727. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  36728. + firstLine->line.substring (endPosition.getIndexInLine());
  36729. firstLine->updateLength();
  36730. }
  36731. else
  36732. {
  36733. lastAffectedLine = lines.size();
  36734. CodeDocumentLine* const lastLine = lines.getUnchecked (endLine);
  36735. jassert (lastLine != 0);
  36736. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  36737. + lastLine->line.substring (endPosition.getIndexInLine());
  36738. firstLine->updateLength();
  36739. int numLinesToRemove = endLine - firstAffectedLine;
  36740. lines.removeRange (firstAffectedLine + 1, numLinesToRemove);
  36741. }
  36742. int i;
  36743. for (i = firstAffectedLine + 1; i < lines.size(); ++i)
  36744. {
  36745. CodeDocumentLine* const l = lines.getUnchecked (i);
  36746. const CodeDocumentLine* const previousLine = lines.getUnchecked (i - 1);
  36747. l->lineStartInFile = previousLine->lineStartInFile + previousLine->lineLength;
  36748. }
  36749. checkLastLineStatus();
  36750. const int totalChars = getNumCharacters();
  36751. for (i = 0; i < positionsToMaintain.size(); ++i)
  36752. {
  36753. CodeDocument::Position* p = positionsToMaintain.getUnchecked(i);
  36754. if (p->getPosition() > startPosition.getPosition())
  36755. p->setPosition (jmax (startPos, p->getPosition() + startPos - endPos));
  36756. if (p->getPosition() > totalChars)
  36757. p->setPosition (totalChars);
  36758. }
  36759. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  36760. }
  36761. }
  36762. END_JUCE_NAMESPACE
  36763. /*** End of inlined file: juce_CodeDocument.cpp ***/
  36764. /*** Start of inlined file: juce_CodeEditorComponent.cpp ***/
  36765. BEGIN_JUCE_NAMESPACE
  36766. class CodeEditorComponent::CaretComponent : public Component,
  36767. public Timer
  36768. {
  36769. public:
  36770. CaretComponent (CodeEditorComponent& owner_)
  36771. : owner (owner_)
  36772. {
  36773. setAlwaysOnTop (true);
  36774. setInterceptsMouseClicks (false, false);
  36775. }
  36776. ~CaretComponent()
  36777. {
  36778. }
  36779. void paint (Graphics& g)
  36780. {
  36781. g.fillAll (findColour (CodeEditorComponent::caretColourId));
  36782. }
  36783. void timerCallback()
  36784. {
  36785. setVisible (shouldBeShown() && ! isVisible());
  36786. }
  36787. void updatePosition()
  36788. {
  36789. startTimer (400);
  36790. setVisible (shouldBeShown());
  36791. setBounds (owner.getCharacterBounds (owner.getCaretPos()).withWidth (2));
  36792. }
  36793. private:
  36794. CodeEditorComponent& owner;
  36795. CaretComponent (const CaretComponent&);
  36796. CaretComponent& operator= (const CaretComponent&);
  36797. bool shouldBeShown() const { return owner.hasKeyboardFocus (true); }
  36798. };
  36799. class CodeEditorComponent::CodeEditorLine
  36800. {
  36801. public:
  36802. CodeEditorLine() throw()
  36803. : highlightColumnStart (0), highlightColumnEnd (0)
  36804. {
  36805. }
  36806. ~CodeEditorLine() throw()
  36807. {
  36808. }
  36809. bool update (CodeDocument& document, int lineNum,
  36810. CodeDocument::Iterator& source,
  36811. CodeTokeniser* analyser, const int spacesPerTab,
  36812. const CodeDocument::Position& selectionStart,
  36813. const CodeDocument::Position& selectionEnd)
  36814. {
  36815. Array <SyntaxToken> newTokens;
  36816. newTokens.ensureStorageAllocated (8);
  36817. if (analyser == 0)
  36818. {
  36819. newTokens.add (SyntaxToken (document.getLine (lineNum), -1));
  36820. }
  36821. else if (lineNum < document.getNumLines())
  36822. {
  36823. const CodeDocument::Position pos (&document, lineNum, 0);
  36824. createTokens (pos.getPosition(), pos.getLineText(),
  36825. source, analyser, newTokens);
  36826. }
  36827. replaceTabsWithSpaces (newTokens, spacesPerTab);
  36828. int newHighlightStart = 0;
  36829. int newHighlightEnd = 0;
  36830. if (selectionStart.getLineNumber() <= lineNum && selectionEnd.getLineNumber() >= lineNum)
  36831. {
  36832. const String line (document.getLine (lineNum));
  36833. CodeDocument::Position lineStart (&document, lineNum, 0), lineEnd (&document, lineNum + 1, 0);
  36834. newHighlightStart = indexToColumn (jmax (0, selectionStart.getPosition() - lineStart.getPosition()),
  36835. line, spacesPerTab);
  36836. newHighlightEnd = indexToColumn (jmin (lineEnd.getPosition() - lineStart.getPosition(), selectionEnd.getPosition() - lineStart.getPosition()),
  36837. line, spacesPerTab);
  36838. }
  36839. if (newHighlightStart != highlightColumnStart || newHighlightEnd != highlightColumnEnd)
  36840. {
  36841. highlightColumnStart = newHighlightStart;
  36842. highlightColumnEnd = newHighlightEnd;
  36843. }
  36844. else
  36845. {
  36846. if (tokens.size() == newTokens.size())
  36847. {
  36848. bool allTheSame = true;
  36849. for (int i = newTokens.size(); --i >= 0;)
  36850. {
  36851. if (tokens.getReference(i) != newTokens.getReference(i))
  36852. {
  36853. allTheSame = false;
  36854. break;
  36855. }
  36856. }
  36857. if (allTheSame)
  36858. return false;
  36859. }
  36860. }
  36861. tokens.swapWithArray (newTokens);
  36862. return true;
  36863. }
  36864. void draw (CodeEditorComponent& owner, Graphics& g, const Font& font,
  36865. float x, const int y, const int baselineOffset, const int lineHeight,
  36866. const Colour& highlightColour) const
  36867. {
  36868. if (highlightColumnStart < highlightColumnEnd)
  36869. {
  36870. g.setColour (highlightColour);
  36871. g.fillRect (roundToInt (x + highlightColumnStart * owner.getCharWidth()), y,
  36872. roundToInt ((highlightColumnEnd - highlightColumnStart) * owner.getCharWidth()), lineHeight);
  36873. }
  36874. int lastType = std::numeric_limits<int>::min();
  36875. for (int i = 0; i < tokens.size(); ++i)
  36876. {
  36877. SyntaxToken& token = tokens.getReference(i);
  36878. if (lastType != token.tokenType)
  36879. {
  36880. lastType = token.tokenType;
  36881. g.setColour (owner.getColourForTokenType (lastType));
  36882. }
  36883. g.drawSingleLineText (token.text, roundToInt (x), y + baselineOffset);
  36884. if (i < tokens.size() - 1)
  36885. {
  36886. if (token.width < 0)
  36887. token.width = font.getStringWidthFloat (token.text);
  36888. x += token.width;
  36889. }
  36890. }
  36891. }
  36892. private:
  36893. struct SyntaxToken
  36894. {
  36895. String text;
  36896. int tokenType;
  36897. float width;
  36898. SyntaxToken (const String& text_, const int type) throw()
  36899. : text (text_), tokenType (type), width (-1.0f)
  36900. {
  36901. }
  36902. bool operator!= (const SyntaxToken& other) const throw()
  36903. {
  36904. return text != other.text || tokenType != other.tokenType;
  36905. }
  36906. };
  36907. Array <SyntaxToken> tokens;
  36908. int highlightColumnStart, highlightColumnEnd;
  36909. static void createTokens (int startPosition, const String& lineText,
  36910. CodeDocument::Iterator& source,
  36911. CodeTokeniser* analyser,
  36912. Array <SyntaxToken>& newTokens)
  36913. {
  36914. CodeDocument::Iterator lastIterator (source);
  36915. const int lineLength = lineText.length();
  36916. for (;;)
  36917. {
  36918. int tokenType = analyser->readNextToken (source);
  36919. int tokenStart = lastIterator.getPosition();
  36920. int tokenEnd = source.getPosition();
  36921. if (tokenEnd <= tokenStart)
  36922. break;
  36923. tokenEnd -= startPosition;
  36924. if (tokenEnd > 0)
  36925. {
  36926. tokenStart -= startPosition;
  36927. newTokens.add (SyntaxToken (lineText.substring (jmax (0, tokenStart), tokenEnd),
  36928. tokenType));
  36929. if (tokenEnd >= lineLength)
  36930. break;
  36931. }
  36932. lastIterator = source;
  36933. }
  36934. source = lastIterator;
  36935. }
  36936. static void replaceTabsWithSpaces (Array <SyntaxToken>& tokens, const int spacesPerTab)
  36937. {
  36938. int x = 0;
  36939. for (int i = 0; i < tokens.size(); ++i)
  36940. {
  36941. SyntaxToken& t = tokens.getReference(i);
  36942. for (;;)
  36943. {
  36944. int tabPos = t.text.indexOfChar ('\t');
  36945. if (tabPos < 0)
  36946. break;
  36947. const int spacesNeeded = spacesPerTab - ((tabPos + x) % spacesPerTab);
  36948. t.text = t.text.replaceSection (tabPos, 1, String::repeatedString (" ", spacesNeeded));
  36949. }
  36950. x += t.text.length();
  36951. }
  36952. }
  36953. int indexToColumn (int index, const String& line, int spacesPerTab) const throw()
  36954. {
  36955. jassert (index <= line.length());
  36956. int col = 0;
  36957. for (int i = 0; i < index; ++i)
  36958. {
  36959. if (line[i] != '\t')
  36960. ++col;
  36961. else
  36962. col += spacesPerTab - (col % spacesPerTab);
  36963. }
  36964. return col;
  36965. }
  36966. };
  36967. CodeEditorComponent::CodeEditorComponent (CodeDocument& document_,
  36968. CodeTokeniser* const codeTokeniser_)
  36969. : document (document_),
  36970. firstLineOnScreen (0),
  36971. gutter (5),
  36972. spacesPerTab (4),
  36973. lineHeight (0),
  36974. linesOnScreen (0),
  36975. columnsOnScreen (0),
  36976. scrollbarThickness (16),
  36977. columnToTryToMaintain (-1),
  36978. useSpacesForTabs (false),
  36979. xOffset (0),
  36980. codeTokeniser (codeTokeniser_)
  36981. {
  36982. caretPos = CodeDocument::Position (&document_, 0, 0);
  36983. caretPos.setPositionMaintained (true);
  36984. selectionStart = CodeDocument::Position (&document_, 0, 0);
  36985. selectionStart.setPositionMaintained (true);
  36986. selectionEnd = CodeDocument::Position (&document_, 0, 0);
  36987. selectionEnd.setPositionMaintained (true);
  36988. setOpaque (true);
  36989. setMouseCursor (MouseCursor (MouseCursor::IBeamCursor));
  36990. setWantsKeyboardFocus (true);
  36991. addAndMakeVisible (verticalScrollBar = new ScrollBar (true));
  36992. verticalScrollBar->setSingleStepSize (1.0);
  36993. addAndMakeVisible (horizontalScrollBar = new ScrollBar (false));
  36994. horizontalScrollBar->setSingleStepSize (1.0);
  36995. addAndMakeVisible (caret = new CaretComponent (*this));
  36996. Font f (12.0f);
  36997. f.setTypefaceName (Font::getDefaultMonospacedFontName());
  36998. setFont (f);
  36999. resetToDefaultColours();
  37000. verticalScrollBar->addListener (this);
  37001. horizontalScrollBar->addListener (this);
  37002. document.addListener (this);
  37003. }
  37004. CodeEditorComponent::~CodeEditorComponent()
  37005. {
  37006. document.removeListener (this);
  37007. deleteAllChildren();
  37008. }
  37009. void CodeEditorComponent::loadContent (const String& newContent)
  37010. {
  37011. clearCachedIterators (0);
  37012. document.replaceAllContent (newContent);
  37013. document.clearUndoHistory();
  37014. document.setSavePoint();
  37015. caretPos.setPosition (0);
  37016. selectionStart.setPosition (0);
  37017. selectionEnd.setPosition (0);
  37018. scrollToLine (0);
  37019. }
  37020. bool CodeEditorComponent::isTextInputActive() const
  37021. {
  37022. return true;
  37023. }
  37024. void CodeEditorComponent::codeDocumentChanged (const CodeDocument::Position& affectedTextStart,
  37025. const CodeDocument::Position& affectedTextEnd)
  37026. {
  37027. clearCachedIterators (affectedTextStart.getLineNumber());
  37028. triggerAsyncUpdate();
  37029. caret->updatePosition();
  37030. columnToTryToMaintain = -1;
  37031. if (affectedTextEnd.getPosition() >= selectionStart.getPosition()
  37032. && affectedTextStart.getPosition() <= selectionEnd.getPosition())
  37033. deselectAll();
  37034. if (caretPos.getPosition() > affectedTextEnd.getPosition()
  37035. || caretPos.getPosition() < affectedTextStart.getPosition())
  37036. moveCaretTo (affectedTextStart, false);
  37037. updateScrollBars();
  37038. }
  37039. void CodeEditorComponent::resized()
  37040. {
  37041. linesOnScreen = (getHeight() - scrollbarThickness) / lineHeight;
  37042. columnsOnScreen = (int) ((getWidth() - scrollbarThickness) / charWidth);
  37043. lines.clear();
  37044. rebuildLineTokens();
  37045. caret->updatePosition();
  37046. verticalScrollBar->setBounds (getWidth() - scrollbarThickness, 0, scrollbarThickness, getHeight() - scrollbarThickness);
  37047. horizontalScrollBar->setBounds (gutter, getHeight() - scrollbarThickness, getWidth() - scrollbarThickness - gutter, scrollbarThickness);
  37048. updateScrollBars();
  37049. }
  37050. void CodeEditorComponent::paint (Graphics& g)
  37051. {
  37052. handleUpdateNowIfNeeded();
  37053. g.fillAll (findColour (CodeEditorComponent::backgroundColourId));
  37054. g.reduceClipRegion (gutter, 0, verticalScrollBar->getX() - gutter, horizontalScrollBar->getY());
  37055. g.setFont (font);
  37056. const int baselineOffset = (int) font.getAscent();
  37057. const Colour defaultColour (findColour (CodeEditorComponent::defaultTextColourId));
  37058. const Colour highlightColour (findColour (CodeEditorComponent::highlightColourId));
  37059. const Rectangle<int> clip (g.getClipBounds());
  37060. const int firstLineToDraw = jmax (0, clip.getY() / lineHeight);
  37061. const int lastLineToDraw = jmin (lines.size(), clip.getBottom() / lineHeight + 1);
  37062. for (int j = firstLineToDraw; j < lastLineToDraw; ++j)
  37063. {
  37064. lines.getUnchecked(j)->draw (*this, g, font,
  37065. (float) (gutter - xOffset * charWidth),
  37066. lineHeight * j, baselineOffset, lineHeight,
  37067. highlightColour);
  37068. }
  37069. }
  37070. void CodeEditorComponent::setScrollbarThickness (const int thickness)
  37071. {
  37072. if (scrollbarThickness != thickness)
  37073. {
  37074. scrollbarThickness = thickness;
  37075. resized();
  37076. }
  37077. }
  37078. void CodeEditorComponent::handleAsyncUpdate()
  37079. {
  37080. rebuildLineTokens();
  37081. }
  37082. void CodeEditorComponent::rebuildLineTokens()
  37083. {
  37084. cancelPendingUpdate();
  37085. const int numNeeded = linesOnScreen + 1;
  37086. int minLineToRepaint = numNeeded;
  37087. int maxLineToRepaint = 0;
  37088. if (numNeeded != lines.size())
  37089. {
  37090. lines.clear();
  37091. for (int i = numNeeded; --i >= 0;)
  37092. lines.add (new CodeEditorLine());
  37093. minLineToRepaint = 0;
  37094. maxLineToRepaint = numNeeded;
  37095. }
  37096. jassert (numNeeded == lines.size());
  37097. CodeDocument::Iterator source (&document);
  37098. getIteratorForPosition (CodeDocument::Position (&document, firstLineOnScreen, 0).getPosition(), source);
  37099. for (int i = 0; i < numNeeded; ++i)
  37100. {
  37101. CodeEditorLine* const line = lines.getUnchecked(i);
  37102. if (line->update (document, firstLineOnScreen + i, source, codeTokeniser, spacesPerTab,
  37103. selectionStart, selectionEnd))
  37104. {
  37105. minLineToRepaint = jmin (minLineToRepaint, i);
  37106. maxLineToRepaint = jmax (maxLineToRepaint, i);
  37107. }
  37108. }
  37109. if (minLineToRepaint <= maxLineToRepaint)
  37110. {
  37111. repaint (gutter, lineHeight * minLineToRepaint - 1,
  37112. verticalScrollBar->getX() - gutter,
  37113. lineHeight * (1 + maxLineToRepaint - minLineToRepaint) + 2);
  37114. }
  37115. }
  37116. void CodeEditorComponent::moveCaretTo (const CodeDocument::Position& newPos, const bool highlighting)
  37117. {
  37118. caretPos = newPos;
  37119. columnToTryToMaintain = -1;
  37120. if (highlighting)
  37121. {
  37122. if (dragType == notDragging)
  37123. {
  37124. if (abs (caretPos.getPosition() - selectionStart.getPosition())
  37125. < abs (caretPos.getPosition() - selectionEnd.getPosition()))
  37126. dragType = draggingSelectionStart;
  37127. else
  37128. dragType = draggingSelectionEnd;
  37129. }
  37130. if (dragType == draggingSelectionStart)
  37131. {
  37132. selectionStart = caretPos;
  37133. if (selectionEnd.getPosition() < selectionStart.getPosition())
  37134. {
  37135. const CodeDocument::Position temp (selectionStart);
  37136. selectionStart = selectionEnd;
  37137. selectionEnd = temp;
  37138. dragType = draggingSelectionEnd;
  37139. }
  37140. }
  37141. else
  37142. {
  37143. selectionEnd = caretPos;
  37144. if (selectionEnd.getPosition() < selectionStart.getPosition())
  37145. {
  37146. const CodeDocument::Position temp (selectionStart);
  37147. selectionStart = selectionEnd;
  37148. selectionEnd = temp;
  37149. dragType = draggingSelectionStart;
  37150. }
  37151. }
  37152. triggerAsyncUpdate();
  37153. }
  37154. else
  37155. {
  37156. deselectAll();
  37157. }
  37158. caret->updatePosition();
  37159. scrollToKeepCaretOnScreen();
  37160. updateScrollBars();
  37161. }
  37162. void CodeEditorComponent::deselectAll()
  37163. {
  37164. if (selectionStart != selectionEnd)
  37165. triggerAsyncUpdate();
  37166. selectionStart = caretPos;
  37167. selectionEnd = caretPos;
  37168. }
  37169. void CodeEditorComponent::updateScrollBars()
  37170. {
  37171. verticalScrollBar->setRangeLimits (0, jmax (document.getNumLines(), firstLineOnScreen + linesOnScreen));
  37172. verticalScrollBar->setCurrentRange (firstLineOnScreen, linesOnScreen);
  37173. horizontalScrollBar->setRangeLimits (0, jmax ((double) document.getMaximumLineLength(), xOffset + columnsOnScreen));
  37174. horizontalScrollBar->setCurrentRange (xOffset, columnsOnScreen);
  37175. }
  37176. void CodeEditorComponent::scrollToLineInternal (int newFirstLineOnScreen)
  37177. {
  37178. newFirstLineOnScreen = jlimit (0, jmax (0, document.getNumLines() - 1),
  37179. newFirstLineOnScreen);
  37180. if (newFirstLineOnScreen != firstLineOnScreen)
  37181. {
  37182. firstLineOnScreen = newFirstLineOnScreen;
  37183. caret->updatePosition();
  37184. updateCachedIterators (firstLineOnScreen);
  37185. triggerAsyncUpdate();
  37186. }
  37187. }
  37188. void CodeEditorComponent::scrollToColumnInternal (double column)
  37189. {
  37190. const double newOffset = jlimit (0.0, document.getMaximumLineLength() + 3.0, column);
  37191. if (xOffset != newOffset)
  37192. {
  37193. xOffset = newOffset;
  37194. caret->updatePosition();
  37195. repaint();
  37196. }
  37197. }
  37198. void CodeEditorComponent::scrollToLine (int newFirstLineOnScreen)
  37199. {
  37200. scrollToLineInternal (newFirstLineOnScreen);
  37201. updateScrollBars();
  37202. }
  37203. void CodeEditorComponent::scrollToColumn (int newFirstColumnOnScreen)
  37204. {
  37205. scrollToColumnInternal (newFirstColumnOnScreen);
  37206. updateScrollBars();
  37207. }
  37208. void CodeEditorComponent::scrollBy (int deltaLines)
  37209. {
  37210. scrollToLine (firstLineOnScreen + deltaLines);
  37211. }
  37212. void CodeEditorComponent::scrollToKeepCaretOnScreen()
  37213. {
  37214. if (caretPos.getLineNumber() < firstLineOnScreen)
  37215. scrollBy (caretPos.getLineNumber() - firstLineOnScreen);
  37216. else if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  37217. scrollBy (caretPos.getLineNumber() - (firstLineOnScreen + linesOnScreen - 1));
  37218. const int column = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  37219. if (column >= xOffset + columnsOnScreen - 1)
  37220. scrollToColumn (column + 1 - columnsOnScreen);
  37221. else if (column < xOffset)
  37222. scrollToColumn (column);
  37223. }
  37224. const Rectangle<int> CodeEditorComponent::getCharacterBounds (const CodeDocument::Position& pos) const
  37225. {
  37226. return Rectangle<int> (roundToInt ((gutter - xOffset * charWidth) + indexToColumn (pos.getLineNumber(), pos.getIndexInLine()) * charWidth),
  37227. (pos.getLineNumber() - firstLineOnScreen) * lineHeight,
  37228. roundToInt (charWidth),
  37229. lineHeight);
  37230. }
  37231. const CodeDocument::Position CodeEditorComponent::getPositionAt (int x, int y)
  37232. {
  37233. const int line = y / lineHeight + firstLineOnScreen;
  37234. const int column = roundToInt ((x - (gutter - xOffset * charWidth)) / charWidth);
  37235. const int index = columnToIndex (line, column);
  37236. return CodeDocument::Position (&document, line, index);
  37237. }
  37238. void CodeEditorComponent::insertTextAtCaret (const String& newText)
  37239. {
  37240. document.deleteSection (selectionStart, selectionEnd);
  37241. if (newText.isNotEmpty())
  37242. document.insertText (caretPos, newText);
  37243. scrollToKeepCaretOnScreen();
  37244. }
  37245. void CodeEditorComponent::insertTabAtCaret()
  37246. {
  37247. if (CharacterFunctions::isWhitespace (caretPos.getCharacter())
  37248. && caretPos.getLineNumber() == caretPos.movedBy (1).getLineNumber())
  37249. {
  37250. moveCaretTo (document.findWordBreakAfter (caretPos), false);
  37251. }
  37252. if (useSpacesForTabs)
  37253. {
  37254. const int caretCol = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  37255. const int spacesNeeded = spacesPerTab - (caretCol % spacesPerTab);
  37256. insertTextAtCaret (String::repeatedString (" ", spacesNeeded));
  37257. }
  37258. else
  37259. {
  37260. insertTextAtCaret ("\t");
  37261. }
  37262. }
  37263. void CodeEditorComponent::cut()
  37264. {
  37265. insertTextAtCaret (String::empty);
  37266. }
  37267. void CodeEditorComponent::copy()
  37268. {
  37269. newTransaction();
  37270. const String selection (document.getTextBetween (selectionStart, selectionEnd));
  37271. if (selection.isNotEmpty())
  37272. SystemClipboard::copyTextToClipboard (selection);
  37273. }
  37274. void CodeEditorComponent::copyThenCut()
  37275. {
  37276. copy();
  37277. cut();
  37278. newTransaction();
  37279. }
  37280. void CodeEditorComponent::paste()
  37281. {
  37282. newTransaction();
  37283. const String clip (SystemClipboard::getTextFromClipboard());
  37284. if (clip.isNotEmpty())
  37285. insertTextAtCaret (clip);
  37286. newTransaction();
  37287. }
  37288. void CodeEditorComponent::cursorLeft (const bool moveInWholeWordSteps, const bool selecting)
  37289. {
  37290. newTransaction();
  37291. if (moveInWholeWordSteps)
  37292. moveCaretTo (document.findWordBreakBefore (caretPos), selecting);
  37293. else
  37294. moveCaretTo (caretPos.movedBy (-1), selecting);
  37295. }
  37296. void CodeEditorComponent::cursorRight (const bool moveInWholeWordSteps, const bool selecting)
  37297. {
  37298. newTransaction();
  37299. if (moveInWholeWordSteps)
  37300. moveCaretTo (document.findWordBreakAfter (caretPos), selecting);
  37301. else
  37302. moveCaretTo (caretPos.movedBy (1), selecting);
  37303. }
  37304. void CodeEditorComponent::moveLineDelta (const int delta, const bool selecting)
  37305. {
  37306. CodeDocument::Position pos (caretPos);
  37307. const int newLineNum = pos.getLineNumber() + delta;
  37308. if (columnToTryToMaintain < 0)
  37309. columnToTryToMaintain = indexToColumn (pos.getLineNumber(), pos.getIndexInLine());
  37310. pos.setLineAndIndex (newLineNum, columnToIndex (newLineNum, columnToTryToMaintain));
  37311. const int colToMaintain = columnToTryToMaintain;
  37312. moveCaretTo (pos, selecting);
  37313. columnToTryToMaintain = colToMaintain;
  37314. }
  37315. void CodeEditorComponent::cursorDown (const bool selecting)
  37316. {
  37317. newTransaction();
  37318. if (caretPos.getLineNumber() == document.getNumLines() - 1)
  37319. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  37320. else
  37321. moveLineDelta (1, selecting);
  37322. }
  37323. void CodeEditorComponent::cursorUp (const bool selecting)
  37324. {
  37325. newTransaction();
  37326. if (caretPos.getLineNumber() == 0)
  37327. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  37328. else
  37329. moveLineDelta (-1, selecting);
  37330. }
  37331. void CodeEditorComponent::pageDown (const bool selecting)
  37332. {
  37333. newTransaction();
  37334. scrollBy (jlimit (0, linesOnScreen, 1 + document.getNumLines() - firstLineOnScreen - linesOnScreen));
  37335. moveLineDelta (linesOnScreen, selecting);
  37336. }
  37337. void CodeEditorComponent::pageUp (const bool selecting)
  37338. {
  37339. newTransaction();
  37340. scrollBy (-linesOnScreen);
  37341. moveLineDelta (-linesOnScreen, selecting);
  37342. }
  37343. void CodeEditorComponent::scrollUp()
  37344. {
  37345. newTransaction();
  37346. scrollBy (1);
  37347. if (caretPos.getLineNumber() < firstLineOnScreen)
  37348. moveLineDelta (1, false);
  37349. }
  37350. void CodeEditorComponent::scrollDown()
  37351. {
  37352. newTransaction();
  37353. scrollBy (-1);
  37354. if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  37355. moveLineDelta (-1, false);
  37356. }
  37357. void CodeEditorComponent::goToStartOfDocument (const bool selecting)
  37358. {
  37359. newTransaction();
  37360. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  37361. }
  37362. static int findFirstNonWhitespaceChar (const String& line) throw()
  37363. {
  37364. const int len = line.length();
  37365. for (int i = 0; i < len; ++i)
  37366. if (! CharacterFunctions::isWhitespace (line [i]))
  37367. return i;
  37368. return 0;
  37369. }
  37370. void CodeEditorComponent::goToStartOfLine (const bool selecting)
  37371. {
  37372. newTransaction();
  37373. int index = findFirstNonWhitespaceChar (caretPos.getLineText());
  37374. if (index >= caretPos.getIndexInLine() && caretPos.getIndexInLine() > 0)
  37375. index = 0;
  37376. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), index), selecting);
  37377. }
  37378. void CodeEditorComponent::goToEndOfDocument (const bool selecting)
  37379. {
  37380. newTransaction();
  37381. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  37382. }
  37383. void CodeEditorComponent::goToEndOfLine (const bool selecting)
  37384. {
  37385. newTransaction();
  37386. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), std::numeric_limits<int>::max()), selecting);
  37387. }
  37388. void CodeEditorComponent::backspace (const bool moveInWholeWordSteps)
  37389. {
  37390. if (moveInWholeWordSteps)
  37391. {
  37392. cut(); // in case something is already highlighted
  37393. moveCaretTo (document.findWordBreakBefore (caretPos), true);
  37394. }
  37395. else
  37396. {
  37397. if (selectionStart == selectionEnd)
  37398. selectionStart.moveBy (-1);
  37399. }
  37400. cut();
  37401. }
  37402. void CodeEditorComponent::deleteForward (const bool moveInWholeWordSteps)
  37403. {
  37404. if (moveInWholeWordSteps)
  37405. {
  37406. cut(); // in case something is already highlighted
  37407. moveCaretTo (document.findWordBreakAfter (caretPos), true);
  37408. }
  37409. else
  37410. {
  37411. if (selectionStart == selectionEnd)
  37412. selectionEnd.moveBy (1);
  37413. else
  37414. newTransaction();
  37415. }
  37416. cut();
  37417. }
  37418. void CodeEditorComponent::selectAll()
  37419. {
  37420. newTransaction();
  37421. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), false);
  37422. moveCaretTo (CodeDocument::Position (&document, 0, 0), true);
  37423. }
  37424. void CodeEditorComponent::undo()
  37425. {
  37426. document.undo();
  37427. scrollToKeepCaretOnScreen();
  37428. }
  37429. void CodeEditorComponent::redo()
  37430. {
  37431. document.redo();
  37432. scrollToKeepCaretOnScreen();
  37433. }
  37434. void CodeEditorComponent::newTransaction()
  37435. {
  37436. document.newTransaction();
  37437. startTimer (600);
  37438. }
  37439. void CodeEditorComponent::timerCallback()
  37440. {
  37441. newTransaction();
  37442. }
  37443. const Range<int> CodeEditorComponent::getHighlightedRegion() const
  37444. {
  37445. return Range<int> (selectionStart.getPosition(), selectionEnd.getPosition());
  37446. }
  37447. void CodeEditorComponent::setHighlightedRegion (const Range<int>& newRange)
  37448. {
  37449. moveCaretTo (CodeDocument::Position (&document, newRange.getStart()), false);
  37450. moveCaretTo (CodeDocument::Position (&document, newRange.getEnd()), true);
  37451. }
  37452. const String CodeEditorComponent::getTextInRange (const Range<int>& range) const
  37453. {
  37454. return document.getTextBetween (CodeDocument::Position (&document, range.getStart()),
  37455. CodeDocument::Position (&document, range.getEnd()));
  37456. }
  37457. bool CodeEditorComponent::keyPressed (const KeyPress& key)
  37458. {
  37459. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  37460. const bool shiftDown = key.getModifiers().isShiftDown();
  37461. if (key.isKeyCode (KeyPress::leftKey))
  37462. {
  37463. cursorLeft (moveInWholeWordSteps, shiftDown);
  37464. }
  37465. else if (key.isKeyCode (KeyPress::rightKey))
  37466. {
  37467. cursorRight (moveInWholeWordSteps, shiftDown);
  37468. }
  37469. else if (key.isKeyCode (KeyPress::upKey))
  37470. {
  37471. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  37472. scrollDown();
  37473. #if JUCE_MAC
  37474. else if (key.getModifiers().isCommandDown())
  37475. goToStartOfDocument (shiftDown);
  37476. #endif
  37477. else
  37478. cursorUp (shiftDown);
  37479. }
  37480. else if (key.isKeyCode (KeyPress::downKey))
  37481. {
  37482. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  37483. scrollUp();
  37484. #if JUCE_MAC
  37485. else if (key.getModifiers().isCommandDown())
  37486. goToEndOfDocument (shiftDown);
  37487. #endif
  37488. else
  37489. cursorDown (shiftDown);
  37490. }
  37491. else if (key.isKeyCode (KeyPress::pageDownKey))
  37492. {
  37493. pageDown (shiftDown);
  37494. }
  37495. else if (key.isKeyCode (KeyPress::pageUpKey))
  37496. {
  37497. pageUp (shiftDown);
  37498. }
  37499. else if (key.isKeyCode (KeyPress::homeKey))
  37500. {
  37501. if (moveInWholeWordSteps)
  37502. goToStartOfDocument (shiftDown);
  37503. else
  37504. goToStartOfLine (shiftDown);
  37505. }
  37506. else if (key.isKeyCode (KeyPress::endKey))
  37507. {
  37508. if (moveInWholeWordSteps)
  37509. goToEndOfDocument (shiftDown);
  37510. else
  37511. goToEndOfLine (shiftDown);
  37512. }
  37513. else if (key.isKeyCode (KeyPress::backspaceKey))
  37514. {
  37515. backspace (moveInWholeWordSteps);
  37516. }
  37517. else if (key.isKeyCode (KeyPress::deleteKey))
  37518. {
  37519. deleteForward (moveInWholeWordSteps);
  37520. }
  37521. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0))
  37522. {
  37523. copy();
  37524. }
  37525. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  37526. {
  37527. copyThenCut();
  37528. }
  37529. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0))
  37530. {
  37531. paste();
  37532. }
  37533. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  37534. {
  37535. undo();
  37536. }
  37537. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0)
  37538. || key == KeyPress ('z', ModifierKeys::commandModifier | ModifierKeys::shiftModifier, 0))
  37539. {
  37540. redo();
  37541. }
  37542. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  37543. {
  37544. selectAll();
  37545. }
  37546. else if (key == KeyPress::tabKey || key.getTextCharacter() == '\t')
  37547. {
  37548. insertTabAtCaret();
  37549. }
  37550. else if (key == KeyPress::returnKey)
  37551. {
  37552. newTransaction();
  37553. insertTextAtCaret (document.getNewLineCharacters());
  37554. }
  37555. else if (key.isKeyCode (KeyPress::escapeKey))
  37556. {
  37557. newTransaction();
  37558. }
  37559. else if (key.getTextCharacter() >= ' ')
  37560. {
  37561. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  37562. }
  37563. else
  37564. {
  37565. return false;
  37566. }
  37567. return true;
  37568. }
  37569. void CodeEditorComponent::mouseDown (const MouseEvent& e)
  37570. {
  37571. newTransaction();
  37572. dragType = notDragging;
  37573. if (! e.mods.isPopupMenu())
  37574. {
  37575. beginDragAutoRepeat (100);
  37576. moveCaretTo (getPositionAt (e.x, e.y), e.mods.isShiftDown());
  37577. }
  37578. else
  37579. {
  37580. /*PopupMenu m;
  37581. addPopupMenuItems (m, &e);
  37582. const int result = m.show();
  37583. if (result != 0)
  37584. performPopupMenuAction (result);
  37585. */
  37586. }
  37587. }
  37588. void CodeEditorComponent::mouseDrag (const MouseEvent& e)
  37589. {
  37590. if (! e.mods.isPopupMenu())
  37591. moveCaretTo (getPositionAt (e.x, e.y), true);
  37592. }
  37593. void CodeEditorComponent::mouseUp (const MouseEvent&)
  37594. {
  37595. newTransaction();
  37596. beginDragAutoRepeat (0);
  37597. dragType = notDragging;
  37598. }
  37599. void CodeEditorComponent::mouseDoubleClick (const MouseEvent& e)
  37600. {
  37601. CodeDocument::Position tokenStart (getPositionAt (e.x, e.y));
  37602. CodeDocument::Position tokenEnd (tokenStart);
  37603. if (e.getNumberOfClicks() > 2)
  37604. {
  37605. tokenStart.setLineAndIndex (tokenStart.getLineNumber(), 0);
  37606. tokenEnd.setLineAndIndex (tokenStart.getLineNumber() + 1, 0);
  37607. }
  37608. else
  37609. {
  37610. while (CharacterFunctions::isLetterOrDigit (tokenEnd.getCharacter()))
  37611. tokenEnd.moveBy (1);
  37612. tokenStart = tokenEnd;
  37613. while (tokenStart.getIndexInLine() > 0
  37614. && CharacterFunctions::isLetterOrDigit (tokenStart.movedBy (-1).getCharacter()))
  37615. tokenStart.moveBy (-1);
  37616. }
  37617. moveCaretTo (tokenEnd, false);
  37618. moveCaretTo (tokenStart, true);
  37619. }
  37620. void CodeEditorComponent::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  37621. {
  37622. if ((verticalScrollBar->isVisible() && wheelIncrementY != 0)
  37623. || (horizontalScrollBar->isVisible() && wheelIncrementX != 0))
  37624. {
  37625. verticalScrollBar->mouseWheelMove (e, 0, wheelIncrementY);
  37626. horizontalScrollBar->mouseWheelMove (e, wheelIncrementX, 0);
  37627. }
  37628. else
  37629. {
  37630. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  37631. }
  37632. }
  37633. void CodeEditorComponent::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  37634. {
  37635. if (scrollBarThatHasMoved == verticalScrollBar)
  37636. scrollToLineInternal ((int) newRangeStart);
  37637. else
  37638. scrollToColumnInternal (newRangeStart);
  37639. }
  37640. void CodeEditorComponent::focusGained (FocusChangeType)
  37641. {
  37642. caret->updatePosition();
  37643. }
  37644. void CodeEditorComponent::focusLost (FocusChangeType)
  37645. {
  37646. caret->updatePosition();
  37647. }
  37648. void CodeEditorComponent::setTabSize (const int numSpaces, const bool insertSpaces)
  37649. {
  37650. useSpacesForTabs = insertSpaces;
  37651. if (spacesPerTab != numSpaces)
  37652. {
  37653. spacesPerTab = numSpaces;
  37654. triggerAsyncUpdate();
  37655. }
  37656. }
  37657. int CodeEditorComponent::indexToColumn (int lineNum, int index) const throw()
  37658. {
  37659. const String line (document.getLine (lineNum));
  37660. jassert (index <= line.length());
  37661. int col = 0;
  37662. for (int i = 0; i < index; ++i)
  37663. {
  37664. if (line[i] != '\t')
  37665. ++col;
  37666. else
  37667. col += getTabSize() - (col % getTabSize());
  37668. }
  37669. return col;
  37670. }
  37671. int CodeEditorComponent::columnToIndex (int lineNum, int column) const throw()
  37672. {
  37673. const String line (document.getLine (lineNum));
  37674. const int lineLength = line.length();
  37675. int i, col = 0;
  37676. for (i = 0; i < lineLength; ++i)
  37677. {
  37678. if (line[i] != '\t')
  37679. ++col;
  37680. else
  37681. col += getTabSize() - (col % getTabSize());
  37682. if (col > column)
  37683. break;
  37684. }
  37685. return i;
  37686. }
  37687. void CodeEditorComponent::setFont (const Font& newFont)
  37688. {
  37689. font = newFont;
  37690. charWidth = font.getStringWidthFloat ("0");
  37691. lineHeight = roundToInt (font.getHeight());
  37692. resized();
  37693. }
  37694. void CodeEditorComponent::resetToDefaultColours()
  37695. {
  37696. coloursForTokenCategories.clear();
  37697. if (codeTokeniser != 0)
  37698. {
  37699. for (int i = codeTokeniser->getTokenTypes().size(); --i >= 0;)
  37700. setColourForTokenType (i, codeTokeniser->getDefaultColour (i));
  37701. }
  37702. }
  37703. void CodeEditorComponent::setColourForTokenType (const int tokenType, const Colour& colour)
  37704. {
  37705. jassert (tokenType < 256);
  37706. while (coloursForTokenCategories.size() < tokenType)
  37707. coloursForTokenCategories.add (Colours::black);
  37708. coloursForTokenCategories.set (tokenType, colour);
  37709. repaint();
  37710. }
  37711. const Colour CodeEditorComponent::getColourForTokenType (const int tokenType) const
  37712. {
  37713. if (((unsigned int) tokenType) >= (unsigned int) coloursForTokenCategories.size())
  37714. return findColour (CodeEditorComponent::defaultTextColourId);
  37715. return coloursForTokenCategories.getReference (tokenType);
  37716. }
  37717. void CodeEditorComponent::clearCachedIterators (const int firstLineToBeInvalid)
  37718. {
  37719. int i;
  37720. for (i = cachedIterators.size(); --i >= 0;)
  37721. if (cachedIterators.getUnchecked (i)->getLine() < firstLineToBeInvalid)
  37722. break;
  37723. cachedIterators.removeRange (jmax (0, i - 1), cachedIterators.size());
  37724. }
  37725. void CodeEditorComponent::updateCachedIterators (int maxLineNum)
  37726. {
  37727. const int maxNumCachedPositions = 5000;
  37728. const int linesBetweenCachedSources = jmax (10, document.getNumLines() / maxNumCachedPositions);
  37729. if (cachedIterators.size() == 0)
  37730. cachedIterators.add (new CodeDocument::Iterator (&document));
  37731. if (codeTokeniser == 0)
  37732. return;
  37733. for (;;)
  37734. {
  37735. CodeDocument::Iterator* last = cachedIterators.getLast();
  37736. if (last->getLine() >= maxLineNum)
  37737. break;
  37738. CodeDocument::Iterator* t = new CodeDocument::Iterator (*last);
  37739. cachedIterators.add (t);
  37740. const int targetLine = last->getLine() + linesBetweenCachedSources;
  37741. for (;;)
  37742. {
  37743. codeTokeniser->readNextToken (*t);
  37744. if (t->getLine() >= targetLine)
  37745. break;
  37746. if (t->isEOF())
  37747. return;
  37748. }
  37749. }
  37750. }
  37751. void CodeEditorComponent::getIteratorForPosition (int position, CodeDocument::Iterator& source)
  37752. {
  37753. if (codeTokeniser == 0)
  37754. return;
  37755. for (int i = cachedIterators.size(); --i >= 0;)
  37756. {
  37757. CodeDocument::Iterator* t = cachedIterators.getUnchecked (i);
  37758. if (t->getPosition() <= position)
  37759. {
  37760. source = *t;
  37761. break;
  37762. }
  37763. }
  37764. while (source.getPosition() < position)
  37765. {
  37766. const CodeDocument::Iterator original (source);
  37767. codeTokeniser->readNextToken (source);
  37768. if (source.getPosition() > position || source.isEOF())
  37769. {
  37770. source = original;
  37771. break;
  37772. }
  37773. }
  37774. }
  37775. END_JUCE_NAMESPACE
  37776. /*** End of inlined file: juce_CodeEditorComponent.cpp ***/
  37777. /*** Start of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  37778. BEGIN_JUCE_NAMESPACE
  37779. CPlusPlusCodeTokeniser::CPlusPlusCodeTokeniser()
  37780. {
  37781. }
  37782. CPlusPlusCodeTokeniser::~CPlusPlusCodeTokeniser()
  37783. {
  37784. }
  37785. namespace CppTokeniser
  37786. {
  37787. static bool isIdentifierStart (const juce_wchar c) throw()
  37788. {
  37789. return CharacterFunctions::isLetter (c)
  37790. || c == '_' || c == '@';
  37791. }
  37792. static bool isIdentifierBody (const juce_wchar c) throw()
  37793. {
  37794. return CharacterFunctions::isLetterOrDigit (c)
  37795. || c == '_' || c == '@';
  37796. }
  37797. static bool isReservedKeyword (const juce_wchar* const token, const int tokenLength) throw()
  37798. {
  37799. static const juce_wchar* const keywords2Char[] =
  37800. { JUCE_T("if"), JUCE_T("do"), JUCE_T("or"), JUCE_T("id"), 0 };
  37801. static const juce_wchar* const keywords3Char[] =
  37802. { 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 };
  37803. static const juce_wchar* const keywords4Char[] =
  37804. { JUCE_T("bool"), JUCE_T("void"), JUCE_T("this"), JUCE_T("true"), JUCE_T("long"), JUCE_T("else"), JUCE_T("char"),
  37805. JUCE_T("enum"), JUCE_T("case"), JUCE_T("goto"), JUCE_T("auto"), 0 };
  37806. static const juce_wchar* const keywords5Char[] =
  37807. { JUCE_T("while"), JUCE_T("bitor"), JUCE_T("break"), JUCE_T("catch"), JUCE_T("class"), JUCE_T("compl"), JUCE_T("const"), JUCE_T("false"),
  37808. JUCE_T("float"), JUCE_T("short"), JUCE_T("throw"), JUCE_T("union"), JUCE_T("using"), JUCE_T("or_eq"), 0 };
  37809. static const juce_wchar* const keywords6Char[] =
  37810. { JUCE_T("return"), JUCE_T("struct"), JUCE_T("and_eq"), JUCE_T("bitand"), JUCE_T("delete"), JUCE_T("double"), JUCE_T("extern"),
  37811. JUCE_T("friend"), JUCE_T("inline"), JUCE_T("not_eq"), JUCE_T("public"), JUCE_T("sizeof"), JUCE_T("static"), JUCE_T("signed"),
  37812. JUCE_T("switch"), JUCE_T("typeid"), JUCE_T("wchar_t"), JUCE_T("xor_eq"), 0};
  37813. static const juce_wchar* const keywordsOther[] =
  37814. { JUCE_T("const_cast"), JUCE_T("continue"), JUCE_T("default"), JUCE_T("explicit"), JUCE_T("mutable"), JUCE_T("namespace"),
  37815. JUCE_T("operator"), JUCE_T("private"), JUCE_T("protected"), JUCE_T("register"), JUCE_T("reinterpret_cast"), JUCE_T("static_cast"),
  37816. JUCE_T("template"), JUCE_T("typedef"), JUCE_T("typename"), JUCE_T("unsigned"), JUCE_T("virtual"), JUCE_T("volatile"),
  37817. JUCE_T("@implementation"), JUCE_T("@interface"), JUCE_T("@end"), JUCE_T("@synthesize"), JUCE_T("@dynamic"), JUCE_T("@public"),
  37818. JUCE_T("@private"), JUCE_T("@property"), JUCE_T("@protected"), JUCE_T("@class"), 0 };
  37819. const juce_wchar* const* k;
  37820. switch (tokenLength)
  37821. {
  37822. case 2: k = keywords2Char; break;
  37823. case 3: k = keywords3Char; break;
  37824. case 4: k = keywords4Char; break;
  37825. case 5: k = keywords5Char; break;
  37826. case 6: k = keywords6Char; break;
  37827. default:
  37828. if (tokenLength < 2 || tokenLength > 16)
  37829. return false;
  37830. k = keywordsOther;
  37831. break;
  37832. }
  37833. int i = 0;
  37834. while (k[i] != 0)
  37835. {
  37836. if (k[i][0] == token[0] && CharacterFunctions::compare (k[i], token) == 0)
  37837. return true;
  37838. ++i;
  37839. }
  37840. return false;
  37841. }
  37842. static int parseIdentifier (CodeDocument::Iterator& source) throw()
  37843. {
  37844. int tokenLength = 0;
  37845. juce_wchar possibleIdentifier [19];
  37846. while (isIdentifierBody (source.peekNextChar()))
  37847. {
  37848. const juce_wchar c = source.nextChar();
  37849. if (tokenLength < numElementsInArray (possibleIdentifier) - 1)
  37850. possibleIdentifier [tokenLength] = c;
  37851. ++tokenLength;
  37852. }
  37853. if (tokenLength > 1 && tokenLength <= 16)
  37854. {
  37855. possibleIdentifier [tokenLength] = 0;
  37856. if (isReservedKeyword (possibleIdentifier, tokenLength))
  37857. return CPlusPlusCodeTokeniser::tokenType_builtInKeyword;
  37858. }
  37859. return CPlusPlusCodeTokeniser::tokenType_identifier;
  37860. }
  37861. static bool skipNumberSuffix (CodeDocument::Iterator& source)
  37862. {
  37863. const juce_wchar c = source.peekNextChar();
  37864. if (c == 'l' || c == 'L' || c == 'u' || c == 'U')
  37865. source.skip();
  37866. if (CharacterFunctions::isLetterOrDigit (source.peekNextChar()))
  37867. return false;
  37868. return true;
  37869. }
  37870. static bool isHexDigit (const juce_wchar c) throw()
  37871. {
  37872. return (c >= '0' && c <= '9')
  37873. || (c >= 'a' && c <= 'f')
  37874. || (c >= 'A' && c <= 'F');
  37875. }
  37876. static bool parseHexLiteral (CodeDocument::Iterator& source) throw()
  37877. {
  37878. if (source.nextChar() != '0')
  37879. return false;
  37880. juce_wchar c = source.nextChar();
  37881. if (c != 'x' && c != 'X')
  37882. return false;
  37883. int numDigits = 0;
  37884. while (isHexDigit (source.peekNextChar()))
  37885. {
  37886. ++numDigits;
  37887. source.skip();
  37888. }
  37889. if (numDigits == 0)
  37890. return false;
  37891. return skipNumberSuffix (source);
  37892. }
  37893. static bool isOctalDigit (const juce_wchar c) throw()
  37894. {
  37895. return c >= '0' && c <= '7';
  37896. }
  37897. static bool parseOctalLiteral (CodeDocument::Iterator& source) throw()
  37898. {
  37899. if (source.nextChar() != '0')
  37900. return false;
  37901. if (! isOctalDigit (source.nextChar()))
  37902. return false;
  37903. while (isOctalDigit (source.peekNextChar()))
  37904. source.skip();
  37905. return skipNumberSuffix (source);
  37906. }
  37907. static bool isDecimalDigit (const juce_wchar c) throw()
  37908. {
  37909. return c >= '0' && c <= '9';
  37910. }
  37911. static bool parseDecimalLiteral (CodeDocument::Iterator& source) throw()
  37912. {
  37913. int numChars = 0;
  37914. while (isDecimalDigit (source.peekNextChar()))
  37915. {
  37916. ++numChars;
  37917. source.skip();
  37918. }
  37919. if (numChars == 0)
  37920. return false;
  37921. return skipNumberSuffix (source);
  37922. }
  37923. static bool parseFloatLiteral (CodeDocument::Iterator& source) throw()
  37924. {
  37925. int numDigits = 0;
  37926. while (isDecimalDigit (source.peekNextChar()))
  37927. {
  37928. source.skip();
  37929. ++numDigits;
  37930. }
  37931. const bool hasPoint = (source.peekNextChar() == '.');
  37932. if (hasPoint)
  37933. {
  37934. source.skip();
  37935. while (isDecimalDigit (source.peekNextChar()))
  37936. {
  37937. source.skip();
  37938. ++numDigits;
  37939. }
  37940. }
  37941. if (numDigits == 0)
  37942. return false;
  37943. juce_wchar c = source.peekNextChar();
  37944. const bool hasExponent = (c == 'e' || c == 'E');
  37945. if (hasExponent)
  37946. {
  37947. source.skip();
  37948. c = source.peekNextChar();
  37949. if (c == '+' || c == '-')
  37950. source.skip();
  37951. int numExpDigits = 0;
  37952. while (isDecimalDigit (source.peekNextChar()))
  37953. {
  37954. source.skip();
  37955. ++numExpDigits;
  37956. }
  37957. if (numExpDigits == 0)
  37958. return false;
  37959. }
  37960. c = source.peekNextChar();
  37961. if (c == 'f' || c == 'F')
  37962. source.skip();
  37963. else if (! (hasExponent || hasPoint))
  37964. return false;
  37965. return true;
  37966. }
  37967. static int parseNumber (CodeDocument::Iterator& source)
  37968. {
  37969. const CodeDocument::Iterator original (source);
  37970. if (parseFloatLiteral (source))
  37971. return CPlusPlusCodeTokeniser::tokenType_floatLiteral;
  37972. source = original;
  37973. if (parseHexLiteral (source))
  37974. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37975. source = original;
  37976. if (parseOctalLiteral (source))
  37977. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37978. source = original;
  37979. if (parseDecimalLiteral (source))
  37980. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37981. source = original;
  37982. source.skip();
  37983. return CPlusPlusCodeTokeniser::tokenType_error;
  37984. }
  37985. static void skipQuotedString (CodeDocument::Iterator& source) throw()
  37986. {
  37987. const juce_wchar quote = source.nextChar();
  37988. for (;;)
  37989. {
  37990. const juce_wchar c = source.nextChar();
  37991. if (c == quote || c == 0)
  37992. break;
  37993. if (c == '\\')
  37994. source.skip();
  37995. }
  37996. }
  37997. static void skipComment (CodeDocument::Iterator& source) throw()
  37998. {
  37999. bool lastWasStar = false;
  38000. for (;;)
  38001. {
  38002. const juce_wchar c = source.nextChar();
  38003. if (c == 0 || (c == '/' && lastWasStar))
  38004. break;
  38005. lastWasStar = (c == '*');
  38006. }
  38007. }
  38008. }
  38009. int CPlusPlusCodeTokeniser::readNextToken (CodeDocument::Iterator& source)
  38010. {
  38011. int result = tokenType_error;
  38012. source.skipWhitespace();
  38013. juce_wchar firstChar = source.peekNextChar();
  38014. switch (firstChar)
  38015. {
  38016. case 0:
  38017. source.skip();
  38018. break;
  38019. case '0':
  38020. case '1':
  38021. case '2':
  38022. case '3':
  38023. case '4':
  38024. case '5':
  38025. case '6':
  38026. case '7':
  38027. case '8':
  38028. case '9':
  38029. result = CppTokeniser::parseNumber (source);
  38030. break;
  38031. case '.':
  38032. result = CppTokeniser::parseNumber (source);
  38033. if (result == tokenType_error)
  38034. result = tokenType_punctuation;
  38035. break;
  38036. case ',':
  38037. case ';':
  38038. case ':':
  38039. source.skip();
  38040. result = tokenType_punctuation;
  38041. break;
  38042. case '(':
  38043. case ')':
  38044. case '{':
  38045. case '}':
  38046. case '[':
  38047. case ']':
  38048. source.skip();
  38049. result = tokenType_bracket;
  38050. break;
  38051. case '"':
  38052. case '\'':
  38053. CppTokeniser::skipQuotedString (source);
  38054. result = tokenType_stringLiteral;
  38055. break;
  38056. case '+':
  38057. result = tokenType_operator;
  38058. source.skip();
  38059. if (source.peekNextChar() == '+')
  38060. source.skip();
  38061. else if (source.peekNextChar() == '=')
  38062. source.skip();
  38063. break;
  38064. case '-':
  38065. source.skip();
  38066. result = CppTokeniser::parseNumber (source);
  38067. if (result == tokenType_error)
  38068. {
  38069. result = tokenType_operator;
  38070. if (source.peekNextChar() == '-')
  38071. source.skip();
  38072. else if (source.peekNextChar() == '=')
  38073. source.skip();
  38074. }
  38075. break;
  38076. case '*':
  38077. case '%':
  38078. case '=':
  38079. case '!':
  38080. result = tokenType_operator;
  38081. source.skip();
  38082. if (source.peekNextChar() == '=')
  38083. source.skip();
  38084. break;
  38085. case '/':
  38086. result = tokenType_operator;
  38087. source.skip();
  38088. if (source.peekNextChar() == '=')
  38089. {
  38090. source.skip();
  38091. }
  38092. else if (source.peekNextChar() == '/')
  38093. {
  38094. result = tokenType_comment;
  38095. source.skipToEndOfLine();
  38096. }
  38097. else if (source.peekNextChar() == '*')
  38098. {
  38099. source.skip();
  38100. result = tokenType_comment;
  38101. CppTokeniser::skipComment (source);
  38102. }
  38103. break;
  38104. case '?':
  38105. case '~':
  38106. source.skip();
  38107. result = tokenType_operator;
  38108. break;
  38109. case '<':
  38110. source.skip();
  38111. result = tokenType_operator;
  38112. if (source.peekNextChar() == '=')
  38113. {
  38114. source.skip();
  38115. }
  38116. else if (source.peekNextChar() == '<')
  38117. {
  38118. source.skip();
  38119. if (source.peekNextChar() == '=')
  38120. source.skip();
  38121. }
  38122. break;
  38123. case '>':
  38124. source.skip();
  38125. result = tokenType_operator;
  38126. if (source.peekNextChar() == '=')
  38127. {
  38128. source.skip();
  38129. }
  38130. else if (source.peekNextChar() == '<')
  38131. {
  38132. source.skip();
  38133. if (source.peekNextChar() == '=')
  38134. source.skip();
  38135. }
  38136. break;
  38137. case '|':
  38138. source.skip();
  38139. result = tokenType_operator;
  38140. if (source.peekNextChar() == '=')
  38141. {
  38142. source.skip();
  38143. }
  38144. else if (source.peekNextChar() == '|')
  38145. {
  38146. source.skip();
  38147. if (source.peekNextChar() == '=')
  38148. source.skip();
  38149. }
  38150. break;
  38151. case '&':
  38152. source.skip();
  38153. result = tokenType_operator;
  38154. if (source.peekNextChar() == '=')
  38155. {
  38156. source.skip();
  38157. }
  38158. else if (source.peekNextChar() == '&')
  38159. {
  38160. source.skip();
  38161. if (source.peekNextChar() == '=')
  38162. source.skip();
  38163. }
  38164. break;
  38165. case '^':
  38166. source.skip();
  38167. result = tokenType_operator;
  38168. if (source.peekNextChar() == '=')
  38169. {
  38170. source.skip();
  38171. }
  38172. else if (source.peekNextChar() == '^')
  38173. {
  38174. source.skip();
  38175. if (source.peekNextChar() == '=')
  38176. source.skip();
  38177. }
  38178. break;
  38179. case '#':
  38180. result = tokenType_preprocessor;
  38181. source.skipToEndOfLine();
  38182. break;
  38183. default:
  38184. if (CppTokeniser::isIdentifierStart (firstChar))
  38185. result = CppTokeniser::parseIdentifier (source);
  38186. else
  38187. source.skip();
  38188. break;
  38189. }
  38190. return result;
  38191. }
  38192. const StringArray CPlusPlusCodeTokeniser::getTokenTypes()
  38193. {
  38194. const char* const types[] =
  38195. {
  38196. "Error",
  38197. "Comment",
  38198. "C++ keyword",
  38199. "Identifier",
  38200. "Integer literal",
  38201. "Float literal",
  38202. "String literal",
  38203. "Operator",
  38204. "Bracket",
  38205. "Punctuation",
  38206. "Preprocessor line",
  38207. 0
  38208. };
  38209. return StringArray (types);
  38210. }
  38211. const Colour CPlusPlusCodeTokeniser::getDefaultColour (const int tokenType)
  38212. {
  38213. const uint32 colours[] =
  38214. {
  38215. 0xffcc0000, // error
  38216. 0xff00aa00, // comment
  38217. 0xff0000cc, // keyword
  38218. 0xff000000, // identifier
  38219. 0xff880000, // int literal
  38220. 0xff885500, // float literal
  38221. 0xff990099, // string literal
  38222. 0xff225500, // operator
  38223. 0xff000055, // bracket
  38224. 0xff004400, // punctuation
  38225. 0xff660000 // preprocessor
  38226. };
  38227. if (tokenType >= 0 && tokenType < numElementsInArray (colours))
  38228. return Colour (colours [tokenType]);
  38229. return Colours::black;
  38230. }
  38231. bool CPlusPlusCodeTokeniser::isReservedKeyword (const String& token) throw()
  38232. {
  38233. return CppTokeniser::isReservedKeyword (token, token.length());
  38234. }
  38235. END_JUCE_NAMESPACE
  38236. /*** End of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  38237. /*** Start of inlined file: juce_ComboBox.cpp ***/
  38238. BEGIN_JUCE_NAMESPACE
  38239. ComboBox::ComboBox (const String& name)
  38240. : Component (name),
  38241. lastCurrentId (0),
  38242. isButtonDown (false),
  38243. separatorPending (false),
  38244. menuActive (false),
  38245. label (0)
  38246. {
  38247. noChoicesMessage = TRANS("(no choices)");
  38248. setRepaintsOnMouseActivity (true);
  38249. lookAndFeelChanged();
  38250. currentId.addListener (this);
  38251. }
  38252. ComboBox::~ComboBox()
  38253. {
  38254. currentId.removeListener (this);
  38255. if (menuActive)
  38256. PopupMenu::dismissAllActiveMenus();
  38257. label = 0;
  38258. deleteAllChildren();
  38259. }
  38260. void ComboBox::setEditableText (const bool isEditable)
  38261. {
  38262. if (label->isEditableOnSingleClick() != isEditable || label->isEditableOnDoubleClick() != isEditable)
  38263. {
  38264. label->setEditable (isEditable, isEditable, false);
  38265. setWantsKeyboardFocus (! isEditable);
  38266. resized();
  38267. }
  38268. }
  38269. bool ComboBox::isTextEditable() const throw()
  38270. {
  38271. return label->isEditable();
  38272. }
  38273. void ComboBox::setJustificationType (const Justification& justification)
  38274. {
  38275. label->setJustificationType (justification);
  38276. }
  38277. const Justification ComboBox::getJustificationType() const throw()
  38278. {
  38279. return label->getJustificationType();
  38280. }
  38281. void ComboBox::setTooltip (const String& newTooltip)
  38282. {
  38283. SettableTooltipClient::setTooltip (newTooltip);
  38284. label->setTooltip (newTooltip);
  38285. }
  38286. void ComboBox::addItem (const String& newItemText, const int newItemId)
  38287. {
  38288. // you can't add empty strings to the list..
  38289. jassert (newItemText.isNotEmpty());
  38290. // IDs must be non-zero, as zero is used to indicate a lack of selecion.
  38291. jassert (newItemId != 0);
  38292. // you shouldn't use duplicate item IDs!
  38293. jassert (getItemForId (newItemId) == 0);
  38294. if (newItemText.isNotEmpty() && newItemId != 0)
  38295. {
  38296. if (separatorPending)
  38297. {
  38298. separatorPending = false;
  38299. ItemInfo* const item = new ItemInfo();
  38300. item->itemId = 0;
  38301. item->isEnabled = false;
  38302. item->isHeading = false;
  38303. items.add (item);
  38304. }
  38305. ItemInfo* const item = new ItemInfo();
  38306. item->name = newItemText;
  38307. item->itemId = newItemId;
  38308. item->isEnabled = true;
  38309. item->isHeading = false;
  38310. items.add (item);
  38311. }
  38312. }
  38313. void ComboBox::addSeparator()
  38314. {
  38315. separatorPending = (items.size() > 0);
  38316. }
  38317. void ComboBox::addSectionHeading (const String& headingName)
  38318. {
  38319. // you can't add empty strings to the list..
  38320. jassert (headingName.isNotEmpty());
  38321. if (headingName.isNotEmpty())
  38322. {
  38323. if (separatorPending)
  38324. {
  38325. separatorPending = false;
  38326. ItemInfo* const item = new ItemInfo();
  38327. item->itemId = 0;
  38328. item->isEnabled = false;
  38329. item->isHeading = false;
  38330. items.add (item);
  38331. }
  38332. ItemInfo* const item = new ItemInfo();
  38333. item->name = headingName;
  38334. item->itemId = 0;
  38335. item->isEnabled = true;
  38336. item->isHeading = true;
  38337. items.add (item);
  38338. }
  38339. }
  38340. void ComboBox::setItemEnabled (const int itemId, const bool shouldBeEnabled)
  38341. {
  38342. ItemInfo* const item = getItemForId (itemId);
  38343. if (item != 0)
  38344. item->isEnabled = shouldBeEnabled;
  38345. }
  38346. void ComboBox::changeItemText (const int itemId, const String& newText)
  38347. {
  38348. ItemInfo* const item = getItemForId (itemId);
  38349. jassert (item != 0);
  38350. if (item != 0)
  38351. item->name = newText;
  38352. }
  38353. void ComboBox::clear (const bool dontSendChangeMessage)
  38354. {
  38355. items.clear();
  38356. separatorPending = false;
  38357. if (! label->isEditable())
  38358. setSelectedItemIndex (-1, dontSendChangeMessage);
  38359. }
  38360. bool ComboBox::ItemInfo::isSeparator() const throw()
  38361. {
  38362. return name.isEmpty();
  38363. }
  38364. bool ComboBox::ItemInfo::isRealItem() const throw()
  38365. {
  38366. return ! (isHeading || name.isEmpty());
  38367. }
  38368. ComboBox::ItemInfo* ComboBox::getItemForId (const int itemId) const throw()
  38369. {
  38370. if (itemId != 0)
  38371. {
  38372. for (int i = items.size(); --i >= 0;)
  38373. if (items.getUnchecked(i)->itemId == itemId)
  38374. return items.getUnchecked(i);
  38375. }
  38376. return 0;
  38377. }
  38378. ComboBox::ItemInfo* ComboBox::getItemForIndex (const int index) const throw()
  38379. {
  38380. int n = 0;
  38381. for (int i = 0; i < items.size(); ++i)
  38382. {
  38383. ItemInfo* const item = items.getUnchecked(i);
  38384. if (item->isRealItem())
  38385. if (n++ == index)
  38386. return item;
  38387. }
  38388. return 0;
  38389. }
  38390. int ComboBox::getNumItems() const throw()
  38391. {
  38392. int n = 0;
  38393. for (int i = items.size(); --i >= 0;)
  38394. if (items.getUnchecked(i)->isRealItem())
  38395. ++n;
  38396. return n;
  38397. }
  38398. const String ComboBox::getItemText (const int index) const
  38399. {
  38400. const ItemInfo* const item = getItemForIndex (index);
  38401. if (item != 0)
  38402. return item->name;
  38403. return String::empty;
  38404. }
  38405. int ComboBox::getItemId (const int index) const throw()
  38406. {
  38407. const ItemInfo* const item = getItemForIndex (index);
  38408. return (item != 0) ? item->itemId : 0;
  38409. }
  38410. int ComboBox::indexOfItemId (const int itemId) const throw()
  38411. {
  38412. int n = 0;
  38413. for (int i = 0; i < items.size(); ++i)
  38414. {
  38415. const ItemInfo* const item = items.getUnchecked(i);
  38416. if (item->isRealItem())
  38417. {
  38418. if (item->itemId == itemId)
  38419. return n;
  38420. ++n;
  38421. }
  38422. }
  38423. return -1;
  38424. }
  38425. int ComboBox::getSelectedItemIndex() const
  38426. {
  38427. int index = indexOfItemId (currentId.getValue());
  38428. if (getText() != getItemText (index))
  38429. index = -1;
  38430. return index;
  38431. }
  38432. void ComboBox::setSelectedItemIndex (const int index, const bool dontSendChangeMessage)
  38433. {
  38434. setSelectedId (getItemId (index), dontSendChangeMessage);
  38435. }
  38436. int ComboBox::getSelectedId() const throw()
  38437. {
  38438. const ItemInfo* const item = getItemForId (currentId.getValue());
  38439. return (item != 0 && getText() == item->name) ? item->itemId : 0;
  38440. }
  38441. void ComboBox::setSelectedId (const int newItemId, const bool dontSendChangeMessage)
  38442. {
  38443. const ItemInfo* const item = getItemForId (newItemId);
  38444. const String newItemText (item != 0 ? item->name : String::empty);
  38445. if (lastCurrentId != newItemId || label->getText() != newItemText)
  38446. {
  38447. if (! dontSendChangeMessage)
  38448. triggerAsyncUpdate();
  38449. label->setText (newItemText, false);
  38450. lastCurrentId = newItemId;
  38451. currentId = newItemId;
  38452. repaint(); // for the benefit of the 'none selected' text
  38453. }
  38454. }
  38455. void ComboBox::valueChanged (Value&)
  38456. {
  38457. if (lastCurrentId != (int) currentId.getValue())
  38458. setSelectedId (currentId.getValue(), false);
  38459. }
  38460. const String ComboBox::getText() const
  38461. {
  38462. return label->getText();
  38463. }
  38464. void ComboBox::setText (const String& newText, const bool dontSendChangeMessage)
  38465. {
  38466. for (int i = items.size(); --i >= 0;)
  38467. {
  38468. const ItemInfo* const item = items.getUnchecked(i);
  38469. if (item->isRealItem()
  38470. && item->name == newText)
  38471. {
  38472. setSelectedId (item->itemId, dontSendChangeMessage);
  38473. return;
  38474. }
  38475. }
  38476. lastCurrentId = 0;
  38477. currentId = 0;
  38478. if (label->getText() != newText)
  38479. {
  38480. label->setText (newText, false);
  38481. if (! dontSendChangeMessage)
  38482. triggerAsyncUpdate();
  38483. }
  38484. repaint();
  38485. }
  38486. void ComboBox::showEditor()
  38487. {
  38488. jassert (isTextEditable()); // you probably shouldn't do this to a non-editable combo box?
  38489. label->showEditor();
  38490. }
  38491. void ComboBox::setTextWhenNothingSelected (const String& newMessage)
  38492. {
  38493. if (textWhenNothingSelected != newMessage)
  38494. {
  38495. textWhenNothingSelected = newMessage;
  38496. repaint();
  38497. }
  38498. }
  38499. const String ComboBox::getTextWhenNothingSelected() const
  38500. {
  38501. return textWhenNothingSelected;
  38502. }
  38503. void ComboBox::setTextWhenNoChoicesAvailable (const String& newMessage)
  38504. {
  38505. noChoicesMessage = newMessage;
  38506. }
  38507. const String ComboBox::getTextWhenNoChoicesAvailable() const
  38508. {
  38509. return noChoicesMessage;
  38510. }
  38511. void ComboBox::paint (Graphics& g)
  38512. {
  38513. getLookAndFeel().drawComboBox (g,
  38514. getWidth(),
  38515. getHeight(),
  38516. isButtonDown,
  38517. label->getRight(),
  38518. 0,
  38519. getWidth() - label->getRight(),
  38520. getHeight(),
  38521. *this);
  38522. if (textWhenNothingSelected.isNotEmpty()
  38523. && label->getText().isEmpty()
  38524. && ! label->isBeingEdited())
  38525. {
  38526. g.setColour (findColour (textColourId).withMultipliedAlpha (0.5f));
  38527. g.setFont (label->getFont());
  38528. g.drawFittedText (textWhenNothingSelected,
  38529. label->getX() + 2, label->getY() + 1,
  38530. label->getWidth() - 4, label->getHeight() - 2,
  38531. label->getJustificationType(),
  38532. jmax (1, (int) (label->getHeight() / label->getFont().getHeight())));
  38533. }
  38534. }
  38535. void ComboBox::resized()
  38536. {
  38537. if (getHeight() > 0 && getWidth() > 0)
  38538. getLookAndFeel().positionComboBoxText (*this, *label);
  38539. }
  38540. void ComboBox::enablementChanged()
  38541. {
  38542. repaint();
  38543. }
  38544. void ComboBox::lookAndFeelChanged()
  38545. {
  38546. repaint();
  38547. Label* const newLabel = getLookAndFeel().createComboBoxTextBox (*this);
  38548. if (label != 0)
  38549. {
  38550. newLabel->setEditable (label->isEditable());
  38551. newLabel->setJustificationType (label->getJustificationType());
  38552. newLabel->setTooltip (label->getTooltip());
  38553. newLabel->setText (label->getText(), false);
  38554. }
  38555. label = newLabel;
  38556. addAndMakeVisible (newLabel);
  38557. newLabel->addListener (this);
  38558. newLabel->addMouseListener (this, false);
  38559. newLabel->setColour (Label::backgroundColourId, Colours::transparentBlack);
  38560. newLabel->setColour (Label::textColourId, findColour (ComboBox::textColourId));
  38561. newLabel->setColour (TextEditor::textColourId, findColour (ComboBox::textColourId));
  38562. newLabel->setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  38563. newLabel->setColour (TextEditor::highlightColourId, findColour (TextEditor::highlightColourId));
  38564. newLabel->setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  38565. resized();
  38566. }
  38567. void ComboBox::colourChanged()
  38568. {
  38569. lookAndFeelChanged();
  38570. }
  38571. bool ComboBox::keyPressed (const KeyPress& key)
  38572. {
  38573. bool used = false;
  38574. if (key.isKeyCode (KeyPress::upKey)
  38575. || key.isKeyCode (KeyPress::leftKey))
  38576. {
  38577. setSelectedItemIndex (jmax (0, getSelectedItemIndex() - 1));
  38578. used = true;
  38579. }
  38580. else if (key.isKeyCode (KeyPress::downKey)
  38581. || key.isKeyCode (KeyPress::rightKey))
  38582. {
  38583. setSelectedItemIndex (jmin (getSelectedItemIndex() + 1, getNumItems() - 1));
  38584. used = true;
  38585. }
  38586. else if (key.isKeyCode (KeyPress::returnKey))
  38587. {
  38588. showPopup();
  38589. used = true;
  38590. }
  38591. return used;
  38592. }
  38593. bool ComboBox::keyStateChanged (const bool isKeyDown)
  38594. {
  38595. // only forward key events that aren't used by this component
  38596. return isKeyDown
  38597. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  38598. || KeyPress::isKeyCurrentlyDown (KeyPress::leftKey)
  38599. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  38600. || KeyPress::isKeyCurrentlyDown (KeyPress::rightKey));
  38601. }
  38602. void ComboBox::focusGained (FocusChangeType)
  38603. {
  38604. repaint();
  38605. }
  38606. void ComboBox::focusLost (FocusChangeType)
  38607. {
  38608. repaint();
  38609. }
  38610. void ComboBox::labelTextChanged (Label*)
  38611. {
  38612. triggerAsyncUpdate();
  38613. }
  38614. class ComboBox::Callback : public ModalComponentManager::Callback
  38615. {
  38616. public:
  38617. Callback (ComboBox* const box_)
  38618. : box (box_)
  38619. {
  38620. }
  38621. void modalStateFinished (int returnValue)
  38622. {
  38623. if (box != 0)
  38624. {
  38625. box->menuActive = false;
  38626. if (returnValue != 0)
  38627. box->setSelectedId (returnValue);
  38628. }
  38629. }
  38630. private:
  38631. Component::SafePointer<ComboBox> box;
  38632. Callback (const Callback&);
  38633. Callback& operator= (const Callback&);
  38634. };
  38635. void ComboBox::showPopup()
  38636. {
  38637. if (! menuActive)
  38638. {
  38639. const int selectedId = getSelectedId();
  38640. PopupMenu menu;
  38641. menu.setLookAndFeel (&getLookAndFeel());
  38642. for (int i = 0; i < items.size(); ++i)
  38643. {
  38644. const ItemInfo* const item = items.getUnchecked(i);
  38645. if (item->isSeparator())
  38646. menu.addSeparator();
  38647. else if (item->isHeading)
  38648. menu.addSectionHeader (item->name);
  38649. else
  38650. menu.addItem (item->itemId, item->name,
  38651. item->isEnabled, item->itemId == selectedId);
  38652. }
  38653. if (items.size() == 0)
  38654. menu.addItem (1, noChoicesMessage, false);
  38655. menuActive = true;
  38656. menu.showAt (this, selectedId, getWidth(), 1, jlimit (12, 24, getHeight()),
  38657. new Callback (this));
  38658. }
  38659. }
  38660. void ComboBox::mouseDown (const MouseEvent& e)
  38661. {
  38662. beginDragAutoRepeat (300);
  38663. isButtonDown = isEnabled();
  38664. if (isButtonDown
  38665. && (e.eventComponent == this || ! label->isEditable()))
  38666. {
  38667. showPopup();
  38668. }
  38669. }
  38670. void ComboBox::mouseDrag (const MouseEvent& e)
  38671. {
  38672. beginDragAutoRepeat (50);
  38673. if (isButtonDown && ! e.mouseWasClicked())
  38674. showPopup();
  38675. }
  38676. void ComboBox::mouseUp (const MouseEvent& e2)
  38677. {
  38678. if (isButtonDown)
  38679. {
  38680. isButtonDown = false;
  38681. repaint();
  38682. const MouseEvent e (e2.getEventRelativeTo (this));
  38683. if (reallyContains (e.x, e.y, true)
  38684. && (e2.eventComponent == this || ! label->isEditable()))
  38685. {
  38686. showPopup();
  38687. }
  38688. }
  38689. }
  38690. void ComboBox::addListener (Listener* const listener)
  38691. {
  38692. listeners.add (listener);
  38693. }
  38694. void ComboBox::removeListener (Listener* const listener)
  38695. {
  38696. listeners.remove (listener);
  38697. }
  38698. void ComboBox::handleAsyncUpdate()
  38699. {
  38700. Component::BailOutChecker checker (this);
  38701. listeners.callChecked (checker, &ComboBoxListener::comboBoxChanged, this); // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  38702. }
  38703. END_JUCE_NAMESPACE
  38704. /*** End of inlined file: juce_ComboBox.cpp ***/
  38705. /*** Start of inlined file: juce_Label.cpp ***/
  38706. BEGIN_JUCE_NAMESPACE
  38707. Label::Label (const String& componentName,
  38708. const String& labelText)
  38709. : Component (componentName),
  38710. textValue (labelText),
  38711. lastTextValue (labelText),
  38712. font (15.0f),
  38713. justification (Justification::centredLeft),
  38714. ownerComponent (0),
  38715. horizontalBorderSize (5),
  38716. verticalBorderSize (1),
  38717. minimumHorizontalScale (0.7f),
  38718. editSingleClick (false),
  38719. editDoubleClick (false),
  38720. lossOfFocusDiscardsChanges (false)
  38721. {
  38722. setColour (TextEditor::textColourId, Colours::black);
  38723. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  38724. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  38725. textValue.addListener (this);
  38726. }
  38727. Label::~Label()
  38728. {
  38729. textValue.removeListener (this);
  38730. if (ownerComponent != 0)
  38731. ownerComponent->removeComponentListener (this);
  38732. editor = 0;
  38733. }
  38734. void Label::setText (const String& newText,
  38735. const bool broadcastChangeMessage)
  38736. {
  38737. hideEditor (true);
  38738. if (lastTextValue != newText)
  38739. {
  38740. lastTextValue = newText;
  38741. textValue = newText;
  38742. repaint();
  38743. textWasChanged();
  38744. if (ownerComponent != 0)
  38745. componentMovedOrResized (*ownerComponent, true, true);
  38746. if (broadcastChangeMessage)
  38747. callChangeListeners();
  38748. }
  38749. }
  38750. const String Label::getText (const bool returnActiveEditorContents) const
  38751. {
  38752. return (returnActiveEditorContents && isBeingEdited())
  38753. ? editor->getText()
  38754. : textValue.toString();
  38755. }
  38756. void Label::valueChanged (Value&)
  38757. {
  38758. if (lastTextValue != textValue.toString())
  38759. setText (textValue.toString(), true);
  38760. }
  38761. void Label::setFont (const Font& newFont)
  38762. {
  38763. if (font != newFont)
  38764. {
  38765. font = newFont;
  38766. repaint();
  38767. }
  38768. }
  38769. const Font& Label::getFont() const throw()
  38770. {
  38771. return font;
  38772. }
  38773. void Label::setEditable (const bool editOnSingleClick,
  38774. const bool editOnDoubleClick,
  38775. const bool lossOfFocusDiscardsChanges_)
  38776. {
  38777. editSingleClick = editOnSingleClick;
  38778. editDoubleClick = editOnDoubleClick;
  38779. lossOfFocusDiscardsChanges = lossOfFocusDiscardsChanges_;
  38780. setWantsKeyboardFocus (editOnSingleClick || editOnDoubleClick);
  38781. setFocusContainer (editOnSingleClick || editOnDoubleClick);
  38782. }
  38783. void Label::setJustificationType (const Justification& newJustification)
  38784. {
  38785. if (justification != newJustification)
  38786. {
  38787. justification = newJustification;
  38788. repaint();
  38789. }
  38790. }
  38791. void Label::setBorderSize (int h, int v)
  38792. {
  38793. if (horizontalBorderSize != h || verticalBorderSize != v)
  38794. {
  38795. horizontalBorderSize = h;
  38796. verticalBorderSize = v;
  38797. repaint();
  38798. }
  38799. }
  38800. Component* Label::getAttachedComponent() const
  38801. {
  38802. return static_cast<Component*> (ownerComponent);
  38803. }
  38804. void Label::attachToComponent (Component* owner,
  38805. const bool onLeft)
  38806. {
  38807. if (ownerComponent != 0)
  38808. ownerComponent->removeComponentListener (this);
  38809. ownerComponent = owner;
  38810. leftOfOwnerComp = onLeft;
  38811. if (ownerComponent != 0)
  38812. {
  38813. setVisible (owner->isVisible());
  38814. ownerComponent->addComponentListener (this);
  38815. componentParentHierarchyChanged (*ownerComponent);
  38816. componentMovedOrResized (*ownerComponent, true, true);
  38817. }
  38818. }
  38819. void Label::componentMovedOrResized (Component& component, bool /*wasMoved*/, bool /*wasResized*/)
  38820. {
  38821. if (leftOfOwnerComp)
  38822. {
  38823. setSize (jmin (getFont().getStringWidth (textValue.toString()) + 8, component.getX()),
  38824. component.getHeight());
  38825. setTopRightPosition (component.getX(), component.getY());
  38826. }
  38827. else
  38828. {
  38829. setSize (component.getWidth(),
  38830. 8 + roundToInt (getFont().getHeight()));
  38831. setTopLeftPosition (component.getX(), component.getY() - getHeight());
  38832. }
  38833. }
  38834. void Label::componentParentHierarchyChanged (Component& component)
  38835. {
  38836. if (component.getParentComponent() != 0)
  38837. component.getParentComponent()->addChildComponent (this);
  38838. }
  38839. void Label::componentVisibilityChanged (Component& component)
  38840. {
  38841. setVisible (component.isVisible());
  38842. }
  38843. void Label::textWasEdited()
  38844. {
  38845. }
  38846. void Label::textWasChanged()
  38847. {
  38848. }
  38849. void Label::showEditor()
  38850. {
  38851. if (editor == 0)
  38852. {
  38853. addAndMakeVisible (editor = createEditorComponent());
  38854. editor->setText (getText(), false);
  38855. editor->addListener (this);
  38856. editor->grabKeyboardFocus();
  38857. editor->setHighlightedRegion (Range<int> (0, textValue.toString().length()));
  38858. editor->addListener (this);
  38859. resized();
  38860. repaint();
  38861. editorShown (editor);
  38862. enterModalState (false);
  38863. editor->grabKeyboardFocus();
  38864. }
  38865. }
  38866. void Label::editorShown (TextEditor* /*editorComponent*/)
  38867. {
  38868. }
  38869. void Label::editorAboutToBeHidden (TextEditor* /*editorComponent*/)
  38870. {
  38871. }
  38872. bool Label::updateFromTextEditorContents()
  38873. {
  38874. jassert (editor != 0);
  38875. const String newText (editor->getText());
  38876. if (textValue.toString() != newText)
  38877. {
  38878. lastTextValue = newText;
  38879. textValue = newText;
  38880. repaint();
  38881. textWasChanged();
  38882. if (ownerComponent != 0)
  38883. componentMovedOrResized (*ownerComponent, true, true);
  38884. return true;
  38885. }
  38886. return false;
  38887. }
  38888. void Label::hideEditor (const bool discardCurrentEditorContents)
  38889. {
  38890. if (editor != 0)
  38891. {
  38892. Component::SafePointer<Component> deletionChecker (this);
  38893. editorAboutToBeHidden (editor);
  38894. const bool changed = (! discardCurrentEditorContents)
  38895. && updateFromTextEditorContents();
  38896. editor = 0;
  38897. repaint();
  38898. if (changed)
  38899. textWasEdited();
  38900. if (deletionChecker != 0)
  38901. exitModalState (0);
  38902. if (changed && deletionChecker != 0)
  38903. callChangeListeners();
  38904. }
  38905. }
  38906. void Label::inputAttemptWhenModal()
  38907. {
  38908. if (editor != 0)
  38909. {
  38910. if (lossOfFocusDiscardsChanges)
  38911. textEditorEscapeKeyPressed (*editor);
  38912. else
  38913. textEditorReturnKeyPressed (*editor);
  38914. }
  38915. }
  38916. bool Label::isBeingEdited() const throw()
  38917. {
  38918. return editor != 0;
  38919. }
  38920. TextEditor* Label::createEditorComponent()
  38921. {
  38922. TextEditor* const ed = new TextEditor (getName());
  38923. ed->setFont (font);
  38924. // copy these colours from our own settings..
  38925. const int cols[] = { TextEditor::backgroundColourId,
  38926. TextEditor::textColourId,
  38927. TextEditor::highlightColourId,
  38928. TextEditor::highlightedTextColourId,
  38929. TextEditor::caretColourId,
  38930. TextEditor::outlineColourId,
  38931. TextEditor::focusedOutlineColourId,
  38932. TextEditor::shadowColourId };
  38933. for (int i = 0; i < numElementsInArray (cols); ++i)
  38934. ed->setColour (cols[i], findColour (cols[i]));
  38935. return ed;
  38936. }
  38937. void Label::paint (Graphics& g)
  38938. {
  38939. getLookAndFeel().drawLabel (g, *this);
  38940. }
  38941. void Label::mouseUp (const MouseEvent& e)
  38942. {
  38943. if (editSingleClick
  38944. && e.mouseWasClicked()
  38945. && contains (e.x, e.y)
  38946. && ! e.mods.isPopupMenu())
  38947. {
  38948. showEditor();
  38949. }
  38950. }
  38951. void Label::mouseDoubleClick (const MouseEvent& e)
  38952. {
  38953. if (editDoubleClick && ! e.mods.isPopupMenu())
  38954. showEditor();
  38955. }
  38956. void Label::resized()
  38957. {
  38958. if (editor != 0)
  38959. editor->setBoundsInset (BorderSize (0));
  38960. }
  38961. void Label::focusGained (FocusChangeType cause)
  38962. {
  38963. if (editSingleClick && cause == focusChangedByTabKey)
  38964. showEditor();
  38965. }
  38966. void Label::enablementChanged()
  38967. {
  38968. repaint();
  38969. }
  38970. void Label::colourChanged()
  38971. {
  38972. repaint();
  38973. }
  38974. void Label::setMinimumHorizontalScale (const float newScale)
  38975. {
  38976. if (minimumHorizontalScale != newScale)
  38977. {
  38978. minimumHorizontalScale = newScale;
  38979. repaint();
  38980. }
  38981. }
  38982. // We'll use a custom focus traverser here to make sure focus goes from the
  38983. // text editor to another component rather than back to the label itself.
  38984. class LabelKeyboardFocusTraverser : public KeyboardFocusTraverser
  38985. {
  38986. public:
  38987. LabelKeyboardFocusTraverser() {}
  38988. Component* getNextComponent (Component* current)
  38989. {
  38990. return KeyboardFocusTraverser::getNextComponent (dynamic_cast <TextEditor*> (current) != 0
  38991. ? current->getParentComponent() : current);
  38992. }
  38993. Component* getPreviousComponent (Component* current)
  38994. {
  38995. return KeyboardFocusTraverser::getPreviousComponent (dynamic_cast <TextEditor*> (current) != 0
  38996. ? current->getParentComponent() : current);
  38997. }
  38998. };
  38999. KeyboardFocusTraverser* Label::createFocusTraverser()
  39000. {
  39001. return new LabelKeyboardFocusTraverser();
  39002. }
  39003. void Label::addListener (Listener* const listener)
  39004. {
  39005. listeners.add (listener);
  39006. }
  39007. void Label::removeListener (Listener* const listener)
  39008. {
  39009. listeners.remove (listener);
  39010. }
  39011. void Label::callChangeListeners()
  39012. {
  39013. Component::BailOutChecker checker (this);
  39014. listeners.callChecked (checker, &LabelListener::labelTextChanged, this); // (can't use Label::Listener due to idiotic VC2005 bug)
  39015. }
  39016. void Label::textEditorTextChanged (TextEditor& ed)
  39017. {
  39018. if (editor != 0)
  39019. {
  39020. jassert (&ed == editor);
  39021. if (! (hasKeyboardFocus (true) || isCurrentlyBlockedByAnotherModalComponent()))
  39022. {
  39023. if (lossOfFocusDiscardsChanges)
  39024. textEditorEscapeKeyPressed (ed);
  39025. else
  39026. textEditorReturnKeyPressed (ed);
  39027. }
  39028. }
  39029. }
  39030. void Label::textEditorReturnKeyPressed (TextEditor& ed)
  39031. {
  39032. if (editor != 0)
  39033. {
  39034. jassert (&ed == editor);
  39035. (void) ed;
  39036. const bool changed = updateFromTextEditorContents();
  39037. hideEditor (true);
  39038. if (changed)
  39039. {
  39040. Component::SafePointer<Component> deletionChecker (this);
  39041. textWasEdited();
  39042. if (deletionChecker != 0)
  39043. callChangeListeners();
  39044. }
  39045. }
  39046. }
  39047. void Label::textEditorEscapeKeyPressed (TextEditor& ed)
  39048. {
  39049. if (editor != 0)
  39050. {
  39051. jassert (&ed == editor);
  39052. (void) ed;
  39053. editor->setText (textValue.toString(), false);
  39054. hideEditor (true);
  39055. }
  39056. }
  39057. void Label::textEditorFocusLost (TextEditor& ed)
  39058. {
  39059. textEditorTextChanged (ed);
  39060. }
  39061. END_JUCE_NAMESPACE
  39062. /*** End of inlined file: juce_Label.cpp ***/
  39063. /*** Start of inlined file: juce_ListBox.cpp ***/
  39064. BEGIN_JUCE_NAMESPACE
  39065. class ListBoxRowComponent : public Component,
  39066. public TooltipClient
  39067. {
  39068. public:
  39069. ListBoxRowComponent (ListBox& owner_)
  39070. : owner (owner_),
  39071. row (-1),
  39072. selected (false),
  39073. isDragging (false)
  39074. {
  39075. }
  39076. ~ListBoxRowComponent()
  39077. {
  39078. deleteAllChildren();
  39079. }
  39080. void paint (Graphics& g)
  39081. {
  39082. if (owner.getModel() != 0)
  39083. owner.getModel()->paintListBoxItem (row, g, getWidth(), getHeight(), selected);
  39084. }
  39085. void update (const int row_, const bool selected_)
  39086. {
  39087. if (row != row_ || selected != selected_)
  39088. {
  39089. repaint();
  39090. row = row_;
  39091. selected = selected_;
  39092. }
  39093. if (owner.getModel() != 0)
  39094. {
  39095. Component* const customComp = owner.getModel()->refreshComponentForRow (row_, selected_, getChildComponent (0));
  39096. if (customComp != 0)
  39097. {
  39098. addAndMakeVisible (customComp);
  39099. customComp->setBounds (getLocalBounds());
  39100. for (int i = getNumChildComponents(); --i >= 0;)
  39101. if (getChildComponent (i) != customComp)
  39102. delete getChildComponent (i);
  39103. }
  39104. else
  39105. {
  39106. deleteAllChildren();
  39107. }
  39108. }
  39109. }
  39110. void mouseDown (const MouseEvent& e)
  39111. {
  39112. isDragging = false;
  39113. selectRowOnMouseUp = false;
  39114. if (isEnabled())
  39115. {
  39116. if (! selected)
  39117. {
  39118. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  39119. if (owner.getModel() != 0)
  39120. owner.getModel()->listBoxItemClicked (row, e);
  39121. }
  39122. else
  39123. {
  39124. selectRowOnMouseUp = true;
  39125. }
  39126. }
  39127. }
  39128. void mouseUp (const MouseEvent& e)
  39129. {
  39130. if (isEnabled() && selectRowOnMouseUp && ! isDragging)
  39131. {
  39132. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  39133. if (owner.getModel() != 0)
  39134. owner.getModel()->listBoxItemClicked (row, e);
  39135. }
  39136. }
  39137. void mouseDoubleClick (const MouseEvent& e)
  39138. {
  39139. if (owner.getModel() != 0 && isEnabled())
  39140. owner.getModel()->listBoxItemDoubleClicked (row, e);
  39141. }
  39142. void mouseDrag (const MouseEvent& e)
  39143. {
  39144. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  39145. {
  39146. const SparseSet<int> selectedRows (owner.getSelectedRows());
  39147. if (selectedRows.size() > 0)
  39148. {
  39149. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  39150. if (dragDescription.isNotEmpty())
  39151. {
  39152. isDragging = true;
  39153. owner.startDragAndDrop (e, dragDescription);
  39154. }
  39155. }
  39156. }
  39157. }
  39158. void resized()
  39159. {
  39160. if (getNumChildComponents() > 0)
  39161. getChildComponent(0)->setBounds (getLocalBounds());
  39162. }
  39163. const String getTooltip()
  39164. {
  39165. if (owner.getModel() != 0)
  39166. return owner.getModel()->getTooltipForRow (row);
  39167. return String::empty;
  39168. }
  39169. juce_UseDebuggingNewOperator
  39170. bool neededFlag;
  39171. private:
  39172. ListBox& owner;
  39173. int row;
  39174. bool selected, isDragging, selectRowOnMouseUp;
  39175. ListBoxRowComponent (const ListBoxRowComponent&);
  39176. ListBoxRowComponent& operator= (const ListBoxRowComponent&);
  39177. };
  39178. class ListViewport : public Viewport
  39179. {
  39180. public:
  39181. int firstIndex, firstWholeIndex, lastWholeIndex;
  39182. bool hasUpdated;
  39183. ListViewport (ListBox& owner_)
  39184. : owner (owner_)
  39185. {
  39186. setWantsKeyboardFocus (false);
  39187. setViewedComponent (new Component());
  39188. getViewedComponent()->addMouseListener (this, false);
  39189. getViewedComponent()->setWantsKeyboardFocus (false);
  39190. }
  39191. ~ListViewport()
  39192. {
  39193. getViewedComponent()->removeMouseListener (this);
  39194. getViewedComponent()->deleteAllChildren();
  39195. }
  39196. ListBoxRowComponent* getComponentForRow (const int row) const throw()
  39197. {
  39198. return static_cast <ListBoxRowComponent*>
  39199. (getViewedComponent()->getChildComponent (row % jmax (1, getViewedComponent()->getNumChildComponents())));
  39200. }
  39201. int getRowNumberOfComponent (Component* const rowComponent) const throw()
  39202. {
  39203. const int index = getIndexOfChildComponent (rowComponent);
  39204. const int num = getViewedComponent()->getNumChildComponents();
  39205. for (int i = num; --i >= 0;)
  39206. if (((firstIndex + i) % jmax (1, num)) == index)
  39207. return firstIndex + i;
  39208. return -1;
  39209. }
  39210. Component* getComponentForRowIfOnscreen (const int row) const throw()
  39211. {
  39212. return (row >= firstIndex && row < firstIndex + getViewedComponent()->getNumChildComponents())
  39213. ? getComponentForRow (row) : 0;
  39214. }
  39215. void visibleAreaChanged (int, int, int, int)
  39216. {
  39217. updateVisibleArea (true);
  39218. if (owner.getModel() != 0)
  39219. owner.getModel()->listWasScrolled();
  39220. }
  39221. void updateVisibleArea (const bool makeSureItUpdatesContent)
  39222. {
  39223. hasUpdated = false;
  39224. const int newX = getViewedComponent()->getX();
  39225. int newY = getViewedComponent()->getY();
  39226. const int newW = jmax (owner.minimumRowWidth, getMaximumVisibleWidth());
  39227. const int newH = owner.totalItems * owner.getRowHeight();
  39228. if (newY + newH < getMaximumVisibleHeight() && newH > getMaximumVisibleHeight())
  39229. newY = getMaximumVisibleHeight() - newH;
  39230. getViewedComponent()->setBounds (newX, newY, newW, newH);
  39231. if (makeSureItUpdatesContent && ! hasUpdated)
  39232. updateContents();
  39233. }
  39234. void updateContents()
  39235. {
  39236. hasUpdated = true;
  39237. const int rowHeight = owner.getRowHeight();
  39238. if (rowHeight > 0)
  39239. {
  39240. const int y = getViewPositionY();
  39241. const int w = getViewedComponent()->getWidth();
  39242. const int numNeeded = 2 + getMaximumVisibleHeight() / rowHeight;
  39243. while (numNeeded > getViewedComponent()->getNumChildComponents())
  39244. getViewedComponent()->addAndMakeVisible (new ListBoxRowComponent (owner));
  39245. jassert (numNeeded >= 0);
  39246. while (numNeeded < getViewedComponent()->getNumChildComponents())
  39247. {
  39248. Component* const rowToRemove
  39249. = getViewedComponent()->getChildComponent (getViewedComponent()->getNumChildComponents() - 1);
  39250. delete rowToRemove;
  39251. }
  39252. firstIndex = y / rowHeight;
  39253. firstWholeIndex = (y + rowHeight - 1) / rowHeight;
  39254. lastWholeIndex = (y + getMaximumVisibleHeight() - 1) / rowHeight;
  39255. for (int i = 0; i < numNeeded; ++i)
  39256. {
  39257. const int row = i + firstIndex;
  39258. ListBoxRowComponent* const rowComp = getComponentForRow (row);
  39259. if (rowComp != 0)
  39260. {
  39261. rowComp->setBounds (0, row * rowHeight, w, rowHeight);
  39262. rowComp->update (row, owner.isRowSelected (row));
  39263. }
  39264. }
  39265. }
  39266. if (owner.headerComponent != 0)
  39267. owner.headerComponent->setBounds (owner.outlineThickness + getViewedComponent()->getX(),
  39268. owner.outlineThickness,
  39269. jmax (owner.getWidth() - owner.outlineThickness * 2,
  39270. getViewedComponent()->getWidth()),
  39271. owner.headerComponent->getHeight());
  39272. }
  39273. void paint (Graphics& g)
  39274. {
  39275. if (isOpaque())
  39276. g.fillAll (owner.findColour (ListBox::backgroundColourId));
  39277. }
  39278. bool keyPressed (const KeyPress& key)
  39279. {
  39280. if (key.isKeyCode (KeyPress::upKey)
  39281. || key.isKeyCode (KeyPress::downKey)
  39282. || key.isKeyCode (KeyPress::pageUpKey)
  39283. || key.isKeyCode (KeyPress::pageDownKey)
  39284. || key.isKeyCode (KeyPress::homeKey)
  39285. || key.isKeyCode (KeyPress::endKey))
  39286. {
  39287. // we want to avoid these keypresses going to the viewport, and instead allow
  39288. // them to pass up to our listbox..
  39289. return false;
  39290. }
  39291. return Viewport::keyPressed (key);
  39292. }
  39293. juce_UseDebuggingNewOperator
  39294. private:
  39295. ListBox& owner;
  39296. ListViewport (const ListViewport&);
  39297. ListViewport& operator= (const ListViewport&);
  39298. };
  39299. ListBox::ListBox (const String& name, ListBoxModel* const model_)
  39300. : Component (name),
  39301. model (model_),
  39302. totalItems (0),
  39303. rowHeight (22),
  39304. minimumRowWidth (0),
  39305. outlineThickness (0),
  39306. lastRowSelected (-1),
  39307. mouseMoveSelects (false),
  39308. multipleSelection (false),
  39309. hasDoneInitialUpdate (false)
  39310. {
  39311. addAndMakeVisible (viewport = new ListViewport (*this));
  39312. setWantsKeyboardFocus (true);
  39313. colourChanged();
  39314. }
  39315. ListBox::~ListBox()
  39316. {
  39317. headerComponent = 0;
  39318. viewport = 0;
  39319. }
  39320. void ListBox::setModel (ListBoxModel* const newModel)
  39321. {
  39322. if (model != newModel)
  39323. {
  39324. model = newModel;
  39325. updateContent();
  39326. }
  39327. }
  39328. void ListBox::setMultipleSelectionEnabled (bool b)
  39329. {
  39330. multipleSelection = b;
  39331. }
  39332. void ListBox::setMouseMoveSelectsRows (bool b)
  39333. {
  39334. mouseMoveSelects = b;
  39335. if (b)
  39336. addMouseListener (this, true);
  39337. }
  39338. void ListBox::paint (Graphics& g)
  39339. {
  39340. if (! hasDoneInitialUpdate)
  39341. updateContent();
  39342. g.fillAll (findColour (backgroundColourId));
  39343. }
  39344. void ListBox::paintOverChildren (Graphics& g)
  39345. {
  39346. if (outlineThickness > 0)
  39347. {
  39348. g.setColour (findColour (outlineColourId));
  39349. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  39350. }
  39351. }
  39352. void ListBox::resized()
  39353. {
  39354. viewport->setBoundsInset (BorderSize (outlineThickness + ((headerComponent != 0) ? headerComponent->getHeight() : 0),
  39355. outlineThickness,
  39356. outlineThickness,
  39357. outlineThickness));
  39358. viewport->setSingleStepSizes (20, getRowHeight());
  39359. viewport->updateVisibleArea (false);
  39360. }
  39361. void ListBox::visibilityChanged()
  39362. {
  39363. viewport->updateVisibleArea (true);
  39364. }
  39365. Viewport* ListBox::getViewport() const throw()
  39366. {
  39367. return viewport;
  39368. }
  39369. void ListBox::updateContent()
  39370. {
  39371. hasDoneInitialUpdate = true;
  39372. totalItems = (model != 0) ? model->getNumRows() : 0;
  39373. bool selectionChanged = false;
  39374. if (selected [selected.size() - 1] >= totalItems)
  39375. {
  39376. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  39377. lastRowSelected = getSelectedRow (0);
  39378. selectionChanged = true;
  39379. }
  39380. viewport->updateVisibleArea (isVisible());
  39381. viewport->resized();
  39382. if (selectionChanged && model != 0)
  39383. model->selectedRowsChanged (lastRowSelected);
  39384. }
  39385. void ListBox::selectRow (const int row,
  39386. bool dontScroll,
  39387. bool deselectOthersFirst)
  39388. {
  39389. selectRowInternal (row, dontScroll, deselectOthersFirst, false);
  39390. }
  39391. void ListBox::selectRowInternal (const int row,
  39392. bool dontScroll,
  39393. bool deselectOthersFirst,
  39394. bool isMouseClick)
  39395. {
  39396. if (! multipleSelection)
  39397. deselectOthersFirst = true;
  39398. if ((! isRowSelected (row))
  39399. || (deselectOthersFirst && getNumSelectedRows() > 1))
  39400. {
  39401. if (((unsigned int) row) < (unsigned int) totalItems)
  39402. {
  39403. if (deselectOthersFirst)
  39404. selected.clear();
  39405. selected.addRange (Range<int> (row, row + 1));
  39406. if (getHeight() == 0 || getWidth() == 0)
  39407. dontScroll = true;
  39408. viewport->hasUpdated = false;
  39409. if (row < viewport->firstWholeIndex && ! dontScroll)
  39410. {
  39411. viewport->setViewPosition (viewport->getViewPositionX(),
  39412. row * getRowHeight());
  39413. }
  39414. else if (row >= viewport->lastWholeIndex && ! dontScroll)
  39415. {
  39416. const int rowsOnScreen = viewport->lastWholeIndex - viewport->firstWholeIndex;
  39417. if (row >= lastRowSelected + rowsOnScreen
  39418. && rowsOnScreen < totalItems - 1
  39419. && ! isMouseClick)
  39420. {
  39421. viewport->setViewPosition (viewport->getViewPositionX(),
  39422. jlimit (0, jmax (0, totalItems - rowsOnScreen), row)
  39423. * getRowHeight());
  39424. }
  39425. else
  39426. {
  39427. viewport->setViewPosition (viewport->getViewPositionX(),
  39428. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  39429. }
  39430. }
  39431. if (! viewport->hasUpdated)
  39432. viewport->updateContents();
  39433. lastRowSelected = row;
  39434. model->selectedRowsChanged (row);
  39435. }
  39436. else
  39437. {
  39438. if (deselectOthersFirst)
  39439. deselectAllRows();
  39440. }
  39441. }
  39442. }
  39443. void ListBox::deselectRow (const int row)
  39444. {
  39445. if (selected.contains (row))
  39446. {
  39447. selected.removeRange (Range <int> (row, row + 1));
  39448. if (row == lastRowSelected)
  39449. lastRowSelected = getSelectedRow (0);
  39450. viewport->updateContents();
  39451. model->selectedRowsChanged (lastRowSelected);
  39452. }
  39453. }
  39454. void ListBox::setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  39455. const bool sendNotificationEventToModel)
  39456. {
  39457. selected = setOfRowsToBeSelected;
  39458. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  39459. if (! isRowSelected (lastRowSelected))
  39460. lastRowSelected = getSelectedRow (0);
  39461. viewport->updateContents();
  39462. if ((model != 0) && sendNotificationEventToModel)
  39463. model->selectedRowsChanged (lastRowSelected);
  39464. }
  39465. const SparseSet<int> ListBox::getSelectedRows() const
  39466. {
  39467. return selected;
  39468. }
  39469. void ListBox::selectRangeOfRows (int firstRow, int lastRow)
  39470. {
  39471. if (multipleSelection && (firstRow != lastRow))
  39472. {
  39473. const int numRows = totalItems - 1;
  39474. firstRow = jlimit (0, jmax (0, numRows), firstRow);
  39475. lastRow = jlimit (0, jmax (0, numRows), lastRow);
  39476. selected.addRange (Range <int> (jmin (firstRow, lastRow),
  39477. jmax (firstRow, lastRow) + 1));
  39478. selected.removeRange (Range <int> (lastRow, lastRow + 1));
  39479. }
  39480. selectRowInternal (lastRow, false, false, true);
  39481. }
  39482. void ListBox::flipRowSelection (const int row)
  39483. {
  39484. if (isRowSelected (row))
  39485. deselectRow (row);
  39486. else
  39487. selectRowInternal (row, false, false, true);
  39488. }
  39489. void ListBox::deselectAllRows()
  39490. {
  39491. if (! selected.isEmpty())
  39492. {
  39493. selected.clear();
  39494. lastRowSelected = -1;
  39495. viewport->updateContents();
  39496. if (model != 0)
  39497. model->selectedRowsChanged (lastRowSelected);
  39498. }
  39499. }
  39500. void ListBox::selectRowsBasedOnModifierKeys (const int row,
  39501. const ModifierKeys& mods)
  39502. {
  39503. if (multipleSelection && mods.isCommandDown())
  39504. {
  39505. flipRowSelection (row);
  39506. }
  39507. else if (multipleSelection && mods.isShiftDown() && lastRowSelected >= 0)
  39508. {
  39509. selectRangeOfRows (lastRowSelected, row);
  39510. }
  39511. else if ((! mods.isPopupMenu()) || ! isRowSelected (row))
  39512. {
  39513. selectRowInternal (row, false, true, true);
  39514. }
  39515. }
  39516. int ListBox::getNumSelectedRows() const
  39517. {
  39518. return selected.size();
  39519. }
  39520. int ListBox::getSelectedRow (const int index) const
  39521. {
  39522. return (((unsigned int) index) < (unsigned int) selected.size())
  39523. ? selected [index] : -1;
  39524. }
  39525. bool ListBox::isRowSelected (const int row) const
  39526. {
  39527. return selected.contains (row);
  39528. }
  39529. int ListBox::getLastRowSelected() const
  39530. {
  39531. return (isRowSelected (lastRowSelected)) ? lastRowSelected : -1;
  39532. }
  39533. int ListBox::getRowContainingPosition (const int x, const int y) const throw()
  39534. {
  39535. if (((unsigned int) x) < (unsigned int) getWidth())
  39536. {
  39537. const int row = (viewport->getViewPositionY() + y - viewport->getY()) / rowHeight;
  39538. if (((unsigned int) row) < (unsigned int) totalItems)
  39539. return row;
  39540. }
  39541. return -1;
  39542. }
  39543. int ListBox::getInsertionIndexForPosition (const int x, const int y) const throw()
  39544. {
  39545. if (((unsigned int) x) < (unsigned int) getWidth())
  39546. {
  39547. const int row = (viewport->getViewPositionY() + y + rowHeight / 2 - viewport->getY()) / rowHeight;
  39548. return jlimit (0, totalItems, row);
  39549. }
  39550. return -1;
  39551. }
  39552. Component* ListBox::getComponentForRowNumber (const int row) const throw()
  39553. {
  39554. Component* const listRowComp = viewport->getComponentForRowIfOnscreen (row);
  39555. return listRowComp != 0 ? listRowComp->getChildComponent (0) : 0;
  39556. }
  39557. int ListBox::getRowNumberOfComponent (Component* const rowComponent) const throw()
  39558. {
  39559. return viewport->getRowNumberOfComponent (rowComponent);
  39560. }
  39561. const Rectangle<int> ListBox::getRowPosition (const int rowNumber,
  39562. const bool relativeToComponentTopLeft) const throw()
  39563. {
  39564. int y = viewport->getY() + rowHeight * rowNumber;
  39565. if (relativeToComponentTopLeft)
  39566. y -= viewport->getViewPositionY();
  39567. return Rectangle<int> (viewport->getX(), y,
  39568. viewport->getViewedComponent()->getWidth(), rowHeight);
  39569. }
  39570. void ListBox::setVerticalPosition (const double proportion)
  39571. {
  39572. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  39573. viewport->setViewPosition (viewport->getViewPositionX(),
  39574. jmax (0, roundToInt (proportion * offscreen)));
  39575. }
  39576. double ListBox::getVerticalPosition() const
  39577. {
  39578. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  39579. return (offscreen > 0) ? viewport->getViewPositionY() / (double) offscreen
  39580. : 0;
  39581. }
  39582. int ListBox::getVisibleRowWidth() const throw()
  39583. {
  39584. return viewport->getViewWidth();
  39585. }
  39586. void ListBox::scrollToEnsureRowIsOnscreen (const int row)
  39587. {
  39588. if (row < viewport->firstWholeIndex)
  39589. {
  39590. viewport->setViewPosition (viewport->getViewPositionX(),
  39591. row * getRowHeight());
  39592. }
  39593. else if (row >= viewport->lastWholeIndex)
  39594. {
  39595. viewport->setViewPosition (viewport->getViewPositionX(),
  39596. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  39597. }
  39598. }
  39599. bool ListBox::keyPressed (const KeyPress& key)
  39600. {
  39601. const int numVisibleRows = viewport->getHeight() / getRowHeight();
  39602. const bool multiple = multipleSelection
  39603. && (lastRowSelected >= 0)
  39604. && (key.getModifiers().isShiftDown()
  39605. || key.getModifiers().isCtrlDown()
  39606. || key.getModifiers().isCommandDown());
  39607. if (key.isKeyCode (KeyPress::upKey))
  39608. {
  39609. if (multiple)
  39610. selectRangeOfRows (lastRowSelected, lastRowSelected - 1);
  39611. else
  39612. selectRow (jmax (0, lastRowSelected - 1));
  39613. }
  39614. else if (key.isKeyCode (KeyPress::returnKey)
  39615. && isRowSelected (lastRowSelected))
  39616. {
  39617. if (model != 0)
  39618. model->returnKeyPressed (lastRowSelected);
  39619. }
  39620. else if (key.isKeyCode (KeyPress::pageUpKey))
  39621. {
  39622. if (multiple)
  39623. selectRangeOfRows (lastRowSelected, lastRowSelected - numVisibleRows);
  39624. else
  39625. selectRow (jmax (0, jmax (0, lastRowSelected) - numVisibleRows));
  39626. }
  39627. else if (key.isKeyCode (KeyPress::pageDownKey))
  39628. {
  39629. if (multiple)
  39630. selectRangeOfRows (lastRowSelected, lastRowSelected + numVisibleRows);
  39631. else
  39632. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + numVisibleRows));
  39633. }
  39634. else if (key.isKeyCode (KeyPress::homeKey))
  39635. {
  39636. if (multiple && key.getModifiers().isShiftDown())
  39637. selectRangeOfRows (lastRowSelected, 0);
  39638. else
  39639. selectRow (0);
  39640. }
  39641. else if (key.isKeyCode (KeyPress::endKey))
  39642. {
  39643. if (multiple && key.getModifiers().isShiftDown())
  39644. selectRangeOfRows (lastRowSelected, totalItems - 1);
  39645. else
  39646. selectRow (totalItems - 1);
  39647. }
  39648. else if (key.isKeyCode (KeyPress::downKey))
  39649. {
  39650. if (multiple)
  39651. selectRangeOfRows (lastRowSelected, lastRowSelected + 1);
  39652. else
  39653. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + 1));
  39654. }
  39655. else if ((key.isKeyCode (KeyPress::deleteKey) || key.isKeyCode (KeyPress::backspaceKey))
  39656. && isRowSelected (lastRowSelected))
  39657. {
  39658. if (model != 0)
  39659. model->deleteKeyPressed (lastRowSelected);
  39660. }
  39661. else if (multiple && key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  39662. {
  39663. selectRangeOfRows (0, std::numeric_limits<int>::max());
  39664. }
  39665. else
  39666. {
  39667. return false;
  39668. }
  39669. return true;
  39670. }
  39671. bool ListBox::keyStateChanged (const bool isKeyDown)
  39672. {
  39673. return isKeyDown
  39674. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  39675. || KeyPress::isKeyCurrentlyDown (KeyPress::pageUpKey)
  39676. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  39677. || KeyPress::isKeyCurrentlyDown (KeyPress::pageDownKey)
  39678. || KeyPress::isKeyCurrentlyDown (KeyPress::homeKey)
  39679. || KeyPress::isKeyCurrentlyDown (KeyPress::endKey)
  39680. || KeyPress::isKeyCurrentlyDown (KeyPress::returnKey));
  39681. }
  39682. void ListBox::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  39683. {
  39684. getHorizontalScrollBar()->mouseWheelMove (e, wheelIncrementX, 0);
  39685. getVerticalScrollBar()->mouseWheelMove (e, 0, wheelIncrementY);
  39686. }
  39687. void ListBox::mouseMove (const MouseEvent& e)
  39688. {
  39689. if (mouseMoveSelects)
  39690. {
  39691. const MouseEvent e2 (e.getEventRelativeTo (this));
  39692. selectRow (getRowContainingPosition (e2.x, e2.y), true);
  39693. }
  39694. }
  39695. void ListBox::mouseExit (const MouseEvent& e)
  39696. {
  39697. mouseMove (e);
  39698. }
  39699. void ListBox::mouseUp (const MouseEvent& e)
  39700. {
  39701. if (e.mouseWasClicked() && model != 0)
  39702. model->backgroundClicked();
  39703. }
  39704. void ListBox::setRowHeight (const int newHeight)
  39705. {
  39706. rowHeight = jmax (1, newHeight);
  39707. viewport->setSingleStepSizes (20, rowHeight);
  39708. updateContent();
  39709. }
  39710. int ListBox::getNumRowsOnScreen() const throw()
  39711. {
  39712. return viewport->getMaximumVisibleHeight() / rowHeight;
  39713. }
  39714. void ListBox::setMinimumContentWidth (const int newMinimumWidth)
  39715. {
  39716. minimumRowWidth = newMinimumWidth;
  39717. updateContent();
  39718. }
  39719. int ListBox::getVisibleContentWidth() const throw()
  39720. {
  39721. return viewport->getMaximumVisibleWidth();
  39722. }
  39723. ScrollBar* ListBox::getVerticalScrollBar() const throw()
  39724. {
  39725. return viewport->getVerticalScrollBar();
  39726. }
  39727. ScrollBar* ListBox::getHorizontalScrollBar() const throw()
  39728. {
  39729. return viewport->getHorizontalScrollBar();
  39730. }
  39731. void ListBox::colourChanged()
  39732. {
  39733. setOpaque (findColour (backgroundColourId).isOpaque());
  39734. viewport->setOpaque (isOpaque());
  39735. repaint();
  39736. }
  39737. void ListBox::setOutlineThickness (const int outlineThickness_)
  39738. {
  39739. outlineThickness = outlineThickness_;
  39740. resized();
  39741. }
  39742. void ListBox::setHeaderComponent (Component* const newHeaderComponent)
  39743. {
  39744. if (newHeaderComponent != headerComponent)
  39745. {
  39746. headerComponent = newHeaderComponent;
  39747. addAndMakeVisible (newHeaderComponent);
  39748. ListBox::resized();
  39749. }
  39750. }
  39751. void ListBox::repaintRow (const int rowNumber) throw()
  39752. {
  39753. repaint (getRowPosition (rowNumber, true));
  39754. }
  39755. const Image ListBox::createSnapshotOfSelectedRows (int& imageX, int& imageY)
  39756. {
  39757. Rectangle<int> imageArea;
  39758. const int firstRow = getRowContainingPosition (0, 0);
  39759. int i;
  39760. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  39761. {
  39762. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  39763. if (rowComp != 0 && isRowSelected (firstRow + i))
  39764. {
  39765. const Point<int> pos (rowComp->relativePositionToOtherComponent (this, Point<int>()));
  39766. const Rectangle<int> rowRect (pos.getX(), pos.getY(), rowComp->getWidth(), rowComp->getHeight());
  39767. imageArea = imageArea.getUnion (rowRect);
  39768. }
  39769. }
  39770. imageArea = imageArea.getIntersection (getLocalBounds());
  39771. imageX = imageArea.getX();
  39772. imageY = imageArea.getY();
  39773. Image snapshot (Image::ARGB, imageArea.getWidth(), imageArea.getHeight(), true, Image::NativeImage);
  39774. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  39775. {
  39776. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  39777. if (rowComp != 0 && isRowSelected (firstRow + i))
  39778. {
  39779. const Point<int> pos (rowComp->relativePositionToOtherComponent (this, Point<int>()));
  39780. Graphics g (snapshot);
  39781. g.setOrigin (pos.getX() - imageX, pos.getY() - imageY);
  39782. if (g.reduceClipRegion (0, 0, rowComp->getWidth(), rowComp->getHeight()))
  39783. rowComp->paintEntireComponent (g);
  39784. }
  39785. }
  39786. return snapshot;
  39787. }
  39788. void ListBox::startDragAndDrop (const MouseEvent& e, const String& dragDescription)
  39789. {
  39790. DragAndDropContainer* const dragContainer
  39791. = DragAndDropContainer::findParentDragContainerFor (this);
  39792. if (dragContainer != 0)
  39793. {
  39794. int x, y;
  39795. Image dragImage (createSnapshotOfSelectedRows (x, y));
  39796. dragImage.multiplyAllAlphas (0.6f);
  39797. MouseEvent e2 (e.getEventRelativeTo (this));
  39798. const Point<int> p (x - e2.x, y - e2.y);
  39799. dragContainer->startDragging (dragDescription, this, dragImage, true, &p);
  39800. }
  39801. else
  39802. {
  39803. // to be able to do a drag-and-drop operation, the listbox needs to
  39804. // be inside a component which is also a DragAndDropContainer.
  39805. jassertfalse;
  39806. }
  39807. }
  39808. Component* ListBoxModel::refreshComponentForRow (int, bool, Component* existingComponentToUpdate)
  39809. {
  39810. (void) existingComponentToUpdate;
  39811. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  39812. return 0;
  39813. }
  39814. void ListBoxModel::listBoxItemClicked (int, const MouseEvent&)
  39815. {
  39816. }
  39817. void ListBoxModel::listBoxItemDoubleClicked (int, const MouseEvent&)
  39818. {
  39819. }
  39820. void ListBoxModel::backgroundClicked()
  39821. {
  39822. }
  39823. void ListBoxModel::selectedRowsChanged (int)
  39824. {
  39825. }
  39826. void ListBoxModel::deleteKeyPressed (int)
  39827. {
  39828. }
  39829. void ListBoxModel::returnKeyPressed (int)
  39830. {
  39831. }
  39832. void ListBoxModel::listWasScrolled()
  39833. {
  39834. }
  39835. const String ListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  39836. {
  39837. return String::empty;
  39838. }
  39839. const String ListBoxModel::getTooltipForRow (int)
  39840. {
  39841. return String::empty;
  39842. }
  39843. END_JUCE_NAMESPACE
  39844. /*** End of inlined file: juce_ListBox.cpp ***/
  39845. /*** Start of inlined file: juce_ProgressBar.cpp ***/
  39846. BEGIN_JUCE_NAMESPACE
  39847. ProgressBar::ProgressBar (double& progress_)
  39848. : progress (progress_),
  39849. displayPercentage (true),
  39850. lastCallbackTime (0)
  39851. {
  39852. currentValue = jlimit (0.0, 1.0, progress);
  39853. }
  39854. ProgressBar::~ProgressBar()
  39855. {
  39856. }
  39857. void ProgressBar::setPercentageDisplay (const bool shouldDisplayPercentage)
  39858. {
  39859. displayPercentage = shouldDisplayPercentage;
  39860. repaint();
  39861. }
  39862. void ProgressBar::setTextToDisplay (const String& text)
  39863. {
  39864. displayPercentage = false;
  39865. displayedMessage = text;
  39866. }
  39867. void ProgressBar::lookAndFeelChanged()
  39868. {
  39869. setOpaque (findColour (backgroundColourId).isOpaque());
  39870. }
  39871. void ProgressBar::colourChanged()
  39872. {
  39873. lookAndFeelChanged();
  39874. }
  39875. void ProgressBar::paint (Graphics& g)
  39876. {
  39877. String text;
  39878. if (displayPercentage)
  39879. {
  39880. if (currentValue >= 0 && currentValue <= 1.0)
  39881. text << roundToInt (currentValue * 100.0) << '%';
  39882. }
  39883. else
  39884. {
  39885. text = displayedMessage;
  39886. }
  39887. getLookAndFeel().drawProgressBar (g, *this,
  39888. getWidth(), getHeight(),
  39889. currentValue, text);
  39890. }
  39891. void ProgressBar::visibilityChanged()
  39892. {
  39893. if (isVisible())
  39894. startTimer (30);
  39895. else
  39896. stopTimer();
  39897. }
  39898. void ProgressBar::timerCallback()
  39899. {
  39900. double newProgress = progress;
  39901. const uint32 now = Time::getMillisecondCounter();
  39902. const int timeSinceLastCallback = (int) (now - lastCallbackTime);
  39903. lastCallbackTime = now;
  39904. if (currentValue != newProgress
  39905. || newProgress < 0 || newProgress >= 1.0
  39906. || currentMessage != displayedMessage)
  39907. {
  39908. if (currentValue < newProgress
  39909. && newProgress >= 0 && newProgress < 1.0
  39910. && currentValue >= 0 && currentValue < 1.0)
  39911. {
  39912. newProgress = jmin (currentValue + 0.0008 * timeSinceLastCallback,
  39913. newProgress);
  39914. }
  39915. currentValue = newProgress;
  39916. currentMessage = displayedMessage;
  39917. repaint();
  39918. }
  39919. }
  39920. END_JUCE_NAMESPACE
  39921. /*** End of inlined file: juce_ProgressBar.cpp ***/
  39922. /*** Start of inlined file: juce_Slider.cpp ***/
  39923. BEGIN_JUCE_NAMESPACE
  39924. class SliderPopupDisplayComponent : public BubbleComponent
  39925. {
  39926. public:
  39927. SliderPopupDisplayComponent (Slider* const owner_)
  39928. : owner (owner_),
  39929. font (15.0f, Font::bold)
  39930. {
  39931. setAlwaysOnTop (true);
  39932. }
  39933. ~SliderPopupDisplayComponent()
  39934. {
  39935. }
  39936. void paintContent (Graphics& g, int w, int h)
  39937. {
  39938. g.setFont (font);
  39939. g.setColour (Colours::black);
  39940. g.drawFittedText (text, 0, 0, w, h, Justification::centred, 1);
  39941. }
  39942. void getContentSize (int& w, int& h)
  39943. {
  39944. w = font.getStringWidth (text) + 18;
  39945. h = (int) (font.getHeight() * 1.6f);
  39946. }
  39947. void updatePosition (const String& newText)
  39948. {
  39949. if (text != newText)
  39950. {
  39951. text = newText;
  39952. repaint();
  39953. }
  39954. BubbleComponent::setPosition (owner);
  39955. }
  39956. juce_UseDebuggingNewOperator
  39957. private:
  39958. Slider* owner;
  39959. Font font;
  39960. String text;
  39961. SliderPopupDisplayComponent (const SliderPopupDisplayComponent&);
  39962. SliderPopupDisplayComponent& operator= (const SliderPopupDisplayComponent&);
  39963. };
  39964. Slider::Slider (const String& name)
  39965. : Component (name),
  39966. lastCurrentValue (0),
  39967. lastValueMin (0),
  39968. lastValueMax (0),
  39969. minimum (0),
  39970. maximum (10),
  39971. interval (0),
  39972. skewFactor (1.0),
  39973. velocityModeSensitivity (1.0),
  39974. velocityModeOffset (0.0),
  39975. velocityModeThreshold (1),
  39976. rotaryStart (float_Pi * 1.2f),
  39977. rotaryEnd (float_Pi * 2.8f),
  39978. numDecimalPlaces (7),
  39979. sliderRegionStart (0),
  39980. sliderRegionSize (1),
  39981. sliderBeingDragged (-1),
  39982. pixelsForFullDragExtent (250),
  39983. style (LinearHorizontal),
  39984. textBoxPos (TextBoxLeft),
  39985. textBoxWidth (80),
  39986. textBoxHeight (20),
  39987. incDecButtonMode (incDecButtonsNotDraggable),
  39988. editableText (true),
  39989. doubleClickToValue (false),
  39990. isVelocityBased (false),
  39991. userKeyOverridesVelocity (true),
  39992. rotaryStop (true),
  39993. incDecButtonsSideBySide (false),
  39994. sendChangeOnlyOnRelease (false),
  39995. popupDisplayEnabled (false),
  39996. menuEnabled (false),
  39997. menuShown (false),
  39998. scrollWheelEnabled (true),
  39999. snapsToMousePos (true),
  40000. valueBox (0),
  40001. incButton (0),
  40002. decButton (0),
  40003. popupDisplay (0),
  40004. parentForPopupDisplay (0)
  40005. {
  40006. setWantsKeyboardFocus (false);
  40007. setRepaintsOnMouseActivity (true);
  40008. lookAndFeelChanged();
  40009. updateText();
  40010. currentValue.addListener (this);
  40011. valueMin.addListener (this);
  40012. valueMax.addListener (this);
  40013. }
  40014. Slider::~Slider()
  40015. {
  40016. currentValue.removeListener (this);
  40017. valueMin.removeListener (this);
  40018. valueMax.removeListener (this);
  40019. popupDisplay = 0;
  40020. deleteAllChildren();
  40021. }
  40022. void Slider::handleAsyncUpdate()
  40023. {
  40024. cancelPendingUpdate();
  40025. Component::BailOutChecker checker (this);
  40026. listeners.callChecked (checker, &SliderListener::sliderValueChanged, this); // (can't use Slider::Listener due to idiotic VC2005 bug)
  40027. }
  40028. void Slider::sendDragStart()
  40029. {
  40030. startedDragging();
  40031. Component::BailOutChecker checker (this);
  40032. listeners.callChecked (checker, &SliderListener::sliderDragStarted, this);
  40033. }
  40034. void Slider::sendDragEnd()
  40035. {
  40036. stoppedDragging();
  40037. sliderBeingDragged = -1;
  40038. Component::BailOutChecker checker (this);
  40039. listeners.callChecked (checker, &SliderListener::sliderDragEnded, this);
  40040. }
  40041. void Slider::addListener (Listener* const listener)
  40042. {
  40043. listeners.add (listener);
  40044. }
  40045. void Slider::removeListener (Listener* const listener)
  40046. {
  40047. listeners.remove (listener);
  40048. }
  40049. void Slider::setSliderStyle (const SliderStyle newStyle)
  40050. {
  40051. if (style != newStyle)
  40052. {
  40053. style = newStyle;
  40054. repaint();
  40055. lookAndFeelChanged();
  40056. }
  40057. }
  40058. void Slider::setRotaryParameters (const float startAngleRadians,
  40059. const float endAngleRadians,
  40060. const bool stopAtEnd)
  40061. {
  40062. // make sure the values are sensible..
  40063. jassert (rotaryStart >= 0 && rotaryEnd >= 0);
  40064. jassert (rotaryStart < float_Pi * 4.0f && rotaryEnd < float_Pi * 4.0f);
  40065. jassert (rotaryStart < rotaryEnd);
  40066. rotaryStart = startAngleRadians;
  40067. rotaryEnd = endAngleRadians;
  40068. rotaryStop = stopAtEnd;
  40069. }
  40070. void Slider::setVelocityBasedMode (const bool velBased)
  40071. {
  40072. isVelocityBased = velBased;
  40073. }
  40074. void Slider::setVelocityModeParameters (const double sensitivity,
  40075. const int threshold,
  40076. const double offset,
  40077. const bool userCanPressKeyToSwapMode)
  40078. {
  40079. jassert (threshold >= 0);
  40080. jassert (sensitivity > 0);
  40081. jassert (offset >= 0);
  40082. velocityModeSensitivity = sensitivity;
  40083. velocityModeOffset = offset;
  40084. velocityModeThreshold = threshold;
  40085. userKeyOverridesVelocity = userCanPressKeyToSwapMode;
  40086. }
  40087. void Slider::setSkewFactor (const double factor)
  40088. {
  40089. skewFactor = factor;
  40090. }
  40091. void Slider::setSkewFactorFromMidPoint (const double sliderValueToShowAtMidPoint)
  40092. {
  40093. if (maximum > minimum)
  40094. skewFactor = log (0.5) / log ((sliderValueToShowAtMidPoint - minimum)
  40095. / (maximum - minimum));
  40096. }
  40097. void Slider::setMouseDragSensitivity (const int distanceForFullScaleDrag)
  40098. {
  40099. jassert (distanceForFullScaleDrag > 0);
  40100. pixelsForFullDragExtent = distanceForFullScaleDrag;
  40101. }
  40102. void Slider::setIncDecButtonsMode (const IncDecButtonMode mode)
  40103. {
  40104. if (incDecButtonMode != mode)
  40105. {
  40106. incDecButtonMode = mode;
  40107. lookAndFeelChanged();
  40108. }
  40109. }
  40110. void Slider::setTextBoxStyle (const TextEntryBoxPosition newPosition,
  40111. const bool isReadOnly,
  40112. const int textEntryBoxWidth,
  40113. const int textEntryBoxHeight)
  40114. {
  40115. if (textBoxPos != newPosition
  40116. || editableText != (! isReadOnly)
  40117. || textBoxWidth != textEntryBoxWidth
  40118. || textBoxHeight != textEntryBoxHeight)
  40119. {
  40120. textBoxPos = newPosition;
  40121. editableText = ! isReadOnly;
  40122. textBoxWidth = textEntryBoxWidth;
  40123. textBoxHeight = textEntryBoxHeight;
  40124. repaint();
  40125. lookAndFeelChanged();
  40126. }
  40127. }
  40128. void Slider::setTextBoxIsEditable (const bool shouldBeEditable)
  40129. {
  40130. editableText = shouldBeEditable;
  40131. if (valueBox != 0)
  40132. valueBox->setEditable (shouldBeEditable && isEnabled());
  40133. }
  40134. void Slider::showTextBox()
  40135. {
  40136. jassert (editableText); // this should probably be avoided in read-only sliders.
  40137. if (valueBox != 0)
  40138. valueBox->showEditor();
  40139. }
  40140. void Slider::hideTextBox (const bool discardCurrentEditorContents)
  40141. {
  40142. if (valueBox != 0)
  40143. {
  40144. valueBox->hideEditor (discardCurrentEditorContents);
  40145. if (discardCurrentEditorContents)
  40146. updateText();
  40147. }
  40148. }
  40149. void Slider::setChangeNotificationOnlyOnRelease (const bool onlyNotifyOnRelease)
  40150. {
  40151. sendChangeOnlyOnRelease = onlyNotifyOnRelease;
  40152. }
  40153. void Slider::setSliderSnapsToMousePosition (const bool shouldSnapToMouse)
  40154. {
  40155. snapsToMousePos = shouldSnapToMouse;
  40156. }
  40157. void Slider::setPopupDisplayEnabled (const bool enabled,
  40158. Component* const parentComponentToUse)
  40159. {
  40160. popupDisplayEnabled = enabled;
  40161. parentForPopupDisplay = parentComponentToUse;
  40162. }
  40163. void Slider::colourChanged()
  40164. {
  40165. lookAndFeelChanged();
  40166. }
  40167. void Slider::lookAndFeelChanged()
  40168. {
  40169. const String previousTextBoxContent (valueBox != 0 ? valueBox->getText()
  40170. : getTextFromValue (currentValue.getValue()));
  40171. deleteAllChildren();
  40172. valueBox = 0;
  40173. LookAndFeel& lf = getLookAndFeel();
  40174. if (textBoxPos != NoTextBox)
  40175. {
  40176. addAndMakeVisible (valueBox = getLookAndFeel().createSliderTextBox (*this));
  40177. valueBox->setWantsKeyboardFocus (false);
  40178. valueBox->setText (previousTextBoxContent, false);
  40179. valueBox->setEditable (editableText && isEnabled());
  40180. valueBox->addListener (this);
  40181. if (style == LinearBar)
  40182. valueBox->addMouseListener (this, false);
  40183. valueBox->setTooltip (getTooltip());
  40184. }
  40185. if (style == IncDecButtons)
  40186. {
  40187. addAndMakeVisible (incButton = lf.createSliderButton (true));
  40188. incButton->addButtonListener (this);
  40189. addAndMakeVisible (decButton = lf.createSliderButton (false));
  40190. decButton->addButtonListener (this);
  40191. if (incDecButtonMode != incDecButtonsNotDraggable)
  40192. {
  40193. incButton->addMouseListener (this, false);
  40194. decButton->addMouseListener (this, false);
  40195. }
  40196. else
  40197. {
  40198. incButton->setRepeatSpeed (300, 100, 20);
  40199. incButton->addMouseListener (decButton, false);
  40200. decButton->setRepeatSpeed (300, 100, 20);
  40201. decButton->addMouseListener (incButton, false);
  40202. }
  40203. incButton->setTooltip (getTooltip());
  40204. decButton->setTooltip (getTooltip());
  40205. }
  40206. setComponentEffect (lf.getSliderEffect());
  40207. resized();
  40208. repaint();
  40209. }
  40210. void Slider::setRange (const double newMin,
  40211. const double newMax,
  40212. const double newInt)
  40213. {
  40214. if (minimum != newMin
  40215. || maximum != newMax
  40216. || interval != newInt)
  40217. {
  40218. minimum = newMin;
  40219. maximum = newMax;
  40220. interval = newInt;
  40221. // figure out the number of DPs needed to display all values at this
  40222. // interval setting.
  40223. numDecimalPlaces = 7;
  40224. if (newInt != 0)
  40225. {
  40226. int v = abs ((int) (newInt * 10000000));
  40227. while ((v % 10) == 0)
  40228. {
  40229. --numDecimalPlaces;
  40230. v /= 10;
  40231. }
  40232. }
  40233. // keep the current values inside the new range..
  40234. if (style != TwoValueHorizontal && style != TwoValueVertical)
  40235. {
  40236. setValue (getValue(), false, false);
  40237. }
  40238. else
  40239. {
  40240. setMinValue (getMinValue(), false, false);
  40241. setMaxValue (getMaxValue(), false, false);
  40242. }
  40243. updateText();
  40244. }
  40245. }
  40246. void Slider::triggerChangeMessage (const bool synchronous)
  40247. {
  40248. if (synchronous)
  40249. handleAsyncUpdate();
  40250. else
  40251. triggerAsyncUpdate();
  40252. valueChanged();
  40253. }
  40254. void Slider::valueChanged (Value& value)
  40255. {
  40256. if (value.refersToSameSourceAs (currentValue))
  40257. {
  40258. if (style != TwoValueHorizontal && style != TwoValueVertical)
  40259. setValue (currentValue.getValue(), false, false);
  40260. }
  40261. else if (value.refersToSameSourceAs (valueMin))
  40262. setMinValue (valueMin.getValue(), false, false, true);
  40263. else if (value.refersToSameSourceAs (valueMax))
  40264. setMaxValue (valueMax.getValue(), false, false, true);
  40265. }
  40266. double Slider::getValue() const
  40267. {
  40268. // for a two-value style slider, you should use the getMinValue() and getMaxValue()
  40269. // methods to get the two values.
  40270. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  40271. return currentValue.getValue();
  40272. }
  40273. void Slider::setValue (double newValue,
  40274. const bool sendUpdateMessage,
  40275. const bool sendMessageSynchronously)
  40276. {
  40277. // for a two-value style slider, you should use the setMinValue() and setMaxValue()
  40278. // methods to set the two values.
  40279. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  40280. newValue = constrainedValue (newValue);
  40281. if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  40282. {
  40283. jassert ((double) valueMin.getValue() <= (double) valueMax.getValue());
  40284. newValue = jlimit ((double) valueMin.getValue(),
  40285. (double) valueMax.getValue(),
  40286. newValue);
  40287. }
  40288. if (newValue != lastCurrentValue)
  40289. {
  40290. if (valueBox != 0)
  40291. valueBox->hideEditor (true);
  40292. lastCurrentValue = newValue;
  40293. currentValue = newValue;
  40294. updateText();
  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. double Slider::getMinValue() const
  40307. {
  40308. // The minimum value only applies to sliders that are in two- or three-value mode.
  40309. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40310. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40311. return valueMin.getValue();
  40312. }
  40313. double Slider::getMaxValue() const
  40314. {
  40315. // The maximum value only applies to sliders that are in two- or three-value mode.
  40316. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40317. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40318. return valueMax.getValue();
  40319. }
  40320. void Slider::setMinValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  40321. {
  40322. // The minimum value only applies to sliders that are in two- or three-value mode.
  40323. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40324. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40325. newValue = constrainedValue (newValue);
  40326. if (style == TwoValueHorizontal || style == TwoValueVertical)
  40327. {
  40328. if (allowNudgingOfOtherValues && newValue > (double) valueMax.getValue())
  40329. setMaxValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40330. newValue = jmin ((double) valueMax.getValue(), newValue);
  40331. }
  40332. else
  40333. {
  40334. if (allowNudgingOfOtherValues && newValue > lastCurrentValue)
  40335. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40336. newValue = jmin (lastCurrentValue, newValue);
  40337. }
  40338. if (lastValueMin != newValue)
  40339. {
  40340. lastValueMin = newValue;
  40341. valueMin = newValue;
  40342. repaint();
  40343. if (popupDisplay != 0)
  40344. {
  40345. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  40346. ->updatePosition (getTextFromValue (newValue));
  40347. popupDisplay->repaint();
  40348. }
  40349. if (sendUpdateMessage)
  40350. triggerChangeMessage (sendMessageSynchronously);
  40351. }
  40352. }
  40353. void Slider::setMaxValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  40354. {
  40355. // The maximum value only applies to sliders that are in two- or three-value mode.
  40356. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40357. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40358. newValue = constrainedValue (newValue);
  40359. if (style == TwoValueHorizontal || style == TwoValueVertical)
  40360. {
  40361. if (allowNudgingOfOtherValues && newValue < (double) valueMin.getValue())
  40362. setMinValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40363. newValue = jmax ((double) valueMin.getValue(), newValue);
  40364. }
  40365. else
  40366. {
  40367. if (allowNudgingOfOtherValues && newValue < lastCurrentValue)
  40368. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40369. newValue = jmax (lastCurrentValue, newValue);
  40370. }
  40371. if (lastValueMax != newValue)
  40372. {
  40373. lastValueMax = newValue;
  40374. valueMax = newValue;
  40375. repaint();
  40376. if (popupDisplay != 0)
  40377. {
  40378. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  40379. ->updatePosition (getTextFromValue (valueMax.getValue()));
  40380. popupDisplay->repaint();
  40381. }
  40382. if (sendUpdateMessage)
  40383. triggerChangeMessage (sendMessageSynchronously);
  40384. }
  40385. }
  40386. void Slider::setDoubleClickReturnValue (const bool isDoubleClickEnabled,
  40387. const double valueToSetOnDoubleClick)
  40388. {
  40389. doubleClickToValue = isDoubleClickEnabled;
  40390. doubleClickReturnValue = valueToSetOnDoubleClick;
  40391. }
  40392. double Slider::getDoubleClickReturnValue (bool& isEnabled_) const
  40393. {
  40394. isEnabled_ = doubleClickToValue;
  40395. return doubleClickReturnValue;
  40396. }
  40397. void Slider::updateText()
  40398. {
  40399. if (valueBox != 0)
  40400. valueBox->setText (getTextFromValue (currentValue.getValue()), false);
  40401. }
  40402. void Slider::setTextValueSuffix (const String& suffix)
  40403. {
  40404. if (textSuffix != suffix)
  40405. {
  40406. textSuffix = suffix;
  40407. updateText();
  40408. }
  40409. }
  40410. const String Slider::getTextValueSuffix() const
  40411. {
  40412. return textSuffix;
  40413. }
  40414. const String Slider::getTextFromValue (double v)
  40415. {
  40416. if (getNumDecimalPlacesToDisplay() > 0)
  40417. return String (v, getNumDecimalPlacesToDisplay()) + getTextValueSuffix();
  40418. else
  40419. return String (roundToInt (v)) + getTextValueSuffix();
  40420. }
  40421. double Slider::getValueFromText (const String& text)
  40422. {
  40423. String t (text.trimStart());
  40424. if (t.endsWith (textSuffix))
  40425. t = t.substring (0, t.length() - textSuffix.length());
  40426. while (t.startsWithChar ('+'))
  40427. t = t.substring (1).trimStart();
  40428. return t.initialSectionContainingOnly ("0123456789.,-")
  40429. .getDoubleValue();
  40430. }
  40431. double Slider::proportionOfLengthToValue (double proportion)
  40432. {
  40433. if (skewFactor != 1.0 && proportion > 0.0)
  40434. proportion = exp (log (proportion) / skewFactor);
  40435. return minimum + (maximum - minimum) * proportion;
  40436. }
  40437. double Slider::valueToProportionOfLength (double value)
  40438. {
  40439. const double n = (value - minimum) / (maximum - minimum);
  40440. return skewFactor == 1.0 ? n : pow (n, skewFactor);
  40441. }
  40442. double Slider::snapValue (double attemptedValue, const bool)
  40443. {
  40444. return attemptedValue;
  40445. }
  40446. void Slider::startedDragging()
  40447. {
  40448. }
  40449. void Slider::stoppedDragging()
  40450. {
  40451. }
  40452. void Slider::valueChanged()
  40453. {
  40454. }
  40455. void Slider::enablementChanged()
  40456. {
  40457. repaint();
  40458. }
  40459. void Slider::setPopupMenuEnabled (const bool menuEnabled_)
  40460. {
  40461. menuEnabled = menuEnabled_;
  40462. }
  40463. void Slider::setScrollWheelEnabled (const bool enabled)
  40464. {
  40465. scrollWheelEnabled = enabled;
  40466. }
  40467. void Slider::labelTextChanged (Label* label)
  40468. {
  40469. const double newValue = snapValue (getValueFromText (label->getText()), false);
  40470. if (newValue != (double) currentValue.getValue())
  40471. {
  40472. sendDragStart();
  40473. setValue (newValue, true, true);
  40474. sendDragEnd();
  40475. }
  40476. updateText(); // force a clean-up of the text, needed in case setValue() hasn't done this.
  40477. }
  40478. void Slider::buttonClicked (Button* button)
  40479. {
  40480. if (style == IncDecButtons)
  40481. {
  40482. sendDragStart();
  40483. if (button == incButton)
  40484. setValue (snapValue (getValue() + interval, false), true, true);
  40485. else if (button == decButton)
  40486. setValue (snapValue (getValue() - interval, false), true, true);
  40487. sendDragEnd();
  40488. }
  40489. }
  40490. double Slider::constrainedValue (double value) const
  40491. {
  40492. if (interval > 0)
  40493. value = minimum + interval * std::floor ((value - minimum) / interval + 0.5);
  40494. if (value <= minimum || maximum <= minimum)
  40495. value = minimum;
  40496. else if (value >= maximum)
  40497. value = maximum;
  40498. return value;
  40499. }
  40500. float Slider::getLinearSliderPos (const double value)
  40501. {
  40502. double sliderPosProportional;
  40503. if (maximum > minimum)
  40504. {
  40505. if (value < minimum)
  40506. {
  40507. sliderPosProportional = 0.0;
  40508. }
  40509. else if (value > maximum)
  40510. {
  40511. sliderPosProportional = 1.0;
  40512. }
  40513. else
  40514. {
  40515. sliderPosProportional = valueToProportionOfLength (value);
  40516. jassert (sliderPosProportional >= 0 && sliderPosProportional <= 1.0);
  40517. }
  40518. }
  40519. else
  40520. {
  40521. sliderPosProportional = 0.5;
  40522. }
  40523. if (isVertical() || style == IncDecButtons)
  40524. sliderPosProportional = 1.0 - sliderPosProportional;
  40525. return (float) (sliderRegionStart + sliderPosProportional * sliderRegionSize);
  40526. }
  40527. bool Slider::isHorizontal() const
  40528. {
  40529. return style == LinearHorizontal
  40530. || style == LinearBar
  40531. || style == TwoValueHorizontal
  40532. || style == ThreeValueHorizontal;
  40533. }
  40534. bool Slider::isVertical() const
  40535. {
  40536. return style == LinearVertical
  40537. || style == TwoValueVertical
  40538. || style == ThreeValueVertical;
  40539. }
  40540. bool Slider::incDecDragDirectionIsHorizontal() const
  40541. {
  40542. return incDecButtonMode == incDecButtonsDraggable_Horizontal
  40543. || (incDecButtonMode == incDecButtonsDraggable_AutoDirection && incDecButtonsSideBySide);
  40544. }
  40545. float Slider::getPositionOfValue (const double value)
  40546. {
  40547. if (isHorizontal() || isVertical())
  40548. {
  40549. return getLinearSliderPos (value);
  40550. }
  40551. else
  40552. {
  40553. jassertfalse; // not a valid call on a slider that doesn't work linearly!
  40554. return 0.0f;
  40555. }
  40556. }
  40557. void Slider::paint (Graphics& g)
  40558. {
  40559. if (style != IncDecButtons)
  40560. {
  40561. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40562. {
  40563. const float sliderPos = (float) valueToProportionOfLength (lastCurrentValue);
  40564. jassert (sliderPos >= 0 && sliderPos <= 1.0f);
  40565. getLookAndFeel().drawRotarySlider (g,
  40566. sliderRect.getX(),
  40567. sliderRect.getY(),
  40568. sliderRect.getWidth(),
  40569. sliderRect.getHeight(),
  40570. sliderPos,
  40571. rotaryStart, rotaryEnd,
  40572. *this);
  40573. }
  40574. else
  40575. {
  40576. getLookAndFeel().drawLinearSlider (g,
  40577. sliderRect.getX(),
  40578. sliderRect.getY(),
  40579. sliderRect.getWidth(),
  40580. sliderRect.getHeight(),
  40581. getLinearSliderPos (lastCurrentValue),
  40582. getLinearSliderPos (lastValueMin),
  40583. getLinearSliderPos (lastValueMax),
  40584. style,
  40585. *this);
  40586. }
  40587. if (style == LinearBar && valueBox == 0)
  40588. {
  40589. g.setColour (findColour (Slider::textBoxOutlineColourId));
  40590. g.drawRect (0, 0, getWidth(), getHeight(), 1);
  40591. }
  40592. }
  40593. }
  40594. void Slider::resized()
  40595. {
  40596. int minXSpace = 0;
  40597. int minYSpace = 0;
  40598. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  40599. minXSpace = 30;
  40600. else
  40601. minYSpace = 15;
  40602. const int tbw = jmax (0, jmin (textBoxWidth, getWidth() - minXSpace));
  40603. const int tbh = jmax (0, jmin (textBoxHeight, getHeight() - minYSpace));
  40604. if (style == LinearBar)
  40605. {
  40606. if (valueBox != 0)
  40607. valueBox->setBounds (getLocalBounds());
  40608. }
  40609. else
  40610. {
  40611. if (textBoxPos == NoTextBox)
  40612. {
  40613. sliderRect = getLocalBounds();
  40614. }
  40615. else if (textBoxPos == TextBoxLeft)
  40616. {
  40617. valueBox->setBounds (0, (getHeight() - tbh) / 2, tbw, tbh);
  40618. sliderRect.setBounds (tbw, 0, getWidth() - tbw, getHeight());
  40619. }
  40620. else if (textBoxPos == TextBoxRight)
  40621. {
  40622. valueBox->setBounds (getWidth() - tbw, (getHeight() - tbh) / 2, tbw, tbh);
  40623. sliderRect.setBounds (0, 0, getWidth() - tbw, getHeight());
  40624. }
  40625. else if (textBoxPos == TextBoxAbove)
  40626. {
  40627. valueBox->setBounds ((getWidth() - tbw) / 2, 0, tbw, tbh);
  40628. sliderRect.setBounds (0, tbh, getWidth(), getHeight() - tbh);
  40629. }
  40630. else if (textBoxPos == TextBoxBelow)
  40631. {
  40632. valueBox->setBounds ((getWidth() - tbw) / 2, getHeight() - tbh, tbw, tbh);
  40633. sliderRect.setBounds (0, 0, getWidth(), getHeight() - tbh);
  40634. }
  40635. }
  40636. const int indent = getLookAndFeel().getSliderThumbRadius (*this);
  40637. if (style == LinearBar)
  40638. {
  40639. const int barIndent = 1;
  40640. sliderRegionStart = barIndent;
  40641. sliderRegionSize = getWidth() - barIndent * 2;
  40642. sliderRect.setBounds (sliderRegionStart, barIndent,
  40643. sliderRegionSize, getHeight() - barIndent * 2);
  40644. }
  40645. else if (isHorizontal())
  40646. {
  40647. sliderRegionStart = sliderRect.getX() + indent;
  40648. sliderRegionSize = jmax (1, sliderRect.getWidth() - indent * 2);
  40649. sliderRect.setBounds (sliderRegionStart, sliderRect.getY(),
  40650. sliderRegionSize, sliderRect.getHeight());
  40651. }
  40652. else if (isVertical())
  40653. {
  40654. sliderRegionStart = sliderRect.getY() + indent;
  40655. sliderRegionSize = jmax (1, sliderRect.getHeight() - indent * 2);
  40656. sliderRect.setBounds (sliderRect.getX(), sliderRegionStart,
  40657. sliderRect.getWidth(), sliderRegionSize);
  40658. }
  40659. else
  40660. {
  40661. sliderRegionStart = 0;
  40662. sliderRegionSize = 100;
  40663. }
  40664. if (style == IncDecButtons)
  40665. {
  40666. Rectangle<int> buttonRect (sliderRect);
  40667. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  40668. buttonRect.expand (-2, 0);
  40669. else
  40670. buttonRect.expand (0, -2);
  40671. incDecButtonsSideBySide = buttonRect.getWidth() > buttonRect.getHeight();
  40672. if (incDecButtonsSideBySide)
  40673. {
  40674. decButton->setBounds (buttonRect.getX(),
  40675. buttonRect.getY(),
  40676. buttonRect.getWidth() / 2,
  40677. buttonRect.getHeight());
  40678. decButton->setConnectedEdges (Button::ConnectedOnRight);
  40679. incButton->setBounds (buttonRect.getCentreX(),
  40680. buttonRect.getY(),
  40681. buttonRect.getWidth() / 2,
  40682. buttonRect.getHeight());
  40683. incButton->setConnectedEdges (Button::ConnectedOnLeft);
  40684. }
  40685. else
  40686. {
  40687. incButton->setBounds (buttonRect.getX(),
  40688. buttonRect.getY(),
  40689. buttonRect.getWidth(),
  40690. buttonRect.getHeight() / 2);
  40691. incButton->setConnectedEdges (Button::ConnectedOnBottom);
  40692. decButton->setBounds (buttonRect.getX(),
  40693. buttonRect.getCentreY(),
  40694. buttonRect.getWidth(),
  40695. buttonRect.getHeight() / 2);
  40696. decButton->setConnectedEdges (Button::ConnectedOnTop);
  40697. }
  40698. }
  40699. }
  40700. void Slider::focusOfChildComponentChanged (FocusChangeType)
  40701. {
  40702. repaint();
  40703. }
  40704. void Slider::mouseDown (const MouseEvent& e)
  40705. {
  40706. mouseWasHidden = false;
  40707. incDecDragged = false;
  40708. mouseXWhenLastDragged = e.x;
  40709. mouseYWhenLastDragged = e.y;
  40710. mouseDragStartX = e.getMouseDownX();
  40711. mouseDragStartY = e.getMouseDownY();
  40712. if (isEnabled())
  40713. {
  40714. if (e.mods.isPopupMenu() && menuEnabled)
  40715. {
  40716. menuShown = true;
  40717. PopupMenu m;
  40718. m.setLookAndFeel (&getLookAndFeel());
  40719. m.addItem (1, TRANS ("velocity-sensitive mode"), true, isVelocityBased);
  40720. m.addSeparator();
  40721. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40722. {
  40723. PopupMenu rotaryMenu;
  40724. rotaryMenu.addItem (2, TRANS ("use circular dragging"), true, style == Rotary);
  40725. rotaryMenu.addItem (3, TRANS ("use left-right dragging"), true, style == RotaryHorizontalDrag);
  40726. rotaryMenu.addItem (4, TRANS ("use up-down dragging"), true, style == RotaryVerticalDrag);
  40727. m.addSubMenu (TRANS ("rotary mode"), rotaryMenu);
  40728. }
  40729. const int r = m.show();
  40730. if (r == 1)
  40731. {
  40732. setVelocityBasedMode (! isVelocityBased);
  40733. }
  40734. else if (r == 2)
  40735. {
  40736. setSliderStyle (Rotary);
  40737. }
  40738. else if (r == 3)
  40739. {
  40740. setSliderStyle (RotaryHorizontalDrag);
  40741. }
  40742. else if (r == 4)
  40743. {
  40744. setSliderStyle (RotaryVerticalDrag);
  40745. }
  40746. }
  40747. else if (maximum > minimum)
  40748. {
  40749. menuShown = false;
  40750. if (valueBox != 0)
  40751. valueBox->hideEditor (true);
  40752. sliderBeingDragged = 0;
  40753. if (style == TwoValueHorizontal
  40754. || style == TwoValueVertical
  40755. || style == ThreeValueHorizontal
  40756. || style == ThreeValueVertical)
  40757. {
  40758. const float mousePos = (float) (isVertical() ? e.y : e.x);
  40759. const float normalPosDistance = std::abs (getLinearSliderPos (currentValue.getValue()) - mousePos);
  40760. const float minPosDistance = std::abs (getLinearSliderPos (valueMin.getValue()) - 0.1f - mousePos);
  40761. const float maxPosDistance = std::abs (getLinearSliderPos (valueMax.getValue()) + 0.1f - mousePos);
  40762. if (style == TwoValueHorizontal || style == TwoValueVertical)
  40763. {
  40764. if (maxPosDistance <= minPosDistance)
  40765. sliderBeingDragged = 2;
  40766. else
  40767. sliderBeingDragged = 1;
  40768. }
  40769. else if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  40770. {
  40771. if (normalPosDistance >= minPosDistance && maxPosDistance >= minPosDistance)
  40772. sliderBeingDragged = 1;
  40773. else if (normalPosDistance >= maxPosDistance)
  40774. sliderBeingDragged = 2;
  40775. }
  40776. }
  40777. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40778. lastAngle = rotaryStart + (rotaryEnd - rotaryStart)
  40779. * valueToProportionOfLength (currentValue.getValue());
  40780. valueWhenLastDragged = ((sliderBeingDragged == 2) ? valueMax
  40781. : ((sliderBeingDragged == 1) ? valueMin
  40782. : currentValue)).getValue();
  40783. valueOnMouseDown = valueWhenLastDragged;
  40784. if (popupDisplayEnabled)
  40785. {
  40786. SliderPopupDisplayComponent* const popup = new SliderPopupDisplayComponent (this);
  40787. popupDisplay = popup;
  40788. if (parentForPopupDisplay != 0)
  40789. {
  40790. parentForPopupDisplay->addChildComponent (popup);
  40791. }
  40792. else
  40793. {
  40794. popup->addToDesktop (0);
  40795. }
  40796. popup->setVisible (true);
  40797. }
  40798. sendDragStart();
  40799. mouseDrag (e);
  40800. }
  40801. }
  40802. }
  40803. void Slider::mouseUp (const MouseEvent&)
  40804. {
  40805. if (isEnabled()
  40806. && (! menuShown)
  40807. && (maximum > minimum)
  40808. && (style != IncDecButtons || incDecDragged))
  40809. {
  40810. restoreMouseIfHidden();
  40811. if (sendChangeOnlyOnRelease && valueOnMouseDown != (double) currentValue.getValue())
  40812. triggerChangeMessage (false);
  40813. sendDragEnd();
  40814. popupDisplay = 0;
  40815. if (style == IncDecButtons)
  40816. {
  40817. incButton->setState (Button::buttonNormal);
  40818. decButton->setState (Button::buttonNormal);
  40819. }
  40820. }
  40821. }
  40822. void Slider::restoreMouseIfHidden()
  40823. {
  40824. if (mouseWasHidden)
  40825. {
  40826. mouseWasHidden = false;
  40827. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  40828. Desktop::getInstance().getMouseSource(i)->enableUnboundedMouseMovement (false);
  40829. const double pos = (sliderBeingDragged == 2) ? getMaxValue()
  40830. : ((sliderBeingDragged == 1) ? getMinValue()
  40831. : (double) currentValue.getValue());
  40832. Point<int> mousePos;
  40833. if (style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40834. {
  40835. mousePos = Desktop::getLastMouseDownPosition();
  40836. if (style == RotaryHorizontalDrag)
  40837. {
  40838. const double posDiff = valueToProportionOfLength (pos) - valueToProportionOfLength (valueOnMouseDown);
  40839. mousePos += Point<int> (roundToInt (pixelsForFullDragExtent * posDiff), 0);
  40840. }
  40841. else
  40842. {
  40843. const double posDiff = valueToProportionOfLength (valueOnMouseDown) - valueToProportionOfLength (pos);
  40844. mousePos += Point<int> (0, roundToInt (pixelsForFullDragExtent * posDiff));
  40845. }
  40846. }
  40847. else
  40848. {
  40849. const int pixelPos = (int) getLinearSliderPos (pos);
  40850. mousePos = relativePositionToGlobal (Point<int> (isHorizontal() ? pixelPos : (getWidth() / 2),
  40851. isVertical() ? pixelPos : (getHeight() / 2)));
  40852. }
  40853. Desktop::setMousePosition (mousePos);
  40854. }
  40855. }
  40856. void Slider::modifierKeysChanged (const ModifierKeys& modifiers)
  40857. {
  40858. if (isEnabled()
  40859. && style != IncDecButtons
  40860. && style != Rotary
  40861. && isVelocityBased == modifiers.isAnyModifierKeyDown())
  40862. {
  40863. restoreMouseIfHidden();
  40864. }
  40865. }
  40866. static double smallestAngleBetween (double a1, double a2)
  40867. {
  40868. return jmin (std::abs (a1 - a2),
  40869. std::abs (a1 + double_Pi * 2.0 - a2),
  40870. std::abs (a2 + double_Pi * 2.0 - a1));
  40871. }
  40872. void Slider::mouseDrag (const MouseEvent& e)
  40873. {
  40874. if (isEnabled()
  40875. && (! menuShown)
  40876. && (maximum > minimum))
  40877. {
  40878. if (style == Rotary)
  40879. {
  40880. int dx = e.x - sliderRect.getCentreX();
  40881. int dy = e.y - sliderRect.getCentreY();
  40882. if (dx * dx + dy * dy > 25)
  40883. {
  40884. double angle = std::atan2 ((double) dx, (double) -dy);
  40885. while (angle < 0.0)
  40886. angle += double_Pi * 2.0;
  40887. if (rotaryStop && ! e.mouseWasClicked())
  40888. {
  40889. if (std::abs (angle - lastAngle) > double_Pi)
  40890. {
  40891. if (angle >= lastAngle)
  40892. angle -= double_Pi * 2.0;
  40893. else
  40894. angle += double_Pi * 2.0;
  40895. }
  40896. if (angle >= lastAngle)
  40897. angle = jmin (angle, (double) jmax (rotaryStart, rotaryEnd));
  40898. else
  40899. angle = jmax (angle, (double) jmin (rotaryStart, rotaryEnd));
  40900. }
  40901. else
  40902. {
  40903. while (angle < rotaryStart)
  40904. angle += double_Pi * 2.0;
  40905. if (angle > rotaryEnd)
  40906. {
  40907. if (smallestAngleBetween (angle, rotaryStart) <= smallestAngleBetween (angle, rotaryEnd))
  40908. angle = rotaryStart;
  40909. else
  40910. angle = rotaryEnd;
  40911. }
  40912. }
  40913. const double proportion = (angle - rotaryStart) / (rotaryEnd - rotaryStart);
  40914. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, proportion));
  40915. lastAngle = angle;
  40916. }
  40917. }
  40918. else
  40919. {
  40920. if (style == LinearBar && e.mouseWasClicked()
  40921. && valueBox != 0 && valueBox->isEditable())
  40922. return;
  40923. if (style == IncDecButtons && ! incDecDragged)
  40924. {
  40925. if (e.getDistanceFromDragStart() < 10 || e.mouseWasClicked())
  40926. return;
  40927. incDecDragged = true;
  40928. mouseDragStartX = e.x;
  40929. mouseDragStartY = e.y;
  40930. }
  40931. if ((isVelocityBased == (userKeyOverridesVelocity ? e.mods.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::commandModifier | ModifierKeys::altModifier)
  40932. : false))
  40933. || ((maximum - minimum) / sliderRegionSize < interval))
  40934. {
  40935. const int mousePos = (isHorizontal() || style == RotaryHorizontalDrag) ? e.x : e.y;
  40936. double scaledMousePos = (mousePos - sliderRegionStart) / (double) sliderRegionSize;
  40937. if (style == RotaryHorizontalDrag
  40938. || style == RotaryVerticalDrag
  40939. || style == IncDecButtons
  40940. || ((style == LinearHorizontal || style == LinearVertical || style == LinearBar)
  40941. && ! snapsToMousePos))
  40942. {
  40943. const int mouseDiff = (style == RotaryHorizontalDrag
  40944. || style == LinearHorizontal
  40945. || style == LinearBar
  40946. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  40947. ? e.x - mouseDragStartX
  40948. : mouseDragStartY - e.y;
  40949. double newPos = valueToProportionOfLength (valueOnMouseDown)
  40950. + mouseDiff * (1.0 / pixelsForFullDragExtent);
  40951. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, newPos));
  40952. if (style == IncDecButtons)
  40953. {
  40954. incButton->setState (mouseDiff < 0 ? Button::buttonNormal : Button::buttonDown);
  40955. decButton->setState (mouseDiff > 0 ? Button::buttonNormal : Button::buttonDown);
  40956. }
  40957. }
  40958. else
  40959. {
  40960. if (isVertical())
  40961. scaledMousePos = 1.0 - scaledMousePos;
  40962. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, scaledMousePos));
  40963. }
  40964. }
  40965. else
  40966. {
  40967. const int mouseDiff = (isHorizontal() || style == RotaryHorizontalDrag
  40968. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  40969. ? e.x - mouseXWhenLastDragged
  40970. : e.y - mouseYWhenLastDragged;
  40971. const double maxSpeed = jmax (200, sliderRegionSize);
  40972. double speed = jlimit (0.0, maxSpeed, (double) abs (mouseDiff));
  40973. if (speed != 0)
  40974. {
  40975. speed = 0.2 * velocityModeSensitivity
  40976. * (1.0 + std::sin (double_Pi * (1.5 + jmin (0.5, velocityModeOffset
  40977. + jmax (0.0, (double) (speed - velocityModeThreshold))
  40978. / maxSpeed))));
  40979. if (mouseDiff < 0)
  40980. speed = -speed;
  40981. if (isVertical() || style == RotaryVerticalDrag
  40982. || (style == IncDecButtons && ! incDecDragDirectionIsHorizontal()))
  40983. speed = -speed;
  40984. const double currentPos = valueToProportionOfLength (valueWhenLastDragged);
  40985. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + speed));
  40986. e.source.enableUnboundedMouseMovement (true, false);
  40987. mouseWasHidden = true;
  40988. }
  40989. }
  40990. }
  40991. valueWhenLastDragged = jlimit (minimum, maximum, valueWhenLastDragged);
  40992. if (sliderBeingDragged == 0)
  40993. {
  40994. setValue (snapValue (valueWhenLastDragged, true),
  40995. ! sendChangeOnlyOnRelease, true);
  40996. }
  40997. else if (sliderBeingDragged == 1)
  40998. {
  40999. setMinValue (snapValue (valueWhenLastDragged, true),
  41000. ! sendChangeOnlyOnRelease, false, true);
  41001. if (e.mods.isShiftDown())
  41002. setMaxValue (getMinValue() + minMaxDiff, false, false, true);
  41003. else
  41004. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  41005. }
  41006. else
  41007. {
  41008. jassert (sliderBeingDragged == 2);
  41009. setMaxValue (snapValue (valueWhenLastDragged, true),
  41010. ! sendChangeOnlyOnRelease, false, true);
  41011. if (e.mods.isShiftDown())
  41012. setMinValue (getMaxValue() - minMaxDiff, false, false, true);
  41013. else
  41014. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  41015. }
  41016. mouseXWhenLastDragged = e.x;
  41017. mouseYWhenLastDragged = e.y;
  41018. }
  41019. }
  41020. void Slider::mouseDoubleClick (const MouseEvent&)
  41021. {
  41022. if (doubleClickToValue
  41023. && isEnabled()
  41024. && style != IncDecButtons
  41025. && minimum <= doubleClickReturnValue
  41026. && maximum >= doubleClickReturnValue)
  41027. {
  41028. sendDragStart();
  41029. setValue (doubleClickReturnValue, true, true);
  41030. sendDragEnd();
  41031. }
  41032. }
  41033. void Slider::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  41034. {
  41035. if (scrollWheelEnabled && isEnabled()
  41036. && style != TwoValueHorizontal
  41037. && style != TwoValueVertical)
  41038. {
  41039. if (maximum > minimum && ! e.mods.isAnyMouseButtonDown())
  41040. {
  41041. if (valueBox != 0)
  41042. valueBox->hideEditor (false);
  41043. const double value = (double) currentValue.getValue();
  41044. const double proportionDelta = (wheelIncrementX != 0 ? -wheelIncrementX : wheelIncrementY) * 0.15f;
  41045. const double currentPos = valueToProportionOfLength (value);
  41046. const double newValue = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + proportionDelta));
  41047. double delta = (newValue != value)
  41048. ? jmax (std::abs (newValue - value), interval) : 0;
  41049. if (value > newValue)
  41050. delta = -delta;
  41051. sendDragStart();
  41052. setValue (snapValue (value + delta, false), true, true);
  41053. sendDragEnd();
  41054. }
  41055. }
  41056. else
  41057. {
  41058. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  41059. }
  41060. }
  41061. void SliderListener::sliderDragStarted (Slider*) // (can't write Slider::Listener due to idiotic VC2005 bug)
  41062. {
  41063. }
  41064. void SliderListener::sliderDragEnded (Slider*)
  41065. {
  41066. }
  41067. END_JUCE_NAMESPACE
  41068. /*** End of inlined file: juce_Slider.cpp ***/
  41069. /*** Start of inlined file: juce_TableHeaderComponent.cpp ***/
  41070. BEGIN_JUCE_NAMESPACE
  41071. class DragOverlayComp : public Component
  41072. {
  41073. public:
  41074. DragOverlayComp (const Image& image_)
  41075. : image (image_)
  41076. {
  41077. image.duplicateIfShared();
  41078. image.multiplyAllAlphas (0.8f);
  41079. setAlwaysOnTop (true);
  41080. }
  41081. ~DragOverlayComp()
  41082. {
  41083. }
  41084. void paint (Graphics& g)
  41085. {
  41086. g.drawImageAt (image, 0, 0);
  41087. }
  41088. private:
  41089. Image image;
  41090. DragOverlayComp (const DragOverlayComp&);
  41091. DragOverlayComp& operator= (const DragOverlayComp&);
  41092. };
  41093. TableHeaderComponent::TableHeaderComponent()
  41094. : columnsChanged (false),
  41095. columnsResized (false),
  41096. sortChanged (false),
  41097. menuActive (true),
  41098. stretchToFit (false),
  41099. columnIdBeingResized (0),
  41100. columnIdBeingDragged (0),
  41101. columnIdUnderMouse (0),
  41102. lastDeliberateWidth (0)
  41103. {
  41104. }
  41105. TableHeaderComponent::~TableHeaderComponent()
  41106. {
  41107. dragOverlayComp = 0;
  41108. }
  41109. void TableHeaderComponent::setPopupMenuActive (const bool hasMenu)
  41110. {
  41111. menuActive = hasMenu;
  41112. }
  41113. bool TableHeaderComponent::isPopupMenuActive() const { return menuActive; }
  41114. int TableHeaderComponent::getNumColumns (const bool onlyCountVisibleColumns) const
  41115. {
  41116. if (onlyCountVisibleColumns)
  41117. {
  41118. int num = 0;
  41119. for (int i = columns.size(); --i >= 0;)
  41120. if (columns.getUnchecked(i)->isVisible())
  41121. ++num;
  41122. return num;
  41123. }
  41124. else
  41125. {
  41126. return columns.size();
  41127. }
  41128. }
  41129. const String TableHeaderComponent::getColumnName (const int columnId) const
  41130. {
  41131. const ColumnInfo* const ci = getInfoForId (columnId);
  41132. return ci != 0 ? ci->name : String::empty;
  41133. }
  41134. void TableHeaderComponent::setColumnName (const int columnId, const String& newName)
  41135. {
  41136. ColumnInfo* const ci = getInfoForId (columnId);
  41137. if (ci != 0 && ci->name != newName)
  41138. {
  41139. ci->name = newName;
  41140. sendColumnsChanged();
  41141. }
  41142. }
  41143. void TableHeaderComponent::addColumn (const String& columnName,
  41144. const int columnId,
  41145. const int width,
  41146. const int minimumWidth,
  41147. const int maximumWidth,
  41148. const int propertyFlags,
  41149. const int insertIndex)
  41150. {
  41151. // can't have a duplicate or null ID!
  41152. jassert (columnId != 0 && getIndexOfColumnId (columnId, false) < 0);
  41153. jassert (width > 0);
  41154. ColumnInfo* const ci = new ColumnInfo();
  41155. ci->name = columnName;
  41156. ci->id = columnId;
  41157. ci->width = width;
  41158. ci->lastDeliberateWidth = width;
  41159. ci->minimumWidth = minimumWidth;
  41160. ci->maximumWidth = maximumWidth;
  41161. if (ci->maximumWidth < 0)
  41162. ci->maximumWidth = std::numeric_limits<int>::max();
  41163. jassert (ci->maximumWidth >= ci->minimumWidth);
  41164. ci->propertyFlags = propertyFlags;
  41165. columns.insert (insertIndex, ci);
  41166. sendColumnsChanged();
  41167. }
  41168. void TableHeaderComponent::removeColumn (const int columnIdToRemove)
  41169. {
  41170. const int index = getIndexOfColumnId (columnIdToRemove, false);
  41171. if (index >= 0)
  41172. {
  41173. columns.remove (index);
  41174. sortChanged = true;
  41175. sendColumnsChanged();
  41176. }
  41177. }
  41178. void TableHeaderComponent::removeAllColumns()
  41179. {
  41180. if (columns.size() > 0)
  41181. {
  41182. columns.clear();
  41183. sendColumnsChanged();
  41184. }
  41185. }
  41186. void TableHeaderComponent::moveColumn (const int columnId, int newIndex)
  41187. {
  41188. const int currentIndex = getIndexOfColumnId (columnId, false);
  41189. newIndex = visibleIndexToTotalIndex (newIndex);
  41190. if (columns [currentIndex] != 0 && currentIndex != newIndex)
  41191. {
  41192. columns.move (currentIndex, newIndex);
  41193. sendColumnsChanged();
  41194. }
  41195. }
  41196. int TableHeaderComponent::getColumnWidth (const int columnId) const
  41197. {
  41198. const ColumnInfo* const ci = getInfoForId (columnId);
  41199. return ci != 0 ? ci->width : 0;
  41200. }
  41201. void TableHeaderComponent::setColumnWidth (const int columnId, const int newWidth)
  41202. {
  41203. ColumnInfo* const ci = getInfoForId (columnId);
  41204. if (ci != 0 && ci->width != newWidth)
  41205. {
  41206. const int numColumns = getNumColumns (true);
  41207. ci->lastDeliberateWidth = ci->width
  41208. = jlimit (ci->minimumWidth, ci->maximumWidth, newWidth);
  41209. if (stretchToFit)
  41210. {
  41211. const int index = getIndexOfColumnId (columnId, true) + 1;
  41212. if (((unsigned int) index) < (unsigned int) numColumns)
  41213. {
  41214. const int x = getColumnPosition (index).getX();
  41215. if (lastDeliberateWidth == 0)
  41216. lastDeliberateWidth = getTotalWidth();
  41217. resizeColumnsToFit (visibleIndexToTotalIndex (index), lastDeliberateWidth - x);
  41218. }
  41219. }
  41220. repaint();
  41221. columnsResized = true;
  41222. triggerAsyncUpdate();
  41223. }
  41224. }
  41225. int TableHeaderComponent::getIndexOfColumnId (const int columnId, const bool onlyCountVisibleColumns) const
  41226. {
  41227. int n = 0;
  41228. for (int i = 0; i < columns.size(); ++i)
  41229. {
  41230. if ((! onlyCountVisibleColumns) || columns.getUnchecked(i)->isVisible())
  41231. {
  41232. if (columns.getUnchecked(i)->id == columnId)
  41233. return n;
  41234. ++n;
  41235. }
  41236. }
  41237. return -1;
  41238. }
  41239. int TableHeaderComponent::getColumnIdOfIndex (int index, const bool onlyCountVisibleColumns) const
  41240. {
  41241. if (onlyCountVisibleColumns)
  41242. index = visibleIndexToTotalIndex (index);
  41243. const ColumnInfo* const ci = columns [index];
  41244. return (ci != 0) ? ci->id : 0;
  41245. }
  41246. const Rectangle<int> TableHeaderComponent::getColumnPosition (const int index) const
  41247. {
  41248. int x = 0, width = 0, n = 0;
  41249. for (int i = 0; i < columns.size(); ++i)
  41250. {
  41251. x += width;
  41252. if (columns.getUnchecked(i)->isVisible())
  41253. {
  41254. width = columns.getUnchecked(i)->width;
  41255. if (n++ == index)
  41256. break;
  41257. }
  41258. else
  41259. {
  41260. width = 0;
  41261. }
  41262. }
  41263. return Rectangle<int> (x, 0, width, getHeight());
  41264. }
  41265. int TableHeaderComponent::getColumnIdAtX (const int xToFind) const
  41266. {
  41267. if (xToFind >= 0)
  41268. {
  41269. int x = 0;
  41270. for (int i = 0; i < columns.size(); ++i)
  41271. {
  41272. const ColumnInfo* const ci = columns.getUnchecked(i);
  41273. if (ci->isVisible())
  41274. {
  41275. x += ci->width;
  41276. if (xToFind < x)
  41277. return ci->id;
  41278. }
  41279. }
  41280. }
  41281. return 0;
  41282. }
  41283. int TableHeaderComponent::getTotalWidth() const
  41284. {
  41285. int w = 0;
  41286. for (int i = columns.size(); --i >= 0;)
  41287. if (columns.getUnchecked(i)->isVisible())
  41288. w += columns.getUnchecked(i)->width;
  41289. return w;
  41290. }
  41291. void TableHeaderComponent::setStretchToFitActive (const bool shouldStretchToFit)
  41292. {
  41293. stretchToFit = shouldStretchToFit;
  41294. lastDeliberateWidth = getTotalWidth();
  41295. resized();
  41296. }
  41297. bool TableHeaderComponent::isStretchToFitActive() const
  41298. {
  41299. return stretchToFit;
  41300. }
  41301. void TableHeaderComponent::resizeAllColumnsToFit (int targetTotalWidth)
  41302. {
  41303. if (stretchToFit && getWidth() > 0
  41304. && columnIdBeingResized == 0 && columnIdBeingDragged == 0)
  41305. {
  41306. lastDeliberateWidth = targetTotalWidth;
  41307. resizeColumnsToFit (0, targetTotalWidth);
  41308. }
  41309. }
  41310. void TableHeaderComponent::resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth)
  41311. {
  41312. targetTotalWidth = jmax (targetTotalWidth, 0);
  41313. StretchableObjectResizer sor;
  41314. int i;
  41315. for (i = firstColumnIndex; i < columns.size(); ++i)
  41316. {
  41317. ColumnInfo* const ci = columns.getUnchecked(i);
  41318. if (ci->isVisible())
  41319. sor.addItem (ci->lastDeliberateWidth, ci->minimumWidth, ci->maximumWidth);
  41320. }
  41321. sor.resizeToFit (targetTotalWidth);
  41322. int visIndex = 0;
  41323. for (i = firstColumnIndex; i < columns.size(); ++i)
  41324. {
  41325. ColumnInfo* const ci = columns.getUnchecked(i);
  41326. if (ci->isVisible())
  41327. {
  41328. const int newWidth = jlimit (ci->minimumWidth, ci->maximumWidth,
  41329. (int) std::floor (sor.getItemSize (visIndex++)));
  41330. if (newWidth != ci->width)
  41331. {
  41332. ci->width = newWidth;
  41333. repaint();
  41334. columnsResized = true;
  41335. triggerAsyncUpdate();
  41336. }
  41337. }
  41338. }
  41339. }
  41340. void TableHeaderComponent::setColumnVisible (const int columnId, const bool shouldBeVisible)
  41341. {
  41342. ColumnInfo* const ci = getInfoForId (columnId);
  41343. if (ci != 0 && shouldBeVisible != ci->isVisible())
  41344. {
  41345. if (shouldBeVisible)
  41346. ci->propertyFlags |= visible;
  41347. else
  41348. ci->propertyFlags &= ~visible;
  41349. sendColumnsChanged();
  41350. resized();
  41351. }
  41352. }
  41353. bool TableHeaderComponent::isColumnVisible (const int columnId) const
  41354. {
  41355. const ColumnInfo* const ci = getInfoForId (columnId);
  41356. return ci != 0 && ci->isVisible();
  41357. }
  41358. void TableHeaderComponent::setSortColumnId (const int columnId, const bool sortForwards)
  41359. {
  41360. if (getSortColumnId() != columnId || isSortedForwards() != sortForwards)
  41361. {
  41362. for (int i = columns.size(); --i >= 0;)
  41363. columns.getUnchecked(i)->propertyFlags &= ~(sortedForwards | sortedBackwards);
  41364. ColumnInfo* const ci = getInfoForId (columnId);
  41365. if (ci != 0)
  41366. ci->propertyFlags |= (sortForwards ? sortedForwards : sortedBackwards);
  41367. reSortTable();
  41368. }
  41369. }
  41370. int TableHeaderComponent::getSortColumnId() const
  41371. {
  41372. for (int i = columns.size(); --i >= 0;)
  41373. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  41374. return columns.getUnchecked(i)->id;
  41375. return 0;
  41376. }
  41377. bool TableHeaderComponent::isSortedForwards() const
  41378. {
  41379. for (int i = columns.size(); --i >= 0;)
  41380. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  41381. return (columns.getUnchecked(i)->propertyFlags & sortedForwards) != 0;
  41382. return true;
  41383. }
  41384. void TableHeaderComponent::reSortTable()
  41385. {
  41386. sortChanged = true;
  41387. repaint();
  41388. triggerAsyncUpdate();
  41389. }
  41390. const String TableHeaderComponent::toString() const
  41391. {
  41392. String s;
  41393. XmlElement doc ("TABLELAYOUT");
  41394. doc.setAttribute ("sortedCol", getSortColumnId());
  41395. doc.setAttribute ("sortForwards", isSortedForwards());
  41396. for (int i = 0; i < columns.size(); ++i)
  41397. {
  41398. const ColumnInfo* const ci = columns.getUnchecked (i);
  41399. XmlElement* const e = doc.createNewChildElement ("COLUMN");
  41400. e->setAttribute ("id", ci->id);
  41401. e->setAttribute ("visible", ci->isVisible());
  41402. e->setAttribute ("width", ci->width);
  41403. }
  41404. return doc.createDocument (String::empty, true, false);
  41405. }
  41406. void TableHeaderComponent::restoreFromString (const String& storedVersion)
  41407. {
  41408. XmlDocument doc (storedVersion);
  41409. ScopedPointer <XmlElement> storedXml (doc.getDocumentElement());
  41410. int index = 0;
  41411. if (storedXml != 0 && storedXml->hasTagName ("TABLELAYOUT"))
  41412. {
  41413. forEachXmlChildElement (*storedXml, col)
  41414. {
  41415. const int tabId = col->getIntAttribute ("id");
  41416. ColumnInfo* const ci = getInfoForId (tabId);
  41417. if (ci != 0)
  41418. {
  41419. columns.move (columns.indexOf (ci), index);
  41420. ci->width = col->getIntAttribute ("width");
  41421. setColumnVisible (tabId, col->getBoolAttribute ("visible"));
  41422. }
  41423. ++index;
  41424. }
  41425. columnsResized = true;
  41426. sendColumnsChanged();
  41427. setSortColumnId (storedXml->getIntAttribute ("sortedCol"),
  41428. storedXml->getBoolAttribute ("sortForwards", true));
  41429. }
  41430. }
  41431. void TableHeaderComponent::addListener (Listener* const newListener)
  41432. {
  41433. listeners.addIfNotAlreadyThere (newListener);
  41434. }
  41435. void TableHeaderComponent::removeListener (Listener* const listenerToRemove)
  41436. {
  41437. listeners.removeValue (listenerToRemove);
  41438. }
  41439. void TableHeaderComponent::columnClicked (int columnId, const ModifierKeys& mods)
  41440. {
  41441. const ColumnInfo* const ci = getInfoForId (columnId);
  41442. if (ci != 0 && (ci->propertyFlags & sortable) != 0 && ! mods.isPopupMenu())
  41443. setSortColumnId (columnId, (ci->propertyFlags & sortedForwards) == 0);
  41444. }
  41445. void TableHeaderComponent::addMenuItems (PopupMenu& menu, const int /*columnIdClicked*/)
  41446. {
  41447. for (int i = 0; i < columns.size(); ++i)
  41448. {
  41449. const ColumnInfo* const ci = columns.getUnchecked(i);
  41450. if ((ci->propertyFlags & appearsOnColumnMenu) != 0)
  41451. menu.addItem (ci->id, ci->name,
  41452. (ci->propertyFlags & (sortedForwards | sortedBackwards)) == 0,
  41453. isColumnVisible (ci->id));
  41454. }
  41455. }
  41456. void TableHeaderComponent::reactToMenuItem (const int menuReturnId, const int /*columnIdClicked*/)
  41457. {
  41458. if (getIndexOfColumnId (menuReturnId, false) >= 0)
  41459. setColumnVisible (menuReturnId, ! isColumnVisible (menuReturnId));
  41460. }
  41461. void TableHeaderComponent::paint (Graphics& g)
  41462. {
  41463. LookAndFeel& lf = getLookAndFeel();
  41464. lf.drawTableHeaderBackground (g, *this);
  41465. const Rectangle<int> clip (g.getClipBounds());
  41466. int x = 0;
  41467. for (int i = 0; i < columns.size(); ++i)
  41468. {
  41469. const ColumnInfo* const ci = columns.getUnchecked(i);
  41470. if (ci->isVisible())
  41471. {
  41472. if (x + ci->width > clip.getX()
  41473. && (ci->id != columnIdBeingDragged
  41474. || dragOverlayComp == 0
  41475. || ! dragOverlayComp->isVisible()))
  41476. {
  41477. g.saveState();
  41478. g.setOrigin (x, 0);
  41479. g.reduceClipRegion (0, 0, ci->width, getHeight());
  41480. lf.drawTableHeaderColumn (g, ci->name, ci->id, ci->width, getHeight(),
  41481. ci->id == columnIdUnderMouse,
  41482. ci->id == columnIdUnderMouse && isMouseButtonDown(),
  41483. ci->propertyFlags);
  41484. g.restoreState();
  41485. }
  41486. x += ci->width;
  41487. if (x >= clip.getRight())
  41488. break;
  41489. }
  41490. }
  41491. }
  41492. void TableHeaderComponent::resized()
  41493. {
  41494. }
  41495. void TableHeaderComponent::mouseMove (const MouseEvent& e)
  41496. {
  41497. updateColumnUnderMouse (e.x, e.y);
  41498. }
  41499. void TableHeaderComponent::mouseEnter (const MouseEvent& e)
  41500. {
  41501. updateColumnUnderMouse (e.x, e.y);
  41502. }
  41503. void TableHeaderComponent::mouseExit (const MouseEvent& e)
  41504. {
  41505. updateColumnUnderMouse (e.x, e.y);
  41506. }
  41507. void TableHeaderComponent::mouseDown (const MouseEvent& e)
  41508. {
  41509. repaint();
  41510. columnIdBeingResized = 0;
  41511. columnIdBeingDragged = 0;
  41512. if (columnIdUnderMouse != 0)
  41513. {
  41514. draggingColumnOffset = e.x - getColumnPosition (getIndexOfColumnId (columnIdUnderMouse, true)).getX();
  41515. if (e.mods.isPopupMenu())
  41516. columnClicked (columnIdUnderMouse, e.mods);
  41517. }
  41518. if (menuActive && e.mods.isPopupMenu())
  41519. showColumnChooserMenu (columnIdUnderMouse);
  41520. }
  41521. void TableHeaderComponent::mouseDrag (const MouseEvent& e)
  41522. {
  41523. if (columnIdBeingResized == 0
  41524. && columnIdBeingDragged == 0
  41525. && ! (e.mouseWasClicked() || e.mods.isPopupMenu()))
  41526. {
  41527. dragOverlayComp = 0;
  41528. columnIdBeingResized = getResizeDraggerAt (e.getMouseDownX());
  41529. if (columnIdBeingResized != 0)
  41530. {
  41531. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  41532. initialColumnWidth = ci->width;
  41533. }
  41534. else
  41535. {
  41536. beginDrag (e);
  41537. }
  41538. }
  41539. if (columnIdBeingResized != 0)
  41540. {
  41541. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  41542. if (ci != 0)
  41543. {
  41544. int w = jlimit (ci->minimumWidth, ci->maximumWidth,
  41545. initialColumnWidth + e.getDistanceFromDragStartX());
  41546. if (stretchToFit)
  41547. {
  41548. // prevent us dragging a column too far right if we're in stretch-to-fit mode
  41549. int minWidthOnRight = 0;
  41550. for (int i = getIndexOfColumnId (columnIdBeingResized, false) + 1; i < columns.size(); ++i)
  41551. if (columns.getUnchecked (i)->isVisible())
  41552. minWidthOnRight += columns.getUnchecked (i)->minimumWidth;
  41553. const Rectangle<int> currentPos (getColumnPosition (getIndexOfColumnId (columnIdBeingResized, true)));
  41554. w = jmax (ci->minimumWidth, jmin (w, getWidth() - minWidthOnRight - currentPos.getX()));
  41555. }
  41556. setColumnWidth (columnIdBeingResized, w);
  41557. }
  41558. }
  41559. else if (columnIdBeingDragged != 0)
  41560. {
  41561. if (e.y >= -50 && e.y < getHeight() + 50)
  41562. {
  41563. if (dragOverlayComp != 0)
  41564. {
  41565. dragOverlayComp->setVisible (true);
  41566. dragOverlayComp->setBounds (jlimit (0,
  41567. jmax (0, getTotalWidth() - dragOverlayComp->getWidth()),
  41568. e.x - draggingColumnOffset),
  41569. 0,
  41570. dragOverlayComp->getWidth(),
  41571. getHeight());
  41572. for (int i = columns.size(); --i >= 0;)
  41573. {
  41574. const int currentIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  41575. int newIndex = currentIndex;
  41576. if (newIndex > 0)
  41577. {
  41578. // if the previous column isn't draggable, we can't move our column
  41579. // past it, because that'd change the undraggable column's position..
  41580. const ColumnInfo* const previous = columns.getUnchecked (newIndex - 1);
  41581. if ((previous->propertyFlags & draggable) != 0)
  41582. {
  41583. const int leftOfPrevious = getColumnPosition (newIndex - 1).getX();
  41584. const int rightOfCurrent = getColumnPosition (newIndex).getRight();
  41585. if (abs (dragOverlayComp->getX() - leftOfPrevious)
  41586. < abs (dragOverlayComp->getRight() - rightOfCurrent))
  41587. {
  41588. --newIndex;
  41589. }
  41590. }
  41591. }
  41592. if (newIndex < columns.size() - 1)
  41593. {
  41594. // if the next column isn't draggable, we can't move our column
  41595. // past it, because that'd change the undraggable column's position..
  41596. const ColumnInfo* const nextCol = columns.getUnchecked (newIndex + 1);
  41597. if ((nextCol->propertyFlags & draggable) != 0)
  41598. {
  41599. const int leftOfCurrent = getColumnPosition (newIndex).getX();
  41600. const int rightOfNext = getColumnPosition (newIndex + 1).getRight();
  41601. if (abs (dragOverlayComp->getX() - leftOfCurrent)
  41602. > abs (dragOverlayComp->getRight() - rightOfNext))
  41603. {
  41604. ++newIndex;
  41605. }
  41606. }
  41607. }
  41608. if (newIndex != currentIndex)
  41609. moveColumn (columnIdBeingDragged, newIndex);
  41610. else
  41611. break;
  41612. }
  41613. }
  41614. }
  41615. else
  41616. {
  41617. endDrag (draggingColumnOriginalIndex);
  41618. }
  41619. }
  41620. }
  41621. void TableHeaderComponent::beginDrag (const MouseEvent& e)
  41622. {
  41623. if (columnIdBeingDragged == 0)
  41624. {
  41625. columnIdBeingDragged = getColumnIdAtX (e.getMouseDownX());
  41626. const ColumnInfo* const ci = getInfoForId (columnIdBeingDragged);
  41627. if (ci == 0 || (ci->propertyFlags & draggable) == 0)
  41628. {
  41629. columnIdBeingDragged = 0;
  41630. }
  41631. else
  41632. {
  41633. draggingColumnOriginalIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  41634. const Rectangle<int> columnRect (getColumnPosition (draggingColumnOriginalIndex));
  41635. const int temp = columnIdBeingDragged;
  41636. columnIdBeingDragged = 0;
  41637. addAndMakeVisible (dragOverlayComp = new DragOverlayComp (createComponentSnapshot (columnRect, false)));
  41638. columnIdBeingDragged = temp;
  41639. dragOverlayComp->setBounds (columnRect);
  41640. for (int i = listeners.size(); --i >= 0;)
  41641. {
  41642. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, columnIdBeingDragged);
  41643. i = jmin (i, listeners.size() - 1);
  41644. }
  41645. }
  41646. }
  41647. }
  41648. void TableHeaderComponent::endDrag (const int finalIndex)
  41649. {
  41650. if (columnIdBeingDragged != 0)
  41651. {
  41652. moveColumn (columnIdBeingDragged, finalIndex);
  41653. columnIdBeingDragged = 0;
  41654. repaint();
  41655. for (int i = listeners.size(); --i >= 0;)
  41656. {
  41657. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, 0);
  41658. i = jmin (i, listeners.size() - 1);
  41659. }
  41660. }
  41661. }
  41662. void TableHeaderComponent::mouseUp (const MouseEvent& e)
  41663. {
  41664. mouseDrag (e);
  41665. for (int i = columns.size(); --i >= 0;)
  41666. if (columns.getUnchecked (i)->isVisible())
  41667. columns.getUnchecked (i)->lastDeliberateWidth = columns.getUnchecked (i)->width;
  41668. columnIdBeingResized = 0;
  41669. repaint();
  41670. endDrag (getIndexOfColumnId (columnIdBeingDragged, true));
  41671. updateColumnUnderMouse (e.x, e.y);
  41672. if (columnIdUnderMouse != 0 && e.mouseWasClicked() && ! e.mods.isPopupMenu())
  41673. columnClicked (columnIdUnderMouse, e.mods);
  41674. dragOverlayComp = 0;
  41675. }
  41676. const MouseCursor TableHeaderComponent::getMouseCursor()
  41677. {
  41678. if (columnIdBeingResized != 0 || (getResizeDraggerAt (getMouseXYRelative().getX()) != 0 && ! isMouseButtonDown()))
  41679. return MouseCursor (MouseCursor::LeftRightResizeCursor);
  41680. return Component::getMouseCursor();
  41681. }
  41682. bool TableHeaderComponent::ColumnInfo::isVisible() const
  41683. {
  41684. return (propertyFlags & TableHeaderComponent::visible) != 0;
  41685. }
  41686. TableHeaderComponent::ColumnInfo* TableHeaderComponent::getInfoForId (const int id) const
  41687. {
  41688. for (int i = columns.size(); --i >= 0;)
  41689. if (columns.getUnchecked(i)->id == id)
  41690. return columns.getUnchecked(i);
  41691. return 0;
  41692. }
  41693. int TableHeaderComponent::visibleIndexToTotalIndex (const int visibleIndex) const
  41694. {
  41695. int n = 0;
  41696. for (int i = 0; i < columns.size(); ++i)
  41697. {
  41698. if (columns.getUnchecked(i)->isVisible())
  41699. {
  41700. if (n == visibleIndex)
  41701. return i;
  41702. ++n;
  41703. }
  41704. }
  41705. return -1;
  41706. }
  41707. void TableHeaderComponent::sendColumnsChanged()
  41708. {
  41709. if (stretchToFit && lastDeliberateWidth > 0)
  41710. resizeAllColumnsToFit (lastDeliberateWidth);
  41711. repaint();
  41712. columnsChanged = true;
  41713. triggerAsyncUpdate();
  41714. }
  41715. void TableHeaderComponent::handleAsyncUpdate()
  41716. {
  41717. const bool changed = columnsChanged || sortChanged;
  41718. const bool sized = columnsResized || changed;
  41719. const bool sorted = sortChanged;
  41720. columnsChanged = false;
  41721. columnsResized = false;
  41722. sortChanged = false;
  41723. if (sorted)
  41724. {
  41725. for (int i = listeners.size(); --i >= 0;)
  41726. {
  41727. listeners.getUnchecked(i)->tableSortOrderChanged (this);
  41728. i = jmin (i, listeners.size() - 1);
  41729. }
  41730. }
  41731. if (changed)
  41732. {
  41733. for (int i = listeners.size(); --i >= 0;)
  41734. {
  41735. listeners.getUnchecked(i)->tableColumnsChanged (this);
  41736. i = jmin (i, listeners.size() - 1);
  41737. }
  41738. }
  41739. if (sized)
  41740. {
  41741. for (int i = listeners.size(); --i >= 0;)
  41742. {
  41743. listeners.getUnchecked(i)->tableColumnsResized (this);
  41744. i = jmin (i, listeners.size() - 1);
  41745. }
  41746. }
  41747. }
  41748. int TableHeaderComponent::getResizeDraggerAt (const int mouseX) const
  41749. {
  41750. if (((unsigned int) mouseX) < (unsigned int) getWidth())
  41751. {
  41752. const int draggableDistance = 3;
  41753. int x = 0;
  41754. for (int i = 0; i < columns.size(); ++i)
  41755. {
  41756. const ColumnInfo* const ci = columns.getUnchecked(i);
  41757. if (ci->isVisible())
  41758. {
  41759. if (abs (mouseX - (x + ci->width)) <= draggableDistance
  41760. && (ci->propertyFlags & resizable) != 0)
  41761. return ci->id;
  41762. x += ci->width;
  41763. }
  41764. }
  41765. }
  41766. return 0;
  41767. }
  41768. void TableHeaderComponent::updateColumnUnderMouse (int x, int y)
  41769. {
  41770. const int newCol = (reallyContains (x, y, true) && getResizeDraggerAt (x) == 0)
  41771. ? getColumnIdAtX (x) : 0;
  41772. if (newCol != columnIdUnderMouse)
  41773. {
  41774. columnIdUnderMouse = newCol;
  41775. repaint();
  41776. }
  41777. }
  41778. void TableHeaderComponent::showColumnChooserMenu (const int columnIdClicked)
  41779. {
  41780. PopupMenu m;
  41781. addMenuItems (m, columnIdClicked);
  41782. if (m.getNumItems() > 0)
  41783. {
  41784. m.setLookAndFeel (&getLookAndFeel());
  41785. const int result = m.show();
  41786. if (result != 0)
  41787. reactToMenuItem (result, columnIdClicked);
  41788. }
  41789. }
  41790. void TableHeaderComponent::Listener::tableColumnDraggingChanged (TableHeaderComponent*, int)
  41791. {
  41792. }
  41793. END_JUCE_NAMESPACE
  41794. /*** End of inlined file: juce_TableHeaderComponent.cpp ***/
  41795. /*** Start of inlined file: juce_TableListBox.cpp ***/
  41796. BEGIN_JUCE_NAMESPACE
  41797. static const char* const tableColumnPropertyTag = "_tableColumnID";
  41798. class TableListRowComp : public Component,
  41799. public TooltipClient
  41800. {
  41801. public:
  41802. TableListRowComp (TableListBox& owner_)
  41803. : owner (owner_),
  41804. row (-1),
  41805. isSelected (false)
  41806. {
  41807. }
  41808. ~TableListRowComp()
  41809. {
  41810. deleteAllChildren();
  41811. }
  41812. void paint (Graphics& g)
  41813. {
  41814. TableListBoxModel* const model = owner.getModel();
  41815. if (model != 0)
  41816. {
  41817. const TableHeaderComponent* const header = owner.getHeader();
  41818. model->paintRowBackground (g, row, getWidth(), getHeight(), isSelected);
  41819. const int numColumns = header->getNumColumns (true);
  41820. for (int i = 0; i < numColumns; ++i)
  41821. {
  41822. if (! columnsWithComponents [i])
  41823. {
  41824. const int columnId = header->getColumnIdOfIndex (i, true);
  41825. Rectangle<int> columnRect (header->getColumnPosition (i));
  41826. columnRect.setSize (columnRect.getWidth(), getHeight());
  41827. g.saveState();
  41828. g.reduceClipRegion (columnRect);
  41829. g.setOrigin (columnRect.getX(), 0);
  41830. model->paintCell (g, row, columnId, columnRect.getWidth(), columnRect.getHeight(), isSelected);
  41831. g.restoreState();
  41832. }
  41833. }
  41834. }
  41835. }
  41836. void update (const int newRow, const bool isNowSelected)
  41837. {
  41838. if (newRow != row || isNowSelected != isSelected)
  41839. {
  41840. row = newRow;
  41841. isSelected = isNowSelected;
  41842. repaint();
  41843. deleteAllChildren();
  41844. }
  41845. if (row < owner.getNumRows())
  41846. {
  41847. jassert (row >= 0);
  41848. const Identifier tagPropertyName ("_tableLastUseNum");
  41849. const int newTag = Random::getSystemRandom().nextInt();
  41850. const TableHeaderComponent* const header = owner.getHeader();
  41851. const int numColumns = header->getNumColumns (true);
  41852. columnsWithComponents.clear();
  41853. if (owner.getModel() != 0)
  41854. {
  41855. for (int i = 0; i < numColumns; ++i)
  41856. {
  41857. const int columnId = header->getColumnIdOfIndex (i, true);
  41858. Component* const newComp
  41859. = owner.getModel()->refreshComponentForCell (row, columnId, isSelected,
  41860. findChildComponentForColumn (columnId));
  41861. if (newComp != 0)
  41862. {
  41863. addAndMakeVisible (newComp);
  41864. newComp->getProperties().set (tagPropertyName, newTag);
  41865. newComp->getProperties().set (tableColumnPropertyTag, columnId);
  41866. const Rectangle<int> columnRect (header->getColumnPosition (i));
  41867. newComp->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  41868. columnsWithComponents.setBit (i);
  41869. }
  41870. }
  41871. }
  41872. for (int i = getNumChildComponents(); --i >= 0;)
  41873. {
  41874. Component* const c = getChildComponent (i);
  41875. if ((int) c->getProperties() [tagPropertyName] != newTag)
  41876. delete c;
  41877. }
  41878. }
  41879. else
  41880. {
  41881. columnsWithComponents.clear();
  41882. deleteAllChildren();
  41883. }
  41884. }
  41885. void resized()
  41886. {
  41887. for (int i = getNumChildComponents(); --i >= 0;)
  41888. {
  41889. Component* const c = getChildComponent (i);
  41890. const int columnId = c->getProperties() [tableColumnPropertyTag];
  41891. if (columnId != 0)
  41892. {
  41893. const Rectangle<int> columnRect (owner.getHeader()->getColumnPosition (owner.getHeader()->getIndexOfColumnId (columnId, true)));
  41894. c->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  41895. }
  41896. }
  41897. }
  41898. void mouseDown (const MouseEvent& e)
  41899. {
  41900. isDragging = false;
  41901. selectRowOnMouseUp = false;
  41902. if (isEnabled())
  41903. {
  41904. if (! isSelected)
  41905. {
  41906. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  41907. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  41908. if (columnId != 0 && owner.getModel() != 0)
  41909. owner.getModel()->cellClicked (row, columnId, e);
  41910. }
  41911. else
  41912. {
  41913. selectRowOnMouseUp = true;
  41914. }
  41915. }
  41916. }
  41917. void mouseDrag (const MouseEvent& e)
  41918. {
  41919. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  41920. {
  41921. const SparseSet<int> selectedRows (owner.getSelectedRows());
  41922. if (selectedRows.size() > 0)
  41923. {
  41924. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  41925. if (dragDescription.isNotEmpty())
  41926. {
  41927. isDragging = true;
  41928. owner.startDragAndDrop (e, dragDescription);
  41929. }
  41930. }
  41931. }
  41932. }
  41933. void mouseUp (const MouseEvent& e)
  41934. {
  41935. if (selectRowOnMouseUp && e.mouseWasClicked() && isEnabled())
  41936. {
  41937. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  41938. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  41939. if (columnId != 0 && owner.getModel() != 0)
  41940. owner.getModel()->cellClicked (row, columnId, e);
  41941. }
  41942. }
  41943. void mouseDoubleClick (const MouseEvent& e)
  41944. {
  41945. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  41946. if (columnId != 0 && owner.getModel() != 0)
  41947. owner.getModel()->cellDoubleClicked (row, columnId, e);
  41948. }
  41949. const String getTooltip()
  41950. {
  41951. const int columnId = owner.getHeader()->getColumnIdAtX (getMouseXYRelative().getX());
  41952. if (columnId != 0 && owner.getModel() != 0)
  41953. return owner.getModel()->getCellTooltip (row, columnId);
  41954. return String::empty;
  41955. }
  41956. Component* findChildComponentForColumn (const int columnId) const
  41957. {
  41958. for (int i = getNumChildComponents(); --i >= 0;)
  41959. {
  41960. Component* const c = getChildComponent (i);
  41961. if ((int) c->getProperties() [tableColumnPropertyTag] == columnId)
  41962. return c;
  41963. }
  41964. return 0;
  41965. }
  41966. juce_UseDebuggingNewOperator
  41967. private:
  41968. TableListBox& owner;
  41969. int row;
  41970. bool isSelected, isDragging, selectRowOnMouseUp;
  41971. BigInteger columnsWithComponents;
  41972. TableListRowComp (const TableListRowComp&);
  41973. TableListRowComp& operator= (const TableListRowComp&);
  41974. };
  41975. class TableListBoxHeader : public TableHeaderComponent
  41976. {
  41977. public:
  41978. TableListBoxHeader (TableListBox& owner_)
  41979. : owner (owner_)
  41980. {
  41981. }
  41982. ~TableListBoxHeader()
  41983. {
  41984. }
  41985. void addMenuItems (PopupMenu& menu, int columnIdClicked)
  41986. {
  41987. if (owner.isAutoSizeMenuOptionShown())
  41988. {
  41989. menu.addItem (0xf836743, TRANS("Auto-size this column"), columnIdClicked != 0);
  41990. menu.addItem (0xf836744, TRANS("Auto-size all columns"), owner.getHeader()->getNumColumns (true) > 0);
  41991. menu.addSeparator();
  41992. }
  41993. TableHeaderComponent::addMenuItems (menu, columnIdClicked);
  41994. }
  41995. void reactToMenuItem (int menuReturnId, int columnIdClicked)
  41996. {
  41997. if (menuReturnId == 0xf836743)
  41998. {
  41999. owner.autoSizeColumn (columnIdClicked);
  42000. }
  42001. else if (menuReturnId == 0xf836744)
  42002. {
  42003. owner.autoSizeAllColumns();
  42004. }
  42005. else
  42006. {
  42007. TableHeaderComponent::reactToMenuItem (menuReturnId, columnIdClicked);
  42008. }
  42009. }
  42010. juce_UseDebuggingNewOperator
  42011. private:
  42012. TableListBox& owner;
  42013. TableListBoxHeader (const TableListBoxHeader&);
  42014. TableListBoxHeader& operator= (const TableListBoxHeader&);
  42015. };
  42016. TableListBox::TableListBox (const String& name, TableListBoxModel* const model_)
  42017. : ListBox (name, 0),
  42018. model (model_),
  42019. autoSizeOptionsShown (true)
  42020. {
  42021. ListBox::model = this;
  42022. header = new TableListBoxHeader (*this);
  42023. header->setSize (100, 28);
  42024. header->addListener (this);
  42025. setHeaderComponent (header);
  42026. }
  42027. TableListBox::~TableListBox()
  42028. {
  42029. header = 0;
  42030. }
  42031. void TableListBox::setModel (TableListBoxModel* const newModel)
  42032. {
  42033. if (model != newModel)
  42034. {
  42035. model = newModel;
  42036. updateContent();
  42037. }
  42038. }
  42039. int TableListBox::getHeaderHeight() const
  42040. {
  42041. return header->getHeight();
  42042. }
  42043. void TableListBox::setHeaderHeight (const int newHeight)
  42044. {
  42045. header->setSize (header->getWidth(), newHeight);
  42046. resized();
  42047. }
  42048. void TableListBox::autoSizeColumn (const int columnId)
  42049. {
  42050. const int width = model != 0 ? model->getColumnAutoSizeWidth (columnId) : 0;
  42051. if (width > 0)
  42052. header->setColumnWidth (columnId, width);
  42053. }
  42054. void TableListBox::autoSizeAllColumns()
  42055. {
  42056. for (int i = 0; i < header->getNumColumns (true); ++i)
  42057. autoSizeColumn (header->getColumnIdOfIndex (i, true));
  42058. }
  42059. void TableListBox::setAutoSizeMenuOptionShown (const bool shouldBeShown)
  42060. {
  42061. autoSizeOptionsShown = shouldBeShown;
  42062. }
  42063. bool TableListBox::isAutoSizeMenuOptionShown() const
  42064. {
  42065. return autoSizeOptionsShown;
  42066. }
  42067. const Rectangle<int> TableListBox::getCellPosition (const int columnId,
  42068. const int rowNumber,
  42069. const bool relativeToComponentTopLeft) const
  42070. {
  42071. Rectangle<int> headerCell (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  42072. if (relativeToComponentTopLeft)
  42073. headerCell.translate (header->getX(), 0);
  42074. const Rectangle<int> row (getRowPosition (rowNumber, relativeToComponentTopLeft));
  42075. return Rectangle<int> (headerCell.getX(), row.getY(),
  42076. headerCell.getWidth(), row.getHeight());
  42077. }
  42078. Component* TableListBox::getCellComponent (int columnId, int rowNumber) const
  42079. {
  42080. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (rowNumber));
  42081. return rowComp != 0 ? rowComp->findChildComponentForColumn (columnId) : 0;
  42082. }
  42083. void TableListBox::scrollToEnsureColumnIsOnscreen (const int columnId)
  42084. {
  42085. ScrollBar* const scrollbar = getHorizontalScrollBar();
  42086. if (scrollbar != 0)
  42087. {
  42088. const Rectangle<int> pos (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  42089. double x = scrollbar->getCurrentRangeStart();
  42090. const double w = scrollbar->getCurrentRangeSize();
  42091. if (pos.getX() < x)
  42092. x = pos.getX();
  42093. else if (pos.getRight() > x + w)
  42094. x += jmax (0.0, pos.getRight() - (x + w));
  42095. scrollbar->setCurrentRangeStart (x);
  42096. }
  42097. }
  42098. int TableListBox::getNumRows()
  42099. {
  42100. return model != 0 ? model->getNumRows() : 0;
  42101. }
  42102. void TableListBox::paintListBoxItem (int, Graphics&, int, int, bool)
  42103. {
  42104. }
  42105. Component* TableListBox::refreshComponentForRow (int rowNumber, bool isRowSelected_, Component* existingComponentToUpdate)
  42106. {
  42107. if (existingComponentToUpdate == 0)
  42108. existingComponentToUpdate = new TableListRowComp (*this);
  42109. static_cast <TableListRowComp*> (existingComponentToUpdate)->update (rowNumber, isRowSelected_);
  42110. return existingComponentToUpdate;
  42111. }
  42112. void TableListBox::selectedRowsChanged (int row)
  42113. {
  42114. if (model != 0)
  42115. model->selectedRowsChanged (row);
  42116. }
  42117. void TableListBox::deleteKeyPressed (int row)
  42118. {
  42119. if (model != 0)
  42120. model->deleteKeyPressed (row);
  42121. }
  42122. void TableListBox::returnKeyPressed (int row)
  42123. {
  42124. if (model != 0)
  42125. model->returnKeyPressed (row);
  42126. }
  42127. void TableListBox::backgroundClicked()
  42128. {
  42129. if (model != 0)
  42130. model->backgroundClicked();
  42131. }
  42132. void TableListBox::listWasScrolled()
  42133. {
  42134. if (model != 0)
  42135. model->listWasScrolled();
  42136. }
  42137. void TableListBox::tableColumnsChanged (TableHeaderComponent*)
  42138. {
  42139. setMinimumContentWidth (header->getTotalWidth());
  42140. repaint();
  42141. updateColumnComponents();
  42142. }
  42143. void TableListBox::tableColumnsResized (TableHeaderComponent*)
  42144. {
  42145. setMinimumContentWidth (header->getTotalWidth());
  42146. repaint();
  42147. updateColumnComponents();
  42148. }
  42149. void TableListBox::tableSortOrderChanged (TableHeaderComponent*)
  42150. {
  42151. if (model != 0)
  42152. model->sortOrderChanged (header->getSortColumnId(),
  42153. header->isSortedForwards());
  42154. }
  42155. void TableListBox::tableColumnDraggingChanged (TableHeaderComponent*, int columnIdNowBeingDragged_)
  42156. {
  42157. columnIdNowBeingDragged = columnIdNowBeingDragged_;
  42158. repaint();
  42159. }
  42160. void TableListBox::resized()
  42161. {
  42162. ListBox::resized();
  42163. header->resizeAllColumnsToFit (getVisibleContentWidth());
  42164. setMinimumContentWidth (header->getTotalWidth());
  42165. }
  42166. void TableListBox::updateColumnComponents() const
  42167. {
  42168. const int firstRow = getRowContainingPosition (0, 0);
  42169. for (int i = firstRow + getNumRowsOnScreen() + 2; --i >= firstRow;)
  42170. {
  42171. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (i));
  42172. if (rowComp != 0)
  42173. rowComp->resized();
  42174. }
  42175. }
  42176. void TableListBoxModel::cellClicked (int, int, const MouseEvent&)
  42177. {
  42178. }
  42179. void TableListBoxModel::cellDoubleClicked (int, int, const MouseEvent&)
  42180. {
  42181. }
  42182. void TableListBoxModel::backgroundClicked()
  42183. {
  42184. }
  42185. void TableListBoxModel::sortOrderChanged (int, const bool)
  42186. {
  42187. }
  42188. int TableListBoxModel::getColumnAutoSizeWidth (int)
  42189. {
  42190. return 0;
  42191. }
  42192. void TableListBoxModel::selectedRowsChanged (int)
  42193. {
  42194. }
  42195. void TableListBoxModel::deleteKeyPressed (int)
  42196. {
  42197. }
  42198. void TableListBoxModel::returnKeyPressed (int)
  42199. {
  42200. }
  42201. void TableListBoxModel::listWasScrolled()
  42202. {
  42203. }
  42204. const String TableListBoxModel::getCellTooltip (int /*rowNumber*/, int /*columnId*/)
  42205. {
  42206. return String::empty;
  42207. }
  42208. const String TableListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  42209. {
  42210. return String::empty;
  42211. }
  42212. Component* TableListBoxModel::refreshComponentForCell (int, int, bool, Component* existingComponentToUpdate)
  42213. {
  42214. (void) existingComponentToUpdate;
  42215. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  42216. return 0;
  42217. }
  42218. END_JUCE_NAMESPACE
  42219. /*** End of inlined file: juce_TableListBox.cpp ***/
  42220. /*** Start of inlined file: juce_TextEditor.cpp ***/
  42221. BEGIN_JUCE_NAMESPACE
  42222. // a word or space that can't be broken down any further
  42223. struct TextAtom
  42224. {
  42225. String atomText;
  42226. float width;
  42227. int numChars;
  42228. bool isWhitespace() const { return CharacterFunctions::isWhitespace (atomText[0]); }
  42229. bool isNewLine() const { return atomText[0] == '\r' || atomText[0] == '\n'; }
  42230. const String getText (const juce_wchar passwordCharacter) const
  42231. {
  42232. if (passwordCharacter == 0)
  42233. return atomText;
  42234. else
  42235. return String::repeatedString (String::charToString (passwordCharacter),
  42236. atomText.length());
  42237. }
  42238. const String getTrimmedText (const juce_wchar passwordCharacter) const
  42239. {
  42240. if (passwordCharacter == 0)
  42241. return atomText.substring (0, numChars);
  42242. else if (isNewLine())
  42243. return String::empty;
  42244. else
  42245. return String::repeatedString (String::charToString (passwordCharacter), numChars);
  42246. }
  42247. };
  42248. // a run of text with a single font and colour
  42249. class TextEditor::UniformTextSection
  42250. {
  42251. public:
  42252. UniformTextSection (const String& text,
  42253. const Font& font_,
  42254. const Colour& colour_,
  42255. const juce_wchar passwordCharacter)
  42256. : font (font_),
  42257. colour (colour_)
  42258. {
  42259. initialiseAtoms (text, passwordCharacter);
  42260. }
  42261. UniformTextSection (const UniformTextSection& other)
  42262. : font (other.font),
  42263. colour (other.colour)
  42264. {
  42265. atoms.ensureStorageAllocated (other.atoms.size());
  42266. for (int i = 0; i < other.atoms.size(); ++i)
  42267. atoms.add (new TextAtom (*other.atoms.getUnchecked(i)));
  42268. }
  42269. ~UniformTextSection()
  42270. {
  42271. // (no need to delete the atoms, as they're explicitly deleted by the caller)
  42272. }
  42273. void clear()
  42274. {
  42275. for (int i = atoms.size(); --i >= 0;)
  42276. delete getAtom(i);
  42277. atoms.clear();
  42278. }
  42279. int getNumAtoms() const
  42280. {
  42281. return atoms.size();
  42282. }
  42283. TextAtom* getAtom (const int index) const throw()
  42284. {
  42285. return atoms.getUnchecked (index);
  42286. }
  42287. void append (const UniformTextSection& other, const juce_wchar passwordCharacter)
  42288. {
  42289. if (other.atoms.size() > 0)
  42290. {
  42291. TextAtom* const lastAtom = atoms.getLast();
  42292. int i = 0;
  42293. if (lastAtom != 0)
  42294. {
  42295. if (! CharacterFunctions::isWhitespace (lastAtom->atomText.getLastCharacter()))
  42296. {
  42297. TextAtom* const first = other.getAtom(0);
  42298. if (! CharacterFunctions::isWhitespace (first->atomText[0]))
  42299. {
  42300. lastAtom->atomText += first->atomText;
  42301. lastAtom->numChars = (uint16) (lastAtom->numChars + first->numChars);
  42302. lastAtom->width = font.getStringWidthFloat (lastAtom->getText (passwordCharacter));
  42303. delete first;
  42304. ++i;
  42305. }
  42306. }
  42307. }
  42308. atoms.ensureStorageAllocated (atoms.size() + other.atoms.size() - i);
  42309. while (i < other.atoms.size())
  42310. {
  42311. atoms.add (other.getAtom(i));
  42312. ++i;
  42313. }
  42314. }
  42315. }
  42316. UniformTextSection* split (const int indexToBreakAt,
  42317. const juce_wchar passwordCharacter)
  42318. {
  42319. UniformTextSection* const section2 = new UniformTextSection (String::empty,
  42320. font, colour,
  42321. passwordCharacter);
  42322. int index = 0;
  42323. for (int i = 0; i < atoms.size(); ++i)
  42324. {
  42325. TextAtom* const atom = getAtom(i);
  42326. const int nextIndex = index + atom->numChars;
  42327. if (index == indexToBreakAt)
  42328. {
  42329. int j;
  42330. for (j = i; j < atoms.size(); ++j)
  42331. section2->atoms.add (getAtom (j));
  42332. for (j = atoms.size(); --j >= i;)
  42333. atoms.remove (j);
  42334. break;
  42335. }
  42336. else if (indexToBreakAt >= index && indexToBreakAt < nextIndex)
  42337. {
  42338. TextAtom* const secondAtom = new TextAtom();
  42339. secondAtom->atomText = atom->atomText.substring (indexToBreakAt - index);
  42340. secondAtom->width = font.getStringWidthFloat (secondAtom->getText (passwordCharacter));
  42341. secondAtom->numChars = (uint16) secondAtom->atomText.length();
  42342. section2->atoms.add (secondAtom);
  42343. atom->atomText = atom->atomText.substring (0, indexToBreakAt - index);
  42344. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  42345. atom->numChars = (uint16) (indexToBreakAt - index);
  42346. int j;
  42347. for (j = i + 1; j < atoms.size(); ++j)
  42348. section2->atoms.add (getAtom (j));
  42349. for (j = atoms.size(); --j > i;)
  42350. atoms.remove (j);
  42351. break;
  42352. }
  42353. index = nextIndex;
  42354. }
  42355. return section2;
  42356. }
  42357. void appendAllText (String::Concatenator& concatenator) const
  42358. {
  42359. for (int i = 0; i < atoms.size(); ++i)
  42360. concatenator.append (getAtom(i)->atomText);
  42361. }
  42362. void appendSubstring (String::Concatenator& concatenator,
  42363. const Range<int>& range) const
  42364. {
  42365. int index = 0;
  42366. for (int i = 0; i < atoms.size(); ++i)
  42367. {
  42368. const TextAtom* const atom = getAtom (i);
  42369. const int nextIndex = index + atom->numChars;
  42370. if (range.getStart() < nextIndex)
  42371. {
  42372. if (range.getEnd() <= index)
  42373. break;
  42374. const Range<int> r ((range - index).getIntersectionWith (Range<int> (0, (int) atom->numChars)));
  42375. if (! r.isEmpty())
  42376. concatenator.append (atom->atomText.substring (r.getStart(), r.getEnd()));
  42377. }
  42378. index = nextIndex;
  42379. }
  42380. }
  42381. int getTotalLength() const
  42382. {
  42383. int total = 0;
  42384. for (int i = atoms.size(); --i >= 0;)
  42385. total += getAtom(i)->numChars;
  42386. return total;
  42387. }
  42388. void setFont (const Font& newFont,
  42389. const juce_wchar passwordCharacter)
  42390. {
  42391. if (font != newFont)
  42392. {
  42393. font = newFont;
  42394. for (int i = atoms.size(); --i >= 0;)
  42395. {
  42396. TextAtom* const atom = atoms.getUnchecked(i);
  42397. atom->width = newFont.getStringWidthFloat (atom->getText (passwordCharacter));
  42398. }
  42399. }
  42400. }
  42401. juce_UseDebuggingNewOperator
  42402. Font font;
  42403. Colour colour;
  42404. private:
  42405. Array <TextAtom*> atoms;
  42406. void initialiseAtoms (const String& textToParse,
  42407. const juce_wchar passwordCharacter)
  42408. {
  42409. int i = 0;
  42410. const int len = textToParse.length();
  42411. const juce_wchar* const text = textToParse;
  42412. while (i < len)
  42413. {
  42414. int start = i;
  42415. // create a whitespace atom unless it starts with non-ws
  42416. if (CharacterFunctions::isWhitespace (text[i])
  42417. && text[i] != '\r'
  42418. && text[i] != '\n')
  42419. {
  42420. while (i < len
  42421. && CharacterFunctions::isWhitespace (text[i])
  42422. && text[i] != '\r'
  42423. && text[i] != '\n')
  42424. {
  42425. ++i;
  42426. }
  42427. }
  42428. else
  42429. {
  42430. if (text[i] == '\r')
  42431. {
  42432. ++i;
  42433. if ((i < len) && (text[i] == '\n'))
  42434. {
  42435. ++start;
  42436. ++i;
  42437. }
  42438. }
  42439. else if (text[i] == '\n')
  42440. {
  42441. ++i;
  42442. }
  42443. else
  42444. {
  42445. while ((i < len) && ! CharacterFunctions::isWhitespace (text[i]))
  42446. ++i;
  42447. }
  42448. }
  42449. TextAtom* const atom = new TextAtom();
  42450. atom->atomText = String (text + start, i - start);
  42451. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  42452. atom->numChars = (uint16) (i - start);
  42453. atoms.add (atom);
  42454. }
  42455. }
  42456. UniformTextSection& operator= (const UniformTextSection& other);
  42457. };
  42458. class TextEditor::Iterator
  42459. {
  42460. public:
  42461. Iterator (const Array <UniformTextSection*>& sections_,
  42462. const float wordWrapWidth_,
  42463. const juce_wchar passwordCharacter_)
  42464. : indexInText (0),
  42465. lineY (0),
  42466. lineHeight (0),
  42467. maxDescent (0),
  42468. atomX (0),
  42469. atomRight (0),
  42470. atom (0),
  42471. currentSection (0),
  42472. sections (sections_),
  42473. sectionIndex (0),
  42474. atomIndex (0),
  42475. wordWrapWidth (wordWrapWidth_),
  42476. passwordCharacter (passwordCharacter_)
  42477. {
  42478. jassert (wordWrapWidth_ > 0);
  42479. if (sections.size() > 0)
  42480. {
  42481. currentSection = sections.getUnchecked (sectionIndex);
  42482. if (currentSection != 0)
  42483. beginNewLine();
  42484. }
  42485. }
  42486. Iterator (const Iterator& other)
  42487. : indexInText (other.indexInText),
  42488. lineY (other.lineY),
  42489. lineHeight (other.lineHeight),
  42490. maxDescent (other.maxDescent),
  42491. atomX (other.atomX),
  42492. atomRight (other.atomRight),
  42493. atom (other.atom),
  42494. currentSection (other.currentSection),
  42495. sections (other.sections),
  42496. sectionIndex (other.sectionIndex),
  42497. atomIndex (other.atomIndex),
  42498. wordWrapWidth (other.wordWrapWidth),
  42499. passwordCharacter (other.passwordCharacter),
  42500. tempAtom (other.tempAtom)
  42501. {
  42502. }
  42503. ~Iterator()
  42504. {
  42505. }
  42506. bool next()
  42507. {
  42508. if (atom == &tempAtom)
  42509. {
  42510. const int numRemaining = tempAtom.atomText.length() - tempAtom.numChars;
  42511. if (numRemaining > 0)
  42512. {
  42513. tempAtom.atomText = tempAtom.atomText.substring (tempAtom.numChars);
  42514. atomX = 0;
  42515. if (tempAtom.numChars > 0)
  42516. lineY += lineHeight;
  42517. indexInText += tempAtom.numChars;
  42518. GlyphArrangement g;
  42519. g.addLineOfText (currentSection->font, atom->getText (passwordCharacter), 0.0f, 0.0f);
  42520. int split;
  42521. for (split = 0; split < g.getNumGlyphs(); ++split)
  42522. if (shouldWrap (g.getGlyph (split).getRight()))
  42523. break;
  42524. if (split > 0 && split <= numRemaining)
  42525. {
  42526. tempAtom.numChars = (uint16) split;
  42527. tempAtom.width = g.getGlyph (split - 1).getRight();
  42528. atomRight = atomX + tempAtom.width;
  42529. return true;
  42530. }
  42531. }
  42532. }
  42533. bool forceNewLine = false;
  42534. if (sectionIndex >= sections.size())
  42535. {
  42536. moveToEndOfLastAtom();
  42537. return false;
  42538. }
  42539. else if (atomIndex >= currentSection->getNumAtoms() - 1)
  42540. {
  42541. if (atomIndex >= currentSection->getNumAtoms())
  42542. {
  42543. if (++sectionIndex >= sections.size())
  42544. {
  42545. moveToEndOfLastAtom();
  42546. return false;
  42547. }
  42548. atomIndex = 0;
  42549. currentSection = sections.getUnchecked (sectionIndex);
  42550. }
  42551. else
  42552. {
  42553. const TextAtom* const lastAtom = currentSection->getAtom (atomIndex);
  42554. if (! lastAtom->isWhitespace())
  42555. {
  42556. // handle the case where the last atom in a section is actually part of the same
  42557. // word as the first atom of the next section...
  42558. float right = atomRight + lastAtom->width;
  42559. float lineHeight2 = lineHeight;
  42560. float maxDescent2 = maxDescent;
  42561. for (int section = sectionIndex + 1; section < sections.size(); ++section)
  42562. {
  42563. const UniformTextSection* const s = sections.getUnchecked (section);
  42564. if (s->getNumAtoms() == 0)
  42565. break;
  42566. const TextAtom* const nextAtom = s->getAtom (0);
  42567. if (nextAtom->isWhitespace())
  42568. break;
  42569. right += nextAtom->width;
  42570. lineHeight2 = jmax (lineHeight2, s->font.getHeight());
  42571. maxDescent2 = jmax (maxDescent2, s->font.getDescent());
  42572. if (shouldWrap (right))
  42573. {
  42574. lineHeight = lineHeight2;
  42575. maxDescent = maxDescent2;
  42576. forceNewLine = true;
  42577. break;
  42578. }
  42579. if (s->getNumAtoms() > 1)
  42580. break;
  42581. }
  42582. }
  42583. }
  42584. }
  42585. if (atom != 0)
  42586. {
  42587. atomX = atomRight;
  42588. indexInText += atom->numChars;
  42589. if (atom->isNewLine())
  42590. beginNewLine();
  42591. }
  42592. atom = currentSection->getAtom (atomIndex);
  42593. atomRight = atomX + atom->width;
  42594. ++atomIndex;
  42595. if (shouldWrap (atomRight) || forceNewLine)
  42596. {
  42597. if (atom->isWhitespace())
  42598. {
  42599. // leave whitespace at the end of a line, but truncate it to avoid scrolling
  42600. atomRight = jmin (atomRight, wordWrapWidth);
  42601. }
  42602. else
  42603. {
  42604. atomRight = atom->width;
  42605. if (shouldWrap (atomRight)) // atom too big to fit on a line, so break it up..
  42606. {
  42607. tempAtom = *atom;
  42608. tempAtom.width = 0;
  42609. tempAtom.numChars = 0;
  42610. atom = &tempAtom;
  42611. if (atomX > 0)
  42612. beginNewLine();
  42613. return next();
  42614. }
  42615. beginNewLine();
  42616. return true;
  42617. }
  42618. }
  42619. return true;
  42620. }
  42621. void beginNewLine()
  42622. {
  42623. atomX = 0;
  42624. lineY += lineHeight;
  42625. int tempSectionIndex = sectionIndex;
  42626. int tempAtomIndex = atomIndex;
  42627. const UniformTextSection* section = sections.getUnchecked (tempSectionIndex);
  42628. lineHeight = section->font.getHeight();
  42629. maxDescent = section->font.getDescent();
  42630. float x = (atom != 0) ? atom->width : 0;
  42631. while (! shouldWrap (x))
  42632. {
  42633. if (tempSectionIndex >= sections.size())
  42634. break;
  42635. bool checkSize = false;
  42636. if (tempAtomIndex >= section->getNumAtoms())
  42637. {
  42638. if (++tempSectionIndex >= sections.size())
  42639. break;
  42640. tempAtomIndex = 0;
  42641. section = sections.getUnchecked (tempSectionIndex);
  42642. checkSize = true;
  42643. }
  42644. const TextAtom* const nextAtom = section->getAtom (tempAtomIndex);
  42645. if (nextAtom == 0)
  42646. break;
  42647. x += nextAtom->width;
  42648. if (shouldWrap (x) || nextAtom->isNewLine())
  42649. break;
  42650. if (checkSize)
  42651. {
  42652. lineHeight = jmax (lineHeight, section->font.getHeight());
  42653. maxDescent = jmax (maxDescent, section->font.getDescent());
  42654. }
  42655. ++tempAtomIndex;
  42656. }
  42657. }
  42658. void draw (Graphics& g, const UniformTextSection*& lastSection) const
  42659. {
  42660. if (passwordCharacter != 0 || ! atom->isWhitespace())
  42661. {
  42662. if (lastSection != currentSection)
  42663. {
  42664. lastSection = currentSection;
  42665. g.setColour (currentSection->colour);
  42666. g.setFont (currentSection->font);
  42667. }
  42668. jassert (atom->getTrimmedText (passwordCharacter).isNotEmpty());
  42669. GlyphArrangement ga;
  42670. ga.addLineOfText (currentSection->font,
  42671. atom->getTrimmedText (passwordCharacter),
  42672. atomX,
  42673. (float) roundToInt (lineY + lineHeight - maxDescent));
  42674. ga.draw (g);
  42675. }
  42676. }
  42677. void drawSelection (Graphics& g,
  42678. const Range<int>& selection) const
  42679. {
  42680. const int startX = roundToInt (indexToX (selection.getStart()));
  42681. const int endX = roundToInt (indexToX (selection.getEnd()));
  42682. const int y = roundToInt (lineY);
  42683. const int nextY = roundToInt (lineY + lineHeight);
  42684. g.fillRect (startX, y, endX - startX, nextY - y);
  42685. }
  42686. void drawSelectedText (Graphics& g,
  42687. const Range<int>& selection,
  42688. const Colour& selectedTextColour) const
  42689. {
  42690. if (passwordCharacter != 0 || ! atom->isWhitespace())
  42691. {
  42692. GlyphArrangement ga;
  42693. ga.addLineOfText (currentSection->font,
  42694. atom->getTrimmedText (passwordCharacter),
  42695. atomX,
  42696. (float) roundToInt (lineY + lineHeight - maxDescent));
  42697. if (selection.getEnd() < indexInText + atom->numChars)
  42698. {
  42699. GlyphArrangement ga2 (ga);
  42700. ga2.removeRangeOfGlyphs (0, selection.getEnd() - indexInText);
  42701. ga.removeRangeOfGlyphs (selection.getEnd() - indexInText, -1);
  42702. g.setColour (currentSection->colour);
  42703. ga2.draw (g);
  42704. }
  42705. if (selection.getStart() > indexInText)
  42706. {
  42707. GlyphArrangement ga2 (ga);
  42708. ga2.removeRangeOfGlyphs (selection.getStart() - indexInText, -1);
  42709. ga.removeRangeOfGlyphs (0, selection.getStart() - indexInText);
  42710. g.setColour (currentSection->colour);
  42711. ga2.draw (g);
  42712. }
  42713. g.setColour (selectedTextColour);
  42714. ga.draw (g);
  42715. }
  42716. }
  42717. float indexToX (const int indexToFind) const
  42718. {
  42719. if (indexToFind <= indexInText)
  42720. return atomX;
  42721. if (indexToFind >= indexInText + atom->numChars)
  42722. return atomRight;
  42723. GlyphArrangement g;
  42724. g.addLineOfText (currentSection->font,
  42725. atom->getText (passwordCharacter),
  42726. atomX, 0.0f);
  42727. if (indexToFind - indexInText >= g.getNumGlyphs())
  42728. return atomRight;
  42729. return jmin (atomRight, g.getGlyph (indexToFind - indexInText).getLeft());
  42730. }
  42731. int xToIndex (const float xToFind) const
  42732. {
  42733. if (xToFind <= atomX || atom->isNewLine())
  42734. return indexInText;
  42735. if (xToFind >= atomRight)
  42736. return indexInText + atom->numChars;
  42737. GlyphArrangement g;
  42738. g.addLineOfText (currentSection->font,
  42739. atom->getText (passwordCharacter),
  42740. atomX, 0.0f);
  42741. int j;
  42742. for (j = 0; j < g.getNumGlyphs(); ++j)
  42743. if ((g.getGlyph(j).getLeft() + g.getGlyph(j).getRight()) / 2 > xToFind)
  42744. break;
  42745. return indexInText + j;
  42746. }
  42747. bool getCharPosition (const int index, float& cx, float& cy, float& lineHeight_)
  42748. {
  42749. while (next())
  42750. {
  42751. if (indexInText + atom->numChars > index)
  42752. {
  42753. cx = indexToX (index);
  42754. cy = lineY;
  42755. lineHeight_ = lineHeight;
  42756. return true;
  42757. }
  42758. }
  42759. cx = atomX;
  42760. cy = lineY;
  42761. lineHeight_ = lineHeight;
  42762. return false;
  42763. }
  42764. juce_UseDebuggingNewOperator
  42765. int indexInText;
  42766. float lineY, lineHeight, maxDescent;
  42767. float atomX, atomRight;
  42768. const TextAtom* atom;
  42769. const UniformTextSection* currentSection;
  42770. private:
  42771. const Array <UniformTextSection*>& sections;
  42772. int sectionIndex, atomIndex;
  42773. const float wordWrapWidth;
  42774. const juce_wchar passwordCharacter;
  42775. TextAtom tempAtom;
  42776. Iterator& operator= (const Iterator&);
  42777. void moveToEndOfLastAtom()
  42778. {
  42779. if (atom != 0)
  42780. {
  42781. atomX = atomRight;
  42782. if (atom->isNewLine())
  42783. {
  42784. atomX = 0.0f;
  42785. lineY += lineHeight;
  42786. }
  42787. }
  42788. }
  42789. bool shouldWrap (const float x) const
  42790. {
  42791. return (x - 0.0001f) >= wordWrapWidth;
  42792. }
  42793. };
  42794. class TextEditor::InsertAction : public UndoableAction
  42795. {
  42796. TextEditor& owner;
  42797. const String text;
  42798. const int insertIndex, oldCaretPos, newCaretPos;
  42799. const Font font;
  42800. const Colour colour;
  42801. InsertAction (const InsertAction&);
  42802. InsertAction& operator= (const InsertAction&);
  42803. public:
  42804. InsertAction (TextEditor& owner_,
  42805. const String& text_,
  42806. const int insertIndex_,
  42807. const Font& font_,
  42808. const Colour& colour_,
  42809. const int oldCaretPos_,
  42810. const int newCaretPos_)
  42811. : owner (owner_),
  42812. text (text_),
  42813. insertIndex (insertIndex_),
  42814. oldCaretPos (oldCaretPos_),
  42815. newCaretPos (newCaretPos_),
  42816. font (font_),
  42817. colour (colour_)
  42818. {
  42819. }
  42820. ~InsertAction()
  42821. {
  42822. }
  42823. bool perform()
  42824. {
  42825. owner.insert (text, insertIndex, font, colour, 0, newCaretPos);
  42826. return true;
  42827. }
  42828. bool undo()
  42829. {
  42830. owner.remove (Range<int> (insertIndex, insertIndex + text.length()), 0, oldCaretPos);
  42831. return true;
  42832. }
  42833. int getSizeInUnits()
  42834. {
  42835. return text.length() + 16;
  42836. }
  42837. };
  42838. class TextEditor::RemoveAction : public UndoableAction
  42839. {
  42840. TextEditor& owner;
  42841. const Range<int> range;
  42842. const int oldCaretPos, newCaretPos;
  42843. Array <UniformTextSection*> removedSections;
  42844. RemoveAction (const RemoveAction&);
  42845. RemoveAction& operator= (const RemoveAction&);
  42846. public:
  42847. RemoveAction (TextEditor& owner_,
  42848. const Range<int> range_,
  42849. const int oldCaretPos_,
  42850. const int newCaretPos_,
  42851. const Array <UniformTextSection*>& removedSections_)
  42852. : owner (owner_),
  42853. range (range_),
  42854. oldCaretPos (oldCaretPos_),
  42855. newCaretPos (newCaretPos_),
  42856. removedSections (removedSections_)
  42857. {
  42858. }
  42859. ~RemoveAction()
  42860. {
  42861. for (int i = removedSections.size(); --i >= 0;)
  42862. {
  42863. UniformTextSection* const section = removedSections.getUnchecked (i);
  42864. section->clear();
  42865. delete section;
  42866. }
  42867. }
  42868. bool perform()
  42869. {
  42870. owner.remove (range, 0, newCaretPos);
  42871. return true;
  42872. }
  42873. bool undo()
  42874. {
  42875. owner.reinsert (range.getStart(), removedSections);
  42876. owner.moveCursorTo (oldCaretPos, false);
  42877. return true;
  42878. }
  42879. int getSizeInUnits()
  42880. {
  42881. int n = 0;
  42882. for (int i = removedSections.size(); --i >= 0;)
  42883. n += removedSections.getUnchecked (i)->getTotalLength();
  42884. return n + 16;
  42885. }
  42886. };
  42887. class TextEditor::TextHolderComponent : public Component,
  42888. public Timer,
  42889. public Value::Listener
  42890. {
  42891. public:
  42892. TextHolderComponent (TextEditor& owner_)
  42893. : owner (owner_)
  42894. {
  42895. setWantsKeyboardFocus (false);
  42896. setInterceptsMouseClicks (false, true);
  42897. owner.getTextValue().addListener (this);
  42898. }
  42899. ~TextHolderComponent()
  42900. {
  42901. owner.getTextValue().removeListener (this);
  42902. }
  42903. void paint (Graphics& g)
  42904. {
  42905. owner.drawContent (g);
  42906. }
  42907. void timerCallback()
  42908. {
  42909. owner.timerCallbackInt();
  42910. }
  42911. const MouseCursor getMouseCursor()
  42912. {
  42913. return owner.getMouseCursor();
  42914. }
  42915. void valueChanged (Value&)
  42916. {
  42917. owner.textWasChangedByValue();
  42918. }
  42919. private:
  42920. TextEditor& owner;
  42921. TextHolderComponent (const TextHolderComponent&);
  42922. TextHolderComponent& operator= (const TextHolderComponent&);
  42923. };
  42924. class TextEditorViewport : public Viewport
  42925. {
  42926. public:
  42927. TextEditorViewport (TextEditor* const owner_)
  42928. : owner (owner_), lastWordWrapWidth (0), rentrant (false)
  42929. {
  42930. }
  42931. ~TextEditorViewport()
  42932. {
  42933. }
  42934. void visibleAreaChanged (int, int, int, int)
  42935. {
  42936. if (! rentrant) // it's rare, but possible to get into a feedback loop as the viewport's scrollbars
  42937. // appear and disappear, causing the wrap width to change.
  42938. {
  42939. const float wordWrapWidth = owner->getWordWrapWidth();
  42940. if (wordWrapWidth != lastWordWrapWidth)
  42941. {
  42942. lastWordWrapWidth = wordWrapWidth;
  42943. rentrant = true;
  42944. owner->updateTextHolderSize();
  42945. rentrant = false;
  42946. }
  42947. }
  42948. }
  42949. private:
  42950. TextEditor* const owner;
  42951. float lastWordWrapWidth;
  42952. bool rentrant;
  42953. TextEditorViewport (const TextEditorViewport&);
  42954. TextEditorViewport& operator= (const TextEditorViewport&);
  42955. };
  42956. namespace TextEditorDefs
  42957. {
  42958. const int flashSpeedIntervalMs = 380;
  42959. const int textChangeMessageId = 0x10003001;
  42960. const int returnKeyMessageId = 0x10003002;
  42961. const int escapeKeyMessageId = 0x10003003;
  42962. const int focusLossMessageId = 0x10003004;
  42963. const int maxActionsPerTransaction = 100;
  42964. static int getCharacterCategory (const juce_wchar character)
  42965. {
  42966. return CharacterFunctions::isLetterOrDigit (character)
  42967. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  42968. }
  42969. }
  42970. TextEditor::TextEditor (const String& name,
  42971. const juce_wchar passwordCharacter_)
  42972. : Component (name),
  42973. borderSize (1, 1, 1, 3),
  42974. readOnly (false),
  42975. multiline (false),
  42976. wordWrap (false),
  42977. returnKeyStartsNewLine (false),
  42978. caretVisible (true),
  42979. popupMenuEnabled (true),
  42980. selectAllTextWhenFocused (false),
  42981. scrollbarVisible (true),
  42982. wasFocused (false),
  42983. caretFlashState (true),
  42984. keepCursorOnScreen (true),
  42985. tabKeyUsed (false),
  42986. menuActive (false),
  42987. valueTextNeedsUpdating (false),
  42988. cursorX (0),
  42989. cursorY (0),
  42990. cursorHeight (0),
  42991. maxTextLength (0),
  42992. leftIndent (4),
  42993. topIndent (4),
  42994. lastTransactionTime (0),
  42995. currentFont (14.0f),
  42996. totalNumChars (0),
  42997. caretPosition (0),
  42998. passwordCharacter (passwordCharacter_),
  42999. dragType (notDragging)
  43000. {
  43001. setOpaque (true);
  43002. addAndMakeVisible (viewport = new TextEditorViewport (this));
  43003. viewport->setViewedComponent (textHolder = new TextHolderComponent (*this));
  43004. viewport->setWantsKeyboardFocus (false);
  43005. viewport->setScrollBarsShown (false, false);
  43006. setMouseCursor (MouseCursor::IBeamCursor);
  43007. setWantsKeyboardFocus (true);
  43008. }
  43009. TextEditor::~TextEditor()
  43010. {
  43011. textValue.referTo (Value());
  43012. clearInternal (0);
  43013. viewport = 0;
  43014. textHolder = 0;
  43015. }
  43016. void TextEditor::newTransaction()
  43017. {
  43018. lastTransactionTime = Time::getApproximateMillisecondCounter();
  43019. undoManager.beginNewTransaction();
  43020. }
  43021. void TextEditor::doUndoRedo (const bool isRedo)
  43022. {
  43023. if (! isReadOnly())
  43024. {
  43025. if (isRedo ? undoManager.redo()
  43026. : undoManager.undo())
  43027. {
  43028. scrollToMakeSureCursorIsVisible();
  43029. repaint();
  43030. textChanged();
  43031. }
  43032. }
  43033. }
  43034. void TextEditor::setMultiLine (const bool shouldBeMultiLine,
  43035. const bool shouldWordWrap)
  43036. {
  43037. if (multiline != shouldBeMultiLine
  43038. || wordWrap != (shouldWordWrap && shouldBeMultiLine))
  43039. {
  43040. multiline = shouldBeMultiLine;
  43041. wordWrap = shouldWordWrap && shouldBeMultiLine;
  43042. viewport->setScrollBarsShown (scrollbarVisible && multiline,
  43043. scrollbarVisible && multiline);
  43044. viewport->setViewPosition (0, 0);
  43045. resized();
  43046. scrollToMakeSureCursorIsVisible();
  43047. }
  43048. }
  43049. bool TextEditor::isMultiLine() const
  43050. {
  43051. return multiline;
  43052. }
  43053. void TextEditor::setScrollbarsShown (bool shown)
  43054. {
  43055. if (scrollbarVisible != shown)
  43056. {
  43057. scrollbarVisible = shown;
  43058. shown = shown && isMultiLine();
  43059. viewport->setScrollBarsShown (shown, shown);
  43060. }
  43061. }
  43062. void TextEditor::setReadOnly (const bool shouldBeReadOnly)
  43063. {
  43064. if (readOnly != shouldBeReadOnly)
  43065. {
  43066. readOnly = shouldBeReadOnly;
  43067. enablementChanged();
  43068. }
  43069. }
  43070. bool TextEditor::isReadOnly() const
  43071. {
  43072. return readOnly || ! isEnabled();
  43073. }
  43074. bool TextEditor::isTextInputActive() const
  43075. {
  43076. return ! isReadOnly();
  43077. }
  43078. void TextEditor::setReturnKeyStartsNewLine (const bool shouldStartNewLine)
  43079. {
  43080. returnKeyStartsNewLine = shouldStartNewLine;
  43081. }
  43082. void TextEditor::setTabKeyUsedAsCharacter (const bool shouldTabKeyBeUsed)
  43083. {
  43084. tabKeyUsed = shouldTabKeyBeUsed;
  43085. }
  43086. void TextEditor::setPopupMenuEnabled (const bool b)
  43087. {
  43088. popupMenuEnabled = b;
  43089. }
  43090. void TextEditor::setSelectAllWhenFocused (const bool b)
  43091. {
  43092. selectAllTextWhenFocused = b;
  43093. }
  43094. const Font TextEditor::getFont() const
  43095. {
  43096. return currentFont;
  43097. }
  43098. void TextEditor::setFont (const Font& newFont)
  43099. {
  43100. currentFont = newFont;
  43101. scrollToMakeSureCursorIsVisible();
  43102. }
  43103. void TextEditor::applyFontToAllText (const Font& newFont)
  43104. {
  43105. currentFont = newFont;
  43106. const Colour overallColour (findColour (textColourId));
  43107. for (int i = sections.size(); --i >= 0;)
  43108. {
  43109. UniformTextSection* const uts = sections.getUnchecked (i);
  43110. uts->setFont (newFont, passwordCharacter);
  43111. uts->colour = overallColour;
  43112. }
  43113. coalesceSimilarSections();
  43114. updateTextHolderSize();
  43115. scrollToMakeSureCursorIsVisible();
  43116. repaint();
  43117. }
  43118. void TextEditor::colourChanged()
  43119. {
  43120. setOpaque (findColour (backgroundColourId).isOpaque());
  43121. repaint();
  43122. }
  43123. void TextEditor::setCaretVisible (const bool shouldCaretBeVisible)
  43124. {
  43125. caretVisible = shouldCaretBeVisible;
  43126. if (shouldCaretBeVisible)
  43127. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43128. setMouseCursor (shouldCaretBeVisible ? MouseCursor::IBeamCursor
  43129. : MouseCursor::NormalCursor);
  43130. }
  43131. void TextEditor::setInputRestrictions (const int maxLen,
  43132. const String& chars)
  43133. {
  43134. maxTextLength = jmax (0, maxLen);
  43135. allowedCharacters = chars;
  43136. }
  43137. void TextEditor::setTextToShowWhenEmpty (const String& text, const Colour& colourToUse)
  43138. {
  43139. textToShowWhenEmpty = text;
  43140. colourForTextWhenEmpty = colourToUse;
  43141. }
  43142. void TextEditor::setPasswordCharacter (const juce_wchar newPasswordCharacter)
  43143. {
  43144. if (passwordCharacter != newPasswordCharacter)
  43145. {
  43146. passwordCharacter = newPasswordCharacter;
  43147. resized();
  43148. repaint();
  43149. }
  43150. }
  43151. void TextEditor::setScrollBarThickness (const int newThicknessPixels)
  43152. {
  43153. viewport->setScrollBarThickness (newThicknessPixels);
  43154. }
  43155. void TextEditor::setScrollBarButtonVisibility (const bool buttonsVisible)
  43156. {
  43157. viewport->setScrollBarButtonVisibility (buttonsVisible);
  43158. }
  43159. void TextEditor::clear()
  43160. {
  43161. clearInternal (0);
  43162. updateTextHolderSize();
  43163. undoManager.clearUndoHistory();
  43164. }
  43165. void TextEditor::setText (const String& newText,
  43166. const bool sendTextChangeMessage)
  43167. {
  43168. const int newLength = newText.length();
  43169. if (newLength != getTotalNumChars() || getText() != newText)
  43170. {
  43171. const int oldCursorPos = caretPosition;
  43172. const bool cursorWasAtEnd = oldCursorPos >= getTotalNumChars();
  43173. clearInternal (0);
  43174. insert (newText, 0, currentFont, findColour (textColourId), 0, caretPosition);
  43175. // if you're adding text with line-feeds to a single-line text editor, it
  43176. // ain't gonna look right!
  43177. jassert (multiline || ! newText.containsAnyOf ("\r\n"));
  43178. if (cursorWasAtEnd && ! isMultiLine())
  43179. moveCursorTo (getTotalNumChars(), false);
  43180. else
  43181. moveCursorTo (oldCursorPos, false);
  43182. if (sendTextChangeMessage)
  43183. textChanged();
  43184. updateTextHolderSize();
  43185. scrollToMakeSureCursorIsVisible();
  43186. undoManager.clearUndoHistory();
  43187. repaint();
  43188. }
  43189. }
  43190. Value& TextEditor::getTextValue()
  43191. {
  43192. if (valueTextNeedsUpdating)
  43193. {
  43194. valueTextNeedsUpdating = false;
  43195. textValue = getText();
  43196. }
  43197. return textValue;
  43198. }
  43199. void TextEditor::textWasChangedByValue()
  43200. {
  43201. if (textValue.getValueSource().getReferenceCount() > 1)
  43202. setText (textValue.getValue());
  43203. }
  43204. void TextEditor::textChanged()
  43205. {
  43206. updateTextHolderSize();
  43207. postCommandMessage (TextEditorDefs::textChangeMessageId);
  43208. if (textValue.getValueSource().getReferenceCount() > 1)
  43209. {
  43210. valueTextNeedsUpdating = false;
  43211. textValue = getText();
  43212. }
  43213. }
  43214. void TextEditor::returnPressed()
  43215. {
  43216. postCommandMessage (TextEditorDefs::returnKeyMessageId);
  43217. }
  43218. void TextEditor::escapePressed()
  43219. {
  43220. postCommandMessage (TextEditorDefs::escapeKeyMessageId);
  43221. }
  43222. void TextEditor::addListener (Listener* const newListener)
  43223. {
  43224. listeners.add (newListener);
  43225. }
  43226. void TextEditor::removeListener (Listener* const listenerToRemove)
  43227. {
  43228. listeners.remove (listenerToRemove);
  43229. }
  43230. void TextEditor::timerCallbackInt()
  43231. {
  43232. const bool newState = (! caretFlashState) && ! isCurrentlyBlockedByAnotherModalComponent();
  43233. if (caretFlashState != newState)
  43234. {
  43235. caretFlashState = newState;
  43236. if (caretFlashState)
  43237. wasFocused = true;
  43238. if (caretVisible
  43239. && hasKeyboardFocus (false)
  43240. && ! isReadOnly())
  43241. {
  43242. repaintCaret();
  43243. }
  43244. }
  43245. const unsigned int now = Time::getApproximateMillisecondCounter();
  43246. if (now > lastTransactionTime + 200)
  43247. newTransaction();
  43248. }
  43249. void TextEditor::repaintCaret()
  43250. {
  43251. if (! findColour (caretColourId).isTransparent())
  43252. repaint (borderSize.getLeft() + textHolder->getX() + leftIndent + roundToInt (cursorX) - 1,
  43253. borderSize.getTop() + textHolder->getY() + topIndent + roundToInt (cursorY) - 1,
  43254. 4,
  43255. roundToInt (cursorHeight) + 2);
  43256. }
  43257. void TextEditor::repaintText (const Range<int>& range)
  43258. {
  43259. if (! range.isEmpty())
  43260. {
  43261. float x = 0, y = 0, lh = currentFont.getHeight();
  43262. const float wordWrapWidth = getWordWrapWidth();
  43263. if (wordWrapWidth > 0)
  43264. {
  43265. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43266. i.getCharPosition (range.getStart(), x, y, lh);
  43267. const int y1 = (int) y;
  43268. int y2;
  43269. if (range.getEnd() >= getTotalNumChars())
  43270. {
  43271. y2 = textHolder->getHeight();
  43272. }
  43273. else
  43274. {
  43275. i.getCharPosition (range.getEnd(), x, y, lh);
  43276. y2 = (int) (y + lh * 2.0f);
  43277. }
  43278. textHolder->repaint (0, y1, textHolder->getWidth(), y2 - y1);
  43279. }
  43280. }
  43281. }
  43282. void TextEditor::moveCaret (int newCaretPos)
  43283. {
  43284. if (newCaretPos < 0)
  43285. newCaretPos = 0;
  43286. else if (newCaretPos > getTotalNumChars())
  43287. newCaretPos = getTotalNumChars();
  43288. if (newCaretPos != getCaretPosition())
  43289. {
  43290. repaintCaret();
  43291. caretFlashState = true;
  43292. caretPosition = newCaretPos;
  43293. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43294. scrollToMakeSureCursorIsVisible();
  43295. repaintCaret();
  43296. }
  43297. }
  43298. void TextEditor::setCaretPosition (const int newIndex)
  43299. {
  43300. moveCursorTo (newIndex, false);
  43301. }
  43302. int TextEditor::getCaretPosition() const
  43303. {
  43304. return caretPosition;
  43305. }
  43306. void TextEditor::scrollEditorToPositionCaret (const int desiredCaretX,
  43307. const int desiredCaretY)
  43308. {
  43309. updateCaretPosition();
  43310. int vx = roundToInt (cursorX) - desiredCaretX;
  43311. int vy = roundToInt (cursorY) - desiredCaretY;
  43312. if (desiredCaretX < jmax (1, proportionOfWidth (0.05f)))
  43313. {
  43314. vx += desiredCaretX - proportionOfWidth (0.2f);
  43315. }
  43316. else if (desiredCaretX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  43317. {
  43318. vx += desiredCaretX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  43319. }
  43320. vx = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), vx);
  43321. if (! isMultiLine())
  43322. {
  43323. vy = viewport->getViewPositionY();
  43324. }
  43325. else
  43326. {
  43327. vy = jlimit (0, jmax (0, textHolder->getHeight() - viewport->getMaximumVisibleHeight()), vy);
  43328. const int curH = roundToInt (cursorHeight);
  43329. if (desiredCaretY < 0)
  43330. {
  43331. vy = jmax (0, desiredCaretY + vy);
  43332. }
  43333. else if (desiredCaretY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  43334. {
  43335. vy += desiredCaretY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  43336. }
  43337. }
  43338. viewport->setViewPosition (vx, vy);
  43339. }
  43340. const Rectangle<int> TextEditor::getCaretRectangle()
  43341. {
  43342. updateCaretPosition();
  43343. return Rectangle<int> (roundToInt (cursorX) - viewport->getX(),
  43344. roundToInt (cursorY) - viewport->getY(),
  43345. 1, roundToInt (cursorHeight));
  43346. }
  43347. float TextEditor::getWordWrapWidth() const
  43348. {
  43349. return (wordWrap) ? (float) (viewport->getMaximumVisibleWidth() - leftIndent - leftIndent / 2)
  43350. : 1.0e10f;
  43351. }
  43352. void TextEditor::updateTextHolderSize()
  43353. {
  43354. const float wordWrapWidth = getWordWrapWidth();
  43355. if (wordWrapWidth > 0)
  43356. {
  43357. float maxWidth = 0.0f;
  43358. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43359. while (i.next())
  43360. maxWidth = jmax (maxWidth, i.atomRight);
  43361. const int w = leftIndent + roundToInt (maxWidth);
  43362. const int h = topIndent + roundToInt (jmax (i.lineY + i.lineHeight,
  43363. currentFont.getHeight()));
  43364. textHolder->setSize (w + 1, h + 1);
  43365. }
  43366. }
  43367. int TextEditor::getTextWidth() const
  43368. {
  43369. return textHolder->getWidth();
  43370. }
  43371. int TextEditor::getTextHeight() const
  43372. {
  43373. return textHolder->getHeight();
  43374. }
  43375. void TextEditor::setIndents (const int newLeftIndent,
  43376. const int newTopIndent)
  43377. {
  43378. leftIndent = newLeftIndent;
  43379. topIndent = newTopIndent;
  43380. }
  43381. void TextEditor::setBorder (const BorderSize& border)
  43382. {
  43383. borderSize = border;
  43384. resized();
  43385. }
  43386. const BorderSize TextEditor::getBorder() const
  43387. {
  43388. return borderSize;
  43389. }
  43390. void TextEditor::setScrollToShowCursor (const bool shouldScrollToShowCursor)
  43391. {
  43392. keepCursorOnScreen = shouldScrollToShowCursor;
  43393. }
  43394. void TextEditor::updateCaretPosition()
  43395. {
  43396. cursorHeight = currentFont.getHeight(); // (in case the text is empty and the call below doesn't set this value)
  43397. getCharPosition (caretPosition, cursorX, cursorY, cursorHeight);
  43398. }
  43399. void TextEditor::scrollToMakeSureCursorIsVisible()
  43400. {
  43401. updateCaretPosition();
  43402. if (keepCursorOnScreen)
  43403. {
  43404. int x = viewport->getViewPositionX();
  43405. int y = viewport->getViewPositionY();
  43406. const int relativeCursorX = roundToInt (cursorX) - x;
  43407. const int relativeCursorY = roundToInt (cursorY) - y;
  43408. if (relativeCursorX < jmax (1, proportionOfWidth (0.05f)))
  43409. {
  43410. x += relativeCursorX - proportionOfWidth (0.2f);
  43411. }
  43412. else if (relativeCursorX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  43413. {
  43414. x += relativeCursorX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  43415. }
  43416. x = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), x);
  43417. if (! isMultiLine())
  43418. {
  43419. y = (getHeight() - textHolder->getHeight() - topIndent) / -2;
  43420. }
  43421. else
  43422. {
  43423. const int curH = roundToInt (cursorHeight);
  43424. if (relativeCursorY < 0)
  43425. {
  43426. y = jmax (0, relativeCursorY + y);
  43427. }
  43428. else if (relativeCursorY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  43429. {
  43430. y += relativeCursorY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  43431. }
  43432. }
  43433. viewport->setViewPosition (x, y);
  43434. }
  43435. }
  43436. void TextEditor::moveCursorTo (const int newPosition,
  43437. const bool isSelecting)
  43438. {
  43439. if (isSelecting)
  43440. {
  43441. moveCaret (newPosition);
  43442. const Range<int> oldSelection (selection);
  43443. if (dragType == notDragging)
  43444. {
  43445. if (abs (getCaretPosition() - selection.getStart()) < abs (getCaretPosition() - selection.getEnd()))
  43446. dragType = draggingSelectionStart;
  43447. else
  43448. dragType = draggingSelectionEnd;
  43449. }
  43450. if (dragType == draggingSelectionStart)
  43451. {
  43452. if (getCaretPosition() >= selection.getEnd())
  43453. dragType = draggingSelectionEnd;
  43454. selection = Range<int>::between (getCaretPosition(), selection.getEnd());
  43455. }
  43456. else
  43457. {
  43458. if (getCaretPosition() < selection.getStart())
  43459. dragType = draggingSelectionStart;
  43460. selection = Range<int>::between (getCaretPosition(), selection.getStart());
  43461. }
  43462. repaintText (selection.getUnionWith (oldSelection));
  43463. }
  43464. else
  43465. {
  43466. dragType = notDragging;
  43467. repaintText (selection);
  43468. moveCaret (newPosition);
  43469. selection = Range<int>::emptyRange (getCaretPosition());
  43470. }
  43471. }
  43472. int TextEditor::getTextIndexAt (const int x,
  43473. const int y)
  43474. {
  43475. return indexAtPosition ((float) (x + viewport->getViewPositionX() - leftIndent),
  43476. (float) (y + viewport->getViewPositionY() - topIndent));
  43477. }
  43478. void TextEditor::insertTextAtCaret (const String& newText_)
  43479. {
  43480. String newText (newText_);
  43481. if (allowedCharacters.isNotEmpty())
  43482. newText = newText.retainCharacters (allowedCharacters);
  43483. if ((! returnKeyStartsNewLine) && newText == "\n")
  43484. {
  43485. returnPressed();
  43486. return;
  43487. }
  43488. if (! isMultiLine())
  43489. newText = newText.replaceCharacters ("\r\n", " ");
  43490. else
  43491. newText = newText.replace ("\r\n", "\n");
  43492. const int newCaretPos = selection.getStart() + newText.length();
  43493. const int insertIndex = selection.getStart();
  43494. remove (selection, getUndoManager(),
  43495. newText.isNotEmpty() ? newCaretPos - 1 : newCaretPos);
  43496. if (maxTextLength > 0)
  43497. newText = newText.substring (0, maxTextLength - getTotalNumChars());
  43498. if (newText.isNotEmpty())
  43499. insert (newText,
  43500. insertIndex,
  43501. currentFont,
  43502. findColour (textColourId),
  43503. getUndoManager(),
  43504. newCaretPos);
  43505. textChanged();
  43506. }
  43507. void TextEditor::setHighlightedRegion (const Range<int>& newSelection)
  43508. {
  43509. moveCursorTo (newSelection.getStart(), false);
  43510. moveCursorTo (newSelection.getEnd(), true);
  43511. }
  43512. void TextEditor::copy()
  43513. {
  43514. if (passwordCharacter == 0)
  43515. {
  43516. const String selectedText (getHighlightedText());
  43517. if (selectedText.isNotEmpty())
  43518. SystemClipboard::copyTextToClipboard (selectedText);
  43519. }
  43520. }
  43521. void TextEditor::paste()
  43522. {
  43523. if (! isReadOnly())
  43524. {
  43525. const String clip (SystemClipboard::getTextFromClipboard());
  43526. if (clip.isNotEmpty())
  43527. insertTextAtCaret (clip);
  43528. }
  43529. }
  43530. void TextEditor::cut()
  43531. {
  43532. if (! isReadOnly())
  43533. {
  43534. moveCaret (selection.getEnd());
  43535. insertTextAtCaret (String::empty);
  43536. }
  43537. }
  43538. void TextEditor::drawContent (Graphics& g)
  43539. {
  43540. const float wordWrapWidth = getWordWrapWidth();
  43541. if (wordWrapWidth > 0)
  43542. {
  43543. g.setOrigin (leftIndent, topIndent);
  43544. const Rectangle<int> clip (g.getClipBounds());
  43545. Colour selectedTextColour;
  43546. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43547. while (i.lineY + 200.0 < clip.getY() && i.next())
  43548. {}
  43549. if (! selection.isEmpty())
  43550. {
  43551. g.setColour (findColour (highlightColourId)
  43552. .withMultipliedAlpha (hasKeyboardFocus (true) ? 1.0f : 0.5f));
  43553. selectedTextColour = findColour (highlightedTextColourId);
  43554. Iterator i2 (i);
  43555. while (i2.next() && i2.lineY < clip.getBottom())
  43556. {
  43557. if (i2.lineY + i2.lineHeight >= clip.getY()
  43558. && selection.intersects (Range<int> (i2.indexInText, i2.indexInText + i2.atom->numChars)))
  43559. {
  43560. i2.drawSelection (g, selection);
  43561. }
  43562. }
  43563. }
  43564. const UniformTextSection* lastSection = 0;
  43565. while (i.next() && i.lineY < clip.getBottom())
  43566. {
  43567. if (i.lineY + i.lineHeight >= clip.getY())
  43568. {
  43569. if (selection.intersects (Range<int> (i.indexInText, i.indexInText + i.atom->numChars)))
  43570. {
  43571. i.drawSelectedText (g, selection, selectedTextColour);
  43572. lastSection = 0;
  43573. }
  43574. else
  43575. {
  43576. i.draw (g, lastSection);
  43577. }
  43578. }
  43579. }
  43580. }
  43581. }
  43582. void TextEditor::paint (Graphics& g)
  43583. {
  43584. getLookAndFeel().fillTextEditorBackground (g, getWidth(), getHeight(), *this);
  43585. }
  43586. void TextEditor::paintOverChildren (Graphics& g)
  43587. {
  43588. if (caretFlashState
  43589. && hasKeyboardFocus (false)
  43590. && caretVisible
  43591. && ! isReadOnly())
  43592. {
  43593. g.setColour (findColour (caretColourId));
  43594. g.fillRect (borderSize.getLeft() + textHolder->getX() + leftIndent + cursorX,
  43595. borderSize.getTop() + textHolder->getY() + topIndent + cursorY,
  43596. 2.0f, cursorHeight);
  43597. }
  43598. if (textToShowWhenEmpty.isNotEmpty()
  43599. && (! hasKeyboardFocus (false))
  43600. && getTotalNumChars() == 0)
  43601. {
  43602. g.setColour (colourForTextWhenEmpty);
  43603. g.setFont (getFont());
  43604. if (isMultiLine())
  43605. {
  43606. g.drawText (textToShowWhenEmpty,
  43607. 0, 0, getWidth(), getHeight(),
  43608. Justification::centred, true);
  43609. }
  43610. else
  43611. {
  43612. g.drawText (textToShowWhenEmpty,
  43613. leftIndent, topIndent,
  43614. viewport->getWidth() - leftIndent,
  43615. viewport->getHeight() - topIndent,
  43616. Justification::centredLeft, true);
  43617. }
  43618. }
  43619. getLookAndFeel().drawTextEditorOutline (g, getWidth(), getHeight(), *this);
  43620. }
  43621. class TextEditorMenuPerformer : public ModalComponentManager::Callback
  43622. {
  43623. public:
  43624. TextEditorMenuPerformer (TextEditor* const editor_)
  43625. : editor (editor_)
  43626. {
  43627. }
  43628. void modalStateFinished (int returnValue)
  43629. {
  43630. if (editor != 0 && returnValue != 0)
  43631. editor->performPopupMenuAction (returnValue);
  43632. }
  43633. private:
  43634. Component::SafePointer<TextEditor> editor;
  43635. TextEditorMenuPerformer (const TextEditorMenuPerformer&);
  43636. TextEditorMenuPerformer& operator= (const TextEditorMenuPerformer&);
  43637. };
  43638. void TextEditor::mouseDown (const MouseEvent& e)
  43639. {
  43640. beginDragAutoRepeat (100);
  43641. newTransaction();
  43642. if (wasFocused || ! selectAllTextWhenFocused)
  43643. {
  43644. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  43645. {
  43646. moveCursorTo (getTextIndexAt (e.x, e.y),
  43647. e.mods.isShiftDown());
  43648. }
  43649. else
  43650. {
  43651. PopupMenu m;
  43652. m.setLookAndFeel (&getLookAndFeel());
  43653. addPopupMenuItems (m, &e);
  43654. m.show (0, 0, 0, 0, new TextEditorMenuPerformer (this));
  43655. }
  43656. }
  43657. }
  43658. void TextEditor::mouseDrag (const MouseEvent& e)
  43659. {
  43660. if (wasFocused || ! selectAllTextWhenFocused)
  43661. {
  43662. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  43663. {
  43664. moveCursorTo (getTextIndexAt (e.x, e.y), true);
  43665. }
  43666. }
  43667. }
  43668. void TextEditor::mouseUp (const MouseEvent& e)
  43669. {
  43670. newTransaction();
  43671. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43672. if (wasFocused || ! selectAllTextWhenFocused)
  43673. {
  43674. if (e.mouseWasClicked() && ! (popupMenuEnabled && e.mods.isPopupMenu()))
  43675. {
  43676. moveCaret (getTextIndexAt (e.x, e.y));
  43677. }
  43678. }
  43679. wasFocused = true;
  43680. }
  43681. void TextEditor::mouseDoubleClick (const MouseEvent& e)
  43682. {
  43683. int tokenEnd = getTextIndexAt (e.x, e.y);
  43684. int tokenStart = tokenEnd;
  43685. if (e.getNumberOfClicks() > 3)
  43686. {
  43687. tokenStart = 0;
  43688. tokenEnd = getTotalNumChars();
  43689. }
  43690. else
  43691. {
  43692. const String t (getText());
  43693. const int totalLength = getTotalNumChars();
  43694. while (tokenEnd < totalLength)
  43695. {
  43696. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  43697. if (CharacterFunctions::isLetterOrDigit (t [tokenEnd]) || t [tokenEnd] > 128)
  43698. ++tokenEnd;
  43699. else
  43700. break;
  43701. }
  43702. tokenStart = tokenEnd;
  43703. while (tokenStart > 0)
  43704. {
  43705. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  43706. if (CharacterFunctions::isLetterOrDigit (t [tokenStart - 1]) || t [tokenStart - 1] > 128)
  43707. --tokenStart;
  43708. else
  43709. break;
  43710. }
  43711. if (e.getNumberOfClicks() > 2)
  43712. {
  43713. while (tokenEnd < totalLength)
  43714. {
  43715. if (t [tokenEnd] != '\r' && t [tokenEnd] != '\n')
  43716. ++tokenEnd;
  43717. else
  43718. break;
  43719. }
  43720. while (tokenStart > 0)
  43721. {
  43722. if (t [tokenStart - 1] != '\r' && t [tokenStart - 1] != '\n')
  43723. --tokenStart;
  43724. else
  43725. break;
  43726. }
  43727. }
  43728. }
  43729. moveCursorTo (tokenEnd, false);
  43730. moveCursorTo (tokenStart, true);
  43731. }
  43732. void TextEditor::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  43733. {
  43734. if (! viewport->useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  43735. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  43736. }
  43737. bool TextEditor::keyPressed (const KeyPress& key)
  43738. {
  43739. if (isReadOnly() && key != KeyPress ('c', ModifierKeys::commandModifier, 0))
  43740. return false;
  43741. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  43742. if (key.isKeyCode (KeyPress::leftKey)
  43743. || key.isKeyCode (KeyPress::upKey))
  43744. {
  43745. newTransaction();
  43746. int newPos;
  43747. if (isMultiLine() && key.isKeyCode (KeyPress::upKey))
  43748. newPos = indexAtPosition (cursorX, cursorY - 1);
  43749. else if (moveInWholeWordSteps)
  43750. newPos = findWordBreakBefore (getCaretPosition());
  43751. else
  43752. newPos = getCaretPosition() - 1;
  43753. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  43754. }
  43755. else if (key.isKeyCode (KeyPress::rightKey)
  43756. || key.isKeyCode (KeyPress::downKey))
  43757. {
  43758. newTransaction();
  43759. int newPos;
  43760. if (isMultiLine() && key.isKeyCode (KeyPress::downKey))
  43761. newPos = indexAtPosition (cursorX, cursorY + cursorHeight + 1);
  43762. else if (moveInWholeWordSteps)
  43763. newPos = findWordBreakAfter (getCaretPosition());
  43764. else
  43765. newPos = getCaretPosition() + 1;
  43766. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  43767. }
  43768. else if (key.isKeyCode (KeyPress::pageDownKey) && isMultiLine())
  43769. {
  43770. newTransaction();
  43771. moveCursorTo (indexAtPosition (cursorX, cursorY + cursorHeight + viewport->getViewHeight()),
  43772. key.getModifiers().isShiftDown());
  43773. }
  43774. else if (key.isKeyCode (KeyPress::pageUpKey) && isMultiLine())
  43775. {
  43776. newTransaction();
  43777. moveCursorTo (indexAtPosition (cursorX, cursorY - viewport->getViewHeight()),
  43778. key.getModifiers().isShiftDown());
  43779. }
  43780. else if (key.isKeyCode (KeyPress::homeKey))
  43781. {
  43782. newTransaction();
  43783. if (isMultiLine() && ! moveInWholeWordSteps)
  43784. moveCursorTo (indexAtPosition (0.0f, cursorY),
  43785. key.getModifiers().isShiftDown());
  43786. else
  43787. moveCursorTo (0, key.getModifiers().isShiftDown());
  43788. }
  43789. else if (key.isKeyCode (KeyPress::endKey))
  43790. {
  43791. newTransaction();
  43792. if (isMultiLine() && ! moveInWholeWordSteps)
  43793. moveCursorTo (indexAtPosition ((float) textHolder->getWidth(), cursorY),
  43794. key.getModifiers().isShiftDown());
  43795. else
  43796. moveCursorTo (getTotalNumChars(), key.getModifiers().isShiftDown());
  43797. }
  43798. else if (key.isKeyCode (KeyPress::backspaceKey))
  43799. {
  43800. if (moveInWholeWordSteps)
  43801. {
  43802. moveCursorTo (findWordBreakBefore (getCaretPosition()), true);
  43803. }
  43804. else
  43805. {
  43806. if (selection.isEmpty() && selection.getStart() > 0)
  43807. selection.setStart (selection.getEnd() - 1);
  43808. }
  43809. cut();
  43810. }
  43811. else if (key.isKeyCode (KeyPress::deleteKey))
  43812. {
  43813. if (key.getModifiers().isShiftDown())
  43814. copy();
  43815. if (selection.isEmpty() && selection.getStart() < getTotalNumChars())
  43816. selection.setEnd (selection.getStart() + 1);
  43817. cut();
  43818. }
  43819. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0)
  43820. || key == KeyPress (KeyPress::insertKey, ModifierKeys::ctrlModifier, 0))
  43821. {
  43822. newTransaction();
  43823. copy();
  43824. }
  43825. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  43826. {
  43827. newTransaction();
  43828. copy();
  43829. cut();
  43830. }
  43831. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0)
  43832. || key == KeyPress (KeyPress::insertKey, ModifierKeys::shiftModifier, 0))
  43833. {
  43834. newTransaction();
  43835. paste();
  43836. }
  43837. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  43838. {
  43839. newTransaction();
  43840. doUndoRedo (false);
  43841. }
  43842. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0))
  43843. {
  43844. newTransaction();
  43845. doUndoRedo (true);
  43846. }
  43847. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  43848. {
  43849. newTransaction();
  43850. moveCursorTo (getTotalNumChars(), false);
  43851. moveCursorTo (0, true);
  43852. }
  43853. else if (key == KeyPress::returnKey)
  43854. {
  43855. newTransaction();
  43856. insertTextAtCaret ("\n");
  43857. }
  43858. else if (key.isKeyCode (KeyPress::escapeKey))
  43859. {
  43860. newTransaction();
  43861. moveCursorTo (getCaretPosition(), false);
  43862. escapePressed();
  43863. }
  43864. else if (key.getTextCharacter() >= ' '
  43865. || (tabKeyUsed && (key.getTextCharacter() == '\t')))
  43866. {
  43867. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  43868. lastTransactionTime = Time::getApproximateMillisecondCounter();
  43869. }
  43870. else
  43871. {
  43872. return false;
  43873. }
  43874. return true;
  43875. }
  43876. bool TextEditor::keyStateChanged (const bool isKeyDown)
  43877. {
  43878. if (! isKeyDown)
  43879. return false;
  43880. #if JUCE_WINDOWS
  43881. if (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0).isCurrentlyDown())
  43882. return false; // We need to explicitly allow alt-F4 to pass through on Windows
  43883. #endif
  43884. // (overridden to avoid forwarding key events to the parent)
  43885. return ! ModifierKeys::getCurrentModifiers().isCommandDown();
  43886. }
  43887. const int baseMenuItemID = 0x7fff0000;
  43888. void TextEditor::addPopupMenuItems (PopupMenu& m, const MouseEvent*)
  43889. {
  43890. const bool writable = ! isReadOnly();
  43891. if (passwordCharacter == 0)
  43892. {
  43893. m.addItem (baseMenuItemID + 1, TRANS("cut"), writable);
  43894. m.addItem (baseMenuItemID + 2, TRANS("copy"), ! selection.isEmpty());
  43895. m.addItem (baseMenuItemID + 3, TRANS("paste"), writable);
  43896. }
  43897. m.addItem (baseMenuItemID + 4, TRANS("delete"), writable);
  43898. m.addSeparator();
  43899. m.addItem (baseMenuItemID + 5, TRANS("select all"));
  43900. m.addSeparator();
  43901. if (getUndoManager() != 0)
  43902. {
  43903. m.addItem (baseMenuItemID + 6, TRANS("undo"), undoManager.canUndo());
  43904. m.addItem (baseMenuItemID + 7, TRANS("redo"), undoManager.canRedo());
  43905. }
  43906. }
  43907. void TextEditor::performPopupMenuAction (const int menuItemID)
  43908. {
  43909. switch (menuItemID)
  43910. {
  43911. case baseMenuItemID + 1:
  43912. copy();
  43913. cut();
  43914. break;
  43915. case baseMenuItemID + 2:
  43916. copy();
  43917. break;
  43918. case baseMenuItemID + 3:
  43919. paste();
  43920. break;
  43921. case baseMenuItemID + 4:
  43922. cut();
  43923. break;
  43924. case baseMenuItemID + 5:
  43925. moveCursorTo (getTotalNumChars(), false);
  43926. moveCursorTo (0, true);
  43927. break;
  43928. case baseMenuItemID + 6:
  43929. doUndoRedo (false);
  43930. break;
  43931. case baseMenuItemID + 7:
  43932. doUndoRedo (true);
  43933. break;
  43934. default:
  43935. break;
  43936. }
  43937. }
  43938. void TextEditor::focusGained (FocusChangeType)
  43939. {
  43940. newTransaction();
  43941. caretFlashState = true;
  43942. if (selectAllTextWhenFocused)
  43943. {
  43944. moveCursorTo (0, false);
  43945. moveCursorTo (getTotalNumChars(), true);
  43946. }
  43947. repaint();
  43948. if (caretVisible)
  43949. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43950. ComponentPeer* const peer = getPeer();
  43951. if (peer != 0 && ! isReadOnly())
  43952. peer->textInputRequired (getScreenPosition() - peer->getScreenPosition());
  43953. }
  43954. void TextEditor::focusLost (FocusChangeType)
  43955. {
  43956. newTransaction();
  43957. wasFocused = false;
  43958. textHolder->stopTimer();
  43959. caretFlashState = false;
  43960. postCommandMessage (TextEditorDefs::focusLossMessageId);
  43961. repaint();
  43962. }
  43963. void TextEditor::resized()
  43964. {
  43965. viewport->setBoundsInset (borderSize);
  43966. viewport->setSingleStepSizes (16, roundToInt (currentFont.getHeight()));
  43967. updateTextHolderSize();
  43968. if (! isMultiLine())
  43969. {
  43970. scrollToMakeSureCursorIsVisible();
  43971. }
  43972. else
  43973. {
  43974. updateCaretPosition();
  43975. }
  43976. }
  43977. void TextEditor::handleCommandMessage (const int commandId)
  43978. {
  43979. Component::BailOutChecker checker (this);
  43980. switch (commandId)
  43981. {
  43982. case TextEditorDefs::textChangeMessageId:
  43983. listeners.callChecked (checker, &TextEditor::Listener::textEditorTextChanged, (TextEditor&) *this);
  43984. break;
  43985. case TextEditorDefs::returnKeyMessageId:
  43986. listeners.callChecked (checker, &TextEditor::Listener::textEditorReturnKeyPressed, (TextEditor&) *this);
  43987. break;
  43988. case TextEditorDefs::escapeKeyMessageId:
  43989. listeners.callChecked (checker, &TextEditor::Listener::textEditorEscapeKeyPressed, (TextEditor&) *this);
  43990. break;
  43991. case TextEditorDefs::focusLossMessageId:
  43992. listeners.callChecked (checker, &TextEditor::Listener::textEditorFocusLost, (TextEditor&) *this);
  43993. break;
  43994. default:
  43995. jassertfalse;
  43996. break;
  43997. }
  43998. }
  43999. void TextEditor::enablementChanged()
  44000. {
  44001. setMouseCursor (isReadOnly() ? MouseCursor::NormalCursor
  44002. : MouseCursor::IBeamCursor);
  44003. repaint();
  44004. }
  44005. UndoManager* TextEditor::getUndoManager() throw()
  44006. {
  44007. return isReadOnly() ? 0 : &undoManager;
  44008. }
  44009. void TextEditor::clearInternal (UndoManager* const um)
  44010. {
  44011. remove (Range<int> (0, getTotalNumChars()), um, caretPosition);
  44012. }
  44013. void TextEditor::insert (const String& text,
  44014. const int insertIndex,
  44015. const Font& font,
  44016. const Colour& colour,
  44017. UndoManager* const um,
  44018. const int caretPositionToMoveTo)
  44019. {
  44020. if (text.isNotEmpty())
  44021. {
  44022. if (um != 0)
  44023. {
  44024. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  44025. newTransaction();
  44026. um->perform (new InsertAction (*this, text, insertIndex, font, colour,
  44027. caretPosition, caretPositionToMoveTo));
  44028. }
  44029. else
  44030. {
  44031. repaintText (Range<int> (insertIndex, getTotalNumChars())); // must do this before and after changing the data, in case
  44032. // a line gets moved due to word wrap
  44033. int index = 0;
  44034. int nextIndex = 0;
  44035. for (int i = 0; i < sections.size(); ++i)
  44036. {
  44037. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  44038. if (insertIndex == index)
  44039. {
  44040. sections.insert (i, new UniformTextSection (text,
  44041. font, colour,
  44042. passwordCharacter));
  44043. break;
  44044. }
  44045. else if (insertIndex > index && insertIndex < nextIndex)
  44046. {
  44047. splitSection (i, insertIndex - index);
  44048. sections.insert (i + 1, new UniformTextSection (text,
  44049. font, colour,
  44050. passwordCharacter));
  44051. break;
  44052. }
  44053. index = nextIndex;
  44054. }
  44055. if (nextIndex == insertIndex)
  44056. sections.add (new UniformTextSection (text,
  44057. font, colour,
  44058. passwordCharacter));
  44059. coalesceSimilarSections();
  44060. totalNumChars = -1;
  44061. valueTextNeedsUpdating = true;
  44062. moveCursorTo (caretPositionToMoveTo, false);
  44063. repaintText (Range<int> (insertIndex, getTotalNumChars()));
  44064. }
  44065. }
  44066. }
  44067. void TextEditor::reinsert (const int insertIndex,
  44068. const Array <UniformTextSection*>& sectionsToInsert)
  44069. {
  44070. int index = 0;
  44071. int nextIndex = 0;
  44072. for (int i = 0; i < sections.size(); ++i)
  44073. {
  44074. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  44075. if (insertIndex == index)
  44076. {
  44077. for (int j = sectionsToInsert.size(); --j >= 0;)
  44078. sections.insert (i, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  44079. break;
  44080. }
  44081. else if (insertIndex > index && insertIndex < nextIndex)
  44082. {
  44083. splitSection (i, insertIndex - index);
  44084. for (int j = sectionsToInsert.size(); --j >= 0;)
  44085. sections.insert (i + 1, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  44086. break;
  44087. }
  44088. index = nextIndex;
  44089. }
  44090. if (nextIndex == insertIndex)
  44091. {
  44092. for (int j = 0; j < sectionsToInsert.size(); ++j)
  44093. sections.add (new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  44094. }
  44095. coalesceSimilarSections();
  44096. totalNumChars = -1;
  44097. valueTextNeedsUpdating = true;
  44098. }
  44099. void TextEditor::remove (const Range<int>& range,
  44100. UndoManager* const um,
  44101. const int caretPositionToMoveTo)
  44102. {
  44103. if (! range.isEmpty())
  44104. {
  44105. int index = 0;
  44106. for (int i = 0; i < sections.size(); ++i)
  44107. {
  44108. const int nextIndex = index + sections.getUnchecked(i)->getTotalLength();
  44109. if (range.getStart() > index && range.getStart() < nextIndex)
  44110. {
  44111. splitSection (i, range.getStart() - index);
  44112. --i;
  44113. }
  44114. else if (range.getEnd() > index && range.getEnd() < nextIndex)
  44115. {
  44116. splitSection (i, range.getEnd() - index);
  44117. --i;
  44118. }
  44119. else
  44120. {
  44121. index = nextIndex;
  44122. if (index > range.getEnd())
  44123. break;
  44124. }
  44125. }
  44126. index = 0;
  44127. if (um != 0)
  44128. {
  44129. Array <UniformTextSection*> removedSections;
  44130. for (int i = 0; i < sections.size(); ++i)
  44131. {
  44132. if (range.getEnd() <= range.getStart())
  44133. break;
  44134. UniformTextSection* const section = sections.getUnchecked (i);
  44135. const int nextIndex = index + section->getTotalLength();
  44136. if (range.getStart() <= index && range.getEnd() >= nextIndex)
  44137. removedSections.add (new UniformTextSection (*section));
  44138. index = nextIndex;
  44139. }
  44140. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  44141. newTransaction();
  44142. um->perform (new RemoveAction (*this, range, caretPosition,
  44143. caretPositionToMoveTo, removedSections));
  44144. }
  44145. else
  44146. {
  44147. Range<int> remainingRange (range);
  44148. for (int i = 0; i < sections.size(); ++i)
  44149. {
  44150. UniformTextSection* const section = sections.getUnchecked (i);
  44151. const int nextIndex = index + section->getTotalLength();
  44152. if (remainingRange.getStart() <= index && remainingRange.getEnd() >= nextIndex)
  44153. {
  44154. sections.remove(i);
  44155. section->clear();
  44156. delete section;
  44157. remainingRange.setEnd (remainingRange.getEnd() - (nextIndex - index));
  44158. if (remainingRange.isEmpty())
  44159. break;
  44160. --i;
  44161. }
  44162. else
  44163. {
  44164. index = nextIndex;
  44165. }
  44166. }
  44167. coalesceSimilarSections();
  44168. totalNumChars = -1;
  44169. valueTextNeedsUpdating = true;
  44170. moveCursorTo (caretPositionToMoveTo, false);
  44171. repaintText (Range<int> (range.getStart(), getTotalNumChars()));
  44172. }
  44173. }
  44174. }
  44175. const String TextEditor::getText() const
  44176. {
  44177. String t;
  44178. t.preallocateStorage (getTotalNumChars());
  44179. String::Concatenator concatenator (t);
  44180. for (int i = 0; i < sections.size(); ++i)
  44181. sections.getUnchecked (i)->appendAllText (concatenator);
  44182. return t;
  44183. }
  44184. const String TextEditor::getTextInRange (const Range<int>& range) const
  44185. {
  44186. String t;
  44187. if (! range.isEmpty())
  44188. {
  44189. t.preallocateStorage (jmin (getTotalNumChars(), range.getLength()));
  44190. String::Concatenator concatenator (t);
  44191. int index = 0;
  44192. for (int i = 0; i < sections.size(); ++i)
  44193. {
  44194. const UniformTextSection* const s = sections.getUnchecked (i);
  44195. const int nextIndex = index + s->getTotalLength();
  44196. if (range.getStart() < nextIndex)
  44197. {
  44198. if (range.getEnd() <= index)
  44199. break;
  44200. s->appendSubstring (concatenator, range - index);
  44201. }
  44202. index = nextIndex;
  44203. }
  44204. }
  44205. return t;
  44206. }
  44207. const String TextEditor::getHighlightedText() const
  44208. {
  44209. return getTextInRange (selection);
  44210. }
  44211. int TextEditor::getTotalNumChars() const
  44212. {
  44213. if (totalNumChars < 0)
  44214. {
  44215. totalNumChars = 0;
  44216. for (int i = sections.size(); --i >= 0;)
  44217. totalNumChars += sections.getUnchecked (i)->getTotalLength();
  44218. }
  44219. return totalNumChars;
  44220. }
  44221. bool TextEditor::isEmpty() const
  44222. {
  44223. return getTotalNumChars() == 0;
  44224. }
  44225. void TextEditor::getCharPosition (const int index, float& cx, float& cy, float& lineHeight) const
  44226. {
  44227. const float wordWrapWidth = getWordWrapWidth();
  44228. if (wordWrapWidth > 0 && sections.size() > 0)
  44229. {
  44230. Iterator i (sections, wordWrapWidth, passwordCharacter);
  44231. i.getCharPosition (index, cx, cy, lineHeight);
  44232. }
  44233. else
  44234. {
  44235. cx = cy = 0;
  44236. lineHeight = currentFont.getHeight();
  44237. }
  44238. }
  44239. int TextEditor::indexAtPosition (const float x, const float y)
  44240. {
  44241. const float wordWrapWidth = getWordWrapWidth();
  44242. if (wordWrapWidth > 0)
  44243. {
  44244. Iterator i (sections, wordWrapWidth, passwordCharacter);
  44245. while (i.next())
  44246. {
  44247. if (i.lineY + i.lineHeight > y)
  44248. {
  44249. if (i.lineY > y)
  44250. return jmax (0, i.indexInText - 1);
  44251. if (i.atomX >= x)
  44252. return i.indexInText;
  44253. if (x < i.atomRight)
  44254. return i.xToIndex (x);
  44255. }
  44256. }
  44257. }
  44258. return getTotalNumChars();
  44259. }
  44260. int TextEditor::findWordBreakAfter (const int position) const
  44261. {
  44262. const String t (getTextInRange (Range<int> (position, position + 512)));
  44263. const int totalLength = t.length();
  44264. int i = 0;
  44265. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  44266. ++i;
  44267. const int type = TextEditorDefs::getCharacterCategory (t[i]);
  44268. while (i < totalLength && type == TextEditorDefs::getCharacterCategory (t[i]))
  44269. ++i;
  44270. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  44271. ++i;
  44272. return position + i;
  44273. }
  44274. int TextEditor::findWordBreakBefore (const int position) const
  44275. {
  44276. if (position <= 0)
  44277. return 0;
  44278. const int startOfBuffer = jmax (0, position - 512);
  44279. const String t (getTextInRange (Range<int> (startOfBuffer, position)));
  44280. int i = position - startOfBuffer;
  44281. while (i > 0 && CharacterFunctions::isWhitespace (t [i - 1]))
  44282. --i;
  44283. if (i > 0)
  44284. {
  44285. const int type = TextEditorDefs::getCharacterCategory (t [i - 1]);
  44286. while (i > 0 && type == TextEditorDefs::getCharacterCategory (t [i - 1]))
  44287. --i;
  44288. }
  44289. jassert (startOfBuffer + i >= 0);
  44290. return startOfBuffer + i;
  44291. }
  44292. void TextEditor::splitSection (const int sectionIndex,
  44293. const int charToSplitAt)
  44294. {
  44295. jassert (sections[sectionIndex] != 0);
  44296. sections.insert (sectionIndex + 1,
  44297. sections.getUnchecked (sectionIndex)->split (charToSplitAt, passwordCharacter));
  44298. }
  44299. void TextEditor::coalesceSimilarSections()
  44300. {
  44301. for (int i = 0; i < sections.size() - 1; ++i)
  44302. {
  44303. UniformTextSection* const s1 = sections.getUnchecked (i);
  44304. UniformTextSection* const s2 = sections.getUnchecked (i + 1);
  44305. if (s1->font == s2->font
  44306. && s1->colour == s2->colour)
  44307. {
  44308. s1->append (*s2, passwordCharacter);
  44309. sections.remove (i + 1);
  44310. delete s2;
  44311. --i;
  44312. }
  44313. }
  44314. }
  44315. END_JUCE_NAMESPACE
  44316. /*** End of inlined file: juce_TextEditor.cpp ***/
  44317. /*** Start of inlined file: juce_Toolbar.cpp ***/
  44318. BEGIN_JUCE_NAMESPACE
  44319. const char* const Toolbar::toolbarDragDescriptor = "_toolbarItem_";
  44320. class ToolbarSpacerComp : public ToolbarItemComponent
  44321. {
  44322. public:
  44323. ToolbarSpacerComp (const int itemId_, const float fixedSize_, const bool drawBar_)
  44324. : ToolbarItemComponent (itemId_, String::empty, false),
  44325. fixedSize (fixedSize_),
  44326. drawBar (drawBar_)
  44327. {
  44328. }
  44329. ~ToolbarSpacerComp()
  44330. {
  44331. }
  44332. bool getToolbarItemSizes (int toolbarThickness, bool /*isToolbarVertical*/,
  44333. int& preferredSize, int& minSize, int& maxSize)
  44334. {
  44335. if (fixedSize <= 0)
  44336. {
  44337. preferredSize = toolbarThickness * 2;
  44338. minSize = 4;
  44339. maxSize = 32768;
  44340. }
  44341. else
  44342. {
  44343. maxSize = roundToInt (toolbarThickness * fixedSize);
  44344. minSize = drawBar ? maxSize : jmin (4, maxSize);
  44345. preferredSize = maxSize;
  44346. if (getEditingMode() == editableOnPalette)
  44347. preferredSize = maxSize = toolbarThickness / (drawBar ? 3 : 2);
  44348. }
  44349. return true;
  44350. }
  44351. void paintButtonArea (Graphics&, int, int, bool, bool)
  44352. {
  44353. }
  44354. void contentAreaChanged (const Rectangle<int>&)
  44355. {
  44356. }
  44357. int getResizeOrder() const throw()
  44358. {
  44359. return fixedSize <= 0 ? 0 : 1;
  44360. }
  44361. void paint (Graphics& g)
  44362. {
  44363. const int w = getWidth();
  44364. const int h = getHeight();
  44365. if (drawBar)
  44366. {
  44367. g.setColour (findColour (Toolbar::separatorColourId, true));
  44368. const float thickness = 0.2f;
  44369. if (isToolbarVertical())
  44370. g.fillRect (w * 0.1f, h * (0.5f - thickness * 0.5f), w * 0.8f, h * thickness);
  44371. else
  44372. g.fillRect (w * (0.5f - thickness * 0.5f), h * 0.1f, w * thickness, h * 0.8f);
  44373. }
  44374. if (getEditingMode() != normalMode && ! drawBar)
  44375. {
  44376. g.setColour (findColour (Toolbar::separatorColourId, true));
  44377. const int indentX = jmin (2, (w - 3) / 2);
  44378. const int indentY = jmin (2, (h - 3) / 2);
  44379. g.drawRect (indentX, indentY, w - indentX * 2, h - indentY * 2, 1);
  44380. if (fixedSize <= 0)
  44381. {
  44382. float x1, y1, x2, y2, x3, y3, x4, y4, hw, hl;
  44383. if (isToolbarVertical())
  44384. {
  44385. x1 = w * 0.5f;
  44386. y1 = h * 0.4f;
  44387. x2 = x1;
  44388. y2 = indentX * 2.0f;
  44389. x3 = x1;
  44390. y3 = h * 0.6f;
  44391. x4 = x1;
  44392. y4 = h - y2;
  44393. hw = w * 0.15f;
  44394. hl = w * 0.2f;
  44395. }
  44396. else
  44397. {
  44398. x1 = w * 0.4f;
  44399. y1 = h * 0.5f;
  44400. x2 = indentX * 2.0f;
  44401. y2 = y1;
  44402. x3 = w * 0.6f;
  44403. y3 = y1;
  44404. x4 = w - x2;
  44405. y4 = y1;
  44406. hw = h * 0.15f;
  44407. hl = h * 0.2f;
  44408. }
  44409. Path p;
  44410. p.addArrow (Line<float> (x1, y1, x2, y2), 1.5f, hw, hl);
  44411. p.addArrow (Line<float> (x3, y3, x4, y4), 1.5f, hw, hl);
  44412. g.fillPath (p);
  44413. }
  44414. }
  44415. }
  44416. juce_UseDebuggingNewOperator
  44417. private:
  44418. const float fixedSize;
  44419. const bool drawBar;
  44420. ToolbarSpacerComp (const ToolbarSpacerComp&);
  44421. ToolbarSpacerComp& operator= (const ToolbarSpacerComp&);
  44422. };
  44423. class Toolbar::MissingItemsComponent : public PopupMenuCustomComponent
  44424. {
  44425. public:
  44426. MissingItemsComponent (Toolbar& owner_, const int height_)
  44427. : PopupMenuCustomComponent (true),
  44428. owner (owner_),
  44429. height (height_)
  44430. {
  44431. for (int i = owner_.items.size(); --i >= 0;)
  44432. {
  44433. ToolbarItemComponent* const tc = owner_.items.getUnchecked(i);
  44434. if (dynamic_cast <ToolbarSpacerComp*> (tc) == 0 && ! tc->isVisible())
  44435. {
  44436. oldIndexes.insert (0, i);
  44437. addAndMakeVisible (tc, 0);
  44438. }
  44439. }
  44440. layout (400);
  44441. }
  44442. ~MissingItemsComponent()
  44443. {
  44444. // deleting the toolbar while its menu it open??
  44445. jassert (owner.isValidComponent());
  44446. for (int i = 0; i < getNumChildComponents(); ++i)
  44447. {
  44448. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  44449. if (tc != 0)
  44450. {
  44451. tc->setVisible (false);
  44452. const int index = oldIndexes.remove (i);
  44453. owner.addChildComponent (tc, index);
  44454. --i;
  44455. }
  44456. }
  44457. owner.resized();
  44458. }
  44459. void layout (const int preferredWidth)
  44460. {
  44461. const int indent = 8;
  44462. int x = indent;
  44463. int y = indent;
  44464. int maxX = 0;
  44465. for (int i = 0; i < getNumChildComponents(); ++i)
  44466. {
  44467. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  44468. if (tc != 0)
  44469. {
  44470. int preferredSize = 1, minSize = 1, maxSize = 1;
  44471. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  44472. {
  44473. if (x + preferredSize > preferredWidth && x > indent)
  44474. {
  44475. x = indent;
  44476. y += height;
  44477. }
  44478. tc->setBounds (x, y, preferredSize, height);
  44479. x += preferredSize;
  44480. maxX = jmax (maxX, x);
  44481. }
  44482. }
  44483. }
  44484. setSize (maxX + 8, y + height + 8);
  44485. }
  44486. void getIdealSize (int& idealWidth, int& idealHeight)
  44487. {
  44488. idealWidth = getWidth();
  44489. idealHeight = getHeight();
  44490. }
  44491. juce_UseDebuggingNewOperator
  44492. private:
  44493. Toolbar& owner;
  44494. const int height;
  44495. Array <int> oldIndexes;
  44496. MissingItemsComponent (const MissingItemsComponent&);
  44497. MissingItemsComponent& operator= (const MissingItemsComponent&);
  44498. };
  44499. Toolbar::Toolbar()
  44500. : vertical (false),
  44501. isEditingActive (false),
  44502. toolbarStyle (Toolbar::iconsOnly)
  44503. {
  44504. addChildComponent (missingItemsButton = getLookAndFeel().createToolbarMissingItemsButton (*this));
  44505. missingItemsButton->setAlwaysOnTop (true);
  44506. missingItemsButton->addButtonListener (this);
  44507. }
  44508. Toolbar::~Toolbar()
  44509. {
  44510. animator.cancelAllAnimations (true);
  44511. deleteAllChildren();
  44512. }
  44513. void Toolbar::setVertical (const bool shouldBeVertical)
  44514. {
  44515. if (vertical != shouldBeVertical)
  44516. {
  44517. vertical = shouldBeVertical;
  44518. resized();
  44519. }
  44520. }
  44521. void Toolbar::clear()
  44522. {
  44523. for (int i = items.size(); --i >= 0;)
  44524. {
  44525. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44526. items.remove (i);
  44527. delete tc;
  44528. }
  44529. resized();
  44530. }
  44531. ToolbarItemComponent* Toolbar::createItem (ToolbarItemFactory& factory, const int itemId)
  44532. {
  44533. if (itemId == ToolbarItemFactory::separatorBarId)
  44534. return new ToolbarSpacerComp (itemId, 0.1f, true);
  44535. else if (itemId == ToolbarItemFactory::spacerId)
  44536. return new ToolbarSpacerComp (itemId, 0.5f, false);
  44537. else if (itemId == ToolbarItemFactory::flexibleSpacerId)
  44538. return new ToolbarSpacerComp (itemId, 0, false);
  44539. return factory.createItem (itemId);
  44540. }
  44541. void Toolbar::addItemInternal (ToolbarItemFactory& factory,
  44542. const int itemId,
  44543. const int insertIndex)
  44544. {
  44545. // An ID can't be zero - this might indicate a mistake somewhere?
  44546. jassert (itemId != 0);
  44547. ToolbarItemComponent* const tc = createItem (factory, itemId);
  44548. if (tc != 0)
  44549. {
  44550. #if JUCE_DEBUG
  44551. Array <int> allowedIds;
  44552. factory.getAllToolbarItemIds (allowedIds);
  44553. // If your factory can create an item for a given ID, it must also return
  44554. // that ID from its getAllToolbarItemIds() method!
  44555. jassert (allowedIds.contains (itemId));
  44556. #endif
  44557. items.insert (insertIndex, tc);
  44558. addAndMakeVisible (tc, insertIndex);
  44559. }
  44560. }
  44561. void Toolbar::addItem (ToolbarItemFactory& factory,
  44562. const int itemId,
  44563. const int insertIndex)
  44564. {
  44565. addItemInternal (factory, itemId, insertIndex);
  44566. resized();
  44567. }
  44568. void Toolbar::addDefaultItems (ToolbarItemFactory& factoryToUse)
  44569. {
  44570. Array <int> ids;
  44571. factoryToUse.getDefaultItemSet (ids);
  44572. clear();
  44573. for (int i = 0; i < ids.size(); ++i)
  44574. addItemInternal (factoryToUse, ids.getUnchecked (i), -1);
  44575. resized();
  44576. }
  44577. void Toolbar::removeToolbarItem (const int itemIndex)
  44578. {
  44579. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  44580. if (tc != 0)
  44581. {
  44582. items.removeValue (tc);
  44583. delete tc;
  44584. resized();
  44585. }
  44586. }
  44587. int Toolbar::getNumItems() const throw()
  44588. {
  44589. return items.size();
  44590. }
  44591. int Toolbar::getItemId (const int itemIndex) const throw()
  44592. {
  44593. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  44594. return tc != 0 ? tc->getItemId() : 0;
  44595. }
  44596. ToolbarItemComponent* Toolbar::getItemComponent (const int itemIndex) const throw()
  44597. {
  44598. return items [itemIndex];
  44599. }
  44600. ToolbarItemComponent* Toolbar::getNextActiveComponent (int index, const int delta) const
  44601. {
  44602. for (;;)
  44603. {
  44604. index += delta;
  44605. ToolbarItemComponent* const tc = getItemComponent (index);
  44606. if (tc == 0)
  44607. break;
  44608. if (tc->isActive)
  44609. return tc;
  44610. }
  44611. return 0;
  44612. }
  44613. void Toolbar::setStyle (const ToolbarItemStyle& newStyle)
  44614. {
  44615. if (toolbarStyle != newStyle)
  44616. {
  44617. toolbarStyle = newStyle;
  44618. updateAllItemPositions (false);
  44619. }
  44620. }
  44621. const String Toolbar::toString() const
  44622. {
  44623. String s ("TB:");
  44624. for (int i = 0; i < getNumItems(); ++i)
  44625. s << getItemId(i) << ' ';
  44626. return s.trimEnd();
  44627. }
  44628. bool Toolbar::restoreFromString (ToolbarItemFactory& factoryToUse,
  44629. const String& savedVersion)
  44630. {
  44631. if (! savedVersion.startsWith ("TB:"))
  44632. return false;
  44633. StringArray tokens;
  44634. tokens.addTokens (savedVersion.substring (3), false);
  44635. clear();
  44636. for (int i = 0; i < tokens.size(); ++i)
  44637. addItemInternal (factoryToUse, tokens[i].getIntValue(), -1);
  44638. resized();
  44639. return true;
  44640. }
  44641. void Toolbar::paint (Graphics& g)
  44642. {
  44643. getLookAndFeel().paintToolbarBackground (g, getWidth(), getHeight(), *this);
  44644. }
  44645. int Toolbar::getThickness() const throw()
  44646. {
  44647. return vertical ? getWidth() : getHeight();
  44648. }
  44649. int Toolbar::getLength() const throw()
  44650. {
  44651. return vertical ? getHeight() : getWidth();
  44652. }
  44653. void Toolbar::setEditingActive (const bool active)
  44654. {
  44655. if (isEditingActive != active)
  44656. {
  44657. isEditingActive = active;
  44658. updateAllItemPositions (false);
  44659. }
  44660. }
  44661. void Toolbar::resized()
  44662. {
  44663. updateAllItemPositions (false);
  44664. }
  44665. void Toolbar::updateAllItemPositions (const bool animate)
  44666. {
  44667. if (getWidth() > 0 && getHeight() > 0)
  44668. {
  44669. StretchableObjectResizer resizer;
  44670. int i;
  44671. for (i = 0; i < items.size(); ++i)
  44672. {
  44673. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44674. tc->setEditingMode (isEditingActive ? ToolbarItemComponent::editableOnToolbar
  44675. : ToolbarItemComponent::normalMode);
  44676. tc->setStyle (toolbarStyle);
  44677. ToolbarSpacerComp* const spacer = dynamic_cast <ToolbarSpacerComp*> (tc);
  44678. int preferredSize = 1, minSize = 1, maxSize = 1;
  44679. if (tc->getToolbarItemSizes (getThickness(), isVertical(),
  44680. preferredSize, minSize, maxSize))
  44681. {
  44682. tc->isActive = true;
  44683. resizer.addItem (preferredSize, minSize, maxSize,
  44684. spacer != 0 ? spacer->getResizeOrder() : 2);
  44685. }
  44686. else
  44687. {
  44688. tc->isActive = false;
  44689. tc->setVisible (false);
  44690. }
  44691. }
  44692. resizer.resizeToFit (getLength());
  44693. int totalLength = 0;
  44694. for (i = 0; i < resizer.getNumItems(); ++i)
  44695. totalLength += (int) resizer.getItemSize (i);
  44696. const bool itemsOffTheEnd = totalLength > getLength();
  44697. const int extrasButtonSize = getThickness() / 2;
  44698. missingItemsButton->setSize (extrasButtonSize, extrasButtonSize);
  44699. missingItemsButton->setVisible (itemsOffTheEnd);
  44700. missingItemsButton->setEnabled (! isEditingActive);
  44701. if (vertical)
  44702. missingItemsButton->setCentrePosition (getWidth() / 2,
  44703. getHeight() - 4 - extrasButtonSize / 2);
  44704. else
  44705. missingItemsButton->setCentrePosition (getWidth() - 4 - extrasButtonSize / 2,
  44706. getHeight() / 2);
  44707. const int maxLength = itemsOffTheEnd ? (vertical ? missingItemsButton->getY()
  44708. : missingItemsButton->getX()) - 4
  44709. : getLength();
  44710. int pos = 0, activeIndex = 0;
  44711. for (i = 0; i < items.size(); ++i)
  44712. {
  44713. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44714. if (tc->isActive)
  44715. {
  44716. const int size = (int) resizer.getItemSize (activeIndex++);
  44717. Rectangle<int> newBounds;
  44718. if (vertical)
  44719. newBounds.setBounds (0, pos, getWidth(), size);
  44720. else
  44721. newBounds.setBounds (pos, 0, size, getHeight());
  44722. if (animate)
  44723. {
  44724. animator.animateComponent (tc, newBounds, 200, 3.0, 0.0);
  44725. }
  44726. else
  44727. {
  44728. animator.cancelAnimation (tc, false);
  44729. tc->setBounds (newBounds);
  44730. }
  44731. pos += size;
  44732. tc->setVisible (pos <= maxLength
  44733. && ((! tc->isBeingDragged)
  44734. || tc->getEditingMode() == ToolbarItemComponent::editableOnPalette));
  44735. }
  44736. }
  44737. }
  44738. }
  44739. void Toolbar::buttonClicked (Button*)
  44740. {
  44741. jassert (missingItemsButton->isShowing());
  44742. if (missingItemsButton->isShowing())
  44743. {
  44744. PopupMenu m;
  44745. m.addCustomItem (1, new MissingItemsComponent (*this, getThickness()));
  44746. m.showAt (missingItemsButton);
  44747. }
  44748. }
  44749. bool Toolbar::isInterestedInDragSource (const String& sourceDescription,
  44750. Component* /*sourceComponent*/)
  44751. {
  44752. return sourceDescription == toolbarDragDescriptor && isEditingActive;
  44753. }
  44754. void Toolbar::itemDragMove (const String&, Component* sourceComponent, int x, int y)
  44755. {
  44756. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  44757. if (tc != 0)
  44758. {
  44759. if (getNumItems() == 0)
  44760. {
  44761. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  44762. {
  44763. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  44764. if (palette != 0)
  44765. palette->replaceComponent (tc);
  44766. }
  44767. else
  44768. {
  44769. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  44770. }
  44771. items.add (tc);
  44772. addChildComponent (tc);
  44773. updateAllItemPositions (false);
  44774. }
  44775. else
  44776. {
  44777. for (int i = getNumItems(); --i >= 0;)
  44778. {
  44779. int currentIndex = getIndexOfChildComponent (tc);
  44780. if (currentIndex < 0)
  44781. {
  44782. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  44783. {
  44784. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  44785. if (palette != 0)
  44786. palette->replaceComponent (tc);
  44787. }
  44788. else
  44789. {
  44790. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  44791. }
  44792. items.add (tc);
  44793. addChildComponent (tc);
  44794. currentIndex = getIndexOfChildComponent (tc);
  44795. updateAllItemPositions (true);
  44796. }
  44797. int newIndex = currentIndex;
  44798. const int dragObjectLeft = vertical ? (y - tc->dragOffsetY) : (x - tc->dragOffsetX);
  44799. const int dragObjectRight = dragObjectLeft + (vertical ? tc->getHeight() : tc->getWidth());
  44800. const Rectangle<int> current (animator.getComponentDestination (getChildComponent (newIndex)));
  44801. ToolbarItemComponent* const prev = getNextActiveComponent (newIndex, -1);
  44802. if (prev != 0)
  44803. {
  44804. const Rectangle<int> previousPos (animator.getComponentDestination (prev));
  44805. if (abs (dragObjectLeft - (vertical ? previousPos.getY() : previousPos.getX())
  44806. < abs (dragObjectRight - (vertical ? current.getBottom() : current.getRight()))))
  44807. {
  44808. newIndex = getIndexOfChildComponent (prev);
  44809. }
  44810. }
  44811. ToolbarItemComponent* const next = getNextActiveComponent (newIndex, 1);
  44812. if (next != 0)
  44813. {
  44814. const Rectangle<int> nextPos (animator.getComponentDestination (next));
  44815. if (abs (dragObjectLeft - (vertical ? current.getY() : current.getX())
  44816. > abs (dragObjectRight - (vertical ? nextPos.getBottom() : nextPos.getRight()))))
  44817. {
  44818. newIndex = getIndexOfChildComponent (next) + 1;
  44819. }
  44820. }
  44821. if (newIndex != currentIndex)
  44822. {
  44823. items.removeValue (tc);
  44824. removeChildComponent (tc);
  44825. addChildComponent (tc, newIndex);
  44826. items.insert (newIndex, tc);
  44827. updateAllItemPositions (true);
  44828. }
  44829. else
  44830. {
  44831. break;
  44832. }
  44833. }
  44834. }
  44835. }
  44836. }
  44837. void Toolbar::itemDragExit (const String&, Component* sourceComponent)
  44838. {
  44839. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  44840. if (tc != 0)
  44841. {
  44842. if (isParentOf (tc))
  44843. {
  44844. items.removeValue (tc);
  44845. removeChildComponent (tc);
  44846. updateAllItemPositions (true);
  44847. }
  44848. }
  44849. }
  44850. void Toolbar::itemDropped (const String&, Component*, int, int)
  44851. {
  44852. }
  44853. void Toolbar::mouseDown (const MouseEvent& e)
  44854. {
  44855. if (e.mods.isPopupMenu())
  44856. {
  44857. }
  44858. }
  44859. class ToolbarCustomisationDialog : public DialogWindow
  44860. {
  44861. public:
  44862. ToolbarCustomisationDialog (ToolbarItemFactory& factory,
  44863. Toolbar* const toolbar_,
  44864. const int optionFlags)
  44865. : DialogWindow (TRANS("Add/remove items from toolbar"), Colours::white, true, true),
  44866. toolbar (toolbar_)
  44867. {
  44868. setContentComponent (new CustomiserPanel (factory, toolbar, optionFlags), true, true);
  44869. setResizable (true, true);
  44870. setResizeLimits (400, 300, 1500, 1000);
  44871. positionNearBar();
  44872. }
  44873. ~ToolbarCustomisationDialog()
  44874. {
  44875. setContentComponent (0, true);
  44876. }
  44877. void closeButtonPressed()
  44878. {
  44879. setVisible (false);
  44880. }
  44881. bool canModalEventBeSentToComponent (const Component* comp)
  44882. {
  44883. return toolbar->isParentOf (comp);
  44884. }
  44885. void positionNearBar()
  44886. {
  44887. const Rectangle<int> screenSize (toolbar->getParentMonitorArea());
  44888. const int tbx = toolbar->getScreenX();
  44889. const int tby = toolbar->getScreenY();
  44890. const int gap = 8;
  44891. int x, y;
  44892. if (toolbar->isVertical())
  44893. {
  44894. y = tby;
  44895. if (tbx > screenSize.getCentreX())
  44896. x = tbx - getWidth() - gap;
  44897. else
  44898. x = tbx + toolbar->getWidth() + gap;
  44899. }
  44900. else
  44901. {
  44902. x = tbx + (toolbar->getWidth() - getWidth()) / 2;
  44903. if (tby > screenSize.getCentreY())
  44904. y = tby - getHeight() - gap;
  44905. else
  44906. y = tby + toolbar->getHeight() + gap;
  44907. }
  44908. setTopLeftPosition (x, y);
  44909. }
  44910. private:
  44911. Toolbar* const toolbar;
  44912. class CustomiserPanel : public Component,
  44913. private ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  44914. private ButtonListener
  44915. {
  44916. public:
  44917. CustomiserPanel (ToolbarItemFactory& factory_,
  44918. Toolbar* const toolbar_,
  44919. const int optionFlags)
  44920. : factory (factory_),
  44921. toolbar (toolbar_),
  44922. styleBox (0),
  44923. defaultButton (0)
  44924. {
  44925. addAndMakeVisible (palette = new ToolbarItemPalette (factory, toolbar));
  44926. if ((optionFlags & (Toolbar::allowIconsOnlyChoice
  44927. | Toolbar::allowIconsWithTextChoice
  44928. | Toolbar::allowTextOnlyChoice)) != 0)
  44929. {
  44930. addAndMakeVisible (styleBox = new ComboBox (String::empty));
  44931. styleBox->setEditableText (false);
  44932. if ((optionFlags & Toolbar::allowIconsOnlyChoice) != 0)
  44933. styleBox->addItem (TRANS("Show icons only"), 1);
  44934. if ((optionFlags & Toolbar::allowIconsWithTextChoice) != 0)
  44935. styleBox->addItem (TRANS("Show icons and descriptions"), 2);
  44936. if ((optionFlags & Toolbar::allowTextOnlyChoice) != 0)
  44937. styleBox->addItem (TRANS("Show descriptions only"), 3);
  44938. if (toolbar_->getStyle() == Toolbar::iconsOnly)
  44939. styleBox->setSelectedId (1);
  44940. else if (toolbar_->getStyle() == Toolbar::iconsWithText)
  44941. styleBox->setSelectedId (2);
  44942. else if (toolbar_->getStyle() == Toolbar::textOnly)
  44943. styleBox->setSelectedId (3);
  44944. styleBox->addListener (this);
  44945. }
  44946. if ((optionFlags & Toolbar::showResetToDefaultsButton) != 0)
  44947. {
  44948. addAndMakeVisible (defaultButton = new TextButton (TRANS ("Restore to default set of items")));
  44949. defaultButton->addButtonListener (this);
  44950. }
  44951. addAndMakeVisible (instructions = new Label (String::empty,
  44952. 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.")));
  44953. instructions->setFont (Font (13.0f));
  44954. setSize (500, 300);
  44955. }
  44956. ~CustomiserPanel()
  44957. {
  44958. deleteAllChildren();
  44959. }
  44960. void comboBoxChanged (ComboBox*)
  44961. {
  44962. if (styleBox->getSelectedId() == 1)
  44963. toolbar->setStyle (Toolbar::iconsOnly);
  44964. else if (styleBox->getSelectedId() == 2)
  44965. toolbar->setStyle (Toolbar::iconsWithText);
  44966. else if (styleBox->getSelectedId() == 3)
  44967. toolbar->setStyle (Toolbar::textOnly);
  44968. palette->resized(); // to make it update the styles
  44969. }
  44970. void buttonClicked (Button*)
  44971. {
  44972. toolbar->addDefaultItems (factory);
  44973. }
  44974. void paint (Graphics& g)
  44975. {
  44976. Colour background;
  44977. DialogWindow* const dw = findParentComponentOfClass ((DialogWindow*) 0);
  44978. if (dw != 0)
  44979. background = dw->getBackgroundColour();
  44980. g.setColour (background.contrasting().withAlpha (0.3f));
  44981. g.fillRect (palette->getX(), palette->getBottom() - 1, palette->getWidth(), 1);
  44982. }
  44983. void resized()
  44984. {
  44985. palette->setBounds (0, 0, getWidth(), getHeight() - 120);
  44986. if (styleBox != 0)
  44987. styleBox->setBounds (10, getHeight() - 110, 200, 22);
  44988. if (defaultButton != 0)
  44989. {
  44990. defaultButton->changeWidthToFitText (22);
  44991. defaultButton->setTopLeftPosition (240, getHeight() - 110);
  44992. }
  44993. instructions->setBounds (10, getHeight() - 80, getWidth() - 20, 80);
  44994. }
  44995. private:
  44996. ToolbarItemFactory& factory;
  44997. Toolbar* const toolbar;
  44998. Label* instructions;
  44999. ToolbarItemPalette* palette;
  45000. ComboBox* styleBox;
  45001. TextButton* defaultButton;
  45002. };
  45003. };
  45004. void Toolbar::showCustomisationDialog (ToolbarItemFactory& factory, const int optionFlags)
  45005. {
  45006. setEditingActive (true);
  45007. ToolbarCustomisationDialog dw (factory, this, optionFlags);
  45008. dw.runModalLoop();
  45009. jassert (isValidComponent()); // ? deleting the toolbar while it's being edited?
  45010. setEditingActive (false);
  45011. }
  45012. END_JUCE_NAMESPACE
  45013. /*** End of inlined file: juce_Toolbar.cpp ***/
  45014. /*** Start of inlined file: juce_ToolbarItemComponent.cpp ***/
  45015. BEGIN_JUCE_NAMESPACE
  45016. ToolbarItemFactory::ToolbarItemFactory()
  45017. {
  45018. }
  45019. ToolbarItemFactory::~ToolbarItemFactory()
  45020. {
  45021. }
  45022. class ItemDragAndDropOverlayComponent : public Component
  45023. {
  45024. public:
  45025. ItemDragAndDropOverlayComponent()
  45026. : isDragging (false)
  45027. {
  45028. setAlwaysOnTop (true);
  45029. setRepaintsOnMouseActivity (true);
  45030. setMouseCursor (MouseCursor::DraggingHandCursor);
  45031. }
  45032. ~ItemDragAndDropOverlayComponent()
  45033. {
  45034. }
  45035. void paint (Graphics& g)
  45036. {
  45037. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  45038. if (isMouseOverOrDragging()
  45039. && tc != 0
  45040. && tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  45041. {
  45042. g.setColour (findColour (Toolbar::editingModeOutlineColourId, true));
  45043. g.drawRect (0, 0, getWidth(), getHeight(),
  45044. jmin (2, (getWidth() - 1) / 2, (getHeight() - 1) / 2));
  45045. }
  45046. }
  45047. void mouseDown (const MouseEvent& e)
  45048. {
  45049. isDragging = false;
  45050. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  45051. if (tc != 0)
  45052. {
  45053. tc->dragOffsetX = e.x;
  45054. tc->dragOffsetY = e.y;
  45055. }
  45056. }
  45057. void mouseDrag (const MouseEvent& e)
  45058. {
  45059. if (! (isDragging || e.mouseWasClicked()))
  45060. {
  45061. isDragging = true;
  45062. DragAndDropContainer* const dnd = DragAndDropContainer::findParentDragContainerFor (this);
  45063. if (dnd != 0)
  45064. {
  45065. dnd->startDragging (Toolbar::toolbarDragDescriptor, getParentComponent(), Image::null, true);
  45066. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  45067. if (tc != 0)
  45068. {
  45069. tc->isBeingDragged = true;
  45070. if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  45071. tc->setVisible (false);
  45072. }
  45073. }
  45074. }
  45075. }
  45076. void mouseUp (const MouseEvent&)
  45077. {
  45078. isDragging = false;
  45079. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  45080. if (tc != 0)
  45081. {
  45082. tc->isBeingDragged = false;
  45083. Toolbar* const tb = tc->getToolbar();
  45084. if (tb != 0)
  45085. tb->updateAllItemPositions (true);
  45086. else if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  45087. delete tc;
  45088. }
  45089. }
  45090. void parentSizeChanged()
  45091. {
  45092. setBounds (0, 0, getParentWidth(), getParentHeight());
  45093. }
  45094. juce_UseDebuggingNewOperator
  45095. private:
  45096. bool isDragging;
  45097. ItemDragAndDropOverlayComponent (const ItemDragAndDropOverlayComponent&);
  45098. ItemDragAndDropOverlayComponent& operator= (const ItemDragAndDropOverlayComponent&);
  45099. };
  45100. ToolbarItemComponent::ToolbarItemComponent (const int itemId_,
  45101. const String& labelText,
  45102. const bool isBeingUsedAsAButton_)
  45103. : Button (labelText),
  45104. itemId (itemId_),
  45105. mode (normalMode),
  45106. toolbarStyle (Toolbar::iconsOnly),
  45107. dragOffsetX (0),
  45108. dragOffsetY (0),
  45109. isActive (true),
  45110. isBeingDragged (false),
  45111. isBeingUsedAsAButton (isBeingUsedAsAButton_)
  45112. {
  45113. // Your item ID can't be 0!
  45114. jassert (itemId_ != 0);
  45115. }
  45116. ToolbarItemComponent::~ToolbarItemComponent()
  45117. {
  45118. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  45119. overlayComp = 0;
  45120. }
  45121. Toolbar* ToolbarItemComponent::getToolbar() const
  45122. {
  45123. return dynamic_cast <Toolbar*> (getParentComponent());
  45124. }
  45125. bool ToolbarItemComponent::isToolbarVertical() const
  45126. {
  45127. const Toolbar* const t = getToolbar();
  45128. return t != 0 && t->isVertical();
  45129. }
  45130. void ToolbarItemComponent::setStyle (const Toolbar::ToolbarItemStyle& newStyle)
  45131. {
  45132. if (toolbarStyle != newStyle)
  45133. {
  45134. toolbarStyle = newStyle;
  45135. repaint();
  45136. resized();
  45137. }
  45138. }
  45139. void ToolbarItemComponent::paintButton (Graphics& g, const bool over, const bool down)
  45140. {
  45141. if (isBeingUsedAsAButton)
  45142. getLookAndFeel().paintToolbarButtonBackground (g, getWidth(), getHeight(),
  45143. over, down, *this);
  45144. if (toolbarStyle != Toolbar::iconsOnly)
  45145. {
  45146. const int indent = contentArea.getX();
  45147. int y = indent;
  45148. int h = getHeight() - indent * 2;
  45149. if (toolbarStyle == Toolbar::iconsWithText)
  45150. {
  45151. y = contentArea.getBottom() + indent / 2;
  45152. h -= contentArea.getHeight();
  45153. }
  45154. getLookAndFeel().paintToolbarButtonLabel (g, indent, y, getWidth() - indent * 2, h,
  45155. getButtonText(), *this);
  45156. }
  45157. if (! contentArea.isEmpty())
  45158. {
  45159. g.saveState();
  45160. g.setOrigin (contentArea.getX(), contentArea.getY());
  45161. g.reduceClipRegion (0, 0, contentArea.getWidth(), contentArea.getHeight());
  45162. paintButtonArea (g, contentArea.getWidth(), contentArea.getHeight(), over, down);
  45163. g.restoreState();
  45164. }
  45165. }
  45166. void ToolbarItemComponent::resized()
  45167. {
  45168. if (toolbarStyle != Toolbar::textOnly)
  45169. {
  45170. const int indent = jmin (proportionOfWidth (0.08f),
  45171. proportionOfHeight (0.08f));
  45172. contentArea = Rectangle<int> (indent, indent,
  45173. getWidth() - indent * 2,
  45174. toolbarStyle == Toolbar::iconsWithText ? proportionOfHeight (0.55f)
  45175. : (getHeight() - indent * 2));
  45176. }
  45177. else
  45178. {
  45179. contentArea = Rectangle<int>();
  45180. }
  45181. contentAreaChanged (contentArea);
  45182. }
  45183. void ToolbarItemComponent::setEditingMode (const ToolbarEditingMode newMode)
  45184. {
  45185. if (mode != newMode)
  45186. {
  45187. mode = newMode;
  45188. repaint();
  45189. if (mode == normalMode)
  45190. {
  45191. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  45192. overlayComp = 0;
  45193. }
  45194. else if (overlayComp == 0)
  45195. {
  45196. addAndMakeVisible (overlayComp = new ItemDragAndDropOverlayComponent());
  45197. overlayComp->parentSizeChanged();
  45198. }
  45199. resized();
  45200. }
  45201. }
  45202. END_JUCE_NAMESPACE
  45203. /*** End of inlined file: juce_ToolbarItemComponent.cpp ***/
  45204. /*** Start of inlined file: juce_ToolbarItemPalette.cpp ***/
  45205. BEGIN_JUCE_NAMESPACE
  45206. ToolbarItemPalette::ToolbarItemPalette (ToolbarItemFactory& factory_,
  45207. Toolbar* const toolbar_)
  45208. : factory (factory_),
  45209. toolbar (toolbar_)
  45210. {
  45211. Component* const itemHolder = new Component();
  45212. Array <int> allIds;
  45213. factory_.getAllToolbarItemIds (allIds);
  45214. for (int i = 0; i < allIds.size(); ++i)
  45215. {
  45216. ToolbarItemComponent* const tc = Toolbar::createItem (factory_, allIds.getUnchecked (i));
  45217. jassert (tc != 0);
  45218. if (tc != 0)
  45219. {
  45220. itemHolder->addAndMakeVisible (tc);
  45221. tc->setEditingMode (ToolbarItemComponent::editableOnPalette);
  45222. }
  45223. }
  45224. viewport = new Viewport();
  45225. viewport->setViewedComponent (itemHolder);
  45226. addAndMakeVisible (viewport);
  45227. }
  45228. ToolbarItemPalette::~ToolbarItemPalette()
  45229. {
  45230. viewport->getViewedComponent()->deleteAllChildren();
  45231. deleteAllChildren();
  45232. }
  45233. void ToolbarItemPalette::resized()
  45234. {
  45235. viewport->setBoundsInset (BorderSize (1));
  45236. Component* const itemHolder = viewport->getViewedComponent();
  45237. const int indent = 8;
  45238. const int preferredWidth = viewport->getWidth() - viewport->getScrollBarThickness() - indent;
  45239. const int height = toolbar->getThickness();
  45240. int x = indent;
  45241. int y = indent;
  45242. int maxX = 0;
  45243. for (int i = 0; i < itemHolder->getNumChildComponents(); ++i)
  45244. {
  45245. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (itemHolder->getChildComponent (i));
  45246. if (tc != 0)
  45247. {
  45248. tc->setStyle (toolbar->getStyle());
  45249. int preferredSize = 1, minSize = 1, maxSize = 1;
  45250. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  45251. {
  45252. if (x + preferredSize > preferredWidth && x > indent)
  45253. {
  45254. x = indent;
  45255. y += height;
  45256. }
  45257. tc->setBounds (x, y, preferredSize, height);
  45258. x += preferredSize + 8;
  45259. maxX = jmax (maxX, x);
  45260. }
  45261. }
  45262. }
  45263. itemHolder->setSize (maxX, y + height + 8);
  45264. }
  45265. void ToolbarItemPalette::replaceComponent (ToolbarItemComponent* const comp)
  45266. {
  45267. ToolbarItemComponent* const tc = Toolbar::createItem (factory, comp->getItemId());
  45268. jassert (tc != 0);
  45269. if (tc != 0)
  45270. {
  45271. tc->setBounds (comp->getBounds());
  45272. tc->setStyle (toolbar->getStyle());
  45273. tc->setEditingMode (comp->getEditingMode());
  45274. viewport->getViewedComponent()->addAndMakeVisible (tc, getIndexOfChildComponent (comp));
  45275. }
  45276. }
  45277. END_JUCE_NAMESPACE
  45278. /*** End of inlined file: juce_ToolbarItemPalette.cpp ***/
  45279. /*** Start of inlined file: juce_TreeView.cpp ***/
  45280. BEGIN_JUCE_NAMESPACE
  45281. class TreeViewContentComponent : public Component,
  45282. public TooltipClient
  45283. {
  45284. public:
  45285. TreeViewContentComponent (TreeView& owner_)
  45286. : owner (owner_),
  45287. buttonUnderMouse (0),
  45288. isDragging (false)
  45289. {
  45290. }
  45291. ~TreeViewContentComponent()
  45292. {
  45293. deleteAllChildren();
  45294. }
  45295. void mouseDown (const MouseEvent& e)
  45296. {
  45297. updateButtonUnderMouse (e);
  45298. isDragging = false;
  45299. needSelectionOnMouseUp = false;
  45300. Rectangle<int> pos;
  45301. TreeViewItem* const item = findItemAt (e.y, pos);
  45302. if (item == 0)
  45303. return;
  45304. // (if the open/close buttons are hidden, we'll treat clicks to the left of the item
  45305. // as selection clicks)
  45306. if (e.x < pos.getX() && owner.openCloseButtonsVisible)
  45307. {
  45308. if (e.x >= pos.getX() - owner.getIndentSize())
  45309. item->setOpen (! item->isOpen());
  45310. // (clicks to the left of an open/close button are ignored)
  45311. }
  45312. else
  45313. {
  45314. // mouse-down inside the body of the item..
  45315. if (! owner.isMultiSelectEnabled())
  45316. item->setSelected (true, true);
  45317. else if (item->isSelected())
  45318. needSelectionOnMouseUp = ! e.mods.isPopupMenu();
  45319. else
  45320. selectBasedOnModifiers (item, e.mods);
  45321. if (e.x >= pos.getX())
  45322. item->itemClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  45323. }
  45324. }
  45325. void mouseUp (const MouseEvent& e)
  45326. {
  45327. updateButtonUnderMouse (e);
  45328. if (needSelectionOnMouseUp && e.mouseWasClicked())
  45329. {
  45330. Rectangle<int> pos;
  45331. TreeViewItem* const item = findItemAt (e.y, pos);
  45332. if (item != 0)
  45333. selectBasedOnModifiers (item, e.mods);
  45334. }
  45335. }
  45336. void mouseDoubleClick (const MouseEvent& e)
  45337. {
  45338. if (e.getNumberOfClicks() != 3) // ignore triple clicks
  45339. {
  45340. Rectangle<int> pos;
  45341. TreeViewItem* const item = findItemAt (e.y, pos);
  45342. if (item != 0 && (e.x >= pos.getX() || ! owner.openCloseButtonsVisible))
  45343. item->itemDoubleClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  45344. }
  45345. }
  45346. void mouseDrag (const MouseEvent& e)
  45347. {
  45348. if (isEnabled()
  45349. && ! (isDragging || e.mouseWasClicked()
  45350. || e.getDistanceFromDragStart() < 5
  45351. || e.mods.isPopupMenu()))
  45352. {
  45353. isDragging = true;
  45354. Rectangle<int> pos;
  45355. TreeViewItem* const item = findItemAt (e.getMouseDownY(), pos);
  45356. if (item != 0 && e.getMouseDownX() >= pos.getX())
  45357. {
  45358. const String dragDescription (item->getDragSourceDescription());
  45359. if (dragDescription.isNotEmpty())
  45360. {
  45361. DragAndDropContainer* const dragContainer
  45362. = DragAndDropContainer::findParentDragContainerFor (this);
  45363. if (dragContainer != 0)
  45364. {
  45365. pos.setSize (pos.getWidth(), item->itemHeight);
  45366. Image dragImage (Component::createComponentSnapshot (pos, true));
  45367. dragImage.multiplyAllAlphas (0.6f);
  45368. Point<int> imageOffset (pos.getPosition() - e.getPosition());
  45369. dragContainer->startDragging (dragDescription, &owner, dragImage, true, &imageOffset);
  45370. }
  45371. else
  45372. {
  45373. // to be able to do a drag-and-drop operation, the treeview needs to
  45374. // be inside a component which is also a DragAndDropContainer.
  45375. jassertfalse;
  45376. }
  45377. }
  45378. }
  45379. }
  45380. }
  45381. void mouseMove (const MouseEvent& e)
  45382. {
  45383. updateButtonUnderMouse (e);
  45384. }
  45385. void mouseExit (const MouseEvent& e)
  45386. {
  45387. updateButtonUnderMouse (e);
  45388. }
  45389. void paint (Graphics& g)
  45390. {
  45391. if (owner.rootItem != 0)
  45392. {
  45393. owner.handleAsyncUpdate();
  45394. if (! owner.rootItemVisible)
  45395. g.setOrigin (0, -owner.rootItem->itemHeight);
  45396. owner.rootItem->paintRecursively (g, getWidth());
  45397. }
  45398. }
  45399. TreeViewItem* findItemAt (int y, Rectangle<int>& itemPosition) const
  45400. {
  45401. if (owner.rootItem != 0)
  45402. {
  45403. owner.handleAsyncUpdate();
  45404. if (! owner.rootItemVisible)
  45405. y += owner.rootItem->itemHeight;
  45406. TreeViewItem* const ti = owner.rootItem->findItemRecursively (y);
  45407. if (ti != 0)
  45408. itemPosition = ti->getItemPosition (false);
  45409. return ti;
  45410. }
  45411. return 0;
  45412. }
  45413. void updateComponents()
  45414. {
  45415. const int visibleTop = -getY();
  45416. const int visibleBottom = visibleTop + getParentHeight();
  45417. BigInteger itemsToKeep;
  45418. {
  45419. TreeViewItem* item = owner.rootItem;
  45420. int y = (item != 0 && ! owner.rootItemVisible) ? -item->itemHeight : 0;
  45421. while (item != 0 && y < visibleBottom)
  45422. {
  45423. y += item->itemHeight;
  45424. if (y >= visibleTop)
  45425. {
  45426. const int index = rowComponentIds.indexOf (item->uid);
  45427. if (index < 0)
  45428. {
  45429. Component* const comp = item->createItemComponent();
  45430. if (comp != 0)
  45431. {
  45432. addAndMakeVisible (comp);
  45433. itemsToKeep.setBit (rowComponentItems.size());
  45434. rowComponentItems.add (item);
  45435. rowComponentIds.add (item->uid);
  45436. rowComponents.add (comp);
  45437. }
  45438. }
  45439. else
  45440. {
  45441. itemsToKeep.setBit (index);
  45442. }
  45443. }
  45444. item = item->getNextVisibleItem (true);
  45445. }
  45446. }
  45447. for (int i = rowComponentItems.size(); --i >= 0;)
  45448. {
  45449. Component* const comp = rowComponents.getUnchecked(i);
  45450. bool keep = false;
  45451. if (isParentOf (comp))
  45452. {
  45453. if (itemsToKeep[i])
  45454. {
  45455. const TreeViewItem* const item = rowComponentItems.getUnchecked(i);
  45456. Rectangle<int> pos (item->getItemPosition (false));
  45457. pos.setSize (pos.getWidth(), item->itemHeight);
  45458. if (pos.getBottom() >= visibleTop && pos.getY() < visibleBottom)
  45459. {
  45460. keep = true;
  45461. comp->setBounds (pos);
  45462. }
  45463. }
  45464. if ((! keep) && isMouseDraggingInChildCompOf (comp))
  45465. {
  45466. keep = true;
  45467. comp->setSize (0, 0);
  45468. }
  45469. }
  45470. if (! keep)
  45471. {
  45472. delete comp;
  45473. rowComponents.remove (i);
  45474. rowComponentIds.remove (i);
  45475. rowComponentItems.remove (i);
  45476. }
  45477. }
  45478. }
  45479. void updateButtonUnderMouse (const MouseEvent& e)
  45480. {
  45481. TreeViewItem* newItem = 0;
  45482. if (owner.openCloseButtonsVisible)
  45483. {
  45484. Rectangle<int> pos;
  45485. TreeViewItem* item = findItemAt (e.y, pos);
  45486. if (item != 0 && e.x < pos.getX() && e.x >= pos.getX() - owner.getIndentSize())
  45487. {
  45488. newItem = item;
  45489. if (! newItem->mightContainSubItems())
  45490. newItem = 0;
  45491. }
  45492. }
  45493. if (buttonUnderMouse != newItem)
  45494. {
  45495. if (buttonUnderMouse != 0 && containsItem (buttonUnderMouse))
  45496. {
  45497. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  45498. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  45499. }
  45500. buttonUnderMouse = newItem;
  45501. if (buttonUnderMouse != 0)
  45502. {
  45503. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  45504. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  45505. }
  45506. }
  45507. }
  45508. bool isMouseOverButton (TreeViewItem* const item) const throw()
  45509. {
  45510. return item == buttonUnderMouse;
  45511. }
  45512. void resized()
  45513. {
  45514. owner.itemsChanged();
  45515. }
  45516. const String getTooltip()
  45517. {
  45518. Rectangle<int> pos;
  45519. TreeViewItem* const item = findItemAt (getMouseXYRelative().getY(), pos);
  45520. if (item != 0)
  45521. return item->getTooltip();
  45522. return owner.getTooltip();
  45523. }
  45524. juce_UseDebuggingNewOperator
  45525. private:
  45526. TreeView& owner;
  45527. Array <TreeViewItem*> rowComponentItems;
  45528. Array <int> rowComponentIds;
  45529. Array <Component*> rowComponents;
  45530. TreeViewItem* buttonUnderMouse;
  45531. bool isDragging, needSelectionOnMouseUp;
  45532. void selectBasedOnModifiers (TreeViewItem* const item, const ModifierKeys& modifiers)
  45533. {
  45534. TreeViewItem* firstSelected = 0;
  45535. if (modifiers.isShiftDown() && ((firstSelected = owner.getSelectedItem (0)) != 0))
  45536. {
  45537. TreeViewItem* const lastSelected = owner.getSelectedItem (owner.getNumSelectedItems() - 1);
  45538. jassert (lastSelected != 0);
  45539. int rowStart = firstSelected->getRowNumberInTree();
  45540. int rowEnd = lastSelected->getRowNumberInTree();
  45541. if (rowStart > rowEnd)
  45542. swapVariables (rowStart, rowEnd);
  45543. int ourRow = item->getRowNumberInTree();
  45544. int otherEnd = ourRow < rowEnd ? rowStart : rowEnd;
  45545. if (ourRow > otherEnd)
  45546. swapVariables (ourRow, otherEnd);
  45547. for (int i = ourRow; i <= otherEnd; ++i)
  45548. owner.getItemOnRow (i)->setSelected (true, false);
  45549. }
  45550. else
  45551. {
  45552. const bool cmd = modifiers.isCommandDown();
  45553. item->setSelected ((! cmd) || ! item->isSelected(), ! cmd);
  45554. }
  45555. }
  45556. bool containsItem (TreeViewItem* const item) const
  45557. {
  45558. for (int i = rowComponentItems.size(); --i >= 0;)
  45559. if (rowComponentItems.getUnchecked(i) == item)
  45560. return true;
  45561. return false;
  45562. }
  45563. static bool isMouseDraggingInChildCompOf (Component* const comp)
  45564. {
  45565. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  45566. {
  45567. MouseInputSource* const source = Desktop::getInstance().getMouseSource(i);
  45568. if (source->isDragging())
  45569. {
  45570. Component* const underMouse = source->getComponentUnderMouse();
  45571. if (underMouse != 0 && (comp == underMouse || comp->isParentOf (underMouse)))
  45572. return true;
  45573. }
  45574. }
  45575. return false;
  45576. }
  45577. TreeViewContentComponent (const TreeViewContentComponent&);
  45578. TreeViewContentComponent& operator= (const TreeViewContentComponent&);
  45579. };
  45580. class TreeView::TreeViewport : public Viewport
  45581. {
  45582. public:
  45583. TreeViewport() throw() : lastX (-1) {}
  45584. ~TreeViewport() throw() {}
  45585. void updateComponents (const bool triggerResize = false)
  45586. {
  45587. TreeViewContentComponent* const tvc = static_cast <TreeViewContentComponent*> (getViewedComponent());
  45588. if (tvc != 0)
  45589. {
  45590. if (triggerResize)
  45591. tvc->resized();
  45592. else
  45593. tvc->updateComponents();
  45594. }
  45595. repaint();
  45596. }
  45597. void visibleAreaChanged (int x, int, int, int)
  45598. {
  45599. const bool hasScrolledSideways = (x != lastX);
  45600. lastX = x;
  45601. updateComponents (hasScrolledSideways);
  45602. }
  45603. juce_UseDebuggingNewOperator
  45604. private:
  45605. int lastX;
  45606. TreeViewport (const TreeViewport&);
  45607. TreeViewport& operator= (const TreeViewport&);
  45608. };
  45609. TreeView::TreeView (const String& componentName)
  45610. : Component (componentName),
  45611. rootItem (0),
  45612. indentSize (24),
  45613. defaultOpenness (false),
  45614. needsRecalculating (true),
  45615. rootItemVisible (true),
  45616. multiSelectEnabled (false),
  45617. openCloseButtonsVisible (true)
  45618. {
  45619. addAndMakeVisible (viewport = new TreeViewport());
  45620. viewport->setViewedComponent (new TreeViewContentComponent (*this));
  45621. viewport->setWantsKeyboardFocus (false);
  45622. setWantsKeyboardFocus (true);
  45623. }
  45624. TreeView::~TreeView()
  45625. {
  45626. if (rootItem != 0)
  45627. rootItem->setOwnerView (0);
  45628. }
  45629. void TreeView::setRootItem (TreeViewItem* const newRootItem)
  45630. {
  45631. if (rootItem != newRootItem)
  45632. {
  45633. if (newRootItem != 0)
  45634. {
  45635. jassert (newRootItem->ownerView == 0); // can't use a tree item in more than one tree at once..
  45636. if (newRootItem->ownerView != 0)
  45637. newRootItem->ownerView->setRootItem (0);
  45638. }
  45639. if (rootItem != 0)
  45640. rootItem->setOwnerView (0);
  45641. rootItem = newRootItem;
  45642. if (newRootItem != 0)
  45643. newRootItem->setOwnerView (this);
  45644. needsRecalculating = true;
  45645. handleAsyncUpdate();
  45646. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  45647. {
  45648. rootItem->setOpen (false); // force a re-open
  45649. rootItem->setOpen (true);
  45650. }
  45651. }
  45652. }
  45653. void TreeView::deleteRootItem()
  45654. {
  45655. const ScopedPointer <TreeViewItem> deleter (rootItem);
  45656. setRootItem (0);
  45657. }
  45658. void TreeView::setRootItemVisible (const bool shouldBeVisible)
  45659. {
  45660. rootItemVisible = shouldBeVisible;
  45661. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  45662. {
  45663. rootItem->setOpen (false); // force a re-open
  45664. rootItem->setOpen (true);
  45665. }
  45666. itemsChanged();
  45667. }
  45668. void TreeView::colourChanged()
  45669. {
  45670. setOpaque (findColour (backgroundColourId).isOpaque());
  45671. repaint();
  45672. }
  45673. void TreeView::setIndentSize (const int newIndentSize)
  45674. {
  45675. if (indentSize != newIndentSize)
  45676. {
  45677. indentSize = newIndentSize;
  45678. resized();
  45679. }
  45680. }
  45681. void TreeView::setDefaultOpenness (const bool isOpenByDefault)
  45682. {
  45683. if (defaultOpenness != isOpenByDefault)
  45684. {
  45685. defaultOpenness = isOpenByDefault;
  45686. itemsChanged();
  45687. }
  45688. }
  45689. void TreeView::setMultiSelectEnabled (const bool canMultiSelect)
  45690. {
  45691. multiSelectEnabled = canMultiSelect;
  45692. }
  45693. void TreeView::setOpenCloseButtonsVisible (const bool shouldBeVisible)
  45694. {
  45695. if (openCloseButtonsVisible != shouldBeVisible)
  45696. {
  45697. openCloseButtonsVisible = shouldBeVisible;
  45698. itemsChanged();
  45699. }
  45700. }
  45701. Viewport* TreeView::getViewport() const throw()
  45702. {
  45703. return viewport;
  45704. }
  45705. void TreeView::clearSelectedItems()
  45706. {
  45707. if (rootItem != 0)
  45708. rootItem->deselectAllRecursively();
  45709. }
  45710. int TreeView::getNumSelectedItems() const throw()
  45711. {
  45712. return (rootItem != 0) ? rootItem->countSelectedItemsRecursively() : 0;
  45713. }
  45714. TreeViewItem* TreeView::getSelectedItem (const int index) const throw()
  45715. {
  45716. return (rootItem != 0) ? rootItem->getSelectedItemWithIndex (index) : 0;
  45717. }
  45718. int TreeView::getNumRowsInTree() const
  45719. {
  45720. if (rootItem != 0)
  45721. return rootItem->getNumRows() - (rootItemVisible ? 0 : 1);
  45722. return 0;
  45723. }
  45724. TreeViewItem* TreeView::getItemOnRow (int index) const
  45725. {
  45726. if (! rootItemVisible)
  45727. ++index;
  45728. if (rootItem != 0 && index >= 0)
  45729. return rootItem->getItemOnRow (index);
  45730. return 0;
  45731. }
  45732. TreeViewItem* TreeView::getItemAt (int y) const throw()
  45733. {
  45734. TreeViewContentComponent* const tc = static_cast <TreeViewContentComponent*> (viewport->getViewedComponent());
  45735. Rectangle<int> pos;
  45736. return tc->findItemAt (relativePositionToOtherComponent (tc, Point<int> (0, y)).getY(), pos);
  45737. }
  45738. TreeViewItem* TreeView::findItemFromIdentifierString (const String& identifierString) const
  45739. {
  45740. if (rootItem == 0)
  45741. return 0;
  45742. return rootItem->findItemFromIdentifierString (identifierString);
  45743. }
  45744. XmlElement* TreeView::getOpennessState (const bool alsoIncludeScrollPosition) const
  45745. {
  45746. XmlElement* e = 0;
  45747. if (rootItem != 0)
  45748. {
  45749. e = rootItem->getOpennessState();
  45750. if (e != 0 && alsoIncludeScrollPosition)
  45751. e->setAttribute ("scrollPos", viewport->getViewPositionY());
  45752. }
  45753. return e;
  45754. }
  45755. void TreeView::restoreOpennessState (const XmlElement& newState)
  45756. {
  45757. if (rootItem != 0)
  45758. {
  45759. rootItem->restoreOpennessState (newState);
  45760. if (newState.hasAttribute ("scrollPos"))
  45761. viewport->setViewPosition (viewport->getViewPositionX(),
  45762. newState.getIntAttribute ("scrollPos"));
  45763. }
  45764. }
  45765. void TreeView::paint (Graphics& g)
  45766. {
  45767. g.fillAll (findColour (backgroundColourId));
  45768. }
  45769. void TreeView::resized()
  45770. {
  45771. viewport->setBounds (getLocalBounds());
  45772. itemsChanged();
  45773. handleAsyncUpdate();
  45774. }
  45775. void TreeView::enablementChanged()
  45776. {
  45777. repaint();
  45778. }
  45779. void TreeView::moveSelectedRow (int delta)
  45780. {
  45781. if (delta == 0)
  45782. return;
  45783. int rowSelected = 0;
  45784. TreeViewItem* const firstSelected = getSelectedItem (0);
  45785. if (firstSelected != 0)
  45786. rowSelected = firstSelected->getRowNumberInTree();
  45787. rowSelected = jlimit (0, getNumRowsInTree() - 1, rowSelected + delta);
  45788. for (;;)
  45789. {
  45790. TreeViewItem* item = getItemOnRow (rowSelected);
  45791. if (item != 0)
  45792. {
  45793. if (! item->canBeSelected())
  45794. {
  45795. // if the row we want to highlight doesn't allow it, try skipping
  45796. // to the next item..
  45797. const int nextRowToTry = jlimit (0, getNumRowsInTree() - 1,
  45798. rowSelected + (delta < 0 ? -1 : 1));
  45799. if (rowSelected != nextRowToTry)
  45800. {
  45801. rowSelected = nextRowToTry;
  45802. continue;
  45803. }
  45804. else
  45805. {
  45806. break;
  45807. }
  45808. }
  45809. item->setSelected (true, true);
  45810. scrollToKeepItemVisible (item);
  45811. }
  45812. break;
  45813. }
  45814. }
  45815. void TreeView::scrollToKeepItemVisible (TreeViewItem* item)
  45816. {
  45817. if (item != 0 && item->ownerView == this)
  45818. {
  45819. handleAsyncUpdate();
  45820. item = item->getDeepestOpenParentItem();
  45821. int y = item->y;
  45822. int viewTop = viewport->getViewPositionY();
  45823. if (y < viewTop)
  45824. {
  45825. viewport->setViewPosition (viewport->getViewPositionX(), y);
  45826. }
  45827. else if (y + item->itemHeight > viewTop + viewport->getViewHeight())
  45828. {
  45829. viewport->setViewPosition (viewport->getViewPositionX(),
  45830. (y + item->itemHeight) - viewport->getViewHeight());
  45831. }
  45832. }
  45833. }
  45834. bool TreeView::keyPressed (const KeyPress& key)
  45835. {
  45836. if (key.isKeyCode (KeyPress::upKey))
  45837. {
  45838. moveSelectedRow (-1);
  45839. }
  45840. else if (key.isKeyCode (KeyPress::downKey))
  45841. {
  45842. moveSelectedRow (1);
  45843. }
  45844. else if (key.isKeyCode (KeyPress::pageDownKey) || key.isKeyCode (KeyPress::pageUpKey))
  45845. {
  45846. if (rootItem != 0)
  45847. {
  45848. int rowsOnScreen = getHeight() / jmax (1, rootItem->itemHeight);
  45849. if (key.isKeyCode (KeyPress::pageUpKey))
  45850. rowsOnScreen = -rowsOnScreen;
  45851. moveSelectedRow (rowsOnScreen);
  45852. }
  45853. }
  45854. else if (key.isKeyCode (KeyPress::homeKey))
  45855. {
  45856. moveSelectedRow (-0x3fffffff);
  45857. }
  45858. else if (key.isKeyCode (KeyPress::endKey))
  45859. {
  45860. moveSelectedRow (0x3fffffff);
  45861. }
  45862. else if (key.isKeyCode (KeyPress::returnKey))
  45863. {
  45864. TreeViewItem* const firstSelected = getSelectedItem (0);
  45865. if (firstSelected != 0)
  45866. firstSelected->setOpen (! firstSelected->isOpen());
  45867. }
  45868. else if (key.isKeyCode (KeyPress::leftKey))
  45869. {
  45870. TreeViewItem* const firstSelected = getSelectedItem (0);
  45871. if (firstSelected != 0)
  45872. {
  45873. if (firstSelected->isOpen())
  45874. {
  45875. firstSelected->setOpen (false);
  45876. }
  45877. else
  45878. {
  45879. TreeViewItem* parent = firstSelected->parentItem;
  45880. if ((! rootItemVisible) && parent == rootItem)
  45881. parent = 0;
  45882. if (parent != 0)
  45883. {
  45884. parent->setSelected (true, true);
  45885. scrollToKeepItemVisible (parent);
  45886. }
  45887. }
  45888. }
  45889. }
  45890. else if (key.isKeyCode (KeyPress::rightKey))
  45891. {
  45892. TreeViewItem* const firstSelected = getSelectedItem (0);
  45893. if (firstSelected != 0)
  45894. {
  45895. if (firstSelected->isOpen() || ! firstSelected->mightContainSubItems())
  45896. moveSelectedRow (1);
  45897. else
  45898. firstSelected->setOpen (true);
  45899. }
  45900. }
  45901. else
  45902. {
  45903. return false;
  45904. }
  45905. return true;
  45906. }
  45907. void TreeView::itemsChanged() throw()
  45908. {
  45909. needsRecalculating = true;
  45910. repaint();
  45911. triggerAsyncUpdate();
  45912. }
  45913. void TreeView::handleAsyncUpdate()
  45914. {
  45915. if (needsRecalculating)
  45916. {
  45917. needsRecalculating = false;
  45918. const ScopedLock sl (nodeAlterationLock);
  45919. if (rootItem != 0)
  45920. rootItem->updatePositions (rootItemVisible ? 0 : -rootItem->itemHeight);
  45921. viewport->updateComponents();
  45922. if (rootItem != 0)
  45923. {
  45924. viewport->getViewedComponent()
  45925. ->setSize (jmax (viewport->getMaximumVisibleWidth(), rootItem->totalWidth),
  45926. rootItem->totalHeight - (rootItemVisible ? 0 : rootItem->itemHeight));
  45927. }
  45928. else
  45929. {
  45930. viewport->getViewedComponent()->setSize (0, 0);
  45931. }
  45932. }
  45933. }
  45934. class TreeView::InsertPointHighlight : public Component
  45935. {
  45936. public:
  45937. InsertPointHighlight()
  45938. : lastItem (0)
  45939. {
  45940. setSize (100, 12);
  45941. setAlwaysOnTop (true);
  45942. setInterceptsMouseClicks (false, false);
  45943. }
  45944. ~InsertPointHighlight() {}
  45945. void setTargetPosition (TreeViewItem* const item, int insertIndex, const int x, const int y, const int width) throw()
  45946. {
  45947. lastItem = item;
  45948. lastIndex = insertIndex;
  45949. const int offset = getHeight() / 2;
  45950. setBounds (x - offset, y - offset, width - (x - offset), getHeight());
  45951. }
  45952. void paint (Graphics& g)
  45953. {
  45954. Path p;
  45955. const float h = (float) getHeight();
  45956. p.addEllipse (2.0f, 2.0f, h - 4.0f, h - 4.0f);
  45957. p.startNewSubPath (h - 2.0f, h / 2.0f);
  45958. p.lineTo ((float) getWidth(), h / 2.0f);
  45959. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  45960. g.strokePath (p, PathStrokeType (2.0f));
  45961. }
  45962. TreeViewItem* lastItem;
  45963. int lastIndex;
  45964. private:
  45965. InsertPointHighlight (const InsertPointHighlight&);
  45966. InsertPointHighlight& operator= (const InsertPointHighlight&);
  45967. };
  45968. class TreeView::TargetGroupHighlight : public Component
  45969. {
  45970. public:
  45971. TargetGroupHighlight()
  45972. {
  45973. setAlwaysOnTop (true);
  45974. setInterceptsMouseClicks (false, false);
  45975. }
  45976. ~TargetGroupHighlight() {}
  45977. void setTargetPosition (TreeViewItem* const item) throw()
  45978. {
  45979. Rectangle<int> r (item->getItemPosition (true));
  45980. r.setHeight (item->getItemHeight());
  45981. setBounds (r);
  45982. }
  45983. void paint (Graphics& g)
  45984. {
  45985. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  45986. g.drawRoundedRectangle (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 3.0f, 2.0f);
  45987. }
  45988. private:
  45989. TargetGroupHighlight (const TargetGroupHighlight&);
  45990. TargetGroupHighlight& operator= (const TargetGroupHighlight&);
  45991. };
  45992. void TreeView::showDragHighlight (TreeViewItem* item, int insertIndex, int x, int y) throw()
  45993. {
  45994. beginDragAutoRepeat (100);
  45995. if (dragInsertPointHighlight == 0)
  45996. {
  45997. addAndMakeVisible (dragInsertPointHighlight = new InsertPointHighlight());
  45998. addAndMakeVisible (dragTargetGroupHighlight = new TargetGroupHighlight());
  45999. }
  46000. dragInsertPointHighlight->setTargetPosition (item, insertIndex, x, y, viewport->getViewWidth());
  46001. dragTargetGroupHighlight->setTargetPosition (item);
  46002. }
  46003. void TreeView::hideDragHighlight() throw()
  46004. {
  46005. dragInsertPointHighlight = 0;
  46006. dragTargetGroupHighlight = 0;
  46007. }
  46008. TreeViewItem* TreeView::getInsertPosition (int& x, int& y, int& insertIndex,
  46009. const StringArray& files, const String& sourceDescription,
  46010. Component* sourceComponent) const throw()
  46011. {
  46012. insertIndex = 0;
  46013. TreeViewItem* item = getItemAt (y);
  46014. if (item == 0)
  46015. return 0;
  46016. Rectangle<int> itemPos (item->getItemPosition (true));
  46017. insertIndex = item->getIndexInParent();
  46018. const int oldY = y;
  46019. y = itemPos.getY();
  46020. if (item->getNumSubItems() == 0 || ! item->isOpen())
  46021. {
  46022. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  46023. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  46024. {
  46025. // Check if we're trying to drag into an empty group item..
  46026. if (oldY > itemPos.getY() + itemPos.getHeight() / 4
  46027. && oldY < itemPos.getBottom() - itemPos.getHeight() / 4)
  46028. {
  46029. insertIndex = 0;
  46030. x = itemPos.getX() + getIndentSize();
  46031. y = itemPos.getBottom();
  46032. return item;
  46033. }
  46034. }
  46035. }
  46036. if (oldY > itemPos.getCentreY())
  46037. {
  46038. y += item->getItemHeight();
  46039. while (item->isLastOfSiblings() && item->parentItem != 0
  46040. && item->parentItem->parentItem != 0)
  46041. {
  46042. if (x > itemPos.getX())
  46043. break;
  46044. item = item->parentItem;
  46045. itemPos = item->getItemPosition (true);
  46046. insertIndex = item->getIndexInParent();
  46047. }
  46048. ++insertIndex;
  46049. }
  46050. x = itemPos.getX();
  46051. return item->parentItem;
  46052. }
  46053. void TreeView::handleDrag (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  46054. {
  46055. const bool scrolled = viewport->autoScroll (x, y, 20, 10);
  46056. int insertIndex;
  46057. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  46058. if (item != 0)
  46059. {
  46060. if (scrolled || dragInsertPointHighlight == 0
  46061. || dragInsertPointHighlight->lastItem != item
  46062. || dragInsertPointHighlight->lastIndex != insertIndex)
  46063. {
  46064. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  46065. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  46066. showDragHighlight (item, insertIndex, x, y);
  46067. else
  46068. hideDragHighlight();
  46069. }
  46070. }
  46071. else
  46072. {
  46073. hideDragHighlight();
  46074. }
  46075. }
  46076. void TreeView::handleDrop (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  46077. {
  46078. hideDragHighlight();
  46079. int insertIndex;
  46080. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  46081. if (item != 0)
  46082. {
  46083. if (files.size() > 0)
  46084. {
  46085. if (item->isInterestedInFileDrag (files))
  46086. item->filesDropped (files, insertIndex);
  46087. }
  46088. else
  46089. {
  46090. if (item->isInterestedInDragSource (sourceDescription, sourceComponent))
  46091. item->itemDropped (sourceDescription, sourceComponent, insertIndex);
  46092. }
  46093. }
  46094. }
  46095. bool TreeView::isInterestedInFileDrag (const StringArray&)
  46096. {
  46097. return true;
  46098. }
  46099. void TreeView::fileDragEnter (const StringArray& files, int x, int y)
  46100. {
  46101. fileDragMove (files, x, y);
  46102. }
  46103. void TreeView::fileDragMove (const StringArray& files, int x, int y)
  46104. {
  46105. handleDrag (files, String::empty, 0, x, y);
  46106. }
  46107. void TreeView::fileDragExit (const StringArray&)
  46108. {
  46109. hideDragHighlight();
  46110. }
  46111. void TreeView::filesDropped (const StringArray& files, int x, int y)
  46112. {
  46113. handleDrop (files, String::empty, 0, x, y);
  46114. }
  46115. bool TreeView::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  46116. {
  46117. return true;
  46118. }
  46119. void TreeView::itemDragEnter (const String& sourceDescription, Component* sourceComponent, int x, int y)
  46120. {
  46121. itemDragMove (sourceDescription, sourceComponent, x, y);
  46122. }
  46123. void TreeView::itemDragMove (const String& sourceDescription, Component* sourceComponent, int x, int y)
  46124. {
  46125. handleDrag (StringArray(), sourceDescription, sourceComponent, x, y);
  46126. }
  46127. void TreeView::itemDragExit (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  46128. {
  46129. hideDragHighlight();
  46130. }
  46131. void TreeView::itemDropped (const String& sourceDescription, Component* sourceComponent, int x, int y)
  46132. {
  46133. handleDrop (StringArray(), sourceDescription, sourceComponent, x, y);
  46134. }
  46135. enum TreeViewOpenness
  46136. {
  46137. opennessDefault = 0,
  46138. opennessClosed = 1,
  46139. opennessOpen = 2
  46140. };
  46141. TreeViewItem::TreeViewItem()
  46142. : ownerView (0),
  46143. parentItem (0),
  46144. y (0),
  46145. itemHeight (0),
  46146. totalHeight (0),
  46147. selected (false),
  46148. redrawNeeded (true),
  46149. drawLinesInside (true),
  46150. drawsInLeftMargin (false),
  46151. openness (opennessDefault)
  46152. {
  46153. static int nextUID = 0;
  46154. uid = nextUID++;
  46155. }
  46156. TreeViewItem::~TreeViewItem()
  46157. {
  46158. }
  46159. const String TreeViewItem::getUniqueName() const
  46160. {
  46161. return String::empty;
  46162. }
  46163. void TreeViewItem::itemOpennessChanged (bool)
  46164. {
  46165. }
  46166. int TreeViewItem::getNumSubItems() const throw()
  46167. {
  46168. return subItems.size();
  46169. }
  46170. TreeViewItem* TreeViewItem::getSubItem (const int index) const throw()
  46171. {
  46172. return subItems [index];
  46173. }
  46174. void TreeViewItem::clearSubItems()
  46175. {
  46176. if (subItems.size() > 0)
  46177. {
  46178. if (ownerView != 0)
  46179. {
  46180. const ScopedLock sl (ownerView->nodeAlterationLock);
  46181. subItems.clear();
  46182. treeHasChanged();
  46183. }
  46184. else
  46185. {
  46186. subItems.clear();
  46187. }
  46188. }
  46189. }
  46190. void TreeViewItem::addSubItem (TreeViewItem* const newItem, const int insertPosition)
  46191. {
  46192. if (newItem != 0)
  46193. {
  46194. newItem->parentItem = this;
  46195. newItem->setOwnerView (ownerView);
  46196. newItem->y = 0;
  46197. newItem->itemHeight = newItem->getItemHeight();
  46198. newItem->totalHeight = 0;
  46199. newItem->itemWidth = newItem->getItemWidth();
  46200. newItem->totalWidth = 0;
  46201. if (ownerView != 0)
  46202. {
  46203. const ScopedLock sl (ownerView->nodeAlterationLock);
  46204. subItems.insert (insertPosition, newItem);
  46205. treeHasChanged();
  46206. if (newItem->isOpen())
  46207. newItem->itemOpennessChanged (true);
  46208. }
  46209. else
  46210. {
  46211. subItems.insert (insertPosition, newItem);
  46212. if (newItem->isOpen())
  46213. newItem->itemOpennessChanged (true);
  46214. }
  46215. }
  46216. }
  46217. void TreeViewItem::removeSubItem (const int index, const bool deleteItem)
  46218. {
  46219. if (ownerView != 0)
  46220. {
  46221. const ScopedLock sl (ownerView->nodeAlterationLock);
  46222. if (((unsigned int) index) < (unsigned int) subItems.size())
  46223. {
  46224. subItems.remove (index, deleteItem);
  46225. treeHasChanged();
  46226. }
  46227. }
  46228. else
  46229. {
  46230. subItems.remove (index, deleteItem);
  46231. }
  46232. }
  46233. bool TreeViewItem::isOpen() const throw()
  46234. {
  46235. if (openness == opennessDefault)
  46236. return ownerView != 0 && ownerView->defaultOpenness;
  46237. else
  46238. return openness == opennessOpen;
  46239. }
  46240. void TreeViewItem::setOpen (const bool shouldBeOpen)
  46241. {
  46242. if (isOpen() != shouldBeOpen)
  46243. {
  46244. openness = shouldBeOpen ? opennessOpen
  46245. : opennessClosed;
  46246. treeHasChanged();
  46247. itemOpennessChanged (isOpen());
  46248. }
  46249. }
  46250. bool TreeViewItem::isSelected() const throw()
  46251. {
  46252. return selected;
  46253. }
  46254. void TreeViewItem::deselectAllRecursively()
  46255. {
  46256. setSelected (false, false);
  46257. for (int i = 0; i < subItems.size(); ++i)
  46258. subItems.getUnchecked(i)->deselectAllRecursively();
  46259. }
  46260. void TreeViewItem::setSelected (const bool shouldBeSelected,
  46261. const bool deselectOtherItemsFirst)
  46262. {
  46263. if (shouldBeSelected && ! canBeSelected())
  46264. return;
  46265. if (deselectOtherItemsFirst)
  46266. getTopLevelItem()->deselectAllRecursively();
  46267. if (shouldBeSelected != selected)
  46268. {
  46269. selected = shouldBeSelected;
  46270. if (ownerView != 0)
  46271. ownerView->repaint();
  46272. itemSelectionChanged (shouldBeSelected);
  46273. }
  46274. }
  46275. void TreeViewItem::paintItem (Graphics&, int, int)
  46276. {
  46277. }
  46278. void TreeViewItem::paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver)
  46279. {
  46280. ownerView->getLookAndFeel()
  46281. .drawTreeviewPlusMinusBox (g, 0, 0, width, height, ! isOpen(), isMouseOver);
  46282. }
  46283. void TreeViewItem::itemClicked (const MouseEvent&)
  46284. {
  46285. }
  46286. void TreeViewItem::itemDoubleClicked (const MouseEvent&)
  46287. {
  46288. if (mightContainSubItems())
  46289. setOpen (! isOpen());
  46290. }
  46291. void TreeViewItem::itemSelectionChanged (bool)
  46292. {
  46293. }
  46294. const String TreeViewItem::getTooltip()
  46295. {
  46296. return String::empty;
  46297. }
  46298. const String TreeViewItem::getDragSourceDescription()
  46299. {
  46300. return String::empty;
  46301. }
  46302. bool TreeViewItem::isInterestedInFileDrag (const StringArray&)
  46303. {
  46304. return false;
  46305. }
  46306. void TreeViewItem::filesDropped (const StringArray& /*files*/, int /*insertIndex*/)
  46307. {
  46308. }
  46309. bool TreeViewItem::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  46310. {
  46311. return false;
  46312. }
  46313. void TreeViewItem::itemDropped (const String& /*sourceDescription*/, Component* /*sourceComponent*/, int /*insertIndex*/)
  46314. {
  46315. }
  46316. const Rectangle<int> TreeViewItem::getItemPosition (const bool relativeToTreeViewTopLeft) const throw()
  46317. {
  46318. const int indentX = getIndentX();
  46319. int width = itemWidth;
  46320. if (ownerView != 0 && width < 0)
  46321. width = ownerView->viewport->getViewWidth() - indentX;
  46322. Rectangle<int> r (indentX, y, jmax (0, width), totalHeight);
  46323. if (relativeToTreeViewTopLeft)
  46324. r -= ownerView->viewport->getViewPosition();
  46325. return r;
  46326. }
  46327. void TreeViewItem::treeHasChanged() const throw()
  46328. {
  46329. if (ownerView != 0)
  46330. ownerView->itemsChanged();
  46331. }
  46332. void TreeViewItem::repaintItem() const
  46333. {
  46334. if (ownerView != 0 && areAllParentsOpen())
  46335. {
  46336. Rectangle<int> r (getItemPosition (true));
  46337. r.setLeft (0);
  46338. ownerView->viewport->repaint (r);
  46339. }
  46340. }
  46341. bool TreeViewItem::areAllParentsOpen() const throw()
  46342. {
  46343. return parentItem == 0
  46344. || (parentItem->isOpen() && parentItem->areAllParentsOpen());
  46345. }
  46346. void TreeViewItem::updatePositions (int newY)
  46347. {
  46348. y = newY;
  46349. itemHeight = getItemHeight();
  46350. totalHeight = itemHeight;
  46351. itemWidth = getItemWidth();
  46352. totalWidth = jmax (itemWidth, 0) + getIndentX();
  46353. if (isOpen())
  46354. {
  46355. newY += totalHeight;
  46356. for (int i = 0; i < subItems.size(); ++i)
  46357. {
  46358. TreeViewItem* const ti = subItems.getUnchecked(i);
  46359. ti->updatePositions (newY);
  46360. newY += ti->totalHeight;
  46361. totalHeight += ti->totalHeight;
  46362. totalWidth = jmax (totalWidth, ti->totalWidth);
  46363. }
  46364. }
  46365. }
  46366. TreeViewItem* TreeViewItem::getDeepestOpenParentItem() throw()
  46367. {
  46368. TreeViewItem* result = this;
  46369. TreeViewItem* item = this;
  46370. while (item->parentItem != 0)
  46371. {
  46372. item = item->parentItem;
  46373. if (! item->isOpen())
  46374. result = item;
  46375. }
  46376. return result;
  46377. }
  46378. void TreeViewItem::setOwnerView (TreeView* const newOwner) throw()
  46379. {
  46380. ownerView = newOwner;
  46381. for (int i = subItems.size(); --i >= 0;)
  46382. subItems.getUnchecked(i)->setOwnerView (newOwner);
  46383. }
  46384. int TreeViewItem::getIndentX() const throw()
  46385. {
  46386. const int indentWidth = ownerView->getIndentSize();
  46387. int x = ownerView->rootItemVisible ? indentWidth : 0;
  46388. if (! ownerView->openCloseButtonsVisible)
  46389. x -= indentWidth;
  46390. TreeViewItem* p = parentItem;
  46391. while (p != 0)
  46392. {
  46393. x += indentWidth;
  46394. p = p->parentItem;
  46395. }
  46396. return x;
  46397. }
  46398. void TreeViewItem::setDrawsInLeftMargin (bool canDrawInLeftMargin) throw()
  46399. {
  46400. drawsInLeftMargin = canDrawInLeftMargin;
  46401. }
  46402. void TreeViewItem::paintRecursively (Graphics& g, int width)
  46403. {
  46404. jassert (ownerView != 0);
  46405. if (ownerView == 0)
  46406. return;
  46407. const int indent = getIndentX();
  46408. const int itemW = itemWidth < 0 ? width - indent : itemWidth;
  46409. {
  46410. g.saveState();
  46411. g.setOrigin (indent, 0);
  46412. if (g.reduceClipRegion (drawsInLeftMargin ? -indent : 0, 0,
  46413. drawsInLeftMargin ? itemW + indent : itemW, itemHeight))
  46414. paintItem (g, itemW, itemHeight);
  46415. g.restoreState();
  46416. }
  46417. g.setColour (ownerView->findColour (TreeView::linesColourId));
  46418. const float halfH = itemHeight * 0.5f;
  46419. int depth = 0;
  46420. TreeViewItem* p = parentItem;
  46421. while (p != 0)
  46422. {
  46423. ++depth;
  46424. p = p->parentItem;
  46425. }
  46426. if (! ownerView->rootItemVisible)
  46427. --depth;
  46428. const int indentWidth = ownerView->getIndentSize();
  46429. if (depth >= 0 && ownerView->openCloseButtonsVisible)
  46430. {
  46431. float x = (depth + 0.5f) * indentWidth;
  46432. if (depth >= 0)
  46433. {
  46434. if (parentItem != 0 && parentItem->drawLinesInside)
  46435. g.drawLine (x, 0, x, isLastOfSiblings() ? halfH : (float) itemHeight);
  46436. if ((parentItem != 0 && parentItem->drawLinesInside)
  46437. || (parentItem == 0 && drawLinesInside))
  46438. g.drawLine (x, halfH, x + indentWidth / 2, halfH);
  46439. }
  46440. p = parentItem;
  46441. int d = depth;
  46442. while (p != 0 && --d >= 0)
  46443. {
  46444. x -= (float) indentWidth;
  46445. if ((p->parentItem == 0 || p->parentItem->drawLinesInside)
  46446. && ! p->isLastOfSiblings())
  46447. {
  46448. g.drawLine (x, 0, x, (float) itemHeight);
  46449. }
  46450. p = p->parentItem;
  46451. }
  46452. if (mightContainSubItems())
  46453. {
  46454. g.saveState();
  46455. g.setOrigin (depth * indentWidth, 0);
  46456. g.reduceClipRegion (0, 0, indentWidth, itemHeight);
  46457. paintOpenCloseButton (g, indentWidth, itemHeight,
  46458. static_cast <TreeViewContentComponent*> (ownerView->viewport->getViewedComponent())
  46459. ->isMouseOverButton (this));
  46460. g.restoreState();
  46461. }
  46462. }
  46463. if (isOpen())
  46464. {
  46465. const Rectangle<int> clip (g.getClipBounds());
  46466. for (int i = 0; i < subItems.size(); ++i)
  46467. {
  46468. TreeViewItem* const ti = subItems.getUnchecked(i);
  46469. const int relY = ti->y - y;
  46470. if (relY >= clip.getBottom())
  46471. break;
  46472. if (relY + ti->totalHeight >= clip.getY())
  46473. {
  46474. g.saveState();
  46475. g.setOrigin (0, relY);
  46476. if (g.reduceClipRegion (0, 0, width, ti->totalHeight))
  46477. ti->paintRecursively (g, width);
  46478. g.restoreState();
  46479. }
  46480. }
  46481. }
  46482. }
  46483. bool TreeViewItem::isLastOfSiblings() const throw()
  46484. {
  46485. return parentItem == 0
  46486. || parentItem->subItems.getLast() == this;
  46487. }
  46488. int TreeViewItem::getIndexInParent() const throw()
  46489. {
  46490. if (parentItem == 0)
  46491. return 0;
  46492. return parentItem->subItems.indexOf (this);
  46493. }
  46494. TreeViewItem* TreeViewItem::getTopLevelItem() throw()
  46495. {
  46496. return (parentItem == 0) ? this
  46497. : parentItem->getTopLevelItem();
  46498. }
  46499. int TreeViewItem::getNumRows() const throw()
  46500. {
  46501. int num = 1;
  46502. if (isOpen())
  46503. {
  46504. for (int i = subItems.size(); --i >= 0;)
  46505. num += subItems.getUnchecked(i)->getNumRows();
  46506. }
  46507. return num;
  46508. }
  46509. TreeViewItem* TreeViewItem::getItemOnRow (int index) throw()
  46510. {
  46511. if (index == 0)
  46512. return this;
  46513. if (index > 0 && isOpen())
  46514. {
  46515. --index;
  46516. for (int i = 0; i < subItems.size(); ++i)
  46517. {
  46518. TreeViewItem* const item = subItems.getUnchecked(i);
  46519. if (index == 0)
  46520. return item;
  46521. const int numRows = item->getNumRows();
  46522. if (numRows > index)
  46523. return item->getItemOnRow (index);
  46524. index -= numRows;
  46525. }
  46526. }
  46527. return 0;
  46528. }
  46529. TreeViewItem* TreeViewItem::findItemRecursively (int targetY) throw()
  46530. {
  46531. if (((unsigned int) targetY) < (unsigned int) totalHeight)
  46532. {
  46533. const int h = itemHeight;
  46534. if (targetY < h)
  46535. return this;
  46536. if (isOpen())
  46537. {
  46538. targetY -= h;
  46539. for (int i = 0; i < subItems.size(); ++i)
  46540. {
  46541. TreeViewItem* const ti = subItems.getUnchecked(i);
  46542. if (targetY < ti->totalHeight)
  46543. return ti->findItemRecursively (targetY);
  46544. targetY -= ti->totalHeight;
  46545. }
  46546. }
  46547. }
  46548. return 0;
  46549. }
  46550. int TreeViewItem::countSelectedItemsRecursively() const throw()
  46551. {
  46552. int total = 0;
  46553. if (isSelected())
  46554. ++total;
  46555. for (int i = subItems.size(); --i >= 0;)
  46556. total += subItems.getUnchecked(i)->countSelectedItemsRecursively();
  46557. return total;
  46558. }
  46559. TreeViewItem* TreeViewItem::getSelectedItemWithIndex (int index) throw()
  46560. {
  46561. if (isSelected())
  46562. {
  46563. if (index == 0)
  46564. return this;
  46565. --index;
  46566. }
  46567. if (index >= 0)
  46568. {
  46569. for (int i = 0; i < subItems.size(); ++i)
  46570. {
  46571. TreeViewItem* const item = subItems.getUnchecked(i);
  46572. TreeViewItem* const found = item->getSelectedItemWithIndex (index);
  46573. if (found != 0)
  46574. return found;
  46575. index -= item->countSelectedItemsRecursively();
  46576. }
  46577. }
  46578. return 0;
  46579. }
  46580. int TreeViewItem::getRowNumberInTree() const throw()
  46581. {
  46582. if (parentItem != 0 && ownerView != 0)
  46583. {
  46584. int n = 1 + parentItem->getRowNumberInTree();
  46585. int ourIndex = parentItem->subItems.indexOf (this);
  46586. jassert (ourIndex >= 0);
  46587. while (--ourIndex >= 0)
  46588. n += parentItem->subItems [ourIndex]->getNumRows();
  46589. if (parentItem->parentItem == 0
  46590. && ! ownerView->rootItemVisible)
  46591. --n;
  46592. return n;
  46593. }
  46594. else
  46595. {
  46596. return 0;
  46597. }
  46598. }
  46599. void TreeViewItem::setLinesDrawnForSubItems (const bool drawLines) throw()
  46600. {
  46601. drawLinesInside = drawLines;
  46602. }
  46603. TreeViewItem* TreeViewItem::getNextVisibleItem (const bool recurse) const throw()
  46604. {
  46605. if (recurse && isOpen() && subItems.size() > 0)
  46606. return subItems [0];
  46607. if (parentItem != 0)
  46608. {
  46609. const int nextIndex = parentItem->subItems.indexOf (this) + 1;
  46610. if (nextIndex >= parentItem->subItems.size())
  46611. return parentItem->getNextVisibleItem (false);
  46612. return parentItem->subItems [nextIndex];
  46613. }
  46614. return 0;
  46615. }
  46616. const String TreeViewItem::getItemIdentifierString() const
  46617. {
  46618. String s;
  46619. if (parentItem != 0)
  46620. s = parentItem->getItemIdentifierString();
  46621. return s + "/" + getUniqueName().replaceCharacter ('/', '\\');
  46622. }
  46623. TreeViewItem* TreeViewItem::findItemFromIdentifierString (const String& identifierString)
  46624. {
  46625. const String thisId (getUniqueName());
  46626. if (thisId == identifierString)
  46627. return this;
  46628. if (identifierString.startsWith (thisId + "/"))
  46629. {
  46630. const String remainingPath (identifierString.substring (thisId.length() + 1));
  46631. bool wasOpen = isOpen();
  46632. setOpen (true);
  46633. for (int i = subItems.size(); --i >= 0;)
  46634. {
  46635. TreeViewItem* item = subItems.getUnchecked(i)->findItemFromIdentifierString (remainingPath);
  46636. if (item != 0)
  46637. return item;
  46638. }
  46639. setOpen (wasOpen);
  46640. }
  46641. return 0;
  46642. }
  46643. void TreeViewItem::restoreOpennessState (const XmlElement& e) throw()
  46644. {
  46645. if (e.hasTagName ("CLOSED"))
  46646. {
  46647. setOpen (false);
  46648. }
  46649. else if (e.hasTagName ("OPEN"))
  46650. {
  46651. setOpen (true);
  46652. forEachXmlChildElement (e, n)
  46653. {
  46654. const String id (n->getStringAttribute ("id"));
  46655. for (int i = 0; i < subItems.size(); ++i)
  46656. {
  46657. TreeViewItem* const ti = subItems.getUnchecked(i);
  46658. if (ti->getUniqueName() == id)
  46659. {
  46660. ti->restoreOpennessState (*n);
  46661. break;
  46662. }
  46663. }
  46664. }
  46665. }
  46666. }
  46667. XmlElement* TreeViewItem::getOpennessState() const throw()
  46668. {
  46669. const String name (getUniqueName());
  46670. if (name.isNotEmpty())
  46671. {
  46672. XmlElement* e;
  46673. if (isOpen())
  46674. {
  46675. e = new XmlElement ("OPEN");
  46676. for (int i = 0; i < subItems.size(); ++i)
  46677. e->addChildElement (subItems.getUnchecked(i)->getOpennessState());
  46678. }
  46679. else
  46680. {
  46681. e = new XmlElement ("CLOSED");
  46682. }
  46683. e->setAttribute ("id", name);
  46684. return e;
  46685. }
  46686. else
  46687. {
  46688. // trying to save the openness for an element that has no name - this won't
  46689. // work because it needs the names to identify what to open.
  46690. jassertfalse;
  46691. }
  46692. return 0;
  46693. }
  46694. END_JUCE_NAMESPACE
  46695. /*** End of inlined file: juce_TreeView.cpp ***/
  46696. /*** Start of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  46697. BEGIN_JUCE_NAMESPACE
  46698. DirectoryContentsDisplayComponent::DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow)
  46699. : fileList (listToShow)
  46700. {
  46701. }
  46702. DirectoryContentsDisplayComponent::~DirectoryContentsDisplayComponent()
  46703. {
  46704. }
  46705. FileBrowserListener::~FileBrowserListener()
  46706. {
  46707. }
  46708. void DirectoryContentsDisplayComponent::addListener (FileBrowserListener* const listener)
  46709. {
  46710. listeners.add (listener);
  46711. }
  46712. void DirectoryContentsDisplayComponent::removeListener (FileBrowserListener* const listener)
  46713. {
  46714. listeners.remove (listener);
  46715. }
  46716. void DirectoryContentsDisplayComponent::sendSelectionChangeMessage()
  46717. {
  46718. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46719. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  46720. }
  46721. void DirectoryContentsDisplayComponent::sendMouseClickMessage (const File& file, const MouseEvent& e)
  46722. {
  46723. if (fileList.getDirectory().exists())
  46724. {
  46725. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46726. listeners.callChecked (checker, &FileBrowserListener::fileClicked, file, e);
  46727. }
  46728. }
  46729. void DirectoryContentsDisplayComponent::sendDoubleClickMessage (const File& file)
  46730. {
  46731. if (fileList.getDirectory().exists())
  46732. {
  46733. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46734. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, file);
  46735. }
  46736. }
  46737. END_JUCE_NAMESPACE
  46738. /*** End of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  46739. /*** Start of inlined file: juce_DirectoryContentsList.cpp ***/
  46740. BEGIN_JUCE_NAMESPACE
  46741. DirectoryContentsList::DirectoryContentsList (const FileFilter* const fileFilter_,
  46742. TimeSliceThread& thread_)
  46743. : fileFilter (fileFilter_),
  46744. thread (thread_),
  46745. fileTypeFlags (File::ignoreHiddenFiles | File::findFiles),
  46746. fileFindHandle (0),
  46747. shouldStop (true)
  46748. {
  46749. }
  46750. DirectoryContentsList::~DirectoryContentsList()
  46751. {
  46752. clear();
  46753. }
  46754. void DirectoryContentsList::setIgnoresHiddenFiles (const bool shouldIgnoreHiddenFiles)
  46755. {
  46756. setTypeFlags (shouldIgnoreHiddenFiles ? (fileTypeFlags | File::ignoreHiddenFiles)
  46757. : (fileTypeFlags & ~File::ignoreHiddenFiles));
  46758. }
  46759. bool DirectoryContentsList::ignoresHiddenFiles() const
  46760. {
  46761. return (fileTypeFlags & File::ignoreHiddenFiles) != 0;
  46762. }
  46763. const File& DirectoryContentsList::getDirectory() const
  46764. {
  46765. return root;
  46766. }
  46767. void DirectoryContentsList::setDirectory (const File& directory,
  46768. const bool includeDirectories,
  46769. const bool includeFiles)
  46770. {
  46771. jassert (includeDirectories || includeFiles); // you have to speciify at least one of these!
  46772. if (directory != root)
  46773. {
  46774. clear();
  46775. root = directory;
  46776. // (this forces a refresh when setTypeFlags() is called, rather than triggering two refreshes)
  46777. fileTypeFlags &= ~(File::findDirectories | File::findFiles);
  46778. }
  46779. int newFlags = fileTypeFlags;
  46780. if (includeDirectories) newFlags |= File::findDirectories; else newFlags &= ~File::findDirectories;
  46781. if (includeFiles) newFlags |= File::findFiles; else newFlags &= ~File::findFiles;
  46782. setTypeFlags (newFlags);
  46783. }
  46784. void DirectoryContentsList::setTypeFlags (const int newFlags)
  46785. {
  46786. if (fileTypeFlags != newFlags)
  46787. {
  46788. fileTypeFlags = newFlags;
  46789. refresh();
  46790. }
  46791. }
  46792. void DirectoryContentsList::clear()
  46793. {
  46794. shouldStop = true;
  46795. thread.removeTimeSliceClient (this);
  46796. fileFindHandle = 0;
  46797. if (files.size() > 0)
  46798. {
  46799. files.clear();
  46800. changed();
  46801. }
  46802. }
  46803. void DirectoryContentsList::refresh()
  46804. {
  46805. clear();
  46806. if (root.isDirectory())
  46807. {
  46808. fileFindHandle = new DirectoryIterator (root, false, "*", fileTypeFlags);
  46809. shouldStop = false;
  46810. thread.addTimeSliceClient (this);
  46811. }
  46812. }
  46813. int DirectoryContentsList::getNumFiles() const
  46814. {
  46815. return files.size();
  46816. }
  46817. bool DirectoryContentsList::getFileInfo (const int index,
  46818. FileInfo& result) const
  46819. {
  46820. const ScopedLock sl (fileListLock);
  46821. const FileInfo* const info = files [index];
  46822. if (info != 0)
  46823. {
  46824. result = *info;
  46825. return true;
  46826. }
  46827. return false;
  46828. }
  46829. const File DirectoryContentsList::getFile (const int index) const
  46830. {
  46831. const ScopedLock sl (fileListLock);
  46832. const FileInfo* const info = files [index];
  46833. if (info != 0)
  46834. return root.getChildFile (info->filename);
  46835. return File::nonexistent;
  46836. }
  46837. bool DirectoryContentsList::isStillLoading() const
  46838. {
  46839. return fileFindHandle != 0;
  46840. }
  46841. void DirectoryContentsList::changed()
  46842. {
  46843. sendChangeMessage (this);
  46844. }
  46845. bool DirectoryContentsList::useTimeSlice()
  46846. {
  46847. const uint32 startTime = Time::getApproximateMillisecondCounter();
  46848. bool hasChanged = false;
  46849. for (int i = 100; --i >= 0;)
  46850. {
  46851. if (! checkNextFile (hasChanged))
  46852. {
  46853. if (hasChanged)
  46854. changed();
  46855. return false;
  46856. }
  46857. if (shouldStop || (Time::getApproximateMillisecondCounter() > startTime + 150))
  46858. break;
  46859. }
  46860. if (hasChanged)
  46861. changed();
  46862. return true;
  46863. }
  46864. bool DirectoryContentsList::checkNextFile (bool& hasChanged)
  46865. {
  46866. if (fileFindHandle != 0)
  46867. {
  46868. bool fileFoundIsDir, isHidden, isReadOnly;
  46869. int64 fileSize;
  46870. Time modTime, creationTime;
  46871. if (fileFindHandle->next (&fileFoundIsDir, &isHidden, &fileSize,
  46872. &modTime, &creationTime, &isReadOnly))
  46873. {
  46874. if (addFile (fileFindHandle->getFile(), fileFoundIsDir,
  46875. fileSize, modTime, creationTime, isReadOnly))
  46876. {
  46877. hasChanged = true;
  46878. }
  46879. return true;
  46880. }
  46881. else
  46882. {
  46883. fileFindHandle = 0;
  46884. }
  46885. }
  46886. return false;
  46887. }
  46888. int DirectoryContentsList::compareElements (const DirectoryContentsList::FileInfo* const first,
  46889. const DirectoryContentsList::FileInfo* const second)
  46890. {
  46891. #if JUCE_WINDOWS
  46892. if (first->isDirectory != second->isDirectory)
  46893. return first->isDirectory ? -1 : 1;
  46894. #endif
  46895. return first->filename.compareIgnoreCase (second->filename);
  46896. }
  46897. bool DirectoryContentsList::addFile (const File& file,
  46898. const bool isDir,
  46899. const int64 fileSize,
  46900. const Time& modTime,
  46901. const Time& creationTime,
  46902. const bool isReadOnly)
  46903. {
  46904. if (fileFilter == 0
  46905. || ((! isDir) && fileFilter->isFileSuitable (file))
  46906. || (isDir && fileFilter->isDirectorySuitable (file)))
  46907. {
  46908. ScopedPointer <FileInfo> info (new FileInfo());
  46909. info->filename = file.getFileName();
  46910. info->fileSize = fileSize;
  46911. info->modificationTime = modTime;
  46912. info->creationTime = creationTime;
  46913. info->isDirectory = isDir;
  46914. info->isReadOnly = isReadOnly;
  46915. const ScopedLock sl (fileListLock);
  46916. for (int i = files.size(); --i >= 0;)
  46917. if (files.getUnchecked(i)->filename == info->filename)
  46918. return false;
  46919. files.addSorted (*this, info.release());
  46920. return true;
  46921. }
  46922. return false;
  46923. }
  46924. END_JUCE_NAMESPACE
  46925. /*** End of inlined file: juce_DirectoryContentsList.cpp ***/
  46926. /*** Start of inlined file: juce_FileBrowserComponent.cpp ***/
  46927. BEGIN_JUCE_NAMESPACE
  46928. FileBrowserComponent::FileBrowserComponent (int flags_,
  46929. const File& initialFileOrDirectory,
  46930. const FileFilter* fileFilter_,
  46931. FilePreviewComponent* previewComp_)
  46932. : FileFilter (String::empty),
  46933. fileFilter (fileFilter_),
  46934. flags (flags_),
  46935. previewComp (previewComp_),
  46936. thread ("Juce FileBrowser")
  46937. {
  46938. // You need to specify one or other of the open/save flags..
  46939. jassert ((flags & (saveMode | openMode)) != 0);
  46940. jassert ((flags & (saveMode | openMode)) != (saveMode | openMode));
  46941. // You need to specify at least one of these flags..
  46942. jassert ((flags & (canSelectFiles | canSelectDirectories)) != 0);
  46943. String filename;
  46944. if (initialFileOrDirectory == File::nonexistent)
  46945. {
  46946. currentRoot = File::getCurrentWorkingDirectory();
  46947. }
  46948. else if (initialFileOrDirectory.isDirectory())
  46949. {
  46950. currentRoot = initialFileOrDirectory;
  46951. }
  46952. else
  46953. {
  46954. chosenFiles.add (initialFileOrDirectory);
  46955. currentRoot = initialFileOrDirectory.getParentDirectory();
  46956. filename = initialFileOrDirectory.getFileName();
  46957. }
  46958. fileList = new DirectoryContentsList (this, thread);
  46959. if ((flags & useTreeView) != 0)
  46960. {
  46961. FileTreeComponent* const tree = new FileTreeComponent (*fileList);
  46962. if ((flags & canSelectMultipleItems) != 0)
  46963. tree->setMultiSelectEnabled (true);
  46964. addAndMakeVisible (tree);
  46965. fileListComponent = tree;
  46966. }
  46967. else
  46968. {
  46969. FileListComponent* const list = new FileListComponent (*fileList);
  46970. list->setOutlineThickness (1);
  46971. if ((flags & canSelectMultipleItems) != 0)
  46972. list->setMultipleSelectionEnabled (true);
  46973. addAndMakeVisible (list);
  46974. fileListComponent = list;
  46975. }
  46976. fileListComponent->addListener (this);
  46977. addAndMakeVisible (currentPathBox = new ComboBox ("path"));
  46978. currentPathBox->setEditableText (true);
  46979. StringArray rootNames, rootPaths;
  46980. const BigInteger separators (getRoots (rootNames, rootPaths));
  46981. for (int i = 0; i < rootNames.size(); ++i)
  46982. {
  46983. if (separators [i])
  46984. currentPathBox->addSeparator();
  46985. currentPathBox->addItem (rootNames[i], i + 1);
  46986. }
  46987. currentPathBox->addSeparator();
  46988. currentPathBox->addListener (this);
  46989. addAndMakeVisible (filenameBox = new TextEditor());
  46990. filenameBox->setMultiLine (false);
  46991. filenameBox->setSelectAllWhenFocused (true);
  46992. filenameBox->setText (filename, false);
  46993. filenameBox->addListener (this);
  46994. filenameBox->setReadOnly ((flags & (filenameBoxIsReadOnly | canSelectMultipleItems)) != 0);
  46995. Label* label = new Label ("f", TRANS("file:"));
  46996. addAndMakeVisible (label);
  46997. label->attachToComponent (filenameBox, true);
  46998. addAndMakeVisible (goUpButton = getLookAndFeel().createFileBrowserGoUpButton());
  46999. goUpButton->addButtonListener (this);
  47000. goUpButton->setTooltip (TRANS ("go up to parent directory"));
  47001. if (previewComp != 0)
  47002. addAndMakeVisible (previewComp);
  47003. setRoot (currentRoot);
  47004. thread.startThread (4);
  47005. }
  47006. FileBrowserComponent::~FileBrowserComponent()
  47007. {
  47008. if (previewComp != 0)
  47009. removeChildComponent (previewComp);
  47010. deleteAllChildren();
  47011. fileList = 0;
  47012. thread.stopThread (10000);
  47013. }
  47014. void FileBrowserComponent::addListener (FileBrowserListener* const newListener)
  47015. {
  47016. listeners.add (newListener);
  47017. }
  47018. void FileBrowserComponent::removeListener (FileBrowserListener* const listener)
  47019. {
  47020. listeners.remove (listener);
  47021. }
  47022. bool FileBrowserComponent::isSaveMode() const throw()
  47023. {
  47024. return (flags & saveMode) != 0;
  47025. }
  47026. int FileBrowserComponent::getNumSelectedFiles() const throw()
  47027. {
  47028. if (chosenFiles.size() == 0 && currentFileIsValid())
  47029. return 1;
  47030. return chosenFiles.size();
  47031. }
  47032. const File FileBrowserComponent::getSelectedFile (int index) const throw()
  47033. {
  47034. if ((flags & canSelectDirectories) != 0 && filenameBox->getText().isEmpty())
  47035. return currentRoot;
  47036. if (! filenameBox->isReadOnly())
  47037. return currentRoot.getChildFile (filenameBox->getText());
  47038. return chosenFiles[index];
  47039. }
  47040. bool FileBrowserComponent::currentFileIsValid() const
  47041. {
  47042. if (isSaveMode())
  47043. return ! getSelectedFile (0).isDirectory();
  47044. else
  47045. return getSelectedFile (0).exists();
  47046. }
  47047. const File FileBrowserComponent::getHighlightedFile() const throw()
  47048. {
  47049. return fileListComponent->getSelectedFile (0);
  47050. }
  47051. void FileBrowserComponent::deselectAllFiles()
  47052. {
  47053. fileListComponent->deselectAllFiles();
  47054. }
  47055. bool FileBrowserComponent::isFileSuitable (const File& file) const
  47056. {
  47057. return (flags & canSelectFiles) != 0 ? (fileFilter == 0 || fileFilter->isFileSuitable (file))
  47058. : false;
  47059. }
  47060. bool FileBrowserComponent::isDirectorySuitable (const File&) const
  47061. {
  47062. return true;
  47063. }
  47064. bool FileBrowserComponent::isFileOrDirSuitable (const File& f) const
  47065. {
  47066. if (f.isDirectory())
  47067. return (flags & canSelectDirectories) != 0 && (fileFilter == 0 || fileFilter->isDirectorySuitable (f));
  47068. return (flags & canSelectFiles) != 0 && f.exists()
  47069. && (fileFilter == 0 || fileFilter->isFileSuitable (f));
  47070. }
  47071. const File FileBrowserComponent::getRoot() const
  47072. {
  47073. return currentRoot;
  47074. }
  47075. void FileBrowserComponent::setRoot (const File& newRootDirectory)
  47076. {
  47077. if (currentRoot != newRootDirectory)
  47078. {
  47079. fileListComponent->scrollToTop();
  47080. String path (newRootDirectory.getFullPathName());
  47081. if (path.isEmpty())
  47082. path = File::separatorString;
  47083. StringArray rootNames, rootPaths;
  47084. getRoots (rootNames, rootPaths);
  47085. if (! rootPaths.contains (path, true))
  47086. {
  47087. bool alreadyListed = false;
  47088. for (int i = currentPathBox->getNumItems(); --i >= 0;)
  47089. {
  47090. if (currentPathBox->getItemText (i).equalsIgnoreCase (path))
  47091. {
  47092. alreadyListed = true;
  47093. break;
  47094. }
  47095. }
  47096. if (! alreadyListed)
  47097. currentPathBox->addItem (path, currentPathBox->getNumItems() + 2);
  47098. }
  47099. }
  47100. currentRoot = newRootDirectory;
  47101. fileList->setDirectory (currentRoot, true, true);
  47102. String currentRootName (currentRoot.getFullPathName());
  47103. if (currentRootName.isEmpty())
  47104. currentRootName = File::separatorString;
  47105. currentPathBox->setText (currentRootName, true);
  47106. goUpButton->setEnabled (currentRoot.getParentDirectory().isDirectory()
  47107. && currentRoot.getParentDirectory() != currentRoot);
  47108. }
  47109. void FileBrowserComponent::goUp()
  47110. {
  47111. setRoot (getRoot().getParentDirectory());
  47112. }
  47113. void FileBrowserComponent::refresh()
  47114. {
  47115. fileList->refresh();
  47116. }
  47117. const String FileBrowserComponent::getActionVerb() const
  47118. {
  47119. return isSaveMode() ? TRANS("Save") : TRANS("Open");
  47120. }
  47121. FilePreviewComponent* FileBrowserComponent::getPreviewComponent() const throw()
  47122. {
  47123. return previewComp;
  47124. }
  47125. void FileBrowserComponent::resized()
  47126. {
  47127. getLookAndFeel()
  47128. .layoutFileBrowserComponent (*this, fileListComponent,
  47129. previewComp, currentPathBox,
  47130. filenameBox, goUpButton);
  47131. }
  47132. void FileBrowserComponent::sendListenerChangeMessage()
  47133. {
  47134. Component::BailOutChecker checker (this);
  47135. if (previewComp != 0)
  47136. previewComp->selectedFileChanged (getSelectedFile (0));
  47137. // You shouldn't delete the browser when the file gets changed!
  47138. jassert (! checker.shouldBailOut());
  47139. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  47140. }
  47141. void FileBrowserComponent::selectionChanged()
  47142. {
  47143. StringArray newFilenames;
  47144. bool resetChosenFiles = true;
  47145. for (int i = 0; i < fileListComponent->getNumSelectedFiles(); ++i)
  47146. {
  47147. const File f (fileListComponent->getSelectedFile (i));
  47148. if (isFileOrDirSuitable (f))
  47149. {
  47150. if (resetChosenFiles)
  47151. {
  47152. chosenFiles.clear();
  47153. resetChosenFiles = false;
  47154. }
  47155. chosenFiles.add (f);
  47156. newFilenames.add (f.getRelativePathFrom (getRoot()));
  47157. }
  47158. }
  47159. if (newFilenames.size() > 0)
  47160. filenameBox->setText (newFilenames.joinIntoString (", "), false);
  47161. sendListenerChangeMessage();
  47162. }
  47163. void FileBrowserComponent::fileClicked (const File& f, const MouseEvent& e)
  47164. {
  47165. Component::BailOutChecker checker (this);
  47166. listeners.callChecked (checker, &FileBrowserListener::fileClicked, f, e);
  47167. }
  47168. void FileBrowserComponent::fileDoubleClicked (const File& f)
  47169. {
  47170. if (f.isDirectory())
  47171. {
  47172. setRoot (f);
  47173. if ((flags & canSelectDirectories) != 0)
  47174. filenameBox->setText (String::empty);
  47175. }
  47176. else
  47177. {
  47178. Component::BailOutChecker checker (this);
  47179. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, f);
  47180. }
  47181. }
  47182. bool FileBrowserComponent::keyPressed (const KeyPress& key)
  47183. {
  47184. (void) key;
  47185. #if JUCE_LINUX || JUCE_WINDOWS
  47186. if (key.getModifiers().isCommandDown()
  47187. && (key.getKeyCode() == 'H' || key.getKeyCode() == 'h'))
  47188. {
  47189. fileList->setIgnoresHiddenFiles (! fileList->ignoresHiddenFiles());
  47190. fileList->refresh();
  47191. return true;
  47192. }
  47193. #endif
  47194. return false;
  47195. }
  47196. void FileBrowserComponent::textEditorTextChanged (TextEditor&)
  47197. {
  47198. sendListenerChangeMessage();
  47199. }
  47200. void FileBrowserComponent::textEditorReturnKeyPressed (TextEditor&)
  47201. {
  47202. if (filenameBox->getText().containsChar (File::separator))
  47203. {
  47204. const File f (currentRoot.getChildFile (filenameBox->getText()));
  47205. if (f.isDirectory())
  47206. {
  47207. setRoot (f);
  47208. chosenFiles.clear();
  47209. filenameBox->setText (String::empty);
  47210. }
  47211. else
  47212. {
  47213. setRoot (f.getParentDirectory());
  47214. chosenFiles.clear();
  47215. chosenFiles.add (f);
  47216. filenameBox->setText (f.getFileName());
  47217. }
  47218. }
  47219. else
  47220. {
  47221. fileDoubleClicked (getSelectedFile (0));
  47222. }
  47223. }
  47224. void FileBrowserComponent::textEditorEscapeKeyPressed (TextEditor&)
  47225. {
  47226. }
  47227. void FileBrowserComponent::textEditorFocusLost (TextEditor&)
  47228. {
  47229. if (! isSaveMode())
  47230. selectionChanged();
  47231. }
  47232. void FileBrowserComponent::buttonClicked (Button*)
  47233. {
  47234. goUp();
  47235. }
  47236. void FileBrowserComponent::comboBoxChanged (ComboBox*)
  47237. {
  47238. const String newText (currentPathBox->getText().trim().unquoted());
  47239. if (newText.isNotEmpty())
  47240. {
  47241. const int index = currentPathBox->getSelectedId() - 1;
  47242. StringArray rootNames, rootPaths;
  47243. getRoots (rootNames, rootPaths);
  47244. if (rootPaths [index].isNotEmpty())
  47245. {
  47246. setRoot (File (rootPaths [index]));
  47247. }
  47248. else
  47249. {
  47250. File f (newText);
  47251. for (;;)
  47252. {
  47253. if (f.isDirectory())
  47254. {
  47255. setRoot (f);
  47256. break;
  47257. }
  47258. if (f.getParentDirectory() == f)
  47259. break;
  47260. f = f.getParentDirectory();
  47261. }
  47262. }
  47263. }
  47264. }
  47265. const BigInteger FileBrowserComponent::getRoots (StringArray& rootNames, StringArray& rootPaths)
  47266. {
  47267. BigInteger separators;
  47268. #if JUCE_WINDOWS
  47269. Array<File> roots;
  47270. File::findFileSystemRoots (roots);
  47271. rootPaths.clear();
  47272. for (int i = 0; i < roots.size(); ++i)
  47273. {
  47274. const File& drive = roots.getReference(i);
  47275. String name (drive.getFullPathName());
  47276. rootPaths.add (name);
  47277. if (drive.isOnHardDisk())
  47278. {
  47279. String volume (drive.getVolumeLabel());
  47280. if (volume.isEmpty())
  47281. volume = TRANS("Hard Drive");
  47282. name << " [" << drive.getVolumeLabel() << ']';
  47283. }
  47284. else if (drive.isOnCDRomDrive())
  47285. {
  47286. name << TRANS(" [CD/DVD drive]");
  47287. }
  47288. rootNames.add (name);
  47289. }
  47290. separators.setBit (rootPaths.size());
  47291. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  47292. rootNames.add ("Documents");
  47293. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  47294. rootNames.add ("Desktop");
  47295. #endif
  47296. #if JUCE_MAC
  47297. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  47298. rootNames.add ("Home folder");
  47299. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  47300. rootNames.add ("Documents");
  47301. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  47302. rootNames.add ("Desktop");
  47303. separators.setBit (rootPaths.size());
  47304. Array <File> volumes;
  47305. File vol ("/Volumes");
  47306. vol.findChildFiles (volumes, File::findDirectories, false);
  47307. for (int i = 0; i < volumes.size(); ++i)
  47308. {
  47309. const File& volume = volumes.getReference(i);
  47310. if (volume.isDirectory() && ! volume.getFileName().startsWithChar ('.'))
  47311. {
  47312. rootPaths.add (volume.getFullPathName());
  47313. rootNames.add (volume.getFileName());
  47314. }
  47315. }
  47316. #endif
  47317. #if JUCE_LINUX
  47318. rootPaths.add ("/");
  47319. rootNames.add ("/");
  47320. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  47321. rootNames.add ("Home folder");
  47322. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  47323. rootNames.add ("Desktop");
  47324. #endif
  47325. return separators;
  47326. }
  47327. END_JUCE_NAMESPACE
  47328. /*** End of inlined file: juce_FileBrowserComponent.cpp ***/
  47329. /*** Start of inlined file: juce_FileChooser.cpp ***/
  47330. BEGIN_JUCE_NAMESPACE
  47331. FileChooser::FileChooser (const String& chooserBoxTitle,
  47332. const File& currentFileOrDirectory,
  47333. const String& fileFilters,
  47334. const bool useNativeDialogBox_)
  47335. : title (chooserBoxTitle),
  47336. filters (fileFilters),
  47337. startingFile (currentFileOrDirectory),
  47338. useNativeDialogBox (useNativeDialogBox_)
  47339. {
  47340. #if JUCE_LINUX
  47341. useNativeDialogBox = false;
  47342. #endif
  47343. if (! fileFilters.containsNonWhitespaceChars())
  47344. filters = "*";
  47345. }
  47346. FileChooser::~FileChooser()
  47347. {
  47348. }
  47349. bool FileChooser::browseForFileToOpen (FilePreviewComponent* previewComponent)
  47350. {
  47351. return showDialog (false, true, false, false, false, previewComponent);
  47352. }
  47353. bool FileChooser::browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent)
  47354. {
  47355. return showDialog (false, true, false, false, true, previewComponent);
  47356. }
  47357. bool FileChooser::browseForMultipleFilesOrDirectories (FilePreviewComponent* previewComponent)
  47358. {
  47359. return showDialog (true, true, false, false, true, previewComponent);
  47360. }
  47361. bool FileChooser::browseForFileToSave (const bool warnAboutOverwritingExistingFiles)
  47362. {
  47363. return showDialog (false, true, true, warnAboutOverwritingExistingFiles, false, 0);
  47364. }
  47365. bool FileChooser::browseForDirectory()
  47366. {
  47367. return showDialog (true, false, false, false, false, 0);
  47368. }
  47369. const File FileChooser::getResult() const
  47370. {
  47371. // if you've used a multiple-file select, you should use the getResults() method
  47372. // to retrieve all the files that were chosen.
  47373. jassert (results.size() <= 1);
  47374. return results.getFirst();
  47375. }
  47376. const Array<File>& FileChooser::getResults() const
  47377. {
  47378. return results;
  47379. }
  47380. bool FileChooser::showDialog (const bool selectsDirectories,
  47381. const bool selectsFiles,
  47382. const bool isSave,
  47383. const bool warnAboutOverwritingExistingFiles,
  47384. const bool selectMultipleFiles,
  47385. FilePreviewComponent* const previewComponent)
  47386. {
  47387. Component::SafePointer<Component> previouslyFocused (Component::getCurrentlyFocusedComponent());
  47388. results.clear();
  47389. // the preview component needs to be the right size before you pass it in here..
  47390. jassert (previewComponent == 0 || (previewComponent->getWidth() > 10
  47391. && previewComponent->getHeight() > 10));
  47392. #if JUCE_WINDOWS
  47393. if (useNativeDialogBox && ! (selectsFiles && selectsDirectories))
  47394. #elif JUCE_MAC
  47395. if (useNativeDialogBox && (previewComponent == 0))
  47396. #else
  47397. if (false)
  47398. #endif
  47399. {
  47400. showPlatformDialog (results, title, startingFile, filters,
  47401. selectsDirectories, selectsFiles, isSave,
  47402. warnAboutOverwritingExistingFiles,
  47403. selectMultipleFiles,
  47404. previewComponent);
  47405. }
  47406. else
  47407. {
  47408. WildcardFileFilter wildcard (selectsFiles ? filters : String::empty,
  47409. selectsDirectories ? "*" : String::empty,
  47410. String::empty);
  47411. int flags = isSave ? FileBrowserComponent::saveMode
  47412. : FileBrowserComponent::openMode;
  47413. if (selectsFiles)
  47414. flags |= FileBrowserComponent::canSelectFiles;
  47415. if (selectsDirectories)
  47416. {
  47417. flags |= FileBrowserComponent::canSelectDirectories;
  47418. if (! isSave)
  47419. flags |= FileBrowserComponent::filenameBoxIsReadOnly;
  47420. }
  47421. if (selectMultipleFiles)
  47422. flags |= FileBrowserComponent::canSelectMultipleItems;
  47423. FileBrowserComponent browserComponent (flags, startingFile, &wildcard, previewComponent);
  47424. FileChooserDialogBox box (title, String::empty,
  47425. browserComponent,
  47426. warnAboutOverwritingExistingFiles,
  47427. browserComponent.findColour (AlertWindow::backgroundColourId));
  47428. if (box.show())
  47429. {
  47430. for (int i = 0; i < browserComponent.getNumSelectedFiles(); ++i)
  47431. results.add (browserComponent.getSelectedFile (i));
  47432. }
  47433. }
  47434. if (previouslyFocused != 0)
  47435. previouslyFocused->grabKeyboardFocus();
  47436. return results.size() > 0;
  47437. }
  47438. FilePreviewComponent::FilePreviewComponent()
  47439. {
  47440. }
  47441. FilePreviewComponent::~FilePreviewComponent()
  47442. {
  47443. }
  47444. END_JUCE_NAMESPACE
  47445. /*** End of inlined file: juce_FileChooser.cpp ***/
  47446. /*** Start of inlined file: juce_FileChooserDialogBox.cpp ***/
  47447. BEGIN_JUCE_NAMESPACE
  47448. FileChooserDialogBox::FileChooserDialogBox (const String& name,
  47449. const String& instructions,
  47450. FileBrowserComponent& chooserComponent,
  47451. const bool warnAboutOverwritingExistingFiles_,
  47452. const Colour& backgroundColour)
  47453. : ResizableWindow (name, backgroundColour, true),
  47454. warnAboutOverwritingExistingFiles (warnAboutOverwritingExistingFiles_)
  47455. {
  47456. setContentComponent (content = new ContentComponent (name, instructions, chooserComponent));
  47457. setResizable (true, true);
  47458. setResizeLimits (300, 300, 1200, 1000);
  47459. content->okButton.addButtonListener (this);
  47460. content->cancelButton.addButtonListener (this);
  47461. content->chooserComponent.addListener (this);
  47462. }
  47463. FileChooserDialogBox::~FileChooserDialogBox()
  47464. {
  47465. content->chooserComponent.removeListener (this);
  47466. }
  47467. bool FileChooserDialogBox::show (int w, int h)
  47468. {
  47469. return showAt (-1, -1, w, h);
  47470. }
  47471. bool FileChooserDialogBox::showAt (int x, int y, int w, int h)
  47472. {
  47473. if (w <= 0)
  47474. {
  47475. Component* const previewComp = content->chooserComponent.getPreviewComponent();
  47476. if (previewComp != 0)
  47477. w = 400 + previewComp->getWidth();
  47478. else
  47479. w = 600;
  47480. }
  47481. if (h <= 0)
  47482. h = 500;
  47483. if (x < 0 || y < 0)
  47484. centreWithSize (w, h);
  47485. else
  47486. setBounds (x, y, w, h);
  47487. const bool ok = (runModalLoop() != 0);
  47488. setVisible (false);
  47489. return ok;
  47490. }
  47491. void FileChooserDialogBox::buttonClicked (Button* button)
  47492. {
  47493. if (button == &(content->okButton))
  47494. {
  47495. if (warnAboutOverwritingExistingFiles
  47496. && content->chooserComponent.isSaveMode()
  47497. && content->chooserComponent.getSelectedFile(0).exists())
  47498. {
  47499. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  47500. TRANS("File already exists"),
  47501. TRANS("There's already a file called:")
  47502. + "\n\n" + content->chooserComponent.getSelectedFile(0).getFullPathName()
  47503. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  47504. TRANS("overwrite"),
  47505. TRANS("cancel")))
  47506. {
  47507. return;
  47508. }
  47509. }
  47510. exitModalState (1);
  47511. }
  47512. else if (button == &(content->cancelButton))
  47513. {
  47514. closeButtonPressed();
  47515. }
  47516. }
  47517. void FileChooserDialogBox::closeButtonPressed()
  47518. {
  47519. setVisible (false);
  47520. }
  47521. void FileChooserDialogBox::selectionChanged()
  47522. {
  47523. content->okButton.setEnabled (content->chooserComponent.currentFileIsValid());
  47524. }
  47525. void FileChooserDialogBox::fileClicked (const File&, const MouseEvent&)
  47526. {
  47527. }
  47528. void FileChooserDialogBox::fileDoubleClicked (const File&)
  47529. {
  47530. selectionChanged();
  47531. content->okButton.triggerClick();
  47532. }
  47533. FileChooserDialogBox::ContentComponent::ContentComponent (const String& name, const String& instructions_, FileBrowserComponent& chooserComponent_)
  47534. : Component (name), instructions (instructions_),
  47535. chooserComponent (chooserComponent_),
  47536. okButton (chooserComponent_.getActionVerb()),
  47537. cancelButton (TRANS ("Cancel"))
  47538. {
  47539. addAndMakeVisible (&chooserComponent);
  47540. addAndMakeVisible (&okButton);
  47541. okButton.setEnabled (chooserComponent.currentFileIsValid());
  47542. okButton.addShortcut (KeyPress (KeyPress::returnKey, 0, 0));
  47543. addAndMakeVisible (&cancelButton);
  47544. cancelButton.addShortcut (KeyPress (KeyPress::escapeKey, 0, 0));
  47545. setInterceptsMouseClicks (false, true);
  47546. }
  47547. FileChooserDialogBox::ContentComponent::~ContentComponent()
  47548. {
  47549. }
  47550. void FileChooserDialogBox::ContentComponent::paint (Graphics& g)
  47551. {
  47552. g.setColour (getLookAndFeel().findColour (FileChooserDialogBox::titleTextColourId));
  47553. text.draw (g);
  47554. }
  47555. void FileChooserDialogBox::ContentComponent::resized()
  47556. {
  47557. getLookAndFeel().createFileChooserHeaderText (getName(), instructions, text, getWidth());
  47558. const Rectangle<float> bb (text.getBoundingBox (0, text.getNumGlyphs(), false));
  47559. const int y = roundToInt (bb.getBottom()) + 10;
  47560. const int buttonHeight = 26;
  47561. const int buttonY = getHeight() - buttonHeight - 8;
  47562. chooserComponent.setBounds (0, y, getWidth(), buttonY - y - 20);
  47563. okButton.setBounds (proportionOfWidth (0.25f), buttonY,
  47564. proportionOfWidth (0.2f), buttonHeight);
  47565. cancelButton.setBounds (proportionOfWidth (0.55f), buttonY,
  47566. proportionOfWidth (0.2f), buttonHeight);
  47567. }
  47568. END_JUCE_NAMESPACE
  47569. /*** End of inlined file: juce_FileChooserDialogBox.cpp ***/
  47570. /*** Start of inlined file: juce_FileFilter.cpp ***/
  47571. BEGIN_JUCE_NAMESPACE
  47572. FileFilter::FileFilter (const String& filterDescription)
  47573. : description (filterDescription)
  47574. {
  47575. }
  47576. FileFilter::~FileFilter()
  47577. {
  47578. }
  47579. const String& FileFilter::getDescription() const throw()
  47580. {
  47581. return description;
  47582. }
  47583. END_JUCE_NAMESPACE
  47584. /*** End of inlined file: juce_FileFilter.cpp ***/
  47585. /*** Start of inlined file: juce_FileListComponent.cpp ***/
  47586. BEGIN_JUCE_NAMESPACE
  47587. const Image juce_createIconForFile (const File& file);
  47588. FileListComponent::FileListComponent (DirectoryContentsList& listToShow)
  47589. : ListBox (String::empty, 0),
  47590. DirectoryContentsDisplayComponent (listToShow)
  47591. {
  47592. setModel (this);
  47593. fileList.addChangeListener (this);
  47594. }
  47595. FileListComponent::~FileListComponent()
  47596. {
  47597. fileList.removeChangeListener (this);
  47598. }
  47599. int FileListComponent::getNumSelectedFiles() const
  47600. {
  47601. return getNumSelectedRows();
  47602. }
  47603. const File FileListComponent::getSelectedFile (int index) const
  47604. {
  47605. return fileList.getFile (getSelectedRow (index));
  47606. }
  47607. void FileListComponent::deselectAllFiles()
  47608. {
  47609. deselectAllRows();
  47610. }
  47611. void FileListComponent::scrollToTop()
  47612. {
  47613. getVerticalScrollBar()->setCurrentRangeStart (0);
  47614. }
  47615. void FileListComponent::changeListenerCallback (void*)
  47616. {
  47617. updateContent();
  47618. if (lastDirectory != fileList.getDirectory())
  47619. {
  47620. lastDirectory = fileList.getDirectory();
  47621. deselectAllRows();
  47622. }
  47623. }
  47624. class FileListItemComponent : public Component,
  47625. public TimeSliceClient,
  47626. public AsyncUpdater
  47627. {
  47628. public:
  47629. FileListItemComponent (FileListComponent& owner_, TimeSliceThread& thread_)
  47630. : owner (owner_), thread (thread_),
  47631. highlighted (false), index (0), icon (0)
  47632. {
  47633. }
  47634. ~FileListItemComponent()
  47635. {
  47636. thread.removeTimeSliceClient (this);
  47637. clearIcon();
  47638. }
  47639. void paint (Graphics& g)
  47640. {
  47641. getLookAndFeel().drawFileBrowserRow (g, getWidth(), getHeight(),
  47642. file.getFileName(),
  47643. &icon,
  47644. fileSize, modTime,
  47645. isDirectory, highlighted,
  47646. index, owner);
  47647. }
  47648. void mouseDown (const MouseEvent& e)
  47649. {
  47650. owner.selectRowsBasedOnModifierKeys (index, e.mods);
  47651. owner.sendMouseClickMessage (file, e);
  47652. }
  47653. void mouseDoubleClick (const MouseEvent&)
  47654. {
  47655. owner.sendDoubleClickMessage (file);
  47656. }
  47657. void update (const File& root,
  47658. const DirectoryContentsList::FileInfo* const fileInfo,
  47659. const int index_,
  47660. const bool highlighted_)
  47661. {
  47662. thread.removeTimeSliceClient (this);
  47663. if (highlighted_ != highlighted
  47664. || index_ != index)
  47665. {
  47666. index = index_;
  47667. highlighted = highlighted_;
  47668. repaint();
  47669. }
  47670. File newFile;
  47671. String newFileSize;
  47672. String newModTime;
  47673. if (fileInfo != 0)
  47674. {
  47675. newFile = root.getChildFile (fileInfo->filename);
  47676. newFileSize = File::descriptionOfSizeInBytes (fileInfo->fileSize);
  47677. newModTime = fileInfo->modificationTime.formatted ("%d %b '%y %H:%M");
  47678. }
  47679. if (newFile != file
  47680. || fileSize != newFileSize
  47681. || modTime != newModTime)
  47682. {
  47683. file = newFile;
  47684. fileSize = newFileSize;
  47685. modTime = newModTime;
  47686. isDirectory = fileInfo != 0 && fileInfo->isDirectory;
  47687. repaint();
  47688. clearIcon();
  47689. }
  47690. if (file != File::nonexistent && icon.isNull() && ! isDirectory)
  47691. {
  47692. updateIcon (true);
  47693. if (! icon.isValid())
  47694. thread.addTimeSliceClient (this);
  47695. }
  47696. }
  47697. bool useTimeSlice()
  47698. {
  47699. updateIcon (false);
  47700. return false;
  47701. }
  47702. void handleAsyncUpdate()
  47703. {
  47704. repaint();
  47705. }
  47706. juce_UseDebuggingNewOperator
  47707. private:
  47708. FileListComponent& owner;
  47709. TimeSliceThread& thread;
  47710. bool highlighted;
  47711. int index;
  47712. File file;
  47713. String fileSize;
  47714. String modTime;
  47715. Image icon;
  47716. bool isDirectory;
  47717. void clearIcon()
  47718. {
  47719. icon = Image::null;
  47720. }
  47721. void updateIcon (const bool onlyUpdateIfCached)
  47722. {
  47723. if (icon.isNull())
  47724. {
  47725. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  47726. Image im (ImageCache::getFromHashCode (hashCode));
  47727. if (im.isNull() && ! onlyUpdateIfCached)
  47728. {
  47729. im = juce_createIconForFile (file);
  47730. if (im.isValid())
  47731. ImageCache::addImageToCache (im, hashCode);
  47732. }
  47733. if (im.isValid())
  47734. {
  47735. icon = im;
  47736. triggerAsyncUpdate();
  47737. }
  47738. }
  47739. }
  47740. };
  47741. int FileListComponent::getNumRows()
  47742. {
  47743. return fileList.getNumFiles();
  47744. }
  47745. void FileListComponent::paintListBoxItem (int, Graphics&, int, int, bool)
  47746. {
  47747. }
  47748. Component* FileListComponent::refreshComponentForRow (int row, bool isSelected, Component* existingComponentToUpdate)
  47749. {
  47750. FileListItemComponent* comp = dynamic_cast <FileListItemComponent*> (existingComponentToUpdate);
  47751. if (comp == 0)
  47752. {
  47753. delete existingComponentToUpdate;
  47754. comp = new FileListItemComponent (*this, fileList.getTimeSliceThread());
  47755. }
  47756. DirectoryContentsList::FileInfo fileInfo;
  47757. if (fileList.getFileInfo (row, fileInfo))
  47758. comp->update (fileList.getDirectory(), &fileInfo, row, isSelected);
  47759. else
  47760. comp->update (fileList.getDirectory(), 0, row, isSelected);
  47761. return comp;
  47762. }
  47763. void FileListComponent::selectedRowsChanged (int /*lastRowSelected*/)
  47764. {
  47765. sendSelectionChangeMessage();
  47766. }
  47767. void FileListComponent::deleteKeyPressed (int /*currentSelectedRow*/)
  47768. {
  47769. }
  47770. void FileListComponent::returnKeyPressed (int currentSelectedRow)
  47771. {
  47772. sendDoubleClickMessage (fileList.getFile (currentSelectedRow));
  47773. }
  47774. END_JUCE_NAMESPACE
  47775. /*** End of inlined file: juce_FileListComponent.cpp ***/
  47776. /*** Start of inlined file: juce_FilenameComponent.cpp ***/
  47777. BEGIN_JUCE_NAMESPACE
  47778. FilenameComponent::FilenameComponent (const String& name,
  47779. const File& currentFile,
  47780. const bool canEditFilename,
  47781. const bool isDirectory,
  47782. const bool isForSaving,
  47783. const String& fileBrowserWildcard,
  47784. const String& enforcedSuffix_,
  47785. const String& textWhenNothingSelected)
  47786. : Component (name),
  47787. maxRecentFiles (30),
  47788. isDir (isDirectory),
  47789. isSaving (isForSaving),
  47790. isFileDragOver (false),
  47791. wildcard (fileBrowserWildcard),
  47792. enforcedSuffix (enforcedSuffix_)
  47793. {
  47794. addAndMakeVisible (&filenameBox);
  47795. filenameBox.setEditableText (canEditFilename);
  47796. filenameBox.addListener (this);
  47797. filenameBox.setTextWhenNothingSelected (textWhenNothingSelected);
  47798. filenameBox.setTextWhenNoChoicesAvailable (TRANS("(no recently seleced files)"));
  47799. setBrowseButtonText ("...");
  47800. setCurrentFile (currentFile, true);
  47801. }
  47802. FilenameComponent::~FilenameComponent()
  47803. {
  47804. }
  47805. void FilenameComponent::paintOverChildren (Graphics& g)
  47806. {
  47807. if (isFileDragOver)
  47808. {
  47809. g.setColour (Colours::red.withAlpha (0.2f));
  47810. g.drawRect (0, 0, getWidth(), getHeight(), 3);
  47811. }
  47812. }
  47813. void FilenameComponent::resized()
  47814. {
  47815. getLookAndFeel().layoutFilenameComponent (*this, &filenameBox, browseButton);
  47816. }
  47817. void FilenameComponent::setBrowseButtonText (const String& newBrowseButtonText)
  47818. {
  47819. browseButtonText = newBrowseButtonText;
  47820. lookAndFeelChanged();
  47821. }
  47822. void FilenameComponent::lookAndFeelChanged()
  47823. {
  47824. browseButton = 0;
  47825. addAndMakeVisible (browseButton = getLookAndFeel().createFilenameComponentBrowseButton (browseButtonText));
  47826. browseButton->setConnectedEdges (Button::ConnectedOnLeft);
  47827. resized();
  47828. browseButton->addButtonListener (this);
  47829. }
  47830. void FilenameComponent::setTooltip (const String& newTooltip)
  47831. {
  47832. SettableTooltipClient::setTooltip (newTooltip);
  47833. filenameBox.setTooltip (newTooltip);
  47834. }
  47835. void FilenameComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  47836. {
  47837. defaultBrowseFile = newDefaultDirectory;
  47838. }
  47839. void FilenameComponent::buttonClicked (Button*)
  47840. {
  47841. FileChooser fc (TRANS("Choose a new file"),
  47842. getCurrentFile() == File::nonexistent ? defaultBrowseFile
  47843. : getCurrentFile(),
  47844. wildcard);
  47845. if (isDir ? fc.browseForDirectory()
  47846. : (isSaving ? fc.browseForFileToSave (false)
  47847. : fc.browseForFileToOpen()))
  47848. {
  47849. setCurrentFile (fc.getResult(), true);
  47850. }
  47851. }
  47852. void FilenameComponent::comboBoxChanged (ComboBox*)
  47853. {
  47854. setCurrentFile (getCurrentFile(), true);
  47855. }
  47856. bool FilenameComponent::isInterestedInFileDrag (const StringArray&)
  47857. {
  47858. return true;
  47859. }
  47860. void FilenameComponent::filesDropped (const StringArray& filenames, int, int)
  47861. {
  47862. isFileDragOver = false;
  47863. repaint();
  47864. const File f (filenames[0]);
  47865. if (f.exists() && (f.isDirectory() == isDir))
  47866. setCurrentFile (f, true);
  47867. }
  47868. void FilenameComponent::fileDragEnter (const StringArray&, int, int)
  47869. {
  47870. isFileDragOver = true;
  47871. repaint();
  47872. }
  47873. void FilenameComponent::fileDragExit (const StringArray&)
  47874. {
  47875. isFileDragOver = false;
  47876. repaint();
  47877. }
  47878. const File FilenameComponent::getCurrentFile() const
  47879. {
  47880. File f (filenameBox.getText());
  47881. if (enforcedSuffix.isNotEmpty())
  47882. f = f.withFileExtension (enforcedSuffix);
  47883. return f;
  47884. }
  47885. void FilenameComponent::setCurrentFile (File newFile,
  47886. const bool addToRecentlyUsedList,
  47887. const bool sendChangeNotification)
  47888. {
  47889. if (enforcedSuffix.isNotEmpty())
  47890. newFile = newFile.withFileExtension (enforcedSuffix);
  47891. if (newFile.getFullPathName() != lastFilename)
  47892. {
  47893. lastFilename = newFile.getFullPathName();
  47894. if (addToRecentlyUsedList)
  47895. addRecentlyUsedFile (newFile);
  47896. filenameBox.setText (lastFilename, true);
  47897. if (sendChangeNotification)
  47898. triggerAsyncUpdate();
  47899. }
  47900. }
  47901. void FilenameComponent::setFilenameIsEditable (const bool shouldBeEditable)
  47902. {
  47903. filenameBox.setEditableText (shouldBeEditable);
  47904. }
  47905. const StringArray FilenameComponent::getRecentlyUsedFilenames() const
  47906. {
  47907. StringArray names;
  47908. for (int i = 0; i < filenameBox.getNumItems(); ++i)
  47909. names.add (filenameBox.getItemText (i));
  47910. return names;
  47911. }
  47912. void FilenameComponent::setRecentlyUsedFilenames (const StringArray& filenames)
  47913. {
  47914. if (filenames != getRecentlyUsedFilenames())
  47915. {
  47916. filenameBox.clear();
  47917. for (int i = 0; i < jmin (filenames.size(), maxRecentFiles); ++i)
  47918. filenameBox.addItem (filenames[i], i + 1);
  47919. }
  47920. }
  47921. void FilenameComponent::setMaxNumberOfRecentFiles (const int newMaximum)
  47922. {
  47923. maxRecentFiles = jmax (1, newMaximum);
  47924. setRecentlyUsedFilenames (getRecentlyUsedFilenames());
  47925. }
  47926. void FilenameComponent::addRecentlyUsedFile (const File& file)
  47927. {
  47928. StringArray files (getRecentlyUsedFilenames());
  47929. if (file.getFullPathName().isNotEmpty())
  47930. {
  47931. files.removeString (file.getFullPathName(), true);
  47932. files.insert (0, file.getFullPathName());
  47933. setRecentlyUsedFilenames (files);
  47934. }
  47935. }
  47936. void FilenameComponent::addListener (FilenameComponentListener* const listener)
  47937. {
  47938. listeners.add (listener);
  47939. }
  47940. void FilenameComponent::removeListener (FilenameComponentListener* const listener)
  47941. {
  47942. listeners.remove (listener);
  47943. }
  47944. void FilenameComponent::handleAsyncUpdate()
  47945. {
  47946. Component::BailOutChecker checker (this);
  47947. listeners.callChecked (checker, &FilenameComponentListener::filenameComponentChanged, this);
  47948. }
  47949. END_JUCE_NAMESPACE
  47950. /*** End of inlined file: juce_FilenameComponent.cpp ***/
  47951. /*** Start of inlined file: juce_FileSearchPathListComponent.cpp ***/
  47952. BEGIN_JUCE_NAMESPACE
  47953. FileSearchPathListComponent::FileSearchPathListComponent()
  47954. {
  47955. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  47956. listBox->setColour (ListBox::backgroundColourId, Colours::black.withAlpha (0.02f));
  47957. listBox->setColour (ListBox::outlineColourId, Colours::black.withAlpha (0.1f));
  47958. listBox->setOutlineThickness (1);
  47959. addAndMakeVisible (addButton = new TextButton ("+"));
  47960. addButton->addButtonListener (this);
  47961. addButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  47962. addAndMakeVisible (removeButton = new TextButton ("-"));
  47963. removeButton->addButtonListener (this);
  47964. removeButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  47965. addAndMakeVisible (changeButton = new TextButton (TRANS("change...")));
  47966. changeButton->addButtonListener (this);
  47967. addAndMakeVisible (upButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  47968. upButton->addButtonListener (this);
  47969. {
  47970. Path arrowPath;
  47971. arrowPath.addArrow (Line<float> (50.0f, 100.0f, 50.0f, 0.0f), 40.0f, 100.0f, 50.0f);
  47972. DrawablePath arrowImage;
  47973. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  47974. arrowImage.setPath (arrowPath);
  47975. upButton->setImages (&arrowImage);
  47976. }
  47977. addAndMakeVisible (downButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  47978. downButton->addButtonListener (this);
  47979. {
  47980. Path arrowPath;
  47981. arrowPath.addArrow (Line<float> (50.0f, 0.0f, 50.0f, 100.0f), 40.0f, 100.0f, 50.0f);
  47982. DrawablePath arrowImage;
  47983. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  47984. arrowImage.setPath (arrowPath);
  47985. downButton->setImages (&arrowImage);
  47986. }
  47987. updateButtons();
  47988. }
  47989. FileSearchPathListComponent::~FileSearchPathListComponent()
  47990. {
  47991. deleteAllChildren();
  47992. }
  47993. void FileSearchPathListComponent::updateButtons()
  47994. {
  47995. const bool anythingSelected = listBox->getNumSelectedRows() > 0;
  47996. removeButton->setEnabled (anythingSelected);
  47997. changeButton->setEnabled (anythingSelected);
  47998. upButton->setEnabled (anythingSelected);
  47999. downButton->setEnabled (anythingSelected);
  48000. }
  48001. void FileSearchPathListComponent::changed()
  48002. {
  48003. listBox->updateContent();
  48004. listBox->repaint();
  48005. updateButtons();
  48006. }
  48007. void FileSearchPathListComponent::setPath (const FileSearchPath& newPath)
  48008. {
  48009. if (newPath.toString() != path.toString())
  48010. {
  48011. path = newPath;
  48012. changed();
  48013. }
  48014. }
  48015. void FileSearchPathListComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  48016. {
  48017. defaultBrowseTarget = newDefaultDirectory;
  48018. }
  48019. int FileSearchPathListComponent::getNumRows()
  48020. {
  48021. return path.getNumPaths();
  48022. }
  48023. void FileSearchPathListComponent::paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected)
  48024. {
  48025. if (rowIsSelected)
  48026. g.fillAll (findColour (TextEditor::highlightColourId));
  48027. g.setColour (findColour (ListBox::textColourId));
  48028. Font f (height * 0.7f);
  48029. f.setHorizontalScale (0.9f);
  48030. g.setFont (f);
  48031. g.drawText (path [rowNumber].getFullPathName(),
  48032. 4, 0, width - 6, height,
  48033. Justification::centredLeft, true);
  48034. }
  48035. void FileSearchPathListComponent::deleteKeyPressed (int row)
  48036. {
  48037. if (((unsigned int) row) < (unsigned int) path.getNumPaths())
  48038. {
  48039. path.remove (row);
  48040. changed();
  48041. }
  48042. }
  48043. void FileSearchPathListComponent::returnKeyPressed (int row)
  48044. {
  48045. FileChooser chooser (TRANS("Change folder..."), path [row], "*");
  48046. if (chooser.browseForDirectory())
  48047. {
  48048. path.remove (row);
  48049. path.add (chooser.getResult(), row);
  48050. changed();
  48051. }
  48052. }
  48053. void FileSearchPathListComponent::listBoxItemDoubleClicked (int row, const MouseEvent&)
  48054. {
  48055. returnKeyPressed (row);
  48056. }
  48057. void FileSearchPathListComponent::selectedRowsChanged (int)
  48058. {
  48059. updateButtons();
  48060. }
  48061. void FileSearchPathListComponent::paint (Graphics& g)
  48062. {
  48063. g.fillAll (findColour (backgroundColourId));
  48064. }
  48065. void FileSearchPathListComponent::resized()
  48066. {
  48067. const int buttonH = 22;
  48068. const int buttonY = getHeight() - buttonH - 4;
  48069. listBox->setBounds (2, 2, getWidth() - 4, buttonY - 5);
  48070. addButton->setBounds (2, buttonY, buttonH, buttonH);
  48071. removeButton->setBounds (addButton->getRight(), buttonY, buttonH, buttonH);
  48072. changeButton->changeWidthToFitText (buttonH);
  48073. downButton->setSize (buttonH * 2, buttonH);
  48074. upButton->setSize (buttonH * 2, buttonH);
  48075. downButton->setTopRightPosition (getWidth() - 2, buttonY);
  48076. upButton->setTopRightPosition (downButton->getX() - 4, buttonY);
  48077. changeButton->setTopRightPosition (upButton->getX() - 8, buttonY);
  48078. }
  48079. bool FileSearchPathListComponent::isInterestedInFileDrag (const StringArray&)
  48080. {
  48081. return true;
  48082. }
  48083. void FileSearchPathListComponent::filesDropped (const StringArray& filenames, int, int mouseY)
  48084. {
  48085. for (int i = filenames.size(); --i >= 0;)
  48086. {
  48087. const File f (filenames[i]);
  48088. if (f.isDirectory())
  48089. {
  48090. const int row = listBox->getRowContainingPosition (0, mouseY - listBox->getY());
  48091. path.add (f, row);
  48092. changed();
  48093. }
  48094. }
  48095. }
  48096. void FileSearchPathListComponent::buttonClicked (Button* button)
  48097. {
  48098. const int currentRow = listBox->getSelectedRow();
  48099. if (button == removeButton)
  48100. {
  48101. deleteKeyPressed (currentRow);
  48102. }
  48103. else if (button == addButton)
  48104. {
  48105. File start (defaultBrowseTarget);
  48106. if (start == File::nonexistent)
  48107. start = path [0];
  48108. if (start == File::nonexistent)
  48109. start = File::getCurrentWorkingDirectory();
  48110. FileChooser chooser (TRANS("Add a folder..."), start, "*");
  48111. if (chooser.browseForDirectory())
  48112. {
  48113. path.add (chooser.getResult(), currentRow);
  48114. }
  48115. }
  48116. else if (button == changeButton)
  48117. {
  48118. returnKeyPressed (currentRow);
  48119. }
  48120. else if (button == upButton)
  48121. {
  48122. if (currentRow > 0 && currentRow < path.getNumPaths())
  48123. {
  48124. const File f (path[currentRow]);
  48125. path.remove (currentRow);
  48126. path.add (f, currentRow - 1);
  48127. listBox->selectRow (currentRow - 1);
  48128. }
  48129. }
  48130. else if (button == downButton)
  48131. {
  48132. if (currentRow >= 0 && currentRow < path.getNumPaths() - 1)
  48133. {
  48134. const File f (path[currentRow]);
  48135. path.remove (currentRow);
  48136. path.add (f, currentRow + 1);
  48137. listBox->selectRow (currentRow + 1);
  48138. }
  48139. }
  48140. changed();
  48141. }
  48142. END_JUCE_NAMESPACE
  48143. /*** End of inlined file: juce_FileSearchPathListComponent.cpp ***/
  48144. /*** Start of inlined file: juce_FileTreeComponent.cpp ***/
  48145. BEGIN_JUCE_NAMESPACE
  48146. const Image juce_createIconForFile (const File& file);
  48147. class FileListTreeItem : public TreeViewItem,
  48148. public TimeSliceClient,
  48149. public AsyncUpdater,
  48150. public ChangeListener
  48151. {
  48152. public:
  48153. FileListTreeItem (FileTreeComponent& owner_,
  48154. DirectoryContentsList* const parentContentsList_,
  48155. const int indexInContentsList_,
  48156. const File& file_,
  48157. TimeSliceThread& thread_)
  48158. : file (file_),
  48159. owner (owner_),
  48160. parentContentsList (parentContentsList_),
  48161. indexInContentsList (indexInContentsList_),
  48162. subContentsList (0),
  48163. canDeleteSubContentsList (false),
  48164. thread (thread_),
  48165. icon (0)
  48166. {
  48167. DirectoryContentsList::FileInfo fileInfo;
  48168. if (parentContentsList_ != 0
  48169. && parentContentsList_->getFileInfo (indexInContentsList_, fileInfo))
  48170. {
  48171. fileSize = File::descriptionOfSizeInBytes (fileInfo.fileSize);
  48172. modTime = fileInfo.modificationTime.formatted ("%d %b '%y %H:%M");
  48173. isDirectory = fileInfo.isDirectory;
  48174. }
  48175. else
  48176. {
  48177. isDirectory = true;
  48178. }
  48179. }
  48180. ~FileListTreeItem()
  48181. {
  48182. thread.removeTimeSliceClient (this);
  48183. clearSubItems();
  48184. if (canDeleteSubContentsList)
  48185. delete subContentsList;
  48186. }
  48187. bool mightContainSubItems() { return isDirectory; }
  48188. const String getUniqueName() const { return file.getFullPathName(); }
  48189. int getItemHeight() const { return 22; }
  48190. const String getDragSourceDescription() { return owner.getDragAndDropDescription(); }
  48191. void itemOpennessChanged (bool isNowOpen)
  48192. {
  48193. if (isNowOpen)
  48194. {
  48195. clearSubItems();
  48196. isDirectory = file.isDirectory();
  48197. if (isDirectory)
  48198. {
  48199. if (subContentsList == 0)
  48200. {
  48201. jassert (parentContentsList != 0);
  48202. DirectoryContentsList* const l = new DirectoryContentsList (parentContentsList->getFilter(), thread);
  48203. l->setDirectory (file, true, true);
  48204. setSubContentsList (l);
  48205. canDeleteSubContentsList = true;
  48206. }
  48207. changeListenerCallback (0);
  48208. }
  48209. }
  48210. }
  48211. void setSubContentsList (DirectoryContentsList* newList)
  48212. {
  48213. jassert (subContentsList == 0);
  48214. subContentsList = newList;
  48215. newList->addChangeListener (this);
  48216. }
  48217. void changeListenerCallback (void*)
  48218. {
  48219. clearSubItems();
  48220. if (isOpen() && subContentsList != 0)
  48221. {
  48222. for (int i = 0; i < subContentsList->getNumFiles(); ++i)
  48223. {
  48224. FileListTreeItem* const item
  48225. = new FileListTreeItem (owner, subContentsList, i, subContentsList->getFile(i), thread);
  48226. addSubItem (item);
  48227. }
  48228. }
  48229. }
  48230. void paintItem (Graphics& g, int width, int height)
  48231. {
  48232. if (file != File::nonexistent)
  48233. {
  48234. updateIcon (true);
  48235. if (icon.isNull())
  48236. thread.addTimeSliceClient (this);
  48237. }
  48238. owner.getLookAndFeel()
  48239. .drawFileBrowserRow (g, width, height,
  48240. file.getFileName(),
  48241. &icon, fileSize, modTime,
  48242. isDirectory, isSelected(),
  48243. indexInContentsList, owner);
  48244. }
  48245. void itemClicked (const MouseEvent& e)
  48246. {
  48247. owner.sendMouseClickMessage (file, e);
  48248. }
  48249. void itemDoubleClicked (const MouseEvent& e)
  48250. {
  48251. TreeViewItem::itemDoubleClicked (e);
  48252. owner.sendDoubleClickMessage (file);
  48253. }
  48254. void itemSelectionChanged (bool)
  48255. {
  48256. owner.sendSelectionChangeMessage();
  48257. }
  48258. bool useTimeSlice()
  48259. {
  48260. updateIcon (false);
  48261. thread.removeTimeSliceClient (this);
  48262. return false;
  48263. }
  48264. void handleAsyncUpdate()
  48265. {
  48266. owner.repaint();
  48267. }
  48268. const File file;
  48269. juce_UseDebuggingNewOperator
  48270. private:
  48271. FileTreeComponent& owner;
  48272. DirectoryContentsList* parentContentsList;
  48273. int indexInContentsList;
  48274. DirectoryContentsList* subContentsList;
  48275. bool isDirectory, canDeleteSubContentsList;
  48276. TimeSliceThread& thread;
  48277. Image icon;
  48278. String fileSize;
  48279. String modTime;
  48280. void updateIcon (const bool onlyUpdateIfCached)
  48281. {
  48282. if (icon.isNull())
  48283. {
  48284. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  48285. Image im (ImageCache::getFromHashCode (hashCode));
  48286. if (im.isNull() && ! onlyUpdateIfCached)
  48287. {
  48288. im = juce_createIconForFile (file);
  48289. if (im.isValid())
  48290. ImageCache::addImageToCache (im, hashCode);
  48291. }
  48292. if (im.isValid())
  48293. {
  48294. icon = im;
  48295. triggerAsyncUpdate();
  48296. }
  48297. }
  48298. }
  48299. };
  48300. FileTreeComponent::FileTreeComponent (DirectoryContentsList& listToShow)
  48301. : DirectoryContentsDisplayComponent (listToShow)
  48302. {
  48303. FileListTreeItem* const root
  48304. = new FileListTreeItem (*this, 0, 0, listToShow.getDirectory(),
  48305. listToShow.getTimeSliceThread());
  48306. root->setSubContentsList (&listToShow);
  48307. setRootItemVisible (false);
  48308. setRootItem (root);
  48309. }
  48310. FileTreeComponent::~FileTreeComponent()
  48311. {
  48312. deleteRootItem();
  48313. }
  48314. const File FileTreeComponent::getSelectedFile (const int index) const
  48315. {
  48316. const FileListTreeItem* const item = dynamic_cast <const FileListTreeItem*> (getSelectedItem (index));
  48317. return item != 0 ? item->file
  48318. : File::nonexistent;
  48319. }
  48320. void FileTreeComponent::deselectAllFiles()
  48321. {
  48322. clearSelectedItems();
  48323. }
  48324. void FileTreeComponent::scrollToTop()
  48325. {
  48326. getViewport()->getVerticalScrollBar()->setCurrentRangeStart (0);
  48327. }
  48328. void FileTreeComponent::setDragAndDropDescription (const String& description)
  48329. {
  48330. dragAndDropDescription = description;
  48331. }
  48332. END_JUCE_NAMESPACE
  48333. /*** End of inlined file: juce_FileTreeComponent.cpp ***/
  48334. /*** Start of inlined file: juce_ImagePreviewComponent.cpp ***/
  48335. BEGIN_JUCE_NAMESPACE
  48336. ImagePreviewComponent::ImagePreviewComponent()
  48337. {
  48338. }
  48339. ImagePreviewComponent::~ImagePreviewComponent()
  48340. {
  48341. }
  48342. void ImagePreviewComponent::getThumbSize (int& w, int& h) const
  48343. {
  48344. const int availableW = proportionOfWidth (0.97f);
  48345. const int availableH = getHeight() - 13 * 4;
  48346. const double scale = jmin (1.0,
  48347. availableW / (double) w,
  48348. availableH / (double) h);
  48349. w = roundToInt (scale * w);
  48350. h = roundToInt (scale * h);
  48351. }
  48352. void ImagePreviewComponent::selectedFileChanged (const File& file)
  48353. {
  48354. if (fileToLoad != file)
  48355. {
  48356. fileToLoad = file;
  48357. startTimer (100);
  48358. }
  48359. }
  48360. void ImagePreviewComponent::timerCallback()
  48361. {
  48362. stopTimer();
  48363. currentThumbnail = Image::null;
  48364. currentDetails = String::empty;
  48365. repaint();
  48366. ScopedPointer <FileInputStream> in (fileToLoad.createInputStream());
  48367. if (in != 0)
  48368. {
  48369. ImageFileFormat* const format = ImageFileFormat::findImageFormatForStream (*in);
  48370. if (format != 0)
  48371. {
  48372. currentThumbnail = format->decodeImage (*in);
  48373. if (currentThumbnail.isValid())
  48374. {
  48375. int w = currentThumbnail.getWidth();
  48376. int h = currentThumbnail.getHeight();
  48377. currentDetails
  48378. << fileToLoad.getFileName() << "\n"
  48379. << format->getFormatName() << "\n"
  48380. << w << " x " << h << " pixels\n"
  48381. << File::descriptionOfSizeInBytes (fileToLoad.getSize());
  48382. getThumbSize (w, h);
  48383. currentThumbnail = currentThumbnail.rescaled (w, h);
  48384. }
  48385. }
  48386. }
  48387. }
  48388. void ImagePreviewComponent::paint (Graphics& g)
  48389. {
  48390. if (currentThumbnail.isValid())
  48391. {
  48392. g.setFont (13.0f);
  48393. int w = currentThumbnail.getWidth();
  48394. int h = currentThumbnail.getHeight();
  48395. getThumbSize (w, h);
  48396. const int numLines = 4;
  48397. const int totalH = 13 * numLines + h + 4;
  48398. const int y = (getHeight() - totalH) / 2;
  48399. g.drawImageWithin (currentThumbnail,
  48400. (getWidth() - w) / 2, y, w, h,
  48401. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  48402. false);
  48403. g.drawFittedText (currentDetails,
  48404. 0, y + h + 4, getWidth(), 100,
  48405. Justification::centredTop, numLines);
  48406. }
  48407. }
  48408. END_JUCE_NAMESPACE
  48409. /*** End of inlined file: juce_ImagePreviewComponent.cpp ***/
  48410. /*** Start of inlined file: juce_WildcardFileFilter.cpp ***/
  48411. BEGIN_JUCE_NAMESPACE
  48412. WildcardFileFilter::WildcardFileFilter (const String& fileWildcardPatterns,
  48413. const String& directoryWildcardPatterns,
  48414. const String& description_)
  48415. : FileFilter (description_.isEmpty() ? fileWildcardPatterns
  48416. : (description_ + " (" + fileWildcardPatterns + ")"))
  48417. {
  48418. parse (fileWildcardPatterns, fileWildcards);
  48419. parse (directoryWildcardPatterns, directoryWildcards);
  48420. }
  48421. WildcardFileFilter::~WildcardFileFilter()
  48422. {
  48423. }
  48424. bool WildcardFileFilter::isFileSuitable (const File& file) const
  48425. {
  48426. return match (file, fileWildcards);
  48427. }
  48428. bool WildcardFileFilter::isDirectorySuitable (const File& file) const
  48429. {
  48430. return match (file, directoryWildcards);
  48431. }
  48432. void WildcardFileFilter::parse (const String& pattern, StringArray& result)
  48433. {
  48434. result.addTokens (pattern.toLowerCase(), ";,", "\"'");
  48435. result.trim();
  48436. result.removeEmptyStrings();
  48437. // special case for *.*, because people use it to mean "any file", but it
  48438. // would actually ignore files with no extension.
  48439. for (int i = result.size(); --i >= 0;)
  48440. if (result[i] == "*.*")
  48441. result.set (i, "*");
  48442. }
  48443. bool WildcardFileFilter::match (const File& file, const StringArray& wildcards)
  48444. {
  48445. const String filename (file.getFileName());
  48446. for (int i = wildcards.size(); --i >= 0;)
  48447. if (filename.matchesWildcard (wildcards[i], true))
  48448. return true;
  48449. return false;
  48450. }
  48451. END_JUCE_NAMESPACE
  48452. /*** End of inlined file: juce_WildcardFileFilter.cpp ***/
  48453. /*** Start of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  48454. BEGIN_JUCE_NAMESPACE
  48455. KeyboardFocusTraverser::KeyboardFocusTraverser()
  48456. {
  48457. }
  48458. KeyboardFocusTraverser::~KeyboardFocusTraverser()
  48459. {
  48460. }
  48461. namespace KeyboardFocusHelpers
  48462. {
  48463. // This will sort a set of components, so that they are ordered in terms of
  48464. // left-to-right and then top-to-bottom.
  48465. class ScreenPositionComparator
  48466. {
  48467. public:
  48468. ScreenPositionComparator() {}
  48469. static int compareElements (const Component* const first, const Component* const second)
  48470. {
  48471. int explicitOrder1 = first->getExplicitFocusOrder();
  48472. if (explicitOrder1 <= 0)
  48473. explicitOrder1 = std::numeric_limits<int>::max() / 2;
  48474. int explicitOrder2 = second->getExplicitFocusOrder();
  48475. if (explicitOrder2 <= 0)
  48476. explicitOrder2 = std::numeric_limits<int>::max() / 2;
  48477. if (explicitOrder1 != explicitOrder2)
  48478. return explicitOrder1 - explicitOrder2;
  48479. const int diff = first->getY() - second->getY();
  48480. return (diff == 0) ? first->getX() - second->getX()
  48481. : diff;
  48482. }
  48483. };
  48484. static void findAllFocusableComponents (Component* const parent, Array <Component*>& comps)
  48485. {
  48486. if (parent->getNumChildComponents() > 0)
  48487. {
  48488. Array <Component*> localComps;
  48489. ScreenPositionComparator comparator;
  48490. int i;
  48491. for (i = parent->getNumChildComponents(); --i >= 0;)
  48492. {
  48493. Component* const c = parent->getChildComponent (i);
  48494. if (c->isVisible() && c->isEnabled())
  48495. localComps.addSorted (comparator, c);
  48496. }
  48497. for (i = 0; i < localComps.size(); ++i)
  48498. {
  48499. Component* const c = localComps.getUnchecked (i);
  48500. if (c->getWantsKeyboardFocus())
  48501. comps.add (c);
  48502. if (! c->isFocusContainer())
  48503. findAllFocusableComponents (c, comps);
  48504. }
  48505. }
  48506. }
  48507. }
  48508. static Component* getIncrementedComponent (Component* const current, const int delta)
  48509. {
  48510. Component* focusContainer = current->getParentComponent();
  48511. if (focusContainer != 0)
  48512. {
  48513. while (focusContainer->getParentComponent() != 0 && ! focusContainer->isFocusContainer())
  48514. focusContainer = focusContainer->getParentComponent();
  48515. if (focusContainer != 0)
  48516. {
  48517. Array <Component*> comps;
  48518. KeyboardFocusHelpers::findAllFocusableComponents (focusContainer, comps);
  48519. if (comps.size() > 0)
  48520. {
  48521. const int index = comps.indexOf (current);
  48522. return comps [(index + comps.size() + delta) % comps.size()];
  48523. }
  48524. }
  48525. }
  48526. return 0;
  48527. }
  48528. Component* KeyboardFocusTraverser::getNextComponent (Component* current)
  48529. {
  48530. return getIncrementedComponent (current, 1);
  48531. }
  48532. Component* KeyboardFocusTraverser::getPreviousComponent (Component* current)
  48533. {
  48534. return getIncrementedComponent (current, -1);
  48535. }
  48536. Component* KeyboardFocusTraverser::getDefaultComponent (Component* parentComponent)
  48537. {
  48538. Array <Component*> comps;
  48539. if (parentComponent != 0)
  48540. KeyboardFocusHelpers::findAllFocusableComponents (parentComponent, comps);
  48541. return comps.getFirst();
  48542. }
  48543. END_JUCE_NAMESPACE
  48544. /*** End of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  48545. /*** Start of inlined file: juce_KeyListener.cpp ***/
  48546. BEGIN_JUCE_NAMESPACE
  48547. bool KeyListener::keyStateChanged (const bool, Component*)
  48548. {
  48549. return false;
  48550. }
  48551. END_JUCE_NAMESPACE
  48552. /*** End of inlined file: juce_KeyListener.cpp ***/
  48553. /*** Start of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  48554. BEGIN_JUCE_NAMESPACE
  48555. // N.B. these two includes are put here deliberately to avoid problems with
  48556. // old GCCs failing on long include paths
  48557. const int maxKeys = 3;
  48558. class KeyMappingChangeButton : public Button
  48559. {
  48560. public:
  48561. KeyMappingChangeButton (KeyMappingEditorComponent* const owner_,
  48562. const CommandID commandID_,
  48563. const String& keyName,
  48564. const int keyNum_)
  48565. : Button (keyName),
  48566. owner (owner_),
  48567. commandID (commandID_),
  48568. keyNum (keyNum_)
  48569. {
  48570. setWantsKeyboardFocus (false);
  48571. setTriggeredOnMouseDown (keyNum >= 0);
  48572. if (keyNum_ < 0)
  48573. setTooltip (TRANS("adds a new key-mapping"));
  48574. else
  48575. setTooltip (TRANS("click to change this key-mapping"));
  48576. }
  48577. ~KeyMappingChangeButton()
  48578. {
  48579. }
  48580. void paintButton (Graphics& g, bool /*isOver*/, bool /*isDown*/)
  48581. {
  48582. getLookAndFeel().drawKeymapChangeButton (g, getWidth(), getHeight(), *this,
  48583. keyNum >= 0 ? getName() : String::empty);
  48584. }
  48585. void clicked()
  48586. {
  48587. if (keyNum >= 0)
  48588. {
  48589. // existing key clicked..
  48590. PopupMenu m;
  48591. m.addItem (1, TRANS("change this key-mapping"));
  48592. m.addSeparator();
  48593. m.addItem (2, TRANS("remove this key-mapping"));
  48594. const int res = m.show();
  48595. if (res == 1)
  48596. {
  48597. owner->assignNewKey (commandID, keyNum);
  48598. }
  48599. else if (res == 2)
  48600. {
  48601. owner->getMappings()->removeKeyPress (commandID, keyNum);
  48602. }
  48603. }
  48604. else
  48605. {
  48606. // + button pressed..
  48607. owner->assignNewKey (commandID, -1);
  48608. }
  48609. }
  48610. void fitToContent (const int h) throw()
  48611. {
  48612. if (keyNum < 0)
  48613. {
  48614. setSize (h, h);
  48615. }
  48616. else
  48617. {
  48618. Font f (h * 0.6f);
  48619. setSize (jlimit (h * 4, h * 8, 6 + f.getStringWidth (getName())), h);
  48620. }
  48621. }
  48622. juce_UseDebuggingNewOperator
  48623. private:
  48624. KeyMappingEditorComponent* const owner;
  48625. const CommandID commandID;
  48626. const int keyNum;
  48627. KeyMappingChangeButton (const KeyMappingChangeButton&);
  48628. KeyMappingChangeButton& operator= (const KeyMappingChangeButton&);
  48629. };
  48630. class KeyMappingItemComponent : public Component
  48631. {
  48632. public:
  48633. KeyMappingItemComponent (KeyMappingEditorComponent* const owner_,
  48634. const CommandID commandID_)
  48635. : owner (owner_),
  48636. commandID (commandID_)
  48637. {
  48638. setInterceptsMouseClicks (false, true);
  48639. const bool isReadOnly = owner_->isCommandReadOnly (commandID);
  48640. const Array <KeyPress> keyPresses (owner_->getMappings()->getKeyPressesAssignedToCommand (commandID));
  48641. for (int i = 0; i < jmin (maxKeys, keyPresses.size()); ++i)
  48642. {
  48643. KeyMappingChangeButton* const kb
  48644. = new KeyMappingChangeButton (owner_, commandID,
  48645. owner_->getDescriptionForKeyPress (keyPresses.getReference (i)), i);
  48646. kb->setEnabled (! isReadOnly);
  48647. addAndMakeVisible (kb);
  48648. }
  48649. KeyMappingChangeButton* const kb
  48650. = new KeyMappingChangeButton (owner_, commandID, String::empty, -1);
  48651. addChildComponent (kb);
  48652. kb->setVisible (keyPresses.size() < maxKeys && ! isReadOnly);
  48653. }
  48654. ~KeyMappingItemComponent()
  48655. {
  48656. deleteAllChildren();
  48657. }
  48658. void paint (Graphics& g)
  48659. {
  48660. g.setFont (getHeight() * 0.7f);
  48661. g.setColour (findColour (KeyMappingEditorComponent::textColourId));
  48662. g.drawFittedText (owner->getMappings()->getCommandManager()->getNameOfCommand (commandID),
  48663. 4, 0, jmax (40, getChildComponent (0)->getX() - 5), getHeight(),
  48664. Justification::centredLeft, true);
  48665. }
  48666. void resized()
  48667. {
  48668. int x = getWidth() - 4;
  48669. for (int i = getNumChildComponents(); --i >= 0;)
  48670. {
  48671. KeyMappingChangeButton* const kb = dynamic_cast <KeyMappingChangeButton*> (getChildComponent (i));
  48672. kb->fitToContent (getHeight() - 2);
  48673. kb->setTopRightPosition (x, 1);
  48674. x -= kb->getWidth() + 5;
  48675. }
  48676. }
  48677. juce_UseDebuggingNewOperator
  48678. private:
  48679. KeyMappingEditorComponent* const owner;
  48680. const CommandID commandID;
  48681. KeyMappingItemComponent (const KeyMappingItemComponent&);
  48682. KeyMappingItemComponent& operator= (const KeyMappingItemComponent&);
  48683. };
  48684. class KeyMappingTreeViewItem : public TreeViewItem
  48685. {
  48686. public:
  48687. KeyMappingTreeViewItem (KeyMappingEditorComponent* const owner_,
  48688. const CommandID commandID_)
  48689. : owner (owner_),
  48690. commandID (commandID_)
  48691. {
  48692. }
  48693. ~KeyMappingTreeViewItem()
  48694. {
  48695. }
  48696. const String getUniqueName() const { return String ((int) commandID) + "_id"; }
  48697. bool mightContainSubItems() { return false; }
  48698. int getItemHeight() const { return 20; }
  48699. Component* createItemComponent()
  48700. {
  48701. return new KeyMappingItemComponent (owner, commandID);
  48702. }
  48703. juce_UseDebuggingNewOperator
  48704. private:
  48705. KeyMappingEditorComponent* const owner;
  48706. const CommandID commandID;
  48707. KeyMappingTreeViewItem (const KeyMappingTreeViewItem&);
  48708. KeyMappingTreeViewItem& operator= (const KeyMappingTreeViewItem&);
  48709. };
  48710. class KeyCategoryTreeViewItem : public TreeViewItem
  48711. {
  48712. public:
  48713. KeyCategoryTreeViewItem (KeyMappingEditorComponent* const owner_,
  48714. const String& name)
  48715. : owner (owner_),
  48716. categoryName (name)
  48717. {
  48718. }
  48719. ~KeyCategoryTreeViewItem()
  48720. {
  48721. }
  48722. const String getUniqueName() const { return categoryName + "_cat"; }
  48723. bool mightContainSubItems() { return true; }
  48724. int getItemHeight() const { return 28; }
  48725. void paintItem (Graphics& g, int width, int height)
  48726. {
  48727. g.setFont (height * 0.6f, Font::bold);
  48728. g.setColour (owner->findColour (KeyMappingEditorComponent::textColourId));
  48729. g.drawText (categoryName,
  48730. 2, 0, width - 2, height,
  48731. Justification::centredLeft, true);
  48732. }
  48733. void itemOpennessChanged (bool isNowOpen)
  48734. {
  48735. if (isNowOpen)
  48736. {
  48737. if (getNumSubItems() == 0)
  48738. {
  48739. Array <CommandID> commands (owner->getMappings()->getCommandManager()->getCommandsInCategory (categoryName));
  48740. for (int i = 0; i < commands.size(); ++i)
  48741. {
  48742. if (owner->shouldCommandBeIncluded (commands[i]))
  48743. addSubItem (new KeyMappingTreeViewItem (owner, commands[i]));
  48744. }
  48745. }
  48746. }
  48747. else
  48748. {
  48749. clearSubItems();
  48750. }
  48751. }
  48752. juce_UseDebuggingNewOperator
  48753. private:
  48754. KeyMappingEditorComponent* owner;
  48755. String categoryName;
  48756. KeyCategoryTreeViewItem (const KeyCategoryTreeViewItem&);
  48757. KeyCategoryTreeViewItem& operator= (const KeyCategoryTreeViewItem&);
  48758. };
  48759. KeyMappingEditorComponent::KeyMappingEditorComponent (KeyPressMappingSet* const mappingManager,
  48760. const bool showResetToDefaultButton)
  48761. : mappings (mappingManager)
  48762. {
  48763. jassert (mappingManager != 0); // can't be null!
  48764. mappingManager->addChangeListener (this);
  48765. setLinesDrawnForSubItems (false);
  48766. resetButton = 0;
  48767. if (showResetToDefaultButton)
  48768. {
  48769. addAndMakeVisible (resetButton = new TextButton (TRANS("reset to defaults")));
  48770. resetButton->addButtonListener (this);
  48771. }
  48772. addAndMakeVisible (tree = new TreeView());
  48773. tree->setColour (TreeView::backgroundColourId, findColour (backgroundColourId));
  48774. tree->setRootItemVisible (false);
  48775. tree->setDefaultOpenness (true);
  48776. tree->setRootItem (this);
  48777. }
  48778. KeyMappingEditorComponent::~KeyMappingEditorComponent()
  48779. {
  48780. mappings->removeChangeListener (this);
  48781. deleteAllChildren();
  48782. }
  48783. bool KeyMappingEditorComponent::mightContainSubItems()
  48784. {
  48785. return true;
  48786. }
  48787. const String KeyMappingEditorComponent::getUniqueName() const
  48788. {
  48789. return "keys";
  48790. }
  48791. void KeyMappingEditorComponent::setColours (const Colour& mainBackground,
  48792. const Colour& textColour)
  48793. {
  48794. setColour (backgroundColourId, mainBackground);
  48795. setColour (textColourId, textColour);
  48796. tree->setColour (TreeView::backgroundColourId, mainBackground);
  48797. }
  48798. void KeyMappingEditorComponent::parentHierarchyChanged()
  48799. {
  48800. changeListenerCallback (0);
  48801. }
  48802. void KeyMappingEditorComponent::resized()
  48803. {
  48804. int h = getHeight();
  48805. if (resetButton != 0)
  48806. {
  48807. const int buttonHeight = 20;
  48808. h -= buttonHeight + 8;
  48809. int x = getWidth() - 8;
  48810. resetButton->changeWidthToFitText (buttonHeight);
  48811. resetButton->setTopRightPosition (x, h + 6);
  48812. }
  48813. tree->setBounds (0, 0, getWidth(), h);
  48814. }
  48815. void KeyMappingEditorComponent::buttonClicked (Button* button)
  48816. {
  48817. if (button == resetButton)
  48818. {
  48819. if (AlertWindow::showOkCancelBox (AlertWindow::QuestionIcon,
  48820. TRANS("Reset to defaults"),
  48821. TRANS("Are you sure you want to reset all the key-mappings to their default state?"),
  48822. TRANS("Reset")))
  48823. {
  48824. mappings->resetToDefaultMappings();
  48825. }
  48826. }
  48827. }
  48828. void KeyMappingEditorComponent::changeListenerCallback (void*)
  48829. {
  48830. ScopedPointer <XmlElement> oldOpenness (tree->getOpennessState (true));
  48831. clearSubItems();
  48832. const StringArray categories (mappings->getCommandManager()->getCommandCategories());
  48833. for (int i = 0; i < categories.size(); ++i)
  48834. {
  48835. const Array <CommandID> commands (mappings->getCommandManager()->getCommandsInCategory (categories[i]));
  48836. int count = 0;
  48837. for (int j = 0; j < commands.size(); ++j)
  48838. if (shouldCommandBeIncluded (commands[j]))
  48839. ++count;
  48840. if (count > 0)
  48841. addSubItem (new KeyCategoryTreeViewItem (this, categories[i]));
  48842. }
  48843. if (oldOpenness != 0)
  48844. tree->restoreOpennessState (*oldOpenness);
  48845. }
  48846. class KeyEntryWindow : public AlertWindow
  48847. {
  48848. public:
  48849. KeyEntryWindow (KeyMappingEditorComponent* const owner_)
  48850. : AlertWindow (TRANS("New key-mapping"),
  48851. TRANS("Please press a key combination now..."),
  48852. AlertWindow::NoIcon),
  48853. owner (owner_)
  48854. {
  48855. addButton (TRANS("ok"), 1);
  48856. addButton (TRANS("cancel"), 0);
  48857. // (avoid return + escape keys getting processed by the buttons..)
  48858. for (int i = getNumChildComponents(); --i >= 0;)
  48859. getChildComponent (i)->setWantsKeyboardFocus (false);
  48860. setWantsKeyboardFocus (true);
  48861. grabKeyboardFocus();
  48862. }
  48863. ~KeyEntryWindow()
  48864. {
  48865. }
  48866. bool keyPressed (const KeyPress& key)
  48867. {
  48868. lastPress = key;
  48869. String message (TRANS("Key: ") + owner->getDescriptionForKeyPress (key));
  48870. const CommandID previousCommand = owner->getMappings()->findCommandForKeyPress (key);
  48871. if (previousCommand != 0)
  48872. {
  48873. message << "\n\n"
  48874. << TRANS("(Currently assigned to \"")
  48875. << owner->getMappings()->getCommandManager()->getNameOfCommand (previousCommand)
  48876. << "\")";
  48877. }
  48878. setMessage (message);
  48879. return true;
  48880. }
  48881. bool keyStateChanged (bool)
  48882. {
  48883. return true;
  48884. }
  48885. KeyPress lastPress;
  48886. juce_UseDebuggingNewOperator
  48887. private:
  48888. KeyMappingEditorComponent* owner;
  48889. KeyEntryWindow (const KeyEntryWindow&);
  48890. KeyEntryWindow& operator= (const KeyEntryWindow&);
  48891. };
  48892. void KeyMappingEditorComponent::assignNewKey (const CommandID commandID, const int index)
  48893. {
  48894. KeyEntryWindow entryWindow (this);
  48895. if (entryWindow.runModalLoop() != 0)
  48896. {
  48897. entryWindow.setVisible (false);
  48898. if (entryWindow.lastPress.isValid())
  48899. {
  48900. const CommandID previousCommand = mappings->findCommandForKeyPress (entryWindow.lastPress);
  48901. if (previousCommand != 0)
  48902. {
  48903. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  48904. TRANS("Change key-mapping"),
  48905. TRANS("This key is already assigned to the command \"")
  48906. + mappings->getCommandManager()->getNameOfCommand (previousCommand)
  48907. + TRANS("\"\n\nDo you want to re-assign it to this new command instead?"),
  48908. TRANS("re-assign"),
  48909. TRANS("cancel")))
  48910. {
  48911. return;
  48912. }
  48913. }
  48914. mappings->removeKeyPress (entryWindow.lastPress);
  48915. if (index >= 0)
  48916. mappings->removeKeyPress (commandID, index);
  48917. mappings->addKeyPress (commandID, entryWindow.lastPress, index);
  48918. }
  48919. }
  48920. }
  48921. bool KeyMappingEditorComponent::shouldCommandBeIncluded (const CommandID commandID)
  48922. {
  48923. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  48924. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::hiddenFromKeyEditor) == 0);
  48925. }
  48926. bool KeyMappingEditorComponent::isCommandReadOnly (const CommandID commandID)
  48927. {
  48928. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  48929. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::readOnlyInKeyEditor) != 0);
  48930. }
  48931. const String KeyMappingEditorComponent::getDescriptionForKeyPress (const KeyPress& key)
  48932. {
  48933. return key.getTextDescription();
  48934. }
  48935. END_JUCE_NAMESPACE
  48936. /*** End of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  48937. /*** Start of inlined file: juce_KeyPress.cpp ***/
  48938. BEGIN_JUCE_NAMESPACE
  48939. KeyPress::KeyPress() throw()
  48940. : keyCode (0),
  48941. mods (0),
  48942. textCharacter (0)
  48943. {
  48944. }
  48945. KeyPress::KeyPress (const int keyCode_,
  48946. const ModifierKeys& mods_,
  48947. const juce_wchar textCharacter_) throw()
  48948. : keyCode (keyCode_),
  48949. mods (mods_),
  48950. textCharacter (textCharacter_)
  48951. {
  48952. }
  48953. KeyPress::KeyPress (const int keyCode_) throw()
  48954. : keyCode (keyCode_),
  48955. textCharacter (0)
  48956. {
  48957. }
  48958. KeyPress::KeyPress (const KeyPress& other) throw()
  48959. : keyCode (other.keyCode),
  48960. mods (other.mods),
  48961. textCharacter (other.textCharacter)
  48962. {
  48963. }
  48964. KeyPress& KeyPress::operator= (const KeyPress& other) throw()
  48965. {
  48966. keyCode = other.keyCode;
  48967. mods = other.mods;
  48968. textCharacter = other.textCharacter;
  48969. return *this;
  48970. }
  48971. bool KeyPress::operator== (const KeyPress& other) const throw()
  48972. {
  48973. return mods.getRawFlags() == other.mods.getRawFlags()
  48974. && (textCharacter == other.textCharacter
  48975. || textCharacter == 0
  48976. || other.textCharacter == 0)
  48977. && (keyCode == other.keyCode
  48978. || (keyCode < 256
  48979. && other.keyCode < 256
  48980. && CharacterFunctions::toLowerCase ((juce_wchar) keyCode)
  48981. == CharacterFunctions::toLowerCase ((juce_wchar) other.keyCode)));
  48982. }
  48983. bool KeyPress::operator!= (const KeyPress& other) const throw()
  48984. {
  48985. return ! operator== (other);
  48986. }
  48987. bool KeyPress::isCurrentlyDown() const
  48988. {
  48989. return isKeyCurrentlyDown (keyCode)
  48990. && (ModifierKeys::getCurrentModifiers().getRawFlags() & ModifierKeys::allKeyboardModifiers)
  48991. == (mods.getRawFlags() & ModifierKeys::allKeyboardModifiers);
  48992. }
  48993. namespace KeyPressHelpers
  48994. {
  48995. struct KeyNameAndCode
  48996. {
  48997. const char* name;
  48998. int code;
  48999. };
  49000. static const KeyNameAndCode translations[] =
  49001. {
  49002. { "spacebar", KeyPress::spaceKey },
  49003. { "return", KeyPress::returnKey },
  49004. { "escape", KeyPress::escapeKey },
  49005. { "backspace", KeyPress::backspaceKey },
  49006. { "cursor left", KeyPress::leftKey },
  49007. { "cursor right", KeyPress::rightKey },
  49008. { "cursor up", KeyPress::upKey },
  49009. { "cursor down", KeyPress::downKey },
  49010. { "page up", KeyPress::pageUpKey },
  49011. { "page down", KeyPress::pageDownKey },
  49012. { "home", KeyPress::homeKey },
  49013. { "end", KeyPress::endKey },
  49014. { "delete", KeyPress::deleteKey },
  49015. { "insert", KeyPress::insertKey },
  49016. { "tab", KeyPress::tabKey },
  49017. { "play", KeyPress::playKey },
  49018. { "stop", KeyPress::stopKey },
  49019. { "fast forward", KeyPress::fastForwardKey },
  49020. { "rewind", KeyPress::rewindKey }
  49021. };
  49022. static const String numberPadPrefix() { return "numpad "; }
  49023. }
  49024. const KeyPress KeyPress::createFromDescription (const String& desc)
  49025. {
  49026. int modifiers = 0;
  49027. if (desc.containsWholeWordIgnoreCase ("ctrl")
  49028. || desc.containsWholeWordIgnoreCase ("control")
  49029. || desc.containsWholeWordIgnoreCase ("ctl"))
  49030. modifiers |= ModifierKeys::ctrlModifier;
  49031. if (desc.containsWholeWordIgnoreCase ("shift")
  49032. || desc.containsWholeWordIgnoreCase ("shft"))
  49033. modifiers |= ModifierKeys::shiftModifier;
  49034. if (desc.containsWholeWordIgnoreCase ("alt")
  49035. || desc.containsWholeWordIgnoreCase ("option"))
  49036. modifiers |= ModifierKeys::altModifier;
  49037. if (desc.containsWholeWordIgnoreCase ("command")
  49038. || desc.containsWholeWordIgnoreCase ("cmd"))
  49039. modifiers |= ModifierKeys::commandModifier;
  49040. int key = 0;
  49041. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  49042. {
  49043. if (desc.containsWholeWordIgnoreCase (String (KeyPressHelpers::translations[i].name)))
  49044. {
  49045. key = KeyPressHelpers::translations[i].code;
  49046. break;
  49047. }
  49048. }
  49049. if (key == 0)
  49050. {
  49051. // see if it's a numpad key..
  49052. if (desc.containsIgnoreCase (KeyPressHelpers::numberPadPrefix()))
  49053. {
  49054. const juce_wchar lastChar = desc.trimEnd().getLastCharacter();
  49055. if (lastChar >= '0' && lastChar <= '9')
  49056. key = numberPad0 + lastChar - '0';
  49057. else if (lastChar == '+')
  49058. key = numberPadAdd;
  49059. else if (lastChar == '-')
  49060. key = numberPadSubtract;
  49061. else if (lastChar == '*')
  49062. key = numberPadMultiply;
  49063. else if (lastChar == '/')
  49064. key = numberPadDivide;
  49065. else if (lastChar == '.')
  49066. key = numberPadDecimalPoint;
  49067. else if (lastChar == '=')
  49068. key = numberPadEquals;
  49069. else if (desc.endsWith ("separator"))
  49070. key = numberPadSeparator;
  49071. else if (desc.endsWith ("delete"))
  49072. key = numberPadDelete;
  49073. }
  49074. if (key == 0)
  49075. {
  49076. // see if it's a function key..
  49077. if (! desc.containsChar ('#')) // avoid mistaking hex-codes like "#f1"
  49078. for (int i = 1; i <= 12; ++i)
  49079. if (desc.containsWholeWordIgnoreCase ("f" + String (i)))
  49080. key = F1Key + i - 1;
  49081. if (key == 0)
  49082. {
  49083. // give up and use the hex code..
  49084. const int hexCode = desc.fromFirstOccurrenceOf ("#", false, false)
  49085. .toLowerCase()
  49086. .retainCharacters ("0123456789abcdef")
  49087. .getHexValue32();
  49088. if (hexCode > 0)
  49089. key = hexCode;
  49090. else
  49091. key = CharacterFunctions::toUpperCase (desc.getLastCharacter());
  49092. }
  49093. }
  49094. }
  49095. return KeyPress (key, ModifierKeys (modifiers), 0);
  49096. }
  49097. const String KeyPress::getTextDescription() const
  49098. {
  49099. String desc;
  49100. if (keyCode > 0)
  49101. {
  49102. // some keyboard layouts use a shift-key to get the slash, but in those cases, we
  49103. // want to store it as being a slash, not shift+whatever.
  49104. if (textCharacter == '/')
  49105. return "/";
  49106. if (mods.isCtrlDown())
  49107. desc << "ctrl + ";
  49108. if (mods.isShiftDown())
  49109. desc << "shift + ";
  49110. #if JUCE_MAC
  49111. // only do this on the mac, because on Windows ctrl and command are the same,
  49112. // and this would get confusing
  49113. if (mods.isCommandDown())
  49114. desc << "command + ";
  49115. if (mods.isAltDown())
  49116. desc << "option + ";
  49117. #else
  49118. if (mods.isAltDown())
  49119. desc << "alt + ";
  49120. #endif
  49121. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  49122. if (keyCode == KeyPressHelpers::translations[i].code)
  49123. return desc + KeyPressHelpers::translations[i].name;
  49124. if (keyCode >= F1Key && keyCode <= F16Key)
  49125. desc << 'F' << (1 + keyCode - F1Key);
  49126. else if (keyCode >= numberPad0 && keyCode <= numberPad9)
  49127. desc << KeyPressHelpers::numberPadPrefix() << (keyCode - numberPad0);
  49128. else if (keyCode >= 33 && keyCode < 176)
  49129. desc += CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  49130. else if (keyCode == numberPadAdd)
  49131. desc << KeyPressHelpers::numberPadPrefix() << '+';
  49132. else if (keyCode == numberPadSubtract)
  49133. desc << KeyPressHelpers::numberPadPrefix() << '-';
  49134. else if (keyCode == numberPadMultiply)
  49135. desc << KeyPressHelpers::numberPadPrefix() << '*';
  49136. else if (keyCode == numberPadDivide)
  49137. desc << KeyPressHelpers::numberPadPrefix() << '/';
  49138. else if (keyCode == numberPadSeparator)
  49139. desc << KeyPressHelpers::numberPadPrefix() << "separator";
  49140. else if (keyCode == numberPadDecimalPoint)
  49141. desc << KeyPressHelpers::numberPadPrefix() << '.';
  49142. else if (keyCode == numberPadDelete)
  49143. desc << KeyPressHelpers::numberPadPrefix() << "delete";
  49144. else
  49145. desc << '#' << String::toHexString (keyCode);
  49146. }
  49147. return desc;
  49148. }
  49149. END_JUCE_NAMESPACE
  49150. /*** End of inlined file: juce_KeyPress.cpp ***/
  49151. /*** Start of inlined file: juce_KeyPressMappingSet.cpp ***/
  49152. BEGIN_JUCE_NAMESPACE
  49153. KeyPressMappingSet::KeyPressMappingSet (ApplicationCommandManager* const commandManager_)
  49154. : commandManager (commandManager_)
  49155. {
  49156. // A manager is needed to get the descriptions of commands, and will be called when
  49157. // a command is invoked. So you can't leave this null..
  49158. jassert (commandManager_ != 0);
  49159. Desktop::getInstance().addFocusChangeListener (this);
  49160. }
  49161. KeyPressMappingSet::KeyPressMappingSet (const KeyPressMappingSet& other)
  49162. : commandManager (other.commandManager)
  49163. {
  49164. Desktop::getInstance().addFocusChangeListener (this);
  49165. }
  49166. KeyPressMappingSet::~KeyPressMappingSet()
  49167. {
  49168. Desktop::getInstance().removeFocusChangeListener (this);
  49169. }
  49170. const Array <KeyPress> KeyPressMappingSet::getKeyPressesAssignedToCommand (const CommandID commandID) const
  49171. {
  49172. for (int i = 0; i < mappings.size(); ++i)
  49173. if (mappings.getUnchecked(i)->commandID == commandID)
  49174. return mappings.getUnchecked (i)->keypresses;
  49175. return Array <KeyPress> ();
  49176. }
  49177. void KeyPressMappingSet::addKeyPress (const CommandID commandID,
  49178. const KeyPress& newKeyPress,
  49179. int insertIndex)
  49180. {
  49181. // If you specify an upper-case letter but no shift key, how is the user supposed to press it!?
  49182. // Stick to lower-case letters when defining a keypress, to avoid ambiguity.
  49183. jassert (! (CharacterFunctions::isUpperCase (newKeyPress.getTextCharacter())
  49184. && ! newKeyPress.getModifiers().isShiftDown()));
  49185. if (findCommandForKeyPress (newKeyPress) != commandID)
  49186. {
  49187. removeKeyPress (newKeyPress);
  49188. if (newKeyPress.isValid())
  49189. {
  49190. for (int i = mappings.size(); --i >= 0;)
  49191. {
  49192. if (mappings.getUnchecked(i)->commandID == commandID)
  49193. {
  49194. mappings.getUnchecked(i)->keypresses.insert (insertIndex, newKeyPress);
  49195. sendChangeMessage (this);
  49196. return;
  49197. }
  49198. }
  49199. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  49200. if (ci != 0)
  49201. {
  49202. CommandMapping* const cm = new CommandMapping();
  49203. cm->commandID = commandID;
  49204. cm->keypresses.add (newKeyPress);
  49205. cm->wantsKeyUpDownCallbacks = (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) != 0;
  49206. mappings.add (cm);
  49207. sendChangeMessage (this);
  49208. }
  49209. }
  49210. }
  49211. }
  49212. void KeyPressMappingSet::resetToDefaultMappings()
  49213. {
  49214. mappings.clear();
  49215. for (int i = 0; i < commandManager->getNumCommands(); ++i)
  49216. {
  49217. const ApplicationCommandInfo* const ci = commandManager->getCommandForIndex (i);
  49218. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  49219. {
  49220. addKeyPress (ci->commandID,
  49221. ci->defaultKeypresses.getReference (j));
  49222. }
  49223. }
  49224. sendChangeMessage (this);
  49225. }
  49226. void KeyPressMappingSet::resetToDefaultMapping (const CommandID commandID)
  49227. {
  49228. clearAllKeyPresses (commandID);
  49229. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  49230. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  49231. {
  49232. addKeyPress (ci->commandID,
  49233. ci->defaultKeypresses.getReference (j));
  49234. }
  49235. }
  49236. void KeyPressMappingSet::clearAllKeyPresses()
  49237. {
  49238. if (mappings.size() > 0)
  49239. {
  49240. sendChangeMessage (this);
  49241. mappings.clear();
  49242. }
  49243. }
  49244. void KeyPressMappingSet::clearAllKeyPresses (const CommandID commandID)
  49245. {
  49246. for (int i = mappings.size(); --i >= 0;)
  49247. {
  49248. if (mappings.getUnchecked(i)->commandID == commandID)
  49249. {
  49250. mappings.remove (i);
  49251. sendChangeMessage (this);
  49252. }
  49253. }
  49254. }
  49255. void KeyPressMappingSet::removeKeyPress (const KeyPress& keypress)
  49256. {
  49257. if (keypress.isValid())
  49258. {
  49259. for (int i = mappings.size(); --i >= 0;)
  49260. {
  49261. CommandMapping* const cm = mappings.getUnchecked(i);
  49262. for (int j = cm->keypresses.size(); --j >= 0;)
  49263. {
  49264. if (keypress == cm->keypresses [j])
  49265. {
  49266. cm->keypresses.remove (j);
  49267. sendChangeMessage (this);
  49268. }
  49269. }
  49270. }
  49271. }
  49272. }
  49273. void KeyPressMappingSet::removeKeyPress (const CommandID commandID, const int keyPressIndex)
  49274. {
  49275. for (int i = mappings.size(); --i >= 0;)
  49276. {
  49277. if (mappings.getUnchecked(i)->commandID == commandID)
  49278. {
  49279. mappings.getUnchecked(i)->keypresses.remove (keyPressIndex);
  49280. sendChangeMessage (this);
  49281. break;
  49282. }
  49283. }
  49284. }
  49285. CommandID KeyPressMappingSet::findCommandForKeyPress (const KeyPress& keyPress) const throw()
  49286. {
  49287. for (int i = 0; i < mappings.size(); ++i)
  49288. if (mappings.getUnchecked(i)->keypresses.contains (keyPress))
  49289. return mappings.getUnchecked(i)->commandID;
  49290. return 0;
  49291. }
  49292. bool KeyPressMappingSet::containsMapping (const CommandID commandID, const KeyPress& keyPress) const throw()
  49293. {
  49294. for (int i = mappings.size(); --i >= 0;)
  49295. if (mappings.getUnchecked(i)->commandID == commandID)
  49296. return mappings.getUnchecked(i)->keypresses.contains (keyPress);
  49297. return false;
  49298. }
  49299. void KeyPressMappingSet::invokeCommand (const CommandID commandID,
  49300. const KeyPress& key,
  49301. const bool isKeyDown,
  49302. const int millisecsSinceKeyPressed,
  49303. Component* const originatingComponent) const
  49304. {
  49305. ApplicationCommandTarget::InvocationInfo info (commandID);
  49306. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromKeyPress;
  49307. info.isKeyDown = isKeyDown;
  49308. info.keyPress = key;
  49309. info.millisecsSinceKeyPressed = millisecsSinceKeyPressed;
  49310. info.originatingComponent = originatingComponent;
  49311. commandManager->invoke (info, false);
  49312. }
  49313. bool KeyPressMappingSet::restoreFromXml (const XmlElement& xmlVersion)
  49314. {
  49315. if (xmlVersion.hasTagName ("KEYMAPPINGS"))
  49316. {
  49317. if (xmlVersion.getBoolAttribute ("basedOnDefaults", true))
  49318. {
  49319. // if the XML was created as a set of differences from the default mappings,
  49320. // (i.e. by calling createXml (true)), then we need to first restore the defaults.
  49321. resetToDefaultMappings();
  49322. }
  49323. else
  49324. {
  49325. // if the XML was created calling createXml (false), then we need to clear all
  49326. // the keys and treat the xml as describing the entire set of mappings.
  49327. clearAllKeyPresses();
  49328. }
  49329. forEachXmlChildElement (xmlVersion, map)
  49330. {
  49331. const CommandID commandId = map->getStringAttribute ("commandId").getHexValue32();
  49332. if (commandId != 0)
  49333. {
  49334. const KeyPress key (KeyPress::createFromDescription (map->getStringAttribute ("key")));
  49335. if (map->hasTagName ("MAPPING"))
  49336. {
  49337. addKeyPress (commandId, key);
  49338. }
  49339. else if (map->hasTagName ("UNMAPPING"))
  49340. {
  49341. if (containsMapping (commandId, key))
  49342. removeKeyPress (key);
  49343. }
  49344. }
  49345. }
  49346. return true;
  49347. }
  49348. return false;
  49349. }
  49350. XmlElement* KeyPressMappingSet::createXml (const bool saveDifferencesFromDefaultSet) const
  49351. {
  49352. ScopedPointer <KeyPressMappingSet> defaultSet;
  49353. if (saveDifferencesFromDefaultSet)
  49354. {
  49355. defaultSet = new KeyPressMappingSet (commandManager);
  49356. defaultSet->resetToDefaultMappings();
  49357. }
  49358. XmlElement* const doc = new XmlElement ("KEYMAPPINGS");
  49359. doc->setAttribute ("basedOnDefaults", saveDifferencesFromDefaultSet);
  49360. int i;
  49361. for (i = 0; i < mappings.size(); ++i)
  49362. {
  49363. const CommandMapping* const cm = mappings.getUnchecked(i);
  49364. for (int j = 0; j < cm->keypresses.size(); ++j)
  49365. {
  49366. if (defaultSet == 0
  49367. || ! defaultSet->containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  49368. {
  49369. XmlElement* const map = doc->createNewChildElement ("MAPPING");
  49370. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  49371. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  49372. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  49373. }
  49374. }
  49375. }
  49376. if (defaultSet != 0)
  49377. {
  49378. for (i = 0; i < defaultSet->mappings.size(); ++i)
  49379. {
  49380. const CommandMapping* const cm = defaultSet->mappings.getUnchecked(i);
  49381. for (int j = 0; j < cm->keypresses.size(); ++j)
  49382. {
  49383. if (! containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  49384. {
  49385. XmlElement* const map = doc->createNewChildElement ("UNMAPPING");
  49386. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  49387. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  49388. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  49389. }
  49390. }
  49391. }
  49392. }
  49393. return doc;
  49394. }
  49395. bool KeyPressMappingSet::keyPressed (const KeyPress& key,
  49396. Component* originatingComponent)
  49397. {
  49398. bool used = false;
  49399. const CommandID commandID = findCommandForKeyPress (key);
  49400. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  49401. if (ci != 0
  49402. && (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) == 0)
  49403. {
  49404. ApplicationCommandInfo info (0);
  49405. if (commandManager->getTargetForCommand (commandID, info) != 0
  49406. && (info.flags & ApplicationCommandInfo::isDisabled) == 0)
  49407. {
  49408. invokeCommand (commandID, key, true, 0, originatingComponent);
  49409. used = true;
  49410. }
  49411. else
  49412. {
  49413. if (originatingComponent != 0)
  49414. originatingComponent->getLookAndFeel().playAlertSound();
  49415. }
  49416. }
  49417. return used;
  49418. }
  49419. bool KeyPressMappingSet::keyStateChanged (const bool /*isKeyDown*/, Component* originatingComponent)
  49420. {
  49421. bool used = false;
  49422. const uint32 now = Time::getMillisecondCounter();
  49423. for (int i = mappings.size(); --i >= 0;)
  49424. {
  49425. CommandMapping* const cm = mappings.getUnchecked(i);
  49426. if (cm->wantsKeyUpDownCallbacks)
  49427. {
  49428. for (int j = cm->keypresses.size(); --j >= 0;)
  49429. {
  49430. const KeyPress key (cm->keypresses.getReference (j));
  49431. const bool isDown = key.isCurrentlyDown();
  49432. int keyPressEntryIndex = 0;
  49433. bool wasDown = false;
  49434. for (int k = keysDown.size(); --k >= 0;)
  49435. {
  49436. if (key == keysDown.getUnchecked(k)->key)
  49437. {
  49438. keyPressEntryIndex = k;
  49439. wasDown = true;
  49440. used = true;
  49441. break;
  49442. }
  49443. }
  49444. if (isDown != wasDown)
  49445. {
  49446. int millisecs = 0;
  49447. if (isDown)
  49448. {
  49449. KeyPressTime* const k = new KeyPressTime();
  49450. k->key = key;
  49451. k->timeWhenPressed = now;
  49452. keysDown.add (k);
  49453. }
  49454. else
  49455. {
  49456. const uint32 pressTime = keysDown.getUnchecked (keyPressEntryIndex)->timeWhenPressed;
  49457. if (now > pressTime)
  49458. millisecs = now - pressTime;
  49459. keysDown.remove (keyPressEntryIndex);
  49460. }
  49461. invokeCommand (cm->commandID, key, isDown, millisecs, originatingComponent);
  49462. used = true;
  49463. }
  49464. }
  49465. }
  49466. }
  49467. return used;
  49468. }
  49469. void KeyPressMappingSet::globalFocusChanged (Component* focusedComponent)
  49470. {
  49471. if (focusedComponent != 0)
  49472. focusedComponent->keyStateChanged (false);
  49473. }
  49474. END_JUCE_NAMESPACE
  49475. /*** End of inlined file: juce_KeyPressMappingSet.cpp ***/
  49476. /*** Start of inlined file: juce_ModifierKeys.cpp ***/
  49477. BEGIN_JUCE_NAMESPACE
  49478. ModifierKeys::ModifierKeys (const int flags_) throw()
  49479. : flags (flags_)
  49480. {
  49481. }
  49482. ModifierKeys::ModifierKeys (const ModifierKeys& other) throw()
  49483. : flags (other.flags)
  49484. {
  49485. }
  49486. ModifierKeys& ModifierKeys::operator= (const ModifierKeys& other) throw()
  49487. {
  49488. flags = other.flags;
  49489. return *this;
  49490. }
  49491. ModifierKeys ModifierKeys::currentModifiers;
  49492. const ModifierKeys ModifierKeys::getCurrentModifiers() throw()
  49493. {
  49494. return currentModifiers;
  49495. }
  49496. int ModifierKeys::getNumMouseButtonsDown() const throw()
  49497. {
  49498. int num = 0;
  49499. if (isLeftButtonDown()) ++num;
  49500. if (isRightButtonDown()) ++num;
  49501. if (isMiddleButtonDown()) ++num;
  49502. return num;
  49503. }
  49504. END_JUCE_NAMESPACE
  49505. /*** End of inlined file: juce_ModifierKeys.cpp ***/
  49506. /*** Start of inlined file: juce_ComponentAnimator.cpp ***/
  49507. BEGIN_JUCE_NAMESPACE
  49508. class ComponentAnimator::AnimationTask
  49509. {
  49510. public:
  49511. AnimationTask (Component* const comp)
  49512. : component (comp)
  49513. {
  49514. }
  49515. bool useTimeslice (const int elapsed)
  49516. {
  49517. if (component == 0)
  49518. return false;
  49519. msElapsed += elapsed;
  49520. double newProgress = msElapsed / (double) msTotal;
  49521. if (newProgress >= 0 && newProgress < 1.0)
  49522. {
  49523. newProgress = timeToDistance (newProgress);
  49524. const double delta = (newProgress - lastProgress) / (1.0 - lastProgress);
  49525. jassert (newProgress >= lastProgress);
  49526. lastProgress = newProgress;
  49527. left += (destination.getX() - left) * delta;
  49528. top += (destination.getY() - top) * delta;
  49529. right += (destination.getRight() - right) * delta;
  49530. bottom += (destination.getBottom() - bottom) * delta;
  49531. if (delta < 1.0)
  49532. {
  49533. const Rectangle<int> newBounds (roundToInt (left),
  49534. roundToInt (top),
  49535. roundToInt (right - left),
  49536. roundToInt (bottom - top));
  49537. if (newBounds != destination)
  49538. {
  49539. component->setBounds (newBounds);
  49540. return true;
  49541. }
  49542. }
  49543. }
  49544. component->setBounds (destination);
  49545. return false;
  49546. }
  49547. void moveToFinalDestination()
  49548. {
  49549. if (component != 0)
  49550. component->setBounds (destination);
  49551. }
  49552. Component::SafePointer<Component> component;
  49553. Rectangle<int> destination;
  49554. int msElapsed, msTotal;
  49555. double startSpeed, midSpeed, endSpeed, lastProgress;
  49556. double left, top, right, bottom;
  49557. private:
  49558. inline double timeToDistance (const double time) const
  49559. {
  49560. return (time < 0.5) ? time * (startSpeed + time * (midSpeed - startSpeed))
  49561. : 0.5 * (startSpeed + 0.5 * (midSpeed - startSpeed))
  49562. + (time - 0.5) * (midSpeed + (time - 0.5) * (endSpeed - midSpeed));
  49563. }
  49564. };
  49565. ComponentAnimator::ComponentAnimator()
  49566. : lastTime (0)
  49567. {
  49568. }
  49569. ComponentAnimator::~ComponentAnimator()
  49570. {
  49571. }
  49572. ComponentAnimator::AnimationTask* ComponentAnimator::findTaskFor (Component* const component) const
  49573. {
  49574. for (int i = tasks.size(); --i >= 0;)
  49575. if (component == tasks.getUnchecked(i)->component.getComponent())
  49576. return tasks.getUnchecked(i);
  49577. return 0;
  49578. }
  49579. void ComponentAnimator::animateComponent (Component* const component,
  49580. const Rectangle<int>& finalPosition,
  49581. const int millisecondsToSpendMoving,
  49582. const double startSpeed,
  49583. const double endSpeed)
  49584. {
  49585. if (component != 0)
  49586. {
  49587. AnimationTask* at = findTaskFor (component);
  49588. if (at == 0)
  49589. {
  49590. at = new AnimationTask (component);
  49591. tasks.add (at);
  49592. sendChangeMessage (this);
  49593. }
  49594. at->msElapsed = 0;
  49595. at->lastProgress = 0;
  49596. at->msTotal = jmax (1, millisecondsToSpendMoving);
  49597. at->destination = finalPosition;
  49598. // the speeds must be 0 or greater!
  49599. jassert (startSpeed >= 0 && endSpeed >= 0)
  49600. const double invTotalDistance = 4.0 / (startSpeed + endSpeed + 2.0);
  49601. at->startSpeed = jmax (0.0, startSpeed * invTotalDistance);
  49602. at->midSpeed = invTotalDistance;
  49603. at->endSpeed = jmax (0.0, endSpeed * invTotalDistance);
  49604. at->left = component->getX();
  49605. at->top = component->getY();
  49606. at->right = component->getRight();
  49607. at->bottom = component->getBottom();
  49608. if (! isTimerRunning())
  49609. {
  49610. lastTime = Time::getMillisecondCounter();
  49611. startTimer (1000 / 50);
  49612. }
  49613. }
  49614. }
  49615. void ComponentAnimator::cancelAllAnimations (const bool moveComponentsToTheirFinalPositions)
  49616. {
  49617. if (tasks.size() > 0)
  49618. {
  49619. if (moveComponentsToTheirFinalPositions)
  49620. for (int i = tasks.size(); --i >= 0;)
  49621. tasks.getUnchecked(i)->moveToFinalDestination();
  49622. tasks.clear();
  49623. sendChangeMessage (this);
  49624. }
  49625. }
  49626. void ComponentAnimator::cancelAnimation (Component* const component,
  49627. const bool moveComponentToItsFinalPosition)
  49628. {
  49629. AnimationTask* const at = findTaskFor (component);
  49630. if (at != 0)
  49631. {
  49632. if (moveComponentToItsFinalPosition)
  49633. at->moveToFinalDestination();
  49634. tasks.removeObject (at);
  49635. sendChangeMessage (this);
  49636. }
  49637. }
  49638. const Rectangle<int> ComponentAnimator::getComponentDestination (Component* const component)
  49639. {
  49640. AnimationTask* const at = findTaskFor (component);
  49641. if (at != 0)
  49642. return at->destination;
  49643. else if (component != 0)
  49644. return component->getBounds();
  49645. return Rectangle<int>();
  49646. }
  49647. bool ComponentAnimator::isAnimating (Component* component) const
  49648. {
  49649. return findTaskFor (component) != 0;
  49650. }
  49651. void ComponentAnimator::timerCallback()
  49652. {
  49653. const uint32 timeNow = Time::getMillisecondCounter();
  49654. if (lastTime == 0 || lastTime == timeNow)
  49655. lastTime = timeNow;
  49656. const int elapsed = timeNow - lastTime;
  49657. for (int i = tasks.size(); --i >= 0;)
  49658. {
  49659. if (! tasks.getUnchecked(i)->useTimeslice (elapsed))
  49660. {
  49661. tasks.remove (i);
  49662. sendChangeMessage (this);
  49663. }
  49664. }
  49665. lastTime = timeNow;
  49666. if (tasks.size() == 0)
  49667. stopTimer();
  49668. }
  49669. END_JUCE_NAMESPACE
  49670. /*** End of inlined file: juce_ComponentAnimator.cpp ***/
  49671. /*** Start of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  49672. BEGIN_JUCE_NAMESPACE
  49673. ComponentBoundsConstrainer::ComponentBoundsConstrainer() throw()
  49674. : minW (0),
  49675. maxW (0x3fffffff),
  49676. minH (0),
  49677. maxH (0x3fffffff),
  49678. minOffTop (0),
  49679. minOffLeft (0),
  49680. minOffBottom (0),
  49681. minOffRight (0),
  49682. aspectRatio (0.0)
  49683. {
  49684. }
  49685. ComponentBoundsConstrainer::~ComponentBoundsConstrainer()
  49686. {
  49687. }
  49688. void ComponentBoundsConstrainer::setMinimumWidth (const int minimumWidth) throw()
  49689. {
  49690. minW = minimumWidth;
  49691. }
  49692. void ComponentBoundsConstrainer::setMaximumWidth (const int maximumWidth) throw()
  49693. {
  49694. maxW = maximumWidth;
  49695. }
  49696. void ComponentBoundsConstrainer::setMinimumHeight (const int minimumHeight) throw()
  49697. {
  49698. minH = minimumHeight;
  49699. }
  49700. void ComponentBoundsConstrainer::setMaximumHeight (const int maximumHeight) throw()
  49701. {
  49702. maxH = maximumHeight;
  49703. }
  49704. void ComponentBoundsConstrainer::setMinimumSize (const int minimumWidth, const int minimumHeight) throw()
  49705. {
  49706. jassert (maxW >= minimumWidth);
  49707. jassert (maxH >= minimumHeight);
  49708. jassert (minimumWidth > 0 && minimumHeight > 0);
  49709. minW = minimumWidth;
  49710. minH = minimumHeight;
  49711. if (minW > maxW)
  49712. maxW = minW;
  49713. if (minH > maxH)
  49714. maxH = minH;
  49715. }
  49716. void ComponentBoundsConstrainer::setMaximumSize (const int maximumWidth, const int maximumHeight) throw()
  49717. {
  49718. jassert (maximumWidth >= minW);
  49719. jassert (maximumHeight >= minH);
  49720. jassert (maximumWidth > 0 && maximumHeight > 0);
  49721. maxW = jmax (minW, maximumWidth);
  49722. maxH = jmax (minH, maximumHeight);
  49723. }
  49724. void ComponentBoundsConstrainer::setSizeLimits (const int minimumWidth,
  49725. const int minimumHeight,
  49726. const int maximumWidth,
  49727. const int maximumHeight) throw()
  49728. {
  49729. jassert (maximumWidth >= minimumWidth);
  49730. jassert (maximumHeight >= minimumHeight);
  49731. jassert (maximumWidth > 0 && maximumHeight > 0);
  49732. jassert (minimumWidth > 0 && minimumHeight > 0);
  49733. minW = jmax (0, minimumWidth);
  49734. minH = jmax (0, minimumHeight);
  49735. maxW = jmax (minW, maximumWidth);
  49736. maxH = jmax (minH, maximumHeight);
  49737. }
  49738. void ComponentBoundsConstrainer::setMinimumOnscreenAmounts (const int minimumWhenOffTheTop,
  49739. const int minimumWhenOffTheLeft,
  49740. const int minimumWhenOffTheBottom,
  49741. const int minimumWhenOffTheRight) throw()
  49742. {
  49743. minOffTop = minimumWhenOffTheTop;
  49744. minOffLeft = minimumWhenOffTheLeft;
  49745. minOffBottom = minimumWhenOffTheBottom;
  49746. minOffRight = minimumWhenOffTheRight;
  49747. }
  49748. void ComponentBoundsConstrainer::setFixedAspectRatio (const double widthOverHeight) throw()
  49749. {
  49750. aspectRatio = jmax (0.0, widthOverHeight);
  49751. }
  49752. double ComponentBoundsConstrainer::getFixedAspectRatio() const throw()
  49753. {
  49754. return aspectRatio;
  49755. }
  49756. void ComponentBoundsConstrainer::setBoundsForComponent (Component* const component,
  49757. const Rectangle<int>& targetBounds,
  49758. const bool isStretchingTop,
  49759. const bool isStretchingLeft,
  49760. const bool isStretchingBottom,
  49761. const bool isStretchingRight)
  49762. {
  49763. jassert (component != 0);
  49764. Rectangle<int> limits, bounds (targetBounds);
  49765. BorderSize border;
  49766. Component* const parent = component->getParentComponent();
  49767. if (parent == 0)
  49768. {
  49769. ComponentPeer* peer = component->getPeer();
  49770. if (peer != 0)
  49771. border = peer->getFrameSize();
  49772. limits = Desktop::getInstance().getMonitorAreaContaining (bounds.getCentre());
  49773. }
  49774. else
  49775. {
  49776. limits.setSize (parent->getWidth(), parent->getHeight());
  49777. }
  49778. border.addTo (bounds);
  49779. checkBounds (bounds,
  49780. border.addedTo (component->getBounds()), limits,
  49781. isStretchingTop, isStretchingLeft,
  49782. isStretchingBottom, isStretchingRight);
  49783. border.subtractFrom (bounds);
  49784. applyBoundsToComponent (component, bounds);
  49785. }
  49786. void ComponentBoundsConstrainer::checkComponentBounds (Component* component)
  49787. {
  49788. setBoundsForComponent (component, component->getBounds(),
  49789. false, false, false, false);
  49790. }
  49791. void ComponentBoundsConstrainer::applyBoundsToComponent (Component* component,
  49792. const Rectangle<int>& bounds)
  49793. {
  49794. component->setBounds (bounds);
  49795. }
  49796. void ComponentBoundsConstrainer::resizeStart()
  49797. {
  49798. }
  49799. void ComponentBoundsConstrainer::resizeEnd()
  49800. {
  49801. }
  49802. void ComponentBoundsConstrainer::checkBounds (Rectangle<int>& bounds,
  49803. const Rectangle<int>& old,
  49804. const Rectangle<int>& limits,
  49805. const bool isStretchingTop,
  49806. const bool isStretchingLeft,
  49807. const bool isStretchingBottom,
  49808. const bool isStretchingRight)
  49809. {
  49810. int x = bounds.getX();
  49811. int y = bounds.getY();
  49812. int w = bounds.getWidth();
  49813. int h = bounds.getHeight();
  49814. // constrain the size if it's being stretched..
  49815. if (isStretchingLeft)
  49816. {
  49817. x = jlimit (old.getRight() - maxW, old.getRight() - minW, x);
  49818. w = old.getRight() - x;
  49819. }
  49820. if (isStretchingRight)
  49821. {
  49822. w = jlimit (minW, maxW, w);
  49823. }
  49824. if (isStretchingTop)
  49825. {
  49826. y = jlimit (old.getBottom() - maxH, old.getBottom() - minH, y);
  49827. h = old.getBottom() - y;
  49828. }
  49829. if (isStretchingBottom)
  49830. {
  49831. h = jlimit (minH, maxH, h);
  49832. }
  49833. // constrain the aspect ratio if one has been specified..
  49834. if (aspectRatio > 0.0 && w > 0 && h > 0)
  49835. {
  49836. bool adjustWidth;
  49837. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  49838. {
  49839. adjustWidth = true;
  49840. }
  49841. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  49842. {
  49843. adjustWidth = false;
  49844. }
  49845. else
  49846. {
  49847. const double oldRatio = (old.getHeight() > 0) ? std::abs (old.getWidth() / (double) old.getHeight()) : 0.0;
  49848. const double newRatio = std::abs (w / (double) h);
  49849. adjustWidth = (oldRatio > newRatio);
  49850. }
  49851. if (adjustWidth)
  49852. {
  49853. w = roundToInt (h * aspectRatio);
  49854. if (w > maxW || w < minW)
  49855. {
  49856. w = jlimit (minW, maxW, w);
  49857. h = roundToInt (w / aspectRatio);
  49858. }
  49859. }
  49860. else
  49861. {
  49862. h = roundToInt (w / aspectRatio);
  49863. if (h > maxH || h < minH)
  49864. {
  49865. h = jlimit (minH, maxH, h);
  49866. w = roundToInt (h * aspectRatio);
  49867. }
  49868. }
  49869. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  49870. {
  49871. x = old.getX() + (old.getWidth() - w) / 2;
  49872. }
  49873. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  49874. {
  49875. y = old.getY() + (old.getHeight() - h) / 2;
  49876. }
  49877. else
  49878. {
  49879. if (isStretchingLeft)
  49880. x = old.getRight() - w;
  49881. if (isStretchingTop)
  49882. y = old.getBottom() - h;
  49883. }
  49884. }
  49885. // ...and constrain the position if limits have been set for that.
  49886. if (minOffTop > 0 || minOffLeft > 0 || minOffBottom > 0 || minOffRight > 0)
  49887. {
  49888. if (minOffTop > 0)
  49889. {
  49890. const int limit = limits.getY() + jmin (minOffTop - h, 0);
  49891. if (y < limit)
  49892. {
  49893. if (isStretchingTop)
  49894. h -= (limit - y);
  49895. y = limit;
  49896. }
  49897. }
  49898. if (minOffLeft > 0)
  49899. {
  49900. const int limit = limits.getX() + jmin (minOffLeft - w, 0);
  49901. if (x < limit)
  49902. {
  49903. if (isStretchingLeft)
  49904. w -= (limit - x);
  49905. x = limit;
  49906. }
  49907. }
  49908. if (minOffBottom > 0)
  49909. {
  49910. const int limit = limits.getBottom() - jmin (minOffBottom, h);
  49911. if (y > limit)
  49912. {
  49913. if (isStretchingBottom)
  49914. h += (limit - y);
  49915. else
  49916. y = limit;
  49917. }
  49918. }
  49919. if (minOffRight > 0)
  49920. {
  49921. const int limit = limits.getRight() - jmin (minOffRight, w);
  49922. if (x > limit)
  49923. {
  49924. if (isStretchingRight)
  49925. w += (limit - x);
  49926. else
  49927. x = limit;
  49928. }
  49929. }
  49930. }
  49931. jassert (w >= 0 && h >= 0);
  49932. bounds = Rectangle<int> (x, y, w, h);
  49933. }
  49934. END_JUCE_NAMESPACE
  49935. /*** End of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  49936. /*** Start of inlined file: juce_ComponentMovementWatcher.cpp ***/
  49937. BEGIN_JUCE_NAMESPACE
  49938. ComponentMovementWatcher::ComponentMovementWatcher (Component* const component_)
  49939. : component (component_),
  49940. lastPeer (0),
  49941. reentrant (false)
  49942. {
  49943. jassert (component != 0); // can't use this with a null pointer..
  49944. component->addComponentListener (this);
  49945. registerWithParentComps();
  49946. }
  49947. ComponentMovementWatcher::~ComponentMovementWatcher()
  49948. {
  49949. component->removeComponentListener (this);
  49950. unregister();
  49951. }
  49952. void ComponentMovementWatcher::componentParentHierarchyChanged (Component&)
  49953. {
  49954. // agh! don't delete the target component without deleting this object first!
  49955. jassert (component != 0);
  49956. if (! reentrant)
  49957. {
  49958. reentrant = true;
  49959. ComponentPeer* const peer = component->getPeer();
  49960. if (peer != lastPeer)
  49961. {
  49962. componentPeerChanged();
  49963. if (component == 0)
  49964. return;
  49965. lastPeer = peer;
  49966. }
  49967. unregister();
  49968. registerWithParentComps();
  49969. reentrant = false;
  49970. componentMovedOrResized (*component, true, true);
  49971. }
  49972. }
  49973. void ComponentMovementWatcher::componentMovedOrResized (Component&, bool wasMoved, bool wasResized)
  49974. {
  49975. // agh! don't delete the target component without deleting this object first!
  49976. jassert (component != 0);
  49977. if (wasMoved)
  49978. {
  49979. const Point<int> pos (component->relativePositionToOtherComponent (component->getTopLevelComponent(), Point<int>()));
  49980. wasMoved = lastBounds.getPosition() != pos;
  49981. lastBounds.setPosition (pos);
  49982. }
  49983. wasResized = (lastBounds.getWidth() != component->getWidth() || lastBounds.getHeight() != component->getHeight());
  49984. lastBounds.setSize (component->getWidth(), component->getHeight());
  49985. if (wasMoved || wasResized)
  49986. componentMovedOrResized (wasMoved, wasResized);
  49987. }
  49988. void ComponentMovementWatcher::registerWithParentComps()
  49989. {
  49990. Component* p = component->getParentComponent();
  49991. while (p != 0)
  49992. {
  49993. p->addComponentListener (this);
  49994. registeredParentComps.add (p);
  49995. p = p->getParentComponent();
  49996. }
  49997. }
  49998. void ComponentMovementWatcher::unregister()
  49999. {
  50000. for (int i = registeredParentComps.size(); --i >= 0;)
  50001. registeredParentComps.getUnchecked(i)->removeComponentListener (this);
  50002. registeredParentComps.clear();
  50003. }
  50004. END_JUCE_NAMESPACE
  50005. /*** End of inlined file: juce_ComponentMovementWatcher.cpp ***/
  50006. /*** Start of inlined file: juce_GroupComponent.cpp ***/
  50007. BEGIN_JUCE_NAMESPACE
  50008. GroupComponent::GroupComponent (const String& componentName,
  50009. const String& labelText)
  50010. : Component (componentName),
  50011. text (labelText),
  50012. justification (Justification::left)
  50013. {
  50014. setInterceptsMouseClicks (false, true);
  50015. }
  50016. GroupComponent::~GroupComponent()
  50017. {
  50018. }
  50019. void GroupComponent::setText (const String& newText)
  50020. {
  50021. if (text != newText)
  50022. {
  50023. text = newText;
  50024. repaint();
  50025. }
  50026. }
  50027. const String GroupComponent::getText() const
  50028. {
  50029. return text;
  50030. }
  50031. void GroupComponent::setTextLabelPosition (const Justification& newJustification)
  50032. {
  50033. if (justification != newJustification)
  50034. {
  50035. justification = newJustification;
  50036. repaint();
  50037. }
  50038. }
  50039. void GroupComponent::paint (Graphics& g)
  50040. {
  50041. getLookAndFeel()
  50042. .drawGroupComponentOutline (g, getWidth(), getHeight(),
  50043. text, justification,
  50044. *this);
  50045. }
  50046. void GroupComponent::enablementChanged()
  50047. {
  50048. repaint();
  50049. }
  50050. void GroupComponent::colourChanged()
  50051. {
  50052. repaint();
  50053. }
  50054. END_JUCE_NAMESPACE
  50055. /*** End of inlined file: juce_GroupComponent.cpp ***/
  50056. /*** Start of inlined file: juce_MultiDocumentPanel.cpp ***/
  50057. BEGIN_JUCE_NAMESPACE
  50058. MultiDocumentPanelWindow::MultiDocumentPanelWindow (const Colour& backgroundColour)
  50059. : DocumentWindow (String::empty, backgroundColour,
  50060. DocumentWindow::maximiseButton | DocumentWindow::closeButton, false)
  50061. {
  50062. }
  50063. MultiDocumentPanelWindow::~MultiDocumentPanelWindow()
  50064. {
  50065. }
  50066. void MultiDocumentPanelWindow::maximiseButtonPressed()
  50067. {
  50068. MultiDocumentPanel* const owner = getOwner();
  50069. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  50070. if (owner != 0)
  50071. owner->setLayoutMode (MultiDocumentPanel::MaximisedWindowsWithTabs);
  50072. }
  50073. void MultiDocumentPanelWindow::closeButtonPressed()
  50074. {
  50075. MultiDocumentPanel* const owner = getOwner();
  50076. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  50077. if (owner != 0)
  50078. owner->closeDocument (getContentComponent(), true);
  50079. }
  50080. void MultiDocumentPanelWindow::activeWindowStatusChanged()
  50081. {
  50082. DocumentWindow::activeWindowStatusChanged();
  50083. updateOrder();
  50084. }
  50085. void MultiDocumentPanelWindow::broughtToFront()
  50086. {
  50087. DocumentWindow::broughtToFront();
  50088. updateOrder();
  50089. }
  50090. void MultiDocumentPanelWindow::updateOrder()
  50091. {
  50092. MultiDocumentPanel* const owner = getOwner();
  50093. if (owner != 0)
  50094. owner->updateOrder();
  50095. }
  50096. MultiDocumentPanel* MultiDocumentPanelWindow::getOwner() const throw()
  50097. {
  50098. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  50099. return findParentComponentOfClass ((MultiDocumentPanel*) 0);
  50100. }
  50101. class MDITabbedComponentInternal : public TabbedComponent
  50102. {
  50103. public:
  50104. MDITabbedComponentInternal()
  50105. : TabbedComponent (TabbedButtonBar::TabsAtTop)
  50106. {
  50107. }
  50108. ~MDITabbedComponentInternal()
  50109. {
  50110. }
  50111. void currentTabChanged (int, const String&)
  50112. {
  50113. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  50114. MultiDocumentPanel* const owner = findParentComponentOfClass ((MultiDocumentPanel*) 0);
  50115. if (owner != 0)
  50116. owner->updateOrder();
  50117. }
  50118. };
  50119. MultiDocumentPanel::MultiDocumentPanel()
  50120. : mode (MaximisedWindowsWithTabs),
  50121. backgroundColour (Colours::lightblue),
  50122. maximumNumDocuments (0),
  50123. numDocsBeforeTabsUsed (0)
  50124. {
  50125. setOpaque (true);
  50126. }
  50127. MultiDocumentPanel::~MultiDocumentPanel()
  50128. {
  50129. closeAllDocuments (false);
  50130. }
  50131. static bool shouldDeleteComp (Component* const c)
  50132. {
  50133. return c->getProperties() ["mdiDocumentDelete_"];
  50134. }
  50135. bool MultiDocumentPanel::closeAllDocuments (const bool checkItsOkToCloseFirst)
  50136. {
  50137. while (components.size() > 0)
  50138. if (! closeDocument (components.getLast(), checkItsOkToCloseFirst))
  50139. return false;
  50140. return true;
  50141. }
  50142. MultiDocumentPanelWindow* MultiDocumentPanel::createNewDocumentWindow()
  50143. {
  50144. return new MultiDocumentPanelWindow (backgroundColour);
  50145. }
  50146. void MultiDocumentPanel::addWindow (Component* component)
  50147. {
  50148. MultiDocumentPanelWindow* const dw = createNewDocumentWindow();
  50149. dw->setResizable (true, false);
  50150. dw->setContentComponent (component, false, true);
  50151. dw->setName (component->getName());
  50152. const var bkg (component->getProperties() ["mdiDocumentBkg_"]);
  50153. dw->setBackgroundColour (bkg.isVoid() ? backgroundColour : Colour ((int) bkg));
  50154. int x = 4;
  50155. Component* const topComp = getChildComponent (getNumChildComponents() - 1);
  50156. if (topComp != 0 && topComp->getX() == x && topComp->getY() == x)
  50157. x += 16;
  50158. dw->setTopLeftPosition (x, x);
  50159. const var pos (component->getProperties() ["mdiDocumentPos_"]);
  50160. if (pos.toString().isNotEmpty())
  50161. dw->restoreWindowStateFromString (pos.toString());
  50162. addAndMakeVisible (dw);
  50163. dw->toFront (true);
  50164. }
  50165. bool MultiDocumentPanel::addDocument (Component* const component,
  50166. const Colour& docColour,
  50167. const bool deleteWhenRemoved)
  50168. {
  50169. // If you try passing a full DocumentWindow or ResizableWindow in here, you'll end up
  50170. // with a frame-within-a-frame! Just pass in the bare content component.
  50171. jassert (dynamic_cast <ResizableWindow*> (component) == 0);
  50172. if (component == 0 || (maximumNumDocuments > 0 && components.size() >= maximumNumDocuments))
  50173. return false;
  50174. components.add (component);
  50175. component->getProperties().set ("mdiDocumentDelete_", deleteWhenRemoved);
  50176. component->getProperties().set ("mdiDocumentBkg_", (int) docColour.getARGB());
  50177. component->addComponentListener (this);
  50178. if (mode == FloatingWindows)
  50179. {
  50180. if (isFullscreenWhenOneDocument())
  50181. {
  50182. if (components.size() == 1)
  50183. {
  50184. addAndMakeVisible (component);
  50185. }
  50186. else
  50187. {
  50188. if (components.size() == 2)
  50189. addWindow (components.getFirst());
  50190. addWindow (component);
  50191. }
  50192. }
  50193. else
  50194. {
  50195. addWindow (component);
  50196. }
  50197. }
  50198. else
  50199. {
  50200. if (tabComponent == 0 && components.size() > numDocsBeforeTabsUsed)
  50201. {
  50202. addAndMakeVisible (tabComponent = new MDITabbedComponentInternal());
  50203. Array <Component*> temp (components);
  50204. for (int i = 0; i < temp.size(); ++i)
  50205. tabComponent->addTab (temp[i]->getName(), docColour, temp[i], false);
  50206. resized();
  50207. }
  50208. else
  50209. {
  50210. if (tabComponent != 0)
  50211. tabComponent->addTab (component->getName(), docColour, component, false);
  50212. else
  50213. addAndMakeVisible (component);
  50214. }
  50215. setActiveDocument (component);
  50216. }
  50217. resized();
  50218. activeDocumentChanged();
  50219. return true;
  50220. }
  50221. bool MultiDocumentPanel::closeDocument (Component* component,
  50222. const bool checkItsOkToCloseFirst)
  50223. {
  50224. if (components.contains (component))
  50225. {
  50226. if (checkItsOkToCloseFirst && ! tryToCloseDocument (component))
  50227. return false;
  50228. component->removeComponentListener (this);
  50229. const bool shouldDelete = shouldDeleteComp (component);
  50230. component->getProperties().remove ("mdiDocumentDelete_");
  50231. component->getProperties().remove ("mdiDocumentBkg_");
  50232. if (mode == FloatingWindows)
  50233. {
  50234. for (int i = getNumChildComponents(); --i >= 0;)
  50235. {
  50236. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50237. if (dw != 0 && dw->getContentComponent() == component)
  50238. {
  50239. dw->setContentComponent (0, false);
  50240. delete dw;
  50241. break;
  50242. }
  50243. }
  50244. if (shouldDelete)
  50245. delete component;
  50246. components.removeValue (component);
  50247. if (isFullscreenWhenOneDocument() && components.size() == 1)
  50248. {
  50249. for (int i = getNumChildComponents(); --i >= 0;)
  50250. {
  50251. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50252. if (dw != 0)
  50253. {
  50254. dw->setContentComponent (0, false);
  50255. delete dw;
  50256. }
  50257. }
  50258. addAndMakeVisible (components.getFirst());
  50259. }
  50260. }
  50261. else
  50262. {
  50263. jassert (components.indexOf (component) >= 0);
  50264. if (tabComponent != 0)
  50265. {
  50266. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50267. if (tabComponent->getTabContentComponent (i) == component)
  50268. tabComponent->removeTab (i);
  50269. }
  50270. else
  50271. {
  50272. removeChildComponent (component);
  50273. }
  50274. if (shouldDelete)
  50275. delete component;
  50276. if (tabComponent != 0 && tabComponent->getNumTabs() <= numDocsBeforeTabsUsed)
  50277. tabComponent = 0;
  50278. components.removeValue (component);
  50279. if (components.size() > 0 && tabComponent == 0)
  50280. addAndMakeVisible (components.getFirst());
  50281. }
  50282. resized();
  50283. activeDocumentChanged();
  50284. }
  50285. else
  50286. {
  50287. jassertfalse;
  50288. }
  50289. return true;
  50290. }
  50291. int MultiDocumentPanel::getNumDocuments() const throw()
  50292. {
  50293. return components.size();
  50294. }
  50295. Component* MultiDocumentPanel::getDocument (const int index) const throw()
  50296. {
  50297. return components [index];
  50298. }
  50299. Component* MultiDocumentPanel::getActiveDocument() const throw()
  50300. {
  50301. if (mode == FloatingWindows)
  50302. {
  50303. for (int i = getNumChildComponents(); --i >= 0;)
  50304. {
  50305. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50306. if (dw != 0 && dw->isActiveWindow())
  50307. return dw->getContentComponent();
  50308. }
  50309. }
  50310. return components.getLast();
  50311. }
  50312. void MultiDocumentPanel::setActiveDocument (Component* component)
  50313. {
  50314. if (mode == FloatingWindows)
  50315. {
  50316. component = getContainerComp (component);
  50317. if (component != 0)
  50318. component->toFront (true);
  50319. }
  50320. else if (tabComponent != 0)
  50321. {
  50322. jassert (components.indexOf (component) >= 0);
  50323. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50324. {
  50325. if (tabComponent->getTabContentComponent (i) == component)
  50326. {
  50327. tabComponent->setCurrentTabIndex (i);
  50328. break;
  50329. }
  50330. }
  50331. }
  50332. else
  50333. {
  50334. component->grabKeyboardFocus();
  50335. }
  50336. }
  50337. void MultiDocumentPanel::activeDocumentChanged()
  50338. {
  50339. }
  50340. void MultiDocumentPanel::setMaximumNumDocuments (const int newNumber)
  50341. {
  50342. maximumNumDocuments = newNumber;
  50343. }
  50344. void MultiDocumentPanel::useFullscreenWhenOneDocument (const bool shouldUseTabs)
  50345. {
  50346. numDocsBeforeTabsUsed = shouldUseTabs ? 1 : 0;
  50347. }
  50348. bool MultiDocumentPanel::isFullscreenWhenOneDocument() const throw()
  50349. {
  50350. return numDocsBeforeTabsUsed != 0;
  50351. }
  50352. void MultiDocumentPanel::setLayoutMode (const LayoutMode newLayoutMode)
  50353. {
  50354. if (mode != newLayoutMode)
  50355. {
  50356. mode = newLayoutMode;
  50357. if (mode == FloatingWindows)
  50358. {
  50359. tabComponent = 0;
  50360. }
  50361. else
  50362. {
  50363. for (int i = getNumChildComponents(); --i >= 0;)
  50364. {
  50365. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50366. if (dw != 0)
  50367. {
  50368. dw->getContentComponent()->getProperties().set ("mdiDocumentPos_", dw->getWindowStateAsString());
  50369. dw->setContentComponent (0, false);
  50370. delete dw;
  50371. }
  50372. }
  50373. }
  50374. resized();
  50375. const Array <Component*> tempComps (components);
  50376. components.clear();
  50377. for (int i = 0; i < tempComps.size(); ++i)
  50378. {
  50379. Component* const c = tempComps.getUnchecked(i);
  50380. addDocument (c,
  50381. Colour ((int) c->getProperties().getWithDefault ("mdiDocumentBkg_", (int) Colours::white.getARGB())),
  50382. shouldDeleteComp (c));
  50383. }
  50384. }
  50385. }
  50386. void MultiDocumentPanel::setBackgroundColour (const Colour& newBackgroundColour)
  50387. {
  50388. if (backgroundColour != newBackgroundColour)
  50389. {
  50390. backgroundColour = newBackgroundColour;
  50391. setOpaque (newBackgroundColour.isOpaque());
  50392. repaint();
  50393. }
  50394. }
  50395. void MultiDocumentPanel::paint (Graphics& g)
  50396. {
  50397. g.fillAll (backgroundColour);
  50398. }
  50399. void MultiDocumentPanel::resized()
  50400. {
  50401. if (mode == MaximisedWindowsWithTabs || components.size() == numDocsBeforeTabsUsed)
  50402. {
  50403. for (int i = getNumChildComponents(); --i >= 0;)
  50404. getChildComponent (i)->setBounds (getLocalBounds());
  50405. }
  50406. setWantsKeyboardFocus (components.size() == 0);
  50407. }
  50408. Component* MultiDocumentPanel::getContainerComp (Component* c) const
  50409. {
  50410. if (mode == FloatingWindows)
  50411. {
  50412. for (int i = 0; i < getNumChildComponents(); ++i)
  50413. {
  50414. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50415. if (dw != 0 && dw->getContentComponent() == c)
  50416. {
  50417. c = dw;
  50418. break;
  50419. }
  50420. }
  50421. }
  50422. return c;
  50423. }
  50424. void MultiDocumentPanel::componentNameChanged (Component&)
  50425. {
  50426. if (mode == FloatingWindows)
  50427. {
  50428. for (int i = 0; i < getNumChildComponents(); ++i)
  50429. {
  50430. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50431. if (dw != 0)
  50432. dw->setName (dw->getContentComponent()->getName());
  50433. }
  50434. }
  50435. else if (tabComponent != 0)
  50436. {
  50437. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50438. tabComponent->setTabName (i, tabComponent->getTabContentComponent (i)->getName());
  50439. }
  50440. }
  50441. void MultiDocumentPanel::updateOrder()
  50442. {
  50443. const Array <Component*> oldList (components);
  50444. if (mode == FloatingWindows)
  50445. {
  50446. components.clear();
  50447. for (int i = 0; i < getNumChildComponents(); ++i)
  50448. {
  50449. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50450. if (dw != 0)
  50451. components.add (dw->getContentComponent());
  50452. }
  50453. }
  50454. else
  50455. {
  50456. if (tabComponent != 0)
  50457. {
  50458. Component* const current = tabComponent->getCurrentContentComponent();
  50459. if (current != 0)
  50460. {
  50461. components.removeValue (current);
  50462. components.add (current);
  50463. }
  50464. }
  50465. }
  50466. if (components != oldList)
  50467. activeDocumentChanged();
  50468. }
  50469. END_JUCE_NAMESPACE
  50470. /*** End of inlined file: juce_MultiDocumentPanel.cpp ***/
  50471. /*** Start of inlined file: juce_ResizableBorderComponent.cpp ***/
  50472. BEGIN_JUCE_NAMESPACE
  50473. ResizableBorderComponent::Zone::Zone (int zoneFlags) throw()
  50474. : zone (zoneFlags)
  50475. {
  50476. }
  50477. ResizableBorderComponent::Zone::Zone (const ResizableBorderComponent::Zone& other) throw() : zone (other.zone) {}
  50478. ResizableBorderComponent::Zone& ResizableBorderComponent::Zone::operator= (const ResizableBorderComponent::Zone& other) throw() { zone = other.zone; return *this; }
  50479. bool ResizableBorderComponent::Zone::operator== (const ResizableBorderComponent::Zone& other) const throw() { return zone == other.zone; }
  50480. bool ResizableBorderComponent::Zone::operator!= (const ResizableBorderComponent::Zone& other) const throw() { return zone != other.zone; }
  50481. const ResizableBorderComponent::Zone ResizableBorderComponent::Zone::fromPositionOnBorder (const Rectangle<int>& totalSize,
  50482. const BorderSize& border,
  50483. const Point<int>& position)
  50484. {
  50485. int z = 0;
  50486. if (totalSize.contains (position)
  50487. && ! border.subtractedFrom (totalSize).contains (position))
  50488. {
  50489. const int minW = jmax (totalSize.getWidth() / 10, jmin (10, totalSize.getWidth() / 3));
  50490. if (position.getX() < jmax (border.getLeft(), minW))
  50491. z |= left;
  50492. else if (position.getX() >= totalSize.getWidth() - jmax (border.getRight(), minW))
  50493. z |= right;
  50494. const int minH = jmax (totalSize.getHeight() / 10, jmin (10, totalSize.getHeight() / 3));
  50495. if (position.getY() < jmax (border.getTop(), minH))
  50496. z |= top;
  50497. else if (position.getY() >= totalSize.getHeight() - jmax (border.getBottom(), minH))
  50498. z |= bottom;
  50499. }
  50500. return Zone (z);
  50501. }
  50502. const MouseCursor ResizableBorderComponent::Zone::getMouseCursor() const throw()
  50503. {
  50504. MouseCursor::StandardCursorType mc = MouseCursor::NormalCursor;
  50505. switch (zone)
  50506. {
  50507. case (left | top): mc = MouseCursor::TopLeftCornerResizeCursor; break;
  50508. case top: mc = MouseCursor::TopEdgeResizeCursor; break;
  50509. case (right | top): mc = MouseCursor::TopRightCornerResizeCursor; break;
  50510. case left: mc = MouseCursor::LeftEdgeResizeCursor; break;
  50511. case right: mc = MouseCursor::RightEdgeResizeCursor; break;
  50512. case (left | bottom): mc = MouseCursor::BottomLeftCornerResizeCursor; break;
  50513. case bottom: mc = MouseCursor::BottomEdgeResizeCursor; break;
  50514. case (right | bottom): mc = MouseCursor::BottomRightCornerResizeCursor; break;
  50515. default: break;
  50516. }
  50517. return mc;
  50518. }
  50519. const Rectangle<int> ResizableBorderComponent::Zone::resizeRectangleBy (Rectangle<int> b, const Point<int>& offset) const throw()
  50520. {
  50521. if (isDraggingWholeObject())
  50522. return b + offset;
  50523. if (isDraggingLeftEdge())
  50524. b.setLeft (b.getX() + offset.getX());
  50525. if (isDraggingRightEdge())
  50526. b.setWidth (jmax (0, b.getWidth() + offset.getX()));
  50527. if (isDraggingTopEdge())
  50528. b.setTop (b.getY() + offset.getY());
  50529. if (isDraggingBottomEdge())
  50530. b.setHeight (jmax (0, b.getHeight() + offset.getY()));
  50531. return b;
  50532. }
  50533. const Rectangle<float> ResizableBorderComponent::Zone::resizeRectangleBy (Rectangle<float> b, const Point<float>& offset) const throw()
  50534. {
  50535. if (isDraggingWholeObject())
  50536. return b + offset;
  50537. if (isDraggingLeftEdge())
  50538. b.setLeft (b.getX() + offset.getX());
  50539. if (isDraggingRightEdge())
  50540. b.setWidth (jmax (0.0f, b.getWidth() + offset.getX()));
  50541. if (isDraggingTopEdge())
  50542. b.setTop (b.getY() + offset.getY());
  50543. if (isDraggingBottomEdge())
  50544. b.setHeight (jmax (0.0f, b.getHeight() + offset.getY()));
  50545. return b;
  50546. }
  50547. ResizableBorderComponent::ResizableBorderComponent (Component* const componentToResize,
  50548. ComponentBoundsConstrainer* const constrainer_)
  50549. : component (componentToResize),
  50550. constrainer (constrainer_),
  50551. borderSize (5),
  50552. mouseZone (0)
  50553. {
  50554. }
  50555. ResizableBorderComponent::~ResizableBorderComponent()
  50556. {
  50557. }
  50558. void ResizableBorderComponent::paint (Graphics& g)
  50559. {
  50560. getLookAndFeel().drawResizableFrame (g, getWidth(), getHeight(), borderSize);
  50561. }
  50562. void ResizableBorderComponent::mouseEnter (const MouseEvent& e)
  50563. {
  50564. updateMouseZone (e);
  50565. }
  50566. void ResizableBorderComponent::mouseMove (const MouseEvent& e)
  50567. {
  50568. updateMouseZone (e);
  50569. }
  50570. void ResizableBorderComponent::mouseDown (const MouseEvent& e)
  50571. {
  50572. if (component == 0)
  50573. {
  50574. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  50575. return;
  50576. }
  50577. updateMouseZone (e);
  50578. originalBounds = component->getBounds();
  50579. if (constrainer != 0)
  50580. constrainer->resizeStart();
  50581. }
  50582. void ResizableBorderComponent::mouseDrag (const MouseEvent& e)
  50583. {
  50584. if (component == 0)
  50585. {
  50586. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  50587. return;
  50588. }
  50589. const Rectangle<int> bounds (mouseZone.resizeRectangleBy (originalBounds, e.getOffsetFromDragStart()));
  50590. if (constrainer != 0)
  50591. constrainer->setBoundsForComponent (component, bounds,
  50592. mouseZone.isDraggingTopEdge(),
  50593. mouseZone.isDraggingLeftEdge(),
  50594. mouseZone.isDraggingBottomEdge(),
  50595. mouseZone.isDraggingRightEdge());
  50596. else
  50597. component->setBounds (bounds);
  50598. }
  50599. void ResizableBorderComponent::mouseUp (const MouseEvent&)
  50600. {
  50601. if (constrainer != 0)
  50602. constrainer->resizeEnd();
  50603. }
  50604. bool ResizableBorderComponent::hitTest (int x, int y)
  50605. {
  50606. return x < borderSize.getLeft()
  50607. || x >= getWidth() - borderSize.getRight()
  50608. || y < borderSize.getTop()
  50609. || y >= getHeight() - borderSize.getBottom();
  50610. }
  50611. void ResizableBorderComponent::setBorderThickness (const BorderSize& newBorderSize)
  50612. {
  50613. if (borderSize != newBorderSize)
  50614. {
  50615. borderSize = newBorderSize;
  50616. repaint();
  50617. }
  50618. }
  50619. const BorderSize ResizableBorderComponent::getBorderThickness() const
  50620. {
  50621. return borderSize;
  50622. }
  50623. void ResizableBorderComponent::updateMouseZone (const MouseEvent& e)
  50624. {
  50625. Zone newZone (Zone::fromPositionOnBorder (getLocalBounds(), borderSize, e.getPosition()));
  50626. if (mouseZone != newZone)
  50627. {
  50628. mouseZone = newZone;
  50629. setMouseCursor (newZone.getMouseCursor());
  50630. }
  50631. }
  50632. END_JUCE_NAMESPACE
  50633. /*** End of inlined file: juce_ResizableBorderComponent.cpp ***/
  50634. /*** Start of inlined file: juce_ResizableCornerComponent.cpp ***/
  50635. BEGIN_JUCE_NAMESPACE
  50636. ResizableCornerComponent::ResizableCornerComponent (Component* const componentToResize,
  50637. ComponentBoundsConstrainer* const constrainer_)
  50638. : component (componentToResize),
  50639. constrainer (constrainer_)
  50640. {
  50641. setRepaintsOnMouseActivity (true);
  50642. setMouseCursor (MouseCursor::BottomRightCornerResizeCursor);
  50643. }
  50644. ResizableCornerComponent::~ResizableCornerComponent()
  50645. {
  50646. }
  50647. void ResizableCornerComponent::paint (Graphics& g)
  50648. {
  50649. getLookAndFeel()
  50650. .drawCornerResizer (g, getWidth(), getHeight(),
  50651. isMouseOverOrDragging(),
  50652. isMouseButtonDown());
  50653. }
  50654. void ResizableCornerComponent::mouseDown (const MouseEvent&)
  50655. {
  50656. if (component == 0)
  50657. {
  50658. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  50659. return;
  50660. }
  50661. originalBounds = component->getBounds();
  50662. if (constrainer != 0)
  50663. constrainer->resizeStart();
  50664. }
  50665. void ResizableCornerComponent::mouseDrag (const MouseEvent& e)
  50666. {
  50667. if (component == 0)
  50668. {
  50669. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  50670. return;
  50671. }
  50672. Rectangle<int> r (originalBounds.withSize (originalBounds.getWidth() + e.getDistanceFromDragStartX(),
  50673. originalBounds.getHeight() + e.getDistanceFromDragStartY()));
  50674. if (constrainer != 0)
  50675. constrainer->setBoundsForComponent (component, r, false, false, true, true);
  50676. else
  50677. component->setBounds (r);
  50678. }
  50679. void ResizableCornerComponent::mouseUp (const MouseEvent&)
  50680. {
  50681. if (constrainer != 0)
  50682. constrainer->resizeStart();
  50683. }
  50684. bool ResizableCornerComponent::hitTest (int x, int y)
  50685. {
  50686. if (getWidth() <= 0)
  50687. return false;
  50688. const int yAtX = getHeight() - (getHeight() * x / getWidth());
  50689. return y >= yAtX - getHeight() / 4;
  50690. }
  50691. END_JUCE_NAMESPACE
  50692. /*** End of inlined file: juce_ResizableCornerComponent.cpp ***/
  50693. /*** Start of inlined file: juce_ScrollBar.cpp ***/
  50694. BEGIN_JUCE_NAMESPACE
  50695. class ScrollBar::ScrollbarButton : public Button
  50696. {
  50697. public:
  50698. int direction;
  50699. ScrollbarButton (const int direction_, ScrollBar& owner_)
  50700. : Button (String::empty),
  50701. direction (direction_),
  50702. owner (owner_)
  50703. {
  50704. setWantsKeyboardFocus (false);
  50705. }
  50706. ~ScrollbarButton()
  50707. {
  50708. }
  50709. void paintButton (Graphics& g, bool over, bool down)
  50710. {
  50711. getLookAndFeel()
  50712. .drawScrollbarButton (g, owner,
  50713. getWidth(), getHeight(),
  50714. direction,
  50715. owner.isVertical(),
  50716. over, down);
  50717. }
  50718. void clicked()
  50719. {
  50720. owner.moveScrollbarInSteps ((direction == 1 || direction == 2) ? 1 : -1);
  50721. }
  50722. juce_UseDebuggingNewOperator
  50723. private:
  50724. ScrollBar& owner;
  50725. ScrollbarButton (const ScrollbarButton&);
  50726. ScrollbarButton& operator= (const ScrollbarButton&);
  50727. };
  50728. ScrollBar::ScrollBar (const bool vertical_,
  50729. const bool buttonsAreVisible)
  50730. : totalRange (0.0, 1.0),
  50731. visibleRange (0.0, 0.1),
  50732. singleStepSize (0.1),
  50733. thumbAreaStart (0),
  50734. thumbAreaSize (0),
  50735. thumbStart (0),
  50736. thumbSize (0),
  50737. initialDelayInMillisecs (100),
  50738. repeatDelayInMillisecs (50),
  50739. minimumDelayInMillisecs (10),
  50740. vertical (vertical_),
  50741. isDraggingThumb (false),
  50742. autohides (true)
  50743. {
  50744. setButtonVisibility (buttonsAreVisible);
  50745. setRepaintsOnMouseActivity (true);
  50746. setFocusContainer (true);
  50747. }
  50748. ScrollBar::~ScrollBar()
  50749. {
  50750. upButton = 0;
  50751. downButton = 0;
  50752. }
  50753. void ScrollBar::setRangeLimits (const Range<double>& newRangeLimit)
  50754. {
  50755. if (totalRange != newRangeLimit)
  50756. {
  50757. totalRange = newRangeLimit;
  50758. setCurrentRange (visibleRange);
  50759. updateThumbPosition();
  50760. }
  50761. }
  50762. void ScrollBar::setRangeLimits (const double newMinimum, const double newMaximum)
  50763. {
  50764. jassert (newMaximum >= newMinimum); // these can't be the wrong way round!
  50765. setRangeLimits (Range<double> (newMinimum, newMaximum));
  50766. }
  50767. void ScrollBar::setCurrentRange (const Range<double>& newRange)
  50768. {
  50769. const Range<double> constrainedRange (totalRange.constrainRange (newRange));
  50770. if (visibleRange != constrainedRange)
  50771. {
  50772. visibleRange = constrainedRange;
  50773. updateThumbPosition();
  50774. triggerAsyncUpdate();
  50775. }
  50776. }
  50777. void ScrollBar::setCurrentRange (const double newStart, const double newSize)
  50778. {
  50779. setCurrentRange (Range<double> (newStart, newStart + newSize));
  50780. }
  50781. void ScrollBar::setCurrentRangeStart (const double newStart)
  50782. {
  50783. setCurrentRange (visibleRange.movedToStartAt (newStart));
  50784. }
  50785. void ScrollBar::setSingleStepSize (const double newSingleStepSize)
  50786. {
  50787. singleStepSize = newSingleStepSize;
  50788. }
  50789. void ScrollBar::moveScrollbarInSteps (const int howManySteps)
  50790. {
  50791. setCurrentRange (visibleRange + howManySteps * singleStepSize);
  50792. }
  50793. void ScrollBar::moveScrollbarInPages (const int howManyPages)
  50794. {
  50795. setCurrentRange (visibleRange + howManyPages * visibleRange.getLength());
  50796. }
  50797. void ScrollBar::scrollToTop()
  50798. {
  50799. setCurrentRange (visibleRange.movedToStartAt (getMinimumRangeLimit()));
  50800. }
  50801. void ScrollBar::scrollToBottom()
  50802. {
  50803. setCurrentRange (visibleRange.movedToEndAt (getMaximumRangeLimit()));
  50804. }
  50805. void ScrollBar::setButtonRepeatSpeed (const int initialDelayInMillisecs_,
  50806. const int repeatDelayInMillisecs_,
  50807. const int minimumDelayInMillisecs_)
  50808. {
  50809. initialDelayInMillisecs = initialDelayInMillisecs_;
  50810. repeatDelayInMillisecs = repeatDelayInMillisecs_;
  50811. minimumDelayInMillisecs = minimumDelayInMillisecs_;
  50812. if (upButton != 0)
  50813. {
  50814. upButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50815. downButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50816. }
  50817. }
  50818. void ScrollBar::addListener (Listener* const listener)
  50819. {
  50820. listeners.add (listener);
  50821. }
  50822. void ScrollBar::removeListener (Listener* const listener)
  50823. {
  50824. listeners.remove (listener);
  50825. }
  50826. void ScrollBar::handleAsyncUpdate()
  50827. {
  50828. double start = visibleRange.getStart(); // (need to use a temp variable for VC7 compatibility)
  50829. listeners.call (&ScrollBar::Listener::scrollBarMoved, this, start);
  50830. }
  50831. void ScrollBar::updateThumbPosition()
  50832. {
  50833. int newThumbSize = roundToInt (totalRange.getLength() > 0 ? (visibleRange.getLength() * thumbAreaSize) / totalRange.getLength()
  50834. : thumbAreaSize);
  50835. if (newThumbSize < getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50836. newThumbSize = jmin (getLookAndFeel().getMinimumScrollbarThumbSize (*this), thumbAreaSize - 1);
  50837. if (newThumbSize > thumbAreaSize)
  50838. newThumbSize = thumbAreaSize;
  50839. int newThumbStart = thumbAreaStart;
  50840. if (totalRange.getLength() > visibleRange.getLength())
  50841. newThumbStart += roundToInt (((visibleRange.getStart() - totalRange.getStart()) * (thumbAreaSize - newThumbSize))
  50842. / (totalRange.getLength() - visibleRange.getLength()));
  50843. setVisible ((! autohides) || (totalRange.getLength() > visibleRange.getLength() && visibleRange.getLength() > 0.0));
  50844. if (thumbStart != newThumbStart || thumbSize != newThumbSize)
  50845. {
  50846. const int repaintStart = jmin (thumbStart, newThumbStart) - 4;
  50847. const int repaintSize = jmax (thumbStart + thumbSize, newThumbStart + newThumbSize) + 8 - repaintStart;
  50848. if (vertical)
  50849. repaint (0, repaintStart, getWidth(), repaintSize);
  50850. else
  50851. repaint (repaintStart, 0, repaintSize, getHeight());
  50852. thumbStart = newThumbStart;
  50853. thumbSize = newThumbSize;
  50854. }
  50855. }
  50856. void ScrollBar::setOrientation (const bool shouldBeVertical)
  50857. {
  50858. if (vertical != shouldBeVertical)
  50859. {
  50860. vertical = shouldBeVertical;
  50861. if (upButton != 0)
  50862. {
  50863. upButton->direction = vertical ? 0 : 3;
  50864. downButton->direction = vertical ? 2 : 1;
  50865. }
  50866. updateThumbPosition();
  50867. }
  50868. }
  50869. void ScrollBar::setButtonVisibility (const bool buttonsAreVisible)
  50870. {
  50871. upButton = 0;
  50872. downButton = 0;
  50873. if (buttonsAreVisible)
  50874. {
  50875. addAndMakeVisible (upButton = new ScrollbarButton (vertical ? 0 : 3, *this));
  50876. addAndMakeVisible (downButton = new ScrollbarButton (vertical ? 2 : 1, *this));
  50877. setButtonRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50878. }
  50879. updateThumbPosition();
  50880. }
  50881. void ScrollBar::setAutoHide (const bool shouldHideWhenFullRange)
  50882. {
  50883. autohides = shouldHideWhenFullRange;
  50884. updateThumbPosition();
  50885. }
  50886. bool ScrollBar::autoHides() const throw()
  50887. {
  50888. return autohides;
  50889. }
  50890. void ScrollBar::paint (Graphics& g)
  50891. {
  50892. if (thumbAreaSize > 0)
  50893. {
  50894. LookAndFeel& lf = getLookAndFeel();
  50895. const int thumb = (thumbAreaSize > lf.getMinimumScrollbarThumbSize (*this))
  50896. ? thumbSize : 0;
  50897. if (vertical)
  50898. {
  50899. lf.drawScrollbar (g, *this,
  50900. 0, thumbAreaStart,
  50901. getWidth(), thumbAreaSize,
  50902. vertical,
  50903. thumbStart, thumb,
  50904. isMouseOver(), isMouseButtonDown());
  50905. }
  50906. else
  50907. {
  50908. lf.drawScrollbar (g, *this,
  50909. thumbAreaStart, 0,
  50910. thumbAreaSize, getHeight(),
  50911. vertical,
  50912. thumbStart, thumb,
  50913. isMouseOver(), isMouseButtonDown());
  50914. }
  50915. }
  50916. }
  50917. void ScrollBar::lookAndFeelChanged()
  50918. {
  50919. setComponentEffect (getLookAndFeel().getScrollbarEffect());
  50920. }
  50921. void ScrollBar::resized()
  50922. {
  50923. const int length = ((vertical) ? getHeight() : getWidth());
  50924. const int buttonSize = (upButton != 0) ? jmin (getLookAndFeel().getScrollbarButtonSize (*this), (length >> 1))
  50925. : 0;
  50926. if (length < 32 + getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50927. {
  50928. thumbAreaStart = length >> 1;
  50929. thumbAreaSize = 0;
  50930. }
  50931. else
  50932. {
  50933. thumbAreaStart = buttonSize;
  50934. thumbAreaSize = length - (buttonSize << 1);
  50935. }
  50936. if (upButton != 0)
  50937. {
  50938. if (vertical)
  50939. {
  50940. upButton->setBounds (0, 0, getWidth(), buttonSize);
  50941. downButton->setBounds (0, thumbAreaStart + thumbAreaSize, getWidth(), buttonSize);
  50942. }
  50943. else
  50944. {
  50945. upButton->setBounds (0, 0, buttonSize, getHeight());
  50946. downButton->setBounds (thumbAreaStart + thumbAreaSize, 0, buttonSize, getHeight());
  50947. }
  50948. }
  50949. updateThumbPosition();
  50950. }
  50951. void ScrollBar::mouseDown (const MouseEvent& e)
  50952. {
  50953. isDraggingThumb = false;
  50954. lastMousePos = vertical ? e.y : e.x;
  50955. dragStartMousePos = lastMousePos;
  50956. dragStartRange = visibleRange.getStart();
  50957. if (dragStartMousePos < thumbStart)
  50958. {
  50959. moveScrollbarInPages (-1);
  50960. startTimer (400);
  50961. }
  50962. else if (dragStartMousePos >= thumbStart + thumbSize)
  50963. {
  50964. moveScrollbarInPages (1);
  50965. startTimer (400);
  50966. }
  50967. else
  50968. {
  50969. isDraggingThumb = (thumbAreaSize > getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50970. && (thumbAreaSize > thumbSize);
  50971. }
  50972. }
  50973. void ScrollBar::mouseDrag (const MouseEvent& e)
  50974. {
  50975. if (isDraggingThumb)
  50976. {
  50977. const int deltaPixels = ((vertical) ? e.y : e.x) - dragStartMousePos;
  50978. setCurrentRangeStart (dragStartRange
  50979. + deltaPixels * (totalRange.getLength() - visibleRange.getLength())
  50980. / (thumbAreaSize - thumbSize));
  50981. }
  50982. else
  50983. {
  50984. lastMousePos = (vertical) ? e.y : e.x;
  50985. }
  50986. }
  50987. void ScrollBar::mouseUp (const MouseEvent&)
  50988. {
  50989. isDraggingThumb = false;
  50990. stopTimer();
  50991. repaint();
  50992. }
  50993. void ScrollBar::mouseWheelMove (const MouseEvent&,
  50994. float wheelIncrementX,
  50995. float wheelIncrementY)
  50996. {
  50997. float increment = vertical ? wheelIncrementY : wheelIncrementX;
  50998. if (increment < 0)
  50999. increment = jmin (increment * 10.0f, -1.0f);
  51000. else if (increment > 0)
  51001. increment = jmax (increment * 10.0f, 1.0f);
  51002. setCurrentRange (visibleRange - singleStepSize * increment);
  51003. }
  51004. void ScrollBar::timerCallback()
  51005. {
  51006. if (isMouseButtonDown())
  51007. {
  51008. startTimer (40);
  51009. if (lastMousePos < thumbStart)
  51010. setCurrentRange (visibleRange - visibleRange.getLength());
  51011. else if (lastMousePos > thumbStart + thumbSize)
  51012. setCurrentRangeStart (visibleRange.getEnd());
  51013. }
  51014. else
  51015. {
  51016. stopTimer();
  51017. }
  51018. }
  51019. bool ScrollBar::keyPressed (const KeyPress& key)
  51020. {
  51021. if (! isVisible())
  51022. return false;
  51023. if (key.isKeyCode (KeyPress::upKey) || key.isKeyCode (KeyPress::leftKey))
  51024. moveScrollbarInSteps (-1);
  51025. else if (key.isKeyCode (KeyPress::downKey) || key.isKeyCode (KeyPress::rightKey))
  51026. moveScrollbarInSteps (1);
  51027. else if (key.isKeyCode (KeyPress::pageUpKey))
  51028. moveScrollbarInPages (-1);
  51029. else if (key.isKeyCode (KeyPress::pageDownKey))
  51030. moveScrollbarInPages (1);
  51031. else if (key.isKeyCode (KeyPress::homeKey))
  51032. scrollToTop();
  51033. else if (key.isKeyCode (KeyPress::endKey))
  51034. scrollToBottom();
  51035. else
  51036. return false;
  51037. return true;
  51038. }
  51039. END_JUCE_NAMESPACE
  51040. /*** End of inlined file: juce_ScrollBar.cpp ***/
  51041. /*** Start of inlined file: juce_StretchableLayoutManager.cpp ***/
  51042. BEGIN_JUCE_NAMESPACE
  51043. StretchableLayoutManager::StretchableLayoutManager()
  51044. : totalSize (0)
  51045. {
  51046. }
  51047. StretchableLayoutManager::~StretchableLayoutManager()
  51048. {
  51049. }
  51050. void StretchableLayoutManager::clearAllItems()
  51051. {
  51052. items.clear();
  51053. totalSize = 0;
  51054. }
  51055. void StretchableLayoutManager::setItemLayout (const int itemIndex,
  51056. const double minimumSize,
  51057. const double maximumSize,
  51058. const double preferredSize)
  51059. {
  51060. ItemLayoutProperties* layout = getInfoFor (itemIndex);
  51061. if (layout == 0)
  51062. {
  51063. layout = new ItemLayoutProperties();
  51064. layout->itemIndex = itemIndex;
  51065. int i;
  51066. for (i = 0; i < items.size(); ++i)
  51067. if (items.getUnchecked (i)->itemIndex > itemIndex)
  51068. break;
  51069. items.insert (i, layout);
  51070. }
  51071. layout->minSize = minimumSize;
  51072. layout->maxSize = maximumSize;
  51073. layout->preferredSize = preferredSize;
  51074. layout->currentSize = 0;
  51075. }
  51076. bool StretchableLayoutManager::getItemLayout (const int itemIndex,
  51077. double& minimumSize,
  51078. double& maximumSize,
  51079. double& preferredSize) const
  51080. {
  51081. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  51082. if (layout != 0)
  51083. {
  51084. minimumSize = layout->minSize;
  51085. maximumSize = layout->maxSize;
  51086. preferredSize = layout->preferredSize;
  51087. return true;
  51088. }
  51089. return false;
  51090. }
  51091. void StretchableLayoutManager::setTotalSize (const int newTotalSize)
  51092. {
  51093. totalSize = newTotalSize;
  51094. fitComponentsIntoSpace (0, items.size(), totalSize, 0);
  51095. }
  51096. int StretchableLayoutManager::getItemCurrentPosition (const int itemIndex) const
  51097. {
  51098. int pos = 0;
  51099. for (int i = 0; i < itemIndex; ++i)
  51100. {
  51101. const ItemLayoutProperties* const layout = getInfoFor (i);
  51102. if (layout != 0)
  51103. pos += layout->currentSize;
  51104. }
  51105. return pos;
  51106. }
  51107. int StretchableLayoutManager::getItemCurrentAbsoluteSize (const int itemIndex) const
  51108. {
  51109. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  51110. if (layout != 0)
  51111. return layout->currentSize;
  51112. return 0;
  51113. }
  51114. double StretchableLayoutManager::getItemCurrentRelativeSize (const int itemIndex) const
  51115. {
  51116. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  51117. if (layout != 0)
  51118. return -layout->currentSize / (double) totalSize;
  51119. return 0;
  51120. }
  51121. void StretchableLayoutManager::setItemPosition (const int itemIndex,
  51122. int newPosition)
  51123. {
  51124. for (int i = items.size(); --i >= 0;)
  51125. {
  51126. const ItemLayoutProperties* const layout = items.getUnchecked(i);
  51127. if (layout->itemIndex == itemIndex)
  51128. {
  51129. int realTotalSize = jmax (totalSize, getMinimumSizeOfItems (0, items.size()));
  51130. const int minSizeAfterThisComp = getMinimumSizeOfItems (i, items.size());
  51131. const int maxSizeAfterThisComp = getMaximumSizeOfItems (i + 1, items.size());
  51132. newPosition = jmax (newPosition, totalSize - maxSizeAfterThisComp - layout->currentSize);
  51133. newPosition = jmin (newPosition, realTotalSize - minSizeAfterThisComp);
  51134. int endPos = fitComponentsIntoSpace (0, i, newPosition, 0);
  51135. endPos += layout->currentSize;
  51136. fitComponentsIntoSpace (i + 1, items.size(), totalSize - endPos, endPos);
  51137. updatePrefSizesToMatchCurrentPositions();
  51138. break;
  51139. }
  51140. }
  51141. }
  51142. void StretchableLayoutManager::layOutComponents (Component** const components,
  51143. int numComponents,
  51144. int x, int y, int w, int h,
  51145. const bool vertically,
  51146. const bool resizeOtherDimension)
  51147. {
  51148. setTotalSize (vertically ? h : w);
  51149. int pos = vertically ? y : x;
  51150. for (int i = 0; i < numComponents; ++i)
  51151. {
  51152. const ItemLayoutProperties* const layout = getInfoFor (i);
  51153. if (layout != 0)
  51154. {
  51155. Component* const c = components[i];
  51156. if (c != 0)
  51157. {
  51158. if (i == numComponents - 1)
  51159. {
  51160. // if it's the last item, crop it to exactly fit the available space..
  51161. if (resizeOtherDimension)
  51162. {
  51163. if (vertically)
  51164. c->setBounds (x, pos, w, jmax (layout->currentSize, h - pos));
  51165. else
  51166. c->setBounds (pos, y, jmax (layout->currentSize, w - pos), h);
  51167. }
  51168. else
  51169. {
  51170. if (vertically)
  51171. c->setBounds (c->getX(), pos, c->getWidth(), jmax (layout->currentSize, h - pos));
  51172. else
  51173. c->setBounds (pos, c->getY(), jmax (layout->currentSize, w - pos), c->getHeight());
  51174. }
  51175. }
  51176. else
  51177. {
  51178. if (resizeOtherDimension)
  51179. {
  51180. if (vertically)
  51181. c->setBounds (x, pos, w, layout->currentSize);
  51182. else
  51183. c->setBounds (pos, y, layout->currentSize, h);
  51184. }
  51185. else
  51186. {
  51187. if (vertically)
  51188. c->setBounds (c->getX(), pos, c->getWidth(), layout->currentSize);
  51189. else
  51190. c->setBounds (pos, c->getY(), layout->currentSize, c->getHeight());
  51191. }
  51192. }
  51193. }
  51194. pos += layout->currentSize;
  51195. }
  51196. }
  51197. }
  51198. StretchableLayoutManager::ItemLayoutProperties* StretchableLayoutManager::getInfoFor (const int itemIndex) const
  51199. {
  51200. for (int i = items.size(); --i >= 0;)
  51201. if (items.getUnchecked(i)->itemIndex == itemIndex)
  51202. return items.getUnchecked(i);
  51203. return 0;
  51204. }
  51205. int StretchableLayoutManager::fitComponentsIntoSpace (const int startIndex,
  51206. const int endIndex,
  51207. const int availableSpace,
  51208. int startPos)
  51209. {
  51210. // calculate the total sizes
  51211. int i;
  51212. double totalIdealSize = 0.0;
  51213. int totalMinimums = 0;
  51214. for (i = startIndex; i < endIndex; ++i)
  51215. {
  51216. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51217. layout->currentSize = sizeToRealSize (layout->minSize, totalSize);
  51218. totalMinimums += layout->currentSize;
  51219. totalIdealSize += sizeToRealSize (layout->preferredSize, totalSize);
  51220. }
  51221. if (totalIdealSize <= 0)
  51222. totalIdealSize = 1.0;
  51223. // now calc the best sizes..
  51224. int extraSpace = availableSpace - totalMinimums;
  51225. while (extraSpace > 0)
  51226. {
  51227. int numWantingMoreSpace = 0;
  51228. int numHavingTakenExtraSpace = 0;
  51229. // first figure out how many comps want a slice of the extra space..
  51230. for (i = startIndex; i < endIndex; ++i)
  51231. {
  51232. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51233. double sizeWanted = sizeToRealSize (layout->preferredSize, totalSize);
  51234. const int bestSize = jlimit (layout->currentSize,
  51235. jmax (layout->currentSize,
  51236. sizeToRealSize (layout->maxSize, totalSize)),
  51237. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  51238. if (bestSize > layout->currentSize)
  51239. ++numWantingMoreSpace;
  51240. }
  51241. // ..share out the extra space..
  51242. for (i = startIndex; i < endIndex; ++i)
  51243. {
  51244. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51245. double sizeWanted = sizeToRealSize (layout->preferredSize, totalSize);
  51246. int bestSize = jlimit (layout->currentSize,
  51247. jmax (layout->currentSize, sizeToRealSize (layout->maxSize, totalSize)),
  51248. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  51249. const int extraWanted = bestSize - layout->currentSize;
  51250. if (extraWanted > 0)
  51251. {
  51252. const int extraAllowed = jmin (extraWanted,
  51253. extraSpace / jmax (1, numWantingMoreSpace));
  51254. if (extraAllowed > 0)
  51255. {
  51256. ++numHavingTakenExtraSpace;
  51257. --numWantingMoreSpace;
  51258. layout->currentSize += extraAllowed;
  51259. extraSpace -= extraAllowed;
  51260. }
  51261. }
  51262. }
  51263. if (numHavingTakenExtraSpace <= 0)
  51264. break;
  51265. }
  51266. // ..and calculate the end position
  51267. for (i = startIndex; i < endIndex; ++i)
  51268. {
  51269. ItemLayoutProperties* const layout = items.getUnchecked(i);
  51270. startPos += layout->currentSize;
  51271. }
  51272. return startPos;
  51273. }
  51274. int StretchableLayoutManager::getMinimumSizeOfItems (const int startIndex,
  51275. const int endIndex) const
  51276. {
  51277. int totalMinimums = 0;
  51278. for (int i = startIndex; i < endIndex; ++i)
  51279. totalMinimums += sizeToRealSize (items.getUnchecked (i)->minSize, totalSize);
  51280. return totalMinimums;
  51281. }
  51282. int StretchableLayoutManager::getMaximumSizeOfItems (const int startIndex, const int endIndex) const
  51283. {
  51284. int totalMaximums = 0;
  51285. for (int i = startIndex; i < endIndex; ++i)
  51286. totalMaximums += sizeToRealSize (items.getUnchecked (i)->maxSize, totalSize);
  51287. return totalMaximums;
  51288. }
  51289. void StretchableLayoutManager::updatePrefSizesToMatchCurrentPositions()
  51290. {
  51291. for (int i = 0; i < items.size(); ++i)
  51292. {
  51293. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51294. layout->preferredSize
  51295. = (layout->preferredSize < 0) ? getItemCurrentRelativeSize (i)
  51296. : getItemCurrentAbsoluteSize (i);
  51297. }
  51298. }
  51299. int StretchableLayoutManager::sizeToRealSize (double size, int totalSpace)
  51300. {
  51301. if (size < 0)
  51302. size *= -totalSpace;
  51303. return roundToInt (size);
  51304. }
  51305. END_JUCE_NAMESPACE
  51306. /*** End of inlined file: juce_StretchableLayoutManager.cpp ***/
  51307. /*** Start of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  51308. BEGIN_JUCE_NAMESPACE
  51309. StretchableLayoutResizerBar::StretchableLayoutResizerBar (StretchableLayoutManager* layout_,
  51310. const int itemIndex_,
  51311. const bool isVertical_)
  51312. : layout (layout_),
  51313. itemIndex (itemIndex_),
  51314. isVertical (isVertical_)
  51315. {
  51316. setRepaintsOnMouseActivity (true);
  51317. setMouseCursor (MouseCursor (isVertical_ ? MouseCursor::LeftRightResizeCursor
  51318. : MouseCursor::UpDownResizeCursor));
  51319. }
  51320. StretchableLayoutResizerBar::~StretchableLayoutResizerBar()
  51321. {
  51322. }
  51323. void StretchableLayoutResizerBar::paint (Graphics& g)
  51324. {
  51325. getLookAndFeel().drawStretchableLayoutResizerBar (g,
  51326. getWidth(), getHeight(),
  51327. isVertical,
  51328. isMouseOver(),
  51329. isMouseButtonDown());
  51330. }
  51331. void StretchableLayoutResizerBar::mouseDown (const MouseEvent&)
  51332. {
  51333. mouseDownPos = layout->getItemCurrentPosition (itemIndex);
  51334. }
  51335. void StretchableLayoutResizerBar::mouseDrag (const MouseEvent& e)
  51336. {
  51337. const int desiredPos = mouseDownPos + (isVertical ? e.getDistanceFromDragStartX()
  51338. : e.getDistanceFromDragStartY());
  51339. layout->setItemPosition (itemIndex, desiredPos);
  51340. hasBeenMoved();
  51341. }
  51342. void StretchableLayoutResizerBar::hasBeenMoved()
  51343. {
  51344. if (getParentComponent() != 0)
  51345. getParentComponent()->resized();
  51346. }
  51347. END_JUCE_NAMESPACE
  51348. /*** End of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  51349. /*** Start of inlined file: juce_StretchableObjectResizer.cpp ***/
  51350. BEGIN_JUCE_NAMESPACE
  51351. StretchableObjectResizer::StretchableObjectResizer()
  51352. {
  51353. }
  51354. StretchableObjectResizer::~StretchableObjectResizer()
  51355. {
  51356. }
  51357. void StretchableObjectResizer::addItem (const double size,
  51358. const double minSize, const double maxSize,
  51359. const int order)
  51360. {
  51361. // the order must be >= 0 but less than the maximum integer value.
  51362. jassert (order >= 0 && order < std::numeric_limits<int>::max());
  51363. Item* const item = new Item();
  51364. item->size = size;
  51365. item->minSize = minSize;
  51366. item->maxSize = maxSize;
  51367. item->order = order;
  51368. items.add (item);
  51369. }
  51370. double StretchableObjectResizer::getItemSize (const int index) const throw()
  51371. {
  51372. const Item* const it = items [index];
  51373. return it != 0 ? it->size : 0;
  51374. }
  51375. void StretchableObjectResizer::resizeToFit (const double targetSize)
  51376. {
  51377. int order = 0;
  51378. for (;;)
  51379. {
  51380. double currentSize = 0;
  51381. double minSize = 0;
  51382. double maxSize = 0;
  51383. int nextHighestOrder = std::numeric_limits<int>::max();
  51384. for (int i = 0; i < items.size(); ++i)
  51385. {
  51386. const Item* const it = items.getUnchecked(i);
  51387. currentSize += it->size;
  51388. if (it->order <= order)
  51389. {
  51390. minSize += it->minSize;
  51391. maxSize += it->maxSize;
  51392. }
  51393. else
  51394. {
  51395. minSize += it->size;
  51396. maxSize += it->size;
  51397. nextHighestOrder = jmin (nextHighestOrder, it->order);
  51398. }
  51399. }
  51400. const double thisIterationTarget = jlimit (minSize, maxSize, targetSize);
  51401. if (thisIterationTarget >= currentSize)
  51402. {
  51403. const double availableExtraSpace = maxSize - currentSize;
  51404. const double targetAmountOfExtraSpace = thisIterationTarget - currentSize;
  51405. const double scale = targetAmountOfExtraSpace / availableExtraSpace;
  51406. for (int i = 0; i < items.size(); ++i)
  51407. {
  51408. Item* const it = items.getUnchecked(i);
  51409. if (it->order <= order)
  51410. it->size = jmin (it->maxSize, it->size + (it->maxSize - it->size) * scale);
  51411. }
  51412. }
  51413. else
  51414. {
  51415. const double amountOfSlack = currentSize - minSize;
  51416. const double targetAmountOfSlack = thisIterationTarget - minSize;
  51417. const double scale = targetAmountOfSlack / amountOfSlack;
  51418. for (int i = 0; i < items.size(); ++i)
  51419. {
  51420. Item* const it = items.getUnchecked(i);
  51421. if (it->order <= order)
  51422. it->size = jmax (it->minSize, it->minSize + (it->size - it->minSize) * scale);
  51423. }
  51424. }
  51425. if (nextHighestOrder < std::numeric_limits<int>::max())
  51426. order = nextHighestOrder;
  51427. else
  51428. break;
  51429. }
  51430. }
  51431. END_JUCE_NAMESPACE
  51432. /*** End of inlined file: juce_StretchableObjectResizer.cpp ***/
  51433. /*** Start of inlined file: juce_TabbedButtonBar.cpp ***/
  51434. BEGIN_JUCE_NAMESPACE
  51435. TabBarButton::TabBarButton (const String& name,
  51436. TabbedButtonBar* const owner_,
  51437. const int index)
  51438. : Button (name),
  51439. owner (owner_),
  51440. tabIndex (index),
  51441. overlapPixels (0)
  51442. {
  51443. shadow.setShadowProperties (2.2f, 0.7f, 0, 0);
  51444. setComponentEffect (&shadow);
  51445. setWantsKeyboardFocus (false);
  51446. }
  51447. TabBarButton::~TabBarButton()
  51448. {
  51449. }
  51450. void TabBarButton::paintButton (Graphics& g,
  51451. bool isMouseOverButton,
  51452. bool isButtonDown)
  51453. {
  51454. int x, y, w, h;
  51455. getActiveArea (x, y, w, h);
  51456. g.setOrigin (x, y);
  51457. getLookAndFeel()
  51458. .drawTabButton (g, w, h,
  51459. owner->getTabBackgroundColour (tabIndex),
  51460. tabIndex, getButtonText(), *this,
  51461. owner->getOrientation(),
  51462. isMouseOverButton, isButtonDown,
  51463. getToggleState());
  51464. }
  51465. void TabBarButton::clicked (const ModifierKeys& mods)
  51466. {
  51467. if (mods.isPopupMenu())
  51468. owner->popupMenuClickOnTab (tabIndex, getButtonText());
  51469. else
  51470. owner->setCurrentTabIndex (tabIndex);
  51471. }
  51472. bool TabBarButton::hitTest (int mx, int my)
  51473. {
  51474. int x, y, w, h;
  51475. getActiveArea (x, y, w, h);
  51476. if (owner->getOrientation() == TabbedButtonBar::TabsAtLeft
  51477. || owner->getOrientation() == TabbedButtonBar::TabsAtRight)
  51478. {
  51479. if (((unsigned int) mx) < (unsigned int) getWidth()
  51480. && my >= y + overlapPixels
  51481. && my < y + h - overlapPixels)
  51482. return true;
  51483. }
  51484. else
  51485. {
  51486. if (mx >= x + overlapPixels && mx < x + w - overlapPixels
  51487. && ((unsigned int) my) < (unsigned int) getHeight())
  51488. return true;
  51489. }
  51490. Path p;
  51491. getLookAndFeel()
  51492. .createTabButtonShape (p, w, h, tabIndex, getButtonText(), *this,
  51493. owner->getOrientation(),
  51494. false, false, getToggleState());
  51495. return p.contains ((float) (mx - x),
  51496. (float) (my - y));
  51497. }
  51498. int TabBarButton::getBestTabLength (const int depth)
  51499. {
  51500. return jlimit (depth * 2,
  51501. depth * 7,
  51502. getLookAndFeel().getTabButtonBestWidth (tabIndex, getButtonText(), depth, *this));
  51503. }
  51504. void TabBarButton::getActiveArea (int& x, int& y, int& w, int& h)
  51505. {
  51506. x = 0;
  51507. y = 0;
  51508. int r = getWidth();
  51509. int b = getHeight();
  51510. const int spaceAroundImage = getLookAndFeel().getTabButtonSpaceAroundImage();
  51511. if (owner->getOrientation() != TabbedButtonBar::TabsAtLeft)
  51512. r -= spaceAroundImage;
  51513. if (owner->getOrientation() != TabbedButtonBar::TabsAtRight)
  51514. x += spaceAroundImage;
  51515. if (owner->getOrientation() != TabbedButtonBar::TabsAtBottom)
  51516. y += spaceAroundImage;
  51517. if (owner->getOrientation() != TabbedButtonBar::TabsAtTop)
  51518. b -= spaceAroundImage;
  51519. w = r - x;
  51520. h = b - y;
  51521. }
  51522. class TabAreaBehindFrontButtonComponent : public Component
  51523. {
  51524. public:
  51525. TabAreaBehindFrontButtonComponent (TabbedButtonBar* const owner_)
  51526. : owner (owner_)
  51527. {
  51528. setInterceptsMouseClicks (false, false);
  51529. }
  51530. ~TabAreaBehindFrontButtonComponent()
  51531. {
  51532. }
  51533. void paint (Graphics& g)
  51534. {
  51535. getLookAndFeel()
  51536. .drawTabAreaBehindFrontButton (g, getWidth(), getHeight(),
  51537. *owner, owner->getOrientation());
  51538. }
  51539. void enablementChanged()
  51540. {
  51541. repaint();
  51542. }
  51543. private:
  51544. TabbedButtonBar* const owner;
  51545. TabAreaBehindFrontButtonComponent (const TabAreaBehindFrontButtonComponent&);
  51546. TabAreaBehindFrontButtonComponent& operator= (const TabAreaBehindFrontButtonComponent&);
  51547. };
  51548. TabbedButtonBar::TabbedButtonBar (const Orientation orientation_)
  51549. : orientation (orientation_),
  51550. currentTabIndex (-1)
  51551. {
  51552. setInterceptsMouseClicks (false, true);
  51553. addAndMakeVisible (behindFrontTab = new TabAreaBehindFrontButtonComponent (this));
  51554. setFocusContainer (true);
  51555. }
  51556. TabbedButtonBar::~TabbedButtonBar()
  51557. {
  51558. extraTabsButton = 0;
  51559. deleteAllChildren();
  51560. }
  51561. void TabbedButtonBar::setOrientation (const Orientation newOrientation)
  51562. {
  51563. orientation = newOrientation;
  51564. for (int i = getNumChildComponents(); --i >= 0;)
  51565. getChildComponent (i)->resized();
  51566. resized();
  51567. }
  51568. TabBarButton* TabbedButtonBar::createTabButton (const String& name, const int index)
  51569. {
  51570. return new TabBarButton (name, this, index);
  51571. }
  51572. void TabbedButtonBar::clearTabs()
  51573. {
  51574. tabs.clear();
  51575. tabColours.clear();
  51576. currentTabIndex = -1;
  51577. extraTabsButton = 0;
  51578. removeChildComponent (behindFrontTab);
  51579. deleteAllChildren();
  51580. addChildComponent (behindFrontTab);
  51581. setCurrentTabIndex (-1);
  51582. }
  51583. void TabbedButtonBar::addTab (const String& tabName,
  51584. const Colour& tabBackgroundColour,
  51585. int insertIndex)
  51586. {
  51587. jassert (tabName.isNotEmpty()); // you have to give them all a name..
  51588. if (tabName.isNotEmpty())
  51589. {
  51590. if (((unsigned int) insertIndex) > (unsigned int) tabs.size())
  51591. insertIndex = tabs.size();
  51592. for (int i = tabs.size(); --i >= insertIndex;)
  51593. {
  51594. TabBarButton* const tb = getTabButton (i);
  51595. if (tb != 0)
  51596. tb->tabIndex++;
  51597. }
  51598. tabs.insert (insertIndex, tabName);
  51599. tabColours.insert (insertIndex, tabBackgroundColour);
  51600. TabBarButton* const tb = createTabButton (tabName, insertIndex);
  51601. jassert (tb != 0); // your createTabButton() mustn't return zero!
  51602. addAndMakeVisible (tb, insertIndex);
  51603. resized();
  51604. if (currentTabIndex < 0)
  51605. setCurrentTabIndex (0);
  51606. }
  51607. }
  51608. void TabbedButtonBar::setTabName (const int tabIndex,
  51609. const String& newName)
  51610. {
  51611. if (((unsigned int) tabIndex) < (unsigned int) tabs.size()
  51612. && tabs[tabIndex] != newName)
  51613. {
  51614. tabs.set (tabIndex, newName);
  51615. TabBarButton* const tb = getTabButton (tabIndex);
  51616. if (tb != 0)
  51617. tb->setButtonText (newName);
  51618. resized();
  51619. }
  51620. }
  51621. void TabbedButtonBar::removeTab (const int tabIndex)
  51622. {
  51623. if (((unsigned int) tabIndex) < (unsigned int) tabs.size())
  51624. {
  51625. const int oldTabIndex = currentTabIndex;
  51626. if (currentTabIndex == tabIndex)
  51627. currentTabIndex = -1;
  51628. tabs.remove (tabIndex);
  51629. tabColours.remove (tabIndex);
  51630. delete getTabButton (tabIndex);
  51631. for (int i = tabIndex + 1; i <= tabs.size(); ++i)
  51632. {
  51633. TabBarButton* const tb = getTabButton (i);
  51634. if (tb != 0)
  51635. tb->tabIndex--;
  51636. }
  51637. resized();
  51638. setCurrentTabIndex (jlimit (0, jmax (0, tabs.size() - 1), oldTabIndex));
  51639. }
  51640. }
  51641. void TabbedButtonBar::moveTab (const int currentIndex,
  51642. const int newIndex)
  51643. {
  51644. tabs.move (currentIndex, newIndex);
  51645. tabColours.move (currentIndex, newIndex);
  51646. resized();
  51647. }
  51648. int TabbedButtonBar::getNumTabs() const
  51649. {
  51650. return tabs.size();
  51651. }
  51652. const StringArray TabbedButtonBar::getTabNames() const
  51653. {
  51654. return tabs;
  51655. }
  51656. void TabbedButtonBar::setCurrentTabIndex (int newIndex, const bool sendChangeMessage_)
  51657. {
  51658. if (currentTabIndex != newIndex)
  51659. {
  51660. if (((unsigned int) newIndex) >= (unsigned int) tabs.size())
  51661. newIndex = -1;
  51662. currentTabIndex = newIndex;
  51663. for (int i = 0; i < getNumChildComponents(); ++i)
  51664. {
  51665. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  51666. if (tb != 0)
  51667. tb->setToggleState (tb->tabIndex == newIndex, false);
  51668. }
  51669. resized();
  51670. if (sendChangeMessage_)
  51671. sendChangeMessage (this);
  51672. currentTabChanged (newIndex, newIndex >= 0 ? tabs [newIndex] : String::empty);
  51673. }
  51674. }
  51675. TabBarButton* TabbedButtonBar::getTabButton (const int index) const
  51676. {
  51677. for (int i = getNumChildComponents(); --i >= 0;)
  51678. {
  51679. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  51680. if (tb != 0 && tb->tabIndex == index)
  51681. return tb;
  51682. }
  51683. return 0;
  51684. }
  51685. void TabbedButtonBar::lookAndFeelChanged()
  51686. {
  51687. extraTabsButton = 0;
  51688. resized();
  51689. }
  51690. void TabbedButtonBar::resized()
  51691. {
  51692. const double minimumScale = 0.7;
  51693. int depth = getWidth();
  51694. int length = getHeight();
  51695. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51696. swapVariables (depth, length);
  51697. const int overlap = getLookAndFeel().getTabButtonOverlap (depth)
  51698. + getLookAndFeel().getTabButtonSpaceAroundImage() * 2;
  51699. int i, totalLength = overlap;
  51700. int numVisibleButtons = tabs.size();
  51701. for (i = 0; i < getNumChildComponents(); ++i)
  51702. {
  51703. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  51704. if (tb != 0)
  51705. {
  51706. totalLength += tb->getBestTabLength (depth) - overlap;
  51707. tb->overlapPixels = overlap / 2;
  51708. }
  51709. }
  51710. double scale = 1.0;
  51711. if (totalLength > length)
  51712. scale = jmax (minimumScale, length / (double) totalLength);
  51713. const bool isTooBig = totalLength * scale > length;
  51714. int tabsButtonPos = 0;
  51715. if (isTooBig)
  51716. {
  51717. if (extraTabsButton == 0)
  51718. {
  51719. addAndMakeVisible (extraTabsButton = getLookAndFeel().createTabBarExtrasButton());
  51720. extraTabsButton->addButtonListener (this);
  51721. extraTabsButton->setAlwaysOnTop (true);
  51722. extraTabsButton->setTriggeredOnMouseDown (true);
  51723. }
  51724. const int buttonSize = jmin (proportionOfWidth (0.7f), proportionOfHeight (0.7f));
  51725. extraTabsButton->setSize (buttonSize, buttonSize);
  51726. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51727. {
  51728. tabsButtonPos = getWidth() - buttonSize / 2 - 1;
  51729. extraTabsButton->setCentrePosition (tabsButtonPos, getHeight() / 2);
  51730. }
  51731. else
  51732. {
  51733. tabsButtonPos = getHeight() - buttonSize / 2 - 1;
  51734. extraTabsButton->setCentrePosition (getWidth() / 2, tabsButtonPos);
  51735. }
  51736. totalLength = 0;
  51737. for (i = 0; i < tabs.size(); ++i)
  51738. {
  51739. TabBarButton* const tb = getTabButton (i);
  51740. if (tb != 0)
  51741. {
  51742. const int newLength = totalLength + tb->getBestTabLength (depth);
  51743. if (i > 0 && newLength * minimumScale > tabsButtonPos)
  51744. {
  51745. totalLength += overlap;
  51746. break;
  51747. }
  51748. numVisibleButtons = i + 1;
  51749. totalLength = newLength - overlap;
  51750. }
  51751. }
  51752. scale = jmax (minimumScale, tabsButtonPos / (double) totalLength);
  51753. }
  51754. else
  51755. {
  51756. extraTabsButton = 0;
  51757. }
  51758. int pos = 0;
  51759. TabBarButton* frontTab = 0;
  51760. for (i = 0; i < tabs.size(); ++i)
  51761. {
  51762. TabBarButton* const tb = getTabButton (i);
  51763. if (tb != 0)
  51764. {
  51765. const int bestLength = roundToInt (scale * tb->getBestTabLength (depth));
  51766. if (i < numVisibleButtons)
  51767. {
  51768. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51769. tb->setBounds (pos, 0, bestLength, getHeight());
  51770. else
  51771. tb->setBounds (0, pos, getWidth(), bestLength);
  51772. tb->toBack();
  51773. if (tb->tabIndex == currentTabIndex)
  51774. frontTab = tb;
  51775. tb->setVisible (true);
  51776. }
  51777. else
  51778. {
  51779. tb->setVisible (false);
  51780. }
  51781. pos += bestLength - overlap;
  51782. }
  51783. }
  51784. behindFrontTab->setBounds (getLocalBounds());
  51785. if (frontTab != 0)
  51786. {
  51787. frontTab->toFront (false);
  51788. behindFrontTab->toBehind (frontTab);
  51789. }
  51790. }
  51791. const Colour TabbedButtonBar::getTabBackgroundColour (const int tabIndex)
  51792. {
  51793. return tabColours [tabIndex];
  51794. }
  51795. void TabbedButtonBar::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  51796. {
  51797. if (((unsigned int) tabIndex) < (unsigned int) tabColours.size()
  51798. && tabColours [tabIndex] != newColour)
  51799. {
  51800. tabColours.set (tabIndex, newColour);
  51801. repaint();
  51802. }
  51803. }
  51804. void TabbedButtonBar::buttonClicked (Button* button)
  51805. {
  51806. if (button == extraTabsButton)
  51807. {
  51808. PopupMenu m;
  51809. for (int i = 0; i < tabs.size(); ++i)
  51810. {
  51811. TabBarButton* const tb = getTabButton (i);
  51812. if (tb != 0 && ! tb->isVisible())
  51813. m.addItem (tb->tabIndex + 1, tabs[i], true, i == currentTabIndex);
  51814. }
  51815. const int res = m.showAt (extraTabsButton);
  51816. if (res != 0)
  51817. setCurrentTabIndex (res - 1);
  51818. }
  51819. }
  51820. void TabbedButtonBar::currentTabChanged (const int, const String&)
  51821. {
  51822. }
  51823. void TabbedButtonBar::popupMenuClickOnTab (const int, const String&)
  51824. {
  51825. }
  51826. END_JUCE_NAMESPACE
  51827. /*** End of inlined file: juce_TabbedButtonBar.cpp ***/
  51828. /*** Start of inlined file: juce_TabbedComponent.cpp ***/
  51829. BEGIN_JUCE_NAMESPACE
  51830. class TabCompButtonBar : public TabbedButtonBar
  51831. {
  51832. public:
  51833. TabCompButtonBar (TabbedComponent* const owner_,
  51834. const TabbedButtonBar::Orientation orientation_)
  51835. : TabbedButtonBar (orientation_),
  51836. owner (owner_)
  51837. {
  51838. }
  51839. ~TabCompButtonBar()
  51840. {
  51841. }
  51842. void currentTabChanged (int newCurrentTabIndex, const String& newTabName)
  51843. {
  51844. owner->changeCallback (newCurrentTabIndex, newTabName);
  51845. }
  51846. void popupMenuClickOnTab (int tabIndex, const String& tabName)
  51847. {
  51848. owner->popupMenuClickOnTab (tabIndex, tabName);
  51849. }
  51850. const Colour getTabBackgroundColour (const int tabIndex)
  51851. {
  51852. return owner->tabs->getTabBackgroundColour (tabIndex);
  51853. }
  51854. TabBarButton* createTabButton (const String& tabName, int tabIndex)
  51855. {
  51856. return owner->createTabButton (tabName, tabIndex);
  51857. }
  51858. juce_UseDebuggingNewOperator
  51859. private:
  51860. TabbedComponent* const owner;
  51861. TabCompButtonBar (const TabCompButtonBar&);
  51862. TabCompButtonBar& operator= (const TabCompButtonBar&);
  51863. };
  51864. TabbedComponent::TabbedComponent (const TabbedButtonBar::Orientation orientation)
  51865. : panelComponent (0),
  51866. tabDepth (30),
  51867. outlineThickness (1),
  51868. edgeIndent (0)
  51869. {
  51870. addAndMakeVisible (tabs = new TabCompButtonBar (this, orientation));
  51871. }
  51872. TabbedComponent::~TabbedComponent()
  51873. {
  51874. clearTabs();
  51875. delete tabs;
  51876. }
  51877. void TabbedComponent::setOrientation (const TabbedButtonBar::Orientation orientation)
  51878. {
  51879. tabs->setOrientation (orientation);
  51880. resized();
  51881. }
  51882. TabbedButtonBar::Orientation TabbedComponent::getOrientation() const throw()
  51883. {
  51884. return tabs->getOrientation();
  51885. }
  51886. void TabbedComponent::setTabBarDepth (const int newDepth)
  51887. {
  51888. if (tabDepth != newDepth)
  51889. {
  51890. tabDepth = newDepth;
  51891. resized();
  51892. }
  51893. }
  51894. TabBarButton* TabbedComponent::createTabButton (const String& tabName, const int tabIndex)
  51895. {
  51896. return new TabBarButton (tabName, tabs, tabIndex);
  51897. }
  51898. const Identifier TabbedComponent::deleteComponentId ("deleteByTabComp_");
  51899. void TabbedComponent::clearTabs()
  51900. {
  51901. if (panelComponent != 0)
  51902. {
  51903. panelComponent->setVisible (false);
  51904. removeChildComponent (panelComponent);
  51905. panelComponent = 0;
  51906. }
  51907. tabs->clearTabs();
  51908. for (int i = contentComponents.size(); --i >= 0;)
  51909. {
  51910. Component* const c = contentComponents.getUnchecked(i);
  51911. // be careful not to delete these components until they've been removed from the tab component
  51912. jassert (c == 0 || c->isValidComponent());
  51913. if (c != 0 && (bool) c->getProperties() [deleteComponentId])
  51914. delete c;
  51915. }
  51916. contentComponents.clear();
  51917. }
  51918. void TabbedComponent::addTab (const String& tabName,
  51919. const Colour& tabBackgroundColour,
  51920. Component* const contentComponent,
  51921. const bool deleteComponentWhenNotNeeded,
  51922. const int insertIndex)
  51923. {
  51924. contentComponents.insert (insertIndex, contentComponent);
  51925. if (contentComponent != 0)
  51926. contentComponent->getProperties().set (deleteComponentId, deleteComponentWhenNotNeeded);
  51927. tabs->addTab (tabName, tabBackgroundColour, insertIndex);
  51928. }
  51929. void TabbedComponent::setTabName (const int tabIndex, const String& newName)
  51930. {
  51931. tabs->setTabName (tabIndex, newName);
  51932. }
  51933. void TabbedComponent::removeTab (const int tabIndex)
  51934. {
  51935. Component* const c = contentComponents [tabIndex];
  51936. if (c != 0 && (bool) c->getProperties() [deleteComponentId])
  51937. {
  51938. if (c == panelComponent)
  51939. panelComponent = 0;
  51940. delete c;
  51941. }
  51942. contentComponents.remove (tabIndex);
  51943. tabs->removeTab (tabIndex);
  51944. }
  51945. int TabbedComponent::getNumTabs() const
  51946. {
  51947. return tabs->getNumTabs();
  51948. }
  51949. const StringArray TabbedComponent::getTabNames() const
  51950. {
  51951. return tabs->getTabNames();
  51952. }
  51953. Component* TabbedComponent::getTabContentComponent (const int tabIndex) const throw()
  51954. {
  51955. return contentComponents [tabIndex];
  51956. }
  51957. const Colour TabbedComponent::getTabBackgroundColour (const int tabIndex) const throw()
  51958. {
  51959. return tabs->getTabBackgroundColour (tabIndex);
  51960. }
  51961. void TabbedComponent::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  51962. {
  51963. tabs->setTabBackgroundColour (tabIndex, newColour);
  51964. if (getCurrentTabIndex() == tabIndex)
  51965. repaint();
  51966. }
  51967. void TabbedComponent::setCurrentTabIndex (const int newTabIndex, const bool sendChangeMessage)
  51968. {
  51969. tabs->setCurrentTabIndex (newTabIndex, sendChangeMessage);
  51970. }
  51971. int TabbedComponent::getCurrentTabIndex() const
  51972. {
  51973. return tabs->getCurrentTabIndex();
  51974. }
  51975. const String& TabbedComponent::getCurrentTabName() const
  51976. {
  51977. return tabs->getCurrentTabName();
  51978. }
  51979. void TabbedComponent::setOutline (int thickness)
  51980. {
  51981. outlineThickness = thickness;
  51982. repaint();
  51983. }
  51984. void TabbedComponent::setIndent (const int indentThickness)
  51985. {
  51986. edgeIndent = indentThickness;
  51987. }
  51988. void TabbedComponent::paint (Graphics& g)
  51989. {
  51990. g.fillAll (findColour (backgroundColourId));
  51991. const TabbedButtonBar::Orientation o = getOrientation();
  51992. int x = 0;
  51993. int y = 0;
  51994. int r = getWidth();
  51995. int b = getHeight();
  51996. if (o == TabbedButtonBar::TabsAtTop)
  51997. y += tabDepth;
  51998. else if (o == TabbedButtonBar::TabsAtBottom)
  51999. b -= tabDepth;
  52000. else if (o == TabbedButtonBar::TabsAtLeft)
  52001. x += tabDepth;
  52002. else if (o == TabbedButtonBar::TabsAtRight)
  52003. r -= tabDepth;
  52004. g.reduceClipRegion (x, y, r - x, b - y);
  52005. g.fillAll (tabs->getTabBackgroundColour (getCurrentTabIndex()));
  52006. if (outlineThickness > 0)
  52007. {
  52008. if (o == TabbedButtonBar::TabsAtTop)
  52009. --y;
  52010. else if (o == TabbedButtonBar::TabsAtBottom)
  52011. ++b;
  52012. else if (o == TabbedButtonBar::TabsAtLeft)
  52013. --x;
  52014. else if (o == TabbedButtonBar::TabsAtRight)
  52015. ++r;
  52016. g.setColour (findColour (outlineColourId));
  52017. g.drawRect (x, y, r - x, b - y, outlineThickness);
  52018. }
  52019. }
  52020. void TabbedComponent::resized()
  52021. {
  52022. const TabbedButtonBar::Orientation o = getOrientation();
  52023. const int indent = edgeIndent + outlineThickness;
  52024. BorderSize indents (indent);
  52025. if (o == TabbedButtonBar::TabsAtTop)
  52026. {
  52027. tabs->setBounds (0, 0, getWidth(), tabDepth);
  52028. indents.setTop (tabDepth + edgeIndent);
  52029. }
  52030. else if (o == TabbedButtonBar::TabsAtBottom)
  52031. {
  52032. tabs->setBounds (0, getHeight() - tabDepth, getWidth(), tabDepth);
  52033. indents.setBottom (tabDepth + edgeIndent);
  52034. }
  52035. else if (o == TabbedButtonBar::TabsAtLeft)
  52036. {
  52037. tabs->setBounds (0, 0, tabDepth, getHeight());
  52038. indents.setLeft (tabDepth + edgeIndent);
  52039. }
  52040. else if (o == TabbedButtonBar::TabsAtRight)
  52041. {
  52042. tabs->setBounds (getWidth() - tabDepth, 0, tabDepth, getHeight());
  52043. indents.setRight (tabDepth + edgeIndent);
  52044. }
  52045. const Rectangle<int> bounds (indents.subtractedFrom (getLocalBounds()));
  52046. for (int i = contentComponents.size(); --i >= 0;)
  52047. if (contentComponents.getUnchecked (i) != 0)
  52048. contentComponents.getUnchecked (i)->setBounds (bounds);
  52049. }
  52050. void TabbedComponent::lookAndFeelChanged()
  52051. {
  52052. for (int i = contentComponents.size(); --i >= 0;)
  52053. if (contentComponents.getUnchecked (i) != 0)
  52054. contentComponents.getUnchecked (i)->lookAndFeelChanged();
  52055. }
  52056. void TabbedComponent::changeCallback (const int newCurrentTabIndex,
  52057. const String& newTabName)
  52058. {
  52059. if (panelComponent != 0)
  52060. {
  52061. panelComponent->setVisible (false);
  52062. removeChildComponent (panelComponent);
  52063. panelComponent = 0;
  52064. }
  52065. if (getCurrentTabIndex() >= 0)
  52066. {
  52067. panelComponent = contentComponents [getCurrentTabIndex()];
  52068. if (panelComponent != 0)
  52069. {
  52070. // do these ops as two stages instead of addAndMakeVisible() so that the
  52071. // component has always got a parent when it gets the visibilityChanged() callback
  52072. addChildComponent (panelComponent);
  52073. panelComponent->setVisible (true);
  52074. panelComponent->toFront (true);
  52075. }
  52076. repaint();
  52077. }
  52078. resized();
  52079. currentTabChanged (newCurrentTabIndex, newTabName);
  52080. }
  52081. void TabbedComponent::currentTabChanged (const int, const String&)
  52082. {
  52083. }
  52084. void TabbedComponent::popupMenuClickOnTab (const int, const String&)
  52085. {
  52086. }
  52087. END_JUCE_NAMESPACE
  52088. /*** End of inlined file: juce_TabbedComponent.cpp ***/
  52089. /*** Start of inlined file: juce_Viewport.cpp ***/
  52090. BEGIN_JUCE_NAMESPACE
  52091. Viewport::Viewport (const String& componentName)
  52092. : Component (componentName),
  52093. scrollBarThickness (0),
  52094. singleStepX (16),
  52095. singleStepY (16),
  52096. showHScrollbar (true),
  52097. showVScrollbar (true),
  52098. verticalScrollBar (true),
  52099. horizontalScrollBar (false)
  52100. {
  52101. // content holder is used to clip the contents so they don't overlap the scrollbars
  52102. addAndMakeVisible (&contentHolder);
  52103. contentHolder.setInterceptsMouseClicks (false, true);
  52104. addChildComponent (&verticalScrollBar);
  52105. addChildComponent (&horizontalScrollBar);
  52106. verticalScrollBar.addListener (this);
  52107. horizontalScrollBar.addListener (this);
  52108. setInterceptsMouseClicks (false, true);
  52109. setWantsKeyboardFocus (true);
  52110. }
  52111. Viewport::~Viewport()
  52112. {
  52113. contentHolder.deleteAllChildren();
  52114. }
  52115. void Viewport::visibleAreaChanged (int, int, int, int)
  52116. {
  52117. }
  52118. void Viewport::setViewedComponent (Component* const newViewedComponent)
  52119. {
  52120. if (contentComp.getComponent() != newViewedComponent)
  52121. {
  52122. {
  52123. ScopedPointer<Component> oldCompDeleter (contentComp);
  52124. contentComp = 0;
  52125. }
  52126. contentComp = newViewedComponent;
  52127. if (contentComp != 0)
  52128. {
  52129. contentComp->setTopLeftPosition (0, 0);
  52130. contentHolder.addAndMakeVisible (contentComp);
  52131. contentComp->addComponentListener (this);
  52132. }
  52133. updateVisibleArea();
  52134. }
  52135. }
  52136. int Viewport::getMaximumVisibleWidth() const
  52137. {
  52138. return contentHolder.getWidth();
  52139. }
  52140. int Viewport::getMaximumVisibleHeight() const
  52141. {
  52142. return contentHolder.getHeight();
  52143. }
  52144. void Viewport::setViewPosition (const int xPixelsOffset, const int yPixelsOffset)
  52145. {
  52146. if (contentComp != 0)
  52147. contentComp->setTopLeftPosition (jmax (jmin (0, contentHolder.getWidth() - contentComp->getWidth()), jmin (0, -xPixelsOffset)),
  52148. jmax (jmin (0, contentHolder.getHeight() - contentComp->getHeight()), jmin (0, -yPixelsOffset)));
  52149. }
  52150. void Viewport::setViewPosition (const Point<int>& newPosition)
  52151. {
  52152. setViewPosition (newPosition.getX(), newPosition.getY());
  52153. }
  52154. void Viewport::setViewPositionProportionately (const double x, const double y)
  52155. {
  52156. if (contentComp != 0)
  52157. setViewPosition (jmax (0, roundToInt (x * (contentComp->getWidth() - getWidth()))),
  52158. jmax (0, roundToInt (y * (contentComp->getHeight() - getHeight()))));
  52159. }
  52160. bool Viewport::autoScroll (const int mouseX, const int mouseY, const int activeBorderThickness, const int maximumSpeed)
  52161. {
  52162. if (contentComp != 0)
  52163. {
  52164. int dx = 0, dy = 0;
  52165. if (horizontalScrollBar.isVisible() || contentComp->getX() < 0 || contentComp->getRight() > getWidth())
  52166. {
  52167. if (mouseX < activeBorderThickness)
  52168. dx = activeBorderThickness - mouseX;
  52169. else if (mouseX >= contentHolder.getWidth() - activeBorderThickness)
  52170. dx = (contentHolder.getWidth() - activeBorderThickness) - mouseX;
  52171. if (dx < 0)
  52172. dx = jmax (dx, -maximumSpeed, contentHolder.getWidth() - contentComp->getRight());
  52173. else
  52174. dx = jmin (dx, maximumSpeed, -contentComp->getX());
  52175. }
  52176. if (verticalScrollBar.isVisible() || contentComp->getY() < 0 || contentComp->getBottom() > getHeight())
  52177. {
  52178. if (mouseY < activeBorderThickness)
  52179. dy = activeBorderThickness - mouseY;
  52180. else if (mouseY >= contentHolder.getHeight() - activeBorderThickness)
  52181. dy = (contentHolder.getHeight() - activeBorderThickness) - mouseY;
  52182. if (dy < 0)
  52183. dy = jmax (dy, -maximumSpeed, contentHolder.getHeight() - contentComp->getBottom());
  52184. else
  52185. dy = jmin (dy, maximumSpeed, -contentComp->getY());
  52186. }
  52187. if (dx != 0 || dy != 0)
  52188. {
  52189. contentComp->setTopLeftPosition (contentComp->getX() + dx,
  52190. contentComp->getY() + dy);
  52191. return true;
  52192. }
  52193. }
  52194. return false;
  52195. }
  52196. void Viewport::componentMovedOrResized (Component&, bool, bool)
  52197. {
  52198. updateVisibleArea();
  52199. }
  52200. void Viewport::resized()
  52201. {
  52202. updateVisibleArea();
  52203. }
  52204. void Viewport::updateVisibleArea()
  52205. {
  52206. const int scrollbarWidth = getScrollBarThickness();
  52207. const bool canShowAnyBars = getWidth() > scrollbarWidth && getHeight() > scrollbarWidth;
  52208. const bool canShowHBar = showHScrollbar && canShowAnyBars;
  52209. const bool canShowVBar = showVScrollbar && canShowAnyBars;
  52210. bool hBarVisible = canShowHBar && ! horizontalScrollBar.autoHides();
  52211. bool vBarVisible = canShowVBar && ! verticalScrollBar.autoHides();
  52212. Rectangle<int> contentArea (getLocalBounds());
  52213. if (contentComp != 0 && ! contentArea.contains (contentComp->getBounds()))
  52214. {
  52215. hBarVisible = canShowHBar && (hBarVisible || contentComp->getX() < 0 || contentComp->getRight() > contentArea.getWidth());
  52216. vBarVisible = canShowVBar && (vBarVisible || contentComp->getY() < 0 || contentComp->getBottom() > contentArea.getHeight());
  52217. if (vBarVisible)
  52218. contentArea.setWidth (getWidth() - scrollbarWidth);
  52219. if (hBarVisible)
  52220. contentArea.setHeight (getHeight() - scrollbarWidth);
  52221. if (! contentArea.contains (contentComp->getBounds()))
  52222. {
  52223. hBarVisible = canShowHBar && (hBarVisible || contentComp->getRight() > contentArea.getWidth());
  52224. vBarVisible = canShowVBar && (vBarVisible || contentComp->getBottom() > contentArea.getHeight());
  52225. }
  52226. }
  52227. if (vBarVisible)
  52228. contentArea.setWidth (getWidth() - scrollbarWidth);
  52229. if (hBarVisible)
  52230. contentArea.setHeight (getHeight() - scrollbarWidth);
  52231. contentHolder.setBounds (contentArea);
  52232. Rectangle<int> contentBounds;
  52233. if (contentComp != 0)
  52234. contentBounds = contentComp->getBounds();
  52235. const Point<int> visibleOrigin (-contentBounds.getPosition());
  52236. if (hBarVisible)
  52237. {
  52238. horizontalScrollBar.setBounds (0, contentArea.getHeight(), contentArea.getWidth(), scrollbarWidth);
  52239. horizontalScrollBar.setRangeLimits (0.0, contentBounds.getWidth());
  52240. horizontalScrollBar.setCurrentRange (visibleOrigin.getX(), contentArea.getWidth());
  52241. horizontalScrollBar.setSingleStepSize (singleStepX);
  52242. horizontalScrollBar.cancelPendingUpdate();
  52243. }
  52244. if (vBarVisible)
  52245. {
  52246. verticalScrollBar.setBounds (contentArea.getWidth(), 0, scrollbarWidth, contentArea.getHeight());
  52247. verticalScrollBar.setRangeLimits (0.0, contentBounds.getHeight());
  52248. verticalScrollBar.setCurrentRange (visibleOrigin.getY(), contentArea.getHeight());
  52249. verticalScrollBar.setSingleStepSize (singleStepY);
  52250. verticalScrollBar.cancelPendingUpdate();
  52251. }
  52252. // Force the visibility *after* setting the ranges to avoid flicker caused by edge conditions in the numbers.
  52253. horizontalScrollBar.setVisible (hBarVisible);
  52254. verticalScrollBar.setVisible (vBarVisible);
  52255. const Rectangle<int> visibleArea (visibleOrigin.getX(), visibleOrigin.getY(),
  52256. jmin (contentBounds.getWidth() - visibleOrigin.getX(), contentArea.getWidth()),
  52257. jmin (contentBounds.getHeight() - visibleOrigin.getY(), contentArea.getHeight()));
  52258. if (lastVisibleArea != visibleArea)
  52259. {
  52260. lastVisibleArea = visibleArea;
  52261. visibleAreaChanged (visibleArea.getX(), visibleArea.getY(), visibleArea.getWidth(), visibleArea.getHeight());
  52262. }
  52263. horizontalScrollBar.handleUpdateNowIfNeeded();
  52264. verticalScrollBar.handleUpdateNowIfNeeded();
  52265. }
  52266. void Viewport::setSingleStepSizes (const int stepX, const int stepY)
  52267. {
  52268. if (singleStepX != stepX || singleStepY != stepY)
  52269. {
  52270. singleStepX = stepX;
  52271. singleStepY = stepY;
  52272. updateVisibleArea();
  52273. }
  52274. }
  52275. void Viewport::setScrollBarsShown (const bool showVerticalScrollbarIfNeeded,
  52276. const bool showHorizontalScrollbarIfNeeded)
  52277. {
  52278. if (showVScrollbar != showVerticalScrollbarIfNeeded
  52279. || showHScrollbar != showHorizontalScrollbarIfNeeded)
  52280. {
  52281. showVScrollbar = showVerticalScrollbarIfNeeded;
  52282. showHScrollbar = showHorizontalScrollbarIfNeeded;
  52283. updateVisibleArea();
  52284. }
  52285. }
  52286. void Viewport::setScrollBarThickness (const int thickness)
  52287. {
  52288. if (scrollBarThickness != thickness)
  52289. {
  52290. scrollBarThickness = thickness;
  52291. updateVisibleArea();
  52292. }
  52293. }
  52294. int Viewport::getScrollBarThickness() const
  52295. {
  52296. return scrollBarThickness > 0 ? scrollBarThickness
  52297. : getLookAndFeel().getDefaultScrollbarWidth();
  52298. }
  52299. void Viewport::setScrollBarButtonVisibility (const bool buttonsVisible)
  52300. {
  52301. verticalScrollBar.setButtonVisibility (buttonsVisible);
  52302. horizontalScrollBar.setButtonVisibility (buttonsVisible);
  52303. }
  52304. void Viewport::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  52305. {
  52306. const int newRangeStartInt = roundToInt (newRangeStart);
  52307. if (scrollBarThatHasMoved == &horizontalScrollBar)
  52308. {
  52309. setViewPosition (newRangeStartInt, getViewPositionY());
  52310. }
  52311. else if (scrollBarThatHasMoved == &verticalScrollBar)
  52312. {
  52313. setViewPosition (getViewPositionX(), newRangeStartInt);
  52314. }
  52315. }
  52316. void Viewport::mouseWheelMove (const MouseEvent& e, const float wheelIncrementX, const float wheelIncrementY)
  52317. {
  52318. if (! useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  52319. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  52320. }
  52321. bool Viewport::useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  52322. {
  52323. if (! (e.mods.isAltDown() || e.mods.isCtrlDown()))
  52324. {
  52325. const bool hasVertBar = verticalScrollBar.isVisible();
  52326. const bool hasHorzBar = horizontalScrollBar.isVisible();
  52327. if (hasHorzBar || hasVertBar)
  52328. {
  52329. if (wheelIncrementX != 0)
  52330. {
  52331. wheelIncrementX *= 14.0f * singleStepX;
  52332. wheelIncrementX = (wheelIncrementX < 0) ? jmin (wheelIncrementX, -1.0f)
  52333. : jmax (wheelIncrementX, 1.0f);
  52334. }
  52335. if (wheelIncrementY != 0)
  52336. {
  52337. wheelIncrementY *= 14.0f * singleStepY;
  52338. wheelIncrementY = (wheelIncrementY < 0) ? jmin (wheelIncrementY, -1.0f)
  52339. : jmax (wheelIncrementY, 1.0f);
  52340. }
  52341. Point<int> pos (getViewPosition());
  52342. if (wheelIncrementX != 0 && wheelIncrementY != 0 && hasHorzBar && hasVertBar)
  52343. {
  52344. pos.setX (pos.getX() - roundToInt (wheelIncrementX));
  52345. pos.setY (pos.getY() - roundToInt (wheelIncrementY));
  52346. }
  52347. else if (hasHorzBar && (wheelIncrementX != 0 || e.mods.isShiftDown() || ! hasVertBar))
  52348. {
  52349. if (wheelIncrementX == 0 && ! hasVertBar)
  52350. wheelIncrementX = wheelIncrementY;
  52351. pos.setX (pos.getX() - roundToInt (wheelIncrementX));
  52352. }
  52353. else if (hasVertBar && wheelIncrementY != 0)
  52354. {
  52355. pos.setY (pos.getY() - roundToInt (wheelIncrementY));
  52356. }
  52357. if (pos != getViewPosition())
  52358. {
  52359. setViewPosition (pos);
  52360. return true;
  52361. }
  52362. }
  52363. }
  52364. return false;
  52365. }
  52366. bool Viewport::keyPressed (const KeyPress& key)
  52367. {
  52368. const bool isUpDownKey = key.isKeyCode (KeyPress::upKey)
  52369. || key.isKeyCode (KeyPress::downKey)
  52370. || key.isKeyCode (KeyPress::pageUpKey)
  52371. || key.isKeyCode (KeyPress::pageDownKey)
  52372. || key.isKeyCode (KeyPress::homeKey)
  52373. || key.isKeyCode (KeyPress::endKey);
  52374. if (verticalScrollBar.isVisible() && isUpDownKey)
  52375. return verticalScrollBar.keyPressed (key);
  52376. const bool isLeftRightKey = key.isKeyCode (KeyPress::leftKey)
  52377. || key.isKeyCode (KeyPress::rightKey);
  52378. if (horizontalScrollBar.isVisible() && (isUpDownKey || isLeftRightKey))
  52379. return horizontalScrollBar.keyPressed (key);
  52380. return false;
  52381. }
  52382. END_JUCE_NAMESPACE
  52383. /*** End of inlined file: juce_Viewport.cpp ***/
  52384. /*** Start of inlined file: juce_LookAndFeel.cpp ***/
  52385. BEGIN_JUCE_NAMESPACE
  52386. static const Colour createBaseColour (const Colour& buttonColour,
  52387. const bool hasKeyboardFocus,
  52388. const bool isMouseOverButton,
  52389. const bool isButtonDown) throw()
  52390. {
  52391. const float sat = hasKeyboardFocus ? 1.3f : 0.9f;
  52392. const Colour baseColour (buttonColour.withMultipliedSaturation (sat));
  52393. if (isButtonDown)
  52394. return baseColour.contrasting (0.2f);
  52395. else if (isMouseOverButton)
  52396. return baseColour.contrasting (0.1f);
  52397. return baseColour;
  52398. }
  52399. LookAndFeel::LookAndFeel()
  52400. {
  52401. /* if this fails it means you're trying to create a LookAndFeel object before
  52402. the static Colours have been initialised. That ain't gonna work. It probably
  52403. means that you're using a static LookAndFeel object and that your compiler has
  52404. decided to intialise it before the Colours class.
  52405. */
  52406. jassert (Colours::white == Colour (0xffffffff));
  52407. // set up the standard set of colours..
  52408. const int textButtonColour = 0xffbbbbff;
  52409. const int textHighlightColour = 0x401111ee;
  52410. const int standardOutlineColour = 0xb2808080;
  52411. static const int standardColours[] =
  52412. {
  52413. TextButton::buttonColourId, textButtonColour,
  52414. TextButton::buttonOnColourId, 0xff4444ff,
  52415. TextButton::textColourOnId, 0xff000000,
  52416. TextButton::textColourOffId, 0xff000000,
  52417. ComboBox::buttonColourId, 0xffbbbbff,
  52418. ComboBox::outlineColourId, standardOutlineColour,
  52419. ToggleButton::textColourId, 0xff000000,
  52420. TextEditor::backgroundColourId, 0xffffffff,
  52421. TextEditor::textColourId, 0xff000000,
  52422. TextEditor::highlightColourId, textHighlightColour,
  52423. TextEditor::highlightedTextColourId, 0xff000000,
  52424. TextEditor::caretColourId, 0xff000000,
  52425. TextEditor::outlineColourId, 0x00000000,
  52426. TextEditor::focusedOutlineColourId, textButtonColour,
  52427. TextEditor::shadowColourId, 0x38000000,
  52428. Label::backgroundColourId, 0x00000000,
  52429. Label::textColourId, 0xff000000,
  52430. Label::outlineColourId, 0x00000000,
  52431. ScrollBar::backgroundColourId, 0x00000000,
  52432. ScrollBar::thumbColourId, 0xffffffff,
  52433. ScrollBar::trackColourId, 0xffffffff,
  52434. TreeView::linesColourId, 0x4c000000,
  52435. TreeView::backgroundColourId, 0x00000000,
  52436. TreeView::dragAndDropIndicatorColourId, 0x80ff0000,
  52437. PopupMenu::backgroundColourId, 0xffffffff,
  52438. PopupMenu::textColourId, 0xff000000,
  52439. PopupMenu::headerTextColourId, 0xff000000,
  52440. PopupMenu::highlightedTextColourId, 0xffffffff,
  52441. PopupMenu::highlightedBackgroundColourId, 0x991111aa,
  52442. ComboBox::textColourId, 0xff000000,
  52443. ComboBox::backgroundColourId, 0xffffffff,
  52444. ComboBox::arrowColourId, 0x99000000,
  52445. ListBox::backgroundColourId, 0xffffffff,
  52446. ListBox::outlineColourId, standardOutlineColour,
  52447. ListBox::textColourId, 0xff000000,
  52448. Slider::backgroundColourId, 0x00000000,
  52449. Slider::thumbColourId, textButtonColour,
  52450. Slider::trackColourId, 0x7fffffff,
  52451. Slider::rotarySliderFillColourId, 0x7f0000ff,
  52452. Slider::rotarySliderOutlineColourId, 0x66000000,
  52453. Slider::textBoxTextColourId, 0xff000000,
  52454. Slider::textBoxBackgroundColourId, 0xffffffff,
  52455. Slider::textBoxHighlightColourId, textHighlightColour,
  52456. Slider::textBoxOutlineColourId, standardOutlineColour,
  52457. ResizableWindow::backgroundColourId, 0xff777777,
  52458. //DocumentWindow::textColourId, 0xff000000, // (this is deliberately not set)
  52459. AlertWindow::backgroundColourId, 0xffededed,
  52460. AlertWindow::textColourId, 0xff000000,
  52461. AlertWindow::outlineColourId, 0xff666666,
  52462. ProgressBar::backgroundColourId, 0xffeeeeee,
  52463. ProgressBar::foregroundColourId, 0xffaaaaee,
  52464. TooltipWindow::backgroundColourId, 0xffeeeebb,
  52465. TooltipWindow::textColourId, 0xff000000,
  52466. TooltipWindow::outlineColourId, 0x4c000000,
  52467. TabbedComponent::backgroundColourId, 0x00000000,
  52468. TabbedComponent::outlineColourId, 0xff777777,
  52469. TabbedButtonBar::tabOutlineColourId, 0x80000000,
  52470. TabbedButtonBar::frontOutlineColourId, 0x90000000,
  52471. Toolbar::backgroundColourId, 0xfff6f8f9,
  52472. Toolbar::separatorColourId, 0x4c000000,
  52473. Toolbar::buttonMouseOverBackgroundColourId, 0x4c0000ff,
  52474. Toolbar::buttonMouseDownBackgroundColourId, 0x800000ff,
  52475. Toolbar::labelTextColourId, 0xff000000,
  52476. Toolbar::editingModeOutlineColourId, 0xffff0000,
  52477. HyperlinkButton::textColourId, 0xcc1111ee,
  52478. GroupComponent::outlineColourId, 0x66000000,
  52479. GroupComponent::textColourId, 0xff000000,
  52480. DirectoryContentsDisplayComponent::highlightColourId, textHighlightColour,
  52481. DirectoryContentsDisplayComponent::textColourId, 0xff000000,
  52482. 0x1000440, /*LassoComponent::lassoFillColourId*/ 0x66dddddd,
  52483. 0x1000441, /*LassoComponent::lassoOutlineColourId*/ 0x99111111,
  52484. MidiKeyboardComponent::whiteNoteColourId, 0xffffffff,
  52485. MidiKeyboardComponent::blackNoteColourId, 0xff000000,
  52486. MidiKeyboardComponent::keySeparatorLineColourId, 0x66000000,
  52487. MidiKeyboardComponent::mouseOverKeyOverlayColourId, 0x80ffff00,
  52488. MidiKeyboardComponent::keyDownOverlayColourId, 0xffb6b600,
  52489. MidiKeyboardComponent::textLabelColourId, 0xff000000,
  52490. MidiKeyboardComponent::upDownButtonBackgroundColourId, 0xffd3d3d3,
  52491. MidiKeyboardComponent::upDownButtonArrowColourId, 0xff000000,
  52492. CodeEditorComponent::backgroundColourId, 0xffffffff,
  52493. CodeEditorComponent::caretColourId, 0xff000000,
  52494. CodeEditorComponent::highlightColourId, textHighlightColour,
  52495. CodeEditorComponent::defaultTextColourId, 0xff000000,
  52496. ColourSelector::backgroundColourId, 0xffe5e5e5,
  52497. ColourSelector::labelTextColourId, 0xff000000,
  52498. KeyMappingEditorComponent::backgroundColourId, 0x00000000,
  52499. KeyMappingEditorComponent::textColourId, 0xff000000,
  52500. FileSearchPathListComponent::backgroundColourId, 0xffffffff,
  52501. FileChooserDialogBox::titleTextColourId, 0xff000000,
  52502. DrawableButton::textColourId, 0xff000000,
  52503. };
  52504. for (int i = 0; i < numElementsInArray (standardColours); i += 2)
  52505. setColour (standardColours [i], Colour (standardColours [i + 1]));
  52506. static String defaultSansName, defaultSerifName, defaultFixedName;
  52507. if (defaultSansName.isEmpty())
  52508. Font::getPlatformDefaultFontNames (defaultSansName, defaultSerifName, defaultFixedName);
  52509. defaultSans = defaultSansName;
  52510. defaultSerif = defaultSerifName;
  52511. defaultFixed = defaultFixedName;
  52512. }
  52513. LookAndFeel::~LookAndFeel()
  52514. {
  52515. }
  52516. const Colour LookAndFeel::findColour (const int colourId) const throw()
  52517. {
  52518. const int index = colourIds.indexOf (colourId);
  52519. if (index >= 0)
  52520. return colours [index];
  52521. jassertfalse;
  52522. return Colours::black;
  52523. }
  52524. void LookAndFeel::setColour (const int colourId, const Colour& colour) throw()
  52525. {
  52526. const int index = colourIds.indexOf (colourId);
  52527. if (index >= 0)
  52528. {
  52529. colours.set (index, colour);
  52530. }
  52531. else
  52532. {
  52533. colourIds.add (colourId);
  52534. colours.add (colour);
  52535. }
  52536. }
  52537. bool LookAndFeel::isColourSpecified (const int colourId) const throw()
  52538. {
  52539. return colourIds.contains (colourId);
  52540. }
  52541. static LookAndFeel* defaultLF = 0;
  52542. static LookAndFeel* currentDefaultLF = 0;
  52543. LookAndFeel& LookAndFeel::getDefaultLookAndFeel() throw()
  52544. {
  52545. // if this happens, your app hasn't initialised itself properly.. if you're
  52546. // trying to hack your own main() function, have a look at
  52547. // JUCEApplication::initialiseForGUI()
  52548. jassert (currentDefaultLF != 0);
  52549. return *currentDefaultLF;
  52550. }
  52551. void LookAndFeel::setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw()
  52552. {
  52553. if (newDefaultLookAndFeel == 0)
  52554. {
  52555. if (defaultLF == 0)
  52556. defaultLF = new LookAndFeel();
  52557. newDefaultLookAndFeel = defaultLF;
  52558. }
  52559. currentDefaultLF = newDefaultLookAndFeel;
  52560. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  52561. {
  52562. Component* const c = Desktop::getInstance().getComponent (i);
  52563. if (c != 0)
  52564. c->sendLookAndFeelChange();
  52565. }
  52566. }
  52567. void LookAndFeel::clearDefaultLookAndFeel() throw()
  52568. {
  52569. if (currentDefaultLF == defaultLF)
  52570. currentDefaultLF = 0;
  52571. deleteAndZero (defaultLF);
  52572. }
  52573. const Typeface::Ptr LookAndFeel::getTypefaceForFont (const Font& font)
  52574. {
  52575. String faceName (font.getTypefaceName());
  52576. if (faceName == Font::getDefaultSansSerifFontName())
  52577. faceName = defaultSans;
  52578. else if (faceName == Font::getDefaultSerifFontName())
  52579. faceName = defaultSerif;
  52580. else if (faceName == Font::getDefaultMonospacedFontName())
  52581. faceName = defaultFixed;
  52582. Font f (font);
  52583. f.setTypefaceName (faceName);
  52584. return Typeface::createSystemTypefaceFor (f);
  52585. }
  52586. void LookAndFeel::setDefaultSansSerifTypefaceName (const String& newName)
  52587. {
  52588. defaultSans = newName;
  52589. }
  52590. const MouseCursor LookAndFeel::getMouseCursorFor (Component& component)
  52591. {
  52592. return component.getMouseCursor();
  52593. }
  52594. void LookAndFeel::drawButtonBackground (Graphics& g,
  52595. Button& button,
  52596. const Colour& backgroundColour,
  52597. bool isMouseOverButton,
  52598. bool isButtonDown)
  52599. {
  52600. const int width = button.getWidth();
  52601. const int height = button.getHeight();
  52602. const float outlineThickness = button.isEnabled() ? ((isButtonDown || isMouseOverButton) ? 1.2f : 0.7f) : 0.4f;
  52603. const float halfThickness = outlineThickness * 0.5f;
  52604. const float indentL = button.isConnectedOnLeft() ? 0.1f : halfThickness;
  52605. const float indentR = button.isConnectedOnRight() ? 0.1f : halfThickness;
  52606. const float indentT = button.isConnectedOnTop() ? 0.1f : halfThickness;
  52607. const float indentB = button.isConnectedOnBottom() ? 0.1f : halfThickness;
  52608. const Colour baseColour (createBaseColour (backgroundColour,
  52609. button.hasKeyboardFocus (true),
  52610. isMouseOverButton, isButtonDown)
  52611. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  52612. drawGlassLozenge (g,
  52613. indentL,
  52614. indentT,
  52615. width - indentL - indentR,
  52616. height - indentT - indentB,
  52617. baseColour, outlineThickness, -1.0f,
  52618. button.isConnectedOnLeft(),
  52619. button.isConnectedOnRight(),
  52620. button.isConnectedOnTop(),
  52621. button.isConnectedOnBottom());
  52622. }
  52623. const Font LookAndFeel::getFontForTextButton (TextButton& button)
  52624. {
  52625. return button.getFont();
  52626. }
  52627. void LookAndFeel::drawButtonText (Graphics& g, TextButton& button,
  52628. bool /*isMouseOverButton*/, bool /*isButtonDown*/)
  52629. {
  52630. Font font (getFontForTextButton (button));
  52631. g.setFont (font);
  52632. g.setColour (button.findColour (button.getToggleState() ? TextButton::textColourOnId
  52633. : TextButton::textColourOffId)
  52634. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  52635. const int yIndent = jmin (4, button.proportionOfHeight (0.3f));
  52636. const int cornerSize = jmin (button.getHeight(), button.getWidth()) / 2;
  52637. const int fontHeight = roundToInt (font.getHeight() * 0.6f);
  52638. const int leftIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnLeft() ? 4 : 2));
  52639. const int rightIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnRight() ? 4 : 2));
  52640. g.drawFittedText (button.getButtonText(),
  52641. leftIndent,
  52642. yIndent,
  52643. button.getWidth() - leftIndent - rightIndent,
  52644. button.getHeight() - yIndent * 2,
  52645. Justification::centred, 2);
  52646. }
  52647. void LookAndFeel::drawTickBox (Graphics& g,
  52648. Component& component,
  52649. float x, float y, float w, float h,
  52650. const bool ticked,
  52651. const bool isEnabled,
  52652. const bool isMouseOverButton,
  52653. const bool isButtonDown)
  52654. {
  52655. const float boxSize = w * 0.7f;
  52656. drawGlassSphere (g, x, y + (h - boxSize) * 0.5f, boxSize,
  52657. createBaseColour (component.findColour (TextButton::buttonColourId)
  52658. .withMultipliedAlpha (isEnabled ? 1.0f : 0.5f),
  52659. true,
  52660. isMouseOverButton,
  52661. isButtonDown),
  52662. isEnabled ? ((isButtonDown || isMouseOverButton) ? 1.1f : 0.5f) : 0.3f);
  52663. if (ticked)
  52664. {
  52665. Path tick;
  52666. tick.startNewSubPath (1.5f, 3.0f);
  52667. tick.lineTo (3.0f, 6.0f);
  52668. tick.lineTo (6.0f, 0.0f);
  52669. g.setColour (isEnabled ? Colours::black : Colours::grey);
  52670. const AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f)
  52671. .translated (x, y));
  52672. g.strokePath (tick, PathStrokeType (2.5f), trans);
  52673. }
  52674. }
  52675. void LookAndFeel::drawToggleButton (Graphics& g,
  52676. ToggleButton& button,
  52677. bool isMouseOverButton,
  52678. bool isButtonDown)
  52679. {
  52680. if (button.hasKeyboardFocus (true))
  52681. {
  52682. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  52683. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  52684. }
  52685. float fontSize = jmin (15.0f, button.getHeight() * 0.75f);
  52686. const float tickWidth = fontSize * 1.1f;
  52687. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  52688. tickWidth, tickWidth,
  52689. button.getToggleState(),
  52690. button.isEnabled(),
  52691. isMouseOverButton,
  52692. isButtonDown);
  52693. g.setColour (button.findColour (ToggleButton::textColourId));
  52694. g.setFont (fontSize);
  52695. if (! button.isEnabled())
  52696. g.setOpacity (0.5f);
  52697. const int textX = (int) tickWidth + 5;
  52698. g.drawFittedText (button.getButtonText(),
  52699. textX, 0,
  52700. button.getWidth() - textX - 2, button.getHeight(),
  52701. Justification::centredLeft, 10);
  52702. }
  52703. void LookAndFeel::changeToggleButtonWidthToFitText (ToggleButton& button)
  52704. {
  52705. Font font (jmin (15.0f, button.getHeight() * 0.6f));
  52706. const int tickWidth = jmin (24, button.getHeight());
  52707. button.setSize (font.getStringWidth (button.getButtonText()) + tickWidth + 8,
  52708. button.getHeight());
  52709. }
  52710. AlertWindow* LookAndFeel::createAlertWindow (const String& title,
  52711. const String& message,
  52712. const String& button1,
  52713. const String& button2,
  52714. const String& button3,
  52715. AlertWindow::AlertIconType iconType,
  52716. int numButtons,
  52717. Component* associatedComponent)
  52718. {
  52719. AlertWindow* aw = new AlertWindow (title, message, iconType, associatedComponent);
  52720. if (numButtons == 1)
  52721. {
  52722. aw->addButton (button1, 0,
  52723. KeyPress (KeyPress::escapeKey, 0, 0),
  52724. KeyPress (KeyPress::returnKey, 0, 0));
  52725. }
  52726. else
  52727. {
  52728. const KeyPress button1ShortCut (CharacterFunctions::toLowerCase (button1[0]), 0, 0);
  52729. KeyPress button2ShortCut (CharacterFunctions::toLowerCase (button2[0]), 0, 0);
  52730. if (button1ShortCut == button2ShortCut)
  52731. button2ShortCut = KeyPress();
  52732. if (numButtons == 2)
  52733. {
  52734. aw->addButton (button1, 1, KeyPress (KeyPress::returnKey, 0, 0), button1ShortCut);
  52735. aw->addButton (button2, 0, KeyPress (KeyPress::escapeKey, 0, 0), button2ShortCut);
  52736. }
  52737. else if (numButtons == 3)
  52738. {
  52739. aw->addButton (button1, 1, button1ShortCut);
  52740. aw->addButton (button2, 2, button2ShortCut);
  52741. aw->addButton (button3, 0, KeyPress (KeyPress::escapeKey, 0, 0));
  52742. }
  52743. }
  52744. return aw;
  52745. }
  52746. void LookAndFeel::drawAlertBox (Graphics& g,
  52747. AlertWindow& alert,
  52748. const Rectangle<int>& textArea,
  52749. TextLayout& textLayout)
  52750. {
  52751. g.fillAll (alert.findColour (AlertWindow::backgroundColourId));
  52752. int iconSpaceUsed = 0;
  52753. Justification alignment (Justification::horizontallyCentred);
  52754. const int iconWidth = 80;
  52755. int iconSize = jmin (iconWidth + 50, alert.getHeight() + 20);
  52756. if (alert.containsAnyExtraComponents() || alert.getNumButtons() > 2)
  52757. iconSize = jmin (iconSize, textArea.getHeight() + 50);
  52758. const Rectangle<int> iconRect (iconSize / -10, iconSize / -10,
  52759. iconSize, iconSize);
  52760. if (alert.getAlertType() != AlertWindow::NoIcon)
  52761. {
  52762. Path icon;
  52763. uint32 colour;
  52764. char character;
  52765. if (alert.getAlertType() == AlertWindow::WarningIcon)
  52766. {
  52767. colour = 0x55ff5555;
  52768. character = '!';
  52769. icon.addTriangle (iconRect.getX() + iconRect.getWidth() * 0.5f, (float) iconRect.getY(),
  52770. (float) iconRect.getRight(), (float) iconRect.getBottom(),
  52771. (float) iconRect.getX(), (float) iconRect.getBottom());
  52772. icon = icon.createPathWithRoundedCorners (5.0f);
  52773. }
  52774. else
  52775. {
  52776. colour = alert.getAlertType() == AlertWindow::InfoIcon ? 0x605555ff : 0x40b69900;
  52777. character = alert.getAlertType() == AlertWindow::InfoIcon ? 'i' : '?';
  52778. icon.addEllipse ((float) iconRect.getX(), (float) iconRect.getY(),
  52779. (float) iconRect.getWidth(), (float) iconRect.getHeight());
  52780. }
  52781. GlyphArrangement ga;
  52782. ga.addFittedText (Font (iconRect.getHeight() * 0.9f, Font::bold),
  52783. String::charToString (character),
  52784. (float) iconRect.getX(), (float) iconRect.getY(),
  52785. (float) iconRect.getWidth(), (float) iconRect.getHeight(),
  52786. Justification::centred, false);
  52787. ga.createPath (icon);
  52788. icon.setUsingNonZeroWinding (false);
  52789. g.setColour (Colour (colour));
  52790. g.fillPath (icon);
  52791. iconSpaceUsed = iconWidth;
  52792. alignment = Justification::left;
  52793. }
  52794. g.setColour (alert.findColour (AlertWindow::textColourId));
  52795. textLayout.drawWithin (g,
  52796. textArea.getX() + iconSpaceUsed, textArea.getY(),
  52797. textArea.getWidth() - iconSpaceUsed, textArea.getHeight(),
  52798. alignment.getFlags() | Justification::top);
  52799. g.setColour (alert.findColour (AlertWindow::outlineColourId));
  52800. g.drawRect (0, 0, alert.getWidth(), alert.getHeight());
  52801. }
  52802. int LookAndFeel::getAlertBoxWindowFlags()
  52803. {
  52804. return ComponentPeer::windowAppearsOnTaskbar
  52805. | ComponentPeer::windowHasDropShadow;
  52806. }
  52807. int LookAndFeel::getAlertWindowButtonHeight()
  52808. {
  52809. return 28;
  52810. }
  52811. const Font LookAndFeel::getAlertWindowFont()
  52812. {
  52813. return Font (12.0f);
  52814. }
  52815. void LookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  52816. int width, int height,
  52817. double progress, const String& textToShow)
  52818. {
  52819. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  52820. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  52821. g.fillAll (background);
  52822. if (progress >= 0.0f && progress < 1.0f)
  52823. {
  52824. drawGlassLozenge (g, 1.0f, 1.0f,
  52825. (float) jlimit (0.0, width - 2.0, progress * (width - 2.0)),
  52826. (float) (height - 2),
  52827. foreground,
  52828. 0.5f, 0.0f,
  52829. true, true, true, true);
  52830. }
  52831. else
  52832. {
  52833. // spinning bar..
  52834. g.setColour (foreground);
  52835. const int stripeWidth = height * 2;
  52836. const int position = (Time::getMillisecondCounter() / 15) % stripeWidth;
  52837. Path p;
  52838. for (float x = (float) (- position); x < width + stripeWidth; x += stripeWidth)
  52839. p.addQuadrilateral (x, 0.0f,
  52840. x + stripeWidth * 0.5f, 0.0f,
  52841. x, (float) height,
  52842. x - stripeWidth * 0.5f, (float) height);
  52843. Image im (Image::ARGB, width, height, true);
  52844. {
  52845. Graphics g2 (im);
  52846. drawGlassLozenge (g2, 1.0f, 1.0f,
  52847. (float) (width - 2),
  52848. (float) (height - 2),
  52849. foreground,
  52850. 0.5f, 0.0f,
  52851. true, true, true, true);
  52852. }
  52853. g.setTiledImageFill (im, 0, 0, 0.85f);
  52854. g.fillPath (p);
  52855. }
  52856. if (textToShow.isNotEmpty())
  52857. {
  52858. g.setColour (Colour::contrasting (background, foreground));
  52859. g.setFont (height * 0.6f);
  52860. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  52861. }
  52862. }
  52863. void LookAndFeel::drawSpinningWaitAnimation (Graphics& g, const Colour& colour, int x, int y, int w, int h)
  52864. {
  52865. const float radius = jmin (w, h) * 0.4f;
  52866. const float thickness = radius * 0.15f;
  52867. Path p;
  52868. p.addRoundedRectangle (radius * 0.4f, thickness * -0.5f,
  52869. radius * 0.6f, thickness,
  52870. thickness * 0.5f);
  52871. const float cx = x + w * 0.5f;
  52872. const float cy = y + h * 0.5f;
  52873. const uint32 animationIndex = (Time::getMillisecondCounter() / (1000 / 10)) % 12;
  52874. for (int i = 0; i < 12; ++i)
  52875. {
  52876. const int n = (i + 12 - animationIndex) % 12;
  52877. g.setColour (colour.withMultipliedAlpha ((n + 1) / 12.0f));
  52878. g.fillPath (p, AffineTransform::rotation (i * (float_Pi / 6.0f))
  52879. .translated (cx, cy));
  52880. }
  52881. }
  52882. void LookAndFeel::drawScrollbarButton (Graphics& g,
  52883. ScrollBar& scrollbar,
  52884. int width, int height,
  52885. int buttonDirection,
  52886. bool /*isScrollbarVertical*/,
  52887. bool /*isMouseOverButton*/,
  52888. bool isButtonDown)
  52889. {
  52890. Path p;
  52891. if (buttonDirection == 0)
  52892. p.addTriangle (width * 0.5f, height * 0.2f,
  52893. width * 0.1f, height * 0.7f,
  52894. width * 0.9f, height * 0.7f);
  52895. else if (buttonDirection == 1)
  52896. p.addTriangle (width * 0.8f, height * 0.5f,
  52897. width * 0.3f, height * 0.1f,
  52898. width * 0.3f, height * 0.9f);
  52899. else if (buttonDirection == 2)
  52900. p.addTriangle (width * 0.5f, height * 0.8f,
  52901. width * 0.1f, height * 0.3f,
  52902. width * 0.9f, height * 0.3f);
  52903. else if (buttonDirection == 3)
  52904. p.addTriangle (width * 0.2f, height * 0.5f,
  52905. width * 0.7f, height * 0.1f,
  52906. width * 0.7f, height * 0.9f);
  52907. if (isButtonDown)
  52908. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId).contrasting (0.2f));
  52909. else
  52910. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId));
  52911. g.fillPath (p);
  52912. g.setColour (Colour (0x80000000));
  52913. g.strokePath (p, PathStrokeType (0.5f));
  52914. }
  52915. void LookAndFeel::drawScrollbar (Graphics& g,
  52916. ScrollBar& scrollbar,
  52917. int x, int y,
  52918. int width, int height,
  52919. bool isScrollbarVertical,
  52920. int thumbStartPosition,
  52921. int thumbSize,
  52922. bool /*isMouseOver*/,
  52923. bool /*isMouseDown*/)
  52924. {
  52925. g.fillAll (scrollbar.findColour (ScrollBar::backgroundColourId));
  52926. Path slotPath, thumbPath;
  52927. const float slotIndent = jmin (width, height) > 15 ? 1.0f : 0.0f;
  52928. const float slotIndentx2 = slotIndent * 2.0f;
  52929. const float thumbIndent = slotIndent + 1.0f;
  52930. const float thumbIndentx2 = thumbIndent * 2.0f;
  52931. float gx1 = 0.0f, gy1 = 0.0f, gx2 = 0.0f, gy2 = 0.0f;
  52932. if (isScrollbarVertical)
  52933. {
  52934. slotPath.addRoundedRectangle (x + slotIndent,
  52935. y + slotIndent,
  52936. width - slotIndentx2,
  52937. height - slotIndentx2,
  52938. (width - slotIndentx2) * 0.5f);
  52939. if (thumbSize > 0)
  52940. thumbPath.addRoundedRectangle (x + thumbIndent,
  52941. thumbStartPosition + thumbIndent,
  52942. width - thumbIndentx2,
  52943. thumbSize - thumbIndentx2,
  52944. (width - thumbIndentx2) * 0.5f);
  52945. gx1 = (float) x;
  52946. gx2 = x + width * 0.7f;
  52947. }
  52948. else
  52949. {
  52950. slotPath.addRoundedRectangle (x + slotIndent,
  52951. y + slotIndent,
  52952. width - slotIndentx2,
  52953. height - slotIndentx2,
  52954. (height - slotIndentx2) * 0.5f);
  52955. if (thumbSize > 0)
  52956. thumbPath.addRoundedRectangle (thumbStartPosition + thumbIndent,
  52957. y + thumbIndent,
  52958. thumbSize - thumbIndentx2,
  52959. height - thumbIndentx2,
  52960. (height - thumbIndentx2) * 0.5f);
  52961. gy1 = (float) y;
  52962. gy2 = y + height * 0.7f;
  52963. }
  52964. const Colour thumbColour (scrollbar.findColour (ScrollBar::thumbColourId));
  52965. g.setGradientFill (ColourGradient (thumbColour.overlaidWith (Colour (0x44000000)), gx1, gy1,
  52966. thumbColour.overlaidWith (Colour (0x19000000)), gx2, gy2, false));
  52967. g.fillPath (slotPath);
  52968. if (isScrollbarVertical)
  52969. {
  52970. gx1 = x + width * 0.6f;
  52971. gx2 = (float) x + width;
  52972. }
  52973. else
  52974. {
  52975. gy1 = y + height * 0.6f;
  52976. gy2 = (float) y + height;
  52977. }
  52978. g.setGradientFill (ColourGradient (Colours::transparentBlack,gx1, gy1,
  52979. Colour (0x19000000), gx2, gy2, false));
  52980. g.fillPath (slotPath);
  52981. g.setColour (thumbColour);
  52982. g.fillPath (thumbPath);
  52983. g.setGradientFill (ColourGradient (Colour (0x10000000), gx1, gy1,
  52984. Colours::transparentBlack, gx2, gy2, false));
  52985. g.saveState();
  52986. if (isScrollbarVertical)
  52987. g.reduceClipRegion (x + width / 2, y, width, height);
  52988. else
  52989. g.reduceClipRegion (x, y + height / 2, width, height);
  52990. g.fillPath (thumbPath);
  52991. g.restoreState();
  52992. g.setColour (Colour (0x4c000000));
  52993. g.strokePath (thumbPath, PathStrokeType (0.4f));
  52994. }
  52995. ImageEffectFilter* LookAndFeel::getScrollbarEffect()
  52996. {
  52997. return 0;
  52998. }
  52999. int LookAndFeel::getMinimumScrollbarThumbSize (ScrollBar& scrollbar)
  53000. {
  53001. return jmin (scrollbar.getWidth(), scrollbar.getHeight()) * 2;
  53002. }
  53003. int LookAndFeel::getDefaultScrollbarWidth()
  53004. {
  53005. return 18;
  53006. }
  53007. int LookAndFeel::getScrollbarButtonSize (ScrollBar& scrollbar)
  53008. {
  53009. return 2 + (scrollbar.isVertical() ? scrollbar.getWidth()
  53010. : scrollbar.getHeight());
  53011. }
  53012. const Path LookAndFeel::getTickShape (const float height)
  53013. {
  53014. static const unsigned char tickShapeData[] =
  53015. {
  53016. 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,
  53017. 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,
  53018. 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,
  53019. 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,
  53020. 96,140,68,0,128,188,67,0,224,168,68,0,0,119,67,99,101
  53021. };
  53022. Path p;
  53023. p.loadPathFromData (tickShapeData, sizeof (tickShapeData));
  53024. p.scaleToFit (0, 0, height * 2.0f, height, true);
  53025. return p;
  53026. }
  53027. const Path LookAndFeel::getCrossShape (const float height)
  53028. {
  53029. static const unsigned char crossShapeData[] =
  53030. {
  53031. 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,
  53032. 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,
  53033. 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,
  53034. 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,
  53035. 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,
  53036. 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,
  53037. 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
  53038. };
  53039. Path p;
  53040. p.loadPathFromData (crossShapeData, sizeof (crossShapeData));
  53041. p.scaleToFit (0, 0, height * 2.0f, height, true);
  53042. return p;
  53043. }
  53044. void LookAndFeel::drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool /*isMouseOver*/)
  53045. {
  53046. const int boxSize = ((jmin (16, w, h) << 1) / 3) | 1;
  53047. x += (w - boxSize) >> 1;
  53048. y += (h - boxSize) >> 1;
  53049. w = boxSize;
  53050. h = boxSize;
  53051. g.setColour (Colour (0xe5ffffff));
  53052. g.fillRect (x, y, w, h);
  53053. g.setColour (Colour (0x80000000));
  53054. g.drawRect (x, y, w, h);
  53055. const float size = boxSize / 2 + 1.0f;
  53056. const float centre = (float) (boxSize / 2);
  53057. g.fillRect (x + (w - size) * 0.5f, y + centre, size, 1.0f);
  53058. if (isPlus)
  53059. g.fillRect (x + centre, y + (h - size) * 0.5f, 1.0f, size);
  53060. }
  53061. void LookAndFeel::drawBubble (Graphics& g,
  53062. float tipX, float tipY,
  53063. float boxX, float boxY,
  53064. float boxW, float boxH)
  53065. {
  53066. int side = 0;
  53067. if (tipX < boxX)
  53068. side = 1;
  53069. else if (tipX > boxX + boxW)
  53070. side = 3;
  53071. else if (tipY > boxY + boxH)
  53072. side = 2;
  53073. const float indent = 2.0f;
  53074. Path p;
  53075. p.addBubble (boxX + indent,
  53076. boxY + indent,
  53077. boxW - indent * 2.0f,
  53078. boxH - indent * 2.0f,
  53079. 5.0f,
  53080. tipX, tipY,
  53081. side,
  53082. 0.5f,
  53083. jmin (15.0f, boxW * 0.3f, boxH * 0.3f));
  53084. //xxx need to take comp as param for colour
  53085. g.setColour (findColour (TooltipWindow::backgroundColourId).withAlpha (0.9f));
  53086. g.fillPath (p);
  53087. //xxx as above
  53088. g.setColour (findColour (TooltipWindow::textColourId).withAlpha (0.4f));
  53089. g.strokePath (p, PathStrokeType (1.33f));
  53090. }
  53091. const Font LookAndFeel::getPopupMenuFont()
  53092. {
  53093. return Font (17.0f);
  53094. }
  53095. void LookAndFeel::getIdealPopupMenuItemSize (const String& text,
  53096. const bool isSeparator,
  53097. int standardMenuItemHeight,
  53098. int& idealWidth,
  53099. int& idealHeight)
  53100. {
  53101. if (isSeparator)
  53102. {
  53103. idealWidth = 50;
  53104. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight / 2 : 10;
  53105. }
  53106. else
  53107. {
  53108. Font font (getPopupMenuFont());
  53109. if (standardMenuItemHeight > 0 && font.getHeight() > standardMenuItemHeight / 1.3f)
  53110. font.setHeight (standardMenuItemHeight / 1.3f);
  53111. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight : roundToInt (font.getHeight() * 1.3f);
  53112. idealWidth = font.getStringWidth (text) + idealHeight * 2;
  53113. }
  53114. }
  53115. void LookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  53116. {
  53117. const Colour background (findColour (PopupMenu::backgroundColourId));
  53118. g.fillAll (background);
  53119. g.setColour (background.overlaidWith (Colour (0x2badd8e6)));
  53120. for (int i = 0; i < height; i += 3)
  53121. g.fillRect (0, i, width, 1);
  53122. #if ! JUCE_MAC
  53123. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.6f));
  53124. g.drawRect (0, 0, width, height);
  53125. #endif
  53126. }
  53127. void LookAndFeel::drawPopupMenuUpDownArrow (Graphics& g,
  53128. int width, int height,
  53129. bool isScrollUpArrow)
  53130. {
  53131. const Colour background (findColour (PopupMenu::backgroundColourId));
  53132. g.setGradientFill (ColourGradient (background, 0.0f, height * 0.5f,
  53133. background.withAlpha (0.0f),
  53134. 0.0f, isScrollUpArrow ? ((float) height) : 0.0f,
  53135. false));
  53136. g.fillRect (1, 1, width - 2, height - 2);
  53137. const float hw = width * 0.5f;
  53138. const float arrowW = height * 0.3f;
  53139. const float y1 = height * (isScrollUpArrow ? 0.6f : 0.3f);
  53140. const float y2 = height * (isScrollUpArrow ? 0.3f : 0.6f);
  53141. Path p;
  53142. p.addTriangle (hw - arrowW, y1,
  53143. hw + arrowW, y1,
  53144. hw, y2);
  53145. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.5f));
  53146. g.fillPath (p);
  53147. }
  53148. void LookAndFeel::drawPopupMenuItem (Graphics& g,
  53149. int width, int height,
  53150. const bool isSeparator,
  53151. const bool isActive,
  53152. const bool isHighlighted,
  53153. const bool isTicked,
  53154. const bool hasSubMenu,
  53155. const String& text,
  53156. const String& shortcutKeyText,
  53157. Image* image,
  53158. const Colour* const textColourToUse)
  53159. {
  53160. const float halfH = height * 0.5f;
  53161. if (isSeparator)
  53162. {
  53163. const float separatorIndent = 5.5f;
  53164. g.setColour (Colour (0x33000000));
  53165. g.drawLine (separatorIndent, halfH, width - separatorIndent, halfH);
  53166. g.setColour (Colour (0x66ffffff));
  53167. g.drawLine (separatorIndent, halfH + 1.0f, width - separatorIndent, halfH + 1.0f);
  53168. }
  53169. else
  53170. {
  53171. Colour textColour (findColour (PopupMenu::textColourId));
  53172. if (textColourToUse != 0)
  53173. textColour = *textColourToUse;
  53174. if (isHighlighted)
  53175. {
  53176. g.setColour (findColour (PopupMenu::highlightedBackgroundColourId));
  53177. g.fillRect (1, 1, width - 2, height - 2);
  53178. g.setColour (findColour (PopupMenu::highlightedTextColourId));
  53179. }
  53180. else
  53181. {
  53182. g.setColour (textColour);
  53183. }
  53184. if (! isActive)
  53185. g.setOpacity (0.3f);
  53186. Font font (getPopupMenuFont());
  53187. if (font.getHeight() > height / 1.3f)
  53188. font.setHeight (height / 1.3f);
  53189. g.setFont (font);
  53190. const int leftBorder = (height * 5) / 4;
  53191. const int rightBorder = 4;
  53192. if (image != 0)
  53193. {
  53194. g.drawImageWithin (*image,
  53195. 2, 1, leftBorder - 4, height - 2,
  53196. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, false);
  53197. }
  53198. else if (isTicked)
  53199. {
  53200. const Path tick (getTickShape (1.0f));
  53201. const float th = font.getAscent();
  53202. const float ty = halfH - th * 0.5f;
  53203. g.fillPath (tick, tick.getTransformToScaleToFit (2.0f, ty, (float) (leftBorder - 4),
  53204. th, true));
  53205. }
  53206. g.drawFittedText (text,
  53207. leftBorder, 0,
  53208. width - (leftBorder + rightBorder), height,
  53209. Justification::centredLeft, 1);
  53210. if (shortcutKeyText.isNotEmpty())
  53211. {
  53212. Font f2 (font);
  53213. f2.setHeight (f2.getHeight() * 0.75f);
  53214. f2.setHorizontalScale (0.95f);
  53215. g.setFont (f2);
  53216. g.drawText (shortcutKeyText,
  53217. leftBorder,
  53218. 0,
  53219. width - (leftBorder + rightBorder + 4),
  53220. height,
  53221. Justification::centredRight,
  53222. true);
  53223. }
  53224. if (hasSubMenu)
  53225. {
  53226. const float arrowH = 0.6f * getPopupMenuFont().getAscent();
  53227. const float x = width - height * 0.6f;
  53228. Path p;
  53229. p.addTriangle (x, halfH - arrowH * 0.5f,
  53230. x, halfH + arrowH * 0.5f,
  53231. x + arrowH * 0.6f, halfH);
  53232. g.fillPath (p);
  53233. }
  53234. }
  53235. }
  53236. int LookAndFeel::getMenuWindowFlags()
  53237. {
  53238. return ComponentPeer::windowHasDropShadow;
  53239. }
  53240. void LookAndFeel::drawMenuBarBackground (Graphics& g, int width, int height,
  53241. bool, MenuBarComponent& menuBar)
  53242. {
  53243. const Colour baseColour (createBaseColour (menuBar.findColour (PopupMenu::backgroundColourId), false, false, false));
  53244. if (menuBar.isEnabled())
  53245. {
  53246. drawShinyButtonShape (g,
  53247. -4.0f, 0.0f,
  53248. width + 8.0f, (float) height,
  53249. 0.0f,
  53250. baseColour,
  53251. 0.4f,
  53252. true, true, true, true);
  53253. }
  53254. else
  53255. {
  53256. g.fillAll (baseColour);
  53257. }
  53258. }
  53259. const Font LookAndFeel::getMenuBarFont (MenuBarComponent& menuBar, int /*itemIndex*/, const String& /*itemText*/)
  53260. {
  53261. return Font (menuBar.getHeight() * 0.7f);
  53262. }
  53263. int LookAndFeel::getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText)
  53264. {
  53265. return getMenuBarFont (menuBar, itemIndex, itemText)
  53266. .getStringWidth (itemText) + menuBar.getHeight();
  53267. }
  53268. void LookAndFeel::drawMenuBarItem (Graphics& g,
  53269. int width, int height,
  53270. int itemIndex,
  53271. const String& itemText,
  53272. bool isMouseOverItem,
  53273. bool isMenuOpen,
  53274. bool /*isMouseOverBar*/,
  53275. MenuBarComponent& menuBar)
  53276. {
  53277. if (! menuBar.isEnabled())
  53278. {
  53279. g.setColour (menuBar.findColour (PopupMenu::textColourId)
  53280. .withMultipliedAlpha (0.5f));
  53281. }
  53282. else if (isMenuOpen || isMouseOverItem)
  53283. {
  53284. g.fillAll (menuBar.findColour (PopupMenu::highlightedBackgroundColourId));
  53285. g.setColour (menuBar.findColour (PopupMenu::highlightedTextColourId));
  53286. }
  53287. else
  53288. {
  53289. g.setColour (menuBar.findColour (PopupMenu::textColourId));
  53290. }
  53291. g.setFont (getMenuBarFont (menuBar, itemIndex, itemText));
  53292. g.drawFittedText (itemText, 0, 0, width, height, Justification::centred, 1);
  53293. }
  53294. void LookAndFeel::fillTextEditorBackground (Graphics& g, int /*width*/, int /*height*/,
  53295. TextEditor& textEditor)
  53296. {
  53297. g.fillAll (textEditor.findColour (TextEditor::backgroundColourId));
  53298. }
  53299. void LookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  53300. {
  53301. if (textEditor.isEnabled())
  53302. {
  53303. if (textEditor.hasKeyboardFocus (true) && ! textEditor.isReadOnly())
  53304. {
  53305. const int border = 2;
  53306. g.setColour (textEditor.findColour (TextEditor::focusedOutlineColourId));
  53307. g.drawRect (0, 0, width, height, border);
  53308. g.setOpacity (1.0f);
  53309. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId).withMultipliedAlpha (0.75f));
  53310. g.drawBevel (0, 0, width, height + 2, border + 2, shadowColour, shadowColour);
  53311. }
  53312. else
  53313. {
  53314. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  53315. g.drawRect (0, 0, width, height);
  53316. g.setOpacity (1.0f);
  53317. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId));
  53318. g.drawBevel (0, 0, width, height + 2, 3, shadowColour, shadowColour);
  53319. }
  53320. }
  53321. }
  53322. void LookAndFeel::drawComboBox (Graphics& g, int width, int height,
  53323. const bool isButtonDown,
  53324. int buttonX, int buttonY,
  53325. int buttonW, int buttonH,
  53326. ComboBox& box)
  53327. {
  53328. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  53329. if (box.isEnabled() && box.hasKeyboardFocus (false))
  53330. {
  53331. g.setColour (box.findColour (TextButton::buttonColourId));
  53332. g.drawRect (0, 0, width, height, 2);
  53333. }
  53334. else
  53335. {
  53336. g.setColour (box.findColour (ComboBox::outlineColourId));
  53337. g.drawRect (0, 0, width, height);
  53338. }
  53339. const float outlineThickness = box.isEnabled() ? (isButtonDown ? 1.2f : 0.5f) : 0.3f;
  53340. const Colour baseColour (createBaseColour (box.findColour (ComboBox::buttonColourId),
  53341. box.hasKeyboardFocus (true),
  53342. false, isButtonDown)
  53343. .withMultipliedAlpha (box.isEnabled() ? 1.0f : 0.5f));
  53344. drawGlassLozenge (g,
  53345. buttonX + outlineThickness, buttonY + outlineThickness,
  53346. buttonW - outlineThickness * 2.0f, buttonH - outlineThickness * 2.0f,
  53347. baseColour, outlineThickness, -1.0f,
  53348. true, true, true, true);
  53349. if (box.isEnabled())
  53350. {
  53351. const float arrowX = 0.3f;
  53352. const float arrowH = 0.2f;
  53353. Path p;
  53354. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  53355. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  53356. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  53357. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  53358. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  53359. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  53360. g.setColour (box.findColour (ComboBox::arrowColourId));
  53361. g.fillPath (p);
  53362. }
  53363. }
  53364. const Font LookAndFeel::getComboBoxFont (ComboBox& box)
  53365. {
  53366. return Font (jmin (15.0f, box.getHeight() * 0.85f));
  53367. }
  53368. Label* LookAndFeel::createComboBoxTextBox (ComboBox&)
  53369. {
  53370. return new Label (String::empty, String::empty);
  53371. }
  53372. void LookAndFeel::positionComboBoxText (ComboBox& box, Label& label)
  53373. {
  53374. label.setBounds (1, 1,
  53375. box.getWidth() + 3 - box.getHeight(),
  53376. box.getHeight() - 2);
  53377. label.setFont (getComboBoxFont (box));
  53378. }
  53379. void LookAndFeel::drawLabel (Graphics& g, Label& label)
  53380. {
  53381. g.fillAll (label.findColour (Label::backgroundColourId));
  53382. if (! label.isBeingEdited())
  53383. {
  53384. const float alpha = label.isEnabled() ? 1.0f : 0.5f;
  53385. g.setColour (label.findColour (Label::textColourId).withMultipliedAlpha (alpha));
  53386. g.setFont (label.getFont());
  53387. g.drawFittedText (label.getText(),
  53388. label.getHorizontalBorderSize(),
  53389. label.getVerticalBorderSize(),
  53390. label.getWidth() - 2 * label.getHorizontalBorderSize(),
  53391. label.getHeight() - 2 * label.getVerticalBorderSize(),
  53392. label.getJustificationType(),
  53393. jmax (1, (int) (label.getHeight() / label.getFont().getHeight())),
  53394. label.getMinimumHorizontalScale());
  53395. g.setColour (label.findColour (Label::outlineColourId).withMultipliedAlpha (alpha));
  53396. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  53397. }
  53398. else if (label.isEnabled())
  53399. {
  53400. g.setColour (label.findColour (Label::outlineColourId));
  53401. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  53402. }
  53403. }
  53404. void LookAndFeel::drawLinearSliderBackground (Graphics& g,
  53405. int x, int y,
  53406. int width, int height,
  53407. float /*sliderPos*/,
  53408. float /*minSliderPos*/,
  53409. float /*maxSliderPos*/,
  53410. const Slider::SliderStyle /*style*/,
  53411. Slider& slider)
  53412. {
  53413. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  53414. const Colour trackColour (slider.findColour (Slider::trackColourId));
  53415. const Colour gradCol1 (trackColour.overlaidWith (Colours::black.withAlpha (slider.isEnabled() ? 0.25f : 0.13f)));
  53416. const Colour gradCol2 (trackColour.overlaidWith (Colour (0x14000000)));
  53417. Path indent;
  53418. if (slider.isHorizontal())
  53419. {
  53420. const float iy = y + height * 0.5f - sliderRadius * 0.5f;
  53421. const float ih = sliderRadius;
  53422. g.setGradientFill (ColourGradient (gradCol1, 0.0f, iy,
  53423. gradCol2, 0.0f, iy + ih, false));
  53424. indent.addRoundedRectangle (x - sliderRadius * 0.5f, iy,
  53425. width + sliderRadius, ih,
  53426. 5.0f);
  53427. g.fillPath (indent);
  53428. }
  53429. else
  53430. {
  53431. const float ix = x + width * 0.5f - sliderRadius * 0.5f;
  53432. const float iw = sliderRadius;
  53433. g.setGradientFill (ColourGradient (gradCol1, ix, 0.0f,
  53434. gradCol2, ix + iw, 0.0f, false));
  53435. indent.addRoundedRectangle (ix, y - sliderRadius * 0.5f,
  53436. iw, height + sliderRadius,
  53437. 5.0f);
  53438. g.fillPath (indent);
  53439. }
  53440. g.setColour (Colour (0x4c000000));
  53441. g.strokePath (indent, PathStrokeType (0.5f));
  53442. }
  53443. void LookAndFeel::drawLinearSliderThumb (Graphics& g,
  53444. int x, int y,
  53445. int width, int height,
  53446. float sliderPos,
  53447. float minSliderPos,
  53448. float maxSliderPos,
  53449. const Slider::SliderStyle style,
  53450. Slider& slider)
  53451. {
  53452. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  53453. Colour knobColour (createBaseColour (slider.findColour (Slider::thumbColourId),
  53454. slider.hasKeyboardFocus (false) && slider.isEnabled(),
  53455. slider.isMouseOverOrDragging() && slider.isEnabled(),
  53456. slider.isMouseButtonDown() && slider.isEnabled()));
  53457. const float outlineThickness = slider.isEnabled() ? 0.8f : 0.3f;
  53458. if (style == Slider::LinearHorizontal || style == Slider::LinearVertical)
  53459. {
  53460. float kx, ky;
  53461. if (style == Slider::LinearVertical)
  53462. {
  53463. kx = x + width * 0.5f;
  53464. ky = sliderPos;
  53465. }
  53466. else
  53467. {
  53468. kx = sliderPos;
  53469. ky = y + height * 0.5f;
  53470. }
  53471. drawGlassSphere (g,
  53472. kx - sliderRadius,
  53473. ky - sliderRadius,
  53474. sliderRadius * 2.0f,
  53475. knobColour, outlineThickness);
  53476. }
  53477. else
  53478. {
  53479. if (style == Slider::ThreeValueVertical)
  53480. {
  53481. drawGlassSphere (g, x + width * 0.5f - sliderRadius,
  53482. sliderPos - sliderRadius,
  53483. sliderRadius * 2.0f,
  53484. knobColour, outlineThickness);
  53485. }
  53486. else if (style == Slider::ThreeValueHorizontal)
  53487. {
  53488. drawGlassSphere (g,sliderPos - sliderRadius,
  53489. y + height * 0.5f - sliderRadius,
  53490. sliderRadius * 2.0f,
  53491. knobColour, outlineThickness);
  53492. }
  53493. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  53494. {
  53495. const float sr = jmin (sliderRadius, width * 0.4f);
  53496. drawGlassPointer (g, jmax (0.0f, x + width * 0.5f - sliderRadius * 2.0f),
  53497. minSliderPos - sliderRadius,
  53498. sliderRadius * 2.0f, knobColour, outlineThickness, 1);
  53499. drawGlassPointer (g, jmin (x + width - sliderRadius * 2.0f, x + width * 0.5f), maxSliderPos - sr,
  53500. sliderRadius * 2.0f, knobColour, outlineThickness, 3);
  53501. }
  53502. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  53503. {
  53504. const float sr = jmin (sliderRadius, height * 0.4f);
  53505. drawGlassPointer (g, minSliderPos - sr,
  53506. jmax (0.0f, y + height * 0.5f - sliderRadius * 2.0f),
  53507. sliderRadius * 2.0f, knobColour, outlineThickness, 2);
  53508. drawGlassPointer (g, maxSliderPos - sliderRadius,
  53509. jmin (y + height - sliderRadius * 2.0f, y + height * 0.5f),
  53510. sliderRadius * 2.0f, knobColour, outlineThickness, 4);
  53511. }
  53512. }
  53513. }
  53514. void LookAndFeel::drawLinearSlider (Graphics& g,
  53515. int x, int y,
  53516. int width, int height,
  53517. float sliderPos,
  53518. float minSliderPos,
  53519. float maxSliderPos,
  53520. const Slider::SliderStyle style,
  53521. Slider& slider)
  53522. {
  53523. g.fillAll (slider.findColour (Slider::backgroundColourId));
  53524. if (style == Slider::LinearBar)
  53525. {
  53526. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  53527. Colour baseColour (createBaseColour (slider.findColour (Slider::thumbColourId)
  53528. .withMultipliedSaturation (slider.isEnabled() ? 1.0f : 0.5f),
  53529. false,
  53530. isMouseOver,
  53531. isMouseOver || slider.isMouseButtonDown()));
  53532. drawShinyButtonShape (g,
  53533. (float) x, (float) y, sliderPos - (float) x, (float) height, 0.0f,
  53534. baseColour,
  53535. slider.isEnabled() ? 0.9f : 0.3f,
  53536. true, true, true, true);
  53537. }
  53538. else
  53539. {
  53540. drawLinearSliderBackground (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  53541. drawLinearSliderThumb (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  53542. }
  53543. }
  53544. int LookAndFeel::getSliderThumbRadius (Slider& slider)
  53545. {
  53546. return jmin (7,
  53547. slider.getHeight() / 2,
  53548. slider.getWidth() / 2) + 2;
  53549. }
  53550. void LookAndFeel::drawRotarySlider (Graphics& g,
  53551. int x, int y,
  53552. int width, int height,
  53553. float sliderPos,
  53554. const float rotaryStartAngle,
  53555. const float rotaryEndAngle,
  53556. Slider& slider)
  53557. {
  53558. const float radius = jmin (width / 2, height / 2) - 2.0f;
  53559. const float centreX = x + width * 0.5f;
  53560. const float centreY = y + height * 0.5f;
  53561. const float rx = centreX - radius;
  53562. const float ry = centreY - radius;
  53563. const float rw = radius * 2.0f;
  53564. const float angle = rotaryStartAngle + sliderPos * (rotaryEndAngle - rotaryStartAngle);
  53565. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  53566. if (radius > 12.0f)
  53567. {
  53568. if (slider.isEnabled())
  53569. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  53570. else
  53571. g.setColour (Colour (0x80808080));
  53572. const float thickness = 0.7f;
  53573. {
  53574. Path filledArc;
  53575. filledArc.addPieSegment (rx, ry, rw, rw,
  53576. rotaryStartAngle,
  53577. angle,
  53578. thickness);
  53579. g.fillPath (filledArc);
  53580. }
  53581. if (thickness > 0)
  53582. {
  53583. const float innerRadius = radius * 0.2f;
  53584. Path p;
  53585. p.addTriangle (-innerRadius, 0.0f,
  53586. 0.0f, -radius * thickness * 1.1f,
  53587. innerRadius, 0.0f);
  53588. p.addEllipse (-innerRadius, -innerRadius, innerRadius * 2.0f, innerRadius * 2.0f);
  53589. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  53590. }
  53591. if (slider.isEnabled())
  53592. g.setColour (slider.findColour (Slider::rotarySliderOutlineColourId));
  53593. else
  53594. g.setColour (Colour (0x80808080));
  53595. Path outlineArc;
  53596. outlineArc.addPieSegment (rx, ry, rw, rw, rotaryStartAngle, rotaryEndAngle, thickness);
  53597. outlineArc.closeSubPath();
  53598. g.strokePath (outlineArc, PathStrokeType (slider.isEnabled() ? (isMouseOver ? 2.0f : 1.2f) : 0.3f));
  53599. }
  53600. else
  53601. {
  53602. if (slider.isEnabled())
  53603. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  53604. else
  53605. g.setColour (Colour (0x80808080));
  53606. Path p;
  53607. p.addEllipse (-0.4f * rw, -0.4f * rw, rw * 0.8f, rw * 0.8f);
  53608. PathStrokeType (rw * 0.1f).createStrokedPath (p, p);
  53609. p.addLineSegment (Line<float> (0.0f, 0.0f, 0.0f, -radius), rw * 0.2f);
  53610. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  53611. }
  53612. }
  53613. Button* LookAndFeel::createSliderButton (const bool isIncrement)
  53614. {
  53615. return new TextButton (isIncrement ? "+" : "-", String::empty);
  53616. }
  53617. class SliderLabelComp : public Label
  53618. {
  53619. public:
  53620. SliderLabelComp() : Label (String::empty, String::empty) {}
  53621. ~SliderLabelComp() {}
  53622. void mouseWheelMove (const MouseEvent&, float, float) {}
  53623. };
  53624. Label* LookAndFeel::createSliderTextBox (Slider& slider)
  53625. {
  53626. Label* const l = new SliderLabelComp();
  53627. l->setJustificationType (Justification::centred);
  53628. l->setColour (Label::textColourId, slider.findColour (Slider::textBoxTextColourId));
  53629. l->setColour (Label::backgroundColourId,
  53630. (slider.getSliderStyle() == Slider::LinearBar) ? Colours::transparentBlack
  53631. : slider.findColour (Slider::textBoxBackgroundColourId));
  53632. l->setColour (Label::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  53633. l->setColour (TextEditor::textColourId, slider.findColour (Slider::textBoxTextColourId));
  53634. l->setColour (TextEditor::backgroundColourId,
  53635. slider.findColour (Slider::textBoxBackgroundColourId)
  53636. .withAlpha (slider.getSliderStyle() == Slider::LinearBar ? 0.7f : 1.0f));
  53637. l->setColour (TextEditor::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  53638. return l;
  53639. }
  53640. ImageEffectFilter* LookAndFeel::getSliderEffect()
  53641. {
  53642. return 0;
  53643. }
  53644. static const TextLayout layoutTooltipText (const String& text) throw()
  53645. {
  53646. const float tooltipFontSize = 12.0f;
  53647. const int maxToolTipWidth = 400;
  53648. const Font f (tooltipFontSize, Font::bold);
  53649. TextLayout tl (text, f);
  53650. tl.layout (maxToolTipWidth, Justification::left, true);
  53651. return tl;
  53652. }
  53653. void LookAndFeel::getTooltipSize (const String& tipText, int& width, int& height)
  53654. {
  53655. const TextLayout tl (layoutTooltipText (tipText));
  53656. width = tl.getWidth() + 14;
  53657. height = tl.getHeight() + 6;
  53658. }
  53659. void LookAndFeel::drawTooltip (Graphics& g, const String& text, int width, int height)
  53660. {
  53661. g.fillAll (findColour (TooltipWindow::backgroundColourId));
  53662. const Colour textCol (findColour (TooltipWindow::textColourId));
  53663. #if ! JUCE_MAC // The mac windows already have a non-optional 1 pix outline, so don't double it here..
  53664. g.setColour (findColour (TooltipWindow::outlineColourId));
  53665. g.drawRect (0, 0, width, height, 1);
  53666. #endif
  53667. const TextLayout tl (layoutTooltipText (text));
  53668. g.setColour (findColour (TooltipWindow::textColourId));
  53669. tl.drawWithin (g, 0, 0, width, height, Justification::centred);
  53670. }
  53671. Button* LookAndFeel::createFilenameComponentBrowseButton (const String& text)
  53672. {
  53673. return new TextButton (text, TRANS("click to browse for a different file"));
  53674. }
  53675. void LookAndFeel::layoutFilenameComponent (FilenameComponent& filenameComp,
  53676. ComboBox* filenameBox,
  53677. Button* browseButton)
  53678. {
  53679. browseButton->setSize (80, filenameComp.getHeight());
  53680. TextButton* const tb = dynamic_cast <TextButton*> (browseButton);
  53681. if (tb != 0)
  53682. tb->changeWidthToFitText();
  53683. browseButton->setTopRightPosition (filenameComp.getWidth(), 0);
  53684. filenameBox->setBounds (0, 0, browseButton->getX(), filenameComp.getHeight());
  53685. }
  53686. void LookAndFeel::drawImageButton (Graphics& g, Image* image,
  53687. int imageX, int imageY, int imageW, int imageH,
  53688. const Colour& overlayColour,
  53689. float imageOpacity,
  53690. ImageButton& button)
  53691. {
  53692. if (! button.isEnabled())
  53693. imageOpacity *= 0.3f;
  53694. if (! overlayColour.isOpaque())
  53695. {
  53696. g.setOpacity (imageOpacity);
  53697. g.drawImage (*image, imageX, imageY, imageW, imageH,
  53698. 0, 0, image->getWidth(), image->getHeight(), false);
  53699. }
  53700. if (! overlayColour.isTransparent())
  53701. {
  53702. g.setColour (overlayColour);
  53703. g.drawImage (*image, imageX, imageY, imageW, imageH,
  53704. 0, 0, image->getWidth(), image->getHeight(), true);
  53705. }
  53706. }
  53707. void LookAndFeel::drawCornerResizer (Graphics& g,
  53708. int w, int h,
  53709. bool /*isMouseOver*/,
  53710. bool /*isMouseDragging*/)
  53711. {
  53712. const float lineThickness = jmin (w, h) * 0.075f;
  53713. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  53714. {
  53715. g.setColour (Colours::lightgrey);
  53716. g.drawLine (w * i,
  53717. h + 1.0f,
  53718. w + 1.0f,
  53719. h * i,
  53720. lineThickness);
  53721. g.setColour (Colours::darkgrey);
  53722. g.drawLine (w * i + lineThickness,
  53723. h + 1.0f,
  53724. w + 1.0f,
  53725. h * i + lineThickness,
  53726. lineThickness);
  53727. }
  53728. }
  53729. void LookAndFeel::drawResizableFrame (Graphics& g, int w, int h, const BorderSize& border)
  53730. {
  53731. if (! border.isEmpty())
  53732. {
  53733. const Rectangle<int> fullSize (0, 0, w, h);
  53734. const Rectangle<int> centreArea (border.subtractedFrom (fullSize));
  53735. g.saveState();
  53736. g.excludeClipRegion (centreArea);
  53737. g.setColour (Colour (0x50000000));
  53738. g.drawRect (fullSize);
  53739. g.setColour (Colour (0x19000000));
  53740. g.drawRect (centreArea.expanded (1, 1));
  53741. g.restoreState();
  53742. }
  53743. }
  53744. void LookAndFeel::fillResizableWindowBackground (Graphics& g, int /*w*/, int /*h*/,
  53745. const BorderSize& /*border*/, ResizableWindow& window)
  53746. {
  53747. g.fillAll (window.getBackgroundColour());
  53748. }
  53749. void LookAndFeel::drawResizableWindowBorder (Graphics&, int /*w*/, int /*h*/,
  53750. const BorderSize& /*border*/, ResizableWindow&)
  53751. {
  53752. }
  53753. void LookAndFeel::drawDocumentWindowTitleBar (DocumentWindow& window,
  53754. Graphics& g, int w, int h,
  53755. int titleSpaceX, int titleSpaceW,
  53756. const Image* icon,
  53757. bool drawTitleTextOnLeft)
  53758. {
  53759. const bool isActive = window.isActiveWindow();
  53760. g.setGradientFill (ColourGradient (window.getBackgroundColour(),
  53761. 0.0f, 0.0f,
  53762. window.getBackgroundColour().contrasting (isActive ? 0.15f : 0.05f),
  53763. 0.0f, (float) h, false));
  53764. g.fillAll();
  53765. Font font (h * 0.65f, Font::bold);
  53766. g.setFont (font);
  53767. int textW = font.getStringWidth (window.getName());
  53768. int iconW = 0;
  53769. int iconH = 0;
  53770. if (icon != 0)
  53771. {
  53772. iconH = (int) font.getHeight();
  53773. iconW = icon->getWidth() * iconH / icon->getHeight() + 4;
  53774. }
  53775. textW = jmin (titleSpaceW, textW + iconW);
  53776. int textX = drawTitleTextOnLeft ? titleSpaceX
  53777. : jmax (titleSpaceX, (w - textW) / 2);
  53778. if (textX + textW > titleSpaceX + titleSpaceW)
  53779. textX = titleSpaceX + titleSpaceW - textW;
  53780. if (icon != 0)
  53781. {
  53782. g.setOpacity (isActive ? 1.0f : 0.6f);
  53783. g.drawImageWithin (*icon, textX, (h - iconH) / 2, iconW, iconH,
  53784. RectanglePlacement::centred, false);
  53785. textX += iconW;
  53786. textW -= iconW;
  53787. }
  53788. if (window.isColourSpecified (DocumentWindow::textColourId) || isColourSpecified (DocumentWindow::textColourId))
  53789. g.setColour (findColour (DocumentWindow::textColourId));
  53790. else
  53791. g.setColour (window.getBackgroundColour().contrasting (isActive ? 0.7f : 0.4f));
  53792. g.drawText (window.getName(), textX, 0, textW, h, Justification::centredLeft, true);
  53793. }
  53794. class GlassWindowButton : public Button
  53795. {
  53796. public:
  53797. GlassWindowButton (const String& name, const Colour& col,
  53798. const Path& normalShape_,
  53799. const Path& toggledShape_) throw()
  53800. : Button (name),
  53801. colour (col),
  53802. normalShape (normalShape_),
  53803. toggledShape (toggledShape_)
  53804. {
  53805. }
  53806. ~GlassWindowButton()
  53807. {
  53808. }
  53809. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  53810. {
  53811. float alpha = isMouseOverButton ? (isButtonDown ? 1.0f : 0.8f) : 0.55f;
  53812. if (! isEnabled())
  53813. alpha *= 0.5f;
  53814. float x = 0, y = 0, diam;
  53815. if (getWidth() < getHeight())
  53816. {
  53817. diam = (float) getWidth();
  53818. y = (getHeight() - getWidth()) * 0.5f;
  53819. }
  53820. else
  53821. {
  53822. diam = (float) getHeight();
  53823. y = (getWidth() - getHeight()) * 0.5f;
  53824. }
  53825. x += diam * 0.05f;
  53826. y += diam * 0.05f;
  53827. diam *= 0.9f;
  53828. g.setGradientFill (ColourGradient (Colour::greyLevel (0.9f).withAlpha (alpha), 0, y + diam,
  53829. Colour::greyLevel (0.6f).withAlpha (alpha), 0, y, false));
  53830. g.fillEllipse (x, y, diam, diam);
  53831. x += 2.0f;
  53832. y += 2.0f;
  53833. diam -= 4.0f;
  53834. LookAndFeel::drawGlassSphere (g, x, y, diam, colour.withAlpha (alpha), 1.0f);
  53835. Path& p = getToggleState() ? toggledShape : normalShape;
  53836. const AffineTransform t (p.getTransformToScaleToFit (x + diam * 0.3f, y + diam * 0.3f,
  53837. diam * 0.4f, diam * 0.4f, true));
  53838. g.setColour (Colours::black.withAlpha (alpha * 0.6f));
  53839. g.fillPath (p, t);
  53840. }
  53841. juce_UseDebuggingNewOperator
  53842. private:
  53843. Colour colour;
  53844. Path normalShape, toggledShape;
  53845. GlassWindowButton (const GlassWindowButton&);
  53846. GlassWindowButton& operator= (const GlassWindowButton&);
  53847. };
  53848. Button* LookAndFeel::createDocumentWindowButton (int buttonType)
  53849. {
  53850. Path shape;
  53851. const float crossThickness = 0.25f;
  53852. if (buttonType == DocumentWindow::closeButton)
  53853. {
  53854. shape.addLineSegment (Line<float> (0.0f, 0.0f, 1.0f, 1.0f), crossThickness * 1.4f);
  53855. shape.addLineSegment (Line<float> (1.0f, 0.0f, 0.0f, 1.0f), crossThickness * 1.4f);
  53856. return new GlassWindowButton ("close", Colour (0xffdd1100), shape, shape);
  53857. }
  53858. else if (buttonType == DocumentWindow::minimiseButton)
  53859. {
  53860. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), crossThickness);
  53861. return new GlassWindowButton ("minimise", Colour (0xffaa8811), shape, shape);
  53862. }
  53863. else if (buttonType == DocumentWindow::maximiseButton)
  53864. {
  53865. shape.addLineSegment (Line<float> (0.5f, 0.0f, 0.5f, 1.0f), crossThickness);
  53866. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), crossThickness);
  53867. Path fullscreenShape;
  53868. fullscreenShape.startNewSubPath (45.0f, 100.0f);
  53869. fullscreenShape.lineTo (0.0f, 100.0f);
  53870. fullscreenShape.lineTo (0.0f, 0.0f);
  53871. fullscreenShape.lineTo (100.0f, 0.0f);
  53872. fullscreenShape.lineTo (100.0f, 45.0f);
  53873. fullscreenShape.addRectangle (45.0f, 45.0f, 100.0f, 100.0f);
  53874. PathStrokeType (30.0f).createStrokedPath (fullscreenShape, fullscreenShape);
  53875. return new GlassWindowButton ("maximise", Colour (0xff119911), shape, fullscreenShape);
  53876. }
  53877. jassertfalse;
  53878. return 0;
  53879. }
  53880. void LookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  53881. int titleBarX,
  53882. int titleBarY,
  53883. int titleBarW,
  53884. int titleBarH,
  53885. Button* minimiseButton,
  53886. Button* maximiseButton,
  53887. Button* closeButton,
  53888. bool positionTitleBarButtonsOnLeft)
  53889. {
  53890. const int buttonW = titleBarH - titleBarH / 8;
  53891. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  53892. : titleBarX + titleBarW - buttonW - buttonW / 4;
  53893. if (closeButton != 0)
  53894. {
  53895. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53896. x += positionTitleBarButtonsOnLeft ? buttonW : -(buttonW + buttonW / 4);
  53897. }
  53898. if (positionTitleBarButtonsOnLeft)
  53899. swapVariables (minimiseButton, maximiseButton);
  53900. if (maximiseButton != 0)
  53901. {
  53902. maximiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53903. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  53904. }
  53905. if (minimiseButton != 0)
  53906. minimiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53907. }
  53908. int LookAndFeel::getDefaultMenuBarHeight()
  53909. {
  53910. return 24;
  53911. }
  53912. DropShadower* LookAndFeel::createDropShadowerForComponent (Component*)
  53913. {
  53914. return new DropShadower (0.4f, 1, 5, 10);
  53915. }
  53916. void LookAndFeel::drawStretchableLayoutResizerBar (Graphics& g,
  53917. int w, int h,
  53918. bool /*isVerticalBar*/,
  53919. bool isMouseOver,
  53920. bool isMouseDragging)
  53921. {
  53922. float alpha = 0.5f;
  53923. if (isMouseOver || isMouseDragging)
  53924. {
  53925. g.fillAll (Colour (0x190000ff));
  53926. alpha = 1.0f;
  53927. }
  53928. const float cx = w * 0.5f;
  53929. const float cy = h * 0.5f;
  53930. const float cr = jmin (w, h) * 0.4f;
  53931. g.setGradientFill (ColourGradient (Colours::white.withAlpha (alpha), cx + cr * 0.1f, cy + cr,
  53932. Colours::black.withAlpha (alpha), cx, cy - cr * 4.0f,
  53933. true));
  53934. g.fillEllipse (cx - cr, cy - cr, cr * 2.0f, cr * 2.0f);
  53935. }
  53936. void LookAndFeel::drawGroupComponentOutline (Graphics& g, int width, int height,
  53937. const String& text,
  53938. const Justification& position,
  53939. GroupComponent& group)
  53940. {
  53941. const float textH = 15.0f;
  53942. const float indent = 3.0f;
  53943. const float textEdgeGap = 4.0f;
  53944. float cs = 5.0f;
  53945. Font f (textH);
  53946. Path p;
  53947. float x = indent;
  53948. float y = f.getAscent() - 3.0f;
  53949. float w = jmax (0.0f, width - x * 2.0f);
  53950. float h = jmax (0.0f, height - y - indent);
  53951. cs = jmin (cs, w * 0.5f, h * 0.5f);
  53952. const float cs2 = 2.0f * cs;
  53953. float textW = text.isEmpty() ? 0 : jlimit (0.0f, jmax (0.0f, w - cs2 - textEdgeGap * 2), f.getStringWidth (text) + textEdgeGap * 2.0f);
  53954. float textX = cs + textEdgeGap;
  53955. if (position.testFlags (Justification::horizontallyCentred))
  53956. textX = cs + (w - cs2 - textW) * 0.5f;
  53957. else if (position.testFlags (Justification::right))
  53958. textX = w - cs - textW - textEdgeGap;
  53959. p.startNewSubPath (x + textX + textW, y);
  53960. p.lineTo (x + w - cs, y);
  53961. p.addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  53962. p.lineTo (x + w, y + h - cs);
  53963. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  53964. p.lineTo (x + cs, y + h);
  53965. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  53966. p.lineTo (x, y + cs);
  53967. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  53968. p.lineTo (x + textX, y);
  53969. const float alpha = group.isEnabled() ? 1.0f : 0.5f;
  53970. g.setColour (group.findColour (GroupComponent::outlineColourId)
  53971. .withMultipliedAlpha (alpha));
  53972. g.strokePath (p, PathStrokeType (2.0f));
  53973. g.setColour (group.findColour (GroupComponent::textColourId)
  53974. .withMultipliedAlpha (alpha));
  53975. g.setFont (f);
  53976. g.drawText (text,
  53977. roundToInt (x + textX), 0,
  53978. roundToInt (textW),
  53979. roundToInt (textH),
  53980. Justification::centred, true);
  53981. }
  53982. int LookAndFeel::getTabButtonOverlap (int tabDepth)
  53983. {
  53984. return 1 + tabDepth / 3;
  53985. }
  53986. int LookAndFeel::getTabButtonSpaceAroundImage()
  53987. {
  53988. return 4;
  53989. }
  53990. void LookAndFeel::createTabButtonShape (Path& p,
  53991. int width, int height,
  53992. int /*tabIndex*/,
  53993. const String& /*text*/,
  53994. Button& /*button*/,
  53995. TabbedButtonBar::Orientation orientation,
  53996. const bool /*isMouseOver*/,
  53997. const bool /*isMouseDown*/,
  53998. const bool /*isFrontTab*/)
  53999. {
  54000. const float w = (float) width;
  54001. const float h = (float) height;
  54002. float length = w;
  54003. float depth = h;
  54004. if (orientation == TabbedButtonBar::TabsAtLeft
  54005. || orientation == TabbedButtonBar::TabsAtRight)
  54006. {
  54007. swapVariables (length, depth);
  54008. }
  54009. const float indent = (float) getTabButtonOverlap ((int) depth);
  54010. const float overhang = 4.0f;
  54011. if (orientation == TabbedButtonBar::TabsAtLeft)
  54012. {
  54013. p.startNewSubPath (w, 0.0f);
  54014. p.lineTo (0.0f, indent);
  54015. p.lineTo (0.0f, h - indent);
  54016. p.lineTo (w, h);
  54017. p.lineTo (w + overhang, h + overhang);
  54018. p.lineTo (w + overhang, -overhang);
  54019. }
  54020. else if (orientation == TabbedButtonBar::TabsAtRight)
  54021. {
  54022. p.startNewSubPath (0.0f, 0.0f);
  54023. p.lineTo (w, indent);
  54024. p.lineTo (w, h - indent);
  54025. p.lineTo (0.0f, h);
  54026. p.lineTo (-overhang, h + overhang);
  54027. p.lineTo (-overhang, -overhang);
  54028. }
  54029. else if (orientation == TabbedButtonBar::TabsAtBottom)
  54030. {
  54031. p.startNewSubPath (0.0f, 0.0f);
  54032. p.lineTo (indent, h);
  54033. p.lineTo (w - indent, h);
  54034. p.lineTo (w, 0.0f);
  54035. p.lineTo (w + overhang, -overhang);
  54036. p.lineTo (-overhang, -overhang);
  54037. }
  54038. else
  54039. {
  54040. p.startNewSubPath (0.0f, h);
  54041. p.lineTo (indent, 0.0f);
  54042. p.lineTo (w - indent, 0.0f);
  54043. p.lineTo (w, h);
  54044. p.lineTo (w + overhang, h + overhang);
  54045. p.lineTo (-overhang, h + overhang);
  54046. }
  54047. p.closeSubPath();
  54048. p = p.createPathWithRoundedCorners (3.0f);
  54049. }
  54050. void LookAndFeel::fillTabButtonShape (Graphics& g,
  54051. const Path& path,
  54052. const Colour& preferredColour,
  54053. int /*tabIndex*/,
  54054. const String& /*text*/,
  54055. Button& button,
  54056. TabbedButtonBar::Orientation /*orientation*/,
  54057. const bool /*isMouseOver*/,
  54058. const bool /*isMouseDown*/,
  54059. const bool isFrontTab)
  54060. {
  54061. g.setColour (isFrontTab ? preferredColour
  54062. : preferredColour.withMultipliedAlpha (0.9f));
  54063. g.fillPath (path);
  54064. g.setColour (button.findColour (isFrontTab ? TabbedButtonBar::frontOutlineColourId
  54065. : TabbedButtonBar::tabOutlineColourId, false)
  54066. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  54067. g.strokePath (path, PathStrokeType (isFrontTab ? 1.0f : 0.5f));
  54068. }
  54069. void LookAndFeel::drawTabButtonText (Graphics& g,
  54070. int x, int y, int w, int h,
  54071. const Colour& preferredBackgroundColour,
  54072. int /*tabIndex*/,
  54073. const String& text,
  54074. Button& button,
  54075. TabbedButtonBar::Orientation orientation,
  54076. const bool isMouseOver,
  54077. const bool isMouseDown,
  54078. const bool isFrontTab)
  54079. {
  54080. int length = w;
  54081. int depth = h;
  54082. if (orientation == TabbedButtonBar::TabsAtLeft
  54083. || orientation == TabbedButtonBar::TabsAtRight)
  54084. {
  54085. swapVariables (length, depth);
  54086. }
  54087. Font font (depth * 0.6f);
  54088. font.setUnderline (button.hasKeyboardFocus (false));
  54089. GlyphArrangement textLayout;
  54090. textLayout.addFittedText (font, text.trim(),
  54091. 0.0f, 0.0f, (float) length, (float) depth,
  54092. Justification::centred,
  54093. jmax (1, depth / 12));
  54094. AffineTransform transform;
  54095. if (orientation == TabbedButtonBar::TabsAtLeft)
  54096. {
  54097. transform = transform.rotated (float_Pi * -0.5f)
  54098. .translated ((float) x, (float) (y + h));
  54099. }
  54100. else if (orientation == TabbedButtonBar::TabsAtRight)
  54101. {
  54102. transform = transform.rotated (float_Pi * 0.5f)
  54103. .translated ((float) (x + w), (float) y);
  54104. }
  54105. else
  54106. {
  54107. transform = transform.translated ((float) x, (float) y);
  54108. }
  54109. if (isFrontTab && (button.isColourSpecified (TabbedButtonBar::frontTextColourId) || isColourSpecified (TabbedButtonBar::frontTextColourId)))
  54110. g.setColour (findColour (TabbedButtonBar::frontTextColourId));
  54111. else if (button.isColourSpecified (TabbedButtonBar::tabTextColourId) || isColourSpecified (TabbedButtonBar::tabTextColourId))
  54112. g.setColour (findColour (TabbedButtonBar::tabTextColourId));
  54113. else
  54114. g.setColour (preferredBackgroundColour.contrasting());
  54115. if (! (isMouseOver || isMouseDown))
  54116. g.setOpacity (0.8f);
  54117. if (! button.isEnabled())
  54118. g.setOpacity (0.3f);
  54119. textLayout.draw (g, transform);
  54120. }
  54121. int LookAndFeel::getTabButtonBestWidth (int /*tabIndex*/,
  54122. const String& text,
  54123. int tabDepth,
  54124. Button&)
  54125. {
  54126. Font f (tabDepth * 0.6f);
  54127. return f.getStringWidth (text.trim()) + getTabButtonOverlap (tabDepth) * 2;
  54128. }
  54129. void LookAndFeel::drawTabButton (Graphics& g,
  54130. int w, int h,
  54131. const Colour& preferredColour,
  54132. int tabIndex,
  54133. const String& text,
  54134. Button& button,
  54135. TabbedButtonBar::Orientation orientation,
  54136. const bool isMouseOver,
  54137. const bool isMouseDown,
  54138. const bool isFrontTab)
  54139. {
  54140. int length = w;
  54141. int depth = h;
  54142. if (orientation == TabbedButtonBar::TabsAtLeft
  54143. || orientation == TabbedButtonBar::TabsAtRight)
  54144. {
  54145. swapVariables (length, depth);
  54146. }
  54147. Path tabShape;
  54148. createTabButtonShape (tabShape, w, h,
  54149. tabIndex, text, button, orientation,
  54150. isMouseOver, isMouseDown, isFrontTab);
  54151. fillTabButtonShape (g, tabShape, preferredColour,
  54152. tabIndex, text, button, orientation,
  54153. isMouseOver, isMouseDown, isFrontTab);
  54154. const int indent = getTabButtonOverlap (depth);
  54155. int x = 0, y = 0;
  54156. if (orientation == TabbedButtonBar::TabsAtLeft
  54157. || orientation == TabbedButtonBar::TabsAtRight)
  54158. {
  54159. y += indent;
  54160. h -= indent * 2;
  54161. }
  54162. else
  54163. {
  54164. x += indent;
  54165. w -= indent * 2;
  54166. }
  54167. drawTabButtonText (g, x, y, w, h, preferredColour,
  54168. tabIndex, text, button, orientation,
  54169. isMouseOver, isMouseDown, isFrontTab);
  54170. }
  54171. void LookAndFeel::drawTabAreaBehindFrontButton (Graphics& g,
  54172. int w, int h,
  54173. TabbedButtonBar& tabBar,
  54174. TabbedButtonBar::Orientation orientation)
  54175. {
  54176. const float shadowSize = 0.2f;
  54177. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  54178. Rectangle<int> shadowRect;
  54179. if (orientation == TabbedButtonBar::TabsAtLeft)
  54180. {
  54181. x1 = (float) w;
  54182. x2 = w * (1.0f - shadowSize);
  54183. shadowRect.setBounds ((int) x2, 0, w - (int) x2, h);
  54184. }
  54185. else if (orientation == TabbedButtonBar::TabsAtRight)
  54186. {
  54187. x2 = w * shadowSize;
  54188. shadowRect.setBounds (0, 0, (int) x2, h);
  54189. }
  54190. else if (orientation == TabbedButtonBar::TabsAtBottom)
  54191. {
  54192. y2 = h * shadowSize;
  54193. shadowRect.setBounds (0, 0, w, (int) y2);
  54194. }
  54195. else
  54196. {
  54197. y1 = (float) h;
  54198. y2 = h * (1.0f - shadowSize);
  54199. shadowRect.setBounds (0, (int) y2, w, h - (int) y2);
  54200. }
  54201. g.setGradientFill (ColourGradient (Colours::black.withAlpha (tabBar.isEnabled() ? 0.3f : 0.15f), x1, y1,
  54202. Colours::transparentBlack, x2, y2, false));
  54203. shadowRect.expand (2, 2);
  54204. g.fillRect (shadowRect);
  54205. g.setColour (Colour (0x80000000));
  54206. if (orientation == TabbedButtonBar::TabsAtLeft)
  54207. {
  54208. g.fillRect (w - 1, 0, 1, h);
  54209. }
  54210. else if (orientation == TabbedButtonBar::TabsAtRight)
  54211. {
  54212. g.fillRect (0, 0, 1, h);
  54213. }
  54214. else if (orientation == TabbedButtonBar::TabsAtBottom)
  54215. {
  54216. g.fillRect (0, 0, w, 1);
  54217. }
  54218. else
  54219. {
  54220. g.fillRect (0, h - 1, w, 1);
  54221. }
  54222. }
  54223. Button* LookAndFeel::createTabBarExtrasButton()
  54224. {
  54225. const float thickness = 7.0f;
  54226. const float indent = 22.0f;
  54227. Path p;
  54228. p.addEllipse (-10.0f, -10.0f, 120.0f, 120.0f);
  54229. DrawablePath ellipse;
  54230. ellipse.setPath (p);
  54231. ellipse.setFill (Colour (0x99ffffff));
  54232. p.clear();
  54233. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  54234. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  54235. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  54236. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  54237. p.setUsingNonZeroWinding (false);
  54238. DrawablePath dp;
  54239. dp.setPath (p);
  54240. dp.setFill (Colour (0x59000000));
  54241. DrawableComposite normalImage;
  54242. normalImage.insertDrawable (ellipse);
  54243. normalImage.insertDrawable (dp);
  54244. dp.setFill (Colour (0xcc000000));
  54245. DrawableComposite overImage;
  54246. overImage.insertDrawable (ellipse);
  54247. overImage.insertDrawable (dp);
  54248. DrawableButton* db = new DrawableButton ("tabs", DrawableButton::ImageFitted);
  54249. db->setImages (&normalImage, &overImage, 0);
  54250. return db;
  54251. }
  54252. void LookAndFeel::drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header)
  54253. {
  54254. g.fillAll (Colours::white);
  54255. const int w = header.getWidth();
  54256. const int h = header.getHeight();
  54257. g.setGradientFill (ColourGradient (Colour (0xffe8ebf9), 0.0f, h * 0.5f,
  54258. Colour (0xfff6f8f9), 0.0f, h - 1.0f,
  54259. false));
  54260. g.fillRect (0, h / 2, w, h);
  54261. g.setColour (Colour (0x33000000));
  54262. g.fillRect (0, h - 1, w, 1);
  54263. for (int i = header.getNumColumns (true); --i >= 0;)
  54264. g.fillRect (header.getColumnPosition (i).getRight() - 1, 0, 1, h - 1);
  54265. }
  54266. void LookAndFeel::drawTableHeaderColumn (Graphics& g, const String& columnName, int /*columnId*/,
  54267. int width, int height,
  54268. bool isMouseOver, bool isMouseDown,
  54269. int columnFlags)
  54270. {
  54271. if (isMouseDown)
  54272. g.fillAll (Colour (0x8899aadd));
  54273. else if (isMouseOver)
  54274. g.fillAll (Colour (0x5599aadd));
  54275. int rightOfText = width - 4;
  54276. if ((columnFlags & (TableHeaderComponent::sortedForwards | TableHeaderComponent::sortedBackwards)) != 0)
  54277. {
  54278. const float top = height * ((columnFlags & TableHeaderComponent::sortedForwards) != 0 ? 0.35f : (1.0f - 0.35f));
  54279. const float bottom = height - top;
  54280. const float w = height * 0.5f;
  54281. const float x = rightOfText - (w * 1.25f);
  54282. rightOfText = (int) x;
  54283. Path sortArrow;
  54284. sortArrow.addTriangle (x, bottom, x + w * 0.5f, top, x + w, bottom);
  54285. g.setColour (Colour (0x99000000));
  54286. g.fillPath (sortArrow);
  54287. }
  54288. g.setColour (Colours::black);
  54289. g.setFont (height * 0.5f, Font::bold);
  54290. const int textX = 4;
  54291. g.drawFittedText (columnName, textX, 0, rightOfText - textX, height, Justification::centredLeft, 1);
  54292. }
  54293. void LookAndFeel::paintToolbarBackground (Graphics& g, int w, int h, Toolbar& toolbar)
  54294. {
  54295. const Colour background (toolbar.findColour (Toolbar::backgroundColourId));
  54296. g.setGradientFill (ColourGradient (background, 0.0f, 0.0f,
  54297. background.darker (0.1f),
  54298. toolbar.isVertical() ? w - 1.0f : 0.0f,
  54299. toolbar.isVertical() ? 0.0f : h - 1.0f,
  54300. false));
  54301. g.fillAll();
  54302. }
  54303. Button* LookAndFeel::createToolbarMissingItemsButton (Toolbar& /*toolbar*/)
  54304. {
  54305. return createTabBarExtrasButton();
  54306. }
  54307. void LookAndFeel::paintToolbarButtonBackground (Graphics& g, int /*width*/, int /*height*/,
  54308. bool isMouseOver, bool isMouseDown,
  54309. ToolbarItemComponent& component)
  54310. {
  54311. if (isMouseDown)
  54312. g.fillAll (component.findColour (Toolbar::buttonMouseDownBackgroundColourId, true));
  54313. else if (isMouseOver)
  54314. g.fillAll (component.findColour (Toolbar::buttonMouseOverBackgroundColourId, true));
  54315. }
  54316. void LookAndFeel::paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  54317. const String& text, ToolbarItemComponent& component)
  54318. {
  54319. g.setColour (component.findColour (Toolbar::labelTextColourId, true)
  54320. .withAlpha (component.isEnabled() ? 1.0f : 0.25f));
  54321. const float fontHeight = jmin (14.0f, height * 0.85f);
  54322. g.setFont (fontHeight);
  54323. g.drawFittedText (text,
  54324. x, y, width, height,
  54325. Justification::centred,
  54326. jmax (1, height / (int) fontHeight));
  54327. }
  54328. void LookAndFeel::drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  54329. bool isOpen, int width, int height)
  54330. {
  54331. const int buttonSize = (height * 3) / 4;
  54332. const int buttonIndent = (height - buttonSize) / 2;
  54333. drawTreeviewPlusMinusBox (g, buttonIndent, buttonIndent, buttonSize, buttonSize, ! isOpen, false);
  54334. const int textX = buttonIndent * 2 + buttonSize + 2;
  54335. g.setColour (Colours::black);
  54336. g.setFont (height * 0.7f, Font::bold);
  54337. g.drawText (name, textX, 0, width - textX - 4, height, Justification::centredLeft, true);
  54338. }
  54339. void LookAndFeel::drawPropertyComponentBackground (Graphics& g, int width, int height,
  54340. PropertyComponent&)
  54341. {
  54342. g.setColour (Colour (0x66ffffff));
  54343. g.fillRect (0, 0, width, height - 1);
  54344. }
  54345. void LookAndFeel::drawPropertyComponentLabel (Graphics& g, int, int height,
  54346. PropertyComponent& component)
  54347. {
  54348. g.setColour (Colours::black);
  54349. if (! component.isEnabled())
  54350. g.setOpacity (0.6f);
  54351. g.setFont (jmin (height, 24) * 0.65f);
  54352. const Rectangle<int> r (getPropertyComponentContentPosition (component));
  54353. g.drawFittedText (component.getName(),
  54354. 3, r.getY(), r.getX() - 5, r.getHeight(),
  54355. Justification::centredLeft, 2);
  54356. }
  54357. const Rectangle<int> LookAndFeel::getPropertyComponentContentPosition (PropertyComponent& component)
  54358. {
  54359. return Rectangle<int> (component.getWidth() / 3, 1,
  54360. component.getWidth() - component.getWidth() / 3 - 1, component.getHeight() - 3);
  54361. }
  54362. void LookAndFeel::drawCallOutBoxBackground (CallOutBox& box, Graphics& g, const Path& path)
  54363. {
  54364. Image content (Image::ARGB, box.getWidth(), box.getHeight(), true);
  54365. {
  54366. Graphics g2 (content);
  54367. g2.setColour (Colour::greyLevel (0.23f).withAlpha (0.9f));
  54368. g2.fillPath (path);
  54369. g2.setColour (Colours::white.withAlpha (0.8f));
  54370. g2.strokePath (path, PathStrokeType (2.0f));
  54371. }
  54372. DropShadowEffect shadow;
  54373. shadow.setShadowProperties (5.0f, 0.4f, 0, 2);
  54374. shadow.applyEffect (content, g);
  54375. }
  54376. void LookAndFeel::createFileChooserHeaderText (const String& title,
  54377. const String& instructions,
  54378. GlyphArrangement& text,
  54379. int width)
  54380. {
  54381. text.clear();
  54382. text.addJustifiedText (Font (17.0f, Font::bold), title,
  54383. 8.0f, 22.0f, width - 16.0f,
  54384. Justification::centred);
  54385. text.addJustifiedText (Font (14.0f), instructions,
  54386. 8.0f, 24.0f + 16.0f, width - 16.0f,
  54387. Justification::centred);
  54388. }
  54389. void LookAndFeel::drawFileBrowserRow (Graphics& g, int width, int height,
  54390. const String& filename, Image* icon,
  54391. const String& fileSizeDescription,
  54392. const String& fileTimeDescription,
  54393. const bool isDirectory,
  54394. const bool isItemSelected,
  54395. const int /*itemIndex*/,
  54396. DirectoryContentsDisplayComponent&)
  54397. {
  54398. if (isItemSelected)
  54399. g.fillAll (findColour (DirectoryContentsDisplayComponent::highlightColourId));
  54400. g.setColour (findColour (DirectoryContentsDisplayComponent::textColourId));
  54401. g.setFont (height * 0.7f);
  54402. Image im;
  54403. if (icon != 0)
  54404. im = *icon;
  54405. if (im.isNull())
  54406. im = isDirectory ? getDefaultFolderImage()
  54407. : getDefaultDocumentFileImage();
  54408. const int x = 32;
  54409. if (im.isValid())
  54410. {
  54411. g.drawImageWithin (im, 2, 2, x - 4, height - 4,
  54412. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  54413. false);
  54414. }
  54415. if (width > 450 && ! isDirectory)
  54416. {
  54417. const int sizeX = roundToInt (width * 0.7f);
  54418. const int dateX = roundToInt (width * 0.8f);
  54419. g.drawFittedText (filename,
  54420. x, 0, sizeX - x, height,
  54421. Justification::centredLeft, 1);
  54422. g.setFont (height * 0.5f);
  54423. g.setColour (Colours::darkgrey);
  54424. if (! isDirectory)
  54425. {
  54426. g.drawFittedText (fileSizeDescription,
  54427. sizeX, 0, dateX - sizeX - 8, height,
  54428. Justification::centredRight, 1);
  54429. g.drawFittedText (fileTimeDescription,
  54430. dateX, 0, width - 8 - dateX, height,
  54431. Justification::centredRight, 1);
  54432. }
  54433. }
  54434. else
  54435. {
  54436. g.drawFittedText (filename,
  54437. x, 0, width - x, height,
  54438. Justification::centredLeft, 1);
  54439. }
  54440. }
  54441. Button* LookAndFeel::createFileBrowserGoUpButton()
  54442. {
  54443. DrawableButton* goUpButton = new DrawableButton ("up", DrawableButton::ImageOnButtonBackground);
  54444. Path arrowPath;
  54445. arrowPath.addArrow (Line<float> (50.0f, 100.0f, 50.0f, 0.0f), 40.0f, 100.0f, 50.0f);
  54446. DrawablePath arrowImage;
  54447. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  54448. arrowImage.setPath (arrowPath);
  54449. goUpButton->setImages (&arrowImage);
  54450. return goUpButton;
  54451. }
  54452. void LookAndFeel::layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  54453. DirectoryContentsDisplayComponent* fileListComponent,
  54454. FilePreviewComponent* previewComp,
  54455. ComboBox* currentPathBox,
  54456. TextEditor* filenameBox,
  54457. Button* goUpButton)
  54458. {
  54459. const int x = 8;
  54460. int w = browserComp.getWidth() - x - x;
  54461. if (previewComp != 0)
  54462. {
  54463. const int previewWidth = w / 3;
  54464. previewComp->setBounds (x + w - previewWidth, 0, previewWidth, browserComp.getHeight());
  54465. w -= previewWidth + 4;
  54466. }
  54467. int y = 4;
  54468. const int controlsHeight = 22;
  54469. const int bottomSectionHeight = controlsHeight + 8;
  54470. const int upButtonWidth = 50;
  54471. currentPathBox->setBounds (x, y, w - upButtonWidth - 6, controlsHeight);
  54472. goUpButton->setBounds (x + w - upButtonWidth, y, upButtonWidth, controlsHeight);
  54473. y += controlsHeight + 4;
  54474. Component* const listAsComp = dynamic_cast <Component*> (fileListComponent);
  54475. listAsComp->setBounds (x, y, w, browserComp.getHeight() - y - bottomSectionHeight);
  54476. y = listAsComp->getBottom() + 4;
  54477. filenameBox->setBounds (x + 50, y, w - 50, controlsHeight);
  54478. }
  54479. const Image LookAndFeel::getDefaultFolderImage()
  54480. {
  54481. 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,
  54482. 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,
  54483. 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,
  54484. 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,
  54485. 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,
  54486. 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,
  54487. 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,
  54488. 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,
  54489. 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,
  54490. 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,
  54491. 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,
  54492. 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,
  54493. 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,
  54494. 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,
  54495. 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,
  54496. 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,
  54497. 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,
  54498. 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,
  54499. 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,
  54500. 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,
  54501. 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,
  54502. 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,
  54503. 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,
  54504. 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,
  54505. 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,
  54506. 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,
  54507. 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,
  54508. 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,
  54509. 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,
  54510. 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,
  54511. 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,
  54512. 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,
  54513. 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,
  54514. 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,
  54515. 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,
  54516. 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,
  54517. 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,
  54518. 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,
  54519. 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,
  54520. 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,
  54521. 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,
  54522. 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,
  54523. 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,
  54524. 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};
  54525. return ImageCache::getFromMemory (foldericon_png, sizeof (foldericon_png));
  54526. }
  54527. const Image LookAndFeel::getDefaultDocumentFileImage()
  54528. {
  54529. 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,
  54530. 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,
  54531. 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,
  54532. 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,
  54533. 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,
  54534. 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,
  54535. 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,
  54536. 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,
  54537. 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,
  54538. 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,
  54539. 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,
  54540. 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,
  54541. 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,
  54542. 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,
  54543. 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,
  54544. 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,
  54545. 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,
  54546. 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,
  54547. 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,
  54548. 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,
  54549. 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,
  54550. 174,66,96,130,0,0};
  54551. return ImageCache::getFromMemory (fileicon_png, sizeof (fileicon_png));
  54552. }
  54553. void LookAndFeel::playAlertSound()
  54554. {
  54555. PlatformUtilities::beep();
  54556. }
  54557. void LookAndFeel::drawLevelMeter (Graphics& g, int width, int height, float level)
  54558. {
  54559. g.setColour (Colours::white.withAlpha (0.7f));
  54560. g.fillRoundedRectangle (0.0f, 0.0f, (float) width, (float) height, 3.0f);
  54561. g.setColour (Colours::black.withAlpha (0.2f));
  54562. g.drawRoundedRectangle (1.0f, 1.0f, width - 2.0f, height - 2.0f, 3.0f, 1.0f);
  54563. const int totalBlocks = 7;
  54564. const int numBlocks = roundToInt (totalBlocks * level);
  54565. const float w = (width - 6.0f) / (float) totalBlocks;
  54566. for (int i = 0; i < totalBlocks; ++i)
  54567. {
  54568. if (i >= numBlocks)
  54569. g.setColour (Colours::lightblue.withAlpha (0.6f));
  54570. else
  54571. g.setColour (i < totalBlocks - 1 ? Colours::blue.withAlpha (0.5f)
  54572. : Colours::red);
  54573. g.fillRoundedRectangle (3.0f + i * w + w * 0.1f, 3.0f, w * 0.8f, height - 6.0f, w * 0.4f);
  54574. }
  54575. }
  54576. void LookAndFeel::drawKeymapChangeButton (Graphics& g, int width, int height, Button& button, const String& keyDescription)
  54577. {
  54578. const Colour textColour (button.findColour (KeyMappingEditorComponent::textColourId, true));
  54579. if (keyDescription.isNotEmpty())
  54580. {
  54581. if (button.isEnabled())
  54582. {
  54583. const float alpha = button.isDown() ? 0.3f : (button.isOver() ? 0.15f : 0.08f);
  54584. g.fillAll (textColour.withAlpha (alpha));
  54585. g.setOpacity (0.3f);
  54586. g.drawBevel (0, 0, width, height, 2);
  54587. }
  54588. g.setColour (textColour);
  54589. g.setFont (height * 0.6f);
  54590. g.drawFittedText (keyDescription,
  54591. 3, 0, width - 6, height,
  54592. Justification::centred, 1);
  54593. }
  54594. else
  54595. {
  54596. const float thickness = 7.0f;
  54597. const float indent = 22.0f;
  54598. Path p;
  54599. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  54600. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  54601. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  54602. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  54603. p.setUsingNonZeroWinding (false);
  54604. g.setColour (textColour.withAlpha (button.isDown() ? 0.7f : (button.isOver() ? 0.5f : 0.3f)));
  54605. g.fillPath (p, p.getTransformToScaleToFit (2.0f, 2.0f, width - 4.0f, height - 4.0f, true));
  54606. }
  54607. if (button.hasKeyboardFocus (false))
  54608. {
  54609. g.setColour (textColour.withAlpha (0.4f));
  54610. g.drawRect (0, 0, width, height);
  54611. }
  54612. }
  54613. static void createRoundedPath (Path& p,
  54614. const float x, const float y,
  54615. const float w, const float h,
  54616. const float cs,
  54617. const bool curveTopLeft, const bool curveTopRight,
  54618. const bool curveBottomLeft, const bool curveBottomRight) throw()
  54619. {
  54620. const float cs2 = 2.0f * cs;
  54621. if (curveTopLeft)
  54622. {
  54623. p.startNewSubPath (x, y + cs);
  54624. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  54625. }
  54626. else
  54627. {
  54628. p.startNewSubPath (x, y);
  54629. }
  54630. if (curveTopRight)
  54631. {
  54632. p.lineTo (x + w - cs, y);
  54633. p.addArc (x + w - cs2, y, cs2, cs2, 0.0f, float_Pi * 0.5f);
  54634. }
  54635. else
  54636. {
  54637. p.lineTo (x + w, y);
  54638. }
  54639. if (curveBottomRight)
  54640. {
  54641. p.lineTo (x + w, y + h - cs);
  54642. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  54643. }
  54644. else
  54645. {
  54646. p.lineTo (x + w, y + h);
  54647. }
  54648. if (curveBottomLeft)
  54649. {
  54650. p.lineTo (x + cs, y + h);
  54651. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  54652. }
  54653. else
  54654. {
  54655. p.lineTo (x, y + h);
  54656. }
  54657. p.closeSubPath();
  54658. }
  54659. void LookAndFeel::drawShinyButtonShape (Graphics& g,
  54660. float x, float y, float w, float h,
  54661. float maxCornerSize,
  54662. const Colour& baseColour,
  54663. const float strokeWidth,
  54664. const bool flatOnLeft,
  54665. const bool flatOnRight,
  54666. const bool flatOnTop,
  54667. const bool flatOnBottom) throw()
  54668. {
  54669. if (w <= strokeWidth * 1.1f || h <= strokeWidth * 1.1f)
  54670. return;
  54671. const float cs = jmin (maxCornerSize, w * 0.5f, h * 0.5f);
  54672. Path outline;
  54673. createRoundedPath (outline, x, y, w, h, cs,
  54674. ! (flatOnLeft || flatOnTop),
  54675. ! (flatOnRight || flatOnTop),
  54676. ! (flatOnLeft || flatOnBottom),
  54677. ! (flatOnRight || flatOnBottom));
  54678. ColourGradient cg (baseColour, 0.0f, y,
  54679. baseColour.overlaidWith (Colour (0x070000ff)), 0.0f, y + h,
  54680. false);
  54681. cg.addColour (0.5, baseColour.overlaidWith (Colour (0x33ffffff)));
  54682. cg.addColour (0.51, baseColour.overlaidWith (Colour (0x110000ff)));
  54683. g.setGradientFill (cg);
  54684. g.fillPath (outline);
  54685. g.setColour (Colour (0x80000000));
  54686. g.strokePath (outline, PathStrokeType (strokeWidth));
  54687. }
  54688. void LookAndFeel::drawGlassSphere (Graphics& g,
  54689. const float x, const float y,
  54690. const float diameter,
  54691. const Colour& colour,
  54692. const float outlineThickness) throw()
  54693. {
  54694. if (diameter <= outlineThickness)
  54695. return;
  54696. Path p;
  54697. p.addEllipse (x, y, diameter, diameter);
  54698. {
  54699. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  54700. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  54701. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  54702. g.setGradientFill (cg);
  54703. g.fillPath (p);
  54704. }
  54705. g.setGradientFill (ColourGradient (Colours::white, 0, y + diameter * 0.06f,
  54706. Colours::transparentWhite, 0, y + diameter * 0.3f, false));
  54707. g.fillEllipse (x + diameter * 0.2f, y + diameter * 0.05f, diameter * 0.6f, diameter * 0.4f);
  54708. ColourGradient cg (Colours::transparentBlack,
  54709. x + diameter * 0.5f, y + diameter * 0.5f,
  54710. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  54711. x, y + diameter * 0.5f, true);
  54712. cg.addColour (0.7, Colours::transparentBlack);
  54713. cg.addColour (0.8, Colours::black.withAlpha (0.1f * outlineThickness));
  54714. g.setGradientFill (cg);
  54715. g.fillPath (p);
  54716. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  54717. g.drawEllipse (x, y, diameter, diameter, outlineThickness);
  54718. }
  54719. void LookAndFeel::drawGlassPointer (Graphics& g,
  54720. const float x, const float y,
  54721. const float diameter,
  54722. const Colour& colour, const float outlineThickness,
  54723. const int direction) throw()
  54724. {
  54725. if (diameter <= outlineThickness)
  54726. return;
  54727. Path p;
  54728. p.startNewSubPath (x + diameter * 0.5f, y);
  54729. p.lineTo (x + diameter, y + diameter * 0.6f);
  54730. p.lineTo (x + diameter, y + diameter);
  54731. p.lineTo (x, y + diameter);
  54732. p.lineTo (x, y + diameter * 0.6f);
  54733. p.closeSubPath();
  54734. p.applyTransform (AffineTransform::rotation (direction * (float_Pi * 0.5f), x + diameter * 0.5f, y + diameter * 0.5f));
  54735. {
  54736. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  54737. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  54738. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  54739. g.setGradientFill (cg);
  54740. g.fillPath (p);
  54741. }
  54742. ColourGradient cg (Colours::transparentBlack,
  54743. x + diameter * 0.5f, y + diameter * 0.5f,
  54744. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  54745. x - diameter * 0.2f, y + diameter * 0.5f, true);
  54746. cg.addColour (0.5, Colours::transparentBlack);
  54747. cg.addColour (0.7, Colours::black.withAlpha (0.07f * outlineThickness));
  54748. g.setGradientFill (cg);
  54749. g.fillPath (p);
  54750. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  54751. g.strokePath (p, PathStrokeType (outlineThickness));
  54752. }
  54753. void LookAndFeel::drawGlassLozenge (Graphics& g,
  54754. const float x, const float y,
  54755. const float width, const float height,
  54756. const Colour& colour,
  54757. const float outlineThickness,
  54758. const float cornerSize,
  54759. const bool flatOnLeft,
  54760. const bool flatOnRight,
  54761. const bool flatOnTop,
  54762. const bool flatOnBottom) throw()
  54763. {
  54764. if (width <= outlineThickness || height <= outlineThickness)
  54765. return;
  54766. const int intX = (int) x;
  54767. const int intY = (int) y;
  54768. const int intW = (int) width;
  54769. const int intH = (int) height;
  54770. const float cs = cornerSize < 0 ? jmin (width * 0.5f, height * 0.5f) : cornerSize;
  54771. const float edgeBlurRadius = height * 0.75f + (height - cs * 2.0f);
  54772. const int intEdge = (int) edgeBlurRadius;
  54773. Path outline;
  54774. createRoundedPath (outline, x, y, width, height, cs,
  54775. ! (flatOnLeft || flatOnTop),
  54776. ! (flatOnRight || flatOnTop),
  54777. ! (flatOnLeft || flatOnBottom),
  54778. ! (flatOnRight || flatOnBottom));
  54779. {
  54780. ColourGradient cg (colour.darker (0.2f), 0, y,
  54781. colour.darker (0.2f), 0, y + height, false);
  54782. cg.addColour (0.03, colour.withMultipliedAlpha (0.3f));
  54783. cg.addColour (0.4, colour);
  54784. cg.addColour (0.97, colour.withMultipliedAlpha (0.3f));
  54785. g.setGradientFill (cg);
  54786. g.fillPath (outline);
  54787. }
  54788. ColourGradient cg (Colours::transparentBlack, x + edgeBlurRadius, y + height * 0.5f,
  54789. colour.darker (0.2f), x, y + height * 0.5f, true);
  54790. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.5f) / edgeBlurRadius), Colours::transparentBlack);
  54791. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.25f) / edgeBlurRadius), colour.darker (0.2f).withMultipliedAlpha (0.3f));
  54792. if (! (flatOnLeft || flatOnTop || flatOnBottom))
  54793. {
  54794. g.saveState();
  54795. g.setGradientFill (cg);
  54796. g.reduceClipRegion (intX, intY, intEdge, intH);
  54797. g.fillPath (outline);
  54798. g.restoreState();
  54799. }
  54800. if (! (flatOnRight || flatOnTop || flatOnBottom))
  54801. {
  54802. cg.point1.setX (x + width - edgeBlurRadius);
  54803. cg.point2.setX (x + width);
  54804. g.saveState();
  54805. g.setGradientFill (cg);
  54806. g.reduceClipRegion (intX + intW - intEdge, intY, 2 + intEdge, intH);
  54807. g.fillPath (outline);
  54808. g.restoreState();
  54809. }
  54810. {
  54811. const float leftIndent = flatOnLeft ? 0.0f : cs * 0.4f;
  54812. const float rightIndent = flatOnRight ? 0.0f : cs * 0.4f;
  54813. Path highlight;
  54814. createRoundedPath (highlight,
  54815. x + leftIndent,
  54816. y + cs * 0.1f,
  54817. width - (leftIndent + rightIndent),
  54818. height * 0.4f, cs * 0.4f,
  54819. ! (flatOnLeft || flatOnTop),
  54820. ! (flatOnRight || flatOnTop),
  54821. ! (flatOnLeft || flatOnBottom),
  54822. ! (flatOnRight || flatOnBottom));
  54823. g.setGradientFill (ColourGradient (colour.brighter (10.0f), 0, y + height * 0.06f,
  54824. Colours::transparentWhite, 0, y + height * 0.4f, false));
  54825. g.fillPath (highlight);
  54826. }
  54827. g.setColour (colour.darker().withMultipliedAlpha (1.5f));
  54828. g.strokePath (outline, PathStrokeType (outlineThickness));
  54829. }
  54830. END_JUCE_NAMESPACE
  54831. /*** End of inlined file: juce_LookAndFeel.cpp ***/
  54832. /*** Start of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  54833. BEGIN_JUCE_NAMESPACE
  54834. OldSchoolLookAndFeel::OldSchoolLookAndFeel()
  54835. {
  54836. setColour (TextButton::buttonColourId, Colour (0xffbbbbff));
  54837. setColour (ListBox::outlineColourId, findColour (ComboBox::outlineColourId));
  54838. setColour (ScrollBar::thumbColourId, Colour (0xffbbbbdd));
  54839. setColour (ScrollBar::backgroundColourId, Colours::transparentBlack);
  54840. setColour (Slider::thumbColourId, Colours::white);
  54841. setColour (Slider::trackColourId, Colour (0x7f000000));
  54842. setColour (Slider::textBoxOutlineColourId, Colours::grey);
  54843. setColour (ProgressBar::backgroundColourId, Colours::white.withAlpha (0.6f));
  54844. setColour (ProgressBar::foregroundColourId, Colours::green.withAlpha (0.7f));
  54845. setColour (PopupMenu::backgroundColourId, Colour (0xffeef5f8));
  54846. setColour (PopupMenu::highlightedBackgroundColourId, Colour (0xbfa4c2ce));
  54847. setColour (PopupMenu::highlightedTextColourId, Colours::black);
  54848. setColour (TextEditor::focusedOutlineColourId, findColour (TextButton::buttonColourId));
  54849. scrollbarShadow.setShadowProperties (2.2f, 0.5f, 0, 0);
  54850. }
  54851. OldSchoolLookAndFeel::~OldSchoolLookAndFeel()
  54852. {
  54853. }
  54854. void OldSchoolLookAndFeel::drawButtonBackground (Graphics& g,
  54855. Button& button,
  54856. const Colour& backgroundColour,
  54857. bool isMouseOverButton,
  54858. bool isButtonDown)
  54859. {
  54860. const int width = button.getWidth();
  54861. const int height = button.getHeight();
  54862. const float indent = 2.0f;
  54863. const int cornerSize = jmin (roundToInt (width * 0.4f),
  54864. roundToInt (height * 0.4f));
  54865. Path p;
  54866. p.addRoundedRectangle (indent, indent,
  54867. width - indent * 2.0f,
  54868. height - indent * 2.0f,
  54869. (float) cornerSize);
  54870. Colour bc (backgroundColour.withMultipliedSaturation (0.3f));
  54871. if (isMouseOverButton)
  54872. {
  54873. if (isButtonDown)
  54874. bc = bc.brighter();
  54875. else if (bc.getBrightness() > 0.5f)
  54876. bc = bc.darker (0.1f);
  54877. else
  54878. bc = bc.brighter (0.1f);
  54879. }
  54880. g.setColour (bc);
  54881. g.fillPath (p);
  54882. g.setColour (bc.contrasting().withAlpha ((isMouseOverButton) ? 0.6f : 0.4f));
  54883. g.strokePath (p, PathStrokeType ((isMouseOverButton) ? 2.0f : 1.4f));
  54884. }
  54885. void OldSchoolLookAndFeel::drawTickBox (Graphics& g,
  54886. Component& /*component*/,
  54887. float x, float y, float w, float h,
  54888. const bool ticked,
  54889. const bool isEnabled,
  54890. const bool /*isMouseOverButton*/,
  54891. const bool isButtonDown)
  54892. {
  54893. Path box;
  54894. box.addRoundedRectangle (0.0f, 2.0f, 6.0f, 6.0f, 1.0f);
  54895. g.setColour (isEnabled ? Colours::blue.withAlpha (isButtonDown ? 0.3f : 0.1f)
  54896. : Colours::lightgrey.withAlpha (0.1f));
  54897. AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f).translated (x, y));
  54898. g.fillPath (box, trans);
  54899. g.setColour (Colours::black.withAlpha (0.6f));
  54900. g.strokePath (box, PathStrokeType (0.9f), trans);
  54901. if (ticked)
  54902. {
  54903. Path tick;
  54904. tick.startNewSubPath (1.5f, 3.0f);
  54905. tick.lineTo (3.0f, 6.0f);
  54906. tick.lineTo (6.0f, 0.0f);
  54907. g.setColour (isEnabled ? Colours::black : Colours::grey);
  54908. g.strokePath (tick, PathStrokeType (2.5f), trans);
  54909. }
  54910. }
  54911. void OldSchoolLookAndFeel::drawToggleButton (Graphics& g,
  54912. ToggleButton& button,
  54913. bool isMouseOverButton,
  54914. bool isButtonDown)
  54915. {
  54916. if (button.hasKeyboardFocus (true))
  54917. {
  54918. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  54919. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  54920. }
  54921. const int tickWidth = jmin (20, button.getHeight() - 4);
  54922. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  54923. (float) tickWidth, (float) tickWidth,
  54924. button.getToggleState(),
  54925. button.isEnabled(),
  54926. isMouseOverButton,
  54927. isButtonDown);
  54928. g.setColour (button.findColour (ToggleButton::textColourId));
  54929. g.setFont (jmin (15.0f, button.getHeight() * 0.6f));
  54930. if (! button.isEnabled())
  54931. g.setOpacity (0.5f);
  54932. const int textX = tickWidth + 5;
  54933. g.drawFittedText (button.getButtonText(),
  54934. textX, 4,
  54935. button.getWidth() - textX - 2, button.getHeight() - 8,
  54936. Justification::centredLeft, 10);
  54937. }
  54938. void OldSchoolLookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  54939. int width, int height,
  54940. double progress, const String& textToShow)
  54941. {
  54942. if (progress < 0 || progress >= 1.0)
  54943. {
  54944. LookAndFeel::drawProgressBar (g, progressBar, width, height, progress, textToShow);
  54945. }
  54946. else
  54947. {
  54948. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  54949. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  54950. g.fillAll (background);
  54951. g.setColour (foreground);
  54952. g.fillRect (1, 1,
  54953. jlimit (0, width - 2, roundToInt (progress * (width - 2))),
  54954. height - 2);
  54955. if (textToShow.isNotEmpty())
  54956. {
  54957. g.setColour (Colour::contrasting (background, foreground));
  54958. g.setFont (height * 0.6f);
  54959. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  54960. }
  54961. }
  54962. }
  54963. void OldSchoolLookAndFeel::drawScrollbarButton (Graphics& g,
  54964. ScrollBar& bar,
  54965. int width, int height,
  54966. int buttonDirection,
  54967. bool isScrollbarVertical,
  54968. bool isMouseOverButton,
  54969. bool isButtonDown)
  54970. {
  54971. if (isScrollbarVertical)
  54972. width -= 2;
  54973. else
  54974. height -= 2;
  54975. Path p;
  54976. if (buttonDirection == 0)
  54977. p.addTriangle (width * 0.5f, height * 0.2f,
  54978. width * 0.1f, height * 0.7f,
  54979. width * 0.9f, height * 0.7f);
  54980. else if (buttonDirection == 1)
  54981. p.addTriangle (width * 0.8f, height * 0.5f,
  54982. width * 0.3f, height * 0.1f,
  54983. width * 0.3f, height * 0.9f);
  54984. else if (buttonDirection == 2)
  54985. p.addTriangle (width * 0.5f, height * 0.8f,
  54986. width * 0.1f, height * 0.3f,
  54987. width * 0.9f, height * 0.3f);
  54988. else if (buttonDirection == 3)
  54989. p.addTriangle (width * 0.2f, height * 0.5f,
  54990. width * 0.7f, height * 0.1f,
  54991. width * 0.7f, height * 0.9f);
  54992. if (isButtonDown)
  54993. g.setColour (Colours::white);
  54994. else if (isMouseOverButton)
  54995. g.setColour (Colours::white.withAlpha (0.7f));
  54996. else
  54997. g.setColour (bar.findColour (ScrollBar::thumbColourId).withAlpha (0.5f));
  54998. g.fillPath (p);
  54999. g.setColour (Colours::black.withAlpha (0.5f));
  55000. g.strokePath (p, PathStrokeType (0.5f));
  55001. }
  55002. void OldSchoolLookAndFeel::drawScrollbar (Graphics& g,
  55003. ScrollBar& bar,
  55004. int x, int y,
  55005. int width, int height,
  55006. bool isScrollbarVertical,
  55007. int thumbStartPosition,
  55008. int thumbSize,
  55009. bool isMouseOver,
  55010. bool isMouseDown)
  55011. {
  55012. g.fillAll (bar.findColour (ScrollBar::backgroundColourId));
  55013. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  55014. .withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.15f));
  55015. if (thumbSize > 0.0f)
  55016. {
  55017. Rectangle<int> thumb;
  55018. if (isScrollbarVertical)
  55019. {
  55020. width -= 2;
  55021. g.fillRect (x + roundToInt (width * 0.35f), y,
  55022. roundToInt (width * 0.3f), height);
  55023. thumb.setBounds (x + 1, thumbStartPosition,
  55024. width - 2, thumbSize);
  55025. }
  55026. else
  55027. {
  55028. height -= 2;
  55029. g.fillRect (x, y + roundToInt (height * 0.35f),
  55030. width, roundToInt (height * 0.3f));
  55031. thumb.setBounds (thumbStartPosition, y + 1,
  55032. thumbSize, height - 2);
  55033. }
  55034. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  55035. .withAlpha ((isMouseOver || isMouseDown) ? 0.95f : 0.7f));
  55036. g.fillRect (thumb);
  55037. g.setColour (Colours::black.withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.25f));
  55038. g.drawRect (thumb.getX(), thumb.getY(), thumb.getWidth(), thumb.getHeight());
  55039. if (thumbSize > 16)
  55040. {
  55041. for (int i = 3; --i >= 0;)
  55042. {
  55043. const float linePos = thumbStartPosition + thumbSize / 2 + (i - 1) * 4.0f;
  55044. g.setColour (Colours::black.withAlpha (0.15f));
  55045. if (isScrollbarVertical)
  55046. {
  55047. g.drawLine (x + width * 0.2f, linePos, width * 0.8f, linePos);
  55048. g.setColour (Colours::white.withAlpha (0.15f));
  55049. g.drawLine (width * 0.2f, linePos - 1, width * 0.8f, linePos - 1);
  55050. }
  55051. else
  55052. {
  55053. g.drawLine (linePos, height * 0.2f, linePos, height * 0.8f);
  55054. g.setColour (Colours::white.withAlpha (0.15f));
  55055. g.drawLine (linePos - 1, height * 0.2f, linePos - 1, height * 0.8f);
  55056. }
  55057. }
  55058. }
  55059. }
  55060. }
  55061. ImageEffectFilter* OldSchoolLookAndFeel::getScrollbarEffect()
  55062. {
  55063. return &scrollbarShadow;
  55064. }
  55065. void OldSchoolLookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  55066. {
  55067. g.fillAll (findColour (PopupMenu::backgroundColourId));
  55068. g.setColour (Colours::black.withAlpha (0.6f));
  55069. g.drawRect (0, 0, width, height);
  55070. }
  55071. void OldSchoolLookAndFeel::drawMenuBarBackground (Graphics& g, int /*width*/, int /*height*/,
  55072. bool, MenuBarComponent& menuBar)
  55073. {
  55074. g.fillAll (menuBar.findColour (PopupMenu::backgroundColourId));
  55075. }
  55076. void OldSchoolLookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  55077. {
  55078. if (textEditor.isEnabled())
  55079. {
  55080. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  55081. g.drawRect (0, 0, width, height);
  55082. }
  55083. }
  55084. void OldSchoolLookAndFeel::drawComboBox (Graphics& g, int width, int height,
  55085. const bool isButtonDown,
  55086. int buttonX, int buttonY,
  55087. int buttonW, int buttonH,
  55088. ComboBox& box)
  55089. {
  55090. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  55091. g.setColour (box.findColour ((isButtonDown) ? ComboBox::buttonColourId
  55092. : ComboBox::backgroundColourId));
  55093. g.fillRect (buttonX, buttonY, buttonW, buttonH);
  55094. g.setColour (box.findColour (ComboBox::outlineColourId));
  55095. g.drawRect (0, 0, width, height);
  55096. const float arrowX = 0.2f;
  55097. const float arrowH = 0.3f;
  55098. if (box.isEnabled())
  55099. {
  55100. Path p;
  55101. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  55102. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  55103. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  55104. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  55105. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  55106. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  55107. g.setColour (box.findColour ((isButtonDown) ? ComboBox::backgroundColourId
  55108. : ComboBox::buttonColourId));
  55109. g.fillPath (p);
  55110. }
  55111. }
  55112. const Font OldSchoolLookAndFeel::getComboBoxFont (ComboBox& box)
  55113. {
  55114. Font f (jmin (15.0f, box.getHeight() * 0.85f));
  55115. f.setHorizontalScale (0.9f);
  55116. return f;
  55117. }
  55118. static void drawTriangle (Graphics& g, float x1, float y1, float x2, float y2, float x3, float y3, const Colour& fill, const Colour& outline) throw()
  55119. {
  55120. Path p;
  55121. p.addTriangle (x1, y1, x2, y2, x3, y3);
  55122. g.setColour (fill);
  55123. g.fillPath (p);
  55124. g.setColour (outline);
  55125. g.strokePath (p, PathStrokeType (0.3f));
  55126. }
  55127. void OldSchoolLookAndFeel::drawLinearSlider (Graphics& g,
  55128. int x, int y,
  55129. int w, int h,
  55130. float sliderPos,
  55131. float minSliderPos,
  55132. float maxSliderPos,
  55133. const Slider::SliderStyle style,
  55134. Slider& slider)
  55135. {
  55136. g.fillAll (slider.findColour (Slider::backgroundColourId));
  55137. if (style == Slider::LinearBar)
  55138. {
  55139. g.setColour (slider.findColour (Slider::thumbColourId));
  55140. g.fillRect (x, y, (int) sliderPos - x, h);
  55141. g.setColour (slider.findColour (Slider::textBoxTextColourId).withMultipliedAlpha (0.5f));
  55142. g.drawRect (x, y, (int) sliderPos - x, h);
  55143. }
  55144. else
  55145. {
  55146. g.setColour (slider.findColour (Slider::trackColourId)
  55147. .withMultipliedAlpha (slider.isEnabled() ? 1.0f : 0.3f));
  55148. if (slider.isHorizontal())
  55149. {
  55150. g.fillRect (x, y + roundToInt (h * 0.6f),
  55151. w, roundToInt (h * 0.2f));
  55152. }
  55153. else
  55154. {
  55155. g.fillRect (x + roundToInt (w * 0.5f - jmin (3.0f, w * 0.1f)), y,
  55156. jmin (4, roundToInt (w * 0.2f)), h);
  55157. }
  55158. float alpha = 0.35f;
  55159. if (slider.isEnabled())
  55160. alpha = slider.isMouseOverOrDragging() ? 1.0f : 0.7f;
  55161. const Colour fill (slider.findColour (Slider::thumbColourId).withAlpha (alpha));
  55162. const Colour outline (Colours::black.withAlpha (slider.isEnabled() ? 0.7f : 0.35f));
  55163. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  55164. {
  55165. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), minSliderPos,
  55166. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos - 7.0f,
  55167. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos,
  55168. fill, outline);
  55169. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), maxSliderPos,
  55170. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos,
  55171. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos + 7.0f,
  55172. fill, outline);
  55173. }
  55174. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  55175. {
  55176. drawTriangle (g, minSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  55177. minSliderPos - 7.0f, y + h * 0.9f ,
  55178. minSliderPos, y + h * 0.9f,
  55179. fill, outline);
  55180. drawTriangle (g, maxSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  55181. maxSliderPos, y + h * 0.9f,
  55182. maxSliderPos + 7.0f, y + h * 0.9f,
  55183. fill, outline);
  55184. }
  55185. if (style == Slider::LinearHorizontal || style == Slider::ThreeValueHorizontal)
  55186. {
  55187. drawTriangle (g, sliderPos, y + h * 0.9f,
  55188. sliderPos - 7.0f, y + h * 0.2f,
  55189. sliderPos + 7.0f, y + h * 0.2f,
  55190. fill, outline);
  55191. }
  55192. else if (style == Slider::LinearVertical || style == Slider::ThreeValueVertical)
  55193. {
  55194. drawTriangle (g, x + w * 0.5f - jmin (4.0f, w * 0.3f), sliderPos,
  55195. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos - 7.0f,
  55196. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos + 7.0f,
  55197. fill, outline);
  55198. }
  55199. }
  55200. }
  55201. Button* OldSchoolLookAndFeel::createSliderButton (const bool isIncrement)
  55202. {
  55203. if (isIncrement)
  55204. return new ArrowButton ("u", 0.75f, Colours::white.withAlpha (0.8f));
  55205. else
  55206. return new ArrowButton ("d", 0.25f, Colours::white.withAlpha (0.8f));
  55207. }
  55208. ImageEffectFilter* OldSchoolLookAndFeel::getSliderEffect()
  55209. {
  55210. return &scrollbarShadow;
  55211. }
  55212. int OldSchoolLookAndFeel::getSliderThumbRadius (Slider&)
  55213. {
  55214. return 8;
  55215. }
  55216. void OldSchoolLookAndFeel::drawCornerResizer (Graphics& g,
  55217. int w, int h,
  55218. bool isMouseOver,
  55219. bool isMouseDragging)
  55220. {
  55221. g.setColour ((isMouseOver || isMouseDragging) ? Colours::lightgrey
  55222. : Colours::darkgrey);
  55223. const float lineThickness = jmin (w, h) * 0.1f;
  55224. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  55225. {
  55226. g.drawLine (w * i,
  55227. h + 1.0f,
  55228. w + 1.0f,
  55229. h * i,
  55230. lineThickness);
  55231. }
  55232. }
  55233. Button* OldSchoolLookAndFeel::createDocumentWindowButton (int buttonType)
  55234. {
  55235. Path shape;
  55236. if (buttonType == DocumentWindow::closeButton)
  55237. {
  55238. shape.addLineSegment (Line<float> (0.0f, 0.0f, 1.0f, 1.0f), 0.35f);
  55239. shape.addLineSegment (Line<float> (1.0f, 0.0f, 0.0f, 1.0f), 0.35f);
  55240. ShapeButton* const b = new ShapeButton ("close",
  55241. Colour (0x7fff3333),
  55242. Colour (0xd7ff3333),
  55243. Colour (0xf7ff3333));
  55244. b->setShape (shape, true, true, true);
  55245. return b;
  55246. }
  55247. else if (buttonType == DocumentWindow::minimiseButton)
  55248. {
  55249. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), 0.25f);
  55250. DrawableButton* b = new DrawableButton ("minimise", DrawableButton::ImageFitted);
  55251. DrawablePath dp;
  55252. dp.setPath (shape);
  55253. dp.setFill (Colours::black.withAlpha (0.3f));
  55254. b->setImages (&dp);
  55255. return b;
  55256. }
  55257. else if (buttonType == DocumentWindow::maximiseButton)
  55258. {
  55259. shape.addLineSegment (Line<float> (0.5f, 0.0f, 0.5f, 1.0f), 0.25f);
  55260. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), 0.25f);
  55261. DrawableButton* b = new DrawableButton ("maximise", DrawableButton::ImageFitted);
  55262. DrawablePath dp;
  55263. dp.setPath (shape);
  55264. dp.setFill (Colours::black.withAlpha (0.3f));
  55265. b->setImages (&dp);
  55266. return b;
  55267. }
  55268. jassertfalse;
  55269. return 0;
  55270. }
  55271. void OldSchoolLookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  55272. int titleBarX,
  55273. int titleBarY,
  55274. int titleBarW,
  55275. int titleBarH,
  55276. Button* minimiseButton,
  55277. Button* maximiseButton,
  55278. Button* closeButton,
  55279. bool positionTitleBarButtonsOnLeft)
  55280. {
  55281. titleBarY += titleBarH / 8;
  55282. titleBarH -= titleBarH / 4;
  55283. const int buttonW = titleBarH;
  55284. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  55285. : titleBarX + titleBarW - buttonW - 4;
  55286. if (closeButton != 0)
  55287. {
  55288. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  55289. x += positionTitleBarButtonsOnLeft ? buttonW + buttonW / 5
  55290. : -(buttonW + buttonW / 5);
  55291. }
  55292. if (positionTitleBarButtonsOnLeft)
  55293. swapVariables (minimiseButton, maximiseButton);
  55294. if (maximiseButton != 0)
  55295. {
  55296. maximiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  55297. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  55298. }
  55299. if (minimiseButton != 0)
  55300. minimiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  55301. }
  55302. END_JUCE_NAMESPACE
  55303. /*** End of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  55304. /*** Start of inlined file: juce_MenuBarComponent.cpp ***/
  55305. BEGIN_JUCE_NAMESPACE
  55306. MenuBarComponent::MenuBarComponent (MenuBarModel* model_)
  55307. : model (0),
  55308. itemUnderMouse (-1),
  55309. currentPopupIndex (-1),
  55310. topLevelIndexClicked (0),
  55311. lastMouseX (0),
  55312. lastMouseY (0)
  55313. {
  55314. setRepaintsOnMouseActivity (true);
  55315. setWantsKeyboardFocus (false);
  55316. setMouseClickGrabsKeyboardFocus (false);
  55317. setModel (model_);
  55318. }
  55319. MenuBarComponent::~MenuBarComponent()
  55320. {
  55321. setModel (0);
  55322. Desktop::getInstance().removeGlobalMouseListener (this);
  55323. }
  55324. MenuBarModel* MenuBarComponent::getModel() const throw()
  55325. {
  55326. return model;
  55327. }
  55328. void MenuBarComponent::setModel (MenuBarModel* const newModel)
  55329. {
  55330. if (model != newModel)
  55331. {
  55332. if (model != 0)
  55333. model->removeListener (this);
  55334. model = newModel;
  55335. if (model != 0)
  55336. model->addListener (this);
  55337. repaint();
  55338. menuBarItemsChanged (0);
  55339. }
  55340. }
  55341. void MenuBarComponent::paint (Graphics& g)
  55342. {
  55343. const bool isMouseOverBar = currentPopupIndex >= 0 || itemUnderMouse >= 0 || isMouseOver();
  55344. getLookAndFeel().drawMenuBarBackground (g,
  55345. getWidth(),
  55346. getHeight(),
  55347. isMouseOverBar,
  55348. *this);
  55349. if (model != 0)
  55350. {
  55351. for (int i = 0; i < menuNames.size(); ++i)
  55352. {
  55353. g.saveState();
  55354. g.setOrigin (xPositions [i], 0);
  55355. g.reduceClipRegion (0, 0, xPositions[i + 1] - xPositions[i], getHeight());
  55356. getLookAndFeel().drawMenuBarItem (g,
  55357. xPositions[i + 1] - xPositions[i],
  55358. getHeight(),
  55359. i,
  55360. menuNames[i],
  55361. i == itemUnderMouse,
  55362. i == currentPopupIndex,
  55363. isMouseOverBar,
  55364. *this);
  55365. g.restoreState();
  55366. }
  55367. }
  55368. }
  55369. void MenuBarComponent::resized()
  55370. {
  55371. xPositions.clear();
  55372. int x = 0;
  55373. xPositions.add (x);
  55374. for (int i = 0; i < menuNames.size(); ++i)
  55375. {
  55376. x += getLookAndFeel().getMenuBarItemWidth (*this, i, menuNames[i]);
  55377. xPositions.add (x);
  55378. }
  55379. }
  55380. int MenuBarComponent::getItemAt (const int x, const int y)
  55381. {
  55382. for (int i = 0; i < xPositions.size(); ++i)
  55383. if (x >= xPositions[i] && x < xPositions[i + 1])
  55384. return reallyContains (x, y, true) ? i : -1;
  55385. return -1;
  55386. }
  55387. void MenuBarComponent::repaintMenuItem (int index)
  55388. {
  55389. if (((unsigned int) index) < (unsigned int) xPositions.size())
  55390. {
  55391. const int x1 = xPositions [index];
  55392. const int x2 = xPositions [index + 1];
  55393. repaint (x1 - 2, 0, x2 - x1 + 4, getHeight());
  55394. }
  55395. }
  55396. void MenuBarComponent::setItemUnderMouse (const int index)
  55397. {
  55398. if (itemUnderMouse != index)
  55399. {
  55400. repaintMenuItem (itemUnderMouse);
  55401. itemUnderMouse = index;
  55402. repaintMenuItem (itemUnderMouse);
  55403. }
  55404. }
  55405. void MenuBarComponent::setOpenItem (int index)
  55406. {
  55407. if (currentPopupIndex != index)
  55408. {
  55409. repaintMenuItem (currentPopupIndex);
  55410. currentPopupIndex = index;
  55411. repaintMenuItem (currentPopupIndex);
  55412. if (index >= 0)
  55413. Desktop::getInstance().addGlobalMouseListener (this);
  55414. else
  55415. Desktop::getInstance().removeGlobalMouseListener (this);
  55416. }
  55417. }
  55418. void MenuBarComponent::updateItemUnderMouse (int x, int y)
  55419. {
  55420. setItemUnderMouse (getItemAt (x, y));
  55421. }
  55422. class MenuBarComponent::AsyncCallback : public ModalComponentManager::Callback
  55423. {
  55424. public:
  55425. AsyncCallback (MenuBarComponent* const bar_, const int topLevelIndex_)
  55426. : bar (bar_), topLevelIndex (topLevelIndex_)
  55427. {
  55428. }
  55429. ~AsyncCallback() {}
  55430. void modalStateFinished (int returnValue)
  55431. {
  55432. if (bar != 0)
  55433. bar->menuDismissed (topLevelIndex, returnValue);
  55434. }
  55435. private:
  55436. Component::SafePointer<MenuBarComponent> bar;
  55437. const int topLevelIndex;
  55438. AsyncCallback (const AsyncCallback&);
  55439. AsyncCallback& operator= (const AsyncCallback&);
  55440. };
  55441. void MenuBarComponent::showMenu (int index)
  55442. {
  55443. if (index != currentPopupIndex)
  55444. {
  55445. PopupMenu::dismissAllActiveMenus();
  55446. menuBarItemsChanged (0);
  55447. setOpenItem (index);
  55448. setItemUnderMouse (index);
  55449. if (index >= 0)
  55450. {
  55451. PopupMenu m (model->getMenuForIndex (itemUnderMouse,
  55452. menuNames [itemUnderMouse]));
  55453. if (m.lookAndFeel == 0)
  55454. m.setLookAndFeel (&getLookAndFeel());
  55455. const Rectangle<int> itemPos (xPositions [index], 0, xPositions [index + 1] - xPositions [index], getHeight());
  55456. m.showMenu (itemPos + getScreenPosition(),
  55457. 0, itemPos.getWidth(), 0, 0, true, this,
  55458. new AsyncCallback (this, index));
  55459. }
  55460. }
  55461. }
  55462. void MenuBarComponent::menuDismissed (int topLevelIndex, int itemId)
  55463. {
  55464. topLevelIndexClicked = topLevelIndex;
  55465. postCommandMessage (itemId);
  55466. }
  55467. void MenuBarComponent::handleCommandMessage (int commandId)
  55468. {
  55469. const Point<int> mousePos (getMouseXYRelative());
  55470. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  55471. if (currentPopupIndex == topLevelIndexClicked)
  55472. setOpenItem (-1);
  55473. if (commandId != 0 && model != 0)
  55474. model->menuItemSelected (commandId, topLevelIndexClicked);
  55475. }
  55476. void MenuBarComponent::mouseEnter (const MouseEvent& e)
  55477. {
  55478. if (e.eventComponent == this)
  55479. updateItemUnderMouse (e.x, e.y);
  55480. }
  55481. void MenuBarComponent::mouseExit (const MouseEvent& e)
  55482. {
  55483. if (e.eventComponent == this)
  55484. updateItemUnderMouse (e.x, e.y);
  55485. }
  55486. void MenuBarComponent::mouseDown (const MouseEvent& e)
  55487. {
  55488. if (currentPopupIndex < 0)
  55489. {
  55490. const MouseEvent e2 (e.getEventRelativeTo (this));
  55491. updateItemUnderMouse (e2.x, e2.y);
  55492. currentPopupIndex = -2;
  55493. showMenu (itemUnderMouse);
  55494. }
  55495. }
  55496. void MenuBarComponent::mouseDrag (const MouseEvent& e)
  55497. {
  55498. const MouseEvent e2 (e.getEventRelativeTo (this));
  55499. const int item = getItemAt (e2.x, e2.y);
  55500. if (item >= 0)
  55501. showMenu (item);
  55502. }
  55503. void MenuBarComponent::mouseUp (const MouseEvent& e)
  55504. {
  55505. const MouseEvent e2 (e.getEventRelativeTo (this));
  55506. updateItemUnderMouse (e2.x, e2.y);
  55507. if (itemUnderMouse < 0 && getLocalBounds().contains (e2.x, e2.y))
  55508. {
  55509. setOpenItem (-1);
  55510. PopupMenu::dismissAllActiveMenus();
  55511. }
  55512. }
  55513. void MenuBarComponent::mouseMove (const MouseEvent& e)
  55514. {
  55515. const MouseEvent e2 (e.getEventRelativeTo (this));
  55516. if (lastMouseX != e2.x || lastMouseY != e2.y)
  55517. {
  55518. if (currentPopupIndex >= 0)
  55519. {
  55520. const int item = getItemAt (e2.x, e2.y);
  55521. if (item >= 0)
  55522. showMenu (item);
  55523. }
  55524. else
  55525. {
  55526. updateItemUnderMouse (e2.x, e2.y);
  55527. }
  55528. lastMouseX = e2.x;
  55529. lastMouseY = e2.y;
  55530. }
  55531. }
  55532. bool MenuBarComponent::keyPressed (const KeyPress& key)
  55533. {
  55534. bool used = false;
  55535. const int numMenus = menuNames.size();
  55536. const int currentIndex = jlimit (0, menuNames.size() - 1, currentPopupIndex);
  55537. if (key.isKeyCode (KeyPress::leftKey))
  55538. {
  55539. showMenu ((currentIndex + numMenus - 1) % numMenus);
  55540. used = true;
  55541. }
  55542. else if (key.isKeyCode (KeyPress::rightKey))
  55543. {
  55544. showMenu ((currentIndex + 1) % numMenus);
  55545. used = true;
  55546. }
  55547. return used;
  55548. }
  55549. void MenuBarComponent::menuBarItemsChanged (MenuBarModel* /*menuBarModel*/)
  55550. {
  55551. StringArray newNames;
  55552. if (model != 0)
  55553. newNames = model->getMenuBarNames();
  55554. if (newNames != menuNames)
  55555. {
  55556. menuNames = newNames;
  55557. repaint();
  55558. resized();
  55559. }
  55560. }
  55561. void MenuBarComponent::menuCommandInvoked (MenuBarModel* /*menuBarModel*/,
  55562. const ApplicationCommandTarget::InvocationInfo& info)
  55563. {
  55564. if (model == 0 || (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) != 0)
  55565. return;
  55566. for (int i = 0; i < menuNames.size(); ++i)
  55567. {
  55568. const PopupMenu menu (model->getMenuForIndex (i, menuNames [i]));
  55569. if (menu.containsCommandItem (info.commandID))
  55570. {
  55571. setItemUnderMouse (i);
  55572. startTimer (200);
  55573. break;
  55574. }
  55575. }
  55576. }
  55577. void MenuBarComponent::timerCallback()
  55578. {
  55579. stopTimer();
  55580. const Point<int> mousePos (getMouseXYRelative());
  55581. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  55582. }
  55583. END_JUCE_NAMESPACE
  55584. /*** End of inlined file: juce_MenuBarComponent.cpp ***/
  55585. /*** Start of inlined file: juce_MenuBarModel.cpp ***/
  55586. BEGIN_JUCE_NAMESPACE
  55587. MenuBarModel::MenuBarModel() throw()
  55588. : manager (0)
  55589. {
  55590. }
  55591. MenuBarModel::~MenuBarModel()
  55592. {
  55593. setApplicationCommandManagerToWatch (0);
  55594. }
  55595. void MenuBarModel::menuItemsChanged()
  55596. {
  55597. triggerAsyncUpdate();
  55598. }
  55599. void MenuBarModel::setApplicationCommandManagerToWatch (ApplicationCommandManager* const newManager) throw()
  55600. {
  55601. if (manager != newManager)
  55602. {
  55603. if (manager != 0)
  55604. manager->removeListener (this);
  55605. manager = newManager;
  55606. if (manager != 0)
  55607. manager->addListener (this);
  55608. }
  55609. }
  55610. void MenuBarModel::addListener (Listener* const newListener) throw()
  55611. {
  55612. listeners.add (newListener);
  55613. }
  55614. void MenuBarModel::removeListener (Listener* const listenerToRemove) throw()
  55615. {
  55616. // Trying to remove a listener that isn't on the list!
  55617. // If this assertion happens because this object is a dangling pointer, make sure you've not
  55618. // deleted this menu model while it's still being used by something (e.g. by a MenuBarComponent)
  55619. jassert (listeners.contains (listenerToRemove));
  55620. listeners.remove (listenerToRemove);
  55621. }
  55622. void MenuBarModel::handleAsyncUpdate()
  55623. {
  55624. listeners.call (&MenuBarModel::Listener::menuBarItemsChanged, this);
  55625. }
  55626. void MenuBarModel::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  55627. {
  55628. listeners.call (&MenuBarModel::Listener::menuCommandInvoked, this, info);
  55629. }
  55630. void MenuBarModel::applicationCommandListChanged()
  55631. {
  55632. menuItemsChanged();
  55633. }
  55634. END_JUCE_NAMESPACE
  55635. /*** End of inlined file: juce_MenuBarModel.cpp ***/
  55636. /*** Start of inlined file: juce_PopupMenu.cpp ***/
  55637. BEGIN_JUCE_NAMESPACE
  55638. class PopupMenu::Item
  55639. {
  55640. public:
  55641. Item()
  55642. : itemId (0), active (true), isSeparator (true), isTicked (false),
  55643. usesColour (false), customComp (0), commandManager (0)
  55644. {
  55645. }
  55646. Item (const int itemId_,
  55647. const String& text_,
  55648. const bool active_,
  55649. const bool isTicked_,
  55650. const Image& im,
  55651. const Colour& textColour_,
  55652. const bool usesColour_,
  55653. PopupMenuCustomComponent* const customComp_,
  55654. const PopupMenu* const subMenu_,
  55655. ApplicationCommandManager* const commandManager_)
  55656. : itemId (itemId_), text (text_), textColour (textColour_),
  55657. active (active_), isSeparator (false), isTicked (isTicked_),
  55658. usesColour (usesColour_), image (im), customComp (customComp_),
  55659. commandManager (commandManager_)
  55660. {
  55661. if (subMenu_ != 0)
  55662. subMenu = new PopupMenu (*subMenu_);
  55663. if (commandManager_ != 0 && itemId_ != 0)
  55664. {
  55665. String shortcutKey;
  55666. Array <KeyPress> keyPresses (commandManager_->getKeyMappings()
  55667. ->getKeyPressesAssignedToCommand (itemId_));
  55668. for (int i = 0; i < keyPresses.size(); ++i)
  55669. {
  55670. const String key (keyPresses.getReference(i).getTextDescription());
  55671. if (shortcutKey.isNotEmpty())
  55672. shortcutKey << ", ";
  55673. if (key.length() == 1)
  55674. shortcutKey << "shortcut: '" << key << '\'';
  55675. else
  55676. shortcutKey << key;
  55677. }
  55678. shortcutKey = shortcutKey.trim();
  55679. if (shortcutKey.isNotEmpty())
  55680. text << "<end>" << shortcutKey;
  55681. }
  55682. }
  55683. Item (const Item& other)
  55684. : itemId (other.itemId),
  55685. text (other.text),
  55686. textColour (other.textColour),
  55687. active (other.active),
  55688. isSeparator (other.isSeparator),
  55689. isTicked (other.isTicked),
  55690. usesColour (other.usesColour),
  55691. image (other.image),
  55692. customComp (other.customComp),
  55693. commandManager (other.commandManager)
  55694. {
  55695. if (other.subMenu != 0)
  55696. subMenu = new PopupMenu (*(other.subMenu));
  55697. }
  55698. ~Item()
  55699. {
  55700. customComp = 0;
  55701. }
  55702. bool canBeTriggered() const throw()
  55703. {
  55704. return active && ! (isSeparator || (subMenu != 0));
  55705. }
  55706. bool hasActiveSubMenu() const throw()
  55707. {
  55708. return active && (subMenu != 0);
  55709. }
  55710. const int itemId;
  55711. String text;
  55712. const Colour textColour;
  55713. const bool active, isSeparator, isTicked, usesColour;
  55714. Image image;
  55715. ReferenceCountedObjectPtr <PopupMenuCustomComponent> customComp;
  55716. ScopedPointer <PopupMenu> subMenu;
  55717. ApplicationCommandManager* const commandManager;
  55718. juce_UseDebuggingNewOperator
  55719. private:
  55720. Item& operator= (const Item&);
  55721. };
  55722. class PopupMenu::ItemComponent : public Component
  55723. {
  55724. public:
  55725. ItemComponent (const PopupMenu::Item& itemInfo_)
  55726. : itemInfo (itemInfo_),
  55727. isHighlighted (false)
  55728. {
  55729. if (itemInfo.customComp != 0)
  55730. addAndMakeVisible (itemInfo.customComp);
  55731. }
  55732. ~ItemComponent()
  55733. {
  55734. if (itemInfo.customComp != 0)
  55735. removeChildComponent (itemInfo.customComp);
  55736. }
  55737. void getIdealSize (int& idealWidth,
  55738. int& idealHeight,
  55739. const int standardItemHeight)
  55740. {
  55741. if (itemInfo.customComp != 0)
  55742. {
  55743. itemInfo.customComp->getIdealSize (idealWidth, idealHeight);
  55744. }
  55745. else
  55746. {
  55747. getLookAndFeel().getIdealPopupMenuItemSize (itemInfo.text,
  55748. itemInfo.isSeparator,
  55749. standardItemHeight,
  55750. idealWidth,
  55751. idealHeight);
  55752. }
  55753. }
  55754. void paint (Graphics& g)
  55755. {
  55756. if (itemInfo.customComp == 0)
  55757. {
  55758. String mainText (itemInfo.text);
  55759. String endText;
  55760. const int endIndex = mainText.indexOf ("<end>");
  55761. if (endIndex >= 0)
  55762. {
  55763. endText = mainText.substring (endIndex + 5).trim();
  55764. mainText = mainText.substring (0, endIndex);
  55765. }
  55766. getLookAndFeel()
  55767. .drawPopupMenuItem (g, getWidth(), getHeight(),
  55768. itemInfo.isSeparator,
  55769. itemInfo.active,
  55770. isHighlighted,
  55771. itemInfo.isTicked,
  55772. itemInfo.subMenu != 0,
  55773. mainText, endText,
  55774. itemInfo.image.isValid() ? &itemInfo.image : 0,
  55775. itemInfo.usesColour ? &(itemInfo.textColour) : 0);
  55776. }
  55777. }
  55778. void resized()
  55779. {
  55780. if (getNumChildComponents() > 0)
  55781. getChildComponent(0)->setBounds (2, 0, getWidth() - 4, getHeight());
  55782. }
  55783. void setHighlighted (bool shouldBeHighlighted)
  55784. {
  55785. shouldBeHighlighted = shouldBeHighlighted && itemInfo.active;
  55786. if (isHighlighted != shouldBeHighlighted)
  55787. {
  55788. isHighlighted = shouldBeHighlighted;
  55789. if (itemInfo.customComp != 0)
  55790. {
  55791. itemInfo.customComp->isHighlighted = shouldBeHighlighted;
  55792. itemInfo.customComp->repaint();
  55793. }
  55794. repaint();
  55795. }
  55796. }
  55797. PopupMenu::Item itemInfo;
  55798. juce_UseDebuggingNewOperator
  55799. private:
  55800. bool isHighlighted;
  55801. ItemComponent (const ItemComponent&);
  55802. ItemComponent& operator= (const ItemComponent&);
  55803. };
  55804. namespace PopupMenuSettings
  55805. {
  55806. static const int scrollZone = 24;
  55807. static const int borderSize = 2;
  55808. static const int timerInterval = 50;
  55809. static const int dismissCommandId = 0x6287345f;
  55810. }
  55811. class PopupMenu::Window : public Component,
  55812. private Timer
  55813. {
  55814. public:
  55815. Window()
  55816. : Component ("menu"),
  55817. owner (0),
  55818. currentChild (0),
  55819. activeSubMenu (0),
  55820. managerOfChosenCommand (0),
  55821. minimumWidth (0),
  55822. maximumNumColumns (7),
  55823. standardItemHeight (0),
  55824. isOver (false),
  55825. hasBeenOver (false),
  55826. isDown (false),
  55827. needsToScroll (false),
  55828. hideOnExit (false),
  55829. disableMouseMoves (false),
  55830. hasAnyJuceCompHadFocus (false),
  55831. numColumns (0),
  55832. contentHeight (0),
  55833. childYOffset (0),
  55834. timeEnteredCurrentChildComp (0),
  55835. scrollAcceleration (1.0)
  55836. {
  55837. menuCreationTime = lastFocused = lastScroll = Time::getMillisecondCounter();
  55838. setWantsKeyboardFocus (true);
  55839. setMouseClickGrabsKeyboardFocus (false);
  55840. setAlwaysOnTop (true);
  55841. Desktop::getInstance().addGlobalMouseListener (this);
  55842. getActiveWindows().add (this);
  55843. }
  55844. ~Window()
  55845. {
  55846. getActiveWindows().removeValue (this);
  55847. Desktop::getInstance().removeGlobalMouseListener (this);
  55848. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  55849. activeSubMenu = 0;
  55850. deleteAllChildren();
  55851. }
  55852. static Window* create (const PopupMenu& menu,
  55853. const bool dismissOnMouseUp,
  55854. Window* const owner_,
  55855. const Rectangle<int>& target,
  55856. const int minimumWidth,
  55857. const int maximumNumColumns,
  55858. const int standardItemHeight,
  55859. const bool alignToRectangle,
  55860. const int itemIdThatMustBeVisible,
  55861. ApplicationCommandManager** managerOfChosenCommand,
  55862. Component* const componentAttachedTo)
  55863. {
  55864. if (menu.items.size() > 0)
  55865. {
  55866. int totalItems = 0;
  55867. ScopedPointer <Window> mw (new Window());
  55868. mw->setLookAndFeel (menu.lookAndFeel);
  55869. mw->setWantsKeyboardFocus (false);
  55870. mw->setOpaque (mw->getLookAndFeel().findColour (PopupMenu::backgroundColourId).isOpaque() || ! Desktop::canUseSemiTransparentWindows());
  55871. mw->minimumWidth = minimumWidth;
  55872. mw->maximumNumColumns = maximumNumColumns;
  55873. mw->standardItemHeight = standardItemHeight;
  55874. mw->dismissOnMouseUp = dismissOnMouseUp;
  55875. for (int i = 0; i < menu.items.size(); ++i)
  55876. {
  55877. PopupMenu::Item* const item = menu.items.getUnchecked(i);
  55878. mw->addItem (*item);
  55879. ++totalItems;
  55880. }
  55881. if (totalItems > 0)
  55882. {
  55883. mw->owner = owner_;
  55884. mw->managerOfChosenCommand = managerOfChosenCommand;
  55885. mw->componentAttachedTo = componentAttachedTo;
  55886. mw->componentAttachedToOriginal = componentAttachedTo;
  55887. mw->calculateWindowPos (target, alignToRectangle);
  55888. mw->setTopLeftPosition (mw->windowPos.getX(),
  55889. mw->windowPos.getY());
  55890. mw->updateYPositions();
  55891. if (itemIdThatMustBeVisible != 0)
  55892. {
  55893. const int y = target.getY() - mw->windowPos.getY();
  55894. mw->ensureItemIsVisible (itemIdThatMustBeVisible,
  55895. (((unsigned int) y) < (unsigned int) mw->windowPos.getHeight()) ? y : -1);
  55896. }
  55897. mw->resizeToBestWindowPos();
  55898. mw->addToDesktop (ComponentPeer::windowIsTemporary
  55899. | mw->getLookAndFeel().getMenuWindowFlags());
  55900. return mw.release();
  55901. }
  55902. }
  55903. return 0;
  55904. }
  55905. void paint (Graphics& g)
  55906. {
  55907. if (isOpaque())
  55908. g.fillAll (Colours::white);
  55909. getLookAndFeel().drawPopupMenuBackground (g, getWidth(), getHeight());
  55910. }
  55911. void paintOverChildren (Graphics& g)
  55912. {
  55913. if (isScrolling())
  55914. {
  55915. LookAndFeel& lf = getLookAndFeel();
  55916. if (isScrollZoneActive (false))
  55917. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, true);
  55918. if (isScrollZoneActive (true))
  55919. {
  55920. g.setOrigin (0, getHeight() - PopupMenuSettings::scrollZone);
  55921. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, false);
  55922. }
  55923. }
  55924. }
  55925. bool isScrollZoneActive (bool bottomOne) const
  55926. {
  55927. return isScrolling()
  55928. && (bottomOne
  55929. ? childYOffset < contentHeight - windowPos.getHeight()
  55930. : childYOffset > 0);
  55931. }
  55932. void addItem (const PopupMenu::Item& item)
  55933. {
  55934. PopupMenu::ItemComponent* const mic = new PopupMenu::ItemComponent (item);
  55935. addAndMakeVisible (mic);
  55936. int itemW = 80;
  55937. int itemH = 16;
  55938. mic->getIdealSize (itemW, itemH, standardItemHeight);
  55939. mic->setSize (itemW, jlimit (2, 600, itemH));
  55940. mic->addMouseListener (this, false);
  55941. }
  55942. // hide this and all sub-comps
  55943. void hide (const PopupMenu::Item* const item)
  55944. {
  55945. if (isVisible())
  55946. {
  55947. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  55948. activeSubMenu = 0;
  55949. currentChild = 0;
  55950. exitModalState (item != 0 ? item->itemId : 0);
  55951. setVisible (false);
  55952. if (item != 0
  55953. && item->commandManager != 0
  55954. && item->itemId != 0)
  55955. {
  55956. *managerOfChosenCommand = item->commandManager;
  55957. }
  55958. }
  55959. }
  55960. void dismissMenu (const PopupMenu::Item* const item)
  55961. {
  55962. if (owner != 0)
  55963. {
  55964. owner->dismissMenu (item);
  55965. }
  55966. else
  55967. {
  55968. if (item != 0)
  55969. {
  55970. // need a copy of this on the stack as the one passed in will get deleted during this call
  55971. const PopupMenu::Item mi (*item);
  55972. hide (&mi);
  55973. }
  55974. else
  55975. {
  55976. hide (0);
  55977. }
  55978. }
  55979. }
  55980. void mouseMove (const MouseEvent&)
  55981. {
  55982. timerCallback();
  55983. }
  55984. void mouseDown (const MouseEvent&)
  55985. {
  55986. timerCallback();
  55987. }
  55988. void mouseDrag (const MouseEvent&)
  55989. {
  55990. timerCallback();
  55991. }
  55992. void mouseUp (const MouseEvent&)
  55993. {
  55994. timerCallback();
  55995. }
  55996. void mouseWheelMove (const MouseEvent&, float /*amountX*/, float amountY)
  55997. {
  55998. alterChildYPos (roundToInt (-10.0f * amountY * PopupMenuSettings::scrollZone));
  55999. lastMouse = Point<int> (-1, -1);
  56000. }
  56001. bool keyPressed (const KeyPress& key)
  56002. {
  56003. if (key.isKeyCode (KeyPress::downKey))
  56004. {
  56005. selectNextItem (1);
  56006. }
  56007. else if (key.isKeyCode (KeyPress::upKey))
  56008. {
  56009. selectNextItem (-1);
  56010. }
  56011. else if (key.isKeyCode (KeyPress::leftKey))
  56012. {
  56013. if (owner != 0)
  56014. {
  56015. Component::SafePointer<Window> parentWindow (owner);
  56016. PopupMenu::ItemComponent* currentChildOfParent = parentWindow->currentChild;
  56017. hide (0);
  56018. if (parentWindow != 0)
  56019. parentWindow->setCurrentlyHighlightedChild (currentChildOfParent);
  56020. disableTimerUntilMouseMoves();
  56021. }
  56022. else if (componentAttachedTo != 0)
  56023. {
  56024. componentAttachedTo->keyPressed (key);
  56025. }
  56026. }
  56027. else if (key.isKeyCode (KeyPress::rightKey))
  56028. {
  56029. disableTimerUntilMouseMoves();
  56030. if (showSubMenuFor (currentChild))
  56031. {
  56032. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  56033. if (activeSubMenu != 0 && activeSubMenu->isVisible())
  56034. activeSubMenu->selectNextItem (1);
  56035. }
  56036. else if (componentAttachedTo != 0)
  56037. {
  56038. componentAttachedTo->keyPressed (key);
  56039. }
  56040. }
  56041. else if (key.isKeyCode (KeyPress::returnKey))
  56042. {
  56043. triggerCurrentlyHighlightedItem();
  56044. }
  56045. else if (key.isKeyCode (KeyPress::escapeKey))
  56046. {
  56047. dismissMenu (0);
  56048. }
  56049. else
  56050. {
  56051. return false;
  56052. }
  56053. return true;
  56054. }
  56055. void inputAttemptWhenModal()
  56056. {
  56057. Component::SafePointer<Component> deletionChecker (this);
  56058. timerCallback();
  56059. if (deletionChecker != 0 && ! isOverAnyMenu())
  56060. {
  56061. if (componentAttachedTo != 0)
  56062. {
  56063. // we want to dismiss the menu, but if we do it synchronously, then
  56064. // the mouse-click will be allowed to pass through. That's good, except
  56065. // when the user clicks on the button that orginally popped the menu up,
  56066. // as they'll expect the menu to go away, and in fact it'll just
  56067. // come back. So only dismiss synchronously if they're not on the original
  56068. // comp that we're attached to.
  56069. const Point<int> mousePos (componentAttachedTo->getMouseXYRelative());
  56070. if (componentAttachedTo->reallyContains (mousePos.getX(), mousePos.getY(), true))
  56071. {
  56072. postCommandMessage (PopupMenuSettings::dismissCommandId); // dismiss asynchrounously
  56073. return;
  56074. }
  56075. }
  56076. dismissMenu (0);
  56077. }
  56078. }
  56079. void handleCommandMessage (int commandId)
  56080. {
  56081. Component::handleCommandMessage (commandId);
  56082. if (commandId == PopupMenuSettings::dismissCommandId)
  56083. dismissMenu (0);
  56084. }
  56085. void timerCallback()
  56086. {
  56087. if (! isVisible())
  56088. return;
  56089. if (componentAttachedTo != componentAttachedToOriginal)
  56090. {
  56091. dismissMenu (0);
  56092. return;
  56093. }
  56094. Window* currentlyModalWindow = dynamic_cast <Window*> (Component::getCurrentlyModalComponent());
  56095. if (currentlyModalWindow != 0 && ! treeContains (currentlyModalWindow))
  56096. return;
  56097. startTimer (PopupMenuSettings::timerInterval); // do this in case it was called from a mouse
  56098. // move rather than a real timer callback
  56099. const Point<int> globalMousePos (Desktop::getMousePosition());
  56100. const Point<int> localMousePos (globalPositionToRelative (globalMousePos));
  56101. const uint32 now = Time::getMillisecondCounter();
  56102. if (now > timeEnteredCurrentChildComp + 100
  56103. && reallyContains (localMousePos.getX(), localMousePos.getY(), true)
  56104. && currentChild->isValidComponent()
  56105. && (! disableMouseMoves)
  56106. && ! (activeSubMenu != 0 && activeSubMenu->isVisible()))
  56107. {
  56108. showSubMenuFor (currentChild);
  56109. }
  56110. if (globalMousePos != lastMouse || now > lastMouseMoveTime + 350)
  56111. {
  56112. highlightItemUnderMouse (globalMousePos, localMousePos);
  56113. }
  56114. bool overScrollArea = false;
  56115. if (isScrolling()
  56116. && (isOver || (isDown && ((unsigned int) localMousePos.getX()) < (unsigned int) getWidth()))
  56117. && ((isScrollZoneActive (false) && localMousePos.getY() < PopupMenuSettings::scrollZone)
  56118. || (isScrollZoneActive (true) && localMousePos.getY() > getHeight() - PopupMenuSettings::scrollZone)))
  56119. {
  56120. if (now > lastScroll + 20)
  56121. {
  56122. scrollAcceleration = jmin (4.0, scrollAcceleration * 1.04);
  56123. int amount = 0;
  56124. for (int i = 0; i < getNumChildComponents() && amount == 0; ++i)
  56125. amount = ((int) scrollAcceleration) * getChildComponent (i)->getHeight();
  56126. alterChildYPos (localMousePos.getY() < PopupMenuSettings::scrollZone ? -amount : amount);
  56127. lastScroll = now;
  56128. }
  56129. overScrollArea = true;
  56130. lastMouse = Point<int> (-1, -1); // trigger a mouse-move
  56131. }
  56132. else
  56133. {
  56134. scrollAcceleration = 1.0;
  56135. }
  56136. const bool wasDown = isDown;
  56137. bool isOverAny = isOverAnyMenu();
  56138. if (hideOnExit && hasBeenOver && (! isOverAny) && activeSubMenu != 0)
  56139. {
  56140. activeSubMenu->updateMouseOverStatus (globalMousePos);
  56141. isOverAny = isOverAnyMenu();
  56142. }
  56143. if (hideOnExit && hasBeenOver && ! isOverAny)
  56144. {
  56145. hide (0);
  56146. }
  56147. else
  56148. {
  56149. isDown = hasBeenOver
  56150. && (ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown()
  56151. || ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown());
  56152. bool anyFocused = Process::isForegroundProcess();
  56153. if (anyFocused && Component::getCurrentlyFocusedComponent() == 0)
  56154. {
  56155. // because no component at all may have focus, our test here will
  56156. // only be triggered when something has focus and then loses it.
  56157. anyFocused = ! hasAnyJuceCompHadFocus;
  56158. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  56159. {
  56160. if (ComponentPeer::getPeer (i)->isFocused())
  56161. {
  56162. anyFocused = true;
  56163. hasAnyJuceCompHadFocus = true;
  56164. break;
  56165. }
  56166. }
  56167. }
  56168. if (! anyFocused)
  56169. {
  56170. if (now > lastFocused + 10)
  56171. {
  56172. wasHiddenBecauseOfAppChange() = true;
  56173. dismissMenu (0);
  56174. return; // may have been deleted by the previous call..
  56175. }
  56176. }
  56177. else if (wasDown && now > menuCreationTime + 250
  56178. && ! (isDown || overScrollArea))
  56179. {
  56180. isOver = reallyContains (localMousePos.getX(), localMousePos.getY(), true);
  56181. if (isOver)
  56182. {
  56183. triggerCurrentlyHighlightedItem();
  56184. }
  56185. else if ((hasBeenOver || ! dismissOnMouseUp) && ! isOverAny)
  56186. {
  56187. dismissMenu (0);
  56188. }
  56189. return; // may have been deleted by the previous calls..
  56190. }
  56191. else
  56192. {
  56193. lastFocused = now;
  56194. }
  56195. }
  56196. }
  56197. static Array<Window*>& getActiveWindows()
  56198. {
  56199. static Array<Window*> activeMenuWindows;
  56200. return activeMenuWindows;
  56201. }
  56202. static bool& wasHiddenBecauseOfAppChange() throw()
  56203. {
  56204. static bool b = false;
  56205. return b;
  56206. }
  56207. juce_UseDebuggingNewOperator
  56208. private:
  56209. Window* owner;
  56210. PopupMenu::ItemComponent* currentChild;
  56211. ScopedPointer <Window> activeSubMenu;
  56212. ApplicationCommandManager** managerOfChosenCommand;
  56213. Component::SafePointer<Component> componentAttachedTo;
  56214. Component* componentAttachedToOriginal;
  56215. Rectangle<int> windowPos;
  56216. Point<int> lastMouse;
  56217. int minimumWidth, maximumNumColumns, standardItemHeight;
  56218. bool isOver, hasBeenOver, isDown, needsToScroll;
  56219. bool dismissOnMouseUp, hideOnExit, disableMouseMoves, hasAnyJuceCompHadFocus;
  56220. int numColumns, contentHeight, childYOffset;
  56221. Array <int> columnWidths;
  56222. uint32 menuCreationTime, lastFocused, lastScroll, lastMouseMoveTime, timeEnteredCurrentChildComp;
  56223. double scrollAcceleration;
  56224. bool overlaps (const Rectangle<int>& r) const
  56225. {
  56226. return r.intersects (getBounds())
  56227. || (owner != 0 && owner->overlaps (r));
  56228. }
  56229. bool isOverAnyMenu() const
  56230. {
  56231. return (owner != 0) ? owner->isOverAnyMenu()
  56232. : isOverChildren();
  56233. }
  56234. bool isOverChildren() const
  56235. {
  56236. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  56237. return isVisible()
  56238. && (isOver || (activeSubMenu != 0 && activeSubMenu->isOverChildren()));
  56239. }
  56240. void updateMouseOverStatus (const Point<int>& globalMousePos)
  56241. {
  56242. const Point<int> relPos (globalPositionToRelative (globalMousePos));
  56243. isOver = reallyContains (relPos.getX(), relPos.getY(), true);
  56244. if (activeSubMenu != 0)
  56245. activeSubMenu->updateMouseOverStatus (globalMousePos);
  56246. }
  56247. bool treeContains (const Window* const window) const throw()
  56248. {
  56249. const Window* mw = this;
  56250. while (mw->owner != 0)
  56251. mw = mw->owner;
  56252. while (mw != 0)
  56253. {
  56254. if (mw == window)
  56255. return true;
  56256. mw = mw->activeSubMenu;
  56257. }
  56258. return false;
  56259. }
  56260. void calculateWindowPos (const Rectangle<int>& target, const bool alignToRectangle)
  56261. {
  56262. const Rectangle<int> mon (Desktop::getInstance()
  56263. .getMonitorAreaContaining (target.getCentre(),
  56264. #if JUCE_MAC
  56265. true));
  56266. #else
  56267. false)); // on windows, don't stop the menu overlapping the taskbar
  56268. #endif
  56269. int x, y, widthToUse, heightToUse;
  56270. layoutMenuItems (mon.getWidth() - 24, widthToUse, heightToUse);
  56271. if (alignToRectangle)
  56272. {
  56273. x = target.getX();
  56274. const int spaceUnder = mon.getHeight() - (target.getBottom() - mon.getY());
  56275. const int spaceOver = target.getY() - mon.getY();
  56276. if (heightToUse < spaceUnder - 30 || spaceUnder >= spaceOver)
  56277. y = target.getBottom();
  56278. else
  56279. y = target.getY() - heightToUse;
  56280. }
  56281. else
  56282. {
  56283. bool tendTowardsRight = target.getCentreX() < mon.getCentreX();
  56284. if (owner != 0)
  56285. {
  56286. if (owner->owner != 0)
  56287. {
  56288. const bool ownerGoingRight = (owner->getX() + owner->getWidth() / 2
  56289. > owner->owner->getX() + owner->owner->getWidth() / 2);
  56290. if (ownerGoingRight && target.getRight() + widthToUse < mon.getRight() - 4)
  56291. tendTowardsRight = true;
  56292. else if ((! ownerGoingRight) && target.getX() > widthToUse + 4)
  56293. tendTowardsRight = false;
  56294. }
  56295. else if (target.getRight() + widthToUse < mon.getRight() - 32)
  56296. {
  56297. tendTowardsRight = true;
  56298. }
  56299. }
  56300. const int biggestSpace = jmax (mon.getRight() - target.getRight(),
  56301. target.getX() - mon.getX()) - 32;
  56302. if (biggestSpace < widthToUse)
  56303. {
  56304. layoutMenuItems (biggestSpace + target.getWidth() / 3, widthToUse, heightToUse);
  56305. if (numColumns > 1)
  56306. layoutMenuItems (biggestSpace - 4, widthToUse, heightToUse);
  56307. tendTowardsRight = (mon.getRight() - target.getRight()) >= (target.getX() - mon.getX());
  56308. }
  56309. if (tendTowardsRight)
  56310. x = jmin (mon.getRight() - widthToUse - 4, target.getRight());
  56311. else
  56312. x = jmax (mon.getX() + 4, target.getX() - widthToUse);
  56313. y = target.getY();
  56314. if (target.getCentreY() > mon.getCentreY())
  56315. y = jmax (mon.getY(), target.getBottom() - heightToUse);
  56316. }
  56317. x = jmax (mon.getX() + 1, jmin (mon.getRight() - (widthToUse + 6), x));
  56318. y = jmax (mon.getY() + 1, jmin (mon.getBottom() - (heightToUse + 6), y));
  56319. windowPos.setBounds (x, y, widthToUse, heightToUse);
  56320. // sets this flag if it's big enough to obscure any of its parent menus
  56321. hideOnExit = (owner != 0)
  56322. && owner->windowPos.intersects (windowPos.expanded (-4, -4));
  56323. }
  56324. void layoutMenuItems (const int maxMenuW, int& width, int& height)
  56325. {
  56326. numColumns = 0;
  56327. contentHeight = 0;
  56328. const int maxMenuH = getParentHeight() - 24;
  56329. int totalW;
  56330. do
  56331. {
  56332. ++numColumns;
  56333. totalW = workOutBestSize (maxMenuW);
  56334. if (totalW > maxMenuW)
  56335. {
  56336. numColumns = jmax (1, numColumns - 1);
  56337. totalW = workOutBestSize (maxMenuW); // to update col widths
  56338. break;
  56339. }
  56340. else if (totalW > maxMenuW / 2 || contentHeight < maxMenuH)
  56341. {
  56342. break;
  56343. }
  56344. } while (numColumns < maximumNumColumns);
  56345. const int actualH = jmin (contentHeight, maxMenuH);
  56346. needsToScroll = contentHeight > actualH;
  56347. width = updateYPositions();
  56348. height = actualH + PopupMenuSettings::borderSize * 2;
  56349. }
  56350. int workOutBestSize (const int maxMenuW)
  56351. {
  56352. int totalW = 0;
  56353. contentHeight = 0;
  56354. int childNum = 0;
  56355. for (int col = 0; col < numColumns; ++col)
  56356. {
  56357. int i, colW = 50, colH = 0;
  56358. const int numChildren = jmin (getNumChildComponents() - childNum,
  56359. (getNumChildComponents() + numColumns - 1) / numColumns);
  56360. for (i = numChildren; --i >= 0;)
  56361. {
  56362. colW = jmax (colW, getChildComponent (childNum + i)->getWidth());
  56363. colH += getChildComponent (childNum + i)->getHeight();
  56364. }
  56365. colW = jmin (maxMenuW / jmax (1, numColumns - 2), colW + PopupMenuSettings::borderSize * 2);
  56366. columnWidths.set (col, colW);
  56367. totalW += colW;
  56368. contentHeight = jmax (contentHeight, colH);
  56369. childNum += numChildren;
  56370. }
  56371. if (totalW < minimumWidth)
  56372. {
  56373. totalW = minimumWidth;
  56374. for (int col = 0; col < numColumns; ++col)
  56375. columnWidths.set (0, totalW / numColumns);
  56376. }
  56377. return totalW;
  56378. }
  56379. void ensureItemIsVisible (const int itemId, int wantedY)
  56380. {
  56381. jassert (itemId != 0)
  56382. for (int i = getNumChildComponents(); --i >= 0;)
  56383. {
  56384. PopupMenu::ItemComponent* const m = static_cast <PopupMenu::ItemComponent*> (getChildComponent (i));
  56385. if (m != 0
  56386. && m->itemInfo.itemId == itemId
  56387. && windowPos.getHeight() > PopupMenuSettings::scrollZone * 4)
  56388. {
  56389. const int currentY = m->getY();
  56390. if (wantedY > 0 || currentY < 0 || m->getBottom() > windowPos.getHeight())
  56391. {
  56392. if (wantedY < 0)
  56393. wantedY = jlimit (PopupMenuSettings::scrollZone,
  56394. jmax (PopupMenuSettings::scrollZone,
  56395. windowPos.getHeight() - (PopupMenuSettings::scrollZone + m->getHeight())),
  56396. currentY);
  56397. const Rectangle<int> mon (Desktop::getInstance().getMonitorAreaContaining (windowPos.getPosition(), true));
  56398. int deltaY = wantedY - currentY;
  56399. windowPos.setSize (jmin (windowPos.getWidth(), mon.getWidth()),
  56400. jmin (windowPos.getHeight(), mon.getHeight()));
  56401. const int newY = jlimit (mon.getY(),
  56402. mon.getBottom() - windowPos.getHeight(),
  56403. windowPos.getY() + deltaY);
  56404. deltaY -= newY - windowPos.getY();
  56405. childYOffset -= deltaY;
  56406. windowPos.setPosition (windowPos.getX(), newY);
  56407. updateYPositions();
  56408. }
  56409. break;
  56410. }
  56411. }
  56412. }
  56413. void resizeToBestWindowPos()
  56414. {
  56415. Rectangle<int> r (windowPos);
  56416. if (childYOffset < 0)
  56417. {
  56418. r.setBounds (r.getX(), r.getY() - childYOffset,
  56419. r.getWidth(), r.getHeight() + childYOffset);
  56420. }
  56421. else if (childYOffset > 0)
  56422. {
  56423. const int spaceAtBottom = r.getHeight() - (contentHeight - childYOffset);
  56424. if (spaceAtBottom > 0)
  56425. r.setSize (r.getWidth(), r.getHeight() - spaceAtBottom);
  56426. }
  56427. setBounds (r);
  56428. updateYPositions();
  56429. }
  56430. void alterChildYPos (const int delta)
  56431. {
  56432. if (isScrolling())
  56433. {
  56434. childYOffset += delta;
  56435. if (delta < 0)
  56436. {
  56437. childYOffset = jmax (childYOffset, 0);
  56438. }
  56439. else if (delta > 0)
  56440. {
  56441. childYOffset = jmin (childYOffset,
  56442. contentHeight - windowPos.getHeight() + PopupMenuSettings::borderSize);
  56443. }
  56444. updateYPositions();
  56445. }
  56446. else
  56447. {
  56448. childYOffset = 0;
  56449. }
  56450. resizeToBestWindowPos();
  56451. repaint();
  56452. }
  56453. int updateYPositions()
  56454. {
  56455. int x = 0;
  56456. int childNum = 0;
  56457. for (int col = 0; col < numColumns; ++col)
  56458. {
  56459. const int numChildren = jmin (getNumChildComponents() - childNum,
  56460. (getNumChildComponents() + numColumns - 1) / numColumns);
  56461. const int colW = columnWidths [col];
  56462. int y = PopupMenuSettings::borderSize - (childYOffset + (getY() - windowPos.getY()));
  56463. for (int i = 0; i < numChildren; ++i)
  56464. {
  56465. Component* const c = getChildComponent (childNum + i);
  56466. c->setBounds (x, y, colW, c->getHeight());
  56467. y += c->getHeight();
  56468. }
  56469. x += colW;
  56470. childNum += numChildren;
  56471. }
  56472. return x;
  56473. }
  56474. bool isScrolling() const throw()
  56475. {
  56476. return childYOffset != 0 || needsToScroll;
  56477. }
  56478. void setCurrentlyHighlightedChild (PopupMenu::ItemComponent* const child)
  56479. {
  56480. if (currentChild->isValidComponent())
  56481. currentChild->setHighlighted (false);
  56482. currentChild = child;
  56483. if (currentChild != 0)
  56484. {
  56485. currentChild->setHighlighted (true);
  56486. timeEnteredCurrentChildComp = Time::getApproximateMillisecondCounter();
  56487. }
  56488. }
  56489. bool showSubMenuFor (PopupMenu::ItemComponent* const childComp)
  56490. {
  56491. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  56492. activeSubMenu = 0;
  56493. if (childComp->isValidComponent() && childComp->itemInfo.hasActiveSubMenu())
  56494. {
  56495. activeSubMenu = Window::create (*(childComp->itemInfo.subMenu),
  56496. dismissOnMouseUp,
  56497. this,
  56498. childComp->getScreenBounds(),
  56499. 0, maximumNumColumns,
  56500. standardItemHeight,
  56501. false, 0, managerOfChosenCommand,
  56502. componentAttachedTo);
  56503. if (activeSubMenu != 0)
  56504. {
  56505. activeSubMenu->setVisible (true);
  56506. activeSubMenu->enterModalState (false);
  56507. activeSubMenu->toFront (false);
  56508. return true;
  56509. }
  56510. }
  56511. return false;
  56512. }
  56513. void highlightItemUnderMouse (const Point<int>& globalMousePos, const Point<int>& localMousePos)
  56514. {
  56515. isOver = reallyContains (localMousePos.getX(), localMousePos.getY(), true);
  56516. if (isOver)
  56517. hasBeenOver = true;
  56518. if (lastMouse.getDistanceFrom (globalMousePos) > 2)
  56519. {
  56520. lastMouseMoveTime = Time::getApproximateMillisecondCounter();
  56521. if (disableMouseMoves && isOver)
  56522. disableMouseMoves = false;
  56523. }
  56524. if (disableMouseMoves || (activeSubMenu != 0 && activeSubMenu->isOverChildren()))
  56525. return;
  56526. bool isMovingTowardsMenu = false;
  56527. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent())
  56528. if (isOver && (activeSubMenu != 0) && globalMousePos != lastMouse)
  56529. {
  56530. // try to intelligently guess whether the user is moving the mouse towards a currently-open
  56531. // submenu. To do this, look at whether the mouse stays inside a triangular region that
  56532. // extends from the last mouse pos to the submenu's rectangle..
  56533. float subX = (float) activeSubMenu->getScreenX();
  56534. if (activeSubMenu->getX() > getX())
  56535. {
  56536. lastMouse -= Point<int> (2, 0); // to enlarge the triangle a bit, in case the mouse only moves a couple of pixels
  56537. }
  56538. else
  56539. {
  56540. lastMouse += Point<int> (2, 0);
  56541. subX += activeSubMenu->getWidth();
  56542. }
  56543. Path areaTowardsSubMenu;
  56544. areaTowardsSubMenu.addTriangle ((float) lastMouse.getX(),
  56545. (float) lastMouse.getY(),
  56546. subX,
  56547. (float) activeSubMenu->getScreenY(),
  56548. subX,
  56549. (float) (activeSubMenu->getScreenY() + activeSubMenu->getHeight()));
  56550. isMovingTowardsMenu = areaTowardsSubMenu.contains ((float) globalMousePos.getX(), (float) globalMousePos.getY());
  56551. }
  56552. lastMouse = globalMousePos;
  56553. if (! isMovingTowardsMenu)
  56554. {
  56555. Component* c = getComponentAt (localMousePos.getX(), localMousePos.getY());
  56556. if (c == this)
  56557. c = 0;
  56558. PopupMenu::ItemComponent* mic = dynamic_cast <PopupMenu::ItemComponent*> (c);
  56559. if (mic == 0 && c != 0)
  56560. mic = c->findParentComponentOfClass ((PopupMenu::ItemComponent*) 0);
  56561. if (mic != currentChild
  56562. && (isOver || (activeSubMenu == 0) || ! activeSubMenu->isVisible()))
  56563. {
  56564. if (isOver && (c != 0) && (activeSubMenu != 0))
  56565. {
  56566. activeSubMenu->hide (0);
  56567. }
  56568. if (! isOver)
  56569. mic = 0;
  56570. setCurrentlyHighlightedChild (mic);
  56571. }
  56572. }
  56573. }
  56574. void triggerCurrentlyHighlightedItem()
  56575. {
  56576. if (currentChild->isValidComponent()
  56577. && currentChild->itemInfo.canBeTriggered()
  56578. && (currentChild->itemInfo.customComp == 0
  56579. || currentChild->itemInfo.customComp->isTriggeredAutomatically))
  56580. {
  56581. dismissMenu (&currentChild->itemInfo);
  56582. }
  56583. }
  56584. void selectNextItem (const int delta)
  56585. {
  56586. disableTimerUntilMouseMoves();
  56587. PopupMenu::ItemComponent* mic = 0;
  56588. bool wasLastOne = (currentChild == 0);
  56589. const int numItems = getNumChildComponents();
  56590. for (int i = 0; i < numItems + 1; ++i)
  56591. {
  56592. int index = (delta > 0) ? i : (numItems - 1 - i);
  56593. index = (index + numItems) % numItems;
  56594. mic = dynamic_cast <PopupMenu::ItemComponent*> (getChildComponent (index));
  56595. if (mic != 0 && (mic->itemInfo.canBeTriggered() || mic->itemInfo.hasActiveSubMenu())
  56596. && wasLastOne)
  56597. break;
  56598. if (mic == currentChild)
  56599. wasLastOne = true;
  56600. }
  56601. setCurrentlyHighlightedChild (mic);
  56602. }
  56603. void disableTimerUntilMouseMoves()
  56604. {
  56605. disableMouseMoves = true;
  56606. if (owner != 0)
  56607. owner->disableTimerUntilMouseMoves();
  56608. }
  56609. Window (const Window&);
  56610. Window& operator= (const Window&);
  56611. };
  56612. PopupMenu::PopupMenu()
  56613. : lookAndFeel (0),
  56614. separatorPending (false)
  56615. {
  56616. }
  56617. PopupMenu::PopupMenu (const PopupMenu& other)
  56618. : lookAndFeel (other.lookAndFeel),
  56619. separatorPending (false)
  56620. {
  56621. items.addCopiesOf (other.items);
  56622. }
  56623. PopupMenu& PopupMenu::operator= (const PopupMenu& other)
  56624. {
  56625. if (this != &other)
  56626. {
  56627. lookAndFeel = other.lookAndFeel;
  56628. clear();
  56629. items.addCopiesOf (other.items);
  56630. }
  56631. return *this;
  56632. }
  56633. PopupMenu::~PopupMenu()
  56634. {
  56635. clear();
  56636. }
  56637. void PopupMenu::clear()
  56638. {
  56639. items.clear();
  56640. separatorPending = false;
  56641. }
  56642. void PopupMenu::addSeparatorIfPending()
  56643. {
  56644. if (separatorPending)
  56645. {
  56646. separatorPending = false;
  56647. if (items.size() > 0)
  56648. items.add (new Item());
  56649. }
  56650. }
  56651. void PopupMenu::addItem (const int itemResultId,
  56652. const String& itemText,
  56653. const bool isActive,
  56654. const bool isTicked,
  56655. const Image& iconToUse)
  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, itemText, isActive, isTicked, iconToUse,
  56662. Colours::black, false, 0, 0, 0));
  56663. }
  56664. void PopupMenu::addCommandItem (ApplicationCommandManager* commandManager,
  56665. const int commandID,
  56666. const String& displayName)
  56667. {
  56668. jassert (commandManager != 0 && commandID != 0);
  56669. const ApplicationCommandInfo* const registeredInfo = commandManager->getCommandForID (commandID);
  56670. if (registeredInfo != 0)
  56671. {
  56672. ApplicationCommandInfo info (*registeredInfo);
  56673. ApplicationCommandTarget* const target = commandManager->getTargetForCommand (commandID, info);
  56674. addSeparatorIfPending();
  56675. items.add (new Item (commandID,
  56676. displayName.isNotEmpty() ? displayName
  56677. : info.shortName,
  56678. target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0,
  56679. (info.flags & ApplicationCommandInfo::isTicked) != 0,
  56680. Image::null,
  56681. Colours::black,
  56682. false,
  56683. 0, 0,
  56684. commandManager));
  56685. }
  56686. }
  56687. void PopupMenu::addColouredItem (const int itemResultId,
  56688. const String& itemText,
  56689. const Colour& itemTextColour,
  56690. const bool isActive,
  56691. const bool isTicked,
  56692. const Image& iconToUse)
  56693. {
  56694. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56695. // didn't pick anything, so you shouldn't use it as the id
  56696. // for an item..
  56697. addSeparatorIfPending();
  56698. items.add (new Item (itemResultId, itemText, isActive, isTicked, iconToUse,
  56699. itemTextColour, true, 0, 0, 0));
  56700. }
  56701. void PopupMenu::addCustomItem (const int itemResultId,
  56702. PopupMenuCustomComponent* const customComponent)
  56703. {
  56704. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56705. // didn't pick anything, so you shouldn't use it as the id
  56706. // for an item..
  56707. addSeparatorIfPending();
  56708. items.add (new Item (itemResultId, String::empty, true, false, Image::null,
  56709. Colours::black, false, customComponent, 0, 0));
  56710. }
  56711. class NormalComponentWrapper : public PopupMenuCustomComponent
  56712. {
  56713. public:
  56714. NormalComponentWrapper (Component* const comp,
  56715. const int w, const int h,
  56716. const bool triggerMenuItemAutomaticallyWhenClicked)
  56717. : PopupMenuCustomComponent (triggerMenuItemAutomaticallyWhenClicked),
  56718. width (w),
  56719. height (h)
  56720. {
  56721. addAndMakeVisible (comp);
  56722. }
  56723. ~NormalComponentWrapper() {}
  56724. void getIdealSize (int& idealWidth, int& idealHeight)
  56725. {
  56726. idealWidth = width;
  56727. idealHeight = height;
  56728. }
  56729. void resized()
  56730. {
  56731. if (getChildComponent(0) != 0)
  56732. getChildComponent(0)->setBounds (getLocalBounds());
  56733. }
  56734. juce_UseDebuggingNewOperator
  56735. private:
  56736. const int width, height;
  56737. NormalComponentWrapper (const NormalComponentWrapper&);
  56738. NormalComponentWrapper& operator= (const NormalComponentWrapper&);
  56739. };
  56740. void PopupMenu::addCustomItem (const int itemResultId,
  56741. Component* customComponent,
  56742. int idealWidth, int idealHeight,
  56743. const bool triggerMenuItemAutomaticallyWhenClicked)
  56744. {
  56745. addCustomItem (itemResultId,
  56746. new NormalComponentWrapper (customComponent,
  56747. idealWidth, idealHeight,
  56748. triggerMenuItemAutomaticallyWhenClicked));
  56749. }
  56750. void PopupMenu::addSubMenu (const String& subMenuName,
  56751. const PopupMenu& subMenu,
  56752. const bool isActive,
  56753. const Image& iconToUse,
  56754. const bool isTicked)
  56755. {
  56756. addSeparatorIfPending();
  56757. items.add (new Item (0, subMenuName, isActive && (subMenu.getNumItems() > 0), isTicked,
  56758. iconToUse, Colours::black, false, 0, &subMenu, 0));
  56759. }
  56760. void PopupMenu::addSeparator()
  56761. {
  56762. separatorPending = true;
  56763. }
  56764. class HeaderItemComponent : public PopupMenuCustomComponent
  56765. {
  56766. public:
  56767. HeaderItemComponent (const String& name)
  56768. : PopupMenuCustomComponent (false)
  56769. {
  56770. setName (name);
  56771. }
  56772. ~HeaderItemComponent()
  56773. {
  56774. }
  56775. void paint (Graphics& g)
  56776. {
  56777. Font f (getLookAndFeel().getPopupMenuFont());
  56778. f.setBold (true);
  56779. g.setFont (f);
  56780. g.setColour (findColour (PopupMenu::headerTextColourId));
  56781. g.drawFittedText (getName(),
  56782. 12, 0, getWidth() - 16, proportionOfHeight (0.8f),
  56783. Justification::bottomLeft, 1);
  56784. }
  56785. void getIdealSize (int& idealWidth,
  56786. int& idealHeight)
  56787. {
  56788. getLookAndFeel().getIdealPopupMenuItemSize (getName(), false, -1, idealWidth, idealHeight);
  56789. idealHeight += idealHeight / 2;
  56790. idealWidth += idealWidth / 4;
  56791. }
  56792. juce_UseDebuggingNewOperator
  56793. };
  56794. void PopupMenu::addSectionHeader (const String& title)
  56795. {
  56796. addCustomItem (0X4734a34f, new HeaderItemComponent (title));
  56797. }
  56798. // This invokes any command manager commands and deletes the menu window when it is dismissed
  56799. class PopupMenuCompletionCallback : public ModalComponentManager::Callback
  56800. {
  56801. public:
  56802. PopupMenuCompletionCallback()
  56803. : managerOfChosenCommand (0)
  56804. {
  56805. }
  56806. ~PopupMenuCompletionCallback() {}
  56807. void modalStateFinished (int result)
  56808. {
  56809. if (managerOfChosenCommand != 0 && result != 0)
  56810. {
  56811. ApplicationCommandTarget::InvocationInfo info (result);
  56812. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  56813. managerOfChosenCommand->invoke (info, true);
  56814. }
  56815. }
  56816. ApplicationCommandManager* managerOfChosenCommand;
  56817. ScopedPointer<Component> component;
  56818. private:
  56819. PopupMenuCompletionCallback (const PopupMenuCompletionCallback&);
  56820. PopupMenuCompletionCallback& operator= (const PopupMenuCompletionCallback&);
  56821. };
  56822. int PopupMenu::showMenu (const Rectangle<int>& target,
  56823. const int itemIdThatMustBeVisible,
  56824. const int minimumWidth,
  56825. const int maximumNumColumns,
  56826. const int standardItemHeight,
  56827. const bool alignToRectangle,
  56828. Component* const componentAttachedTo,
  56829. ModalComponentManager::Callback* userCallback)
  56830. {
  56831. ScopedPointer<ModalComponentManager::Callback> userCallbackDeleter (userCallback);
  56832. Component::SafePointer<Component> prevFocused (Component::getCurrentlyFocusedComponent());
  56833. Component::SafePointer<Component> prevTopLevel ((prevFocused != 0) ? prevFocused->getTopLevelComponent() : 0);
  56834. Window::wasHiddenBecauseOfAppChange() = false;
  56835. PopupMenuCompletionCallback* callback = new PopupMenuCompletionCallback();
  56836. ScopedPointer<PopupMenuCompletionCallback> callbackDeleter (callback);
  56837. callback->component = Window::create (*this, ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown(),
  56838. 0, target, minimumWidth, maximumNumColumns > 0 ? maximumNumColumns : 7,
  56839. standardItemHeight, alignToRectangle, itemIdThatMustBeVisible,
  56840. &callback->managerOfChosenCommand, componentAttachedTo);
  56841. if (callback->component == 0)
  56842. return 0;
  56843. callbackDeleter.release();
  56844. callback->component->enterModalState (false, userCallbackDeleter.release());
  56845. callback->component->toFront (false); // need to do this after making it modal, or it could
  56846. // be stuck behind other comps that are already modal..
  56847. ModalComponentManager::getInstance()->attachCallback (callback->component, callback);
  56848. if (userCallback != 0)
  56849. return 0;
  56850. const int result = callback->component->runModalLoop();
  56851. if (! Window::wasHiddenBecauseOfAppChange())
  56852. {
  56853. if (prevTopLevel != 0)
  56854. prevTopLevel->toFront (true);
  56855. if (prevFocused != 0)
  56856. prevFocused->grabKeyboardFocus();
  56857. }
  56858. return result;
  56859. }
  56860. int PopupMenu::show (const int itemIdThatMustBeVisible,
  56861. const int minimumWidth,
  56862. const int maximumNumColumns,
  56863. const int standardItemHeight,
  56864. ModalComponentManager::Callback* callback)
  56865. {
  56866. const Point<int> mousePos (Desktop::getMousePosition());
  56867. return showAt (mousePos.getX(), mousePos.getY(),
  56868. itemIdThatMustBeVisible,
  56869. minimumWidth,
  56870. maximumNumColumns,
  56871. standardItemHeight,
  56872. callback);
  56873. }
  56874. int PopupMenu::showAt (const int screenX,
  56875. const int screenY,
  56876. const int itemIdThatMustBeVisible,
  56877. const int minimumWidth,
  56878. const int maximumNumColumns,
  56879. const int standardItemHeight,
  56880. ModalComponentManager::Callback* callback)
  56881. {
  56882. return showMenu (Rectangle<int> (screenX, screenY, 1, 1),
  56883. itemIdThatMustBeVisible,
  56884. minimumWidth, maximumNumColumns,
  56885. standardItemHeight,
  56886. false, 0, callback);
  56887. }
  56888. int PopupMenu::showAt (Component* componentToAttachTo,
  56889. const int itemIdThatMustBeVisible,
  56890. const int minimumWidth,
  56891. const int maximumNumColumns,
  56892. const int standardItemHeight,
  56893. ModalComponentManager::Callback* callback)
  56894. {
  56895. if (componentToAttachTo != 0)
  56896. {
  56897. return showMenu (componentToAttachTo->getScreenBounds(),
  56898. itemIdThatMustBeVisible,
  56899. minimumWidth,
  56900. maximumNumColumns,
  56901. standardItemHeight,
  56902. true, componentToAttachTo, callback);
  56903. }
  56904. else
  56905. {
  56906. return show (itemIdThatMustBeVisible,
  56907. minimumWidth,
  56908. maximumNumColumns,
  56909. standardItemHeight,
  56910. callback);
  56911. }
  56912. }
  56913. void JUCE_CALLTYPE PopupMenu::dismissAllActiveMenus()
  56914. {
  56915. for (int i = Window::getActiveWindows().size(); --i >= 0;)
  56916. {
  56917. Window* const pmw = Window::getActiveWindows()[i];
  56918. if (pmw != 0)
  56919. pmw->dismissMenu (0);
  56920. }
  56921. }
  56922. int PopupMenu::getNumItems() const throw()
  56923. {
  56924. int num = 0;
  56925. for (int i = items.size(); --i >= 0;)
  56926. if (! (items.getUnchecked(i))->isSeparator)
  56927. ++num;
  56928. return num;
  56929. }
  56930. bool PopupMenu::containsCommandItem (const int commandID) const
  56931. {
  56932. for (int i = items.size(); --i >= 0;)
  56933. {
  56934. const Item* mi = items.getUnchecked (i);
  56935. if ((mi->itemId == commandID && mi->commandManager != 0)
  56936. || (mi->subMenu != 0 && mi->subMenu->containsCommandItem (commandID)))
  56937. {
  56938. return true;
  56939. }
  56940. }
  56941. return false;
  56942. }
  56943. bool PopupMenu::containsAnyActiveItems() const throw()
  56944. {
  56945. for (int i = items.size(); --i >= 0;)
  56946. {
  56947. const Item* const mi = items.getUnchecked (i);
  56948. if (mi->subMenu != 0)
  56949. {
  56950. if (mi->subMenu->containsAnyActiveItems())
  56951. return true;
  56952. }
  56953. else if (mi->active)
  56954. {
  56955. return true;
  56956. }
  56957. }
  56958. return false;
  56959. }
  56960. void PopupMenu::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  56961. {
  56962. lookAndFeel = newLookAndFeel;
  56963. }
  56964. PopupMenuCustomComponent::PopupMenuCustomComponent (const bool isTriggeredAutomatically_)
  56965. : isHighlighted (false),
  56966. isTriggeredAutomatically (isTriggeredAutomatically_)
  56967. {
  56968. }
  56969. PopupMenuCustomComponent::~PopupMenuCustomComponent()
  56970. {
  56971. }
  56972. void PopupMenuCustomComponent::triggerMenuItem()
  56973. {
  56974. PopupMenu::ItemComponent* const mic = dynamic_cast <PopupMenu::ItemComponent*> (getParentComponent());
  56975. if (mic != 0)
  56976. {
  56977. PopupMenu::Window* const pmw = dynamic_cast <PopupMenu::Window*> (mic->getParentComponent());
  56978. if (pmw != 0)
  56979. {
  56980. pmw->dismissMenu (&mic->itemInfo);
  56981. }
  56982. else
  56983. {
  56984. // something must have gone wrong with the component hierarchy if this happens..
  56985. jassertfalse;
  56986. }
  56987. }
  56988. else
  56989. {
  56990. // why isn't this component inside a menu? Not much point triggering the item if
  56991. // there's no menu.
  56992. jassertfalse;
  56993. }
  56994. }
  56995. PopupMenu::MenuItemIterator::MenuItemIterator (const PopupMenu& menu_)
  56996. : subMenu (0),
  56997. itemId (0),
  56998. isSeparator (false),
  56999. isTicked (false),
  57000. isEnabled (false),
  57001. isCustomComponent (false),
  57002. isSectionHeader (false),
  57003. customColour (0),
  57004. customImage (0),
  57005. menu (menu_),
  57006. index (0)
  57007. {
  57008. }
  57009. PopupMenu::MenuItemIterator::~MenuItemIterator()
  57010. {
  57011. }
  57012. bool PopupMenu::MenuItemIterator::next()
  57013. {
  57014. if (index >= menu.items.size())
  57015. return false;
  57016. const Item* const item = menu.items.getUnchecked (index);
  57017. ++index;
  57018. itemName = item->customComp != 0 ? item->customComp->getName() : item->text;
  57019. subMenu = item->subMenu;
  57020. itemId = item->itemId;
  57021. isSeparator = item->isSeparator;
  57022. isTicked = item->isTicked;
  57023. isEnabled = item->active;
  57024. isSectionHeader = dynamic_cast <HeaderItemComponent*> ((PopupMenuCustomComponent*) item->customComp) != 0;
  57025. isCustomComponent = (! isSectionHeader) && item->customComp != 0;
  57026. customColour = item->usesColour ? &(item->textColour) : 0;
  57027. customImage = item->image;
  57028. commandManager = item->commandManager;
  57029. return true;
  57030. }
  57031. END_JUCE_NAMESPACE
  57032. /*** End of inlined file: juce_PopupMenu.cpp ***/
  57033. /*** Start of inlined file: juce_ComponentDragger.cpp ***/
  57034. BEGIN_JUCE_NAMESPACE
  57035. ComponentDragger::ComponentDragger()
  57036. : constrainer (0)
  57037. {
  57038. }
  57039. ComponentDragger::~ComponentDragger()
  57040. {
  57041. }
  57042. void ComponentDragger::startDraggingComponent (Component* const componentToDrag,
  57043. ComponentBoundsConstrainer* const constrainer_)
  57044. {
  57045. jassert (componentToDrag->isValidComponent());
  57046. if (componentToDrag != 0)
  57047. {
  57048. constrainer = constrainer_;
  57049. originalPos = componentToDrag->relativePositionToGlobal (Point<int>());
  57050. }
  57051. }
  57052. void ComponentDragger::dragComponent (Component* const componentToDrag, const MouseEvent& e)
  57053. {
  57054. jassert (componentToDrag->isValidComponent());
  57055. jassert (e.mods.isAnyMouseButtonDown()); // (the event has to be a drag event..)
  57056. if (componentToDrag != 0)
  57057. {
  57058. Rectangle<int> bounds (componentToDrag->getBounds().withPosition (originalPos));
  57059. const Component* const parentComp = componentToDrag->getParentComponent();
  57060. if (parentComp != 0)
  57061. bounds.setPosition (parentComp->globalPositionToRelative (originalPos));
  57062. bounds.setPosition (bounds.getPosition() + e.getOffsetFromDragStart());
  57063. if (constrainer != 0)
  57064. constrainer->setBoundsForComponent (componentToDrag, bounds, false, false, false, false);
  57065. else
  57066. componentToDrag->setBounds (bounds);
  57067. }
  57068. }
  57069. END_JUCE_NAMESPACE
  57070. /*** End of inlined file: juce_ComponentDragger.cpp ***/
  57071. /*** Start of inlined file: juce_DragAndDropContainer.cpp ***/
  57072. BEGIN_JUCE_NAMESPACE
  57073. bool juce_performDragDropFiles (const StringArray& files, const bool copyFiles, bool& shouldStop);
  57074. bool juce_performDragDropText (const String& text, bool& shouldStop);
  57075. class DragImageComponent : public Component,
  57076. public Timer
  57077. {
  57078. public:
  57079. DragImageComponent (const Image& im,
  57080. const String& desc,
  57081. Component* const sourceComponent,
  57082. Component* const mouseDragSource_,
  57083. DragAndDropContainer* const o,
  57084. const Point<int>& imageOffset_)
  57085. : image (im),
  57086. source (sourceComponent),
  57087. mouseDragSource (mouseDragSource_),
  57088. owner (o),
  57089. dragDesc (desc),
  57090. imageOffset (imageOffset_),
  57091. hasCheckedForExternalDrag (false),
  57092. drawImage (true)
  57093. {
  57094. setSize (im.getWidth(), im.getHeight());
  57095. if (mouseDragSource == 0)
  57096. mouseDragSource = source;
  57097. mouseDragSource->addMouseListener (this, false);
  57098. startTimer (200);
  57099. setInterceptsMouseClicks (false, false);
  57100. setAlwaysOnTop (true);
  57101. }
  57102. ~DragImageComponent()
  57103. {
  57104. if (owner->dragImageComponent == this)
  57105. owner->dragImageComponent.release();
  57106. if (mouseDragSource != 0)
  57107. {
  57108. mouseDragSource->removeMouseListener (this);
  57109. if (getCurrentlyOver() != 0 && getCurrentlyOver()->isInterestedInDragSource (dragDesc, source))
  57110. getCurrentlyOver()->itemDragExit (dragDesc, source);
  57111. }
  57112. }
  57113. void paint (Graphics& g)
  57114. {
  57115. if (isOpaque())
  57116. g.fillAll (Colours::white);
  57117. if (drawImage)
  57118. {
  57119. g.setOpacity (1.0f);
  57120. g.drawImageAt (image, 0, 0);
  57121. }
  57122. }
  57123. DragAndDropTarget* findTarget (const Point<int>& screenPos, Point<int>& relativePos)
  57124. {
  57125. Component* hit = getParentComponent();
  57126. if (hit == 0)
  57127. {
  57128. hit = Desktop::getInstance().findComponentAt (screenPos);
  57129. }
  57130. else
  57131. {
  57132. const Point<int> relPos (hit->globalPositionToRelative (screenPos));
  57133. hit = hit->getComponentAt (relPos.getX(), relPos.getY());
  57134. }
  57135. // (note: use a local copy of the dragDesc member in case the callback runs
  57136. // a modal loop and deletes this object before the method completes)
  57137. const String dragDescLocal (dragDesc);
  57138. while (hit != 0)
  57139. {
  57140. DragAndDropTarget* const ddt = dynamic_cast <DragAndDropTarget*> (hit);
  57141. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  57142. {
  57143. relativePos = hit->globalPositionToRelative (screenPos);
  57144. return ddt;
  57145. }
  57146. hit = hit->getParentComponent();
  57147. }
  57148. return 0;
  57149. }
  57150. void mouseUp (const MouseEvent& e)
  57151. {
  57152. if (e.originalComponent != this)
  57153. {
  57154. if (mouseDragSource != 0)
  57155. mouseDragSource->removeMouseListener (this);
  57156. bool dropAccepted = false;
  57157. DragAndDropTarget* ddt = 0;
  57158. Point<int> relPos;
  57159. if (isVisible())
  57160. {
  57161. setVisible (false);
  57162. ddt = findTarget (e.getScreenPosition(), relPos);
  57163. // fade this component and remove it - it'll be deleted later by the timer callback
  57164. dropAccepted = ddt != 0;
  57165. setVisible (true);
  57166. if (dropAccepted || source == 0)
  57167. {
  57168. fadeOutComponent (120);
  57169. }
  57170. else
  57171. {
  57172. const Point<int> target (source->relativePositionToGlobal (Point<int> (source->getWidth() / 2,
  57173. source->getHeight() / 2)));
  57174. const Point<int> ourCentre (relativePositionToGlobal (Point<int> (getWidth() / 2,
  57175. getHeight() / 2)));
  57176. fadeOutComponent (120,
  57177. target.getX() - ourCentre.getX(),
  57178. target.getY() - ourCentre.getY());
  57179. }
  57180. }
  57181. if (getParentComponent() != 0)
  57182. getParentComponent()->removeChildComponent (this);
  57183. if (dropAccepted && ddt != 0)
  57184. {
  57185. // (note: use a local copy of the dragDesc member in case the callback runs
  57186. // a modal loop and deletes this object before the method completes)
  57187. const String dragDescLocal (dragDesc);
  57188. currentlyOverComp = 0;
  57189. ddt->itemDropped (dragDescLocal, source, relPos.getX(), relPos.getY());
  57190. }
  57191. // careful - this object could now be deleted..
  57192. }
  57193. }
  57194. void updateLocation (const bool canDoExternalDrag, const Point<int>& screenPos)
  57195. {
  57196. // (note: use a local copy of the dragDesc member in case the callback runs
  57197. // a modal loop and deletes this object before it returns)
  57198. const String dragDescLocal (dragDesc);
  57199. Point<int> newPos (screenPos + imageOffset);
  57200. if (getParentComponent() != 0)
  57201. newPos = getParentComponent()->globalPositionToRelative (newPos);
  57202. //if (newX != getX() || newY != getY())
  57203. {
  57204. setTopLeftPosition (newPos.getX(), newPos.getY());
  57205. Point<int> relPos;
  57206. DragAndDropTarget* const ddt = findTarget (screenPos, relPos);
  57207. Component* ddtComp = dynamic_cast <Component*> (ddt);
  57208. drawImage = (ddt == 0) || ddt->shouldDrawDragImageWhenOver();
  57209. if (ddtComp != currentlyOverComp)
  57210. {
  57211. if (currentlyOverComp != 0 && source != 0
  57212. && getCurrentlyOver()->isInterestedInDragSource (dragDescLocal, source))
  57213. {
  57214. getCurrentlyOver()->itemDragExit (dragDescLocal, source);
  57215. }
  57216. currentlyOverComp = ddtComp;
  57217. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  57218. ddt->itemDragEnter (dragDescLocal, source, relPos.getX(), relPos.getY());
  57219. }
  57220. DragAndDropTarget* target = getCurrentlyOver();
  57221. if (target != 0 && target->isInterestedInDragSource (dragDescLocal, source))
  57222. target->itemDragMove (dragDescLocal, source, relPos.getX(), relPos.getY());
  57223. if (getCurrentlyOver() == 0 && canDoExternalDrag && ! hasCheckedForExternalDrag)
  57224. {
  57225. if (Desktop::getInstance().findComponentAt (screenPos) == 0)
  57226. {
  57227. hasCheckedForExternalDrag = true;
  57228. StringArray files;
  57229. bool canMoveFiles = false;
  57230. if (owner->shouldDropFilesWhenDraggedExternally (dragDescLocal, source, files, canMoveFiles)
  57231. && files.size() > 0)
  57232. {
  57233. Component::SafePointer<Component> cdw (this);
  57234. setVisible (false);
  57235. if (ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  57236. DragAndDropContainer::performExternalDragDropOfFiles (files, canMoveFiles);
  57237. if (cdw != 0)
  57238. delete this;
  57239. return;
  57240. }
  57241. }
  57242. }
  57243. }
  57244. }
  57245. void mouseDrag (const MouseEvent& e)
  57246. {
  57247. if (e.originalComponent != this)
  57248. updateLocation (true, e.getScreenPosition());
  57249. }
  57250. void timerCallback()
  57251. {
  57252. if (source == 0)
  57253. {
  57254. delete this;
  57255. }
  57256. else if (! isMouseButtonDownAnywhere())
  57257. {
  57258. if (mouseDragSource != 0)
  57259. mouseDragSource->removeMouseListener (this);
  57260. delete this;
  57261. }
  57262. }
  57263. private:
  57264. Image image;
  57265. Component::SafePointer<Component> source;
  57266. Component::SafePointer<Component> mouseDragSource;
  57267. DragAndDropContainer* const owner;
  57268. Component::SafePointer<Component> currentlyOverComp;
  57269. DragAndDropTarget* getCurrentlyOver()
  57270. {
  57271. return dynamic_cast <DragAndDropTarget*> (static_cast <Component*> (currentlyOverComp));
  57272. }
  57273. String dragDesc;
  57274. const Point<int> imageOffset;
  57275. bool hasCheckedForExternalDrag, drawImage;
  57276. DragImageComponent (const DragImageComponent&);
  57277. DragImageComponent& operator= (const DragImageComponent&);
  57278. };
  57279. DragAndDropContainer::DragAndDropContainer()
  57280. {
  57281. }
  57282. DragAndDropContainer::~DragAndDropContainer()
  57283. {
  57284. dragImageComponent = 0;
  57285. }
  57286. void DragAndDropContainer::startDragging (const String& sourceDescription,
  57287. Component* sourceComponent,
  57288. const Image& dragImage_,
  57289. const bool allowDraggingToExternalWindows,
  57290. const Point<int>* imageOffsetFromMouse)
  57291. {
  57292. Image dragImage (dragImage_);
  57293. if (dragImageComponent == 0)
  57294. {
  57295. Component* const thisComp = dynamic_cast <Component*> (this);
  57296. if (thisComp == 0)
  57297. {
  57298. jassertfalse; // Your DragAndDropContainer needs to be a Component!
  57299. return;
  57300. }
  57301. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource (0);
  57302. if (draggingSource == 0 || ! draggingSource->isDragging())
  57303. {
  57304. jassertfalse; // You must call startDragging() from within a mouseDown or mouseDrag callback!
  57305. return;
  57306. }
  57307. const Point<int> lastMouseDown (Desktop::getLastMouseDownPosition());
  57308. Point<int> imageOffset;
  57309. if (dragImage.isNull())
  57310. {
  57311. dragImage = sourceComponent->createComponentSnapshot (sourceComponent->getLocalBounds())
  57312. .convertedToFormat (Image::ARGB);
  57313. dragImage.multiplyAllAlphas (0.6f);
  57314. const int lo = 150;
  57315. const int hi = 400;
  57316. Point<int> relPos (sourceComponent->globalPositionToRelative (lastMouseDown));
  57317. Point<int> clipped (dragImage.getBounds().getConstrainedPoint (relPos));
  57318. for (int y = dragImage.getHeight(); --y >= 0;)
  57319. {
  57320. const double dy = (y - clipped.getY()) * (y - clipped.getY());
  57321. for (int x = dragImage.getWidth(); --x >= 0;)
  57322. {
  57323. const int dx = x - clipped.getX();
  57324. const int distance = roundToInt (std::sqrt (dx * dx + dy));
  57325. if (distance > lo)
  57326. {
  57327. const float alpha = (distance > hi) ? 0
  57328. : (hi - distance) / (float) (hi - lo)
  57329. + Random::getSystemRandom().nextFloat() * 0.008f;
  57330. dragImage.multiplyAlphaAt (x, y, alpha);
  57331. }
  57332. }
  57333. }
  57334. imageOffset = -clipped;
  57335. }
  57336. else
  57337. {
  57338. if (imageOffsetFromMouse == 0)
  57339. imageOffset = -dragImage.getBounds().getCentre();
  57340. else
  57341. imageOffset = -(dragImage.getBounds().getConstrainedPoint (-*imageOffsetFromMouse));
  57342. }
  57343. dragImageComponent = new DragImageComponent (dragImage, sourceDescription, sourceComponent,
  57344. draggingSource->getComponentUnderMouse(), this, imageOffset);
  57345. currentDragDesc = sourceDescription;
  57346. if (allowDraggingToExternalWindows)
  57347. {
  57348. if (! Desktop::canUseSemiTransparentWindows())
  57349. dragImageComponent->setOpaque (true);
  57350. dragImageComponent->addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  57351. | ComponentPeer::windowIsTemporary
  57352. | ComponentPeer::windowIgnoresKeyPresses);
  57353. }
  57354. else
  57355. thisComp->addChildComponent (dragImageComponent);
  57356. static_cast <DragImageComponent*> (static_cast <Component*> (dragImageComponent))->updateLocation (false, lastMouseDown);
  57357. dragImageComponent->setVisible (true);
  57358. }
  57359. }
  57360. bool DragAndDropContainer::isDragAndDropActive() const
  57361. {
  57362. return dragImageComponent != 0;
  57363. }
  57364. const String DragAndDropContainer::getCurrentDragDescription() const
  57365. {
  57366. return (dragImageComponent != 0) ? currentDragDesc
  57367. : String::empty;
  57368. }
  57369. DragAndDropContainer* DragAndDropContainer::findParentDragContainerFor (Component* c)
  57370. {
  57371. return c == 0 ? 0 : c->findParentComponentOfClass ((DragAndDropContainer*) 0);
  57372. }
  57373. bool DragAndDropContainer::shouldDropFilesWhenDraggedExternally (const String&, Component*, StringArray&, bool&)
  57374. {
  57375. return false;
  57376. }
  57377. void DragAndDropTarget::itemDragEnter (const String&, Component*, int, int)
  57378. {
  57379. }
  57380. void DragAndDropTarget::itemDragMove (const String&, Component*, int, int)
  57381. {
  57382. }
  57383. void DragAndDropTarget::itemDragExit (const String&, Component*)
  57384. {
  57385. }
  57386. bool DragAndDropTarget::shouldDrawDragImageWhenOver()
  57387. {
  57388. return true;
  57389. }
  57390. void FileDragAndDropTarget::fileDragEnter (const StringArray&, int, int)
  57391. {
  57392. }
  57393. void FileDragAndDropTarget::fileDragMove (const StringArray&, int, int)
  57394. {
  57395. }
  57396. void FileDragAndDropTarget::fileDragExit (const StringArray&)
  57397. {
  57398. }
  57399. END_JUCE_NAMESPACE
  57400. /*** End of inlined file: juce_DragAndDropContainer.cpp ***/
  57401. /*** Start of inlined file: juce_MouseCursor.cpp ***/
  57402. BEGIN_JUCE_NAMESPACE
  57403. class MouseCursor::SharedCursorHandle
  57404. {
  57405. public:
  57406. explicit SharedCursorHandle (const MouseCursor::StandardCursorType type)
  57407. : handle (createStandardMouseCursor (type)),
  57408. refCount (1),
  57409. standardType (type),
  57410. isStandard (true)
  57411. {
  57412. }
  57413. SharedCursorHandle (const Image& image, const int hotSpotX, const int hotSpotY)
  57414. : handle (createMouseCursorFromImage (image, hotSpotX, hotSpotY)),
  57415. refCount (1),
  57416. standardType (MouseCursor::NormalCursor),
  57417. isStandard (false)
  57418. {
  57419. }
  57420. static SharedCursorHandle* createStandard (const MouseCursor::StandardCursorType type)
  57421. {
  57422. const ScopedLock sl (getLock());
  57423. for (int i = 0; i < getCursors().size(); ++i)
  57424. {
  57425. SharedCursorHandle* const sc = getCursors().getUnchecked(i);
  57426. if (sc->standardType == type)
  57427. return sc->retain();
  57428. }
  57429. SharedCursorHandle* const sc = new SharedCursorHandle (type);
  57430. getCursors().add (sc);
  57431. return sc;
  57432. }
  57433. SharedCursorHandle* retain() throw()
  57434. {
  57435. ++refCount;
  57436. return this;
  57437. }
  57438. void release()
  57439. {
  57440. if (--refCount == 0)
  57441. {
  57442. if (isStandard)
  57443. {
  57444. const ScopedLock sl (getLock());
  57445. getCursors().removeValue (this);
  57446. }
  57447. delete this;
  57448. }
  57449. }
  57450. void* getHandle() const throw() { return handle; }
  57451. juce_UseDebuggingNewOperator
  57452. private:
  57453. void* const handle;
  57454. Atomic <int> refCount;
  57455. const MouseCursor::StandardCursorType standardType;
  57456. const bool isStandard;
  57457. static CriticalSection& getLock()
  57458. {
  57459. static CriticalSection lock;
  57460. return lock;
  57461. }
  57462. static Array <SharedCursorHandle*>& getCursors()
  57463. {
  57464. static Array <SharedCursorHandle*> cursors;
  57465. return cursors;
  57466. }
  57467. ~SharedCursorHandle()
  57468. {
  57469. deleteMouseCursor (handle, isStandard);
  57470. }
  57471. SharedCursorHandle& operator= (const SharedCursorHandle&);
  57472. };
  57473. MouseCursor::MouseCursor()
  57474. : cursorHandle (SharedCursorHandle::createStandard (NormalCursor))
  57475. {
  57476. jassert (cursorHandle != 0);
  57477. }
  57478. MouseCursor::MouseCursor (const StandardCursorType type)
  57479. : cursorHandle (SharedCursorHandle::createStandard (type))
  57480. {
  57481. jassert (cursorHandle != 0);
  57482. }
  57483. MouseCursor::MouseCursor (const Image& image, const int hotSpotX, const int hotSpotY)
  57484. : cursorHandle (new SharedCursorHandle (image, hotSpotX, hotSpotY))
  57485. {
  57486. }
  57487. MouseCursor::MouseCursor (const MouseCursor& other)
  57488. : cursorHandle (other.cursorHandle->retain())
  57489. {
  57490. }
  57491. MouseCursor::~MouseCursor()
  57492. {
  57493. cursorHandle->release();
  57494. }
  57495. MouseCursor& MouseCursor::operator= (const MouseCursor& other)
  57496. {
  57497. other.cursorHandle->retain();
  57498. cursorHandle->release();
  57499. cursorHandle = other.cursorHandle;
  57500. return *this;
  57501. }
  57502. bool MouseCursor::operator== (const MouseCursor& other) const throw()
  57503. {
  57504. return getHandle() == other.getHandle();
  57505. }
  57506. bool MouseCursor::operator!= (const MouseCursor& other) const throw()
  57507. {
  57508. return getHandle() != other.getHandle();
  57509. }
  57510. void* MouseCursor::getHandle() const throw()
  57511. {
  57512. return cursorHandle->getHandle();
  57513. }
  57514. void MouseCursor::showWaitCursor()
  57515. {
  57516. Desktop::getInstance().getMainMouseSource().showMouseCursor (MouseCursor::WaitCursor);
  57517. }
  57518. void MouseCursor::hideWaitCursor()
  57519. {
  57520. Desktop::getInstance().getMainMouseSource().revealCursor();
  57521. }
  57522. END_JUCE_NAMESPACE
  57523. /*** End of inlined file: juce_MouseCursor.cpp ***/
  57524. /*** Start of inlined file: juce_MouseEvent.cpp ***/
  57525. BEGIN_JUCE_NAMESPACE
  57526. MouseEvent::MouseEvent (MouseInputSource& source_,
  57527. const Point<int>& position,
  57528. const ModifierKeys& mods_,
  57529. Component* const eventComponent_,
  57530. Component* const originator,
  57531. const Time& eventTime_,
  57532. const Point<int> mouseDownPos_,
  57533. const Time& mouseDownTime_,
  57534. const int numberOfClicks_,
  57535. const bool mouseWasDragged) throw()
  57536. : x (position.getX()),
  57537. y (position.getY()),
  57538. mods (mods_),
  57539. eventComponent (eventComponent_),
  57540. originalComponent (originator),
  57541. eventTime (eventTime_),
  57542. source (source_),
  57543. mouseDownPos (mouseDownPos_),
  57544. mouseDownTime (mouseDownTime_),
  57545. numberOfClicks (numberOfClicks_),
  57546. wasMovedSinceMouseDown (mouseWasDragged)
  57547. {
  57548. }
  57549. MouseEvent::~MouseEvent() throw()
  57550. {
  57551. }
  57552. const MouseEvent MouseEvent::getEventRelativeTo (Component* const otherComponent) const throw()
  57553. {
  57554. if (otherComponent == 0)
  57555. {
  57556. jassertfalse;
  57557. return *this;
  57558. }
  57559. return MouseEvent (source, eventComponent->relativePositionToOtherComponent (otherComponent, getPosition()),
  57560. mods, otherComponent, originalComponent, eventTime,
  57561. eventComponent->relativePositionToOtherComponent (otherComponent, mouseDownPos),
  57562. mouseDownTime, numberOfClicks, wasMovedSinceMouseDown);
  57563. }
  57564. const MouseEvent MouseEvent::withNewPosition (const Point<int>& newPosition) const throw()
  57565. {
  57566. return MouseEvent (source, newPosition, mods, eventComponent, originalComponent,
  57567. eventTime, mouseDownPos, mouseDownTime,
  57568. numberOfClicks, wasMovedSinceMouseDown);
  57569. }
  57570. bool MouseEvent::mouseWasClicked() const throw()
  57571. {
  57572. return ! wasMovedSinceMouseDown;
  57573. }
  57574. int MouseEvent::getMouseDownX() const throw()
  57575. {
  57576. return mouseDownPos.getX();
  57577. }
  57578. int MouseEvent::getMouseDownY() const throw()
  57579. {
  57580. return mouseDownPos.getY();
  57581. }
  57582. const Point<int> MouseEvent::getMouseDownPosition() const throw()
  57583. {
  57584. return mouseDownPos;
  57585. }
  57586. int MouseEvent::getDistanceFromDragStartX() const throw()
  57587. {
  57588. return x - mouseDownPos.getX();
  57589. }
  57590. int MouseEvent::getDistanceFromDragStartY() const throw()
  57591. {
  57592. return y - mouseDownPos.getY();
  57593. }
  57594. int MouseEvent::getDistanceFromDragStart() const throw()
  57595. {
  57596. return mouseDownPos.getDistanceFrom (getPosition());
  57597. }
  57598. const Point<int> MouseEvent::getOffsetFromDragStart() const throw()
  57599. {
  57600. return getPosition() - mouseDownPos;
  57601. }
  57602. int MouseEvent::getLengthOfMousePress() const throw()
  57603. {
  57604. if (mouseDownTime.toMilliseconds() > 0)
  57605. return jmax (0, (int) (eventTime - mouseDownTime).inMilliseconds());
  57606. return 0;
  57607. }
  57608. const Point<int> MouseEvent::getPosition() const throw()
  57609. {
  57610. return Point<int> (x, y);
  57611. }
  57612. int MouseEvent::getScreenX() const
  57613. {
  57614. return getScreenPosition().getX();
  57615. }
  57616. int MouseEvent::getScreenY() const
  57617. {
  57618. return getScreenPosition().getY();
  57619. }
  57620. const Point<int> MouseEvent::getScreenPosition() const
  57621. {
  57622. return eventComponent->relativePositionToGlobal (Point<int> (x, y));
  57623. }
  57624. int MouseEvent::getMouseDownScreenX() const
  57625. {
  57626. return getMouseDownScreenPosition().getX();
  57627. }
  57628. int MouseEvent::getMouseDownScreenY() const
  57629. {
  57630. return getMouseDownScreenPosition().getY();
  57631. }
  57632. const Point<int> MouseEvent::getMouseDownScreenPosition() const
  57633. {
  57634. return eventComponent->relativePositionToGlobal (mouseDownPos);
  57635. }
  57636. int MouseEvent::doubleClickTimeOutMs = 400;
  57637. void MouseEvent::setDoubleClickTimeout (const int newTime) throw()
  57638. {
  57639. doubleClickTimeOutMs = newTime;
  57640. }
  57641. int MouseEvent::getDoubleClickTimeout() throw()
  57642. {
  57643. return doubleClickTimeOutMs;
  57644. }
  57645. END_JUCE_NAMESPACE
  57646. /*** End of inlined file: juce_MouseEvent.cpp ***/
  57647. /*** Start of inlined file: juce_MouseInputSource.cpp ***/
  57648. BEGIN_JUCE_NAMESPACE
  57649. class MouseInputSourceInternal : public AsyncUpdater
  57650. {
  57651. public:
  57652. MouseInputSourceInternal (MouseInputSource& source_, const int index_, const bool isMouseDevice_)
  57653. : index (index_), isMouseDevice (isMouseDevice_), source (source_), lastPeer (0),
  57654. isUnboundedMouseModeOn (false), isCursorVisibleUntilOffscreen (false), currentCursorHandle (0),
  57655. mouseEventCounter (0), lastTime (0)
  57656. {
  57657. zerostruct (mouseDowns);
  57658. }
  57659. ~MouseInputSourceInternal()
  57660. {
  57661. }
  57662. bool isDragging() const throw()
  57663. {
  57664. return buttonState.isAnyMouseButtonDown();
  57665. }
  57666. Component* getComponentUnderMouse() const
  57667. {
  57668. return static_cast <Component*> (componentUnderMouse);
  57669. }
  57670. const ModifierKeys getCurrentModifiers() const
  57671. {
  57672. return ModifierKeys::getCurrentModifiers().withoutMouseButtons().withFlags (buttonState.getRawFlags());
  57673. }
  57674. ComponentPeer* getPeer()
  57675. {
  57676. if (! ComponentPeer::isValidPeer (lastPeer))
  57677. lastPeer = 0;
  57678. return lastPeer;
  57679. }
  57680. Component* findComponentAt (const Point<int>& screenPos)
  57681. {
  57682. ComponentPeer* const peer = getPeer();
  57683. if (peer != 0)
  57684. {
  57685. Component* const comp = peer->getComponent();
  57686. const Point<int> relativePos (comp->globalPositionToRelative (screenPos));
  57687. // (the contains() call is needed to test for overlapping desktop windows)
  57688. if (comp->contains (relativePos.getX(), relativePos.getY()))
  57689. return comp->getComponentAt (relativePos);
  57690. }
  57691. return 0;
  57692. }
  57693. const Point<int> getScreenPosition() const throw()
  57694. {
  57695. return lastScreenPos + unboundedMouseOffset;
  57696. }
  57697. void sendMouseEnter (Component* const comp, const Point<int>& screenPos, const int64 time)
  57698. {
  57699. //DBG ("Mouse " + String (source.getIndex()) + " enter: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57700. comp->internalMouseEnter (source, comp->globalPositionToRelative (screenPos), time);
  57701. }
  57702. void sendMouseExit (Component* const comp, const Point<int>& screenPos, const int64 time)
  57703. {
  57704. //DBG ("Mouse " + String (source.getIndex()) + " exit: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57705. comp->internalMouseExit (source, comp->globalPositionToRelative (screenPos), time);
  57706. }
  57707. void sendMouseMove (Component* const comp, const Point<int>& screenPos, const int64 time)
  57708. {
  57709. //DBG ("Mouse " + String (source.getIndex()) + " move: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57710. comp->internalMouseMove (source, comp->globalPositionToRelative (screenPos), time);
  57711. }
  57712. void sendMouseDown (Component* const comp, const Point<int>& screenPos, const int64 time)
  57713. {
  57714. //DBG ("Mouse " + String (source.getIndex()) + " down: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57715. comp->internalMouseDown (source, comp->globalPositionToRelative (screenPos), time);
  57716. }
  57717. void sendMouseDrag (Component* const comp, const Point<int>& screenPos, const int64 time)
  57718. {
  57719. //DBG ("Mouse " + String (source.getIndex()) + " drag: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57720. comp->internalMouseDrag (source, comp->globalPositionToRelative (screenPos), time);
  57721. }
  57722. void sendMouseUp (Component* const comp, const Point<int>& screenPos, const int64 time)
  57723. {
  57724. //DBG ("Mouse " + String (source.getIndex()) + " up: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57725. comp->internalMouseUp (source, comp->globalPositionToRelative (screenPos), time, getCurrentModifiers());
  57726. }
  57727. void sendMouseWheel (Component* const comp, const Point<int>& screenPos, const int64 time, float x, float y)
  57728. {
  57729. //DBG ("Mouse " + String (source.getIndex()) + " wheel: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57730. comp->internalMouseWheel (source, comp->globalPositionToRelative (screenPos), time, x, y);
  57731. }
  57732. // (returns true if the button change caused a modal event loop)
  57733. bool setButtons (const Point<int>& screenPos, const int64 time, const ModifierKeys& newButtonState)
  57734. {
  57735. if (buttonState == newButtonState)
  57736. return false;
  57737. setScreenPos (screenPos, time, false);
  57738. // (ignore secondary clicks when there's already a button down)
  57739. if (buttonState.isAnyMouseButtonDown() == newButtonState.isAnyMouseButtonDown())
  57740. {
  57741. buttonState = newButtonState;
  57742. return false;
  57743. }
  57744. const int lastCounter = mouseEventCounter;
  57745. if (buttonState.isAnyMouseButtonDown())
  57746. {
  57747. Component* const current = getComponentUnderMouse();
  57748. if (current != 0)
  57749. sendMouseUp (current, screenPos + unboundedMouseOffset, time);
  57750. enableUnboundedMouseMovement (false, false);
  57751. }
  57752. buttonState = newButtonState;
  57753. if (buttonState.isAnyMouseButtonDown())
  57754. {
  57755. Desktop::getInstance().incrementMouseClickCounter();
  57756. Component* const current = getComponentUnderMouse();
  57757. if (current != 0)
  57758. {
  57759. registerMouseDown (screenPos, time, current, buttonState);
  57760. sendMouseDown (current, screenPos, time);
  57761. }
  57762. }
  57763. return lastCounter != mouseEventCounter;
  57764. }
  57765. void setComponentUnderMouse (Component* const newComponent, const Point<int>& screenPos, const int64 time)
  57766. {
  57767. Component* current = getComponentUnderMouse();
  57768. if (newComponent != current)
  57769. {
  57770. Component::SafePointer<Component> safeNewComp (newComponent);
  57771. const ModifierKeys originalButtonState (buttonState);
  57772. if (current != 0)
  57773. {
  57774. setButtons (screenPos, time, ModifierKeys());
  57775. sendMouseExit (current, screenPos, time);
  57776. buttonState = originalButtonState;
  57777. }
  57778. componentUnderMouse = safeNewComp;
  57779. current = getComponentUnderMouse();
  57780. if (current != 0)
  57781. sendMouseEnter (current, screenPos, time);
  57782. revealCursor (false);
  57783. setButtons (screenPos, time, originalButtonState);
  57784. }
  57785. }
  57786. void setPeer (ComponentPeer* const newPeer, const Point<int>& screenPos, const int64 time)
  57787. {
  57788. ModifierKeys::updateCurrentModifiers();
  57789. if (newPeer != lastPeer)
  57790. {
  57791. setComponentUnderMouse (0, screenPos, time);
  57792. lastPeer = newPeer;
  57793. setComponentUnderMouse (findComponentAt (screenPos), screenPos, time);
  57794. }
  57795. }
  57796. void setScreenPos (const Point<int>& newScreenPos, const int64 time, const bool forceUpdate)
  57797. {
  57798. if (! isDragging())
  57799. setComponentUnderMouse (findComponentAt (newScreenPos), newScreenPos, time);
  57800. if (newScreenPos != lastScreenPos || forceUpdate)
  57801. {
  57802. cancelPendingUpdate();
  57803. lastScreenPos = newScreenPos;
  57804. Component* const current = getComponentUnderMouse();
  57805. if (current != 0)
  57806. {
  57807. if (isDragging())
  57808. {
  57809. registerMouseDrag (newScreenPos);
  57810. sendMouseDrag (current, newScreenPos + unboundedMouseOffset, time);
  57811. if (isUnboundedMouseModeOn)
  57812. handleUnboundedDrag (current);
  57813. }
  57814. else
  57815. {
  57816. sendMouseMove (current, newScreenPos, time);
  57817. }
  57818. }
  57819. revealCursor (false);
  57820. }
  57821. }
  57822. void handleEvent (ComponentPeer* const newPeer, const Point<int>& positionWithinPeer, const int64 time, const ModifierKeys& newMods)
  57823. {
  57824. jassert (newPeer != 0);
  57825. lastTime = time;
  57826. ++mouseEventCounter;
  57827. const Point<int> screenPos (newPeer->relativePositionToGlobal (positionWithinPeer));
  57828. if (isDragging() && newMods.isAnyMouseButtonDown())
  57829. {
  57830. setScreenPos (screenPos, time, false);
  57831. }
  57832. else
  57833. {
  57834. setPeer (newPeer, screenPos, time);
  57835. ComponentPeer* peer = getPeer();
  57836. if (peer != 0)
  57837. {
  57838. if (setButtons (screenPos, time, newMods))
  57839. return; // some modal events have been dispatched, so the current event is now out-of-date
  57840. peer = getPeer();
  57841. if (peer != 0)
  57842. setScreenPos (screenPos, time, false);
  57843. }
  57844. }
  57845. }
  57846. void handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, int64 time, float x, float y)
  57847. {
  57848. jassert (peer != 0);
  57849. lastTime = time;
  57850. ++mouseEventCounter;
  57851. const Point<int> screenPos (peer->relativePositionToGlobal (positionWithinPeer));
  57852. setPeer (peer, screenPos, time);
  57853. setScreenPos (screenPos, time, false);
  57854. triggerFakeMove();
  57855. if (! isDragging())
  57856. {
  57857. Component* current = getComponentUnderMouse();
  57858. if (current != 0)
  57859. sendMouseWheel (current, screenPos, time, x, y);
  57860. }
  57861. }
  57862. const Time getLastMouseDownTime() const throw()
  57863. {
  57864. return Time (mouseDowns[0].time);
  57865. }
  57866. const Point<int> getLastMouseDownPosition() const throw()
  57867. {
  57868. return mouseDowns[0].position;
  57869. }
  57870. int getNumberOfMultipleClicks() const throw()
  57871. {
  57872. int numClicks = 0;
  57873. if (mouseDowns[0].time != 0)
  57874. {
  57875. if (! mouseMovedSignificantlySincePressed)
  57876. ++numClicks;
  57877. for (int i = 1; i < numElementsInArray (mouseDowns); ++i)
  57878. {
  57879. if (mouseDowns[0].canBePartOfMultipleClickWith (mouseDowns[1], (int) (MouseEvent::getDoubleClickTimeout() * (1.0 + 0.25 * (i - 1)))))
  57880. ++numClicks;
  57881. else
  57882. break;
  57883. }
  57884. }
  57885. return numClicks;
  57886. }
  57887. bool hasMouseMovedSignificantlySincePressed() const throw()
  57888. {
  57889. return mouseMovedSignificantlySincePressed
  57890. || lastTime > mouseDowns[0].time + 300;
  57891. }
  57892. void triggerFakeMove()
  57893. {
  57894. triggerAsyncUpdate();
  57895. }
  57896. void handleAsyncUpdate()
  57897. {
  57898. setScreenPos (lastScreenPos, jmax (lastTime, Time::currentTimeMillis()), true);
  57899. }
  57900. void enableUnboundedMouseMovement (bool enable, bool keepCursorVisibleUntilOffscreen)
  57901. {
  57902. enable = enable && isDragging();
  57903. isCursorVisibleUntilOffscreen = keepCursorVisibleUntilOffscreen;
  57904. if (enable != isUnboundedMouseModeOn)
  57905. {
  57906. if ((! enable) && ((! isCursorVisibleUntilOffscreen) || ! unboundedMouseOffset.isOrigin()))
  57907. {
  57908. // when released, return the mouse to within the component's bounds
  57909. Component* current = getComponentUnderMouse();
  57910. if (current != 0)
  57911. Desktop::setMousePosition (current->getScreenBounds()
  57912. .getConstrainedPoint (lastScreenPos));
  57913. }
  57914. isUnboundedMouseModeOn = enable;
  57915. unboundedMouseOffset = Point<int>();
  57916. revealCursor (true);
  57917. }
  57918. }
  57919. void handleUnboundedDrag (Component* current)
  57920. {
  57921. const Rectangle<int> screenArea (current->getParentMonitorArea().expanded (-2, -2));
  57922. if (! screenArea.contains (lastScreenPos))
  57923. {
  57924. const Point<int> componentCentre (current->getScreenBounds().getCentre());
  57925. unboundedMouseOffset += (lastScreenPos - componentCentre);
  57926. Desktop::setMousePosition (componentCentre);
  57927. }
  57928. else if (isCursorVisibleUntilOffscreen
  57929. && (! unboundedMouseOffset.isOrigin())
  57930. && screenArea.contains (lastScreenPos + unboundedMouseOffset))
  57931. {
  57932. Desktop::setMousePosition (lastScreenPos + unboundedMouseOffset);
  57933. unboundedMouseOffset = Point<int>();
  57934. }
  57935. }
  57936. void showMouseCursor (MouseCursor cursor, bool forcedUpdate)
  57937. {
  57938. if (isUnboundedMouseModeOn && ((! unboundedMouseOffset.isOrigin()) || ! isCursorVisibleUntilOffscreen))
  57939. {
  57940. cursor = MouseCursor::NoCursor;
  57941. forcedUpdate = true;
  57942. }
  57943. if (forcedUpdate || cursor.getHandle() != currentCursorHandle)
  57944. {
  57945. currentCursorHandle = cursor.getHandle();
  57946. cursor.showInWindow (getPeer());
  57947. }
  57948. }
  57949. void hideCursor()
  57950. {
  57951. showMouseCursor (MouseCursor::NoCursor, true);
  57952. }
  57953. void revealCursor (bool forcedUpdate)
  57954. {
  57955. MouseCursor mc (MouseCursor::NormalCursor);
  57956. Component* current = getComponentUnderMouse();
  57957. if (current != 0)
  57958. mc = current->getLookAndFeel().getMouseCursorFor (*current);
  57959. showMouseCursor (mc, forcedUpdate);
  57960. }
  57961. int index;
  57962. bool isMouseDevice;
  57963. Point<int> lastScreenPos;
  57964. ModifierKeys buttonState;
  57965. private:
  57966. MouseInputSource& source;
  57967. Component::SafePointer<Component> componentUnderMouse;
  57968. ComponentPeer* lastPeer;
  57969. Point<int> unboundedMouseOffset;
  57970. bool isUnboundedMouseModeOn, isCursorVisibleUntilOffscreen;
  57971. void* currentCursorHandle;
  57972. int mouseEventCounter;
  57973. struct RecentMouseDown
  57974. {
  57975. Point<int> position;
  57976. int64 time;
  57977. Component* component;
  57978. ModifierKeys buttons;
  57979. bool canBePartOfMultipleClickWith (const RecentMouseDown& other, int maxTimeBetween) const
  57980. {
  57981. return time - other.time < maxTimeBetween
  57982. && abs (position.getX() - other.position.getX()) < 8
  57983. && abs (position.getY() - other.position.getY()) < 8
  57984. && buttons == other.buttons;;
  57985. }
  57986. };
  57987. RecentMouseDown mouseDowns[4];
  57988. bool mouseMovedSignificantlySincePressed;
  57989. int64 lastTime;
  57990. void registerMouseDown (const Point<int>& screenPos, const int64 time,
  57991. Component* const component, const ModifierKeys& modifiers) throw()
  57992. {
  57993. for (int i = numElementsInArray (mouseDowns); --i > 0;)
  57994. mouseDowns[i] = mouseDowns[i - 1];
  57995. mouseDowns[0].position = screenPos;
  57996. mouseDowns[0].time = time;
  57997. mouseDowns[0].component = component;
  57998. mouseDowns[0].buttons = modifiers.withOnlyMouseButtons();
  57999. mouseMovedSignificantlySincePressed = false;
  58000. }
  58001. void registerMouseDrag (const Point<int>& screenPos) throw()
  58002. {
  58003. mouseMovedSignificantlySincePressed = mouseMovedSignificantlySincePressed
  58004. || mouseDowns[0].position.getDistanceFrom (screenPos) >= 4;
  58005. }
  58006. MouseInputSourceInternal (const MouseInputSourceInternal&);
  58007. MouseInputSourceInternal& operator= (const MouseInputSourceInternal&);
  58008. };
  58009. MouseInputSource::MouseInputSource (const int index, const bool isMouseDevice)
  58010. {
  58011. pimpl = new MouseInputSourceInternal (*this, index, isMouseDevice);
  58012. }
  58013. MouseInputSource::~MouseInputSource()
  58014. {
  58015. }
  58016. bool MouseInputSource::isMouse() const { return pimpl->isMouseDevice; }
  58017. bool MouseInputSource::isTouch() const { return ! isMouse(); }
  58018. bool MouseInputSource::canHover() const { return isMouse(); }
  58019. bool MouseInputSource::hasMouseWheel() const { return isMouse(); }
  58020. int MouseInputSource::getIndex() const { return pimpl->index; }
  58021. bool MouseInputSource::isDragging() const { return pimpl->isDragging(); }
  58022. const Point<int> MouseInputSource::getScreenPosition() const { return pimpl->getScreenPosition(); }
  58023. const ModifierKeys MouseInputSource::getCurrentModifiers() const { return pimpl->getCurrentModifiers(); }
  58024. Component* MouseInputSource::getComponentUnderMouse() const { return pimpl->getComponentUnderMouse(); }
  58025. void MouseInputSource::triggerFakeMove() const { pimpl->triggerFakeMove(); }
  58026. int MouseInputSource::getNumberOfMultipleClicks() const throw() { return pimpl->getNumberOfMultipleClicks(); }
  58027. const Time MouseInputSource::getLastMouseDownTime() const throw() { return pimpl->getLastMouseDownTime(); }
  58028. const Point<int> MouseInputSource::getLastMouseDownPosition() const throw() { return pimpl->getLastMouseDownPosition(); }
  58029. bool MouseInputSource::hasMouseMovedSignificantlySincePressed() const throw() { return pimpl->hasMouseMovedSignificantlySincePressed(); }
  58030. bool MouseInputSource::canDoUnboundedMovement() const throw() { return isMouse(); }
  58031. void MouseInputSource::enableUnboundedMouseMovement (bool isEnabled, bool keepCursorVisibleUntilOffscreen) { pimpl->enableUnboundedMouseMovement (isEnabled, keepCursorVisibleUntilOffscreen); }
  58032. bool MouseInputSource::hasMouseCursor() const throw() { return isMouse(); }
  58033. void MouseInputSource::showMouseCursor (const MouseCursor& cursor) { pimpl->showMouseCursor (cursor, false); }
  58034. void MouseInputSource::hideCursor() { pimpl->hideCursor(); }
  58035. void MouseInputSource::revealCursor() { pimpl->revealCursor (false); }
  58036. void MouseInputSource::forceMouseCursorUpdate() { pimpl->revealCursor (true); }
  58037. void MouseInputSource::handleEvent (ComponentPeer* peer, const Point<int>& positionWithinPeer, const int64 time, const ModifierKeys& mods)
  58038. {
  58039. pimpl->handleEvent (peer, positionWithinPeer, time, mods.withOnlyMouseButtons());
  58040. }
  58041. void MouseInputSource::handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  58042. {
  58043. pimpl->handleWheel (peer, positionWithinPeer, time, x, y);
  58044. }
  58045. END_JUCE_NAMESPACE
  58046. /*** End of inlined file: juce_MouseInputSource.cpp ***/
  58047. /*** Start of inlined file: juce_MouseHoverDetector.cpp ***/
  58048. BEGIN_JUCE_NAMESPACE
  58049. MouseHoverDetector::MouseHoverDetector (const int hoverTimeMillisecs_)
  58050. : source (0),
  58051. hoverTimeMillisecs (hoverTimeMillisecs_),
  58052. hasJustHovered (false)
  58053. {
  58054. internalTimer.owner = this;
  58055. }
  58056. MouseHoverDetector::~MouseHoverDetector()
  58057. {
  58058. setHoverComponent (0);
  58059. }
  58060. void MouseHoverDetector::setHoverTimeMillisecs (const int newTimeInMillisecs)
  58061. {
  58062. hoverTimeMillisecs = newTimeInMillisecs;
  58063. }
  58064. void MouseHoverDetector::setHoverComponent (Component* const newSourceComponent)
  58065. {
  58066. if (source != newSourceComponent)
  58067. {
  58068. internalTimer.stopTimer();
  58069. hasJustHovered = false;
  58070. if (source != 0)
  58071. {
  58072. // ! you need to delete the hover detector before deleting its component
  58073. jassert (source->isValidComponent());
  58074. source->removeMouseListener (&internalTimer);
  58075. }
  58076. source = newSourceComponent;
  58077. if (newSourceComponent != 0)
  58078. newSourceComponent->addMouseListener (&internalTimer, false);
  58079. }
  58080. }
  58081. void MouseHoverDetector::hoverTimerCallback()
  58082. {
  58083. internalTimer.stopTimer();
  58084. if (source != 0)
  58085. {
  58086. const Point<int> pos (source->getMouseXYRelative());
  58087. if (source->reallyContains (pos.getX(), pos.getY(), false))
  58088. {
  58089. hasJustHovered = true;
  58090. mouseHovered (pos.getX(), pos.getY());
  58091. }
  58092. }
  58093. }
  58094. void MouseHoverDetector::checkJustHoveredCallback()
  58095. {
  58096. if (hasJustHovered)
  58097. {
  58098. hasJustHovered = false;
  58099. mouseMovedAfterHover();
  58100. }
  58101. }
  58102. void MouseHoverDetector::HoverDetectorInternal::timerCallback()
  58103. {
  58104. owner->hoverTimerCallback();
  58105. }
  58106. void MouseHoverDetector::HoverDetectorInternal::mouseEnter (const MouseEvent&)
  58107. {
  58108. stopTimer();
  58109. owner->checkJustHoveredCallback();
  58110. }
  58111. void MouseHoverDetector::HoverDetectorInternal::mouseExit (const MouseEvent&)
  58112. {
  58113. stopTimer();
  58114. owner->checkJustHoveredCallback();
  58115. }
  58116. void MouseHoverDetector::HoverDetectorInternal::mouseDown (const MouseEvent&)
  58117. {
  58118. stopTimer();
  58119. owner->checkJustHoveredCallback();
  58120. }
  58121. void MouseHoverDetector::HoverDetectorInternal::mouseUp (const MouseEvent&)
  58122. {
  58123. stopTimer();
  58124. owner->checkJustHoveredCallback();
  58125. }
  58126. void MouseHoverDetector::HoverDetectorInternal::mouseMove (const MouseEvent& e)
  58127. {
  58128. if (lastX != e.x || lastY != e.y) // to avoid fake mouse-moves setting it off
  58129. {
  58130. lastX = e.x;
  58131. lastY = e.y;
  58132. if (owner->source != 0)
  58133. startTimer (owner->hoverTimeMillisecs);
  58134. owner->checkJustHoveredCallback();
  58135. }
  58136. }
  58137. void MouseHoverDetector::HoverDetectorInternal::mouseWheelMove (const MouseEvent&, float, float)
  58138. {
  58139. stopTimer();
  58140. owner->checkJustHoveredCallback();
  58141. }
  58142. END_JUCE_NAMESPACE
  58143. /*** End of inlined file: juce_MouseHoverDetector.cpp ***/
  58144. /*** Start of inlined file: juce_MouseListener.cpp ***/
  58145. BEGIN_JUCE_NAMESPACE
  58146. void MouseListener::mouseEnter (const MouseEvent&)
  58147. {
  58148. }
  58149. void MouseListener::mouseExit (const MouseEvent&)
  58150. {
  58151. }
  58152. void MouseListener::mouseDown (const MouseEvent&)
  58153. {
  58154. }
  58155. void MouseListener::mouseUp (const MouseEvent&)
  58156. {
  58157. }
  58158. void MouseListener::mouseDrag (const MouseEvent&)
  58159. {
  58160. }
  58161. void MouseListener::mouseMove (const MouseEvent&)
  58162. {
  58163. }
  58164. void MouseListener::mouseDoubleClick (const MouseEvent&)
  58165. {
  58166. }
  58167. void MouseListener::mouseWheelMove (const MouseEvent&, float, float)
  58168. {
  58169. }
  58170. END_JUCE_NAMESPACE
  58171. /*** End of inlined file: juce_MouseListener.cpp ***/
  58172. /*** Start of inlined file: juce_BooleanPropertyComponent.cpp ***/
  58173. BEGIN_JUCE_NAMESPACE
  58174. BooleanPropertyComponent::BooleanPropertyComponent (const String& name,
  58175. const String& buttonTextWhenTrue,
  58176. const String& buttonTextWhenFalse)
  58177. : PropertyComponent (name),
  58178. onText (buttonTextWhenTrue),
  58179. offText (buttonTextWhenFalse)
  58180. {
  58181. addAndMakeVisible (&button);
  58182. button.setClickingTogglesState (false);
  58183. button.addButtonListener (this);
  58184. }
  58185. BooleanPropertyComponent::BooleanPropertyComponent (const Value& valueToControl,
  58186. const String& name,
  58187. const String& buttonText)
  58188. : PropertyComponent (name),
  58189. onText (buttonText),
  58190. offText (buttonText)
  58191. {
  58192. addAndMakeVisible (&button);
  58193. button.setClickingTogglesState (false);
  58194. button.setButtonText (buttonText);
  58195. button.getToggleStateValue().referTo (valueToControl);
  58196. button.setClickingTogglesState (true);
  58197. }
  58198. BooleanPropertyComponent::~BooleanPropertyComponent()
  58199. {
  58200. }
  58201. void BooleanPropertyComponent::setState (const bool newState)
  58202. {
  58203. button.setToggleState (newState, true);
  58204. }
  58205. bool BooleanPropertyComponent::getState() const
  58206. {
  58207. return button.getToggleState();
  58208. }
  58209. void BooleanPropertyComponent::paint (Graphics& g)
  58210. {
  58211. PropertyComponent::paint (g);
  58212. g.setColour (Colours::white);
  58213. g.fillRect (button.getBounds());
  58214. g.setColour (findColour (ComboBox::outlineColourId));
  58215. g.drawRect (button.getBounds());
  58216. }
  58217. void BooleanPropertyComponent::refresh()
  58218. {
  58219. button.setToggleState (getState(), false);
  58220. button.setButtonText (button.getToggleState() ? onText : offText);
  58221. }
  58222. void BooleanPropertyComponent::buttonClicked (Button*)
  58223. {
  58224. setState (! getState());
  58225. }
  58226. END_JUCE_NAMESPACE
  58227. /*** End of inlined file: juce_BooleanPropertyComponent.cpp ***/
  58228. /*** Start of inlined file: juce_ButtonPropertyComponent.cpp ***/
  58229. BEGIN_JUCE_NAMESPACE
  58230. ButtonPropertyComponent::ButtonPropertyComponent (const String& name,
  58231. const bool triggerOnMouseDown)
  58232. : PropertyComponent (name)
  58233. {
  58234. addAndMakeVisible (&button);
  58235. button.setTriggeredOnMouseDown (triggerOnMouseDown);
  58236. button.addButtonListener (this);
  58237. }
  58238. ButtonPropertyComponent::~ButtonPropertyComponent()
  58239. {
  58240. }
  58241. void ButtonPropertyComponent::refresh()
  58242. {
  58243. button.setButtonText (getButtonText());
  58244. }
  58245. void ButtonPropertyComponent::buttonClicked (Button*)
  58246. {
  58247. buttonClicked();
  58248. }
  58249. END_JUCE_NAMESPACE
  58250. /*** End of inlined file: juce_ButtonPropertyComponent.cpp ***/
  58251. /*** Start of inlined file: juce_ChoicePropertyComponent.cpp ***/
  58252. BEGIN_JUCE_NAMESPACE
  58253. class ChoicePropertyComponent::RemapperValueSource : public Value::ValueSource,
  58254. public Value::Listener
  58255. {
  58256. public:
  58257. RemapperValueSource (const Value& sourceValue_, const Array<var>& mappings_)
  58258. : sourceValue (sourceValue_),
  58259. mappings (mappings_)
  58260. {
  58261. sourceValue.addListener (this);
  58262. }
  58263. ~RemapperValueSource() {}
  58264. const var getValue() const
  58265. {
  58266. return mappings.indexOf (sourceValue.getValue()) + 1;
  58267. }
  58268. void setValue (const var& newValue)
  58269. {
  58270. const var remappedVal (mappings [(int) newValue - 1]);
  58271. if (remappedVal != sourceValue)
  58272. sourceValue = remappedVal;
  58273. }
  58274. void valueChanged (Value&)
  58275. {
  58276. sendChangeMessage (true);
  58277. }
  58278. juce_UseDebuggingNewOperator
  58279. protected:
  58280. Value sourceValue;
  58281. Array<var> mappings;
  58282. RemapperValueSource (const RemapperValueSource&);
  58283. const RemapperValueSource& operator= (const RemapperValueSource&);
  58284. };
  58285. ChoicePropertyComponent::ChoicePropertyComponent (const String& name)
  58286. : PropertyComponent (name),
  58287. isCustomClass (true)
  58288. {
  58289. }
  58290. ChoicePropertyComponent::ChoicePropertyComponent (const Value& valueToControl,
  58291. const String& name,
  58292. const StringArray& choices_,
  58293. const Array <var>& correspondingValues)
  58294. : PropertyComponent (name),
  58295. choices (choices_),
  58296. isCustomClass (false)
  58297. {
  58298. // The array of corresponding values must contain one value for each of the items in
  58299. // the choices array!
  58300. jassert (correspondingValues.size() == choices.size());
  58301. createComboBox();
  58302. comboBox.getSelectedIdAsValue().referTo (Value (new RemapperValueSource (valueToControl, correspondingValues)));
  58303. }
  58304. ChoicePropertyComponent::~ChoicePropertyComponent()
  58305. {
  58306. }
  58307. void ChoicePropertyComponent::createComboBox()
  58308. {
  58309. addAndMakeVisible (&comboBox);
  58310. for (int i = 0; i < choices.size(); ++i)
  58311. {
  58312. if (choices[i].isNotEmpty())
  58313. comboBox.addItem (choices[i], i + 1);
  58314. else
  58315. comboBox.addSeparator();
  58316. }
  58317. comboBox.setEditableText (false);
  58318. }
  58319. void ChoicePropertyComponent::setIndex (const int /*newIndex*/)
  58320. {
  58321. jassertfalse; // you need to override this method in your subclass!
  58322. }
  58323. int ChoicePropertyComponent::getIndex() const
  58324. {
  58325. jassertfalse; // you need to override this method in your subclass!
  58326. return -1;
  58327. }
  58328. const StringArray& ChoicePropertyComponent::getChoices() const
  58329. {
  58330. return choices;
  58331. }
  58332. void ChoicePropertyComponent::refresh()
  58333. {
  58334. if (isCustomClass)
  58335. {
  58336. if (! comboBox.isVisible())
  58337. {
  58338. createComboBox();
  58339. comboBox.addListener (this);
  58340. }
  58341. comboBox.setSelectedId (getIndex() + 1, true);
  58342. }
  58343. }
  58344. void ChoicePropertyComponent::comboBoxChanged (ComboBox*)
  58345. {
  58346. if (isCustomClass)
  58347. {
  58348. const int newIndex = comboBox.getSelectedId() - 1;
  58349. if (newIndex != getIndex())
  58350. setIndex (newIndex);
  58351. }
  58352. }
  58353. END_JUCE_NAMESPACE
  58354. /*** End of inlined file: juce_ChoicePropertyComponent.cpp ***/
  58355. /*** Start of inlined file: juce_PropertyComponent.cpp ***/
  58356. BEGIN_JUCE_NAMESPACE
  58357. PropertyComponent::PropertyComponent (const String& name,
  58358. const int preferredHeight_)
  58359. : Component (name),
  58360. preferredHeight (preferredHeight_)
  58361. {
  58362. jassert (name.isNotEmpty());
  58363. }
  58364. PropertyComponent::~PropertyComponent()
  58365. {
  58366. }
  58367. void PropertyComponent::paint (Graphics& g)
  58368. {
  58369. getLookAndFeel().drawPropertyComponentBackground (g, getWidth(), getHeight(), *this);
  58370. getLookAndFeel().drawPropertyComponentLabel (g, getWidth(), getHeight(), *this);
  58371. }
  58372. void PropertyComponent::resized()
  58373. {
  58374. if (getNumChildComponents() > 0)
  58375. getChildComponent (0)->setBounds (getLookAndFeel().getPropertyComponentContentPosition (*this));
  58376. }
  58377. void PropertyComponent::enablementChanged()
  58378. {
  58379. repaint();
  58380. }
  58381. END_JUCE_NAMESPACE
  58382. /*** End of inlined file: juce_PropertyComponent.cpp ***/
  58383. /*** Start of inlined file: juce_PropertyPanel.cpp ***/
  58384. BEGIN_JUCE_NAMESPACE
  58385. class PropertyPanel::PropertyHolderComponent : public Component
  58386. {
  58387. public:
  58388. PropertyHolderComponent()
  58389. {
  58390. }
  58391. ~PropertyHolderComponent()
  58392. {
  58393. deleteAllChildren();
  58394. }
  58395. void paint (Graphics&)
  58396. {
  58397. }
  58398. void updateLayout (int width);
  58399. void refreshAll() const;
  58400. private:
  58401. PropertyHolderComponent (const PropertyHolderComponent&);
  58402. PropertyHolderComponent& operator= (const PropertyHolderComponent&);
  58403. };
  58404. class PropertySectionComponent : public Component
  58405. {
  58406. public:
  58407. PropertySectionComponent (const String& sectionTitle,
  58408. const Array <PropertyComponent*>& newProperties,
  58409. const bool open)
  58410. : Component (sectionTitle),
  58411. titleHeight (sectionTitle.isNotEmpty() ? 22 : 0),
  58412. isOpen_ (open)
  58413. {
  58414. for (int i = newProperties.size(); --i >= 0;)
  58415. {
  58416. addAndMakeVisible (newProperties.getUnchecked(i));
  58417. newProperties.getUnchecked(i)->refresh();
  58418. }
  58419. }
  58420. ~PropertySectionComponent()
  58421. {
  58422. deleteAllChildren();
  58423. }
  58424. void paint (Graphics& g)
  58425. {
  58426. if (titleHeight > 0)
  58427. getLookAndFeel().drawPropertyPanelSectionHeader (g, getName(), isOpen(), getWidth(), titleHeight);
  58428. }
  58429. void resized()
  58430. {
  58431. int y = titleHeight;
  58432. for (int i = getNumChildComponents(); --i >= 0;)
  58433. {
  58434. PropertyComponent* const pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  58435. if (pec != 0)
  58436. {
  58437. const int prefH = pec->getPreferredHeight();
  58438. pec->setBounds (1, y, getWidth() - 2, prefH);
  58439. y += prefH;
  58440. }
  58441. }
  58442. }
  58443. int getPreferredHeight() const
  58444. {
  58445. int y = titleHeight;
  58446. if (isOpen())
  58447. {
  58448. for (int i = 0; i < getNumChildComponents(); ++i)
  58449. {
  58450. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  58451. if (pec != 0)
  58452. y += pec->getPreferredHeight();
  58453. }
  58454. }
  58455. return y;
  58456. }
  58457. void setOpen (const bool open)
  58458. {
  58459. if (isOpen_ != open)
  58460. {
  58461. isOpen_ = open;
  58462. for (int i = 0; i < getNumChildComponents(); ++i)
  58463. {
  58464. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  58465. if (pec != 0)
  58466. pec->setVisible (open);
  58467. }
  58468. // (unable to use the syntax findParentComponentOfClass <DragAndDropContainer> () because of a VC6 compiler bug)
  58469. PropertyPanel* const pp = findParentComponentOfClass ((PropertyPanel*) 0);
  58470. if (pp != 0)
  58471. pp->resized();
  58472. }
  58473. }
  58474. bool isOpen() const
  58475. {
  58476. return isOpen_;
  58477. }
  58478. void refreshAll() const
  58479. {
  58480. for (int i = 0; i < getNumChildComponents(); ++i)
  58481. {
  58482. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  58483. if (pec != 0)
  58484. pec->refresh();
  58485. }
  58486. }
  58487. void mouseDown (const MouseEvent&)
  58488. {
  58489. }
  58490. void mouseUp (const MouseEvent& e)
  58491. {
  58492. if (e.getMouseDownX() < titleHeight
  58493. && e.x < titleHeight
  58494. && e.y < titleHeight
  58495. && e.getNumberOfClicks() != 2)
  58496. {
  58497. setOpen (! isOpen());
  58498. }
  58499. }
  58500. void mouseDoubleClick (const MouseEvent& e)
  58501. {
  58502. if (e.y < titleHeight)
  58503. setOpen (! isOpen());
  58504. }
  58505. private:
  58506. int titleHeight;
  58507. bool isOpen_;
  58508. PropertySectionComponent (const PropertySectionComponent&);
  58509. PropertySectionComponent& operator= (const PropertySectionComponent&);
  58510. };
  58511. void PropertyPanel::PropertyHolderComponent::updateLayout (const int width)
  58512. {
  58513. int y = 0;
  58514. for (int i = getNumChildComponents(); --i >= 0;)
  58515. {
  58516. PropertySectionComponent* const section
  58517. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  58518. if (section != 0)
  58519. {
  58520. const int prefH = section->getPreferredHeight();
  58521. section->setBounds (0, y, width, prefH);
  58522. y += prefH;
  58523. }
  58524. }
  58525. setSize (width, y);
  58526. repaint();
  58527. }
  58528. void PropertyPanel::PropertyHolderComponent::refreshAll() const
  58529. {
  58530. for (int i = getNumChildComponents(); --i >= 0;)
  58531. {
  58532. PropertySectionComponent* const section
  58533. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  58534. if (section != 0)
  58535. section->refreshAll();
  58536. }
  58537. }
  58538. PropertyPanel::PropertyPanel()
  58539. {
  58540. messageWhenEmpty = TRANS("(nothing selected)");
  58541. addAndMakeVisible (&viewport);
  58542. viewport.setViewedComponent (propertyHolderComponent = new PropertyHolderComponent());
  58543. viewport.setFocusContainer (true);
  58544. }
  58545. PropertyPanel::~PropertyPanel()
  58546. {
  58547. clear();
  58548. }
  58549. void PropertyPanel::paint (Graphics& g)
  58550. {
  58551. if (propertyHolderComponent->getNumChildComponents() == 0)
  58552. {
  58553. g.setColour (Colours::black.withAlpha (0.5f));
  58554. g.setFont (14.0f);
  58555. g.drawText (messageWhenEmpty, 0, 0, getWidth(), 30,
  58556. Justification::centred, true);
  58557. }
  58558. }
  58559. void PropertyPanel::resized()
  58560. {
  58561. viewport.setBounds (getLocalBounds());
  58562. updatePropHolderLayout();
  58563. }
  58564. void PropertyPanel::clear()
  58565. {
  58566. if (propertyHolderComponent->getNumChildComponents() > 0)
  58567. {
  58568. propertyHolderComponent->deleteAllChildren();
  58569. repaint();
  58570. }
  58571. }
  58572. void PropertyPanel::addProperties (const Array <PropertyComponent*>& newProperties)
  58573. {
  58574. if (propertyHolderComponent->getNumChildComponents() == 0)
  58575. repaint();
  58576. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (String::empty,
  58577. newProperties,
  58578. true), 0);
  58579. updatePropHolderLayout();
  58580. }
  58581. void PropertyPanel::addSection (const String& sectionTitle,
  58582. const Array <PropertyComponent*>& newProperties,
  58583. const bool shouldBeOpen)
  58584. {
  58585. jassert (sectionTitle.isNotEmpty());
  58586. if (propertyHolderComponent->getNumChildComponents() == 0)
  58587. repaint();
  58588. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (sectionTitle,
  58589. newProperties,
  58590. shouldBeOpen), 0);
  58591. updatePropHolderLayout();
  58592. }
  58593. void PropertyPanel::updatePropHolderLayout() const
  58594. {
  58595. const int maxWidth = viewport.getMaximumVisibleWidth();
  58596. propertyHolderComponent->updateLayout (maxWidth);
  58597. const int newMaxWidth = viewport.getMaximumVisibleWidth();
  58598. if (maxWidth != newMaxWidth)
  58599. {
  58600. // need to do this twice because of scrollbars changing the size, etc.
  58601. propertyHolderComponent->updateLayout (newMaxWidth);
  58602. }
  58603. }
  58604. void PropertyPanel::refreshAll() const
  58605. {
  58606. propertyHolderComponent->refreshAll();
  58607. }
  58608. const StringArray PropertyPanel::getSectionNames() const
  58609. {
  58610. StringArray s;
  58611. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  58612. {
  58613. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  58614. if (section != 0 && section->getName().isNotEmpty())
  58615. s.add (section->getName());
  58616. }
  58617. return s;
  58618. }
  58619. bool PropertyPanel::isSectionOpen (const int sectionIndex) const
  58620. {
  58621. int index = 0;
  58622. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  58623. {
  58624. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  58625. if (section != 0 && section->getName().isNotEmpty())
  58626. {
  58627. if (index == sectionIndex)
  58628. return section->isOpen();
  58629. ++index;
  58630. }
  58631. }
  58632. return false;
  58633. }
  58634. void PropertyPanel::setSectionOpen (const int sectionIndex, const bool shouldBeOpen)
  58635. {
  58636. int index = 0;
  58637. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  58638. {
  58639. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  58640. if (section != 0 && section->getName().isNotEmpty())
  58641. {
  58642. if (index == sectionIndex)
  58643. {
  58644. section->setOpen (shouldBeOpen);
  58645. break;
  58646. }
  58647. ++index;
  58648. }
  58649. }
  58650. }
  58651. void PropertyPanel::setSectionEnabled (const int sectionIndex, const bool shouldBeEnabled)
  58652. {
  58653. int index = 0;
  58654. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  58655. {
  58656. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  58657. if (section != 0 && section->getName().isNotEmpty())
  58658. {
  58659. if (index == sectionIndex)
  58660. {
  58661. section->setEnabled (shouldBeEnabled);
  58662. break;
  58663. }
  58664. ++index;
  58665. }
  58666. }
  58667. }
  58668. XmlElement* PropertyPanel::getOpennessState() const
  58669. {
  58670. XmlElement* const xml = new XmlElement ("PROPERTYPANELSTATE");
  58671. xml->setAttribute ("scrollPos", viewport.getViewPositionY());
  58672. const StringArray sections (getSectionNames());
  58673. for (int i = 0; i < sections.size(); ++i)
  58674. {
  58675. if (sections[i].isNotEmpty())
  58676. {
  58677. XmlElement* const e = xml->createNewChildElement ("SECTION");
  58678. e->setAttribute ("name", sections[i]);
  58679. e->setAttribute ("open", isSectionOpen (i) ? 1 : 0);
  58680. }
  58681. }
  58682. return xml;
  58683. }
  58684. void PropertyPanel::restoreOpennessState (const XmlElement& xml)
  58685. {
  58686. if (xml.hasTagName ("PROPERTYPANELSTATE"))
  58687. {
  58688. const StringArray sections (getSectionNames());
  58689. forEachXmlChildElementWithTagName (xml, e, "SECTION")
  58690. {
  58691. setSectionOpen (sections.indexOf (e->getStringAttribute ("name")),
  58692. e->getBoolAttribute ("open"));
  58693. }
  58694. viewport.setViewPosition (viewport.getViewPositionX(),
  58695. xml.getIntAttribute ("scrollPos", viewport.getViewPositionY()));
  58696. }
  58697. }
  58698. void PropertyPanel::setMessageWhenEmpty (const String& newMessage)
  58699. {
  58700. if (messageWhenEmpty != newMessage)
  58701. {
  58702. messageWhenEmpty = newMessage;
  58703. repaint();
  58704. }
  58705. }
  58706. const String& PropertyPanel::getMessageWhenEmpty() const
  58707. {
  58708. return messageWhenEmpty;
  58709. }
  58710. END_JUCE_NAMESPACE
  58711. /*** End of inlined file: juce_PropertyPanel.cpp ***/
  58712. /*** Start of inlined file: juce_SliderPropertyComponent.cpp ***/
  58713. BEGIN_JUCE_NAMESPACE
  58714. SliderPropertyComponent::SliderPropertyComponent (const String& name,
  58715. const double rangeMin,
  58716. const double rangeMax,
  58717. const double interval,
  58718. const double skewFactor)
  58719. : PropertyComponent (name)
  58720. {
  58721. addAndMakeVisible (&slider);
  58722. slider.setRange (rangeMin, rangeMax, interval);
  58723. slider.setSkewFactor (skewFactor);
  58724. slider.setSliderStyle (Slider::LinearBar);
  58725. slider.addListener (this);
  58726. }
  58727. SliderPropertyComponent::SliderPropertyComponent (const Value& valueToControl,
  58728. const String& name,
  58729. const double rangeMin,
  58730. const double rangeMax,
  58731. const double interval,
  58732. const double skewFactor)
  58733. : PropertyComponent (name)
  58734. {
  58735. addAndMakeVisible (&slider);
  58736. slider.setRange (rangeMin, rangeMax, interval);
  58737. slider.setSkewFactor (skewFactor);
  58738. slider.setSliderStyle (Slider::LinearBar);
  58739. slider.getValueObject().referTo (valueToControl);
  58740. }
  58741. SliderPropertyComponent::~SliderPropertyComponent()
  58742. {
  58743. }
  58744. void SliderPropertyComponent::setValue (const double /*newValue*/)
  58745. {
  58746. }
  58747. double SliderPropertyComponent::getValue() const
  58748. {
  58749. return slider.getValue();
  58750. }
  58751. void SliderPropertyComponent::refresh()
  58752. {
  58753. slider.setValue (getValue(), false);
  58754. }
  58755. void SliderPropertyComponent::sliderValueChanged (Slider*)
  58756. {
  58757. if (getValue() != slider.getValue())
  58758. setValue (slider.getValue());
  58759. }
  58760. END_JUCE_NAMESPACE
  58761. /*** End of inlined file: juce_SliderPropertyComponent.cpp ***/
  58762. /*** Start of inlined file: juce_TextPropertyComponent.cpp ***/
  58763. BEGIN_JUCE_NAMESPACE
  58764. class TextPropLabel : public Label
  58765. {
  58766. TextPropertyComponent& owner;
  58767. int maxChars;
  58768. bool isMultiline;
  58769. public:
  58770. TextPropLabel (TextPropertyComponent& owner_,
  58771. const int maxChars_, const bool isMultiline_)
  58772. : Label (String::empty, String::empty),
  58773. owner (owner_),
  58774. maxChars (maxChars_),
  58775. isMultiline (isMultiline_)
  58776. {
  58777. setEditable (true, true, false);
  58778. setColour (backgroundColourId, Colours::white);
  58779. setColour (outlineColourId, findColour (ComboBox::outlineColourId));
  58780. }
  58781. ~TextPropLabel()
  58782. {
  58783. }
  58784. TextEditor* createEditorComponent()
  58785. {
  58786. TextEditor* const textEditor = Label::createEditorComponent();
  58787. textEditor->setInputRestrictions (maxChars);
  58788. if (isMultiline)
  58789. {
  58790. textEditor->setMultiLine (true, true);
  58791. textEditor->setReturnKeyStartsNewLine (true);
  58792. }
  58793. return textEditor;
  58794. }
  58795. void textWasEdited()
  58796. {
  58797. owner.textWasEdited();
  58798. }
  58799. };
  58800. TextPropertyComponent::TextPropertyComponent (const String& name,
  58801. const int maxNumChars,
  58802. const bool isMultiLine)
  58803. : PropertyComponent (name)
  58804. {
  58805. createEditor (maxNumChars, isMultiLine);
  58806. }
  58807. TextPropertyComponent::TextPropertyComponent (const Value& valueToControl,
  58808. const String& name,
  58809. const int maxNumChars,
  58810. const bool isMultiLine)
  58811. : PropertyComponent (name)
  58812. {
  58813. createEditor (maxNumChars, isMultiLine);
  58814. textEditor->getTextValue().referTo (valueToControl);
  58815. }
  58816. TextPropertyComponent::~TextPropertyComponent()
  58817. {
  58818. deleteAllChildren();
  58819. }
  58820. void TextPropertyComponent::setText (const String& newText)
  58821. {
  58822. textEditor->setText (newText, true);
  58823. }
  58824. const String TextPropertyComponent::getText() const
  58825. {
  58826. return textEditor->getText();
  58827. }
  58828. void TextPropertyComponent::createEditor (const int maxNumChars, const bool isMultiLine)
  58829. {
  58830. addAndMakeVisible (textEditor = new TextPropLabel (*this, maxNumChars, isMultiLine));
  58831. if (isMultiLine)
  58832. {
  58833. textEditor->setJustificationType (Justification::topLeft);
  58834. preferredHeight = 120;
  58835. }
  58836. }
  58837. void TextPropertyComponent::refresh()
  58838. {
  58839. textEditor->setText (getText(), false);
  58840. }
  58841. void TextPropertyComponent::textWasEdited()
  58842. {
  58843. const String newText (textEditor->getText());
  58844. if (getText() != newText)
  58845. setText (newText);
  58846. }
  58847. END_JUCE_NAMESPACE
  58848. /*** End of inlined file: juce_TextPropertyComponent.cpp ***/
  58849. /*** Start of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  58850. BEGIN_JUCE_NAMESPACE
  58851. class SimpleDeviceManagerInputLevelMeter : public Component,
  58852. public Timer
  58853. {
  58854. public:
  58855. SimpleDeviceManagerInputLevelMeter (AudioDeviceManager* const manager_)
  58856. : manager (manager_),
  58857. level (0)
  58858. {
  58859. startTimer (50);
  58860. manager->enableInputLevelMeasurement (true);
  58861. }
  58862. ~SimpleDeviceManagerInputLevelMeter()
  58863. {
  58864. manager->enableInputLevelMeasurement (false);
  58865. }
  58866. void timerCallback()
  58867. {
  58868. const float newLevel = (float) manager->getCurrentInputLevel();
  58869. if (std::abs (level - newLevel) > 0.005f)
  58870. {
  58871. level = newLevel;
  58872. repaint();
  58873. }
  58874. }
  58875. void paint (Graphics& g)
  58876. {
  58877. getLookAndFeel().drawLevelMeter (g, getWidth(), getHeight(),
  58878. (float) exp (log (level) / 3.0)); // (add a bit of a skew to make the level more obvious)
  58879. }
  58880. private:
  58881. AudioDeviceManager* const manager;
  58882. float level;
  58883. SimpleDeviceManagerInputLevelMeter (const SimpleDeviceManagerInputLevelMeter&);
  58884. SimpleDeviceManagerInputLevelMeter& operator= (const SimpleDeviceManagerInputLevelMeter&);
  58885. };
  58886. class AudioDeviceSelectorComponent::MidiInputSelectorComponentListBox : public ListBox,
  58887. public ListBoxModel
  58888. {
  58889. public:
  58890. MidiInputSelectorComponentListBox (AudioDeviceManager& deviceManager_,
  58891. const String& noItemsMessage_,
  58892. const int minNumber_,
  58893. const int maxNumber_)
  58894. : ListBox (String::empty, 0),
  58895. deviceManager (deviceManager_),
  58896. noItemsMessage (noItemsMessage_),
  58897. minNumber (minNumber_),
  58898. maxNumber (maxNumber_)
  58899. {
  58900. items = MidiInput::getDevices();
  58901. setModel (this);
  58902. setOutlineThickness (1);
  58903. }
  58904. ~MidiInputSelectorComponentListBox()
  58905. {
  58906. }
  58907. int getNumRows()
  58908. {
  58909. return items.size();
  58910. }
  58911. void paintListBoxItem (int row,
  58912. Graphics& g,
  58913. int width, int height,
  58914. bool rowIsSelected)
  58915. {
  58916. if (((unsigned int) row) < (unsigned int) items.size())
  58917. {
  58918. if (rowIsSelected)
  58919. g.fillAll (findColour (TextEditor::highlightColourId)
  58920. .withMultipliedAlpha (0.3f));
  58921. const String item (items [row]);
  58922. bool enabled = deviceManager.isMidiInputEnabled (item);
  58923. const int x = getTickX();
  58924. const float tickW = height * 0.75f;
  58925. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  58926. enabled, true, true, false);
  58927. g.setFont (height * 0.6f);
  58928. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  58929. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  58930. }
  58931. }
  58932. void listBoxItemClicked (int row, const MouseEvent& e)
  58933. {
  58934. selectRow (row);
  58935. if (e.x < getTickX())
  58936. flipEnablement (row);
  58937. }
  58938. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  58939. {
  58940. flipEnablement (row);
  58941. }
  58942. void returnKeyPressed (int row)
  58943. {
  58944. flipEnablement (row);
  58945. }
  58946. void paint (Graphics& g)
  58947. {
  58948. ListBox::paint (g);
  58949. if (items.size() == 0)
  58950. {
  58951. g.setColour (Colours::grey);
  58952. g.setFont (13.0f);
  58953. g.drawText (noItemsMessage,
  58954. 0, 0, getWidth(), getHeight() / 2,
  58955. Justification::centred, true);
  58956. }
  58957. }
  58958. int getBestHeight (const int preferredHeight)
  58959. {
  58960. const int extra = getOutlineThickness() * 2;
  58961. return jmax (getRowHeight() * 2 + extra,
  58962. jmin (getRowHeight() * getNumRows() + extra,
  58963. preferredHeight));
  58964. }
  58965. juce_UseDebuggingNewOperator
  58966. private:
  58967. AudioDeviceManager& deviceManager;
  58968. const String noItemsMessage;
  58969. StringArray items;
  58970. int minNumber, maxNumber;
  58971. void flipEnablement (const int row)
  58972. {
  58973. if (((unsigned int) row) < (unsigned int) items.size())
  58974. {
  58975. const String item (items [row]);
  58976. deviceManager.setMidiInputEnabled (item, ! deviceManager.isMidiInputEnabled (item));
  58977. }
  58978. }
  58979. int getTickX() const
  58980. {
  58981. return getRowHeight() + 5;
  58982. }
  58983. MidiInputSelectorComponentListBox (const MidiInputSelectorComponentListBox&);
  58984. MidiInputSelectorComponentListBox& operator= (const MidiInputSelectorComponentListBox&);
  58985. };
  58986. class AudioDeviceSettingsPanel : public Component,
  58987. public ChangeListener,
  58988. public ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  58989. public ButtonListener
  58990. {
  58991. public:
  58992. AudioDeviceSettingsPanel (AudioIODeviceType* type_,
  58993. AudioIODeviceType::DeviceSetupDetails& setup_,
  58994. const bool hideAdvancedOptionsWithButton)
  58995. : type (type_),
  58996. setup (setup_)
  58997. {
  58998. if (hideAdvancedOptionsWithButton)
  58999. {
  59000. addAndMakeVisible (showAdvancedSettingsButton = new TextButton (TRANS("Show advanced settings...")));
  59001. showAdvancedSettingsButton->addButtonListener (this);
  59002. }
  59003. type->scanForDevices();
  59004. setup.manager->addChangeListener (this);
  59005. changeListenerCallback (0);
  59006. }
  59007. ~AudioDeviceSettingsPanel()
  59008. {
  59009. setup.manager->removeChangeListener (this);
  59010. }
  59011. void resized()
  59012. {
  59013. const int lx = proportionOfWidth (0.35f);
  59014. const int w = proportionOfWidth (0.4f);
  59015. const int h = 24;
  59016. const int space = 6;
  59017. const int dh = h + space;
  59018. int y = 0;
  59019. if (outputDeviceDropDown != 0)
  59020. {
  59021. outputDeviceDropDown->setBounds (lx, y, w, h);
  59022. if (testButton != 0)
  59023. testButton->setBounds (proportionOfWidth (0.77f),
  59024. outputDeviceDropDown->getY(),
  59025. proportionOfWidth (0.18f),
  59026. h);
  59027. y += dh;
  59028. }
  59029. if (inputDeviceDropDown != 0)
  59030. {
  59031. inputDeviceDropDown->setBounds (lx, y, w, h);
  59032. inputLevelMeter->setBounds (proportionOfWidth (0.77f),
  59033. inputDeviceDropDown->getY(),
  59034. proportionOfWidth (0.18f),
  59035. h);
  59036. y += dh;
  59037. }
  59038. const int maxBoxHeight = 100;//(getHeight() - y - dh * 2) / numBoxes;
  59039. if (outputChanList != 0)
  59040. {
  59041. const int bh = outputChanList->getBestHeight (maxBoxHeight);
  59042. outputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  59043. y += bh + space;
  59044. }
  59045. if (inputChanList != 0)
  59046. {
  59047. const int bh = inputChanList->getBestHeight (maxBoxHeight);
  59048. inputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  59049. y += bh + space;
  59050. }
  59051. y += space * 2;
  59052. if (showAdvancedSettingsButton != 0)
  59053. {
  59054. showAdvancedSettingsButton->changeWidthToFitText (h);
  59055. showAdvancedSettingsButton->setTopLeftPosition (lx, y);
  59056. }
  59057. if (sampleRateDropDown != 0)
  59058. {
  59059. sampleRateDropDown->setVisible (showAdvancedSettingsButton == 0
  59060. || ! showAdvancedSettingsButton->isVisible());
  59061. sampleRateDropDown->setBounds (lx, y, w, h);
  59062. y += dh;
  59063. }
  59064. if (bufferSizeDropDown != 0)
  59065. {
  59066. bufferSizeDropDown->setVisible (showAdvancedSettingsButton == 0
  59067. || ! showAdvancedSettingsButton->isVisible());
  59068. bufferSizeDropDown->setBounds (lx, y, w, h);
  59069. y += dh;
  59070. }
  59071. if (showUIButton != 0)
  59072. {
  59073. showUIButton->setVisible (showAdvancedSettingsButton == 0
  59074. || ! showAdvancedSettingsButton->isVisible());
  59075. showUIButton->changeWidthToFitText (h);
  59076. showUIButton->setTopLeftPosition (lx, y);
  59077. }
  59078. }
  59079. void comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  59080. {
  59081. if (comboBoxThatHasChanged == 0)
  59082. return;
  59083. AudioDeviceManager::AudioDeviceSetup config;
  59084. setup.manager->getAudioDeviceSetup (config);
  59085. String error;
  59086. if (comboBoxThatHasChanged == outputDeviceDropDown
  59087. || comboBoxThatHasChanged == inputDeviceDropDown)
  59088. {
  59089. if (outputDeviceDropDown != 0)
  59090. config.outputDeviceName = outputDeviceDropDown->getSelectedId() < 0 ? String::empty
  59091. : outputDeviceDropDown->getText();
  59092. if (inputDeviceDropDown != 0)
  59093. config.inputDeviceName = inputDeviceDropDown->getSelectedId() < 0 ? String::empty
  59094. : inputDeviceDropDown->getText();
  59095. if (! type->hasSeparateInputsAndOutputs())
  59096. config.inputDeviceName = config.outputDeviceName;
  59097. if (comboBoxThatHasChanged == inputDeviceDropDown)
  59098. config.useDefaultInputChannels = true;
  59099. else
  59100. config.useDefaultOutputChannels = true;
  59101. error = setup.manager->setAudioDeviceSetup (config, true);
  59102. showCorrectDeviceName (inputDeviceDropDown, true);
  59103. showCorrectDeviceName (outputDeviceDropDown, false);
  59104. updateControlPanelButton();
  59105. resized();
  59106. }
  59107. else if (comboBoxThatHasChanged == sampleRateDropDown)
  59108. {
  59109. if (sampleRateDropDown->getSelectedId() > 0)
  59110. {
  59111. config.sampleRate = sampleRateDropDown->getSelectedId();
  59112. error = setup.manager->setAudioDeviceSetup (config, true);
  59113. }
  59114. }
  59115. else if (comboBoxThatHasChanged == bufferSizeDropDown)
  59116. {
  59117. if (bufferSizeDropDown->getSelectedId() > 0)
  59118. {
  59119. config.bufferSize = bufferSizeDropDown->getSelectedId();
  59120. error = setup.manager->setAudioDeviceSetup (config, true);
  59121. }
  59122. }
  59123. if (error.isNotEmpty())
  59124. {
  59125. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  59126. "Error when trying to open audio device!",
  59127. error);
  59128. }
  59129. }
  59130. void buttonClicked (Button* button)
  59131. {
  59132. if (button == showAdvancedSettingsButton)
  59133. {
  59134. showAdvancedSettingsButton->setVisible (false);
  59135. resized();
  59136. }
  59137. else if (button == showUIButton)
  59138. {
  59139. AudioIODevice* const device = setup.manager->getCurrentAudioDevice();
  59140. if (device != 0 && device->showControlPanel())
  59141. {
  59142. setup.manager->closeAudioDevice();
  59143. setup.manager->restartLastAudioDevice();
  59144. getTopLevelComponent()->toFront (true);
  59145. }
  59146. }
  59147. else if (button == testButton && testButton != 0)
  59148. {
  59149. setup.manager->playTestSound();
  59150. }
  59151. }
  59152. void updateControlPanelButton()
  59153. {
  59154. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  59155. showUIButton = 0;
  59156. if (currentDevice != 0 && currentDevice->hasControlPanel())
  59157. {
  59158. addAndMakeVisible (showUIButton = new TextButton (TRANS ("show this device's control panel"),
  59159. TRANS ("opens the device's own control panel")));
  59160. showUIButton->addButtonListener (this);
  59161. }
  59162. resized();
  59163. }
  59164. void changeListenerCallback (void*)
  59165. {
  59166. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  59167. if (setup.maxNumOutputChannels > 0 || ! type->hasSeparateInputsAndOutputs())
  59168. {
  59169. if (outputDeviceDropDown == 0)
  59170. {
  59171. outputDeviceDropDown = new ComboBox (String::empty);
  59172. outputDeviceDropDown->addListener (this);
  59173. addAndMakeVisible (outputDeviceDropDown);
  59174. outputDeviceLabel = new Label (String::empty,
  59175. type->hasSeparateInputsAndOutputs() ? TRANS ("output:")
  59176. : TRANS ("device:"));
  59177. outputDeviceLabel->attachToComponent (outputDeviceDropDown, true);
  59178. if (setup.maxNumOutputChannels > 0)
  59179. {
  59180. addAndMakeVisible (testButton = new TextButton (TRANS ("Test")));
  59181. testButton->addButtonListener (this);
  59182. }
  59183. }
  59184. addNamesToDeviceBox (*outputDeviceDropDown, false);
  59185. }
  59186. if (setup.maxNumInputChannels > 0 && type->hasSeparateInputsAndOutputs())
  59187. {
  59188. if (inputDeviceDropDown == 0)
  59189. {
  59190. inputDeviceDropDown = new ComboBox (String::empty);
  59191. inputDeviceDropDown->addListener (this);
  59192. addAndMakeVisible (inputDeviceDropDown);
  59193. inputDeviceLabel = new Label (String::empty, TRANS ("input:"));
  59194. inputDeviceLabel->attachToComponent (inputDeviceDropDown, true);
  59195. addAndMakeVisible (inputLevelMeter
  59196. = new SimpleDeviceManagerInputLevelMeter (setup.manager));
  59197. }
  59198. addNamesToDeviceBox (*inputDeviceDropDown, true);
  59199. }
  59200. updateControlPanelButton();
  59201. showCorrectDeviceName (inputDeviceDropDown, true);
  59202. showCorrectDeviceName (outputDeviceDropDown, false);
  59203. if (currentDevice != 0)
  59204. {
  59205. if (setup.maxNumOutputChannels > 0
  59206. && setup.minNumOutputChannels < setup.manager->getCurrentAudioDevice()->getOutputChannelNames().size())
  59207. {
  59208. if (outputChanList == 0)
  59209. {
  59210. addAndMakeVisible (outputChanList
  59211. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioOutputType,
  59212. TRANS ("(no audio output channels found)")));
  59213. outputChanLabel = new Label (String::empty, TRANS ("active output channels:"));
  59214. outputChanLabel->attachToComponent (outputChanList, true);
  59215. }
  59216. outputChanList->refresh();
  59217. }
  59218. else
  59219. {
  59220. outputChanLabel = 0;
  59221. outputChanList = 0;
  59222. }
  59223. if (setup.maxNumInputChannels > 0
  59224. && setup.minNumInputChannels < setup.manager->getCurrentAudioDevice()->getInputChannelNames().size())
  59225. {
  59226. if (inputChanList == 0)
  59227. {
  59228. addAndMakeVisible (inputChanList
  59229. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioInputType,
  59230. TRANS ("(no audio input channels found)")));
  59231. inputChanLabel = new Label (String::empty, TRANS ("active input channels:"));
  59232. inputChanLabel->attachToComponent (inputChanList, true);
  59233. }
  59234. inputChanList->refresh();
  59235. }
  59236. else
  59237. {
  59238. inputChanLabel = 0;
  59239. inputChanList = 0;
  59240. }
  59241. // sample rate..
  59242. {
  59243. if (sampleRateDropDown == 0)
  59244. {
  59245. addAndMakeVisible (sampleRateDropDown = new ComboBox (String::empty));
  59246. sampleRateLabel = new Label (String::empty, TRANS ("sample rate:"));
  59247. sampleRateLabel->attachToComponent (sampleRateDropDown, true);
  59248. }
  59249. else
  59250. {
  59251. sampleRateDropDown->clear();
  59252. sampleRateDropDown->removeListener (this);
  59253. }
  59254. const int numRates = currentDevice->getNumSampleRates();
  59255. for (int i = 0; i < numRates; ++i)
  59256. {
  59257. const int rate = roundToInt (currentDevice->getSampleRate (i));
  59258. sampleRateDropDown->addItem (String (rate) + " Hz", rate);
  59259. }
  59260. sampleRateDropDown->setSelectedId (roundToInt (currentDevice->getCurrentSampleRate()), true);
  59261. sampleRateDropDown->addListener (this);
  59262. }
  59263. // buffer size
  59264. {
  59265. if (bufferSizeDropDown == 0)
  59266. {
  59267. addAndMakeVisible (bufferSizeDropDown = new ComboBox (String::empty));
  59268. bufferSizeLabel = new Label (String::empty, TRANS ("audio buffer size:"));
  59269. bufferSizeLabel->attachToComponent (bufferSizeDropDown, true);
  59270. }
  59271. else
  59272. {
  59273. bufferSizeDropDown->clear();
  59274. bufferSizeDropDown->removeListener (this);
  59275. }
  59276. const int numBufferSizes = currentDevice->getNumBufferSizesAvailable();
  59277. double currentRate = currentDevice->getCurrentSampleRate();
  59278. if (currentRate == 0)
  59279. currentRate = 48000.0;
  59280. for (int i = 0; i < numBufferSizes; ++i)
  59281. {
  59282. const int bs = currentDevice->getBufferSizeSamples (i);
  59283. bufferSizeDropDown->addItem (String (bs)
  59284. + " samples ("
  59285. + String (bs * 1000.0 / currentRate, 1)
  59286. + " ms)",
  59287. bs);
  59288. }
  59289. bufferSizeDropDown->setSelectedId (currentDevice->getCurrentBufferSizeSamples(), true);
  59290. bufferSizeDropDown->addListener (this);
  59291. }
  59292. }
  59293. else
  59294. {
  59295. jassert (setup.manager->getCurrentAudioDevice() == 0); // not the correct device type!
  59296. sampleRateLabel = 0;
  59297. bufferSizeLabel = 0;
  59298. sampleRateDropDown = 0;
  59299. bufferSizeDropDown = 0;
  59300. if (outputDeviceDropDown != 0)
  59301. outputDeviceDropDown->setSelectedId (-1, true);
  59302. if (inputDeviceDropDown != 0)
  59303. inputDeviceDropDown->setSelectedId (-1, true);
  59304. }
  59305. resized();
  59306. setSize (getWidth(), getLowestY() + 4);
  59307. }
  59308. private:
  59309. AudioIODeviceType* const type;
  59310. const AudioIODeviceType::DeviceSetupDetails setup;
  59311. ScopedPointer<ComboBox> outputDeviceDropDown, inputDeviceDropDown, sampleRateDropDown, bufferSizeDropDown;
  59312. ScopedPointer<Label> outputDeviceLabel, inputDeviceLabel, sampleRateLabel, bufferSizeLabel, inputChanLabel, outputChanLabel;
  59313. ScopedPointer<TextButton> testButton;
  59314. ScopedPointer<Component> inputLevelMeter;
  59315. ScopedPointer<TextButton> showUIButton, showAdvancedSettingsButton;
  59316. void showCorrectDeviceName (ComboBox* const box, const bool isInput)
  59317. {
  59318. if (box != 0)
  59319. {
  59320. AudioIODevice* const currentDevice = dynamic_cast <AudioIODevice*> (setup.manager->getCurrentAudioDevice());
  59321. const int index = type->getIndexOfDevice (currentDevice, isInput);
  59322. box->setSelectedId (index + 1, true);
  59323. if (testButton != 0 && ! isInput)
  59324. testButton->setEnabled (index >= 0);
  59325. }
  59326. }
  59327. void addNamesToDeviceBox (ComboBox& combo, bool isInputs)
  59328. {
  59329. const StringArray devs (type->getDeviceNames (isInputs));
  59330. combo.clear (true);
  59331. for (int i = 0; i < devs.size(); ++i)
  59332. combo.addItem (devs[i], i + 1);
  59333. combo.addItem (TRANS("<< none >>"), -1);
  59334. combo.setSelectedId (-1, true);
  59335. }
  59336. int getLowestY() const
  59337. {
  59338. int y = 0;
  59339. for (int i = getNumChildComponents(); --i >= 0;)
  59340. y = jmax (y, getChildComponent (i)->getBottom());
  59341. return y;
  59342. }
  59343. public:
  59344. class ChannelSelectorListBox : public ListBox,
  59345. public ListBoxModel
  59346. {
  59347. public:
  59348. enum BoxType
  59349. {
  59350. audioInputType,
  59351. audioOutputType
  59352. };
  59353. ChannelSelectorListBox (const AudioIODeviceType::DeviceSetupDetails& setup_,
  59354. const BoxType type_,
  59355. const String& noItemsMessage_)
  59356. : ListBox (String::empty, 0),
  59357. setup (setup_),
  59358. type (type_),
  59359. noItemsMessage (noItemsMessage_)
  59360. {
  59361. refresh();
  59362. setModel (this);
  59363. setOutlineThickness (1);
  59364. }
  59365. ~ChannelSelectorListBox()
  59366. {
  59367. }
  59368. void refresh()
  59369. {
  59370. items.clear();
  59371. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  59372. if (currentDevice != 0)
  59373. {
  59374. if (type == audioInputType)
  59375. items = currentDevice->getInputChannelNames();
  59376. else if (type == audioOutputType)
  59377. items = currentDevice->getOutputChannelNames();
  59378. if (setup.useStereoPairs)
  59379. {
  59380. StringArray pairs;
  59381. for (int i = 0; i < items.size(); i += 2)
  59382. {
  59383. const String name (items[i]);
  59384. const String name2 (items[i + 1]);
  59385. String commonBit;
  59386. for (int j = 0; j < name.length(); ++j)
  59387. if (name.substring (0, j).equalsIgnoreCase (name2.substring (0, j)))
  59388. commonBit = name.substring (0, j);
  59389. // Make sure we only split the name at a space, because otherwise, things
  59390. // like "input 11" + "input 12" would become "input 11 + 2"
  59391. while (commonBit.isNotEmpty() && ! CharacterFunctions::isWhitespace (commonBit.getLastCharacter()))
  59392. commonBit = commonBit.dropLastCharacters (1);
  59393. pairs.add (name.trim() + " + " + name2.substring (commonBit.length()).trim());
  59394. }
  59395. items = pairs;
  59396. }
  59397. }
  59398. updateContent();
  59399. repaint();
  59400. }
  59401. int getNumRows()
  59402. {
  59403. return items.size();
  59404. }
  59405. void paintListBoxItem (int row,
  59406. Graphics& g,
  59407. int width, int height,
  59408. bool rowIsSelected)
  59409. {
  59410. if (((unsigned int) row) < (unsigned int) items.size())
  59411. {
  59412. if (rowIsSelected)
  59413. g.fillAll (findColour (TextEditor::highlightColourId)
  59414. .withMultipliedAlpha (0.3f));
  59415. const String item (items [row]);
  59416. bool enabled = false;
  59417. AudioDeviceManager::AudioDeviceSetup config;
  59418. setup.manager->getAudioDeviceSetup (config);
  59419. if (setup.useStereoPairs)
  59420. {
  59421. if (type == audioInputType)
  59422. enabled = config.inputChannels [row * 2] || config.inputChannels [row * 2 + 1];
  59423. else if (type == audioOutputType)
  59424. enabled = config.outputChannels [row * 2] || config.outputChannels [row * 2 + 1];
  59425. }
  59426. else
  59427. {
  59428. if (type == audioInputType)
  59429. enabled = config.inputChannels [row];
  59430. else if (type == audioOutputType)
  59431. enabled = config.outputChannels [row];
  59432. }
  59433. const int x = getTickX();
  59434. const float tickW = height * 0.75f;
  59435. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  59436. enabled, true, true, false);
  59437. g.setFont (height * 0.6f);
  59438. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  59439. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  59440. }
  59441. }
  59442. void listBoxItemClicked (int row, const MouseEvent& e)
  59443. {
  59444. selectRow (row);
  59445. if (e.x < getTickX())
  59446. flipEnablement (row);
  59447. }
  59448. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  59449. {
  59450. flipEnablement (row);
  59451. }
  59452. void returnKeyPressed (int row)
  59453. {
  59454. flipEnablement (row);
  59455. }
  59456. void paint (Graphics& g)
  59457. {
  59458. ListBox::paint (g);
  59459. if (items.size() == 0)
  59460. {
  59461. g.setColour (Colours::grey);
  59462. g.setFont (13.0f);
  59463. g.drawText (noItemsMessage,
  59464. 0, 0, getWidth(), getHeight() / 2,
  59465. Justification::centred, true);
  59466. }
  59467. }
  59468. int getBestHeight (int maxHeight)
  59469. {
  59470. return getRowHeight() * jlimit (2, jmax (2, maxHeight / getRowHeight()),
  59471. getNumRows())
  59472. + getOutlineThickness() * 2;
  59473. }
  59474. juce_UseDebuggingNewOperator
  59475. private:
  59476. const AudioIODeviceType::DeviceSetupDetails setup;
  59477. const BoxType type;
  59478. const String noItemsMessage;
  59479. StringArray items;
  59480. void flipEnablement (const int row)
  59481. {
  59482. jassert (type == audioInputType || type == audioOutputType);
  59483. if (((unsigned int) row) < (unsigned int) items.size())
  59484. {
  59485. AudioDeviceManager::AudioDeviceSetup config;
  59486. setup.manager->getAudioDeviceSetup (config);
  59487. if (setup.useStereoPairs)
  59488. {
  59489. BigInteger bits;
  59490. BigInteger& original = (type == audioInputType ? config.inputChannels
  59491. : config.outputChannels);
  59492. int i;
  59493. for (i = 0; i < 256; i += 2)
  59494. bits.setBit (i / 2, original [i] || original [i + 1]);
  59495. if (type == audioInputType)
  59496. {
  59497. config.useDefaultInputChannels = false;
  59498. flipBit (bits, row, setup.minNumInputChannels / 2, setup.maxNumInputChannels / 2);
  59499. }
  59500. else
  59501. {
  59502. config.useDefaultOutputChannels = false;
  59503. flipBit (bits, row, setup.minNumOutputChannels / 2, setup.maxNumOutputChannels / 2);
  59504. }
  59505. for (i = 0; i < 256; ++i)
  59506. original.setBit (i, bits [i / 2]);
  59507. }
  59508. else
  59509. {
  59510. if (type == audioInputType)
  59511. {
  59512. config.useDefaultInputChannels = false;
  59513. flipBit (config.inputChannels, row, setup.minNumInputChannels, setup.maxNumInputChannels);
  59514. }
  59515. else
  59516. {
  59517. config.useDefaultOutputChannels = false;
  59518. flipBit (config.outputChannels, row, setup.minNumOutputChannels, setup.maxNumOutputChannels);
  59519. }
  59520. }
  59521. String error (setup.manager->setAudioDeviceSetup (config, true));
  59522. if (! error.isEmpty())
  59523. {
  59524. //xxx
  59525. }
  59526. }
  59527. }
  59528. static void flipBit (BigInteger& chans, int index, int minNumber, int maxNumber)
  59529. {
  59530. const int numActive = chans.countNumberOfSetBits();
  59531. if (chans [index])
  59532. {
  59533. if (numActive > minNumber)
  59534. chans.setBit (index, false);
  59535. }
  59536. else
  59537. {
  59538. if (numActive >= maxNumber)
  59539. {
  59540. const int firstActiveChan = chans.findNextSetBit();
  59541. chans.setBit (index > firstActiveChan
  59542. ? firstActiveChan : chans.getHighestBit(),
  59543. false);
  59544. }
  59545. chans.setBit (index, true);
  59546. }
  59547. }
  59548. int getTickX() const
  59549. {
  59550. return getRowHeight() + 5;
  59551. }
  59552. ChannelSelectorListBox (const ChannelSelectorListBox&);
  59553. ChannelSelectorListBox& operator= (const ChannelSelectorListBox&);
  59554. };
  59555. private:
  59556. ScopedPointer<ChannelSelectorListBox> inputChanList, outputChanList;
  59557. AudioDeviceSettingsPanel (const AudioDeviceSettingsPanel&);
  59558. AudioDeviceSettingsPanel& operator= (const AudioDeviceSettingsPanel&);
  59559. };
  59560. AudioDeviceSelectorComponent::AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager_,
  59561. const int minInputChannels_,
  59562. const int maxInputChannels_,
  59563. const int minOutputChannels_,
  59564. const int maxOutputChannels_,
  59565. const bool showMidiInputOptions,
  59566. const bool showMidiOutputSelector,
  59567. const bool showChannelsAsStereoPairs_,
  59568. const bool hideAdvancedOptionsWithButton_)
  59569. : deviceManager (deviceManager_),
  59570. deviceTypeDropDown (0),
  59571. deviceTypeDropDownLabel (0),
  59572. minOutputChannels (minOutputChannels_),
  59573. maxOutputChannels (maxOutputChannels_),
  59574. minInputChannels (minInputChannels_),
  59575. maxInputChannels (maxInputChannels_),
  59576. showChannelsAsStereoPairs (showChannelsAsStereoPairs_),
  59577. hideAdvancedOptionsWithButton (hideAdvancedOptionsWithButton_)
  59578. {
  59579. jassert (minOutputChannels >= 0 && minOutputChannels <= maxOutputChannels);
  59580. jassert (minInputChannels >= 0 && minInputChannels <= maxInputChannels);
  59581. if (deviceManager_.getAvailableDeviceTypes().size() > 1)
  59582. {
  59583. deviceTypeDropDown = new ComboBox (String::empty);
  59584. for (int i = 0; i < deviceManager_.getAvailableDeviceTypes().size(); ++i)
  59585. {
  59586. deviceTypeDropDown
  59587. ->addItem (deviceManager_.getAvailableDeviceTypes().getUnchecked(i)->getTypeName(),
  59588. i + 1);
  59589. }
  59590. addAndMakeVisible (deviceTypeDropDown);
  59591. deviceTypeDropDown->addListener (this);
  59592. deviceTypeDropDownLabel = new Label (String::empty, TRANS ("audio device type:"));
  59593. deviceTypeDropDownLabel->setJustificationType (Justification::centredRight);
  59594. deviceTypeDropDownLabel->attachToComponent (deviceTypeDropDown, true);
  59595. }
  59596. if (showMidiInputOptions)
  59597. {
  59598. addAndMakeVisible (midiInputsList
  59599. = new MidiInputSelectorComponentListBox (deviceManager,
  59600. TRANS("(no midi inputs available)"),
  59601. 0, 0));
  59602. midiInputsLabel = new Label (String::empty, TRANS ("active midi inputs:"));
  59603. midiInputsLabel->setJustificationType (Justification::topRight);
  59604. midiInputsLabel->attachToComponent (midiInputsList, true);
  59605. }
  59606. else
  59607. {
  59608. midiInputsList = 0;
  59609. midiInputsLabel = 0;
  59610. }
  59611. if (showMidiOutputSelector)
  59612. {
  59613. addAndMakeVisible (midiOutputSelector = new ComboBox (String::empty));
  59614. midiOutputSelector->addListener (this);
  59615. midiOutputLabel = new Label ("lm", TRANS("Midi Output:"));
  59616. midiOutputLabel->attachToComponent (midiOutputSelector, true);
  59617. }
  59618. else
  59619. {
  59620. midiOutputSelector = 0;
  59621. midiOutputLabel = 0;
  59622. }
  59623. deviceManager_.addChangeListener (this);
  59624. changeListenerCallback (0);
  59625. }
  59626. AudioDeviceSelectorComponent::~AudioDeviceSelectorComponent()
  59627. {
  59628. deviceManager.removeChangeListener (this);
  59629. }
  59630. void AudioDeviceSelectorComponent::resized()
  59631. {
  59632. const int lx = proportionOfWidth (0.35f);
  59633. const int w = proportionOfWidth (0.4f);
  59634. const int h = 24;
  59635. const int space = 6;
  59636. const int dh = h + space;
  59637. int y = 15;
  59638. if (deviceTypeDropDown != 0)
  59639. {
  59640. deviceTypeDropDown->setBounds (lx, y, proportionOfWidth (0.3f), h);
  59641. y += dh + space * 2;
  59642. }
  59643. if (audioDeviceSettingsComp != 0)
  59644. {
  59645. audioDeviceSettingsComp->setBounds (0, y, getWidth(), audioDeviceSettingsComp->getHeight());
  59646. y += audioDeviceSettingsComp->getHeight() + space;
  59647. }
  59648. if (midiInputsList != 0)
  59649. {
  59650. const int bh = midiInputsList->getBestHeight (jmin (h * 8, getHeight() - y - space - h));
  59651. midiInputsList->setBounds (lx, y, w, bh);
  59652. y += bh + space;
  59653. }
  59654. if (midiOutputSelector != 0)
  59655. midiOutputSelector->setBounds (lx, y, w, h);
  59656. }
  59657. void AudioDeviceSelectorComponent::childBoundsChanged (Component* child)
  59658. {
  59659. if (child == audioDeviceSettingsComp)
  59660. resized();
  59661. }
  59662. void AudioDeviceSelectorComponent::buttonClicked (Button*)
  59663. {
  59664. AudioIODevice* const device = deviceManager.getCurrentAudioDevice();
  59665. if (device != 0 && device->hasControlPanel())
  59666. {
  59667. if (device->showControlPanel())
  59668. deviceManager.restartLastAudioDevice();
  59669. getTopLevelComponent()->toFront (true);
  59670. }
  59671. }
  59672. void AudioDeviceSelectorComponent::comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  59673. {
  59674. if (comboBoxThatHasChanged == deviceTypeDropDown)
  59675. {
  59676. AudioIODeviceType* const type = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown->getSelectedId() - 1];
  59677. if (type != 0)
  59678. {
  59679. audioDeviceSettingsComp = 0;
  59680. deviceManager.setCurrentAudioDeviceType (type->getTypeName(), true);
  59681. changeListenerCallback (0); // needed in case the type hasn't actally changed
  59682. }
  59683. }
  59684. else if (comboBoxThatHasChanged == midiOutputSelector)
  59685. {
  59686. deviceManager.setDefaultMidiOutput (midiOutputSelector->getText());
  59687. }
  59688. }
  59689. void AudioDeviceSelectorComponent::changeListenerCallback (void*)
  59690. {
  59691. if (deviceTypeDropDown != 0)
  59692. {
  59693. deviceTypeDropDown->setText (deviceManager.getCurrentAudioDeviceType(), false);
  59694. }
  59695. if (audioDeviceSettingsComp == 0
  59696. || audioDeviceSettingsCompType != deviceManager.getCurrentAudioDeviceType())
  59697. {
  59698. audioDeviceSettingsCompType = deviceManager.getCurrentAudioDeviceType();
  59699. audioDeviceSettingsComp = 0;
  59700. AudioIODeviceType* const type
  59701. = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown == 0
  59702. ? 0 : deviceTypeDropDown->getSelectedId() - 1];
  59703. if (type != 0)
  59704. {
  59705. AudioIODeviceType::DeviceSetupDetails details;
  59706. details.manager = &deviceManager;
  59707. details.minNumInputChannels = minInputChannels;
  59708. details.maxNumInputChannels = maxInputChannels;
  59709. details.minNumOutputChannels = minOutputChannels;
  59710. details.maxNumOutputChannels = maxOutputChannels;
  59711. details.useStereoPairs = showChannelsAsStereoPairs;
  59712. audioDeviceSettingsComp = new AudioDeviceSettingsPanel (type, details, hideAdvancedOptionsWithButton);
  59713. if (audioDeviceSettingsComp != 0)
  59714. {
  59715. addAndMakeVisible (audioDeviceSettingsComp);
  59716. audioDeviceSettingsComp->resized();
  59717. }
  59718. }
  59719. }
  59720. if (midiInputsList != 0)
  59721. {
  59722. midiInputsList->updateContent();
  59723. midiInputsList->repaint();
  59724. }
  59725. if (midiOutputSelector != 0)
  59726. {
  59727. midiOutputSelector->clear();
  59728. const StringArray midiOuts (MidiOutput::getDevices());
  59729. midiOutputSelector->addItem (TRANS("<< none >>"), -1);
  59730. midiOutputSelector->addSeparator();
  59731. for (int i = 0; i < midiOuts.size(); ++i)
  59732. midiOutputSelector->addItem (midiOuts[i], i + 1);
  59733. int current = -1;
  59734. if (deviceManager.getDefaultMidiOutput() != 0)
  59735. current = 1 + midiOuts.indexOf (deviceManager.getDefaultMidiOutputName());
  59736. midiOutputSelector->setSelectedId (current, true);
  59737. }
  59738. resized();
  59739. }
  59740. END_JUCE_NAMESPACE
  59741. /*** End of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  59742. /*** Start of inlined file: juce_BubbleComponent.cpp ***/
  59743. BEGIN_JUCE_NAMESPACE
  59744. BubbleComponent::BubbleComponent()
  59745. : side (0),
  59746. allowablePlacements (above | below | left | right),
  59747. arrowTipX (0.0f),
  59748. arrowTipY (0.0f)
  59749. {
  59750. setInterceptsMouseClicks (false, false);
  59751. shadow.setShadowProperties (5.0f, 0.35f, 0, 0);
  59752. setComponentEffect (&shadow);
  59753. }
  59754. BubbleComponent::~BubbleComponent()
  59755. {
  59756. }
  59757. void BubbleComponent::paint (Graphics& g)
  59758. {
  59759. int x = content.getX();
  59760. int y = content.getY();
  59761. int w = content.getWidth();
  59762. int h = content.getHeight();
  59763. int cw, ch;
  59764. getContentSize (cw, ch);
  59765. if (side == 3)
  59766. x += w - cw;
  59767. else if (side != 1)
  59768. x += (w - cw) / 2;
  59769. w = cw;
  59770. if (side == 2)
  59771. y += h - ch;
  59772. else if (side != 0)
  59773. y += (h - ch) / 2;
  59774. h = ch;
  59775. getLookAndFeel().drawBubble (g, arrowTipX, arrowTipY,
  59776. (float) x, (float) y,
  59777. (float) w, (float) h);
  59778. const int cx = x + (w - cw) / 2;
  59779. const int cy = y + (h - ch) / 2;
  59780. const int indent = 3;
  59781. g.setOrigin (cx + indent, cy + indent);
  59782. g.reduceClipRegion (0, 0, cw - indent * 2, ch - indent * 2);
  59783. paintContent (g, cw - indent * 2, ch - indent * 2);
  59784. }
  59785. void BubbleComponent::setAllowedPlacement (const int newPlacement)
  59786. {
  59787. allowablePlacements = newPlacement;
  59788. }
  59789. void BubbleComponent::setPosition (Component* componentToPointTo)
  59790. {
  59791. jassert (componentToPointTo->isValidComponent());
  59792. Point<int> pos;
  59793. if (getParentComponent() != 0)
  59794. pos = componentToPointTo->relativePositionToOtherComponent (getParentComponent(), pos);
  59795. else
  59796. pos = componentToPointTo->relativePositionToGlobal (pos);
  59797. setPosition (Rectangle<int> (pos.getX(), pos.getY(), componentToPointTo->getWidth(), componentToPointTo->getHeight()));
  59798. }
  59799. void BubbleComponent::setPosition (const int arrowTipX_,
  59800. const int arrowTipY_)
  59801. {
  59802. setPosition (Rectangle<int> (arrowTipX_, arrowTipY_, 1, 1));
  59803. }
  59804. void BubbleComponent::setPosition (const Rectangle<int>& rectangleToPointTo)
  59805. {
  59806. Rectangle<int> availableSpace;
  59807. if (getParentComponent() != 0)
  59808. {
  59809. availableSpace.setSize (getParentComponent()->getWidth(),
  59810. getParentComponent()->getHeight());
  59811. }
  59812. else
  59813. {
  59814. availableSpace = getParentMonitorArea();
  59815. }
  59816. int x = 0;
  59817. int y = 0;
  59818. int w = 150;
  59819. int h = 30;
  59820. getContentSize (w, h);
  59821. w += 30;
  59822. h += 30;
  59823. const float edgeIndent = 2.0f;
  59824. const int arrowLength = jmin (10, h / 3, w / 3);
  59825. int spaceAbove = ((allowablePlacements & above) != 0) ? jmax (0, rectangleToPointTo.getY() - availableSpace.getY()) : -1;
  59826. int spaceBelow = ((allowablePlacements & below) != 0) ? jmax (0, availableSpace.getBottom() - rectangleToPointTo.getBottom()) : -1;
  59827. int spaceLeft = ((allowablePlacements & left) != 0) ? jmax (0, rectangleToPointTo.getX() - availableSpace.getX()) : -1;
  59828. int spaceRight = ((allowablePlacements & right) != 0) ? jmax (0, availableSpace.getRight() - rectangleToPointTo.getRight()) : -1;
  59829. // look at whether the component is elongated, and if so, try to position next to its longer dimension.
  59830. if (rectangleToPointTo.getWidth() > rectangleToPointTo.getHeight() * 2
  59831. && (spaceAbove > h + 20 || spaceBelow > h + 20))
  59832. {
  59833. spaceLeft = spaceRight = 0;
  59834. }
  59835. else if (rectangleToPointTo.getWidth() < rectangleToPointTo.getHeight() / 2
  59836. && (spaceLeft > w + 20 || spaceRight > w + 20))
  59837. {
  59838. spaceAbove = spaceBelow = 0;
  59839. }
  59840. if (jmax (spaceAbove, spaceBelow) >= jmax (spaceLeft, spaceRight))
  59841. {
  59842. x = rectangleToPointTo.getX() + (rectangleToPointTo.getWidth() - w) / 2;
  59843. arrowTipX = w * 0.5f;
  59844. content.setSize (w, h - arrowLength);
  59845. if (spaceAbove >= spaceBelow)
  59846. {
  59847. // above
  59848. y = rectangleToPointTo.getY() - h;
  59849. content.setPosition (0, 0);
  59850. arrowTipY = h - edgeIndent;
  59851. side = 2;
  59852. }
  59853. else
  59854. {
  59855. // below
  59856. y = rectangleToPointTo.getBottom();
  59857. content.setPosition (0, arrowLength);
  59858. arrowTipY = edgeIndent;
  59859. side = 0;
  59860. }
  59861. }
  59862. else
  59863. {
  59864. y = rectangleToPointTo.getY() + (rectangleToPointTo.getHeight() - h) / 2;
  59865. arrowTipY = h * 0.5f;
  59866. content.setSize (w - arrowLength, h);
  59867. if (spaceLeft > spaceRight)
  59868. {
  59869. // on the left
  59870. x = rectangleToPointTo.getX() - w;
  59871. content.setPosition (0, 0);
  59872. arrowTipX = w - edgeIndent;
  59873. side = 3;
  59874. }
  59875. else
  59876. {
  59877. // on the right
  59878. x = rectangleToPointTo.getRight();
  59879. content.setPosition (arrowLength, 0);
  59880. arrowTipX = edgeIndent;
  59881. side = 1;
  59882. }
  59883. }
  59884. setBounds (x, y, w, h);
  59885. }
  59886. END_JUCE_NAMESPACE
  59887. /*** End of inlined file: juce_BubbleComponent.cpp ***/
  59888. /*** Start of inlined file: juce_BubbleMessageComponent.cpp ***/
  59889. BEGIN_JUCE_NAMESPACE
  59890. BubbleMessageComponent::BubbleMessageComponent (int fadeOutLengthMs)
  59891. : fadeOutLength (fadeOutLengthMs),
  59892. deleteAfterUse (false)
  59893. {
  59894. }
  59895. BubbleMessageComponent::~BubbleMessageComponent()
  59896. {
  59897. fadeOutComponent (fadeOutLength);
  59898. }
  59899. void BubbleMessageComponent::showAt (int x, int y,
  59900. const String& text,
  59901. const int numMillisecondsBeforeRemoving,
  59902. const bool removeWhenMouseClicked,
  59903. const bool deleteSelfAfterUse)
  59904. {
  59905. textLayout.clear();
  59906. textLayout.setText (text, Font (14.0f));
  59907. textLayout.layout (256, Justification::centredLeft, true);
  59908. setPosition (x, y);
  59909. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  59910. }
  59911. void BubbleMessageComponent::showAt (Component* const component,
  59912. const String& text,
  59913. const int numMillisecondsBeforeRemoving,
  59914. const bool removeWhenMouseClicked,
  59915. const bool deleteSelfAfterUse)
  59916. {
  59917. textLayout.clear();
  59918. textLayout.setText (text, Font (14.0f));
  59919. textLayout.layout (256, Justification::centredLeft, true);
  59920. setPosition (component);
  59921. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  59922. }
  59923. void BubbleMessageComponent::init (const int numMillisecondsBeforeRemoving,
  59924. const bool removeWhenMouseClicked,
  59925. const bool deleteSelfAfterUse)
  59926. {
  59927. setVisible (true);
  59928. deleteAfterUse = deleteSelfAfterUse;
  59929. if (numMillisecondsBeforeRemoving > 0)
  59930. expiryTime = Time::getMillisecondCounter() + numMillisecondsBeforeRemoving;
  59931. else
  59932. expiryTime = 0;
  59933. startTimer (77);
  59934. mouseClickCounter = Desktop::getInstance().getMouseButtonClickCounter();
  59935. if (! (removeWhenMouseClicked && isShowing()))
  59936. mouseClickCounter += 0xfffff;
  59937. repaint();
  59938. }
  59939. void BubbleMessageComponent::getContentSize (int& w, int& h)
  59940. {
  59941. w = textLayout.getWidth() + 16;
  59942. h = textLayout.getHeight() + 16;
  59943. }
  59944. void BubbleMessageComponent::paintContent (Graphics& g, int w, int h)
  59945. {
  59946. g.setColour (findColour (TooltipWindow::textColourId));
  59947. textLayout.drawWithin (g, 0, 0, w, h, Justification::centred);
  59948. }
  59949. void BubbleMessageComponent::timerCallback()
  59950. {
  59951. if (Desktop::getInstance().getMouseButtonClickCounter() > mouseClickCounter)
  59952. {
  59953. stopTimer();
  59954. setVisible (false);
  59955. if (deleteAfterUse)
  59956. delete this;
  59957. }
  59958. else if (expiryTime != 0 && Time::getMillisecondCounter() > expiryTime)
  59959. {
  59960. stopTimer();
  59961. fadeOutComponent (fadeOutLength);
  59962. if (deleteAfterUse)
  59963. delete this;
  59964. }
  59965. }
  59966. END_JUCE_NAMESPACE
  59967. /*** End of inlined file: juce_BubbleMessageComponent.cpp ***/
  59968. /*** Start of inlined file: juce_ColourSelector.cpp ***/
  59969. BEGIN_JUCE_NAMESPACE
  59970. class ColourComponentSlider : public Slider
  59971. {
  59972. public:
  59973. ColourComponentSlider (const String& name)
  59974. : Slider (name)
  59975. {
  59976. setRange (0.0, 255.0, 1.0);
  59977. }
  59978. ~ColourComponentSlider()
  59979. {
  59980. }
  59981. const String getTextFromValue (double value)
  59982. {
  59983. return String::toHexString ((int) value).toUpperCase().paddedLeft ('0', 2);
  59984. }
  59985. double getValueFromText (const String& text)
  59986. {
  59987. return (double) text.getHexValue32();
  59988. }
  59989. private:
  59990. ColourComponentSlider (const ColourComponentSlider&);
  59991. ColourComponentSlider& operator= (const ColourComponentSlider&);
  59992. };
  59993. class ColourSpaceMarker : public Component
  59994. {
  59995. public:
  59996. ColourSpaceMarker()
  59997. {
  59998. setInterceptsMouseClicks (false, false);
  59999. }
  60000. ~ColourSpaceMarker()
  60001. {
  60002. }
  60003. void paint (Graphics& g)
  60004. {
  60005. g.setColour (Colour::greyLevel (0.1f));
  60006. g.drawEllipse (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 1.0f);
  60007. g.setColour (Colour::greyLevel (0.9f));
  60008. g.drawEllipse (2.0f, 2.0f, getWidth() - 4.0f, getHeight() - 4.0f, 1.0f);
  60009. }
  60010. private:
  60011. ColourSpaceMarker (const ColourSpaceMarker&);
  60012. ColourSpaceMarker& operator= (const ColourSpaceMarker&);
  60013. };
  60014. class ColourSelector::ColourSpaceView : public Component
  60015. {
  60016. public:
  60017. ColourSpaceView (ColourSelector* owner_,
  60018. float& h_, float& s_, float& v_,
  60019. const int edgeSize)
  60020. : owner (owner_),
  60021. h (h_), s (s_), v (v_),
  60022. lastHue (0.0f),
  60023. edge (edgeSize)
  60024. {
  60025. addAndMakeVisible (&marker);
  60026. setMouseCursor (MouseCursor::CrosshairCursor);
  60027. }
  60028. ~ColourSpaceView()
  60029. {
  60030. }
  60031. void paint (Graphics& g)
  60032. {
  60033. if (colours.isNull())
  60034. {
  60035. const int width = getWidth() / 2;
  60036. const int height = getHeight() / 2;
  60037. colours = Image (Image::RGB, width, height, false);
  60038. Image::BitmapData pixels (colours, true);
  60039. for (int y = 0; y < height; ++y)
  60040. {
  60041. const float val = 1.0f - y / (float) height;
  60042. for (int x = 0; x < width; ++x)
  60043. {
  60044. const float sat = x / (float) width;
  60045. pixels.setPixelColour (x, y, Colour (h, sat, val, 1.0f));
  60046. }
  60047. }
  60048. }
  60049. g.setOpacity (1.0f);
  60050. g.drawImage (colours, edge, edge, getWidth() - edge * 2, getHeight() - edge * 2,
  60051. 0, 0, colours.getWidth(), colours.getHeight());
  60052. }
  60053. void mouseDown (const MouseEvent& e)
  60054. {
  60055. mouseDrag (e);
  60056. }
  60057. void mouseDrag (const MouseEvent& e)
  60058. {
  60059. const float sat = (e.x - edge) / (float) (getWidth() - edge * 2);
  60060. const float val = 1.0f - (e.y - edge) / (float) (getHeight() - edge * 2);
  60061. owner->setSV (sat, val);
  60062. }
  60063. void updateIfNeeded()
  60064. {
  60065. if (lastHue != h)
  60066. {
  60067. lastHue = h;
  60068. colours = Image::null;
  60069. repaint();
  60070. }
  60071. updateMarker();
  60072. }
  60073. void resized()
  60074. {
  60075. colours = Image::null;
  60076. updateMarker();
  60077. }
  60078. private:
  60079. ColourSelector* const owner;
  60080. float& h;
  60081. float& s;
  60082. float& v;
  60083. float lastHue;
  60084. ColourSpaceMarker marker;
  60085. const int edge;
  60086. Image colours;
  60087. void updateMarker()
  60088. {
  60089. marker.setBounds (roundToInt ((getWidth() - edge * 2) * s),
  60090. roundToInt ((getHeight() - edge * 2) * (1.0f - v)),
  60091. edge * 2, edge * 2);
  60092. }
  60093. ColourSpaceView (const ColourSpaceView&);
  60094. ColourSpaceView& operator= (const ColourSpaceView&);
  60095. };
  60096. class HueSelectorMarker : public Component
  60097. {
  60098. public:
  60099. HueSelectorMarker()
  60100. {
  60101. setInterceptsMouseClicks (false, false);
  60102. }
  60103. ~HueSelectorMarker()
  60104. {
  60105. }
  60106. void paint (Graphics& g)
  60107. {
  60108. Path p;
  60109. p.addTriangle (1.0f, 1.0f,
  60110. getWidth() * 0.3f, getHeight() * 0.5f,
  60111. 1.0f, getHeight() - 1.0f);
  60112. p.addTriangle (getWidth() - 1.0f, 1.0f,
  60113. getWidth() * 0.7f, getHeight() * 0.5f,
  60114. getWidth() - 1.0f, getHeight() - 1.0f);
  60115. g.setColour (Colours::white.withAlpha (0.75f));
  60116. g.fillPath (p);
  60117. g.setColour (Colours::black.withAlpha (0.75f));
  60118. g.strokePath (p, PathStrokeType (1.2f));
  60119. }
  60120. private:
  60121. HueSelectorMarker (const HueSelectorMarker&);
  60122. HueSelectorMarker& operator= (const HueSelectorMarker&);
  60123. };
  60124. class ColourSelector::HueSelectorComp : public Component
  60125. {
  60126. public:
  60127. HueSelectorComp (ColourSelector* owner_,
  60128. float& h_, float& s_, float& v_,
  60129. const int edgeSize)
  60130. : owner (owner_),
  60131. h (h_), s (s_), v (v_),
  60132. lastHue (0.0f),
  60133. edge (edgeSize)
  60134. {
  60135. addAndMakeVisible (&marker);
  60136. }
  60137. ~HueSelectorComp()
  60138. {
  60139. }
  60140. void paint (Graphics& g)
  60141. {
  60142. const float yScale = 1.0f / (getHeight() - edge * 2);
  60143. const Rectangle<int> clip (g.getClipBounds());
  60144. for (int y = jmin (clip.getBottom(), getHeight() - edge); --y >= jmax (edge, clip.getY());)
  60145. {
  60146. g.setColour (Colour ((y - edge) * yScale, 1.0f, 1.0f, 1.0f));
  60147. g.fillRect (edge, y, getWidth() - edge * 2, 1);
  60148. }
  60149. }
  60150. void resized()
  60151. {
  60152. marker.setBounds (0, roundToInt ((getHeight() - edge * 2) * h),
  60153. getWidth(), edge * 2);
  60154. }
  60155. void mouseDown (const MouseEvent& e)
  60156. {
  60157. mouseDrag (e);
  60158. }
  60159. void mouseDrag (const MouseEvent& e)
  60160. {
  60161. const float hue = (e.y - edge) / (float) (getHeight() - edge * 2);
  60162. owner->setHue (hue);
  60163. }
  60164. void updateIfNeeded()
  60165. {
  60166. resized();
  60167. }
  60168. private:
  60169. ColourSelector* const owner;
  60170. float& h;
  60171. float& s;
  60172. float& v;
  60173. float lastHue;
  60174. HueSelectorMarker marker;
  60175. const int edge;
  60176. HueSelectorComp (const HueSelectorComp&);
  60177. HueSelectorComp& operator= (const HueSelectorComp&);
  60178. };
  60179. class ColourSelector::SwatchComponent : public Component
  60180. {
  60181. public:
  60182. SwatchComponent (ColourSelector* owner_, int index_)
  60183. : owner (owner_),
  60184. index (index_)
  60185. {
  60186. }
  60187. ~SwatchComponent()
  60188. {
  60189. }
  60190. void paint (Graphics& g)
  60191. {
  60192. const Colour colour (owner->getSwatchColour (index));
  60193. g.fillCheckerBoard (getLocalBounds(), 6, 6,
  60194. Colour (0xffdddddd).overlaidWith (colour),
  60195. Colour (0xffffffff).overlaidWith (colour));
  60196. }
  60197. void mouseDown (const MouseEvent&)
  60198. {
  60199. PopupMenu m;
  60200. m.addItem (1, TRANS("Use this swatch as the current colour"));
  60201. m.addSeparator();
  60202. m.addItem (2, TRANS("Set this swatch to the current colour"));
  60203. const int r = m.showAt (this);
  60204. if (r == 1)
  60205. {
  60206. owner->setCurrentColour (owner->getSwatchColour (index));
  60207. }
  60208. else if (r == 2)
  60209. {
  60210. if (owner->getSwatchColour (index) != owner->getCurrentColour())
  60211. {
  60212. owner->setSwatchColour (index, owner->getCurrentColour());
  60213. repaint();
  60214. }
  60215. }
  60216. }
  60217. private:
  60218. ColourSelector* const owner;
  60219. const int index;
  60220. SwatchComponent (const SwatchComponent&);
  60221. SwatchComponent& operator= (const SwatchComponent&);
  60222. };
  60223. ColourSelector::ColourSelector (const int flags_,
  60224. const int edgeGap_,
  60225. const int gapAroundColourSpaceComponent)
  60226. : colour (Colours::white),
  60227. colourSpace (0),
  60228. hueSelector (0),
  60229. flags (flags_),
  60230. edgeGap (edgeGap_)
  60231. {
  60232. // not much point having a selector with no components in it!
  60233. jassert ((flags_ & (showColourAtTop | showSliders | showColourspace)) != 0);
  60234. updateHSV();
  60235. if ((flags & showSliders) != 0)
  60236. {
  60237. addAndMakeVisible (sliders[0] = new ColourComponentSlider (TRANS ("red")));
  60238. addAndMakeVisible (sliders[1] = new ColourComponentSlider (TRANS ("green")));
  60239. addAndMakeVisible (sliders[2] = new ColourComponentSlider (TRANS ("blue")));
  60240. addChildComponent (sliders[3] = new ColourComponentSlider (TRANS ("alpha")));
  60241. sliders[3]->setVisible ((flags & showAlphaChannel) != 0);
  60242. for (int i = 4; --i >= 0;)
  60243. sliders[i]->addListener (this);
  60244. }
  60245. else
  60246. {
  60247. zeromem (sliders, sizeof (sliders));
  60248. }
  60249. if ((flags & showColourspace) != 0)
  60250. {
  60251. addAndMakeVisible (colourSpace = new ColourSpaceView (this, h, s, v, gapAroundColourSpaceComponent));
  60252. addAndMakeVisible (hueSelector = new HueSelectorComp (this, h, s, v, gapAroundColourSpaceComponent));
  60253. }
  60254. update();
  60255. }
  60256. ColourSelector::~ColourSelector()
  60257. {
  60258. dispatchPendingMessages();
  60259. swatchComponents.clear();
  60260. deleteAllChildren();
  60261. }
  60262. const Colour ColourSelector::getCurrentColour() const
  60263. {
  60264. return ((flags & showAlphaChannel) != 0) ? colour
  60265. : colour.withAlpha ((uint8) 0xff);
  60266. }
  60267. void ColourSelector::setCurrentColour (const Colour& c)
  60268. {
  60269. if (c != colour)
  60270. {
  60271. colour = ((flags & showAlphaChannel) != 0) ? c : c.withAlpha ((uint8) 0xff);
  60272. updateHSV();
  60273. update();
  60274. }
  60275. }
  60276. void ColourSelector::setHue (float newH)
  60277. {
  60278. newH = jlimit (0.0f, 1.0f, newH);
  60279. if (h != newH)
  60280. {
  60281. h = newH;
  60282. colour = Colour (h, s, v, colour.getFloatAlpha());
  60283. update();
  60284. }
  60285. }
  60286. void ColourSelector::setSV (float newS, float newV)
  60287. {
  60288. newS = jlimit (0.0f, 1.0f, newS);
  60289. newV = jlimit (0.0f, 1.0f, newV);
  60290. if (s != newS || v != newV)
  60291. {
  60292. s = newS;
  60293. v = newV;
  60294. colour = Colour (h, s, v, colour.getFloatAlpha());
  60295. update();
  60296. }
  60297. }
  60298. void ColourSelector::updateHSV()
  60299. {
  60300. colour.getHSB (h, s, v);
  60301. }
  60302. void ColourSelector::update()
  60303. {
  60304. if (sliders[0] != 0)
  60305. {
  60306. sliders[0]->setValue ((int) colour.getRed());
  60307. sliders[1]->setValue ((int) colour.getGreen());
  60308. sliders[2]->setValue ((int) colour.getBlue());
  60309. sliders[3]->setValue ((int) colour.getAlpha());
  60310. }
  60311. if (colourSpace != 0)
  60312. {
  60313. colourSpace->updateIfNeeded();
  60314. hueSelector->updateIfNeeded();
  60315. }
  60316. if ((flags & showColourAtTop) != 0)
  60317. repaint (previewArea);
  60318. sendChangeMessage (this);
  60319. }
  60320. void ColourSelector::paint (Graphics& g)
  60321. {
  60322. g.fillAll (findColour (backgroundColourId));
  60323. if ((flags & showColourAtTop) != 0)
  60324. {
  60325. const Colour currentColour (getCurrentColour());
  60326. g.fillCheckerBoard (previewArea, 10, 10,
  60327. Colour (0xffdddddd).overlaidWith (currentColour),
  60328. Colour (0xffffffff).overlaidWith (currentColour));
  60329. g.setColour (Colours::white.overlaidWith (currentColour).contrasting());
  60330. g.setFont (14.0f, true);
  60331. g.drawText (currentColour.toDisplayString ((flags & showAlphaChannel) != 0),
  60332. previewArea.getX(), previewArea.getY(), previewArea.getWidth(), previewArea.getHeight(),
  60333. Justification::centred, false);
  60334. }
  60335. if ((flags & showSliders) != 0)
  60336. {
  60337. g.setColour (findColour (labelTextColourId));
  60338. g.setFont (11.0f);
  60339. for (int i = 4; --i >= 0;)
  60340. {
  60341. if (sliders[i]->isVisible())
  60342. g.drawText (sliders[i]->getName() + ":",
  60343. 0, sliders[i]->getY(),
  60344. sliders[i]->getX() - 8, sliders[i]->getHeight(),
  60345. Justification::centredRight, false);
  60346. }
  60347. }
  60348. }
  60349. void ColourSelector::resized()
  60350. {
  60351. const int swatchesPerRow = 8;
  60352. const int swatchHeight = 22;
  60353. const int numSliders = ((flags & showAlphaChannel) != 0) ? 4 : 3;
  60354. const int numSwatches = getNumSwatches();
  60355. const int swatchSpace = numSwatches > 0 ? edgeGap + swatchHeight * ((numSwatches + 7) / swatchesPerRow) : 0;
  60356. const int sliderSpace = ((flags & showSliders) != 0) ? jmin (22 * numSliders + edgeGap, proportionOfHeight (0.3f)) : 0;
  60357. const int topSpace = ((flags & showColourAtTop) != 0) ? jmin (30 + edgeGap * 2, proportionOfHeight (0.2f)) : edgeGap;
  60358. previewArea.setBounds (edgeGap, edgeGap, getWidth() - edgeGap * 2, topSpace - edgeGap * 2);
  60359. int y = topSpace;
  60360. if ((flags & showColourspace) != 0)
  60361. {
  60362. const int hueWidth = jmin (50, proportionOfWidth (0.15f));
  60363. colourSpace->setBounds (edgeGap, y,
  60364. getWidth() - hueWidth - edgeGap - 4,
  60365. getHeight() - topSpace - sliderSpace - swatchSpace - edgeGap);
  60366. hueSelector->setBounds (colourSpace->getRight() + 4, y,
  60367. getWidth() - edgeGap - (colourSpace->getRight() + 4),
  60368. colourSpace->getHeight());
  60369. y = getHeight() - sliderSpace - swatchSpace - edgeGap;
  60370. }
  60371. if ((flags & showSliders) != 0)
  60372. {
  60373. const int sliderHeight = jmax (4, sliderSpace / numSliders);
  60374. for (int i = 0; i < numSliders; ++i)
  60375. {
  60376. sliders[i]->setBounds (proportionOfWidth (0.2f), y,
  60377. proportionOfWidth (0.72f), sliderHeight - 2);
  60378. y += sliderHeight;
  60379. }
  60380. }
  60381. if (numSwatches > 0)
  60382. {
  60383. const int startX = 8;
  60384. const int xGap = 4;
  60385. const int yGap = 4;
  60386. const int swatchWidth = (getWidth() - startX * 2) / swatchesPerRow;
  60387. y += edgeGap;
  60388. if (swatchComponents.size() != numSwatches)
  60389. {
  60390. swatchComponents.clear();
  60391. for (int i = 0; i < numSwatches; ++i)
  60392. {
  60393. SwatchComponent* const sc = new SwatchComponent (this, i);
  60394. swatchComponents.add (sc);
  60395. addAndMakeVisible (sc);
  60396. }
  60397. }
  60398. int x = startX;
  60399. for (int i = 0; i < swatchComponents.size(); ++i)
  60400. {
  60401. SwatchComponent* const sc = swatchComponents.getUnchecked(i);
  60402. sc->setBounds (x + xGap / 2,
  60403. y + yGap / 2,
  60404. swatchWidth - xGap,
  60405. swatchHeight - yGap);
  60406. if (((i + 1) % swatchesPerRow) == 0)
  60407. {
  60408. x = startX;
  60409. y += swatchHeight;
  60410. }
  60411. else
  60412. {
  60413. x += swatchWidth;
  60414. }
  60415. }
  60416. }
  60417. }
  60418. void ColourSelector::sliderValueChanged (Slider*)
  60419. {
  60420. if (sliders[0] != 0)
  60421. setCurrentColour (Colour ((uint8) sliders[0]->getValue(),
  60422. (uint8) sliders[1]->getValue(),
  60423. (uint8) sliders[2]->getValue(),
  60424. (uint8) sliders[3]->getValue()));
  60425. }
  60426. int ColourSelector::getNumSwatches() const
  60427. {
  60428. return 0;
  60429. }
  60430. const Colour ColourSelector::getSwatchColour (const int) const
  60431. {
  60432. jassertfalse; // if you've overridden getNumSwatches(), you also need to implement this method
  60433. return Colours::black;
  60434. }
  60435. void ColourSelector::setSwatchColour (const int, const Colour&) const
  60436. {
  60437. jassertfalse; // if you've overridden getNumSwatches(), you also need to implement this method
  60438. }
  60439. END_JUCE_NAMESPACE
  60440. /*** End of inlined file: juce_ColourSelector.cpp ***/
  60441. /*** Start of inlined file: juce_DropShadower.cpp ***/
  60442. BEGIN_JUCE_NAMESPACE
  60443. class ShadowWindow : public Component
  60444. {
  60445. Component* owner;
  60446. Image shadowImageSections [12];
  60447. const int type; // 0 = left, 1 = right, 2 = top, 3 = bottom. left + right are full-height
  60448. public:
  60449. ShadowWindow (Component* const owner_,
  60450. const int type_,
  60451. const Image shadowImageSections_ [12])
  60452. : owner (owner_),
  60453. type (type_)
  60454. {
  60455. for (int i = 0; i < numElementsInArray (shadowImageSections); ++i)
  60456. shadowImageSections [i] = shadowImageSections_ [i];
  60457. setInterceptsMouseClicks (false, false);
  60458. if (owner_->isOnDesktop())
  60459. {
  60460. setSize (1, 1); // to keep the OS happy by not having zero-size windows
  60461. addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  60462. | ComponentPeer::windowIsTemporary
  60463. | ComponentPeer::windowIgnoresKeyPresses);
  60464. }
  60465. else if (owner_->getParentComponent() != 0)
  60466. {
  60467. owner_->getParentComponent()->addChildComponent (this);
  60468. }
  60469. }
  60470. ~ShadowWindow()
  60471. {
  60472. }
  60473. void paint (Graphics& g)
  60474. {
  60475. const Image& topLeft = shadowImageSections [type * 3];
  60476. const Image& bottomRight = shadowImageSections [type * 3 + 1];
  60477. const Image& filler = shadowImageSections [type * 3 + 2];
  60478. g.setOpacity (1.0f);
  60479. if (type < 2)
  60480. {
  60481. int imH = jmin (topLeft.getHeight(), getHeight() / 2);
  60482. g.drawImage (topLeft,
  60483. 0, 0, topLeft.getWidth(), imH,
  60484. 0, 0, topLeft.getWidth(), imH);
  60485. imH = jmin (bottomRight.getHeight(), getHeight() - getHeight() / 2);
  60486. g.drawImage (bottomRight,
  60487. 0, getHeight() - imH, bottomRight.getWidth(), imH,
  60488. 0, bottomRight.getHeight() - imH, bottomRight.getWidth(), imH);
  60489. g.setTiledImageFill (filler, 0, 0, 1.0f);
  60490. g.fillRect (0, topLeft.getHeight(), getWidth(), getHeight() - (topLeft.getHeight() + bottomRight.getHeight()));
  60491. }
  60492. else
  60493. {
  60494. int imW = jmin (topLeft.getWidth(), getWidth() / 2);
  60495. g.drawImage (topLeft,
  60496. 0, 0, imW, topLeft.getHeight(),
  60497. 0, 0, imW, topLeft.getHeight());
  60498. imW = jmin (bottomRight.getWidth(), getWidth() - getWidth() / 2);
  60499. g.drawImage (bottomRight,
  60500. getWidth() - imW, 0, imW, bottomRight.getHeight(),
  60501. bottomRight.getWidth() - imW, 0, imW, bottomRight.getHeight());
  60502. g.setTiledImageFill (filler, 0, 0, 1.0f);
  60503. g.fillRect (topLeft.getWidth(), 0, getWidth() - (topLeft.getWidth() + bottomRight.getWidth()), getHeight());
  60504. }
  60505. }
  60506. void resized()
  60507. {
  60508. repaint(); // (needed for correct repainting)
  60509. }
  60510. private:
  60511. ShadowWindow (const ShadowWindow&);
  60512. ShadowWindow& operator= (const ShadowWindow&);
  60513. };
  60514. DropShadower::DropShadower (const float alpha_,
  60515. const int xOffset_,
  60516. const int yOffset_,
  60517. const float blurRadius_)
  60518. : owner (0),
  60519. numShadows (0),
  60520. shadowEdge (jmax (xOffset_, yOffset_) + (int) blurRadius_),
  60521. xOffset (xOffset_),
  60522. yOffset (yOffset_),
  60523. alpha (alpha_),
  60524. blurRadius (blurRadius_),
  60525. inDestructor (false),
  60526. reentrant (false)
  60527. {
  60528. }
  60529. DropShadower::~DropShadower()
  60530. {
  60531. if (owner != 0)
  60532. owner->removeComponentListener (this);
  60533. inDestructor = true;
  60534. deleteShadowWindows();
  60535. }
  60536. void DropShadower::deleteShadowWindows()
  60537. {
  60538. if (numShadows > 0)
  60539. {
  60540. int i;
  60541. for (i = numShadows; --i >= 0;)
  60542. delete shadowWindows[i];
  60543. numShadows = 0;
  60544. }
  60545. }
  60546. void DropShadower::setOwner (Component* componentToFollow)
  60547. {
  60548. if (componentToFollow != owner)
  60549. {
  60550. if (owner != 0)
  60551. owner->removeComponentListener (this);
  60552. // (the component can't be null)
  60553. jassert (componentToFollow != 0);
  60554. owner = componentToFollow;
  60555. jassert (owner != 0);
  60556. jassert (owner->isOpaque()); // doesn't work properly for semi-transparent comps!
  60557. owner->addComponentListener (this);
  60558. updateShadows();
  60559. }
  60560. }
  60561. void DropShadower::componentMovedOrResized (Component&, bool /*wasMoved*/, bool /*wasResized*/)
  60562. {
  60563. updateShadows();
  60564. }
  60565. void DropShadower::componentBroughtToFront (Component&)
  60566. {
  60567. bringShadowWindowsToFront();
  60568. }
  60569. void DropShadower::componentChildrenChanged (Component&)
  60570. {
  60571. }
  60572. void DropShadower::componentParentHierarchyChanged (Component&)
  60573. {
  60574. deleteShadowWindows();
  60575. updateShadows();
  60576. }
  60577. void DropShadower::componentVisibilityChanged (Component&)
  60578. {
  60579. updateShadows();
  60580. }
  60581. void DropShadower::updateShadows()
  60582. {
  60583. if (reentrant || inDestructor || (owner == 0))
  60584. return;
  60585. reentrant = true;
  60586. ComponentPeer* const nw = owner->getPeer();
  60587. const bool isOwnerVisible = owner->isVisible()
  60588. && (nw == 0 || ! nw->isMinimised());
  60589. const bool createShadowWindows = numShadows == 0
  60590. && owner->getWidth() > 0
  60591. && owner->getHeight() > 0
  60592. && isOwnerVisible
  60593. && (Desktop::canUseSemiTransparentWindows()
  60594. || owner->getParentComponent() != 0);
  60595. if (createShadowWindows)
  60596. {
  60597. // keep a cached version of the image to save doing the gaussian too often
  60598. String imageId;
  60599. imageId << shadowEdge << ',' << xOffset << ',' << yOffset << ',' << alpha;
  60600. const int hash = imageId.hashCode();
  60601. Image bigIm (ImageCache::getFromHashCode (hash));
  60602. if (bigIm.isNull())
  60603. {
  60604. bigIm = Image (Image::ARGB, shadowEdge * 5, shadowEdge * 5, true, Image::NativeImage);
  60605. Graphics bigG (bigIm);
  60606. bigG.setColour (Colours::black.withAlpha (alpha));
  60607. bigG.fillRect (shadowEdge + xOffset,
  60608. shadowEdge + yOffset,
  60609. bigIm.getWidth() - (shadowEdge * 2),
  60610. bigIm.getHeight() - (shadowEdge * 2));
  60611. ImageConvolutionKernel blurKernel (roundToInt (blurRadius * 2.0f));
  60612. blurKernel.createGaussianBlur (blurRadius);
  60613. blurKernel.applyToImage (bigIm, bigIm,
  60614. Rectangle<int> (xOffset, yOffset,
  60615. bigIm.getWidth(), bigIm.getHeight()));
  60616. ImageCache::addImageToCache (bigIm, hash);
  60617. }
  60618. const int iw = bigIm.getWidth();
  60619. const int ih = bigIm.getHeight();
  60620. const int shadowEdge2 = shadowEdge * 2;
  60621. setShadowImage (bigIm, 0, shadowEdge, shadowEdge2, 0, 0);
  60622. setShadowImage (bigIm, 1, shadowEdge, shadowEdge2, 0, ih - shadowEdge2);
  60623. setShadowImage (bigIm, 2, shadowEdge, shadowEdge, 0, shadowEdge2);
  60624. setShadowImage (bigIm, 3, shadowEdge, shadowEdge2, iw - shadowEdge, 0);
  60625. setShadowImage (bigIm, 4, shadowEdge, shadowEdge2, iw - shadowEdge, ih - shadowEdge2);
  60626. setShadowImage (bigIm, 5, shadowEdge, shadowEdge, iw - shadowEdge, shadowEdge2);
  60627. setShadowImage (bigIm, 6, shadowEdge, shadowEdge, shadowEdge, 0);
  60628. setShadowImage (bigIm, 7, shadowEdge, shadowEdge, iw - shadowEdge2, 0);
  60629. setShadowImage (bigIm, 8, shadowEdge, shadowEdge, shadowEdge2, 0);
  60630. setShadowImage (bigIm, 9, shadowEdge, shadowEdge, shadowEdge, ih - shadowEdge);
  60631. setShadowImage (bigIm, 10, shadowEdge, shadowEdge, iw - shadowEdge2, ih - shadowEdge);
  60632. setShadowImage (bigIm, 11, shadowEdge, shadowEdge, shadowEdge2, ih - shadowEdge);
  60633. for (int i = 0; i < 4; ++i)
  60634. {
  60635. shadowWindows[numShadows] = new ShadowWindow (owner, i, shadowImageSections);
  60636. ++numShadows;
  60637. }
  60638. }
  60639. if (numShadows > 0)
  60640. {
  60641. for (int i = numShadows; --i >= 0;)
  60642. {
  60643. shadowWindows[i]->setAlwaysOnTop (owner->isAlwaysOnTop());
  60644. shadowWindows[i]->setVisible (isOwnerVisible);
  60645. }
  60646. const int x = owner->getX();
  60647. const int y = owner->getY() - shadowEdge;
  60648. const int w = owner->getWidth();
  60649. const int h = owner->getHeight() + shadowEdge + shadowEdge;
  60650. shadowWindows[0]->setBounds (x - shadowEdge,
  60651. y,
  60652. shadowEdge,
  60653. h);
  60654. shadowWindows[1]->setBounds (x + w,
  60655. y,
  60656. shadowEdge,
  60657. h);
  60658. shadowWindows[2]->setBounds (x,
  60659. y,
  60660. w,
  60661. shadowEdge);
  60662. shadowWindows[3]->setBounds (x,
  60663. owner->getBottom(),
  60664. w,
  60665. shadowEdge);
  60666. }
  60667. reentrant = false;
  60668. if (createShadowWindows)
  60669. bringShadowWindowsToFront();
  60670. }
  60671. void DropShadower::setShadowImage (const Image& src, const int num, const int w, const int h,
  60672. const int sx, const int sy)
  60673. {
  60674. shadowImageSections[num] = Image (Image::ARGB, w, h, true, Image::NativeImage);
  60675. Graphics g (shadowImageSections[num]);
  60676. g.drawImage (src, 0, 0, w, h, sx, sy, w, h);
  60677. }
  60678. void DropShadower::bringShadowWindowsToFront()
  60679. {
  60680. if (! (inDestructor || reentrant))
  60681. {
  60682. updateShadows();
  60683. reentrant = true;
  60684. for (int i = numShadows; --i >= 0;)
  60685. shadowWindows[i]->toBehind (owner);
  60686. reentrant = false;
  60687. }
  60688. }
  60689. END_JUCE_NAMESPACE
  60690. /*** End of inlined file: juce_DropShadower.cpp ***/
  60691. /*** Start of inlined file: juce_MagnifierComponent.cpp ***/
  60692. BEGIN_JUCE_NAMESPACE
  60693. class MagnifyingPeer : public ComponentPeer
  60694. {
  60695. public:
  60696. MagnifyingPeer (Component* const component_,
  60697. MagnifierComponent* const magnifierComp_)
  60698. : ComponentPeer (component_, 0),
  60699. magnifierComp (magnifierComp_)
  60700. {
  60701. }
  60702. ~MagnifyingPeer()
  60703. {
  60704. }
  60705. void* getNativeHandle() const { return 0; }
  60706. void setVisible (bool) {}
  60707. void setTitle (const String&) {}
  60708. void setPosition (int, int) {}
  60709. void setSize (int, int) {}
  60710. void setBounds (int, int, int, int, bool) {}
  60711. void setMinimised (bool) {}
  60712. bool isMinimised() const { return false; }
  60713. void setFullScreen (bool) {}
  60714. bool isFullScreen() const { return false; }
  60715. const BorderSize getFrameSize() const { return BorderSize (0); }
  60716. bool setAlwaysOnTop (bool) { return true; }
  60717. void toFront (bool) {}
  60718. void toBehind (ComponentPeer*) {}
  60719. void setIcon (const Image&) {}
  60720. bool isFocused() const
  60721. {
  60722. return magnifierComp->hasKeyboardFocus (true);
  60723. }
  60724. void grabFocus()
  60725. {
  60726. ComponentPeer* peer = magnifierComp->getPeer();
  60727. if (peer != 0)
  60728. peer->grabFocus();
  60729. }
  60730. void textInputRequired (const Point<int>& position)
  60731. {
  60732. ComponentPeer* peer = magnifierComp->getPeer();
  60733. if (peer != 0)
  60734. peer->textInputRequired (position);
  60735. }
  60736. const Rectangle<int> getBounds() const
  60737. {
  60738. return Rectangle<int> (magnifierComp->getScreenX(), magnifierComp->getScreenY(),
  60739. component->getWidth(), component->getHeight());
  60740. }
  60741. const Point<int> getScreenPosition() const
  60742. {
  60743. return magnifierComp->getScreenPosition();
  60744. }
  60745. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  60746. {
  60747. const double zoom = magnifierComp->getScaleFactor();
  60748. return magnifierComp->relativePositionToGlobal (Point<int> (roundToInt (relativePosition.getX() * zoom),
  60749. roundToInt (relativePosition.getY() * zoom)));
  60750. }
  60751. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  60752. {
  60753. const Point<int> p (magnifierComp->globalPositionToRelative (screenPosition));
  60754. const double zoom = magnifierComp->getScaleFactor();
  60755. return Point<int> (roundToInt (p.getX() / zoom),
  60756. roundToInt (p.getY() / zoom));
  60757. }
  60758. bool contains (const Point<int>& position, bool) const
  60759. {
  60760. return ((unsigned int) position.getX()) < (unsigned int) magnifierComp->getWidth()
  60761. && ((unsigned int) position.getY()) < (unsigned int) magnifierComp->getHeight();
  60762. }
  60763. void repaint (const Rectangle<int>& area)
  60764. {
  60765. const double zoom = magnifierComp->getScaleFactor();
  60766. magnifierComp->repaint ((int) (area.getX() * zoom),
  60767. (int) (area.getY() * zoom),
  60768. roundToInt (area.getWidth() * zoom) + 1,
  60769. roundToInt (area.getHeight() * zoom) + 1);
  60770. }
  60771. void performAnyPendingRepaintsNow()
  60772. {
  60773. }
  60774. juce_UseDebuggingNewOperator
  60775. private:
  60776. MagnifierComponent* const magnifierComp;
  60777. MagnifyingPeer (const MagnifyingPeer&);
  60778. MagnifyingPeer& operator= (const MagnifyingPeer&);
  60779. };
  60780. class PeerHolderComp : public Component
  60781. {
  60782. public:
  60783. PeerHolderComp (MagnifierComponent* const magnifierComp_)
  60784. : magnifierComp (magnifierComp_)
  60785. {
  60786. setVisible (true);
  60787. }
  60788. ~PeerHolderComp()
  60789. {
  60790. }
  60791. ComponentPeer* createNewPeer (int, void*)
  60792. {
  60793. return new MagnifyingPeer (this, magnifierComp);
  60794. }
  60795. void childBoundsChanged (Component* c)
  60796. {
  60797. if (c != 0)
  60798. {
  60799. setSize (c->getWidth(), c->getHeight());
  60800. magnifierComp->childBoundsChanged (this);
  60801. }
  60802. }
  60803. void mouseWheelMove (const MouseEvent& e, float ix, float iy)
  60804. {
  60805. // unhandled mouse wheel moves can be referred upwards to the parent comp..
  60806. Component* const p = magnifierComp->getParentComponent();
  60807. if (p != 0)
  60808. p->mouseWheelMove (e.getEventRelativeTo (p), ix, iy);
  60809. }
  60810. private:
  60811. MagnifierComponent* const magnifierComp;
  60812. PeerHolderComp (const PeerHolderComp&);
  60813. PeerHolderComp& operator= (const PeerHolderComp&);
  60814. };
  60815. MagnifierComponent::MagnifierComponent (Component* const content_,
  60816. const bool deleteContentCompWhenNoLongerNeeded)
  60817. : content (content_),
  60818. scaleFactor (0.0),
  60819. peer (0),
  60820. deleteContent (deleteContentCompWhenNoLongerNeeded),
  60821. quality (Graphics::lowResamplingQuality),
  60822. mouseSource (0, true)
  60823. {
  60824. holderComp = new PeerHolderComp (this);
  60825. setScaleFactor (1.0);
  60826. }
  60827. MagnifierComponent::~MagnifierComponent()
  60828. {
  60829. delete holderComp;
  60830. if (deleteContent)
  60831. delete content;
  60832. }
  60833. void MagnifierComponent::setScaleFactor (double newScaleFactor)
  60834. {
  60835. jassert (newScaleFactor > 0.0); // hmm - unlikely to work well with a negative scale factor
  60836. newScaleFactor = jlimit (1.0 / 8.0, 1000.0, newScaleFactor);
  60837. if (scaleFactor != newScaleFactor)
  60838. {
  60839. scaleFactor = newScaleFactor;
  60840. if (scaleFactor == 1.0)
  60841. {
  60842. holderComp->removeFromDesktop();
  60843. peer = 0;
  60844. addChildComponent (content);
  60845. childBoundsChanged (content);
  60846. }
  60847. else
  60848. {
  60849. holderComp->addAndMakeVisible (content);
  60850. holderComp->childBoundsChanged (content);
  60851. childBoundsChanged (holderComp);
  60852. holderComp->addToDesktop (0);
  60853. peer = holderComp->getPeer();
  60854. }
  60855. repaint();
  60856. }
  60857. }
  60858. void MagnifierComponent::setResamplingQuality (Graphics::ResamplingQuality newQuality)
  60859. {
  60860. quality = newQuality;
  60861. }
  60862. void MagnifierComponent::paint (Graphics& g)
  60863. {
  60864. const int w = holderComp->getWidth();
  60865. const int h = holderComp->getHeight();
  60866. if (w == 0 || h == 0)
  60867. return;
  60868. const Rectangle<int> r (g.getClipBounds());
  60869. const int srcX = (int) (r.getX() / scaleFactor);
  60870. const int srcY = (int) (r.getY() / scaleFactor);
  60871. int srcW = roundToInt (r.getRight() / scaleFactor) - srcX;
  60872. int srcH = roundToInt (r.getBottom() / scaleFactor) - srcY;
  60873. if (scaleFactor >= 1.0)
  60874. {
  60875. ++srcW;
  60876. ++srcH;
  60877. }
  60878. Image temp (Image::ARGB, jmax (w, srcX + srcW), jmax (h, srcY + srcH), false);
  60879. temp.clear (Rectangle<int> (srcX, srcY, srcW, srcH));
  60880. {
  60881. Graphics g2 (temp);
  60882. g2.reduceClipRegion (srcX, srcY, srcW, srcH);
  60883. holderComp->paintEntireComponent (g2);
  60884. }
  60885. g.setImageResamplingQuality (quality);
  60886. g.drawImageTransformed (temp, AffineTransform::scale ((float) scaleFactor, (float) scaleFactor), false);
  60887. }
  60888. void MagnifierComponent::childBoundsChanged (Component* c)
  60889. {
  60890. if (c != 0)
  60891. setSize (roundToInt (c->getWidth() * scaleFactor),
  60892. roundToInt (c->getHeight() * scaleFactor));
  60893. }
  60894. void MagnifierComponent::passOnMouseEventToPeer (const MouseEvent& e)
  60895. {
  60896. if (peer != 0)
  60897. mouseSource.handleEvent (peer, Point<int> (scaleInt (e.x), scaleInt (e.y)),
  60898. e.eventTime.toMilliseconds(), ModifierKeys::getCurrentModifiers());
  60899. }
  60900. void MagnifierComponent::mouseDown (const MouseEvent& e)
  60901. {
  60902. passOnMouseEventToPeer (e);
  60903. }
  60904. void MagnifierComponent::mouseUp (const MouseEvent& e)
  60905. {
  60906. passOnMouseEventToPeer (e);
  60907. }
  60908. void MagnifierComponent::mouseDrag (const MouseEvent& e)
  60909. {
  60910. passOnMouseEventToPeer (e);
  60911. }
  60912. void MagnifierComponent::mouseMove (const MouseEvent& e)
  60913. {
  60914. passOnMouseEventToPeer (e);
  60915. }
  60916. void MagnifierComponent::mouseEnter (const MouseEvent& e)
  60917. {
  60918. passOnMouseEventToPeer (e);
  60919. }
  60920. void MagnifierComponent::mouseExit (const MouseEvent& e)
  60921. {
  60922. passOnMouseEventToPeer (e);
  60923. }
  60924. void MagnifierComponent::mouseWheelMove (const MouseEvent& e, float ix, float iy)
  60925. {
  60926. if (peer != 0)
  60927. peer->handleMouseWheel (e.source.getIndex(),
  60928. Point<int> (scaleInt (e.x), scaleInt (e.y)), e.eventTime.toMilliseconds(),
  60929. ix * 256.0f, iy * 256.0f);
  60930. else
  60931. Component::mouseWheelMove (e, ix, iy);
  60932. }
  60933. int MagnifierComponent::scaleInt (const int n) const
  60934. {
  60935. return roundToInt (n / scaleFactor);
  60936. }
  60937. END_JUCE_NAMESPACE
  60938. /*** End of inlined file: juce_MagnifierComponent.cpp ***/
  60939. /*** Start of inlined file: juce_MidiKeyboardComponent.cpp ***/
  60940. BEGIN_JUCE_NAMESPACE
  60941. class MidiKeyboardUpDownButton : public Button
  60942. {
  60943. public:
  60944. MidiKeyboardUpDownButton (MidiKeyboardComponent* const owner_,
  60945. const int delta_)
  60946. : Button (String::empty),
  60947. owner (owner_),
  60948. delta (delta_)
  60949. {
  60950. setOpaque (true);
  60951. }
  60952. ~MidiKeyboardUpDownButton()
  60953. {
  60954. }
  60955. void clicked()
  60956. {
  60957. int note = owner->getLowestVisibleKey();
  60958. if (delta < 0)
  60959. note = (note - 1) / 12;
  60960. else
  60961. note = note / 12 + 1;
  60962. owner->setLowestVisibleKey (note * 12);
  60963. }
  60964. void paintButton (Graphics& g,
  60965. bool isMouseOverButton,
  60966. bool isButtonDown)
  60967. {
  60968. owner->drawUpDownButton (g, getWidth(), getHeight(),
  60969. isMouseOverButton, isButtonDown,
  60970. delta > 0);
  60971. }
  60972. private:
  60973. MidiKeyboardComponent* const owner;
  60974. const int delta;
  60975. MidiKeyboardUpDownButton (const MidiKeyboardUpDownButton&);
  60976. MidiKeyboardUpDownButton& operator= (const MidiKeyboardUpDownButton&);
  60977. };
  60978. MidiKeyboardComponent::MidiKeyboardComponent (MidiKeyboardState& state_,
  60979. const Orientation orientation_)
  60980. : state (state_),
  60981. xOffset (0),
  60982. blackNoteLength (1),
  60983. keyWidth (16.0f),
  60984. orientation (orientation_),
  60985. midiChannel (1),
  60986. midiInChannelMask (0xffff),
  60987. velocity (1.0f),
  60988. noteUnderMouse (-1),
  60989. mouseDownNote (-1),
  60990. rangeStart (0),
  60991. rangeEnd (127),
  60992. firstKey (12 * 4),
  60993. canScroll (true),
  60994. mouseDragging (false),
  60995. useMousePositionForVelocity (true),
  60996. keyMappingOctave (6),
  60997. octaveNumForMiddleC (3)
  60998. {
  60999. addChildComponent (scrollDown = new MidiKeyboardUpDownButton (this, -1));
  61000. addChildComponent (scrollUp = new MidiKeyboardUpDownButton (this, 1));
  61001. // initialise with a default set of querty key-mappings..
  61002. const char* const keymap = "awsedftgyhujkolp;";
  61003. for (int i = String (keymap).length(); --i >= 0;)
  61004. setKeyPressForNote (KeyPress (keymap[i], 0, 0), i);
  61005. setOpaque (true);
  61006. setWantsKeyboardFocus (true);
  61007. state.addListener (this);
  61008. }
  61009. MidiKeyboardComponent::~MidiKeyboardComponent()
  61010. {
  61011. state.removeListener (this);
  61012. jassert (mouseDownNote < 0 && keysPressed.countNumberOfSetBits() == 0); // leaving stuck notes!
  61013. deleteAllChildren();
  61014. }
  61015. void MidiKeyboardComponent::setKeyWidth (const float widthInPixels)
  61016. {
  61017. keyWidth = widthInPixels;
  61018. resized();
  61019. }
  61020. void MidiKeyboardComponent::setOrientation (const Orientation newOrientation)
  61021. {
  61022. if (orientation != newOrientation)
  61023. {
  61024. orientation = newOrientation;
  61025. resized();
  61026. }
  61027. }
  61028. void MidiKeyboardComponent::setAvailableRange (const int lowestNote,
  61029. const int highestNote)
  61030. {
  61031. jassert (lowestNote >= 0 && lowestNote <= 127);
  61032. jassert (highestNote >= 0 && highestNote <= 127);
  61033. jassert (lowestNote <= highestNote);
  61034. if (rangeStart != lowestNote || rangeEnd != highestNote)
  61035. {
  61036. rangeStart = jlimit (0, 127, lowestNote);
  61037. rangeEnd = jlimit (0, 127, highestNote);
  61038. firstKey = jlimit (rangeStart, rangeEnd, firstKey);
  61039. resized();
  61040. }
  61041. }
  61042. void MidiKeyboardComponent::setLowestVisibleKey (int noteNumber)
  61043. {
  61044. noteNumber = jlimit (rangeStart, rangeEnd, noteNumber);
  61045. if (noteNumber != firstKey)
  61046. {
  61047. firstKey = noteNumber;
  61048. sendChangeMessage (this);
  61049. resized();
  61050. }
  61051. }
  61052. void MidiKeyboardComponent::setScrollButtonsVisible (const bool canScroll_)
  61053. {
  61054. if (canScroll != canScroll_)
  61055. {
  61056. canScroll = canScroll_;
  61057. resized();
  61058. }
  61059. }
  61060. void MidiKeyboardComponent::colourChanged()
  61061. {
  61062. repaint();
  61063. }
  61064. void MidiKeyboardComponent::setMidiChannel (const int midiChannelNumber)
  61065. {
  61066. jassert (midiChannelNumber > 0 && midiChannelNumber <= 16);
  61067. if (midiChannel != midiChannelNumber)
  61068. {
  61069. resetAnyKeysInUse();
  61070. midiChannel = jlimit (1, 16, midiChannelNumber);
  61071. }
  61072. }
  61073. void MidiKeyboardComponent::setMidiChannelsToDisplay (const int midiChannelMask)
  61074. {
  61075. midiInChannelMask = midiChannelMask;
  61076. triggerAsyncUpdate();
  61077. }
  61078. void MidiKeyboardComponent::setVelocity (const float velocity_, const bool useMousePositionForVelocity_)
  61079. {
  61080. velocity = jlimit (0.0f, 1.0f, velocity_);
  61081. useMousePositionForVelocity = useMousePositionForVelocity_;
  61082. }
  61083. void MidiKeyboardComponent::getKeyPosition (int midiNoteNumber, const float keyWidth_, int& x, int& w) const
  61084. {
  61085. jassert (midiNoteNumber >= 0 && midiNoteNumber < 128);
  61086. static const float blackNoteWidth = 0.7f;
  61087. static const float notePos[] = { 0.0f, 1 - blackNoteWidth * 0.6f,
  61088. 1.0f, 2 - blackNoteWidth * 0.4f,
  61089. 2.0f, 3.0f, 4 - blackNoteWidth * 0.7f,
  61090. 4.0f, 5 - blackNoteWidth * 0.5f,
  61091. 5.0f, 6 - blackNoteWidth * 0.3f,
  61092. 6.0f };
  61093. static const float widths[] = { 1.0f, blackNoteWidth,
  61094. 1.0f, blackNoteWidth,
  61095. 1.0f, 1.0f, blackNoteWidth,
  61096. 1.0f, blackNoteWidth,
  61097. 1.0f, blackNoteWidth,
  61098. 1.0f };
  61099. const int octave = midiNoteNumber / 12;
  61100. const int note = midiNoteNumber % 12;
  61101. x = roundToInt (octave * 7.0f * keyWidth_ + notePos [note] * keyWidth_);
  61102. w = roundToInt (widths [note] * keyWidth_);
  61103. }
  61104. void MidiKeyboardComponent::getKeyPos (int midiNoteNumber, int& x, int& w) const
  61105. {
  61106. getKeyPosition (midiNoteNumber, keyWidth, x, w);
  61107. int rx, rw;
  61108. getKeyPosition (rangeStart, keyWidth, rx, rw);
  61109. x -= xOffset + rx;
  61110. }
  61111. int MidiKeyboardComponent::getKeyStartPosition (const int midiNoteNumber) const
  61112. {
  61113. int x, y;
  61114. getKeyPos (midiNoteNumber, x, y);
  61115. return x;
  61116. }
  61117. const uint8 MidiKeyboardComponent::whiteNotes[] = { 0, 2, 4, 5, 7, 9, 11 };
  61118. const uint8 MidiKeyboardComponent::blackNotes[] = { 1, 3, 6, 8, 10 };
  61119. int MidiKeyboardComponent::xyToNote (const Point<int>& pos, float& mousePositionVelocity)
  61120. {
  61121. if (! reallyContains (pos.getX(), pos.getY(), false))
  61122. return -1;
  61123. Point<int> p (pos);
  61124. if (orientation != horizontalKeyboard)
  61125. {
  61126. p = Point<int> (p.getY(), p.getX());
  61127. if (orientation == verticalKeyboardFacingLeft)
  61128. p = Point<int> (p.getX(), getWidth() - p.getY());
  61129. else
  61130. p = Point<int> (getHeight() - p.getX(), p.getY());
  61131. }
  61132. return remappedXYToNote (p + Point<int> (xOffset, 0), mousePositionVelocity);
  61133. }
  61134. int MidiKeyboardComponent::remappedXYToNote (const Point<int>& pos, float& mousePositionVelocity) const
  61135. {
  61136. if (pos.getY() < blackNoteLength)
  61137. {
  61138. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  61139. {
  61140. for (int i = 0; i < 5; ++i)
  61141. {
  61142. const int note = octaveStart + blackNotes [i];
  61143. if (note >= rangeStart && note <= rangeEnd)
  61144. {
  61145. int kx, kw;
  61146. getKeyPos (note, kx, kw);
  61147. kx += xOffset;
  61148. if (pos.getX() >= kx && pos.getX() < kx + kw)
  61149. {
  61150. mousePositionVelocity = pos.getY() / (float) blackNoteLength;
  61151. return note;
  61152. }
  61153. }
  61154. }
  61155. }
  61156. }
  61157. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  61158. {
  61159. for (int i = 0; i < 7; ++i)
  61160. {
  61161. const int note = octaveStart + whiteNotes [i];
  61162. if (note >= rangeStart && note <= rangeEnd)
  61163. {
  61164. int kx, kw;
  61165. getKeyPos (note, kx, kw);
  61166. kx += xOffset;
  61167. if (pos.getX() >= kx && pos.getX() < kx + kw)
  61168. {
  61169. const int whiteNoteLength = (orientation == horizontalKeyboard) ? getHeight() : getWidth();
  61170. mousePositionVelocity = pos.getY() / (float) whiteNoteLength;
  61171. return note;
  61172. }
  61173. }
  61174. }
  61175. }
  61176. mousePositionVelocity = 0;
  61177. return -1;
  61178. }
  61179. void MidiKeyboardComponent::repaintNote (const int noteNum)
  61180. {
  61181. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  61182. {
  61183. int x, w;
  61184. getKeyPos (noteNum, x, w);
  61185. if (orientation == horizontalKeyboard)
  61186. repaint (x, 0, w, getHeight());
  61187. else if (orientation == verticalKeyboardFacingLeft)
  61188. repaint (0, x, getWidth(), w);
  61189. else if (orientation == verticalKeyboardFacingRight)
  61190. repaint (0, getHeight() - x - w, getWidth(), w);
  61191. }
  61192. }
  61193. void MidiKeyboardComponent::paint (Graphics& g)
  61194. {
  61195. g.fillAll (Colours::white.overlaidWith (findColour (whiteNoteColourId)));
  61196. const Colour lineColour (findColour (keySeparatorLineColourId));
  61197. const Colour textColour (findColour (textLabelColourId));
  61198. int x, w, octave;
  61199. for (octave = 0; octave < 128; octave += 12)
  61200. {
  61201. for (int white = 0; white < 7; ++white)
  61202. {
  61203. const int noteNum = octave + whiteNotes [white];
  61204. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  61205. {
  61206. getKeyPos (noteNum, x, w);
  61207. if (orientation == horizontalKeyboard)
  61208. drawWhiteNote (noteNum, g, x, 0, w, getHeight(),
  61209. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61210. noteUnderMouse == noteNum,
  61211. lineColour, textColour);
  61212. else if (orientation == verticalKeyboardFacingLeft)
  61213. drawWhiteNote (noteNum, g, 0, x, getWidth(), w,
  61214. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61215. noteUnderMouse == noteNum,
  61216. lineColour, textColour);
  61217. else if (orientation == verticalKeyboardFacingRight)
  61218. drawWhiteNote (noteNum, g, 0, getHeight() - x - w, getWidth(), w,
  61219. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61220. noteUnderMouse == noteNum,
  61221. lineColour, textColour);
  61222. }
  61223. }
  61224. }
  61225. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  61226. if (orientation == verticalKeyboardFacingLeft)
  61227. {
  61228. x1 = getWidth() - 1.0f;
  61229. x2 = getWidth() - 5.0f;
  61230. }
  61231. else if (orientation == verticalKeyboardFacingRight)
  61232. x2 = 5.0f;
  61233. else
  61234. y2 = 5.0f;
  61235. g.setGradientFill (ColourGradient (Colours::black.withAlpha (0.3f), x1, y1,
  61236. Colours::transparentBlack, x2, y2, false));
  61237. getKeyPos (rangeEnd, x, w);
  61238. x += w;
  61239. if (orientation == verticalKeyboardFacingLeft)
  61240. g.fillRect (getWidth() - 5, 0, 5, x);
  61241. else if (orientation == verticalKeyboardFacingRight)
  61242. g.fillRect (0, 0, 5, x);
  61243. else
  61244. g.fillRect (0, 0, x, 5);
  61245. g.setColour (lineColour);
  61246. if (orientation == verticalKeyboardFacingLeft)
  61247. g.fillRect (0, 0, 1, x);
  61248. else if (orientation == verticalKeyboardFacingRight)
  61249. g.fillRect (getWidth() - 1, 0, 1, x);
  61250. else
  61251. g.fillRect (0, getHeight() - 1, x, 1);
  61252. const Colour blackNoteColour (findColour (blackNoteColourId));
  61253. for (octave = 0; octave < 128; octave += 12)
  61254. {
  61255. for (int black = 0; black < 5; ++black)
  61256. {
  61257. const int noteNum = octave + blackNotes [black];
  61258. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  61259. {
  61260. getKeyPos (noteNum, x, w);
  61261. if (orientation == horizontalKeyboard)
  61262. drawBlackNote (noteNum, g, x, 0, w, blackNoteLength,
  61263. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61264. noteUnderMouse == noteNum,
  61265. blackNoteColour);
  61266. else if (orientation == verticalKeyboardFacingLeft)
  61267. drawBlackNote (noteNum, g, getWidth() - blackNoteLength, x, blackNoteLength, w,
  61268. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61269. noteUnderMouse == noteNum,
  61270. blackNoteColour);
  61271. else if (orientation == verticalKeyboardFacingRight)
  61272. drawBlackNote (noteNum, g, 0, getHeight() - x - w, blackNoteLength, w,
  61273. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61274. noteUnderMouse == noteNum,
  61275. blackNoteColour);
  61276. }
  61277. }
  61278. }
  61279. }
  61280. void MidiKeyboardComponent::drawWhiteNote (int midiNoteNumber,
  61281. Graphics& g, int x, int y, int w, int h,
  61282. bool isDown, bool isOver,
  61283. const Colour& lineColour,
  61284. const Colour& textColour)
  61285. {
  61286. Colour c (Colours::transparentWhite);
  61287. if (isDown)
  61288. c = findColour (keyDownOverlayColourId);
  61289. if (isOver)
  61290. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  61291. g.setColour (c);
  61292. g.fillRect (x, y, w, h);
  61293. const String text (getWhiteNoteText (midiNoteNumber));
  61294. if (! text.isEmpty())
  61295. {
  61296. g.setColour (textColour);
  61297. Font f (jmin (12.0f, keyWidth * 0.9f));
  61298. f.setHorizontalScale (0.8f);
  61299. g.setFont (f);
  61300. Justification justification (Justification::centredBottom);
  61301. if (orientation == verticalKeyboardFacingLeft)
  61302. justification = Justification::centredLeft;
  61303. else if (orientation == verticalKeyboardFacingRight)
  61304. justification = Justification::centredRight;
  61305. g.drawFittedText (text, x + 2, y + 2, w - 4, h - 4, justification, 1);
  61306. }
  61307. g.setColour (lineColour);
  61308. if (orientation == horizontalKeyboard)
  61309. g.fillRect (x, y, 1, h);
  61310. else if (orientation == verticalKeyboardFacingLeft)
  61311. g.fillRect (x, y, w, 1);
  61312. else if (orientation == verticalKeyboardFacingRight)
  61313. g.fillRect (x, y + h - 1, w, 1);
  61314. if (midiNoteNumber == rangeEnd)
  61315. {
  61316. if (orientation == horizontalKeyboard)
  61317. g.fillRect (x + w, y, 1, h);
  61318. else if (orientation == verticalKeyboardFacingLeft)
  61319. g.fillRect (x, y + h, w, 1);
  61320. else if (orientation == verticalKeyboardFacingRight)
  61321. g.fillRect (x, y - 1, w, 1);
  61322. }
  61323. }
  61324. void MidiKeyboardComponent::drawBlackNote (int /*midiNoteNumber*/,
  61325. Graphics& g, int x, int y, int w, int h,
  61326. bool isDown, bool isOver,
  61327. const Colour& noteFillColour)
  61328. {
  61329. Colour c (noteFillColour);
  61330. if (isDown)
  61331. c = c.overlaidWith (findColour (keyDownOverlayColourId));
  61332. if (isOver)
  61333. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  61334. g.setColour (c);
  61335. g.fillRect (x, y, w, h);
  61336. if (isDown)
  61337. {
  61338. g.setColour (noteFillColour);
  61339. g.drawRect (x, y, w, h);
  61340. }
  61341. else
  61342. {
  61343. const int xIndent = jmax (1, jmin (w, h) / 8);
  61344. g.setColour (c.brighter());
  61345. if (orientation == horizontalKeyboard)
  61346. g.fillRect (x + xIndent, y, w - xIndent * 2, 7 * h / 8);
  61347. else if (orientation == verticalKeyboardFacingLeft)
  61348. g.fillRect (x + w / 8, y + xIndent, w - w / 8, h - xIndent * 2);
  61349. else if (orientation == verticalKeyboardFacingRight)
  61350. g.fillRect (x, y + xIndent, 7 * w / 8, h - xIndent * 2);
  61351. }
  61352. }
  61353. void MidiKeyboardComponent::setOctaveForMiddleC (const int octaveNumForMiddleC_)
  61354. {
  61355. octaveNumForMiddleC = octaveNumForMiddleC_;
  61356. repaint();
  61357. }
  61358. const String MidiKeyboardComponent::getWhiteNoteText (const int midiNoteNumber)
  61359. {
  61360. if (keyWidth > 14.0f && midiNoteNumber % 12 == 0)
  61361. return MidiMessage::getMidiNoteName (midiNoteNumber, true, true, octaveNumForMiddleC);
  61362. return String::empty;
  61363. }
  61364. void MidiKeyboardComponent::drawUpDownButton (Graphics& g, int w, int h,
  61365. const bool isMouseOver_,
  61366. const bool isButtonDown,
  61367. const bool movesOctavesUp)
  61368. {
  61369. g.fillAll (findColour (upDownButtonBackgroundColourId));
  61370. float angle;
  61371. if (orientation == MidiKeyboardComponent::horizontalKeyboard)
  61372. angle = movesOctavesUp ? 0.0f : 0.5f;
  61373. else if (orientation == MidiKeyboardComponent::verticalKeyboardFacingLeft)
  61374. angle = movesOctavesUp ? 0.25f : 0.75f;
  61375. else
  61376. angle = movesOctavesUp ? 0.75f : 0.25f;
  61377. Path path;
  61378. path.lineTo (0.0f, 1.0f);
  61379. path.lineTo (1.0f, 0.5f);
  61380. path.closeSubPath();
  61381. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * angle, 0.5f, 0.5f));
  61382. g.setColour (findColour (upDownButtonArrowColourId)
  61383. .withAlpha (isButtonDown ? 1.0f : (isMouseOver_ ? 0.6f : 0.4f)));
  61384. g.fillPath (path, path.getTransformToScaleToFit (1.0f, 1.0f,
  61385. w - 2.0f,
  61386. h - 2.0f,
  61387. true));
  61388. }
  61389. void MidiKeyboardComponent::resized()
  61390. {
  61391. int w = getWidth();
  61392. int h = getHeight();
  61393. if (w > 0 && h > 0)
  61394. {
  61395. if (orientation != horizontalKeyboard)
  61396. swapVariables (w, h);
  61397. blackNoteLength = roundToInt (h * 0.7f);
  61398. int kx2, kw2;
  61399. getKeyPos (rangeEnd, kx2, kw2);
  61400. kx2 += kw2;
  61401. if (firstKey != rangeStart)
  61402. {
  61403. int kx1, kw1;
  61404. getKeyPos (rangeStart, kx1, kw1);
  61405. if (kx2 - kx1 <= w)
  61406. {
  61407. firstKey = rangeStart;
  61408. sendChangeMessage (this);
  61409. repaint();
  61410. }
  61411. }
  61412. const bool showScrollButtons = canScroll && (firstKey > rangeStart || kx2 > w + xOffset * 2);
  61413. scrollDown->setVisible (showScrollButtons);
  61414. scrollUp->setVisible (showScrollButtons);
  61415. xOffset = 0;
  61416. if (showScrollButtons)
  61417. {
  61418. const int scrollButtonW = jmin (12, w / 2);
  61419. if (orientation == horizontalKeyboard)
  61420. {
  61421. scrollDown->setBounds (0, 0, scrollButtonW, getHeight());
  61422. scrollUp->setBounds (getWidth() - scrollButtonW, 0, scrollButtonW, getHeight());
  61423. }
  61424. else if (orientation == verticalKeyboardFacingLeft)
  61425. {
  61426. scrollDown->setBounds (0, 0, getWidth(), scrollButtonW);
  61427. scrollUp->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  61428. }
  61429. else if (orientation == verticalKeyboardFacingRight)
  61430. {
  61431. scrollDown->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  61432. scrollUp->setBounds (0, 0, getWidth(), scrollButtonW);
  61433. }
  61434. int endOfLastKey, kw;
  61435. getKeyPos (rangeEnd, endOfLastKey, kw);
  61436. endOfLastKey += kw;
  61437. float mousePositionVelocity;
  61438. const int spaceAvailable = w - scrollButtonW * 2;
  61439. const int lastStartKey = remappedXYToNote (Point<int> (endOfLastKey - spaceAvailable, 0), mousePositionVelocity) + 1;
  61440. if (lastStartKey >= 0 && firstKey > lastStartKey)
  61441. {
  61442. firstKey = jlimit (rangeStart, rangeEnd, lastStartKey);
  61443. sendChangeMessage (this);
  61444. }
  61445. int newOffset = 0;
  61446. getKeyPos (firstKey, newOffset, kw);
  61447. xOffset = newOffset - scrollButtonW;
  61448. }
  61449. else
  61450. {
  61451. firstKey = rangeStart;
  61452. }
  61453. timerCallback();
  61454. repaint();
  61455. }
  61456. }
  61457. void MidiKeyboardComponent::handleNoteOn (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/, float /*velocity*/)
  61458. {
  61459. triggerAsyncUpdate();
  61460. }
  61461. void MidiKeyboardComponent::handleNoteOff (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/)
  61462. {
  61463. triggerAsyncUpdate();
  61464. }
  61465. void MidiKeyboardComponent::handleAsyncUpdate()
  61466. {
  61467. for (int i = rangeStart; i <= rangeEnd; ++i)
  61468. {
  61469. if (keysCurrentlyDrawnDown[i] != state.isNoteOnForChannels (midiInChannelMask, i))
  61470. {
  61471. keysCurrentlyDrawnDown.setBit (i, state.isNoteOnForChannels (midiInChannelMask, i));
  61472. repaintNote (i);
  61473. }
  61474. }
  61475. }
  61476. void MidiKeyboardComponent::resetAnyKeysInUse()
  61477. {
  61478. if (keysPressed.countNumberOfSetBits() > 0 || mouseDownNote > 0)
  61479. {
  61480. state.allNotesOff (midiChannel);
  61481. keysPressed.clear();
  61482. mouseDownNote = -1;
  61483. }
  61484. }
  61485. void MidiKeyboardComponent::updateNoteUnderMouse (const Point<int>& pos)
  61486. {
  61487. float mousePositionVelocity = 0.0f;
  61488. const int newNote = (mouseDragging || isMouseOver())
  61489. ? xyToNote (pos, mousePositionVelocity) : -1;
  61490. if (noteUnderMouse != newNote)
  61491. {
  61492. if (mouseDownNote >= 0)
  61493. {
  61494. state.noteOff (midiChannel, mouseDownNote);
  61495. mouseDownNote = -1;
  61496. }
  61497. if (mouseDragging && newNote >= 0)
  61498. {
  61499. if (! useMousePositionForVelocity)
  61500. mousePositionVelocity = 1.0f;
  61501. state.noteOn (midiChannel, newNote, mousePositionVelocity * velocity);
  61502. mouseDownNote = newNote;
  61503. }
  61504. repaintNote (noteUnderMouse);
  61505. noteUnderMouse = newNote;
  61506. repaintNote (noteUnderMouse);
  61507. }
  61508. else if (mouseDownNote >= 0 && ! mouseDragging)
  61509. {
  61510. state.noteOff (midiChannel, mouseDownNote);
  61511. mouseDownNote = -1;
  61512. }
  61513. }
  61514. void MidiKeyboardComponent::mouseMove (const MouseEvent& e)
  61515. {
  61516. updateNoteUnderMouse (e.getPosition());
  61517. stopTimer();
  61518. }
  61519. void MidiKeyboardComponent::mouseDrag (const MouseEvent& e)
  61520. {
  61521. float mousePositionVelocity;
  61522. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  61523. if (newNote >= 0)
  61524. mouseDraggedToKey (newNote, e);
  61525. updateNoteUnderMouse (e.getPosition());
  61526. }
  61527. bool MidiKeyboardComponent::mouseDownOnKey (int /*midiNoteNumber*/, const MouseEvent&)
  61528. {
  61529. return true;
  61530. }
  61531. void MidiKeyboardComponent::mouseDraggedToKey (int /*midiNoteNumber*/, const MouseEvent&)
  61532. {
  61533. }
  61534. void MidiKeyboardComponent::mouseDown (const MouseEvent& e)
  61535. {
  61536. float mousePositionVelocity;
  61537. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  61538. mouseDragging = false;
  61539. if (newNote >= 0 && mouseDownOnKey (newNote, e))
  61540. {
  61541. repaintNote (noteUnderMouse);
  61542. noteUnderMouse = -1;
  61543. mouseDragging = true;
  61544. updateNoteUnderMouse (e.getPosition());
  61545. startTimer (500);
  61546. }
  61547. }
  61548. void MidiKeyboardComponent::mouseUp (const MouseEvent& e)
  61549. {
  61550. mouseDragging = false;
  61551. updateNoteUnderMouse (e.getPosition());
  61552. stopTimer();
  61553. }
  61554. void MidiKeyboardComponent::mouseEnter (const MouseEvent& e)
  61555. {
  61556. updateNoteUnderMouse (e.getPosition());
  61557. }
  61558. void MidiKeyboardComponent::mouseExit (const MouseEvent& e)
  61559. {
  61560. updateNoteUnderMouse (e.getPosition());
  61561. }
  61562. void MidiKeyboardComponent::mouseWheelMove (const MouseEvent&, float ix, float iy)
  61563. {
  61564. setLowestVisibleKey (getLowestVisibleKey() + roundToInt ((ix != 0 ? ix : iy) * 5.0f));
  61565. }
  61566. void MidiKeyboardComponent::timerCallback()
  61567. {
  61568. updateNoteUnderMouse (getMouseXYRelative());
  61569. }
  61570. void MidiKeyboardComponent::clearKeyMappings()
  61571. {
  61572. resetAnyKeysInUse();
  61573. keyPressNotes.clear();
  61574. keyPresses.clear();
  61575. }
  61576. void MidiKeyboardComponent::setKeyPressForNote (const KeyPress& key,
  61577. const int midiNoteOffsetFromC)
  61578. {
  61579. removeKeyPressForNote (midiNoteOffsetFromC);
  61580. keyPressNotes.add (midiNoteOffsetFromC);
  61581. keyPresses.add (key);
  61582. }
  61583. void MidiKeyboardComponent::removeKeyPressForNote (const int midiNoteOffsetFromC)
  61584. {
  61585. for (int i = keyPressNotes.size(); --i >= 0;)
  61586. {
  61587. if (keyPressNotes.getUnchecked (i) == midiNoteOffsetFromC)
  61588. {
  61589. keyPressNotes.remove (i);
  61590. keyPresses.remove (i);
  61591. }
  61592. }
  61593. }
  61594. void MidiKeyboardComponent::setKeyPressBaseOctave (const int newOctaveNumber)
  61595. {
  61596. jassert (newOctaveNumber >= 0 && newOctaveNumber <= 10);
  61597. keyMappingOctave = newOctaveNumber;
  61598. }
  61599. bool MidiKeyboardComponent::keyStateChanged (const bool /*isKeyDown*/)
  61600. {
  61601. bool keyPressUsed = false;
  61602. for (int i = keyPresses.size(); --i >= 0;)
  61603. {
  61604. const int note = 12 * keyMappingOctave + keyPressNotes.getUnchecked (i);
  61605. if (keyPresses.getReference(i).isCurrentlyDown())
  61606. {
  61607. if (! keysPressed [note])
  61608. {
  61609. keysPressed.setBit (note);
  61610. state.noteOn (midiChannel, note, velocity);
  61611. keyPressUsed = true;
  61612. }
  61613. }
  61614. else
  61615. {
  61616. if (keysPressed [note])
  61617. {
  61618. keysPressed.clearBit (note);
  61619. state.noteOff (midiChannel, note);
  61620. keyPressUsed = true;
  61621. }
  61622. }
  61623. }
  61624. return keyPressUsed;
  61625. }
  61626. void MidiKeyboardComponent::focusLost (FocusChangeType)
  61627. {
  61628. resetAnyKeysInUse();
  61629. }
  61630. END_JUCE_NAMESPACE
  61631. /*** End of inlined file: juce_MidiKeyboardComponent.cpp ***/
  61632. /*** Start of inlined file: juce_OpenGLComponent.cpp ***/
  61633. #if JUCE_OPENGL
  61634. BEGIN_JUCE_NAMESPACE
  61635. extern void juce_glViewport (const int w, const int h);
  61636. OpenGLPixelFormat::OpenGLPixelFormat (const int bitsPerRGBComponent,
  61637. const int alphaBits_,
  61638. const int depthBufferBits_,
  61639. const int stencilBufferBits_)
  61640. : redBits (bitsPerRGBComponent),
  61641. greenBits (bitsPerRGBComponent),
  61642. blueBits (bitsPerRGBComponent),
  61643. alphaBits (alphaBits_),
  61644. depthBufferBits (depthBufferBits_),
  61645. stencilBufferBits (stencilBufferBits_),
  61646. accumulationBufferRedBits (0),
  61647. accumulationBufferGreenBits (0),
  61648. accumulationBufferBlueBits (0),
  61649. accumulationBufferAlphaBits (0),
  61650. fullSceneAntiAliasingNumSamples (0)
  61651. {
  61652. }
  61653. OpenGLPixelFormat::OpenGLPixelFormat (const OpenGLPixelFormat& other)
  61654. : redBits (other.redBits),
  61655. greenBits (other.greenBits),
  61656. blueBits (other.blueBits),
  61657. alphaBits (other.alphaBits),
  61658. depthBufferBits (other.depthBufferBits),
  61659. stencilBufferBits (other.stencilBufferBits),
  61660. accumulationBufferRedBits (other.accumulationBufferRedBits),
  61661. accumulationBufferGreenBits (other.accumulationBufferGreenBits),
  61662. accumulationBufferBlueBits (other.accumulationBufferBlueBits),
  61663. accumulationBufferAlphaBits (other.accumulationBufferAlphaBits),
  61664. fullSceneAntiAliasingNumSamples (other.fullSceneAntiAliasingNumSamples)
  61665. {
  61666. }
  61667. OpenGLPixelFormat& OpenGLPixelFormat::operator= (const OpenGLPixelFormat& other)
  61668. {
  61669. redBits = other.redBits;
  61670. greenBits = other.greenBits;
  61671. blueBits = other.blueBits;
  61672. alphaBits = other.alphaBits;
  61673. depthBufferBits = other.depthBufferBits;
  61674. stencilBufferBits = other.stencilBufferBits;
  61675. accumulationBufferRedBits = other.accumulationBufferRedBits;
  61676. accumulationBufferGreenBits = other.accumulationBufferGreenBits;
  61677. accumulationBufferBlueBits = other.accumulationBufferBlueBits;
  61678. accumulationBufferAlphaBits = other.accumulationBufferAlphaBits;
  61679. fullSceneAntiAliasingNumSamples = other.fullSceneAntiAliasingNumSamples;
  61680. return *this;
  61681. }
  61682. bool OpenGLPixelFormat::operator== (const OpenGLPixelFormat& other) const
  61683. {
  61684. return redBits == other.redBits
  61685. && greenBits == other.greenBits
  61686. && blueBits == other.blueBits
  61687. && alphaBits == other.alphaBits
  61688. && depthBufferBits == other.depthBufferBits
  61689. && stencilBufferBits == other.stencilBufferBits
  61690. && accumulationBufferRedBits == other.accumulationBufferRedBits
  61691. && accumulationBufferGreenBits == other.accumulationBufferGreenBits
  61692. && accumulationBufferBlueBits == other.accumulationBufferBlueBits
  61693. && accumulationBufferAlphaBits == other.accumulationBufferAlphaBits
  61694. && fullSceneAntiAliasingNumSamples == other.fullSceneAntiAliasingNumSamples;
  61695. }
  61696. static Array<OpenGLContext*> knownContexts;
  61697. OpenGLContext::OpenGLContext() throw()
  61698. {
  61699. knownContexts.add (this);
  61700. }
  61701. OpenGLContext::~OpenGLContext()
  61702. {
  61703. knownContexts.removeValue (this);
  61704. }
  61705. OpenGLContext* OpenGLContext::getCurrentContext()
  61706. {
  61707. for (int i = knownContexts.size(); --i >= 0;)
  61708. {
  61709. OpenGLContext* const oglc = knownContexts.getUnchecked(i);
  61710. if (oglc->isActive())
  61711. return oglc;
  61712. }
  61713. return 0;
  61714. }
  61715. class OpenGLComponent::OpenGLComponentWatcher : public ComponentMovementWatcher
  61716. {
  61717. public:
  61718. OpenGLComponentWatcher (OpenGLComponent* const owner_)
  61719. : ComponentMovementWatcher (owner_),
  61720. owner (owner_),
  61721. wasShowing (false)
  61722. {
  61723. }
  61724. ~OpenGLComponentWatcher() {}
  61725. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  61726. {
  61727. owner->updateContextPosition();
  61728. }
  61729. void componentPeerChanged()
  61730. {
  61731. const ScopedLock sl (owner->getContextLock());
  61732. owner->deleteContext();
  61733. }
  61734. void componentVisibilityChanged (Component&)
  61735. {
  61736. const bool isShowingNow = owner->isShowing();
  61737. if (wasShowing != isShowingNow)
  61738. {
  61739. wasShowing = isShowingNow;
  61740. if (! isShowingNow)
  61741. {
  61742. const ScopedLock sl (owner->getContextLock());
  61743. owner->deleteContext();
  61744. }
  61745. }
  61746. }
  61747. juce_UseDebuggingNewOperator
  61748. private:
  61749. OpenGLComponent* const owner;
  61750. bool wasShowing;
  61751. };
  61752. OpenGLComponent::OpenGLComponent (const OpenGLType type_)
  61753. : type (type_),
  61754. contextToShareListsWith (0),
  61755. needToUpdateViewport (true)
  61756. {
  61757. setOpaque (true);
  61758. componentWatcher = new OpenGLComponentWatcher (this);
  61759. }
  61760. OpenGLComponent::~OpenGLComponent()
  61761. {
  61762. deleteContext();
  61763. componentWatcher = 0;
  61764. }
  61765. void OpenGLComponent::deleteContext()
  61766. {
  61767. const ScopedLock sl (contextLock);
  61768. context = 0;
  61769. }
  61770. void OpenGLComponent::updateContextPosition()
  61771. {
  61772. needToUpdateViewport = true;
  61773. if (getWidth() > 0 && getHeight() > 0)
  61774. {
  61775. Component* const topComp = getTopLevelComponent();
  61776. if (topComp->getPeer() != 0)
  61777. {
  61778. const ScopedLock sl (contextLock);
  61779. if (context != 0)
  61780. context->updateWindowPosition (getScreenX() - topComp->getScreenX(),
  61781. getScreenY() - topComp->getScreenY(),
  61782. getWidth(),
  61783. getHeight(),
  61784. topComp->getHeight());
  61785. }
  61786. }
  61787. }
  61788. const OpenGLPixelFormat OpenGLComponent::getPixelFormat() const
  61789. {
  61790. OpenGLPixelFormat pf;
  61791. const ScopedLock sl (contextLock);
  61792. if (context != 0)
  61793. pf = context->getPixelFormat();
  61794. return pf;
  61795. }
  61796. void OpenGLComponent::setPixelFormat (const OpenGLPixelFormat& formatToUse)
  61797. {
  61798. if (! (preferredPixelFormat == formatToUse))
  61799. {
  61800. const ScopedLock sl (contextLock);
  61801. deleteContext();
  61802. preferredPixelFormat = formatToUse;
  61803. }
  61804. }
  61805. void OpenGLComponent::shareWith (OpenGLContext* c)
  61806. {
  61807. if (contextToShareListsWith != c)
  61808. {
  61809. const ScopedLock sl (contextLock);
  61810. deleteContext();
  61811. contextToShareListsWith = c;
  61812. }
  61813. }
  61814. bool OpenGLComponent::makeCurrentContextActive()
  61815. {
  61816. if (context == 0)
  61817. {
  61818. const ScopedLock sl (contextLock);
  61819. if (isShowing() && getTopLevelComponent()->getPeer() != 0)
  61820. {
  61821. context = createContext();
  61822. if (context != 0)
  61823. {
  61824. updateContextPosition();
  61825. if (context->makeActive())
  61826. newOpenGLContextCreated();
  61827. }
  61828. }
  61829. }
  61830. return context != 0 && context->makeActive();
  61831. }
  61832. void OpenGLComponent::makeCurrentContextInactive()
  61833. {
  61834. if (context != 0)
  61835. context->makeInactive();
  61836. }
  61837. bool OpenGLComponent::isActiveContext() const throw()
  61838. {
  61839. return context != 0 && context->isActive();
  61840. }
  61841. void OpenGLComponent::swapBuffers()
  61842. {
  61843. if (context != 0)
  61844. context->swapBuffers();
  61845. }
  61846. void OpenGLComponent::paint (Graphics&)
  61847. {
  61848. if (renderAndSwapBuffers())
  61849. {
  61850. ComponentPeer* const peer = getPeer();
  61851. if (peer != 0)
  61852. {
  61853. const Point<int> topLeft (getScreenPosition() - peer->getScreenPosition());
  61854. peer->addMaskedRegion (topLeft.getX(), topLeft.getY(), getWidth(), getHeight());
  61855. }
  61856. }
  61857. }
  61858. bool OpenGLComponent::renderAndSwapBuffers()
  61859. {
  61860. const ScopedLock sl (contextLock);
  61861. if (! makeCurrentContextActive())
  61862. return false;
  61863. if (needToUpdateViewport)
  61864. {
  61865. needToUpdateViewport = false;
  61866. juce_glViewport (getWidth(), getHeight());
  61867. }
  61868. renderOpenGL();
  61869. swapBuffers();
  61870. return true;
  61871. }
  61872. void OpenGLComponent::internalRepaint (int x, int y, int w, int h)
  61873. {
  61874. Component::internalRepaint (x, y, w, h);
  61875. if (context != 0)
  61876. context->repaint();
  61877. }
  61878. END_JUCE_NAMESPACE
  61879. #endif
  61880. /*** End of inlined file: juce_OpenGLComponent.cpp ***/
  61881. /*** Start of inlined file: juce_PreferencesPanel.cpp ***/
  61882. BEGIN_JUCE_NAMESPACE
  61883. PreferencesPanel::PreferencesPanel()
  61884. : buttonSize (70)
  61885. {
  61886. }
  61887. PreferencesPanel::~PreferencesPanel()
  61888. {
  61889. currentPage = 0;
  61890. deleteAllChildren();
  61891. }
  61892. void PreferencesPanel::addSettingsPage (const String& title,
  61893. const Drawable* icon,
  61894. const Drawable* overIcon,
  61895. const Drawable* downIcon)
  61896. {
  61897. DrawableButton* button = new DrawableButton (title, DrawableButton::ImageAboveTextLabel);
  61898. button->setImages (icon, overIcon, downIcon);
  61899. button->setRadioGroupId (1);
  61900. button->addButtonListener (this);
  61901. button->setClickingTogglesState (true);
  61902. button->setWantsKeyboardFocus (false);
  61903. addAndMakeVisible (button);
  61904. resized();
  61905. if (currentPage == 0)
  61906. setCurrentPage (title);
  61907. }
  61908. void PreferencesPanel::addSettingsPage (const String& title,
  61909. const void* imageData,
  61910. const int imageDataSize)
  61911. {
  61912. DrawableImage icon, iconOver, iconDown;
  61913. icon.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61914. iconOver.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61915. iconOver.setOverlayColour (Colours::black.withAlpha (0.12f));
  61916. iconDown.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61917. iconDown.setOverlayColour (Colours::black.withAlpha (0.25f));
  61918. addSettingsPage (title, &icon, &iconOver, &iconDown);
  61919. }
  61920. class PrefsDialogWindow : public DialogWindow
  61921. {
  61922. public:
  61923. PrefsDialogWindow (const String& dialogtitle,
  61924. const Colour& backgroundColour)
  61925. : DialogWindow (dialogtitle, backgroundColour, true)
  61926. {
  61927. }
  61928. ~PrefsDialogWindow()
  61929. {
  61930. }
  61931. void closeButtonPressed()
  61932. {
  61933. exitModalState (0);
  61934. }
  61935. private:
  61936. PrefsDialogWindow (const PrefsDialogWindow&);
  61937. PrefsDialogWindow& operator= (const PrefsDialogWindow&);
  61938. };
  61939. void PreferencesPanel::showInDialogBox (const String& dialogtitle,
  61940. int dialogWidth,
  61941. int dialogHeight,
  61942. const Colour& backgroundColour)
  61943. {
  61944. setSize (dialogWidth, dialogHeight);
  61945. PrefsDialogWindow dw (dialogtitle, backgroundColour);
  61946. dw.setContentComponent (this, true, true);
  61947. dw.centreAroundComponent (0, dw.getWidth(), dw.getHeight());
  61948. dw.runModalLoop();
  61949. dw.setContentComponent (0, false, false);
  61950. }
  61951. void PreferencesPanel::resized()
  61952. {
  61953. int x = 0;
  61954. for (int i = 0; i < getNumChildComponents(); ++i)
  61955. {
  61956. Component* c = getChildComponent (i);
  61957. if (dynamic_cast <DrawableButton*> (c) == 0)
  61958. {
  61959. c->setBounds (0, buttonSize + 5, getWidth(), getHeight() - buttonSize - 5);
  61960. }
  61961. else
  61962. {
  61963. c->setBounds (x, 0, buttonSize, buttonSize);
  61964. x += buttonSize;
  61965. }
  61966. }
  61967. }
  61968. void PreferencesPanel::paint (Graphics& g)
  61969. {
  61970. g.setColour (Colours::grey);
  61971. g.fillRect (0, buttonSize + 2, getWidth(), 1);
  61972. }
  61973. void PreferencesPanel::setCurrentPage (const String& pageName)
  61974. {
  61975. if (currentPageName != pageName)
  61976. {
  61977. currentPageName = pageName;
  61978. currentPage = 0;
  61979. currentPage = createComponentForPage (pageName);
  61980. if (currentPage != 0)
  61981. {
  61982. addAndMakeVisible (currentPage);
  61983. currentPage->toBack();
  61984. resized();
  61985. }
  61986. for (int i = 0; i < getNumChildComponents(); ++i)
  61987. {
  61988. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  61989. if (db != 0 && db->getName() == pageName)
  61990. {
  61991. db->setToggleState (true, false);
  61992. break;
  61993. }
  61994. }
  61995. }
  61996. }
  61997. void PreferencesPanel::buttonClicked (Button*)
  61998. {
  61999. for (int i = 0; i < getNumChildComponents(); ++i)
  62000. {
  62001. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  62002. if (db != 0 && db->getToggleState())
  62003. {
  62004. setCurrentPage (db->getName());
  62005. break;
  62006. }
  62007. }
  62008. }
  62009. END_JUCE_NAMESPACE
  62010. /*** End of inlined file: juce_PreferencesPanel.cpp ***/
  62011. /*** Start of inlined file: juce_SystemTrayIconComponent.cpp ***/
  62012. #if JUCE_WINDOWS || JUCE_LINUX
  62013. BEGIN_JUCE_NAMESPACE
  62014. SystemTrayIconComponent::SystemTrayIconComponent()
  62015. {
  62016. addToDesktop (0);
  62017. }
  62018. SystemTrayIconComponent::~SystemTrayIconComponent()
  62019. {
  62020. }
  62021. END_JUCE_NAMESPACE
  62022. #endif
  62023. /*** End of inlined file: juce_SystemTrayIconComponent.cpp ***/
  62024. /*** Start of inlined file: juce_AlertWindow.cpp ***/
  62025. BEGIN_JUCE_NAMESPACE
  62026. class AlertWindowTextEditor : public TextEditor
  62027. {
  62028. public:
  62029. AlertWindowTextEditor (const String& name, const bool isPasswordBox)
  62030. : TextEditor (name, isPasswordBox ? getDefaultPasswordChar() : 0)
  62031. {
  62032. setSelectAllWhenFocused (true);
  62033. }
  62034. ~AlertWindowTextEditor()
  62035. {
  62036. }
  62037. void returnPressed()
  62038. {
  62039. // pass these up the component hierarchy to be trigger the buttons
  62040. getParentComponent()->keyPressed (KeyPress (KeyPress::returnKey, 0, '\n'));
  62041. }
  62042. void escapePressed()
  62043. {
  62044. // pass these up the component hierarchy to be trigger the buttons
  62045. getParentComponent()->keyPressed (KeyPress (KeyPress::escapeKey, 0, 0));
  62046. }
  62047. private:
  62048. AlertWindowTextEditor (const AlertWindowTextEditor&);
  62049. AlertWindowTextEditor& operator= (const AlertWindowTextEditor&);
  62050. static juce_wchar getDefaultPasswordChar() throw()
  62051. {
  62052. #if JUCE_LINUX
  62053. return 0x2022;
  62054. #else
  62055. return 0x25cf;
  62056. #endif
  62057. }
  62058. };
  62059. AlertWindow::AlertWindow (const String& title,
  62060. const String& message,
  62061. AlertIconType iconType,
  62062. Component* associatedComponent_)
  62063. : TopLevelWindow (title, true),
  62064. alertIconType (iconType),
  62065. associatedComponent (associatedComponent_)
  62066. {
  62067. if (message.isEmpty())
  62068. text = " "; // to force an update if the message is empty
  62069. setMessage (message);
  62070. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  62071. {
  62072. Component* const c = Desktop::getInstance().getComponent (i);
  62073. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  62074. {
  62075. setAlwaysOnTop (true);
  62076. break;
  62077. }
  62078. }
  62079. if (! JUCEApplication::isStandaloneApp())
  62080. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  62081. lookAndFeelChanged();
  62082. constrainer.setMinimumOnscreenAmounts (0x10000, 0x10000, 0x10000, 0x10000);
  62083. }
  62084. AlertWindow::~AlertWindow()
  62085. {
  62086. for (int i = customComps.size(); --i >= 0;)
  62087. removeChildComponent ((Component*) customComps[i]);
  62088. deleteAllChildren();
  62089. }
  62090. void AlertWindow::userTriedToCloseWindow()
  62091. {
  62092. exitModalState (0);
  62093. }
  62094. void AlertWindow::setMessage (const String& message)
  62095. {
  62096. const String newMessage (message.substring (0, 2048));
  62097. if (text != newMessage)
  62098. {
  62099. text = newMessage;
  62100. font.setHeight (15.0f);
  62101. Font titleFont (font.getHeight() * 1.1f, Font::bold);
  62102. textLayout.setText (getName() + "\n\n", titleFont);
  62103. textLayout.appendText (text, font);
  62104. updateLayout (true);
  62105. repaint();
  62106. }
  62107. }
  62108. void AlertWindow::buttonClicked (Button* button)
  62109. {
  62110. for (int i = 0; i < buttons.size(); i++)
  62111. {
  62112. TextButton* const c = (TextButton*) buttons[i];
  62113. if (button->getName() == c->getName())
  62114. {
  62115. if (c->getParentComponent() != 0)
  62116. c->getParentComponent()->exitModalState (c->getCommandID());
  62117. break;
  62118. }
  62119. }
  62120. }
  62121. void AlertWindow::addButton (const String& name,
  62122. const int returnValue,
  62123. const KeyPress& shortcutKey1,
  62124. const KeyPress& shortcutKey2)
  62125. {
  62126. TextButton* const b = new TextButton (name, String::empty);
  62127. b->setWantsKeyboardFocus (true);
  62128. b->setMouseClickGrabsKeyboardFocus (false);
  62129. b->setCommandToTrigger (0, returnValue, false);
  62130. b->addShortcut (shortcutKey1);
  62131. b->addShortcut (shortcutKey2);
  62132. b->addButtonListener (this);
  62133. b->changeWidthToFitText (getLookAndFeel().getAlertWindowButtonHeight());
  62134. addAndMakeVisible (b, 0);
  62135. buttons.add (b);
  62136. updateLayout (false);
  62137. }
  62138. int AlertWindow::getNumButtons() const
  62139. {
  62140. return buttons.size();
  62141. }
  62142. void AlertWindow::triggerButtonClick (const String& buttonName)
  62143. {
  62144. for (int i = buttons.size(); --i >= 0;)
  62145. {
  62146. TextButton* const b = (TextButton*) buttons[i];
  62147. if (buttonName == b->getName())
  62148. {
  62149. b->triggerClick();
  62150. break;
  62151. }
  62152. }
  62153. }
  62154. void AlertWindow::addTextEditor (const String& name,
  62155. const String& initialContents,
  62156. const String& onScreenLabel,
  62157. const bool isPasswordBox)
  62158. {
  62159. AlertWindowTextEditor* const tc = new AlertWindowTextEditor (name, isPasswordBox);
  62160. tc->setColour (TextEditor::outlineColourId, findColour (ComboBox::outlineColourId));
  62161. tc->setFont (font);
  62162. tc->setText (initialContents);
  62163. tc->setCaretPosition (initialContents.length());
  62164. addAndMakeVisible (tc);
  62165. textBoxes.add (tc);
  62166. allComps.add (tc);
  62167. textboxNames.add (onScreenLabel);
  62168. updateLayout (false);
  62169. }
  62170. TextEditor* AlertWindow::getTextEditor (const String& nameOfTextEditor) const
  62171. {
  62172. for (int i = textBoxes.size(); --i >= 0;)
  62173. if (static_cast <TextEditor*> (textBoxes.getUnchecked(i))->getName() == nameOfTextEditor)
  62174. return static_cast <TextEditor*> (textBoxes.getUnchecked(i));
  62175. return 0;
  62176. }
  62177. const String AlertWindow::getTextEditorContents (const String& nameOfTextEditor) const
  62178. {
  62179. TextEditor* const t = getTextEditor (nameOfTextEditor);
  62180. return t != 0 ? t->getText() : String::empty;
  62181. }
  62182. void AlertWindow::addComboBox (const String& name,
  62183. const StringArray& items,
  62184. const String& onScreenLabel)
  62185. {
  62186. ComboBox* const cb = new ComboBox (name);
  62187. for (int i = 0; i < items.size(); ++i)
  62188. cb->addItem (items[i], i + 1);
  62189. addAndMakeVisible (cb);
  62190. cb->setSelectedItemIndex (0);
  62191. comboBoxes.add (cb);
  62192. allComps.add (cb);
  62193. comboBoxNames.add (onScreenLabel);
  62194. updateLayout (false);
  62195. }
  62196. ComboBox* AlertWindow::getComboBoxComponent (const String& nameOfList) const
  62197. {
  62198. for (int i = comboBoxes.size(); --i >= 0;)
  62199. if (((ComboBox*) comboBoxes[i])->getName() == nameOfList)
  62200. return (ComboBox*) comboBoxes[i];
  62201. return 0;
  62202. }
  62203. class AlertTextComp : public TextEditor
  62204. {
  62205. public:
  62206. AlertTextComp (const String& message,
  62207. const Font& font)
  62208. {
  62209. setReadOnly (true);
  62210. setMultiLine (true, true);
  62211. setCaretVisible (false);
  62212. setScrollbarsShown (true);
  62213. lookAndFeelChanged();
  62214. setWantsKeyboardFocus (false);
  62215. setFont (font);
  62216. setText (message, false);
  62217. bestWidth = 2 * (int) std::sqrt (font.getHeight() * font.getStringWidth (message));
  62218. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  62219. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  62220. setColour (TextEditor::shadowColourId, Colours::transparentBlack);
  62221. }
  62222. ~AlertTextComp()
  62223. {
  62224. }
  62225. int getPreferredWidth() const throw() { return bestWidth; }
  62226. void updateLayout (const int width)
  62227. {
  62228. TextLayout text;
  62229. text.appendText (getText(), getFont());
  62230. text.layout (width - 8, Justification::topLeft, true);
  62231. setSize (width, jmin (width, text.getHeight() + (int) getFont().getHeight()));
  62232. }
  62233. private:
  62234. int bestWidth;
  62235. AlertTextComp (const AlertTextComp&);
  62236. AlertTextComp& operator= (const AlertTextComp&);
  62237. };
  62238. void AlertWindow::addTextBlock (const String& textBlock)
  62239. {
  62240. AlertTextComp* const c = new AlertTextComp (textBlock, font);
  62241. textBlocks.add (c);
  62242. allComps.add (c);
  62243. addAndMakeVisible (c);
  62244. updateLayout (false);
  62245. }
  62246. void AlertWindow::addProgressBarComponent (double& progressValue)
  62247. {
  62248. ProgressBar* const pb = new ProgressBar (progressValue);
  62249. progressBars.add (pb);
  62250. allComps.add (pb);
  62251. addAndMakeVisible (pb);
  62252. updateLayout (false);
  62253. }
  62254. void AlertWindow::addCustomComponent (Component* const component)
  62255. {
  62256. customComps.add (component);
  62257. allComps.add (component);
  62258. addAndMakeVisible (component);
  62259. updateLayout (false);
  62260. }
  62261. int AlertWindow::getNumCustomComponents() const
  62262. {
  62263. return customComps.size();
  62264. }
  62265. Component* AlertWindow::getCustomComponent (const int index) const
  62266. {
  62267. return (Component*) customComps [index];
  62268. }
  62269. Component* AlertWindow::removeCustomComponent (const int index)
  62270. {
  62271. Component* const c = getCustomComponent (index);
  62272. if (c != 0)
  62273. {
  62274. customComps.removeValue (c);
  62275. allComps.removeValue (c);
  62276. removeChildComponent (c);
  62277. updateLayout (false);
  62278. }
  62279. return c;
  62280. }
  62281. void AlertWindow::paint (Graphics& g)
  62282. {
  62283. getLookAndFeel().drawAlertBox (g, *this, textArea, textLayout);
  62284. g.setColour (findColour (textColourId));
  62285. g.setFont (getLookAndFeel().getAlertWindowFont());
  62286. int i;
  62287. for (i = textBoxes.size(); --i >= 0;)
  62288. {
  62289. const TextEditor* const te = (TextEditor*) textBoxes[i];
  62290. g.drawFittedText (textboxNames[i],
  62291. te->getX(), te->getY() - 14,
  62292. te->getWidth(), 14,
  62293. Justification::centredLeft, 1);
  62294. }
  62295. for (i = comboBoxNames.size(); --i >= 0;)
  62296. {
  62297. const ComboBox* const cb = (ComboBox*) comboBoxes[i];
  62298. g.drawFittedText (comboBoxNames[i],
  62299. cb->getX(), cb->getY() - 14,
  62300. cb->getWidth(), 14,
  62301. Justification::centredLeft, 1);
  62302. }
  62303. for (i = customComps.size(); --i >= 0;)
  62304. {
  62305. const Component* const c = (Component*) customComps[i];
  62306. g.drawFittedText (c->getName(),
  62307. c->getX(), c->getY() - 14,
  62308. c->getWidth(), 14,
  62309. Justification::centredLeft, 1);
  62310. }
  62311. }
  62312. void AlertWindow::updateLayout (const bool onlyIncreaseSize)
  62313. {
  62314. const int titleH = 24;
  62315. const int iconWidth = 80;
  62316. const int wid = jmax (font.getStringWidth (text),
  62317. font.getStringWidth (getName()));
  62318. const int sw = (int) std::sqrt (font.getHeight() * wid);
  62319. int w = jmin (300 + sw * 2, (int) (getParentWidth() * 0.7f));
  62320. const int edgeGap = 10;
  62321. const int labelHeight = 18;
  62322. int iconSpace;
  62323. if (alertIconType == NoIcon)
  62324. {
  62325. textLayout.layout (w, Justification::horizontallyCentred, true);
  62326. iconSpace = 0;
  62327. }
  62328. else
  62329. {
  62330. textLayout.layout (w, Justification::left, true);
  62331. iconSpace = iconWidth;
  62332. }
  62333. w = jmax (350, textLayout.getWidth() + iconSpace + edgeGap * 4);
  62334. w = jmin (w, (int) (getParentWidth() * 0.7f));
  62335. const int textLayoutH = textLayout.getHeight();
  62336. const int textBottom = 16 + titleH + textLayoutH;
  62337. int h = textBottom;
  62338. int buttonW = 40;
  62339. int i;
  62340. for (i = 0; i < buttons.size(); ++i)
  62341. buttonW += 16 + ((const TextButton*) buttons[i])->getWidth();
  62342. w = jmax (buttonW, w);
  62343. h += (textBoxes.size() + comboBoxes.size() + progressBars.size()) * 50;
  62344. if (buttons.size() > 0)
  62345. h += 20 + ((TextButton*) buttons[0])->getHeight();
  62346. for (i = customComps.size(); --i >= 0;)
  62347. {
  62348. Component* c = (Component*) customComps[i];
  62349. w = jmax (w, (c->getWidth() * 100) / 80);
  62350. h += 10 + c->getHeight();
  62351. if (c->getName().isNotEmpty())
  62352. h += labelHeight;
  62353. }
  62354. for (i = textBlocks.size(); --i >= 0;)
  62355. {
  62356. const AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  62357. w = jmax (w, ac->getPreferredWidth());
  62358. }
  62359. w = jmin (w, (int) (getParentWidth() * 0.7f));
  62360. for (i = textBlocks.size(); --i >= 0;)
  62361. {
  62362. AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  62363. ac->updateLayout ((int) (w * 0.8f));
  62364. h += ac->getHeight() + 10;
  62365. }
  62366. h = jmin (getParentHeight() - 50, h);
  62367. if (onlyIncreaseSize)
  62368. {
  62369. w = jmax (w, getWidth());
  62370. h = jmax (h, getHeight());
  62371. }
  62372. if (! isVisible())
  62373. {
  62374. centreAroundComponent (associatedComponent, w, h);
  62375. }
  62376. else
  62377. {
  62378. const int cx = getX() + getWidth() / 2;
  62379. const int cy = getY() + getHeight() / 2;
  62380. setBounds (cx - w / 2,
  62381. cy - h / 2,
  62382. w, h);
  62383. }
  62384. textArea.setBounds (edgeGap, edgeGap, w - (edgeGap * 2), h - edgeGap);
  62385. const int spacer = 16;
  62386. int totalWidth = -spacer;
  62387. for (i = buttons.size(); --i >= 0;)
  62388. totalWidth += ((TextButton*) buttons[i])->getWidth() + spacer;
  62389. int x = (w - totalWidth) / 2;
  62390. int y = (int) (getHeight() * 0.95f);
  62391. for (i = 0; i < buttons.size(); ++i)
  62392. {
  62393. TextButton* const c = (TextButton*) buttons[i];
  62394. int ny = proportionOfHeight (0.95f) - c->getHeight();
  62395. c->setTopLeftPosition (x, ny);
  62396. if (ny < y)
  62397. y = ny;
  62398. x += c->getWidth() + spacer;
  62399. c->toFront (false);
  62400. }
  62401. y = textBottom;
  62402. for (i = 0; i < allComps.size(); ++i)
  62403. {
  62404. Component* const c = (Component*) allComps[i];
  62405. h = 22;
  62406. const int comboIndex = comboBoxes.indexOf (c);
  62407. if (comboIndex >= 0 && comboBoxNames [comboIndex].isNotEmpty())
  62408. y += labelHeight;
  62409. const int tbIndex = textBoxes.indexOf (c);
  62410. if (tbIndex >= 0 && textboxNames[tbIndex].isNotEmpty())
  62411. y += labelHeight;
  62412. if (customComps.contains (c))
  62413. {
  62414. if (c->getName().isNotEmpty())
  62415. y += labelHeight;
  62416. c->setTopLeftPosition (proportionOfWidth (0.1f), y);
  62417. h = c->getHeight();
  62418. }
  62419. else if (textBlocks.contains (c))
  62420. {
  62421. c->setTopLeftPosition ((getWidth() - c->getWidth()) / 2, y);
  62422. h = c->getHeight();
  62423. }
  62424. else
  62425. {
  62426. c->setBounds (proportionOfWidth (0.1f), y, proportionOfWidth (0.8f), h);
  62427. }
  62428. y += h + 10;
  62429. }
  62430. setWantsKeyboardFocus (getNumChildComponents() == 0);
  62431. }
  62432. bool AlertWindow::containsAnyExtraComponents() const
  62433. {
  62434. return textBoxes.size()
  62435. + comboBoxes.size()
  62436. + progressBars.size()
  62437. + customComps.size() > 0;
  62438. }
  62439. void AlertWindow::mouseDown (const MouseEvent&)
  62440. {
  62441. dragger.startDraggingComponent (this, &constrainer);
  62442. }
  62443. void AlertWindow::mouseDrag (const MouseEvent& e)
  62444. {
  62445. dragger.dragComponent (this, e);
  62446. }
  62447. bool AlertWindow::keyPressed (const KeyPress& key)
  62448. {
  62449. for (int i = buttons.size(); --i >= 0;)
  62450. {
  62451. TextButton* const b = (TextButton*) buttons[i];
  62452. if (b->isRegisteredForShortcut (key))
  62453. {
  62454. b->triggerClick();
  62455. return true;
  62456. }
  62457. }
  62458. if (key.isKeyCode (KeyPress::escapeKey) && buttons.size() == 0)
  62459. {
  62460. exitModalState (0);
  62461. return true;
  62462. }
  62463. else if (key.isKeyCode (KeyPress::returnKey) && buttons.size() == 1)
  62464. {
  62465. ((TextButton*) buttons.getFirst())->triggerClick();
  62466. return true;
  62467. }
  62468. return false;
  62469. }
  62470. void AlertWindow::lookAndFeelChanged()
  62471. {
  62472. const int newFlags = getLookAndFeel().getAlertBoxWindowFlags();
  62473. setUsingNativeTitleBar ((newFlags & ComponentPeer::windowHasTitleBar) != 0);
  62474. setDropShadowEnabled (isOpaque() && (newFlags & ComponentPeer::windowHasDropShadow) != 0);
  62475. }
  62476. int AlertWindow::getDesktopWindowStyleFlags() const
  62477. {
  62478. return getLookAndFeel().getAlertBoxWindowFlags();
  62479. }
  62480. struct AlertWindowInfo
  62481. {
  62482. String title, message, button1, button2, button3;
  62483. AlertWindow::AlertIconType iconType;
  62484. int numButtons;
  62485. Component::SafePointer<Component> associatedComponent;
  62486. int run() const
  62487. {
  62488. return (int) (pointer_sized_int)
  62489. MessageManager::getInstance()->callFunctionOnMessageThread (showCallback, (void*) this);
  62490. }
  62491. private:
  62492. int show() const
  62493. {
  62494. LookAndFeel& lf = associatedComponent != 0 ? associatedComponent->getLookAndFeel()
  62495. : LookAndFeel::getDefaultLookAndFeel();
  62496. ScopedPointer <Component> alertBox (lf.createAlertWindow (title, message, button1, button2, button3,
  62497. iconType, numButtons, associatedComponent));
  62498. jassert (alertBox != 0); // you have to return one of these!
  62499. return alertBox->runModalLoop();
  62500. }
  62501. static void* showCallback (void* userData)
  62502. {
  62503. return (void*) (pointer_sized_int) ((const AlertWindowInfo*) userData)->show();
  62504. }
  62505. };
  62506. void AlertWindow::showMessageBox (AlertIconType iconType,
  62507. const String& title,
  62508. const String& message,
  62509. const String& buttonText,
  62510. Component* associatedComponent)
  62511. {
  62512. AlertWindowInfo info;
  62513. info.title = title;
  62514. info.message = message;
  62515. info.button1 = buttonText.isEmpty() ? TRANS("ok") : buttonText;
  62516. info.iconType = iconType;
  62517. info.numButtons = 1;
  62518. info.associatedComponent = associatedComponent;
  62519. info.run();
  62520. }
  62521. bool AlertWindow::showOkCancelBox (AlertIconType iconType,
  62522. const String& title,
  62523. const String& message,
  62524. const String& button1Text,
  62525. const String& button2Text,
  62526. Component* associatedComponent)
  62527. {
  62528. AlertWindowInfo info;
  62529. info.title = title;
  62530. info.message = message;
  62531. info.button1 = button1Text.isEmpty() ? TRANS("ok") : button1Text;
  62532. info.button2 = button2Text.isEmpty() ? TRANS("cancel") : button2Text;
  62533. info.iconType = iconType;
  62534. info.numButtons = 2;
  62535. info.associatedComponent = associatedComponent;
  62536. return info.run() != 0;
  62537. }
  62538. int AlertWindow::showYesNoCancelBox (AlertIconType iconType,
  62539. const String& title,
  62540. const String& message,
  62541. const String& button1Text,
  62542. const String& button2Text,
  62543. const String& button3Text,
  62544. Component* associatedComponent)
  62545. {
  62546. AlertWindowInfo info;
  62547. info.title = title;
  62548. info.message = message;
  62549. info.button1 = button1Text.isEmpty() ? TRANS("yes") : button1Text;
  62550. info.button2 = button2Text.isEmpty() ? TRANS("no") : button2Text;
  62551. info.button3 = button3Text.isEmpty() ? TRANS("cancel") : button3Text;
  62552. info.iconType = iconType;
  62553. info.numButtons = 3;
  62554. info.associatedComponent = associatedComponent;
  62555. return info.run();
  62556. }
  62557. END_JUCE_NAMESPACE
  62558. /*** End of inlined file: juce_AlertWindow.cpp ***/
  62559. /*** Start of inlined file: juce_CallOutBox.cpp ***/
  62560. BEGIN_JUCE_NAMESPACE
  62561. CallOutBox::CallOutBox (Component& contentComponent,
  62562. Component& componentToPointTo,
  62563. Component* const parentComponent)
  62564. : borderSpace (20), arrowSize (16.0f), content (contentComponent)
  62565. {
  62566. addAndMakeVisible (&content);
  62567. if (parentComponent != 0)
  62568. {
  62569. parentComponent->addChildComponent (this);
  62570. updatePosition (componentToPointTo.getLocalBounds()
  62571. + componentToPointTo.relativePositionToOtherComponent (parentComponent, Point<int>()),
  62572. parentComponent->getLocalBounds());
  62573. setVisible (true);
  62574. }
  62575. else
  62576. {
  62577. if (! JUCEApplication::isStandaloneApp())
  62578. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  62579. updatePosition (componentToPointTo.getScreenBounds(),
  62580. componentToPointTo.getParentMonitorArea());
  62581. addToDesktop (ComponentPeer::windowIsTemporary);
  62582. }
  62583. }
  62584. CallOutBox::~CallOutBox()
  62585. {
  62586. }
  62587. void CallOutBox::setArrowSize (const float newSize)
  62588. {
  62589. arrowSize = newSize;
  62590. borderSpace = jmax (20, (int) arrowSize);
  62591. refreshPath();
  62592. }
  62593. void CallOutBox::paint (Graphics& g)
  62594. {
  62595. if (background.isNull())
  62596. {
  62597. background = Image (Image::ARGB, getWidth(), getHeight(), true);
  62598. Graphics g (background);
  62599. getLookAndFeel().drawCallOutBoxBackground (*this, g, outline);
  62600. }
  62601. g.setColour (Colours::black);
  62602. g.drawImageAt (background, 0, 0);
  62603. }
  62604. void CallOutBox::resized()
  62605. {
  62606. content.setTopLeftPosition (borderSpace, borderSpace);
  62607. refreshPath();
  62608. }
  62609. void CallOutBox::moved()
  62610. {
  62611. refreshPath();
  62612. }
  62613. void CallOutBox::childBoundsChanged (Component*)
  62614. {
  62615. updatePosition (targetArea, availableArea);
  62616. }
  62617. bool CallOutBox::hitTest (int x, int y)
  62618. {
  62619. return outline.contains ((float) x, (float) y);
  62620. }
  62621. enum { callOutBoxDismissCommandId = 0x4f83a04b };
  62622. void CallOutBox::inputAttemptWhenModal()
  62623. {
  62624. const Point<int> mousePos (getMouseXYRelative() + getBounds().getPosition());
  62625. if (targetArea.contains (mousePos))
  62626. {
  62627. // if you click on the area that originally popped-up the callout, you expect it
  62628. // to get rid of the box, but deleting the box here allows the click to pass through and
  62629. // probably re-trigger it, so we need to dismiss the box asynchronously to consume the click..
  62630. postCommandMessage (callOutBoxDismissCommandId);
  62631. }
  62632. else
  62633. {
  62634. exitModalState (0);
  62635. setVisible (false);
  62636. }
  62637. }
  62638. void CallOutBox::handleCommandMessage (int commandId)
  62639. {
  62640. Component::handleCommandMessage (commandId);
  62641. if (commandId == callOutBoxDismissCommandId)
  62642. {
  62643. exitModalState (0);
  62644. setVisible (false);
  62645. }
  62646. }
  62647. bool CallOutBox::keyPressed (const KeyPress& key)
  62648. {
  62649. if (key.isKeyCode (KeyPress::escapeKey))
  62650. {
  62651. inputAttemptWhenModal();
  62652. return true;
  62653. }
  62654. return false;
  62655. }
  62656. void CallOutBox::updatePosition (const Rectangle<int>& newAreaToPointTo, const Rectangle<int>& newAreaToFitIn)
  62657. {
  62658. targetArea = newAreaToPointTo;
  62659. availableArea = newAreaToFitIn;
  62660. Rectangle<int> bounds (0, 0,
  62661. content.getWidth() + borderSpace * 2,
  62662. content.getHeight() + borderSpace * 2);
  62663. const int hw = bounds.getWidth() / 2;
  62664. const int hh = bounds.getHeight() / 2;
  62665. const float hwReduced = (float) (hw - borderSpace * 3);
  62666. const float hhReduced = (float) (hh - borderSpace * 3);
  62667. const float arrowIndent = borderSpace - arrowSize;
  62668. Point<float> targets[4] = { Point<float> ((float) targetArea.getCentreX(), (float) targetArea.getBottom()),
  62669. Point<float> ((float) targetArea.getRight(), (float) targetArea.getCentreY()),
  62670. Point<float> ((float) targetArea.getX(), (float) targetArea.getCentreY()),
  62671. Point<float> ((float) targetArea.getCentreX(), (float) targetArea.getY()) };
  62672. Line<float> lines[4] = { Line<float> (targets[0].translated (-hwReduced, hh - arrowIndent), targets[0].translated (hwReduced, hh - arrowIndent)),
  62673. Line<float> (targets[1].translated (hw - arrowIndent, -hhReduced), targets[1].translated (hw - arrowIndent, hhReduced)),
  62674. Line<float> (targets[2].translated (-(hw - arrowIndent), -hhReduced), targets[2].translated (-(hw - arrowIndent), hhReduced)),
  62675. Line<float> (targets[3].translated (-hwReduced, -(hh - arrowIndent)), targets[3].translated (hwReduced, -(hh - arrowIndent))) };
  62676. const Rectangle<float> centrePointArea (newAreaToFitIn.reduced (hw, hh).toFloat());
  62677. float nearest = 1.0e9f;
  62678. for (int i = 0; i < 4; ++i)
  62679. {
  62680. Line<float> constrainedLine (centrePointArea.getConstrainedPoint (lines[i].getStart()),
  62681. centrePointArea.getConstrainedPoint (lines[i].getEnd()));
  62682. const Point<float> centre (constrainedLine.findNearestPointTo (centrePointArea.getCentre()));
  62683. float distanceFromCentre = centre.getDistanceFrom (centrePointArea.getCentre());
  62684. if (! (centrePointArea.contains (lines[i].getStart()) || centrePointArea.contains (lines[i].getEnd())))
  62685. distanceFromCentre *= 2.0f;
  62686. if (distanceFromCentre < nearest)
  62687. {
  62688. nearest = distanceFromCentre;
  62689. targetPoint = targets[i];
  62690. bounds.setPosition ((int) (centre.getX() - hw),
  62691. (int) (centre.getY() - hh));
  62692. }
  62693. }
  62694. setBounds (bounds);
  62695. }
  62696. void CallOutBox::refreshPath()
  62697. {
  62698. repaint();
  62699. background = Image::null;
  62700. outline.clear();
  62701. const float gap = 4.5f;
  62702. const float cornerSize = 9.0f;
  62703. const float cornerSize2 = 2.0f * cornerSize;
  62704. const float arrowBaseWidth = arrowSize * 0.7f;
  62705. const float left = content.getX() - gap, top = content.getY() - gap, right = content.getRight() + gap, bottom = content.getBottom() + gap;
  62706. const float targetX = targetPoint.getX() - getX(), targetY = targetPoint.getY() - getY();
  62707. outline.startNewSubPath (left + cornerSize, top);
  62708. if (targetY <= top)
  62709. {
  62710. outline.lineTo (targetX - arrowBaseWidth, top);
  62711. outline.lineTo (targetX, targetY);
  62712. outline.lineTo (targetX + arrowBaseWidth, top);
  62713. }
  62714. outline.lineTo (right - cornerSize, top);
  62715. outline.addArc (right - cornerSize2, top, cornerSize2, cornerSize2, 0, float_Pi * 0.5f);
  62716. if (targetX >= right)
  62717. {
  62718. outline.lineTo (right, targetY - arrowBaseWidth);
  62719. outline.lineTo (targetX, targetY);
  62720. outline.lineTo (right, targetY + arrowBaseWidth);
  62721. }
  62722. outline.lineTo (right, bottom - cornerSize);
  62723. outline.addArc (right - cornerSize2, bottom - cornerSize2, cornerSize2, cornerSize2, float_Pi * 0.5f, float_Pi);
  62724. if (targetY >= bottom)
  62725. {
  62726. outline.lineTo (targetX + arrowBaseWidth, bottom);
  62727. outline.lineTo (targetX, targetY);
  62728. outline.lineTo (targetX - arrowBaseWidth, bottom);
  62729. }
  62730. outline.lineTo (left + cornerSize, bottom);
  62731. outline.addArc (left, bottom - cornerSize2, cornerSize2, cornerSize2, float_Pi, float_Pi * 1.5f);
  62732. if (targetX <= left)
  62733. {
  62734. outline.lineTo (left, targetY + arrowBaseWidth);
  62735. outline.lineTo (targetX, targetY);
  62736. outline.lineTo (left, targetY - arrowBaseWidth);
  62737. }
  62738. outline.lineTo (left, top + cornerSize);
  62739. outline.addArc (left, top, cornerSize2, cornerSize2, float_Pi * 1.5f, float_Pi * 2.0f - 0.05f);
  62740. outline.closeSubPath();
  62741. }
  62742. END_JUCE_NAMESPACE
  62743. /*** End of inlined file: juce_CallOutBox.cpp ***/
  62744. /*** Start of inlined file: juce_ComponentPeer.cpp ***/
  62745. BEGIN_JUCE_NAMESPACE
  62746. //#define JUCE_ENABLE_REPAINT_DEBUGGING 1
  62747. static Array <ComponentPeer*> heavyweightPeers;
  62748. ComponentPeer::ComponentPeer (Component* const component_, const int styleFlags_)
  62749. : component (component_),
  62750. styleFlags (styleFlags_),
  62751. lastPaintTime (0),
  62752. constrainer (0),
  62753. lastDragAndDropCompUnderMouse (0),
  62754. fakeMouseMessageSent (false),
  62755. isWindowMinimised (false)
  62756. {
  62757. heavyweightPeers.add (this);
  62758. }
  62759. ComponentPeer::~ComponentPeer()
  62760. {
  62761. heavyweightPeers.removeValue (this);
  62762. Desktop::getInstance().triggerFocusCallback();
  62763. }
  62764. int ComponentPeer::getNumPeers() throw()
  62765. {
  62766. return heavyweightPeers.size();
  62767. }
  62768. ComponentPeer* ComponentPeer::getPeer (const int index) throw()
  62769. {
  62770. return heavyweightPeers [index];
  62771. }
  62772. ComponentPeer* ComponentPeer::getPeerFor (const Component* const component) throw()
  62773. {
  62774. for (int i = heavyweightPeers.size(); --i >= 0;)
  62775. {
  62776. ComponentPeer* const peer = heavyweightPeers.getUnchecked(i);
  62777. if (peer->getComponent() == component)
  62778. return peer;
  62779. }
  62780. return 0;
  62781. }
  62782. bool ComponentPeer::isValidPeer (const ComponentPeer* const peer) throw()
  62783. {
  62784. return heavyweightPeers.contains (const_cast <ComponentPeer*> (peer));
  62785. }
  62786. void ComponentPeer::updateCurrentModifiers() throw()
  62787. {
  62788. ModifierKeys::updateCurrentModifiers();
  62789. }
  62790. void ComponentPeer::handleMouseEvent (const int touchIndex, const Point<int>& positionWithinPeer, const ModifierKeys& newMods, const int64 time)
  62791. {
  62792. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  62793. jassert (mouse != 0); // not enough sources!
  62794. mouse->handleEvent (this, positionWithinPeer, time, newMods);
  62795. }
  62796. void ComponentPeer::handleMouseWheel (const int touchIndex, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  62797. {
  62798. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  62799. jassert (mouse != 0); // not enough sources!
  62800. mouse->handleWheel (this, positionWithinPeer, time, x, y);
  62801. }
  62802. void ComponentPeer::handlePaint (LowLevelGraphicsContext& contextToPaintTo)
  62803. {
  62804. Graphics g (&contextToPaintTo);
  62805. #if JUCE_ENABLE_REPAINT_DEBUGGING
  62806. g.saveState();
  62807. #endif
  62808. JUCE_TRY
  62809. {
  62810. component->paintEntireComponent (g);
  62811. }
  62812. JUCE_CATCH_EXCEPTION
  62813. #if JUCE_ENABLE_REPAINT_DEBUGGING
  62814. // enabling this code will fill all areas that get repainted with a colour overlay, to show
  62815. // clearly when things are being repainted.
  62816. {
  62817. g.restoreState();
  62818. g.fillAll (Colour ((uint8) Random::getSystemRandom().nextInt (255),
  62819. (uint8) Random::getSystemRandom().nextInt (255),
  62820. (uint8) Random::getSystemRandom().nextInt (255),
  62821. (uint8) 0x50));
  62822. }
  62823. #endif
  62824. /** If this fails, it's probably be because your CPU floating-point precision mode has
  62825. been set to low.. This setting is sometimes changed by things like Direct3D, and can
  62826. mess up a lot of the calculations that the library needs to do.
  62827. */
  62828. jassert (roundToInt (10.1f) == 10);
  62829. }
  62830. bool ComponentPeer::handleKeyPress (const int keyCode,
  62831. const juce_wchar textCharacter)
  62832. {
  62833. updateCurrentModifiers();
  62834. Component* target = Component::getCurrentlyFocusedComponent() != 0
  62835. ? Component::getCurrentlyFocusedComponent()
  62836. : component;
  62837. if (target->isCurrentlyBlockedByAnotherModalComponent())
  62838. {
  62839. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  62840. if (currentModalComp != 0)
  62841. target = currentModalComp;
  62842. }
  62843. const KeyPress keyInfo (keyCode,
  62844. ModifierKeys::getCurrentModifiers().getRawFlags()
  62845. & ModifierKeys::allKeyboardModifiers,
  62846. textCharacter);
  62847. bool keyWasUsed = false;
  62848. while (target != 0)
  62849. {
  62850. const Component::SafePointer<Component> deletionChecker (target);
  62851. if (target->keyListeners_ != 0)
  62852. {
  62853. for (int i = target->keyListeners_->size(); --i >= 0;)
  62854. {
  62855. keyWasUsed = target->keyListeners_->getUnchecked(i)->keyPressed (keyInfo, target);
  62856. if (keyWasUsed || deletionChecker == 0)
  62857. return keyWasUsed;
  62858. i = jmin (i, target->keyListeners_->size());
  62859. }
  62860. }
  62861. keyWasUsed = target->keyPressed (keyInfo);
  62862. if (keyWasUsed || deletionChecker == 0)
  62863. break;
  62864. if (keyInfo.isKeyCode (KeyPress::tabKey) && Component::getCurrentlyFocusedComponent() != 0)
  62865. {
  62866. Component* const currentlyFocused = Component::getCurrentlyFocusedComponent();
  62867. currentlyFocused->moveKeyboardFocusToSibling (! keyInfo.getModifiers().isShiftDown());
  62868. keyWasUsed = (currentlyFocused != Component::getCurrentlyFocusedComponent());
  62869. break;
  62870. }
  62871. target = target->parentComponent_;
  62872. }
  62873. return keyWasUsed;
  62874. }
  62875. bool ComponentPeer::handleKeyUpOrDown (const bool isKeyDown)
  62876. {
  62877. updateCurrentModifiers();
  62878. Component* target = Component::getCurrentlyFocusedComponent() != 0
  62879. ? Component::getCurrentlyFocusedComponent()
  62880. : component;
  62881. if (target->isCurrentlyBlockedByAnotherModalComponent())
  62882. {
  62883. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  62884. if (currentModalComp != 0)
  62885. target = currentModalComp;
  62886. }
  62887. bool keyWasUsed = false;
  62888. while (target != 0)
  62889. {
  62890. const Component::SafePointer<Component> deletionChecker (target);
  62891. keyWasUsed = target->keyStateChanged (isKeyDown);
  62892. if (keyWasUsed || deletionChecker == 0)
  62893. break;
  62894. if (target->keyListeners_ != 0)
  62895. {
  62896. for (int i = target->keyListeners_->size(); --i >= 0;)
  62897. {
  62898. keyWasUsed = target->keyListeners_->getUnchecked(i)->keyStateChanged (isKeyDown, target);
  62899. if (keyWasUsed || deletionChecker == 0)
  62900. return keyWasUsed;
  62901. i = jmin (i, target->keyListeners_->size());
  62902. }
  62903. }
  62904. target = target->parentComponent_;
  62905. }
  62906. return keyWasUsed;
  62907. }
  62908. void ComponentPeer::handleModifierKeysChange()
  62909. {
  62910. updateCurrentModifiers();
  62911. Component* target = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  62912. if (target == 0)
  62913. target = Component::getCurrentlyFocusedComponent();
  62914. if (target == 0)
  62915. target = component;
  62916. if (target != 0)
  62917. target->internalModifierKeysChanged();
  62918. }
  62919. TextInputTarget* ComponentPeer::findCurrentTextInputTarget()
  62920. {
  62921. Component* const c = Component::getCurrentlyFocusedComponent();
  62922. if (component->isParentOf (c))
  62923. {
  62924. TextInputTarget* const ti = dynamic_cast <TextInputTarget*> (c);
  62925. if (ti != 0 && ti->isTextInputActive())
  62926. return ti;
  62927. }
  62928. return 0;
  62929. }
  62930. void ComponentPeer::handleBroughtToFront()
  62931. {
  62932. updateCurrentModifiers();
  62933. if (component != 0)
  62934. component->internalBroughtToFront();
  62935. }
  62936. void ComponentPeer::setConstrainer (ComponentBoundsConstrainer* const newConstrainer) throw()
  62937. {
  62938. constrainer = newConstrainer;
  62939. }
  62940. void ComponentPeer::handleMovedOrResized()
  62941. {
  62942. jassert (component->isValidComponent());
  62943. updateCurrentModifiers();
  62944. const bool nowMinimised = isMinimised();
  62945. if (component->flags.hasHeavyweightPeerFlag && ! nowMinimised)
  62946. {
  62947. const Component::SafePointer<Component> deletionChecker (component);
  62948. const Rectangle<int> newBounds (getBounds());
  62949. const bool wasMoved = (component->getPosition() != newBounds.getPosition());
  62950. const bool wasResized = (component->getWidth() != newBounds.getWidth() || component->getHeight() != newBounds.getHeight());
  62951. if (wasMoved || wasResized)
  62952. {
  62953. component->bounds_ = newBounds;
  62954. if (wasResized)
  62955. component->repaint();
  62956. component->sendMovedResizedMessages (wasMoved, wasResized);
  62957. if (deletionChecker == 0)
  62958. return;
  62959. }
  62960. }
  62961. if (isWindowMinimised != nowMinimised)
  62962. {
  62963. isWindowMinimised = nowMinimised;
  62964. component->minimisationStateChanged (nowMinimised);
  62965. component->sendVisibilityChangeMessage();
  62966. }
  62967. if (! isFullScreen())
  62968. lastNonFullscreenBounds = component->getBounds();
  62969. }
  62970. void ComponentPeer::handleFocusGain()
  62971. {
  62972. updateCurrentModifiers();
  62973. if (component->isParentOf (lastFocusedComponent))
  62974. {
  62975. Component::currentlyFocusedComponent = lastFocusedComponent;
  62976. Desktop::getInstance().triggerFocusCallback();
  62977. lastFocusedComponent->internalFocusGain (Component::focusChangedDirectly);
  62978. }
  62979. else
  62980. {
  62981. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  62982. component->grabKeyboardFocus();
  62983. else
  62984. Component::bringModalComponentToFront();
  62985. }
  62986. }
  62987. void ComponentPeer::handleFocusLoss()
  62988. {
  62989. updateCurrentModifiers();
  62990. if (component->hasKeyboardFocus (true))
  62991. {
  62992. lastFocusedComponent = Component::currentlyFocusedComponent;
  62993. if (lastFocusedComponent != 0)
  62994. {
  62995. Component::currentlyFocusedComponent = 0;
  62996. Desktop::getInstance().triggerFocusCallback();
  62997. lastFocusedComponent->internalFocusLoss (Component::focusChangedByMouseClick);
  62998. }
  62999. }
  63000. }
  63001. Component* ComponentPeer::getLastFocusedSubcomponent() const throw()
  63002. {
  63003. return (component->isParentOf (lastFocusedComponent) && lastFocusedComponent->isShowing())
  63004. ? static_cast <Component*> (lastFocusedComponent)
  63005. : component;
  63006. }
  63007. void ComponentPeer::handleScreenSizeChange()
  63008. {
  63009. updateCurrentModifiers();
  63010. component->parentSizeChanged();
  63011. handleMovedOrResized();
  63012. }
  63013. void ComponentPeer::setNonFullScreenBounds (const Rectangle<int>& newBounds) throw()
  63014. {
  63015. lastNonFullscreenBounds = newBounds;
  63016. }
  63017. const Rectangle<int>& ComponentPeer::getNonFullScreenBounds() const throw()
  63018. {
  63019. return lastNonFullscreenBounds;
  63020. }
  63021. static FileDragAndDropTarget* findDragAndDropTarget (Component* c,
  63022. const StringArray& files,
  63023. FileDragAndDropTarget* const lastOne)
  63024. {
  63025. while (c != 0)
  63026. {
  63027. FileDragAndDropTarget* const t = dynamic_cast <FileDragAndDropTarget*> (c);
  63028. if (t != 0 && (t == lastOne || t->isInterestedInFileDrag (files)))
  63029. return t;
  63030. c = c->getParentComponent();
  63031. }
  63032. return 0;
  63033. }
  63034. void ComponentPeer::handleFileDragMove (const StringArray& files, const Point<int>& position)
  63035. {
  63036. updateCurrentModifiers();
  63037. FileDragAndDropTarget* lastTarget
  63038. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  63039. FileDragAndDropTarget* newTarget = 0;
  63040. Component* const compUnderMouse = component->getComponentAt (position);
  63041. if (compUnderMouse != lastDragAndDropCompUnderMouse)
  63042. {
  63043. lastDragAndDropCompUnderMouse = compUnderMouse;
  63044. newTarget = findDragAndDropTarget (compUnderMouse, files, lastTarget);
  63045. if (newTarget != lastTarget)
  63046. {
  63047. if (lastTarget != 0)
  63048. lastTarget->fileDragExit (files);
  63049. dragAndDropTargetComponent = 0;
  63050. if (newTarget != 0)
  63051. {
  63052. dragAndDropTargetComponent = dynamic_cast <Component*> (newTarget);
  63053. const Point<int> pos (component->relativePositionToOtherComponent (dragAndDropTargetComponent, position));
  63054. newTarget->fileDragEnter (files, pos.getX(), pos.getY());
  63055. }
  63056. }
  63057. }
  63058. else
  63059. {
  63060. newTarget = lastTarget;
  63061. }
  63062. if (newTarget != 0)
  63063. {
  63064. Component* const targetComp = dynamic_cast <Component*> (newTarget);
  63065. const Point<int> pos (component->relativePositionToOtherComponent (targetComp, position));
  63066. newTarget->fileDragMove (files, pos.getX(), pos.getY());
  63067. }
  63068. }
  63069. void ComponentPeer::handleFileDragExit (const StringArray& files)
  63070. {
  63071. handleFileDragMove (files, Point<int> (-1, -1));
  63072. jassert (dragAndDropTargetComponent == 0);
  63073. lastDragAndDropCompUnderMouse = 0;
  63074. }
  63075. void ComponentPeer::handleFileDragDrop (const StringArray& files, const Point<int>& position)
  63076. {
  63077. handleFileDragMove (files, position);
  63078. if (dragAndDropTargetComponent != 0)
  63079. {
  63080. FileDragAndDropTarget* const target
  63081. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  63082. dragAndDropTargetComponent = 0;
  63083. lastDragAndDropCompUnderMouse = 0;
  63084. if (target != 0)
  63085. {
  63086. Component* const targetComp = dynamic_cast <Component*> (target);
  63087. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  63088. {
  63089. targetComp->internalModalInputAttempt();
  63090. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  63091. return;
  63092. }
  63093. const Point<int> pos (component->relativePositionToOtherComponent (targetComp, position));
  63094. target->filesDropped (files, pos.getX(), pos.getY());
  63095. }
  63096. }
  63097. }
  63098. void ComponentPeer::handleUserClosingWindow()
  63099. {
  63100. updateCurrentModifiers();
  63101. component->userTriedToCloseWindow();
  63102. }
  63103. void ComponentPeer::bringModalComponentToFront()
  63104. {
  63105. Component::bringModalComponentToFront();
  63106. }
  63107. void ComponentPeer::clearMaskedRegion()
  63108. {
  63109. maskedRegion.clear();
  63110. }
  63111. void ComponentPeer::addMaskedRegion (int x, int y, int w, int h)
  63112. {
  63113. maskedRegion.add (x, y, w, h);
  63114. }
  63115. const StringArray ComponentPeer::getAvailableRenderingEngines()
  63116. {
  63117. StringArray s;
  63118. s.add ("Software Renderer");
  63119. return s;
  63120. }
  63121. int ComponentPeer::getCurrentRenderingEngine() throw()
  63122. {
  63123. return 0;
  63124. }
  63125. void ComponentPeer::setCurrentRenderingEngine (int /*index*/)
  63126. {
  63127. }
  63128. END_JUCE_NAMESPACE
  63129. /*** End of inlined file: juce_ComponentPeer.cpp ***/
  63130. /*** Start of inlined file: juce_DialogWindow.cpp ***/
  63131. BEGIN_JUCE_NAMESPACE
  63132. DialogWindow::DialogWindow (const String& name,
  63133. const Colour& backgroundColour_,
  63134. const bool escapeKeyTriggersCloseButton_,
  63135. const bool addToDesktop_)
  63136. : DocumentWindow (name, backgroundColour_, DocumentWindow::closeButton, addToDesktop_),
  63137. escapeKeyTriggersCloseButton (escapeKeyTriggersCloseButton_)
  63138. {
  63139. }
  63140. DialogWindow::~DialogWindow()
  63141. {
  63142. }
  63143. void DialogWindow::resized()
  63144. {
  63145. DocumentWindow::resized();
  63146. const KeyPress esc (KeyPress::escapeKey, 0, 0);
  63147. if (escapeKeyTriggersCloseButton
  63148. && getCloseButton() != 0
  63149. && ! getCloseButton()->isRegisteredForShortcut (esc))
  63150. {
  63151. getCloseButton()->addShortcut (esc);
  63152. }
  63153. }
  63154. class TempDialogWindow : public DialogWindow
  63155. {
  63156. public:
  63157. TempDialogWindow (const String& title, const Colour& colour, const bool escapeCloses)
  63158. : DialogWindow (title, colour, escapeCloses, true)
  63159. {
  63160. if (! JUCEApplication::isStandaloneApp())
  63161. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  63162. }
  63163. ~TempDialogWindow()
  63164. {
  63165. }
  63166. void closeButtonPressed()
  63167. {
  63168. setVisible (false);
  63169. }
  63170. private:
  63171. TempDialogWindow (const TempDialogWindow&);
  63172. TempDialogWindow& operator= (const TempDialogWindow&);
  63173. };
  63174. int DialogWindow::showModalDialog (const String& dialogTitle,
  63175. Component* contentComponent,
  63176. Component* componentToCentreAround,
  63177. const Colour& colour,
  63178. const bool escapeKeyTriggersCloseButton,
  63179. const bool shouldBeResizable,
  63180. const bool useBottomRightCornerResizer)
  63181. {
  63182. TempDialogWindow dw (dialogTitle, colour, escapeKeyTriggersCloseButton);
  63183. dw.setContentComponent (contentComponent, true, true);
  63184. dw.centreAroundComponent (componentToCentreAround, dw.getWidth(), dw.getHeight());
  63185. dw.setResizable (shouldBeResizable, useBottomRightCornerResizer);
  63186. const int result = dw.runModalLoop();
  63187. dw.setContentComponent (0, false);
  63188. return result;
  63189. }
  63190. END_JUCE_NAMESPACE
  63191. /*** End of inlined file: juce_DialogWindow.cpp ***/
  63192. /*** Start of inlined file: juce_DocumentWindow.cpp ***/
  63193. BEGIN_JUCE_NAMESPACE
  63194. class DocumentWindow::ButtonListenerProxy : public ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  63195. {
  63196. public:
  63197. ButtonListenerProxy (DocumentWindow& owner_)
  63198. : owner (owner_)
  63199. {
  63200. }
  63201. void buttonClicked (Button* button)
  63202. {
  63203. if (button == owner.getMinimiseButton())
  63204. owner.minimiseButtonPressed();
  63205. else if (button == owner.getMaximiseButton())
  63206. owner.maximiseButtonPressed();
  63207. else if (button == owner.getCloseButton())
  63208. owner.closeButtonPressed();
  63209. }
  63210. juce_UseDebuggingNewOperator
  63211. private:
  63212. DocumentWindow& owner;
  63213. ButtonListenerProxy (const ButtonListenerProxy&);
  63214. ButtonListenerProxy& operator= (const ButtonListenerProxy&);
  63215. };
  63216. DocumentWindow::DocumentWindow (const String& title,
  63217. const Colour& backgroundColour,
  63218. const int requiredButtons_,
  63219. const bool addToDesktop_)
  63220. : ResizableWindow (title, backgroundColour, addToDesktop_),
  63221. titleBarHeight (26),
  63222. menuBarHeight (24),
  63223. requiredButtons (requiredButtons_),
  63224. #if JUCE_MAC
  63225. positionTitleBarButtonsOnLeft (true),
  63226. #else
  63227. positionTitleBarButtonsOnLeft (false),
  63228. #endif
  63229. drawTitleTextCentred (true),
  63230. menuBarModel (0)
  63231. {
  63232. setResizeLimits (128, 128, 32768, 32768);
  63233. lookAndFeelChanged();
  63234. }
  63235. DocumentWindow::~DocumentWindow()
  63236. {
  63237. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  63238. titleBarButtons[i] = 0;
  63239. menuBar = 0;
  63240. }
  63241. void DocumentWindow::repaintTitleBar()
  63242. {
  63243. repaint (getTitleBarArea());
  63244. }
  63245. void DocumentWindow::setName (const String& newName)
  63246. {
  63247. if (newName != getName())
  63248. {
  63249. Component::setName (newName);
  63250. repaintTitleBar();
  63251. }
  63252. }
  63253. void DocumentWindow::setIcon (const Image& imageToUse)
  63254. {
  63255. titleBarIcon = imageToUse;
  63256. repaintTitleBar();
  63257. }
  63258. void DocumentWindow::setTitleBarHeight (const int newHeight)
  63259. {
  63260. titleBarHeight = newHeight;
  63261. resized();
  63262. repaintTitleBar();
  63263. }
  63264. void DocumentWindow::setTitleBarButtonsRequired (const int requiredButtons_,
  63265. const bool positionTitleBarButtonsOnLeft_)
  63266. {
  63267. requiredButtons = requiredButtons_;
  63268. positionTitleBarButtonsOnLeft = positionTitleBarButtonsOnLeft_;
  63269. lookAndFeelChanged();
  63270. }
  63271. void DocumentWindow::setTitleBarTextCentred (const bool textShouldBeCentred)
  63272. {
  63273. drawTitleTextCentred = textShouldBeCentred;
  63274. repaintTitleBar();
  63275. }
  63276. void DocumentWindow::setMenuBar (MenuBarModel* menuBarModel_,
  63277. const int menuBarHeight_)
  63278. {
  63279. if (menuBarModel != menuBarModel_)
  63280. {
  63281. menuBar = 0;
  63282. menuBarModel = menuBarModel_;
  63283. menuBarHeight = (menuBarHeight_ > 0) ? menuBarHeight_
  63284. : getLookAndFeel().getDefaultMenuBarHeight();
  63285. if (menuBarModel != 0)
  63286. {
  63287. // (call the Component method directly to avoid the assertion in ResizableWindow)
  63288. Component::addAndMakeVisible (menuBar = new MenuBarComponent (menuBarModel));
  63289. menuBar->setEnabled (isActiveWindow());
  63290. }
  63291. resized();
  63292. }
  63293. }
  63294. void DocumentWindow::closeButtonPressed()
  63295. {
  63296. /* If you've got a close button, you have to override this method to get
  63297. rid of your window!
  63298. If the window is just a pop-up, you should override this method and make
  63299. it delete the window in whatever way is appropriate for your app. E.g. you
  63300. might just want to call "delete this".
  63301. If your app is centred around this window such that the whole app should quit when
  63302. the window is closed, then you will probably want to use this method as an opportunity
  63303. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  63304. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  63305. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  63306. or closing it via the taskbar icon on Windows).
  63307. */
  63308. jassertfalse;
  63309. }
  63310. void DocumentWindow::minimiseButtonPressed()
  63311. {
  63312. setMinimised (true);
  63313. }
  63314. void DocumentWindow::maximiseButtonPressed()
  63315. {
  63316. setFullScreen (! isFullScreen());
  63317. }
  63318. void DocumentWindow::paint (Graphics& g)
  63319. {
  63320. ResizableWindow::paint (g);
  63321. if (resizableBorder == 0)
  63322. {
  63323. g.setColour (getBackgroundColour().overlaidWith (Colour (0x80000000)));
  63324. const BorderSize border (getBorderThickness());
  63325. g.fillRect (0, 0, getWidth(), border.getTop());
  63326. g.fillRect (0, border.getTop(), border.getLeft(), getHeight() - border.getTopAndBottom());
  63327. g.fillRect (getWidth() - border.getRight(), border.getTop(), border.getRight(), getHeight() - border.getTopAndBottom());
  63328. g.fillRect (0, getHeight() - border.getBottom(), getWidth(), border.getBottom());
  63329. }
  63330. const Rectangle<int> titleBarArea (getTitleBarArea());
  63331. g.setOrigin (titleBarArea.getX(), titleBarArea.getY());
  63332. g.reduceClipRegion (0, 0, titleBarArea.getWidth(), titleBarArea.getHeight());
  63333. int titleSpaceX1 = 6;
  63334. int titleSpaceX2 = titleBarArea.getWidth() - 6;
  63335. for (int i = 0; i < 3; ++i)
  63336. {
  63337. if (titleBarButtons[i] != 0)
  63338. {
  63339. if (positionTitleBarButtonsOnLeft)
  63340. titleSpaceX1 = jmax (titleSpaceX1, titleBarButtons[i]->getRight() + (getWidth() - titleBarButtons[i]->getRight()) / 8);
  63341. else
  63342. titleSpaceX2 = jmin (titleSpaceX2, titleBarButtons[i]->getX() - (titleBarButtons[i]->getX() / 8));
  63343. }
  63344. }
  63345. getLookAndFeel().drawDocumentWindowTitleBar (*this, g,
  63346. titleBarArea.getWidth(),
  63347. titleBarArea.getHeight(),
  63348. titleSpaceX1,
  63349. jmax (1, titleSpaceX2 - titleSpaceX1),
  63350. titleBarIcon.isValid() ? &titleBarIcon : 0,
  63351. ! drawTitleTextCentred);
  63352. }
  63353. void DocumentWindow::resized()
  63354. {
  63355. ResizableWindow::resized();
  63356. if (titleBarButtons[1] != 0)
  63357. titleBarButtons[1]->setToggleState (isFullScreen(), false);
  63358. const Rectangle<int> titleBarArea (getTitleBarArea());
  63359. getLookAndFeel()
  63360. .positionDocumentWindowButtons (*this,
  63361. titleBarArea.getX(), titleBarArea.getY(),
  63362. titleBarArea.getWidth(), titleBarArea.getHeight(),
  63363. titleBarButtons[0],
  63364. titleBarButtons[1],
  63365. titleBarButtons[2],
  63366. positionTitleBarButtonsOnLeft);
  63367. if (menuBar != 0)
  63368. menuBar->setBounds (titleBarArea.getX(), titleBarArea.getBottom(),
  63369. titleBarArea.getWidth(), menuBarHeight);
  63370. }
  63371. const BorderSize DocumentWindow::getBorderThickness()
  63372. {
  63373. return BorderSize ((isFullScreen() || isUsingNativeTitleBar())
  63374. ? 0 : (resizableBorder != 0 ? 4 : 1));
  63375. }
  63376. const BorderSize DocumentWindow::getContentComponentBorder()
  63377. {
  63378. BorderSize border (getBorderThickness());
  63379. border.setTop (border.getTop()
  63380. + (isUsingNativeTitleBar() ? 0 : titleBarHeight)
  63381. + (menuBar != 0 ? menuBarHeight : 0));
  63382. return border;
  63383. }
  63384. int DocumentWindow::getTitleBarHeight() const
  63385. {
  63386. return isUsingNativeTitleBar() ? 0 : jmin (titleBarHeight, getHeight() - 4);
  63387. }
  63388. const Rectangle<int> DocumentWindow::getTitleBarArea()
  63389. {
  63390. const BorderSize border (getBorderThickness());
  63391. return Rectangle<int> (border.getLeft(), border.getTop(),
  63392. getWidth() - border.getLeftAndRight(),
  63393. getTitleBarHeight());
  63394. }
  63395. Button* DocumentWindow::getCloseButton() const throw()
  63396. {
  63397. return titleBarButtons[2];
  63398. }
  63399. Button* DocumentWindow::getMinimiseButton() const throw()
  63400. {
  63401. return titleBarButtons[0];
  63402. }
  63403. Button* DocumentWindow::getMaximiseButton() const throw()
  63404. {
  63405. return titleBarButtons[1];
  63406. }
  63407. int DocumentWindow::getDesktopWindowStyleFlags() const
  63408. {
  63409. int styleFlags = ResizableWindow::getDesktopWindowStyleFlags();
  63410. if ((requiredButtons & minimiseButton) != 0)
  63411. styleFlags |= ComponentPeer::windowHasMinimiseButton;
  63412. if ((requiredButtons & maximiseButton) != 0)
  63413. styleFlags |= ComponentPeer::windowHasMaximiseButton;
  63414. if ((requiredButtons & closeButton) != 0)
  63415. styleFlags |= ComponentPeer::windowHasCloseButton;
  63416. return styleFlags;
  63417. }
  63418. void DocumentWindow::lookAndFeelChanged()
  63419. {
  63420. int i;
  63421. for (i = numElementsInArray (titleBarButtons); --i >= 0;)
  63422. titleBarButtons[i] = 0;
  63423. if (! isUsingNativeTitleBar())
  63424. {
  63425. titleBarButtons[0] = ((requiredButtons & minimiseButton) != 0)
  63426. ? getLookAndFeel().createDocumentWindowButton (minimiseButton) : 0;
  63427. titleBarButtons[1] = ((requiredButtons & maximiseButton) != 0)
  63428. ? getLookAndFeel().createDocumentWindowButton (maximiseButton) : 0;
  63429. titleBarButtons[2] = ((requiredButtons & closeButton) != 0)
  63430. ? getLookAndFeel().createDocumentWindowButton (closeButton) : 0;
  63431. for (i = 0; i < 3; ++i)
  63432. {
  63433. if (titleBarButtons[i] != 0)
  63434. {
  63435. if (buttonListener == 0)
  63436. buttonListener = new ButtonListenerProxy (*this);
  63437. titleBarButtons[i]->addButtonListener (buttonListener);
  63438. titleBarButtons[i]->setWantsKeyboardFocus (false);
  63439. // (call the Component method directly to avoid the assertion in ResizableWindow)
  63440. Component::addAndMakeVisible (titleBarButtons[i]);
  63441. }
  63442. }
  63443. if (getCloseButton() != 0)
  63444. {
  63445. #if JUCE_MAC
  63446. getCloseButton()->addShortcut (KeyPress ('w', ModifierKeys::commandModifier, 0));
  63447. #else
  63448. getCloseButton()->addShortcut (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0));
  63449. #endif
  63450. }
  63451. }
  63452. activeWindowStatusChanged();
  63453. ResizableWindow::lookAndFeelChanged();
  63454. }
  63455. void DocumentWindow::parentHierarchyChanged()
  63456. {
  63457. lookAndFeelChanged();
  63458. }
  63459. void DocumentWindow::activeWindowStatusChanged()
  63460. {
  63461. ResizableWindow::activeWindowStatusChanged();
  63462. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  63463. if (titleBarButtons[i] != 0)
  63464. titleBarButtons[i]->setEnabled (isActiveWindow());
  63465. if (menuBar != 0)
  63466. menuBar->setEnabled (isActiveWindow());
  63467. }
  63468. void DocumentWindow::mouseDoubleClick (const MouseEvent& e)
  63469. {
  63470. if (getTitleBarArea().contains (e.x, e.y)
  63471. && getMaximiseButton() != 0)
  63472. {
  63473. getMaximiseButton()->triggerClick();
  63474. }
  63475. }
  63476. void DocumentWindow::userTriedToCloseWindow()
  63477. {
  63478. closeButtonPressed();
  63479. }
  63480. END_JUCE_NAMESPACE
  63481. /*** End of inlined file: juce_DocumentWindow.cpp ***/
  63482. /*** Start of inlined file: juce_ResizableWindow.cpp ***/
  63483. BEGIN_JUCE_NAMESPACE
  63484. ResizableWindow::ResizableWindow (const String& name,
  63485. const bool addToDesktop_)
  63486. : TopLevelWindow (name, addToDesktop_),
  63487. resizeToFitContent (false),
  63488. fullscreen (false),
  63489. lastNonFullScreenPos (50, 50, 256, 256),
  63490. constrainer (0)
  63491. #if JUCE_DEBUG
  63492. , hasBeenResized (false)
  63493. #endif
  63494. {
  63495. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  63496. lastNonFullScreenPos.setBounds (50, 50, 256, 256);
  63497. if (addToDesktop_)
  63498. Component::addToDesktop (getDesktopWindowStyleFlags());
  63499. }
  63500. ResizableWindow::ResizableWindow (const String& name,
  63501. const Colour& backgroundColour_,
  63502. const bool addToDesktop_)
  63503. : TopLevelWindow (name, addToDesktop_),
  63504. resizeToFitContent (false),
  63505. fullscreen (false),
  63506. lastNonFullScreenPos (50, 50, 256, 256),
  63507. constrainer (0)
  63508. #if JUCE_DEBUG
  63509. , hasBeenResized (false)
  63510. #endif
  63511. {
  63512. setBackgroundColour (backgroundColour_);
  63513. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  63514. if (addToDesktop_)
  63515. Component::addToDesktop (getDesktopWindowStyleFlags());
  63516. }
  63517. ResizableWindow::~ResizableWindow()
  63518. {
  63519. resizableCorner = 0;
  63520. resizableBorder = 0;
  63521. contentComponent.deleteAndZero();
  63522. // have you been adding your own components directly to this window..? tut tut tut.
  63523. // Read the instructions for using a ResizableWindow!
  63524. jassert (getNumChildComponents() == 0);
  63525. }
  63526. int ResizableWindow::getDesktopWindowStyleFlags() const
  63527. {
  63528. int styleFlags = TopLevelWindow::getDesktopWindowStyleFlags();
  63529. if (isResizable() && (styleFlags & ComponentPeer::windowHasTitleBar) != 0)
  63530. styleFlags |= ComponentPeer::windowIsResizable;
  63531. return styleFlags;
  63532. }
  63533. void ResizableWindow::setContentComponent (Component* const newContentComponent,
  63534. const bool deleteOldOne,
  63535. const bool resizeToFit)
  63536. {
  63537. resizeToFitContent = resizeToFit;
  63538. if (newContentComponent != static_cast <Component*> (contentComponent))
  63539. {
  63540. if (deleteOldOne)
  63541. contentComponent.deleteAndZero(); // (avoid using a scoped pointer for this, so that it survives
  63542. // external deletion of the content comp)
  63543. else
  63544. removeChildComponent (contentComponent);
  63545. contentComponent = newContentComponent;
  63546. Component::addAndMakeVisible (contentComponent);
  63547. }
  63548. if (resizeToFit)
  63549. childBoundsChanged (contentComponent);
  63550. resized(); // must always be called to position the new content comp
  63551. }
  63552. void ResizableWindow::setContentComponentSize (int width, int height)
  63553. {
  63554. jassert (width > 0 && height > 0); // not a great idea to give it a zero size..
  63555. const BorderSize border (getContentComponentBorder());
  63556. setSize (width + border.getLeftAndRight(),
  63557. height + border.getTopAndBottom());
  63558. }
  63559. const BorderSize ResizableWindow::getBorderThickness()
  63560. {
  63561. return BorderSize (isUsingNativeTitleBar() ? 0 : ((resizableBorder != 0 && ! isFullScreen()) ? 5 : 3));
  63562. }
  63563. const BorderSize ResizableWindow::getContentComponentBorder()
  63564. {
  63565. return getBorderThickness();
  63566. }
  63567. void ResizableWindow::moved()
  63568. {
  63569. updateLastPos();
  63570. }
  63571. void ResizableWindow::visibilityChanged()
  63572. {
  63573. TopLevelWindow::visibilityChanged();
  63574. updateLastPos();
  63575. }
  63576. void ResizableWindow::resized()
  63577. {
  63578. if (resizableBorder != 0)
  63579. {
  63580. #if JUCE_WINDOWS || JUCE_LINUX
  63581. // hide the resizable border if the OS already provides one..
  63582. resizableBorder->setVisible (! (isFullScreen() || isUsingNativeTitleBar()));
  63583. #else
  63584. resizableBorder->setVisible (! isFullScreen());
  63585. #endif
  63586. resizableBorder->setBorderThickness (getBorderThickness());
  63587. resizableBorder->setSize (getWidth(), getHeight());
  63588. resizableBorder->toBack();
  63589. }
  63590. if (resizableCorner != 0)
  63591. {
  63592. #if JUCE_MAC
  63593. // hide the resizable border if the OS already provides one..
  63594. resizableCorner->setVisible (! (isFullScreen() || isUsingNativeTitleBar()));
  63595. #else
  63596. resizableCorner->setVisible (! isFullScreen());
  63597. #endif
  63598. const int resizerSize = 18;
  63599. resizableCorner->setBounds (getWidth() - resizerSize,
  63600. getHeight() - resizerSize,
  63601. resizerSize, resizerSize);
  63602. }
  63603. if (contentComponent != 0)
  63604. contentComponent->setBoundsInset (getContentComponentBorder());
  63605. updateLastPos();
  63606. #if JUCE_DEBUG
  63607. hasBeenResized = true;
  63608. #endif
  63609. }
  63610. void ResizableWindow::childBoundsChanged (Component* child)
  63611. {
  63612. if ((child == contentComponent) && (child != 0) && resizeToFitContent)
  63613. {
  63614. // not going to look very good if this component has a zero size..
  63615. jassert (child->getWidth() > 0);
  63616. jassert (child->getHeight() > 0);
  63617. const BorderSize borders (getContentComponentBorder());
  63618. setSize (child->getWidth() + borders.getLeftAndRight(),
  63619. child->getHeight() + borders.getTopAndBottom());
  63620. }
  63621. }
  63622. void ResizableWindow::activeWindowStatusChanged()
  63623. {
  63624. const BorderSize border (getContentComponentBorder());
  63625. Rectangle<int> area (getLocalBounds());
  63626. repaint (area.removeFromTop (border.getTop()));
  63627. repaint (area.removeFromLeft (border.getLeft()));
  63628. repaint (area.removeFromRight (border.getRight()));
  63629. repaint (area.removeFromBottom (border.getBottom()));
  63630. }
  63631. void ResizableWindow::setResizable (const bool shouldBeResizable,
  63632. const bool useBottomRightCornerResizer)
  63633. {
  63634. if (shouldBeResizable)
  63635. {
  63636. if (useBottomRightCornerResizer)
  63637. {
  63638. resizableBorder = 0;
  63639. if (resizableCorner == 0)
  63640. {
  63641. Component::addChildComponent (resizableCorner = new ResizableCornerComponent (this, constrainer));
  63642. resizableCorner->setAlwaysOnTop (true);
  63643. }
  63644. }
  63645. else
  63646. {
  63647. resizableCorner = 0;
  63648. if (resizableBorder == 0)
  63649. Component::addChildComponent (resizableBorder = new ResizableBorderComponent (this, constrainer));
  63650. }
  63651. }
  63652. else
  63653. {
  63654. resizableCorner = 0;
  63655. resizableBorder = 0;
  63656. }
  63657. if (isUsingNativeTitleBar())
  63658. recreateDesktopWindow();
  63659. childBoundsChanged (contentComponent);
  63660. resized();
  63661. }
  63662. bool ResizableWindow::isResizable() const throw()
  63663. {
  63664. return resizableCorner != 0
  63665. || resizableBorder != 0;
  63666. }
  63667. void ResizableWindow::setResizeLimits (const int newMinimumWidth,
  63668. const int newMinimumHeight,
  63669. const int newMaximumWidth,
  63670. const int newMaximumHeight) throw()
  63671. {
  63672. // if you've set up a custom constrainer then these settings won't have any effect..
  63673. jassert (constrainer == &defaultConstrainer || constrainer == 0);
  63674. if (constrainer == 0)
  63675. setConstrainer (&defaultConstrainer);
  63676. defaultConstrainer.setSizeLimits (newMinimumWidth, newMinimumHeight,
  63677. newMaximumWidth, newMaximumHeight);
  63678. setBoundsConstrained (getBounds());
  63679. }
  63680. void ResizableWindow::setConstrainer (ComponentBoundsConstrainer* newConstrainer)
  63681. {
  63682. if (constrainer != newConstrainer)
  63683. {
  63684. constrainer = newConstrainer;
  63685. const bool useBottomRightCornerResizer = resizableCorner != 0;
  63686. const bool shouldBeResizable = useBottomRightCornerResizer || resizableBorder != 0;
  63687. resizableCorner = 0;
  63688. resizableBorder = 0;
  63689. setResizable (shouldBeResizable, useBottomRightCornerResizer);
  63690. ComponentPeer* const peer = getPeer();
  63691. if (peer != 0)
  63692. peer->setConstrainer (newConstrainer);
  63693. }
  63694. }
  63695. void ResizableWindow::setBoundsConstrained (const Rectangle<int>& bounds)
  63696. {
  63697. if (constrainer != 0)
  63698. constrainer->setBoundsForComponent (this, bounds, false, false, false, false);
  63699. else
  63700. setBounds (bounds);
  63701. }
  63702. void ResizableWindow::paint (Graphics& g)
  63703. {
  63704. getLookAndFeel().fillResizableWindowBackground (g, getWidth(), getHeight(),
  63705. getBorderThickness(), *this);
  63706. if (! isFullScreen())
  63707. {
  63708. getLookAndFeel().drawResizableWindowBorder (g, getWidth(), getHeight(),
  63709. getBorderThickness(), *this);
  63710. }
  63711. #if JUCE_DEBUG
  63712. /* If this fails, then you've probably written a subclass with a resized()
  63713. callback but forgotten to make it call its parent class's resized() method.
  63714. It's important when you override methods like resized(), moved(),
  63715. etc., that you make sure the base class methods also get called.
  63716. Of course you shouldn't really be overriding ResizableWindow::resized() anyway,
  63717. because your content should all be inside the content component - and it's the
  63718. content component's resized() method that you should be using to do your
  63719. layout.
  63720. */
  63721. jassert (hasBeenResized || (getWidth() == 0 && getHeight() == 0));
  63722. #endif
  63723. }
  63724. void ResizableWindow::lookAndFeelChanged()
  63725. {
  63726. resized();
  63727. if (isOnDesktop())
  63728. {
  63729. Component::addToDesktop (getDesktopWindowStyleFlags());
  63730. ComponentPeer* const peer = getPeer();
  63731. if (peer != 0)
  63732. peer->setConstrainer (constrainer);
  63733. }
  63734. }
  63735. const Colour ResizableWindow::getBackgroundColour() const throw()
  63736. {
  63737. return findColour (backgroundColourId, false);
  63738. }
  63739. void ResizableWindow::setBackgroundColour (const Colour& newColour)
  63740. {
  63741. Colour backgroundColour (newColour);
  63742. if (! Desktop::canUseSemiTransparentWindows())
  63743. backgroundColour = newColour.withAlpha (1.0f);
  63744. setColour (backgroundColourId, backgroundColour);
  63745. setOpaque (backgroundColour.isOpaque());
  63746. repaint();
  63747. }
  63748. bool ResizableWindow::isFullScreen() const
  63749. {
  63750. if (isOnDesktop())
  63751. {
  63752. ComponentPeer* const peer = getPeer();
  63753. return peer != 0 && peer->isFullScreen();
  63754. }
  63755. return fullscreen;
  63756. }
  63757. void ResizableWindow::setFullScreen (const bool shouldBeFullScreen)
  63758. {
  63759. if (shouldBeFullScreen != isFullScreen())
  63760. {
  63761. updateLastPos();
  63762. fullscreen = shouldBeFullScreen;
  63763. if (isOnDesktop())
  63764. {
  63765. ComponentPeer* const peer = getPeer();
  63766. if (peer != 0)
  63767. {
  63768. // keep a copy of this intact in case the real one gets messed-up while we're un-maximising
  63769. const Rectangle<int> lastPos (lastNonFullScreenPos);
  63770. peer->setFullScreen (shouldBeFullScreen);
  63771. if ((! shouldBeFullScreen) && ! lastPos.isEmpty())
  63772. setBounds (lastPos);
  63773. }
  63774. else
  63775. {
  63776. jassertfalse;
  63777. }
  63778. }
  63779. else
  63780. {
  63781. if (shouldBeFullScreen)
  63782. setBounds (0, 0, getParentWidth(), getParentHeight());
  63783. else
  63784. setBounds (lastNonFullScreenPos);
  63785. }
  63786. resized();
  63787. }
  63788. }
  63789. bool ResizableWindow::isMinimised() const
  63790. {
  63791. ComponentPeer* const peer = getPeer();
  63792. return (peer != 0) && peer->isMinimised();
  63793. }
  63794. void ResizableWindow::setMinimised (const bool shouldMinimise)
  63795. {
  63796. if (shouldMinimise != isMinimised())
  63797. {
  63798. ComponentPeer* const peer = getPeer();
  63799. if (peer != 0)
  63800. {
  63801. updateLastPos();
  63802. peer->setMinimised (shouldMinimise);
  63803. }
  63804. else
  63805. {
  63806. jassertfalse;
  63807. }
  63808. }
  63809. }
  63810. void ResizableWindow::updateLastPos()
  63811. {
  63812. if (isShowing() && ! (isFullScreen() || isMinimised()))
  63813. {
  63814. lastNonFullScreenPos = getBounds();
  63815. }
  63816. }
  63817. void ResizableWindow::parentSizeChanged()
  63818. {
  63819. if (isFullScreen() && getParentComponent() != 0)
  63820. {
  63821. setBounds (0, 0, getParentWidth(), getParentHeight());
  63822. }
  63823. }
  63824. const String ResizableWindow::getWindowStateAsString()
  63825. {
  63826. updateLastPos();
  63827. return (isFullScreen() ? "fs " : "") + lastNonFullScreenPos.toString();
  63828. }
  63829. bool ResizableWindow::restoreWindowStateFromString (const String& s)
  63830. {
  63831. StringArray tokens;
  63832. tokens.addTokens (s, false);
  63833. tokens.removeEmptyStrings();
  63834. tokens.trim();
  63835. const bool fs = tokens[0].startsWithIgnoreCase ("fs");
  63836. const int firstCoord = fs ? 1 : 0;
  63837. if (tokens.size() != firstCoord + 4)
  63838. return false;
  63839. Rectangle<int> newPos (tokens[firstCoord].getIntValue(),
  63840. tokens[firstCoord + 1].getIntValue(),
  63841. tokens[firstCoord + 2].getIntValue(),
  63842. tokens[firstCoord + 3].getIntValue());
  63843. if (newPos.isEmpty())
  63844. return false;
  63845. const Rectangle<int> screen (Desktop::getInstance().getMonitorAreaContaining (newPos.getCentre()));
  63846. ComponentPeer* const peer = isOnDesktop() ? getPeer() : 0;
  63847. if (peer != 0)
  63848. peer->getFrameSize().addTo (newPos);
  63849. if (! screen.contains (newPos))
  63850. {
  63851. newPos.setSize (jmin (newPos.getWidth(), screen.getWidth()),
  63852. jmin (newPos.getHeight(), screen.getHeight()));
  63853. newPos.setPosition (jlimit (screen.getX(), screen.getRight() - newPos.getWidth(), newPos.getX()),
  63854. jlimit (screen.getY(), screen.getBottom() - newPos.getHeight(), newPos.getY()));
  63855. }
  63856. if (peer != 0)
  63857. {
  63858. peer->getFrameSize().subtractFrom (newPos);
  63859. peer->setNonFullScreenBounds (newPos);
  63860. }
  63861. lastNonFullScreenPos = newPos;
  63862. setFullScreen (fs);
  63863. if (! fs)
  63864. setBoundsConstrained (newPos);
  63865. return true;
  63866. }
  63867. void ResizableWindow::mouseDown (const MouseEvent&)
  63868. {
  63869. if (! isFullScreen())
  63870. dragger.startDraggingComponent (this, constrainer);
  63871. }
  63872. void ResizableWindow::mouseDrag (const MouseEvent& e)
  63873. {
  63874. if (! isFullScreen())
  63875. dragger.dragComponent (this, e);
  63876. }
  63877. #if JUCE_DEBUG
  63878. void ResizableWindow::addChildComponent (Component* const child, int zOrder)
  63879. {
  63880. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  63881. manages its child components automatically, and if you add your own it'll cause
  63882. trouble. Instead, use setContentComponent() to give it a component which
  63883. will be automatically resized and kept in the right place - then you can add
  63884. subcomponents to the content comp. See the notes for the ResizableWindow class
  63885. for more info.
  63886. If you really know what you're doing and want to avoid this assertion, just call
  63887. Component::addChildComponent directly.
  63888. */
  63889. jassertfalse;
  63890. Component::addChildComponent (child, zOrder);
  63891. }
  63892. void ResizableWindow::addAndMakeVisible (Component* const child, int zOrder)
  63893. {
  63894. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  63895. manages its child components automatically, and if you add your own it'll cause
  63896. trouble. Instead, use setContentComponent() to give it a component which
  63897. will be automatically resized and kept in the right place - then you can add
  63898. subcomponents to the content comp. See the notes for the ResizableWindow class
  63899. for more info.
  63900. If you really know what you're doing and want to avoid this assertion, just call
  63901. Component::addAndMakeVisible directly.
  63902. */
  63903. jassertfalse;
  63904. Component::addAndMakeVisible (child, zOrder);
  63905. }
  63906. #endif
  63907. END_JUCE_NAMESPACE
  63908. /*** End of inlined file: juce_ResizableWindow.cpp ***/
  63909. /*** Start of inlined file: juce_SplashScreen.cpp ***/
  63910. BEGIN_JUCE_NAMESPACE
  63911. SplashScreen::SplashScreen()
  63912. {
  63913. setOpaque (true);
  63914. }
  63915. SplashScreen::~SplashScreen()
  63916. {
  63917. }
  63918. void SplashScreen::show (const String& title,
  63919. const Image& backgroundImage_,
  63920. const int minimumTimeToDisplayFor,
  63921. const bool useDropShadow,
  63922. const bool removeOnMouseClick)
  63923. {
  63924. backgroundImage = backgroundImage_;
  63925. jassert (backgroundImage_.isValid());
  63926. if (backgroundImage_.isValid())
  63927. {
  63928. setOpaque (! backgroundImage_.hasAlphaChannel());
  63929. show (title,
  63930. backgroundImage_.getWidth(),
  63931. backgroundImage_.getHeight(),
  63932. minimumTimeToDisplayFor,
  63933. useDropShadow,
  63934. removeOnMouseClick);
  63935. }
  63936. }
  63937. void SplashScreen::show (const String& title,
  63938. const int width,
  63939. const int height,
  63940. const int minimumTimeToDisplayFor,
  63941. const bool useDropShadow,
  63942. const bool removeOnMouseClick)
  63943. {
  63944. setName (title);
  63945. setAlwaysOnTop (true);
  63946. setVisible (true);
  63947. centreWithSize (width, height);
  63948. addToDesktop (useDropShadow ? ComponentPeer::windowHasDropShadow : 0);
  63949. toFront (false);
  63950. MessageManager::getInstance()->runDispatchLoopUntil (300);
  63951. repaint();
  63952. originalClickCounter = removeOnMouseClick
  63953. ? Desktop::getMouseButtonClickCounter()
  63954. : std::numeric_limits<int>::max();
  63955. earliestTimeToDelete = Time::getCurrentTime() + RelativeTime::milliseconds (minimumTimeToDisplayFor);
  63956. startTimer (50);
  63957. }
  63958. void SplashScreen::paint (Graphics& g)
  63959. {
  63960. g.setOpacity (1.0f);
  63961. g.drawImage (backgroundImage,
  63962. 0, 0, getWidth(), getHeight(),
  63963. 0, 0, backgroundImage.getWidth(), backgroundImage.getHeight());
  63964. }
  63965. void SplashScreen::timerCallback()
  63966. {
  63967. if (Time::getCurrentTime() > earliestTimeToDelete
  63968. || Desktop::getMouseButtonClickCounter() > originalClickCounter)
  63969. {
  63970. delete this;
  63971. }
  63972. }
  63973. END_JUCE_NAMESPACE
  63974. /*** End of inlined file: juce_SplashScreen.cpp ***/
  63975. /*** Start of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  63976. BEGIN_JUCE_NAMESPACE
  63977. ThreadWithProgressWindow::ThreadWithProgressWindow (const String& title,
  63978. const bool hasProgressBar,
  63979. const bool hasCancelButton,
  63980. const int timeOutMsWhenCancelling_,
  63981. const String& cancelButtonText)
  63982. : Thread ("Juce Progress Window"),
  63983. progress (0.0),
  63984. timeOutMsWhenCancelling (timeOutMsWhenCancelling_)
  63985. {
  63986. alertWindow = LookAndFeel::getDefaultLookAndFeel()
  63987. .createAlertWindow (title, String::empty, cancelButtonText,
  63988. String::empty, String::empty,
  63989. AlertWindow::NoIcon, hasCancelButton ? 1 : 0, 0);
  63990. if (hasProgressBar)
  63991. alertWindow->addProgressBarComponent (progress);
  63992. }
  63993. ThreadWithProgressWindow::~ThreadWithProgressWindow()
  63994. {
  63995. stopThread (timeOutMsWhenCancelling);
  63996. }
  63997. bool ThreadWithProgressWindow::runThread (const int priority)
  63998. {
  63999. startThread (priority);
  64000. startTimer (100);
  64001. {
  64002. const ScopedLock sl (messageLock);
  64003. alertWindow->setMessage (message);
  64004. }
  64005. const bool finishedNaturally = alertWindow->runModalLoop() != 0;
  64006. stopThread (timeOutMsWhenCancelling);
  64007. alertWindow->setVisible (false);
  64008. return finishedNaturally;
  64009. }
  64010. void ThreadWithProgressWindow::setProgress (const double newProgress)
  64011. {
  64012. progress = newProgress;
  64013. }
  64014. void ThreadWithProgressWindow::setStatusMessage (const String& newStatusMessage)
  64015. {
  64016. const ScopedLock sl (messageLock);
  64017. message = newStatusMessage;
  64018. }
  64019. void ThreadWithProgressWindow::timerCallback()
  64020. {
  64021. if (! isThreadRunning())
  64022. {
  64023. // thread has finished normally..
  64024. alertWindow->exitModalState (1);
  64025. alertWindow->setVisible (false);
  64026. }
  64027. else
  64028. {
  64029. const ScopedLock sl (messageLock);
  64030. alertWindow->setMessage (message);
  64031. }
  64032. }
  64033. END_JUCE_NAMESPACE
  64034. /*** End of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  64035. /*** Start of inlined file: juce_TooltipWindow.cpp ***/
  64036. BEGIN_JUCE_NAMESPACE
  64037. TooltipWindow::TooltipWindow (Component* const parentComponent,
  64038. const int millisecondsBeforeTipAppears_)
  64039. : Component ("tooltip"),
  64040. millisecondsBeforeTipAppears (millisecondsBeforeTipAppears_),
  64041. mouseClicks (0),
  64042. lastHideTime (0),
  64043. lastComponentUnderMouse (0),
  64044. changedCompsSinceShown (true)
  64045. {
  64046. if (Desktop::getInstance().getMainMouseSource().canHover())
  64047. startTimer (123);
  64048. setAlwaysOnTop (true);
  64049. setOpaque (true);
  64050. if (parentComponent != 0)
  64051. parentComponent->addChildComponent (this);
  64052. }
  64053. TooltipWindow::~TooltipWindow()
  64054. {
  64055. hide();
  64056. }
  64057. void TooltipWindow::setMillisecondsBeforeTipAppears (const int newTimeMs) throw()
  64058. {
  64059. millisecondsBeforeTipAppears = newTimeMs;
  64060. }
  64061. void TooltipWindow::paint (Graphics& g)
  64062. {
  64063. getLookAndFeel().drawTooltip (g, tipShowing, getWidth(), getHeight());
  64064. }
  64065. void TooltipWindow::mouseEnter (const MouseEvent&)
  64066. {
  64067. hide();
  64068. }
  64069. void TooltipWindow::showFor (const String& tip)
  64070. {
  64071. jassert (tip.isNotEmpty());
  64072. if (tipShowing != tip)
  64073. repaint();
  64074. tipShowing = tip;
  64075. Point<int> mousePos (Desktop::getMousePosition());
  64076. if (getParentComponent() != 0)
  64077. mousePos = getParentComponent()->globalPositionToRelative (mousePos);
  64078. int x, y, w, h;
  64079. getLookAndFeel().getTooltipSize (tip, w, h);
  64080. if (mousePos.getX() > getParentWidth() / 2)
  64081. x = mousePos.getX() - (w + 12);
  64082. else
  64083. x = mousePos.getX() + 24;
  64084. if (mousePos.getY() > getParentHeight() / 2)
  64085. y = mousePos.getY() - (h + 6);
  64086. else
  64087. y = mousePos.getY() + 6;
  64088. setBounds (x, y, w, h);
  64089. setVisible (true);
  64090. if (getParentComponent() == 0)
  64091. {
  64092. addToDesktop (ComponentPeer::windowHasDropShadow
  64093. | ComponentPeer::windowIsTemporary
  64094. | ComponentPeer::windowIgnoresKeyPresses);
  64095. }
  64096. toFront (false);
  64097. }
  64098. const String TooltipWindow::getTipFor (Component* const c)
  64099. {
  64100. if (c != 0
  64101. && Process::isForegroundProcess()
  64102. && ! Component::isMouseButtonDownAnywhere())
  64103. {
  64104. TooltipClient* const ttc = dynamic_cast <TooltipClient*> (c);
  64105. if (ttc != 0 && ! c->isCurrentlyBlockedByAnotherModalComponent())
  64106. return ttc->getTooltip();
  64107. }
  64108. return String::empty;
  64109. }
  64110. void TooltipWindow::hide()
  64111. {
  64112. tipShowing = String::empty;
  64113. removeFromDesktop();
  64114. setVisible (false);
  64115. }
  64116. void TooltipWindow::timerCallback()
  64117. {
  64118. const unsigned int now = Time::getApproximateMillisecondCounter();
  64119. Component* const newComp = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  64120. const String newTip (getTipFor (newComp));
  64121. const bool tipChanged = (newTip != lastTipUnderMouse || newComp != lastComponentUnderMouse);
  64122. lastComponentUnderMouse = newComp;
  64123. lastTipUnderMouse = newTip;
  64124. const int clickCount = Desktop::getInstance().getMouseButtonClickCounter();
  64125. const bool mouseWasClicked = clickCount > mouseClicks;
  64126. mouseClicks = clickCount;
  64127. const Point<int> mousePos (Desktop::getMousePosition());
  64128. const bool mouseMovedQuickly = mousePos.getDistanceFrom (lastMousePos) > 12;
  64129. lastMousePos = mousePos;
  64130. if (tipChanged || mouseWasClicked || mouseMovedQuickly)
  64131. lastCompChangeTime = now;
  64132. if (isVisible() || now < lastHideTime + 500)
  64133. {
  64134. // if a tip is currently visible (or has just disappeared), update to a new one
  64135. // immediately if needed..
  64136. if (newComp == 0 || mouseWasClicked || newTip.isEmpty())
  64137. {
  64138. if (isVisible())
  64139. {
  64140. lastHideTime = now;
  64141. hide();
  64142. }
  64143. }
  64144. else if (tipChanged)
  64145. {
  64146. showFor (newTip);
  64147. }
  64148. }
  64149. else
  64150. {
  64151. // if there isn't currently a tip, but one is needed, only let it
  64152. // appear after a timeout..
  64153. if (newTip.isNotEmpty()
  64154. && newTip != tipShowing
  64155. && now > lastCompChangeTime + millisecondsBeforeTipAppears)
  64156. {
  64157. showFor (newTip);
  64158. }
  64159. }
  64160. }
  64161. END_JUCE_NAMESPACE
  64162. /*** End of inlined file: juce_TooltipWindow.cpp ***/
  64163. /*** Start of inlined file: juce_TopLevelWindow.cpp ***/
  64164. BEGIN_JUCE_NAMESPACE
  64165. /** Keeps track of the active top level window.
  64166. */
  64167. class TopLevelWindowManager : public Timer,
  64168. public DeletedAtShutdown
  64169. {
  64170. public:
  64171. TopLevelWindowManager()
  64172. : currentActive (0)
  64173. {
  64174. }
  64175. ~TopLevelWindowManager()
  64176. {
  64177. clearSingletonInstance();
  64178. }
  64179. juce_DeclareSingleton_SingleThreaded_Minimal (TopLevelWindowManager)
  64180. void timerCallback()
  64181. {
  64182. startTimer (jmin (1731, getTimerInterval() * 2));
  64183. TopLevelWindow* active = 0;
  64184. if (Process::isForegroundProcess())
  64185. {
  64186. active = currentActive;
  64187. Component* const c = Component::getCurrentlyFocusedComponent();
  64188. TopLevelWindow* tlw = dynamic_cast <TopLevelWindow*> (c);
  64189. if (tlw == 0 && c != 0)
  64190. // (unable to use the syntax findParentComponentOfClass <TopLevelWindow> () because of a VC6 compiler bug)
  64191. tlw = c->findParentComponentOfClass ((TopLevelWindow*) 0);
  64192. if (tlw != 0)
  64193. active = tlw;
  64194. }
  64195. if (active != currentActive)
  64196. {
  64197. currentActive = active;
  64198. for (int i = windows.size(); --i >= 0;)
  64199. {
  64200. TopLevelWindow* const tlw = windows.getUnchecked (i);
  64201. tlw->setWindowActive (isWindowActive (tlw));
  64202. i = jmin (i, windows.size() - 1);
  64203. }
  64204. Desktop::getInstance().triggerFocusCallback();
  64205. }
  64206. }
  64207. bool addWindow (TopLevelWindow* const w)
  64208. {
  64209. windows.add (w);
  64210. startTimer (10);
  64211. return isWindowActive (w);
  64212. }
  64213. void removeWindow (TopLevelWindow* const w)
  64214. {
  64215. startTimer (10);
  64216. if (currentActive == w)
  64217. currentActive = 0;
  64218. windows.removeValue (w);
  64219. if (windows.size() == 0)
  64220. deleteInstance();
  64221. }
  64222. Array <TopLevelWindow*> windows;
  64223. private:
  64224. TopLevelWindow* currentActive;
  64225. bool isWindowActive (TopLevelWindow* const tlw) const
  64226. {
  64227. return (tlw == currentActive
  64228. || tlw->isParentOf (currentActive)
  64229. || tlw->hasKeyboardFocus (true))
  64230. && tlw->isShowing();
  64231. }
  64232. TopLevelWindowManager (const TopLevelWindowManager&);
  64233. TopLevelWindowManager& operator= (const TopLevelWindowManager&);
  64234. };
  64235. juce_ImplementSingleton_SingleThreaded (TopLevelWindowManager)
  64236. void juce_CheckCurrentlyFocusedTopLevelWindow()
  64237. {
  64238. if (TopLevelWindowManager::getInstanceWithoutCreating() != 0)
  64239. TopLevelWindowManager::getInstanceWithoutCreating()->startTimer (20);
  64240. }
  64241. TopLevelWindow::TopLevelWindow (const String& name,
  64242. const bool addToDesktop_)
  64243. : Component (name),
  64244. useDropShadow (true),
  64245. useNativeTitleBar (false),
  64246. windowIsActive_ (false)
  64247. {
  64248. setOpaque (true);
  64249. if (addToDesktop_)
  64250. Component::addToDesktop (getDesktopWindowStyleFlags());
  64251. else
  64252. setDropShadowEnabled (true);
  64253. setWantsKeyboardFocus (true);
  64254. setBroughtToFrontOnMouseClick (true);
  64255. windowIsActive_ = TopLevelWindowManager::getInstance()->addWindow (this);
  64256. }
  64257. TopLevelWindow::~TopLevelWindow()
  64258. {
  64259. shadower = 0;
  64260. TopLevelWindowManager::getInstance()->removeWindow (this);
  64261. }
  64262. void TopLevelWindow::focusOfChildComponentChanged (FocusChangeType)
  64263. {
  64264. if (hasKeyboardFocus (true))
  64265. TopLevelWindowManager::getInstance()->timerCallback();
  64266. else
  64267. TopLevelWindowManager::getInstance()->startTimer (10);
  64268. }
  64269. void TopLevelWindow::setWindowActive (const bool isNowActive)
  64270. {
  64271. if (windowIsActive_ != isNowActive)
  64272. {
  64273. windowIsActive_ = isNowActive;
  64274. activeWindowStatusChanged();
  64275. }
  64276. }
  64277. void TopLevelWindow::activeWindowStatusChanged()
  64278. {
  64279. }
  64280. void TopLevelWindow::parentHierarchyChanged()
  64281. {
  64282. setDropShadowEnabled (useDropShadow);
  64283. }
  64284. void TopLevelWindow::visibilityChanged()
  64285. {
  64286. if (isShowing())
  64287. toFront (true);
  64288. }
  64289. int TopLevelWindow::getDesktopWindowStyleFlags() const
  64290. {
  64291. int styleFlags = ComponentPeer::windowAppearsOnTaskbar;
  64292. if (useDropShadow)
  64293. styleFlags |= ComponentPeer::windowHasDropShadow;
  64294. if (useNativeTitleBar)
  64295. styleFlags |= ComponentPeer::windowHasTitleBar;
  64296. return styleFlags;
  64297. }
  64298. void TopLevelWindow::setDropShadowEnabled (const bool useShadow)
  64299. {
  64300. useDropShadow = useShadow;
  64301. if (isOnDesktop())
  64302. {
  64303. shadower = 0;
  64304. Component::addToDesktop (getDesktopWindowStyleFlags());
  64305. }
  64306. else
  64307. {
  64308. if (useShadow && isOpaque())
  64309. {
  64310. if (shadower == 0)
  64311. {
  64312. shadower = getLookAndFeel().createDropShadowerForComponent (this);
  64313. if (shadower != 0)
  64314. shadower->setOwner (this);
  64315. }
  64316. }
  64317. else
  64318. {
  64319. shadower = 0;
  64320. }
  64321. }
  64322. }
  64323. void TopLevelWindow::setUsingNativeTitleBar (const bool useNativeTitleBar_)
  64324. {
  64325. if (useNativeTitleBar != useNativeTitleBar_)
  64326. {
  64327. useNativeTitleBar = useNativeTitleBar_;
  64328. recreateDesktopWindow();
  64329. sendLookAndFeelChange();
  64330. }
  64331. }
  64332. void TopLevelWindow::recreateDesktopWindow()
  64333. {
  64334. if (isOnDesktop())
  64335. {
  64336. Component::addToDesktop (getDesktopWindowStyleFlags());
  64337. toFront (true);
  64338. }
  64339. }
  64340. void TopLevelWindow::addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo)
  64341. {
  64342. /* It's not recommended to change the desktop window flags directly for a TopLevelWindow,
  64343. because this class needs to make sure its layout corresponds with settings like whether
  64344. it's got a native title bar or not.
  64345. If you need custom flags for your window, you can override the getDesktopWindowStyleFlags()
  64346. method. If you do this, it's best to call the base class's getDesktopWindowStyleFlags()
  64347. method, then add or remove whatever flags are necessary from this value before returning it.
  64348. */
  64349. jassert ((windowStyleFlags & ~ComponentPeer::windowIsSemiTransparent)
  64350. == (getDesktopWindowStyleFlags() & ~ComponentPeer::windowIsSemiTransparent));
  64351. Component::addToDesktop (windowStyleFlags, nativeWindowToAttachTo);
  64352. if (windowStyleFlags != getDesktopWindowStyleFlags())
  64353. sendLookAndFeelChange();
  64354. }
  64355. void TopLevelWindow::centreAroundComponent (Component* c, const int width, const int height)
  64356. {
  64357. if (c == 0)
  64358. c = TopLevelWindow::getActiveTopLevelWindow();
  64359. if (c == 0)
  64360. {
  64361. centreWithSize (width, height);
  64362. }
  64363. else
  64364. {
  64365. Point<int> p (c->relativePositionToGlobal (Point<int> ((c->getWidth() - width) / 2,
  64366. (c->getHeight() - height) / 2)));
  64367. Rectangle<int> parentArea (c->getParentMonitorArea());
  64368. if (getParentComponent() != 0)
  64369. {
  64370. p = getParentComponent()->globalPositionToRelative (p);
  64371. parentArea.setBounds (0, 0, getParentWidth(), getParentHeight());
  64372. }
  64373. parentArea.reduce (12, 12);
  64374. setBounds (jlimit (parentArea.getX(), jmax (parentArea.getX(), parentArea.getRight() - width), p.getX()),
  64375. jlimit (parentArea.getY(), jmax (parentArea.getY(), parentArea.getBottom() - height), p.getY()),
  64376. width, height);
  64377. }
  64378. }
  64379. int TopLevelWindow::getNumTopLevelWindows() throw()
  64380. {
  64381. return TopLevelWindowManager::getInstance()->windows.size();
  64382. }
  64383. TopLevelWindow* TopLevelWindow::getTopLevelWindow (const int index) throw()
  64384. {
  64385. return static_cast <TopLevelWindow*> (TopLevelWindowManager::getInstance()->windows [index]);
  64386. }
  64387. TopLevelWindow* TopLevelWindow::getActiveTopLevelWindow() throw()
  64388. {
  64389. TopLevelWindow* best = 0;
  64390. int bestNumTWLParents = -1;
  64391. for (int i = TopLevelWindow::getNumTopLevelWindows(); --i >= 0;)
  64392. {
  64393. TopLevelWindow* const tlw = TopLevelWindow::getTopLevelWindow (i);
  64394. if (tlw->isActiveWindow())
  64395. {
  64396. int numTWLParents = 0;
  64397. const Component* c = tlw->getParentComponent();
  64398. while (c != 0)
  64399. {
  64400. if (dynamic_cast <const TopLevelWindow*> (c) != 0)
  64401. ++numTWLParents;
  64402. c = c->getParentComponent();
  64403. }
  64404. if (bestNumTWLParents < numTWLParents)
  64405. {
  64406. best = tlw;
  64407. bestNumTWLParents = numTWLParents;
  64408. }
  64409. }
  64410. }
  64411. return best;
  64412. }
  64413. END_JUCE_NAMESPACE
  64414. /*** End of inlined file: juce_TopLevelWindow.cpp ***/
  64415. /*** Start of inlined file: juce_RelativeCoordinate.cpp ***/
  64416. BEGIN_JUCE_NAMESPACE
  64417. namespace RelativeCoordinateHelpers
  64418. {
  64419. static void skipComma (const juce_wchar* const s, int& i)
  64420. {
  64421. while (CharacterFunctions::isWhitespace (s[i]))
  64422. ++i;
  64423. if (s[i] == ',')
  64424. ++i;
  64425. }
  64426. }
  64427. const String RelativeCoordinate::Strings::parent ("parent");
  64428. const String RelativeCoordinate::Strings::left ("left");
  64429. const String RelativeCoordinate::Strings::right ("right");
  64430. const String RelativeCoordinate::Strings::top ("top");
  64431. const String RelativeCoordinate::Strings::bottom ("bottom");
  64432. const String RelativeCoordinate::Strings::parentLeft ("parent.left");
  64433. const String RelativeCoordinate::Strings::parentTop ("parent.top");
  64434. const String RelativeCoordinate::Strings::parentRight ("parent.right");
  64435. const String RelativeCoordinate::Strings::parentBottom ("parent.bottom");
  64436. RelativeCoordinate::RelativeCoordinate()
  64437. {
  64438. }
  64439. RelativeCoordinate::RelativeCoordinate (const Expression& term_)
  64440. : term (term_)
  64441. {
  64442. }
  64443. RelativeCoordinate::RelativeCoordinate (const RelativeCoordinate& other)
  64444. : term (other.term)
  64445. {
  64446. }
  64447. RelativeCoordinate& RelativeCoordinate::operator= (const RelativeCoordinate& other)
  64448. {
  64449. term = other.term;
  64450. return *this;
  64451. }
  64452. RelativeCoordinate::RelativeCoordinate (const double absoluteDistanceFromOrigin)
  64453. : term (absoluteDistanceFromOrigin)
  64454. {
  64455. }
  64456. RelativeCoordinate::RelativeCoordinate (const String& s)
  64457. {
  64458. try
  64459. {
  64460. term = Expression (s);
  64461. }
  64462. catch (...)
  64463. {}
  64464. }
  64465. RelativeCoordinate::~RelativeCoordinate()
  64466. {
  64467. }
  64468. bool RelativeCoordinate::operator== (const RelativeCoordinate& other) const throw()
  64469. {
  64470. return term.toString() == other.term.toString();
  64471. }
  64472. bool RelativeCoordinate::operator!= (const RelativeCoordinate& other) const throw()
  64473. {
  64474. return ! operator== (other);
  64475. }
  64476. double RelativeCoordinate::resolve (const Expression::EvaluationContext* context) const
  64477. {
  64478. try
  64479. {
  64480. if (context != 0)
  64481. return term.evaluate (*context);
  64482. else
  64483. return term.evaluate();
  64484. }
  64485. catch (...)
  64486. {}
  64487. return 0.0;
  64488. }
  64489. bool RelativeCoordinate::isRecursive (const Expression::EvaluationContext* context) const
  64490. {
  64491. try
  64492. {
  64493. if (context != 0)
  64494. term.evaluate (*context);
  64495. else
  64496. term.evaluate();
  64497. }
  64498. catch (...)
  64499. {
  64500. return true;
  64501. }
  64502. return false;
  64503. }
  64504. void RelativeCoordinate::moveToAbsolute (double newPos, const Expression::EvaluationContext* context)
  64505. {
  64506. try
  64507. {
  64508. if (context != 0)
  64509. {
  64510. term = term.adjustedToGiveNewResult (newPos, *context);
  64511. }
  64512. else
  64513. {
  64514. Expression::EvaluationContext defaultContext;
  64515. term = term.adjustedToGiveNewResult (newPos, defaultContext);
  64516. }
  64517. }
  64518. catch (...)
  64519. {}
  64520. }
  64521. bool RelativeCoordinate::references (const String& coordName, const Expression::EvaluationContext* context) const
  64522. {
  64523. try
  64524. {
  64525. return term.referencesSymbol (coordName, context);
  64526. }
  64527. catch (...)
  64528. {}
  64529. return false;
  64530. }
  64531. bool RelativeCoordinate::isDynamic() const
  64532. {
  64533. return term.usesAnySymbols();
  64534. }
  64535. const String RelativeCoordinate::toString() const
  64536. {
  64537. return term.toString();
  64538. }
  64539. void RelativeCoordinate::renameSymbolIfUsed (const String& oldName, const String& newName)
  64540. {
  64541. jassert (newName.isNotEmpty() && newName.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_"));
  64542. if (term.referencesSymbol (oldName, 0))
  64543. term = term.withRenamedSymbol (oldName, newName);
  64544. }
  64545. RelativePoint::RelativePoint()
  64546. {
  64547. }
  64548. RelativePoint::RelativePoint (const Point<float>& absolutePoint)
  64549. : x (absolutePoint.getX()), y (absolutePoint.getY())
  64550. {
  64551. }
  64552. RelativePoint::RelativePoint (const float x_, const float y_)
  64553. : x (x_), y (y_)
  64554. {
  64555. }
  64556. RelativePoint::RelativePoint (const RelativeCoordinate& x_, const RelativeCoordinate& y_)
  64557. : x (x_), y (y_)
  64558. {
  64559. }
  64560. RelativePoint::RelativePoint (const String& s)
  64561. {
  64562. int i = 0;
  64563. x = RelativeCoordinate (Expression::parse (s, i));
  64564. RelativeCoordinateHelpers::skipComma (s, i);
  64565. y = RelativeCoordinate (Expression::parse (s, i));
  64566. }
  64567. bool RelativePoint::operator== (const RelativePoint& other) const throw()
  64568. {
  64569. return x == other.x && y == other.y;
  64570. }
  64571. bool RelativePoint::operator!= (const RelativePoint& other) const throw()
  64572. {
  64573. return ! operator== (other);
  64574. }
  64575. const Point<float> RelativePoint::resolve (const Expression::EvaluationContext* context) const
  64576. {
  64577. return Point<float> ((float) x.resolve (context),
  64578. (float) y.resolve (context));
  64579. }
  64580. void RelativePoint::moveToAbsolute (const Point<float>& newPos, const Expression::EvaluationContext* context)
  64581. {
  64582. x.moveToAbsolute (newPos.getX(), context);
  64583. y.moveToAbsolute (newPos.getY(), context);
  64584. }
  64585. const String RelativePoint::toString() const
  64586. {
  64587. return x.toString() + ", " + y.toString();
  64588. }
  64589. void RelativePoint::renameSymbolIfUsed (const String& oldName, const String& newName)
  64590. {
  64591. x.renameSymbolIfUsed (oldName, newName);
  64592. y.renameSymbolIfUsed (oldName, newName);
  64593. }
  64594. bool RelativePoint::isDynamic() const
  64595. {
  64596. return x.isDynamic() || y.isDynamic();
  64597. }
  64598. RelativeRectangle::RelativeRectangle()
  64599. {
  64600. }
  64601. RelativeRectangle::RelativeRectangle (const RelativeCoordinate& left_, const RelativeCoordinate& right_,
  64602. const RelativeCoordinate& top_, const RelativeCoordinate& bottom_)
  64603. : left (left_), right (right_), top (top_), bottom (bottom_)
  64604. {
  64605. }
  64606. RelativeRectangle::RelativeRectangle (const Rectangle<float>& rect, const String& componentName)
  64607. : left (rect.getX()),
  64608. right (Expression::symbol (componentName + "." + RelativeCoordinate::Strings::left) + Expression ((double) rect.getWidth())),
  64609. top (rect.getY()),
  64610. bottom (Expression::symbol (componentName + "." + RelativeCoordinate::Strings::top) + Expression ((double) rect.getHeight()))
  64611. {
  64612. }
  64613. RelativeRectangle::RelativeRectangle (const String& s)
  64614. {
  64615. int i = 0;
  64616. left = RelativeCoordinate (Expression::parse (s, i));
  64617. RelativeCoordinateHelpers::skipComma (s, i);
  64618. top = RelativeCoordinate (Expression::parse (s, i));
  64619. RelativeCoordinateHelpers::skipComma (s, i);
  64620. right = RelativeCoordinate (Expression::parse (s, i));
  64621. RelativeCoordinateHelpers::skipComma (s, i);
  64622. bottom = RelativeCoordinate (Expression::parse (s, i));
  64623. }
  64624. bool RelativeRectangle::operator== (const RelativeRectangle& other) const throw()
  64625. {
  64626. return left == other.left && top == other.top && right == other.right && bottom == other.bottom;
  64627. }
  64628. bool RelativeRectangle::operator!= (const RelativeRectangle& other) const throw()
  64629. {
  64630. return ! operator== (other);
  64631. }
  64632. const Rectangle<float> RelativeRectangle::resolve (const Expression::EvaluationContext* context) const
  64633. {
  64634. const double l = left.resolve (context);
  64635. const double r = right.resolve (context);
  64636. const double t = top.resolve (context);
  64637. const double b = bottom.resolve (context);
  64638. return Rectangle<float> ((float) l, (float) t, (float) (r - l), (float) (b - t));
  64639. }
  64640. void RelativeRectangle::moveToAbsolute (const Rectangle<float>& newPos, const Expression::EvaluationContext* context)
  64641. {
  64642. left.moveToAbsolute (newPos.getX(), context);
  64643. right.moveToAbsolute (newPos.getRight(), context);
  64644. top.moveToAbsolute (newPos.getY(), context);
  64645. bottom.moveToAbsolute (newPos.getBottom(), context);
  64646. }
  64647. const String RelativeRectangle::toString() const
  64648. {
  64649. return left.toString() + ", " + top.toString() + ", " + right.toString() + ", " + bottom.toString();
  64650. }
  64651. void RelativeRectangle::renameSymbolIfUsed (const String& oldName, const String& newName)
  64652. {
  64653. left.renameSymbolIfUsed (oldName, newName);
  64654. right.renameSymbolIfUsed (oldName, newName);
  64655. top.renameSymbolIfUsed (oldName, newName);
  64656. bottom.renameSymbolIfUsed (oldName, newName);
  64657. }
  64658. RelativePointPath::RelativePointPath()
  64659. : usesNonZeroWinding (true),
  64660. containsDynamicPoints (false)
  64661. {
  64662. }
  64663. RelativePointPath::RelativePointPath (const RelativePointPath& other)
  64664. : usesNonZeroWinding (true),
  64665. containsDynamicPoints (false)
  64666. {
  64667. ValueTree state (DrawablePath::valueTreeType);
  64668. other.writeTo (state, 0);
  64669. parse (state);
  64670. }
  64671. RelativePointPath::RelativePointPath (const ValueTree& drawable)
  64672. : usesNonZeroWinding (true),
  64673. containsDynamicPoints (false)
  64674. {
  64675. parse (drawable);
  64676. }
  64677. RelativePointPath::RelativePointPath (const Path& path)
  64678. {
  64679. usesNonZeroWinding = path.isUsingNonZeroWinding();
  64680. Path::Iterator i (path);
  64681. while (i.next())
  64682. {
  64683. switch (i.elementType)
  64684. {
  64685. case Path::Iterator::startNewSubPath: elements.add (new StartSubPath (RelativePoint (i.x1, i.y1))); break;
  64686. case Path::Iterator::lineTo: elements.add (new LineTo (RelativePoint (i.x1, i.y1))); break;
  64687. case Path::Iterator::quadraticTo: elements.add (new QuadraticTo (RelativePoint (i.x1, i.y1), RelativePoint (i.x2, i.y2))); break;
  64688. case Path::Iterator::cubicTo: elements.add (new CubicTo (RelativePoint (i.x1, i.y1), RelativePoint (i.x2, i.y2), RelativePoint (i.x3, i.y3))); break;
  64689. case Path::Iterator::closePath: elements.add (new CloseSubPath()); break;
  64690. default: jassertfalse; break;
  64691. }
  64692. }
  64693. }
  64694. void RelativePointPath::writeTo (ValueTree state, UndoManager* undoManager) const
  64695. {
  64696. DrawablePath::ValueTreeWrapper wrapper (state);
  64697. wrapper.setUsesNonZeroWinding (usesNonZeroWinding, undoManager);
  64698. ValueTree pathTree (wrapper.getPathState());
  64699. pathTree.removeAllChildren (undoManager);
  64700. for (int i = 0; i < elements.size(); ++i)
  64701. pathTree.addChild (elements.getUnchecked(i)->createTree(), -1, undoManager);
  64702. }
  64703. void RelativePointPath::parse (const ValueTree& state)
  64704. {
  64705. DrawablePath::ValueTreeWrapper wrapper (state);
  64706. usesNonZeroWinding = wrapper.usesNonZeroWinding();
  64707. RelativePoint points[3];
  64708. const ValueTree pathTree (wrapper.getPathState());
  64709. const int num = pathTree.getNumChildren();
  64710. for (int i = 0; i < num; ++i)
  64711. {
  64712. const DrawablePath::ValueTreeWrapper::Element e (pathTree.getChild(i));
  64713. const int numCps = e.getNumControlPoints();
  64714. for (int j = 0; j < numCps; ++j)
  64715. {
  64716. points[j] = e.getControlPoint (j);
  64717. containsDynamicPoints = containsDynamicPoints || points[j].isDynamic();
  64718. }
  64719. const Identifier type (e.getType());
  64720. if (type == DrawablePath::ValueTreeWrapper::Element::startSubPathElement)
  64721. elements.add (new StartSubPath (points[0]));
  64722. else if (type == DrawablePath::ValueTreeWrapper::Element::closeSubPathElement)
  64723. elements.add (new CloseSubPath());
  64724. else if (type == DrawablePath::ValueTreeWrapper::Element::lineToElement)
  64725. elements.add (new LineTo (points[0]));
  64726. else if (type == DrawablePath::ValueTreeWrapper::Element::quadraticToElement)
  64727. elements.add (new QuadraticTo (points[0], points[1]));
  64728. else if (type == DrawablePath::ValueTreeWrapper::Element::cubicToElement)
  64729. elements.add (new CubicTo (points[0], points[1], points[2]));
  64730. else
  64731. jassertfalse;
  64732. }
  64733. }
  64734. RelativePointPath::~RelativePointPath()
  64735. {
  64736. }
  64737. void RelativePointPath::swapWith (RelativePointPath& other) throw()
  64738. {
  64739. elements.swapWithArray (other.elements);
  64740. swapVariables (usesNonZeroWinding, other.usesNonZeroWinding);
  64741. }
  64742. void RelativePointPath::createPath (Path& path, Expression::EvaluationContext* coordFinder)
  64743. {
  64744. for (int i = 0; i < elements.size(); ++i)
  64745. elements.getUnchecked(i)->addToPath (path, coordFinder);
  64746. }
  64747. bool RelativePointPath::containsAnyDynamicPoints() const
  64748. {
  64749. return containsDynamicPoints;
  64750. }
  64751. RelativePointPath::ElementBase::ElementBase (const ElementType type_) : type (type_)
  64752. {
  64753. }
  64754. RelativePointPath::StartSubPath::StartSubPath (const RelativePoint& pos)
  64755. : ElementBase (startSubPathElement), startPos (pos)
  64756. {
  64757. }
  64758. const ValueTree RelativePointPath::StartSubPath::createTree() const
  64759. {
  64760. ValueTree v (DrawablePath::ValueTreeWrapper::Element::startSubPathElement);
  64761. v.setProperty (DrawablePath::ValueTreeWrapper::point1, startPos.toString(), 0);
  64762. return v;
  64763. }
  64764. void RelativePointPath::StartSubPath::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64765. {
  64766. path.startNewSubPath (startPos.resolve (coordFinder));
  64767. }
  64768. RelativePoint* RelativePointPath::StartSubPath::getControlPoints (int& numPoints)
  64769. {
  64770. numPoints = 1;
  64771. return &startPos;
  64772. }
  64773. RelativePointPath::CloseSubPath::CloseSubPath()
  64774. : ElementBase (closeSubPathElement)
  64775. {
  64776. }
  64777. const ValueTree RelativePointPath::CloseSubPath::createTree() const
  64778. {
  64779. return ValueTree (DrawablePath::ValueTreeWrapper::Element::closeSubPathElement);
  64780. }
  64781. void RelativePointPath::CloseSubPath::addToPath (Path& path, Expression::EvaluationContext*) const
  64782. {
  64783. path.closeSubPath();
  64784. }
  64785. RelativePoint* RelativePointPath::CloseSubPath::getControlPoints (int& numPoints)
  64786. {
  64787. numPoints = 0;
  64788. return 0;
  64789. }
  64790. RelativePointPath::LineTo::LineTo (const RelativePoint& endPoint_)
  64791. : ElementBase (lineToElement), endPoint (endPoint_)
  64792. {
  64793. }
  64794. const ValueTree RelativePointPath::LineTo::createTree() const
  64795. {
  64796. ValueTree v (DrawablePath::ValueTreeWrapper::Element::lineToElement);
  64797. v.setProperty (DrawablePath::ValueTreeWrapper::point1, endPoint.toString(), 0);
  64798. return v;
  64799. }
  64800. void RelativePointPath::LineTo::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64801. {
  64802. path.lineTo (endPoint.resolve (coordFinder));
  64803. }
  64804. RelativePoint* RelativePointPath::LineTo::getControlPoints (int& numPoints)
  64805. {
  64806. numPoints = 1;
  64807. return &endPoint;
  64808. }
  64809. RelativePointPath::QuadraticTo::QuadraticTo (const RelativePoint& controlPoint, const RelativePoint& endPoint)
  64810. : ElementBase (quadraticToElement)
  64811. {
  64812. controlPoints[0] = controlPoint;
  64813. controlPoints[1] = endPoint;
  64814. }
  64815. const ValueTree RelativePointPath::QuadraticTo::createTree() const
  64816. {
  64817. ValueTree v (DrawablePath::ValueTreeWrapper::Element::quadraticToElement);
  64818. v.setProperty (DrawablePath::ValueTreeWrapper::point1, controlPoints[0].toString(), 0);
  64819. v.setProperty (DrawablePath::ValueTreeWrapper::point2, controlPoints[1].toString(), 0);
  64820. return v;
  64821. }
  64822. void RelativePointPath::QuadraticTo::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64823. {
  64824. path.quadraticTo (controlPoints[0].resolve (coordFinder),
  64825. controlPoints[1].resolve (coordFinder));
  64826. }
  64827. RelativePoint* RelativePointPath::QuadraticTo::getControlPoints (int& numPoints)
  64828. {
  64829. numPoints = 2;
  64830. return controlPoints;
  64831. }
  64832. RelativePointPath::CubicTo::CubicTo (const RelativePoint& controlPoint1, const RelativePoint& controlPoint2, const RelativePoint& endPoint)
  64833. : ElementBase (cubicToElement)
  64834. {
  64835. controlPoints[0] = controlPoint1;
  64836. controlPoints[1] = controlPoint2;
  64837. controlPoints[2] = endPoint;
  64838. }
  64839. const ValueTree RelativePointPath::CubicTo::createTree() const
  64840. {
  64841. ValueTree v (DrawablePath::ValueTreeWrapper::Element::cubicToElement);
  64842. v.setProperty (DrawablePath::ValueTreeWrapper::point1, controlPoints[0].toString(), 0);
  64843. v.setProperty (DrawablePath::ValueTreeWrapper::point2, controlPoints[1].toString(), 0);
  64844. v.setProperty (DrawablePath::ValueTreeWrapper::point3, controlPoints[2].toString(), 0);
  64845. return v;
  64846. }
  64847. void RelativePointPath::CubicTo::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64848. {
  64849. path.cubicTo (controlPoints[0].resolve (coordFinder),
  64850. controlPoints[1].resolve (coordFinder),
  64851. controlPoints[2].resolve (coordFinder));
  64852. }
  64853. RelativePoint* RelativePointPath::CubicTo::getControlPoints (int& numPoints)
  64854. {
  64855. numPoints = 3;
  64856. return controlPoints;
  64857. }
  64858. RelativeParallelogram::RelativeParallelogram()
  64859. {
  64860. }
  64861. RelativeParallelogram::RelativeParallelogram (const RelativePoint& topLeft_, const RelativePoint& topRight_, const RelativePoint& bottomLeft_)
  64862. : topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
  64863. {
  64864. }
  64865. RelativeParallelogram::RelativeParallelogram (const String& topLeft_, const String& topRight_, const String& bottomLeft_)
  64866. : topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
  64867. {
  64868. }
  64869. RelativeParallelogram::~RelativeParallelogram()
  64870. {
  64871. }
  64872. void RelativeParallelogram::resolveThreePoints (Point<float>* points, Expression::EvaluationContext* const coordFinder) const
  64873. {
  64874. points[0] = topLeft.resolve (coordFinder);
  64875. points[1] = topRight.resolve (coordFinder);
  64876. points[2] = bottomLeft.resolve (coordFinder);
  64877. }
  64878. void RelativeParallelogram::resolveFourCorners (Point<float>* points, Expression::EvaluationContext* const coordFinder) const
  64879. {
  64880. resolveThreePoints (points, coordFinder);
  64881. points[3] = points[1] + (points[2] - points[0]);
  64882. }
  64883. const Rectangle<float> RelativeParallelogram::getBounds (Expression::EvaluationContext* const coordFinder) const
  64884. {
  64885. Point<float> points[4];
  64886. resolveFourCorners (points, coordFinder);
  64887. return Rectangle<float>::findAreaContainingPoints (points, 4);
  64888. }
  64889. void RelativeParallelogram::getPath (Path& path, Expression::EvaluationContext* const coordFinder) const
  64890. {
  64891. Point<float> points[4];
  64892. resolveFourCorners (points, coordFinder);
  64893. path.startNewSubPath (points[0]);
  64894. path.lineTo (points[1]);
  64895. path.lineTo (points[3]);
  64896. path.lineTo (points[2]);
  64897. path.closeSubPath();
  64898. }
  64899. const AffineTransform RelativeParallelogram::resetToPerpendicular (Expression::EvaluationContext* const coordFinder)
  64900. {
  64901. Point<float> corners[3];
  64902. resolveThreePoints (corners, coordFinder);
  64903. const Line<float> top (corners[0], corners[1]);
  64904. const Line<float> left (corners[0], corners[2]);
  64905. const Point<float> newTopRight (corners[0] + Point<float> (top.getLength(), 0.0f));
  64906. const Point<float> newBottomLeft (corners[0] + Point<float> (0.0f, left.getLength()));
  64907. topRight.moveToAbsolute (newTopRight, coordFinder);
  64908. bottomLeft.moveToAbsolute (newBottomLeft, coordFinder);
  64909. return AffineTransform::fromTargetPoints (corners[0].getX(), corners[0].getY(), corners[0].getX(), corners[0].getY(),
  64910. corners[1].getX(), corners[1].getY(), newTopRight.getX(), newTopRight.getY(),
  64911. corners[2].getX(), corners[2].getY(), newBottomLeft.getX(), newBottomLeft.getY());
  64912. }
  64913. bool RelativeParallelogram::operator== (const RelativeParallelogram& other) const throw()
  64914. {
  64915. return topLeft == other.topLeft && topRight == other.topRight && bottomLeft == other.bottomLeft;
  64916. }
  64917. bool RelativeParallelogram::operator!= (const RelativeParallelogram& other) const throw()
  64918. {
  64919. return ! operator== (other);
  64920. }
  64921. const Point<float> RelativeParallelogram::getInternalCoordForPoint (const Point<float>* const corners, Point<float> target) throw()
  64922. {
  64923. const Point<float> tr (corners[1] - corners[0]);
  64924. const Point<float> bl (corners[2] - corners[0]);
  64925. target -= corners[0];
  64926. return Point<float> (Line<float> (Point<float>(), tr).getIntersection (Line<float> (target, target - bl)).getDistanceFromOrigin(),
  64927. Line<float> (Point<float>(), bl).getIntersection (Line<float> (target, target - tr)).getDistanceFromOrigin());
  64928. }
  64929. const Point<float> RelativeParallelogram::getPointForInternalCoord (const Point<float>* const corners, const Point<float>& point) throw()
  64930. {
  64931. return corners[0]
  64932. + Line<float> (Point<float>(), corners[1] - corners[0]).getPointAlongLine (point.getX())
  64933. + Line<float> (Point<float>(), corners[2] - corners[0]).getPointAlongLine (point.getY());
  64934. }
  64935. END_JUCE_NAMESPACE
  64936. /*** End of inlined file: juce_RelativeCoordinate.cpp ***/
  64937. #endif
  64938. #if JUCE_BUILD_MISC // (put these in misc to balance the file sizes and avoid problems in iphone build)
  64939. /*** Start of inlined file: juce_Colour.cpp ***/
  64940. BEGIN_JUCE_NAMESPACE
  64941. namespace ColourHelpers
  64942. {
  64943. static uint8 floatAlphaToInt (const float alpha) throw()
  64944. {
  64945. return (uint8) jlimit (0, 0xff, roundToInt (alpha * 255.0f));
  64946. }
  64947. static void convertHSBtoRGB (float h, float s, float v,
  64948. uint8& r, uint8& g, uint8& b) throw()
  64949. {
  64950. v = jlimit (0.0f, 1.0f, v);
  64951. v *= 255.0f;
  64952. const uint8 intV = (uint8) roundToInt (v);
  64953. if (s <= 0)
  64954. {
  64955. r = intV;
  64956. g = intV;
  64957. b = intV;
  64958. }
  64959. else
  64960. {
  64961. s = jmin (1.0f, s);
  64962. h = jlimit (0.0f, 1.0f, h);
  64963. h = (h - std::floor (h)) * 6.0f + 0.00001f; // need a small adjustment to compensate for rounding errors
  64964. const float f = h - std::floor (h);
  64965. const uint8 x = (uint8) roundToInt (v * (1.0f - s));
  64966. const float y = v * (1.0f - s * f);
  64967. const float z = v * (1.0f - (s * (1.0f - f)));
  64968. if (h < 1.0f)
  64969. {
  64970. r = intV;
  64971. g = (uint8) roundToInt (z);
  64972. b = x;
  64973. }
  64974. else if (h < 2.0f)
  64975. {
  64976. r = (uint8) roundToInt (y);
  64977. g = intV;
  64978. b = x;
  64979. }
  64980. else if (h < 3.0f)
  64981. {
  64982. r = x;
  64983. g = intV;
  64984. b = (uint8) roundToInt (z);
  64985. }
  64986. else if (h < 4.0f)
  64987. {
  64988. r = x;
  64989. g = (uint8) roundToInt (y);
  64990. b = intV;
  64991. }
  64992. else if (h < 5.0f)
  64993. {
  64994. r = (uint8) roundToInt (z);
  64995. g = x;
  64996. b = intV;
  64997. }
  64998. else if (h < 6.0f)
  64999. {
  65000. r = intV;
  65001. g = x;
  65002. b = (uint8) roundToInt (y);
  65003. }
  65004. else
  65005. {
  65006. r = 0;
  65007. g = 0;
  65008. b = 0;
  65009. }
  65010. }
  65011. }
  65012. }
  65013. Colour::Colour() throw()
  65014. : argb (0)
  65015. {
  65016. }
  65017. Colour::Colour (const Colour& other) throw()
  65018. : argb (other.argb)
  65019. {
  65020. }
  65021. Colour& Colour::operator= (const Colour& other) throw()
  65022. {
  65023. argb = other.argb;
  65024. return *this;
  65025. }
  65026. bool Colour::operator== (const Colour& other) const throw()
  65027. {
  65028. return argb.getARGB() == other.argb.getARGB();
  65029. }
  65030. bool Colour::operator!= (const Colour& other) const throw()
  65031. {
  65032. return argb.getARGB() != other.argb.getARGB();
  65033. }
  65034. Colour::Colour (const uint32 argb_) throw()
  65035. : argb (argb_)
  65036. {
  65037. }
  65038. Colour::Colour (const uint8 red,
  65039. const uint8 green,
  65040. const uint8 blue) throw()
  65041. {
  65042. argb.setARGB (0xff, red, green, blue);
  65043. }
  65044. const Colour Colour::fromRGB (const uint8 red,
  65045. const uint8 green,
  65046. const uint8 blue) throw()
  65047. {
  65048. return Colour (red, green, blue);
  65049. }
  65050. Colour::Colour (const uint8 red,
  65051. const uint8 green,
  65052. const uint8 blue,
  65053. const uint8 alpha) throw()
  65054. {
  65055. argb.setARGB (alpha, red, green, blue);
  65056. }
  65057. const Colour Colour::fromRGBA (const uint8 red,
  65058. const uint8 green,
  65059. const uint8 blue,
  65060. const uint8 alpha) throw()
  65061. {
  65062. return Colour (red, green, blue, alpha);
  65063. }
  65064. Colour::Colour (const uint8 red,
  65065. const uint8 green,
  65066. const uint8 blue,
  65067. const float alpha) throw()
  65068. {
  65069. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), red, green, blue);
  65070. }
  65071. const Colour Colour::fromRGBAFloat (const uint8 red,
  65072. const uint8 green,
  65073. const uint8 blue,
  65074. const float alpha) throw()
  65075. {
  65076. return Colour (red, green, blue, alpha);
  65077. }
  65078. Colour::Colour (const float hue,
  65079. const float saturation,
  65080. const float brightness,
  65081. const float alpha) throw()
  65082. {
  65083. uint8 r = getRed(), g = getGreen(), b = getBlue();
  65084. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  65085. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), r, g, b);
  65086. }
  65087. const Colour Colour::fromHSV (const float hue,
  65088. const float saturation,
  65089. const float brightness,
  65090. const float alpha) throw()
  65091. {
  65092. return Colour (hue, saturation, brightness, alpha);
  65093. }
  65094. Colour::Colour (const float hue,
  65095. const float saturation,
  65096. const float brightness,
  65097. const uint8 alpha) throw()
  65098. {
  65099. uint8 r = getRed(), g = getGreen(), b = getBlue();
  65100. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  65101. argb.setARGB (alpha, r, g, b);
  65102. }
  65103. Colour::~Colour() throw()
  65104. {
  65105. }
  65106. const PixelARGB Colour::getPixelARGB() const throw()
  65107. {
  65108. PixelARGB p (argb);
  65109. p.premultiply();
  65110. return p;
  65111. }
  65112. uint32 Colour::getARGB() const throw()
  65113. {
  65114. return argb.getARGB();
  65115. }
  65116. bool Colour::isTransparent() const throw()
  65117. {
  65118. return getAlpha() == 0;
  65119. }
  65120. bool Colour::isOpaque() const throw()
  65121. {
  65122. return getAlpha() == 0xff;
  65123. }
  65124. const Colour Colour::withAlpha (const uint8 newAlpha) const throw()
  65125. {
  65126. PixelARGB newCol (argb);
  65127. newCol.setAlpha (newAlpha);
  65128. return Colour (newCol.getARGB());
  65129. }
  65130. const Colour Colour::withAlpha (const float newAlpha) const throw()
  65131. {
  65132. jassert (newAlpha >= 0 && newAlpha <= 1.0f);
  65133. PixelARGB newCol (argb);
  65134. newCol.setAlpha (ColourHelpers::floatAlphaToInt (newAlpha));
  65135. return Colour (newCol.getARGB());
  65136. }
  65137. const Colour Colour::withMultipliedAlpha (const float alphaMultiplier) const throw()
  65138. {
  65139. jassert (alphaMultiplier >= 0);
  65140. PixelARGB newCol (argb);
  65141. newCol.setAlpha ((uint8) jmin (0xff, roundToInt (alphaMultiplier * newCol.getAlpha())));
  65142. return Colour (newCol.getARGB());
  65143. }
  65144. const Colour Colour::overlaidWith (const Colour& src) const throw()
  65145. {
  65146. const int destAlpha = getAlpha();
  65147. if (destAlpha > 0)
  65148. {
  65149. const int invA = 0xff - (int) src.getAlpha();
  65150. const int resA = 0xff - (((0xff - destAlpha) * invA) >> 8);
  65151. if (resA > 0)
  65152. {
  65153. const int da = (invA * destAlpha) / resA;
  65154. return Colour ((uint8) (src.getRed() + ((((int) getRed() - src.getRed()) * da) >> 8)),
  65155. (uint8) (src.getGreen() + ((((int) getGreen() - src.getGreen()) * da) >> 8)),
  65156. (uint8) (src.getBlue() + ((((int) getBlue() - src.getBlue()) * da) >> 8)),
  65157. (uint8) resA);
  65158. }
  65159. return *this;
  65160. }
  65161. else
  65162. {
  65163. return src;
  65164. }
  65165. }
  65166. const Colour Colour::interpolatedWith (const Colour& other, float proportionOfOther) const throw()
  65167. {
  65168. if (proportionOfOther <= 0)
  65169. return *this;
  65170. if (proportionOfOther >= 1.0f)
  65171. return other;
  65172. PixelARGB c1 (getPixelARGB());
  65173. const PixelARGB c2 (other.getPixelARGB());
  65174. c1.tween (c2, roundToInt (proportionOfOther * 255.0f));
  65175. c1.unpremultiply();
  65176. return Colour (c1.getARGB());
  65177. }
  65178. float Colour::getFloatRed() const throw()
  65179. {
  65180. return getRed() / 255.0f;
  65181. }
  65182. float Colour::getFloatGreen() const throw()
  65183. {
  65184. return getGreen() / 255.0f;
  65185. }
  65186. float Colour::getFloatBlue() const throw()
  65187. {
  65188. return getBlue() / 255.0f;
  65189. }
  65190. float Colour::getFloatAlpha() const throw()
  65191. {
  65192. return getAlpha() / 255.0f;
  65193. }
  65194. void Colour::getHSB (float& h, float& s, float& v) const throw()
  65195. {
  65196. const int r = getRed();
  65197. const int g = getGreen();
  65198. const int b = getBlue();
  65199. const int hi = jmax (r, g, b);
  65200. const int lo = jmin (r, g, b);
  65201. if (hi != 0)
  65202. {
  65203. s = (hi - lo) / (float) hi;
  65204. if (s != 0)
  65205. {
  65206. const float invDiff = 1.0f / (hi - lo);
  65207. const float red = (hi - r) * invDiff;
  65208. const float green = (hi - g) * invDiff;
  65209. const float blue = (hi - b) * invDiff;
  65210. if (r == hi)
  65211. h = blue - green;
  65212. else if (g == hi)
  65213. h = 2.0f + red - blue;
  65214. else
  65215. h = 4.0f + green - red;
  65216. h *= 1.0f / 6.0f;
  65217. if (h < 0)
  65218. ++h;
  65219. }
  65220. else
  65221. {
  65222. h = 0;
  65223. }
  65224. }
  65225. else
  65226. {
  65227. s = 0;
  65228. h = 0;
  65229. }
  65230. v = hi / 255.0f;
  65231. }
  65232. float Colour::getHue() const throw()
  65233. {
  65234. float h, s, b;
  65235. getHSB (h, s, b);
  65236. return h;
  65237. }
  65238. const Colour Colour::withHue (const float hue) const throw()
  65239. {
  65240. float h, s, b;
  65241. getHSB (h, s, b);
  65242. return Colour (hue, s, b, getAlpha());
  65243. }
  65244. const Colour Colour::withRotatedHue (const float amountToRotate) const throw()
  65245. {
  65246. float h, s, b;
  65247. getHSB (h, s, b);
  65248. h += amountToRotate;
  65249. h -= std::floor (h);
  65250. return Colour (h, s, b, getAlpha());
  65251. }
  65252. float Colour::getSaturation() const throw()
  65253. {
  65254. float h, s, b;
  65255. getHSB (h, s, b);
  65256. return s;
  65257. }
  65258. const Colour Colour::withSaturation (const float saturation) const throw()
  65259. {
  65260. float h, s, b;
  65261. getHSB (h, s, b);
  65262. return Colour (h, saturation, b, getAlpha());
  65263. }
  65264. const Colour Colour::withMultipliedSaturation (const float amount) const throw()
  65265. {
  65266. float h, s, b;
  65267. getHSB (h, s, b);
  65268. return Colour (h, jmin (1.0f, s * amount), b, getAlpha());
  65269. }
  65270. float Colour::getBrightness() const throw()
  65271. {
  65272. float h, s, b;
  65273. getHSB (h, s, b);
  65274. return b;
  65275. }
  65276. const Colour Colour::withBrightness (const float brightness) const throw()
  65277. {
  65278. float h, s, b;
  65279. getHSB (h, s, b);
  65280. return Colour (h, s, brightness, getAlpha());
  65281. }
  65282. const Colour Colour::withMultipliedBrightness (const float amount) const throw()
  65283. {
  65284. float h, s, b;
  65285. getHSB (h, s, b);
  65286. b *= amount;
  65287. if (b > 1.0f)
  65288. b = 1.0f;
  65289. return Colour (h, s, b, getAlpha());
  65290. }
  65291. const Colour Colour::brighter (float amount) const throw()
  65292. {
  65293. amount = 1.0f / (1.0f + amount);
  65294. return Colour ((uint8) (255 - (amount * (255 - getRed()))),
  65295. (uint8) (255 - (amount * (255 - getGreen()))),
  65296. (uint8) (255 - (amount * (255 - getBlue()))),
  65297. getAlpha());
  65298. }
  65299. const Colour Colour::darker (float amount) const throw()
  65300. {
  65301. amount = 1.0f / (1.0f + amount);
  65302. return Colour ((uint8) (amount * getRed()),
  65303. (uint8) (amount * getGreen()),
  65304. (uint8) (amount * getBlue()),
  65305. getAlpha());
  65306. }
  65307. const Colour Colour::greyLevel (const float brightness) throw()
  65308. {
  65309. const uint8 level
  65310. = (uint8) jlimit (0x00, 0xff, roundToInt (brightness * 255.0f));
  65311. return Colour (level, level, level);
  65312. }
  65313. const Colour Colour::contrasting (const float amount) const throw()
  65314. {
  65315. return overlaidWith ((((int) getRed() + (int) getGreen() + (int) getBlue() >= 3 * 128)
  65316. ? Colours::black
  65317. : Colours::white).withAlpha (amount));
  65318. }
  65319. const Colour Colour::contrasting (const Colour& colour1,
  65320. const Colour& colour2) throw()
  65321. {
  65322. const float b1 = colour1.getBrightness();
  65323. const float b2 = colour2.getBrightness();
  65324. float best = 0.0f;
  65325. float bestDist = 0.0f;
  65326. for (float i = 0.0f; i < 1.0f; i += 0.02f)
  65327. {
  65328. const float d1 = std::abs (i - b1);
  65329. const float d2 = std::abs (i - b2);
  65330. const float dist = jmin (d1, d2, 1.0f - d1, 1.0f - d2);
  65331. if (dist > bestDist)
  65332. {
  65333. best = i;
  65334. bestDist = dist;
  65335. }
  65336. }
  65337. return colour1.overlaidWith (colour2.withMultipliedAlpha (0.5f))
  65338. .withBrightness (best);
  65339. }
  65340. const String Colour::toString() const
  65341. {
  65342. return String::toHexString ((int) argb.getARGB());
  65343. }
  65344. const Colour Colour::fromString (const String& encodedColourString)
  65345. {
  65346. return Colour ((uint32) encodedColourString.getHexValue32());
  65347. }
  65348. const String Colour::toDisplayString (const bool includeAlphaValue) const
  65349. {
  65350. return String::toHexString ((int) (argb.getARGB() & (includeAlphaValue ? 0xffffffff : 0xffffff)))
  65351. .paddedLeft ('0', includeAlphaValue ? 8 : 6)
  65352. .toUpperCase();
  65353. }
  65354. END_JUCE_NAMESPACE
  65355. /*** End of inlined file: juce_Colour.cpp ***/
  65356. /*** Start of inlined file: juce_ColourGradient.cpp ***/
  65357. BEGIN_JUCE_NAMESPACE
  65358. ColourGradient::ColourGradient() throw()
  65359. {
  65360. #if JUCE_DEBUG
  65361. point1.setX (987654.0f);
  65362. #endif
  65363. }
  65364. ColourGradient::ColourGradient (const Colour& colour1, const float x1_, const float y1_,
  65365. const Colour& colour2, const float x2_, const float y2_,
  65366. const bool isRadial_)
  65367. : point1 (x1_, y1_),
  65368. point2 (x2_, y2_),
  65369. isRadial (isRadial_)
  65370. {
  65371. colours.add (ColourPoint (0.0, colour1));
  65372. colours.add (ColourPoint (1.0, colour2));
  65373. }
  65374. ColourGradient::~ColourGradient()
  65375. {
  65376. }
  65377. bool ColourGradient::operator== (const ColourGradient& other) const throw()
  65378. {
  65379. return point1 == other.point1 && point2 == other.point2
  65380. && isRadial == other.isRadial
  65381. && colours == other.colours;
  65382. }
  65383. bool ColourGradient::operator!= (const ColourGradient& other) const throw()
  65384. {
  65385. return ! operator== (other);
  65386. }
  65387. void ColourGradient::clearColours()
  65388. {
  65389. colours.clear();
  65390. }
  65391. int ColourGradient::addColour (const double proportionAlongGradient, const Colour& colour)
  65392. {
  65393. // must be within the two end-points
  65394. jassert (proportionAlongGradient >= 0 && proportionAlongGradient <= 1.0);
  65395. const double pos = jlimit (0.0, 1.0, proportionAlongGradient);
  65396. int i;
  65397. for (i = 0; i < colours.size(); ++i)
  65398. if (colours.getReference(i).position > pos)
  65399. break;
  65400. colours.insert (i, ColourPoint (pos, colour));
  65401. return i;
  65402. }
  65403. void ColourGradient::removeColour (int index)
  65404. {
  65405. jassert (index > 0 && index < colours.size() - 1);
  65406. colours.remove (index);
  65407. }
  65408. void ColourGradient::multiplyOpacity (const float multiplier) throw()
  65409. {
  65410. for (int i = 0; i < colours.size(); ++i)
  65411. {
  65412. Colour& c = colours.getReference(i).colour;
  65413. c = c.withMultipliedAlpha (multiplier);
  65414. }
  65415. }
  65416. int ColourGradient::getNumColours() const throw()
  65417. {
  65418. return colours.size();
  65419. }
  65420. double ColourGradient::getColourPosition (const int index) const throw()
  65421. {
  65422. if (((unsigned int) index) < (unsigned int) colours.size())
  65423. return colours.getReference (index).position;
  65424. return 0;
  65425. }
  65426. const Colour ColourGradient::getColour (const int index) const throw()
  65427. {
  65428. if (((unsigned int) index) < (unsigned int) colours.size())
  65429. return colours.getReference (index).colour;
  65430. return Colour();
  65431. }
  65432. void ColourGradient::setColour (int index, const Colour& newColour) throw()
  65433. {
  65434. if (((unsigned int) index) < (unsigned int) colours.size())
  65435. colours.getReference (index).colour = newColour;
  65436. }
  65437. const Colour ColourGradient::getColourAtPosition (const double position) const throw()
  65438. {
  65439. jassert (colours.getReference(0).position == 0); // the first colour specified has to go at position 0
  65440. if (position <= 0 || colours.size() <= 1)
  65441. return colours.getReference(0).colour;
  65442. int i = colours.size() - 1;
  65443. while (position < colours.getReference(i).position)
  65444. --i;
  65445. const ColourPoint& p1 = colours.getReference (i);
  65446. if (i >= colours.size() - 1)
  65447. return p1.colour;
  65448. const ColourPoint& p2 = colours.getReference (i + 1);
  65449. return p1.colour.interpolatedWith (p2.colour, (float) ((position - p1.position) / (p2.position - p1.position)));
  65450. }
  65451. int ColourGradient::createLookupTable (const AffineTransform& transform, HeapBlock <PixelARGB>& lookupTable) const
  65452. {
  65453. #if JUCE_DEBUG
  65454. // trying to use the object without setting its co-ordinates? Have a careful read of
  65455. // the comments for the constructors.
  65456. jassert (point1.getX() != 987654.0f);
  65457. #endif
  65458. const int numEntries = jlimit (1, jmax (1, (colours.size() - 1) << 8),
  65459. 3 * (int) point1.transformedBy (transform)
  65460. .getDistanceFrom (point2.transformedBy (transform)));
  65461. lookupTable.malloc (numEntries);
  65462. if (colours.size() >= 2)
  65463. {
  65464. jassert (colours.getReference(0).position == 0); // the first colour specified has to go at position 0
  65465. PixelARGB pix1 (colours.getReference (0).colour.getPixelARGB());
  65466. int index = 0;
  65467. for (int j = 1; j < colours.size(); ++j)
  65468. {
  65469. const ColourPoint& p = colours.getReference (j);
  65470. const int numToDo = roundToInt (p.position * (numEntries - 1)) - index;
  65471. const PixelARGB pix2 (p.colour.getPixelARGB());
  65472. for (int i = 0; i < numToDo; ++i)
  65473. {
  65474. jassert (index >= 0 && index < numEntries);
  65475. lookupTable[index] = pix1;
  65476. lookupTable[index].tween (pix2, (i << 8) / numToDo);
  65477. ++index;
  65478. }
  65479. pix1 = pix2;
  65480. }
  65481. while (index < numEntries)
  65482. lookupTable [index++] = pix1;
  65483. }
  65484. else
  65485. {
  65486. jassertfalse; // no colours specified!
  65487. }
  65488. return numEntries;
  65489. }
  65490. bool ColourGradient::isOpaque() const throw()
  65491. {
  65492. for (int i = 0; i < colours.size(); ++i)
  65493. if (! colours.getReference(i).colour.isOpaque())
  65494. return false;
  65495. return true;
  65496. }
  65497. bool ColourGradient::isInvisible() const throw()
  65498. {
  65499. for (int i = 0; i < colours.size(); ++i)
  65500. if (! colours.getReference(i).colour.isTransparent())
  65501. return false;
  65502. return true;
  65503. }
  65504. END_JUCE_NAMESPACE
  65505. /*** End of inlined file: juce_ColourGradient.cpp ***/
  65506. /*** Start of inlined file: juce_Colours.cpp ***/
  65507. BEGIN_JUCE_NAMESPACE
  65508. const Colour Colours::transparentBlack (0);
  65509. const Colour Colours::transparentWhite (0x00ffffff);
  65510. const Colour Colours::aliceblue (0xfff0f8ff);
  65511. const Colour Colours::antiquewhite (0xfffaebd7);
  65512. const Colour Colours::aqua (0xff00ffff);
  65513. const Colour Colours::aquamarine (0xff7fffd4);
  65514. const Colour Colours::azure (0xfff0ffff);
  65515. const Colour Colours::beige (0xfff5f5dc);
  65516. const Colour Colours::bisque (0xffffe4c4);
  65517. const Colour Colours::black (0xff000000);
  65518. const Colour Colours::blanchedalmond (0xffffebcd);
  65519. const Colour Colours::blue (0xff0000ff);
  65520. const Colour Colours::blueviolet (0xff8a2be2);
  65521. const Colour Colours::brown (0xffa52a2a);
  65522. const Colour Colours::burlywood (0xffdeb887);
  65523. const Colour Colours::cadetblue (0xff5f9ea0);
  65524. const Colour Colours::chartreuse (0xff7fff00);
  65525. const Colour Colours::chocolate (0xffd2691e);
  65526. const Colour Colours::coral (0xffff7f50);
  65527. const Colour Colours::cornflowerblue (0xff6495ed);
  65528. const Colour Colours::cornsilk (0xfffff8dc);
  65529. const Colour Colours::crimson (0xffdc143c);
  65530. const Colour Colours::cyan (0xff00ffff);
  65531. const Colour Colours::darkblue (0xff00008b);
  65532. const Colour Colours::darkcyan (0xff008b8b);
  65533. const Colour Colours::darkgoldenrod (0xffb8860b);
  65534. const Colour Colours::darkgrey (0xff555555);
  65535. const Colour Colours::darkgreen (0xff006400);
  65536. const Colour Colours::darkkhaki (0xffbdb76b);
  65537. const Colour Colours::darkmagenta (0xff8b008b);
  65538. const Colour Colours::darkolivegreen (0xff556b2f);
  65539. const Colour Colours::darkorange (0xffff8c00);
  65540. const Colour Colours::darkorchid (0xff9932cc);
  65541. const Colour Colours::darkred (0xff8b0000);
  65542. const Colour Colours::darksalmon (0xffe9967a);
  65543. const Colour Colours::darkseagreen (0xff8fbc8f);
  65544. const Colour Colours::darkslateblue (0xff483d8b);
  65545. const Colour Colours::darkslategrey (0xff2f4f4f);
  65546. const Colour Colours::darkturquoise (0xff00ced1);
  65547. const Colour Colours::darkviolet (0xff9400d3);
  65548. const Colour Colours::deeppink (0xffff1493);
  65549. const Colour Colours::deepskyblue (0xff00bfff);
  65550. const Colour Colours::dimgrey (0xff696969);
  65551. const Colour Colours::dodgerblue (0xff1e90ff);
  65552. const Colour Colours::firebrick (0xffb22222);
  65553. const Colour Colours::floralwhite (0xfffffaf0);
  65554. const Colour Colours::forestgreen (0xff228b22);
  65555. const Colour Colours::fuchsia (0xffff00ff);
  65556. const Colour Colours::gainsboro (0xffdcdcdc);
  65557. const Colour Colours::gold (0xffffd700);
  65558. const Colour Colours::goldenrod (0xffdaa520);
  65559. const Colour Colours::grey (0xff808080);
  65560. const Colour Colours::green (0xff008000);
  65561. const Colour Colours::greenyellow (0xffadff2f);
  65562. const Colour Colours::honeydew (0xfff0fff0);
  65563. const Colour Colours::hotpink (0xffff69b4);
  65564. const Colour Colours::indianred (0xffcd5c5c);
  65565. const Colour Colours::indigo (0xff4b0082);
  65566. const Colour Colours::ivory (0xfffffff0);
  65567. const Colour Colours::khaki (0xfff0e68c);
  65568. const Colour Colours::lavender (0xffe6e6fa);
  65569. const Colour Colours::lavenderblush (0xfffff0f5);
  65570. const Colour Colours::lemonchiffon (0xfffffacd);
  65571. const Colour Colours::lightblue (0xffadd8e6);
  65572. const Colour Colours::lightcoral (0xfff08080);
  65573. const Colour Colours::lightcyan (0xffe0ffff);
  65574. const Colour Colours::lightgoldenrodyellow (0xfffafad2);
  65575. const Colour Colours::lightgreen (0xff90ee90);
  65576. const Colour Colours::lightgrey (0xffd3d3d3);
  65577. const Colour Colours::lightpink (0xffffb6c1);
  65578. const Colour Colours::lightsalmon (0xffffa07a);
  65579. const Colour Colours::lightseagreen (0xff20b2aa);
  65580. const Colour Colours::lightskyblue (0xff87cefa);
  65581. const Colour Colours::lightslategrey (0xff778899);
  65582. const Colour Colours::lightsteelblue (0xffb0c4de);
  65583. const Colour Colours::lightyellow (0xffffffe0);
  65584. const Colour Colours::lime (0xff00ff00);
  65585. const Colour Colours::limegreen (0xff32cd32);
  65586. const Colour Colours::linen (0xfffaf0e6);
  65587. const Colour Colours::magenta (0xffff00ff);
  65588. const Colour Colours::maroon (0xff800000);
  65589. const Colour Colours::mediumaquamarine (0xff66cdaa);
  65590. const Colour Colours::mediumblue (0xff0000cd);
  65591. const Colour Colours::mediumorchid (0xffba55d3);
  65592. const Colour Colours::mediumpurple (0xff9370db);
  65593. const Colour Colours::mediumseagreen (0xff3cb371);
  65594. const Colour Colours::mediumslateblue (0xff7b68ee);
  65595. const Colour Colours::mediumspringgreen (0xff00fa9a);
  65596. const Colour Colours::mediumturquoise (0xff48d1cc);
  65597. const Colour Colours::mediumvioletred (0xffc71585);
  65598. const Colour Colours::midnightblue (0xff191970);
  65599. const Colour Colours::mintcream (0xfff5fffa);
  65600. const Colour Colours::mistyrose (0xffffe4e1);
  65601. const Colour Colours::navajowhite (0xffffdead);
  65602. const Colour Colours::navy (0xff000080);
  65603. const Colour Colours::oldlace (0xfffdf5e6);
  65604. const Colour Colours::olive (0xff808000);
  65605. const Colour Colours::olivedrab (0xff6b8e23);
  65606. const Colour Colours::orange (0xffffa500);
  65607. const Colour Colours::orangered (0xffff4500);
  65608. const Colour Colours::orchid (0xffda70d6);
  65609. const Colour Colours::palegoldenrod (0xffeee8aa);
  65610. const Colour Colours::palegreen (0xff98fb98);
  65611. const Colour Colours::paleturquoise (0xffafeeee);
  65612. const Colour Colours::palevioletred (0xffdb7093);
  65613. const Colour Colours::papayawhip (0xffffefd5);
  65614. const Colour Colours::peachpuff (0xffffdab9);
  65615. const Colour Colours::peru (0xffcd853f);
  65616. const Colour Colours::pink (0xffffc0cb);
  65617. const Colour Colours::plum (0xffdda0dd);
  65618. const Colour Colours::powderblue (0xffb0e0e6);
  65619. const Colour Colours::purple (0xff800080);
  65620. const Colour Colours::red (0xffff0000);
  65621. const Colour Colours::rosybrown (0xffbc8f8f);
  65622. const Colour Colours::royalblue (0xff4169e1);
  65623. const Colour Colours::saddlebrown (0xff8b4513);
  65624. const Colour Colours::salmon (0xfffa8072);
  65625. const Colour Colours::sandybrown (0xfff4a460);
  65626. const Colour Colours::seagreen (0xff2e8b57);
  65627. const Colour Colours::seashell (0xfffff5ee);
  65628. const Colour Colours::sienna (0xffa0522d);
  65629. const Colour Colours::silver (0xffc0c0c0);
  65630. const Colour Colours::skyblue (0xff87ceeb);
  65631. const Colour Colours::slateblue (0xff6a5acd);
  65632. const Colour Colours::slategrey (0xff708090);
  65633. const Colour Colours::snow (0xfffffafa);
  65634. const Colour Colours::springgreen (0xff00ff7f);
  65635. const Colour Colours::steelblue (0xff4682b4);
  65636. const Colour Colours::tan (0xffd2b48c);
  65637. const Colour Colours::teal (0xff008080);
  65638. const Colour Colours::thistle (0xffd8bfd8);
  65639. const Colour Colours::tomato (0xffff6347);
  65640. const Colour Colours::turquoise (0xff40e0d0);
  65641. const Colour Colours::violet (0xffee82ee);
  65642. const Colour Colours::wheat (0xfff5deb3);
  65643. const Colour Colours::white (0xffffffff);
  65644. const Colour Colours::whitesmoke (0xfff5f5f5);
  65645. const Colour Colours::yellow (0xffffff00);
  65646. const Colour Colours::yellowgreen (0xff9acd32);
  65647. const Colour Colours::findColourForName (const String& colourName,
  65648. const Colour& defaultColour)
  65649. {
  65650. static const int presets[] =
  65651. {
  65652. // (first value is the string's hashcode, second is ARGB)
  65653. 0x05978fff, 0xff000000, /* black */
  65654. 0x06bdcc29, 0xffffffff, /* white */
  65655. 0x002e305a, 0xff0000ff, /* blue */
  65656. 0x00308adf, 0xff808080, /* grey */
  65657. 0x05e0cf03, 0xff008000, /* green */
  65658. 0x0001b891, 0xffff0000, /* red */
  65659. 0xd43c6474, 0xffffff00, /* yellow */
  65660. 0x620886da, 0xfff0f8ff, /* aliceblue */
  65661. 0x20a2676a, 0xfffaebd7, /* antiquewhite */
  65662. 0x002dcebc, 0xff00ffff, /* aqua */
  65663. 0x46bb5f7e, 0xff7fffd4, /* aquamarine */
  65664. 0x0590228f, 0xfff0ffff, /* azure */
  65665. 0x05947fe4, 0xfff5f5dc, /* beige */
  65666. 0xad388e35, 0xffffe4c4, /* bisque */
  65667. 0x00674f7e, 0xffffebcd, /* blanchedalmond */
  65668. 0x39129959, 0xff8a2be2, /* blueviolet */
  65669. 0x059a8136, 0xffa52a2a, /* brown */
  65670. 0x89cea8f9, 0xffdeb887, /* burlywood */
  65671. 0x0fa260cf, 0xff5f9ea0, /* cadetblue */
  65672. 0x6b748956, 0xff7fff00, /* chartreuse */
  65673. 0x2903623c, 0xffd2691e, /* chocolate */
  65674. 0x05a74431, 0xffff7f50, /* coral */
  65675. 0x618d42dd, 0xff6495ed, /* cornflowerblue */
  65676. 0xe4b479fd, 0xfffff8dc, /* cornsilk */
  65677. 0x3d8c4edf, 0xffdc143c, /* crimson */
  65678. 0x002ed323, 0xff00ffff, /* cyan */
  65679. 0x67cc74d0, 0xff00008b, /* darkblue */
  65680. 0x67cd1799, 0xff008b8b, /* darkcyan */
  65681. 0x31bbd168, 0xffb8860b, /* darkgoldenrod */
  65682. 0x67cecf55, 0xff555555, /* darkgrey */
  65683. 0x920b194d, 0xff006400, /* darkgreen */
  65684. 0x923edd4c, 0xffbdb76b, /* darkkhaki */
  65685. 0x5c293873, 0xff8b008b, /* darkmagenta */
  65686. 0x6b6671fe, 0xff556b2f, /* darkolivegreen */
  65687. 0xbcfd2524, 0xffff8c00, /* darkorange */
  65688. 0xbcfdf799, 0xff9932cc, /* darkorchid */
  65689. 0x55ee0d5b, 0xff8b0000, /* darkred */
  65690. 0xc2e5f564, 0xffe9967a, /* darksalmon */
  65691. 0x61be858a, 0xff8fbc8f, /* darkseagreen */
  65692. 0xc2b0f2bd, 0xff483d8b, /* darkslateblue */
  65693. 0xc2b34d42, 0xff2f4f4f, /* darkslategrey */
  65694. 0x7cf2b06b, 0xff00ced1, /* darkturquoise */
  65695. 0xc8769375, 0xff9400d3, /* darkviolet */
  65696. 0x25832862, 0xffff1493, /* deeppink */
  65697. 0xfcad568f, 0xff00bfff, /* deepskyblue */
  65698. 0x634c8b67, 0xff696969, /* dimgrey */
  65699. 0x45c1ce55, 0xff1e90ff, /* dodgerblue */
  65700. 0xef19e3cb, 0xffb22222, /* firebrick */
  65701. 0xb852b195, 0xfffffaf0, /* floralwhite */
  65702. 0xd086fd06, 0xff228b22, /* forestgreen */
  65703. 0xe106b6d7, 0xffff00ff, /* fuchsia */
  65704. 0x7880d61e, 0xffdcdcdc, /* gainsboro */
  65705. 0x00308060, 0xffffd700, /* gold */
  65706. 0xb3b3bc1e, 0xffdaa520, /* goldenrod */
  65707. 0xbab8a537, 0xffadff2f, /* greenyellow */
  65708. 0xe4cacafb, 0xfff0fff0, /* honeydew */
  65709. 0x41892743, 0xffff69b4, /* hotpink */
  65710. 0xd5796f1a, 0xffcd5c5c, /* indianred */
  65711. 0xb969fed2, 0xff4b0082, /* indigo */
  65712. 0x05fef6a9, 0xfffffff0, /* ivory */
  65713. 0x06149302, 0xfff0e68c, /* khaki */
  65714. 0xad5a05c7, 0xffe6e6fa, /* lavender */
  65715. 0x7c4d5b99, 0xfffff0f5, /* lavenderblush */
  65716. 0x195756f0, 0xfffffacd, /* lemonchiffon */
  65717. 0x28e4ea70, 0xffadd8e6, /* lightblue */
  65718. 0xf3c7ccdb, 0xfff08080, /* lightcoral */
  65719. 0x28e58d39, 0xffe0ffff, /* lightcyan */
  65720. 0x21234e3c, 0xfffafad2, /* lightgoldenrodyellow */
  65721. 0xf40157ad, 0xff90ee90, /* lightgreen */
  65722. 0x28e744f5, 0xffd3d3d3, /* lightgrey */
  65723. 0x28eb3b8c, 0xffffb6c1, /* lightpink */
  65724. 0x9fb78304, 0xffffa07a, /* lightsalmon */
  65725. 0x50632b2a, 0xff20b2aa, /* lightseagreen */
  65726. 0x68fb7b25, 0xff87cefa, /* lightskyblue */
  65727. 0xa8a35ba2, 0xff778899, /* lightslategrey */
  65728. 0xa20d484f, 0xffb0c4de, /* lightsteelblue */
  65729. 0xaa2cf10a, 0xffffffe0, /* lightyellow */
  65730. 0x0032afd5, 0xff00ff00, /* lime */
  65731. 0x607bbc4e, 0xff32cd32, /* limegreen */
  65732. 0x06234efa, 0xfffaf0e6, /* linen */
  65733. 0x316858a9, 0xffff00ff, /* magenta */
  65734. 0xbf8ca470, 0xff800000, /* maroon */
  65735. 0xbd58e0b3, 0xff66cdaa, /* mediumaquamarine */
  65736. 0x967dfd4f, 0xff0000cd, /* mediumblue */
  65737. 0x056f5c58, 0xffba55d3, /* mediumorchid */
  65738. 0x07556b71, 0xff9370db, /* mediumpurple */
  65739. 0x5369b689, 0xff3cb371, /* mediumseagreen */
  65740. 0x066be19e, 0xff7b68ee, /* mediumslateblue */
  65741. 0x3256b281, 0xff00fa9a, /* mediumspringgreen */
  65742. 0xc0ad9f4c, 0xff48d1cc, /* mediumturquoise */
  65743. 0x628e63dd, 0xffc71585, /* mediumvioletred */
  65744. 0x168eb32a, 0xff191970, /* midnightblue */
  65745. 0x4306b960, 0xfff5fffa, /* mintcream */
  65746. 0x4cbc0e6b, 0xffffe4e1, /* mistyrose */
  65747. 0xe97218a6, 0xffffdead, /* navajowhite */
  65748. 0x00337bb6, 0xff000080, /* navy */
  65749. 0xadd2d33e, 0xfffdf5e6, /* oldlace */
  65750. 0x064ee1db, 0xff808000, /* olive */
  65751. 0x9e33a98a, 0xff6b8e23, /* olivedrab */
  65752. 0xc3de262e, 0xffffa500, /* orange */
  65753. 0x58bebba3, 0xffff4500, /* orangered */
  65754. 0xc3def8a3, 0xffda70d6, /* orchid */
  65755. 0x28cb4834, 0xffeee8aa, /* palegoldenrod */
  65756. 0x3d9dd619, 0xff98fb98, /* palegreen */
  65757. 0x74022737, 0xffafeeee, /* paleturquoise */
  65758. 0x15e2ebc8, 0xffdb7093, /* palevioletred */
  65759. 0x5fd898e2, 0xffffefd5, /* papayawhip */
  65760. 0x93e1b776, 0xffffdab9, /* peachpuff */
  65761. 0x003472f8, 0xffcd853f, /* peru */
  65762. 0x00348176, 0xffffc0cb, /* pink */
  65763. 0x00348d94, 0xffdda0dd, /* plum */
  65764. 0xd036be93, 0xffb0e0e6, /* powderblue */
  65765. 0xc5c507bc, 0xff800080, /* purple */
  65766. 0xa89d65b3, 0xffbc8f8f, /* rosybrown */
  65767. 0xbd9413e1, 0xff4169e1, /* royalblue */
  65768. 0xf456044f, 0xff8b4513, /* saddlebrown */
  65769. 0xc9c6f66e, 0xfffa8072, /* salmon */
  65770. 0x0bb131e1, 0xfff4a460, /* sandybrown */
  65771. 0x34636c14, 0xff2e8b57, /* seagreen */
  65772. 0x3507fb41, 0xfffff5ee, /* seashell */
  65773. 0xca348772, 0xffa0522d, /* sienna */
  65774. 0xca37d30d, 0xffc0c0c0, /* silver */
  65775. 0x80da74fb, 0xff87ceeb, /* skyblue */
  65776. 0x44a8dd73, 0xff6a5acd, /* slateblue */
  65777. 0x44ab37f8, 0xff708090, /* slategrey */
  65778. 0x0035f183, 0xfffffafa, /* snow */
  65779. 0xd5440d16, 0xff00ff7f, /* springgreen */
  65780. 0x3e1524a5, 0xff4682b4, /* steelblue */
  65781. 0x0001bfa1, 0xffd2b48c, /* tan */
  65782. 0x0036425c, 0xff008080, /* teal */
  65783. 0xafc8858f, 0xffd8bfd8, /* thistle */
  65784. 0xcc41600a, 0xffff6347, /* tomato */
  65785. 0xfeea9b21, 0xff40e0d0, /* turquoise */
  65786. 0xcf57947f, 0xffee82ee, /* violet */
  65787. 0x06bdbae7, 0xfff5deb3, /* wheat */
  65788. 0x10802ee6, 0xfff5f5f5, /* whitesmoke */
  65789. 0xe1b5130f, 0xff9acd32 /* yellowgreen */
  65790. };
  65791. const int hash = colourName.trim().toLowerCase().hashCode();
  65792. for (int i = 0; i < numElementsInArray (presets); i += 2)
  65793. if (presets [i] == hash)
  65794. return Colour (presets [i + 1]);
  65795. return defaultColour;
  65796. }
  65797. END_JUCE_NAMESPACE
  65798. /*** End of inlined file: juce_Colours.cpp ***/
  65799. /*** Start of inlined file: juce_EdgeTable.cpp ***/
  65800. BEGIN_JUCE_NAMESPACE
  65801. const int juce_edgeTableDefaultEdgesPerLine = 32;
  65802. EdgeTable::EdgeTable (const Rectangle<int>& bounds_,
  65803. const Path& path, const AffineTransform& transform)
  65804. : bounds (bounds_),
  65805. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65806. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65807. needToCheckEmptinesss (true)
  65808. {
  65809. table.malloc ((bounds.getHeight() + 1) * lineStrideElements);
  65810. int* t = table;
  65811. for (int i = bounds.getHeight(); --i >= 0;)
  65812. {
  65813. *t = 0;
  65814. t += lineStrideElements;
  65815. }
  65816. const int topLimit = bounds.getY() << 8;
  65817. const int heightLimit = bounds.getHeight() << 8;
  65818. const int leftLimit = bounds.getX() << 8;
  65819. const int rightLimit = bounds.getRight() << 8;
  65820. PathFlatteningIterator iter (path, transform);
  65821. while (iter.next())
  65822. {
  65823. int y1 = roundToInt (iter.y1 * 256.0f);
  65824. int y2 = roundToInt (iter.y2 * 256.0f);
  65825. if (y1 != y2)
  65826. {
  65827. y1 -= topLimit;
  65828. y2 -= topLimit;
  65829. const int startY = y1;
  65830. int direction = -1;
  65831. if (y1 > y2)
  65832. {
  65833. swapVariables (y1, y2);
  65834. direction = 1;
  65835. }
  65836. if (y1 < 0)
  65837. y1 = 0;
  65838. if (y2 > heightLimit)
  65839. y2 = heightLimit;
  65840. if (y1 < y2)
  65841. {
  65842. const double startX = 256.0f * iter.x1;
  65843. const double multiplier = (iter.x2 - iter.x1) / (iter.y2 - iter.y1);
  65844. const int stepSize = jlimit (1, 256, 256 / (1 + (int) std::abs (multiplier)));
  65845. do
  65846. {
  65847. const int step = jmin (stepSize, y2 - y1, 256 - (y1 & 255));
  65848. int x = roundToInt (startX + multiplier * ((y1 + (step >> 1)) - startY));
  65849. if (x < leftLimit)
  65850. x = leftLimit;
  65851. else if (x >= rightLimit)
  65852. x = rightLimit - 1;
  65853. addEdgePoint (x, y1 >> 8, direction * step);
  65854. y1 += step;
  65855. }
  65856. while (y1 < y2);
  65857. }
  65858. }
  65859. }
  65860. sanitiseLevels (path.isUsingNonZeroWinding());
  65861. }
  65862. EdgeTable::EdgeTable (const Rectangle<int>& rectangleToAdd)
  65863. : bounds (rectangleToAdd),
  65864. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65865. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65866. needToCheckEmptinesss (true)
  65867. {
  65868. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65869. table[0] = 0;
  65870. const int x1 = rectangleToAdd.getX() << 8;
  65871. const int x2 = rectangleToAdd.getRight() << 8;
  65872. int* t = table;
  65873. for (int i = rectangleToAdd.getHeight(); --i >= 0;)
  65874. {
  65875. t[0] = 2;
  65876. t[1] = x1;
  65877. t[2] = 255;
  65878. t[3] = x2;
  65879. t[4] = 0;
  65880. t += lineStrideElements;
  65881. }
  65882. }
  65883. EdgeTable::EdgeTable (const RectangleList& rectanglesToAdd)
  65884. : bounds (rectanglesToAdd.getBounds()),
  65885. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65886. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65887. needToCheckEmptinesss (true)
  65888. {
  65889. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65890. int* t = table;
  65891. for (int i = bounds.getHeight(); --i >= 0;)
  65892. {
  65893. *t = 0;
  65894. t += lineStrideElements;
  65895. }
  65896. for (RectangleList::Iterator iter (rectanglesToAdd); iter.next();)
  65897. {
  65898. const Rectangle<int>* const r = iter.getRectangle();
  65899. const int x1 = r->getX() << 8;
  65900. const int x2 = r->getRight() << 8;
  65901. int y = r->getY() - bounds.getY();
  65902. for (int j = r->getHeight(); --j >= 0;)
  65903. {
  65904. addEdgePoint (x1, y, 255);
  65905. addEdgePoint (x2, y, -255);
  65906. ++y;
  65907. }
  65908. }
  65909. sanitiseLevels (true);
  65910. }
  65911. EdgeTable::EdgeTable (const Rectangle<float>& rectangleToAdd)
  65912. : bounds (Rectangle<int> ((int) std::floor (rectangleToAdd.getX()),
  65913. roundToInt (rectangleToAdd.getY() * 256.0f) >> 8,
  65914. 2 + (int) rectangleToAdd.getWidth(),
  65915. 2 + (int) rectangleToAdd.getHeight())),
  65916. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65917. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65918. needToCheckEmptinesss (true)
  65919. {
  65920. jassert (! rectangleToAdd.isEmpty());
  65921. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65922. table[0] = 0;
  65923. const int x1 = roundToInt (rectangleToAdd.getX() * 256.0f);
  65924. const int x2 = roundToInt (rectangleToAdd.getRight() * 256.0f);
  65925. int y1 = roundToInt (rectangleToAdd.getY() * 256.0f) - (bounds.getY() << 8);
  65926. jassert (y1 < 256);
  65927. int y2 = roundToInt (rectangleToAdd.getBottom() * 256.0f) - (bounds.getY() << 8);
  65928. if (x2 <= x1 || y2 <= y1)
  65929. {
  65930. bounds.setHeight (0);
  65931. return;
  65932. }
  65933. int lineY = 0;
  65934. int* t = table;
  65935. if ((y1 >> 8) == (y2 >> 8))
  65936. {
  65937. t[0] = 2;
  65938. t[1] = x1;
  65939. t[2] = y2 - y1;
  65940. t[3] = x2;
  65941. t[4] = 0;
  65942. ++lineY;
  65943. t += lineStrideElements;
  65944. }
  65945. else
  65946. {
  65947. t[0] = 2;
  65948. t[1] = x1;
  65949. t[2] = 255 - (y1 & 255);
  65950. t[3] = x2;
  65951. t[4] = 0;
  65952. ++lineY;
  65953. t += lineStrideElements;
  65954. while (lineY < (y2 >> 8))
  65955. {
  65956. t[0] = 2;
  65957. t[1] = x1;
  65958. t[2] = 255;
  65959. t[3] = x2;
  65960. t[4] = 0;
  65961. ++lineY;
  65962. t += lineStrideElements;
  65963. }
  65964. jassert (lineY < bounds.getHeight());
  65965. t[0] = 2;
  65966. t[1] = x1;
  65967. t[2] = y2 & 255;
  65968. t[3] = x2;
  65969. t[4] = 0;
  65970. ++lineY;
  65971. t += lineStrideElements;
  65972. }
  65973. while (lineY < bounds.getHeight())
  65974. {
  65975. t[0] = 0;
  65976. t += lineStrideElements;
  65977. ++lineY;
  65978. }
  65979. }
  65980. EdgeTable::EdgeTable (const EdgeTable& other)
  65981. {
  65982. operator= (other);
  65983. }
  65984. EdgeTable& EdgeTable::operator= (const EdgeTable& other)
  65985. {
  65986. bounds = other.bounds;
  65987. maxEdgesPerLine = other.maxEdgesPerLine;
  65988. lineStrideElements = other.lineStrideElements;
  65989. needToCheckEmptinesss = other.needToCheckEmptinesss;
  65990. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65991. copyEdgeTableData (table, lineStrideElements, other.table, lineStrideElements, bounds.getHeight());
  65992. return *this;
  65993. }
  65994. EdgeTable::~EdgeTable()
  65995. {
  65996. }
  65997. void EdgeTable::copyEdgeTableData (int* dest, const int destLineStride, const int* src, const int srcLineStride, int numLines) throw()
  65998. {
  65999. while (--numLines >= 0)
  66000. {
  66001. memcpy (dest, src, (src[0] * 2 + 1) * sizeof (int));
  66002. src += srcLineStride;
  66003. dest += destLineStride;
  66004. }
  66005. }
  66006. void EdgeTable::sanitiseLevels (const bool useNonZeroWinding) throw()
  66007. {
  66008. // Convert the table from relative windings to absolute levels..
  66009. int* lineStart = table;
  66010. for (int i = bounds.getHeight(); --i >= 0;)
  66011. {
  66012. int* line = lineStart;
  66013. lineStart += lineStrideElements;
  66014. int num = *line;
  66015. if (num == 0)
  66016. continue;
  66017. int level = 0;
  66018. if (useNonZeroWinding)
  66019. {
  66020. while (--num > 0)
  66021. {
  66022. line += 2;
  66023. level += *line;
  66024. int corrected = abs (level);
  66025. if (corrected >> 8)
  66026. corrected = 255;
  66027. *line = corrected;
  66028. }
  66029. }
  66030. else
  66031. {
  66032. while (--num > 0)
  66033. {
  66034. line += 2;
  66035. level += *line;
  66036. int corrected = abs (level);
  66037. if (corrected >> 8)
  66038. {
  66039. corrected &= 511;
  66040. if (corrected >> 8)
  66041. corrected = 511 - corrected;
  66042. }
  66043. *line = corrected;
  66044. }
  66045. }
  66046. line[2] = 0; // force the last level to 0, just in case something went wrong in creating the table
  66047. }
  66048. }
  66049. void EdgeTable::remapTableForNumEdges (const int newNumEdgesPerLine) throw()
  66050. {
  66051. if (newNumEdgesPerLine != maxEdgesPerLine)
  66052. {
  66053. maxEdgesPerLine = newNumEdgesPerLine;
  66054. jassert (bounds.getHeight() > 0);
  66055. const int newLineStrideElements = maxEdgesPerLine * 2 + 1;
  66056. HeapBlock <int> newTable (bounds.getHeight() * newLineStrideElements);
  66057. copyEdgeTableData (newTable, newLineStrideElements, table, lineStrideElements, bounds.getHeight());
  66058. table.swapWith (newTable);
  66059. lineStrideElements = newLineStrideElements;
  66060. }
  66061. }
  66062. void EdgeTable::optimiseTable() throw()
  66063. {
  66064. int maxLineElements = 0;
  66065. for (int i = bounds.getHeight(); --i >= 0;)
  66066. maxLineElements = jmax (maxLineElements, table [i * lineStrideElements]);
  66067. remapTableForNumEdges (maxLineElements);
  66068. }
  66069. void EdgeTable::addEdgePoint (const int x, const int y, const int winding) throw()
  66070. {
  66071. jassert (y >= 0 && y < bounds.getHeight());
  66072. int* line = table + lineStrideElements * y;
  66073. const int numPoints = line[0];
  66074. int n = numPoints << 1;
  66075. if (n > 0)
  66076. {
  66077. while (n > 0)
  66078. {
  66079. const int cx = line [n - 1];
  66080. if (cx <= x)
  66081. {
  66082. if (cx == x)
  66083. {
  66084. line [n] += winding;
  66085. return;
  66086. }
  66087. break;
  66088. }
  66089. n -= 2;
  66090. }
  66091. if (numPoints >= maxEdgesPerLine)
  66092. {
  66093. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  66094. jassert (numPoints < maxEdgesPerLine);
  66095. line = table + lineStrideElements * y;
  66096. }
  66097. memmove (line + (n + 3), line + (n + 1), sizeof (int) * ((numPoints << 1) - n));
  66098. }
  66099. line [n + 1] = x;
  66100. line [n + 2] = winding;
  66101. line[0]++;
  66102. }
  66103. void EdgeTable::translate (float dx, const int dy) throw()
  66104. {
  66105. bounds.translate ((int) std::floor (dx), dy);
  66106. int* lineStart = table;
  66107. const int intDx = (int) (dx * 256.0f);
  66108. for (int i = bounds.getHeight(); --i >= 0;)
  66109. {
  66110. int* line = lineStart;
  66111. lineStart += lineStrideElements;
  66112. int num = *line++;
  66113. while (--num >= 0)
  66114. {
  66115. *line += intDx;
  66116. line += 2;
  66117. }
  66118. }
  66119. }
  66120. void EdgeTable::intersectWithEdgeTableLine (const int y, const int* otherLine) throw()
  66121. {
  66122. jassert (y >= 0 && y < bounds.getHeight());
  66123. int* dest = table + lineStrideElements * y;
  66124. if (dest[0] == 0)
  66125. return;
  66126. int otherNumPoints = *otherLine;
  66127. if (otherNumPoints == 0)
  66128. {
  66129. *dest = 0;
  66130. return;
  66131. }
  66132. const int right = bounds.getRight() << 8;
  66133. // optimise for the common case where our line lies entirely within a
  66134. // single pair of points, as happens when clipping to a simple rect.
  66135. if (otherNumPoints == 2 && otherLine[2] >= 255)
  66136. {
  66137. clipEdgeTableLineToRange (dest, otherLine[1], jmin (right, otherLine[3]));
  66138. return;
  66139. }
  66140. ++otherLine;
  66141. const size_t lineSizeBytes = (dest[0] * 2 + 1) * sizeof (int);
  66142. int* temp = static_cast<int*> (alloca (lineSizeBytes));
  66143. memcpy (temp, dest, lineSizeBytes);
  66144. const int* src1 = temp;
  66145. int srcNum1 = *src1++;
  66146. int x1 = *src1++;
  66147. const int* src2 = otherLine;
  66148. int srcNum2 = otherNumPoints;
  66149. int x2 = *src2++;
  66150. int destIndex = 0, destTotal = 0;
  66151. int level1 = 0, level2 = 0;
  66152. int lastX = std::numeric_limits<int>::min(), lastLevel = 0;
  66153. while (srcNum1 > 0 && srcNum2 > 0)
  66154. {
  66155. int nextX;
  66156. if (x1 < x2)
  66157. {
  66158. nextX = x1;
  66159. level1 = *src1++;
  66160. x1 = *src1++;
  66161. --srcNum1;
  66162. }
  66163. else if (x1 == x2)
  66164. {
  66165. nextX = x1;
  66166. level1 = *src1++;
  66167. level2 = *src2++;
  66168. x1 = *src1++;
  66169. x2 = *src2++;
  66170. --srcNum1;
  66171. --srcNum2;
  66172. }
  66173. else
  66174. {
  66175. nextX = x2;
  66176. level2 = *src2++;
  66177. x2 = *src2++;
  66178. --srcNum2;
  66179. }
  66180. if (nextX > lastX)
  66181. {
  66182. if (nextX >= right)
  66183. break;
  66184. lastX = nextX;
  66185. const int nextLevel = (level1 * (level2 + 1)) >> 8;
  66186. jassert (((unsigned int) nextLevel) < (unsigned int) 256);
  66187. if (nextLevel != lastLevel)
  66188. {
  66189. if (destTotal >= maxEdgesPerLine)
  66190. {
  66191. dest[0] = destTotal;
  66192. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  66193. dest = table + lineStrideElements * y;
  66194. }
  66195. ++destTotal;
  66196. lastLevel = nextLevel;
  66197. dest[++destIndex] = nextX;
  66198. dest[++destIndex] = nextLevel;
  66199. }
  66200. }
  66201. }
  66202. if (lastLevel > 0)
  66203. {
  66204. if (destTotal >= maxEdgesPerLine)
  66205. {
  66206. dest[0] = destTotal;
  66207. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  66208. dest = table + lineStrideElements * y;
  66209. }
  66210. ++destTotal;
  66211. dest[++destIndex] = right;
  66212. dest[++destIndex] = 0;
  66213. }
  66214. dest[0] = destTotal;
  66215. #if JUCE_DEBUG
  66216. int last = std::numeric_limits<int>::min();
  66217. for (int i = 0; i < dest[0]; ++i)
  66218. {
  66219. jassert (dest[i * 2 + 1] > last);
  66220. last = dest[i * 2 + 1];
  66221. }
  66222. jassert (dest [dest[0] * 2] == 0);
  66223. #endif
  66224. }
  66225. void EdgeTable::clipEdgeTableLineToRange (int* dest, const int x1, const int x2) throw()
  66226. {
  66227. int* lastItem = dest + (dest[0] * 2 - 1);
  66228. if (x2 < lastItem[0])
  66229. {
  66230. if (x2 <= dest[1])
  66231. {
  66232. dest[0] = 0;
  66233. return;
  66234. }
  66235. while (x2 < lastItem[-2])
  66236. {
  66237. --(dest[0]);
  66238. lastItem -= 2;
  66239. }
  66240. lastItem[0] = x2;
  66241. lastItem[1] = 0;
  66242. }
  66243. if (x1 > dest[1])
  66244. {
  66245. while (lastItem[0] > x1)
  66246. lastItem -= 2;
  66247. const int itemsRemoved = (int) (lastItem - (dest + 1)) / 2;
  66248. if (itemsRemoved > 0)
  66249. {
  66250. dest[0] -= itemsRemoved;
  66251. memmove (dest + 1, lastItem, dest[0] * (sizeof (int) * 2));
  66252. }
  66253. dest[1] = x1;
  66254. }
  66255. }
  66256. void EdgeTable::clipToRectangle (const Rectangle<int>& r) throw()
  66257. {
  66258. const Rectangle<int> clipped (r.getIntersection (bounds));
  66259. if (clipped.isEmpty())
  66260. {
  66261. needToCheckEmptinesss = false;
  66262. bounds.setHeight (0);
  66263. }
  66264. else
  66265. {
  66266. const int top = clipped.getY() - bounds.getY();
  66267. const int bottom = clipped.getBottom() - bounds.getY();
  66268. if (bottom < bounds.getHeight())
  66269. bounds.setHeight (bottom);
  66270. if (clipped.getRight() < bounds.getRight())
  66271. bounds.setRight (clipped.getRight());
  66272. for (int i = top; --i >= 0;)
  66273. table [lineStrideElements * i] = 0;
  66274. if (clipped.getX() > bounds.getX())
  66275. {
  66276. const int x1 = clipped.getX() << 8;
  66277. const int x2 = jmin (bounds.getRight(), clipped.getRight()) << 8;
  66278. int* line = table + lineStrideElements * top;
  66279. for (int i = bottom - top; --i >= 0;)
  66280. {
  66281. if (line[0] != 0)
  66282. clipEdgeTableLineToRange (line, x1, x2);
  66283. line += lineStrideElements;
  66284. }
  66285. }
  66286. needToCheckEmptinesss = true;
  66287. }
  66288. }
  66289. void EdgeTable::excludeRectangle (const Rectangle<int>& r) throw()
  66290. {
  66291. const Rectangle<int> clipped (r.getIntersection (bounds));
  66292. if (! clipped.isEmpty())
  66293. {
  66294. const int top = clipped.getY() - bounds.getY();
  66295. const int bottom = clipped.getBottom() - bounds.getY();
  66296. //XXX optimise here by shortening the table if it fills top or bottom
  66297. const int rectLine[] = { 4, std::numeric_limits<int>::min(), 255,
  66298. clipped.getX() << 8, 0,
  66299. clipped.getRight() << 8, 255,
  66300. std::numeric_limits<int>::max(), 0 };
  66301. for (int i = top; i < bottom; ++i)
  66302. intersectWithEdgeTableLine (i, rectLine);
  66303. needToCheckEmptinesss = true;
  66304. }
  66305. }
  66306. void EdgeTable::clipToEdgeTable (const EdgeTable& other)
  66307. {
  66308. const Rectangle<int> clipped (other.bounds.getIntersection (bounds));
  66309. if (clipped.isEmpty())
  66310. {
  66311. needToCheckEmptinesss = false;
  66312. bounds.setHeight (0);
  66313. }
  66314. else
  66315. {
  66316. const int top = clipped.getY() - bounds.getY();
  66317. const int bottom = clipped.getBottom() - bounds.getY();
  66318. if (bottom < bounds.getHeight())
  66319. bounds.setHeight (bottom);
  66320. if (clipped.getRight() < bounds.getRight())
  66321. bounds.setRight (clipped.getRight());
  66322. int i = 0;
  66323. for (i = top; --i >= 0;)
  66324. table [lineStrideElements * i] = 0;
  66325. const int* otherLine = other.table + other.lineStrideElements * (clipped.getY() - other.bounds.getY());
  66326. for (i = top; i < bottom; ++i)
  66327. {
  66328. intersectWithEdgeTableLine (i, otherLine);
  66329. otherLine += other.lineStrideElements;
  66330. }
  66331. needToCheckEmptinesss = true;
  66332. }
  66333. }
  66334. void EdgeTable::clipLineToMask (int x, int y, const uint8* mask, int maskStride, int numPixels) throw()
  66335. {
  66336. y -= bounds.getY();
  66337. if (y < 0 || y >= bounds.getHeight())
  66338. return;
  66339. needToCheckEmptinesss = true;
  66340. if (numPixels <= 0)
  66341. {
  66342. table [lineStrideElements * y] = 0;
  66343. return;
  66344. }
  66345. int* tempLine = static_cast<int*> (alloca ((numPixels * 2 + 4) * sizeof (int)));
  66346. int destIndex = 0, lastLevel = 0;
  66347. while (--numPixels >= 0)
  66348. {
  66349. const int alpha = *mask;
  66350. mask += maskStride;
  66351. if (alpha != lastLevel)
  66352. {
  66353. tempLine[++destIndex] = (x << 8);
  66354. tempLine[++destIndex] = alpha;
  66355. lastLevel = alpha;
  66356. }
  66357. ++x;
  66358. }
  66359. if (lastLevel > 0)
  66360. {
  66361. tempLine[++destIndex] = (x << 8);
  66362. tempLine[++destIndex] = 0;
  66363. }
  66364. tempLine[0] = destIndex >> 1;
  66365. intersectWithEdgeTableLine (y, tempLine);
  66366. }
  66367. bool EdgeTable::isEmpty() throw()
  66368. {
  66369. if (needToCheckEmptinesss)
  66370. {
  66371. needToCheckEmptinesss = false;
  66372. int* t = table;
  66373. for (int i = bounds.getHeight(); --i >= 0;)
  66374. {
  66375. if (t[0] > 1)
  66376. return false;
  66377. t += lineStrideElements;
  66378. }
  66379. bounds.setHeight (0);
  66380. }
  66381. return bounds.getHeight() == 0;
  66382. }
  66383. END_JUCE_NAMESPACE
  66384. /*** End of inlined file: juce_EdgeTable.cpp ***/
  66385. /*** Start of inlined file: juce_FillType.cpp ***/
  66386. BEGIN_JUCE_NAMESPACE
  66387. FillType::FillType() throw()
  66388. : colour (0xff000000), image (0)
  66389. {
  66390. }
  66391. FillType::FillType (const Colour& colour_) throw()
  66392. : colour (colour_), image (0)
  66393. {
  66394. }
  66395. FillType::FillType (const ColourGradient& gradient_)
  66396. : colour (0xff000000), gradient (new ColourGradient (gradient_)), image (0)
  66397. {
  66398. }
  66399. FillType::FillType (const Image& image_, const AffineTransform& transform_) throw()
  66400. : colour (0xff000000), image (image_), transform (transform_)
  66401. {
  66402. }
  66403. FillType::FillType (const FillType& other)
  66404. : colour (other.colour),
  66405. gradient (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0),
  66406. image (other.image), transform (other.transform)
  66407. {
  66408. }
  66409. FillType& FillType::operator= (const FillType& other)
  66410. {
  66411. if (this != &other)
  66412. {
  66413. colour = other.colour;
  66414. gradient = (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0);
  66415. image = other.image;
  66416. transform = other.transform;
  66417. }
  66418. return *this;
  66419. }
  66420. FillType::~FillType() throw()
  66421. {
  66422. }
  66423. bool FillType::operator== (const FillType& other) const
  66424. {
  66425. return colour == other.colour && image == other.image
  66426. && transform == other.transform
  66427. && (gradient == other.gradient
  66428. || (gradient != 0 && other.gradient != 0 && *gradient == *other.gradient));
  66429. }
  66430. bool FillType::operator!= (const FillType& other) const
  66431. {
  66432. return ! operator== (other);
  66433. }
  66434. void FillType::setColour (const Colour& newColour) throw()
  66435. {
  66436. gradient = 0;
  66437. image = Image::null;
  66438. colour = newColour;
  66439. }
  66440. void FillType::setGradient (const ColourGradient& newGradient)
  66441. {
  66442. if (gradient != 0)
  66443. {
  66444. *gradient = newGradient;
  66445. }
  66446. else
  66447. {
  66448. image = Image::null;
  66449. gradient = new ColourGradient (newGradient);
  66450. colour = Colours::black;
  66451. }
  66452. }
  66453. void FillType::setTiledImage (const Image& image_, const AffineTransform& transform_) throw()
  66454. {
  66455. gradient = 0;
  66456. image = image_;
  66457. transform = transform_;
  66458. colour = Colours::black;
  66459. }
  66460. void FillType::setOpacity (const float newOpacity) throw()
  66461. {
  66462. colour = colour.withAlpha (newOpacity);
  66463. }
  66464. bool FillType::isInvisible() const throw()
  66465. {
  66466. return colour.isTransparent() || (gradient != 0 && gradient->isInvisible());
  66467. }
  66468. END_JUCE_NAMESPACE
  66469. /*** End of inlined file: juce_FillType.cpp ***/
  66470. /*** Start of inlined file: juce_Graphics.cpp ***/
  66471. BEGIN_JUCE_NAMESPACE
  66472. template <typename Type>
  66473. static bool areCoordsSensibleNumbers (Type x, Type y, Type w, Type h)
  66474. {
  66475. const int maxVal = 0x3fffffff;
  66476. return (int) x >= -maxVal && (int) x <= maxVal
  66477. && (int) y >= -maxVal && (int) y <= maxVal
  66478. && (int) w >= -maxVal && (int) w <= maxVal
  66479. && (int) h >= -maxVal && (int) h <= maxVal;
  66480. }
  66481. LowLevelGraphicsContext::LowLevelGraphicsContext()
  66482. {
  66483. }
  66484. LowLevelGraphicsContext::~LowLevelGraphicsContext()
  66485. {
  66486. }
  66487. Graphics::Graphics (const Image& imageToDrawOnto)
  66488. : context (imageToDrawOnto.createLowLevelContext()),
  66489. contextToDelete (context),
  66490. saveStatePending (false)
  66491. {
  66492. }
  66493. Graphics::Graphics (LowLevelGraphicsContext* const internalContext) throw()
  66494. : context (internalContext),
  66495. saveStatePending (false)
  66496. {
  66497. }
  66498. Graphics::~Graphics()
  66499. {
  66500. }
  66501. void Graphics::resetToDefaultState()
  66502. {
  66503. saveStateIfPending();
  66504. context->setFill (FillType());
  66505. context->setFont (Font());
  66506. context->setInterpolationQuality (Graphics::mediumResamplingQuality);
  66507. }
  66508. bool Graphics::isVectorDevice() const
  66509. {
  66510. return context->isVectorDevice();
  66511. }
  66512. bool Graphics::reduceClipRegion (const int x, const int y, const int w, const int h)
  66513. {
  66514. saveStateIfPending();
  66515. return context->clipToRectangle (Rectangle<int> (x, y, w, h));
  66516. }
  66517. bool Graphics::reduceClipRegion (const RectangleList& clipRegion)
  66518. {
  66519. saveStateIfPending();
  66520. return context->clipToRectangleList (clipRegion);
  66521. }
  66522. bool Graphics::reduceClipRegion (const Path& path, const AffineTransform& transform)
  66523. {
  66524. saveStateIfPending();
  66525. context->clipToPath (path, transform);
  66526. return ! context->isClipEmpty();
  66527. }
  66528. bool Graphics::reduceClipRegion (const Image& image, const AffineTransform& transform)
  66529. {
  66530. saveStateIfPending();
  66531. context->clipToImageAlpha (image, transform);
  66532. return ! context->isClipEmpty();
  66533. }
  66534. void Graphics::excludeClipRegion (const Rectangle<int>& rectangleToExclude)
  66535. {
  66536. saveStateIfPending();
  66537. context->excludeClipRectangle (rectangleToExclude);
  66538. }
  66539. bool Graphics::isClipEmpty() const
  66540. {
  66541. return context->isClipEmpty();
  66542. }
  66543. const Rectangle<int> Graphics::getClipBounds() const
  66544. {
  66545. return context->getClipBounds();
  66546. }
  66547. void Graphics::saveState()
  66548. {
  66549. saveStateIfPending();
  66550. saveStatePending = true;
  66551. }
  66552. void Graphics::restoreState()
  66553. {
  66554. if (saveStatePending)
  66555. saveStatePending = false;
  66556. else
  66557. context->restoreState();
  66558. }
  66559. void Graphics::saveStateIfPending()
  66560. {
  66561. if (saveStatePending)
  66562. {
  66563. saveStatePending = false;
  66564. context->saveState();
  66565. }
  66566. }
  66567. void Graphics::setOrigin (const int newOriginX, const int newOriginY)
  66568. {
  66569. saveStateIfPending();
  66570. context->setOrigin (newOriginX, newOriginY);
  66571. }
  66572. bool Graphics::clipRegionIntersects (const Rectangle<int>& area) const
  66573. {
  66574. return context->clipRegionIntersects (area);
  66575. }
  66576. void Graphics::setColour (const Colour& newColour)
  66577. {
  66578. saveStateIfPending();
  66579. context->setFill (newColour);
  66580. }
  66581. void Graphics::setOpacity (const float newOpacity)
  66582. {
  66583. saveStateIfPending();
  66584. context->setOpacity (newOpacity);
  66585. }
  66586. void Graphics::setGradientFill (const ColourGradient& gradient)
  66587. {
  66588. setFillType (gradient);
  66589. }
  66590. void Graphics::setTiledImageFill (const Image& imageToUse, const int anchorX, const int anchorY, const float opacity)
  66591. {
  66592. saveStateIfPending();
  66593. context->setFill (FillType (imageToUse, AffineTransform::translation ((float) anchorX, (float) anchorY)));
  66594. context->setOpacity (opacity);
  66595. }
  66596. void Graphics::setFillType (const FillType& newFill)
  66597. {
  66598. saveStateIfPending();
  66599. context->setFill (newFill);
  66600. }
  66601. void Graphics::setFont (const Font& newFont)
  66602. {
  66603. saveStateIfPending();
  66604. context->setFont (newFont);
  66605. }
  66606. void Graphics::setFont (const float newFontHeight, const int newFontStyleFlags)
  66607. {
  66608. saveStateIfPending();
  66609. Font f (context->getFont());
  66610. f.setSizeAndStyle (newFontHeight, newFontStyleFlags, 1.0f, 0);
  66611. context->setFont (f);
  66612. }
  66613. const Font Graphics::getCurrentFont() const
  66614. {
  66615. return context->getFont();
  66616. }
  66617. void Graphics::drawSingleLineText (const String& text, const int startX, const int baselineY) const
  66618. {
  66619. if (text.isNotEmpty()
  66620. && startX < context->getClipBounds().getRight())
  66621. {
  66622. GlyphArrangement arr;
  66623. arr.addLineOfText (context->getFont(), text, (float) startX, (float) baselineY);
  66624. arr.draw (*this);
  66625. }
  66626. }
  66627. void Graphics::drawTextAsPath (const String& text, const AffineTransform& transform) const
  66628. {
  66629. if (text.isNotEmpty())
  66630. {
  66631. GlyphArrangement arr;
  66632. arr.addLineOfText (context->getFont(), text, 0.0f, 0.0f);
  66633. arr.draw (*this, transform);
  66634. }
  66635. }
  66636. void Graphics::drawMultiLineText (const String& text, const int startX, const int baselineY, const int maximumLineWidth) const
  66637. {
  66638. if (text.isNotEmpty()
  66639. && startX < context->getClipBounds().getRight())
  66640. {
  66641. GlyphArrangement arr;
  66642. arr.addJustifiedText (context->getFont(), text,
  66643. (float) startX, (float) baselineY, (float) maximumLineWidth,
  66644. Justification::left);
  66645. arr.draw (*this);
  66646. }
  66647. }
  66648. void Graphics::drawText (const String& text,
  66649. const int x, const int y, const int width, const int height,
  66650. const Justification& justificationType,
  66651. const bool useEllipsesIfTooBig) const
  66652. {
  66653. if (text.isNotEmpty() && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66654. {
  66655. GlyphArrangement arr;
  66656. arr.addCurtailedLineOfText (context->getFont(), text,
  66657. 0.0f, 0.0f, (float) width,
  66658. useEllipsesIfTooBig);
  66659. arr.justifyGlyphs (0, arr.getNumGlyphs(),
  66660. (float) x, (float) y, (float) width, (float) height,
  66661. justificationType);
  66662. arr.draw (*this);
  66663. }
  66664. }
  66665. void Graphics::drawFittedText (const String& text,
  66666. const int x, const int y, const int width, const int height,
  66667. const Justification& justification,
  66668. const int maximumNumberOfLines,
  66669. const float minimumHorizontalScale) const
  66670. {
  66671. if (text.isNotEmpty()
  66672. && width > 0 && height > 0
  66673. && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66674. {
  66675. GlyphArrangement arr;
  66676. arr.addFittedText (context->getFont(), text,
  66677. (float) x, (float) y, (float) width, (float) height,
  66678. justification,
  66679. maximumNumberOfLines,
  66680. minimumHorizontalScale);
  66681. arr.draw (*this);
  66682. }
  66683. }
  66684. void Graphics::fillRect (int x, int y, int width, int height) const
  66685. {
  66686. // passing in a silly number can cause maths problems in rendering!
  66687. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66688. context->fillRect (Rectangle<int> (x, y, width, height), false);
  66689. }
  66690. void Graphics::fillRect (const Rectangle<int>& r) const
  66691. {
  66692. context->fillRect (r, false);
  66693. }
  66694. void Graphics::fillRect (const float x, const float y, const float width, const float height) const
  66695. {
  66696. // passing in a silly number can cause maths problems in rendering!
  66697. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66698. Path p;
  66699. p.addRectangle (x, y, width, height);
  66700. fillPath (p);
  66701. }
  66702. void Graphics::setPixel (int x, int y) const
  66703. {
  66704. context->fillRect (Rectangle<int> (x, y, 1, 1), false);
  66705. }
  66706. void Graphics::fillAll() const
  66707. {
  66708. fillRect (context->getClipBounds());
  66709. }
  66710. void Graphics::fillAll (const Colour& colourToUse) const
  66711. {
  66712. if (! colourToUse.isTransparent())
  66713. {
  66714. const Rectangle<int> clip (context->getClipBounds());
  66715. context->saveState();
  66716. context->setFill (colourToUse);
  66717. context->fillRect (clip, false);
  66718. context->restoreState();
  66719. }
  66720. }
  66721. void Graphics::fillPath (const Path& path, const AffineTransform& transform) const
  66722. {
  66723. if ((! context->isClipEmpty()) && ! path.isEmpty())
  66724. context->fillPath (path, transform);
  66725. }
  66726. void Graphics::strokePath (const Path& path,
  66727. const PathStrokeType& strokeType,
  66728. const AffineTransform& transform) const
  66729. {
  66730. Path stroke;
  66731. strokeType.createStrokedPath (stroke, path, transform);
  66732. fillPath (stroke);
  66733. }
  66734. void Graphics::drawRect (const int x, const int y, const int width, const int height,
  66735. const int lineThickness) const
  66736. {
  66737. // passing in a silly number can cause maths problems in rendering!
  66738. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66739. context->fillRect (Rectangle<int> (x, y, width, lineThickness), false);
  66740. context->fillRect (Rectangle<int> (x, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  66741. context->fillRect (Rectangle<int> (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  66742. context->fillRect (Rectangle<int> (x, y + height - lineThickness, width, lineThickness), false);
  66743. }
  66744. void Graphics::drawRect (const float x, const float y, const float width, const float height, const float lineThickness) const
  66745. {
  66746. // passing in a silly number can cause maths problems in rendering!
  66747. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66748. Path p;
  66749. p.addRectangle (x, y, width, lineThickness);
  66750. p.addRectangle (x, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  66751. p.addRectangle (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  66752. p.addRectangle (x, y + height - lineThickness, width, lineThickness);
  66753. fillPath (p);
  66754. }
  66755. void Graphics::drawRect (const Rectangle<int>& r, const int lineThickness) const
  66756. {
  66757. drawRect (r.getX(), r.getY(), r.getWidth(), r.getHeight(), lineThickness);
  66758. }
  66759. void Graphics::drawBevel (const int x, const int y, const int width, const int height,
  66760. const int bevelThickness, const Colour& topLeftColour, const Colour& bottomRightColour,
  66761. const bool useGradient, const bool sharpEdgeOnOutside) const
  66762. {
  66763. // passing in a silly number can cause maths problems in rendering!
  66764. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66765. if (clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66766. {
  66767. context->saveState();
  66768. const float oldOpacity = 1.0f;//xxx state->colour.getFloatAlpha();
  66769. const float ramp = oldOpacity / bevelThickness;
  66770. for (int i = bevelThickness; --i >= 0;)
  66771. {
  66772. const float op = useGradient ? ramp * (sharpEdgeOnOutside ? bevelThickness - i : i)
  66773. : oldOpacity;
  66774. context->setFill (topLeftColour.withMultipliedAlpha (op));
  66775. context->fillRect (Rectangle<int> (x + i, y + i, width - i * 2, 1), false);
  66776. context->setFill (topLeftColour.withMultipliedAlpha (op * 0.75f));
  66777. context->fillRect (Rectangle<int> (x + i, y + i + 1, 1, height - i * 2 - 2), false);
  66778. context->setFill (bottomRightColour.withMultipliedAlpha (op));
  66779. context->fillRect (Rectangle<int> (x + i, y + height - i - 1, width - i * 2, 1), false);
  66780. context->setFill (bottomRightColour.withMultipliedAlpha (op * 0.75f));
  66781. context->fillRect (Rectangle<int> (x + width - i - 1, y + i + 1, 1, height - i * 2 - 2), false);
  66782. }
  66783. context->restoreState();
  66784. }
  66785. }
  66786. void Graphics::fillEllipse (const float x, const float y, const float width, const float height) const
  66787. {
  66788. // passing in a silly number can cause maths problems in rendering!
  66789. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66790. Path p;
  66791. p.addEllipse (x, y, width, height);
  66792. fillPath (p);
  66793. }
  66794. void Graphics::drawEllipse (const float x, const float y, const float width, const float height,
  66795. const float lineThickness) const
  66796. {
  66797. // passing in a silly number can cause maths problems in rendering!
  66798. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66799. Path p;
  66800. p.addEllipse (x, y, width, height);
  66801. strokePath (p, PathStrokeType (lineThickness));
  66802. }
  66803. void Graphics::fillRoundedRectangle (const float x, const float y, const float width, const float height, const float cornerSize) const
  66804. {
  66805. // passing in a silly number can cause maths problems in rendering!
  66806. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66807. Path p;
  66808. p.addRoundedRectangle (x, y, width, height, cornerSize);
  66809. fillPath (p);
  66810. }
  66811. void Graphics::fillRoundedRectangle (const Rectangle<float>& r, const float cornerSize) const
  66812. {
  66813. fillRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize);
  66814. }
  66815. void Graphics::drawRoundedRectangle (const float x, const float y, const float width, const float height,
  66816. const float cornerSize, const float lineThickness) const
  66817. {
  66818. // passing in a silly number can cause maths problems in rendering!
  66819. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66820. Path p;
  66821. p.addRoundedRectangle (x, y, width, height, cornerSize);
  66822. strokePath (p, PathStrokeType (lineThickness));
  66823. }
  66824. void Graphics::drawRoundedRectangle (const Rectangle<float>& r, const float cornerSize, const float lineThickness) const
  66825. {
  66826. drawRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize, lineThickness);
  66827. }
  66828. void Graphics::drawArrow (const Line<float>& line, const float lineThickness, const float arrowheadWidth, const float arrowheadLength) const
  66829. {
  66830. Path p;
  66831. p.addArrow (line, lineThickness, arrowheadWidth, arrowheadLength);
  66832. fillPath (p);
  66833. }
  66834. void Graphics::fillCheckerBoard (const Rectangle<int>& area,
  66835. const int checkWidth, const int checkHeight,
  66836. const Colour& colour1, const Colour& colour2) const
  66837. {
  66838. jassert (checkWidth > 0 && checkHeight > 0); // can't be zero or less!
  66839. if (checkWidth > 0 && checkHeight > 0)
  66840. {
  66841. context->saveState();
  66842. if (colour1 == colour2)
  66843. {
  66844. context->setFill (colour1);
  66845. context->fillRect (area, false);
  66846. }
  66847. else
  66848. {
  66849. const Rectangle<int> clipped (context->getClipBounds().getIntersection (area));
  66850. if (! clipped.isEmpty())
  66851. {
  66852. context->clipToRectangle (clipped);
  66853. const int checkNumX = (clipped.getX() - area.getX()) / checkWidth;
  66854. const int checkNumY = (clipped.getY() - area.getY()) / checkHeight;
  66855. const int startX = area.getX() + checkNumX * checkWidth;
  66856. const int startY = area.getY() + checkNumY * checkHeight;
  66857. const int right = clipped.getRight();
  66858. const int bottom = clipped.getBottom();
  66859. for (int i = 0; i < 2; ++i)
  66860. {
  66861. context->setFill (i == ((checkNumX ^ checkNumY) & 1) ? colour1 : colour2);
  66862. int cy = i;
  66863. for (int y = startY; y < bottom; y += checkHeight)
  66864. for (int x = startX + (cy++ & 1) * checkWidth; x < right; x += checkWidth * 2)
  66865. context->fillRect (Rectangle<int> (x, y, checkWidth, checkHeight), false);
  66866. }
  66867. }
  66868. }
  66869. context->restoreState();
  66870. }
  66871. }
  66872. void Graphics::drawVerticalLine (const int x, float top, float bottom) const
  66873. {
  66874. context->drawVerticalLine (x, top, bottom);
  66875. }
  66876. void Graphics::drawHorizontalLine (const int y, float left, float right) const
  66877. {
  66878. context->drawHorizontalLine (y, left, right);
  66879. }
  66880. void Graphics::drawLine (float x1, float y1, float x2, float y2) const
  66881. {
  66882. context->drawLine (Line<float> (x1, y1, x2, y2));
  66883. }
  66884. void Graphics::drawLine (const float startX, const float startY,
  66885. const float endX, const float endY,
  66886. const float lineThickness) const
  66887. {
  66888. drawLine (Line<float> (startX, startY, endX, endY),lineThickness);
  66889. }
  66890. void Graphics::drawLine (const Line<float>& line) const
  66891. {
  66892. drawLine (line.getStartX(), line.getStartY(), line.getEndX(), line.getEndY());
  66893. }
  66894. void Graphics::drawLine (const Line<float>& line, const float lineThickness) const
  66895. {
  66896. Path p;
  66897. p.addLineSegment (line, lineThickness);
  66898. fillPath (p);
  66899. }
  66900. void Graphics::drawDashedLine (const float startX, const float startY,
  66901. const float endX, const float endY,
  66902. const float* const dashLengths,
  66903. const int numDashLengths,
  66904. const float lineThickness) const
  66905. {
  66906. const double dx = endX - startX;
  66907. const double dy = endY - startY;
  66908. const double totalLen = juce_hypot (dx, dy);
  66909. if (totalLen >= 0.5)
  66910. {
  66911. const double onePixAlpha = 1.0 / totalLen;
  66912. double alpha = 0.0;
  66913. float x = startX;
  66914. float y = startY;
  66915. int n = 0;
  66916. while (alpha < 1.0f)
  66917. {
  66918. alpha = jmin (1.0, alpha + dashLengths[n++] * onePixAlpha);
  66919. n = n % numDashLengths;
  66920. const float oldX = x;
  66921. const float oldY = y;
  66922. x = (float) (startX + dx * alpha);
  66923. y = (float) (startY + dy * alpha);
  66924. if ((n & 1) != 0)
  66925. {
  66926. if (lineThickness != 1.0f)
  66927. drawLine (oldX, oldY, x, y, lineThickness);
  66928. else
  66929. drawLine (oldX, oldY, x, y);
  66930. }
  66931. }
  66932. }
  66933. }
  66934. void Graphics::setImageResamplingQuality (const Graphics::ResamplingQuality newQuality)
  66935. {
  66936. saveStateIfPending();
  66937. context->setInterpolationQuality (newQuality);
  66938. }
  66939. void Graphics::drawImageAt (const Image& imageToDraw,
  66940. const int topLeftX, const int topLeftY,
  66941. const bool fillAlphaChannelWithCurrentBrush) const
  66942. {
  66943. const int imageW = imageToDraw.getWidth();
  66944. const int imageH = imageToDraw.getHeight();
  66945. drawImage (imageToDraw,
  66946. topLeftX, topLeftY, imageW, imageH,
  66947. 0, 0, imageW, imageH,
  66948. fillAlphaChannelWithCurrentBrush);
  66949. }
  66950. void Graphics::drawImageWithin (const Image& imageToDraw,
  66951. const int destX, const int destY,
  66952. const int destW, const int destH,
  66953. const RectanglePlacement& placementWithinTarget,
  66954. const bool fillAlphaChannelWithCurrentBrush) const
  66955. {
  66956. // passing in a silly number can cause maths problems in rendering!
  66957. jassert (areCoordsSensibleNumbers (destX, destY, destW, destH));
  66958. if (imageToDraw.isValid())
  66959. {
  66960. const int imageW = imageToDraw.getWidth();
  66961. const int imageH = imageToDraw.getHeight();
  66962. if (imageW > 0 && imageH > 0)
  66963. {
  66964. double newX = 0.0, newY = 0.0;
  66965. double newW = imageW;
  66966. double newH = imageH;
  66967. placementWithinTarget.applyTo (newX, newY, newW, newH,
  66968. destX, destY, destW, destH);
  66969. if (newW > 0 && newH > 0)
  66970. {
  66971. drawImage (imageToDraw,
  66972. roundToInt (newX), roundToInt (newY),
  66973. roundToInt (newW), roundToInt (newH),
  66974. 0, 0, imageW, imageH,
  66975. fillAlphaChannelWithCurrentBrush);
  66976. }
  66977. }
  66978. }
  66979. }
  66980. void Graphics::drawImage (const Image& imageToDraw,
  66981. int dx, int dy, int dw, int dh,
  66982. int sx, int sy, int sw, int sh,
  66983. const bool fillAlphaChannelWithCurrentBrush) const
  66984. {
  66985. // passing in a silly number can cause maths problems in rendering!
  66986. jassert (areCoordsSensibleNumbers (dx, dy, dw, dh));
  66987. jassert (areCoordsSensibleNumbers (sx, sy, sw, sh));
  66988. if (imageToDraw.isValid() && context->clipRegionIntersects (Rectangle<int> (dx, dy, dw, dh)))
  66989. {
  66990. drawImageTransformed (imageToDraw.getClippedImage (Rectangle<int> (sx, sy, sw, sh)),
  66991. AffineTransform::scale (dw / (float) sw, dh / (float) sh)
  66992. .translated ((float) dx, (float) dy),
  66993. fillAlphaChannelWithCurrentBrush);
  66994. }
  66995. }
  66996. void Graphics::drawImageTransformed (const Image& imageToDraw,
  66997. const AffineTransform& transform,
  66998. const bool fillAlphaChannelWithCurrentBrush) const
  66999. {
  67000. if (imageToDraw.isValid() && ! context->isClipEmpty())
  67001. {
  67002. if (fillAlphaChannelWithCurrentBrush)
  67003. {
  67004. context->saveState();
  67005. context->clipToImageAlpha (imageToDraw, transform);
  67006. fillAll();
  67007. context->restoreState();
  67008. }
  67009. else
  67010. {
  67011. context->drawImage (imageToDraw, transform, false);
  67012. }
  67013. }
  67014. }
  67015. END_JUCE_NAMESPACE
  67016. /*** End of inlined file: juce_Graphics.cpp ***/
  67017. /*** Start of inlined file: juce_Justification.cpp ***/
  67018. BEGIN_JUCE_NAMESPACE
  67019. Justification::Justification (const Justification& other) throw()
  67020. : flags (other.flags)
  67021. {
  67022. }
  67023. Justification& Justification::operator= (const Justification& other) throw()
  67024. {
  67025. flags = other.flags;
  67026. return *this;
  67027. }
  67028. int Justification::getOnlyVerticalFlags() const throw()
  67029. {
  67030. return flags & (top | bottom | verticallyCentred);
  67031. }
  67032. int Justification::getOnlyHorizontalFlags() const throw()
  67033. {
  67034. return flags & (left | right | horizontallyCentred | horizontallyJustified);
  67035. }
  67036. void Justification::applyToRectangle (int& x, int& y,
  67037. const int w, const int h,
  67038. const int spaceX, const int spaceY,
  67039. const int spaceW, const int spaceH) const throw()
  67040. {
  67041. if ((flags & horizontallyCentred) != 0)
  67042. x = spaceX + ((spaceW - w) >> 1);
  67043. else if ((flags & right) != 0)
  67044. x = spaceX + spaceW - w;
  67045. else
  67046. x = spaceX;
  67047. if ((flags & verticallyCentred) != 0)
  67048. y = spaceY + ((spaceH - h) >> 1);
  67049. else if ((flags & bottom) != 0)
  67050. y = spaceY + spaceH - h;
  67051. else
  67052. y = spaceY;
  67053. }
  67054. END_JUCE_NAMESPACE
  67055. /*** End of inlined file: juce_Justification.cpp ***/
  67056. /*** Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  67057. BEGIN_JUCE_NAMESPACE
  67058. // this will throw an assertion if you try to draw something that's not
  67059. // possible in postscript
  67060. #define WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS 0
  67061. #if JUCE_DEBUG && WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS
  67062. #define notPossibleInPostscriptAssert jassertfalse
  67063. #else
  67064. #define notPossibleInPostscriptAssert
  67065. #endif
  67066. LowLevelGraphicsPostScriptRenderer::LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  67067. const String& documentTitle,
  67068. const int totalWidth_,
  67069. const int totalHeight_)
  67070. : out (resultingPostScript),
  67071. totalWidth (totalWidth_),
  67072. totalHeight (totalHeight_),
  67073. needToClip (true)
  67074. {
  67075. stateStack.add (new SavedState());
  67076. stateStack.getLast()->clip = Rectangle<int> (totalWidth_, totalHeight_);
  67077. const float scale = jmin ((520.0f / totalWidth_), (750.0f / totalHeight));
  67078. out << "%!PS-Adobe-3.0 EPSF-3.0"
  67079. "\n%%BoundingBox: 0 0 600 824"
  67080. "\n%%Pages: 0"
  67081. "\n%%Creator: Raw Material Software JUCE"
  67082. "\n%%Title: " << documentTitle <<
  67083. "\n%%CreationDate: none"
  67084. "\n%%LanguageLevel: 2"
  67085. "\n%%EndComments"
  67086. "\n%%BeginProlog"
  67087. "\n%%BeginResource: JRes"
  67088. "\n/bd {bind def} bind def"
  67089. "\n/c {setrgbcolor} bd"
  67090. "\n/m {moveto} bd"
  67091. "\n/l {lineto} bd"
  67092. "\n/rl {rlineto} bd"
  67093. "\n/ct {curveto} bd"
  67094. "\n/cp {closepath} bd"
  67095. "\n/pr {3 index 3 index moveto 1 index 0 rlineto 0 1 index rlineto pop neg 0 rlineto pop pop closepath} bd"
  67096. "\n/doclip {initclip newpath} bd"
  67097. "\n/endclip {clip newpath} bd"
  67098. "\n%%EndResource"
  67099. "\n%%EndProlog"
  67100. "\n%%BeginSetup"
  67101. "\n%%EndSetup"
  67102. "\n%%Page: 1 1"
  67103. "\n%%BeginPageSetup"
  67104. "\n%%EndPageSetup\n\n"
  67105. << "40 800 translate\n"
  67106. << scale << ' ' << scale << " scale\n\n";
  67107. }
  67108. LowLevelGraphicsPostScriptRenderer::~LowLevelGraphicsPostScriptRenderer()
  67109. {
  67110. }
  67111. bool LowLevelGraphicsPostScriptRenderer::isVectorDevice() const
  67112. {
  67113. return true;
  67114. }
  67115. void LowLevelGraphicsPostScriptRenderer::setOrigin (int x, int y)
  67116. {
  67117. if (x != 0 || y != 0)
  67118. {
  67119. stateStack.getLast()->xOffset += x;
  67120. stateStack.getLast()->yOffset += y;
  67121. needToClip = true;
  67122. }
  67123. }
  67124. bool LowLevelGraphicsPostScriptRenderer::clipToRectangle (const Rectangle<int>& r)
  67125. {
  67126. needToClip = true;
  67127. return stateStack.getLast()->clip.clipTo (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  67128. }
  67129. bool LowLevelGraphicsPostScriptRenderer::clipToRectangleList (const RectangleList& clipRegion)
  67130. {
  67131. needToClip = true;
  67132. return stateStack.getLast()->clip.clipTo (clipRegion);
  67133. }
  67134. void LowLevelGraphicsPostScriptRenderer::excludeClipRectangle (const Rectangle<int>& r)
  67135. {
  67136. needToClip = true;
  67137. stateStack.getLast()->clip.subtract (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  67138. }
  67139. void LowLevelGraphicsPostScriptRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  67140. {
  67141. writeClip();
  67142. Path p (path);
  67143. p.applyTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  67144. writePath (p);
  67145. out << "clip\n";
  67146. }
  67147. void LowLevelGraphicsPostScriptRenderer::clipToImageAlpha (const Image& /*sourceImage*/, const AffineTransform& /*transform*/)
  67148. {
  67149. needToClip = true;
  67150. jassertfalse; // xxx
  67151. }
  67152. bool LowLevelGraphicsPostScriptRenderer::clipRegionIntersects (const Rectangle<int>& r)
  67153. {
  67154. return stateStack.getLast()->clip.intersectsRectangle (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  67155. }
  67156. const Rectangle<int> LowLevelGraphicsPostScriptRenderer::getClipBounds() const
  67157. {
  67158. return stateStack.getLast()->clip.getBounds().translated (-stateStack.getLast()->xOffset,
  67159. -stateStack.getLast()->yOffset);
  67160. }
  67161. bool LowLevelGraphicsPostScriptRenderer::isClipEmpty() const
  67162. {
  67163. return stateStack.getLast()->clip.isEmpty();
  67164. }
  67165. LowLevelGraphicsPostScriptRenderer::SavedState::SavedState()
  67166. : xOffset (0),
  67167. yOffset (0)
  67168. {
  67169. }
  67170. LowLevelGraphicsPostScriptRenderer::SavedState::~SavedState()
  67171. {
  67172. }
  67173. void LowLevelGraphicsPostScriptRenderer::saveState()
  67174. {
  67175. stateStack.add (new SavedState (*stateStack.getLast()));
  67176. }
  67177. void LowLevelGraphicsPostScriptRenderer::restoreState()
  67178. {
  67179. jassert (stateStack.size() > 0);
  67180. if (stateStack.size() > 0)
  67181. stateStack.removeLast();
  67182. }
  67183. void LowLevelGraphicsPostScriptRenderer::writeClip()
  67184. {
  67185. if (needToClip)
  67186. {
  67187. needToClip = false;
  67188. out << "doclip ";
  67189. int itemsOnLine = 0;
  67190. for (RectangleList::Iterator i (stateStack.getLast()->clip); i.next();)
  67191. {
  67192. if (++itemsOnLine == 6)
  67193. {
  67194. itemsOnLine = 0;
  67195. out << '\n';
  67196. }
  67197. const Rectangle<int>& r = *i.getRectangle();
  67198. out << r.getX() << ' ' << -r.getY() << ' '
  67199. << r.getWidth() << ' ' << -r.getHeight() << " pr ";
  67200. }
  67201. out << "endclip\n";
  67202. }
  67203. }
  67204. void LowLevelGraphicsPostScriptRenderer::writeColour (const Colour& colour)
  67205. {
  67206. Colour c (Colours::white.overlaidWith (colour));
  67207. if (lastColour != c)
  67208. {
  67209. lastColour = c;
  67210. out << String (c.getFloatRed(), 3) << ' '
  67211. << String (c.getFloatGreen(), 3) << ' '
  67212. << String (c.getFloatBlue(), 3) << " c\n";
  67213. }
  67214. }
  67215. void LowLevelGraphicsPostScriptRenderer::writeXY (const float x, const float y) const
  67216. {
  67217. out << String (x, 2) << ' '
  67218. << String (-y, 2) << ' ';
  67219. }
  67220. void LowLevelGraphicsPostScriptRenderer::writePath (const Path& path) const
  67221. {
  67222. out << "newpath ";
  67223. float lastX = 0.0f;
  67224. float lastY = 0.0f;
  67225. int itemsOnLine = 0;
  67226. Path::Iterator i (path);
  67227. while (i.next())
  67228. {
  67229. if (++itemsOnLine == 4)
  67230. {
  67231. itemsOnLine = 0;
  67232. out << '\n';
  67233. }
  67234. switch (i.elementType)
  67235. {
  67236. case Path::Iterator::startNewSubPath:
  67237. writeXY (i.x1, i.y1);
  67238. lastX = i.x1;
  67239. lastY = i.y1;
  67240. out << "m ";
  67241. break;
  67242. case Path::Iterator::lineTo:
  67243. writeXY (i.x1, i.y1);
  67244. lastX = i.x1;
  67245. lastY = i.y1;
  67246. out << "l ";
  67247. break;
  67248. case Path::Iterator::quadraticTo:
  67249. {
  67250. const float cp1x = lastX + (i.x1 - lastX) * 2.0f / 3.0f;
  67251. const float cp1y = lastY + (i.y1 - lastY) * 2.0f / 3.0f;
  67252. const float cp2x = cp1x + (i.x2 - lastX) / 3.0f;
  67253. const float cp2y = cp1y + (i.y2 - lastY) / 3.0f;
  67254. writeXY (cp1x, cp1y);
  67255. writeXY (cp2x, cp2y);
  67256. writeXY (i.x2, i.y2);
  67257. out << "ct ";
  67258. lastX = i.x2;
  67259. lastY = i.y2;
  67260. }
  67261. break;
  67262. case Path::Iterator::cubicTo:
  67263. writeXY (i.x1, i.y1);
  67264. writeXY (i.x2, i.y2);
  67265. writeXY (i.x3, i.y3);
  67266. out << "ct ";
  67267. lastX = i.x3;
  67268. lastY = i.y3;
  67269. break;
  67270. case Path::Iterator::closePath:
  67271. out << "cp ";
  67272. break;
  67273. default:
  67274. jassertfalse;
  67275. break;
  67276. }
  67277. }
  67278. out << '\n';
  67279. }
  67280. void LowLevelGraphicsPostScriptRenderer::writeTransform (const AffineTransform& trans) const
  67281. {
  67282. out << "[ "
  67283. << trans.mat00 << ' '
  67284. << trans.mat10 << ' '
  67285. << trans.mat01 << ' '
  67286. << trans.mat11 << ' '
  67287. << trans.mat02 << ' '
  67288. << trans.mat12 << " ] concat ";
  67289. }
  67290. void LowLevelGraphicsPostScriptRenderer::setFill (const FillType& fillType)
  67291. {
  67292. stateStack.getLast()->fillType = fillType;
  67293. }
  67294. void LowLevelGraphicsPostScriptRenderer::setOpacity (float /*opacity*/)
  67295. {
  67296. }
  67297. void LowLevelGraphicsPostScriptRenderer::setInterpolationQuality (Graphics::ResamplingQuality /*quality*/)
  67298. {
  67299. }
  67300. void LowLevelGraphicsPostScriptRenderer::fillRect (const Rectangle<int>& r, const bool /*replaceExistingContents*/)
  67301. {
  67302. if (stateStack.getLast()->fillType.isColour())
  67303. {
  67304. writeClip();
  67305. writeColour (stateStack.getLast()->fillType.colour);
  67306. Rectangle<int> r2 (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  67307. out << r2.getX() << ' ' << -r2.getBottom() << ' ' << r2.getWidth() << ' ' << r2.getHeight() << " rectfill\n";
  67308. }
  67309. else
  67310. {
  67311. Path p;
  67312. p.addRectangle (r);
  67313. fillPath (p, AffineTransform::identity);
  67314. }
  67315. }
  67316. void LowLevelGraphicsPostScriptRenderer::fillPath (const Path& path, const AffineTransform& t)
  67317. {
  67318. if (stateStack.getLast()->fillType.isColour())
  67319. {
  67320. writeClip();
  67321. Path p (path);
  67322. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset,
  67323. (float) stateStack.getLast()->yOffset));
  67324. writePath (p);
  67325. writeColour (stateStack.getLast()->fillType.colour);
  67326. out << "fill\n";
  67327. }
  67328. else if (stateStack.getLast()->fillType.isGradient())
  67329. {
  67330. // this doesn't work correctly yet - it could be improved to handle solid gradients, but
  67331. // postscript can't do semi-transparent ones.
  67332. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  67333. writeClip();
  67334. out << "gsave ";
  67335. {
  67336. Path p (path);
  67337. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  67338. writePath (p);
  67339. out << "clip\n";
  67340. }
  67341. const Rectangle<int> bounds (stateStack.getLast()->clip.getBounds());
  67342. // ideally this would draw lots of lines or ellipses to approximate the gradient, but for the
  67343. // time-being, this just fills it with the average colour..
  67344. writeColour (stateStack.getLast()->fillType.gradient->getColourAtPosition (0.5f));
  67345. out << bounds.getX() << ' ' << -bounds.getBottom() << ' ' << bounds.getWidth() << ' ' << bounds.getHeight() << " rectfill\n";
  67346. out << "grestore\n";
  67347. }
  67348. }
  67349. void LowLevelGraphicsPostScriptRenderer::writeImage (const Image& im,
  67350. const int sx, const int sy,
  67351. const int maxW, const int maxH) const
  67352. {
  67353. out << "{<\n";
  67354. const int w = jmin (maxW, im.getWidth());
  67355. const int h = jmin (maxH, im.getHeight());
  67356. int charsOnLine = 0;
  67357. const Image::BitmapData srcData (im, 0, 0, w, h);
  67358. Colour pixel;
  67359. for (int y = h; --y >= 0;)
  67360. {
  67361. for (int x = 0; x < w; ++x)
  67362. {
  67363. const uint8* pixelData = srcData.getPixelPointer (x, y);
  67364. if (x >= sx && y >= sy)
  67365. {
  67366. if (im.isARGB())
  67367. {
  67368. PixelARGB p (*(const PixelARGB*) pixelData);
  67369. p.unpremultiply();
  67370. pixel = Colours::white.overlaidWith (Colour (p.getARGB()));
  67371. }
  67372. else if (im.isRGB())
  67373. {
  67374. pixel = Colour (((const PixelRGB*) pixelData)->getARGB());
  67375. }
  67376. else
  67377. {
  67378. pixel = Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixelData);
  67379. }
  67380. }
  67381. else
  67382. {
  67383. pixel = Colours::transparentWhite;
  67384. }
  67385. const uint8 pixelValues[3] = { pixel.getRed(), pixel.getGreen(), pixel.getBlue() };
  67386. out << String::toHexString (pixelValues, 3, 0);
  67387. charsOnLine += 3;
  67388. if (charsOnLine > 100)
  67389. {
  67390. out << '\n';
  67391. charsOnLine = 0;
  67392. }
  67393. }
  67394. }
  67395. out << "\n>}\n";
  67396. }
  67397. void LowLevelGraphicsPostScriptRenderer::drawImage (const Image& sourceImage, const AffineTransform& transform, const bool /*fillEntireClipAsTiles*/)
  67398. {
  67399. const int w = sourceImage.getWidth();
  67400. const int h = sourceImage.getHeight();
  67401. writeClip();
  67402. out << "gsave ";
  67403. writeTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset)
  67404. .scaled (1.0f, -1.0f));
  67405. RectangleList imageClip;
  67406. sourceImage.createSolidAreaMask (imageClip, 0.5f);
  67407. out << "newpath ";
  67408. int itemsOnLine = 0;
  67409. for (RectangleList::Iterator i (imageClip); i.next();)
  67410. {
  67411. if (++itemsOnLine == 6)
  67412. {
  67413. out << '\n';
  67414. itemsOnLine = 0;
  67415. }
  67416. const Rectangle<int>& r = *i.getRectangle();
  67417. out << r.getX() << ' ' << r.getY() << ' ' << r.getWidth() << ' ' << r.getHeight() << " pr ";
  67418. }
  67419. out << " clip newpath\n";
  67420. out << w << ' ' << h << " scale\n";
  67421. out << w << ' ' << h << " 8 [" << w << " 0 0 -" << h << ' ' << (int) 0 << ' ' << h << " ]\n";
  67422. writeImage (sourceImage, 0, 0, w, h);
  67423. out << "false 3 colorimage grestore\n";
  67424. needToClip = true;
  67425. }
  67426. void LowLevelGraphicsPostScriptRenderer::drawLine (const Line <float>& line)
  67427. {
  67428. Path p;
  67429. p.addLineSegment (line, 1.0f);
  67430. fillPath (p, AffineTransform::identity);
  67431. }
  67432. void LowLevelGraphicsPostScriptRenderer::drawVerticalLine (const int x, float top, float bottom)
  67433. {
  67434. drawLine (Line<float> ((float) x, top, (float) x, bottom));
  67435. }
  67436. void LowLevelGraphicsPostScriptRenderer::drawHorizontalLine (const int y, float left, float right)
  67437. {
  67438. drawLine (Line<float> (left, (float) y, right, (float) y));
  67439. }
  67440. void LowLevelGraphicsPostScriptRenderer::setFont (const Font& newFont)
  67441. {
  67442. stateStack.getLast()->font = newFont;
  67443. }
  67444. const Font LowLevelGraphicsPostScriptRenderer::getFont()
  67445. {
  67446. return stateStack.getLast()->font;
  67447. }
  67448. void LowLevelGraphicsPostScriptRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  67449. {
  67450. Path p;
  67451. Font& font = stateStack.getLast()->font;
  67452. font.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  67453. fillPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight()).followedBy (transform));
  67454. }
  67455. END_JUCE_NAMESPACE
  67456. /*** End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  67457. /*** Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  67458. BEGIN_JUCE_NAMESPACE
  67459. #if (JUCE_WINDOWS || JUCE_LINUX) && ! JUCE_64BIT
  67460. #define JUCE_USE_SSE_INSTRUCTIONS 1
  67461. #endif
  67462. #if JUCE_MSVC
  67463. #pragma warning (push)
  67464. #pragma warning (disable: 4127) // "expression is constant" warning
  67465. #if JUCE_DEBUG
  67466. #pragma optimize ("t", on) // optimise just this file, to avoid sluggish graphics when debugging
  67467. #pragma warning (disable: 4714) // warning about forcedinline methods not being inlined
  67468. #endif
  67469. #endif
  67470. namespace SoftwareRendererClasses
  67471. {
  67472. template <class PixelType, bool replaceExisting = false>
  67473. class SolidColourEdgeTableRenderer
  67474. {
  67475. public:
  67476. SolidColourEdgeTableRenderer (const Image::BitmapData& data_, const PixelARGB& colour)
  67477. : data (data_),
  67478. sourceColour (colour)
  67479. {
  67480. if (sizeof (PixelType) == 3)
  67481. {
  67482. areRGBComponentsEqual = sourceColour.getRed() == sourceColour.getGreen()
  67483. && sourceColour.getGreen() == sourceColour.getBlue();
  67484. filler[0].set (sourceColour);
  67485. filler[1].set (sourceColour);
  67486. filler[2].set (sourceColour);
  67487. filler[3].set (sourceColour);
  67488. }
  67489. }
  67490. forcedinline void setEdgeTableYPos (const int y) throw()
  67491. {
  67492. linePixels = (PixelType*) data.getLinePointer (y);
  67493. }
  67494. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  67495. {
  67496. if (replaceExisting)
  67497. linePixels[x].set (sourceColour);
  67498. else
  67499. linePixels[x].blend (sourceColour, alphaLevel);
  67500. }
  67501. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67502. {
  67503. if (replaceExisting)
  67504. linePixels[x].set (sourceColour);
  67505. else
  67506. linePixels[x].blend (sourceColour);
  67507. }
  67508. forcedinline void handleEdgeTableLine (const int x, const int width, const int alphaLevel) const throw()
  67509. {
  67510. PixelARGB p (sourceColour);
  67511. p.multiplyAlpha (alphaLevel);
  67512. PixelType* dest = linePixels + x;
  67513. if (replaceExisting || p.getAlpha() >= 0xff)
  67514. replaceLine (dest, p, width);
  67515. else
  67516. blendLine (dest, p, width);
  67517. }
  67518. forcedinline void handleEdgeTableLineFull (const int x, const int width) const throw()
  67519. {
  67520. PixelType* dest = linePixels + x;
  67521. if (replaceExisting || sourceColour.getAlpha() >= 0xff)
  67522. replaceLine (dest, sourceColour, width);
  67523. else
  67524. blendLine (dest, sourceColour, width);
  67525. }
  67526. private:
  67527. const Image::BitmapData& data;
  67528. PixelType* linePixels;
  67529. PixelARGB sourceColour;
  67530. PixelRGB filler [4];
  67531. bool areRGBComponentsEqual;
  67532. inline void blendLine (PixelType* dest, const PixelARGB& colour, int width) const throw()
  67533. {
  67534. do
  67535. {
  67536. dest->blend (colour);
  67537. ++dest;
  67538. } while (--width > 0);
  67539. }
  67540. forcedinline void replaceLine (PixelRGB* dest, const PixelARGB& colour, int width) const throw()
  67541. {
  67542. if (areRGBComponentsEqual) // if all the component values are the same, we can cheat..
  67543. {
  67544. memset (dest, colour.getRed(), width * 3);
  67545. }
  67546. else
  67547. {
  67548. if (width >> 5)
  67549. {
  67550. const int* const intFiller = reinterpret_cast<const int*> (filler);
  67551. while (width > 8 && (((pointer_sized_int) dest) & 7) != 0)
  67552. {
  67553. dest->set (colour);
  67554. ++dest;
  67555. --width;
  67556. }
  67557. while (width > 4)
  67558. {
  67559. int* d = reinterpret_cast<int*> (dest);
  67560. *d++ = intFiller[0];
  67561. *d++ = intFiller[1];
  67562. *d++ = intFiller[2];
  67563. dest = reinterpret_cast<PixelRGB*> (d);
  67564. width -= 4;
  67565. }
  67566. }
  67567. while (--width >= 0)
  67568. {
  67569. dest->set (colour);
  67570. ++dest;
  67571. }
  67572. }
  67573. }
  67574. forcedinline void replaceLine (PixelAlpha* const dest, const PixelARGB& colour, int const width) const throw()
  67575. {
  67576. memset (dest, colour.getAlpha(), width);
  67577. }
  67578. forcedinline void replaceLine (PixelARGB* dest, const PixelARGB& colour, int width) const throw()
  67579. {
  67580. do
  67581. {
  67582. dest->set (colour);
  67583. ++dest;
  67584. } while (--width > 0);
  67585. }
  67586. SolidColourEdgeTableRenderer (const SolidColourEdgeTableRenderer&);
  67587. SolidColourEdgeTableRenderer& operator= (const SolidColourEdgeTableRenderer&);
  67588. };
  67589. class LinearGradientPixelGenerator
  67590. {
  67591. public:
  67592. LinearGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform, const PixelARGB* const lookupTable_, const int numEntries_)
  67593. : lookupTable (lookupTable_), numEntries (numEntries_)
  67594. {
  67595. jassert (numEntries_ >= 0);
  67596. Point<float> p1 (gradient.point1);
  67597. Point<float> p2 (gradient.point2);
  67598. if (! transform.isIdentity())
  67599. {
  67600. const Line<float> l (p2, p1);
  67601. Point<float> p3 = l.getPointAlongLine (0.0f, 100.0f);
  67602. p1.applyTransform (transform);
  67603. p2.applyTransform (transform);
  67604. p3.applyTransform (transform);
  67605. p2 = Line<float> (p2, p3).findNearestPointTo (p1);
  67606. }
  67607. vertical = std::abs (p1.getX() - p2.getX()) < 0.001f;
  67608. horizontal = std::abs (p1.getY() - p2.getY()) < 0.001f;
  67609. if (vertical)
  67610. {
  67611. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getY() - p1.getY()));
  67612. start = roundToInt (p1.getY() * scale);
  67613. }
  67614. else if (horizontal)
  67615. {
  67616. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getX() - p1.getX()));
  67617. start = roundToInt (p1.getX() * scale);
  67618. }
  67619. else
  67620. {
  67621. grad = (p2.getY() - p1.getY()) / (double) (p1.getX() - p2.getX());
  67622. yTerm = p1.getY() - p1.getX() / grad;
  67623. scale = roundToInt ((numEntries << (int) numScaleBits) / (yTerm * grad - (p2.getY() * grad - p2.getX())));
  67624. grad *= scale;
  67625. }
  67626. }
  67627. forcedinline void setY (const int y) throw()
  67628. {
  67629. if (vertical)
  67630. linePix = lookupTable [jlimit (0, numEntries, (y * scale - start) >> (int) numScaleBits)];
  67631. else if (! horizontal)
  67632. start = roundToInt ((y - yTerm) * grad);
  67633. }
  67634. inline const PixelARGB getPixel (const int x) const throw()
  67635. {
  67636. return vertical ? linePix
  67637. : lookupTable [jlimit (0, numEntries, (x * scale - start) >> (int) numScaleBits)];
  67638. }
  67639. private:
  67640. const PixelARGB* const lookupTable;
  67641. const int numEntries;
  67642. PixelARGB linePix;
  67643. int start, scale;
  67644. double grad, yTerm;
  67645. bool vertical, horizontal;
  67646. enum { numScaleBits = 12 };
  67647. LinearGradientPixelGenerator (const LinearGradientPixelGenerator&);
  67648. LinearGradientPixelGenerator& operator= (const LinearGradientPixelGenerator&);
  67649. };
  67650. class RadialGradientPixelGenerator
  67651. {
  67652. public:
  67653. RadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform&,
  67654. const PixelARGB* const lookupTable_, const int numEntries_)
  67655. : lookupTable (lookupTable_),
  67656. numEntries (numEntries_),
  67657. gx1 (gradient.point1.getX()),
  67658. gy1 (gradient.point1.getY())
  67659. {
  67660. jassert (numEntries_ >= 0);
  67661. const Point<float> diff (gradient.point1 - gradient.point2);
  67662. maxDist = diff.getX() * diff.getX() + diff.getY() * diff.getY();
  67663. invScale = numEntries / std::sqrt (maxDist);
  67664. jassert (roundToInt (std::sqrt (maxDist) * invScale) <= numEntries);
  67665. }
  67666. forcedinline void setY (const int y) throw()
  67667. {
  67668. dy = y - gy1;
  67669. dy *= dy;
  67670. }
  67671. inline const PixelARGB getPixel (const int px) const throw()
  67672. {
  67673. double x = px - gx1;
  67674. x *= x;
  67675. x += dy;
  67676. return lookupTable [x >= maxDist ? numEntries : roundToInt (std::sqrt (x) * invScale)];
  67677. }
  67678. protected:
  67679. const PixelARGB* const lookupTable;
  67680. const int numEntries;
  67681. const double gx1, gy1;
  67682. double maxDist, invScale, dy;
  67683. RadialGradientPixelGenerator (const RadialGradientPixelGenerator&);
  67684. RadialGradientPixelGenerator& operator= (const RadialGradientPixelGenerator&);
  67685. };
  67686. class TransformedRadialGradientPixelGenerator : public RadialGradientPixelGenerator
  67687. {
  67688. public:
  67689. TransformedRadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform,
  67690. const PixelARGB* const lookupTable_, const int numEntries_)
  67691. : RadialGradientPixelGenerator (gradient, transform, lookupTable_, numEntries_),
  67692. inverseTransform (transform.inverted())
  67693. {
  67694. tM10 = inverseTransform.mat10;
  67695. tM00 = inverseTransform.mat00;
  67696. }
  67697. forcedinline void setY (const int y) throw()
  67698. {
  67699. lineYM01 = inverseTransform.mat01 * y + inverseTransform.mat02 - gx1;
  67700. lineYM11 = inverseTransform.mat11 * y + inverseTransform.mat12 - gy1;
  67701. }
  67702. inline const PixelARGB getPixel (const int px) const throw()
  67703. {
  67704. double x = px;
  67705. const double y = tM10 * x + lineYM11;
  67706. x = tM00 * x + lineYM01;
  67707. x *= x;
  67708. x += y * y;
  67709. if (x >= maxDist)
  67710. return lookupTable [numEntries];
  67711. else
  67712. return lookupTable [jmin (numEntries, roundToInt (std::sqrt (x) * invScale))];
  67713. }
  67714. private:
  67715. double tM10, tM00, lineYM01, lineYM11;
  67716. const AffineTransform inverseTransform;
  67717. TransformedRadialGradientPixelGenerator (const TransformedRadialGradientPixelGenerator&);
  67718. TransformedRadialGradientPixelGenerator& operator= (const TransformedRadialGradientPixelGenerator&);
  67719. };
  67720. template <class PixelType, class GradientType>
  67721. class GradientEdgeTableRenderer : public GradientType
  67722. {
  67723. public:
  67724. GradientEdgeTableRenderer (const Image::BitmapData& destData_, const ColourGradient& gradient, const AffineTransform& transform,
  67725. const PixelARGB* const lookupTable_, const int numEntries_)
  67726. : GradientType (gradient, transform, lookupTable_, numEntries_ - 1),
  67727. destData (destData_)
  67728. {
  67729. }
  67730. forcedinline void setEdgeTableYPos (const int y) throw()
  67731. {
  67732. linePixels = (PixelType*) destData.getLinePointer (y);
  67733. GradientType::setY (y);
  67734. }
  67735. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  67736. {
  67737. linePixels[x].blend (GradientType::getPixel (x), alphaLevel);
  67738. }
  67739. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67740. {
  67741. linePixels[x].blend (GradientType::getPixel (x));
  67742. }
  67743. void handleEdgeTableLine (int x, int width, const int alphaLevel) const throw()
  67744. {
  67745. PixelType* dest = linePixels + x;
  67746. if (alphaLevel < 0xff)
  67747. {
  67748. do
  67749. {
  67750. (dest++)->blend (GradientType::getPixel (x++), alphaLevel);
  67751. } while (--width > 0);
  67752. }
  67753. else
  67754. {
  67755. do
  67756. {
  67757. (dest++)->blend (GradientType::getPixel (x++));
  67758. } while (--width > 0);
  67759. }
  67760. }
  67761. void handleEdgeTableLineFull (int x, int width) const throw()
  67762. {
  67763. PixelType* dest = linePixels + x;
  67764. do
  67765. {
  67766. (dest++)->blend (GradientType::getPixel (x++));
  67767. } while (--width > 0);
  67768. }
  67769. private:
  67770. const Image::BitmapData& destData;
  67771. PixelType* linePixels;
  67772. GradientEdgeTableRenderer (const GradientEdgeTableRenderer&);
  67773. GradientEdgeTableRenderer& operator= (const GradientEdgeTableRenderer&);
  67774. };
  67775. static forcedinline int safeModulo (int n, const int divisor) throw()
  67776. {
  67777. jassert (divisor > 0);
  67778. n %= divisor;
  67779. return (n < 0) ? (n + divisor) : n;
  67780. }
  67781. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  67782. class ImageFillEdgeTableRenderer
  67783. {
  67784. public:
  67785. ImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  67786. const Image::BitmapData& srcData_,
  67787. const int extraAlpha_,
  67788. const int x, const int y)
  67789. : destData (destData_),
  67790. srcData (srcData_),
  67791. extraAlpha (extraAlpha_ + 1),
  67792. xOffset (repeatPattern ? safeModulo (x, srcData_.width) - srcData_.width : x),
  67793. yOffset (repeatPattern ? safeModulo (y, srcData_.height) - srcData_.height : y)
  67794. {
  67795. }
  67796. forcedinline void setEdgeTableYPos (int y) throw()
  67797. {
  67798. linePixels = (DestPixelType*) destData.getLinePointer (y);
  67799. y -= yOffset;
  67800. if (repeatPattern)
  67801. {
  67802. jassert (y >= 0);
  67803. y %= srcData.height;
  67804. }
  67805. sourceLineStart = (SrcPixelType*) srcData.getLinePointer (y);
  67806. }
  67807. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) const throw()
  67808. {
  67809. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  67810. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], alphaLevel);
  67811. }
  67812. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67813. {
  67814. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], extraAlpha);
  67815. }
  67816. void handleEdgeTableLine (int x, int width, int alphaLevel) const throw()
  67817. {
  67818. DestPixelType* dest = linePixels + x;
  67819. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  67820. x -= xOffset;
  67821. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  67822. if (alphaLevel < 0xfe)
  67823. {
  67824. do
  67825. {
  67826. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], alphaLevel);
  67827. } while (--width > 0);
  67828. }
  67829. else
  67830. {
  67831. if (repeatPattern)
  67832. {
  67833. do
  67834. {
  67835. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  67836. } while (--width > 0);
  67837. }
  67838. else
  67839. {
  67840. copyRow (dest, sourceLineStart + x, width);
  67841. }
  67842. }
  67843. }
  67844. void handleEdgeTableLineFull (int x, int width) const throw()
  67845. {
  67846. DestPixelType* dest = linePixels + x;
  67847. x -= xOffset;
  67848. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  67849. if (extraAlpha < 0xfe)
  67850. {
  67851. do
  67852. {
  67853. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], extraAlpha);
  67854. } while (--width > 0);
  67855. }
  67856. else
  67857. {
  67858. if (repeatPattern)
  67859. {
  67860. do
  67861. {
  67862. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  67863. } while (--width > 0);
  67864. }
  67865. else
  67866. {
  67867. copyRow (dest, sourceLineStart + x, width);
  67868. }
  67869. }
  67870. }
  67871. void clipEdgeTableLine (EdgeTable& et, int x, int y, int width)
  67872. {
  67873. jassert (x - xOffset >= 0 && x + width - xOffset <= srcData.width);
  67874. SrcPixelType* s = (SrcPixelType*) srcData.getLinePointer (y - yOffset);
  67875. uint8* mask = (uint8*) (s + x - xOffset);
  67876. if (sizeof (SrcPixelType) == sizeof (PixelARGB))
  67877. mask += PixelARGB::indexA;
  67878. et.clipLineToMask (x, y, mask, sizeof (SrcPixelType), width);
  67879. }
  67880. private:
  67881. const Image::BitmapData& destData;
  67882. const Image::BitmapData& srcData;
  67883. const int extraAlpha, xOffset, yOffset;
  67884. DestPixelType* linePixels;
  67885. SrcPixelType* sourceLineStart;
  67886. template <class PixelType1, class PixelType2>
  67887. forcedinline static void copyRow (PixelType1* dest, PixelType2* src, int width) throw()
  67888. {
  67889. do
  67890. {
  67891. dest++ ->blend (*src++);
  67892. } while (--width > 0);
  67893. }
  67894. forcedinline static void copyRow (PixelRGB* dest, PixelRGB* src, int width) throw()
  67895. {
  67896. memcpy (dest, src, width * sizeof (PixelRGB));
  67897. }
  67898. ImageFillEdgeTableRenderer (const ImageFillEdgeTableRenderer&);
  67899. ImageFillEdgeTableRenderer& operator= (const ImageFillEdgeTableRenderer&);
  67900. };
  67901. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  67902. class TransformedImageFillEdgeTableRenderer
  67903. {
  67904. public:
  67905. TransformedImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  67906. const Image::BitmapData& srcData_,
  67907. const AffineTransform& transform,
  67908. const int extraAlpha_,
  67909. const bool betterQuality_)
  67910. : interpolator (transform),
  67911. destData (destData_),
  67912. srcData (srcData_),
  67913. extraAlpha (extraAlpha_ + 1),
  67914. betterQuality (betterQuality_),
  67915. pixelOffset (betterQuality_ ? 0.5f : 0.0f),
  67916. pixelOffsetInt (betterQuality_ ? -128 : 0),
  67917. maxX (srcData_.width - 1),
  67918. maxY (srcData_.height - 1),
  67919. scratchSize (2048)
  67920. {
  67921. scratchBuffer.malloc (scratchSize);
  67922. }
  67923. ~TransformedImageFillEdgeTableRenderer()
  67924. {
  67925. }
  67926. forcedinline void setEdgeTableYPos (const int newY) throw()
  67927. {
  67928. y = newY;
  67929. linePixels = (DestPixelType*) destData.getLinePointer (newY);
  67930. }
  67931. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) throw()
  67932. {
  67933. alphaLevel *= extraAlpha;
  67934. alphaLevel >>= 8;
  67935. SrcPixelType p;
  67936. generate (&p, x, 1);
  67937. linePixels[x].blend (p, alphaLevel);
  67938. }
  67939. forcedinline void handleEdgeTablePixelFull (const int x) throw()
  67940. {
  67941. SrcPixelType p;
  67942. generate (&p, x, 1);
  67943. linePixels[x].blend (p, extraAlpha);
  67944. }
  67945. void handleEdgeTableLine (const int x, int width, int alphaLevel) throw()
  67946. {
  67947. if (width > scratchSize)
  67948. {
  67949. scratchSize = width;
  67950. scratchBuffer.malloc (scratchSize);
  67951. }
  67952. SrcPixelType* span = scratchBuffer;
  67953. generate (span, x, width);
  67954. DestPixelType* dest = linePixels + x;
  67955. alphaLevel *= extraAlpha;
  67956. alphaLevel >>= 8;
  67957. if (alphaLevel < 0xfe)
  67958. {
  67959. do
  67960. {
  67961. dest++ ->blend (*span++, alphaLevel);
  67962. } while (--width > 0);
  67963. }
  67964. else
  67965. {
  67966. do
  67967. {
  67968. dest++ ->blend (*span++);
  67969. } while (--width > 0);
  67970. }
  67971. }
  67972. forcedinline void handleEdgeTableLineFull (const int x, int width) throw()
  67973. {
  67974. handleEdgeTableLine (x, width, 255);
  67975. }
  67976. void clipEdgeTableLine (EdgeTable& et, int x, int y_, int width)
  67977. {
  67978. if (width > scratchSize)
  67979. {
  67980. scratchSize = width;
  67981. scratchBuffer.malloc (scratchSize);
  67982. }
  67983. y = y_;
  67984. generate (scratchBuffer, x, width);
  67985. et.clipLineToMask (x, y_,
  67986. reinterpret_cast<uint8*> (scratchBuffer.getData()) + SrcPixelType::indexA,
  67987. sizeof (SrcPixelType), width);
  67988. }
  67989. private:
  67990. void generate (PixelARGB* dest, const int x, int numPixels) throw()
  67991. {
  67992. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  67993. do
  67994. {
  67995. int hiResX, hiResY;
  67996. this->interpolator.next (hiResX, hiResY);
  67997. hiResX += pixelOffsetInt;
  67998. hiResY += pixelOffsetInt;
  67999. int loResX = hiResX >> 8;
  68000. int loResY = hiResY >> 8;
  68001. if (repeatPattern)
  68002. {
  68003. loResX = safeModulo (loResX, srcData.width);
  68004. loResY = safeModulo (loResY, srcData.height);
  68005. }
  68006. if (betterQuality
  68007. && ((unsigned int) loResX) < (unsigned int) maxX
  68008. && ((unsigned int) loResY) < (unsigned int) maxY)
  68009. {
  68010. uint32 c[4] = { 256 * 128, 256 * 128, 256 * 128, 256 * 128 };
  68011. hiResX &= 255;
  68012. hiResY &= 255;
  68013. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  68014. uint32 weight = (256 - hiResX) * (256 - hiResY);
  68015. c[0] += weight * src[0];
  68016. c[1] += weight * src[1];
  68017. c[2] += weight * src[2];
  68018. c[3] += weight * src[3];
  68019. weight = hiResX * (256 - hiResY);
  68020. c[0] += weight * src[4];
  68021. c[1] += weight * src[5];
  68022. c[2] += weight * src[6];
  68023. c[3] += weight * src[7];
  68024. src += this->srcData.lineStride;
  68025. weight = (256 - hiResX) * hiResY;
  68026. c[0] += weight * src[0];
  68027. c[1] += weight * src[1];
  68028. c[2] += weight * src[2];
  68029. c[3] += weight * src[3];
  68030. weight = hiResX * hiResY;
  68031. c[0] += weight * src[4];
  68032. c[1] += weight * src[5];
  68033. c[2] += weight * src[6];
  68034. c[3] += weight * src[7];
  68035. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 16),
  68036. (uint8) (c[PixelARGB::indexR] >> 16),
  68037. (uint8) (c[PixelARGB::indexG] >> 16),
  68038. (uint8) (c[PixelARGB::indexB] >> 16));
  68039. }
  68040. else
  68041. {
  68042. if (! repeatPattern)
  68043. {
  68044. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  68045. if (loResX < 0) loResX = 0;
  68046. if (loResY < 0) loResY = 0;
  68047. if (loResX > maxX) loResX = maxX;
  68048. if (loResY > maxY) loResY = maxY;
  68049. }
  68050. dest->set (*(const PixelARGB*) this->srcData.getPixelPointer (loResX, loResY));
  68051. }
  68052. ++dest;
  68053. } while (--numPixels > 0);
  68054. }
  68055. void generate (PixelRGB* dest, const int x, int numPixels) throw()
  68056. {
  68057. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  68058. do
  68059. {
  68060. int hiResX, hiResY;
  68061. this->interpolator.next (hiResX, hiResY);
  68062. hiResX += pixelOffsetInt;
  68063. hiResY += pixelOffsetInt;
  68064. int loResX = hiResX >> 8;
  68065. int loResY = hiResY >> 8;
  68066. if (repeatPattern)
  68067. {
  68068. loResX = safeModulo (loResX, srcData.width);
  68069. loResY = safeModulo (loResY, srcData.height);
  68070. }
  68071. if (betterQuality
  68072. && ((unsigned int) loResX) < (unsigned int) maxX
  68073. && ((unsigned int) loResY) < (unsigned int) maxY)
  68074. {
  68075. uint32 c[3] = { 256 * 128, 256 * 128, 256 * 128 };
  68076. hiResX &= 255;
  68077. hiResY &= 255;
  68078. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  68079. unsigned int weight = (256 - hiResX) * (256 - hiResY);
  68080. c[0] += weight * src[0];
  68081. c[1] += weight * src[1];
  68082. c[2] += weight * src[2];
  68083. weight = hiResX * (256 - hiResY);
  68084. c[0] += weight * src[3];
  68085. c[1] += weight * src[4];
  68086. c[2] += weight * src[5];
  68087. src += this->srcData.lineStride;
  68088. weight = (256 - hiResX) * hiResY;
  68089. c[0] += weight * src[0];
  68090. c[1] += weight * src[1];
  68091. c[2] += weight * src[2];
  68092. weight = hiResX * hiResY;
  68093. c[0] += weight * src[3];
  68094. c[1] += weight * src[4];
  68095. c[2] += weight * src[5];
  68096. dest->setARGB ((uint8) 255,
  68097. (uint8) (c[PixelRGB::indexR] >> 16),
  68098. (uint8) (c[PixelRGB::indexG] >> 16),
  68099. (uint8) (c[PixelRGB::indexB] >> 16));
  68100. }
  68101. else
  68102. {
  68103. if (! repeatPattern)
  68104. {
  68105. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  68106. if (loResX < 0) loResX = 0;
  68107. if (loResY < 0) loResY = 0;
  68108. if (loResX > maxX) loResX = maxX;
  68109. if (loResY > maxY) loResY = maxY;
  68110. }
  68111. dest->set (*(const PixelRGB*) this->srcData.getPixelPointer (loResX, loResY));
  68112. }
  68113. ++dest;
  68114. } while (--numPixels > 0);
  68115. }
  68116. void generate (PixelAlpha* dest, const int x, int numPixels) throw()
  68117. {
  68118. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  68119. do
  68120. {
  68121. int hiResX, hiResY;
  68122. this->interpolator.next (hiResX, hiResY);
  68123. hiResX += pixelOffsetInt;
  68124. hiResY += pixelOffsetInt;
  68125. int loResX = hiResX >> 8;
  68126. int loResY = hiResY >> 8;
  68127. if (repeatPattern)
  68128. {
  68129. loResX = safeModulo (loResX, srcData.width);
  68130. loResY = safeModulo (loResY, srcData.height);
  68131. }
  68132. if (betterQuality
  68133. && ((unsigned int) loResX) < (unsigned int) maxX
  68134. && ((unsigned int) loResY) < (unsigned int) maxY)
  68135. {
  68136. hiResX &= 255;
  68137. hiResY &= 255;
  68138. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  68139. uint32 c = 256 * 128;
  68140. c += src[0] * ((256 - hiResX) * (256 - hiResY));
  68141. c += src[1] * (hiResX * (256 - hiResY));
  68142. src += this->srcData.lineStride;
  68143. c += src[0] * ((256 - hiResX) * hiResY);
  68144. c += src[1] * (hiResX * hiResY);
  68145. *((uint8*) dest) = (uint8) c;
  68146. }
  68147. else
  68148. {
  68149. if (! repeatPattern)
  68150. {
  68151. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  68152. if (loResX < 0) loResX = 0;
  68153. if (loResY < 0) loResY = 0;
  68154. if (loResX > maxX) loResX = maxX;
  68155. if (loResY > maxY) loResY = maxY;
  68156. }
  68157. *((uint8*) dest) = *(this->srcData.getPixelPointer (loResX, loResY));
  68158. }
  68159. ++dest;
  68160. } while (--numPixels > 0);
  68161. }
  68162. class TransformedImageSpanInterpolator
  68163. {
  68164. public:
  68165. TransformedImageSpanInterpolator (const AffineTransform& transform) throw()
  68166. : inverseTransform (transform.inverted())
  68167. {}
  68168. void setStartOfLine (float x, float y, const int numPixels) throw()
  68169. {
  68170. float x1 = x, y1 = y;
  68171. x += numPixels;
  68172. inverseTransform.transformPoints (x1, y1, x, y);
  68173. xBresenham.set ((int) (x1 * 256.0f), (int) (x * 256.0f), numPixels);
  68174. yBresenham.set ((int) (y1 * 256.0f), (int) (y * 256.0f), numPixels);
  68175. }
  68176. void next (int& x, int& y) throw()
  68177. {
  68178. x = xBresenham.n;
  68179. xBresenham.stepToNext();
  68180. y = yBresenham.n;
  68181. yBresenham.stepToNext();
  68182. }
  68183. private:
  68184. class BresenhamInterpolator
  68185. {
  68186. public:
  68187. BresenhamInterpolator() throw() {}
  68188. void set (const int n1, const int n2, const int numSteps_) throw()
  68189. {
  68190. numSteps = jmax (1, numSteps_);
  68191. step = (n2 - n1) / numSteps;
  68192. remainder = modulo = (n2 - n1) % numSteps;
  68193. n = n1;
  68194. if (modulo <= 0)
  68195. {
  68196. modulo += numSteps;
  68197. remainder += numSteps;
  68198. --step;
  68199. }
  68200. modulo -= numSteps;
  68201. }
  68202. forcedinline void stepToNext() throw()
  68203. {
  68204. modulo += remainder;
  68205. n += step;
  68206. if (modulo > 0)
  68207. {
  68208. modulo -= numSteps;
  68209. ++n;
  68210. }
  68211. }
  68212. int n;
  68213. private:
  68214. int numSteps, step, modulo, remainder;
  68215. };
  68216. const AffineTransform inverseTransform;
  68217. BresenhamInterpolator xBresenham, yBresenham;
  68218. TransformedImageSpanInterpolator (const TransformedImageSpanInterpolator&);
  68219. TransformedImageSpanInterpolator& operator= (const TransformedImageSpanInterpolator&);
  68220. };
  68221. TransformedImageSpanInterpolator interpolator;
  68222. const Image::BitmapData& destData;
  68223. const Image::BitmapData& srcData;
  68224. const int extraAlpha;
  68225. const bool betterQuality;
  68226. const float pixelOffset;
  68227. const int pixelOffsetInt, maxX, maxY;
  68228. int y;
  68229. DestPixelType* linePixels;
  68230. HeapBlock <SrcPixelType> scratchBuffer;
  68231. int scratchSize;
  68232. TransformedImageFillEdgeTableRenderer (const TransformedImageFillEdgeTableRenderer&);
  68233. TransformedImageFillEdgeTableRenderer& operator= (const TransformedImageFillEdgeTableRenderer&);
  68234. };
  68235. class ClipRegionBase : public ReferenceCountedObject
  68236. {
  68237. public:
  68238. ClipRegionBase() {}
  68239. virtual ~ClipRegionBase() {}
  68240. typedef ReferenceCountedObjectPtr<ClipRegionBase> Ptr;
  68241. virtual const Ptr clone() const = 0;
  68242. virtual const Ptr applyClipTo (const Ptr& target) const = 0;
  68243. virtual const Ptr clipToRectangle (const Rectangle<int>& r) = 0;
  68244. virtual const Ptr clipToRectangleList (const RectangleList& r) = 0;
  68245. virtual const Ptr excludeClipRectangle (const Rectangle<int>& r) = 0;
  68246. virtual const Ptr clipToPath (const Path& p, const AffineTransform& transform) = 0;
  68247. virtual const Ptr clipToEdgeTable (const EdgeTable& et) = 0;
  68248. virtual const Ptr clipToImageAlpha (const Image& image, const AffineTransform& t, const bool betterQuality) = 0;
  68249. virtual bool clipRegionIntersects (const Rectangle<int>& r) const = 0;
  68250. virtual const Rectangle<int> getClipBounds() const = 0;
  68251. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const = 0;
  68252. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const = 0;
  68253. virtual void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const = 0;
  68254. virtual void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const = 0;
  68255. virtual void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& t, bool betterQuality, bool tiledFill) const = 0;
  68256. virtual void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const = 0;
  68257. protected:
  68258. template <class Iterator>
  68259. static void renderImageTransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData,
  68260. const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill)
  68261. {
  68262. switch (destData.pixelFormat)
  68263. {
  68264. case Image::ARGB:
  68265. switch (srcData.pixelFormat)
  68266. {
  68267. case Image::ARGB:
  68268. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68269. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68270. break;
  68271. case Image::RGB:
  68272. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68273. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68274. break;
  68275. default:
  68276. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68277. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68278. break;
  68279. }
  68280. break;
  68281. case Image::RGB:
  68282. switch (srcData.pixelFormat)
  68283. {
  68284. case Image::ARGB:
  68285. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68286. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68287. break;
  68288. case Image::RGB:
  68289. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68290. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68291. break;
  68292. default:
  68293. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68294. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68295. break;
  68296. }
  68297. break;
  68298. default:
  68299. switch (srcData.pixelFormat)
  68300. {
  68301. case Image::ARGB:
  68302. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68303. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68304. break;
  68305. case Image::RGB:
  68306. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68307. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68308. break;
  68309. default:
  68310. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68311. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68312. break;
  68313. }
  68314. break;
  68315. }
  68316. }
  68317. template <class Iterator>
  68318. static void renderImageUntransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill)
  68319. {
  68320. switch (destData.pixelFormat)
  68321. {
  68322. case Image::ARGB:
  68323. switch (srcData.pixelFormat)
  68324. {
  68325. case Image::ARGB:
  68326. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68327. else { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68328. break;
  68329. case Image::RGB:
  68330. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68331. else { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68332. break;
  68333. default:
  68334. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68335. else { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68336. break;
  68337. }
  68338. break;
  68339. case Image::RGB:
  68340. switch (srcData.pixelFormat)
  68341. {
  68342. case Image::ARGB:
  68343. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68344. else { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68345. break;
  68346. case Image::RGB:
  68347. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68348. else { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68349. break;
  68350. default:
  68351. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68352. else { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68353. break;
  68354. }
  68355. break;
  68356. default:
  68357. switch (srcData.pixelFormat)
  68358. {
  68359. case Image::ARGB:
  68360. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68361. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68362. break;
  68363. case Image::RGB:
  68364. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68365. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68366. break;
  68367. default:
  68368. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68369. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68370. break;
  68371. }
  68372. break;
  68373. }
  68374. }
  68375. template <class Iterator, class DestPixelType>
  68376. static void renderSolidFill (Iterator& iter, const Image::BitmapData& destData, const PixelARGB& fillColour, const bool replaceContents, DestPixelType*)
  68377. {
  68378. jassert (destData.pixelStride == sizeof (DestPixelType));
  68379. if (replaceContents)
  68380. {
  68381. SolidColourEdgeTableRenderer <DestPixelType, true> r (destData, fillColour);
  68382. iter.iterate (r);
  68383. }
  68384. else
  68385. {
  68386. SolidColourEdgeTableRenderer <DestPixelType, false> r (destData, fillColour);
  68387. iter.iterate (r);
  68388. }
  68389. }
  68390. template <class Iterator, class DestPixelType>
  68391. static void renderGradient (Iterator& iter, const Image::BitmapData& destData, const ColourGradient& g, const AffineTransform& transform,
  68392. const PixelARGB* const lookupTable, const int numLookupEntries, const bool isIdentity, DestPixelType*)
  68393. {
  68394. jassert (destData.pixelStride == sizeof (DestPixelType));
  68395. if (g.isRadial)
  68396. {
  68397. if (isIdentity)
  68398. {
  68399. GradientEdgeTableRenderer <DestPixelType, RadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68400. iter.iterate (renderer);
  68401. }
  68402. else
  68403. {
  68404. GradientEdgeTableRenderer <DestPixelType, TransformedRadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68405. iter.iterate (renderer);
  68406. }
  68407. }
  68408. else
  68409. {
  68410. GradientEdgeTableRenderer <DestPixelType, LinearGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68411. iter.iterate (renderer);
  68412. }
  68413. }
  68414. };
  68415. class ClipRegion_EdgeTable : public ClipRegionBase
  68416. {
  68417. public:
  68418. ClipRegion_EdgeTable (const EdgeTable& e) : edgeTable (e) {}
  68419. ClipRegion_EdgeTable (const Rectangle<int>& r) : edgeTable (r) {}
  68420. ClipRegion_EdgeTable (const Rectangle<float>& r) : edgeTable (r) {}
  68421. ClipRegion_EdgeTable (const RectangleList& r) : edgeTable (r) {}
  68422. ClipRegion_EdgeTable (const Rectangle<int>& bounds, const Path& p, const AffineTransform& t) : edgeTable (bounds, p, t) {}
  68423. ClipRegion_EdgeTable (const ClipRegion_EdgeTable& other) : edgeTable (other.edgeTable) {}
  68424. ~ClipRegion_EdgeTable() {}
  68425. const Ptr clone() const
  68426. {
  68427. return new ClipRegion_EdgeTable (*this);
  68428. }
  68429. const Ptr applyClipTo (const Ptr& target) const
  68430. {
  68431. return target->clipToEdgeTable (edgeTable);
  68432. }
  68433. const Ptr clipToRectangle (const Rectangle<int>& r)
  68434. {
  68435. edgeTable.clipToRectangle (r);
  68436. return edgeTable.isEmpty() ? 0 : this;
  68437. }
  68438. const Ptr clipToRectangleList (const RectangleList& r)
  68439. {
  68440. RectangleList inverse (edgeTable.getMaximumBounds());
  68441. if (inverse.subtract (r))
  68442. for (RectangleList::Iterator iter (inverse); iter.next();)
  68443. edgeTable.excludeRectangle (*iter.getRectangle());
  68444. return edgeTable.isEmpty() ? 0 : this;
  68445. }
  68446. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  68447. {
  68448. edgeTable.excludeRectangle (r);
  68449. return edgeTable.isEmpty() ? 0 : this;
  68450. }
  68451. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  68452. {
  68453. EdgeTable et (edgeTable.getMaximumBounds(), p, transform);
  68454. edgeTable.clipToEdgeTable (et);
  68455. return edgeTable.isEmpty() ? 0 : this;
  68456. }
  68457. const Ptr clipToEdgeTable (const EdgeTable& et)
  68458. {
  68459. edgeTable.clipToEdgeTable (et);
  68460. return edgeTable.isEmpty() ? 0 : this;
  68461. }
  68462. const Ptr clipToImageAlpha (const Image& image, const AffineTransform& transform, const bool betterQuality)
  68463. {
  68464. const Image::BitmapData srcData (image, false);
  68465. if (transform.isOnlyTranslation())
  68466. {
  68467. // If our translation doesn't involve any distortion, just use a simple blit..
  68468. const int tx = (int) (transform.getTranslationX() * 256.0f);
  68469. const int ty = (int) (transform.getTranslationY() * 256.0f);
  68470. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  68471. {
  68472. const int imageX = ((tx + 128) >> 8);
  68473. const int imageY = ((ty + 128) >> 8);
  68474. if (image.getFormat() == Image::ARGB)
  68475. straightClipImage (srcData, imageX, imageY, (PixelARGB*) 0);
  68476. else
  68477. straightClipImage (srcData, imageX, imageY, (PixelAlpha*) 0);
  68478. return edgeTable.isEmpty() ? 0 : this;
  68479. }
  68480. }
  68481. if (transform.isSingularity())
  68482. return 0;
  68483. {
  68484. Path p;
  68485. p.addRectangle (0, 0, (float) srcData.width, (float) srcData.height);
  68486. EdgeTable et2 (edgeTable.getMaximumBounds(), p, transform);
  68487. edgeTable.clipToEdgeTable (et2);
  68488. }
  68489. if (! edgeTable.isEmpty())
  68490. {
  68491. if (image.getFormat() == Image::ARGB)
  68492. transformedClipImage (srcData, transform, betterQuality, (PixelARGB*) 0);
  68493. else
  68494. transformedClipImage (srcData, transform, betterQuality, (PixelAlpha*) 0);
  68495. }
  68496. return edgeTable.isEmpty() ? 0 : this;
  68497. }
  68498. bool clipRegionIntersects (const Rectangle<int>& r) const
  68499. {
  68500. return edgeTable.getMaximumBounds().intersects (r);
  68501. }
  68502. const Rectangle<int> getClipBounds() const
  68503. {
  68504. return edgeTable.getMaximumBounds();
  68505. }
  68506. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  68507. {
  68508. const Rectangle<int> totalClip (edgeTable.getMaximumBounds());
  68509. const Rectangle<int> clipped (totalClip.getIntersection (area));
  68510. if (! clipped.isEmpty())
  68511. {
  68512. ClipRegion_EdgeTable et (clipped);
  68513. et.edgeTable.clipToEdgeTable (edgeTable);
  68514. et.fillAllWithColour (destData, colour, replaceContents);
  68515. }
  68516. }
  68517. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  68518. {
  68519. const Rectangle<float> totalClip (edgeTable.getMaximumBounds().toFloat());
  68520. const Rectangle<float> clipped (totalClip.getIntersection (area));
  68521. if (! clipped.isEmpty())
  68522. {
  68523. ClipRegion_EdgeTable et (clipped);
  68524. et.edgeTable.clipToEdgeTable (edgeTable);
  68525. et.fillAllWithColour (destData, colour, false);
  68526. }
  68527. }
  68528. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  68529. {
  68530. switch (destData.pixelFormat)
  68531. {
  68532. case Image::ARGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68533. case Image::RGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68534. default: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68535. }
  68536. }
  68537. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  68538. {
  68539. HeapBlock <PixelARGB> lookupTable;
  68540. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  68541. jassert (numLookupEntries > 0);
  68542. switch (destData.pixelFormat)
  68543. {
  68544. case Image::ARGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  68545. case Image::RGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  68546. default: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  68547. }
  68548. }
  68549. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  68550. {
  68551. renderImageTransformedInternal (edgeTable, destData, srcData, alpha, transform, betterQuality, tiledFill);
  68552. }
  68553. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  68554. {
  68555. renderImageUntransformedInternal (edgeTable, destData, srcData, alpha, x, y, tiledFill);
  68556. }
  68557. EdgeTable edgeTable;
  68558. private:
  68559. template <class SrcPixelType>
  68560. void transformedClipImage (const Image::BitmapData& srcData, const AffineTransform& transform, const bool betterQuality, const SrcPixelType*)
  68561. {
  68562. TransformedImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, transform, 255, betterQuality);
  68563. for (int y = 0; y < edgeTable.getMaximumBounds().getHeight(); ++y)
  68564. renderer.clipEdgeTableLine (edgeTable, edgeTable.getMaximumBounds().getX(), y + edgeTable.getMaximumBounds().getY(),
  68565. edgeTable.getMaximumBounds().getWidth());
  68566. }
  68567. template <class SrcPixelType>
  68568. void straightClipImage (const Image::BitmapData& srcData, int imageX, int imageY, const SrcPixelType*)
  68569. {
  68570. Rectangle<int> r (imageX, imageY, srcData.width, srcData.height);
  68571. edgeTable.clipToRectangle (r);
  68572. ImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, 255, imageX, imageY);
  68573. for (int y = 0; y < r.getHeight(); ++y)
  68574. renderer.clipEdgeTableLine (edgeTable, r.getX(), y + r.getY(), r.getWidth());
  68575. }
  68576. ClipRegion_EdgeTable& operator= (const ClipRegion_EdgeTable&);
  68577. };
  68578. class ClipRegion_RectangleList : public ClipRegionBase
  68579. {
  68580. public:
  68581. ClipRegion_RectangleList (const Rectangle<int>& r) : clip (r) {}
  68582. ClipRegion_RectangleList (const RectangleList& r) : clip (r) {}
  68583. ClipRegion_RectangleList (const ClipRegion_RectangleList& other) : clip (other.clip) {}
  68584. ~ClipRegion_RectangleList() {}
  68585. const Ptr clone() const
  68586. {
  68587. return new ClipRegion_RectangleList (*this);
  68588. }
  68589. const Ptr applyClipTo (const Ptr& target) const
  68590. {
  68591. return target->clipToRectangleList (clip);
  68592. }
  68593. const Ptr clipToRectangle (const Rectangle<int>& r)
  68594. {
  68595. clip.clipTo (r);
  68596. return clip.isEmpty() ? 0 : this;
  68597. }
  68598. const Ptr clipToRectangleList (const RectangleList& r)
  68599. {
  68600. clip.clipTo (r);
  68601. return clip.isEmpty() ? 0 : this;
  68602. }
  68603. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  68604. {
  68605. clip.subtract (r);
  68606. return clip.isEmpty() ? 0 : this;
  68607. }
  68608. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  68609. {
  68610. return Ptr (new ClipRegion_EdgeTable (clip))->clipToPath (p, transform);
  68611. }
  68612. const Ptr clipToEdgeTable (const EdgeTable& et)
  68613. {
  68614. return Ptr (new ClipRegion_EdgeTable (clip))->clipToEdgeTable (et);
  68615. }
  68616. const Ptr clipToImageAlpha (const Image& image, const AffineTransform& transform, const bool betterQuality)
  68617. {
  68618. return Ptr (new ClipRegion_EdgeTable (clip))->clipToImageAlpha (image, transform, betterQuality);
  68619. }
  68620. bool clipRegionIntersects (const Rectangle<int>& r) const
  68621. {
  68622. return clip.intersects (r);
  68623. }
  68624. const Rectangle<int> getClipBounds() const
  68625. {
  68626. return clip.getBounds();
  68627. }
  68628. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  68629. {
  68630. SubRectangleIterator iter (clip, area);
  68631. switch (destData.pixelFormat)
  68632. {
  68633. case Image::ARGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68634. case Image::RGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68635. default: renderSolidFill (iter, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68636. }
  68637. }
  68638. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  68639. {
  68640. SubRectangleIteratorFloat iter (clip, area);
  68641. switch (destData.pixelFormat)
  68642. {
  68643. case Image::ARGB: renderSolidFill (iter, destData, colour, false, (PixelARGB*) 0); break;
  68644. case Image::RGB: renderSolidFill (iter, destData, colour, false, (PixelRGB*) 0); break;
  68645. default: renderSolidFill (iter, destData, colour, false, (PixelAlpha*) 0); break;
  68646. }
  68647. }
  68648. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  68649. {
  68650. switch (destData.pixelFormat)
  68651. {
  68652. case Image::ARGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68653. case Image::RGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68654. default: renderSolidFill (*this, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68655. }
  68656. }
  68657. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  68658. {
  68659. HeapBlock <PixelARGB> lookupTable;
  68660. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  68661. jassert (numLookupEntries > 0);
  68662. switch (destData.pixelFormat)
  68663. {
  68664. case Image::ARGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  68665. case Image::RGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  68666. default: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  68667. }
  68668. }
  68669. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  68670. {
  68671. renderImageTransformedInternal (*this, destData, srcData, alpha, transform, betterQuality, tiledFill);
  68672. }
  68673. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  68674. {
  68675. renderImageUntransformedInternal (*this, destData, srcData, alpha, x, y, tiledFill);
  68676. }
  68677. RectangleList clip;
  68678. template <class Renderer>
  68679. void iterate (Renderer& r) const throw()
  68680. {
  68681. RectangleList::Iterator iter (clip);
  68682. while (iter.next())
  68683. {
  68684. const Rectangle<int> rect (*iter.getRectangle());
  68685. const int x = rect.getX();
  68686. const int w = rect.getWidth();
  68687. jassert (w > 0);
  68688. const int bottom = rect.getBottom();
  68689. for (int y = rect.getY(); y < bottom; ++y)
  68690. {
  68691. r.setEdgeTableYPos (y);
  68692. r.handleEdgeTableLineFull (x, w);
  68693. }
  68694. }
  68695. }
  68696. private:
  68697. class SubRectangleIterator
  68698. {
  68699. public:
  68700. SubRectangleIterator (const RectangleList& clip_, const Rectangle<int>& area_)
  68701. : clip (clip_), area (area_)
  68702. {
  68703. }
  68704. template <class Renderer>
  68705. void iterate (Renderer& r) const throw()
  68706. {
  68707. RectangleList::Iterator iter (clip);
  68708. while (iter.next())
  68709. {
  68710. const Rectangle<int> rect (iter.getRectangle()->getIntersection (area));
  68711. if (! rect.isEmpty())
  68712. {
  68713. const int x = rect.getX();
  68714. const int w = rect.getWidth();
  68715. const int bottom = rect.getBottom();
  68716. for (int y = rect.getY(); y < bottom; ++y)
  68717. {
  68718. r.setEdgeTableYPos (y);
  68719. r.handleEdgeTableLineFull (x, w);
  68720. }
  68721. }
  68722. }
  68723. }
  68724. private:
  68725. const RectangleList& clip;
  68726. const Rectangle<int> area;
  68727. SubRectangleIterator (const SubRectangleIterator&);
  68728. SubRectangleIterator& operator= (const SubRectangleIterator&);
  68729. };
  68730. class SubRectangleIteratorFloat
  68731. {
  68732. public:
  68733. SubRectangleIteratorFloat (const RectangleList& clip_, const Rectangle<float>& area_)
  68734. : clip (clip_), area (area_)
  68735. {
  68736. }
  68737. template <class Renderer>
  68738. void iterate (Renderer& r) const throw()
  68739. {
  68740. int left = roundToInt (area.getX() * 256.0f);
  68741. int top = roundToInt (area.getY() * 256.0f);
  68742. int right = roundToInt (area.getRight() * 256.0f);
  68743. int bottom = roundToInt (area.getBottom() * 256.0f);
  68744. int totalTop, totalLeft, totalBottom, totalRight;
  68745. int topAlpha, leftAlpha, bottomAlpha, rightAlpha;
  68746. if ((top >> 8) == (bottom >> 8))
  68747. {
  68748. topAlpha = bottom - top;
  68749. bottomAlpha = 0;
  68750. totalTop = top >> 8;
  68751. totalBottom = bottom = top = totalTop + 1;
  68752. }
  68753. else
  68754. {
  68755. if ((top & 255) == 0)
  68756. {
  68757. topAlpha = 0;
  68758. top = totalTop = (top >> 8);
  68759. }
  68760. else
  68761. {
  68762. topAlpha = 255 - (top & 255);
  68763. totalTop = (top >> 8);
  68764. top = totalTop + 1;
  68765. }
  68766. bottomAlpha = bottom & 255;
  68767. bottom >>= 8;
  68768. totalBottom = bottom + (bottomAlpha != 0 ? 1 : 0);
  68769. }
  68770. if ((left >> 8) == (right >> 8))
  68771. {
  68772. leftAlpha = right - left;
  68773. rightAlpha = 0;
  68774. totalLeft = (left >> 8);
  68775. totalRight = right = left = totalLeft + 1;
  68776. }
  68777. else
  68778. {
  68779. if ((left & 255) == 0)
  68780. {
  68781. leftAlpha = 0;
  68782. left = totalLeft = (left >> 8);
  68783. }
  68784. else
  68785. {
  68786. leftAlpha = 255 - (left & 255);
  68787. totalLeft = (left >> 8);
  68788. left = totalLeft + 1;
  68789. }
  68790. rightAlpha = right & 255;
  68791. right >>= 8;
  68792. totalRight = right + (rightAlpha != 0 ? 1 : 0);
  68793. }
  68794. RectangleList::Iterator iter (clip);
  68795. while (iter.next())
  68796. {
  68797. const int clipLeft = iter.getRectangle()->getX();
  68798. const int clipRight = iter.getRectangle()->getRight();
  68799. const int clipTop = iter.getRectangle()->getY();
  68800. const int clipBottom = iter.getRectangle()->getBottom();
  68801. if (totalBottom > clipTop && totalTop < clipBottom && totalRight > clipLeft && totalLeft < clipRight)
  68802. {
  68803. if (right - left == 1 && leftAlpha + rightAlpha == 0) // special case for 1-pix vertical lines
  68804. {
  68805. if (topAlpha != 0 && totalTop >= clipTop)
  68806. {
  68807. r.setEdgeTableYPos (totalTop);
  68808. r.handleEdgeTablePixel (left, topAlpha);
  68809. }
  68810. const int endY = jmin (bottom, clipBottom);
  68811. for (int y = jmax (clipTop, top); y < endY; ++y)
  68812. {
  68813. r.setEdgeTableYPos (y);
  68814. r.handleEdgeTablePixelFull (left);
  68815. }
  68816. if (bottomAlpha != 0 && bottom < clipBottom)
  68817. {
  68818. r.setEdgeTableYPos (bottom);
  68819. r.handleEdgeTablePixel (left, bottomAlpha);
  68820. }
  68821. }
  68822. else
  68823. {
  68824. const int clippedLeft = jmax (left, clipLeft);
  68825. const int clippedWidth = jmin (right, clipRight) - clippedLeft;
  68826. const bool doLeftAlpha = leftAlpha != 0 && totalLeft >= clipLeft;
  68827. const bool doRightAlpha = rightAlpha != 0 && right < clipRight;
  68828. if (topAlpha != 0 && totalTop >= clipTop)
  68829. {
  68830. r.setEdgeTableYPos (totalTop);
  68831. if (doLeftAlpha)
  68832. r.handleEdgeTablePixel (totalLeft, (leftAlpha * topAlpha) >> 8);
  68833. if (clippedWidth > 0)
  68834. r.handleEdgeTableLine (clippedLeft, clippedWidth, topAlpha);
  68835. if (doRightAlpha)
  68836. r.handleEdgeTablePixel (right, (rightAlpha * topAlpha) >> 8);
  68837. }
  68838. const int endY = jmin (bottom, clipBottom);
  68839. for (int y = jmax (clipTop, top); y < endY; ++y)
  68840. {
  68841. r.setEdgeTableYPos (y);
  68842. if (doLeftAlpha)
  68843. r.handleEdgeTablePixel (totalLeft, leftAlpha);
  68844. if (clippedWidth > 0)
  68845. r.handleEdgeTableLineFull (clippedLeft, clippedWidth);
  68846. if (doRightAlpha)
  68847. r.handleEdgeTablePixel (right, rightAlpha);
  68848. }
  68849. if (bottomAlpha != 0 && bottom < clipBottom)
  68850. {
  68851. r.setEdgeTableYPos (bottom);
  68852. if (doLeftAlpha)
  68853. r.handleEdgeTablePixel (totalLeft, (leftAlpha * bottomAlpha) >> 8);
  68854. if (clippedWidth > 0)
  68855. r.handleEdgeTableLine (clippedLeft, clippedWidth, bottomAlpha);
  68856. if (doRightAlpha)
  68857. r.handleEdgeTablePixel (right, (rightAlpha * bottomAlpha) >> 8);
  68858. }
  68859. }
  68860. }
  68861. }
  68862. }
  68863. private:
  68864. const RectangleList& clip;
  68865. const Rectangle<float>& area;
  68866. SubRectangleIteratorFloat (const SubRectangleIteratorFloat&);
  68867. SubRectangleIteratorFloat& operator= (const SubRectangleIteratorFloat&);
  68868. };
  68869. ClipRegion_RectangleList& operator= (const ClipRegion_RectangleList&);
  68870. };
  68871. }
  68872. class LowLevelGraphicsSoftwareRenderer::SavedState
  68873. {
  68874. public:
  68875. SavedState (const Rectangle<int>& clip_, const int xOffset_, const int yOffset_)
  68876. : clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  68877. xOffset (xOffset_), yOffset (yOffset_), interpolationQuality (Graphics::mediumResamplingQuality)
  68878. {
  68879. }
  68880. SavedState (const RectangleList& clip_, const int xOffset_, const int yOffset_)
  68881. : clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  68882. xOffset (xOffset_), yOffset (yOffset_), interpolationQuality (Graphics::mediumResamplingQuality)
  68883. {
  68884. }
  68885. SavedState (const SavedState& other)
  68886. : clip (other.clip), xOffset (other.xOffset), yOffset (other.yOffset), font (other.font),
  68887. fillType (other.fillType), interpolationQuality (other.interpolationQuality)
  68888. {
  68889. }
  68890. ~SavedState()
  68891. {
  68892. }
  68893. void setOrigin (const int x, const int y) throw()
  68894. {
  68895. xOffset += x;
  68896. yOffset += y;
  68897. }
  68898. bool clipToRectangle (const Rectangle<int>& r)
  68899. {
  68900. if (clip != 0)
  68901. {
  68902. cloneClipIfMultiplyReferenced();
  68903. clip = clip->clipToRectangle (r.translated (xOffset, yOffset));
  68904. }
  68905. return clip != 0;
  68906. }
  68907. bool clipToRectangleList (const RectangleList& r)
  68908. {
  68909. if (clip != 0)
  68910. {
  68911. cloneClipIfMultiplyReferenced();
  68912. RectangleList offsetList (r);
  68913. offsetList.offsetAll (xOffset, yOffset);
  68914. clip = clip->clipToRectangleList (offsetList);
  68915. }
  68916. return clip != 0;
  68917. }
  68918. bool excludeClipRectangle (const Rectangle<int>& r)
  68919. {
  68920. if (clip != 0)
  68921. {
  68922. cloneClipIfMultiplyReferenced();
  68923. clip = clip->excludeClipRectangle (r.translated (xOffset, yOffset));
  68924. }
  68925. return clip != 0;
  68926. }
  68927. void clipToPath (const Path& p, const AffineTransform& transform)
  68928. {
  68929. if (clip != 0)
  68930. {
  68931. cloneClipIfMultiplyReferenced();
  68932. clip = clip->clipToPath (p, transform.translated ((float) xOffset, (float) yOffset));
  68933. }
  68934. }
  68935. void clipToImageAlpha (const Image& image, const AffineTransform& t)
  68936. {
  68937. if (clip != 0)
  68938. {
  68939. if (image.hasAlphaChannel())
  68940. {
  68941. cloneClipIfMultiplyReferenced();
  68942. clip = clip->clipToImageAlpha (image, t.translated ((float) xOffset, (float) yOffset),
  68943. interpolationQuality != Graphics::lowResamplingQuality);
  68944. }
  68945. else
  68946. {
  68947. Path p;
  68948. p.addRectangle (image.getBounds());
  68949. clipToPath (p, t);
  68950. }
  68951. }
  68952. }
  68953. bool clipRegionIntersects (const Rectangle<int>& r) const
  68954. {
  68955. return clip != 0 && clip->clipRegionIntersects (r.translated (xOffset, yOffset));
  68956. }
  68957. const Rectangle<int> getClipBounds() const
  68958. {
  68959. return clip == 0 ? Rectangle<int>() : clip->getClipBounds().translated (-xOffset, -yOffset);
  68960. }
  68961. void fillRect (Image& image, const Rectangle<int>& r, const bool replaceContents)
  68962. {
  68963. if (clip != 0)
  68964. {
  68965. if (fillType.isColour())
  68966. {
  68967. Image::BitmapData destData (image, true);
  68968. clip->fillRectWithColour (destData, r.translated (xOffset, yOffset), fillType.colour.getPixelARGB(), replaceContents);
  68969. }
  68970. else
  68971. {
  68972. const Rectangle<int> totalClip (clip->getClipBounds());
  68973. const Rectangle<int> clipped (totalClip.getIntersection (r.translated (xOffset, yOffset)));
  68974. if (! clipped.isEmpty())
  68975. fillShape (image, new SoftwareRendererClasses::ClipRegion_RectangleList (clipped), false);
  68976. }
  68977. }
  68978. }
  68979. void fillRect (Image& image, const Rectangle<float>& r)
  68980. {
  68981. if (clip != 0)
  68982. {
  68983. if (fillType.isColour())
  68984. {
  68985. Image::BitmapData destData (image, true);
  68986. clip->fillRectWithColour (destData, r.translated ((float) xOffset, (float) yOffset), fillType.colour.getPixelARGB());
  68987. }
  68988. else
  68989. {
  68990. const Rectangle<float> totalClip (clip->getClipBounds().toFloat());
  68991. const Rectangle<float> clipped (totalClip.getIntersection (r.translated ((float) xOffset, (float) yOffset)));
  68992. if (! clipped.isEmpty())
  68993. fillShape (image, new SoftwareRendererClasses::ClipRegion_EdgeTable (clipped), false);
  68994. }
  68995. }
  68996. }
  68997. void fillPath (Image& image, const Path& path, const AffineTransform& transform)
  68998. {
  68999. if (clip != 0)
  69000. fillShape (image, new SoftwareRendererClasses::ClipRegion_EdgeTable (clip->getClipBounds(), path, transform.translated ((float) xOffset, (float) yOffset)), false);
  69001. }
  69002. void fillEdgeTable (Image& image, const EdgeTable& edgeTable, const float x, const int y)
  69003. {
  69004. if (clip != 0)
  69005. {
  69006. SoftwareRendererClasses::ClipRegion_EdgeTable* edgeTableClip = new SoftwareRendererClasses::ClipRegion_EdgeTable (edgeTable);
  69007. SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill (edgeTableClip);
  69008. edgeTableClip->edgeTable.translate (x + xOffset, y + yOffset);
  69009. fillShape (image, shapeToFill, false);
  69010. }
  69011. }
  69012. void fillShape (Image& image, SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill, const bool replaceContents)
  69013. {
  69014. jassert (clip != 0);
  69015. shapeToFill = clip->applyClipTo (shapeToFill);
  69016. if (shapeToFill != 0)
  69017. {
  69018. Image::BitmapData destData (image, true);
  69019. if (fillType.isGradient())
  69020. {
  69021. jassert (! replaceContents); // that option is just for solid colours
  69022. ColourGradient g2 (*(fillType.gradient));
  69023. g2.multiplyOpacity (fillType.getOpacity());
  69024. g2.point1.addXY (-0.5f, -0.5f);
  69025. g2.point2.addXY (-0.5f, -0.5f);
  69026. AffineTransform transform (fillType.transform.translated ((float) xOffset, (float) yOffset));
  69027. const bool isIdentity = transform.isOnlyTranslation();
  69028. if (isIdentity)
  69029. {
  69030. // If our translation doesn't involve any distortion, we can speed it up..
  69031. g2.point1.applyTransform (transform);
  69032. g2.point2.applyTransform (transform);
  69033. transform = AffineTransform::identity;
  69034. }
  69035. shapeToFill->fillAllWithGradient (destData, g2, transform, isIdentity);
  69036. }
  69037. else if (fillType.isTiledImage())
  69038. {
  69039. renderImage (image, fillType.image, fillType.transform, shapeToFill);
  69040. }
  69041. else
  69042. {
  69043. shapeToFill->fillAllWithColour (destData, fillType.colour.getPixelARGB(), replaceContents);
  69044. }
  69045. }
  69046. }
  69047. void renderImage (Image& destImage, const Image& sourceImage, const AffineTransform& t, const SoftwareRendererClasses::ClipRegionBase* const tiledFillClipRegion)
  69048. {
  69049. const AffineTransform transform (t.translated ((float) xOffset, (float) yOffset));
  69050. const Image::BitmapData destData (destImage, true);
  69051. const Image::BitmapData srcData (sourceImage, false);
  69052. const int alpha = fillType.colour.getAlpha();
  69053. const bool betterQuality = (interpolationQuality != Graphics::lowResamplingQuality);
  69054. if (transform.isOnlyTranslation())
  69055. {
  69056. // If our translation doesn't involve any distortion, just use a simple blit..
  69057. int tx = (int) (transform.getTranslationX() * 256.0f);
  69058. int ty = (int) (transform.getTranslationY() * 256.0f);
  69059. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  69060. {
  69061. tx = ((tx + 128) >> 8);
  69062. ty = ((ty + 128) >> 8);
  69063. if (tiledFillClipRegion != 0)
  69064. {
  69065. tiledFillClipRegion->renderImageUntransformed (destData, srcData, alpha, tx, ty, true);
  69066. }
  69067. else
  69068. {
  69069. SoftwareRendererClasses::ClipRegionBase::Ptr c (new SoftwareRendererClasses::ClipRegion_EdgeTable (Rectangle<int> (tx, ty, sourceImage.getWidth(), sourceImage.getHeight()).getIntersection (destImage.getBounds())));
  69070. c = clip->applyClipTo (c);
  69071. if (c != 0)
  69072. c->renderImageUntransformed (destData, srcData, alpha, tx, ty, false);
  69073. }
  69074. return;
  69075. }
  69076. }
  69077. if (transform.isSingularity())
  69078. return;
  69079. if (tiledFillClipRegion != 0)
  69080. {
  69081. tiledFillClipRegion->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, true);
  69082. }
  69083. else
  69084. {
  69085. Path p;
  69086. p.addRectangle (sourceImage.getBounds());
  69087. SoftwareRendererClasses::ClipRegionBase::Ptr c (clip->clone());
  69088. c = c->clipToPath (p, transform);
  69089. if (c != 0)
  69090. c->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, false);
  69091. }
  69092. }
  69093. SoftwareRendererClasses::ClipRegionBase::Ptr clip;
  69094. int xOffset, yOffset;
  69095. Font font;
  69096. FillType fillType;
  69097. Graphics::ResamplingQuality interpolationQuality;
  69098. private:
  69099. void cloneClipIfMultiplyReferenced()
  69100. {
  69101. if (clip->getReferenceCount() > 1)
  69102. clip = clip->clone();
  69103. }
  69104. SavedState& operator= (const SavedState&);
  69105. };
  69106. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image_)
  69107. : image (image_)
  69108. {
  69109. currentState = new SavedState (image_.getBounds(), 0, 0);
  69110. }
  69111. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image_, const int xOffset, const int yOffset,
  69112. const RectangleList& initialClip)
  69113. : image (image_)
  69114. {
  69115. currentState = new SavedState (initialClip, xOffset, yOffset);
  69116. }
  69117. LowLevelGraphicsSoftwareRenderer::~LowLevelGraphicsSoftwareRenderer()
  69118. {
  69119. }
  69120. bool LowLevelGraphicsSoftwareRenderer::isVectorDevice() const
  69121. {
  69122. return false;
  69123. }
  69124. void LowLevelGraphicsSoftwareRenderer::setOrigin (int x, int y)
  69125. {
  69126. currentState->setOrigin (x, y);
  69127. }
  69128. bool LowLevelGraphicsSoftwareRenderer::clipToRectangle (const Rectangle<int>& r)
  69129. {
  69130. return currentState->clipToRectangle (r);
  69131. }
  69132. bool LowLevelGraphicsSoftwareRenderer::clipToRectangleList (const RectangleList& clipRegion)
  69133. {
  69134. return currentState->clipToRectangleList (clipRegion);
  69135. }
  69136. void LowLevelGraphicsSoftwareRenderer::excludeClipRectangle (const Rectangle<int>& r)
  69137. {
  69138. currentState->excludeClipRectangle (r);
  69139. }
  69140. void LowLevelGraphicsSoftwareRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  69141. {
  69142. currentState->clipToPath (path, transform);
  69143. }
  69144. void LowLevelGraphicsSoftwareRenderer::clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  69145. {
  69146. currentState->clipToImageAlpha (sourceImage, transform);
  69147. }
  69148. bool LowLevelGraphicsSoftwareRenderer::clipRegionIntersects (const Rectangle<int>& r)
  69149. {
  69150. return currentState->clipRegionIntersects (r);
  69151. }
  69152. const Rectangle<int> LowLevelGraphicsSoftwareRenderer::getClipBounds() const
  69153. {
  69154. return currentState->getClipBounds();
  69155. }
  69156. bool LowLevelGraphicsSoftwareRenderer::isClipEmpty() const
  69157. {
  69158. return currentState->clip == 0;
  69159. }
  69160. void LowLevelGraphicsSoftwareRenderer::saveState()
  69161. {
  69162. stateStack.add (new SavedState (*currentState));
  69163. }
  69164. void LowLevelGraphicsSoftwareRenderer::restoreState()
  69165. {
  69166. SavedState* const top = stateStack.getLast();
  69167. if (top != 0)
  69168. {
  69169. currentState = top;
  69170. stateStack.removeLast (1, false);
  69171. }
  69172. else
  69173. {
  69174. jassertfalse; // trying to pop with an empty stack!
  69175. }
  69176. }
  69177. void LowLevelGraphicsSoftwareRenderer::setFill (const FillType& fillType)
  69178. {
  69179. currentState->fillType = fillType;
  69180. }
  69181. void LowLevelGraphicsSoftwareRenderer::setOpacity (float newOpacity)
  69182. {
  69183. currentState->fillType.setOpacity (newOpacity);
  69184. }
  69185. void LowLevelGraphicsSoftwareRenderer::setInterpolationQuality (Graphics::ResamplingQuality quality)
  69186. {
  69187. currentState->interpolationQuality = quality;
  69188. }
  69189. void LowLevelGraphicsSoftwareRenderer::fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  69190. {
  69191. currentState->fillRect (image, r, replaceExistingContents);
  69192. }
  69193. void LowLevelGraphicsSoftwareRenderer::fillPath (const Path& path, const AffineTransform& transform)
  69194. {
  69195. currentState->fillPath (image, path, transform);
  69196. }
  69197. void LowLevelGraphicsSoftwareRenderer::drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  69198. {
  69199. currentState->renderImage (image, sourceImage, transform,
  69200. fillEntireClipAsTiles ? currentState->clip : 0);
  69201. }
  69202. void LowLevelGraphicsSoftwareRenderer::drawLine (const Line <float>& line)
  69203. {
  69204. Path p;
  69205. p.addLineSegment (line, 1.0f);
  69206. fillPath (p, AffineTransform::identity);
  69207. }
  69208. void LowLevelGraphicsSoftwareRenderer::drawVerticalLine (const int x, float top, float bottom)
  69209. {
  69210. if (bottom > top)
  69211. currentState->fillRect (image, Rectangle<float> ((float) x, top, 1.0f, bottom - top));
  69212. }
  69213. void LowLevelGraphicsSoftwareRenderer::drawHorizontalLine (const int y, float left, float right)
  69214. {
  69215. if (right > left)
  69216. currentState->fillRect (image, Rectangle<float> (left, (float) y, right - left, 1.0f));
  69217. }
  69218. class LowLevelGraphicsSoftwareRenderer::CachedGlyph
  69219. {
  69220. public:
  69221. CachedGlyph() : glyph (0), lastAccessCount (0) {}
  69222. ~CachedGlyph() {}
  69223. void draw (SavedState& state, Image& image, const float x, const float y) const
  69224. {
  69225. if (edgeTable != 0)
  69226. state.fillEdgeTable (image, *edgeTable, x, roundToInt (y));
  69227. }
  69228. void generate (const Font& newFont, const int glyphNumber)
  69229. {
  69230. font = newFont;
  69231. glyph = glyphNumber;
  69232. edgeTable = 0;
  69233. Path glyphPath;
  69234. font.getTypeface()->getOutlineForGlyph (glyphNumber, glyphPath);
  69235. if (! glyphPath.isEmpty())
  69236. {
  69237. const float fontHeight = font.getHeight();
  69238. const AffineTransform transform (AffineTransform::scale (fontHeight * font.getHorizontalScale(), fontHeight)
  69239. #if JUCE_MAC || JUCE_IOS
  69240. .translated (0.0f, -0.5f)
  69241. #endif
  69242. );
  69243. edgeTable = new EdgeTable (glyphPath.getBoundsTransformed (transform).getSmallestIntegerContainer().expanded (1, 0),
  69244. glyphPath, transform);
  69245. }
  69246. }
  69247. int glyph, lastAccessCount;
  69248. Font font;
  69249. juce_UseDebuggingNewOperator
  69250. private:
  69251. ScopedPointer <EdgeTable> edgeTable;
  69252. CachedGlyph (const CachedGlyph&);
  69253. CachedGlyph& operator= (const CachedGlyph&);
  69254. };
  69255. class LowLevelGraphicsSoftwareRenderer::GlyphCache : private DeletedAtShutdown
  69256. {
  69257. public:
  69258. GlyphCache()
  69259. : accessCounter (0), hits (0), misses (0)
  69260. {
  69261. for (int i = 120; --i >= 0;)
  69262. glyphs.add (new CachedGlyph());
  69263. }
  69264. ~GlyphCache()
  69265. {
  69266. clearSingletonInstance();
  69267. }
  69268. juce_DeclareSingleton_SingleThreaded_Minimal (GlyphCache);
  69269. void drawGlyph (SavedState& state, Image& image, const Font& font, const int glyphNumber, float x, float y)
  69270. {
  69271. ++accessCounter;
  69272. int oldestCounter = std::numeric_limits<int>::max();
  69273. CachedGlyph* oldest = 0;
  69274. for (int i = glyphs.size(); --i >= 0;)
  69275. {
  69276. CachedGlyph* const glyph = glyphs.getUnchecked (i);
  69277. if (glyph->glyph == glyphNumber && glyph->font == font)
  69278. {
  69279. ++hits;
  69280. glyph->lastAccessCount = accessCounter;
  69281. glyph->draw (state, image, x, y);
  69282. return;
  69283. }
  69284. if (glyph->lastAccessCount <= oldestCounter)
  69285. {
  69286. oldestCounter = glyph->lastAccessCount;
  69287. oldest = glyph;
  69288. }
  69289. }
  69290. if (hits + ++misses > (glyphs.size() << 4))
  69291. {
  69292. if (misses * 2 > hits)
  69293. {
  69294. for (int i = 32; --i >= 0;)
  69295. glyphs.add (new CachedGlyph());
  69296. }
  69297. hits = misses = 0;
  69298. oldest = glyphs.getLast();
  69299. }
  69300. jassert (oldest != 0);
  69301. oldest->lastAccessCount = accessCounter;
  69302. oldest->generate (font, glyphNumber);
  69303. oldest->draw (state, image, x, y);
  69304. }
  69305. juce_UseDebuggingNewOperator
  69306. private:
  69307. friend class OwnedArray <CachedGlyph>;
  69308. OwnedArray <CachedGlyph> glyphs;
  69309. int accessCounter, hits, misses;
  69310. GlyphCache (const GlyphCache&);
  69311. GlyphCache& operator= (const GlyphCache&);
  69312. };
  69313. juce_ImplementSingleton_SingleThreaded (LowLevelGraphicsSoftwareRenderer::GlyphCache);
  69314. void LowLevelGraphicsSoftwareRenderer::setFont (const Font& newFont)
  69315. {
  69316. currentState->font = newFont;
  69317. }
  69318. const Font LowLevelGraphicsSoftwareRenderer::getFont()
  69319. {
  69320. return currentState->font;
  69321. }
  69322. void LowLevelGraphicsSoftwareRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  69323. {
  69324. Font& f = currentState->font;
  69325. if (transform.isOnlyTranslation())
  69326. {
  69327. GlyphCache::getInstance()->drawGlyph (*currentState, image, f, glyphNumber,
  69328. transform.getTranslationX(),
  69329. transform.getTranslationY());
  69330. }
  69331. else
  69332. {
  69333. Path p;
  69334. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  69335. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight()).followedBy (transform));
  69336. }
  69337. }
  69338. #if JUCE_MSVC
  69339. #pragma warning (pop)
  69340. #if JUCE_DEBUG
  69341. #pragma optimize ("", on) // resets optimisations to the project defaults
  69342. #endif
  69343. #endif
  69344. END_JUCE_NAMESPACE
  69345. /*** End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  69346. /*** Start of inlined file: juce_RectanglePlacement.cpp ***/
  69347. BEGIN_JUCE_NAMESPACE
  69348. RectanglePlacement::RectanglePlacement (const RectanglePlacement& other) throw()
  69349. : flags (other.flags)
  69350. {
  69351. }
  69352. RectanglePlacement& RectanglePlacement::operator= (const RectanglePlacement& other) throw()
  69353. {
  69354. flags = other.flags;
  69355. return *this;
  69356. }
  69357. void RectanglePlacement::applyTo (double& x, double& y,
  69358. double& w, double& h,
  69359. const double dx, const double dy,
  69360. const double dw, const double dh) const throw()
  69361. {
  69362. if (w == 0 || h == 0)
  69363. return;
  69364. if ((flags & stretchToFit) != 0)
  69365. {
  69366. x = dx;
  69367. y = dy;
  69368. w = dw;
  69369. h = dh;
  69370. }
  69371. else
  69372. {
  69373. double scale = (flags & fillDestination) != 0 ? jmax (dw / w, dh / h)
  69374. : jmin (dw / w, dh / h);
  69375. if ((flags & onlyReduceInSize) != 0)
  69376. scale = jmin (scale, 1.0);
  69377. if ((flags & onlyIncreaseInSize) != 0)
  69378. scale = jmax (scale, 1.0);
  69379. w *= scale;
  69380. h *= scale;
  69381. if ((flags & xLeft) != 0)
  69382. x = dx;
  69383. else if ((flags & xRight) != 0)
  69384. x = dx + dw - w;
  69385. else
  69386. x = dx + (dw - w) * 0.5;
  69387. if ((flags & yTop) != 0)
  69388. y = dy;
  69389. else if ((flags & yBottom) != 0)
  69390. y = dy + dh - h;
  69391. else
  69392. y = dy + (dh - h) * 0.5;
  69393. }
  69394. }
  69395. const AffineTransform RectanglePlacement::getTransformToFit (const Rectangle<float>& source, const Rectangle<float>& destination) const throw()
  69396. {
  69397. if (source.isEmpty())
  69398. return AffineTransform::identity;
  69399. float w = source.getWidth();
  69400. float h = source.getHeight();
  69401. const float scaleX = destination.getWidth() / w;
  69402. const float scaleY = destination.getHeight() / h;
  69403. if ((flags & stretchToFit) != 0)
  69404. return AffineTransform::translation (-source.getX(), -source.getY())
  69405. .scaled (scaleX, scaleY)
  69406. .translated (destination.getX(), destination.getY());
  69407. float scale = (flags & fillDestination) != 0 ? jmax (scaleX, scaleY)
  69408. : jmin (scaleX, scaleY);
  69409. if ((flags & onlyReduceInSize) != 0)
  69410. scale = jmin (scale, 1.0f);
  69411. if ((flags & onlyIncreaseInSize) != 0)
  69412. scale = jmax (scale, 1.0f);
  69413. w *= scale;
  69414. h *= scale;
  69415. float newX = destination.getX();
  69416. float newY = destination.getY();
  69417. if ((flags & xRight) != 0)
  69418. newX += destination.getWidth() - w; // right
  69419. else if ((flags & xLeft) == 0)
  69420. newX += (destination.getWidth() - w) / 2.0f; // centre
  69421. if ((flags & yBottom) != 0)
  69422. newY += destination.getHeight() - h; // bottom
  69423. else if ((flags & yTop) == 0)
  69424. newY += (destination.getHeight() - h) / 2.0f; // centre
  69425. return AffineTransform::translation (-source.getX(), -source.getY())
  69426. .scaled (scale, scale)
  69427. .translated (newX, newY);
  69428. }
  69429. END_JUCE_NAMESPACE
  69430. /*** End of inlined file: juce_RectanglePlacement.cpp ***/
  69431. /*** Start of inlined file: juce_Drawable.cpp ***/
  69432. BEGIN_JUCE_NAMESPACE
  69433. Drawable::RenderingContext::RenderingContext (Graphics& g_,
  69434. const AffineTransform& transform_,
  69435. const float opacity_) throw()
  69436. : g (g_),
  69437. transform (transform_),
  69438. opacity (opacity_)
  69439. {
  69440. }
  69441. Drawable::Drawable()
  69442. : parent (0)
  69443. {
  69444. }
  69445. Drawable::~Drawable()
  69446. {
  69447. }
  69448. void Drawable::draw (Graphics& g, const float opacity, const AffineTransform& transform) const
  69449. {
  69450. render (RenderingContext (g, transform, opacity));
  69451. }
  69452. void Drawable::drawAt (Graphics& g, const float x, const float y, const float opacity) const
  69453. {
  69454. draw (g, opacity, AffineTransform::translation (x, y));
  69455. }
  69456. void Drawable::drawWithin (Graphics& g,
  69457. const Rectangle<float>& destArea,
  69458. const RectanglePlacement& placement,
  69459. const float opacity) const
  69460. {
  69461. if (! destArea.isEmpty())
  69462. draw (g, opacity, placement.getTransformToFit (getBounds(), destArea));
  69463. }
  69464. Drawable* Drawable::createFromImageData (const void* data, const size_t numBytes)
  69465. {
  69466. Drawable* result = 0;
  69467. Image image (ImageFileFormat::loadFrom (data, (int) numBytes));
  69468. if (image.isValid())
  69469. {
  69470. DrawableImage* const di = new DrawableImage();
  69471. di->setImage (image);
  69472. result = di;
  69473. }
  69474. else
  69475. {
  69476. const String asString (String::createStringFromData (data, (int) numBytes));
  69477. XmlDocument doc (asString);
  69478. ScopedPointer <XmlElement> outer (doc.getDocumentElement (true));
  69479. if (outer != 0 && outer->hasTagName ("svg"))
  69480. {
  69481. ScopedPointer <XmlElement> svg (doc.getDocumentElement());
  69482. if (svg != 0)
  69483. result = Drawable::createFromSVG (*svg);
  69484. }
  69485. }
  69486. return result;
  69487. }
  69488. Drawable* Drawable::createFromImageDataStream (InputStream& dataSource)
  69489. {
  69490. MemoryOutputStream mo;
  69491. mo.writeFromInputStream (dataSource, -1);
  69492. return createFromImageData (mo.getData(), mo.getDataSize());
  69493. }
  69494. Drawable* Drawable::createFromImageFile (const File& file)
  69495. {
  69496. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  69497. return fin != 0 ? createFromImageDataStream (*fin) : 0;
  69498. }
  69499. Drawable* Drawable::createFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  69500. {
  69501. return createChildFromValueTree (0, tree, imageProvider);
  69502. }
  69503. Drawable* Drawable::createChildFromValueTree (DrawableComposite* parent, const ValueTree& tree, ImageProvider* imageProvider)
  69504. {
  69505. const Identifier type (tree.getType());
  69506. Drawable* d = 0;
  69507. if (type == DrawablePath::valueTreeType)
  69508. d = new DrawablePath();
  69509. else if (type == DrawableComposite::valueTreeType)
  69510. d = new DrawableComposite();
  69511. else if (type == DrawableImage::valueTreeType)
  69512. d = new DrawableImage();
  69513. else if (type == DrawableText::valueTreeType)
  69514. d = new DrawableText();
  69515. if (d != 0)
  69516. {
  69517. d->parent = parent;
  69518. d->refreshFromValueTree (tree, imageProvider);
  69519. }
  69520. return d;
  69521. }
  69522. const Identifier Drawable::ValueTreeWrapperBase::idProperty ("id");
  69523. const Identifier Drawable::ValueTreeWrapperBase::type ("type");
  69524. const Identifier Drawable::ValueTreeWrapperBase::gradientPoint1 ("point1");
  69525. const Identifier Drawable::ValueTreeWrapperBase::gradientPoint2 ("point2");
  69526. const Identifier Drawable::ValueTreeWrapperBase::gradientPoint3 ("point3");
  69527. const Identifier Drawable::ValueTreeWrapperBase::colour ("colour");
  69528. const Identifier Drawable::ValueTreeWrapperBase::radial ("radial");
  69529. const Identifier Drawable::ValueTreeWrapperBase::colours ("colours");
  69530. const Identifier Drawable::ValueTreeWrapperBase::imageId ("imageId");
  69531. const Identifier Drawable::ValueTreeWrapperBase::imageOpacity ("imageOpacity");
  69532. Drawable::ValueTreeWrapperBase::ValueTreeWrapperBase (const ValueTree& state_)
  69533. : state (state_)
  69534. {
  69535. }
  69536. Drawable::ValueTreeWrapperBase::~ValueTreeWrapperBase()
  69537. {
  69538. }
  69539. const String Drawable::ValueTreeWrapperBase::getID() const
  69540. {
  69541. return state [idProperty];
  69542. }
  69543. void Drawable::ValueTreeWrapperBase::setID (const String& newID, UndoManager* const undoManager)
  69544. {
  69545. if (newID.isEmpty())
  69546. state.removeProperty (idProperty, undoManager);
  69547. else
  69548. state.setProperty (idProperty, newID, undoManager);
  69549. }
  69550. const FillType Drawable::ValueTreeWrapperBase::readFillType (const ValueTree& v, RelativePoint* const gp1, RelativePoint* const gp2, RelativePoint* const gp3,
  69551. Expression::EvaluationContext* const nameFinder, ImageProvider* imageProvider)
  69552. {
  69553. const String newType (v[type].toString());
  69554. if (newType == "solid")
  69555. {
  69556. const String colourString (v [colour].toString());
  69557. return FillType (Colour (colourString.isEmpty() ? (uint32) 0xff000000
  69558. : (uint32) colourString.getHexValue32()));
  69559. }
  69560. else if (newType == "gradient")
  69561. {
  69562. RelativePoint p1 (v [gradientPoint1]), p2 (v [gradientPoint2]), p3 (v [gradientPoint3]);
  69563. ColourGradient g;
  69564. if (gp1 != 0) *gp1 = p1;
  69565. if (gp2 != 0) *gp2 = p2;
  69566. if (gp3 != 0) *gp3 = p3;
  69567. g.point1 = p1.resolve (nameFinder);
  69568. g.point2 = p2.resolve (nameFinder);
  69569. g.isRadial = v[radial];
  69570. StringArray colourSteps;
  69571. colourSteps.addTokens (v[colours].toString(), false);
  69572. for (int i = 0; i < colourSteps.size() / 2; ++i)
  69573. g.addColour (colourSteps[i * 2].getDoubleValue(),
  69574. Colour ((uint32) colourSteps[i * 2 + 1].getHexValue32()));
  69575. FillType fillType (g);
  69576. if (g.isRadial)
  69577. {
  69578. const Point<float> point3 (p3.resolve (nameFinder));
  69579. const Point<float> point3Source (g.point1.getX() + g.point2.getY() - g.point1.getY(),
  69580. g.point1.getY() + g.point1.getX() - g.point2.getX());
  69581. fillType.transform = AffineTransform::fromTargetPoints (g.point1.getX(), g.point1.getY(), g.point1.getX(), g.point1.getY(),
  69582. g.point2.getX(), g.point2.getY(), g.point2.getX(), g.point2.getY(),
  69583. point3Source.getX(), point3Source.getY(), point3.getX(), point3.getY());
  69584. }
  69585. return fillType;
  69586. }
  69587. else if (newType == "image")
  69588. {
  69589. Image im;
  69590. if (imageProvider != 0)
  69591. im = imageProvider->getImageForIdentifier (v[imageId]);
  69592. FillType f (im, AffineTransform::identity);
  69593. f.setOpacity ((float) v.getProperty (imageOpacity, 1.0f));
  69594. return f;
  69595. }
  69596. jassertfalse;
  69597. return FillType();
  69598. }
  69599. static const Point<float> calcThirdGradientPoint (const FillType& fillType)
  69600. {
  69601. const ColourGradient& g = *fillType.gradient;
  69602. const Point<float> point3Source (g.point1.getX() + g.point2.getY() - g.point1.getY(),
  69603. g.point1.getY() + g.point1.getX() - g.point2.getX());
  69604. return point3Source.transformedBy (fillType.transform);
  69605. }
  69606. void Drawable::ValueTreeWrapperBase::writeFillType (ValueTree& v, const FillType& fillType,
  69607. const RelativePoint* const gp1, const RelativePoint* const gp2, const RelativePoint* gp3,
  69608. ImageProvider* imageProvider, UndoManager* const undoManager)
  69609. {
  69610. if (fillType.isColour())
  69611. {
  69612. v.setProperty (type, "solid", undoManager);
  69613. v.setProperty (colour, String::toHexString ((int) fillType.colour.getARGB()), undoManager);
  69614. }
  69615. else if (fillType.isGradient())
  69616. {
  69617. v.setProperty (type, "gradient", undoManager);
  69618. v.setProperty (gradientPoint1, gp1 != 0 ? gp1->toString() : fillType.gradient->point1.toString(), undoManager);
  69619. v.setProperty (gradientPoint2, gp2 != 0 ? gp2->toString() : fillType.gradient->point2.toString(), undoManager);
  69620. v.setProperty (gradientPoint3, gp3 != 0 ? gp3->toString() : calcThirdGradientPoint (fillType).toString(), undoManager);
  69621. v.setProperty (radial, fillType.gradient->isRadial, undoManager);
  69622. String s;
  69623. for (int i = 0; i < fillType.gradient->getNumColours(); ++i)
  69624. s << ' ' << fillType.gradient->getColourPosition (i)
  69625. << ' ' << String::toHexString ((int) fillType.gradient->getColour(i).getARGB());
  69626. v.setProperty (colours, s.trimStart(), undoManager);
  69627. }
  69628. else if (fillType.isTiledImage())
  69629. {
  69630. v.setProperty (type, "image", undoManager);
  69631. if (imageProvider != 0)
  69632. v.setProperty (imageId, imageProvider->getIdentifierForImage (fillType.image), undoManager);
  69633. if (fillType.getOpacity() < 1.0f)
  69634. v.setProperty (imageOpacity, fillType.getOpacity(), undoManager);
  69635. else
  69636. v.removeProperty (imageOpacity, undoManager);
  69637. }
  69638. else
  69639. {
  69640. jassertfalse;
  69641. }
  69642. }
  69643. END_JUCE_NAMESPACE
  69644. /*** End of inlined file: juce_Drawable.cpp ***/
  69645. /*** Start of inlined file: juce_DrawableComposite.cpp ***/
  69646. BEGIN_JUCE_NAMESPACE
  69647. DrawableComposite::DrawableComposite()
  69648. : bounds (Point<float>(), Point<float> (100.0f, 0.0f), Point<float> (0.0f, 100.0f))
  69649. {
  69650. setContentArea (RelativeRectangle (RelativeCoordinate (0.0),
  69651. RelativeCoordinate (100.0),
  69652. RelativeCoordinate (0.0),
  69653. RelativeCoordinate (100.0)));
  69654. }
  69655. DrawableComposite::DrawableComposite (const DrawableComposite& other)
  69656. {
  69657. bounds = other.bounds;
  69658. for (int i = 0; i < other.drawables.size(); ++i)
  69659. drawables.add (other.drawables.getUnchecked(i)->createCopy());
  69660. markersX.addCopiesOf (other.markersX);
  69661. markersY.addCopiesOf (other.markersY);
  69662. }
  69663. DrawableComposite::~DrawableComposite()
  69664. {
  69665. }
  69666. void DrawableComposite::insertDrawable (Drawable* drawable, const int index)
  69667. {
  69668. if (drawable != 0)
  69669. {
  69670. jassert (! drawables.contains (drawable)); // trying to add a drawable that's already in here!
  69671. jassert (drawable->parent == 0); // A drawable can only live inside one parent at a time!
  69672. drawables.insert (index, drawable);
  69673. drawable->parent = this;
  69674. }
  69675. }
  69676. void DrawableComposite::insertDrawable (const Drawable& drawable, const int index)
  69677. {
  69678. insertDrawable (drawable.createCopy(), index);
  69679. }
  69680. void DrawableComposite::removeDrawable (const int index, const bool deleteDrawable)
  69681. {
  69682. drawables.remove (index, deleteDrawable);
  69683. }
  69684. Drawable* DrawableComposite::getDrawableWithName (const String& name) const throw()
  69685. {
  69686. for (int i = drawables.size(); --i >= 0;)
  69687. if (drawables.getUnchecked(i)->getName() == name)
  69688. return drawables.getUnchecked(i);
  69689. return 0;
  69690. }
  69691. void DrawableComposite::bringToFront (const int index)
  69692. {
  69693. if (index >= 0 && index < drawables.size() - 1)
  69694. drawables.move (index, -1);
  69695. }
  69696. void DrawableComposite::setBoundingBox (const RelativeParallelogram& newBoundingBox)
  69697. {
  69698. bounds = newBoundingBox;
  69699. }
  69700. DrawableComposite::Marker::Marker (const DrawableComposite::Marker& other)
  69701. : name (other.name), position (other.position)
  69702. {
  69703. }
  69704. DrawableComposite::Marker::Marker (const String& name_, const RelativeCoordinate& position_)
  69705. : name (name_), position (position_)
  69706. {
  69707. }
  69708. bool DrawableComposite::Marker::operator!= (const DrawableComposite::Marker& other) const throw()
  69709. {
  69710. return name != other.name || position != other.position;
  69711. }
  69712. const char* const DrawableComposite::contentLeftMarkerName ("left");
  69713. const char* const DrawableComposite::contentRightMarkerName ("right");
  69714. const char* const DrawableComposite::contentTopMarkerName ("top");
  69715. const char* const DrawableComposite::contentBottomMarkerName ("bottom");
  69716. const RelativeRectangle DrawableComposite::getContentArea() const
  69717. {
  69718. jassert (markersX.size() >= 2 && getMarker (true, 0)->name == contentLeftMarkerName && getMarker (true, 1)->name == contentRightMarkerName);
  69719. jassert (markersY.size() >= 2 && getMarker (false, 0)->name == contentTopMarkerName && getMarker (false, 1)->name == contentBottomMarkerName);
  69720. return RelativeRectangle (markersX.getUnchecked(0)->position, markersX.getUnchecked(1)->position,
  69721. markersY.getUnchecked(0)->position, markersY.getUnchecked(1)->position);
  69722. }
  69723. void DrawableComposite::setContentArea (const RelativeRectangle& newArea)
  69724. {
  69725. setMarker (contentLeftMarkerName, true, newArea.left);
  69726. setMarker (contentRightMarkerName, true, newArea.right);
  69727. setMarker (contentTopMarkerName, false, newArea.top);
  69728. setMarker (contentBottomMarkerName, false, newArea.bottom);
  69729. }
  69730. void DrawableComposite::resetBoundingBoxToContentArea()
  69731. {
  69732. const RelativeRectangle content (getContentArea());
  69733. setBoundingBox (RelativeParallelogram (RelativePoint (content.left, content.top),
  69734. RelativePoint (content.right, content.top),
  69735. RelativePoint (content.left, content.bottom)));
  69736. }
  69737. void DrawableComposite::resetContentAreaAndBoundingBoxToFitChildren()
  69738. {
  69739. const Rectangle<float> bounds (getUntransformedBounds (false));
  69740. setContentArea (RelativeRectangle (RelativeCoordinate (bounds.getX()),
  69741. RelativeCoordinate (bounds.getRight()),
  69742. RelativeCoordinate (bounds.getY()),
  69743. RelativeCoordinate (bounds.getBottom())));
  69744. resetBoundingBoxToContentArea();
  69745. }
  69746. int DrawableComposite::getNumMarkers (const bool xAxis) const throw()
  69747. {
  69748. return (xAxis ? markersX : markersY).size();
  69749. }
  69750. const DrawableComposite::Marker* DrawableComposite::getMarker (const bool xAxis, const int index) const throw()
  69751. {
  69752. return (xAxis ? markersX : markersY) [index];
  69753. }
  69754. void DrawableComposite::setMarker (const String& name, const bool xAxis, const RelativeCoordinate& position)
  69755. {
  69756. OwnedArray <Marker>& markers = (xAxis ? markersX : markersY);
  69757. for (int i = 0; i < markers.size(); ++i)
  69758. {
  69759. Marker* const m = markers.getUnchecked(i);
  69760. if (m->name == name)
  69761. {
  69762. if (m->position != position)
  69763. {
  69764. m->position = position;
  69765. invalidatePoints();
  69766. }
  69767. return;
  69768. }
  69769. }
  69770. (xAxis ? markersX : markersY).add (new Marker (name, position));
  69771. invalidatePoints();
  69772. }
  69773. void DrawableComposite::removeMarker (const bool xAxis, const int index)
  69774. {
  69775. jassert (index >= 2);
  69776. if (index >= 2)
  69777. (xAxis ? markersX : markersY).remove (index);
  69778. }
  69779. const AffineTransform DrawableComposite::calculateTransform() const
  69780. {
  69781. Point<float> resolved[3];
  69782. bounds.resolveThreePoints (resolved, parent);
  69783. const Rectangle<float> content (getContentArea().resolve (parent));
  69784. return AffineTransform::fromTargetPoints (content.getX(), content.getY(), resolved[0].getX(), resolved[0].getY(),
  69785. content.getRight(), content.getY(), resolved[1].getX(), resolved[1].getY(),
  69786. content.getX(), content.getBottom(), resolved[2].getX(), resolved[2].getY());
  69787. }
  69788. void DrawableComposite::render (const Drawable::RenderingContext& context) const
  69789. {
  69790. if (drawables.size() > 0 && context.opacity > 0)
  69791. {
  69792. if (context.opacity >= 1.0f || drawables.size() == 1)
  69793. {
  69794. Drawable::RenderingContext contextCopy (context);
  69795. contextCopy.transform = calculateTransform().followedBy (context.transform);
  69796. for (int i = 0; i < drawables.size(); ++i)
  69797. drawables.getUnchecked(i)->render (contextCopy);
  69798. }
  69799. else
  69800. {
  69801. // To correctly render a whole composite layer with an overall transparency,
  69802. // we need to render everything opaquely into a temp buffer, then blend that
  69803. // with the target opacity...
  69804. const Rectangle<int> clipBounds (context.g.getClipBounds());
  69805. if (! clipBounds.isEmpty())
  69806. {
  69807. Image tempImage (Image::ARGB, clipBounds.getWidth(), clipBounds.getHeight(), true);
  69808. {
  69809. Graphics tempG (tempImage);
  69810. tempG.setOrigin (-clipBounds.getX(), -clipBounds.getY());
  69811. Drawable::RenderingContext tempContext (tempG, context.transform, 1.0f);
  69812. render (tempContext);
  69813. }
  69814. context.g.setOpacity (context.opacity);
  69815. context.g.drawImageAt (tempImage, clipBounds.getX(), clipBounds.getY());
  69816. }
  69817. }
  69818. }
  69819. }
  69820. const Expression DrawableComposite::getSymbolValue (const String& symbol, const String& member) const
  69821. {
  69822. jassert (member.isEmpty()) // the only symbols available in a Drawable are markers.
  69823. int i;
  69824. for (i = 0; i < markersX.size(); ++i)
  69825. {
  69826. Marker* const m = markersX.getUnchecked(i);
  69827. if (m->name == symbol)
  69828. return m->position.getExpression();
  69829. }
  69830. for (i = 0; i < markersY.size(); ++i)
  69831. {
  69832. Marker* const m = markersY.getUnchecked(i);
  69833. if (m->name == symbol)
  69834. return m->position.getExpression();
  69835. }
  69836. throw Expression::EvaluationError (symbol, member);
  69837. }
  69838. const Rectangle<float> DrawableComposite::getUntransformedBounds (const bool includeMarkers) const
  69839. {
  69840. Rectangle<float> bounds;
  69841. int i;
  69842. for (i = 0; i < drawables.size(); ++i)
  69843. bounds = bounds.getUnion (drawables.getUnchecked(i)->getBounds());
  69844. if (includeMarkers)
  69845. {
  69846. if (markersX.size() > 0)
  69847. {
  69848. float minX = std::numeric_limits<float>::max();
  69849. float maxX = std::numeric_limits<float>::min();
  69850. for (i = markersX.size(); --i >= 0;)
  69851. {
  69852. const Marker* m = markersX.getUnchecked(i);
  69853. const float pos = (float) m->position.resolve (this);
  69854. minX = jmin (minX, pos);
  69855. maxX = jmax (maxX, pos);
  69856. }
  69857. if (minX <= maxX)
  69858. {
  69859. if (bounds.getHeight() > 0)
  69860. {
  69861. minX = jmin (minX, bounds.getX());
  69862. maxX = jmax (maxX, bounds.getRight());
  69863. }
  69864. bounds.setLeft (minX);
  69865. bounds.setWidth (maxX - minX);
  69866. }
  69867. }
  69868. if (markersY.size() > 0)
  69869. {
  69870. float minY = std::numeric_limits<float>::max();
  69871. float maxY = std::numeric_limits<float>::min();
  69872. for (i = markersY.size(); --i >= 0;)
  69873. {
  69874. const Marker* m = markersY.getUnchecked(i);
  69875. const float pos = (float) m->position.resolve (this);
  69876. minY = jmin (minY, pos);
  69877. maxY = jmax (maxY, pos);
  69878. }
  69879. if (minY <= maxY)
  69880. {
  69881. if (bounds.getHeight() > 0)
  69882. {
  69883. minY = jmin (minY, bounds.getY());
  69884. maxY = jmax (maxY, bounds.getBottom());
  69885. }
  69886. bounds.setTop (minY);
  69887. bounds.setHeight (maxY - minY);
  69888. }
  69889. }
  69890. }
  69891. return bounds;
  69892. }
  69893. const Rectangle<float> DrawableComposite::getBounds() const
  69894. {
  69895. return getUntransformedBounds (true).transformed (calculateTransform());
  69896. }
  69897. bool DrawableComposite::hitTest (float x, float y) const
  69898. {
  69899. calculateTransform().inverted().transformPoint (x, y);
  69900. for (int i = 0; i < drawables.size(); ++i)
  69901. if (drawables.getUnchecked(i)->hitTest (x, y))
  69902. return true;
  69903. return false;
  69904. }
  69905. Drawable* DrawableComposite::createCopy() const
  69906. {
  69907. return new DrawableComposite (*this);
  69908. }
  69909. void DrawableComposite::invalidatePoints()
  69910. {
  69911. for (int i = 0; i < drawables.size(); ++i)
  69912. drawables.getUnchecked(i)->invalidatePoints();
  69913. }
  69914. const Identifier DrawableComposite::valueTreeType ("Group");
  69915. const Identifier DrawableComposite::ValueTreeWrapper::topLeft ("topLeft");
  69916. const Identifier DrawableComposite::ValueTreeWrapper::topRight ("topRight");
  69917. const Identifier DrawableComposite::ValueTreeWrapper::bottomLeft ("bottomLeft");
  69918. const Identifier DrawableComposite::ValueTreeWrapper::childGroupTag ("Drawables");
  69919. const Identifier DrawableComposite::ValueTreeWrapper::markerGroupTagX ("MarkersX");
  69920. const Identifier DrawableComposite::ValueTreeWrapper::markerGroupTagY ("MarkersY");
  69921. const Identifier DrawableComposite::ValueTreeWrapper::markerTag ("Marker");
  69922. const Identifier DrawableComposite::ValueTreeWrapper::nameProperty ("name");
  69923. const Identifier DrawableComposite::ValueTreeWrapper::posProperty ("position");
  69924. DrawableComposite::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  69925. : ValueTreeWrapperBase (state_)
  69926. {
  69927. jassert (state.hasType (valueTreeType));
  69928. }
  69929. ValueTree DrawableComposite::ValueTreeWrapper::getChildList() const
  69930. {
  69931. return state.getChildWithName (childGroupTag);
  69932. }
  69933. ValueTree DrawableComposite::ValueTreeWrapper::getChildListCreating (UndoManager* undoManager)
  69934. {
  69935. return state.getOrCreateChildWithName (childGroupTag, undoManager);
  69936. }
  69937. int DrawableComposite::ValueTreeWrapper::getNumDrawables() const
  69938. {
  69939. return getChildList().getNumChildren();
  69940. }
  69941. ValueTree DrawableComposite::ValueTreeWrapper::getDrawableState (int index) const
  69942. {
  69943. return getChildList().getChild (index);
  69944. }
  69945. ValueTree DrawableComposite::ValueTreeWrapper::getDrawableWithId (const String& objectId, bool recursive) const
  69946. {
  69947. if (getID() == objectId)
  69948. return state;
  69949. if (! recursive)
  69950. {
  69951. return getChildList().getChildWithProperty (idProperty, objectId);
  69952. }
  69953. else
  69954. {
  69955. const ValueTree childList (getChildList());
  69956. for (int i = getNumDrawables(); --i >= 0;)
  69957. {
  69958. const ValueTree& child = childList.getChild (i);
  69959. if (child [Drawable::ValueTreeWrapperBase::idProperty] == objectId)
  69960. return child;
  69961. if (child.hasType (DrawableComposite::valueTreeType))
  69962. {
  69963. ValueTree v (DrawableComposite::ValueTreeWrapper (child).getDrawableWithId (objectId, true));
  69964. if (v.isValid())
  69965. return v;
  69966. }
  69967. }
  69968. return ValueTree::invalid;
  69969. }
  69970. }
  69971. int DrawableComposite::ValueTreeWrapper::indexOfDrawable (const ValueTree& item) const
  69972. {
  69973. return getChildList().indexOf (item);
  69974. }
  69975. void DrawableComposite::ValueTreeWrapper::addDrawable (const ValueTree& newDrawableState, int index, UndoManager* undoManager)
  69976. {
  69977. getChildListCreating (undoManager).addChild (newDrawableState, index, undoManager);
  69978. }
  69979. void DrawableComposite::ValueTreeWrapper::moveDrawableOrder (int currentIndex, int newIndex, UndoManager* undoManager)
  69980. {
  69981. getChildListCreating (undoManager).moveChild (currentIndex, newIndex, undoManager);
  69982. }
  69983. void DrawableComposite::ValueTreeWrapper::removeDrawable (const ValueTree& child, UndoManager* undoManager)
  69984. {
  69985. getChildList().removeChild (child, undoManager);
  69986. }
  69987. const RelativeParallelogram DrawableComposite::ValueTreeWrapper::getBoundingBox() const
  69988. {
  69989. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  69990. state.getProperty (topRight, "100, 0"),
  69991. state.getProperty (bottomLeft, "0, 100"));
  69992. }
  69993. void DrawableComposite::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  69994. {
  69995. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  69996. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  69997. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  69998. }
  69999. void DrawableComposite::ValueTreeWrapper::resetBoundingBoxToContentArea (UndoManager* undoManager)
  70000. {
  70001. const RelativeRectangle content (getContentArea());
  70002. setBoundingBox (RelativeParallelogram (RelativePoint (content.left, content.top),
  70003. RelativePoint (content.right, content.top),
  70004. RelativePoint (content.left, content.bottom)), undoManager);
  70005. }
  70006. const RelativeRectangle DrawableComposite::ValueTreeWrapper::getContentArea() const
  70007. {
  70008. return RelativeRectangle (getMarker (true, getMarkerState (true, 0)).position,
  70009. getMarker (true, getMarkerState (true, 1)).position,
  70010. getMarker (false, getMarkerState (false, 0)).position,
  70011. getMarker (false, getMarkerState (false, 1)).position);
  70012. }
  70013. void DrawableComposite::ValueTreeWrapper::setContentArea (const RelativeRectangle& newArea, UndoManager* undoManager)
  70014. {
  70015. setMarker (true, Marker (contentLeftMarkerName, newArea.left), undoManager);
  70016. setMarker (true, Marker (contentRightMarkerName, newArea.right), undoManager);
  70017. setMarker (false, Marker (contentTopMarkerName, newArea.top), undoManager);
  70018. setMarker (false, Marker (contentBottomMarkerName, newArea.bottom), undoManager);
  70019. }
  70020. ValueTree DrawableComposite::ValueTreeWrapper::getMarkerList (bool xAxis) const
  70021. {
  70022. return state.getChildWithName (xAxis ? markerGroupTagX : markerGroupTagY);
  70023. }
  70024. ValueTree DrawableComposite::ValueTreeWrapper::getMarkerListCreating (bool xAxis, UndoManager* undoManager)
  70025. {
  70026. return state.getOrCreateChildWithName (xAxis ? markerGroupTagX : markerGroupTagY, undoManager);
  70027. }
  70028. int DrawableComposite::ValueTreeWrapper::getNumMarkers (bool xAxis) const
  70029. {
  70030. return getMarkerList (xAxis).getNumChildren();
  70031. }
  70032. const ValueTree DrawableComposite::ValueTreeWrapper::getMarkerState (bool xAxis, int index) const
  70033. {
  70034. return getMarkerList (xAxis).getChild (index);
  70035. }
  70036. const ValueTree DrawableComposite::ValueTreeWrapper::getMarkerState (bool xAxis, const String& name) const
  70037. {
  70038. return getMarkerList (xAxis).getChildWithProperty (nameProperty, name);
  70039. }
  70040. bool DrawableComposite::ValueTreeWrapper::containsMarker (bool xAxis, const ValueTree& state) const
  70041. {
  70042. return state.isAChildOf (getMarkerList (xAxis));
  70043. }
  70044. const DrawableComposite::Marker DrawableComposite::ValueTreeWrapper::getMarker (bool xAxis, const ValueTree& state) const
  70045. {
  70046. (void) xAxis;
  70047. jassert (containsMarker (xAxis, state));
  70048. return Marker (state [nameProperty], RelativeCoordinate (state [posProperty].toString()));
  70049. }
  70050. void DrawableComposite::ValueTreeWrapper::setMarker (bool xAxis, const Marker& m, UndoManager* undoManager)
  70051. {
  70052. ValueTree markerList (getMarkerListCreating (xAxis, undoManager));
  70053. ValueTree marker (markerList.getChildWithProperty (nameProperty, m.name));
  70054. if (marker.isValid())
  70055. {
  70056. marker.setProperty (posProperty, m.position.toString(), undoManager);
  70057. }
  70058. else
  70059. {
  70060. marker = ValueTree (markerTag);
  70061. marker.setProperty (nameProperty, m.name, 0);
  70062. marker.setProperty (posProperty, m.position.toString(), 0);
  70063. markerList.addChild (marker, -1, undoManager);
  70064. }
  70065. }
  70066. void DrawableComposite::ValueTreeWrapper::removeMarker (bool xAxis, const ValueTree& state, UndoManager* undoManager)
  70067. {
  70068. if (state [nameProperty].toString() != contentLeftMarkerName
  70069. && state [nameProperty].toString() != contentRightMarkerName
  70070. && state [nameProperty].toString() != contentTopMarkerName
  70071. && state [nameProperty].toString() != contentBottomMarkerName)
  70072. return getMarkerList (xAxis).removeChild (state, undoManager);
  70073. }
  70074. const Rectangle<float> DrawableComposite::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  70075. {
  70076. const ValueTreeWrapper wrapper (tree);
  70077. setName (wrapper.getID());
  70078. Rectangle<float> damage;
  70079. bool redrawAll = false;
  70080. const RelativeParallelogram newBounds (wrapper.getBoundingBox());
  70081. if (bounds != newBounds)
  70082. {
  70083. redrawAll = true;
  70084. damage = getBounds();
  70085. bounds = newBounds;
  70086. }
  70087. const int numMarkersX = wrapper.getNumMarkers (true);
  70088. const int numMarkersY = wrapper.getNumMarkers (false);
  70089. // Remove deleted markers...
  70090. if (markersX.size() > numMarkersX || markersY.size() > numMarkersY)
  70091. {
  70092. if (! redrawAll)
  70093. {
  70094. redrawAll = true;
  70095. damage = getBounds();
  70096. }
  70097. markersX.removeRange (jmax (2, numMarkersX), markersX.size());
  70098. markersY.removeRange (jmax (2, numMarkersY), markersY.size());
  70099. }
  70100. // Update markers and add new ones..
  70101. int i;
  70102. for (i = 0; i < numMarkersX; ++i)
  70103. {
  70104. const Marker newMarker (wrapper.getMarker (true, wrapper.getMarkerState (true, i)));
  70105. Marker* m = markersX[i];
  70106. if (m == 0 || newMarker != *m)
  70107. {
  70108. if (! redrawAll)
  70109. {
  70110. redrawAll = true;
  70111. damage = getBounds();
  70112. }
  70113. if (m == 0)
  70114. markersX.add (new Marker (newMarker));
  70115. else
  70116. *m = newMarker;
  70117. }
  70118. }
  70119. for (i = 0; i < numMarkersY; ++i)
  70120. {
  70121. const Marker newMarker (wrapper.getMarker (false, wrapper.getMarkerState (false, i)));
  70122. Marker* m = markersY[i];
  70123. if (m == 0 || newMarker != *m)
  70124. {
  70125. if (! redrawAll)
  70126. {
  70127. redrawAll = true;
  70128. damage = getBounds();
  70129. }
  70130. if (m == 0)
  70131. markersY.add (new Marker (newMarker));
  70132. else
  70133. *m = newMarker;
  70134. }
  70135. }
  70136. // Remove deleted drawables..
  70137. for (i = drawables.size(); --i >= wrapper.getNumDrawables();)
  70138. {
  70139. Drawable* const d = drawables.getUnchecked(i);
  70140. if (! redrawAll)
  70141. damage = damage.getUnion (d->getBounds());
  70142. d->parent = 0;
  70143. drawables.remove (i);
  70144. }
  70145. // Update drawables and add new ones..
  70146. for (i = 0; i < wrapper.getNumDrawables(); ++i)
  70147. {
  70148. const ValueTree newDrawable (wrapper.getDrawableState (i));
  70149. Drawable* d = drawables[i];
  70150. if (d != 0)
  70151. {
  70152. if (newDrawable.hasType (d->getValueTreeType()))
  70153. {
  70154. const Rectangle<float> area (d->refreshFromValueTree (newDrawable, imageProvider));
  70155. if (! redrawAll)
  70156. damage = damage.getUnion (area);
  70157. }
  70158. else
  70159. {
  70160. if (! redrawAll)
  70161. damage = damage.getUnion (d->getBounds());
  70162. d = createChildFromValueTree (this, newDrawable, imageProvider);
  70163. drawables.set (i, d);
  70164. if (! redrawAll)
  70165. damage = damage.getUnion (d->getBounds());
  70166. }
  70167. }
  70168. else
  70169. {
  70170. d = createChildFromValueTree (this, newDrawable, imageProvider);
  70171. drawables.set (i, d);
  70172. if (! redrawAll)
  70173. damage = damage.getUnion (d->getBounds());
  70174. }
  70175. }
  70176. if (redrawAll)
  70177. damage = damage.getUnion (getBounds());
  70178. else if (! damage.isEmpty())
  70179. damage = damage.transformed (calculateTransform());
  70180. return damage;
  70181. }
  70182. const ValueTree DrawableComposite::createValueTree (ImageProvider* imageProvider) const
  70183. {
  70184. ValueTree tree (valueTreeType);
  70185. ValueTreeWrapper v (tree);
  70186. v.setID (getName(), 0);
  70187. v.setBoundingBox (bounds, 0);
  70188. int i;
  70189. for (i = 0; i < drawables.size(); ++i)
  70190. v.addDrawable (drawables.getUnchecked(i)->createValueTree (imageProvider), -1, 0);
  70191. for (i = 0; i < markersX.size(); ++i)
  70192. v.setMarker (true, *markersX.getUnchecked(i), 0);
  70193. for (i = 0; i < markersY.size(); ++i)
  70194. v.setMarker (false, *markersY.getUnchecked(i), 0);
  70195. return tree;
  70196. }
  70197. END_JUCE_NAMESPACE
  70198. /*** End of inlined file: juce_DrawableComposite.cpp ***/
  70199. /*** Start of inlined file: juce_DrawableImage.cpp ***/
  70200. BEGIN_JUCE_NAMESPACE
  70201. DrawableImage::DrawableImage()
  70202. : image (0),
  70203. opacity (1.0f),
  70204. overlayColour (0x00000000)
  70205. {
  70206. bounds.topRight = RelativePoint (Point<float> (1.0f, 0.0f));
  70207. bounds.bottomLeft = RelativePoint (Point<float> (0.0f, 1.0f));
  70208. }
  70209. DrawableImage::DrawableImage (const DrawableImage& other)
  70210. : image (other.image),
  70211. opacity (other.opacity),
  70212. overlayColour (other.overlayColour),
  70213. bounds (other.bounds)
  70214. {
  70215. }
  70216. DrawableImage::~DrawableImage()
  70217. {
  70218. }
  70219. void DrawableImage::setImage (const Image& imageToUse)
  70220. {
  70221. image = imageToUse;
  70222. if (image.isValid())
  70223. {
  70224. bounds.topLeft = RelativePoint (Point<float> (0.0f, 0.0f));
  70225. bounds.topRight = RelativePoint (Point<float> ((float) image.getWidth(), 0.0f));
  70226. bounds.bottomLeft = RelativePoint (Point<float> (0.0f, (float) image.getHeight()));
  70227. }
  70228. }
  70229. void DrawableImage::setOpacity (const float newOpacity)
  70230. {
  70231. opacity = newOpacity;
  70232. }
  70233. void DrawableImage::setOverlayColour (const Colour& newOverlayColour)
  70234. {
  70235. overlayColour = newOverlayColour;
  70236. }
  70237. void DrawableImage::setBoundingBox (const RelativeParallelogram& newBounds)
  70238. {
  70239. bounds = newBounds;
  70240. }
  70241. const AffineTransform DrawableImage::calculateTransform() const
  70242. {
  70243. if (image.isNull())
  70244. return AffineTransform::identity;
  70245. Point<float> resolved[3];
  70246. bounds.resolveThreePoints (resolved, parent);
  70247. const Point<float> tr (resolved[0] + (resolved[1] - resolved[0]) / (float) image.getWidth());
  70248. const Point<float> bl (resolved[0] + (resolved[2] - resolved[0]) / (float) image.getHeight());
  70249. return AffineTransform::fromTargetPoints (resolved[0].getX(), resolved[0].getY(),
  70250. tr.getX(), tr.getY(),
  70251. bl.getX(), bl.getY());
  70252. }
  70253. void DrawableImage::render (const Drawable::RenderingContext& context) const
  70254. {
  70255. if (image.isValid())
  70256. {
  70257. const AffineTransform t (calculateTransform().followedBy (context.transform));
  70258. if (opacity > 0.0f && ! overlayColour.isOpaque())
  70259. {
  70260. context.g.setOpacity (context.opacity * opacity);
  70261. context.g.drawImageTransformed (image, t, false);
  70262. }
  70263. if (! overlayColour.isTransparent())
  70264. {
  70265. context.g.setColour (overlayColour.withMultipliedAlpha (context.opacity));
  70266. context.g.drawImageTransformed (image, t, true);
  70267. }
  70268. }
  70269. }
  70270. const Rectangle<float> DrawableImage::getBounds() const
  70271. {
  70272. if (image.isNull())
  70273. return Rectangle<float>();
  70274. return bounds.getBounds (parent);
  70275. }
  70276. bool DrawableImage::hitTest (float x, float y) const
  70277. {
  70278. if (image.isNull())
  70279. return false;
  70280. calculateTransform().inverted().transformPoint (x, y);
  70281. const int ix = roundToInt (x);
  70282. const int iy = roundToInt (y);
  70283. return ix >= 0
  70284. && iy >= 0
  70285. && ix < image.getWidth()
  70286. && iy < image.getHeight()
  70287. && image.getPixelAt (ix, iy).getAlpha() >= 127;
  70288. }
  70289. Drawable* DrawableImage::createCopy() const
  70290. {
  70291. return new DrawableImage (*this);
  70292. }
  70293. void DrawableImage::invalidatePoints()
  70294. {
  70295. }
  70296. const Identifier DrawableImage::valueTreeType ("Image");
  70297. const Identifier DrawableImage::ValueTreeWrapper::opacity ("opacity");
  70298. const Identifier DrawableImage::ValueTreeWrapper::overlay ("overlay");
  70299. const Identifier DrawableImage::ValueTreeWrapper::image ("image");
  70300. const Identifier DrawableImage::ValueTreeWrapper::topLeft ("topLeft");
  70301. const Identifier DrawableImage::ValueTreeWrapper::topRight ("topRight");
  70302. const Identifier DrawableImage::ValueTreeWrapper::bottomLeft ("bottomLeft");
  70303. DrawableImage::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70304. : ValueTreeWrapperBase (state_)
  70305. {
  70306. jassert (state.hasType (valueTreeType));
  70307. }
  70308. const var DrawableImage::ValueTreeWrapper::getImageIdentifier() const
  70309. {
  70310. return state [image];
  70311. }
  70312. Value DrawableImage::ValueTreeWrapper::getImageIdentifierValue (UndoManager* undoManager)
  70313. {
  70314. return state.getPropertyAsValue (image, undoManager);
  70315. }
  70316. void DrawableImage::ValueTreeWrapper::setImageIdentifier (const var& newIdentifier, UndoManager* undoManager)
  70317. {
  70318. state.setProperty (image, newIdentifier, undoManager);
  70319. }
  70320. float DrawableImage::ValueTreeWrapper::getOpacity() const
  70321. {
  70322. return (float) state.getProperty (opacity, 1.0);
  70323. }
  70324. Value DrawableImage::ValueTreeWrapper::getOpacityValue (UndoManager* undoManager)
  70325. {
  70326. if (! state.hasProperty (opacity))
  70327. state.setProperty (opacity, 1.0, undoManager);
  70328. return state.getPropertyAsValue (opacity, undoManager);
  70329. }
  70330. void DrawableImage::ValueTreeWrapper::setOpacity (float newOpacity, UndoManager* undoManager)
  70331. {
  70332. state.setProperty (opacity, newOpacity, undoManager);
  70333. }
  70334. const Colour DrawableImage::ValueTreeWrapper::getOverlayColour() const
  70335. {
  70336. return Colour (state [overlay].toString().getHexValue32());
  70337. }
  70338. void DrawableImage::ValueTreeWrapper::setOverlayColour (const Colour& newColour, UndoManager* undoManager)
  70339. {
  70340. if (newColour.isTransparent())
  70341. state.removeProperty (overlay, undoManager);
  70342. else
  70343. state.setProperty (overlay, String::toHexString ((int) newColour.getARGB()), undoManager);
  70344. }
  70345. Value DrawableImage::ValueTreeWrapper::getOverlayColourValue (UndoManager* undoManager)
  70346. {
  70347. return state.getPropertyAsValue (overlay, undoManager);
  70348. }
  70349. const RelativeParallelogram DrawableImage::ValueTreeWrapper::getBoundingBox() const
  70350. {
  70351. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  70352. state.getProperty (topRight, "100, 0"),
  70353. state.getProperty (bottomLeft, "0, 100"));
  70354. }
  70355. void DrawableImage::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  70356. {
  70357. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  70358. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  70359. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  70360. }
  70361. const Rectangle<float> DrawableImage::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  70362. {
  70363. const ValueTreeWrapper controller (tree);
  70364. setName (controller.getID());
  70365. const float newOpacity = controller.getOpacity();
  70366. const Colour newOverlayColour (controller.getOverlayColour());
  70367. Image newImage;
  70368. const var imageIdentifier (controller.getImageIdentifier());
  70369. jassert (imageProvider != 0 || imageIdentifier.isVoid()); // if you're using images, you need to provide something that can load and save them!
  70370. if (imageProvider != 0)
  70371. newImage = imageProvider->getImageForIdentifier (imageIdentifier);
  70372. const RelativeParallelogram newBounds (controller.getBoundingBox());
  70373. if (newOpacity != opacity || overlayColour != newOverlayColour || image != newImage || bounds != newBounds)
  70374. {
  70375. const Rectangle<float> damage (getBounds());
  70376. opacity = newOpacity;
  70377. overlayColour = newOverlayColour;
  70378. bounds = newBounds;
  70379. image = newImage;
  70380. return damage.getUnion (getBounds());
  70381. }
  70382. return Rectangle<float>();
  70383. }
  70384. const ValueTree DrawableImage::createValueTree (ImageProvider* imageProvider) const
  70385. {
  70386. ValueTree tree (valueTreeType);
  70387. ValueTreeWrapper v (tree);
  70388. v.setID (getName(), 0);
  70389. v.setOpacity (opacity, 0);
  70390. v.setOverlayColour (overlayColour, 0);
  70391. v.setBoundingBox (bounds, 0);
  70392. if (image.isValid())
  70393. {
  70394. jassert (imageProvider != 0); // if you're using images, you need to provide something that can load and save them!
  70395. if (imageProvider != 0)
  70396. v.setImageIdentifier (imageProvider->getIdentifierForImage (image), 0);
  70397. }
  70398. return tree;
  70399. }
  70400. END_JUCE_NAMESPACE
  70401. /*** End of inlined file: juce_DrawableImage.cpp ***/
  70402. /*** Start of inlined file: juce_DrawablePath.cpp ***/
  70403. BEGIN_JUCE_NAMESPACE
  70404. DrawablePath::DrawablePath()
  70405. : mainFill (Colours::black),
  70406. strokeFill (Colours::black),
  70407. strokeType (0.0f),
  70408. pathNeedsUpdating (true),
  70409. strokeNeedsUpdating (true)
  70410. {
  70411. }
  70412. DrawablePath::DrawablePath (const DrawablePath& other)
  70413. : mainFill (other.mainFill),
  70414. strokeFill (other.strokeFill),
  70415. strokeType (other.strokeType),
  70416. pathNeedsUpdating (true),
  70417. strokeNeedsUpdating (true)
  70418. {
  70419. if (other.relativePath != 0)
  70420. relativePath = new RelativePointPath (*other.relativePath);
  70421. else
  70422. path = other.path;
  70423. }
  70424. DrawablePath::~DrawablePath()
  70425. {
  70426. }
  70427. void DrawablePath::setPath (const Path& newPath)
  70428. {
  70429. path = newPath;
  70430. strokeNeedsUpdating = true;
  70431. }
  70432. void DrawablePath::setFill (const FillType& newFill)
  70433. {
  70434. mainFill = newFill;
  70435. }
  70436. void DrawablePath::setStrokeFill (const FillType& newFill)
  70437. {
  70438. strokeFill = newFill;
  70439. }
  70440. void DrawablePath::setStrokeType (const PathStrokeType& newStrokeType)
  70441. {
  70442. strokeType = newStrokeType;
  70443. strokeNeedsUpdating = true;
  70444. }
  70445. void DrawablePath::setStrokeThickness (const float newThickness)
  70446. {
  70447. setStrokeType (PathStrokeType (newThickness, strokeType.getJointStyle(), strokeType.getEndStyle()));
  70448. }
  70449. void DrawablePath::updatePath() const
  70450. {
  70451. if (pathNeedsUpdating)
  70452. {
  70453. pathNeedsUpdating = false;
  70454. if (relativePath != 0)
  70455. {
  70456. path.clear();
  70457. relativePath->createPath (path, parent);
  70458. strokeNeedsUpdating = true;
  70459. }
  70460. }
  70461. }
  70462. void DrawablePath::updateStroke() const
  70463. {
  70464. if (strokeNeedsUpdating)
  70465. {
  70466. strokeNeedsUpdating = false;
  70467. updatePath();
  70468. stroke.clear();
  70469. strokeType.createStrokedPath (stroke, path, AffineTransform::identity, 4.0f);
  70470. }
  70471. }
  70472. const Path& DrawablePath::getPath() const
  70473. {
  70474. updatePath();
  70475. return path;
  70476. }
  70477. const Path& DrawablePath::getStrokePath() const
  70478. {
  70479. updateStroke();
  70480. return stroke;
  70481. }
  70482. bool DrawablePath::isStrokeVisible() const throw()
  70483. {
  70484. return strokeType.getStrokeThickness() > 0.0f && ! strokeFill.isInvisible();
  70485. }
  70486. void DrawablePath::invalidatePoints()
  70487. {
  70488. pathNeedsUpdating = true;
  70489. strokeNeedsUpdating = true;
  70490. }
  70491. void DrawablePath::render (const Drawable::RenderingContext& context) const
  70492. {
  70493. {
  70494. FillType f (mainFill);
  70495. if (f.isGradient())
  70496. f.gradient->multiplyOpacity (context.opacity);
  70497. else
  70498. f.setOpacity (f.getOpacity() * context.opacity);
  70499. f.transform = f.transform.followedBy (context.transform);
  70500. context.g.setFillType (f);
  70501. context.g.fillPath (getPath(), context.transform);
  70502. }
  70503. if (isStrokeVisible())
  70504. {
  70505. FillType f (strokeFill);
  70506. if (f.isGradient())
  70507. f.gradient->multiplyOpacity (context.opacity);
  70508. else
  70509. f.setOpacity (f.getOpacity() * context.opacity);
  70510. f.transform = f.transform.followedBy (context.transform);
  70511. context.g.setFillType (f);
  70512. context.g.fillPath (getStrokePath(), context.transform);
  70513. }
  70514. }
  70515. const Rectangle<float> DrawablePath::getBounds() const
  70516. {
  70517. if (isStrokeVisible())
  70518. return getStrokePath().getBounds();
  70519. else
  70520. return getPath().getBounds();
  70521. }
  70522. bool DrawablePath::hitTest (float x, float y) const
  70523. {
  70524. return getPath().contains (x, y)
  70525. || (isStrokeVisible() && getStrokePath().contains (x, y));
  70526. }
  70527. Drawable* DrawablePath::createCopy() const
  70528. {
  70529. return new DrawablePath (*this);
  70530. }
  70531. const Identifier DrawablePath::valueTreeType ("Path");
  70532. const Identifier DrawablePath::ValueTreeWrapper::fill ("Fill");
  70533. const Identifier DrawablePath::ValueTreeWrapper::stroke ("Stroke");
  70534. const Identifier DrawablePath::ValueTreeWrapper::path ("Path");
  70535. const Identifier DrawablePath::ValueTreeWrapper::jointStyle ("jointStyle");
  70536. const Identifier DrawablePath::ValueTreeWrapper::capStyle ("capStyle");
  70537. const Identifier DrawablePath::ValueTreeWrapper::strokeWidth ("strokeWidth");
  70538. const Identifier DrawablePath::ValueTreeWrapper::nonZeroWinding ("nonZeroWinding");
  70539. const Identifier DrawablePath::ValueTreeWrapper::point1 ("p1");
  70540. const Identifier DrawablePath::ValueTreeWrapper::point2 ("p2");
  70541. const Identifier DrawablePath::ValueTreeWrapper::point3 ("p3");
  70542. DrawablePath::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70543. : ValueTreeWrapperBase (state_)
  70544. {
  70545. jassert (state.hasType (valueTreeType));
  70546. }
  70547. ValueTree DrawablePath::ValueTreeWrapper::getPathState()
  70548. {
  70549. return state.getOrCreateChildWithName (path, 0);
  70550. }
  70551. ValueTree DrawablePath::ValueTreeWrapper::getMainFillState()
  70552. {
  70553. ValueTree v (state.getChildWithName (fill));
  70554. if (v.isValid())
  70555. return v;
  70556. setMainFill (Colours::black, 0, 0, 0, 0, 0);
  70557. return getMainFillState();
  70558. }
  70559. ValueTree DrawablePath::ValueTreeWrapper::getStrokeFillState()
  70560. {
  70561. ValueTree v (state.getChildWithName (stroke));
  70562. if (v.isValid())
  70563. return v;
  70564. setStrokeFill (Colours::black, 0, 0, 0, 0, 0);
  70565. return getStrokeFillState();
  70566. }
  70567. const FillType DrawablePath::ValueTreeWrapper::getMainFill (Expression::EvaluationContext* nameFinder,
  70568. ImageProvider* imageProvider) const
  70569. {
  70570. return readFillType (state.getChildWithName (fill), 0, 0, 0, nameFinder, imageProvider);
  70571. }
  70572. void DrawablePath::ValueTreeWrapper::setMainFill (const FillType& newFill, const RelativePoint* gp1,
  70573. const RelativePoint* gp2, const RelativePoint* gp3,
  70574. ImageProvider* imageProvider, UndoManager* undoManager)
  70575. {
  70576. ValueTree v (state.getOrCreateChildWithName (fill, undoManager));
  70577. writeFillType (v, newFill, gp1, gp2, gp3, imageProvider, undoManager);
  70578. }
  70579. const FillType DrawablePath::ValueTreeWrapper::getStrokeFill (Expression::EvaluationContext* nameFinder,
  70580. ImageProvider* imageProvider) const
  70581. {
  70582. return readFillType (state.getChildWithName (stroke), 0, 0, 0, nameFinder, imageProvider);
  70583. }
  70584. void DrawablePath::ValueTreeWrapper::setStrokeFill (const FillType& newFill, const RelativePoint* gp1,
  70585. const RelativePoint* gp2, const RelativePoint* gp3,
  70586. ImageProvider* imageProvider, UndoManager* undoManager)
  70587. {
  70588. ValueTree v (state.getOrCreateChildWithName (stroke, undoManager));
  70589. writeFillType (v, newFill, gp1, gp2, gp3, imageProvider, undoManager);
  70590. }
  70591. const PathStrokeType DrawablePath::ValueTreeWrapper::getStrokeType() const
  70592. {
  70593. const String jointStyleString (state [jointStyle].toString());
  70594. const String capStyleString (state [capStyle].toString());
  70595. return PathStrokeType (state [strokeWidth],
  70596. jointStyleString == "curved" ? PathStrokeType::curved
  70597. : (jointStyleString == "bevel" ? PathStrokeType::beveled
  70598. : PathStrokeType::mitered),
  70599. capStyleString == "square" ? PathStrokeType::square
  70600. : (capStyleString == "round" ? PathStrokeType::rounded
  70601. : PathStrokeType::butt));
  70602. }
  70603. void DrawablePath::ValueTreeWrapper::setStrokeType (const PathStrokeType& newStrokeType, UndoManager* undoManager)
  70604. {
  70605. state.setProperty (strokeWidth, (double) newStrokeType.getStrokeThickness(), undoManager);
  70606. state.setProperty (jointStyle, newStrokeType.getJointStyle() == PathStrokeType::mitered
  70607. ? "miter" : (newStrokeType.getJointStyle() == PathStrokeType::curved ? "curved" : "bevel"), undoManager);
  70608. state.setProperty (capStyle, newStrokeType.getEndStyle() == PathStrokeType::butt
  70609. ? "butt" : (newStrokeType.getEndStyle() == PathStrokeType::square ? "square" : "round"), undoManager);
  70610. }
  70611. bool DrawablePath::ValueTreeWrapper::usesNonZeroWinding() const
  70612. {
  70613. return state [nonZeroWinding];
  70614. }
  70615. void DrawablePath::ValueTreeWrapper::setUsesNonZeroWinding (bool b, UndoManager* undoManager)
  70616. {
  70617. state.setProperty (nonZeroWinding, b, undoManager);
  70618. }
  70619. const Identifier DrawablePath::ValueTreeWrapper::Element::mode ("mode");
  70620. const Identifier DrawablePath::ValueTreeWrapper::Element::startSubPathElement ("Move");
  70621. const Identifier DrawablePath::ValueTreeWrapper::Element::closeSubPathElement ("Close");
  70622. const Identifier DrawablePath::ValueTreeWrapper::Element::lineToElement ("Line");
  70623. const Identifier DrawablePath::ValueTreeWrapper::Element::quadraticToElement ("Quad");
  70624. const Identifier DrawablePath::ValueTreeWrapper::Element::cubicToElement ("Cubic");
  70625. const char* DrawablePath::ValueTreeWrapper::Element::cornerMode = "corner";
  70626. const char* DrawablePath::ValueTreeWrapper::Element::roundedMode = "round";
  70627. const char* DrawablePath::ValueTreeWrapper::Element::symmetricMode = "symm";
  70628. DrawablePath::ValueTreeWrapper::Element::Element (const ValueTree& state_)
  70629. : state (state_)
  70630. {
  70631. }
  70632. DrawablePath::ValueTreeWrapper::Element::~Element()
  70633. {
  70634. }
  70635. DrawablePath::ValueTreeWrapper DrawablePath::ValueTreeWrapper::Element::getParent() const
  70636. {
  70637. return ValueTreeWrapper (state.getParent().getParent());
  70638. }
  70639. DrawablePath::ValueTreeWrapper::Element DrawablePath::ValueTreeWrapper::Element::getPreviousElement() const
  70640. {
  70641. return Element (state.getSibling (-1));
  70642. }
  70643. int DrawablePath::ValueTreeWrapper::Element::getNumControlPoints() const throw()
  70644. {
  70645. const Identifier i (state.getType());
  70646. if (i == startSubPathElement || i == lineToElement) return 1;
  70647. if (i == quadraticToElement) return 2;
  70648. if (i == cubicToElement) return 3;
  70649. return 0;
  70650. }
  70651. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getControlPoint (const int index) const
  70652. {
  70653. jassert (index >= 0 && index < getNumControlPoints());
  70654. return RelativePoint (state [index == 0 ? point1 : (index == 1 ? point2 : point3)].toString());
  70655. }
  70656. Value DrawablePath::ValueTreeWrapper::Element::getControlPointValue (int index, UndoManager* undoManager) const
  70657. {
  70658. jassert (index >= 0 && index < getNumControlPoints());
  70659. return state.getPropertyAsValue (index == 0 ? point1 : (index == 1 ? point2 : point3), undoManager);
  70660. }
  70661. void DrawablePath::ValueTreeWrapper::Element::setControlPoint (const int index, const RelativePoint& point, UndoManager* undoManager)
  70662. {
  70663. jassert (index >= 0 && index < getNumControlPoints());
  70664. return state.setProperty (index == 0 ? point1 : (index == 1 ? point2 : point3), point.toString(), undoManager);
  70665. }
  70666. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getStartPoint() const
  70667. {
  70668. const Identifier i (state.getType());
  70669. if (i == startSubPathElement)
  70670. return getControlPoint (0);
  70671. jassert (i == lineToElement || i == quadraticToElement || i == cubicToElement || i == closeSubPathElement);
  70672. return getPreviousElement().getEndPoint();
  70673. }
  70674. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getEndPoint() const
  70675. {
  70676. const Identifier i (state.getType());
  70677. if (i == startSubPathElement || i == lineToElement) return getControlPoint (0);
  70678. if (i == quadraticToElement) return getControlPoint (1);
  70679. if (i == cubicToElement) return getControlPoint (2);
  70680. jassert (i == closeSubPathElement);
  70681. return RelativePoint();
  70682. }
  70683. float DrawablePath::ValueTreeWrapper::Element::getLength (Expression::EvaluationContext* nameFinder) const
  70684. {
  70685. const Identifier i (state.getType());
  70686. if (i == lineToElement || i == closeSubPathElement)
  70687. return getEndPoint().resolve (nameFinder).getDistanceFrom (getStartPoint().resolve (nameFinder));
  70688. if (i == cubicToElement)
  70689. {
  70690. Path p;
  70691. p.startNewSubPath (getStartPoint().resolve (nameFinder));
  70692. p.cubicTo (getControlPoint (0).resolve (nameFinder), getControlPoint (1).resolve (nameFinder), getControlPoint (2).resolve (nameFinder));
  70693. return p.getLength();
  70694. }
  70695. if (i == quadraticToElement)
  70696. {
  70697. Path p;
  70698. p.startNewSubPath (getStartPoint().resolve (nameFinder));
  70699. p.quadraticTo (getControlPoint (0).resolve (nameFinder), getControlPoint (1).resolve (nameFinder));
  70700. return p.getLength();
  70701. }
  70702. jassert (i == startSubPathElement);
  70703. return 0;
  70704. }
  70705. const String DrawablePath::ValueTreeWrapper::Element::getModeOfEndPoint() const
  70706. {
  70707. return state [mode].toString();
  70708. }
  70709. void DrawablePath::ValueTreeWrapper::Element::setModeOfEndPoint (const String& newMode, UndoManager* undoManager)
  70710. {
  70711. if (state.hasType (cubicToElement))
  70712. state.setProperty (mode, newMode, undoManager);
  70713. }
  70714. void DrawablePath::ValueTreeWrapper::Element::convertToLine (UndoManager* undoManager)
  70715. {
  70716. const Identifier i (state.getType());
  70717. if (i == quadraticToElement || i == cubicToElement)
  70718. {
  70719. ValueTree newState (lineToElement);
  70720. Element e (newState);
  70721. e.setControlPoint (0, getEndPoint(), undoManager);
  70722. state = newState;
  70723. }
  70724. }
  70725. void DrawablePath::ValueTreeWrapper::Element::convertToCubic (Expression::EvaluationContext* nameFinder, UndoManager* undoManager)
  70726. {
  70727. const Identifier i (state.getType());
  70728. if (i == lineToElement || i == quadraticToElement)
  70729. {
  70730. ValueTree newState (cubicToElement);
  70731. Element e (newState);
  70732. const RelativePoint start (getStartPoint());
  70733. const RelativePoint end (getEndPoint());
  70734. const Point<float> startResolved (start.resolve (nameFinder));
  70735. const Point<float> endResolved (end.resolve (nameFinder));
  70736. e.setControlPoint (0, startResolved + (endResolved - startResolved) * 0.3f, undoManager);
  70737. e.setControlPoint (1, startResolved + (endResolved - startResolved) * 0.7f, undoManager);
  70738. e.setControlPoint (2, end, undoManager);
  70739. state = newState;
  70740. }
  70741. }
  70742. void DrawablePath::ValueTreeWrapper::Element::convertToPathBreak (UndoManager* undoManager)
  70743. {
  70744. const Identifier i (state.getType());
  70745. if (i != startSubPathElement)
  70746. {
  70747. ValueTree newState (startSubPathElement);
  70748. Element e (newState);
  70749. e.setControlPoint (0, getEndPoint(), undoManager);
  70750. state = newState;
  70751. }
  70752. }
  70753. static const Point<float> findCubicSubdivisionPoint (float proportion, const Point<float> points[4])
  70754. {
  70755. const Point<float> mid1 (points[0] + (points[1] - points[0]) * proportion),
  70756. mid2 (points[1] + (points[2] - points[1]) * proportion),
  70757. mid3 (points[2] + (points[3] - points[2]) * proportion);
  70758. const Point<float> newCp1 (mid1 + (mid2 - mid1) * proportion),
  70759. newCp2 (mid2 + (mid3 - mid2) * proportion);
  70760. return newCp1 + (newCp2 - newCp1) * proportion;
  70761. }
  70762. static const Point<float> findQuadraticSubdivisionPoint (float proportion, const Point<float> points[3])
  70763. {
  70764. const Point<float> mid1 (points[0] + (points[1] - points[0]) * proportion),
  70765. mid2 (points[1] + (points[2] - points[1]) * proportion);
  70766. return mid1 + (mid2 - mid1) * proportion;
  70767. }
  70768. float DrawablePath::ValueTreeWrapper::Element::findProportionAlongLine (const Point<float>& targetPoint, Expression::EvaluationContext* nameFinder) const
  70769. {
  70770. const Identifier i (state.getType());
  70771. float bestProp = 0;
  70772. if (i == cubicToElement)
  70773. {
  70774. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getControlPoint (1)), rp4 (getEndPoint());
  70775. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder), rp4.resolve (nameFinder) };
  70776. float bestDistance = std::numeric_limits<float>::max();
  70777. for (int i = 110; --i >= 0;)
  70778. {
  70779. float prop = i > 10 ? ((i - 10) / 100.0f) : (bestProp + ((i - 5) / 1000.0f));
  70780. const Point<float> centre (findCubicSubdivisionPoint (prop, points));
  70781. const float distance = centre.getDistanceFrom (targetPoint);
  70782. if (distance < bestDistance)
  70783. {
  70784. bestProp = prop;
  70785. bestDistance = distance;
  70786. }
  70787. }
  70788. }
  70789. else if (i == quadraticToElement)
  70790. {
  70791. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getEndPoint());
  70792. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder) };
  70793. float bestDistance = std::numeric_limits<float>::max();
  70794. for (int i = 110; --i >= 0;)
  70795. {
  70796. float prop = i > 10 ? ((i - 10) / 100.0f) : (bestProp + ((i - 5) / 1000.0f));
  70797. const Point<float> centre (findQuadraticSubdivisionPoint ((float) prop, points));
  70798. const float distance = centre.getDistanceFrom (targetPoint);
  70799. if (distance < bestDistance)
  70800. {
  70801. bestProp = prop;
  70802. bestDistance = distance;
  70803. }
  70804. }
  70805. }
  70806. else if (i == lineToElement)
  70807. {
  70808. RelativePoint rp1 (getStartPoint()), rp2 (getEndPoint());
  70809. const Line<float> line (rp1.resolve (nameFinder), rp2.resolve (nameFinder));
  70810. bestProp = line.findNearestProportionalPositionTo (targetPoint);
  70811. }
  70812. return bestProp;
  70813. }
  70814. ValueTree DrawablePath::ValueTreeWrapper::Element::insertPoint (const Point<float>& targetPoint, Expression::EvaluationContext* nameFinder, UndoManager* undoManager)
  70815. {
  70816. ValueTree newTree;
  70817. const Identifier i (state.getType());
  70818. if (i == cubicToElement)
  70819. {
  70820. float bestProp = findProportionAlongLine (targetPoint, nameFinder);
  70821. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getControlPoint (1)), rp4 (getEndPoint());
  70822. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder), rp4.resolve (nameFinder) };
  70823. const Point<float> mid1 (points[0] + (points[1] - points[0]) * bestProp),
  70824. mid2 (points[1] + (points[2] - points[1]) * bestProp),
  70825. mid3 (points[2] + (points[3] - points[2]) * bestProp);
  70826. const Point<float> newCp1 (mid1 + (mid2 - mid1) * bestProp),
  70827. newCp2 (mid2 + (mid3 - mid2) * bestProp);
  70828. const Point<float> newCentre (newCp1 + (newCp2 - newCp1) * bestProp);
  70829. setControlPoint (0, mid1, undoManager);
  70830. setControlPoint (1, newCp1, undoManager);
  70831. setControlPoint (2, newCentre, undoManager);
  70832. setModeOfEndPoint (roundedMode, undoManager);
  70833. Element newElement (newTree = ValueTree (cubicToElement));
  70834. newElement.setControlPoint (0, newCp2, 0);
  70835. newElement.setControlPoint (1, mid3, 0);
  70836. newElement.setControlPoint (2, rp4, 0);
  70837. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70838. }
  70839. else if (i == quadraticToElement)
  70840. {
  70841. float bestProp = findProportionAlongLine (targetPoint, nameFinder);
  70842. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getEndPoint());
  70843. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder) };
  70844. const Point<float> mid1 (points[0] + (points[1] - points[0]) * bestProp),
  70845. mid2 (points[1] + (points[2] - points[1]) * bestProp);
  70846. const Point<float> newCentre (mid1 + (mid2 - mid1) * bestProp);
  70847. setControlPoint (0, mid1, undoManager);
  70848. setControlPoint (1, newCentre, undoManager);
  70849. setModeOfEndPoint (roundedMode, undoManager);
  70850. Element newElement (newTree = ValueTree (quadraticToElement));
  70851. newElement.setControlPoint (0, mid2, 0);
  70852. newElement.setControlPoint (1, rp3, 0);
  70853. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70854. }
  70855. else if (i == lineToElement)
  70856. {
  70857. RelativePoint rp1 (getStartPoint()), rp2 (getEndPoint());
  70858. const Line<float> line (rp1.resolve (nameFinder), rp2.resolve (nameFinder));
  70859. const Point<float> newPoint (line.findNearestPointTo (targetPoint));
  70860. setControlPoint (0, newPoint, undoManager);
  70861. Element newElement (newTree = ValueTree (lineToElement));
  70862. newElement.setControlPoint (0, rp2, 0);
  70863. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70864. }
  70865. else if (i == closeSubPathElement)
  70866. {
  70867. }
  70868. return newTree;
  70869. }
  70870. void DrawablePath::ValueTreeWrapper::Element::removePoint (UndoManager* undoManager)
  70871. {
  70872. state.getParent().removeChild (state, undoManager);
  70873. }
  70874. const Rectangle<float> DrawablePath::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  70875. {
  70876. Rectangle<float> damageRect;
  70877. ValueTreeWrapper v (tree);
  70878. setName (v.getID());
  70879. bool needsRedraw = false;
  70880. const FillType newFill (v.getMainFill (parent, imageProvider));
  70881. if (mainFill != newFill)
  70882. {
  70883. needsRedraw = true;
  70884. mainFill = newFill;
  70885. }
  70886. const FillType newStrokeFill (v.getStrokeFill (parent, imageProvider));
  70887. if (strokeFill != newStrokeFill)
  70888. {
  70889. needsRedraw = true;
  70890. strokeFill = newStrokeFill;
  70891. }
  70892. const PathStrokeType newStroke (v.getStrokeType());
  70893. ScopedPointer<RelativePointPath> newRelativePath (new RelativePointPath (tree));
  70894. Path newPath;
  70895. newRelativePath->createPath (newPath, parent);
  70896. if (! newRelativePath->containsAnyDynamicPoints())
  70897. newRelativePath = 0;
  70898. if (strokeType != newStroke || path != newPath)
  70899. {
  70900. damageRect = getBounds();
  70901. path.swapWithPath (newPath);
  70902. strokeNeedsUpdating = true;
  70903. strokeType = newStroke;
  70904. needsRedraw = true;
  70905. }
  70906. relativePath = newRelativePath;
  70907. if (needsRedraw)
  70908. damageRect = damageRect.getUnion (getBounds());
  70909. return damageRect;
  70910. }
  70911. const ValueTree DrawablePath::createValueTree (ImageProvider* imageProvider) const
  70912. {
  70913. ValueTree tree (valueTreeType);
  70914. ValueTreeWrapper v (tree);
  70915. v.setID (getName(), 0);
  70916. v.setMainFill (mainFill, 0, 0, 0, imageProvider, 0);
  70917. v.setStrokeFill (strokeFill, 0, 0, 0, imageProvider, 0);
  70918. v.setStrokeType (strokeType, 0);
  70919. if (relativePath != 0)
  70920. {
  70921. relativePath->writeTo (tree, 0);
  70922. }
  70923. else
  70924. {
  70925. RelativePointPath rp (path);
  70926. rp.writeTo (tree, 0);
  70927. }
  70928. return tree;
  70929. }
  70930. END_JUCE_NAMESPACE
  70931. /*** End of inlined file: juce_DrawablePath.cpp ***/
  70932. /*** Start of inlined file: juce_DrawableText.cpp ***/
  70933. BEGIN_JUCE_NAMESPACE
  70934. DrawableText::DrawableText()
  70935. : colour (Colours::black),
  70936. justification (Justification::centredLeft)
  70937. {
  70938. setBoundingBox (RelativeParallelogram (RelativePoint (0.0f, 0.0f),
  70939. RelativePoint (50.0f, 0.0f),
  70940. RelativePoint (0.0f, 20.0f)));
  70941. setFont (Font (15.0f), true);
  70942. }
  70943. DrawableText::DrawableText (const DrawableText& other)
  70944. : bounds (other.bounds),
  70945. fontSizeControlPoint (other.fontSizeControlPoint),
  70946. font (other.font),
  70947. text (other.text),
  70948. colour (other.colour),
  70949. justification (other.justification)
  70950. {
  70951. }
  70952. DrawableText::~DrawableText()
  70953. {
  70954. }
  70955. void DrawableText::setText (const String& newText)
  70956. {
  70957. text = newText;
  70958. }
  70959. void DrawableText::setColour (const Colour& newColour)
  70960. {
  70961. colour = newColour;
  70962. }
  70963. void DrawableText::setFont (const Font& newFont, bool applySizeAndScale)
  70964. {
  70965. font = newFont;
  70966. if (applySizeAndScale)
  70967. {
  70968. Point<float> corners[3];
  70969. bounds.resolveThreePoints (corners, parent);
  70970. setFontSizeControlPoint (RelativePoint (RelativeParallelogram::getPointForInternalCoord (corners,
  70971. Point<float> (font.getHorizontalScale() * font.getHeight(), font.getHeight()))));
  70972. }
  70973. }
  70974. void DrawableText::setJustification (const Justification& newJustification)
  70975. {
  70976. justification = newJustification;
  70977. }
  70978. void DrawableText::setBoundingBox (const RelativeParallelogram& newBounds)
  70979. {
  70980. bounds = newBounds;
  70981. }
  70982. void DrawableText::setFontSizeControlPoint (const RelativePoint& newPoint)
  70983. {
  70984. fontSizeControlPoint = newPoint;
  70985. }
  70986. void DrawableText::render (const Drawable::RenderingContext& context) const
  70987. {
  70988. Point<float> points[3];
  70989. bounds.resolveThreePoints (points, parent);
  70990. const float w = Line<float> (points[0], points[1]).getLength();
  70991. const float h = Line<float> (points[0], points[2]).getLength();
  70992. const Point<float> fontCoords (bounds.getInternalCoordForPoint (points, fontSizeControlPoint.resolve (parent)));
  70993. const float fontHeight = jlimit (1.0f, h, fontCoords.getY());
  70994. const float fontWidth = jlimit (0.01f, w, fontCoords.getX());
  70995. Font f (font);
  70996. f.setHeight (fontHeight);
  70997. f.setHorizontalScale (fontWidth / fontHeight);
  70998. context.g.setColour (colour.withMultipliedAlpha (context.opacity));
  70999. GlyphArrangement ga;
  71000. ga.addFittedText (f, text, 0, 0, w, h, justification, 0x100000);
  71001. ga.draw (context.g,
  71002. AffineTransform::fromTargetPoints (0, 0, points[0].getX(), points[0].getY(),
  71003. w, 0, points[1].getX(), points[1].getY(),
  71004. 0, h, points[2].getX(), points[2].getY())
  71005. .followedBy (context.transform));
  71006. }
  71007. const Rectangle<float> DrawableText::getBounds() const
  71008. {
  71009. return bounds.getBounds (parent);
  71010. }
  71011. bool DrawableText::hitTest (float x, float y) const
  71012. {
  71013. Path p;
  71014. bounds.getPath (p, parent);
  71015. return p.contains (x, y);
  71016. }
  71017. Drawable* DrawableText::createCopy() const
  71018. {
  71019. return new DrawableText (*this);
  71020. }
  71021. void DrawableText::invalidatePoints()
  71022. {
  71023. }
  71024. const Identifier DrawableText::valueTreeType ("Text");
  71025. const Identifier DrawableText::ValueTreeWrapper::text ("text");
  71026. const Identifier DrawableText::ValueTreeWrapper::colour ("colour");
  71027. const Identifier DrawableText::ValueTreeWrapper::font ("font");
  71028. const Identifier DrawableText::ValueTreeWrapper::justification ("justification");
  71029. const Identifier DrawableText::ValueTreeWrapper::topLeft ("topLeft");
  71030. const Identifier DrawableText::ValueTreeWrapper::topRight ("topRight");
  71031. const Identifier DrawableText::ValueTreeWrapper::bottomLeft ("bottomLeft");
  71032. const Identifier DrawableText::ValueTreeWrapper::fontSizeAnchor ("fontSizeAnchor");
  71033. DrawableText::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  71034. : ValueTreeWrapperBase (state_)
  71035. {
  71036. jassert (state.hasType (valueTreeType));
  71037. }
  71038. const String DrawableText::ValueTreeWrapper::getText() const
  71039. {
  71040. return state [text].toString();
  71041. }
  71042. void DrawableText::ValueTreeWrapper::setText (const String& newText, UndoManager* undoManager)
  71043. {
  71044. state.setProperty (text, newText, undoManager);
  71045. }
  71046. Value DrawableText::ValueTreeWrapper::getTextValue (UndoManager* undoManager)
  71047. {
  71048. return state.getPropertyAsValue (text, undoManager);
  71049. }
  71050. const Colour DrawableText::ValueTreeWrapper::getColour() const
  71051. {
  71052. return Colour::fromString (state [colour].toString());
  71053. }
  71054. void DrawableText::ValueTreeWrapper::setColour (const Colour& newColour, UndoManager* undoManager)
  71055. {
  71056. state.setProperty (colour, newColour.toString(), undoManager);
  71057. }
  71058. const Justification DrawableText::ValueTreeWrapper::getJustification() const
  71059. {
  71060. return Justification ((int) state [justification]);
  71061. }
  71062. void DrawableText::ValueTreeWrapper::setJustification (const Justification& newJustification, UndoManager* undoManager)
  71063. {
  71064. state.setProperty (justification, newJustification.getFlags(), undoManager);
  71065. }
  71066. const Font DrawableText::ValueTreeWrapper::getFont() const
  71067. {
  71068. return Font::fromString (state [font]);
  71069. }
  71070. void DrawableText::ValueTreeWrapper::setFont (const Font& newFont, UndoManager* undoManager)
  71071. {
  71072. state.setProperty (font, newFont.toString(), undoManager);
  71073. }
  71074. Value DrawableText::ValueTreeWrapper::getFontValue (UndoManager* undoManager)
  71075. {
  71076. return state.getPropertyAsValue (font, undoManager);
  71077. }
  71078. const RelativeParallelogram DrawableText::ValueTreeWrapper::getBoundingBox() const
  71079. {
  71080. return RelativeParallelogram (state [topLeft].toString(), state [topRight].toString(), state [bottomLeft].toString());
  71081. }
  71082. void DrawableText::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  71083. {
  71084. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  71085. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  71086. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  71087. }
  71088. const RelativePoint DrawableText::ValueTreeWrapper::getFontSizeControlPoint() const
  71089. {
  71090. return state [fontSizeAnchor].toString();
  71091. }
  71092. void DrawableText::ValueTreeWrapper::setFontSizeControlPoint (const RelativePoint& p, UndoManager* undoManager)
  71093. {
  71094. state.setProperty (fontSizeAnchor, p.toString(), undoManager);
  71095. }
  71096. const Rectangle<float> DrawableText::refreshFromValueTree (const ValueTree& tree, ImageProvider*)
  71097. {
  71098. ValueTreeWrapper v (tree);
  71099. setName (v.getID());
  71100. const RelativeParallelogram newBounds (v.getBoundingBox());
  71101. const RelativePoint newFontPoint (v.getFontSizeControlPoint());
  71102. const Colour newColour (v.getColour());
  71103. const Justification newJustification (v.getJustification());
  71104. const String newText (v.getText());
  71105. const Font newFont (v.getFont());
  71106. if (text != newText || font != newFont || justification != newJustification
  71107. || colour != newColour || bounds != newBounds || newFontPoint != fontSizeControlPoint)
  71108. {
  71109. const Rectangle<float> damage (getBounds());
  71110. setBoundingBox (newBounds);
  71111. setFontSizeControlPoint (newFontPoint);
  71112. setColour (newColour);
  71113. setFont (newFont, false);
  71114. setJustification (newJustification);
  71115. setText (newText);
  71116. return damage.getUnion (getBounds());
  71117. }
  71118. return Rectangle<float>();
  71119. }
  71120. const ValueTree DrawableText::createValueTree (ImageProvider*) const
  71121. {
  71122. ValueTree tree (valueTreeType);
  71123. ValueTreeWrapper v (tree);
  71124. v.setID (getName(), 0);
  71125. v.setText (text, 0);
  71126. v.setFont (font, 0);
  71127. v.setJustification (justification, 0);
  71128. v.setColour (colour, 0);
  71129. v.setBoundingBox (bounds, 0);
  71130. v.setFontSizeControlPoint (fontSizeControlPoint, 0);
  71131. return tree;
  71132. }
  71133. END_JUCE_NAMESPACE
  71134. /*** End of inlined file: juce_DrawableText.cpp ***/
  71135. /*** Start of inlined file: juce_SVGParser.cpp ***/
  71136. BEGIN_JUCE_NAMESPACE
  71137. class SVGState
  71138. {
  71139. public:
  71140. SVGState (const XmlElement* const topLevel)
  71141. : topLevelXml (topLevel),
  71142. elementX (0), elementY (0),
  71143. width (512), height (512),
  71144. viewBoxW (0), viewBoxH (0)
  71145. {
  71146. }
  71147. ~SVGState()
  71148. {
  71149. }
  71150. Drawable* parseSVGElement (const XmlElement& xml)
  71151. {
  71152. if (! xml.hasTagName ("svg"))
  71153. return 0;
  71154. DrawableComposite* const drawable = new DrawableComposite();
  71155. drawable->setName (xml.getStringAttribute ("id"));
  71156. SVGState newState (*this);
  71157. if (xml.hasAttribute ("transform"))
  71158. newState.addTransform (xml);
  71159. newState.elementX = getCoordLength (xml.getStringAttribute ("x", String (newState.elementX)), viewBoxW);
  71160. newState.elementY = getCoordLength (xml.getStringAttribute ("y", String (newState.elementY)), viewBoxH);
  71161. newState.width = getCoordLength (xml.getStringAttribute ("width", String (newState.width)), viewBoxW);
  71162. newState.height = getCoordLength (xml.getStringAttribute ("height", String (newState.height)), viewBoxH);
  71163. if (xml.hasAttribute ("viewBox"))
  71164. {
  71165. const String viewParams (xml.getStringAttribute ("viewBox"));
  71166. int i = 0;
  71167. float vx, vy, vw, vh;
  71168. if (parseCoords (viewParams, vx, vy, i, true)
  71169. && parseCoords (viewParams, vw, vh, i, true)
  71170. && vw > 0
  71171. && vh > 0)
  71172. {
  71173. newState.viewBoxW = vw;
  71174. newState.viewBoxH = vh;
  71175. int placementFlags = 0;
  71176. const String aspect (xml.getStringAttribute ("preserveAspectRatio"));
  71177. if (aspect.containsIgnoreCase ("none"))
  71178. {
  71179. placementFlags = RectanglePlacement::stretchToFit;
  71180. }
  71181. else
  71182. {
  71183. if (aspect.containsIgnoreCase ("slice"))
  71184. placementFlags |= RectanglePlacement::fillDestination;
  71185. if (aspect.containsIgnoreCase ("xMin"))
  71186. placementFlags |= RectanglePlacement::xLeft;
  71187. else if (aspect.containsIgnoreCase ("xMax"))
  71188. placementFlags |= RectanglePlacement::xRight;
  71189. else
  71190. placementFlags |= RectanglePlacement::xMid;
  71191. if (aspect.containsIgnoreCase ("yMin"))
  71192. placementFlags |= RectanglePlacement::yTop;
  71193. else if (aspect.containsIgnoreCase ("yMax"))
  71194. placementFlags |= RectanglePlacement::yBottom;
  71195. else
  71196. placementFlags |= RectanglePlacement::yMid;
  71197. }
  71198. const RectanglePlacement placement (placementFlags);
  71199. newState.transform
  71200. = placement.getTransformToFit (Rectangle<float> (vx, vy, vw, vh),
  71201. Rectangle<float> (0.0f, 0.0f, newState.width, newState.height))
  71202. .followedBy (newState.transform);
  71203. }
  71204. }
  71205. else
  71206. {
  71207. if (viewBoxW == 0)
  71208. newState.viewBoxW = newState.width;
  71209. if (viewBoxH == 0)
  71210. newState.viewBoxH = newState.height;
  71211. }
  71212. newState.parseSubElements (xml, drawable);
  71213. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  71214. return drawable;
  71215. }
  71216. private:
  71217. const XmlElement* const topLevelXml;
  71218. float elementX, elementY, width, height, viewBoxW, viewBoxH;
  71219. AffineTransform transform;
  71220. String cssStyleText;
  71221. void parseSubElements (const XmlElement& xml, DrawableComposite* const parentDrawable)
  71222. {
  71223. forEachXmlChildElement (xml, e)
  71224. {
  71225. Drawable* d = 0;
  71226. if (e->hasTagName ("g")) d = parseGroupElement (*e);
  71227. else if (e->hasTagName ("svg")) d = parseSVGElement (*e);
  71228. else if (e->hasTagName ("path")) d = parsePath (*e);
  71229. else if (e->hasTagName ("rect")) d = parseRect (*e);
  71230. else if (e->hasTagName ("circle")) d = parseCircle (*e);
  71231. else if (e->hasTagName ("ellipse")) d = parseEllipse (*e);
  71232. else if (e->hasTagName ("line")) d = parseLine (*e);
  71233. else if (e->hasTagName ("polyline")) d = parsePolygon (*e, true);
  71234. else if (e->hasTagName ("polygon")) d = parsePolygon (*e, false);
  71235. else if (e->hasTagName ("text")) d = parseText (*e);
  71236. else if (e->hasTagName ("switch")) d = parseSwitch (*e);
  71237. else if (e->hasTagName ("style")) parseCSSStyle (*e);
  71238. parentDrawable->insertDrawable (d);
  71239. }
  71240. }
  71241. DrawableComposite* parseSwitch (const XmlElement& xml)
  71242. {
  71243. const XmlElement* const group = xml.getChildByName ("g");
  71244. if (group != 0)
  71245. return parseGroupElement (*group);
  71246. return 0;
  71247. }
  71248. DrawableComposite* parseGroupElement (const XmlElement& xml)
  71249. {
  71250. DrawableComposite* const drawable = new DrawableComposite();
  71251. drawable->setName (xml.getStringAttribute ("id"));
  71252. if (xml.hasAttribute ("transform"))
  71253. {
  71254. SVGState newState (*this);
  71255. newState.addTransform (xml);
  71256. newState.parseSubElements (xml, drawable);
  71257. }
  71258. else
  71259. {
  71260. parseSubElements (xml, drawable);
  71261. }
  71262. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  71263. return drawable;
  71264. }
  71265. Drawable* parsePath (const XmlElement& xml) const
  71266. {
  71267. const String d (xml.getStringAttribute ("d").trimStart());
  71268. Path path;
  71269. if (getStyleAttribute (&xml, "fill-rule").trim().equalsIgnoreCase ("evenodd"))
  71270. path.setUsingNonZeroWinding (false);
  71271. int index = 0;
  71272. float lastX = 0, lastY = 0;
  71273. float lastX2 = 0, lastY2 = 0;
  71274. juce_wchar lastCommandChar = 0;
  71275. bool isRelative = true;
  71276. bool carryOn = true;
  71277. const String validCommandChars ("MmLlHhVvCcSsQqTtAaZz");
  71278. while (d[index] != 0)
  71279. {
  71280. float x, y, x2, y2, x3, y3;
  71281. if (validCommandChars.containsChar (d[index]))
  71282. {
  71283. lastCommandChar = d [index++];
  71284. isRelative = (lastCommandChar >= 'a' && lastCommandChar <= 'z');
  71285. }
  71286. switch (lastCommandChar)
  71287. {
  71288. case 'M':
  71289. case 'm':
  71290. case 'L':
  71291. case 'l':
  71292. if (parseCoords (d, x, y, index, false))
  71293. {
  71294. if (isRelative)
  71295. {
  71296. x += lastX;
  71297. y += lastY;
  71298. }
  71299. if (lastCommandChar == 'M' || lastCommandChar == 'm')
  71300. {
  71301. path.startNewSubPath (x, y);
  71302. lastCommandChar = 'l';
  71303. }
  71304. else
  71305. path.lineTo (x, y);
  71306. lastX2 = lastX;
  71307. lastY2 = lastY;
  71308. lastX = x;
  71309. lastY = y;
  71310. }
  71311. else
  71312. {
  71313. ++index;
  71314. }
  71315. break;
  71316. case 'H':
  71317. case 'h':
  71318. if (parseCoord (d, x, index, false, true))
  71319. {
  71320. if (isRelative)
  71321. x += lastX;
  71322. path.lineTo (x, lastY);
  71323. lastX2 = lastX;
  71324. lastX = x;
  71325. }
  71326. else
  71327. {
  71328. ++index;
  71329. }
  71330. break;
  71331. case 'V':
  71332. case 'v':
  71333. if (parseCoord (d, y, index, false, false))
  71334. {
  71335. if (isRelative)
  71336. y += lastY;
  71337. path.lineTo (lastX, y);
  71338. lastY2 = lastY;
  71339. lastY = y;
  71340. }
  71341. else
  71342. {
  71343. ++index;
  71344. }
  71345. break;
  71346. case 'C':
  71347. case 'c':
  71348. if (parseCoords (d, x, y, index, false)
  71349. && parseCoords (d, x2, y2, index, false)
  71350. && parseCoords (d, x3, y3, index, false))
  71351. {
  71352. if (isRelative)
  71353. {
  71354. x += lastX;
  71355. y += lastY;
  71356. x2 += lastX;
  71357. y2 += lastY;
  71358. x3 += lastX;
  71359. y3 += lastY;
  71360. }
  71361. path.cubicTo (x, y, x2, y2, x3, y3);
  71362. lastX2 = x2;
  71363. lastY2 = y2;
  71364. lastX = x3;
  71365. lastY = y3;
  71366. }
  71367. else
  71368. {
  71369. ++index;
  71370. }
  71371. break;
  71372. case 'S':
  71373. case 's':
  71374. if (parseCoords (d, x, y, index, false)
  71375. && parseCoords (d, x3, y3, index, false))
  71376. {
  71377. if (isRelative)
  71378. {
  71379. x += lastX;
  71380. y += lastY;
  71381. x3 += lastX;
  71382. y3 += lastY;
  71383. }
  71384. x2 = lastX + (lastX - lastX2);
  71385. y2 = lastY + (lastY - lastY2);
  71386. path.cubicTo (x2, y2, x, y, x3, y3);
  71387. lastX2 = x;
  71388. lastY2 = y;
  71389. lastX = x3;
  71390. lastY = y3;
  71391. }
  71392. else
  71393. {
  71394. ++index;
  71395. }
  71396. break;
  71397. case 'Q':
  71398. case 'q':
  71399. if (parseCoords (d, x, y, index, false)
  71400. && parseCoords (d, x2, y2, index, false))
  71401. {
  71402. if (isRelative)
  71403. {
  71404. x += lastX;
  71405. y += lastY;
  71406. x2 += lastX;
  71407. y2 += lastY;
  71408. }
  71409. path.quadraticTo (x, y, x2, y2);
  71410. lastX2 = x;
  71411. lastY2 = y;
  71412. lastX = x2;
  71413. lastY = y2;
  71414. }
  71415. else
  71416. {
  71417. ++index;
  71418. }
  71419. break;
  71420. case 'T':
  71421. case 't':
  71422. if (parseCoords (d, x, y, index, false))
  71423. {
  71424. if (isRelative)
  71425. {
  71426. x += lastX;
  71427. y += lastY;
  71428. }
  71429. x2 = lastX + (lastX - lastX2);
  71430. y2 = lastY + (lastY - lastY2);
  71431. path.quadraticTo (x2, y2, x, y);
  71432. lastX2 = x2;
  71433. lastY2 = y2;
  71434. lastX = x;
  71435. lastY = y;
  71436. }
  71437. else
  71438. {
  71439. ++index;
  71440. }
  71441. break;
  71442. case 'A':
  71443. case 'a':
  71444. if (parseCoords (d, x, y, index, false))
  71445. {
  71446. String num;
  71447. if (parseNextNumber (d, num, index, false))
  71448. {
  71449. const float angle = num.getFloatValue() * (180.0f / float_Pi);
  71450. if (parseNextNumber (d, num, index, false))
  71451. {
  71452. const bool largeArc = num.getIntValue() != 0;
  71453. if (parseNextNumber (d, num, index, false))
  71454. {
  71455. const bool sweep = num.getIntValue() != 0;
  71456. if (parseCoords (d, x2, y2, index, false))
  71457. {
  71458. if (isRelative)
  71459. {
  71460. x2 += lastX;
  71461. y2 += lastY;
  71462. }
  71463. if (lastX != x2 || lastY != y2)
  71464. {
  71465. double centreX, centreY, startAngle, deltaAngle;
  71466. double rx = x, ry = y;
  71467. endpointToCentreParameters (lastX, lastY, x2, y2,
  71468. angle, largeArc, sweep,
  71469. rx, ry, centreX, centreY,
  71470. startAngle, deltaAngle);
  71471. path.addCentredArc ((float) centreX, (float) centreY,
  71472. (float) rx, (float) ry,
  71473. angle, (float) startAngle, (float) (startAngle + deltaAngle),
  71474. false);
  71475. path.lineTo (x2, y2);
  71476. }
  71477. lastX2 = lastX;
  71478. lastY2 = lastY;
  71479. lastX = x2;
  71480. lastY = y2;
  71481. }
  71482. }
  71483. }
  71484. }
  71485. }
  71486. else
  71487. {
  71488. ++index;
  71489. }
  71490. break;
  71491. case 'Z':
  71492. case 'z':
  71493. path.closeSubPath();
  71494. while (CharacterFunctions::isWhitespace (d [index]))
  71495. ++index;
  71496. break;
  71497. default:
  71498. carryOn = false;
  71499. break;
  71500. }
  71501. if (! carryOn)
  71502. break;
  71503. }
  71504. return parseShape (xml, path);
  71505. }
  71506. Drawable* parseRect (const XmlElement& xml) const
  71507. {
  71508. Path rect;
  71509. const bool hasRX = xml.hasAttribute ("rx");
  71510. const bool hasRY = xml.hasAttribute ("ry");
  71511. if (hasRX || hasRY)
  71512. {
  71513. float rx = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  71514. float ry = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  71515. if (! hasRX)
  71516. rx = ry;
  71517. else if (! hasRY)
  71518. ry = rx;
  71519. rect.addRoundedRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  71520. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  71521. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  71522. getCoordLength (xml.getStringAttribute ("height"), viewBoxH),
  71523. rx, ry);
  71524. }
  71525. else
  71526. {
  71527. rect.addRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  71528. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  71529. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  71530. getCoordLength (xml.getStringAttribute ("height"), viewBoxH));
  71531. }
  71532. return parseShape (xml, rect);
  71533. }
  71534. Drawable* parseCircle (const XmlElement& xml) const
  71535. {
  71536. Path circle;
  71537. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  71538. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  71539. const float radius = getCoordLength (xml.getStringAttribute ("r"), viewBoxW);
  71540. circle.addEllipse (cx - radius, cy - radius, radius * 2.0f, radius * 2.0f);
  71541. return parseShape (xml, circle);
  71542. }
  71543. Drawable* parseEllipse (const XmlElement& xml) const
  71544. {
  71545. Path ellipse;
  71546. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  71547. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  71548. const float radiusX = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  71549. const float radiusY = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  71550. ellipse.addEllipse (cx - radiusX, cy - radiusY, radiusX * 2.0f, radiusY * 2.0f);
  71551. return parseShape (xml, ellipse);
  71552. }
  71553. Drawable* parseLine (const XmlElement& xml) const
  71554. {
  71555. Path line;
  71556. const float x1 = getCoordLength (xml.getStringAttribute ("x1"), viewBoxW);
  71557. const float y1 = getCoordLength (xml.getStringAttribute ("y1"), viewBoxH);
  71558. const float x2 = getCoordLength (xml.getStringAttribute ("x2"), viewBoxW);
  71559. const float y2 = getCoordLength (xml.getStringAttribute ("y2"), viewBoxH);
  71560. line.startNewSubPath (x1, y1);
  71561. line.lineTo (x2, y2);
  71562. return parseShape (xml, line);
  71563. }
  71564. Drawable* parsePolygon (const XmlElement& xml, const bool isPolyline) const
  71565. {
  71566. const String points (xml.getStringAttribute ("points"));
  71567. Path path;
  71568. int index = 0;
  71569. float x, y;
  71570. if (parseCoords (points, x, y, index, true))
  71571. {
  71572. float firstX = x;
  71573. float firstY = y;
  71574. float lastX = 0, lastY = 0;
  71575. path.startNewSubPath (x, y);
  71576. while (parseCoords (points, x, y, index, true))
  71577. {
  71578. lastX = x;
  71579. lastY = y;
  71580. path.lineTo (x, y);
  71581. }
  71582. if ((! isPolyline) || (firstX == lastX && firstY == lastY))
  71583. path.closeSubPath();
  71584. }
  71585. return parseShape (xml, path);
  71586. }
  71587. Drawable* parseShape (const XmlElement& xml, Path& path,
  71588. const bool shouldParseTransform = true) const
  71589. {
  71590. if (shouldParseTransform && xml.hasAttribute ("transform"))
  71591. {
  71592. SVGState newState (*this);
  71593. newState.addTransform (xml);
  71594. return newState.parseShape (xml, path, false);
  71595. }
  71596. DrawablePath* dp = new DrawablePath();
  71597. dp->setName (xml.getStringAttribute ("id"));
  71598. dp->setFill (Colours::transparentBlack);
  71599. path.applyTransform (transform);
  71600. dp->setPath (path);
  71601. Path::Iterator iter (path);
  71602. bool containsClosedSubPath = false;
  71603. while (iter.next())
  71604. {
  71605. if (iter.elementType == Path::Iterator::closePath)
  71606. {
  71607. containsClosedSubPath = true;
  71608. break;
  71609. }
  71610. }
  71611. dp->setFill (getPathFillType (path,
  71612. getStyleAttribute (&xml, "fill"),
  71613. getStyleAttribute (&xml, "fill-opacity"),
  71614. getStyleAttribute (&xml, "opacity"),
  71615. containsClosedSubPath ? Colours::black
  71616. : Colours::transparentBlack));
  71617. const String strokeType (getStyleAttribute (&xml, "stroke"));
  71618. if (strokeType.isNotEmpty() && ! strokeType.equalsIgnoreCase ("none"))
  71619. {
  71620. dp->setStrokeFill (getPathFillType (path, strokeType,
  71621. getStyleAttribute (&xml, "stroke-opacity"),
  71622. getStyleAttribute (&xml, "opacity"),
  71623. Colours::transparentBlack));
  71624. dp->setStrokeType (getStrokeFor (&xml));
  71625. }
  71626. return dp;
  71627. }
  71628. const XmlElement* findLinkedElement (const XmlElement* e) const
  71629. {
  71630. const String id (e->getStringAttribute ("xlink:href"));
  71631. if (! id.startsWithChar ('#'))
  71632. return 0;
  71633. return findElementForId (topLevelXml, id.substring (1));
  71634. }
  71635. void addGradientStopsIn (ColourGradient& cg, const XmlElement* const fillXml) const
  71636. {
  71637. if (fillXml == 0)
  71638. return;
  71639. forEachXmlChildElementWithTagName (*fillXml, e, "stop")
  71640. {
  71641. int index = 0;
  71642. Colour col (parseColour (getStyleAttribute (e, "stop-color"), index, Colours::black));
  71643. const String opacity (getStyleAttribute (e, "stop-opacity", "1"));
  71644. col = col.withMultipliedAlpha (jlimit (0.0f, 1.0f, opacity.getFloatValue()));
  71645. double offset = e->getDoubleAttribute ("offset");
  71646. if (e->getStringAttribute ("offset").containsChar ('%'))
  71647. offset *= 0.01;
  71648. cg.addColour (jlimit (0.0, 1.0, offset), col);
  71649. }
  71650. }
  71651. const FillType getPathFillType (const Path& path,
  71652. const String& fill,
  71653. const String& fillOpacity,
  71654. const String& overallOpacity,
  71655. const Colour& defaultColour) const
  71656. {
  71657. float opacity = 1.0f;
  71658. if (overallOpacity.isNotEmpty())
  71659. opacity = jlimit (0.0f, 1.0f, overallOpacity.getFloatValue());
  71660. if (fillOpacity.isNotEmpty())
  71661. opacity *= (jlimit (0.0f, 1.0f, fillOpacity.getFloatValue()));
  71662. if (fill.startsWithIgnoreCase ("url"))
  71663. {
  71664. const String id (fill.fromFirstOccurrenceOf ("#", false, false)
  71665. .upToLastOccurrenceOf (")", false, false).trim());
  71666. const XmlElement* const fillXml = findElementForId (topLevelXml, id);
  71667. if (fillXml != 0
  71668. && (fillXml->hasTagName ("linearGradient")
  71669. || fillXml->hasTagName ("radialGradient")))
  71670. {
  71671. const XmlElement* inheritedFrom = findLinkedElement (fillXml);
  71672. ColourGradient gradient;
  71673. addGradientStopsIn (gradient, inheritedFrom);
  71674. addGradientStopsIn (gradient, fillXml);
  71675. if (gradient.getNumColours() > 0)
  71676. {
  71677. gradient.addColour (0.0, gradient.getColour (0));
  71678. gradient.addColour (1.0, gradient.getColour (gradient.getNumColours() - 1));
  71679. }
  71680. else
  71681. {
  71682. gradient.addColour (0.0, Colours::black);
  71683. gradient.addColour (1.0, Colours::black);
  71684. }
  71685. if (overallOpacity.isNotEmpty())
  71686. gradient.multiplyOpacity (overallOpacity.getFloatValue());
  71687. jassert (gradient.getNumColours() > 0);
  71688. gradient.isRadial = fillXml->hasTagName ("radialGradient");
  71689. float gradientWidth = viewBoxW;
  71690. float gradientHeight = viewBoxH;
  71691. float dx = 0.0f;
  71692. float dy = 0.0f;
  71693. const bool userSpace = fillXml->getStringAttribute ("gradientUnits").equalsIgnoreCase ("userSpaceOnUse");
  71694. if (! userSpace)
  71695. {
  71696. const Rectangle<float> bounds (path.getBounds());
  71697. dx = bounds.getX();
  71698. dy = bounds.getY();
  71699. gradientWidth = bounds.getWidth();
  71700. gradientHeight = bounds.getHeight();
  71701. }
  71702. if (gradient.isRadial)
  71703. {
  71704. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("cx", "50%"), gradientWidth),
  71705. dy + getCoordLength (fillXml->getStringAttribute ("cy", "50%"), gradientHeight));
  71706. const float radius = getCoordLength (fillXml->getStringAttribute ("r", "50%"), gradientWidth);
  71707. gradient.point2 = gradient.point1 + Point<float> (radius, 0.0f);
  71708. //xxx (the fx, fy focal point isn't handled properly here..)
  71709. }
  71710. else
  71711. {
  71712. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x1", "0%"), gradientWidth),
  71713. dy + getCoordLength (fillXml->getStringAttribute ("y1", "0%"), gradientHeight));
  71714. gradient.point2.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x2", "100%"), gradientWidth),
  71715. dy + getCoordLength (fillXml->getStringAttribute ("y2", "0%"), gradientHeight));
  71716. if (gradient.point1 == gradient.point2)
  71717. return Colour (gradient.getColour (gradient.getNumColours() - 1));
  71718. }
  71719. FillType type (gradient);
  71720. type.transform = parseTransform (fillXml->getStringAttribute ("gradientTransform"))
  71721. .followedBy (transform);
  71722. return type;
  71723. }
  71724. }
  71725. if (fill.equalsIgnoreCase ("none"))
  71726. return Colours::transparentBlack;
  71727. int i = 0;
  71728. const Colour colour (parseColour (fill, i, defaultColour));
  71729. return colour.withMultipliedAlpha (opacity);
  71730. }
  71731. const PathStrokeType getStrokeFor (const XmlElement* const xml) const
  71732. {
  71733. const String strokeWidth (getStyleAttribute (xml, "stroke-width"));
  71734. const String cap (getStyleAttribute (xml, "stroke-linecap"));
  71735. const String join (getStyleAttribute (xml, "stroke-linejoin"));
  71736. //const String mitreLimit (getStyleAttribute (xml, "stroke-miterlimit"));
  71737. //const String dashArray (getStyleAttribute (xml, "stroke-dasharray"));
  71738. //const String dashOffset (getStyleAttribute (xml, "stroke-dashoffset"));
  71739. PathStrokeType::JointStyle joinStyle = PathStrokeType::mitered;
  71740. PathStrokeType::EndCapStyle capStyle = PathStrokeType::butt;
  71741. if (join.equalsIgnoreCase ("round"))
  71742. joinStyle = PathStrokeType::curved;
  71743. else if (join.equalsIgnoreCase ("bevel"))
  71744. joinStyle = PathStrokeType::beveled;
  71745. if (cap.equalsIgnoreCase ("round"))
  71746. capStyle = PathStrokeType::rounded;
  71747. else if (cap.equalsIgnoreCase ("square"))
  71748. capStyle = PathStrokeType::square;
  71749. float ox = 0.0f, oy = 0.0f;
  71750. float x = getCoordLength (strokeWidth, viewBoxW), y = 0.0f;
  71751. transform.transformPoints (ox, oy, x, y);
  71752. return PathStrokeType (strokeWidth.isNotEmpty() ? juce_hypotf (x - ox, y - oy) : 1.0f,
  71753. joinStyle, capStyle);
  71754. }
  71755. Drawable* parseText (const XmlElement& xml)
  71756. {
  71757. Array <float> xCoords, yCoords, dxCoords, dyCoords;
  71758. getCoordList (xCoords, getInheritedAttribute (&xml, "x"), true, true);
  71759. getCoordList (yCoords, getInheritedAttribute (&xml, "y"), true, false);
  71760. getCoordList (dxCoords, getInheritedAttribute (&xml, "dx"), true, true);
  71761. getCoordList (dyCoords, getInheritedAttribute (&xml, "dy"), true, false);
  71762. //xxx not done text yet!
  71763. forEachXmlChildElement (xml, e)
  71764. {
  71765. if (e->isTextElement())
  71766. {
  71767. const String text (e->getText());
  71768. Path path;
  71769. Drawable* s = parseShape (*e, path);
  71770. delete s; // xxx not finished!
  71771. }
  71772. else if (e->hasTagName ("tspan"))
  71773. {
  71774. Drawable* s = parseText (*e);
  71775. delete s; // xxx not finished!
  71776. }
  71777. }
  71778. return 0;
  71779. }
  71780. void addTransform (const XmlElement& xml)
  71781. {
  71782. transform = parseTransform (xml.getStringAttribute ("transform"))
  71783. .followedBy (transform);
  71784. }
  71785. bool parseCoord (const String& s, float& value, int& index,
  71786. const bool allowUnits, const bool isX) const
  71787. {
  71788. String number;
  71789. if (! parseNextNumber (s, number, index, allowUnits))
  71790. {
  71791. value = 0;
  71792. return false;
  71793. }
  71794. value = getCoordLength (number, isX ? viewBoxW : viewBoxH);
  71795. return true;
  71796. }
  71797. bool parseCoords (const String& s, float& x, float& y,
  71798. int& index, const bool allowUnits) const
  71799. {
  71800. return parseCoord (s, x, index, allowUnits, true)
  71801. && parseCoord (s, y, index, allowUnits, false);
  71802. }
  71803. float getCoordLength (const String& s, const float sizeForProportions) const
  71804. {
  71805. float n = s.getFloatValue();
  71806. const int len = s.length();
  71807. if (len > 2)
  71808. {
  71809. const float dpi = 96.0f;
  71810. const juce_wchar n1 = s [len - 2];
  71811. const juce_wchar n2 = s [len - 1];
  71812. if (n1 == 'i' && n2 == 'n')
  71813. n *= dpi;
  71814. else if (n1 == 'm' && n2 == 'm')
  71815. n *= dpi / 25.4f;
  71816. else if (n1 == 'c' && n2 == 'm')
  71817. n *= dpi / 2.54f;
  71818. else if (n1 == 'p' && n2 == 'c')
  71819. n *= 15.0f;
  71820. else if (n2 == '%')
  71821. n *= 0.01f * sizeForProportions;
  71822. }
  71823. return n;
  71824. }
  71825. void getCoordList (Array <float>& coords, const String& list,
  71826. const bool allowUnits, const bool isX) const
  71827. {
  71828. int index = 0;
  71829. float value;
  71830. while (parseCoord (list, value, index, allowUnits, isX))
  71831. coords.add (value);
  71832. }
  71833. void parseCSSStyle (const XmlElement& xml)
  71834. {
  71835. cssStyleText = xml.getAllSubText() + "\n" + cssStyleText;
  71836. }
  71837. const String getStyleAttribute (const XmlElement* xml, const String& attributeName,
  71838. const String& defaultValue = String::empty) const
  71839. {
  71840. if (xml->hasAttribute (attributeName))
  71841. return xml->getStringAttribute (attributeName, defaultValue);
  71842. const String styleAtt (xml->getStringAttribute ("style"));
  71843. if (styleAtt.isNotEmpty())
  71844. {
  71845. const String value (getAttributeFromStyleList (styleAtt, attributeName, String::empty));
  71846. if (value.isNotEmpty())
  71847. return value;
  71848. }
  71849. else if (xml->hasAttribute ("class"))
  71850. {
  71851. const String className ("." + xml->getStringAttribute ("class"));
  71852. int index = cssStyleText.indexOfIgnoreCase (className + " ");
  71853. if (index < 0)
  71854. index = cssStyleText.indexOfIgnoreCase (className + "{");
  71855. if (index >= 0)
  71856. {
  71857. const int openBracket = cssStyleText.indexOfChar (index, '{');
  71858. if (openBracket > index)
  71859. {
  71860. const int closeBracket = cssStyleText.indexOfChar (openBracket, '}');
  71861. if (closeBracket > openBracket)
  71862. {
  71863. const String value (getAttributeFromStyleList (cssStyleText.substring (openBracket + 1, closeBracket), attributeName, defaultValue));
  71864. if (value.isNotEmpty())
  71865. return value;
  71866. }
  71867. }
  71868. }
  71869. }
  71870. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  71871. if (xml != 0)
  71872. return getStyleAttribute (xml, attributeName, defaultValue);
  71873. return defaultValue;
  71874. }
  71875. const String getInheritedAttribute (const XmlElement* xml, const String& attributeName) const
  71876. {
  71877. if (xml->hasAttribute (attributeName))
  71878. return xml->getStringAttribute (attributeName);
  71879. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  71880. if (xml != 0)
  71881. return getInheritedAttribute (xml, attributeName);
  71882. return String::empty;
  71883. }
  71884. static bool isIdentifierChar (const juce_wchar c)
  71885. {
  71886. return CharacterFunctions::isLetter (c) || c == '-';
  71887. }
  71888. static const String getAttributeFromStyleList (const String& list, const String& attributeName, const String& defaultValue)
  71889. {
  71890. int i = 0;
  71891. for (;;)
  71892. {
  71893. i = list.indexOf (i, attributeName);
  71894. if (i < 0)
  71895. break;
  71896. if ((i == 0 || (i > 0 && ! isIdentifierChar (list [i - 1])))
  71897. && ! isIdentifierChar (list [i + attributeName.length()]))
  71898. {
  71899. i = list.indexOfChar (i, ':');
  71900. if (i < 0)
  71901. break;
  71902. int end = list.indexOfChar (i, ';');
  71903. if (end < 0)
  71904. end = 0x7ffff;
  71905. return list.substring (i + 1, end).trim();
  71906. }
  71907. ++i;
  71908. }
  71909. return defaultValue;
  71910. }
  71911. static bool parseNextNumber (const String& source, String& value, int& index, const bool allowUnits)
  71912. {
  71913. const juce_wchar* const s = source;
  71914. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == ',')
  71915. ++index;
  71916. int start = index;
  71917. if (CharacterFunctions::isDigit (s[index]) || s[index] == '.' || s[index] == '-')
  71918. ++index;
  71919. while (CharacterFunctions::isDigit (s[index]) || s[index] == '.')
  71920. ++index;
  71921. if ((s[index] == 'e' || s[index] == 'E')
  71922. && (CharacterFunctions::isDigit (s[index + 1])
  71923. || s[index + 1] == '-'
  71924. || s[index + 1] == '+'))
  71925. {
  71926. index += 2;
  71927. while (CharacterFunctions::isDigit (s[index]))
  71928. ++index;
  71929. }
  71930. if (allowUnits)
  71931. {
  71932. while (CharacterFunctions::isLetter (s[index]))
  71933. ++index;
  71934. }
  71935. if (index == start)
  71936. return false;
  71937. value = String (s + start, index - start);
  71938. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == ',')
  71939. ++index;
  71940. return true;
  71941. }
  71942. static const Colour parseColour (const String& s, int& index, const Colour& defaultColour)
  71943. {
  71944. if (s [index] == '#')
  71945. {
  71946. uint32 hex [6];
  71947. zeromem (hex, sizeof (hex));
  71948. int numChars = 0;
  71949. for (int i = 6; --i >= 0;)
  71950. {
  71951. const int hexValue = CharacterFunctions::getHexDigitValue (s [++index]);
  71952. if (hexValue >= 0)
  71953. hex [numChars++] = hexValue;
  71954. else
  71955. break;
  71956. }
  71957. if (numChars <= 3)
  71958. return Colour ((uint8) (hex [0] * 0x11),
  71959. (uint8) (hex [1] * 0x11),
  71960. (uint8) (hex [2] * 0x11));
  71961. else
  71962. return Colour ((uint8) ((hex [0] << 4) + hex [1]),
  71963. (uint8) ((hex [2] << 4) + hex [3]),
  71964. (uint8) ((hex [4] << 4) + hex [5]));
  71965. }
  71966. else if (s [index] == 'r'
  71967. && s [index + 1] == 'g'
  71968. && s [index + 2] == 'b')
  71969. {
  71970. const int openBracket = s.indexOfChar (index, '(');
  71971. const int closeBracket = s.indexOfChar (openBracket, ')');
  71972. if (openBracket >= 3 && closeBracket > openBracket)
  71973. {
  71974. index = closeBracket;
  71975. StringArray tokens;
  71976. tokens.addTokens (s.substring (openBracket + 1, closeBracket), ",", "");
  71977. tokens.trim();
  71978. tokens.removeEmptyStrings();
  71979. if (tokens[0].containsChar ('%'))
  71980. return Colour ((uint8) roundToInt (2.55 * tokens[0].getDoubleValue()),
  71981. (uint8) roundToInt (2.55 * tokens[1].getDoubleValue()),
  71982. (uint8) roundToInt (2.55 * tokens[2].getDoubleValue()));
  71983. else
  71984. return Colour ((uint8) tokens[0].getIntValue(),
  71985. (uint8) tokens[1].getIntValue(),
  71986. (uint8) tokens[2].getIntValue());
  71987. }
  71988. }
  71989. return Colours::findColourForName (s, defaultColour);
  71990. }
  71991. static const AffineTransform parseTransform (String t)
  71992. {
  71993. AffineTransform result;
  71994. while (t.isNotEmpty())
  71995. {
  71996. StringArray tokens;
  71997. tokens.addTokens (t.fromFirstOccurrenceOf ("(", false, false)
  71998. .upToFirstOccurrenceOf (")", false, false),
  71999. ", ", String::empty);
  72000. tokens.removeEmptyStrings (true);
  72001. float numbers [6];
  72002. for (int i = 0; i < 6; ++i)
  72003. numbers[i] = tokens[i].getFloatValue();
  72004. AffineTransform trans;
  72005. if (t.startsWithIgnoreCase ("matrix"))
  72006. {
  72007. trans = AffineTransform (numbers[0], numbers[2], numbers[4],
  72008. numbers[1], numbers[3], numbers[5]);
  72009. }
  72010. else if (t.startsWithIgnoreCase ("translate"))
  72011. {
  72012. jassert (tokens.size() == 2);
  72013. trans = AffineTransform::translation (numbers[0], numbers[1]);
  72014. }
  72015. else if (t.startsWithIgnoreCase ("scale"))
  72016. {
  72017. if (tokens.size() == 1)
  72018. trans = AffineTransform::scale (numbers[0], numbers[0]);
  72019. else
  72020. trans = AffineTransform::scale (numbers[0], numbers[1]);
  72021. }
  72022. else if (t.startsWithIgnoreCase ("rotate"))
  72023. {
  72024. if (tokens.size() != 3)
  72025. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi));
  72026. else
  72027. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi),
  72028. numbers[1], numbers[2]);
  72029. }
  72030. else if (t.startsWithIgnoreCase ("skewX"))
  72031. {
  72032. trans = AffineTransform (1.0f, std::tan (numbers[0] * (float_Pi / 180.0f)), 0.0f,
  72033. 0.0f, 1.0f, 0.0f);
  72034. }
  72035. else if (t.startsWithIgnoreCase ("skewY"))
  72036. {
  72037. trans = AffineTransform (1.0f, 0.0f, 0.0f,
  72038. std::tan (numbers[0] * (float_Pi / 180.0f)), 1.0f, 0.0f);
  72039. }
  72040. result = trans.followedBy (result);
  72041. t = t.fromFirstOccurrenceOf (")", false, false).trimStart();
  72042. }
  72043. return result;
  72044. }
  72045. static void endpointToCentreParameters (const double x1, const double y1,
  72046. const double x2, const double y2,
  72047. const double angle,
  72048. const bool largeArc, const bool sweep,
  72049. double& rx, double& ry,
  72050. double& centreX, double& centreY,
  72051. double& startAngle, double& deltaAngle)
  72052. {
  72053. const double midX = (x1 - x2) * 0.5;
  72054. const double midY = (y1 - y2) * 0.5;
  72055. const double cosAngle = cos (angle);
  72056. const double sinAngle = sin (angle);
  72057. const double xp = cosAngle * midX + sinAngle * midY;
  72058. const double yp = cosAngle * midY - sinAngle * midX;
  72059. const double xp2 = xp * xp;
  72060. const double yp2 = yp * yp;
  72061. double rx2 = rx * rx;
  72062. double ry2 = ry * ry;
  72063. const double s = (xp2 / rx2) + (yp2 / ry2);
  72064. double c;
  72065. if (s <= 1.0)
  72066. {
  72067. c = std::sqrt (jmax (0.0, ((rx2 * ry2) - (rx2 * yp2) - (ry2 * xp2))
  72068. / (( rx2 * yp2) + (ry2 * xp2))));
  72069. if (largeArc == sweep)
  72070. c = -c;
  72071. }
  72072. else
  72073. {
  72074. const double s2 = std::sqrt (s);
  72075. rx *= s2;
  72076. ry *= s2;
  72077. rx2 = rx * rx;
  72078. ry2 = ry * ry;
  72079. c = 0;
  72080. }
  72081. const double cpx = ((rx * yp) / ry) * c;
  72082. const double cpy = ((-ry * xp) / rx) * c;
  72083. centreX = ((x1 + x2) * 0.5) + (cosAngle * cpx) - (sinAngle * cpy);
  72084. centreY = ((y1 + y2) * 0.5) + (sinAngle * cpx) + (cosAngle * cpy);
  72085. const double ux = (xp - cpx) / rx;
  72086. const double uy = (yp - cpy) / ry;
  72087. const double vx = (-xp - cpx) / rx;
  72088. const double vy = (-yp - cpy) / ry;
  72089. const double length = juce_hypot (ux, uy);
  72090. startAngle = acos (jlimit (-1.0, 1.0, ux / length));
  72091. if (uy < 0)
  72092. startAngle = -startAngle;
  72093. startAngle += double_Pi * 0.5;
  72094. deltaAngle = acos (jlimit (-1.0, 1.0, ((ux * vx) + (uy * vy))
  72095. / (length * juce_hypot (vx, vy))));
  72096. if ((ux * vy) - (uy * vx) < 0)
  72097. deltaAngle = -deltaAngle;
  72098. if (sweep)
  72099. {
  72100. if (deltaAngle < 0)
  72101. deltaAngle += double_Pi * 2.0;
  72102. }
  72103. else
  72104. {
  72105. if (deltaAngle > 0)
  72106. deltaAngle -= double_Pi * 2.0;
  72107. }
  72108. deltaAngle = fmod (deltaAngle, double_Pi * 2.0);
  72109. }
  72110. static const XmlElement* findElementForId (const XmlElement* const parent, const String& id)
  72111. {
  72112. forEachXmlChildElement (*parent, e)
  72113. {
  72114. if (e->compareAttribute ("id", id))
  72115. return e;
  72116. const XmlElement* const found = findElementForId (e, id);
  72117. if (found != 0)
  72118. return found;
  72119. }
  72120. return 0;
  72121. }
  72122. SVGState& operator= (const SVGState&);
  72123. };
  72124. Drawable* Drawable::createFromSVG (const XmlElement& svgDocument)
  72125. {
  72126. SVGState state (&svgDocument);
  72127. return state.parseSVGElement (svgDocument);
  72128. }
  72129. END_JUCE_NAMESPACE
  72130. /*** End of inlined file: juce_SVGParser.cpp ***/
  72131. /*** Start of inlined file: juce_DropShadowEffect.cpp ***/
  72132. BEGIN_JUCE_NAMESPACE
  72133. #if JUCE_MSVC && JUCE_DEBUG
  72134. #pragma optimize ("t", on)
  72135. #endif
  72136. DropShadowEffect::DropShadowEffect()
  72137. : offsetX (0),
  72138. offsetY (0),
  72139. radius (4),
  72140. opacity (0.6f)
  72141. {
  72142. }
  72143. DropShadowEffect::~DropShadowEffect()
  72144. {
  72145. }
  72146. void DropShadowEffect::setShadowProperties (const float newRadius,
  72147. const float newOpacity,
  72148. const int newShadowOffsetX,
  72149. const int newShadowOffsetY)
  72150. {
  72151. radius = jmax (1.1f, newRadius);
  72152. offsetX = newShadowOffsetX;
  72153. offsetY = newShadowOffsetY;
  72154. opacity = newOpacity;
  72155. }
  72156. void DropShadowEffect::applyEffect (Image& image, Graphics& g)
  72157. {
  72158. const int w = image.getWidth();
  72159. const int h = image.getHeight();
  72160. Image shadowImage (Image::SingleChannel, w, h, false);
  72161. const Image::BitmapData srcData (image, false);
  72162. const Image::BitmapData destData (shadowImage, true);
  72163. const int filter = roundToInt (63.0f / radius);
  72164. const int radiusMinus1 = roundToInt ((radius - 1.0f) * 63.0f);
  72165. for (int x = w; --x >= 0;)
  72166. {
  72167. int shadowAlpha = 0;
  72168. const PixelARGB* src = ((const PixelARGB*) srcData.data) + x;
  72169. uint8* shadowPix = destData.data + x;
  72170. for (int y = h; --y >= 0;)
  72171. {
  72172. shadowAlpha = ((shadowAlpha * radiusMinus1 + (src->getAlpha() << 6)) * filter) >> 12;
  72173. *shadowPix = (uint8) shadowAlpha;
  72174. src = (const PixelARGB*) (((const uint8*) src) + srcData.lineStride);
  72175. shadowPix += destData.lineStride;
  72176. }
  72177. }
  72178. for (int y = h; --y >= 0;)
  72179. {
  72180. int shadowAlpha = 0;
  72181. uint8* shadowPix = destData.getLinePointer (y);
  72182. for (int x = w; --x >= 0;)
  72183. {
  72184. shadowAlpha = ((shadowAlpha * radiusMinus1 + (*shadowPix << 6)) * filter) >> 12;
  72185. *shadowPix++ = (uint8) shadowAlpha;
  72186. }
  72187. }
  72188. g.setColour (Colours::black.withAlpha (opacity));
  72189. g.drawImageAt (shadowImage, offsetX, offsetY, true);
  72190. g.setOpacity (1.0f);
  72191. g.drawImageAt (image, 0, 0);
  72192. }
  72193. #if JUCE_MSVC && JUCE_DEBUG
  72194. #pragma optimize ("", on) // resets optimisations to the project defaults
  72195. #endif
  72196. END_JUCE_NAMESPACE
  72197. /*** End of inlined file: juce_DropShadowEffect.cpp ***/
  72198. /*** Start of inlined file: juce_GlowEffect.cpp ***/
  72199. BEGIN_JUCE_NAMESPACE
  72200. GlowEffect::GlowEffect()
  72201. : radius (2.0f),
  72202. colour (Colours::white)
  72203. {
  72204. }
  72205. GlowEffect::~GlowEffect()
  72206. {
  72207. }
  72208. void GlowEffect::setGlowProperties (const float newRadius,
  72209. const Colour& newColour)
  72210. {
  72211. radius = newRadius;
  72212. colour = newColour;
  72213. }
  72214. void GlowEffect::applyEffect (Image& image, Graphics& g)
  72215. {
  72216. Image temp (image.getFormat(), image.getWidth(), image.getHeight(), true);
  72217. ImageConvolutionKernel blurKernel (roundToInt (radius * 2.0f));
  72218. blurKernel.createGaussianBlur (radius);
  72219. blurKernel.rescaleAllValues (radius);
  72220. blurKernel.applyToImage (temp, image, image.getBounds());
  72221. g.setColour (colour);
  72222. g.drawImageAt (temp, 0, 0, true);
  72223. g.setOpacity (1.0f);
  72224. g.drawImageAt (image, 0, 0, false);
  72225. }
  72226. END_JUCE_NAMESPACE
  72227. /*** End of inlined file: juce_GlowEffect.cpp ***/
  72228. /*** Start of inlined file: juce_ReduceOpacityEffect.cpp ***/
  72229. BEGIN_JUCE_NAMESPACE
  72230. ReduceOpacityEffect::ReduceOpacityEffect (const float opacity_)
  72231. : opacity (opacity_)
  72232. {
  72233. }
  72234. ReduceOpacityEffect::~ReduceOpacityEffect()
  72235. {
  72236. }
  72237. void ReduceOpacityEffect::setOpacity (const float newOpacity)
  72238. {
  72239. opacity = jlimit (0.0f, 1.0f, newOpacity);
  72240. }
  72241. void ReduceOpacityEffect::applyEffect (Image& image, Graphics& g)
  72242. {
  72243. g.setOpacity (opacity);
  72244. g.drawImageAt (image, 0, 0);
  72245. }
  72246. END_JUCE_NAMESPACE
  72247. /*** End of inlined file: juce_ReduceOpacityEffect.cpp ***/
  72248. /*** Start of inlined file: juce_Font.cpp ***/
  72249. BEGIN_JUCE_NAMESPACE
  72250. namespace FontValues
  72251. {
  72252. static float limitFontHeight (const float height) throw()
  72253. {
  72254. return jlimit (0.1f, 10000.0f, height);
  72255. }
  72256. static const float defaultFontHeight = 14.0f;
  72257. static String fallbackFont;
  72258. }
  72259. Font::SharedFontInternal::SharedFontInternal (const String& typefaceName_, const float height_, const float horizontalScale_,
  72260. const float kerning_, const float ascent_, const int styleFlags_,
  72261. Typeface* const typeface_) throw()
  72262. : typefaceName (typefaceName_),
  72263. height (height_),
  72264. horizontalScale (horizontalScale_),
  72265. kerning (kerning_),
  72266. ascent (ascent_),
  72267. styleFlags (styleFlags_),
  72268. typeface (typeface_)
  72269. {
  72270. }
  72271. Font::SharedFontInternal::SharedFontInternal (const SharedFontInternal& other) throw()
  72272. : typefaceName (other.typefaceName),
  72273. height (other.height),
  72274. horizontalScale (other.horizontalScale),
  72275. kerning (other.kerning),
  72276. ascent (other.ascent),
  72277. styleFlags (other.styleFlags),
  72278. typeface (other.typeface)
  72279. {
  72280. }
  72281. Font::Font()
  72282. : font (new SharedFontInternal (getDefaultSansSerifFontName(), FontValues::defaultFontHeight,
  72283. 1.0f, 0, 0, Font::plain, 0))
  72284. {
  72285. }
  72286. Font::Font (const float fontHeight, const int styleFlags_)
  72287. : font (new SharedFontInternal (getDefaultSansSerifFontName(), FontValues::limitFontHeight (fontHeight),
  72288. 1.0f, 0, 0, styleFlags_, 0))
  72289. {
  72290. }
  72291. Font::Font (const String& typefaceName_,
  72292. const float fontHeight,
  72293. const int styleFlags_)
  72294. : font (new SharedFontInternal (typefaceName_, FontValues::limitFontHeight (fontHeight),
  72295. 1.0f, 0, 0, styleFlags_, 0))
  72296. {
  72297. }
  72298. Font::Font (const Font& other) throw()
  72299. : font (other.font)
  72300. {
  72301. }
  72302. Font& Font::operator= (const Font& other) throw()
  72303. {
  72304. font = other.font;
  72305. return *this;
  72306. }
  72307. Font::~Font() throw()
  72308. {
  72309. }
  72310. Font::Font (const Typeface::Ptr& typeface)
  72311. : font (new SharedFontInternal (typeface->getName(), FontValues::defaultFontHeight,
  72312. 1.0f, 0, 0, Font::plain, typeface))
  72313. {
  72314. }
  72315. bool Font::operator== (const Font& other) const throw()
  72316. {
  72317. return font == other.font
  72318. || (font->height == other.font->height
  72319. && font->styleFlags == other.font->styleFlags
  72320. && font->horizontalScale == other.font->horizontalScale
  72321. && font->kerning == other.font->kerning
  72322. && font->typefaceName == other.font->typefaceName);
  72323. }
  72324. bool Font::operator!= (const Font& other) const throw()
  72325. {
  72326. return ! operator== (other);
  72327. }
  72328. void Font::dupeInternalIfShared()
  72329. {
  72330. if (font->getReferenceCount() > 1)
  72331. font = new SharedFontInternal (*font);
  72332. }
  72333. const String Font::getDefaultSansSerifFontName()
  72334. {
  72335. static const String name ("<Sans-Serif>");
  72336. return name;
  72337. }
  72338. const String Font::getDefaultSerifFontName()
  72339. {
  72340. static const String name ("<Serif>");
  72341. return name;
  72342. }
  72343. const String Font::getDefaultMonospacedFontName()
  72344. {
  72345. static const String name ("<Monospaced>");
  72346. return name;
  72347. }
  72348. void Font::setTypefaceName (const String& faceName)
  72349. {
  72350. if (faceName != font->typefaceName)
  72351. {
  72352. dupeInternalIfShared();
  72353. font->typefaceName = faceName;
  72354. font->typeface = 0;
  72355. font->ascent = 0;
  72356. }
  72357. }
  72358. const String Font::getFallbackFontName()
  72359. {
  72360. return FontValues::fallbackFont;
  72361. }
  72362. void Font::setFallbackFontName (const String& name)
  72363. {
  72364. FontValues::fallbackFont = name;
  72365. }
  72366. void Font::setHeight (float newHeight)
  72367. {
  72368. newHeight = FontValues::limitFontHeight (newHeight);
  72369. if (font->height != newHeight)
  72370. {
  72371. dupeInternalIfShared();
  72372. font->height = newHeight;
  72373. }
  72374. }
  72375. void Font::setHeightWithoutChangingWidth (float newHeight)
  72376. {
  72377. newHeight = FontValues::limitFontHeight (newHeight);
  72378. if (font->height != newHeight)
  72379. {
  72380. dupeInternalIfShared();
  72381. font->horizontalScale *= (font->height / newHeight);
  72382. font->height = newHeight;
  72383. }
  72384. }
  72385. void Font::setStyleFlags (const int newFlags)
  72386. {
  72387. if (font->styleFlags != newFlags)
  72388. {
  72389. dupeInternalIfShared();
  72390. font->styleFlags = newFlags;
  72391. font->typeface = 0;
  72392. font->ascent = 0;
  72393. }
  72394. }
  72395. void Font::setSizeAndStyle (float newHeight,
  72396. const int newStyleFlags,
  72397. const float newHorizontalScale,
  72398. const float newKerningAmount)
  72399. {
  72400. newHeight = FontValues::limitFontHeight (newHeight);
  72401. if (font->height != newHeight
  72402. || font->horizontalScale != newHorizontalScale
  72403. || font->kerning != newKerningAmount)
  72404. {
  72405. dupeInternalIfShared();
  72406. font->height = newHeight;
  72407. font->horizontalScale = newHorizontalScale;
  72408. font->kerning = newKerningAmount;
  72409. }
  72410. setStyleFlags (newStyleFlags);
  72411. }
  72412. void Font::setHorizontalScale (const float scaleFactor)
  72413. {
  72414. dupeInternalIfShared();
  72415. font->horizontalScale = scaleFactor;
  72416. }
  72417. void Font::setExtraKerningFactor (const float extraKerning)
  72418. {
  72419. dupeInternalIfShared();
  72420. font->kerning = extraKerning;
  72421. }
  72422. void Font::setBold (const bool shouldBeBold)
  72423. {
  72424. setStyleFlags (shouldBeBold ? (font->styleFlags | bold)
  72425. : (font->styleFlags & ~bold));
  72426. }
  72427. const Font Font::boldened() const
  72428. {
  72429. Font f (*this);
  72430. f.setBold (true);
  72431. return f;
  72432. }
  72433. bool Font::isBold() const throw()
  72434. {
  72435. return (font->styleFlags & bold) != 0;
  72436. }
  72437. void Font::setItalic (const bool shouldBeItalic)
  72438. {
  72439. setStyleFlags (shouldBeItalic ? (font->styleFlags | italic)
  72440. : (font->styleFlags & ~italic));
  72441. }
  72442. const Font Font::italicised() const
  72443. {
  72444. Font f (*this);
  72445. f.setItalic (true);
  72446. return f;
  72447. }
  72448. bool Font::isItalic() const throw()
  72449. {
  72450. return (font->styleFlags & italic) != 0;
  72451. }
  72452. void Font::setUnderline (const bool shouldBeUnderlined)
  72453. {
  72454. setStyleFlags (shouldBeUnderlined ? (font->styleFlags | underlined)
  72455. : (font->styleFlags & ~underlined));
  72456. }
  72457. bool Font::isUnderlined() const throw()
  72458. {
  72459. return (font->styleFlags & underlined) != 0;
  72460. }
  72461. float Font::getAscent() const
  72462. {
  72463. if (font->ascent == 0)
  72464. font->ascent = getTypeface()->getAscent();
  72465. return font->height * font->ascent;
  72466. }
  72467. float Font::getDescent() const
  72468. {
  72469. return font->height - getAscent();
  72470. }
  72471. int Font::getStringWidth (const String& text) const
  72472. {
  72473. return roundToInt (getStringWidthFloat (text));
  72474. }
  72475. float Font::getStringWidthFloat (const String& text) const
  72476. {
  72477. float w = getTypeface()->getStringWidth (text);
  72478. if (font->kerning != 0)
  72479. w += font->kerning * text.length();
  72480. return w * font->height * font->horizontalScale;
  72481. }
  72482. void Font::getGlyphPositions (const String& text, Array <int>& glyphs, Array <float>& xOffsets) const
  72483. {
  72484. getTypeface()->getGlyphPositions (text, glyphs, xOffsets);
  72485. const float scale = font->height * font->horizontalScale;
  72486. const int num = xOffsets.size();
  72487. if (num > 0)
  72488. {
  72489. float* const x = &(xOffsets.getReference(0));
  72490. if (font->kerning != 0)
  72491. {
  72492. for (int i = 0; i < num; ++i)
  72493. x[i] = (x[i] + i * font->kerning) * scale;
  72494. }
  72495. else
  72496. {
  72497. for (int i = 0; i < num; ++i)
  72498. x[i] *= scale;
  72499. }
  72500. }
  72501. }
  72502. void Font::findFonts (Array<Font>& destArray)
  72503. {
  72504. const StringArray names (findAllTypefaceNames());
  72505. for (int i = 0; i < names.size(); ++i)
  72506. destArray.add (Font (names[i], FontValues::defaultFontHeight, Font::plain));
  72507. }
  72508. const String Font::toString() const
  72509. {
  72510. String s (getTypefaceName());
  72511. if (s == getDefaultSansSerifFontName())
  72512. s = String::empty;
  72513. else
  72514. s += "; ";
  72515. s += String (getHeight(), 1);
  72516. if (isBold())
  72517. s += " bold";
  72518. if (isItalic())
  72519. s += " italic";
  72520. return s;
  72521. }
  72522. const Font Font::fromString (const String& fontDescription)
  72523. {
  72524. String name;
  72525. const int separator = fontDescription.indexOfChar (';');
  72526. if (separator > 0)
  72527. name = fontDescription.substring (0, separator).trim();
  72528. if (name.isEmpty())
  72529. name = getDefaultSansSerifFontName();
  72530. String sizeAndStyle (fontDescription.substring (separator + 1));
  72531. float height = sizeAndStyle.getFloatValue();
  72532. if (height <= 0)
  72533. height = 10.0f;
  72534. int flags = Font::plain;
  72535. if (sizeAndStyle.containsIgnoreCase ("bold"))
  72536. flags |= Font::bold;
  72537. if (sizeAndStyle.containsIgnoreCase ("italic"))
  72538. flags |= Font::italic;
  72539. return Font (name, height, flags);
  72540. }
  72541. class TypefaceCache : public DeletedAtShutdown
  72542. {
  72543. public:
  72544. TypefaceCache (int numToCache = 10)
  72545. : counter (1)
  72546. {
  72547. while (--numToCache >= 0)
  72548. faces.add (new CachedFace());
  72549. }
  72550. ~TypefaceCache()
  72551. {
  72552. clearSingletonInstance();
  72553. }
  72554. juce_DeclareSingleton_SingleThreaded_Minimal (TypefaceCache)
  72555. const Typeface::Ptr findTypefaceFor (const Font& font)
  72556. {
  72557. const int flags = font.getStyleFlags() & (Font::bold | Font::italic);
  72558. const String faceName (font.getTypefaceName());
  72559. int i;
  72560. for (i = faces.size(); --i >= 0;)
  72561. {
  72562. CachedFace* const face = faces.getUnchecked(i);
  72563. if (face->flags == flags
  72564. && face->typefaceName == faceName)
  72565. {
  72566. face->lastUsageCount = ++counter;
  72567. return face->typeFace;
  72568. }
  72569. }
  72570. int replaceIndex = 0;
  72571. int bestLastUsageCount = std::numeric_limits<int>::max();
  72572. for (i = faces.size(); --i >= 0;)
  72573. {
  72574. const int lu = faces.getUnchecked(i)->lastUsageCount;
  72575. if (bestLastUsageCount > lu)
  72576. {
  72577. bestLastUsageCount = lu;
  72578. replaceIndex = i;
  72579. }
  72580. }
  72581. CachedFace* const face = faces.getUnchecked (replaceIndex);
  72582. face->typefaceName = faceName;
  72583. face->flags = flags;
  72584. face->lastUsageCount = ++counter;
  72585. face->typeFace = LookAndFeel::getDefaultLookAndFeel().getTypefaceForFont (font);
  72586. jassert (face->typeFace != 0); // the look and feel must return a typeface!
  72587. return face->typeFace;
  72588. }
  72589. juce_UseDebuggingNewOperator
  72590. private:
  72591. struct CachedFace
  72592. {
  72593. CachedFace() throw()
  72594. : lastUsageCount (0), flags (-1)
  72595. {
  72596. }
  72597. String typefaceName;
  72598. int lastUsageCount;
  72599. int flags;
  72600. Typeface::Ptr typeFace;
  72601. };
  72602. int counter;
  72603. OwnedArray <CachedFace> faces;
  72604. TypefaceCache (const TypefaceCache&);
  72605. TypefaceCache& operator= (const TypefaceCache&);
  72606. };
  72607. juce_ImplementSingleton_SingleThreaded (TypefaceCache)
  72608. Typeface* Font::getTypeface() const
  72609. {
  72610. if (font->typeface == 0)
  72611. font->typeface = TypefaceCache::getInstance()->findTypefaceFor (*this);
  72612. return font->typeface;
  72613. }
  72614. END_JUCE_NAMESPACE
  72615. /*** End of inlined file: juce_Font.cpp ***/
  72616. /*** Start of inlined file: juce_GlyphArrangement.cpp ***/
  72617. BEGIN_JUCE_NAMESPACE
  72618. PositionedGlyph::PositionedGlyph (const float x_, const float y_, const float w_, const Font& font_,
  72619. const juce_wchar character_, const int glyph_)
  72620. : x (x_),
  72621. y (y_),
  72622. w (w_),
  72623. font (font_),
  72624. character (character_),
  72625. glyph (glyph_)
  72626. {
  72627. }
  72628. PositionedGlyph::PositionedGlyph (const PositionedGlyph& other)
  72629. : x (other.x),
  72630. y (other.y),
  72631. w (other.w),
  72632. font (other.font),
  72633. character (other.character),
  72634. glyph (other.glyph)
  72635. {
  72636. }
  72637. void PositionedGlyph::draw (const Graphics& g) const
  72638. {
  72639. if (! isWhitespace())
  72640. {
  72641. g.getInternalContext()->setFont (font);
  72642. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y));
  72643. }
  72644. }
  72645. void PositionedGlyph::draw (const Graphics& g,
  72646. const AffineTransform& transform) const
  72647. {
  72648. if (! isWhitespace())
  72649. {
  72650. g.getInternalContext()->setFont (font);
  72651. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y)
  72652. .followedBy (transform));
  72653. }
  72654. }
  72655. void PositionedGlyph::createPath (Path& path) const
  72656. {
  72657. if (! isWhitespace())
  72658. {
  72659. Typeface* const t = font.getTypeface();
  72660. if (t != 0)
  72661. {
  72662. Path p;
  72663. t->getOutlineForGlyph (glyph, p);
  72664. path.addPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight())
  72665. .translated (x, y));
  72666. }
  72667. }
  72668. }
  72669. bool PositionedGlyph::hitTest (float px, float py) const
  72670. {
  72671. if (getBounds().contains (px, py) && ! isWhitespace())
  72672. {
  72673. Typeface* const t = font.getTypeface();
  72674. if (t != 0)
  72675. {
  72676. Path p;
  72677. t->getOutlineForGlyph (glyph, p);
  72678. AffineTransform::translation (-x, -y)
  72679. .scaled (1.0f / (font.getHeight() * font.getHorizontalScale()), 1.0f / font.getHeight())
  72680. .transformPoint (px, py);
  72681. return p.contains (px, py);
  72682. }
  72683. }
  72684. return false;
  72685. }
  72686. void PositionedGlyph::moveBy (const float deltaX,
  72687. const float deltaY)
  72688. {
  72689. x += deltaX;
  72690. y += deltaY;
  72691. }
  72692. GlyphArrangement::GlyphArrangement()
  72693. {
  72694. glyphs.ensureStorageAllocated (128);
  72695. }
  72696. GlyphArrangement::GlyphArrangement (const GlyphArrangement& other)
  72697. {
  72698. addGlyphArrangement (other);
  72699. }
  72700. GlyphArrangement& GlyphArrangement::operator= (const GlyphArrangement& other)
  72701. {
  72702. if (this != &other)
  72703. {
  72704. clear();
  72705. addGlyphArrangement (other);
  72706. }
  72707. return *this;
  72708. }
  72709. GlyphArrangement::~GlyphArrangement()
  72710. {
  72711. }
  72712. void GlyphArrangement::clear()
  72713. {
  72714. glyphs.clear();
  72715. }
  72716. PositionedGlyph& GlyphArrangement::getGlyph (const int index) const
  72717. {
  72718. jassert (((unsigned int) index) < (unsigned int) glyphs.size());
  72719. return *glyphs [index];
  72720. }
  72721. void GlyphArrangement::addGlyphArrangement (const GlyphArrangement& other)
  72722. {
  72723. glyphs.ensureStorageAllocated (glyphs.size() + other.glyphs.size());
  72724. glyphs.addCopiesOf (other.glyphs);
  72725. }
  72726. void GlyphArrangement::removeRangeOfGlyphs (int startIndex, const int num)
  72727. {
  72728. glyphs.removeRange (startIndex, num < 0 ? glyphs.size() : num);
  72729. }
  72730. void GlyphArrangement::addLineOfText (const Font& font,
  72731. const String& text,
  72732. const float xOffset,
  72733. const float yOffset)
  72734. {
  72735. addCurtailedLineOfText (font, text,
  72736. xOffset, yOffset,
  72737. 1.0e10f, false);
  72738. }
  72739. void GlyphArrangement::addCurtailedLineOfText (const Font& font,
  72740. const String& text,
  72741. float xOffset,
  72742. const float yOffset,
  72743. const float maxWidthPixels,
  72744. const bool useEllipsis)
  72745. {
  72746. if (text.isNotEmpty())
  72747. {
  72748. Array <int> newGlyphs;
  72749. Array <float> xOffsets;
  72750. font.getGlyphPositions (text, newGlyphs, xOffsets);
  72751. const int textLen = newGlyphs.size();
  72752. const juce_wchar* const unicodeText = text;
  72753. for (int i = 0; i < textLen; ++i)
  72754. {
  72755. const float thisX = xOffsets.getUnchecked (i);
  72756. const float nextX = xOffsets.getUnchecked (i + 1);
  72757. if (nextX > maxWidthPixels + 1.0f)
  72758. {
  72759. // curtail the string if it's too wide..
  72760. if (useEllipsis && textLen > 3 && glyphs.size() >= 3)
  72761. insertEllipsis (font, xOffset + maxWidthPixels, 0, glyphs.size());
  72762. break;
  72763. }
  72764. else
  72765. {
  72766. glyphs.add (new PositionedGlyph (xOffset + thisX, yOffset, nextX - thisX,
  72767. font, unicodeText[i], newGlyphs.getUnchecked(i)));
  72768. }
  72769. }
  72770. }
  72771. }
  72772. int GlyphArrangement::insertEllipsis (const Font& font, const float maxXPos,
  72773. const int startIndex, int endIndex)
  72774. {
  72775. int numDeleted = 0;
  72776. if (glyphs.size() > 0)
  72777. {
  72778. Array<int> dotGlyphs;
  72779. Array<float> dotXs;
  72780. font.getGlyphPositions ("..", dotGlyphs, dotXs);
  72781. const float dx = dotXs[1];
  72782. float xOffset = 0.0f, yOffset = 0.0f;
  72783. while (endIndex > startIndex)
  72784. {
  72785. const PositionedGlyph* pg = glyphs.getUnchecked (--endIndex);
  72786. xOffset = pg->x;
  72787. yOffset = pg->y;
  72788. glyphs.remove (endIndex);
  72789. ++numDeleted;
  72790. if (xOffset + dx * 3 <= maxXPos)
  72791. break;
  72792. }
  72793. for (int i = 3; --i >= 0;)
  72794. {
  72795. glyphs.insert (endIndex++, new PositionedGlyph (xOffset, yOffset, dx,
  72796. font, '.', dotGlyphs.getFirst()));
  72797. --numDeleted;
  72798. xOffset += dx;
  72799. if (xOffset > maxXPos)
  72800. break;
  72801. }
  72802. }
  72803. return numDeleted;
  72804. }
  72805. void GlyphArrangement::addJustifiedText (const Font& font,
  72806. const String& text,
  72807. float x, float y,
  72808. const float maxLineWidth,
  72809. const Justification& horizontalLayout)
  72810. {
  72811. int lineStartIndex = glyphs.size();
  72812. addLineOfText (font, text, x, y);
  72813. const float originalY = y;
  72814. while (lineStartIndex < glyphs.size())
  72815. {
  72816. int i = lineStartIndex;
  72817. if (glyphs.getUnchecked(i)->getCharacter() != '\n'
  72818. && glyphs.getUnchecked(i)->getCharacter() != '\r')
  72819. ++i;
  72820. const float lineMaxX = glyphs.getUnchecked (lineStartIndex)->getLeft() + maxLineWidth;
  72821. int lastWordBreakIndex = -1;
  72822. while (i < glyphs.size())
  72823. {
  72824. const PositionedGlyph* pg = glyphs.getUnchecked (i);
  72825. const juce_wchar c = pg->getCharacter();
  72826. if (c == '\r' || c == '\n')
  72827. {
  72828. ++i;
  72829. if (c == '\r' && i < glyphs.size()
  72830. && glyphs.getUnchecked(i)->getCharacter() == '\n')
  72831. ++i;
  72832. break;
  72833. }
  72834. else if (pg->isWhitespace())
  72835. {
  72836. lastWordBreakIndex = i + 1;
  72837. }
  72838. else if (pg->getRight() - 0.0001f >= lineMaxX)
  72839. {
  72840. if (lastWordBreakIndex >= 0)
  72841. i = lastWordBreakIndex;
  72842. break;
  72843. }
  72844. ++i;
  72845. }
  72846. const float currentLineStartX = glyphs.getUnchecked (lineStartIndex)->getLeft();
  72847. float currentLineEndX = currentLineStartX;
  72848. for (int j = i; --j >= lineStartIndex;)
  72849. {
  72850. if (! glyphs.getUnchecked (j)->isWhitespace())
  72851. {
  72852. currentLineEndX = glyphs.getUnchecked (j)->getRight();
  72853. break;
  72854. }
  72855. }
  72856. float deltaX = 0.0f;
  72857. if (horizontalLayout.testFlags (Justification::horizontallyJustified))
  72858. spreadOutLine (lineStartIndex, i - lineStartIndex, maxLineWidth);
  72859. else if (horizontalLayout.testFlags (Justification::horizontallyCentred))
  72860. deltaX = (maxLineWidth - (currentLineEndX - currentLineStartX)) * 0.5f;
  72861. else if (horizontalLayout.testFlags (Justification::right))
  72862. deltaX = maxLineWidth - (currentLineEndX - currentLineStartX);
  72863. moveRangeOfGlyphs (lineStartIndex, i - lineStartIndex,
  72864. x + deltaX - currentLineStartX, y - originalY);
  72865. lineStartIndex = i;
  72866. y += font.getHeight();
  72867. }
  72868. }
  72869. void GlyphArrangement::addFittedText (const Font& f,
  72870. const String& text,
  72871. const float x, const float y,
  72872. const float width, const float height,
  72873. const Justification& layout,
  72874. int maximumLines,
  72875. const float minimumHorizontalScale)
  72876. {
  72877. // doesn't make much sense if this is outside a sensible range of 0.5 to 1.0
  72878. jassert (minimumHorizontalScale > 0 && minimumHorizontalScale <= 1.0f);
  72879. if (text.containsAnyOf ("\r\n"))
  72880. {
  72881. GlyphArrangement ga;
  72882. ga.addJustifiedText (f, text, x, y, width, layout);
  72883. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  72884. float dy = y - bb.getY();
  72885. if (layout.testFlags (Justification::verticallyCentred))
  72886. dy += (height - bb.getHeight()) * 0.5f;
  72887. else if (layout.testFlags (Justification::bottom))
  72888. dy += height - bb.getHeight();
  72889. ga.moveRangeOfGlyphs (0, -1, 0.0f, dy);
  72890. glyphs.ensureStorageAllocated (glyphs.size() + ga.glyphs.size());
  72891. for (int i = 0; i < ga.glyphs.size(); ++i)
  72892. glyphs.add (ga.glyphs.getUnchecked (i));
  72893. ga.glyphs.clear (false);
  72894. return;
  72895. }
  72896. int startIndex = glyphs.size();
  72897. addLineOfText (f, text.trim(), x, y);
  72898. if (glyphs.size() > startIndex)
  72899. {
  72900. float lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  72901. - glyphs.getUnchecked (startIndex)->getLeft();
  72902. if (lineWidth <= 0)
  72903. return;
  72904. if (lineWidth * minimumHorizontalScale < width)
  72905. {
  72906. if (lineWidth > width)
  72907. stretchRangeOfGlyphs (startIndex, glyphs.size() - startIndex,
  72908. width / lineWidth);
  72909. justifyGlyphs (startIndex, glyphs.size() - startIndex,
  72910. x, y, width, height, layout);
  72911. }
  72912. else if (maximumLines <= 1)
  72913. {
  72914. fitLineIntoSpace (startIndex, glyphs.size() - startIndex,
  72915. x, y, width, height, f, layout, minimumHorizontalScale);
  72916. }
  72917. else
  72918. {
  72919. Font font (f);
  72920. String txt (text.trim());
  72921. const int length = txt.length();
  72922. const int originalStartIndex = startIndex;
  72923. int numLines = 1;
  72924. if (length <= 12 && ! txt.containsAnyOf (" -\t\r\n"))
  72925. maximumLines = 1;
  72926. maximumLines = jmin (maximumLines, length);
  72927. while (numLines < maximumLines)
  72928. {
  72929. ++numLines;
  72930. const float newFontHeight = height / (float) numLines;
  72931. if (newFontHeight < font.getHeight())
  72932. {
  72933. font.setHeight (jmax (8.0f, newFontHeight));
  72934. removeRangeOfGlyphs (startIndex, -1);
  72935. addLineOfText (font, txt, x, y);
  72936. lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  72937. - glyphs.getUnchecked (startIndex)->getLeft();
  72938. }
  72939. if (numLines > lineWidth / width || newFontHeight < 8.0f)
  72940. break;
  72941. }
  72942. if (numLines < 1)
  72943. numLines = 1;
  72944. float lineY = y;
  72945. float widthPerLine = lineWidth / numLines;
  72946. int lastLineStartIndex = 0;
  72947. for (int line = 0; line < numLines; ++line)
  72948. {
  72949. int i = startIndex;
  72950. lastLineStartIndex = i;
  72951. float lineStartX = glyphs.getUnchecked (startIndex)->getLeft();
  72952. if (line == numLines - 1)
  72953. {
  72954. widthPerLine = width;
  72955. i = glyphs.size();
  72956. }
  72957. else
  72958. {
  72959. while (i < glyphs.size())
  72960. {
  72961. lineWidth = (glyphs.getUnchecked (i)->getRight() - lineStartX);
  72962. if (lineWidth > widthPerLine)
  72963. {
  72964. // got to a point where the line's too long, so skip forward to find a
  72965. // good place to break it..
  72966. const int searchStartIndex = i;
  72967. while (i < glyphs.size())
  72968. {
  72969. if ((glyphs.getUnchecked (i)->getRight() - lineStartX) * minimumHorizontalScale < width)
  72970. {
  72971. if (glyphs.getUnchecked (i)->isWhitespace()
  72972. || glyphs.getUnchecked (i)->getCharacter() == '-')
  72973. {
  72974. ++i;
  72975. break;
  72976. }
  72977. }
  72978. else
  72979. {
  72980. // can't find a suitable break, so try looking backwards..
  72981. i = searchStartIndex;
  72982. for (int back = 1; back < jmin (5, i - startIndex - 1); ++back)
  72983. {
  72984. if (glyphs.getUnchecked (i - back)->isWhitespace()
  72985. || glyphs.getUnchecked (i - back)->getCharacter() == '-')
  72986. {
  72987. i -= back - 1;
  72988. break;
  72989. }
  72990. }
  72991. break;
  72992. }
  72993. ++i;
  72994. }
  72995. break;
  72996. }
  72997. ++i;
  72998. }
  72999. int wsStart = i;
  73000. while (wsStart > 0 && glyphs.getUnchecked (wsStart - 1)->isWhitespace())
  73001. --wsStart;
  73002. int wsEnd = i;
  73003. while (wsEnd < glyphs.size() && glyphs.getUnchecked (wsEnd)->isWhitespace())
  73004. ++wsEnd;
  73005. removeRangeOfGlyphs (wsStart, wsEnd - wsStart);
  73006. i = jmax (wsStart, startIndex + 1);
  73007. }
  73008. i -= fitLineIntoSpace (startIndex, i - startIndex,
  73009. x, lineY, width, font.getHeight(), font,
  73010. layout.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  73011. minimumHorizontalScale);
  73012. startIndex = i;
  73013. lineY += font.getHeight();
  73014. if (startIndex >= glyphs.size())
  73015. break;
  73016. }
  73017. justifyGlyphs (originalStartIndex, glyphs.size() - originalStartIndex,
  73018. x, y, width, height, layout.getFlags() & ~Justification::horizontallyJustified);
  73019. }
  73020. }
  73021. }
  73022. void GlyphArrangement::moveRangeOfGlyphs (int startIndex, int num,
  73023. const float dx, const float dy)
  73024. {
  73025. jassert (startIndex >= 0);
  73026. if (dx != 0.0f || dy != 0.0f)
  73027. {
  73028. if (num < 0 || startIndex + num > glyphs.size())
  73029. num = glyphs.size() - startIndex;
  73030. while (--num >= 0)
  73031. glyphs.getUnchecked (startIndex++)->moveBy (dx, dy);
  73032. }
  73033. }
  73034. int GlyphArrangement::fitLineIntoSpace (int start, int numGlyphs, float x, float y, float w, float h, const Font& font,
  73035. const Justification& justification, float minimumHorizontalScale)
  73036. {
  73037. int numDeleted = 0;
  73038. const float lineStartX = glyphs.getUnchecked (start)->getLeft();
  73039. float lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX;
  73040. if (lineWidth > w)
  73041. {
  73042. if (minimumHorizontalScale < 1.0f)
  73043. {
  73044. stretchRangeOfGlyphs (start, numGlyphs, jmax (minimumHorizontalScale, w / lineWidth));
  73045. lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX - 0.5f;
  73046. }
  73047. if (lineWidth > w)
  73048. {
  73049. numDeleted = insertEllipsis (font, lineStartX + w, start, start + numGlyphs);
  73050. numGlyphs -= numDeleted;
  73051. }
  73052. }
  73053. justifyGlyphs (start, numGlyphs, x, y, w, h, justification);
  73054. return numDeleted;
  73055. }
  73056. void GlyphArrangement::stretchRangeOfGlyphs (int startIndex, int num,
  73057. const float horizontalScaleFactor)
  73058. {
  73059. jassert (startIndex >= 0);
  73060. if (num < 0 || startIndex + num > glyphs.size())
  73061. num = glyphs.size() - startIndex;
  73062. if (num > 0)
  73063. {
  73064. const float xAnchor = glyphs.getUnchecked (startIndex)->getLeft();
  73065. while (--num >= 0)
  73066. {
  73067. PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  73068. pg->x = xAnchor + (pg->x - xAnchor) * horizontalScaleFactor;
  73069. pg->font.setHorizontalScale (pg->font.getHorizontalScale() * horizontalScaleFactor);
  73070. pg->w *= horizontalScaleFactor;
  73071. }
  73072. }
  73073. }
  73074. const Rectangle<float> GlyphArrangement::getBoundingBox (int startIndex, int num, const bool includeWhitespace) const
  73075. {
  73076. jassert (startIndex >= 0);
  73077. if (num < 0 || startIndex + num > glyphs.size())
  73078. num = glyphs.size() - startIndex;
  73079. Rectangle<float> result;
  73080. while (--num >= 0)
  73081. {
  73082. const PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  73083. if (includeWhitespace || ! pg->isWhitespace())
  73084. result = result.getUnion (pg->getBounds());
  73085. }
  73086. return result;
  73087. }
  73088. void GlyphArrangement::justifyGlyphs (const int startIndex, const int num,
  73089. const float x, const float y, const float width, const float height,
  73090. const Justification& justification)
  73091. {
  73092. jassert (num >= 0 && startIndex >= 0);
  73093. if (glyphs.size() > 0 && num > 0)
  73094. {
  73095. const Rectangle<float> bb (getBoundingBox (startIndex, num, ! justification.testFlags (Justification::horizontallyJustified
  73096. | Justification::horizontallyCentred)));
  73097. float deltaX = 0.0f;
  73098. if (justification.testFlags (Justification::horizontallyJustified))
  73099. deltaX = x - bb.getX();
  73100. else if (justification.testFlags (Justification::horizontallyCentred))
  73101. deltaX = x + (width - bb.getWidth()) * 0.5f - bb.getX();
  73102. else if (justification.testFlags (Justification::right))
  73103. deltaX = (x + width) - bb.getRight();
  73104. else
  73105. deltaX = x - bb.getX();
  73106. float deltaY = 0.0f;
  73107. if (justification.testFlags (Justification::top))
  73108. deltaY = y - bb.getY();
  73109. else if (justification.testFlags (Justification::bottom))
  73110. deltaY = (y + height) - bb.getBottom();
  73111. else
  73112. deltaY = y + (height - bb.getHeight()) * 0.5f - bb.getY();
  73113. moveRangeOfGlyphs (startIndex, num, deltaX, deltaY);
  73114. if (justification.testFlags (Justification::horizontallyJustified))
  73115. {
  73116. int lineStart = 0;
  73117. float baseY = glyphs.getUnchecked (startIndex)->getBaselineY();
  73118. int i;
  73119. for (i = 0; i < num; ++i)
  73120. {
  73121. const float glyphY = glyphs.getUnchecked (startIndex + i)->getBaselineY();
  73122. if (glyphY != baseY)
  73123. {
  73124. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  73125. lineStart = i;
  73126. baseY = glyphY;
  73127. }
  73128. }
  73129. if (i > lineStart)
  73130. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  73131. }
  73132. }
  73133. }
  73134. void GlyphArrangement::spreadOutLine (const int start, const int num, const float targetWidth)
  73135. {
  73136. if (start + num < glyphs.size()
  73137. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\r'
  73138. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\n')
  73139. {
  73140. int numSpaces = 0;
  73141. int spacesAtEnd = 0;
  73142. for (int i = 0; i < num; ++i)
  73143. {
  73144. if (glyphs.getUnchecked (start + i)->isWhitespace())
  73145. {
  73146. ++spacesAtEnd;
  73147. ++numSpaces;
  73148. }
  73149. else
  73150. {
  73151. spacesAtEnd = 0;
  73152. }
  73153. }
  73154. numSpaces -= spacesAtEnd;
  73155. if (numSpaces > 0)
  73156. {
  73157. const float startX = glyphs.getUnchecked (start)->getLeft();
  73158. const float endX = glyphs.getUnchecked (start + num - 1 - spacesAtEnd)->getRight();
  73159. const float extraPaddingBetweenWords
  73160. = (targetWidth - (endX - startX)) / (float) numSpaces;
  73161. float deltaX = 0.0f;
  73162. for (int i = 0; i < num; ++i)
  73163. {
  73164. glyphs.getUnchecked (start + i)->moveBy (deltaX, 0.0f);
  73165. if (glyphs.getUnchecked (start + i)->isWhitespace())
  73166. deltaX += extraPaddingBetweenWords;
  73167. }
  73168. }
  73169. }
  73170. }
  73171. void GlyphArrangement::draw (const Graphics& g) const
  73172. {
  73173. for (int i = 0; i < glyphs.size(); ++i)
  73174. {
  73175. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  73176. if (pg->font.isUnderlined())
  73177. {
  73178. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  73179. float nextX = pg->x + pg->w;
  73180. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  73181. nextX = glyphs.getUnchecked (i + 1)->x;
  73182. g.fillRect (pg->x, pg->y + lineThickness * 2.0f,
  73183. nextX - pg->x, lineThickness);
  73184. }
  73185. pg->draw (g);
  73186. }
  73187. }
  73188. void GlyphArrangement::draw (const Graphics& g, const AffineTransform& transform) const
  73189. {
  73190. for (int i = 0; i < glyphs.size(); ++i)
  73191. {
  73192. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  73193. if (pg->font.isUnderlined())
  73194. {
  73195. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  73196. float nextX = pg->x + pg->w;
  73197. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  73198. nextX = glyphs.getUnchecked (i + 1)->x;
  73199. Path p;
  73200. p.addLineSegment (Line<float> (pg->x, pg->y + lineThickness * 2.0f,
  73201. nextX, pg->y + lineThickness * 2.0f),
  73202. lineThickness);
  73203. g.fillPath (p, transform);
  73204. }
  73205. pg->draw (g, transform);
  73206. }
  73207. }
  73208. void GlyphArrangement::createPath (Path& path) const
  73209. {
  73210. for (int i = 0; i < glyphs.size(); ++i)
  73211. glyphs.getUnchecked (i)->createPath (path);
  73212. }
  73213. int GlyphArrangement::findGlyphIndexAt (float x, float y) const
  73214. {
  73215. for (int i = 0; i < glyphs.size(); ++i)
  73216. if (glyphs.getUnchecked (i)->hitTest (x, y))
  73217. return i;
  73218. return -1;
  73219. }
  73220. END_JUCE_NAMESPACE
  73221. /*** End of inlined file: juce_GlyphArrangement.cpp ***/
  73222. /*** Start of inlined file: juce_TextLayout.cpp ***/
  73223. BEGIN_JUCE_NAMESPACE
  73224. class TextLayout::Token
  73225. {
  73226. public:
  73227. String text;
  73228. Font font;
  73229. int x, y, w, h;
  73230. int line, lineHeight;
  73231. bool isWhitespace, isNewLine;
  73232. Token (const String& t,
  73233. const Font& f,
  73234. const bool isWhitespace_)
  73235. : text (t),
  73236. font (f),
  73237. x(0),
  73238. y(0),
  73239. isWhitespace (isWhitespace_)
  73240. {
  73241. w = font.getStringWidth (t);
  73242. h = roundToInt (f.getHeight());
  73243. isNewLine = t.containsChar ('\n') || t.containsChar ('\r');
  73244. }
  73245. Token (const Token& other)
  73246. : text (other.text),
  73247. font (other.font),
  73248. x (other.x),
  73249. y (other.y),
  73250. w (other.w),
  73251. h (other.h),
  73252. line (other.line),
  73253. lineHeight (other.lineHeight),
  73254. isWhitespace (other.isWhitespace),
  73255. isNewLine (other.isNewLine)
  73256. {
  73257. }
  73258. ~Token()
  73259. {
  73260. }
  73261. void draw (Graphics& g,
  73262. const int xOffset,
  73263. const int yOffset)
  73264. {
  73265. if (! isWhitespace)
  73266. {
  73267. g.setFont (font);
  73268. g.drawSingleLineText (text.trimEnd(),
  73269. xOffset + x,
  73270. yOffset + y + (lineHeight - h)
  73271. + roundToInt (font.getAscent()));
  73272. }
  73273. }
  73274. juce_UseDebuggingNewOperator
  73275. };
  73276. TextLayout::TextLayout()
  73277. : totalLines (0)
  73278. {
  73279. tokens.ensureStorageAllocated (64);
  73280. }
  73281. TextLayout::TextLayout (const String& text, const Font& font)
  73282. : totalLines (0)
  73283. {
  73284. tokens.ensureStorageAllocated (64);
  73285. appendText (text, font);
  73286. }
  73287. TextLayout::TextLayout (const TextLayout& other)
  73288. : totalLines (0)
  73289. {
  73290. *this = other;
  73291. }
  73292. TextLayout& TextLayout::operator= (const TextLayout& other)
  73293. {
  73294. if (this != &other)
  73295. {
  73296. clear();
  73297. totalLines = other.totalLines;
  73298. tokens.addCopiesOf (other.tokens);
  73299. }
  73300. return *this;
  73301. }
  73302. TextLayout::~TextLayout()
  73303. {
  73304. clear();
  73305. }
  73306. void TextLayout::clear()
  73307. {
  73308. tokens.clear();
  73309. totalLines = 0;
  73310. }
  73311. bool TextLayout::isEmpty() const
  73312. {
  73313. return tokens.size() == 0;
  73314. }
  73315. void TextLayout::appendText (const String& text, const Font& font)
  73316. {
  73317. const juce_wchar* t = text;
  73318. String currentString;
  73319. int lastCharType = 0;
  73320. for (;;)
  73321. {
  73322. const juce_wchar c = *t++;
  73323. if (c == 0)
  73324. break;
  73325. int charType;
  73326. if (c == '\r' || c == '\n')
  73327. {
  73328. charType = 0;
  73329. }
  73330. else if (CharacterFunctions::isWhitespace (c))
  73331. {
  73332. charType = 2;
  73333. }
  73334. else
  73335. {
  73336. charType = 1;
  73337. }
  73338. if (charType == 0 || charType != lastCharType)
  73339. {
  73340. if (currentString.isNotEmpty())
  73341. {
  73342. tokens.add (new Token (currentString, font,
  73343. lastCharType == 2 || lastCharType == 0));
  73344. }
  73345. currentString = String::charToString (c);
  73346. if (c == '\r' && *t == '\n')
  73347. currentString += *t++;
  73348. }
  73349. else
  73350. {
  73351. currentString += c;
  73352. }
  73353. lastCharType = charType;
  73354. }
  73355. if (currentString.isNotEmpty())
  73356. tokens.add (new Token (currentString, font, lastCharType == 2));
  73357. }
  73358. void TextLayout::setText (const String& text, const Font& font)
  73359. {
  73360. clear();
  73361. appendText (text, font);
  73362. }
  73363. void TextLayout::layout (int maxWidth,
  73364. const Justification& justification,
  73365. const bool attemptToBalanceLineLengths)
  73366. {
  73367. if (attemptToBalanceLineLengths)
  73368. {
  73369. const int originalW = maxWidth;
  73370. int bestWidth = maxWidth;
  73371. float bestLineProportion = 0.0f;
  73372. while (maxWidth > originalW / 2)
  73373. {
  73374. layout (maxWidth, justification, false);
  73375. if (getNumLines() <= 1)
  73376. return;
  73377. const int lastLineW = getLineWidth (getNumLines() - 1);
  73378. const int lastButOneLineW = getLineWidth (getNumLines() - 2);
  73379. const float prop = lastLineW / (float) lastButOneLineW;
  73380. if (prop > 0.9f)
  73381. return;
  73382. if (prop > bestLineProportion)
  73383. {
  73384. bestLineProportion = prop;
  73385. bestWidth = maxWidth;
  73386. }
  73387. maxWidth -= 10;
  73388. }
  73389. layout (bestWidth, justification, false);
  73390. }
  73391. else
  73392. {
  73393. int x = 0;
  73394. int y = 0;
  73395. int h = 0;
  73396. totalLines = 0;
  73397. int i;
  73398. for (i = 0; i < tokens.size(); ++i)
  73399. {
  73400. Token* const t = tokens.getUnchecked(i);
  73401. t->x = x;
  73402. t->y = y;
  73403. t->line = totalLines;
  73404. x += t->w;
  73405. h = jmax (h, t->h);
  73406. const Token* nextTok = tokens [i + 1];
  73407. if (nextTok == 0)
  73408. break;
  73409. if (t->isNewLine || ((! nextTok->isWhitespace) && x + nextTok->w > maxWidth))
  73410. {
  73411. // finished a line, so go back and update the heights of the things on it
  73412. for (int j = i; j >= 0; --j)
  73413. {
  73414. Token* const tok = tokens.getUnchecked(j);
  73415. if (tok->line == totalLines)
  73416. tok->lineHeight = h;
  73417. else
  73418. break;
  73419. }
  73420. x = 0;
  73421. y += h;
  73422. h = 0;
  73423. ++totalLines;
  73424. }
  73425. }
  73426. // finished a line, so go back and update the heights of the things on it
  73427. for (int j = jmin (i, tokens.size() - 1); j >= 0; --j)
  73428. {
  73429. Token* const t = tokens.getUnchecked(j);
  73430. if (t->line == totalLines)
  73431. t->lineHeight = h;
  73432. else
  73433. break;
  73434. }
  73435. ++totalLines;
  73436. if (! justification.testFlags (Justification::left))
  73437. {
  73438. int totalW = getWidth();
  73439. for (i = totalLines; --i >= 0;)
  73440. {
  73441. const int lineW = getLineWidth (i);
  73442. int dx = 0;
  73443. if (justification.testFlags (Justification::horizontallyCentred))
  73444. dx = (totalW - lineW) / 2;
  73445. else if (justification.testFlags (Justification::right))
  73446. dx = totalW - lineW;
  73447. for (int j = tokens.size(); --j >= 0;)
  73448. {
  73449. Token* const t = tokens.getUnchecked(j);
  73450. if (t->line == i)
  73451. t->x += dx;
  73452. }
  73453. }
  73454. }
  73455. }
  73456. }
  73457. int TextLayout::getLineWidth (const int lineNumber) const
  73458. {
  73459. int maxW = 0;
  73460. for (int i = tokens.size(); --i >= 0;)
  73461. {
  73462. const Token* const t = tokens.getUnchecked(i);
  73463. if (t->line == lineNumber && ! t->isWhitespace)
  73464. maxW = jmax (maxW, t->x + t->w);
  73465. }
  73466. return maxW;
  73467. }
  73468. int TextLayout::getWidth() const
  73469. {
  73470. int maxW = 0;
  73471. for (int i = tokens.size(); --i >= 0;)
  73472. {
  73473. const Token* const t = tokens.getUnchecked(i);
  73474. if (! t->isWhitespace)
  73475. maxW = jmax (maxW, t->x + t->w);
  73476. }
  73477. return maxW;
  73478. }
  73479. int TextLayout::getHeight() const
  73480. {
  73481. int maxH = 0;
  73482. for (int i = tokens.size(); --i >= 0;)
  73483. {
  73484. const Token* const t = tokens.getUnchecked(i);
  73485. if (! t->isWhitespace)
  73486. maxH = jmax (maxH, t->y + t->h);
  73487. }
  73488. return maxH;
  73489. }
  73490. void TextLayout::draw (Graphics& g,
  73491. const int xOffset,
  73492. const int yOffset) const
  73493. {
  73494. for (int i = tokens.size(); --i >= 0;)
  73495. tokens.getUnchecked(i)->draw (g, xOffset, yOffset);
  73496. }
  73497. void TextLayout::drawWithin (Graphics& g,
  73498. int x, int y, int w, int h,
  73499. const Justification& justification) const
  73500. {
  73501. justification.applyToRectangle (x, y, getWidth(), getHeight(),
  73502. x, y, w, h);
  73503. draw (g, x, y);
  73504. }
  73505. END_JUCE_NAMESPACE
  73506. /*** End of inlined file: juce_TextLayout.cpp ***/
  73507. /*** Start of inlined file: juce_Typeface.cpp ***/
  73508. BEGIN_JUCE_NAMESPACE
  73509. Typeface::Typeface (const String& name_) throw()
  73510. : name (name_)
  73511. {
  73512. }
  73513. Typeface::~Typeface()
  73514. {
  73515. }
  73516. class CustomTypeface::GlyphInfo
  73517. {
  73518. public:
  73519. GlyphInfo (const juce_wchar character_, const Path& path_, const float width_) throw()
  73520. : character (character_), path (path_), width (width_)
  73521. {
  73522. }
  73523. ~GlyphInfo() throw()
  73524. {
  73525. }
  73526. struct KerningPair
  73527. {
  73528. juce_wchar character2;
  73529. float kerningAmount;
  73530. };
  73531. void addKerningPair (const juce_wchar subsequentCharacter,
  73532. const float extraKerningAmount) throw()
  73533. {
  73534. KerningPair kp;
  73535. kp.character2 = subsequentCharacter;
  73536. kp.kerningAmount = extraKerningAmount;
  73537. kerningPairs.add (kp);
  73538. }
  73539. float getHorizontalSpacing (const juce_wchar subsequentCharacter) const throw()
  73540. {
  73541. if (subsequentCharacter != 0)
  73542. {
  73543. for (int i = kerningPairs.size(); --i >= 0;)
  73544. if (kerningPairs.getReference(i).character2 == subsequentCharacter)
  73545. return width + kerningPairs.getReference(i).kerningAmount;
  73546. }
  73547. return width;
  73548. }
  73549. const juce_wchar character;
  73550. const Path path;
  73551. float width;
  73552. Array <KerningPair> kerningPairs;
  73553. juce_UseDebuggingNewOperator
  73554. private:
  73555. GlyphInfo (const GlyphInfo&);
  73556. GlyphInfo& operator= (const GlyphInfo&);
  73557. };
  73558. CustomTypeface::CustomTypeface()
  73559. : Typeface (String::empty)
  73560. {
  73561. clear();
  73562. }
  73563. CustomTypeface::CustomTypeface (InputStream& serialisedTypefaceStream)
  73564. : Typeface (String::empty)
  73565. {
  73566. clear();
  73567. GZIPDecompressorInputStream gzin (&serialisedTypefaceStream, false);
  73568. BufferedInputStream in (&gzin, 32768, false);
  73569. name = in.readString();
  73570. isBold = in.readBool();
  73571. isItalic = in.readBool();
  73572. ascent = in.readFloat();
  73573. defaultCharacter = (juce_wchar) in.readShort();
  73574. int i, numChars = in.readInt();
  73575. for (i = 0; i < numChars; ++i)
  73576. {
  73577. const juce_wchar c = (juce_wchar) in.readShort();
  73578. const float width = in.readFloat();
  73579. Path p;
  73580. p.loadPathFromStream (in);
  73581. addGlyph (c, p, width);
  73582. }
  73583. const int numKerningPairs = in.readInt();
  73584. for (i = 0; i < numKerningPairs; ++i)
  73585. {
  73586. const juce_wchar char1 = (juce_wchar) in.readShort();
  73587. const juce_wchar char2 = (juce_wchar) in.readShort();
  73588. addKerningPair (char1, char2, in.readFloat());
  73589. }
  73590. }
  73591. CustomTypeface::~CustomTypeface()
  73592. {
  73593. }
  73594. void CustomTypeface::clear()
  73595. {
  73596. defaultCharacter = 0;
  73597. ascent = 1.0f;
  73598. isBold = isItalic = false;
  73599. zeromem (lookupTable, sizeof (lookupTable));
  73600. glyphs.clear();
  73601. }
  73602. void CustomTypeface::setCharacteristics (const String& name_, const float ascent_, const bool isBold_,
  73603. const bool isItalic_, const juce_wchar defaultCharacter_) throw()
  73604. {
  73605. name = name_;
  73606. defaultCharacter = defaultCharacter_;
  73607. ascent = ascent_;
  73608. isBold = isBold_;
  73609. isItalic = isItalic_;
  73610. }
  73611. void CustomTypeface::addGlyph (const juce_wchar character, const Path& path, const float width) throw()
  73612. {
  73613. // Check that you're not trying to add the same character twice..
  73614. jassert (findGlyph (character, false) == 0);
  73615. if (((unsigned int) character) < (unsigned int) numElementsInArray (lookupTable))
  73616. lookupTable [character] = (short) glyphs.size();
  73617. glyphs.add (new GlyphInfo (character, path, width));
  73618. }
  73619. void CustomTypeface::addKerningPair (const juce_wchar char1, const juce_wchar char2, const float extraAmount) throw()
  73620. {
  73621. if (extraAmount != 0)
  73622. {
  73623. GlyphInfo* const g = findGlyph (char1, true);
  73624. jassert (g != 0); // can only add kerning pairs for characters that exist!
  73625. if (g != 0)
  73626. g->addKerningPair (char2, extraAmount);
  73627. }
  73628. }
  73629. CustomTypeface::GlyphInfo* CustomTypeface::findGlyph (const juce_wchar character, const bool loadIfNeeded) throw()
  73630. {
  73631. if (((unsigned int) character) < (unsigned int) numElementsInArray (lookupTable) && lookupTable [character] > 0)
  73632. return glyphs [(int) lookupTable [(int) character]];
  73633. for (int i = 0; i < glyphs.size(); ++i)
  73634. {
  73635. GlyphInfo* const g = glyphs.getUnchecked(i);
  73636. if (g->character == character)
  73637. return g;
  73638. }
  73639. if (loadIfNeeded && loadGlyphIfPossible (character))
  73640. return findGlyph (character, false);
  73641. return 0;
  73642. }
  73643. CustomTypeface::GlyphInfo* CustomTypeface::findGlyphSubstituting (const juce_wchar character) throw()
  73644. {
  73645. GlyphInfo* glyph = findGlyph (character, true);
  73646. if (glyph == 0)
  73647. {
  73648. if (CharacterFunctions::isWhitespace (character) && character != L' ')
  73649. glyph = findGlyph (L' ', true);
  73650. if (glyph == 0)
  73651. {
  73652. const Font fallbackFont (Font::getFallbackFontName(), 10, 0);
  73653. Typeface* const fallbackTypeface = fallbackFont.getTypeface();
  73654. if (fallbackTypeface != 0 && fallbackTypeface != this)
  73655. {
  73656. //xxx
  73657. }
  73658. if (glyph == 0)
  73659. glyph = findGlyph (defaultCharacter, true);
  73660. }
  73661. }
  73662. return glyph;
  73663. }
  73664. bool CustomTypeface::loadGlyphIfPossible (const juce_wchar /*characterNeeded*/)
  73665. {
  73666. return false;
  73667. }
  73668. void CustomTypeface::addGlyphsFromOtherTypeface (Typeface& typefaceToCopy, juce_wchar characterStartIndex, int numCharacters) throw()
  73669. {
  73670. setCharacteristics (name, typefaceToCopy.getAscent(), isBold, isItalic, defaultCharacter);
  73671. for (int i = 0; i < numCharacters; ++i)
  73672. {
  73673. const juce_wchar c = (juce_wchar) (characterStartIndex + i);
  73674. Array <int> glyphIndexes;
  73675. Array <float> offsets;
  73676. typefaceToCopy.getGlyphPositions (String::charToString (c), glyphIndexes, offsets);
  73677. const int glyphIndex = glyphIndexes.getFirst();
  73678. if (glyphIndex >= 0 && glyphIndexes.size() > 0)
  73679. {
  73680. const float glyphWidth = offsets[1];
  73681. Path p;
  73682. typefaceToCopy.getOutlineForGlyph (glyphIndex, p);
  73683. addGlyph (c, p, glyphWidth);
  73684. for (int j = glyphs.size() - 1; --j >= 0;)
  73685. {
  73686. const juce_wchar char2 = glyphs.getUnchecked (j)->character;
  73687. glyphIndexes.clearQuick();
  73688. offsets.clearQuick();
  73689. typefaceToCopy.getGlyphPositions (String::charToString (c) + String::charToString (char2), glyphIndexes, offsets);
  73690. if (offsets.size() > 1)
  73691. addKerningPair (c, char2, offsets[1] - glyphWidth);
  73692. }
  73693. }
  73694. }
  73695. }
  73696. bool CustomTypeface::writeToStream (OutputStream& outputStream)
  73697. {
  73698. GZIPCompressorOutputStream out (&outputStream);
  73699. out.writeString (name);
  73700. out.writeBool (isBold);
  73701. out.writeBool (isItalic);
  73702. out.writeFloat (ascent);
  73703. out.writeShort ((short) (unsigned short) defaultCharacter);
  73704. out.writeInt (glyphs.size());
  73705. int i, numKerningPairs = 0;
  73706. for (i = 0; i < glyphs.size(); ++i)
  73707. {
  73708. const GlyphInfo* const g = glyphs.getUnchecked (i);
  73709. out.writeShort ((short) (unsigned short) g->character);
  73710. out.writeFloat (g->width);
  73711. g->path.writePathToStream (out);
  73712. numKerningPairs += g->kerningPairs.size();
  73713. }
  73714. out.writeInt (numKerningPairs);
  73715. for (i = 0; i < glyphs.size(); ++i)
  73716. {
  73717. const GlyphInfo* const g = glyphs.getUnchecked (i);
  73718. for (int j = 0; j < g->kerningPairs.size(); ++j)
  73719. {
  73720. const GlyphInfo::KerningPair& p = g->kerningPairs.getReference (j);
  73721. out.writeShort ((short) (unsigned short) g->character);
  73722. out.writeShort ((short) (unsigned short) p.character2);
  73723. out.writeFloat (p.kerningAmount);
  73724. }
  73725. }
  73726. return true;
  73727. }
  73728. float CustomTypeface::getAscent() const
  73729. {
  73730. return ascent;
  73731. }
  73732. float CustomTypeface::getDescent() const
  73733. {
  73734. return 1.0f - ascent;
  73735. }
  73736. float CustomTypeface::getStringWidth (const String& text)
  73737. {
  73738. float x = 0;
  73739. const juce_wchar* t = text;
  73740. while (*t != 0)
  73741. {
  73742. const GlyphInfo* const glyph = findGlyphSubstituting (*t++);
  73743. if (glyph != 0)
  73744. x += glyph->getHorizontalSpacing (*t);
  73745. }
  73746. return x;
  73747. }
  73748. void CustomTypeface::getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array<float>& xOffsets)
  73749. {
  73750. xOffsets.add (0);
  73751. float x = 0;
  73752. const juce_wchar* t = text;
  73753. while (*t != 0)
  73754. {
  73755. const juce_wchar c = *t++;
  73756. const GlyphInfo* const glyph = findGlyphSubstituting (c);
  73757. if (glyph != 0)
  73758. {
  73759. x += glyph->getHorizontalSpacing (*t);
  73760. resultGlyphs.add ((int) glyph->character);
  73761. xOffsets.add (x);
  73762. }
  73763. }
  73764. }
  73765. bool CustomTypeface::getOutlineForGlyph (int glyphNumber, Path& path)
  73766. {
  73767. const GlyphInfo* const glyph = findGlyphSubstituting ((juce_wchar) glyphNumber);
  73768. if (glyph != 0)
  73769. {
  73770. path = glyph->path;
  73771. return true;
  73772. }
  73773. return false;
  73774. }
  73775. END_JUCE_NAMESPACE
  73776. /*** End of inlined file: juce_Typeface.cpp ***/
  73777. /*** Start of inlined file: juce_AffineTransform.cpp ***/
  73778. BEGIN_JUCE_NAMESPACE
  73779. AffineTransform::AffineTransform() throw()
  73780. : mat00 (1.0f),
  73781. mat01 (0),
  73782. mat02 (0),
  73783. mat10 (0),
  73784. mat11 (1.0f),
  73785. mat12 (0)
  73786. {
  73787. }
  73788. AffineTransform::AffineTransform (const AffineTransform& other) throw()
  73789. : mat00 (other.mat00),
  73790. mat01 (other.mat01),
  73791. mat02 (other.mat02),
  73792. mat10 (other.mat10),
  73793. mat11 (other.mat11),
  73794. mat12 (other.mat12)
  73795. {
  73796. }
  73797. AffineTransform::AffineTransform (const float mat00_,
  73798. const float mat01_,
  73799. const float mat02_,
  73800. const float mat10_,
  73801. const float mat11_,
  73802. const float mat12_) throw()
  73803. : mat00 (mat00_),
  73804. mat01 (mat01_),
  73805. mat02 (mat02_),
  73806. mat10 (mat10_),
  73807. mat11 (mat11_),
  73808. mat12 (mat12_)
  73809. {
  73810. }
  73811. AffineTransform& AffineTransform::operator= (const AffineTransform& other) throw()
  73812. {
  73813. mat00 = other.mat00;
  73814. mat01 = other.mat01;
  73815. mat02 = other.mat02;
  73816. mat10 = other.mat10;
  73817. mat11 = other.mat11;
  73818. mat12 = other.mat12;
  73819. return *this;
  73820. }
  73821. bool AffineTransform::operator== (const AffineTransform& other) const throw()
  73822. {
  73823. return mat00 == other.mat00
  73824. && mat01 == other.mat01
  73825. && mat02 == other.mat02
  73826. && mat10 == other.mat10
  73827. && mat11 == other.mat11
  73828. && mat12 == other.mat12;
  73829. }
  73830. bool AffineTransform::operator!= (const AffineTransform& other) const throw()
  73831. {
  73832. return ! operator== (other);
  73833. }
  73834. bool AffineTransform::isIdentity() const throw()
  73835. {
  73836. return (mat01 == 0)
  73837. && (mat02 == 0)
  73838. && (mat10 == 0)
  73839. && (mat12 == 0)
  73840. && (mat00 == 1.0f)
  73841. && (mat11 == 1.0f);
  73842. }
  73843. const AffineTransform AffineTransform::identity;
  73844. const AffineTransform AffineTransform::followedBy (const AffineTransform& other) const throw()
  73845. {
  73846. return AffineTransform (other.mat00 * mat00 + other.mat01 * mat10,
  73847. other.mat00 * mat01 + other.mat01 * mat11,
  73848. other.mat00 * mat02 + other.mat01 * mat12 + other.mat02,
  73849. other.mat10 * mat00 + other.mat11 * mat10,
  73850. other.mat10 * mat01 + other.mat11 * mat11,
  73851. other.mat10 * mat02 + other.mat11 * mat12 + other.mat12);
  73852. }
  73853. const AffineTransform AffineTransform::followedBy (const float omat00,
  73854. const float omat01,
  73855. const float omat02,
  73856. const float omat10,
  73857. const float omat11,
  73858. const float omat12) const throw()
  73859. {
  73860. return AffineTransform (omat00 * mat00 + omat01 * mat10,
  73861. omat00 * mat01 + omat01 * mat11,
  73862. omat00 * mat02 + omat01 * mat12 + omat02,
  73863. omat10 * mat00 + omat11 * mat10,
  73864. omat10 * mat01 + omat11 * mat11,
  73865. omat10 * mat02 + omat11 * mat12 + omat12);
  73866. }
  73867. const AffineTransform AffineTransform::translated (const float dx,
  73868. const float dy) const throw()
  73869. {
  73870. return AffineTransform (mat00, mat01, mat02 + dx,
  73871. mat10, mat11, mat12 + dy);
  73872. }
  73873. const AffineTransform AffineTransform::translation (const float dx,
  73874. const float dy) throw()
  73875. {
  73876. return AffineTransform (1.0f, 0, dx,
  73877. 0, 1.0f, dy);
  73878. }
  73879. const AffineTransform AffineTransform::rotated (const float rad) const throw()
  73880. {
  73881. const float cosRad = std::cos (rad);
  73882. const float sinRad = std::sin (rad);
  73883. return followedBy (cosRad, -sinRad, 0,
  73884. sinRad, cosRad, 0);
  73885. }
  73886. const AffineTransform AffineTransform::rotation (const float rad) throw()
  73887. {
  73888. const float cosRad = std::cos (rad);
  73889. const float sinRad = std::sin (rad);
  73890. return AffineTransform (cosRad, -sinRad, 0,
  73891. sinRad, cosRad, 0);
  73892. }
  73893. const AffineTransform AffineTransform::rotated (const float angle,
  73894. const float pivotX,
  73895. const float pivotY) const throw()
  73896. {
  73897. return translated (-pivotX, -pivotY)
  73898. .rotated (angle)
  73899. .translated (pivotX, pivotY);
  73900. }
  73901. const AffineTransform AffineTransform::rotation (const float angle,
  73902. const float pivotX,
  73903. const float pivotY) throw()
  73904. {
  73905. return translation (-pivotX, -pivotY)
  73906. .rotated (angle)
  73907. .translated (pivotX, pivotY);
  73908. }
  73909. const AffineTransform AffineTransform::scaled (const float factorX,
  73910. const float factorY) const throw()
  73911. {
  73912. return AffineTransform (factorX * mat00, factorX * mat01, factorX * mat02,
  73913. factorY * mat10, factorY * mat11, factorY * mat12);
  73914. }
  73915. const AffineTransform AffineTransform::scale (const float factorX,
  73916. const float factorY) throw()
  73917. {
  73918. return AffineTransform (factorX, 0, 0,
  73919. 0, factorY, 0);
  73920. }
  73921. const AffineTransform AffineTransform::sheared (const float shearX,
  73922. const float shearY) const throw()
  73923. {
  73924. return followedBy (1.0f, shearX, 0,
  73925. shearY, 1.0f, 0);
  73926. }
  73927. const AffineTransform AffineTransform::inverted() const throw()
  73928. {
  73929. double determinant = (mat00 * mat11 - mat10 * mat01);
  73930. if (determinant != 0.0)
  73931. {
  73932. determinant = 1.0 / determinant;
  73933. const float dst00 = (float) (mat11 * determinant);
  73934. const float dst10 = (float) (-mat10 * determinant);
  73935. const float dst01 = (float) (-mat01 * determinant);
  73936. const float dst11 = (float) (mat00 * determinant);
  73937. return AffineTransform (dst00, dst01, -mat02 * dst00 - mat12 * dst01,
  73938. dst10, dst11, -mat02 * dst10 - mat12 * dst11);
  73939. }
  73940. else
  73941. {
  73942. // singularity..
  73943. return *this;
  73944. }
  73945. }
  73946. bool AffineTransform::isSingularity() const throw()
  73947. {
  73948. return (mat00 * mat11 - mat10 * mat01) == 0.0;
  73949. }
  73950. const AffineTransform AffineTransform::fromTargetPoints (const float x00, const float y00,
  73951. const float x10, const float y10,
  73952. const float x01, const float y01) throw()
  73953. {
  73954. return AffineTransform (x10 - x00, x01 - x00, x00,
  73955. y10 - y00, y01 - y00, y00);
  73956. }
  73957. const AffineTransform AffineTransform::fromTargetPoints (const float sx1, const float sy1, const float tx1, const float ty1,
  73958. const float sx2, const float sy2, const float tx2, const float ty2,
  73959. const float sx3, const float sy3, const float tx3, const float ty3) throw()
  73960. {
  73961. return fromTargetPoints (sx1, sy1, sx2, sy2, sx3, sy3)
  73962. .inverted()
  73963. .followedBy (fromTargetPoints (tx1, ty1, tx2, ty2, tx3, ty3));
  73964. }
  73965. bool AffineTransform::isOnlyTranslation() const throw()
  73966. {
  73967. return (mat01 == 0)
  73968. && (mat10 == 0)
  73969. && (mat00 == 1.0f)
  73970. && (mat11 == 1.0f);
  73971. }
  73972. END_JUCE_NAMESPACE
  73973. /*** End of inlined file: juce_AffineTransform.cpp ***/
  73974. /*** Start of inlined file: juce_BorderSize.cpp ***/
  73975. BEGIN_JUCE_NAMESPACE
  73976. BorderSize::BorderSize() throw()
  73977. : top (0),
  73978. left (0),
  73979. bottom (0),
  73980. right (0)
  73981. {
  73982. }
  73983. BorderSize::BorderSize (const BorderSize& other) throw()
  73984. : top (other.top),
  73985. left (other.left),
  73986. bottom (other.bottom),
  73987. right (other.right)
  73988. {
  73989. }
  73990. BorderSize::BorderSize (const int topGap,
  73991. const int leftGap,
  73992. const int bottomGap,
  73993. const int rightGap) throw()
  73994. : top (topGap),
  73995. left (leftGap),
  73996. bottom (bottomGap),
  73997. right (rightGap)
  73998. {
  73999. }
  74000. BorderSize::BorderSize (const int allGaps) throw()
  74001. : top (allGaps),
  74002. left (allGaps),
  74003. bottom (allGaps),
  74004. right (allGaps)
  74005. {
  74006. }
  74007. BorderSize::~BorderSize() throw()
  74008. {
  74009. }
  74010. void BorderSize::setTop (const int newTopGap) throw()
  74011. {
  74012. top = newTopGap;
  74013. }
  74014. void BorderSize::setLeft (const int newLeftGap) throw()
  74015. {
  74016. left = newLeftGap;
  74017. }
  74018. void BorderSize::setBottom (const int newBottomGap) throw()
  74019. {
  74020. bottom = newBottomGap;
  74021. }
  74022. void BorderSize::setRight (const int newRightGap) throw()
  74023. {
  74024. right = newRightGap;
  74025. }
  74026. const Rectangle<int> BorderSize::subtractedFrom (const Rectangle<int>& r) const throw()
  74027. {
  74028. return Rectangle<int> (r.getX() + left,
  74029. r.getY() + top,
  74030. r.getWidth() - (left + right),
  74031. r.getHeight() - (top + bottom));
  74032. }
  74033. void BorderSize::subtractFrom (Rectangle<int>& r) const throw()
  74034. {
  74035. r.setBounds (r.getX() + left,
  74036. r.getY() + top,
  74037. r.getWidth() - (left + right),
  74038. r.getHeight() - (top + bottom));
  74039. }
  74040. const Rectangle<int> BorderSize::addedTo (const Rectangle<int>& r) const throw()
  74041. {
  74042. return Rectangle<int> (r.getX() - left,
  74043. r.getY() - top,
  74044. r.getWidth() + (left + right),
  74045. r.getHeight() + (top + bottom));
  74046. }
  74047. void BorderSize::addTo (Rectangle<int>& r) const throw()
  74048. {
  74049. r.setBounds (r.getX() - left,
  74050. r.getY() - top,
  74051. r.getWidth() + (left + right),
  74052. r.getHeight() + (top + bottom));
  74053. }
  74054. bool BorderSize::operator== (const BorderSize& other) const throw()
  74055. {
  74056. return top == other.top
  74057. && left == other.left
  74058. && bottom == other.bottom
  74059. && right == other.right;
  74060. }
  74061. bool BorderSize::operator!= (const BorderSize& other) const throw()
  74062. {
  74063. return ! operator== (other);
  74064. }
  74065. END_JUCE_NAMESPACE
  74066. /*** End of inlined file: juce_BorderSize.cpp ***/
  74067. /*** Start of inlined file: juce_Path.cpp ***/
  74068. BEGIN_JUCE_NAMESPACE
  74069. // tests that some co-ords aren't NaNs
  74070. #define CHECK_COORDS_ARE_VALID(x, y) \
  74071. jassert (x == x && y == y);
  74072. namespace PathHelpers
  74073. {
  74074. static const float ellipseAngularIncrement = 0.05f;
  74075. static const String nextToken (const juce_wchar*& t)
  74076. {
  74077. while (CharacterFunctions::isWhitespace (*t))
  74078. ++t;
  74079. const juce_wchar* const start = t;
  74080. while (*t != 0 && ! CharacterFunctions::isWhitespace (*t))
  74081. ++t;
  74082. return String (start, (int) (t - start));
  74083. }
  74084. }
  74085. const float Path::lineMarker = 100001.0f;
  74086. const float Path::moveMarker = 100002.0f;
  74087. const float Path::quadMarker = 100003.0f;
  74088. const float Path::cubicMarker = 100004.0f;
  74089. const float Path::closeSubPathMarker = 100005.0f;
  74090. Path::Path()
  74091. : numElements (0),
  74092. pathXMin (0),
  74093. pathXMax (0),
  74094. pathYMin (0),
  74095. pathYMax (0),
  74096. useNonZeroWinding (true)
  74097. {
  74098. }
  74099. Path::~Path()
  74100. {
  74101. }
  74102. Path::Path (const Path& other)
  74103. : numElements (other.numElements),
  74104. pathXMin (other.pathXMin),
  74105. pathXMax (other.pathXMax),
  74106. pathYMin (other.pathYMin),
  74107. pathYMax (other.pathYMax),
  74108. useNonZeroWinding (other.useNonZeroWinding)
  74109. {
  74110. if (numElements > 0)
  74111. {
  74112. data.setAllocatedSize ((int) numElements);
  74113. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  74114. }
  74115. }
  74116. Path& Path::operator= (const Path& other)
  74117. {
  74118. if (this != &other)
  74119. {
  74120. data.ensureAllocatedSize ((int) other.numElements);
  74121. numElements = other.numElements;
  74122. pathXMin = other.pathXMin;
  74123. pathXMax = other.pathXMax;
  74124. pathYMin = other.pathYMin;
  74125. pathYMax = other.pathYMax;
  74126. useNonZeroWinding = other.useNonZeroWinding;
  74127. if (numElements > 0)
  74128. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  74129. }
  74130. return *this;
  74131. }
  74132. bool Path::operator== (const Path& other) const throw()
  74133. {
  74134. return ! operator!= (other);
  74135. }
  74136. bool Path::operator!= (const Path& other) const throw()
  74137. {
  74138. if (numElements != other.numElements || useNonZeroWinding != other.useNonZeroWinding)
  74139. return true;
  74140. for (size_t i = 0; i < numElements; ++i)
  74141. if (data.elements[i] != other.data.elements[i])
  74142. return true;
  74143. return false;
  74144. }
  74145. void Path::clear() throw()
  74146. {
  74147. numElements = 0;
  74148. pathXMin = 0;
  74149. pathYMin = 0;
  74150. pathYMax = 0;
  74151. pathXMax = 0;
  74152. }
  74153. void Path::swapWithPath (Path& other) throw()
  74154. {
  74155. data.swapWith (other.data);
  74156. swapVariables <size_t> (numElements, other.numElements);
  74157. swapVariables <float> (pathXMin, other.pathXMin);
  74158. swapVariables <float> (pathXMax, other.pathXMax);
  74159. swapVariables <float> (pathYMin, other.pathYMin);
  74160. swapVariables <float> (pathYMax, other.pathYMax);
  74161. swapVariables <bool> (useNonZeroWinding, other.useNonZeroWinding);
  74162. }
  74163. void Path::setUsingNonZeroWinding (const bool isNonZero) throw()
  74164. {
  74165. useNonZeroWinding = isNonZero;
  74166. }
  74167. void Path::scaleToFit (const float x, const float y, const float w, const float h,
  74168. const bool preserveProportions) throw()
  74169. {
  74170. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions));
  74171. }
  74172. bool Path::isEmpty() const throw()
  74173. {
  74174. size_t i = 0;
  74175. while (i < numElements)
  74176. {
  74177. const float type = data.elements [i++];
  74178. if (type == moveMarker)
  74179. {
  74180. i += 2;
  74181. }
  74182. else if (type == lineMarker
  74183. || type == quadMarker
  74184. || type == cubicMarker)
  74185. {
  74186. return false;
  74187. }
  74188. }
  74189. return true;
  74190. }
  74191. const Rectangle<float> Path::getBounds() const throw()
  74192. {
  74193. return Rectangle<float> (pathXMin, pathYMin,
  74194. pathXMax - pathXMin,
  74195. pathYMax - pathYMin);
  74196. }
  74197. const Rectangle<float> Path::getBoundsTransformed (const AffineTransform& transform) const throw()
  74198. {
  74199. return getBounds().transformed (transform);
  74200. }
  74201. void Path::startNewSubPath (const float x, const float y)
  74202. {
  74203. CHECK_COORDS_ARE_VALID (x, y);
  74204. if (numElements == 0)
  74205. {
  74206. pathXMin = pathXMax = x;
  74207. pathYMin = pathYMax = y;
  74208. }
  74209. else
  74210. {
  74211. pathXMin = jmin (pathXMin, x);
  74212. pathXMax = jmax (pathXMax, x);
  74213. pathYMin = jmin (pathYMin, y);
  74214. pathYMax = jmax (pathYMax, y);
  74215. }
  74216. data.ensureAllocatedSize ((int) numElements + 3);
  74217. data.elements [numElements++] = moveMarker;
  74218. data.elements [numElements++] = x;
  74219. data.elements [numElements++] = y;
  74220. }
  74221. void Path::startNewSubPath (const Point<float>& start)
  74222. {
  74223. startNewSubPath (start.getX(), start.getY());
  74224. }
  74225. void Path::lineTo (const float x, const float y)
  74226. {
  74227. CHECK_COORDS_ARE_VALID (x, y);
  74228. if (numElements == 0)
  74229. startNewSubPath (0, 0);
  74230. data.ensureAllocatedSize ((int) numElements + 3);
  74231. data.elements [numElements++] = lineMarker;
  74232. data.elements [numElements++] = x;
  74233. data.elements [numElements++] = y;
  74234. pathXMin = jmin (pathXMin, x);
  74235. pathXMax = jmax (pathXMax, x);
  74236. pathYMin = jmin (pathYMin, y);
  74237. pathYMax = jmax (pathYMax, y);
  74238. }
  74239. void Path::lineTo (const Point<float>& end)
  74240. {
  74241. lineTo (end.getX(), end.getY());
  74242. }
  74243. void Path::quadraticTo (const float x1, const float y1,
  74244. const float x2, const float y2)
  74245. {
  74246. CHECK_COORDS_ARE_VALID (x1, y1);
  74247. CHECK_COORDS_ARE_VALID (x2, y2);
  74248. if (numElements == 0)
  74249. startNewSubPath (0, 0);
  74250. data.ensureAllocatedSize ((int) numElements + 5);
  74251. data.elements [numElements++] = quadMarker;
  74252. data.elements [numElements++] = x1;
  74253. data.elements [numElements++] = y1;
  74254. data.elements [numElements++] = x2;
  74255. data.elements [numElements++] = y2;
  74256. pathXMin = jmin (pathXMin, x1, x2);
  74257. pathXMax = jmax (pathXMax, x1, x2);
  74258. pathYMin = jmin (pathYMin, y1, y2);
  74259. pathYMax = jmax (pathYMax, y1, y2);
  74260. }
  74261. void Path::quadraticTo (const Point<float>& controlPoint,
  74262. const Point<float>& endPoint)
  74263. {
  74264. quadraticTo (controlPoint.getX(), controlPoint.getY(),
  74265. endPoint.getX(), endPoint.getY());
  74266. }
  74267. void Path::cubicTo (const float x1, const float y1,
  74268. const float x2, const float y2,
  74269. const float x3, const float y3)
  74270. {
  74271. CHECK_COORDS_ARE_VALID (x1, y1);
  74272. CHECK_COORDS_ARE_VALID (x2, y2);
  74273. CHECK_COORDS_ARE_VALID (x3, y3);
  74274. if (numElements == 0)
  74275. startNewSubPath (0, 0);
  74276. data.ensureAllocatedSize ((int) numElements + 7);
  74277. data.elements [numElements++] = cubicMarker;
  74278. data.elements [numElements++] = x1;
  74279. data.elements [numElements++] = y1;
  74280. data.elements [numElements++] = x2;
  74281. data.elements [numElements++] = y2;
  74282. data.elements [numElements++] = x3;
  74283. data.elements [numElements++] = y3;
  74284. pathXMin = jmin (pathXMin, x1, x2, x3);
  74285. pathXMax = jmax (pathXMax, x1, x2, x3);
  74286. pathYMin = jmin (pathYMin, y1, y2, y3);
  74287. pathYMax = jmax (pathYMax, y1, y2, y3);
  74288. }
  74289. void Path::cubicTo (const Point<float>& controlPoint1,
  74290. const Point<float>& controlPoint2,
  74291. const Point<float>& endPoint)
  74292. {
  74293. cubicTo (controlPoint1.getX(), controlPoint1.getY(),
  74294. controlPoint2.getX(), controlPoint2.getY(),
  74295. endPoint.getX(), endPoint.getY());
  74296. }
  74297. void Path::closeSubPath()
  74298. {
  74299. if (numElements > 0
  74300. && data.elements [numElements - 1] != closeSubPathMarker)
  74301. {
  74302. data.ensureAllocatedSize ((int) numElements + 1);
  74303. data.elements [numElements++] = closeSubPathMarker;
  74304. }
  74305. }
  74306. const Point<float> Path::getCurrentPosition() const
  74307. {
  74308. size_t i = numElements - 1;
  74309. if (i > 0 && data.elements[i] == closeSubPathMarker)
  74310. {
  74311. while (i >= 0)
  74312. {
  74313. if (data.elements[i] == moveMarker)
  74314. {
  74315. i += 2;
  74316. break;
  74317. }
  74318. --i;
  74319. }
  74320. }
  74321. if (i > 0)
  74322. return Point<float> (data.elements [i - 1], data.elements [i]);
  74323. return Point<float>();
  74324. }
  74325. void Path::addRectangle (const float x, const float y,
  74326. const float w, const float h)
  74327. {
  74328. float x1 = x, y1 = y, x2 = x + w, y2 = y + h;
  74329. if (w < 0)
  74330. swapVariables (x1, x2);
  74331. if (h < 0)
  74332. swapVariables (y1, y2);
  74333. data.ensureAllocatedSize ((int) numElements + 13);
  74334. if (numElements == 0)
  74335. {
  74336. pathXMin = x1;
  74337. pathXMax = x2;
  74338. pathYMin = y1;
  74339. pathYMax = y2;
  74340. }
  74341. else
  74342. {
  74343. pathXMin = jmin (pathXMin, x1);
  74344. pathXMax = jmax (pathXMax, x2);
  74345. pathYMin = jmin (pathYMin, y1);
  74346. pathYMax = jmax (pathYMax, y2);
  74347. }
  74348. data.elements [numElements++] = moveMarker;
  74349. data.elements [numElements++] = x1;
  74350. data.elements [numElements++] = y2;
  74351. data.elements [numElements++] = lineMarker;
  74352. data.elements [numElements++] = x1;
  74353. data.elements [numElements++] = y1;
  74354. data.elements [numElements++] = lineMarker;
  74355. data.elements [numElements++] = x2;
  74356. data.elements [numElements++] = y1;
  74357. data.elements [numElements++] = lineMarker;
  74358. data.elements [numElements++] = x2;
  74359. data.elements [numElements++] = y2;
  74360. data.elements [numElements++] = closeSubPathMarker;
  74361. }
  74362. void Path::addRoundedRectangle (const float x, const float y,
  74363. const float w, const float h,
  74364. float csx,
  74365. float csy)
  74366. {
  74367. csx = jmin (csx, w * 0.5f);
  74368. csy = jmin (csy, h * 0.5f);
  74369. const float cs45x = csx * 0.45f;
  74370. const float cs45y = csy * 0.45f;
  74371. const float x2 = x + w;
  74372. const float y2 = y + h;
  74373. startNewSubPath (x + csx, y);
  74374. lineTo (x2 - csx, y);
  74375. cubicTo (x2 - cs45x, y, x2, y + cs45y, x2, y + csy);
  74376. lineTo (x2, y2 - csy);
  74377. cubicTo (x2, y2 - cs45y, x2 - cs45x, y2, x2 - csx, y2);
  74378. lineTo (x + csx, y2);
  74379. cubicTo (x + cs45x, y2, x, y2 - cs45y, x, y2 - csy);
  74380. lineTo (x, y + csy);
  74381. cubicTo (x, y + cs45y, x + cs45x, y, x + csx, y);
  74382. closeSubPath();
  74383. }
  74384. void Path::addRoundedRectangle (const float x, const float y,
  74385. const float w, const float h,
  74386. float cs)
  74387. {
  74388. addRoundedRectangle (x, y, w, h, cs, cs);
  74389. }
  74390. void Path::addTriangle (const float x1, const float y1,
  74391. const float x2, const float y2,
  74392. const float x3, const float y3)
  74393. {
  74394. startNewSubPath (x1, y1);
  74395. lineTo (x2, y2);
  74396. lineTo (x3, y3);
  74397. closeSubPath();
  74398. }
  74399. void Path::addQuadrilateral (const float x1, const float y1,
  74400. const float x2, const float y2,
  74401. const float x3, const float y3,
  74402. const float x4, const float y4)
  74403. {
  74404. startNewSubPath (x1, y1);
  74405. lineTo (x2, y2);
  74406. lineTo (x3, y3);
  74407. lineTo (x4, y4);
  74408. closeSubPath();
  74409. }
  74410. void Path::addEllipse (const float x, const float y,
  74411. const float w, const float h)
  74412. {
  74413. const float hw = w * 0.5f;
  74414. const float hw55 = hw * 0.55f;
  74415. const float hh = h * 0.5f;
  74416. const float hh45 = hh * 0.55f;
  74417. const float cx = x + hw;
  74418. const float cy = y + hh;
  74419. startNewSubPath (cx, cy - hh);
  74420. cubicTo (cx + hw55, cy - hh, cx + hw, cy - hh45, cx + hw, cy);
  74421. cubicTo (cx + hw, cy + hh45, cx + hw55, cy + hh, cx, cy + hh);
  74422. cubicTo (cx - hw55, cy + hh, cx - hw, cy + hh45, cx - hw, cy);
  74423. cubicTo (cx - hw, cy - hh45, cx - hw55, cy - hh, cx, cy - hh);
  74424. closeSubPath();
  74425. }
  74426. void Path::addArc (const float x, const float y,
  74427. const float w, const float h,
  74428. const float fromRadians,
  74429. const float toRadians,
  74430. const bool startAsNewSubPath)
  74431. {
  74432. const float radiusX = w / 2.0f;
  74433. const float radiusY = h / 2.0f;
  74434. addCentredArc (x + radiusX,
  74435. y + radiusY,
  74436. radiusX, radiusY,
  74437. 0.0f,
  74438. fromRadians, toRadians,
  74439. startAsNewSubPath);
  74440. }
  74441. void Path::addCentredArc (const float centreX, const float centreY,
  74442. const float radiusX, const float radiusY,
  74443. const float rotationOfEllipse,
  74444. const float fromRadians,
  74445. const float toRadians,
  74446. const bool startAsNewSubPath)
  74447. {
  74448. if (radiusX > 0.0f && radiusY > 0.0f)
  74449. {
  74450. const Point<float> centre (centreX, centreY);
  74451. const AffineTransform rotation (AffineTransform::rotation (rotationOfEllipse, centreX, centreY));
  74452. float angle = fromRadians;
  74453. if (startAsNewSubPath)
  74454. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74455. if (fromRadians < toRadians)
  74456. {
  74457. if (startAsNewSubPath)
  74458. angle += PathHelpers::ellipseAngularIncrement;
  74459. while (angle < toRadians)
  74460. {
  74461. lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74462. angle += PathHelpers::ellipseAngularIncrement;
  74463. }
  74464. }
  74465. else
  74466. {
  74467. if (startAsNewSubPath)
  74468. angle -= PathHelpers::ellipseAngularIncrement;
  74469. while (angle > toRadians)
  74470. {
  74471. lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74472. angle -= PathHelpers::ellipseAngularIncrement;
  74473. }
  74474. }
  74475. lineTo (centre.getPointOnCircumference (radiusX, radiusY, toRadians).transformedBy (rotation));
  74476. }
  74477. }
  74478. void Path::addPieSegment (const float x, const float y,
  74479. const float width, const float height,
  74480. const float fromRadians,
  74481. const float toRadians,
  74482. const float innerCircleProportionalSize)
  74483. {
  74484. float radiusX = width * 0.5f;
  74485. float radiusY = height * 0.5f;
  74486. const Point<float> centre (x + radiusX, y + radiusY);
  74487. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, fromRadians));
  74488. addArc (x, y, width, height, fromRadians, toRadians);
  74489. if (std::abs (fromRadians - toRadians) > float_Pi * 1.999f)
  74490. {
  74491. closeSubPath();
  74492. if (innerCircleProportionalSize > 0)
  74493. {
  74494. radiusX *= innerCircleProportionalSize;
  74495. radiusY *= innerCircleProportionalSize;
  74496. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, toRadians));
  74497. addArc (centre.getX() - radiusX, centre.getY() - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
  74498. }
  74499. }
  74500. else
  74501. {
  74502. if (innerCircleProportionalSize > 0)
  74503. {
  74504. radiusX *= innerCircleProportionalSize;
  74505. radiusY *= innerCircleProportionalSize;
  74506. addArc (centre.getX() - radiusX, centre.getY() - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
  74507. }
  74508. else
  74509. {
  74510. lineTo (centre);
  74511. }
  74512. }
  74513. closeSubPath();
  74514. }
  74515. void Path::addLineSegment (const Line<float>& line, float lineThickness)
  74516. {
  74517. const Line<float> reversed (line.reversed());
  74518. lineThickness *= 0.5f;
  74519. startNewSubPath (line.getPointAlongLine (0, lineThickness));
  74520. lineTo (line.getPointAlongLine (0, -lineThickness));
  74521. lineTo (reversed.getPointAlongLine (0, lineThickness));
  74522. lineTo (reversed.getPointAlongLine (0, -lineThickness));
  74523. closeSubPath();
  74524. }
  74525. void Path::addArrow (const Line<float>& line, float lineThickness,
  74526. float arrowheadWidth, float arrowheadLength)
  74527. {
  74528. const Line<float> reversed (line.reversed());
  74529. lineThickness *= 0.5f;
  74530. arrowheadWidth *= 0.5f;
  74531. arrowheadLength = jmin (arrowheadLength, 0.8f * line.getLength());
  74532. startNewSubPath (line.getPointAlongLine (0, lineThickness));
  74533. lineTo (line.getPointAlongLine (0, -lineThickness));
  74534. lineTo (reversed.getPointAlongLine (arrowheadLength, lineThickness));
  74535. lineTo (reversed.getPointAlongLine (arrowheadLength, arrowheadWidth));
  74536. lineTo (line.getEnd());
  74537. lineTo (reversed.getPointAlongLine (arrowheadLength, -arrowheadWidth));
  74538. lineTo (reversed.getPointAlongLine (arrowheadLength, -lineThickness));
  74539. closeSubPath();
  74540. }
  74541. void Path::addPolygon (const Point<float>& centre, const int numberOfSides,
  74542. const float radius, const float startAngle)
  74543. {
  74544. jassert (numberOfSides > 1); // this would be silly.
  74545. if (numberOfSides > 1)
  74546. {
  74547. const float angleBetweenPoints = float_Pi * 2.0f / numberOfSides;
  74548. for (int i = 0; i < numberOfSides; ++i)
  74549. {
  74550. const float angle = startAngle + i * angleBetweenPoints;
  74551. const Point<float> p (centre.getPointOnCircumference (radius, angle));
  74552. if (i == 0)
  74553. startNewSubPath (p);
  74554. else
  74555. lineTo (p);
  74556. }
  74557. closeSubPath();
  74558. }
  74559. }
  74560. void Path::addStar (const Point<float>& centre, const int numberOfPoints,
  74561. const float innerRadius, const float outerRadius, const float startAngle)
  74562. {
  74563. jassert (numberOfPoints > 1); // this would be silly.
  74564. if (numberOfPoints > 1)
  74565. {
  74566. const float angleBetweenPoints = float_Pi * 2.0f / numberOfPoints;
  74567. for (int i = 0; i < numberOfPoints; ++i)
  74568. {
  74569. const float angle = startAngle + i * angleBetweenPoints;
  74570. const Point<float> p (centre.getPointOnCircumference (outerRadius, angle));
  74571. if (i == 0)
  74572. startNewSubPath (p);
  74573. else
  74574. lineTo (p);
  74575. lineTo (centre.getPointOnCircumference (innerRadius, angle + angleBetweenPoints * 0.5f));
  74576. }
  74577. closeSubPath();
  74578. }
  74579. }
  74580. void Path::addBubble (float x, float y,
  74581. float w, float h,
  74582. float cs,
  74583. float tipX,
  74584. float tipY,
  74585. int whichSide,
  74586. float arrowPos,
  74587. float arrowWidth)
  74588. {
  74589. if (w > 1.0f && h > 1.0f)
  74590. {
  74591. cs = jmin (cs, w * 0.5f, h * 0.5f);
  74592. const float cs2 = 2.0f * cs;
  74593. startNewSubPath (x + cs, y);
  74594. if (whichSide == 0)
  74595. {
  74596. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  74597. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  74598. lineTo (arrowX1, y);
  74599. lineTo (tipX, tipY);
  74600. lineTo (arrowX1 + halfArrowW * 2.0f, y);
  74601. }
  74602. lineTo (x + w - cs, y);
  74603. if (cs > 0.0f)
  74604. addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  74605. if (whichSide == 3)
  74606. {
  74607. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  74608. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  74609. lineTo (x + w, arrowY1);
  74610. lineTo (tipX, tipY);
  74611. lineTo (x + w, arrowY1 + halfArrowH * 2.0f);
  74612. }
  74613. lineTo (x + w, y + h - cs);
  74614. if (cs > 0.0f)
  74615. addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  74616. if (whichSide == 2)
  74617. {
  74618. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  74619. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  74620. lineTo (arrowX1 + halfArrowW * 2.0f, y + h);
  74621. lineTo (tipX, tipY);
  74622. lineTo (arrowX1, y + h);
  74623. }
  74624. lineTo (x + cs, y + h);
  74625. if (cs > 0.0f)
  74626. addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  74627. if (whichSide == 1)
  74628. {
  74629. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  74630. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  74631. lineTo (x, arrowY1 + halfArrowH * 2.0f);
  74632. lineTo (tipX, tipY);
  74633. lineTo (x, arrowY1);
  74634. }
  74635. lineTo (x, y + cs);
  74636. if (cs > 0.0f)
  74637. addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f - PathHelpers::ellipseAngularIncrement);
  74638. closeSubPath();
  74639. }
  74640. }
  74641. void Path::addPath (const Path& other)
  74642. {
  74643. size_t i = 0;
  74644. while (i < other.numElements)
  74645. {
  74646. const float type = other.data.elements [i++];
  74647. if (type == moveMarker)
  74648. {
  74649. startNewSubPath (other.data.elements [i],
  74650. other.data.elements [i + 1]);
  74651. i += 2;
  74652. }
  74653. else if (type == lineMarker)
  74654. {
  74655. lineTo (other.data.elements [i],
  74656. other.data.elements [i + 1]);
  74657. i += 2;
  74658. }
  74659. else if (type == quadMarker)
  74660. {
  74661. quadraticTo (other.data.elements [i],
  74662. other.data.elements [i + 1],
  74663. other.data.elements [i + 2],
  74664. other.data.elements [i + 3]);
  74665. i += 4;
  74666. }
  74667. else if (type == cubicMarker)
  74668. {
  74669. cubicTo (other.data.elements [i],
  74670. other.data.elements [i + 1],
  74671. other.data.elements [i + 2],
  74672. other.data.elements [i + 3],
  74673. other.data.elements [i + 4],
  74674. other.data.elements [i + 5]);
  74675. i += 6;
  74676. }
  74677. else if (type == closeSubPathMarker)
  74678. {
  74679. closeSubPath();
  74680. }
  74681. else
  74682. {
  74683. // something's gone wrong with the element list!
  74684. jassertfalse;
  74685. }
  74686. }
  74687. }
  74688. void Path::addPath (const Path& other,
  74689. const AffineTransform& transformToApply)
  74690. {
  74691. size_t i = 0;
  74692. while (i < other.numElements)
  74693. {
  74694. const float type = other.data.elements [i++];
  74695. if (type == closeSubPathMarker)
  74696. {
  74697. closeSubPath();
  74698. }
  74699. else
  74700. {
  74701. float x = other.data.elements [i++];
  74702. float y = other.data.elements [i++];
  74703. transformToApply.transformPoint (x, y);
  74704. if (type == moveMarker)
  74705. {
  74706. startNewSubPath (x, y);
  74707. }
  74708. else if (type == lineMarker)
  74709. {
  74710. lineTo (x, y);
  74711. }
  74712. else if (type == quadMarker)
  74713. {
  74714. float x2 = other.data.elements [i++];
  74715. float y2 = other.data.elements [i++];
  74716. transformToApply.transformPoint (x2, y2);
  74717. quadraticTo (x, y, x2, y2);
  74718. }
  74719. else if (type == cubicMarker)
  74720. {
  74721. float x2 = other.data.elements [i++];
  74722. float y2 = other.data.elements [i++];
  74723. float x3 = other.data.elements [i++];
  74724. float y3 = other.data.elements [i++];
  74725. transformToApply.transformPoints (x2, y2, x3, y3);
  74726. cubicTo (x, y, x2, y2, x3, y3);
  74727. }
  74728. else
  74729. {
  74730. // something's gone wrong with the element list!
  74731. jassertfalse;
  74732. }
  74733. }
  74734. }
  74735. }
  74736. void Path::applyTransform (const AffineTransform& transform) throw()
  74737. {
  74738. size_t i = 0;
  74739. pathYMin = pathXMin = 0;
  74740. pathYMax = pathXMax = 0;
  74741. bool setMaxMin = false;
  74742. while (i < numElements)
  74743. {
  74744. const float type = data.elements [i++];
  74745. if (type == moveMarker)
  74746. {
  74747. transform.transformPoint (data.elements [i], data.elements [i + 1]);
  74748. if (setMaxMin)
  74749. {
  74750. pathXMin = jmin (pathXMin, data.elements [i]);
  74751. pathXMax = jmax (pathXMax, data.elements [i]);
  74752. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  74753. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  74754. }
  74755. else
  74756. {
  74757. pathXMin = pathXMax = data.elements [i];
  74758. pathYMin = pathYMax = data.elements [i + 1];
  74759. setMaxMin = true;
  74760. }
  74761. i += 2;
  74762. }
  74763. else if (type == lineMarker)
  74764. {
  74765. transform.transformPoint (data.elements [i], data.elements [i + 1]);
  74766. pathXMin = jmin (pathXMin, data.elements [i]);
  74767. pathXMax = jmax (pathXMax, data.elements [i]);
  74768. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  74769. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  74770. i += 2;
  74771. }
  74772. else if (type == quadMarker)
  74773. {
  74774. transform.transformPoints (data.elements [i], data.elements [i + 1],
  74775. data.elements [i + 2], data.elements [i + 3]);
  74776. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2]);
  74777. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2]);
  74778. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3]);
  74779. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3]);
  74780. i += 4;
  74781. }
  74782. else if (type == cubicMarker)
  74783. {
  74784. transform.transformPoints (data.elements [i], data.elements [i + 1],
  74785. data.elements [i + 2], data.elements [i + 3],
  74786. data.elements [i + 4], data.elements [i + 5]);
  74787. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  74788. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  74789. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  74790. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  74791. i += 6;
  74792. }
  74793. }
  74794. }
  74795. const AffineTransform Path::getTransformToScaleToFit (const float x, const float y,
  74796. const float w, const float h,
  74797. const bool preserveProportions,
  74798. const Justification& justification) const
  74799. {
  74800. Rectangle<float> bounds (getBounds());
  74801. if (preserveProportions)
  74802. {
  74803. if (w <= 0 || h <= 0 || bounds.isEmpty())
  74804. return AffineTransform::identity;
  74805. float newW, newH;
  74806. const float srcRatio = bounds.getHeight() / bounds.getWidth();
  74807. if (srcRatio > h / w)
  74808. {
  74809. newW = h / srcRatio;
  74810. newH = h;
  74811. }
  74812. else
  74813. {
  74814. newW = w;
  74815. newH = w * srcRatio;
  74816. }
  74817. float newXCentre = x;
  74818. float newYCentre = y;
  74819. if (justification.testFlags (Justification::left))
  74820. newXCentre += newW * 0.5f;
  74821. else if (justification.testFlags (Justification::right))
  74822. newXCentre += w - newW * 0.5f;
  74823. else
  74824. newXCentre += w * 0.5f;
  74825. if (justification.testFlags (Justification::top))
  74826. newYCentre += newH * 0.5f;
  74827. else if (justification.testFlags (Justification::bottom))
  74828. newYCentre += h - newH * 0.5f;
  74829. else
  74830. newYCentre += h * 0.5f;
  74831. return AffineTransform::translation (bounds.getWidth() * -0.5f - bounds.getX(),
  74832. bounds.getHeight() * -0.5f - bounds.getY())
  74833. .scaled (newW / bounds.getWidth(), newH / bounds.getHeight())
  74834. .translated (newXCentre, newYCentre);
  74835. }
  74836. else
  74837. {
  74838. return AffineTransform::translation (-bounds.getX(), -bounds.getY())
  74839. .scaled (w / bounds.getWidth(), h / bounds.getHeight())
  74840. .translated (x, y);
  74841. }
  74842. }
  74843. bool Path::contains (const float x, const float y, const float tolerence) const
  74844. {
  74845. if (x <= pathXMin || x >= pathXMax
  74846. || y <= pathYMin || y >= pathYMax)
  74847. return false;
  74848. PathFlatteningIterator i (*this, AffineTransform::identity, tolerence);
  74849. int positiveCrossings = 0;
  74850. int negativeCrossings = 0;
  74851. while (i.next())
  74852. {
  74853. if ((i.y1 <= y && i.y2 > y) || (i.y2 <= y && i.y1 > y))
  74854. {
  74855. const float intersectX = i.x1 + (i.x2 - i.x1) * (y - i.y1) / (i.y2 - i.y1);
  74856. if (intersectX <= x)
  74857. {
  74858. if (i.y1 < i.y2)
  74859. ++positiveCrossings;
  74860. else
  74861. ++negativeCrossings;
  74862. }
  74863. }
  74864. }
  74865. return useNonZeroWinding ? (negativeCrossings != positiveCrossings)
  74866. : ((negativeCrossings + positiveCrossings) & 1) != 0;
  74867. }
  74868. bool Path::contains (const Point<float>& point, const float tolerence) const
  74869. {
  74870. return contains (point.getX(), point.getY(), tolerence);
  74871. }
  74872. bool Path::intersectsLine (const Line<float>& line, const float tolerence)
  74873. {
  74874. PathFlatteningIterator i (*this, AffineTransform::identity, tolerence);
  74875. Point<float> intersection;
  74876. while (i.next())
  74877. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  74878. return true;
  74879. return false;
  74880. }
  74881. const Line<float> Path::getClippedLine (const Line<float>& line, const bool keepSectionOutsidePath) const
  74882. {
  74883. Line<float> result (line);
  74884. const bool startInside = contains (line.getStart());
  74885. const bool endInside = contains (line.getEnd());
  74886. if (startInside == endInside)
  74887. {
  74888. if (keepSectionOutsidePath == startInside)
  74889. result = Line<float>();
  74890. }
  74891. else
  74892. {
  74893. PathFlatteningIterator i (*this, AffineTransform::identity);
  74894. Point<float> intersection;
  74895. while (i.next())
  74896. {
  74897. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  74898. {
  74899. if ((startInside && keepSectionOutsidePath) || (endInside && ! keepSectionOutsidePath))
  74900. result.setStart (intersection);
  74901. else
  74902. result.setEnd (intersection);
  74903. }
  74904. }
  74905. }
  74906. return result;
  74907. }
  74908. float Path::getLength (const AffineTransform& transform) const
  74909. {
  74910. float length = 0;
  74911. PathFlatteningIterator i (*this, transform);
  74912. while (i.next())
  74913. length += Line<float> (i.x1, i.y1, i.x2, i.y2).getLength();
  74914. return length;
  74915. }
  74916. const Point<float> Path::getPointAlongPath (float distanceFromStart, const AffineTransform& transform) const
  74917. {
  74918. PathFlatteningIterator i (*this, transform);
  74919. while (i.next())
  74920. {
  74921. const Line<float> line (i.x1, i.y1, i.x2, i.y2);
  74922. const float lineLength = line.getLength();
  74923. if (distanceFromStart <= lineLength)
  74924. return line.getPointAlongLine (distanceFromStart);
  74925. distanceFromStart -= lineLength;
  74926. }
  74927. return Point<float> (i.x2, i.y2);
  74928. }
  74929. float Path::getNearestPoint (const Point<float>& targetPoint, Point<float>& pointOnPath,
  74930. const AffineTransform& transform) const
  74931. {
  74932. PathFlatteningIterator i (*this, transform);
  74933. float bestPosition = 0, bestDistance = std::numeric_limits<float>::max();
  74934. float length = 0;
  74935. Point<float> pointOnLine;
  74936. while (i.next())
  74937. {
  74938. const Line<float> line (i.x1, i.y1, i.x2, i.y2);
  74939. const float distance = line.getDistanceFromPoint (targetPoint, pointOnLine);
  74940. if (distance < bestDistance)
  74941. {
  74942. bestDistance = distance;
  74943. bestPosition = length + pointOnLine.getDistanceFrom (line.getStart());
  74944. pointOnPath = pointOnLine;
  74945. }
  74946. length += line.getLength();
  74947. }
  74948. return bestPosition;
  74949. }
  74950. const Path Path::createPathWithRoundedCorners (const float cornerRadius) const
  74951. {
  74952. if (cornerRadius <= 0.01f)
  74953. return *this;
  74954. size_t indexOfPathStart = 0, indexOfPathStartThis = 0;
  74955. size_t n = 0;
  74956. bool lastWasLine = false, firstWasLine = false;
  74957. Path p;
  74958. while (n < numElements)
  74959. {
  74960. const float type = data.elements [n++];
  74961. if (type == moveMarker)
  74962. {
  74963. indexOfPathStart = p.numElements;
  74964. indexOfPathStartThis = n - 1;
  74965. const float x = data.elements [n++];
  74966. const float y = data.elements [n++];
  74967. p.startNewSubPath (x, y);
  74968. lastWasLine = false;
  74969. firstWasLine = (data.elements [n] == lineMarker);
  74970. }
  74971. else if (type == lineMarker || type == closeSubPathMarker)
  74972. {
  74973. float startX = 0, startY = 0, joinX = 0, joinY = 0, endX, endY;
  74974. if (type == lineMarker)
  74975. {
  74976. endX = data.elements [n++];
  74977. endY = data.elements [n++];
  74978. if (n > 8)
  74979. {
  74980. startX = data.elements [n - 8];
  74981. startY = data.elements [n - 7];
  74982. joinX = data.elements [n - 5];
  74983. joinY = data.elements [n - 4];
  74984. }
  74985. }
  74986. else
  74987. {
  74988. endX = data.elements [indexOfPathStartThis + 1];
  74989. endY = data.elements [indexOfPathStartThis + 2];
  74990. if (n > 6)
  74991. {
  74992. startX = data.elements [n - 6];
  74993. startY = data.elements [n - 5];
  74994. joinX = data.elements [n - 3];
  74995. joinY = data.elements [n - 2];
  74996. }
  74997. }
  74998. if (lastWasLine)
  74999. {
  75000. const double len1 = juce_hypot (startX - joinX,
  75001. startY - joinY);
  75002. if (len1 > 0)
  75003. {
  75004. const double propNeeded = jmin (0.5, cornerRadius / len1);
  75005. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  75006. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  75007. }
  75008. const double len2 = juce_hypot (endX - joinX,
  75009. endY - joinY);
  75010. if (len2 > 0)
  75011. {
  75012. const double propNeeded = jmin (0.5, cornerRadius / len2);
  75013. p.quadraticTo (joinX, joinY,
  75014. (float) (joinX + (endX - joinX) * propNeeded),
  75015. (float) (joinY + (endY - joinY) * propNeeded));
  75016. }
  75017. p.lineTo (endX, endY);
  75018. }
  75019. else if (type == lineMarker)
  75020. {
  75021. p.lineTo (endX, endY);
  75022. lastWasLine = true;
  75023. }
  75024. if (type == closeSubPathMarker)
  75025. {
  75026. if (firstWasLine)
  75027. {
  75028. startX = data.elements [n - 3];
  75029. startY = data.elements [n - 2];
  75030. joinX = endX;
  75031. joinY = endY;
  75032. endX = data.elements [indexOfPathStartThis + 4];
  75033. endY = data.elements [indexOfPathStartThis + 5];
  75034. const double len1 = juce_hypot (startX - joinX,
  75035. startY - joinY);
  75036. if (len1 > 0)
  75037. {
  75038. const double propNeeded = jmin (0.5, cornerRadius / len1);
  75039. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  75040. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  75041. }
  75042. const double len2 = juce_hypot (endX - joinX,
  75043. endY - joinY);
  75044. if (len2 > 0)
  75045. {
  75046. const double propNeeded = jmin (0.5, cornerRadius / len2);
  75047. endX = (float) (joinX + (endX - joinX) * propNeeded);
  75048. endY = (float) (joinY + (endY - joinY) * propNeeded);
  75049. p.quadraticTo (joinX, joinY, endX, endY);
  75050. p.data.elements [indexOfPathStart + 1] = endX;
  75051. p.data.elements [indexOfPathStart + 2] = endY;
  75052. }
  75053. }
  75054. p.closeSubPath();
  75055. }
  75056. }
  75057. else if (type == quadMarker)
  75058. {
  75059. lastWasLine = false;
  75060. const float x1 = data.elements [n++];
  75061. const float y1 = data.elements [n++];
  75062. const float x2 = data.elements [n++];
  75063. const float y2 = data.elements [n++];
  75064. p.quadraticTo (x1, y1, x2, y2);
  75065. }
  75066. else if (type == cubicMarker)
  75067. {
  75068. lastWasLine = false;
  75069. const float x1 = data.elements [n++];
  75070. const float y1 = data.elements [n++];
  75071. const float x2 = data.elements [n++];
  75072. const float y2 = data.elements [n++];
  75073. const float x3 = data.elements [n++];
  75074. const float y3 = data.elements [n++];
  75075. p.cubicTo (x1, y1, x2, y2, x3, y3);
  75076. }
  75077. }
  75078. return p;
  75079. }
  75080. void Path::loadPathFromStream (InputStream& source)
  75081. {
  75082. while (! source.isExhausted())
  75083. {
  75084. switch (source.readByte())
  75085. {
  75086. case 'm':
  75087. {
  75088. const float x = source.readFloat();
  75089. const float y = source.readFloat();
  75090. startNewSubPath (x, y);
  75091. break;
  75092. }
  75093. case 'l':
  75094. {
  75095. const float x = source.readFloat();
  75096. const float y = source.readFloat();
  75097. lineTo (x, y);
  75098. break;
  75099. }
  75100. case 'q':
  75101. {
  75102. const float x1 = source.readFloat();
  75103. const float y1 = source.readFloat();
  75104. const float x2 = source.readFloat();
  75105. const float y2 = source.readFloat();
  75106. quadraticTo (x1, y1, x2, y2);
  75107. break;
  75108. }
  75109. case 'b':
  75110. {
  75111. const float x1 = source.readFloat();
  75112. const float y1 = source.readFloat();
  75113. const float x2 = source.readFloat();
  75114. const float y2 = source.readFloat();
  75115. const float x3 = source.readFloat();
  75116. const float y3 = source.readFloat();
  75117. cubicTo (x1, y1, x2, y2, x3, y3);
  75118. break;
  75119. }
  75120. case 'c':
  75121. closeSubPath();
  75122. break;
  75123. case 'n':
  75124. useNonZeroWinding = true;
  75125. break;
  75126. case 'z':
  75127. useNonZeroWinding = false;
  75128. break;
  75129. case 'e':
  75130. return; // end of path marker
  75131. default:
  75132. jassertfalse; // illegal char in the stream
  75133. break;
  75134. }
  75135. }
  75136. }
  75137. void Path::loadPathFromData (const void* const pathData, const int numberOfBytes)
  75138. {
  75139. MemoryInputStream in (pathData, numberOfBytes, false);
  75140. loadPathFromStream (in);
  75141. }
  75142. void Path::writePathToStream (OutputStream& dest) const
  75143. {
  75144. dest.writeByte (useNonZeroWinding ? 'n' : 'z');
  75145. size_t i = 0;
  75146. while (i < numElements)
  75147. {
  75148. const float type = data.elements [i++];
  75149. if (type == moveMarker)
  75150. {
  75151. dest.writeByte ('m');
  75152. dest.writeFloat (data.elements [i++]);
  75153. dest.writeFloat (data.elements [i++]);
  75154. }
  75155. else if (type == lineMarker)
  75156. {
  75157. dest.writeByte ('l');
  75158. dest.writeFloat (data.elements [i++]);
  75159. dest.writeFloat (data.elements [i++]);
  75160. }
  75161. else if (type == quadMarker)
  75162. {
  75163. dest.writeByte ('q');
  75164. dest.writeFloat (data.elements [i++]);
  75165. dest.writeFloat (data.elements [i++]);
  75166. dest.writeFloat (data.elements [i++]);
  75167. dest.writeFloat (data.elements [i++]);
  75168. }
  75169. else if (type == cubicMarker)
  75170. {
  75171. dest.writeByte ('b');
  75172. dest.writeFloat (data.elements [i++]);
  75173. dest.writeFloat (data.elements [i++]);
  75174. dest.writeFloat (data.elements [i++]);
  75175. dest.writeFloat (data.elements [i++]);
  75176. dest.writeFloat (data.elements [i++]);
  75177. dest.writeFloat (data.elements [i++]);
  75178. }
  75179. else if (type == closeSubPathMarker)
  75180. {
  75181. dest.writeByte ('c');
  75182. }
  75183. }
  75184. dest.writeByte ('e'); // marks the end-of-path
  75185. }
  75186. const String Path::toString() const
  75187. {
  75188. MemoryOutputStream s (2048);
  75189. if (! useNonZeroWinding)
  75190. s << 'a';
  75191. size_t i = 0;
  75192. float lastMarker = 0.0f;
  75193. while (i < numElements)
  75194. {
  75195. const float marker = data.elements [i++];
  75196. char markerChar = 0;
  75197. int numCoords = 0;
  75198. if (marker == moveMarker)
  75199. {
  75200. markerChar = 'm';
  75201. numCoords = 2;
  75202. }
  75203. else if (marker == lineMarker)
  75204. {
  75205. markerChar = 'l';
  75206. numCoords = 2;
  75207. }
  75208. else if (marker == quadMarker)
  75209. {
  75210. markerChar = 'q';
  75211. numCoords = 4;
  75212. }
  75213. else if (marker == cubicMarker)
  75214. {
  75215. markerChar = 'c';
  75216. numCoords = 6;
  75217. }
  75218. else
  75219. {
  75220. jassert (marker == closeSubPathMarker);
  75221. markerChar = 'z';
  75222. }
  75223. if (marker != lastMarker)
  75224. {
  75225. if (s.getDataSize() != 0)
  75226. s << ' ';
  75227. s << markerChar;
  75228. lastMarker = marker;
  75229. }
  75230. while (--numCoords >= 0 && i < numElements)
  75231. {
  75232. String coord (data.elements [i++], 3);
  75233. while (coord.endsWithChar ('0') && coord != "0")
  75234. coord = coord.dropLastCharacters (1);
  75235. if (coord.endsWithChar ('.'))
  75236. coord = coord.dropLastCharacters (1);
  75237. if (s.getDataSize() != 0)
  75238. s << ' ';
  75239. s << coord;
  75240. }
  75241. }
  75242. return s.toUTF8();
  75243. }
  75244. void Path::restoreFromString (const String& stringVersion)
  75245. {
  75246. clear();
  75247. setUsingNonZeroWinding (true);
  75248. const juce_wchar* t = stringVersion;
  75249. juce_wchar marker = 'm';
  75250. int numValues = 2;
  75251. float values [6];
  75252. for (;;)
  75253. {
  75254. const String token (PathHelpers::nextToken (t));
  75255. const juce_wchar firstChar = token[0];
  75256. int startNum = 0;
  75257. if (firstChar == 0)
  75258. break;
  75259. if (firstChar == 'm' || firstChar == 'l')
  75260. {
  75261. marker = firstChar;
  75262. numValues = 2;
  75263. }
  75264. else if (firstChar == 'q')
  75265. {
  75266. marker = firstChar;
  75267. numValues = 4;
  75268. }
  75269. else if (firstChar == 'c')
  75270. {
  75271. marker = firstChar;
  75272. numValues = 6;
  75273. }
  75274. else if (firstChar == 'z')
  75275. {
  75276. marker = firstChar;
  75277. numValues = 0;
  75278. }
  75279. else if (firstChar == 'a')
  75280. {
  75281. setUsingNonZeroWinding (false);
  75282. continue;
  75283. }
  75284. else
  75285. {
  75286. ++startNum;
  75287. values [0] = token.getFloatValue();
  75288. }
  75289. for (int i = startNum; i < numValues; ++i)
  75290. values [i] = PathHelpers::nextToken (t).getFloatValue();
  75291. switch (marker)
  75292. {
  75293. case 'm': startNewSubPath (values[0], values[1]); break;
  75294. case 'l': lineTo (values[0], values[1]); break;
  75295. case 'q': quadraticTo (values[0], values[1], values[2], values[3]); break;
  75296. case 'c': cubicTo (values[0], values[1], values[2], values[3], values[4], values[5]); break;
  75297. case 'z': closeSubPath(); break;
  75298. default: jassertfalse; break; // illegal string format?
  75299. }
  75300. }
  75301. }
  75302. Path::Iterator::Iterator (const Path& path_)
  75303. : path (path_),
  75304. index (0)
  75305. {
  75306. }
  75307. Path::Iterator::~Iterator()
  75308. {
  75309. }
  75310. bool Path::Iterator::next()
  75311. {
  75312. const float* const elements = path.data.elements;
  75313. if (index < path.numElements)
  75314. {
  75315. const float type = elements [index++];
  75316. if (type == moveMarker)
  75317. {
  75318. elementType = startNewSubPath;
  75319. x1 = elements [index++];
  75320. y1 = elements [index++];
  75321. }
  75322. else if (type == lineMarker)
  75323. {
  75324. elementType = lineTo;
  75325. x1 = elements [index++];
  75326. y1 = elements [index++];
  75327. }
  75328. else if (type == quadMarker)
  75329. {
  75330. elementType = quadraticTo;
  75331. x1 = elements [index++];
  75332. y1 = elements [index++];
  75333. x2 = elements [index++];
  75334. y2 = elements [index++];
  75335. }
  75336. else if (type == cubicMarker)
  75337. {
  75338. elementType = cubicTo;
  75339. x1 = elements [index++];
  75340. y1 = elements [index++];
  75341. x2 = elements [index++];
  75342. y2 = elements [index++];
  75343. x3 = elements [index++];
  75344. y3 = elements [index++];
  75345. }
  75346. else if (type == closeSubPathMarker)
  75347. {
  75348. elementType = closePath;
  75349. }
  75350. return true;
  75351. }
  75352. return false;
  75353. }
  75354. END_JUCE_NAMESPACE
  75355. /*** End of inlined file: juce_Path.cpp ***/
  75356. /*** Start of inlined file: juce_PathIterator.cpp ***/
  75357. BEGIN_JUCE_NAMESPACE
  75358. #if JUCE_MSVC && JUCE_DEBUG
  75359. #pragma optimize ("t", on)
  75360. #endif
  75361. PathFlatteningIterator::PathFlatteningIterator (const Path& path_,
  75362. const AffineTransform& transform_,
  75363. float tolerence_)
  75364. : x2 (0),
  75365. y2 (0),
  75366. closesSubPath (false),
  75367. subPathIndex (-1),
  75368. path (path_),
  75369. transform (transform_),
  75370. points (path_.data.elements),
  75371. tolerence (tolerence_ * tolerence_),
  75372. subPathCloseX (0),
  75373. subPathCloseY (0),
  75374. isIdentityTransform (transform_.isIdentity()),
  75375. stackBase (32),
  75376. index (0),
  75377. stackSize (32)
  75378. {
  75379. stackPos = stackBase;
  75380. }
  75381. PathFlatteningIterator::~PathFlatteningIterator()
  75382. {
  75383. }
  75384. bool PathFlatteningIterator::next()
  75385. {
  75386. x1 = x2;
  75387. y1 = y2;
  75388. float x3 = 0;
  75389. float y3 = 0;
  75390. float x4 = 0;
  75391. float y4 = 0;
  75392. float type;
  75393. for (;;)
  75394. {
  75395. if (stackPos == stackBase)
  75396. {
  75397. if (index >= path.numElements)
  75398. {
  75399. return false;
  75400. }
  75401. else
  75402. {
  75403. type = points [index++];
  75404. if (type != Path::closeSubPathMarker)
  75405. {
  75406. x2 = points [index++];
  75407. y2 = points [index++];
  75408. if (type == Path::quadMarker)
  75409. {
  75410. x3 = points [index++];
  75411. y3 = points [index++];
  75412. if (! isIdentityTransform)
  75413. transform.transformPoints (x2, y2, x3, y3);
  75414. }
  75415. else if (type == Path::cubicMarker)
  75416. {
  75417. x3 = points [index++];
  75418. y3 = points [index++];
  75419. x4 = points [index++];
  75420. y4 = points [index++];
  75421. if (! isIdentityTransform)
  75422. transform.transformPoints (x2, y2, x3, y3, x4, y4);
  75423. }
  75424. else
  75425. {
  75426. if (! isIdentityTransform)
  75427. transform.transformPoint (x2, y2);
  75428. }
  75429. }
  75430. }
  75431. }
  75432. else
  75433. {
  75434. type = *--stackPos;
  75435. if (type != Path::closeSubPathMarker)
  75436. {
  75437. x2 = *--stackPos;
  75438. y2 = *--stackPos;
  75439. if (type == Path::quadMarker)
  75440. {
  75441. x3 = *--stackPos;
  75442. y3 = *--stackPos;
  75443. }
  75444. else if (type == Path::cubicMarker)
  75445. {
  75446. x3 = *--stackPos;
  75447. y3 = *--stackPos;
  75448. x4 = *--stackPos;
  75449. y4 = *--stackPos;
  75450. }
  75451. }
  75452. }
  75453. if (type == Path::lineMarker)
  75454. {
  75455. ++subPathIndex;
  75456. closesSubPath = (stackPos == stackBase)
  75457. && (index < path.numElements)
  75458. && (points [index] == Path::closeSubPathMarker)
  75459. && x2 == subPathCloseX
  75460. && y2 == subPathCloseY;
  75461. return true;
  75462. }
  75463. else if (type == Path::quadMarker)
  75464. {
  75465. const size_t offset = (size_t) (stackPos - stackBase);
  75466. if (offset >= stackSize - 10)
  75467. {
  75468. stackSize <<= 1;
  75469. stackBase.realloc (stackSize);
  75470. stackPos = stackBase + offset;
  75471. }
  75472. const float dx1 = x1 - x2;
  75473. const float dy1 = y1 - y2;
  75474. const float dx2 = x2 - x3;
  75475. const float dy2 = y2 - y3;
  75476. const float m1x = (x1 + x2) * 0.5f;
  75477. const float m1y = (y1 + y2) * 0.5f;
  75478. const float m2x = (x2 + x3) * 0.5f;
  75479. const float m2y = (y2 + y3) * 0.5f;
  75480. const float m3x = (m1x + m2x) * 0.5f;
  75481. const float m3y = (m1y + m2y) * 0.5f;
  75482. if (dx1*dx1 + dy1*dy1 + dx2*dx2 + dy2*dy2 > tolerence)
  75483. {
  75484. *stackPos++ = y3;
  75485. *stackPos++ = x3;
  75486. *stackPos++ = m2y;
  75487. *stackPos++ = m2x;
  75488. *stackPos++ = Path::quadMarker;
  75489. *stackPos++ = m3y;
  75490. *stackPos++ = m3x;
  75491. *stackPos++ = m1y;
  75492. *stackPos++ = m1x;
  75493. *stackPos++ = Path::quadMarker;
  75494. }
  75495. else
  75496. {
  75497. *stackPos++ = y3;
  75498. *stackPos++ = x3;
  75499. *stackPos++ = Path::lineMarker;
  75500. *stackPos++ = m3y;
  75501. *stackPos++ = m3x;
  75502. *stackPos++ = Path::lineMarker;
  75503. }
  75504. jassert (stackPos < stackBase + stackSize);
  75505. }
  75506. else if (type == Path::cubicMarker)
  75507. {
  75508. const size_t offset = (size_t) (stackPos - stackBase);
  75509. if (offset >= stackSize - 16)
  75510. {
  75511. stackSize <<= 1;
  75512. stackBase.realloc (stackSize);
  75513. stackPos = stackBase + offset;
  75514. }
  75515. const float dx1 = x1 - x2;
  75516. const float dy1 = y1 - y2;
  75517. const float dx2 = x2 - x3;
  75518. const float dy2 = y2 - y3;
  75519. const float dx3 = x3 - x4;
  75520. const float dy3 = y3 - y4;
  75521. const float m1x = (x1 + x2) * 0.5f;
  75522. const float m1y = (y1 + y2) * 0.5f;
  75523. const float m2x = (x3 + x2) * 0.5f;
  75524. const float m2y = (y3 + y2) * 0.5f;
  75525. const float m3x = (x3 + x4) * 0.5f;
  75526. const float m3y = (y3 + y4) * 0.5f;
  75527. const float m4x = (m1x + m2x) * 0.5f;
  75528. const float m4y = (m1y + m2y) * 0.5f;
  75529. const float m5x = (m3x + m2x) * 0.5f;
  75530. const float m5y = (m3y + m2y) * 0.5f;
  75531. if (dx1*dx1 + dy1*dy1 + dx2*dx2
  75532. + dy2*dy2 + dx3*dx3 + dy3*dy3 > tolerence)
  75533. {
  75534. *stackPos++ = y4;
  75535. *stackPos++ = x4;
  75536. *stackPos++ = m3y;
  75537. *stackPos++ = m3x;
  75538. *stackPos++ = m5y;
  75539. *stackPos++ = m5x;
  75540. *stackPos++ = Path::cubicMarker;
  75541. *stackPos++ = (m4y + m5y) * 0.5f;
  75542. *stackPos++ = (m4x + m5x) * 0.5f;
  75543. *stackPos++ = m4y;
  75544. *stackPos++ = m4x;
  75545. *stackPos++ = m1y;
  75546. *stackPos++ = m1x;
  75547. *stackPos++ = Path::cubicMarker;
  75548. }
  75549. else
  75550. {
  75551. *stackPos++ = y4;
  75552. *stackPos++ = x4;
  75553. *stackPos++ = Path::lineMarker;
  75554. *stackPos++ = m5y;
  75555. *stackPos++ = m5x;
  75556. *stackPos++ = Path::lineMarker;
  75557. *stackPos++ = m4y;
  75558. *stackPos++ = m4x;
  75559. *stackPos++ = Path::lineMarker;
  75560. }
  75561. }
  75562. else if (type == Path::closeSubPathMarker)
  75563. {
  75564. if (x2 != subPathCloseX || y2 != subPathCloseY)
  75565. {
  75566. x1 = x2;
  75567. y1 = y2;
  75568. x2 = subPathCloseX;
  75569. y2 = subPathCloseY;
  75570. closesSubPath = true;
  75571. return true;
  75572. }
  75573. }
  75574. else
  75575. {
  75576. jassert (type == Path::moveMarker);
  75577. subPathIndex = -1;
  75578. subPathCloseX = x1 = x2;
  75579. subPathCloseY = y1 = y2;
  75580. }
  75581. }
  75582. }
  75583. #if JUCE_MSVC && JUCE_DEBUG
  75584. #pragma optimize ("", on) // resets optimisations to the project defaults
  75585. #endif
  75586. END_JUCE_NAMESPACE
  75587. /*** End of inlined file: juce_PathIterator.cpp ***/
  75588. /*** Start of inlined file: juce_PathStrokeType.cpp ***/
  75589. BEGIN_JUCE_NAMESPACE
  75590. PathStrokeType::PathStrokeType (const float strokeThickness,
  75591. const JointStyle jointStyle_,
  75592. const EndCapStyle endStyle_) throw()
  75593. : thickness (strokeThickness),
  75594. jointStyle (jointStyle_),
  75595. endStyle (endStyle_)
  75596. {
  75597. }
  75598. PathStrokeType::PathStrokeType (const PathStrokeType& other) throw()
  75599. : thickness (other.thickness),
  75600. jointStyle (other.jointStyle),
  75601. endStyle (other.endStyle)
  75602. {
  75603. }
  75604. PathStrokeType& PathStrokeType::operator= (const PathStrokeType& other) throw()
  75605. {
  75606. thickness = other.thickness;
  75607. jointStyle = other.jointStyle;
  75608. endStyle = other.endStyle;
  75609. return *this;
  75610. }
  75611. PathStrokeType::~PathStrokeType() throw()
  75612. {
  75613. }
  75614. bool PathStrokeType::operator== (const PathStrokeType& other) const throw()
  75615. {
  75616. return thickness == other.thickness
  75617. && jointStyle == other.jointStyle
  75618. && endStyle == other.endStyle;
  75619. }
  75620. bool PathStrokeType::operator!= (const PathStrokeType& other) const throw()
  75621. {
  75622. return ! operator== (other);
  75623. }
  75624. namespace PathStrokeHelpers
  75625. {
  75626. static bool lineIntersection (const float x1, const float y1,
  75627. const float x2, const float y2,
  75628. const float x3, const float y3,
  75629. const float x4, const float y4,
  75630. float& intersectionX,
  75631. float& intersectionY,
  75632. float& distanceBeyondLine1EndSquared) throw()
  75633. {
  75634. if (x2 != x3 || y2 != y3)
  75635. {
  75636. const float dx1 = x2 - x1;
  75637. const float dy1 = y2 - y1;
  75638. const float dx2 = x4 - x3;
  75639. const float dy2 = y4 - y3;
  75640. const float divisor = dx1 * dy2 - dx2 * dy1;
  75641. if (divisor == 0)
  75642. {
  75643. if (! ((dx1 == 0 && dy1 == 0) || (dx2 == 0 && dy2 == 0)))
  75644. {
  75645. if (dy1 == 0 && dy2 != 0)
  75646. {
  75647. const float along = (y1 - y3) / dy2;
  75648. intersectionX = x3 + along * dx2;
  75649. intersectionY = y1;
  75650. distanceBeyondLine1EndSquared = intersectionX - x2;
  75651. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75652. if ((x2 > x1) == (intersectionX < x2))
  75653. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75654. return along >= 0 && along <= 1.0f;
  75655. }
  75656. else if (dy2 == 0 && dy1 != 0)
  75657. {
  75658. const float along = (y3 - y1) / dy1;
  75659. intersectionX = x1 + along * dx1;
  75660. intersectionY = y3;
  75661. distanceBeyondLine1EndSquared = (along - 1.0f) * dx1;
  75662. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75663. if (along < 1.0f)
  75664. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75665. return along >= 0 && along <= 1.0f;
  75666. }
  75667. else if (dx1 == 0 && dx2 != 0)
  75668. {
  75669. const float along = (x1 - x3) / dx2;
  75670. intersectionX = x1;
  75671. intersectionY = y3 + along * dy2;
  75672. distanceBeyondLine1EndSquared = intersectionY - y2;
  75673. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75674. if ((y2 > y1) == (intersectionY < y2))
  75675. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75676. return along >= 0 && along <= 1.0f;
  75677. }
  75678. else if (dx2 == 0 && dx1 != 0)
  75679. {
  75680. const float along = (x3 - x1) / dx1;
  75681. intersectionX = x3;
  75682. intersectionY = y1 + along * dy1;
  75683. distanceBeyondLine1EndSquared = (along - 1.0f) * dy1;
  75684. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75685. if (along < 1.0f)
  75686. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75687. return along >= 0 && along <= 1.0f;
  75688. }
  75689. }
  75690. intersectionX = 0.5f * (x2 + x3);
  75691. intersectionY = 0.5f * (y2 + y3);
  75692. distanceBeyondLine1EndSquared = 0.0f;
  75693. return false;
  75694. }
  75695. else
  75696. {
  75697. const float along1 = ((y1 - y3) * dx2 - (x1 - x3) * dy2) / divisor;
  75698. intersectionX = x1 + along1 * dx1;
  75699. intersectionY = y1 + along1 * dy1;
  75700. if (along1 >= 0 && along1 <= 1.0f)
  75701. {
  75702. const float along2 = ((y1 - y3) * dx1 - (x1 - x3) * dy1);
  75703. if (along2 >= 0 && along2 <= divisor)
  75704. {
  75705. distanceBeyondLine1EndSquared = 0.0f;
  75706. return true;
  75707. }
  75708. }
  75709. distanceBeyondLine1EndSquared = along1 - 1.0f;
  75710. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75711. distanceBeyondLine1EndSquared *= (dx1 * dx1 + dy1 * dy1);
  75712. if (along1 < 1.0f)
  75713. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75714. return false;
  75715. }
  75716. }
  75717. intersectionX = x2;
  75718. intersectionY = y2;
  75719. distanceBeyondLine1EndSquared = 0.0f;
  75720. return true;
  75721. }
  75722. static void addEdgeAndJoint (Path& destPath,
  75723. const PathStrokeType::JointStyle style,
  75724. const float maxMiterExtensionSquared, const float width,
  75725. const float x1, const float y1,
  75726. const float x2, const float y2,
  75727. const float x3, const float y3,
  75728. const float x4, const float y4,
  75729. const float midX, const float midY)
  75730. {
  75731. if (style == PathStrokeType::beveled
  75732. || (x3 == x4 && y3 == y4)
  75733. || (x1 == x2 && y1 == y2))
  75734. {
  75735. destPath.lineTo (x2, y2);
  75736. destPath.lineTo (x3, y3);
  75737. }
  75738. else
  75739. {
  75740. float jx, jy, distanceBeyondLine1EndSquared;
  75741. // if they intersect, use this point..
  75742. if (lineIntersection (x1, y1, x2, y2,
  75743. x3, y3, x4, y4,
  75744. jx, jy, distanceBeyondLine1EndSquared))
  75745. {
  75746. destPath.lineTo (jx, jy);
  75747. }
  75748. else
  75749. {
  75750. if (style == PathStrokeType::mitered)
  75751. {
  75752. if (distanceBeyondLine1EndSquared < maxMiterExtensionSquared
  75753. && distanceBeyondLine1EndSquared > 0.0f)
  75754. {
  75755. destPath.lineTo (jx, jy);
  75756. }
  75757. else
  75758. {
  75759. // the end sticks out too far, so just use a blunt joint
  75760. destPath.lineTo (x2, y2);
  75761. destPath.lineTo (x3, y3);
  75762. }
  75763. }
  75764. else
  75765. {
  75766. // curved joints
  75767. float angle1 = std::atan2 (x2 - midX, y2 - midY);
  75768. float angle2 = std::atan2 (x3 - midX, y3 - midY);
  75769. const float angleIncrement = 0.1f;
  75770. destPath.lineTo (x2, y2);
  75771. if (std::abs (angle1 - angle2) > angleIncrement)
  75772. {
  75773. if (angle2 > angle1 + float_Pi
  75774. || (angle2 < angle1 && angle2 >= angle1 - float_Pi))
  75775. {
  75776. if (angle2 > angle1)
  75777. angle2 -= float_Pi * 2.0f;
  75778. jassert (angle1 <= angle2 + float_Pi);
  75779. angle1 -= angleIncrement;
  75780. while (angle1 > angle2)
  75781. {
  75782. destPath.lineTo (midX + width * std::sin (angle1),
  75783. midY + width * std::cos (angle1));
  75784. angle1 -= angleIncrement;
  75785. }
  75786. }
  75787. else
  75788. {
  75789. if (angle1 > angle2)
  75790. angle1 -= float_Pi * 2.0f;
  75791. jassert (angle1 >= angle2 - float_Pi);
  75792. angle1 += angleIncrement;
  75793. while (angle1 < angle2)
  75794. {
  75795. destPath.lineTo (midX + width * std::sin (angle1),
  75796. midY + width * std::cos (angle1));
  75797. angle1 += angleIncrement;
  75798. }
  75799. }
  75800. }
  75801. destPath.lineTo (x3, y3);
  75802. }
  75803. }
  75804. }
  75805. }
  75806. static void addLineEnd (Path& destPath,
  75807. const PathStrokeType::EndCapStyle style,
  75808. const float x1, const float y1,
  75809. const float x2, const float y2,
  75810. const float width)
  75811. {
  75812. if (style == PathStrokeType::butt)
  75813. {
  75814. destPath.lineTo (x2, y2);
  75815. }
  75816. else
  75817. {
  75818. float offx1, offy1, offx2, offy2;
  75819. float dx = x2 - x1;
  75820. float dy = y2 - y1;
  75821. const float len = juce_hypotf (dx, dy);
  75822. if (len == 0)
  75823. {
  75824. offx1 = offx2 = x1;
  75825. offy1 = offy2 = y1;
  75826. }
  75827. else
  75828. {
  75829. const float offset = width / len;
  75830. dx *= offset;
  75831. dy *= offset;
  75832. offx1 = x1 + dy;
  75833. offy1 = y1 - dx;
  75834. offx2 = x2 + dy;
  75835. offy2 = y2 - dx;
  75836. }
  75837. if (style == PathStrokeType::square)
  75838. {
  75839. // sqaure ends
  75840. destPath.lineTo (offx1, offy1);
  75841. destPath.lineTo (offx2, offy2);
  75842. destPath.lineTo (x2, y2);
  75843. }
  75844. else
  75845. {
  75846. // rounded ends
  75847. const float midx = (offx1 + offx2) * 0.5f;
  75848. const float midy = (offy1 + offy2) * 0.5f;
  75849. destPath.cubicTo (x1 + (offx1 - x1) * 0.55f, y1 + (offy1 - y1) * 0.55f,
  75850. offx1 + (midx - offx1) * 0.45f, offy1 + (midy - offy1) * 0.45f,
  75851. midx, midy);
  75852. destPath.cubicTo (midx + (offx2 - midx) * 0.55f, midy + (offy2 - midy) * 0.55f,
  75853. offx2 + (x2 - offx2) * 0.45f, offy2 + (y2 - offy2) * 0.45f,
  75854. x2, y2);
  75855. }
  75856. }
  75857. }
  75858. struct Arrowhead
  75859. {
  75860. float startWidth, startLength;
  75861. float endWidth, endLength;
  75862. };
  75863. static void addArrowhead (Path& destPath,
  75864. const float x1, const float y1,
  75865. const float x2, const float y2,
  75866. const float tipX, const float tipY,
  75867. const float width,
  75868. const float arrowheadWidth)
  75869. {
  75870. Line<float> line (x1, y1, x2, y2);
  75871. destPath.lineTo (line.getPointAlongLine (-(arrowheadWidth / 2.0f - width), 0));
  75872. destPath.lineTo (tipX, tipY);
  75873. destPath.lineTo (line.getPointAlongLine (arrowheadWidth - (arrowheadWidth / 2.0f - width), 0));
  75874. destPath.lineTo (x2, y2);
  75875. }
  75876. struct LineSection
  75877. {
  75878. float x1, y1, x2, y2; // original line
  75879. float lx1, ly1, lx2, ly2; // the left-hand stroke
  75880. float rx1, ry1, rx2, ry2; // the right-hand stroke
  75881. };
  75882. static void shortenSubPath (Array<LineSection>& subPath, float amountAtStart, float amountAtEnd)
  75883. {
  75884. while (amountAtEnd > 0 && subPath.size() > 0)
  75885. {
  75886. LineSection& l = subPath.getReference (subPath.size() - 1);
  75887. float dx = l.rx2 - l.rx1;
  75888. float dy = l.ry2 - l.ry1;
  75889. const float len = juce_hypotf (dx, dy);
  75890. if (len <= amountAtEnd && subPath.size() > 1)
  75891. {
  75892. LineSection& prev = subPath.getReference (subPath.size() - 2);
  75893. prev.x2 = l.x2;
  75894. prev.y2 = l.y2;
  75895. subPath.removeLast();
  75896. amountAtEnd -= len;
  75897. }
  75898. else
  75899. {
  75900. const float prop = jmin (0.9999f, amountAtEnd / len);
  75901. dx *= prop;
  75902. dy *= prop;
  75903. l.rx1 += dx;
  75904. l.ry1 += dy;
  75905. l.lx2 += dx;
  75906. l.ly2 += dy;
  75907. break;
  75908. }
  75909. }
  75910. while (amountAtStart > 0 && subPath.size() > 0)
  75911. {
  75912. LineSection& l = subPath.getReference (0);
  75913. float dx = l.rx2 - l.rx1;
  75914. float dy = l.ry2 - l.ry1;
  75915. const float len = juce_hypotf (dx, dy);
  75916. if (len <= amountAtStart && subPath.size() > 1)
  75917. {
  75918. LineSection& next = subPath.getReference (1);
  75919. next.x1 = l.x1;
  75920. next.y1 = l.y1;
  75921. subPath.remove (0);
  75922. amountAtStart -= len;
  75923. }
  75924. else
  75925. {
  75926. const float prop = jmin (0.9999f, amountAtStart / len);
  75927. dx *= prop;
  75928. dy *= prop;
  75929. l.rx2 -= dx;
  75930. l.ry2 -= dy;
  75931. l.lx1 -= dx;
  75932. l.ly1 -= dy;
  75933. break;
  75934. }
  75935. }
  75936. }
  75937. static void addSubPath (Path& destPath, Array<LineSection>& subPath,
  75938. const bool isClosed, const float width, const float maxMiterExtensionSquared,
  75939. const PathStrokeType::JointStyle jointStyle, const PathStrokeType::EndCapStyle endStyle,
  75940. const Arrowhead* const arrowhead)
  75941. {
  75942. jassert (subPath.size() > 0);
  75943. if (arrowhead != 0)
  75944. shortenSubPath (subPath, arrowhead->startLength, arrowhead->endLength);
  75945. const LineSection& firstLine = subPath.getReference (0);
  75946. float lastX1 = firstLine.lx1;
  75947. float lastY1 = firstLine.ly1;
  75948. float lastX2 = firstLine.lx2;
  75949. float lastY2 = firstLine.ly2;
  75950. if (isClosed)
  75951. {
  75952. destPath.startNewSubPath (lastX1, lastY1);
  75953. }
  75954. else
  75955. {
  75956. destPath.startNewSubPath (firstLine.rx2, firstLine.ry2);
  75957. if (arrowhead != 0)
  75958. addArrowhead (destPath, firstLine.rx2, firstLine.ry2, lastX1, lastY1, firstLine.x1, firstLine.y1,
  75959. width, arrowhead->startWidth);
  75960. else
  75961. addLineEnd (destPath, endStyle, firstLine.rx2, firstLine.ry2, lastX1, lastY1, width);
  75962. }
  75963. int i;
  75964. for (i = 1; i < subPath.size(); ++i)
  75965. {
  75966. const LineSection& l = subPath.getReference (i);
  75967. addEdgeAndJoint (destPath, jointStyle,
  75968. maxMiterExtensionSquared, width,
  75969. lastX1, lastY1, lastX2, lastY2,
  75970. l.lx1, l.ly1, l.lx2, l.ly2,
  75971. l.x1, l.y1);
  75972. lastX1 = l.lx1;
  75973. lastY1 = l.ly1;
  75974. lastX2 = l.lx2;
  75975. lastY2 = l.ly2;
  75976. }
  75977. const LineSection& lastLine = subPath.getReference (subPath.size() - 1);
  75978. if (isClosed)
  75979. {
  75980. const LineSection& l = subPath.getReference (0);
  75981. addEdgeAndJoint (destPath, jointStyle,
  75982. maxMiterExtensionSquared, width,
  75983. lastX1, lastY1, lastX2, lastY2,
  75984. l.lx1, l.ly1, l.lx2, l.ly2,
  75985. l.x1, l.y1);
  75986. destPath.closeSubPath();
  75987. destPath.startNewSubPath (lastLine.rx1, lastLine.ry1);
  75988. }
  75989. else
  75990. {
  75991. destPath.lineTo (lastX2, lastY2);
  75992. if (arrowhead != 0)
  75993. addArrowhead (destPath, lastX2, lastY2, lastLine.rx1, lastLine.ry1, lastLine.x2, lastLine.y2,
  75994. width, arrowhead->endWidth);
  75995. else
  75996. addLineEnd (destPath, endStyle, lastX2, lastY2, lastLine.rx1, lastLine.ry1, width);
  75997. }
  75998. lastX1 = lastLine.rx1;
  75999. lastY1 = lastLine.ry1;
  76000. lastX2 = lastLine.rx2;
  76001. lastY2 = lastLine.ry2;
  76002. for (i = subPath.size() - 1; --i >= 0;)
  76003. {
  76004. const LineSection& l = subPath.getReference (i);
  76005. addEdgeAndJoint (destPath, jointStyle,
  76006. maxMiterExtensionSquared, width,
  76007. lastX1, lastY1, lastX2, lastY2,
  76008. l.rx1, l.ry1, l.rx2, l.ry2,
  76009. l.x2, l.y2);
  76010. lastX1 = l.rx1;
  76011. lastY1 = l.ry1;
  76012. lastX2 = l.rx2;
  76013. lastY2 = l.ry2;
  76014. }
  76015. if (isClosed)
  76016. {
  76017. addEdgeAndJoint (destPath, jointStyle,
  76018. maxMiterExtensionSquared, width,
  76019. lastX1, lastY1, lastX2, lastY2,
  76020. lastLine.rx1, lastLine.ry1, lastLine.rx2, lastLine.ry2,
  76021. lastLine.x2, lastLine.y2);
  76022. }
  76023. else
  76024. {
  76025. // do the last line
  76026. destPath.lineTo (lastX2, lastY2);
  76027. }
  76028. destPath.closeSubPath();
  76029. }
  76030. static void createStroke (const float thickness, const PathStrokeType::JointStyle jointStyle,
  76031. const PathStrokeType::EndCapStyle endStyle,
  76032. Path& destPath, const Path& source,
  76033. const AffineTransform& transform,
  76034. const float extraAccuracy, const Arrowhead* const arrowhead)
  76035. {
  76036. if (thickness <= 0)
  76037. {
  76038. destPath.clear();
  76039. return;
  76040. }
  76041. const Path* sourcePath = &source;
  76042. Path temp;
  76043. if (sourcePath == &destPath)
  76044. {
  76045. destPath.swapWithPath (temp);
  76046. sourcePath = &temp;
  76047. }
  76048. else
  76049. {
  76050. destPath.clear();
  76051. }
  76052. destPath.setUsingNonZeroWinding (true);
  76053. const float maxMiterExtensionSquared = 9.0f * thickness * thickness;
  76054. const float width = 0.5f * thickness;
  76055. // Iterate the path, creating a list of the
  76056. // left/right-hand lines along either side of it...
  76057. PathFlatteningIterator it (*sourcePath, transform, 9.0f / extraAccuracy);
  76058. Array <LineSection> subPath;
  76059. subPath.ensureStorageAllocated (512);
  76060. LineSection l;
  76061. l.x1 = 0;
  76062. l.y1 = 0;
  76063. const float minSegmentLength = 2.0f / (extraAccuracy * extraAccuracy);
  76064. while (it.next())
  76065. {
  76066. if (it.subPathIndex == 0)
  76067. {
  76068. if (subPath.size() > 0)
  76069. {
  76070. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  76071. subPath.clearQuick();
  76072. }
  76073. l.x1 = it.x1;
  76074. l.y1 = it.y1;
  76075. }
  76076. l.x2 = it.x2;
  76077. l.y2 = it.y2;
  76078. float dx = l.x2 - l.x1;
  76079. float dy = l.y2 - l.y1;
  76080. const float hypotSquared = dx*dx + dy*dy;
  76081. if (it.closesSubPath || hypotSquared > minSegmentLength || it.isLastInSubpath())
  76082. {
  76083. const float len = std::sqrt (hypotSquared);
  76084. if (len == 0)
  76085. {
  76086. l.rx1 = l.rx2 = l.lx1 = l.lx2 = l.x1;
  76087. l.ry1 = l.ry2 = l.ly1 = l.ly2 = l.y1;
  76088. }
  76089. else
  76090. {
  76091. const float offset = width / len;
  76092. dx *= offset;
  76093. dy *= offset;
  76094. l.rx2 = l.x1 - dy;
  76095. l.ry2 = l.y1 + dx;
  76096. l.lx1 = l.x1 + dy;
  76097. l.ly1 = l.y1 - dx;
  76098. l.lx2 = l.x2 + dy;
  76099. l.ly2 = l.y2 - dx;
  76100. l.rx1 = l.x2 - dy;
  76101. l.ry1 = l.y2 + dx;
  76102. }
  76103. subPath.add (l);
  76104. if (it.closesSubPath)
  76105. {
  76106. addSubPath (destPath, subPath, true, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  76107. subPath.clearQuick();
  76108. }
  76109. else
  76110. {
  76111. l.x1 = it.x2;
  76112. l.y1 = it.y2;
  76113. }
  76114. }
  76115. }
  76116. if (subPath.size() > 0)
  76117. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  76118. }
  76119. }
  76120. void PathStrokeType::createStrokedPath (Path& destPath, const Path& sourcePath,
  76121. const AffineTransform& transform, const float extraAccuracy) const
  76122. {
  76123. PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle, destPath, sourcePath,
  76124. transform, extraAccuracy, 0);
  76125. }
  76126. void PathStrokeType::createDashedStroke (Path& destPath,
  76127. const Path& sourcePath,
  76128. const float* dashLengths,
  76129. int numDashLengths,
  76130. const AffineTransform& transform,
  76131. const float extraAccuracy) const
  76132. {
  76133. if (thickness <= 0)
  76134. return;
  76135. // this should really be an even number..
  76136. jassert ((numDashLengths & 1) == 0);
  76137. Path newDestPath;
  76138. PathFlatteningIterator it (sourcePath, transform, 9.0f / extraAccuracy);
  76139. bool first = true;
  76140. int dashNum = 0;
  76141. float pos = 0.0f, lineLen = 0.0f, lineEndPos = 0.0f;
  76142. float dx = 0.0f, dy = 0.0f;
  76143. for (;;)
  76144. {
  76145. const bool isSolid = ((dashNum & 1) == 0);
  76146. const float dashLen = dashLengths [dashNum++ % numDashLengths];
  76147. jassert (dashLen > 0); // must be a positive increment!
  76148. if (dashLen <= 0)
  76149. break;
  76150. pos += dashLen;
  76151. while (pos > lineEndPos)
  76152. {
  76153. if (! it.next())
  76154. {
  76155. if (isSolid && ! first)
  76156. newDestPath.lineTo (it.x2, it.y2);
  76157. createStrokedPath (destPath, newDestPath, AffineTransform::identity, extraAccuracy);
  76158. return;
  76159. }
  76160. if (isSolid && ! first)
  76161. newDestPath.lineTo (it.x1, it.y1);
  76162. else
  76163. newDestPath.startNewSubPath (it.x1, it.y1);
  76164. dx = it.x2 - it.x1;
  76165. dy = it.y2 - it.y1;
  76166. lineLen = juce_hypotf (dx, dy);
  76167. lineEndPos += lineLen;
  76168. first = it.closesSubPath;
  76169. }
  76170. const float alpha = (pos - (lineEndPos - lineLen)) / lineLen;
  76171. if (isSolid)
  76172. newDestPath.lineTo (it.x1 + dx * alpha,
  76173. it.y1 + dy * alpha);
  76174. else
  76175. newDestPath.startNewSubPath (it.x1 + dx * alpha,
  76176. it.y1 + dy * alpha);
  76177. }
  76178. }
  76179. void PathStrokeType::createStrokeWithArrowheads (Path& destPath,
  76180. const Path& sourcePath,
  76181. const float arrowheadStartWidth, const float arrowheadStartLength,
  76182. const float arrowheadEndWidth, const float arrowheadEndLength,
  76183. const AffineTransform& transform,
  76184. const float extraAccuracy) const
  76185. {
  76186. PathStrokeHelpers::Arrowhead head;
  76187. head.startWidth = arrowheadStartWidth;
  76188. head.startLength = arrowheadStartLength;
  76189. head.endWidth = arrowheadEndWidth;
  76190. head.endLength = arrowheadEndLength;
  76191. PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle,
  76192. destPath, sourcePath, transform, extraAccuracy, &head);
  76193. }
  76194. END_JUCE_NAMESPACE
  76195. /*** End of inlined file: juce_PathStrokeType.cpp ***/
  76196. /*** Start of inlined file: juce_PositionedRectangle.cpp ***/
  76197. BEGIN_JUCE_NAMESPACE
  76198. PositionedRectangle::PositionedRectangle() throw()
  76199. : x (0.0),
  76200. y (0.0),
  76201. w (0.0),
  76202. h (0.0),
  76203. xMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  76204. yMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  76205. wMode (absoluteSize),
  76206. hMode (absoluteSize)
  76207. {
  76208. }
  76209. PositionedRectangle::PositionedRectangle (const PositionedRectangle& other) throw()
  76210. : x (other.x),
  76211. y (other.y),
  76212. w (other.w),
  76213. h (other.h),
  76214. xMode (other.xMode),
  76215. yMode (other.yMode),
  76216. wMode (other.wMode),
  76217. hMode (other.hMode)
  76218. {
  76219. }
  76220. PositionedRectangle& PositionedRectangle::operator= (const PositionedRectangle& other) throw()
  76221. {
  76222. x = other.x;
  76223. y = other.y;
  76224. w = other.w;
  76225. h = other.h;
  76226. xMode = other.xMode;
  76227. yMode = other.yMode;
  76228. wMode = other.wMode;
  76229. hMode = other.hMode;
  76230. return *this;
  76231. }
  76232. PositionedRectangle::~PositionedRectangle() throw()
  76233. {
  76234. }
  76235. bool PositionedRectangle::operator== (const PositionedRectangle& other) const throw()
  76236. {
  76237. return x == other.x
  76238. && y == other.y
  76239. && w == other.w
  76240. && h == other.h
  76241. && xMode == other.xMode
  76242. && yMode == other.yMode
  76243. && wMode == other.wMode
  76244. && hMode == other.hMode;
  76245. }
  76246. bool PositionedRectangle::operator!= (const PositionedRectangle& other) const throw()
  76247. {
  76248. return ! operator== (other);
  76249. }
  76250. PositionedRectangle::PositionedRectangle (const String& stringVersion) throw()
  76251. {
  76252. StringArray tokens;
  76253. tokens.addTokens (stringVersion, false);
  76254. decodePosString (tokens [0], xMode, x);
  76255. decodePosString (tokens [1], yMode, y);
  76256. decodeSizeString (tokens [2], wMode, w);
  76257. decodeSizeString (tokens [3], hMode, h);
  76258. }
  76259. const String PositionedRectangle::toString() const throw()
  76260. {
  76261. String s;
  76262. s.preallocateStorage (12);
  76263. addPosDescription (s, xMode, x);
  76264. s << ' ';
  76265. addPosDescription (s, yMode, y);
  76266. s << ' ';
  76267. addSizeDescription (s, wMode, w);
  76268. s << ' ';
  76269. addSizeDescription (s, hMode, h);
  76270. return s;
  76271. }
  76272. const Rectangle<int> PositionedRectangle::getRectangle (const Rectangle<int>& target) const throw()
  76273. {
  76274. jassert (! target.isEmpty());
  76275. double x_, y_, w_, h_;
  76276. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  76277. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  76278. return Rectangle<int> (roundToInt (x_), roundToInt (y_),
  76279. roundToInt (w_), roundToInt (h_));
  76280. }
  76281. void PositionedRectangle::getRectangleDouble (const Rectangle<int>& target,
  76282. double& x_, double& y_,
  76283. double& w_, double& h_) const throw()
  76284. {
  76285. jassert (! target.isEmpty());
  76286. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  76287. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  76288. }
  76289. void PositionedRectangle::applyToComponent (Component& comp) const throw()
  76290. {
  76291. comp.setBounds (getRectangle (Rectangle<int> (comp.getParentWidth(), comp.getParentHeight())));
  76292. }
  76293. void PositionedRectangle::updateFrom (const Rectangle<int>& rectangle,
  76294. const Rectangle<int>& target) throw()
  76295. {
  76296. updatePosAndSize (x, w, rectangle.getX(), rectangle.getWidth(), xMode, wMode, target.getX(), target.getWidth());
  76297. updatePosAndSize (y, h, rectangle.getY(), rectangle.getHeight(), yMode, hMode, target.getY(), target.getHeight());
  76298. }
  76299. void PositionedRectangle::updateFromDouble (const double newX, const double newY,
  76300. const double newW, const double newH,
  76301. const Rectangle<int>& target) throw()
  76302. {
  76303. updatePosAndSize (x, w, newX, newW, xMode, wMode, target.getX(), target.getWidth());
  76304. updatePosAndSize (y, h, newY, newH, yMode, hMode, target.getY(), target.getHeight());
  76305. }
  76306. void PositionedRectangle::updateFromComponent (const Component& comp) throw()
  76307. {
  76308. if (comp.getParentComponent() == 0 && ! comp.isOnDesktop())
  76309. updateFrom (comp.getBounds(), Rectangle<int>());
  76310. else
  76311. updateFrom (comp.getBounds(), Rectangle<int> (comp.getParentWidth(), comp.getParentHeight()));
  76312. }
  76313. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointX() const throw()
  76314. {
  76315. return (AnchorPoint) (xMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  76316. }
  76317. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeX() const throw()
  76318. {
  76319. return (PositionMode) (xMode & (absoluteFromParentTopLeft
  76320. | absoluteFromParentBottomRight
  76321. | absoluteFromParentCentre
  76322. | proportionOfParentSize));
  76323. }
  76324. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointY() const throw()
  76325. {
  76326. return (AnchorPoint) (yMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  76327. }
  76328. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeY() const throw()
  76329. {
  76330. return (PositionMode) (yMode & (absoluteFromParentTopLeft
  76331. | absoluteFromParentBottomRight
  76332. | absoluteFromParentCentre
  76333. | proportionOfParentSize));
  76334. }
  76335. PositionedRectangle::SizeMode PositionedRectangle::getWidthMode() const throw()
  76336. {
  76337. return (SizeMode) wMode;
  76338. }
  76339. PositionedRectangle::SizeMode PositionedRectangle::getHeightMode() const throw()
  76340. {
  76341. return (SizeMode) hMode;
  76342. }
  76343. void PositionedRectangle::setModes (const AnchorPoint xAnchor,
  76344. const PositionMode xMode_,
  76345. const AnchorPoint yAnchor,
  76346. const PositionMode yMode_,
  76347. const SizeMode widthMode,
  76348. const SizeMode heightMode,
  76349. const Rectangle<int>& target) throw()
  76350. {
  76351. if (xMode != (xAnchor | xMode_) || wMode != widthMode)
  76352. {
  76353. double tx, tw;
  76354. applyPosAndSize (tx, tw, x, w, xMode, wMode, target.getX(), target.getWidth());
  76355. xMode = (uint8) (xAnchor | xMode_);
  76356. wMode = (uint8) widthMode;
  76357. updatePosAndSize (x, w, tx, tw, xMode, wMode, target.getX(), target.getWidth());
  76358. }
  76359. if (yMode != (yAnchor | yMode_) || hMode != heightMode)
  76360. {
  76361. double ty, th;
  76362. applyPosAndSize (ty, th, y, h, yMode, hMode, target.getY(), target.getHeight());
  76363. yMode = (uint8) (yAnchor | yMode_);
  76364. hMode = (uint8) heightMode;
  76365. updatePosAndSize (y, h, ty, th, yMode, hMode, target.getY(), target.getHeight());
  76366. }
  76367. }
  76368. bool PositionedRectangle::isPositionAbsolute() const throw()
  76369. {
  76370. return xMode == absoluteFromParentTopLeft
  76371. && yMode == absoluteFromParentTopLeft
  76372. && wMode == absoluteSize
  76373. && hMode == absoluteSize;
  76374. }
  76375. void PositionedRectangle::addPosDescription (String& s, const uint8 mode, const double value) const throw()
  76376. {
  76377. if ((mode & proportionOfParentSize) != 0)
  76378. {
  76379. s << (roundToInt (value * 100000.0) / 1000.0) << '%';
  76380. }
  76381. else
  76382. {
  76383. s << (roundToInt (value * 100.0) / 100.0);
  76384. if ((mode & absoluteFromParentBottomRight) != 0)
  76385. s << 'R';
  76386. else if ((mode & absoluteFromParentCentre) != 0)
  76387. s << 'C';
  76388. }
  76389. if ((mode & anchorAtRightOrBottom) != 0)
  76390. s << 'r';
  76391. else if ((mode & anchorAtCentre) != 0)
  76392. s << 'c';
  76393. }
  76394. void PositionedRectangle::addSizeDescription (String& s, const uint8 mode, const double value) const throw()
  76395. {
  76396. if (mode == proportionalSize)
  76397. s << (roundToInt (value * 100000.0) / 1000.0) << '%';
  76398. else if (mode == parentSizeMinusAbsolute)
  76399. s << (roundToInt (value * 100.0) / 100.0) << 'M';
  76400. else
  76401. s << (roundToInt (value * 100.0) / 100.0);
  76402. }
  76403. void PositionedRectangle::decodePosString (const String& s, uint8& mode, double& value) throw()
  76404. {
  76405. if (s.containsChar ('r'))
  76406. mode = anchorAtRightOrBottom;
  76407. else if (s.containsChar ('c'))
  76408. mode = anchorAtCentre;
  76409. else
  76410. mode = anchorAtLeftOrTop;
  76411. if (s.containsChar ('%'))
  76412. {
  76413. mode |= proportionOfParentSize;
  76414. value = s.removeCharacters ("%rcRC").getDoubleValue() / 100.0;
  76415. }
  76416. else
  76417. {
  76418. if (s.containsChar ('R'))
  76419. mode |= absoluteFromParentBottomRight;
  76420. else if (s.containsChar ('C'))
  76421. mode |= absoluteFromParentCentre;
  76422. else
  76423. mode |= absoluteFromParentTopLeft;
  76424. value = s.removeCharacters ("rcRC").getDoubleValue();
  76425. }
  76426. }
  76427. void PositionedRectangle::decodeSizeString (const String& s, uint8& mode, double& value) throw()
  76428. {
  76429. if (s.containsChar ('%'))
  76430. {
  76431. mode = proportionalSize;
  76432. value = s.upToFirstOccurrenceOf ("%", false, false).getDoubleValue() / 100.0;
  76433. }
  76434. else if (s.containsChar ('M'))
  76435. {
  76436. mode = parentSizeMinusAbsolute;
  76437. value = s.getDoubleValue();
  76438. }
  76439. else
  76440. {
  76441. mode = absoluteSize;
  76442. value = s.getDoubleValue();
  76443. }
  76444. }
  76445. void PositionedRectangle::applyPosAndSize (double& xOut, double& wOut,
  76446. const double x_, const double w_,
  76447. const uint8 xMode_, const uint8 wMode_,
  76448. const int parentPos,
  76449. const int parentSize) const throw()
  76450. {
  76451. if (wMode_ == proportionalSize)
  76452. wOut = roundToInt (w_ * parentSize);
  76453. else if (wMode_ == parentSizeMinusAbsolute)
  76454. wOut = jmax (0, parentSize - roundToInt (w_));
  76455. else
  76456. wOut = roundToInt (w_);
  76457. if ((xMode_ & proportionOfParentSize) != 0)
  76458. xOut = parentPos + x_ * parentSize;
  76459. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  76460. xOut = (parentPos + parentSize) - x_;
  76461. else if ((xMode_ & absoluteFromParentCentre) != 0)
  76462. xOut = x_ + (parentPos + parentSize / 2);
  76463. else
  76464. xOut = x_ + parentPos;
  76465. if ((xMode_ & anchorAtRightOrBottom) != 0)
  76466. xOut -= wOut;
  76467. else if ((xMode_ & anchorAtCentre) != 0)
  76468. xOut -= wOut / 2;
  76469. }
  76470. void PositionedRectangle::updatePosAndSize (double& xOut, double& wOut,
  76471. double x_, const double w_,
  76472. const uint8 xMode_, const uint8 wMode_,
  76473. const int parentPos,
  76474. const int parentSize) const throw()
  76475. {
  76476. if (wMode_ == proportionalSize)
  76477. {
  76478. if (parentSize > 0)
  76479. wOut = w_ / parentSize;
  76480. }
  76481. else if (wMode_ == parentSizeMinusAbsolute)
  76482. wOut = parentSize - w_;
  76483. else
  76484. wOut = w_;
  76485. if ((xMode_ & anchorAtRightOrBottom) != 0)
  76486. x_ += w_;
  76487. else if ((xMode_ & anchorAtCentre) != 0)
  76488. x_ += w_ / 2;
  76489. if ((xMode_ & proportionOfParentSize) != 0)
  76490. {
  76491. if (parentSize > 0)
  76492. xOut = (x_ - parentPos) / parentSize;
  76493. }
  76494. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  76495. xOut = (parentPos + parentSize) - x_;
  76496. else if ((xMode_ & absoluteFromParentCentre) != 0)
  76497. xOut = x_ - (parentPos + parentSize / 2);
  76498. else
  76499. xOut = x_ - parentPos;
  76500. }
  76501. END_JUCE_NAMESPACE
  76502. /*** End of inlined file: juce_PositionedRectangle.cpp ***/
  76503. /*** Start of inlined file: juce_RectangleList.cpp ***/
  76504. BEGIN_JUCE_NAMESPACE
  76505. RectangleList::RectangleList() throw()
  76506. {
  76507. }
  76508. RectangleList::RectangleList (const Rectangle<int>& rect)
  76509. {
  76510. if (! rect.isEmpty())
  76511. rects.add (rect);
  76512. }
  76513. RectangleList::RectangleList (const RectangleList& other)
  76514. : rects (other.rects)
  76515. {
  76516. }
  76517. RectangleList& RectangleList::operator= (const RectangleList& other)
  76518. {
  76519. rects = other.rects;
  76520. return *this;
  76521. }
  76522. RectangleList::~RectangleList()
  76523. {
  76524. }
  76525. void RectangleList::clear()
  76526. {
  76527. rects.clearQuick();
  76528. }
  76529. const Rectangle<int> RectangleList::getRectangle (const int index) const throw()
  76530. {
  76531. if (((unsigned int) index) < (unsigned int) rects.size())
  76532. return rects.getReference (index);
  76533. return Rectangle<int>();
  76534. }
  76535. bool RectangleList::isEmpty() const throw()
  76536. {
  76537. return rects.size() == 0;
  76538. }
  76539. RectangleList::Iterator::Iterator (const RectangleList& list) throw()
  76540. : current (0),
  76541. owner (list),
  76542. index (list.rects.size())
  76543. {
  76544. }
  76545. RectangleList::Iterator::~Iterator()
  76546. {
  76547. }
  76548. bool RectangleList::Iterator::next() throw()
  76549. {
  76550. if (--index >= 0)
  76551. {
  76552. current = & (owner.rects.getReference (index));
  76553. return true;
  76554. }
  76555. return false;
  76556. }
  76557. void RectangleList::add (const Rectangle<int>& rect)
  76558. {
  76559. if (! rect.isEmpty())
  76560. {
  76561. if (rects.size() == 0)
  76562. {
  76563. rects.add (rect);
  76564. }
  76565. else
  76566. {
  76567. bool anyOverlaps = false;
  76568. int i;
  76569. for (i = rects.size(); --i >= 0;)
  76570. {
  76571. Rectangle<int>& ourRect = rects.getReference (i);
  76572. if (rect.intersects (ourRect))
  76573. {
  76574. if (rect.contains (ourRect))
  76575. rects.remove (i);
  76576. else if (! ourRect.reduceIfPartlyContainedIn (rect))
  76577. anyOverlaps = true;
  76578. }
  76579. }
  76580. if (anyOverlaps && rects.size() > 0)
  76581. {
  76582. RectangleList r (rect);
  76583. for (i = rects.size(); --i >= 0;)
  76584. {
  76585. const Rectangle<int>& ourRect = rects.getReference (i);
  76586. if (rect.intersects (ourRect))
  76587. {
  76588. r.subtract (ourRect);
  76589. if (r.rects.size() == 0)
  76590. return;
  76591. }
  76592. }
  76593. for (i = r.getNumRectangles(); --i >= 0;)
  76594. rects.add (r.rects.getReference (i));
  76595. }
  76596. else
  76597. {
  76598. rects.add (rect);
  76599. }
  76600. }
  76601. }
  76602. }
  76603. void RectangleList::addWithoutMerging (const Rectangle<int>& rect)
  76604. {
  76605. if (! rect.isEmpty())
  76606. rects.add (rect);
  76607. }
  76608. void RectangleList::add (const int x, const int y, const int w, const int h)
  76609. {
  76610. if (rects.size() == 0)
  76611. {
  76612. if (w > 0 && h > 0)
  76613. rects.add (Rectangle<int> (x, y, w, h));
  76614. }
  76615. else
  76616. {
  76617. add (Rectangle<int> (x, y, w, h));
  76618. }
  76619. }
  76620. void RectangleList::add (const RectangleList& other)
  76621. {
  76622. for (int i = 0; i < other.rects.size(); ++i)
  76623. add (other.rects.getReference (i));
  76624. }
  76625. void RectangleList::subtract (const Rectangle<int>& rect)
  76626. {
  76627. const int originalNumRects = rects.size();
  76628. if (originalNumRects > 0)
  76629. {
  76630. const int x1 = rect.x;
  76631. const int y1 = rect.y;
  76632. const int x2 = x1 + rect.w;
  76633. const int y2 = y1 + rect.h;
  76634. for (int i = getNumRectangles(); --i >= 0;)
  76635. {
  76636. Rectangle<int>& r = rects.getReference (i);
  76637. const int rx1 = r.x;
  76638. const int ry1 = r.y;
  76639. const int rx2 = rx1 + r.w;
  76640. const int ry2 = ry1 + r.h;
  76641. if (! (x2 <= rx1 || x1 >= rx2 || y2 <= ry1 || y1 >= ry2))
  76642. {
  76643. if (x1 > rx1 && x1 < rx2)
  76644. {
  76645. if (y1 <= ry1 && y2 >= ry2 && x2 >= rx2)
  76646. {
  76647. r.w = x1 - rx1;
  76648. }
  76649. else
  76650. {
  76651. r.x = x1;
  76652. r.w = rx2 - x1;
  76653. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x1 - rx1, ry2 - ry1));
  76654. i += 2;
  76655. }
  76656. }
  76657. else if (x2 > rx1 && x2 < rx2)
  76658. {
  76659. r.x = x2;
  76660. r.w = rx2 - x2;
  76661. if (y1 > ry1 || y2 < ry2 || x1 > rx1)
  76662. {
  76663. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x2 - rx1, ry2 - ry1));
  76664. i += 2;
  76665. }
  76666. }
  76667. else if (y1 > ry1 && y1 < ry2)
  76668. {
  76669. if (x1 <= rx1 && x2 >= rx2 && y2 >= ry2)
  76670. {
  76671. r.h = y1 - ry1;
  76672. }
  76673. else
  76674. {
  76675. r.y = y1;
  76676. r.h = ry2 - y1;
  76677. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y1 - ry1));
  76678. i += 2;
  76679. }
  76680. }
  76681. else if (y2 > ry1 && y2 < ry2)
  76682. {
  76683. r.y = y2;
  76684. r.h = ry2 - y2;
  76685. if (x1 > rx1 || x2 < rx2 || y1 > ry1)
  76686. {
  76687. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y2 - ry1));
  76688. i += 2;
  76689. }
  76690. }
  76691. else
  76692. {
  76693. rects.remove (i);
  76694. }
  76695. }
  76696. }
  76697. }
  76698. }
  76699. bool RectangleList::subtract (const RectangleList& otherList)
  76700. {
  76701. for (int i = otherList.rects.size(); --i >= 0 && rects.size() > 0;)
  76702. subtract (otherList.rects.getReference (i));
  76703. return rects.size() > 0;
  76704. }
  76705. bool RectangleList::clipTo (const Rectangle<int>& rect)
  76706. {
  76707. bool notEmpty = false;
  76708. if (rect.isEmpty())
  76709. {
  76710. clear();
  76711. }
  76712. else
  76713. {
  76714. for (int i = rects.size(); --i >= 0;)
  76715. {
  76716. Rectangle<int>& r = rects.getReference (i);
  76717. if (! rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76718. rects.remove (i);
  76719. else
  76720. notEmpty = true;
  76721. }
  76722. }
  76723. return notEmpty;
  76724. }
  76725. bool RectangleList::clipTo (const RectangleList& other)
  76726. {
  76727. if (rects.size() == 0)
  76728. return false;
  76729. RectangleList result;
  76730. for (int j = 0; j < rects.size(); ++j)
  76731. {
  76732. const Rectangle<int>& rect = rects.getReference (j);
  76733. for (int i = other.rects.size(); --i >= 0;)
  76734. {
  76735. Rectangle<int> r (other.rects.getReference (i));
  76736. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76737. result.rects.add (r);
  76738. }
  76739. }
  76740. swapWith (result);
  76741. return ! isEmpty();
  76742. }
  76743. bool RectangleList::getIntersectionWith (const Rectangle<int>& rect, RectangleList& destRegion) const
  76744. {
  76745. destRegion.clear();
  76746. if (! rect.isEmpty())
  76747. {
  76748. for (int i = rects.size(); --i >= 0;)
  76749. {
  76750. Rectangle<int> r (rects.getReference (i));
  76751. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76752. destRegion.rects.add (r);
  76753. }
  76754. }
  76755. return destRegion.rects.size() > 0;
  76756. }
  76757. void RectangleList::swapWith (RectangleList& otherList) throw()
  76758. {
  76759. rects.swapWithArray (otherList.rects);
  76760. }
  76761. void RectangleList::consolidate()
  76762. {
  76763. int i;
  76764. for (i = 0; i < getNumRectangles() - 1; ++i)
  76765. {
  76766. Rectangle<int>& r = rects.getReference (i);
  76767. const int rx1 = r.x;
  76768. const int ry1 = r.y;
  76769. const int rx2 = rx1 + r.w;
  76770. const int ry2 = ry1 + r.h;
  76771. for (int j = rects.size(); --j > i;)
  76772. {
  76773. Rectangle<int>& r2 = rects.getReference (j);
  76774. const int jrx1 = r2.x;
  76775. const int jry1 = r2.y;
  76776. const int jrx2 = jrx1 + r2.w;
  76777. const int jry2 = jry1 + r2.h;
  76778. // if the vertical edges of any blocks are touching and their horizontals don't
  76779. // line up, split them horizontally..
  76780. if (jrx1 == rx2 || jrx2 == rx1)
  76781. {
  76782. if (jry1 > ry1 && jry1 < ry2)
  76783. {
  76784. r.h = jry1 - ry1;
  76785. rects.add (Rectangle<int> (rx1, jry1, rx2 - rx1, ry2 - jry1));
  76786. i = -1;
  76787. break;
  76788. }
  76789. if (jry2 > ry1 && jry2 < ry2)
  76790. {
  76791. r.h = jry2 - ry1;
  76792. rects.add (Rectangle<int> (rx1, jry2, rx2 - rx1, ry2 - jry2));
  76793. i = -1;
  76794. break;
  76795. }
  76796. else if (ry1 > jry1 && ry1 < jry2)
  76797. {
  76798. r2.h = ry1 - jry1;
  76799. rects.add (Rectangle<int> (jrx1, ry1, jrx2 - jrx1, jry2 - ry1));
  76800. i = -1;
  76801. break;
  76802. }
  76803. else if (ry2 > jry1 && ry2 < jry2)
  76804. {
  76805. r2.h = ry2 - jry1;
  76806. rects.add (Rectangle<int> (jrx1, ry2, jrx2 - jrx1, jry2 - ry2));
  76807. i = -1;
  76808. break;
  76809. }
  76810. }
  76811. }
  76812. }
  76813. for (i = 0; i < rects.size() - 1; ++i)
  76814. {
  76815. Rectangle<int>& r = rects.getReference (i);
  76816. for (int j = rects.size(); --j > i;)
  76817. {
  76818. if (r.enlargeIfAdjacent (rects.getReference (j)))
  76819. {
  76820. rects.remove (j);
  76821. i = -1;
  76822. break;
  76823. }
  76824. }
  76825. }
  76826. }
  76827. bool RectangleList::containsPoint (const int x, const int y) const throw()
  76828. {
  76829. for (int i = getNumRectangles(); --i >= 0;)
  76830. if (rects.getReference (i).contains (x, y))
  76831. return true;
  76832. return false;
  76833. }
  76834. bool RectangleList::containsRectangle (const Rectangle<int>& rectangleToCheck) const
  76835. {
  76836. if (rects.size() > 1)
  76837. {
  76838. RectangleList r (rectangleToCheck);
  76839. for (int i = rects.size(); --i >= 0;)
  76840. {
  76841. r.subtract (rects.getReference (i));
  76842. if (r.rects.size() == 0)
  76843. return true;
  76844. }
  76845. }
  76846. else if (rects.size() > 0)
  76847. {
  76848. return rects.getReference (0).contains (rectangleToCheck);
  76849. }
  76850. return false;
  76851. }
  76852. bool RectangleList::intersectsRectangle (const Rectangle<int>& rectangleToCheck) const throw()
  76853. {
  76854. for (int i = rects.size(); --i >= 0;)
  76855. if (rects.getReference (i).intersects (rectangleToCheck))
  76856. return true;
  76857. return false;
  76858. }
  76859. bool RectangleList::intersects (const RectangleList& other) const throw()
  76860. {
  76861. for (int i = rects.size(); --i >= 0;)
  76862. if (other.intersectsRectangle (rects.getReference (i)))
  76863. return true;
  76864. return false;
  76865. }
  76866. const Rectangle<int> RectangleList::getBounds() const throw()
  76867. {
  76868. if (rects.size() <= 1)
  76869. {
  76870. if (rects.size() == 0)
  76871. return Rectangle<int>();
  76872. else
  76873. return rects.getReference (0);
  76874. }
  76875. else
  76876. {
  76877. const Rectangle<int>& r = rects.getReference (0);
  76878. int minX = r.x;
  76879. int minY = r.y;
  76880. int maxX = minX + r.w;
  76881. int maxY = minY + r.h;
  76882. for (int i = rects.size(); --i > 0;)
  76883. {
  76884. const Rectangle<int>& r2 = rects.getReference (i);
  76885. minX = jmin (minX, r2.x);
  76886. minY = jmin (minY, r2.y);
  76887. maxX = jmax (maxX, r2.getRight());
  76888. maxY = jmax (maxY, r2.getBottom());
  76889. }
  76890. return Rectangle<int> (minX, minY, maxX - minX, maxY - minY);
  76891. }
  76892. }
  76893. void RectangleList::offsetAll (const int dx, const int dy) throw()
  76894. {
  76895. for (int i = rects.size(); --i >= 0;)
  76896. {
  76897. Rectangle<int>& r = rects.getReference (i);
  76898. r.x += dx;
  76899. r.y += dy;
  76900. }
  76901. }
  76902. const Path RectangleList::toPath() const
  76903. {
  76904. Path p;
  76905. for (int i = rects.size(); --i >= 0;)
  76906. {
  76907. const Rectangle<int>& r = rects.getReference (i);
  76908. p.addRectangle ((float) r.x,
  76909. (float) r.y,
  76910. (float) r.w,
  76911. (float) r.h);
  76912. }
  76913. return p;
  76914. }
  76915. END_JUCE_NAMESPACE
  76916. /*** End of inlined file: juce_RectangleList.cpp ***/
  76917. /*** Start of inlined file: juce_Image.cpp ***/
  76918. BEGIN_JUCE_NAMESPACE
  76919. Image::SharedImage::SharedImage (const PixelFormat format_, const int width_, const int height_)
  76920. : format (format_), width (width_), height (height_)
  76921. {
  76922. jassert (format_ == RGB || format_ == ARGB || format_ == SingleChannel);
  76923. jassert (width > 0 && height > 0); // It's illegal to create a zero-sized image!
  76924. }
  76925. Image::SharedImage::~SharedImage()
  76926. {
  76927. }
  76928. inline uint8* Image::SharedImage::getPixelData (const int x, const int y) const throw()
  76929. {
  76930. return imageData + lineStride * y + pixelStride * x;
  76931. }
  76932. class SoftwareSharedImage : public Image::SharedImage
  76933. {
  76934. public:
  76935. SoftwareSharedImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  76936. : Image::SharedImage (format_, width_, height_)
  76937. {
  76938. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  76939. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  76940. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  76941. imageData = imageDataAllocated;
  76942. }
  76943. ~SoftwareSharedImage()
  76944. {
  76945. }
  76946. Image::ImageType getType() const
  76947. {
  76948. return Image::SoftwareImage;
  76949. }
  76950. LowLevelGraphicsContext* createLowLevelContext()
  76951. {
  76952. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  76953. }
  76954. SharedImage* clone()
  76955. {
  76956. SoftwareSharedImage* s = new SoftwareSharedImage (format, width, height, false);
  76957. memcpy (s->imageData, imageData, lineStride * height);
  76958. return s;
  76959. }
  76960. private:
  76961. HeapBlock<uint8> imageDataAllocated;
  76962. };
  76963. Image::SharedImage* Image::SharedImage::createSoftwareImage (Image::PixelFormat format, int width, int height, bool clearImage)
  76964. {
  76965. return new SoftwareSharedImage (format, width, height, clearImage);
  76966. }
  76967. class SubsectionSharedImage : public Image::SharedImage
  76968. {
  76969. public:
  76970. SubsectionSharedImage (Image::SharedImage* const image_, const Rectangle<int>& area_)
  76971. : Image::SharedImage (image_->getPixelFormat(), area_.getWidth(), area_.getHeight()),
  76972. image (image_), area (area_)
  76973. {
  76974. pixelStride = image_->getPixelStride();
  76975. lineStride = image_->getLineStride();
  76976. imageData = image_->getPixelData (area_.getX(), area_.getY());
  76977. }
  76978. ~SubsectionSharedImage() {}
  76979. Image::ImageType getType() const
  76980. {
  76981. return Image::SoftwareImage;
  76982. }
  76983. LowLevelGraphicsContext* createLowLevelContext()
  76984. {
  76985. LowLevelGraphicsContext* g = image->createLowLevelContext();
  76986. g->clipToRectangle (area);
  76987. g->setOrigin (area.getX(), area.getY());
  76988. return g;
  76989. }
  76990. SharedImage* clone()
  76991. {
  76992. return new SubsectionSharedImage (image->clone(), area);
  76993. }
  76994. private:
  76995. const ReferenceCountedObjectPtr<Image::SharedImage> image;
  76996. const Rectangle<int> area;
  76997. SubsectionSharedImage (const SubsectionSharedImage&);
  76998. SubsectionSharedImage& operator= (const SubsectionSharedImage&);
  76999. };
  77000. const Image Image::getClippedImage (const Rectangle<int>& area) const
  77001. {
  77002. if (area.contains (getBounds()))
  77003. return *this;
  77004. const Rectangle<int> validArea (area.getIntersection (getBounds()));
  77005. if (validArea.isEmpty())
  77006. return Image::null;
  77007. return Image (new SubsectionSharedImage (image, validArea));
  77008. }
  77009. Image::Image()
  77010. {
  77011. }
  77012. Image::Image (SharedImage* const instance)
  77013. : image (instance)
  77014. {
  77015. }
  77016. Image::Image (const PixelFormat format,
  77017. const int width, const int height,
  77018. const bool clearImage, const ImageType type)
  77019. : image (type == Image::NativeImage ? SharedImage::createNativeImage (format, width, height, clearImage)
  77020. : new SoftwareSharedImage (format, width, height, clearImage))
  77021. {
  77022. }
  77023. Image::Image (const Image& other)
  77024. : image (other.image)
  77025. {
  77026. }
  77027. Image& Image::operator= (const Image& other)
  77028. {
  77029. image = other.image;
  77030. return *this;
  77031. }
  77032. Image::~Image()
  77033. {
  77034. }
  77035. const Image Image::null;
  77036. LowLevelGraphicsContext* Image::createLowLevelContext() const
  77037. {
  77038. return image == 0 ? 0 : image->createLowLevelContext();
  77039. }
  77040. void Image::duplicateIfShared()
  77041. {
  77042. if (image != 0 && image->getReferenceCount() > 1)
  77043. image = image->clone();
  77044. }
  77045. const Image Image::rescaled (const int newWidth, const int newHeight, const Graphics::ResamplingQuality quality) const
  77046. {
  77047. if (image == 0 || (image->width == newWidth && image->height == newHeight))
  77048. return *this;
  77049. Image newImage (image->format, newWidth, newHeight, hasAlphaChannel(), image->getType());
  77050. Graphics g (newImage);
  77051. g.setImageResamplingQuality (quality);
  77052. g.drawImage (*this, 0, 0, newWidth, newHeight, 0, 0, image->width, image->height, false);
  77053. return newImage;
  77054. }
  77055. const Image Image::convertedToFormat (PixelFormat newFormat) const
  77056. {
  77057. if (image == 0 || newFormat == image->format)
  77058. return *this;
  77059. Image newImage (newFormat, image->width, image->height, false, image->getType());
  77060. if (newFormat == SingleChannel)
  77061. {
  77062. if (! hasAlphaChannel())
  77063. {
  77064. newImage.clear (getBounds(), Colours::black);
  77065. }
  77066. else
  77067. {
  77068. const BitmapData destData (newImage, 0, 0, image->width, image->height, true);
  77069. const BitmapData srcData (*this, 0, 0, image->width, image->height);
  77070. for (int y = 0; y < image->height; ++y)
  77071. {
  77072. const PixelARGB* src = (const PixelARGB*) srcData.getLinePointer(y);
  77073. uint8* dst = destData.getLinePointer (y);
  77074. for (int x = image->width; --x >= 0;)
  77075. {
  77076. *dst++ = src->getAlpha();
  77077. ++src;
  77078. }
  77079. }
  77080. }
  77081. }
  77082. else
  77083. {
  77084. if (hasAlphaChannel())
  77085. newImage.clear (getBounds());
  77086. Graphics g (newImage);
  77087. g.drawImageAt (*this, 0, 0);
  77088. }
  77089. return newImage;
  77090. }
  77091. const var Image::getTag() const
  77092. {
  77093. return image == 0 ? var::null : image->userTag;
  77094. }
  77095. void Image::setTag (const var& newTag)
  77096. {
  77097. if (image != 0)
  77098. image->userTag = newTag;
  77099. }
  77100. Image::BitmapData::BitmapData (Image& image, const int x, const int y, const int w, const int h, const bool /*makeWritable*/)
  77101. : data (image.image == 0 ? 0 : image.image->getPixelData (x, y)),
  77102. pixelFormat (image.getFormat()),
  77103. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  77104. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  77105. width (w),
  77106. height (h)
  77107. {
  77108. jassert (data != 0);
  77109. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  77110. }
  77111. Image::BitmapData::BitmapData (const Image& image, const int x, const int y, const int w, const int h)
  77112. : data (image.image == 0 ? 0 : image.image->getPixelData (x, y)),
  77113. pixelFormat (image.getFormat()),
  77114. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  77115. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  77116. width (w),
  77117. height (h)
  77118. {
  77119. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  77120. }
  77121. Image::BitmapData::BitmapData (const Image& image, bool /*needsToBeWritable*/)
  77122. : data (image.image == 0 ? 0 : image.image->imageData),
  77123. pixelFormat (image.getFormat()),
  77124. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  77125. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  77126. width (image.getWidth()),
  77127. height (image.getHeight())
  77128. {
  77129. }
  77130. Image::BitmapData::~BitmapData()
  77131. {
  77132. }
  77133. const Colour Image::BitmapData::getPixelColour (const int x, const int y) const throw()
  77134. {
  77135. jassert (((unsigned int) x) < (unsigned int) width && ((unsigned int) y) < (unsigned int) height);
  77136. const uint8* const pixel = getPixelPointer (x, y);
  77137. switch (pixelFormat)
  77138. {
  77139. case Image::ARGB:
  77140. {
  77141. PixelARGB p (*(const PixelARGB*) pixel);
  77142. p.unpremultiply();
  77143. return Colour (p.getARGB());
  77144. }
  77145. case Image::RGB:
  77146. return Colour (((const PixelRGB*) pixel)->getARGB());
  77147. case Image::SingleChannel:
  77148. return Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixel);
  77149. default:
  77150. jassertfalse;
  77151. break;
  77152. }
  77153. return Colour();
  77154. }
  77155. void Image::BitmapData::setPixelColour (const int x, const int y, const Colour& colour) const throw()
  77156. {
  77157. jassert (((unsigned int) x) < (unsigned int) width && ((unsigned int) y) < (unsigned int) height);
  77158. uint8* const pixel = getPixelPointer (x, y);
  77159. const PixelARGB col (colour.getPixelARGB());
  77160. switch (pixelFormat)
  77161. {
  77162. case Image::ARGB: ((PixelARGB*) pixel)->set (col); break;
  77163. case Image::RGB: ((PixelRGB*) pixel)->set (col); break;
  77164. case Image::SingleChannel: *pixel = col.getAlpha(); break;
  77165. default: jassertfalse; break;
  77166. }
  77167. }
  77168. void Image::setPixelData (int x, int y, int w, int h,
  77169. const uint8* const sourcePixelData, const int sourceLineStride)
  77170. {
  77171. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= getWidth() && y + h <= getHeight());
  77172. if (Rectangle<int>::intersectRectangles (x, y, w, h, 0, 0, getWidth(), getHeight()))
  77173. {
  77174. const BitmapData dest (*this, x, y, w, h, true);
  77175. for (int i = 0; i < h; ++i)
  77176. {
  77177. memcpy (dest.getLinePointer(i),
  77178. sourcePixelData + sourceLineStride * i,
  77179. w * dest.pixelStride);
  77180. }
  77181. }
  77182. }
  77183. void Image::clear (const Rectangle<int>& area, const Colour& colourToClearTo)
  77184. {
  77185. const Rectangle<int> clipped (area.getIntersection (getBounds()));
  77186. if (! clipped.isEmpty())
  77187. {
  77188. const PixelARGB col (colourToClearTo.getPixelARGB());
  77189. const BitmapData destData (*this, clipped.getX(), clipped.getY(), clipped.getWidth(), clipped.getHeight(), true);
  77190. uint8* dest = destData.data;
  77191. int dh = clipped.getHeight();
  77192. while (--dh >= 0)
  77193. {
  77194. uint8* line = dest;
  77195. dest += destData.lineStride;
  77196. if (isARGB())
  77197. {
  77198. for (int x = clipped.getWidth(); --x >= 0;)
  77199. {
  77200. ((PixelARGB*) line)->set (col);
  77201. line += destData.pixelStride;
  77202. }
  77203. }
  77204. else if (isRGB())
  77205. {
  77206. for (int x = clipped.getWidth(); --x >= 0;)
  77207. {
  77208. ((PixelRGB*) line)->set (col);
  77209. line += destData.pixelStride;
  77210. }
  77211. }
  77212. else
  77213. {
  77214. for (int x = clipped.getWidth(); --x >= 0;)
  77215. {
  77216. *line = col.getAlpha();
  77217. line += destData.pixelStride;
  77218. }
  77219. }
  77220. }
  77221. }
  77222. }
  77223. const Colour Image::getPixelAt (const int x, const int y) const
  77224. {
  77225. if (((unsigned int) x) < (unsigned int) getWidth()
  77226. && ((unsigned int) y) < (unsigned int) getHeight())
  77227. {
  77228. const BitmapData srcData (*this, x, y, 1, 1);
  77229. return srcData.getPixelColour (0, 0);
  77230. }
  77231. return Colour();
  77232. }
  77233. void Image::setPixelAt (const int x, const int y, const Colour& colour)
  77234. {
  77235. if (((unsigned int) x) < (unsigned int) getWidth()
  77236. && ((unsigned int) y) < (unsigned int) getHeight())
  77237. {
  77238. const BitmapData destData (*this, x, y, 1, 1, true);
  77239. destData.setPixelColour (0, 0, colour);
  77240. }
  77241. }
  77242. void Image::multiplyAlphaAt (const int x, const int y, const float multiplier)
  77243. {
  77244. if (((unsigned int) x) < (unsigned int) getWidth()
  77245. && ((unsigned int) y) < (unsigned int) getHeight()
  77246. && hasAlphaChannel())
  77247. {
  77248. const BitmapData destData (*this, x, y, 1, 1, true);
  77249. if (isARGB())
  77250. ((PixelARGB*) destData.data)->multiplyAlpha (multiplier);
  77251. else
  77252. *(destData.data) = (uint8) (*(destData.data) * multiplier);
  77253. }
  77254. }
  77255. void Image::multiplyAllAlphas (const float amountToMultiplyBy)
  77256. {
  77257. if (hasAlphaChannel())
  77258. {
  77259. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  77260. if (isARGB())
  77261. {
  77262. for (int y = 0; y < destData.height; ++y)
  77263. {
  77264. uint8* p = destData.getLinePointer (y);
  77265. for (int x = 0; x < destData.width; ++x)
  77266. {
  77267. ((PixelARGB*) p)->multiplyAlpha (amountToMultiplyBy);
  77268. p += destData.pixelStride;
  77269. }
  77270. }
  77271. }
  77272. else
  77273. {
  77274. for (int y = 0; y < destData.height; ++y)
  77275. {
  77276. uint8* p = destData.getLinePointer (y);
  77277. for (int x = 0; x < destData.width; ++x)
  77278. {
  77279. *p = (uint8) (*p * amountToMultiplyBy);
  77280. p += destData.pixelStride;
  77281. }
  77282. }
  77283. }
  77284. }
  77285. else
  77286. {
  77287. jassertfalse; // can't do this without an alpha-channel!
  77288. }
  77289. }
  77290. void Image::desaturate()
  77291. {
  77292. if (isARGB() || isRGB())
  77293. {
  77294. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  77295. if (isARGB())
  77296. {
  77297. for (int y = 0; y < destData.height; ++y)
  77298. {
  77299. uint8* p = destData.getLinePointer (y);
  77300. for (int x = 0; x < destData.width; ++x)
  77301. {
  77302. ((PixelARGB*) p)->desaturate();
  77303. p += destData.pixelStride;
  77304. }
  77305. }
  77306. }
  77307. else
  77308. {
  77309. for (int y = 0; y < destData.height; ++y)
  77310. {
  77311. uint8* p = destData.getLinePointer (y);
  77312. for (int x = 0; x < destData.width; ++x)
  77313. {
  77314. ((PixelRGB*) p)->desaturate();
  77315. p += destData.pixelStride;
  77316. }
  77317. }
  77318. }
  77319. }
  77320. }
  77321. void Image::createSolidAreaMask (RectangleList& result, const float alphaThreshold) const
  77322. {
  77323. if (hasAlphaChannel())
  77324. {
  77325. const uint8 threshold = (uint8) jlimit (0, 255, roundToInt (alphaThreshold * 255.0f));
  77326. SparseSet<int> pixelsOnRow;
  77327. const BitmapData srcData (*this, 0, 0, getWidth(), getHeight());
  77328. for (int y = 0; y < srcData.height; ++y)
  77329. {
  77330. pixelsOnRow.clear();
  77331. const uint8* lineData = srcData.getLinePointer (y);
  77332. if (isARGB())
  77333. {
  77334. for (int x = 0; x < srcData.width; ++x)
  77335. {
  77336. if (((const PixelARGB*) lineData)->getAlpha() >= threshold)
  77337. pixelsOnRow.addRange (Range<int> (x, x + 1));
  77338. lineData += srcData.pixelStride;
  77339. }
  77340. }
  77341. else
  77342. {
  77343. for (int x = 0; x < srcData.width; ++x)
  77344. {
  77345. if (*lineData >= threshold)
  77346. pixelsOnRow.addRange (Range<int> (x, x + 1));
  77347. lineData += srcData.pixelStride;
  77348. }
  77349. }
  77350. for (int i = 0; i < pixelsOnRow.getNumRanges(); ++i)
  77351. {
  77352. const Range<int> range (pixelsOnRow.getRange (i));
  77353. result.add (Rectangle<int> (range.getStart(), y, range.getLength(), 1));
  77354. }
  77355. result.consolidate();
  77356. }
  77357. }
  77358. else
  77359. {
  77360. result.add (0, 0, getWidth(), getHeight());
  77361. }
  77362. }
  77363. void Image::moveImageSection (int dx, int dy,
  77364. int sx, int sy,
  77365. int w, int h)
  77366. {
  77367. if (dx < 0)
  77368. {
  77369. w += dx;
  77370. sx -= dx;
  77371. dx = 0;
  77372. }
  77373. if (dy < 0)
  77374. {
  77375. h += dy;
  77376. sy -= dy;
  77377. dy = 0;
  77378. }
  77379. if (sx < 0)
  77380. {
  77381. w += sx;
  77382. dx -= sx;
  77383. sx = 0;
  77384. }
  77385. if (sy < 0)
  77386. {
  77387. h += sy;
  77388. dy -= sy;
  77389. sy = 0;
  77390. }
  77391. const int minX = jmin (dx, sx);
  77392. const int minY = jmin (dy, sy);
  77393. w = jmin (w, getWidth() - jmax (sx, dx));
  77394. h = jmin (h, getHeight() - jmax (sy, dy));
  77395. if (w > 0 && h > 0)
  77396. {
  77397. const int maxX = jmax (dx, sx) + w;
  77398. const int maxY = jmax (dy, sy) + h;
  77399. const BitmapData destData (*this, minX, minY, maxX - minX, maxY - minY, true);
  77400. uint8* dst = destData.getPixelPointer (dx - minX, dy - minY);
  77401. const uint8* src = destData.getPixelPointer (sx - minX, sy - minY);
  77402. const int lineSize = destData.pixelStride * w;
  77403. if (dy > sy)
  77404. {
  77405. while (--h >= 0)
  77406. {
  77407. const int offset = h * destData.lineStride;
  77408. memmove (dst + offset, src + offset, lineSize);
  77409. }
  77410. }
  77411. else if (dst != src)
  77412. {
  77413. while (--h >= 0)
  77414. {
  77415. memmove (dst, src, lineSize);
  77416. dst += destData.lineStride;
  77417. src += destData.lineStride;
  77418. }
  77419. }
  77420. }
  77421. }
  77422. END_JUCE_NAMESPACE
  77423. /*** End of inlined file: juce_Image.cpp ***/
  77424. /*** Start of inlined file: juce_ImageCache.cpp ***/
  77425. BEGIN_JUCE_NAMESPACE
  77426. class ImageCache::Pimpl : public Timer,
  77427. public DeletedAtShutdown
  77428. {
  77429. public:
  77430. Pimpl()
  77431. : cacheTimeout (5000)
  77432. {
  77433. }
  77434. ~Pimpl()
  77435. {
  77436. clearSingletonInstance();
  77437. }
  77438. const Image getFromHashCode (const int64 hashCode)
  77439. {
  77440. const ScopedLock sl (lock);
  77441. for (int i = images.size(); --i >= 0;)
  77442. {
  77443. Item* const item = images.getUnchecked(i);
  77444. if (item->hashCode == hashCode)
  77445. return item->image;
  77446. }
  77447. return Image::null;
  77448. }
  77449. void addImageToCache (const Image& image, const int64 hashCode)
  77450. {
  77451. if (image.isValid())
  77452. {
  77453. if (! isTimerRunning())
  77454. startTimer (2000);
  77455. Item* const item = new Item();
  77456. item->hashCode = hashCode;
  77457. item->image = image;
  77458. item->lastUseTime = Time::getApproximateMillisecondCounter();
  77459. const ScopedLock sl (lock);
  77460. images.add (item);
  77461. }
  77462. }
  77463. void timerCallback()
  77464. {
  77465. const uint32 now = Time::getApproximateMillisecondCounter();
  77466. const ScopedLock sl (lock);
  77467. for (int i = images.size(); --i >= 0;)
  77468. {
  77469. Item* const item = images.getUnchecked(i);
  77470. if (item->image.getReferenceCount() <= 1)
  77471. {
  77472. if (now > item->lastUseTime + cacheTimeout || now < item->lastUseTime - 1000)
  77473. images.remove (i);
  77474. }
  77475. else
  77476. {
  77477. item->lastUseTime = now; // multiply-referenced, so this image is still in use.
  77478. }
  77479. }
  77480. if (images.size() == 0)
  77481. stopTimer();
  77482. }
  77483. struct Item
  77484. {
  77485. Image image;
  77486. int64 hashCode;
  77487. uint32 lastUseTime;
  77488. };
  77489. int cacheTimeout;
  77490. juce_DeclareSingleton_SingleThreaded_Minimal (ImageCache::Pimpl);
  77491. private:
  77492. OwnedArray<Item> images;
  77493. CriticalSection lock;
  77494. Pimpl (const Pimpl&);
  77495. Pimpl& operator= (const Pimpl&);
  77496. };
  77497. juce_ImplementSingleton_SingleThreaded (ImageCache::Pimpl);
  77498. const Image ImageCache::getFromHashCode (const int64 hashCode)
  77499. {
  77500. if (Pimpl::getInstanceWithoutCreating() != 0)
  77501. return Pimpl::getInstanceWithoutCreating()->getFromHashCode (hashCode);
  77502. return Image::null;
  77503. }
  77504. void ImageCache::addImageToCache (const Image& image, const int64 hashCode)
  77505. {
  77506. Pimpl::getInstance()->addImageToCache (image, hashCode);
  77507. }
  77508. const Image ImageCache::getFromFile (const File& file)
  77509. {
  77510. const int64 hashCode = file.hashCode64();
  77511. Image image (getFromHashCode (hashCode));
  77512. if (image.isNull())
  77513. {
  77514. image = ImageFileFormat::loadFrom (file);
  77515. addImageToCache (image, hashCode);
  77516. }
  77517. return image;
  77518. }
  77519. const Image ImageCache::getFromMemory (const void* imageData, const int dataSize)
  77520. {
  77521. const int64 hashCode = (int64) (pointer_sized_int) imageData;
  77522. Image image (getFromHashCode (hashCode));
  77523. if (image.isNull())
  77524. {
  77525. image = ImageFileFormat::loadFrom (imageData, dataSize);
  77526. addImageToCache (image, hashCode);
  77527. }
  77528. return image;
  77529. }
  77530. void ImageCache::setCacheTimeout (const int millisecs)
  77531. {
  77532. Pimpl::getInstance()->cacheTimeout = millisecs;
  77533. }
  77534. END_JUCE_NAMESPACE
  77535. /*** End of inlined file: juce_ImageCache.cpp ***/
  77536. /*** Start of inlined file: juce_ImageConvolutionKernel.cpp ***/
  77537. BEGIN_JUCE_NAMESPACE
  77538. ImageConvolutionKernel::ImageConvolutionKernel (const int size_)
  77539. : values (size_ * size_),
  77540. size (size_)
  77541. {
  77542. clear();
  77543. }
  77544. ImageConvolutionKernel::~ImageConvolutionKernel()
  77545. {
  77546. }
  77547. float ImageConvolutionKernel::getKernelValue (const int x, const int y) const throw()
  77548. {
  77549. if (((unsigned int) x) < (unsigned int) size
  77550. && ((unsigned int) y) < (unsigned int) size)
  77551. {
  77552. return values [x + y * size];
  77553. }
  77554. else
  77555. {
  77556. jassertfalse;
  77557. return 0;
  77558. }
  77559. }
  77560. void ImageConvolutionKernel::setKernelValue (const int x, const int y, const float value) throw()
  77561. {
  77562. if (((unsigned int) x) < (unsigned int) size
  77563. && ((unsigned int) y) < (unsigned int) size)
  77564. {
  77565. values [x + y * size] = value;
  77566. }
  77567. else
  77568. {
  77569. jassertfalse;
  77570. }
  77571. }
  77572. void ImageConvolutionKernel::clear()
  77573. {
  77574. for (int i = size * size; --i >= 0;)
  77575. values[i] = 0;
  77576. }
  77577. void ImageConvolutionKernel::setOverallSum (const float desiredTotalSum)
  77578. {
  77579. double currentTotal = 0.0;
  77580. for (int i = size * size; --i >= 0;)
  77581. currentTotal += values[i];
  77582. rescaleAllValues ((float) (desiredTotalSum / currentTotal));
  77583. }
  77584. void ImageConvolutionKernel::rescaleAllValues (const float multiplier)
  77585. {
  77586. for (int i = size * size; --i >= 0;)
  77587. values[i] *= multiplier;
  77588. }
  77589. void ImageConvolutionKernel::createGaussianBlur (const float radius)
  77590. {
  77591. const double radiusFactor = -1.0 / (radius * radius * 2);
  77592. const int centre = size >> 1;
  77593. for (int y = size; --y >= 0;)
  77594. {
  77595. for (int x = size; --x >= 0;)
  77596. {
  77597. const int cx = x - centre;
  77598. const int cy = y - centre;
  77599. values [x + y * size] = (float) exp (radiusFactor * (cx * cx + cy * cy));
  77600. }
  77601. }
  77602. setOverallSum (1.0f);
  77603. }
  77604. void ImageConvolutionKernel::applyToImage (Image& destImage,
  77605. const Image& sourceImage,
  77606. const Rectangle<int>& destinationArea) const
  77607. {
  77608. if (sourceImage == destImage)
  77609. {
  77610. destImage.duplicateIfShared();
  77611. }
  77612. else
  77613. {
  77614. if (sourceImage.getWidth() != destImage.getWidth()
  77615. || sourceImage.getHeight() != destImage.getHeight()
  77616. || sourceImage.getFormat() != destImage.getFormat())
  77617. {
  77618. jassertfalse;
  77619. return;
  77620. }
  77621. }
  77622. const Rectangle<int> area (destinationArea.getIntersection (destImage.getBounds()));
  77623. if (area.isEmpty())
  77624. return;
  77625. const int right = area.getRight();
  77626. const int bottom = area.getBottom();
  77627. const Image::BitmapData destData (destImage, area.getX(), area.getY(), area.getWidth(), area.getHeight(), true);
  77628. uint8* line = destData.data;
  77629. const Image::BitmapData srcData (sourceImage, false);
  77630. if (destData.pixelStride == 4)
  77631. {
  77632. for (int y = area.getY(); y < bottom; ++y)
  77633. {
  77634. uint8* dest = line;
  77635. line += destData.lineStride;
  77636. for (int x = area.getX(); x < right; ++x)
  77637. {
  77638. float c1 = 0;
  77639. float c2 = 0;
  77640. float c3 = 0;
  77641. float c4 = 0;
  77642. for (int yy = 0; yy < size; ++yy)
  77643. {
  77644. const int sy = y + yy - (size >> 1);
  77645. if (sy >= srcData.height)
  77646. break;
  77647. if (sy >= 0)
  77648. {
  77649. int sx = x - (size >> 1);
  77650. const uint8* src = srcData.getPixelPointer (sx, sy);
  77651. for (int xx = 0; xx < size; ++xx)
  77652. {
  77653. if (sx >= srcData.width)
  77654. break;
  77655. if (sx >= 0)
  77656. {
  77657. const float kernelMult = values [xx + yy * size];
  77658. c1 += kernelMult * *src++;
  77659. c2 += kernelMult * *src++;
  77660. c3 += kernelMult * *src++;
  77661. c4 += kernelMult * *src++;
  77662. }
  77663. else
  77664. {
  77665. src += 4;
  77666. }
  77667. ++sx;
  77668. }
  77669. }
  77670. }
  77671. *dest++ = (uint8) jmin (0xff, roundToInt (c1));
  77672. *dest++ = (uint8) jmin (0xff, roundToInt (c2));
  77673. *dest++ = (uint8) jmin (0xff, roundToInt (c3));
  77674. *dest++ = (uint8) jmin (0xff, roundToInt (c4));
  77675. }
  77676. }
  77677. }
  77678. else if (destData.pixelStride == 3)
  77679. {
  77680. for (int y = area.getY(); y < bottom; ++y)
  77681. {
  77682. uint8* dest = line;
  77683. line += destData.lineStride;
  77684. for (int x = area.getX(); x < right; ++x)
  77685. {
  77686. float c1 = 0;
  77687. float c2 = 0;
  77688. float c3 = 0;
  77689. for (int yy = 0; yy < size; ++yy)
  77690. {
  77691. const int sy = y + yy - (size >> 1);
  77692. if (sy >= srcData.height)
  77693. break;
  77694. if (sy >= 0)
  77695. {
  77696. int sx = x - (size >> 1);
  77697. const uint8* src = srcData.getPixelPointer (sx, sy);
  77698. for (int xx = 0; xx < size; ++xx)
  77699. {
  77700. if (sx >= srcData.width)
  77701. break;
  77702. if (sx >= 0)
  77703. {
  77704. const float kernelMult = values [xx + yy * size];
  77705. c1 += kernelMult * *src++;
  77706. c2 += kernelMult * *src++;
  77707. c3 += kernelMult * *src++;
  77708. }
  77709. else
  77710. {
  77711. src += 3;
  77712. }
  77713. ++sx;
  77714. }
  77715. }
  77716. }
  77717. *dest++ = (uint8) roundToInt (c1);
  77718. *dest++ = (uint8) roundToInt (c2);
  77719. *dest++ = (uint8) roundToInt (c3);
  77720. }
  77721. }
  77722. }
  77723. }
  77724. END_JUCE_NAMESPACE
  77725. /*** End of inlined file: juce_ImageConvolutionKernel.cpp ***/
  77726. /*** Start of inlined file: juce_ImageFileFormat.cpp ***/
  77727. BEGIN_JUCE_NAMESPACE
  77728. ImageFileFormat* ImageFileFormat::findImageFormatForStream (InputStream& input)
  77729. {
  77730. static PNGImageFormat png;
  77731. static JPEGImageFormat jpg;
  77732. static GIFImageFormat gif;
  77733. ImageFileFormat* formats[4];
  77734. int numFormats = 0;
  77735. formats [numFormats++] = &png;
  77736. formats [numFormats++] = &jpg;
  77737. formats [numFormats++] = &gif;
  77738. const int64 streamPos = input.getPosition();
  77739. for (int i = 0; i < numFormats; ++i)
  77740. {
  77741. const bool found = formats[i]->canUnderstand (input);
  77742. input.setPosition (streamPos);
  77743. if (found)
  77744. return formats[i];
  77745. }
  77746. return 0;
  77747. }
  77748. const Image ImageFileFormat::loadFrom (InputStream& input)
  77749. {
  77750. ImageFileFormat* const format = findImageFormatForStream (input);
  77751. if (format != 0)
  77752. return format->decodeImage (input);
  77753. return Image::null;
  77754. }
  77755. const Image ImageFileFormat::loadFrom (const File& file)
  77756. {
  77757. InputStream* const in = file.createInputStream();
  77758. if (in != 0)
  77759. {
  77760. BufferedInputStream b (in, 8192, true);
  77761. return loadFrom (b);
  77762. }
  77763. return Image::null;
  77764. }
  77765. const Image ImageFileFormat::loadFrom (const void* rawData, const int numBytes)
  77766. {
  77767. if (rawData != 0 && numBytes > 4)
  77768. {
  77769. MemoryInputStream stream (rawData, numBytes, false);
  77770. return loadFrom (stream);
  77771. }
  77772. return Image::null;
  77773. }
  77774. END_JUCE_NAMESPACE
  77775. /*** End of inlined file: juce_ImageFileFormat.cpp ***/
  77776. /*** Start of inlined file: juce_GIFLoader.cpp ***/
  77777. BEGIN_JUCE_NAMESPACE
  77778. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  77779. const Image juce_loadWithCoreImage (InputStream& input);
  77780. #else
  77781. class GIFLoader
  77782. {
  77783. public:
  77784. GIFLoader (InputStream& in)
  77785. : input (in),
  77786. dataBlockIsZero (false),
  77787. fresh (false),
  77788. finished (false)
  77789. {
  77790. currentBit = lastBit = lastByteIndex = 0;
  77791. maxCode = maxCodeSize = codeSize = setCodeSize = 0;
  77792. firstcode = oldcode = 0;
  77793. clearCode = end_code = 0;
  77794. int imageWidth, imageHeight;
  77795. int transparent = -1;
  77796. if (! getSizeFromHeader (imageWidth, imageHeight))
  77797. return;
  77798. if ((imageWidth <= 0) || (imageHeight <= 0))
  77799. return;
  77800. unsigned char buf [16];
  77801. if (in.read (buf, 3) != 3)
  77802. return;
  77803. int numColours = 2 << (buf[0] & 7);
  77804. if ((buf[0] & 0x80) != 0)
  77805. readPalette (numColours);
  77806. for (;;)
  77807. {
  77808. if (input.read (buf, 1) != 1 || buf[0] == ';')
  77809. break;
  77810. if (buf[0] == '!')
  77811. {
  77812. if (input.read (buf, 1) != 1)
  77813. break;
  77814. if (processExtension (buf[0], transparent) < 0)
  77815. break;
  77816. continue;
  77817. }
  77818. if (buf[0] != ',')
  77819. continue;
  77820. if (input.read (buf, 9) != 9)
  77821. break;
  77822. imageWidth = makeWord (buf[4], buf[5]);
  77823. imageHeight = makeWord (buf[6], buf[7]);
  77824. numColours = 2 << (buf[8] & 7);
  77825. if ((buf[8] & 0x80) != 0)
  77826. if (! readPalette (numColours))
  77827. break;
  77828. image = Image ((transparent >= 0) ? Image::ARGB : Image::RGB,
  77829. imageWidth, imageHeight, (transparent >= 0));
  77830. readImage ((buf[8] & 0x40) != 0, transparent);
  77831. break;
  77832. }
  77833. }
  77834. ~GIFLoader() {}
  77835. Image image;
  77836. private:
  77837. InputStream& input;
  77838. uint8 buffer [300];
  77839. uint8 palette [256][4];
  77840. bool dataBlockIsZero, fresh, finished;
  77841. int currentBit, lastBit, lastByteIndex;
  77842. int codeSize, setCodeSize;
  77843. int maxCode, maxCodeSize;
  77844. int firstcode, oldcode;
  77845. int clearCode, end_code;
  77846. enum { maxGifCode = 1 << 12 };
  77847. int table [2] [maxGifCode];
  77848. int stack [2 * maxGifCode];
  77849. int *sp;
  77850. bool getSizeFromHeader (int& w, int& h)
  77851. {
  77852. char b[8];
  77853. if (input.read (b, 6) == 6)
  77854. {
  77855. if ((strncmp ("GIF87a", b, 6) == 0)
  77856. || (strncmp ("GIF89a", b, 6) == 0))
  77857. {
  77858. if (input.read (b, 4) == 4)
  77859. {
  77860. w = makeWord (b[0], b[1]);
  77861. h = makeWord (b[2], b[3]);
  77862. return true;
  77863. }
  77864. }
  77865. }
  77866. return false;
  77867. }
  77868. bool readPalette (const int numCols)
  77869. {
  77870. unsigned char rgb[4];
  77871. for (int i = 0; i < numCols; ++i)
  77872. {
  77873. input.read (rgb, 3);
  77874. palette [i][0] = rgb[0];
  77875. palette [i][1] = rgb[1];
  77876. palette [i][2] = rgb[2];
  77877. palette [i][3] = 0xff;
  77878. }
  77879. return true;
  77880. }
  77881. int readDataBlock (unsigned char* dest)
  77882. {
  77883. unsigned char n;
  77884. if (input.read (&n, 1) == 1)
  77885. {
  77886. dataBlockIsZero = (n == 0);
  77887. if (dataBlockIsZero || (input.read (dest, n) == n))
  77888. return n;
  77889. }
  77890. return -1;
  77891. }
  77892. int processExtension (const int type, int& transparent)
  77893. {
  77894. unsigned char b [300];
  77895. int n = 0;
  77896. if (type == 0xf9)
  77897. {
  77898. n = readDataBlock (b);
  77899. if (n < 0)
  77900. return 1;
  77901. if ((b[0] & 0x1) != 0)
  77902. transparent = b[3];
  77903. }
  77904. do
  77905. {
  77906. n = readDataBlock (b);
  77907. }
  77908. while (n > 0);
  77909. return n;
  77910. }
  77911. int readLZWByte (const bool initialise, const int inputCodeSize)
  77912. {
  77913. int code, incode, i;
  77914. if (initialise)
  77915. {
  77916. setCodeSize = inputCodeSize;
  77917. codeSize = setCodeSize + 1;
  77918. clearCode = 1 << setCodeSize;
  77919. end_code = clearCode + 1;
  77920. maxCodeSize = 2 * clearCode;
  77921. maxCode = clearCode + 2;
  77922. getCode (0, true);
  77923. fresh = true;
  77924. for (i = 0; i < clearCode; ++i)
  77925. {
  77926. table[0][i] = 0;
  77927. table[1][i] = i;
  77928. }
  77929. for (; i < maxGifCode; ++i)
  77930. {
  77931. table[0][i] = 0;
  77932. table[1][i] = 0;
  77933. }
  77934. sp = stack;
  77935. return 0;
  77936. }
  77937. else if (fresh)
  77938. {
  77939. fresh = false;
  77940. do
  77941. {
  77942. firstcode = oldcode
  77943. = getCode (codeSize, false);
  77944. }
  77945. while (firstcode == clearCode);
  77946. return firstcode;
  77947. }
  77948. if (sp > stack)
  77949. return *--sp;
  77950. while ((code = getCode (codeSize, false)) >= 0)
  77951. {
  77952. if (code == clearCode)
  77953. {
  77954. for (i = 0; i < clearCode; ++i)
  77955. {
  77956. table[0][i] = 0;
  77957. table[1][i] = i;
  77958. }
  77959. for (; i < maxGifCode; ++i)
  77960. {
  77961. table[0][i] = 0;
  77962. table[1][i] = 0;
  77963. }
  77964. codeSize = setCodeSize + 1;
  77965. maxCodeSize = 2 * clearCode;
  77966. maxCode = clearCode + 2;
  77967. sp = stack;
  77968. firstcode = oldcode = getCode (codeSize, false);
  77969. return firstcode;
  77970. }
  77971. else if (code == end_code)
  77972. {
  77973. if (dataBlockIsZero)
  77974. return -2;
  77975. unsigned char buf [260];
  77976. int n;
  77977. while ((n = readDataBlock (buf)) > 0)
  77978. {}
  77979. if (n != 0)
  77980. return -2;
  77981. }
  77982. incode = code;
  77983. if (code >= maxCode)
  77984. {
  77985. *sp++ = firstcode;
  77986. code = oldcode;
  77987. }
  77988. while (code >= clearCode)
  77989. {
  77990. *sp++ = table[1][code];
  77991. if (code == table[0][code])
  77992. return -2;
  77993. code = table[0][code];
  77994. }
  77995. *sp++ = firstcode = table[1][code];
  77996. if ((code = maxCode) < maxGifCode)
  77997. {
  77998. table[0][code] = oldcode;
  77999. table[1][code] = firstcode;
  78000. ++maxCode;
  78001. if ((maxCode >= maxCodeSize)
  78002. && (maxCodeSize < maxGifCode))
  78003. {
  78004. maxCodeSize <<= 1;
  78005. ++codeSize;
  78006. }
  78007. }
  78008. oldcode = incode;
  78009. if (sp > stack)
  78010. return *--sp;
  78011. }
  78012. return code;
  78013. }
  78014. int getCode (const int codeSize_, const bool initialise)
  78015. {
  78016. if (initialise)
  78017. {
  78018. currentBit = 0;
  78019. lastBit = 0;
  78020. finished = false;
  78021. return 0;
  78022. }
  78023. if ((currentBit + codeSize_) >= lastBit)
  78024. {
  78025. if (finished)
  78026. return -1;
  78027. buffer[0] = buffer [lastByteIndex - 2];
  78028. buffer[1] = buffer [lastByteIndex - 1];
  78029. const int n = readDataBlock (&buffer[2]);
  78030. if (n == 0)
  78031. finished = true;
  78032. lastByteIndex = 2 + n;
  78033. currentBit = (currentBit - lastBit) + 16;
  78034. lastBit = (2 + n) * 8 ;
  78035. }
  78036. int result = 0;
  78037. int i = currentBit;
  78038. for (int j = 0; j < codeSize_; ++j)
  78039. {
  78040. result |= ((buffer[i >> 3] & (1 << (i & 7))) != 0) << j;
  78041. ++i;
  78042. }
  78043. currentBit += codeSize_;
  78044. return result;
  78045. }
  78046. bool readImage (const int interlace, const int transparent)
  78047. {
  78048. unsigned char c;
  78049. if (input.read (&c, 1) != 1
  78050. || readLZWByte (true, c) < 0)
  78051. return false;
  78052. if (transparent >= 0)
  78053. {
  78054. palette [transparent][0] = 0;
  78055. palette [transparent][1] = 0;
  78056. palette [transparent][2] = 0;
  78057. palette [transparent][3] = 0;
  78058. }
  78059. int index;
  78060. int xpos = 0, ypos = 0, pass = 0;
  78061. const Image::BitmapData destData (image, true);
  78062. uint8* p = destData.data;
  78063. const bool hasAlpha = image.hasAlphaChannel();
  78064. while ((index = readLZWByte (false, c)) >= 0)
  78065. {
  78066. const uint8* const paletteEntry = palette [index];
  78067. if (hasAlpha)
  78068. {
  78069. ((PixelARGB*) p)->setARGB (paletteEntry[3],
  78070. paletteEntry[0],
  78071. paletteEntry[1],
  78072. paletteEntry[2]);
  78073. ((PixelARGB*) p)->premultiply();
  78074. }
  78075. else
  78076. {
  78077. ((PixelRGB*) p)->setARGB (0,
  78078. paletteEntry[0],
  78079. paletteEntry[1],
  78080. paletteEntry[2]);
  78081. }
  78082. p += destData.pixelStride;
  78083. ++xpos;
  78084. if (xpos == destData.width)
  78085. {
  78086. xpos = 0;
  78087. if (interlace)
  78088. {
  78089. switch (pass)
  78090. {
  78091. case 0:
  78092. case 1: ypos += 8; break;
  78093. case 2: ypos += 4; break;
  78094. case 3: ypos += 2; break;
  78095. }
  78096. while (ypos >= destData.height)
  78097. {
  78098. ++pass;
  78099. switch (pass)
  78100. {
  78101. case 1: ypos = 4; break;
  78102. case 2: ypos = 2; break;
  78103. case 3: ypos = 1; break;
  78104. default: return true;
  78105. }
  78106. }
  78107. }
  78108. else
  78109. {
  78110. ++ypos;
  78111. }
  78112. p = destData.getPixelPointer (xpos, ypos);
  78113. }
  78114. if (ypos >= destData.height)
  78115. break;
  78116. }
  78117. return true;
  78118. }
  78119. static inline int makeWord (const uint8 a, const uint8 b) { return (b << 8) | a; }
  78120. GIFLoader (const GIFLoader&);
  78121. GIFLoader& operator= (const GIFLoader&);
  78122. };
  78123. #endif
  78124. GIFImageFormat::GIFImageFormat() {}
  78125. GIFImageFormat::~GIFImageFormat() {}
  78126. const String GIFImageFormat::getFormatName() { return "GIF"; }
  78127. bool GIFImageFormat::canUnderstand (InputStream& in)
  78128. {
  78129. char header [4];
  78130. return (in.read (header, sizeof (header)) == sizeof (header))
  78131. && header[0] == 'G'
  78132. && header[1] == 'I'
  78133. && header[2] == 'F';
  78134. }
  78135. const Image GIFImageFormat::decodeImage (InputStream& in)
  78136. {
  78137. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  78138. return juce_loadWithCoreImage (in);
  78139. #else
  78140. const ScopedPointer <GIFLoader> loader (new GIFLoader (in));
  78141. return loader->image;
  78142. #endif
  78143. }
  78144. bool GIFImageFormat::writeImageToStream (const Image& /*sourceImage*/, OutputStream& /*destStream*/)
  78145. {
  78146. jassertfalse; // writing isn't implemented for GIFs!
  78147. return false;
  78148. }
  78149. END_JUCE_NAMESPACE
  78150. /*** End of inlined file: juce_GIFLoader.cpp ***/
  78151. #endif
  78152. //==============================================================================
  78153. // some files include lots of library code, so leave them to the end to avoid cluttering
  78154. // up the build for the clean files.
  78155. #if JUCE_BUILD_CORE
  78156. /*** Start of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  78157. namespace zlibNamespace
  78158. {
  78159. #if JUCE_INCLUDE_ZLIB_CODE
  78160. #undef OS_CODE
  78161. #undef fdopen
  78162. /*** Start of inlined file: zlib.h ***/
  78163. #ifndef ZLIB_H
  78164. #define ZLIB_H
  78165. /*** Start of inlined file: zconf.h ***/
  78166. /* @(#) $Id: zconf.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  78167. #ifndef ZCONF_H
  78168. #define ZCONF_H
  78169. // *** Just a few hacks here to make it compile nicely with Juce..
  78170. #define Z_PREFIX 1
  78171. #undef __MACTYPES__
  78172. #ifdef _MSC_VER
  78173. #pragma warning (disable : 4131 4127 4244 4267)
  78174. #endif
  78175. /*
  78176. * If you *really* need a unique prefix for all types and library functions,
  78177. * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
  78178. */
  78179. #ifdef Z_PREFIX
  78180. # define deflateInit_ z_deflateInit_
  78181. # define deflate z_deflate
  78182. # define deflateEnd z_deflateEnd
  78183. # define inflateInit_ z_inflateInit_
  78184. # define inflate z_inflate
  78185. # define inflateEnd z_inflateEnd
  78186. # define inflatePrime z_inflatePrime
  78187. # define inflateGetHeader z_inflateGetHeader
  78188. # define adler32_combine z_adler32_combine
  78189. # define crc32_combine z_crc32_combine
  78190. # define deflateInit2_ z_deflateInit2_
  78191. # define deflateSetDictionary z_deflateSetDictionary
  78192. # define deflateCopy z_deflateCopy
  78193. # define deflateReset z_deflateReset
  78194. # define deflateParams z_deflateParams
  78195. # define deflateBound z_deflateBound
  78196. # define deflatePrime z_deflatePrime
  78197. # define inflateInit2_ z_inflateInit2_
  78198. # define inflateSetDictionary z_inflateSetDictionary
  78199. # define inflateSync z_inflateSync
  78200. # define inflateSyncPoint z_inflateSyncPoint
  78201. # define inflateCopy z_inflateCopy
  78202. # define inflateReset z_inflateReset
  78203. # define inflateBack z_inflateBack
  78204. # define inflateBackEnd z_inflateBackEnd
  78205. # define compress z_compress
  78206. # define compress2 z_compress2
  78207. # define compressBound z_compressBound
  78208. # define uncompress z_uncompress
  78209. # define adler32 z_adler32
  78210. # define crc32 z_crc32
  78211. # define get_crc_table z_get_crc_table
  78212. # define zError z_zError
  78213. # define alloc_func z_alloc_func
  78214. # define free_func z_free_func
  78215. # define in_func z_in_func
  78216. # define out_func z_out_func
  78217. # define Byte z_Byte
  78218. # define uInt z_uInt
  78219. # define uLong z_uLong
  78220. # define Bytef z_Bytef
  78221. # define charf z_charf
  78222. # define intf z_intf
  78223. # define uIntf z_uIntf
  78224. # define uLongf z_uLongf
  78225. # define voidpf z_voidpf
  78226. # define voidp z_voidp
  78227. #endif
  78228. #if defined(__MSDOS__) && !defined(MSDOS)
  78229. # define MSDOS
  78230. #endif
  78231. #if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
  78232. # define OS2
  78233. #endif
  78234. #if defined(_WINDOWS) && !defined(WINDOWS)
  78235. # define WINDOWS
  78236. #endif
  78237. #if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
  78238. # ifndef WIN32
  78239. # define WIN32
  78240. # endif
  78241. #endif
  78242. #if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
  78243. # if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
  78244. # ifndef SYS16BIT
  78245. # define SYS16BIT
  78246. # endif
  78247. # endif
  78248. #endif
  78249. /*
  78250. * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
  78251. * than 64k bytes at a time (needed on systems with 16-bit int).
  78252. */
  78253. #ifdef SYS16BIT
  78254. # define MAXSEG_64K
  78255. #endif
  78256. #ifdef MSDOS
  78257. # define UNALIGNED_OK
  78258. #endif
  78259. #ifdef __STDC_VERSION__
  78260. # ifndef STDC
  78261. # define STDC
  78262. # endif
  78263. # if __STDC_VERSION__ >= 199901L
  78264. # ifndef STDC99
  78265. # define STDC99
  78266. # endif
  78267. # endif
  78268. #endif
  78269. #if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
  78270. # define STDC
  78271. #endif
  78272. #if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
  78273. # define STDC
  78274. #endif
  78275. #if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
  78276. # define STDC
  78277. #endif
  78278. #if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
  78279. # define STDC
  78280. #endif
  78281. #if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */
  78282. # define STDC
  78283. #endif
  78284. #ifndef STDC
  78285. # ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
  78286. # define const /* note: need a more gentle solution here */
  78287. # endif
  78288. #endif
  78289. /* Some Mac compilers merge all .h files incorrectly: */
  78290. #if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
  78291. # define NO_DUMMY_DECL
  78292. #endif
  78293. /* Maximum value for memLevel in deflateInit2 */
  78294. #ifndef MAX_MEM_LEVEL
  78295. # ifdef MAXSEG_64K
  78296. # define MAX_MEM_LEVEL 8
  78297. # else
  78298. # define MAX_MEM_LEVEL 9
  78299. # endif
  78300. #endif
  78301. /* Maximum value for windowBits in deflateInit2 and inflateInit2.
  78302. * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
  78303. * created by gzip. (Files created by minigzip can still be extracted by
  78304. * gzip.)
  78305. */
  78306. #ifndef MAX_WBITS
  78307. # define MAX_WBITS 15 /* 32K LZ77 window */
  78308. #endif
  78309. /* The memory requirements for deflate are (in bytes):
  78310. (1 << (windowBits+2)) + (1 << (memLevel+9))
  78311. that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
  78312. plus a few kilobytes for small objects. For example, if you want to reduce
  78313. the default memory requirements from 256K to 128K, compile with
  78314. make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
  78315. Of course this will generally degrade compression (there's no free lunch).
  78316. The memory requirements for inflate are (in bytes) 1 << windowBits
  78317. that is, 32K for windowBits=15 (default value) plus a few kilobytes
  78318. for small objects.
  78319. */
  78320. /* Type declarations */
  78321. #ifndef OF /* function prototypes */
  78322. # ifdef STDC
  78323. # define OF(args) args
  78324. # else
  78325. # define OF(args) ()
  78326. # endif
  78327. #endif
  78328. /* The following definitions for FAR are needed only for MSDOS mixed
  78329. * model programming (small or medium model with some far allocations).
  78330. * This was tested only with MSC; for other MSDOS compilers you may have
  78331. * to define NO_MEMCPY in zutil.h. If you don't need the mixed model,
  78332. * just define FAR to be empty.
  78333. */
  78334. #ifdef SYS16BIT
  78335. # if defined(M_I86SM) || defined(M_I86MM)
  78336. /* MSC small or medium model */
  78337. # define SMALL_MEDIUM
  78338. # ifdef _MSC_VER
  78339. # define FAR _far
  78340. # else
  78341. # define FAR far
  78342. # endif
  78343. # endif
  78344. # if (defined(__SMALL__) || defined(__MEDIUM__))
  78345. /* Turbo C small or medium model */
  78346. # define SMALL_MEDIUM
  78347. # ifdef __BORLANDC__
  78348. # define FAR _far
  78349. # else
  78350. # define FAR far
  78351. # endif
  78352. # endif
  78353. #endif
  78354. #if defined(WINDOWS) || defined(WIN32)
  78355. /* If building or using zlib as a DLL, define ZLIB_DLL.
  78356. * This is not mandatory, but it offers a little performance increase.
  78357. */
  78358. # ifdef ZLIB_DLL
  78359. # if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
  78360. # ifdef ZLIB_INTERNAL
  78361. # define ZEXTERN extern __declspec(dllexport)
  78362. # else
  78363. # define ZEXTERN extern __declspec(dllimport)
  78364. # endif
  78365. # endif
  78366. # endif /* ZLIB_DLL */
  78367. /* If building or using zlib with the WINAPI/WINAPIV calling convention,
  78368. * define ZLIB_WINAPI.
  78369. * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
  78370. */
  78371. # ifdef ZLIB_WINAPI
  78372. # ifdef FAR
  78373. # undef FAR
  78374. # endif
  78375. # include <windows.h>
  78376. /* No need for _export, use ZLIB.DEF instead. */
  78377. /* For complete Windows compatibility, use WINAPI, not __stdcall. */
  78378. # define ZEXPORT WINAPI
  78379. # ifdef WIN32
  78380. # define ZEXPORTVA WINAPIV
  78381. # else
  78382. # define ZEXPORTVA FAR CDECL
  78383. # endif
  78384. # endif
  78385. #endif
  78386. #if defined (__BEOS__)
  78387. # ifdef ZLIB_DLL
  78388. # ifdef ZLIB_INTERNAL
  78389. # define ZEXPORT __declspec(dllexport)
  78390. # define ZEXPORTVA __declspec(dllexport)
  78391. # else
  78392. # define ZEXPORT __declspec(dllimport)
  78393. # define ZEXPORTVA __declspec(dllimport)
  78394. # endif
  78395. # endif
  78396. #endif
  78397. #ifndef ZEXTERN
  78398. # define ZEXTERN extern
  78399. #endif
  78400. #ifndef ZEXPORT
  78401. # define ZEXPORT
  78402. #endif
  78403. #ifndef ZEXPORTVA
  78404. # define ZEXPORTVA
  78405. #endif
  78406. #ifndef FAR
  78407. # define FAR
  78408. #endif
  78409. #if !defined(__MACTYPES__)
  78410. typedef unsigned char Byte; /* 8 bits */
  78411. #endif
  78412. typedef unsigned int uInt; /* 16 bits or more */
  78413. typedef unsigned long uLong; /* 32 bits or more */
  78414. #ifdef SMALL_MEDIUM
  78415. /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
  78416. # define Bytef Byte FAR
  78417. #else
  78418. typedef Byte FAR Bytef;
  78419. #endif
  78420. typedef char FAR charf;
  78421. typedef int FAR intf;
  78422. typedef uInt FAR uIntf;
  78423. typedef uLong FAR uLongf;
  78424. #ifdef STDC
  78425. typedef void const *voidpc;
  78426. typedef void FAR *voidpf;
  78427. typedef void *voidp;
  78428. #else
  78429. typedef Byte const *voidpc;
  78430. typedef Byte FAR *voidpf;
  78431. typedef Byte *voidp;
  78432. #endif
  78433. #if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */
  78434. # include <sys/types.h> /* for off_t */
  78435. # include <unistd.h> /* for SEEK_* and off_t */
  78436. # ifdef VMS
  78437. # include <unixio.h> /* for off_t */
  78438. # endif
  78439. # define z_off_t off_t
  78440. #endif
  78441. #ifndef SEEK_SET
  78442. # define SEEK_SET 0 /* Seek from beginning of file. */
  78443. # define SEEK_CUR 1 /* Seek from current position. */
  78444. # define SEEK_END 2 /* Set file pointer to EOF plus "offset" */
  78445. #endif
  78446. #ifndef z_off_t
  78447. # define z_off_t long
  78448. #endif
  78449. #if defined(__OS400__)
  78450. # define NO_vsnprintf
  78451. #endif
  78452. #if defined(__MVS__)
  78453. # define NO_vsnprintf
  78454. # ifdef FAR
  78455. # undef FAR
  78456. # endif
  78457. #endif
  78458. /* MVS linker does not support external names larger than 8 bytes */
  78459. #if defined(__MVS__)
  78460. # pragma map(deflateInit_,"DEIN")
  78461. # pragma map(deflateInit2_,"DEIN2")
  78462. # pragma map(deflateEnd,"DEEND")
  78463. # pragma map(deflateBound,"DEBND")
  78464. # pragma map(inflateInit_,"ININ")
  78465. # pragma map(inflateInit2_,"ININ2")
  78466. # pragma map(inflateEnd,"INEND")
  78467. # pragma map(inflateSync,"INSY")
  78468. # pragma map(inflateSetDictionary,"INSEDI")
  78469. # pragma map(compressBound,"CMBND")
  78470. # pragma map(inflate_table,"INTABL")
  78471. # pragma map(inflate_fast,"INFA")
  78472. # pragma map(inflate_copyright,"INCOPY")
  78473. #endif
  78474. #endif /* ZCONF_H */
  78475. /*** End of inlined file: zconf.h ***/
  78476. #ifdef __cplusplus
  78477. //extern "C" {
  78478. #endif
  78479. #define ZLIB_VERSION "1.2.3"
  78480. #define ZLIB_VERNUM 0x1230
  78481. /*
  78482. The 'zlib' compression library provides in-memory compression and
  78483. decompression functions, including integrity checks of the uncompressed
  78484. data. This version of the library supports only one compression method
  78485. (deflation) but other algorithms will be added later and will have the same
  78486. stream interface.
  78487. Compression can be done in a single step if the buffers are large
  78488. enough (for example if an input file is mmap'ed), or can be done by
  78489. repeated calls of the compression function. In the latter case, the
  78490. application must provide more input and/or consume the output
  78491. (providing more output space) before each call.
  78492. The compressed data format used by default by the in-memory functions is
  78493. the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
  78494. around a deflate stream, which is itself documented in RFC 1951.
  78495. The library also supports reading and writing files in gzip (.gz) format
  78496. with an interface similar to that of stdio using the functions that start
  78497. with "gz". The gzip format is different from the zlib format. gzip is a
  78498. gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.
  78499. This library can optionally read and write gzip streams in memory as well.
  78500. The zlib format was designed to be compact and fast for use in memory
  78501. and on communications channels. The gzip format was designed for single-
  78502. file compression on file systems, has a larger header than zlib to maintain
  78503. directory information, and uses a different, slower check method than zlib.
  78504. The library does not install any signal handler. The decoder checks
  78505. the consistency of the compressed data, so the library should never
  78506. crash even in case of corrupted input.
  78507. */
  78508. typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
  78509. typedef void (*free_func) OF((voidpf opaque, voidpf address));
  78510. struct internal_state;
  78511. typedef struct z_stream_s {
  78512. Bytef *next_in; /* next input byte */
  78513. uInt avail_in; /* number of bytes available at next_in */
  78514. uLong total_in; /* total nb of input bytes read so far */
  78515. Bytef *next_out; /* next output byte should be put there */
  78516. uInt avail_out; /* remaining free space at next_out */
  78517. uLong total_out; /* total nb of bytes output so far */
  78518. char *msg; /* last error message, NULL if no error */
  78519. struct internal_state FAR *state; /* not visible by applications */
  78520. alloc_func zalloc; /* used to allocate the internal state */
  78521. free_func zfree; /* used to free the internal state */
  78522. voidpf opaque; /* private data object passed to zalloc and zfree */
  78523. int data_type; /* best guess about the data type: binary or text */
  78524. uLong adler; /* adler32 value of the uncompressed data */
  78525. uLong reserved; /* reserved for future use */
  78526. } z_stream;
  78527. typedef z_stream FAR *z_streamp;
  78528. /*
  78529. gzip header information passed to and from zlib routines. See RFC 1952
  78530. for more details on the meanings of these fields.
  78531. */
  78532. typedef struct gz_header_s {
  78533. int text; /* true if compressed data believed to be text */
  78534. uLong time; /* modification time */
  78535. int xflags; /* extra flags (not used when writing a gzip file) */
  78536. int os; /* operating system */
  78537. Bytef *extra; /* pointer to extra field or Z_NULL if none */
  78538. uInt extra_len; /* extra field length (valid if extra != Z_NULL) */
  78539. uInt extra_max; /* space at extra (only when reading header) */
  78540. Bytef *name; /* pointer to zero-terminated file name or Z_NULL */
  78541. uInt name_max; /* space at name (only when reading header) */
  78542. Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */
  78543. uInt comm_max; /* space at comment (only when reading header) */
  78544. int hcrc; /* true if there was or will be a header crc */
  78545. int done; /* true when done reading gzip header (not used
  78546. when writing a gzip file) */
  78547. } gz_header;
  78548. typedef gz_header FAR *gz_headerp;
  78549. /*
  78550. The application must update next_in and avail_in when avail_in has
  78551. dropped to zero. It must update next_out and avail_out when avail_out
  78552. has dropped to zero. The application must initialize zalloc, zfree and
  78553. opaque before calling the init function. All other fields are set by the
  78554. compression library and must not be updated by the application.
  78555. The opaque value provided by the application will be passed as the first
  78556. parameter for calls of zalloc and zfree. This can be useful for custom
  78557. memory management. The compression library attaches no meaning to the
  78558. opaque value.
  78559. zalloc must return Z_NULL if there is not enough memory for the object.
  78560. If zlib is used in a multi-threaded application, zalloc and zfree must be
  78561. thread safe.
  78562. On 16-bit systems, the functions zalloc and zfree must be able to allocate
  78563. exactly 65536 bytes, but will not be required to allocate more than this
  78564. if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
  78565. pointers returned by zalloc for objects of exactly 65536 bytes *must*
  78566. have their offset normalized to zero. The default allocation function
  78567. provided by this library ensures this (see zutil.c). To reduce memory
  78568. requirements and avoid any allocation of 64K objects, at the expense of
  78569. compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
  78570. The fields total_in and total_out can be used for statistics or
  78571. progress reports. After compression, total_in holds the total size of
  78572. the uncompressed data and may be saved for use in the decompressor
  78573. (particularly if the decompressor wants to decompress everything in
  78574. a single step).
  78575. */
  78576. /* constants */
  78577. #define Z_NO_FLUSH 0
  78578. #define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
  78579. #define Z_SYNC_FLUSH 2
  78580. #define Z_FULL_FLUSH 3
  78581. #define Z_FINISH 4
  78582. #define Z_BLOCK 5
  78583. /* Allowed flush values; see deflate() and inflate() below for details */
  78584. #define Z_OK 0
  78585. #define Z_STREAM_END 1
  78586. #define Z_NEED_DICT 2
  78587. #define Z_ERRNO (-1)
  78588. #define Z_STREAM_ERROR (-2)
  78589. #define Z_DATA_ERROR (-3)
  78590. #define Z_MEM_ERROR (-4)
  78591. #define Z_BUF_ERROR (-5)
  78592. #define Z_VERSION_ERROR (-6)
  78593. /* Return codes for the compression/decompression functions. Negative
  78594. * values are errors, positive values are used for special but normal events.
  78595. */
  78596. #define Z_NO_COMPRESSION 0
  78597. #define Z_BEST_SPEED 1
  78598. #define Z_BEST_COMPRESSION 9
  78599. #define Z_DEFAULT_COMPRESSION (-1)
  78600. /* compression levels */
  78601. #define Z_FILTERED 1
  78602. #define Z_HUFFMAN_ONLY 2
  78603. #define Z_RLE 3
  78604. #define Z_FIXED 4
  78605. #define Z_DEFAULT_STRATEGY 0
  78606. /* compression strategy; see deflateInit2() below for details */
  78607. #define Z_BINARY 0
  78608. #define Z_TEXT 1
  78609. #define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */
  78610. #define Z_UNKNOWN 2
  78611. /* Possible values of the data_type field (though see inflate()) */
  78612. #define Z_DEFLATED 8
  78613. /* The deflate compression method (the only one supported in this version) */
  78614. #define Z_NULL 0 /* for initializing zalloc, zfree, opaque */
  78615. #define zlib_version zlibVersion()
  78616. /* for compatibility with versions < 1.0.2 */
  78617. /* basic functions */
  78618. //ZEXTERN const char * ZEXPORT zlibVersion OF((void));
  78619. /* The application can compare zlibVersion and ZLIB_VERSION for consistency.
  78620. If the first character differs, the library code actually used is
  78621. not compatible with the zlib.h header file used by the application.
  78622. This check is automatically made by deflateInit and inflateInit.
  78623. */
  78624. /*
  78625. ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
  78626. Initializes the internal stream state for compression. The fields
  78627. zalloc, zfree and opaque must be initialized before by the caller.
  78628. If zalloc and zfree are set to Z_NULL, deflateInit updates them to
  78629. use default allocation functions.
  78630. The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
  78631. 1 gives best speed, 9 gives best compression, 0 gives no compression at
  78632. all (the input data is simply copied a block at a time).
  78633. Z_DEFAULT_COMPRESSION requests a default compromise between speed and
  78634. compression (currently equivalent to level 6).
  78635. deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
  78636. enough memory, Z_STREAM_ERROR if level is not a valid compression level,
  78637. Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
  78638. with the version assumed by the caller (ZLIB_VERSION).
  78639. msg is set to null if there is no error message. deflateInit does not
  78640. perform any compression: this will be done by deflate().
  78641. */
  78642. ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
  78643. /*
  78644. deflate compresses as much data as possible, and stops when the input
  78645. buffer becomes empty or the output buffer becomes full. It may introduce some
  78646. output latency (reading input without producing any output) except when
  78647. forced to flush.
  78648. The detailed semantics are as follows. deflate performs one or both of the
  78649. following actions:
  78650. - Compress more input starting at next_in and update next_in and avail_in
  78651. accordingly. If not all input can be processed (because there is not
  78652. enough room in the output buffer), next_in and avail_in are updated and
  78653. processing will resume at this point for the next call of deflate().
  78654. - Provide more output starting at next_out and update next_out and avail_out
  78655. accordingly. This action is forced if the parameter flush is non zero.
  78656. Forcing flush frequently degrades the compression ratio, so this parameter
  78657. should be set only when necessary (in interactive applications).
  78658. Some output may be provided even if flush is not set.
  78659. Before the call of deflate(), the application should ensure that at least
  78660. one of the actions is possible, by providing more input and/or consuming
  78661. more output, and updating avail_in or avail_out accordingly; avail_out
  78662. should never be zero before the call. The application can consume the
  78663. compressed output when it wants, for example when the output buffer is full
  78664. (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
  78665. and with zero avail_out, it must be called again after making room in the
  78666. output buffer because there might be more output pending.
  78667. Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to
  78668. decide how much data to accumualte before producing output, in order to
  78669. maximize compression.
  78670. If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
  78671. flushed to the output buffer and the output is aligned on a byte boundary, so
  78672. that the decompressor can get all input data available so far. (In particular
  78673. avail_in is zero after the call if enough output space has been provided
  78674. before the call.) Flushing may degrade compression for some compression
  78675. algorithms and so it should be used only when necessary.
  78676. If flush is set to Z_FULL_FLUSH, all output is flushed as with
  78677. Z_SYNC_FLUSH, and the compression state is reset so that decompression can
  78678. restart from this point if previous compressed data has been damaged or if
  78679. random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
  78680. compression.
  78681. If deflate returns with avail_out == 0, this function must be called again
  78682. with the same value of the flush parameter and more output space (updated
  78683. avail_out), until the flush is complete (deflate returns with non-zero
  78684. avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
  78685. avail_out is greater than six to avoid repeated flush markers due to
  78686. avail_out == 0 on return.
  78687. If the parameter flush is set to Z_FINISH, pending input is processed,
  78688. pending output is flushed and deflate returns with Z_STREAM_END if there
  78689. was enough output space; if deflate returns with Z_OK, this function must be
  78690. called again with Z_FINISH and more output space (updated avail_out) but no
  78691. more input data, until it returns with Z_STREAM_END or an error. After
  78692. deflate has returned Z_STREAM_END, the only possible operations on the
  78693. stream are deflateReset or deflateEnd.
  78694. Z_FINISH can be used immediately after deflateInit if all the compression
  78695. is to be done in a single step. In this case, avail_out must be at least
  78696. the value returned by deflateBound (see below). If deflate does not return
  78697. Z_STREAM_END, then it must be called again as described above.
  78698. deflate() sets strm->adler to the adler32 checksum of all input read
  78699. so far (that is, total_in bytes).
  78700. deflate() may update strm->data_type if it can make a good guess about
  78701. the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered
  78702. binary. This field is only for information purposes and does not affect
  78703. the compression algorithm in any manner.
  78704. deflate() returns Z_OK if some progress has been made (more input
  78705. processed or more output produced), Z_STREAM_END if all input has been
  78706. consumed and all output has been produced (only when flush is set to
  78707. Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
  78708. if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
  78709. (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not
  78710. fatal, and deflate() can be called again with more input and more output
  78711. space to continue compressing.
  78712. */
  78713. ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
  78714. /*
  78715. All dynamically allocated data structures for this stream are freed.
  78716. This function discards any unprocessed input and does not flush any
  78717. pending output.
  78718. deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
  78719. stream state was inconsistent, Z_DATA_ERROR if the stream was freed
  78720. prematurely (some input or output was discarded). In the error case,
  78721. msg may be set but then points to a static string (which must not be
  78722. deallocated).
  78723. */
  78724. /*
  78725. ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
  78726. Initializes the internal stream state for decompression. The fields
  78727. next_in, avail_in, zalloc, zfree and opaque must be initialized before by
  78728. the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
  78729. value depends on the compression method), inflateInit determines the
  78730. compression method from the zlib header and allocates all data structures
  78731. accordingly; otherwise the allocation will be deferred to the first call of
  78732. inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to
  78733. use default allocation functions.
  78734. inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78735. memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
  78736. version assumed by the caller. msg is set to null if there is no error
  78737. message. inflateInit does not perform any decompression apart from reading
  78738. the zlib header if present: this will be done by inflate(). (So next_in and
  78739. avail_in may be modified, but next_out and avail_out are unchanged.)
  78740. */
  78741. ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
  78742. /*
  78743. inflate decompresses as much data as possible, and stops when the input
  78744. buffer becomes empty or the output buffer becomes full. It may introduce
  78745. some output latency (reading input without producing any output) except when
  78746. forced to flush.
  78747. The detailed semantics are as follows. inflate performs one or both of the
  78748. following actions:
  78749. - Decompress more input starting at next_in and update next_in and avail_in
  78750. accordingly. If not all input can be processed (because there is not
  78751. enough room in the output buffer), next_in is updated and processing
  78752. will resume at this point for the next call of inflate().
  78753. - Provide more output starting at next_out and update next_out and avail_out
  78754. accordingly. inflate() provides as much output as possible, until there
  78755. is no more input data or no more space in the output buffer (see below
  78756. about the flush parameter).
  78757. Before the call of inflate(), the application should ensure that at least
  78758. one of the actions is possible, by providing more input and/or consuming
  78759. more output, and updating the next_* and avail_* values accordingly.
  78760. The application can consume the uncompressed output when it wants, for
  78761. example when the output buffer is full (avail_out == 0), or after each
  78762. call of inflate(). If inflate returns Z_OK and with zero avail_out, it
  78763. must be called again after making room in the output buffer because there
  78764. might be more output pending.
  78765. The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH,
  78766. Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much
  78767. output as possible to the output buffer. Z_BLOCK requests that inflate() stop
  78768. if and when it gets to the next deflate block boundary. When decoding the
  78769. zlib or gzip format, this will cause inflate() to return immediately after
  78770. the header and before the first block. When doing a raw inflate, inflate()
  78771. will go ahead and process the first block, and will return when it gets to
  78772. the end of that block, or when it runs out of data.
  78773. The Z_BLOCK option assists in appending to or combining deflate streams.
  78774. Also to assist in this, on return inflate() will set strm->data_type to the
  78775. number of unused bits in the last byte taken from strm->next_in, plus 64
  78776. if inflate() is currently decoding the last block in the deflate stream,
  78777. plus 128 if inflate() returned immediately after decoding an end-of-block
  78778. code or decoding the complete header up to just before the first byte of the
  78779. deflate stream. The end-of-block will not be indicated until all of the
  78780. uncompressed data from that block has been written to strm->next_out. The
  78781. number of unused bits may in general be greater than seven, except when
  78782. bit 7 of data_type is set, in which case the number of unused bits will be
  78783. less than eight.
  78784. inflate() should normally be called until it returns Z_STREAM_END or an
  78785. error. However if all decompression is to be performed in a single step
  78786. (a single call of inflate), the parameter flush should be set to
  78787. Z_FINISH. In this case all pending input is processed and all pending
  78788. output is flushed; avail_out must be large enough to hold all the
  78789. uncompressed data. (The size of the uncompressed data may have been saved
  78790. by the compressor for this purpose.) The next operation on this stream must
  78791. be inflateEnd to deallocate the decompression state. The use of Z_FINISH
  78792. is never required, but can be used to inform inflate that a faster approach
  78793. may be used for the single inflate() call.
  78794. In this implementation, inflate() always flushes as much output as
  78795. possible to the output buffer, and always uses the faster approach on the
  78796. first call. So the only effect of the flush parameter in this implementation
  78797. is on the return value of inflate(), as noted below, or when it returns early
  78798. because Z_BLOCK is used.
  78799. If a preset dictionary is needed after this call (see inflateSetDictionary
  78800. below), inflate sets strm->adler to the adler32 checksum of the dictionary
  78801. chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
  78802. strm->adler to the adler32 checksum of all output produced so far (that is,
  78803. total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
  78804. below. At the end of the stream, inflate() checks that its computed adler32
  78805. checksum is equal to that saved by the compressor and returns Z_STREAM_END
  78806. only if the checksum is correct.
  78807. inflate() will decompress and check either zlib-wrapped or gzip-wrapped
  78808. deflate data. The header type is detected automatically. Any information
  78809. contained in the gzip header is not retained, so applications that need that
  78810. information should instead use raw inflate, see inflateInit2() below, or
  78811. inflateBack() and perform their own processing of the gzip header and
  78812. trailer.
  78813. inflate() returns Z_OK if some progress has been made (more input processed
  78814. or more output produced), Z_STREAM_END if the end of the compressed data has
  78815. been reached and all uncompressed output has been produced, Z_NEED_DICT if a
  78816. preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
  78817. corrupted (input stream not conforming to the zlib format or incorrect check
  78818. value), Z_STREAM_ERROR if the stream structure was inconsistent (for example
  78819. if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory,
  78820. Z_BUF_ERROR if no progress is possible or if there was not enough room in the
  78821. output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and
  78822. inflate() can be called again with more input and more output space to
  78823. continue decompressing. If Z_DATA_ERROR is returned, the application may then
  78824. call inflateSync() to look for a good compression block if a partial recovery
  78825. of the data is desired.
  78826. */
  78827. ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
  78828. /*
  78829. All dynamically allocated data structures for this stream are freed.
  78830. This function discards any unprocessed input and does not flush any
  78831. pending output.
  78832. inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
  78833. was inconsistent. In the error case, msg may be set but then points to a
  78834. static string (which must not be deallocated).
  78835. */
  78836. /* Advanced functions */
  78837. /*
  78838. The following functions are needed only in some special applications.
  78839. */
  78840. /*
  78841. ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
  78842. int level,
  78843. int method,
  78844. int windowBits,
  78845. int memLevel,
  78846. int strategy));
  78847. This is another version of deflateInit with more compression options. The
  78848. fields next_in, zalloc, zfree and opaque must be initialized before by
  78849. the caller.
  78850. The method parameter is the compression method. It must be Z_DEFLATED in
  78851. this version of the library.
  78852. The windowBits parameter is the base two logarithm of the window size
  78853. (the size of the history buffer). It should be in the range 8..15 for this
  78854. version of the library. Larger values of this parameter result in better
  78855. compression at the expense of memory usage. The default value is 15 if
  78856. deflateInit is used instead.
  78857. windowBits can also be -8..-15 for raw deflate. In this case, -windowBits
  78858. determines the window size. deflate() will then generate raw deflate data
  78859. with no zlib header or trailer, and will not compute an adler32 check value.
  78860. windowBits can also be greater than 15 for optional gzip encoding. Add
  78861. 16 to windowBits to write a simple gzip header and trailer around the
  78862. compressed data instead of a zlib wrapper. The gzip header will have no
  78863. file name, no extra data, no comment, no modification time (set to zero),
  78864. no header crc, and the operating system will be set to 255 (unknown). If a
  78865. gzip stream is being written, strm->adler is a crc32 instead of an adler32.
  78866. The memLevel parameter specifies how much memory should be allocated
  78867. for the internal compression state. memLevel=1 uses minimum memory but
  78868. is slow and reduces compression ratio; memLevel=9 uses maximum memory
  78869. for optimal speed. The default value is 8. See zconf.h for total memory
  78870. usage as a function of windowBits and memLevel.
  78871. The strategy parameter is used to tune the compression algorithm. Use the
  78872. value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
  78873. filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no
  78874. string match), or Z_RLE to limit match distances to one (run-length
  78875. encoding). Filtered data consists mostly of small values with a somewhat
  78876. random distribution. In this case, the compression algorithm is tuned to
  78877. compress them better. The effect of Z_FILTERED is to force more Huffman
  78878. coding and less string matching; it is somewhat intermediate between
  78879. Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as
  78880. Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy
  78881. parameter only affects the compression ratio but not the correctness of the
  78882. compressed output even if it is not set appropriately. Z_FIXED prevents the
  78883. use of dynamic Huffman codes, allowing for a simpler decoder for special
  78884. applications.
  78885. deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78886. memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
  78887. method). msg is set to null if there is no error message. deflateInit2 does
  78888. not perform any compression: this will be done by deflate().
  78889. */
  78890. ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
  78891. const Bytef *dictionary,
  78892. uInt dictLength));
  78893. /*
  78894. Initializes the compression dictionary from the given byte sequence
  78895. without producing any compressed output. This function must be called
  78896. immediately after deflateInit, deflateInit2 or deflateReset, before any
  78897. call of deflate. The compressor and decompressor must use exactly the same
  78898. dictionary (see inflateSetDictionary).
  78899. The dictionary should consist of strings (byte sequences) that are likely
  78900. to be encountered later in the data to be compressed, with the most commonly
  78901. used strings preferably put towards the end of the dictionary. Using a
  78902. dictionary is most useful when the data to be compressed is short and can be
  78903. predicted with good accuracy; the data can then be compressed better than
  78904. with the default empty dictionary.
  78905. Depending on the size of the compression data structures selected by
  78906. deflateInit or deflateInit2, a part of the dictionary may in effect be
  78907. discarded, for example if the dictionary is larger than the window size in
  78908. deflate or deflate2. Thus the strings most likely to be useful should be
  78909. put at the end of the dictionary, not at the front. In addition, the
  78910. current implementation of deflate will use at most the window size minus
  78911. 262 bytes of the provided dictionary.
  78912. Upon return of this function, strm->adler is set to the adler32 value
  78913. of the dictionary; the decompressor may later use this value to determine
  78914. which dictionary has been used by the compressor. (The adler32 value
  78915. applies to the whole dictionary even if only a subset of the dictionary is
  78916. actually used by the compressor.) If a raw deflate was requested, then the
  78917. adler32 value is not computed and strm->adler is not set.
  78918. deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
  78919. parameter is invalid (such as NULL dictionary) or the stream state is
  78920. inconsistent (for example if deflate has already been called for this stream
  78921. or if the compression method is bsort). deflateSetDictionary does not
  78922. perform any compression: this will be done by deflate().
  78923. */
  78924. ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,
  78925. z_streamp source));
  78926. /*
  78927. Sets the destination stream as a complete copy of the source stream.
  78928. This function can be useful when several compression strategies will be
  78929. tried, for example when there are several ways of pre-processing the input
  78930. data with a filter. The streams that will be discarded should then be freed
  78931. by calling deflateEnd. Note that deflateCopy duplicates the internal
  78932. compression state which can be quite large, so this strategy is slow and
  78933. can consume lots of memory.
  78934. deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  78935. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  78936. (such as zalloc being NULL). msg is left unchanged in both source and
  78937. destination.
  78938. */
  78939. ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
  78940. /*
  78941. This function is equivalent to deflateEnd followed by deflateInit,
  78942. but does not free and reallocate all the internal compression state.
  78943. The stream will keep the same compression level and any other attributes
  78944. that may have been set by deflateInit2.
  78945. deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  78946. stream state was inconsistent (such as zalloc or state being NULL).
  78947. */
  78948. ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
  78949. int level,
  78950. int strategy));
  78951. /*
  78952. Dynamically update the compression level and compression strategy. The
  78953. interpretation of level and strategy is as in deflateInit2. This can be
  78954. used to switch between compression and straight copy of the input data, or
  78955. to switch to a different kind of input data requiring a different
  78956. strategy. If the compression level is changed, the input available so far
  78957. is compressed with the old level (and may be flushed); the new level will
  78958. take effect only at the next call of deflate().
  78959. Before the call of deflateParams, the stream state must be set as for
  78960. a call of deflate(), since the currently available input may have to
  78961. be compressed and flushed. In particular, strm->avail_out must be non-zero.
  78962. deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
  78963. stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
  78964. if strm->avail_out was zero.
  78965. */
  78966. ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm,
  78967. int good_length,
  78968. int max_lazy,
  78969. int nice_length,
  78970. int max_chain));
  78971. /*
  78972. Fine tune deflate's internal compression parameters. This should only be
  78973. used by someone who understands the algorithm used by zlib's deflate for
  78974. searching for the best matching string, and even then only by the most
  78975. fanatic optimizer trying to squeeze out the last compressed bit for their
  78976. specific input data. Read the deflate.c source code for the meaning of the
  78977. max_lazy, good_length, nice_length, and max_chain parameters.
  78978. deflateTune() can be called after deflateInit() or deflateInit2(), and
  78979. returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.
  78980. */
  78981. ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm,
  78982. uLong sourceLen));
  78983. /*
  78984. deflateBound() returns an upper bound on the compressed size after
  78985. deflation of sourceLen bytes. It must be called after deflateInit()
  78986. or deflateInit2(). This would be used to allocate an output buffer
  78987. for deflation in a single pass, and so would be called before deflate().
  78988. */
  78989. ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,
  78990. int bits,
  78991. int value));
  78992. /*
  78993. deflatePrime() inserts bits in the deflate output stream. The intent
  78994. is that this function is used to start off the deflate output with the
  78995. bits leftover from a previous deflate stream when appending to it. As such,
  78996. this function can only be used for raw deflate, and must be used before the
  78997. first deflate() call after a deflateInit2() or deflateReset(). bits must be
  78998. less than or equal to 16, and that many of the least significant bits of
  78999. value will be inserted in the output.
  79000. deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  79001. stream state was inconsistent.
  79002. */
  79003. ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm,
  79004. gz_headerp head));
  79005. /*
  79006. deflateSetHeader() provides gzip header information for when a gzip
  79007. stream is requested by deflateInit2(). deflateSetHeader() may be called
  79008. after deflateInit2() or deflateReset() and before the first call of
  79009. deflate(). The text, time, os, extra field, name, and comment information
  79010. in the provided gz_header structure are written to the gzip header (xflag is
  79011. ignored -- the extra flags are set according to the compression level). The
  79012. caller must assure that, if not Z_NULL, name and comment are terminated with
  79013. a zero byte, and that if extra is not Z_NULL, that extra_len bytes are
  79014. available there. If hcrc is true, a gzip header crc is included. Note that
  79015. the current versions of the command-line version of gzip (up through version
  79016. 1.3.x) do not support header crc's, and will report that it is a "multi-part
  79017. gzip file" and give up.
  79018. If deflateSetHeader is not used, the default gzip header has text false,
  79019. the time set to zero, and os set to 255, with no extra, name, or comment
  79020. fields. The gzip header is returned to the default state by deflateReset().
  79021. deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  79022. stream state was inconsistent.
  79023. */
  79024. /*
  79025. ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
  79026. int windowBits));
  79027. This is another version of inflateInit with an extra parameter. The
  79028. fields next_in, avail_in, zalloc, zfree and opaque must be initialized
  79029. before by the caller.
  79030. The windowBits parameter is the base two logarithm of the maximum window
  79031. size (the size of the history buffer). It should be in the range 8..15 for
  79032. this version of the library. The default value is 15 if inflateInit is used
  79033. instead. windowBits must be greater than or equal to the windowBits value
  79034. provided to deflateInit2() while compressing, or it must be equal to 15 if
  79035. deflateInit2() was not used. If a compressed stream with a larger window
  79036. size is given as input, inflate() will return with the error code
  79037. Z_DATA_ERROR instead of trying to allocate a larger window.
  79038. windowBits can also be -8..-15 for raw inflate. In this case, -windowBits
  79039. determines the window size. inflate() will then process raw deflate data,
  79040. not looking for a zlib or gzip header, not generating a check value, and not
  79041. looking for any check values for comparison at the end of the stream. This
  79042. is for use with other formats that use the deflate compressed data format
  79043. such as zip. Those formats provide their own check values. If a custom
  79044. format is developed using the raw deflate format for compressed data, it is
  79045. recommended that a check value such as an adler32 or a crc32 be applied to
  79046. the uncompressed data as is done in the zlib, gzip, and zip formats. For
  79047. most applications, the zlib format should be used as is. Note that comments
  79048. above on the use in deflateInit2() applies to the magnitude of windowBits.
  79049. windowBits can also be greater than 15 for optional gzip decoding. Add
  79050. 32 to windowBits to enable zlib and gzip decoding with automatic header
  79051. detection, or add 16 to decode only the gzip format (the zlib format will
  79052. return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is
  79053. a crc32 instead of an adler32.
  79054. inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  79055. memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg
  79056. is set to null if there is no error message. inflateInit2 does not perform
  79057. any decompression apart from reading the zlib header if present: this will
  79058. be done by inflate(). (So next_in and avail_in may be modified, but next_out
  79059. and avail_out are unchanged.)
  79060. */
  79061. ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
  79062. const Bytef *dictionary,
  79063. uInt dictLength));
  79064. /*
  79065. Initializes the decompression dictionary from the given uncompressed byte
  79066. sequence. This function must be called immediately after a call of inflate,
  79067. if that call returned Z_NEED_DICT. The dictionary chosen by the compressor
  79068. can be determined from the adler32 value returned by that call of inflate.
  79069. The compressor and decompressor must use exactly the same dictionary (see
  79070. deflateSetDictionary). For raw inflate, this function can be called
  79071. immediately after inflateInit2() or inflateReset() and before any call of
  79072. inflate() to set the dictionary. The application must insure that the
  79073. dictionary that was used for compression is provided.
  79074. inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
  79075. parameter is invalid (such as NULL dictionary) or the stream state is
  79076. inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
  79077. expected one (incorrect adler32 value). inflateSetDictionary does not
  79078. perform any decompression: this will be done by subsequent calls of
  79079. inflate().
  79080. */
  79081. ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
  79082. /*
  79083. Skips invalid compressed data until a full flush point (see above the
  79084. description of deflate with Z_FULL_FLUSH) can be found, or until all
  79085. available input is skipped. No output is provided.
  79086. inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
  79087. if no more input was provided, Z_DATA_ERROR if no flush point has been found,
  79088. or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
  79089. case, the application may save the current current value of total_in which
  79090. indicates where valid compressed data was found. In the error case, the
  79091. application may repeatedly call inflateSync, providing more input each time,
  79092. until success or end of the input data.
  79093. */
  79094. ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest,
  79095. z_streamp source));
  79096. /*
  79097. Sets the destination stream as a complete copy of the source stream.
  79098. This function can be useful when randomly accessing a large stream. The
  79099. first pass through the stream can periodically record the inflate state,
  79100. allowing restarting inflate at those points when randomly accessing the
  79101. stream.
  79102. inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  79103. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  79104. (such as zalloc being NULL). msg is left unchanged in both source and
  79105. destination.
  79106. */
  79107. ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
  79108. /*
  79109. This function is equivalent to inflateEnd followed by inflateInit,
  79110. but does not free and reallocate all the internal decompression state.
  79111. The stream will keep attributes that may have been set by inflateInit2.
  79112. inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  79113. stream state was inconsistent (such as zalloc or state being NULL).
  79114. */
  79115. ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm,
  79116. int bits,
  79117. int value));
  79118. /*
  79119. This function inserts bits in the inflate input stream. The intent is
  79120. that this function is used to start inflating at a bit position in the
  79121. middle of a byte. The provided bits will be used before any bytes are used
  79122. from next_in. This function should only be used with raw inflate, and
  79123. should be used before the first inflate() call after inflateInit2() or
  79124. inflateReset(). bits must be less than or equal to 16, and that many of the
  79125. least significant bits of value will be inserted in the input.
  79126. inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  79127. stream state was inconsistent.
  79128. */
  79129. ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm,
  79130. gz_headerp head));
  79131. /*
  79132. inflateGetHeader() requests that gzip header information be stored in the
  79133. provided gz_header structure. inflateGetHeader() may be called after
  79134. inflateInit2() or inflateReset(), and before the first call of inflate().
  79135. As inflate() processes the gzip stream, head->done is zero until the header
  79136. is completed, at which time head->done is set to one. If a zlib stream is
  79137. being decoded, then head->done is set to -1 to indicate that there will be
  79138. no gzip header information forthcoming. Note that Z_BLOCK can be used to
  79139. force inflate() to return immediately after header processing is complete
  79140. and before any actual data is decompressed.
  79141. The text, time, xflags, and os fields are filled in with the gzip header
  79142. contents. hcrc is set to true if there is a header CRC. (The header CRC
  79143. was valid if done is set to one.) If extra is not Z_NULL, then extra_max
  79144. contains the maximum number of bytes to write to extra. Once done is true,
  79145. extra_len contains the actual extra field length, and extra contains the
  79146. extra field, or that field truncated if extra_max is less than extra_len.
  79147. If name is not Z_NULL, then up to name_max characters are written there,
  79148. terminated with a zero unless the length is greater than name_max. If
  79149. comment is not Z_NULL, then up to comm_max characters are written there,
  79150. terminated with a zero unless the length is greater than comm_max. When
  79151. any of extra, name, or comment are not Z_NULL and the respective field is
  79152. not present in the header, then that field is set to Z_NULL to signal its
  79153. absence. This allows the use of deflateSetHeader() with the returned
  79154. structure to duplicate the header. However if those fields are set to
  79155. allocated memory, then the application will need to save those pointers
  79156. elsewhere so that they can be eventually freed.
  79157. If inflateGetHeader is not used, then the header information is simply
  79158. discarded. The header is always checked for validity, including the header
  79159. CRC if present. inflateReset() will reset the process to discard the header
  79160. information. The application would need to call inflateGetHeader() again to
  79161. retrieve the header from the next gzip stream.
  79162. inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  79163. stream state was inconsistent.
  79164. */
  79165. /*
  79166. ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits,
  79167. unsigned char FAR *window));
  79168. Initialize the internal stream state for decompression using inflateBack()
  79169. calls. The fields zalloc, zfree and opaque in strm must be initialized
  79170. before the call. If zalloc and zfree are Z_NULL, then the default library-
  79171. derived memory allocation routines are used. windowBits is the base two
  79172. logarithm of the window size, in the range 8..15. window is a caller
  79173. supplied buffer of that size. Except for special applications where it is
  79174. assured that deflate was used with small window sizes, windowBits must be 15
  79175. and a 32K byte window must be supplied to be able to decompress general
  79176. deflate streams.
  79177. See inflateBack() for the usage of these routines.
  79178. inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of
  79179. the paramaters are invalid, Z_MEM_ERROR if the internal state could not
  79180. be allocated, or Z_VERSION_ERROR if the version of the library does not
  79181. match the version of the header file.
  79182. */
  79183. typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *));
  79184. typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned));
  79185. ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm,
  79186. in_func in, void FAR *in_desc,
  79187. out_func out, void FAR *out_desc));
  79188. /*
  79189. inflateBack() does a raw inflate with a single call using a call-back
  79190. interface for input and output. This is more efficient than inflate() for
  79191. file i/o applications in that it avoids copying between the output and the
  79192. sliding window by simply making the window itself the output buffer. This
  79193. function trusts the application to not change the output buffer passed by
  79194. the output function, at least until inflateBack() returns.
  79195. inflateBackInit() must be called first to allocate the internal state
  79196. and to initialize the state with the user-provided window buffer.
  79197. inflateBack() may then be used multiple times to inflate a complete, raw
  79198. deflate stream with each call. inflateBackEnd() is then called to free
  79199. the allocated state.
  79200. A raw deflate stream is one with no zlib or gzip header or trailer.
  79201. This routine would normally be used in a utility that reads zip or gzip
  79202. files and writes out uncompressed files. The utility would decode the
  79203. header and process the trailer on its own, hence this routine expects
  79204. only the raw deflate stream to decompress. This is different from the
  79205. normal behavior of inflate(), which expects either a zlib or gzip header and
  79206. trailer around the deflate stream.
  79207. inflateBack() uses two subroutines supplied by the caller that are then
  79208. called by inflateBack() for input and output. inflateBack() calls those
  79209. routines until it reads a complete deflate stream and writes out all of the
  79210. uncompressed data, or until it encounters an error. The function's
  79211. parameters and return types are defined above in the in_func and out_func
  79212. typedefs. inflateBack() will call in(in_desc, &buf) which should return the
  79213. number of bytes of provided input, and a pointer to that input in buf. If
  79214. there is no input available, in() must return zero--buf is ignored in that
  79215. case--and inflateBack() will return a buffer error. inflateBack() will call
  79216. out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out()
  79217. should return zero on success, or non-zero on failure. If out() returns
  79218. non-zero, inflateBack() will return with an error. Neither in() nor out()
  79219. are permitted to change the contents of the window provided to
  79220. inflateBackInit(), which is also the buffer that out() uses to write from.
  79221. The length written by out() will be at most the window size. Any non-zero
  79222. amount of input may be provided by in().
  79223. For convenience, inflateBack() can be provided input on the first call by
  79224. setting strm->next_in and strm->avail_in. If that input is exhausted, then
  79225. in() will be called. Therefore strm->next_in must be initialized before
  79226. calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called
  79227. immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in
  79228. must also be initialized, and then if strm->avail_in is not zero, input will
  79229. initially be taken from strm->next_in[0 .. strm->avail_in - 1].
  79230. The in_desc and out_desc parameters of inflateBack() is passed as the
  79231. first parameter of in() and out() respectively when they are called. These
  79232. descriptors can be optionally used to pass any information that the caller-
  79233. supplied in() and out() functions need to do their job.
  79234. On return, inflateBack() will set strm->next_in and strm->avail_in to
  79235. pass back any unused input that was provided by the last in() call. The
  79236. return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR
  79237. if in() or out() returned an error, Z_DATA_ERROR if there was a format
  79238. error in the deflate stream (in which case strm->msg is set to indicate the
  79239. nature of the error), or Z_STREAM_ERROR if the stream was not properly
  79240. initialized. In the case of Z_BUF_ERROR, an input or output error can be
  79241. distinguished using strm->next_in which will be Z_NULL only if in() returned
  79242. an error. If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to
  79243. out() returning non-zero. (in() will always be called before out(), so
  79244. strm->next_in is assured to be defined if out() returns non-zero.) Note
  79245. that inflateBack() cannot return Z_OK.
  79246. */
  79247. ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm));
  79248. /*
  79249. All memory allocated by inflateBackInit() is freed.
  79250. inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream
  79251. state was inconsistent.
  79252. */
  79253. //ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void));
  79254. /* Return flags indicating compile-time options.
  79255. Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other:
  79256. 1.0: size of uInt
  79257. 3.2: size of uLong
  79258. 5.4: size of voidpf (pointer)
  79259. 7.6: size of z_off_t
  79260. Compiler, assembler, and debug options:
  79261. 8: DEBUG
  79262. 9: ASMV or ASMINF -- use ASM code
  79263. 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention
  79264. 11: 0 (reserved)
  79265. One-time table building (smaller code, but not thread-safe if true):
  79266. 12: BUILDFIXED -- build static block decoding tables when needed
  79267. 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed
  79268. 14,15: 0 (reserved)
  79269. Library content (indicates missing functionality):
  79270. 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking
  79271. deflate code when not needed)
  79272. 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect
  79273. and decode gzip streams (to avoid linking crc code)
  79274. 18-19: 0 (reserved)
  79275. Operation variations (changes in library functionality):
  79276. 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate
  79277. 21: FASTEST -- deflate algorithm with only one, lowest compression level
  79278. 22,23: 0 (reserved)
  79279. The sprintf variant used by gzprintf (zero is best):
  79280. 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format
  79281. 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure!
  79282. 26: 0 = returns value, 1 = void -- 1 means inferred string length returned
  79283. Remainder:
  79284. 27-31: 0 (reserved)
  79285. */
  79286. /* utility functions */
  79287. /*
  79288. The following utility functions are implemented on top of the
  79289. basic stream-oriented functions. To simplify the interface, some
  79290. default options are assumed (compression level and memory usage,
  79291. standard memory allocation functions). The source code of these
  79292. utility functions can easily be modified if you need special options.
  79293. */
  79294. ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen,
  79295. const Bytef *source, uLong sourceLen));
  79296. /*
  79297. Compresses the source buffer into the destination buffer. sourceLen is
  79298. the byte length of the source buffer. Upon entry, destLen is the total
  79299. size of the destination buffer, which must be at least the value returned
  79300. by compressBound(sourceLen). Upon exit, destLen is the actual size of the
  79301. compressed buffer.
  79302. This function can be used to compress a whole file at once if the
  79303. input file is mmap'ed.
  79304. compress returns Z_OK if success, Z_MEM_ERROR if there was not
  79305. enough memory, Z_BUF_ERROR if there was not enough room in the output
  79306. buffer.
  79307. */
  79308. ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen,
  79309. const Bytef *source, uLong sourceLen,
  79310. int level));
  79311. /*
  79312. Compresses the source buffer into the destination buffer. The level
  79313. parameter has the same meaning as in deflateInit. sourceLen is the byte
  79314. length of the source buffer. Upon entry, destLen is the total size of the
  79315. destination buffer, which must be at least the value returned by
  79316. compressBound(sourceLen). Upon exit, destLen is the actual size of the
  79317. compressed buffer.
  79318. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  79319. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  79320. Z_STREAM_ERROR if the level parameter is invalid.
  79321. */
  79322. ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen));
  79323. /*
  79324. compressBound() returns an upper bound on the compressed size after
  79325. compress() or compress2() on sourceLen bytes. It would be used before
  79326. a compress() or compress2() call to allocate the destination buffer.
  79327. */
  79328. ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen,
  79329. const Bytef *source, uLong sourceLen));
  79330. /*
  79331. Decompresses the source buffer into the destination buffer. sourceLen is
  79332. the byte length of the source buffer. Upon entry, destLen is the total
  79333. size of the destination buffer, which must be large enough to hold the
  79334. entire uncompressed data. (The size of the uncompressed data must have
  79335. been saved previously by the compressor and transmitted to the decompressor
  79336. by some mechanism outside the scope of this compression library.)
  79337. Upon exit, destLen is the actual size of the compressed buffer.
  79338. This function can be used to decompress a whole file at once if the
  79339. input file is mmap'ed.
  79340. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
  79341. enough memory, Z_BUF_ERROR if there was not enough room in the output
  79342. buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete.
  79343. */
  79344. typedef voidp gzFile;
  79345. ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));
  79346. /*
  79347. Opens a gzip (.gz) file for reading or writing. The mode parameter
  79348. is as in fopen ("rb" or "wb") but can also include a compression level
  79349. ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
  79350. Huffman only compression as in "wb1h", or 'R' for run-length encoding
  79351. as in "wb1R". (See the description of deflateInit2 for more information
  79352. about the strategy parameter.)
  79353. gzopen can be used to read a file which is not in gzip format; in this
  79354. case gzread will directly read from the file without decompression.
  79355. gzopen returns NULL if the file could not be opened or if there was
  79356. insufficient memory to allocate the (de)compression state; errno
  79357. can be checked to distinguish the two cases (if errno is zero, the
  79358. zlib error is Z_MEM_ERROR). */
  79359. ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));
  79360. /*
  79361. gzdopen() associates a gzFile with the file descriptor fd. File
  79362. descriptors are obtained from calls like open, dup, creat, pipe or
  79363. fileno (in the file has been previously opened with fopen).
  79364. The mode parameter is as in gzopen.
  79365. The next call of gzclose on the returned gzFile will also close the
  79366. file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
  79367. descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
  79368. gzdopen returns NULL if there was insufficient memory to allocate
  79369. the (de)compression state.
  79370. */
  79371. ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
  79372. /*
  79373. Dynamically update the compression level or strategy. See the description
  79374. of deflateInit2 for the meaning of these parameters.
  79375. gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
  79376. opened for writing.
  79377. */
  79378. ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));
  79379. /*
  79380. Reads the given number of uncompressed bytes from the compressed file.
  79381. If the input file was not in gzip format, gzread copies the given number
  79382. of bytes into the buffer.
  79383. gzread returns the number of uncompressed bytes actually read (0 for
  79384. end of file, -1 for error). */
  79385. ZEXTERN int ZEXPORT gzwrite OF((gzFile file,
  79386. voidpc buf, unsigned len));
  79387. /*
  79388. Writes the given number of uncompressed bytes into the compressed file.
  79389. gzwrite returns the number of uncompressed bytes actually written
  79390. (0 in case of error).
  79391. */
  79392. ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...));
  79393. /*
  79394. Converts, formats, and writes the args to the compressed file under
  79395. control of the format string, as in fprintf. gzprintf returns the number of
  79396. uncompressed bytes actually written (0 in case of error). The number of
  79397. uncompressed bytes written is limited to 4095. The caller should assure that
  79398. this limit is not exceeded. If it is exceeded, then gzprintf() will return
  79399. return an error (0) with nothing written. In this case, there may also be a
  79400. buffer overflow with unpredictable consequences, which is possible only if
  79401. zlib was compiled with the insecure functions sprintf() or vsprintf()
  79402. because the secure snprintf() or vsnprintf() functions were not available.
  79403. */
  79404. ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
  79405. /*
  79406. Writes the given null-terminated string to the compressed file, excluding
  79407. the terminating null character.
  79408. gzputs returns the number of characters written, or -1 in case of error.
  79409. */
  79410. ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));
  79411. /*
  79412. Reads bytes from the compressed file until len-1 characters are read, or
  79413. a newline character is read and transferred to buf, or an end-of-file
  79414. condition is encountered. The string is then terminated with a null
  79415. character.
  79416. gzgets returns buf, or Z_NULL in case of error.
  79417. */
  79418. ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c));
  79419. /*
  79420. Writes c, converted to an unsigned char, into the compressed file.
  79421. gzputc returns the value that was written, or -1 in case of error.
  79422. */
  79423. ZEXTERN int ZEXPORT gzgetc OF((gzFile file));
  79424. /*
  79425. Reads one byte from the compressed file. gzgetc returns this byte
  79426. or -1 in case of end of file or error.
  79427. */
  79428. ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file));
  79429. /*
  79430. Push one character back onto the stream to be read again later.
  79431. Only one character of push-back is allowed. gzungetc() returns the
  79432. character pushed, or -1 on failure. gzungetc() will fail if a
  79433. character has been pushed but not read yet, or if c is -1. The pushed
  79434. character will be discarded if the stream is repositioned with gzseek()
  79435. or gzrewind().
  79436. */
  79437. ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush));
  79438. /*
  79439. Flushes all pending output into the compressed file. The parameter
  79440. flush is as in the deflate() function. The return value is the zlib
  79441. error number (see function gzerror below). gzflush returns Z_OK if
  79442. the flush parameter is Z_FINISH and all output could be flushed.
  79443. gzflush should be called only when strictly necessary because it can
  79444. degrade compression.
  79445. */
  79446. ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file,
  79447. z_off_t offset, int whence));
  79448. /*
  79449. Sets the starting position for the next gzread or gzwrite on the
  79450. given compressed file. The offset represents a number of bytes in the
  79451. uncompressed data stream. The whence parameter is defined as in lseek(2);
  79452. the value SEEK_END is not supported.
  79453. If the file is opened for reading, this function is emulated but can be
  79454. extremely slow. If the file is opened for writing, only forward seeks are
  79455. supported; gzseek then compresses a sequence of zeroes up to the new
  79456. starting position.
  79457. gzseek returns the resulting offset location as measured in bytes from
  79458. the beginning of the uncompressed stream, or -1 in case of error, in
  79459. particular if the file is opened for writing and the new starting position
  79460. would be before the current position.
  79461. */
  79462. ZEXTERN int ZEXPORT gzrewind OF((gzFile file));
  79463. /*
  79464. Rewinds the given file. This function is supported only for reading.
  79465. gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
  79466. */
  79467. ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file));
  79468. /*
  79469. Returns the starting position for the next gzread or gzwrite on the
  79470. given compressed file. This position represents a number of bytes in the
  79471. uncompressed data stream.
  79472. gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
  79473. */
  79474. ZEXTERN int ZEXPORT gzeof OF((gzFile file));
  79475. /*
  79476. Returns 1 when EOF has previously been detected reading the given
  79477. input stream, otherwise zero.
  79478. */
  79479. ZEXTERN int ZEXPORT gzdirect OF((gzFile file));
  79480. /*
  79481. Returns 1 if file is being read directly without decompression, otherwise
  79482. zero.
  79483. */
  79484. ZEXTERN int ZEXPORT gzclose OF((gzFile file));
  79485. /*
  79486. Flushes all pending output if necessary, closes the compressed file
  79487. and deallocates all the (de)compression state. The return value is the zlib
  79488. error number (see function gzerror below).
  79489. */
  79490. ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
  79491. /*
  79492. Returns the error message for the last error which occurred on the
  79493. given compressed file. errnum is set to zlib error number. If an
  79494. error occurred in the file system and not in the compression library,
  79495. errnum is set to Z_ERRNO and the application may consult errno
  79496. to get the exact error code.
  79497. */
  79498. ZEXTERN void ZEXPORT gzclearerr OF((gzFile file));
  79499. /*
  79500. Clears the error and end-of-file flags for file. This is analogous to the
  79501. clearerr() function in stdio. This is useful for continuing to read a gzip
  79502. file that is being written concurrently.
  79503. */
  79504. /* checksum functions */
  79505. /*
  79506. These functions are not related to compression but are exported
  79507. anyway because they might be useful in applications using the
  79508. compression library.
  79509. */
  79510. ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
  79511. /*
  79512. Update a running Adler-32 checksum with the bytes buf[0..len-1] and
  79513. return the updated checksum. If buf is NULL, this function returns
  79514. the required initial value for the checksum.
  79515. An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
  79516. much faster. Usage example:
  79517. uLong adler = adler32(0L, Z_NULL, 0);
  79518. while (read_buffer(buffer, length) != EOF) {
  79519. adler = adler32(adler, buffer, length);
  79520. }
  79521. if (adler != original_adler) error();
  79522. */
  79523. ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2,
  79524. z_off_t len2));
  79525. /*
  79526. Combine two Adler-32 checksums into one. For two sequences of bytes, seq1
  79527. and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for
  79528. each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of
  79529. seq1 and seq2 concatenated, requiring only adler1, adler2, and len2.
  79530. */
  79531. ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len));
  79532. /*
  79533. Update a running CRC-32 with the bytes buf[0..len-1] and return the
  79534. updated CRC-32. If buf is NULL, this function returns the required initial
  79535. value for the for the crc. Pre- and post-conditioning (one's complement) is
  79536. performed within this function so it shouldn't be done by the application.
  79537. Usage example:
  79538. uLong crc = crc32(0L, Z_NULL, 0);
  79539. while (read_buffer(buffer, length) != EOF) {
  79540. crc = crc32(crc, buffer, length);
  79541. }
  79542. if (crc != original_crc) error();
  79543. */
  79544. ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2));
  79545. /*
  79546. Combine two CRC-32 check values into one. For two sequences of bytes,
  79547. seq1 and seq2 with lengths len1 and len2, CRC-32 check values were
  79548. calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32
  79549. check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and
  79550. len2.
  79551. */
  79552. /* various hacks, don't look :) */
  79553. /* deflateInit and inflateInit are macros to allow checking the zlib version
  79554. * and the compiler's view of z_stream:
  79555. */
  79556. ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,
  79557. const char *version, int stream_size));
  79558. ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,
  79559. const char *version, int stream_size));
  79560. ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method,
  79561. int windowBits, int memLevel,
  79562. int strategy, const char *version,
  79563. int stream_size));
  79564. ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits,
  79565. const char *version, int stream_size));
  79566. ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits,
  79567. unsigned char FAR *window,
  79568. const char *version,
  79569. int stream_size));
  79570. #define deflateInit(strm, level) \
  79571. deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream))
  79572. #define inflateInit(strm) \
  79573. inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream))
  79574. #define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
  79575. deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
  79576. (strategy), ZLIB_VERSION, sizeof(z_stream))
  79577. #define inflateInit2(strm, windowBits) \
  79578. inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
  79579. #define inflateBackInit(strm, windowBits, window) \
  79580. inflateBackInit_((strm), (windowBits), (window), \
  79581. ZLIB_VERSION, sizeof(z_stream))
  79582. #if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL)
  79583. struct internal_state {int dummy;}; /* hack for buggy compilers */
  79584. #endif
  79585. ZEXTERN const char * ZEXPORT zError OF((int));
  79586. ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z));
  79587. ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void));
  79588. #ifdef __cplusplus
  79589. //}
  79590. #endif
  79591. #endif /* ZLIB_H */
  79592. /*** End of inlined file: zlib.h ***/
  79593. #undef OS_CODE
  79594. #else
  79595. #include <zlib.h>
  79596. #endif
  79597. }
  79598. BEGIN_JUCE_NAMESPACE
  79599. // internal helper object that holds the zlib structures so they don't have to be
  79600. // included publicly.
  79601. class GZIPCompressorHelper
  79602. {
  79603. public:
  79604. GZIPCompressorHelper (const int compressionLevel, const bool nowrap)
  79605. : data (0),
  79606. dataSize (0),
  79607. compLevel (compressionLevel),
  79608. strategy (0),
  79609. setParams (true),
  79610. streamIsValid (false),
  79611. finished (false),
  79612. shouldFinish (false)
  79613. {
  79614. using namespace zlibNamespace;
  79615. zerostruct (stream);
  79616. streamIsValid = (deflateInit2 (&stream, compLevel, Z_DEFLATED,
  79617. nowrap ? -MAX_WBITS : MAX_WBITS,
  79618. 8, strategy) == Z_OK);
  79619. }
  79620. ~GZIPCompressorHelper()
  79621. {
  79622. using namespace zlibNamespace;
  79623. if (streamIsValid)
  79624. deflateEnd (&stream);
  79625. }
  79626. bool needsInput() const throw()
  79627. {
  79628. return dataSize <= 0;
  79629. }
  79630. void setInput (const uint8* const newData, const int size) throw()
  79631. {
  79632. data = newData;
  79633. dataSize = size;
  79634. }
  79635. int doNextBlock (uint8* const dest, const int destSize) throw()
  79636. {
  79637. using namespace zlibNamespace;
  79638. if (streamIsValid)
  79639. {
  79640. stream.next_in = const_cast <uint8*> (data);
  79641. stream.next_out = dest;
  79642. stream.avail_in = dataSize;
  79643. stream.avail_out = destSize;
  79644. const int result = setParams ? deflateParams (&stream, compLevel, strategy)
  79645. : deflate (&stream, shouldFinish ? Z_FINISH : Z_NO_FLUSH);
  79646. setParams = false;
  79647. switch (result)
  79648. {
  79649. case Z_STREAM_END:
  79650. finished = true;
  79651. // Deliberate fall-through..
  79652. case Z_OK:
  79653. data += dataSize - stream.avail_in;
  79654. dataSize = stream.avail_in;
  79655. return destSize - stream.avail_out;
  79656. default:
  79657. break;
  79658. }
  79659. }
  79660. return 0;
  79661. }
  79662. private:
  79663. zlibNamespace::z_stream stream;
  79664. const uint8* data;
  79665. int dataSize, compLevel, strategy;
  79666. bool setParams, streamIsValid;
  79667. public:
  79668. bool finished, shouldFinish;
  79669. };
  79670. const int gzipCompBufferSize = 32768;
  79671. GZIPCompressorOutputStream::GZIPCompressorOutputStream (OutputStream* const destStream_,
  79672. int compressionLevel,
  79673. const bool deleteDestStream,
  79674. const bool noWrap)
  79675. : destStream (destStream_),
  79676. streamToDelete (deleteDestStream ? destStream_ : 0),
  79677. buffer (gzipCompBufferSize)
  79678. {
  79679. if (compressionLevel < 1 || compressionLevel > 9)
  79680. compressionLevel = -1;
  79681. helper = new GZIPCompressorHelper (compressionLevel, noWrap);
  79682. }
  79683. GZIPCompressorOutputStream::~GZIPCompressorOutputStream()
  79684. {
  79685. flush();
  79686. }
  79687. void GZIPCompressorOutputStream::flush()
  79688. {
  79689. if (! helper->finished)
  79690. {
  79691. helper->shouldFinish = true;
  79692. while (! helper->finished)
  79693. doNextBlock();
  79694. }
  79695. destStream->flush();
  79696. }
  79697. bool GZIPCompressorOutputStream::write (const void* destBuffer, int howMany)
  79698. {
  79699. if (! helper->finished)
  79700. {
  79701. helper->setInput (static_cast <const uint8*> (destBuffer), howMany);
  79702. while (! helper->needsInput())
  79703. {
  79704. if (! doNextBlock())
  79705. return false;
  79706. }
  79707. }
  79708. return true;
  79709. }
  79710. bool GZIPCompressorOutputStream::doNextBlock()
  79711. {
  79712. const int len = helper->doNextBlock (buffer, gzipCompBufferSize);
  79713. if (len > 0)
  79714. return destStream->write (buffer, len);
  79715. else
  79716. return true;
  79717. }
  79718. int64 GZIPCompressorOutputStream::getPosition()
  79719. {
  79720. return destStream->getPosition();
  79721. }
  79722. bool GZIPCompressorOutputStream::setPosition (int64 /*newPosition*/)
  79723. {
  79724. jassertfalse; // can't do it!
  79725. return false;
  79726. }
  79727. END_JUCE_NAMESPACE
  79728. /*** End of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  79729. /*** Start of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  79730. #if JUCE_MSVC
  79731. #pragma warning (push)
  79732. #pragma warning (disable: 4309 4305)
  79733. #endif
  79734. namespace zlibNamespace
  79735. {
  79736. #if JUCE_INCLUDE_ZLIB_CODE
  79737. #undef OS_CODE
  79738. #undef fdopen
  79739. #define ZLIB_INTERNAL
  79740. #define NO_DUMMY_DECL
  79741. /*** Start of inlined file: adler32.c ***/
  79742. /* @(#) $Id: adler32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79743. #define ZLIB_INTERNAL
  79744. #define BASE 65521UL /* largest prime smaller than 65536 */
  79745. #define NMAX 5552
  79746. /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
  79747. #define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;}
  79748. #define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
  79749. #define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
  79750. #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
  79751. #define DO16(buf) DO8(buf,0); DO8(buf,8);
  79752. /* use NO_DIVIDE if your processor does not do division in hardware */
  79753. #ifdef NO_DIVIDE
  79754. # define MOD(a) \
  79755. do { \
  79756. if (a >= (BASE << 16)) a -= (BASE << 16); \
  79757. if (a >= (BASE << 15)) a -= (BASE << 15); \
  79758. if (a >= (BASE << 14)) a -= (BASE << 14); \
  79759. if (a >= (BASE << 13)) a -= (BASE << 13); \
  79760. if (a >= (BASE << 12)) a -= (BASE << 12); \
  79761. if (a >= (BASE << 11)) a -= (BASE << 11); \
  79762. if (a >= (BASE << 10)) a -= (BASE << 10); \
  79763. if (a >= (BASE << 9)) a -= (BASE << 9); \
  79764. if (a >= (BASE << 8)) a -= (BASE << 8); \
  79765. if (a >= (BASE << 7)) a -= (BASE << 7); \
  79766. if (a >= (BASE << 6)) a -= (BASE << 6); \
  79767. if (a >= (BASE << 5)) a -= (BASE << 5); \
  79768. if (a >= (BASE << 4)) a -= (BASE << 4); \
  79769. if (a >= (BASE << 3)) a -= (BASE << 3); \
  79770. if (a >= (BASE << 2)) a -= (BASE << 2); \
  79771. if (a >= (BASE << 1)) a -= (BASE << 1); \
  79772. if (a >= BASE) a -= BASE; \
  79773. } while (0)
  79774. # define MOD4(a) \
  79775. do { \
  79776. if (a >= (BASE << 4)) a -= (BASE << 4); \
  79777. if (a >= (BASE << 3)) a -= (BASE << 3); \
  79778. if (a >= (BASE << 2)) a -= (BASE << 2); \
  79779. if (a >= (BASE << 1)) a -= (BASE << 1); \
  79780. if (a >= BASE) a -= BASE; \
  79781. } while (0)
  79782. #else
  79783. # define MOD(a) a %= BASE
  79784. # define MOD4(a) a %= BASE
  79785. #endif
  79786. /* ========================================================================= */
  79787. uLong ZEXPORT adler32(uLong adler, const Bytef *buf, uInt len)
  79788. {
  79789. unsigned long sum2;
  79790. unsigned n;
  79791. /* split Adler-32 into component sums */
  79792. sum2 = (adler >> 16) & 0xffff;
  79793. adler &= 0xffff;
  79794. /* in case user likes doing a byte at a time, keep it fast */
  79795. if (len == 1) {
  79796. adler += buf[0];
  79797. if (adler >= BASE)
  79798. adler -= BASE;
  79799. sum2 += adler;
  79800. if (sum2 >= BASE)
  79801. sum2 -= BASE;
  79802. return adler | (sum2 << 16);
  79803. }
  79804. /* initial Adler-32 value (deferred check for len == 1 speed) */
  79805. if (buf == Z_NULL)
  79806. return 1L;
  79807. /* in case short lengths are provided, keep it somewhat fast */
  79808. if (len < 16) {
  79809. while (len--) {
  79810. adler += *buf++;
  79811. sum2 += adler;
  79812. }
  79813. if (adler >= BASE)
  79814. adler -= BASE;
  79815. MOD4(sum2); /* only added so many BASE's */
  79816. return adler | (sum2 << 16);
  79817. }
  79818. /* do length NMAX blocks -- requires just one modulo operation */
  79819. while (len >= NMAX) {
  79820. len -= NMAX;
  79821. n = NMAX / 16; /* NMAX is divisible by 16 */
  79822. do {
  79823. DO16(buf); /* 16 sums unrolled */
  79824. buf += 16;
  79825. } while (--n);
  79826. MOD(adler);
  79827. MOD(sum2);
  79828. }
  79829. /* do remaining bytes (less than NMAX, still just one modulo) */
  79830. if (len) { /* avoid modulos if none remaining */
  79831. while (len >= 16) {
  79832. len -= 16;
  79833. DO16(buf);
  79834. buf += 16;
  79835. }
  79836. while (len--) {
  79837. adler += *buf++;
  79838. sum2 += adler;
  79839. }
  79840. MOD(adler);
  79841. MOD(sum2);
  79842. }
  79843. /* return recombined sums */
  79844. return adler | (sum2 << 16);
  79845. }
  79846. /* ========================================================================= */
  79847. uLong ZEXPORT adler32_combine(uLong adler1, uLong adler2, z_off_t len2)
  79848. {
  79849. unsigned long sum1;
  79850. unsigned long sum2;
  79851. unsigned rem;
  79852. /* the derivation of this formula is left as an exercise for the reader */
  79853. rem = (unsigned)(len2 % BASE);
  79854. sum1 = adler1 & 0xffff;
  79855. sum2 = rem * sum1;
  79856. MOD(sum2);
  79857. sum1 += (adler2 & 0xffff) + BASE - 1;
  79858. sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;
  79859. if (sum1 > BASE) sum1 -= BASE;
  79860. if (sum1 > BASE) sum1 -= BASE;
  79861. if (sum2 > (BASE << 1)) sum2 -= (BASE << 1);
  79862. if (sum2 > BASE) sum2 -= BASE;
  79863. return sum1 | (sum2 << 16);
  79864. }
  79865. /*** End of inlined file: adler32.c ***/
  79866. /*** Start of inlined file: compress.c ***/
  79867. /* @(#) $Id: compress.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79868. #define ZLIB_INTERNAL
  79869. /* ===========================================================================
  79870. Compresses the source buffer into the destination buffer. The level
  79871. parameter has the same meaning as in deflateInit. sourceLen is the byte
  79872. length of the source buffer. Upon entry, destLen is the total size of the
  79873. destination buffer, which must be at least 0.1% larger than sourceLen plus
  79874. 12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
  79875. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  79876. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  79877. Z_STREAM_ERROR if the level parameter is invalid.
  79878. */
  79879. int ZEXPORT compress2 (Bytef *dest, uLongf *destLen, const Bytef *source,
  79880. uLong sourceLen, int level)
  79881. {
  79882. z_stream stream;
  79883. int err;
  79884. stream.next_in = (Bytef*)source;
  79885. stream.avail_in = (uInt)sourceLen;
  79886. #ifdef MAXSEG_64K
  79887. /* Check for source > 64K on 16-bit machine: */
  79888. if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
  79889. #endif
  79890. stream.next_out = dest;
  79891. stream.avail_out = (uInt)*destLen;
  79892. if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
  79893. stream.zalloc = (alloc_func)0;
  79894. stream.zfree = (free_func)0;
  79895. stream.opaque = (voidpf)0;
  79896. err = deflateInit(&stream, level);
  79897. if (err != Z_OK) return err;
  79898. err = deflate(&stream, Z_FINISH);
  79899. if (err != Z_STREAM_END) {
  79900. deflateEnd(&stream);
  79901. return err == Z_OK ? Z_BUF_ERROR : err;
  79902. }
  79903. *destLen = stream.total_out;
  79904. err = deflateEnd(&stream);
  79905. return err;
  79906. }
  79907. /* ===========================================================================
  79908. */
  79909. int ZEXPORT compress (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen)
  79910. {
  79911. return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);
  79912. }
  79913. /* ===========================================================================
  79914. If the default memLevel or windowBits for deflateInit() is changed, then
  79915. this function needs to be updated.
  79916. */
  79917. uLong ZEXPORT compressBound (uLong sourceLen)
  79918. {
  79919. return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11;
  79920. }
  79921. /*** End of inlined file: compress.c ***/
  79922. #undef DO1
  79923. #undef DO8
  79924. /*** Start of inlined file: crc32.c ***/
  79925. /* @(#) $Id: crc32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79926. /*
  79927. Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore
  79928. protection on the static variables used to control the first-use generation
  79929. of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should
  79930. first call get_crc_table() to initialize the tables before allowing more than
  79931. one thread to use crc32().
  79932. */
  79933. #ifdef MAKECRCH
  79934. # include <stdio.h>
  79935. # ifndef DYNAMIC_CRC_TABLE
  79936. # define DYNAMIC_CRC_TABLE
  79937. # endif /* !DYNAMIC_CRC_TABLE */
  79938. #endif /* MAKECRCH */
  79939. /*** Start of inlined file: zutil.h ***/
  79940. /* WARNING: this file should *not* be used by applications. It is
  79941. part of the implementation of the compression library and is
  79942. subject to change. Applications should only use zlib.h.
  79943. */
  79944. /* @(#) $Id: zutil.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79945. #ifndef ZUTIL_H
  79946. #define ZUTIL_H
  79947. #define ZLIB_INTERNAL
  79948. #ifdef STDC
  79949. # ifndef _WIN32_WCE
  79950. # include <stddef.h>
  79951. # endif
  79952. # include <string.h>
  79953. # include <stdlib.h>
  79954. #endif
  79955. #ifdef NO_ERRNO_H
  79956. # ifdef _WIN32_WCE
  79957. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  79958. * errno. We define it as a global variable to simplify porting.
  79959. * Its value is always 0 and should not be used. We rename it to
  79960. * avoid conflict with other libraries that use the same workaround.
  79961. */
  79962. # define errno z_errno
  79963. # endif
  79964. extern int errno;
  79965. #else
  79966. # ifndef _WIN32_WCE
  79967. # include <errno.h>
  79968. # endif
  79969. #endif
  79970. #ifndef local
  79971. # define local static
  79972. #endif
  79973. /* compile with -Dlocal if your debugger can't find static symbols */
  79974. typedef unsigned char uch;
  79975. typedef uch FAR uchf;
  79976. typedef unsigned short ush;
  79977. typedef ush FAR ushf;
  79978. typedef unsigned long ulg;
  79979. extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
  79980. /* (size given to avoid silly warnings with Visual C++) */
  79981. #define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]
  79982. #define ERR_RETURN(strm,err) \
  79983. return (strm->msg = (char*)ERR_MSG(err), (err))
  79984. /* To be used only when the state is known to be valid */
  79985. /* common constants */
  79986. #ifndef DEF_WBITS
  79987. # define DEF_WBITS MAX_WBITS
  79988. #endif
  79989. /* default windowBits for decompression. MAX_WBITS is for compression only */
  79990. #if MAX_MEM_LEVEL >= 8
  79991. # define DEF_MEM_LEVEL 8
  79992. #else
  79993. # define DEF_MEM_LEVEL MAX_MEM_LEVEL
  79994. #endif
  79995. /* default memLevel */
  79996. #define STORED_BLOCK 0
  79997. #define STATIC_TREES 1
  79998. #define DYN_TREES 2
  79999. /* The three kinds of block type */
  80000. #define MIN_MATCH 3
  80001. #define MAX_MATCH 258
  80002. /* The minimum and maximum match lengths */
  80003. #define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
  80004. /* target dependencies */
  80005. #if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))
  80006. # define OS_CODE 0x00
  80007. # if defined(__TURBOC__) || defined(__BORLANDC__)
  80008. # if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
  80009. /* Allow compilation with ANSI keywords only enabled */
  80010. void _Cdecl farfree( void *block );
  80011. void *_Cdecl farmalloc( unsigned long nbytes );
  80012. # else
  80013. # include <alloc.h>
  80014. # endif
  80015. # else /* MSC or DJGPP */
  80016. # include <malloc.h>
  80017. # endif
  80018. #endif
  80019. #ifdef AMIGA
  80020. # define OS_CODE 0x01
  80021. #endif
  80022. #if defined(VAXC) || defined(VMS)
  80023. # define OS_CODE 0x02
  80024. # define F_OPEN(name, mode) \
  80025. fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512")
  80026. #endif
  80027. #if defined(ATARI) || defined(atarist)
  80028. # define OS_CODE 0x05
  80029. #endif
  80030. #ifdef OS2
  80031. # define OS_CODE 0x06
  80032. # ifdef M_I86
  80033. #include <malloc.h>
  80034. # endif
  80035. #endif
  80036. #if defined(MACOS) || TARGET_OS_MAC
  80037. # define OS_CODE 0x07
  80038. # if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
  80039. # include <unix.h> /* for fdopen */
  80040. # else
  80041. # ifndef fdopen
  80042. # define fdopen(fd,mode) NULL /* No fdopen() */
  80043. # endif
  80044. # endif
  80045. #endif
  80046. #ifdef TOPS20
  80047. # define OS_CODE 0x0a
  80048. #endif
  80049. #ifdef WIN32
  80050. # ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */
  80051. # define OS_CODE 0x0b
  80052. # endif
  80053. #endif
  80054. #ifdef __50SERIES /* Prime/PRIMOS */
  80055. # define OS_CODE 0x0f
  80056. #endif
  80057. #if defined(_BEOS_) || defined(RISCOS)
  80058. # define fdopen(fd,mode) NULL /* No fdopen() */
  80059. #endif
  80060. #if (defined(_MSC_VER) && (_MSC_VER > 600))
  80061. # if defined(_WIN32_WCE)
  80062. # define fdopen(fd,mode) NULL /* No fdopen() */
  80063. # ifndef _PTRDIFF_T_DEFINED
  80064. typedef int ptrdiff_t;
  80065. # define _PTRDIFF_T_DEFINED
  80066. # endif
  80067. # else
  80068. # define fdopen(fd,type) _fdopen(fd,type)
  80069. # endif
  80070. #endif
  80071. /* common defaults */
  80072. #ifndef OS_CODE
  80073. # define OS_CODE 0x03 /* assume Unix */
  80074. #endif
  80075. #ifndef F_OPEN
  80076. # define F_OPEN(name, mode) fopen((name), (mode))
  80077. #endif
  80078. /* functions */
  80079. #if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550)
  80080. # ifndef HAVE_VSNPRINTF
  80081. # define HAVE_VSNPRINTF
  80082. # endif
  80083. #endif
  80084. #if defined(__CYGWIN__)
  80085. # ifndef HAVE_VSNPRINTF
  80086. # define HAVE_VSNPRINTF
  80087. # endif
  80088. #endif
  80089. #ifndef HAVE_VSNPRINTF
  80090. # ifdef MSDOS
  80091. /* vsnprintf may exist on some MS-DOS compilers (DJGPP?),
  80092. but for now we just assume it doesn't. */
  80093. # define NO_vsnprintf
  80094. # endif
  80095. # ifdef __TURBOC__
  80096. # define NO_vsnprintf
  80097. # endif
  80098. # ifdef WIN32
  80099. /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */
  80100. # if !defined(vsnprintf) && !defined(NO_vsnprintf)
  80101. # define vsnprintf _vsnprintf
  80102. # endif
  80103. # endif
  80104. # ifdef __SASC
  80105. # define NO_vsnprintf
  80106. # endif
  80107. #endif
  80108. #ifdef VMS
  80109. # define NO_vsnprintf
  80110. #endif
  80111. #if defined(pyr)
  80112. # define NO_MEMCPY
  80113. #endif
  80114. #if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)
  80115. /* Use our own functions for small and medium model with MSC <= 5.0.
  80116. * You may have to use the same strategy for Borland C (untested).
  80117. * The __SC__ check is for Symantec.
  80118. */
  80119. # define NO_MEMCPY
  80120. #endif
  80121. #if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)
  80122. # define HAVE_MEMCPY
  80123. #endif
  80124. #ifdef HAVE_MEMCPY
  80125. # ifdef SMALL_MEDIUM /* MSDOS small or medium model */
  80126. # define zmemcpy _fmemcpy
  80127. # define zmemcmp _fmemcmp
  80128. # define zmemzero(dest, len) _fmemset(dest, 0, len)
  80129. # else
  80130. # define zmemcpy memcpy
  80131. # define zmemcmp memcmp
  80132. # define zmemzero(dest, len) memset(dest, 0, len)
  80133. # endif
  80134. #else
  80135. extern void zmemcpy OF((Bytef* dest, const Bytef* source, uInt len));
  80136. extern int zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len));
  80137. extern void zmemzero OF((Bytef* dest, uInt len));
  80138. #endif
  80139. /* Diagnostic functions */
  80140. #ifdef DEBUG
  80141. # include <stdio.h>
  80142. extern int z_verbose;
  80143. extern void z_error OF((const char *m));
  80144. # define Assert(cond,msg) {if(!(cond)) z_error(msg);}
  80145. # define Trace(x) {if (z_verbose>=0) fprintf x ;}
  80146. # define Tracev(x) {if (z_verbose>0) fprintf x ;}
  80147. # define Tracevv(x) {if (z_verbose>1) fprintf x ;}
  80148. # define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;}
  80149. # define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;}
  80150. #else
  80151. # define Assert(cond,msg)
  80152. # define Trace(x)
  80153. # define Tracev(x)
  80154. # define Tracevv(x)
  80155. # define Tracec(c,x)
  80156. # define Tracecv(c,x)
  80157. #endif
  80158. voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size));
  80159. void zcfree OF((voidpf opaque, voidpf ptr));
  80160. #define ZALLOC(strm, items, size) \
  80161. (*((strm)->zalloc))((strm)->opaque, (items), (size))
  80162. #define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
  80163. #define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
  80164. #endif /* ZUTIL_H */
  80165. /*** End of inlined file: zutil.h ***/
  80166. /* for STDC and FAR definitions */
  80167. #define local static
  80168. /* Find a four-byte integer type for crc32_little() and crc32_big(). */
  80169. #ifndef NOBYFOUR
  80170. # ifdef STDC /* need ANSI C limits.h to determine sizes */
  80171. # include <limits.h>
  80172. # define BYFOUR
  80173. # if (UINT_MAX == 0xffffffffUL)
  80174. typedef unsigned int u4;
  80175. # else
  80176. # if (ULONG_MAX == 0xffffffffUL)
  80177. typedef unsigned long u4;
  80178. # else
  80179. # if (USHRT_MAX == 0xffffffffUL)
  80180. typedef unsigned short u4;
  80181. # else
  80182. # undef BYFOUR /* can't find a four-byte integer type! */
  80183. # endif
  80184. # endif
  80185. # endif
  80186. # endif /* STDC */
  80187. #endif /* !NOBYFOUR */
  80188. /* Definitions for doing the crc four data bytes at a time. */
  80189. #ifdef BYFOUR
  80190. # define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \
  80191. (((w)&0xff00)<<8)+(((w)&0xff)<<24))
  80192. local unsigned long crc32_little OF((unsigned long,
  80193. const unsigned char FAR *, unsigned));
  80194. local unsigned long crc32_big OF((unsigned long,
  80195. const unsigned char FAR *, unsigned));
  80196. # define TBLS 8
  80197. #else
  80198. # define TBLS 1
  80199. #endif /* BYFOUR */
  80200. /* Local functions for crc concatenation */
  80201. local unsigned long gf2_matrix_times OF((unsigned long *mat,
  80202. unsigned long vec));
  80203. local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));
  80204. #ifdef DYNAMIC_CRC_TABLE
  80205. local volatile int crc_table_empty = 1;
  80206. local unsigned long FAR crc_table[TBLS][256];
  80207. local void make_crc_table OF((void));
  80208. #ifdef MAKECRCH
  80209. local void write_table OF((FILE *, const unsigned long FAR *));
  80210. #endif /* MAKECRCH */
  80211. /*
  80212. Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
  80213. 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.
  80214. Polynomials over GF(2) are represented in binary, one bit per coefficient,
  80215. with the lowest powers in the most significant bit. Then adding polynomials
  80216. is just exclusive-or, and multiplying a polynomial by x is a right shift by
  80217. one. If we call the above polynomial p, and represent a byte as the
  80218. polynomial q, also with the lowest power in the most significant bit (so the
  80219. byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
  80220. where a mod b means the remainder after dividing a by b.
  80221. This calculation is done using the shift-register method of multiplying and
  80222. taking the remainder. The register is initialized to zero, and for each
  80223. incoming bit, x^32 is added mod p to the register if the bit is a one (where
  80224. x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
  80225. x (which is shifting right by one and adding x^32 mod p if the bit shifted
  80226. out is a one). We start with the highest power (least significant bit) of
  80227. q and repeat for all eight bits of q.
  80228. The first table is simply the CRC of all possible eight bit values. This is
  80229. all the information needed to generate CRCs on data a byte at a time for all
  80230. combinations of CRC register values and incoming bytes. The remaining tables
  80231. allow for word-at-a-time CRC calculation for both big-endian and little-
  80232. endian machines, where a word is four bytes.
  80233. */
  80234. local void make_crc_table()
  80235. {
  80236. unsigned long c;
  80237. int n, k;
  80238. unsigned long poly; /* polynomial exclusive-or pattern */
  80239. /* terms of polynomial defining this crc (except x^32): */
  80240. static volatile int first = 1; /* flag to limit concurrent making */
  80241. static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
  80242. /* See if another task is already doing this (not thread-safe, but better
  80243. than nothing -- significantly reduces duration of vulnerability in
  80244. case the advice about DYNAMIC_CRC_TABLE is ignored) */
  80245. if (first) {
  80246. first = 0;
  80247. /* make exclusive-or pattern from polynomial (0xedb88320UL) */
  80248. poly = 0UL;
  80249. for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++)
  80250. poly |= 1UL << (31 - p[n]);
  80251. /* generate a crc for every 8-bit value */
  80252. for (n = 0; n < 256; n++) {
  80253. c = (unsigned long)n;
  80254. for (k = 0; k < 8; k++)
  80255. c = c & 1 ? poly ^ (c >> 1) : c >> 1;
  80256. crc_table[0][n] = c;
  80257. }
  80258. #ifdef BYFOUR
  80259. /* generate crc for each value followed by one, two, and three zeros,
  80260. and then the byte reversal of those as well as the first table */
  80261. for (n = 0; n < 256; n++) {
  80262. c = crc_table[0][n];
  80263. crc_table[4][n] = REV(c);
  80264. for (k = 1; k < 4; k++) {
  80265. c = crc_table[0][c & 0xff] ^ (c >> 8);
  80266. crc_table[k][n] = c;
  80267. crc_table[k + 4][n] = REV(c);
  80268. }
  80269. }
  80270. #endif /* BYFOUR */
  80271. crc_table_empty = 0;
  80272. }
  80273. else { /* not first */
  80274. /* wait for the other guy to finish (not efficient, but rare) */
  80275. while (crc_table_empty)
  80276. ;
  80277. }
  80278. #ifdef MAKECRCH
  80279. /* write out CRC tables to crc32.h */
  80280. {
  80281. FILE *out;
  80282. out = fopen("crc32.h", "w");
  80283. if (out == NULL) return;
  80284. fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n");
  80285. fprintf(out, " * Generated automatically by crc32.c\n */\n\n");
  80286. fprintf(out, "local const unsigned long FAR ");
  80287. fprintf(out, "crc_table[TBLS][256] =\n{\n {\n");
  80288. write_table(out, crc_table[0]);
  80289. # ifdef BYFOUR
  80290. fprintf(out, "#ifdef BYFOUR\n");
  80291. for (k = 1; k < 8; k++) {
  80292. fprintf(out, " },\n {\n");
  80293. write_table(out, crc_table[k]);
  80294. }
  80295. fprintf(out, "#endif\n");
  80296. # endif /* BYFOUR */
  80297. fprintf(out, " }\n};\n");
  80298. fclose(out);
  80299. }
  80300. #endif /* MAKECRCH */
  80301. }
  80302. #ifdef MAKECRCH
  80303. local void write_table(out, table)
  80304. FILE *out;
  80305. const unsigned long FAR *table;
  80306. {
  80307. int n;
  80308. for (n = 0; n < 256; n++)
  80309. fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n],
  80310. n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", "));
  80311. }
  80312. #endif /* MAKECRCH */
  80313. #else /* !DYNAMIC_CRC_TABLE */
  80314. /* ========================================================================
  80315. * Tables of CRC-32s of all single-byte values, made by make_crc_table().
  80316. */
  80317. /*** Start of inlined file: crc32.h ***/
  80318. local const unsigned long FAR crc_table[TBLS][256] =
  80319. {
  80320. {
  80321. 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL,
  80322. 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL,
  80323. 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL,
  80324. 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL,
  80325. 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL,
  80326. 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL,
  80327. 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL,
  80328. 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL,
  80329. 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL,
  80330. 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL,
  80331. 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL,
  80332. 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL,
  80333. 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL,
  80334. 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL,
  80335. 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL,
  80336. 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL,
  80337. 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL,
  80338. 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL,
  80339. 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL,
  80340. 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL,
  80341. 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL,
  80342. 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL,
  80343. 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL,
  80344. 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL,
  80345. 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL,
  80346. 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL,
  80347. 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL,
  80348. 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL,
  80349. 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL,
  80350. 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL,
  80351. 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL,
  80352. 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL,
  80353. 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL,
  80354. 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL,
  80355. 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL,
  80356. 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL,
  80357. 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL,
  80358. 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL,
  80359. 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL,
  80360. 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL,
  80361. 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL,
  80362. 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL,
  80363. 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL,
  80364. 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL,
  80365. 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL,
  80366. 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL,
  80367. 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL,
  80368. 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL,
  80369. 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL,
  80370. 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL,
  80371. 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL,
  80372. 0x2d02ef8dUL
  80373. #ifdef BYFOUR
  80374. },
  80375. {
  80376. 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL,
  80377. 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL,
  80378. 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL,
  80379. 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL,
  80380. 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL,
  80381. 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL,
  80382. 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL,
  80383. 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL,
  80384. 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL,
  80385. 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL,
  80386. 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL,
  80387. 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL,
  80388. 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL,
  80389. 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL,
  80390. 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL,
  80391. 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL,
  80392. 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL,
  80393. 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL,
  80394. 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL,
  80395. 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL,
  80396. 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL,
  80397. 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL,
  80398. 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL,
  80399. 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL,
  80400. 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL,
  80401. 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL,
  80402. 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL,
  80403. 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL,
  80404. 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL,
  80405. 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL,
  80406. 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL,
  80407. 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL,
  80408. 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL,
  80409. 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL,
  80410. 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL,
  80411. 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL,
  80412. 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL,
  80413. 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL,
  80414. 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL,
  80415. 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL,
  80416. 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL,
  80417. 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL,
  80418. 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL,
  80419. 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL,
  80420. 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL,
  80421. 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL,
  80422. 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL,
  80423. 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL,
  80424. 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL,
  80425. 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL,
  80426. 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL,
  80427. 0x9324fd72UL
  80428. },
  80429. {
  80430. 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL,
  80431. 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL,
  80432. 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL,
  80433. 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL,
  80434. 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL,
  80435. 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL,
  80436. 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL,
  80437. 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL,
  80438. 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL,
  80439. 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL,
  80440. 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL,
  80441. 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL,
  80442. 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL,
  80443. 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL,
  80444. 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL,
  80445. 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL,
  80446. 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL,
  80447. 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL,
  80448. 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL,
  80449. 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL,
  80450. 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL,
  80451. 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL,
  80452. 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL,
  80453. 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL,
  80454. 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL,
  80455. 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL,
  80456. 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL,
  80457. 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL,
  80458. 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL,
  80459. 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL,
  80460. 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL,
  80461. 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL,
  80462. 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL,
  80463. 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL,
  80464. 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL,
  80465. 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL,
  80466. 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL,
  80467. 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL,
  80468. 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL,
  80469. 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL,
  80470. 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL,
  80471. 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL,
  80472. 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL,
  80473. 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL,
  80474. 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL,
  80475. 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL,
  80476. 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL,
  80477. 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL,
  80478. 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL,
  80479. 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL,
  80480. 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL,
  80481. 0xbe9834edUL
  80482. },
  80483. {
  80484. 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL,
  80485. 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL,
  80486. 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL,
  80487. 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL,
  80488. 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL,
  80489. 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL,
  80490. 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL,
  80491. 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL,
  80492. 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL,
  80493. 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL,
  80494. 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL,
  80495. 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL,
  80496. 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL,
  80497. 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL,
  80498. 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL,
  80499. 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL,
  80500. 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL,
  80501. 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL,
  80502. 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL,
  80503. 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL,
  80504. 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL,
  80505. 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL,
  80506. 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL,
  80507. 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL,
  80508. 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL,
  80509. 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL,
  80510. 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL,
  80511. 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL,
  80512. 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL,
  80513. 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL,
  80514. 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL,
  80515. 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL,
  80516. 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL,
  80517. 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL,
  80518. 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL,
  80519. 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL,
  80520. 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL,
  80521. 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL,
  80522. 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL,
  80523. 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL,
  80524. 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL,
  80525. 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL,
  80526. 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL,
  80527. 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL,
  80528. 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL,
  80529. 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL,
  80530. 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL,
  80531. 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL,
  80532. 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL,
  80533. 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL,
  80534. 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL,
  80535. 0xde0506f1UL
  80536. },
  80537. {
  80538. 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL,
  80539. 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL,
  80540. 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL,
  80541. 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL,
  80542. 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL,
  80543. 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL,
  80544. 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL,
  80545. 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL,
  80546. 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL,
  80547. 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL,
  80548. 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL,
  80549. 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL,
  80550. 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL,
  80551. 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL,
  80552. 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL,
  80553. 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL,
  80554. 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL,
  80555. 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL,
  80556. 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL,
  80557. 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL,
  80558. 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL,
  80559. 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL,
  80560. 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL,
  80561. 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL,
  80562. 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL,
  80563. 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL,
  80564. 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL,
  80565. 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL,
  80566. 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL,
  80567. 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL,
  80568. 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL,
  80569. 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL,
  80570. 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL,
  80571. 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL,
  80572. 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL,
  80573. 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL,
  80574. 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL,
  80575. 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL,
  80576. 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL,
  80577. 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL,
  80578. 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL,
  80579. 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL,
  80580. 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL,
  80581. 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL,
  80582. 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL,
  80583. 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL,
  80584. 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL,
  80585. 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL,
  80586. 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL,
  80587. 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL,
  80588. 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL,
  80589. 0x8def022dUL
  80590. },
  80591. {
  80592. 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL,
  80593. 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL,
  80594. 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL,
  80595. 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL,
  80596. 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL,
  80597. 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL,
  80598. 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL,
  80599. 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL,
  80600. 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL,
  80601. 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL,
  80602. 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL,
  80603. 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL,
  80604. 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL,
  80605. 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL,
  80606. 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL,
  80607. 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL,
  80608. 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL,
  80609. 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL,
  80610. 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL,
  80611. 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL,
  80612. 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL,
  80613. 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL,
  80614. 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL,
  80615. 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL,
  80616. 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL,
  80617. 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL,
  80618. 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL,
  80619. 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL,
  80620. 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL,
  80621. 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL,
  80622. 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL,
  80623. 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL,
  80624. 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL,
  80625. 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL,
  80626. 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL,
  80627. 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL,
  80628. 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL,
  80629. 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL,
  80630. 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL,
  80631. 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL,
  80632. 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL,
  80633. 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL,
  80634. 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL,
  80635. 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL,
  80636. 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL,
  80637. 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL,
  80638. 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL,
  80639. 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL,
  80640. 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL,
  80641. 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL,
  80642. 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL,
  80643. 0x72fd2493UL
  80644. },
  80645. {
  80646. 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL,
  80647. 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL,
  80648. 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL,
  80649. 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL,
  80650. 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL,
  80651. 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL,
  80652. 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL,
  80653. 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL,
  80654. 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL,
  80655. 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL,
  80656. 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL,
  80657. 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL,
  80658. 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL,
  80659. 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL,
  80660. 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL,
  80661. 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL,
  80662. 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL,
  80663. 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL,
  80664. 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL,
  80665. 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL,
  80666. 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL,
  80667. 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL,
  80668. 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL,
  80669. 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL,
  80670. 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL,
  80671. 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL,
  80672. 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL,
  80673. 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL,
  80674. 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL,
  80675. 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL,
  80676. 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL,
  80677. 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL,
  80678. 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL,
  80679. 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL,
  80680. 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL,
  80681. 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL,
  80682. 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL,
  80683. 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL,
  80684. 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL,
  80685. 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL,
  80686. 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL,
  80687. 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL,
  80688. 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL,
  80689. 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL,
  80690. 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL,
  80691. 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL,
  80692. 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL,
  80693. 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL,
  80694. 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL,
  80695. 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL,
  80696. 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL,
  80697. 0xed3498beUL
  80698. },
  80699. {
  80700. 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL,
  80701. 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL,
  80702. 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL,
  80703. 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL,
  80704. 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL,
  80705. 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL,
  80706. 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL,
  80707. 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL,
  80708. 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL,
  80709. 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL,
  80710. 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL,
  80711. 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL,
  80712. 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL,
  80713. 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL,
  80714. 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL,
  80715. 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL,
  80716. 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL,
  80717. 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL,
  80718. 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL,
  80719. 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL,
  80720. 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL,
  80721. 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL,
  80722. 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL,
  80723. 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL,
  80724. 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL,
  80725. 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL,
  80726. 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL,
  80727. 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL,
  80728. 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL,
  80729. 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL,
  80730. 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL,
  80731. 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL,
  80732. 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL,
  80733. 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL,
  80734. 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL,
  80735. 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL,
  80736. 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL,
  80737. 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL,
  80738. 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL,
  80739. 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL,
  80740. 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL,
  80741. 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL,
  80742. 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL,
  80743. 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL,
  80744. 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL,
  80745. 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL,
  80746. 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL,
  80747. 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL,
  80748. 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL,
  80749. 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL,
  80750. 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL,
  80751. 0xf10605deUL
  80752. #endif
  80753. }
  80754. };
  80755. /*** End of inlined file: crc32.h ***/
  80756. #endif /* DYNAMIC_CRC_TABLE */
  80757. /* =========================================================================
  80758. * This function can be used by asm versions of crc32()
  80759. */
  80760. const unsigned long FAR * ZEXPORT get_crc_table()
  80761. {
  80762. #ifdef DYNAMIC_CRC_TABLE
  80763. if (crc_table_empty)
  80764. make_crc_table();
  80765. #endif /* DYNAMIC_CRC_TABLE */
  80766. return (const unsigned long FAR *)crc_table;
  80767. }
  80768. /* ========================================================================= */
  80769. #define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8)
  80770. #define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1
  80771. /* ========================================================================= */
  80772. unsigned long ZEXPORT crc32 (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80773. {
  80774. if (buf == Z_NULL) return 0UL;
  80775. #ifdef DYNAMIC_CRC_TABLE
  80776. if (crc_table_empty)
  80777. make_crc_table();
  80778. #endif /* DYNAMIC_CRC_TABLE */
  80779. #ifdef BYFOUR
  80780. if (sizeof(void *) == sizeof(ptrdiff_t)) {
  80781. u4 endian;
  80782. endian = 1;
  80783. if (*((unsigned char *)(&endian)))
  80784. return crc32_little(crc, buf, len);
  80785. else
  80786. return crc32_big(crc, buf, len);
  80787. }
  80788. #endif /* BYFOUR */
  80789. crc = crc ^ 0xffffffffUL;
  80790. while (len >= 8) {
  80791. DO8;
  80792. len -= 8;
  80793. }
  80794. if (len) do {
  80795. DO1;
  80796. } while (--len);
  80797. return crc ^ 0xffffffffUL;
  80798. }
  80799. #ifdef BYFOUR
  80800. /* ========================================================================= */
  80801. #define DOLIT4 c ^= *buf4++; \
  80802. c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \
  80803. crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24]
  80804. #define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4
  80805. /* ========================================================================= */
  80806. local unsigned long crc32_little(unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80807. {
  80808. register u4 c;
  80809. register const u4 FAR *buf4;
  80810. c = (u4)crc;
  80811. c = ~c;
  80812. while (len && ((ptrdiff_t)buf & 3)) {
  80813. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  80814. len--;
  80815. }
  80816. buf4 = (const u4 FAR *)(const void FAR *)buf;
  80817. while (len >= 32) {
  80818. DOLIT32;
  80819. len -= 32;
  80820. }
  80821. while (len >= 4) {
  80822. DOLIT4;
  80823. len -= 4;
  80824. }
  80825. buf = (const unsigned char FAR *)buf4;
  80826. if (len) do {
  80827. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  80828. } while (--len);
  80829. c = ~c;
  80830. return (unsigned long)c;
  80831. }
  80832. /* ========================================================================= */
  80833. #define DOBIG4 c ^= *++buf4; \
  80834. c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \
  80835. crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]
  80836. #define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4
  80837. /* ========================================================================= */
  80838. local unsigned long crc32_big (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80839. {
  80840. register u4 c;
  80841. register const u4 FAR *buf4;
  80842. c = REV((u4)crc);
  80843. c = ~c;
  80844. while (len && ((ptrdiff_t)buf & 3)) {
  80845. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  80846. len--;
  80847. }
  80848. buf4 = (const u4 FAR *)(const void FAR *)buf;
  80849. buf4--;
  80850. while (len >= 32) {
  80851. DOBIG32;
  80852. len -= 32;
  80853. }
  80854. while (len >= 4) {
  80855. DOBIG4;
  80856. len -= 4;
  80857. }
  80858. buf4++;
  80859. buf = (const unsigned char FAR *)buf4;
  80860. if (len) do {
  80861. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  80862. } while (--len);
  80863. c = ~c;
  80864. return (unsigned long)(REV(c));
  80865. }
  80866. #endif /* BYFOUR */
  80867. #define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */
  80868. /* ========================================================================= */
  80869. local unsigned long gf2_matrix_times (unsigned long *mat, unsigned long vec)
  80870. {
  80871. unsigned long sum;
  80872. sum = 0;
  80873. while (vec) {
  80874. if (vec & 1)
  80875. sum ^= *mat;
  80876. vec >>= 1;
  80877. mat++;
  80878. }
  80879. return sum;
  80880. }
  80881. /* ========================================================================= */
  80882. local void gf2_matrix_square (unsigned long *square, unsigned long *mat)
  80883. {
  80884. int n;
  80885. for (n = 0; n < GF2_DIM; n++)
  80886. square[n] = gf2_matrix_times(mat, mat[n]);
  80887. }
  80888. /* ========================================================================= */
  80889. uLong ZEXPORT crc32_combine (uLong crc1, uLong crc2, z_off_t len2)
  80890. {
  80891. int n;
  80892. unsigned long row;
  80893. unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */
  80894. unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */
  80895. /* degenerate case */
  80896. if (len2 == 0)
  80897. return crc1;
  80898. /* put operator for one zero bit in odd */
  80899. odd[0] = 0xedb88320L; /* CRC-32 polynomial */
  80900. row = 1;
  80901. for (n = 1; n < GF2_DIM; n++) {
  80902. odd[n] = row;
  80903. row <<= 1;
  80904. }
  80905. /* put operator for two zero bits in even */
  80906. gf2_matrix_square(even, odd);
  80907. /* put operator for four zero bits in odd */
  80908. gf2_matrix_square(odd, even);
  80909. /* apply len2 zeros to crc1 (first square will put the operator for one
  80910. zero byte, eight zero bits, in even) */
  80911. do {
  80912. /* apply zeros operator for this bit of len2 */
  80913. gf2_matrix_square(even, odd);
  80914. if (len2 & 1)
  80915. crc1 = gf2_matrix_times(even, crc1);
  80916. len2 >>= 1;
  80917. /* if no more bits set, then done */
  80918. if (len2 == 0)
  80919. break;
  80920. /* another iteration of the loop with odd and even swapped */
  80921. gf2_matrix_square(odd, even);
  80922. if (len2 & 1)
  80923. crc1 = gf2_matrix_times(odd, crc1);
  80924. len2 >>= 1;
  80925. /* if no more bits set, then done */
  80926. } while (len2 != 0);
  80927. /* return combined crc */
  80928. crc1 ^= crc2;
  80929. return crc1;
  80930. }
  80931. /*** End of inlined file: crc32.c ***/
  80932. /*** Start of inlined file: deflate.c ***/
  80933. /*
  80934. * ALGORITHM
  80935. *
  80936. * The "deflation" process depends on being able to identify portions
  80937. * of the input text which are identical to earlier input (within a
  80938. * sliding window trailing behind the input currently being processed).
  80939. *
  80940. * The most straightforward technique turns out to be the fastest for
  80941. * most input files: try all possible matches and select the longest.
  80942. * The key feature of this algorithm is that insertions into the string
  80943. * dictionary are very simple and thus fast, and deletions are avoided
  80944. * completely. Insertions are performed at each input character, whereas
  80945. * string matches are performed only when the previous match ends. So it
  80946. * is preferable to spend more time in matches to allow very fast string
  80947. * insertions and avoid deletions. The matching algorithm for small
  80948. * strings is inspired from that of Rabin & Karp. A brute force approach
  80949. * is used to find longer strings when a small match has been found.
  80950. * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  80951. * (by Leonid Broukhis).
  80952. * A previous version of this file used a more sophisticated algorithm
  80953. * (by Fiala and Greene) which is guaranteed to run in linear amortized
  80954. * time, but has a larger average cost, uses more memory and is patented.
  80955. * However the F&G algorithm may be faster for some highly redundant
  80956. * files if the parameter max_chain_length (described below) is too large.
  80957. *
  80958. * ACKNOWLEDGEMENTS
  80959. *
  80960. * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  80961. * I found it in 'freeze' written by Leonid Broukhis.
  80962. * Thanks to many people for bug reports and testing.
  80963. *
  80964. * REFERENCES
  80965. *
  80966. * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
  80967. * Available in http://www.ietf.org/rfc/rfc1951.txt
  80968. *
  80969. * A description of the Rabin and Karp algorithm is given in the book
  80970. * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  80971. *
  80972. * Fiala,E.R., and Greene,D.H.
  80973. * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
  80974. *
  80975. */
  80976. /* @(#) $Id: deflate.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80977. /*** Start of inlined file: deflate.h ***/
  80978. /* WARNING: this file should *not* be used by applications. It is
  80979. part of the implementation of the compression library and is
  80980. subject to change. Applications should only use zlib.h.
  80981. */
  80982. /* @(#) $Id: deflate.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80983. #ifndef DEFLATE_H
  80984. #define DEFLATE_H
  80985. /* define NO_GZIP when compiling if you want to disable gzip header and
  80986. trailer creation by deflate(). NO_GZIP would be used to avoid linking in
  80987. the crc code when it is not needed. For shared libraries, gzip encoding
  80988. should be left enabled. */
  80989. #ifndef NO_GZIP
  80990. # define GZIP
  80991. #endif
  80992. #define NO_DUMMY_DECL
  80993. /* ===========================================================================
  80994. * Internal compression state.
  80995. */
  80996. #define LENGTH_CODES 29
  80997. /* number of length codes, not counting the special END_BLOCK code */
  80998. #define LITERALS 256
  80999. /* number of literal bytes 0..255 */
  81000. #define L_CODES (LITERALS+1+LENGTH_CODES)
  81001. /* number of Literal or Length codes, including the END_BLOCK code */
  81002. #define D_CODES 30
  81003. /* number of distance codes */
  81004. #define BL_CODES 19
  81005. /* number of codes used to transfer the bit lengths */
  81006. #define HEAP_SIZE (2*L_CODES+1)
  81007. /* maximum heap size */
  81008. #define MAX_BITS 15
  81009. /* All codes must not exceed MAX_BITS bits */
  81010. #define INIT_STATE 42
  81011. #define EXTRA_STATE 69
  81012. #define NAME_STATE 73
  81013. #define COMMENT_STATE 91
  81014. #define HCRC_STATE 103
  81015. #define BUSY_STATE 113
  81016. #define FINISH_STATE 666
  81017. /* Stream status */
  81018. /* Data structure describing a single value and its code string. */
  81019. typedef struct ct_data_s {
  81020. union {
  81021. ush freq; /* frequency count */
  81022. ush code; /* bit string */
  81023. } fc;
  81024. union {
  81025. ush dad; /* father node in Huffman tree */
  81026. ush len; /* length of bit string */
  81027. } dl;
  81028. } FAR ct_data;
  81029. #define Freq fc.freq
  81030. #define Code fc.code
  81031. #define Dad dl.dad
  81032. #define Len dl.len
  81033. typedef struct static_tree_desc_s static_tree_desc;
  81034. typedef struct tree_desc_s {
  81035. ct_data *dyn_tree; /* the dynamic tree */
  81036. int max_code; /* largest code with non zero frequency */
  81037. static_tree_desc *stat_desc; /* the corresponding static tree */
  81038. } FAR tree_desc;
  81039. typedef ush Pos;
  81040. typedef Pos FAR Posf;
  81041. typedef unsigned IPos;
  81042. /* A Pos is an index in the character window. We use short instead of int to
  81043. * save space in the various tables. IPos is used only for parameter passing.
  81044. */
  81045. typedef struct internal_state {
  81046. z_streamp strm; /* pointer back to this zlib stream */
  81047. int status; /* as the name implies */
  81048. Bytef *pending_buf; /* output still pending */
  81049. ulg pending_buf_size; /* size of pending_buf */
  81050. Bytef *pending_out; /* next pending byte to output to the stream */
  81051. uInt pending; /* nb of bytes in the pending buffer */
  81052. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  81053. gz_headerp gzhead; /* gzip header information to write */
  81054. uInt gzindex; /* where in extra, name, or comment */
  81055. Byte method; /* STORED (for zip only) or DEFLATED */
  81056. int last_flush; /* value of flush param for previous deflate call */
  81057. /* used by deflate.c: */
  81058. uInt w_size; /* LZ77 window size (32K by default) */
  81059. uInt w_bits; /* log2(w_size) (8..16) */
  81060. uInt w_mask; /* w_size - 1 */
  81061. Bytef *window;
  81062. /* Sliding window. Input bytes are read into the second half of the window,
  81063. * and move to the first half later to keep a dictionary of at least wSize
  81064. * bytes. With this organization, matches are limited to a distance of
  81065. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  81066. * performed with a length multiple of the block size. Also, it limits
  81067. * the window size to 64K, which is quite useful on MSDOS.
  81068. * To do: use the user input buffer as sliding window.
  81069. */
  81070. ulg window_size;
  81071. /* Actual size of window: 2*wSize, except when the user input buffer
  81072. * is directly used as sliding window.
  81073. */
  81074. Posf *prev;
  81075. /* Link to older string with same hash index. To limit the size of this
  81076. * array to 64K, this link is maintained only for the last 32K strings.
  81077. * An index in this array is thus a window index modulo 32K.
  81078. */
  81079. Posf *head; /* Heads of the hash chains or NIL. */
  81080. uInt ins_h; /* hash index of string to be inserted */
  81081. uInt hash_size; /* number of elements in hash table */
  81082. uInt hash_bits; /* log2(hash_size) */
  81083. uInt hash_mask; /* hash_size-1 */
  81084. uInt hash_shift;
  81085. /* Number of bits by which ins_h must be shifted at each input
  81086. * step. It must be such that after MIN_MATCH steps, the oldest
  81087. * byte no longer takes part in the hash key, that is:
  81088. * hash_shift * MIN_MATCH >= hash_bits
  81089. */
  81090. long block_start;
  81091. /* Window position at the beginning of the current output block. Gets
  81092. * negative when the window is moved backwards.
  81093. */
  81094. uInt match_length; /* length of best match */
  81095. IPos prev_match; /* previous match */
  81096. int match_available; /* set if previous match exists */
  81097. uInt strstart; /* start of string to insert */
  81098. uInt match_start; /* start of matching string */
  81099. uInt lookahead; /* number of valid bytes ahead in window */
  81100. uInt prev_length;
  81101. /* Length of the best match at previous step. Matches not greater than this
  81102. * are discarded. This is used in the lazy match evaluation.
  81103. */
  81104. uInt max_chain_length;
  81105. /* To speed up deflation, hash chains are never searched beyond this
  81106. * length. A higher limit improves compression ratio but degrades the
  81107. * speed.
  81108. */
  81109. uInt max_lazy_match;
  81110. /* Attempt to find a better match only when the current match is strictly
  81111. * smaller than this value. This mechanism is used only for compression
  81112. * levels >= 4.
  81113. */
  81114. # define max_insert_length max_lazy_match
  81115. /* Insert new strings in the hash table only if the match length is not
  81116. * greater than this length. This saves time but degrades compression.
  81117. * max_insert_length is used only for compression levels <= 3.
  81118. */
  81119. int level; /* compression level (1..9) */
  81120. int strategy; /* favor or force Huffman coding*/
  81121. uInt good_match;
  81122. /* Use a faster search when the previous match is longer than this */
  81123. int nice_match; /* Stop searching when current match exceeds this */
  81124. /* used by trees.c: */
  81125. /* Didn't use ct_data typedef below to supress compiler warning */
  81126. struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  81127. struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  81128. struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  81129. struct tree_desc_s l_desc; /* desc. for literal tree */
  81130. struct tree_desc_s d_desc; /* desc. for distance tree */
  81131. struct tree_desc_s bl_desc; /* desc. for bit length tree */
  81132. ush bl_count[MAX_BITS+1];
  81133. /* number of codes at each bit length for an optimal tree */
  81134. int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  81135. int heap_len; /* number of elements in the heap */
  81136. int heap_max; /* element of largest frequency */
  81137. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  81138. * The same heap array is used to build all trees.
  81139. */
  81140. uch depth[2*L_CODES+1];
  81141. /* Depth of each subtree used as tie breaker for trees of equal frequency
  81142. */
  81143. uchf *l_buf; /* buffer for literals or lengths */
  81144. uInt lit_bufsize;
  81145. /* Size of match buffer for literals/lengths. There are 4 reasons for
  81146. * limiting lit_bufsize to 64K:
  81147. * - frequencies can be kept in 16 bit counters
  81148. * - if compression is not successful for the first block, all input
  81149. * data is still in the window so we can still emit a stored block even
  81150. * when input comes from standard input. (This can also be done for
  81151. * all blocks if lit_bufsize is not greater than 32K.)
  81152. * - if compression is not successful for a file smaller than 64K, we can
  81153. * even emit a stored file instead of a stored block (saving 5 bytes).
  81154. * This is applicable only for zip (not gzip or zlib).
  81155. * - creating new Huffman trees less frequently may not provide fast
  81156. * adaptation to changes in the input data statistics. (Take for
  81157. * example a binary file with poorly compressible code followed by
  81158. * a highly compressible string table.) Smaller buffer sizes give
  81159. * fast adaptation but have of course the overhead of transmitting
  81160. * trees more frequently.
  81161. * - I can't count above 4
  81162. */
  81163. uInt last_lit; /* running index in l_buf */
  81164. ushf *d_buf;
  81165. /* Buffer for distances. To simplify the code, d_buf and l_buf have
  81166. * the same number of elements. To use different lengths, an extra flag
  81167. * array would be necessary.
  81168. */
  81169. ulg opt_len; /* bit length of current block with optimal trees */
  81170. ulg static_len; /* bit length of current block with static trees */
  81171. uInt matches; /* number of string matches in current block */
  81172. int last_eob_len; /* bit length of EOB code for last block */
  81173. #ifdef DEBUG
  81174. ulg compressed_len; /* total bit length of compressed file mod 2^32 */
  81175. ulg bits_sent; /* bit length of compressed data sent mod 2^32 */
  81176. #endif
  81177. ush bi_buf;
  81178. /* Output buffer. bits are inserted starting at the bottom (least
  81179. * significant bits).
  81180. */
  81181. int bi_valid;
  81182. /* Number of valid bits in bi_buf. All bits above the last valid bit
  81183. * are always zero.
  81184. */
  81185. } FAR deflate_state;
  81186. /* Output a byte on the stream.
  81187. * IN assertion: there is enough room in pending_buf.
  81188. */
  81189. #define put_byte(s, c) {s->pending_buf[s->pending++] = (c);}
  81190. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  81191. /* Minimum amount of lookahead, except at the end of the input file.
  81192. * See deflate.c for comments about the MIN_MATCH+1.
  81193. */
  81194. #define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD)
  81195. /* In order to simplify the code, particularly on 16 bit machines, match
  81196. * distances are limited to MAX_DIST instead of WSIZE.
  81197. */
  81198. /* in trees.c */
  81199. void _tr_init OF((deflate_state *s));
  81200. int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));
  81201. void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len,
  81202. int eof));
  81203. void _tr_align OF((deflate_state *s));
  81204. void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len,
  81205. int eof));
  81206. #define d_code(dist) \
  81207. ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
  81208. /* Mapping from a distance to a distance code. dist is the distance - 1 and
  81209. * must not have side effects. _dist_code[256] and _dist_code[257] are never
  81210. * used.
  81211. */
  81212. #ifndef DEBUG
  81213. /* Inline versions of _tr_tally for speed: */
  81214. #if defined(GEN_TREES_H) || !defined(STDC)
  81215. extern uch _length_code[];
  81216. extern uch _dist_code[];
  81217. #else
  81218. extern const uch _length_code[];
  81219. extern const uch _dist_code[];
  81220. #endif
  81221. # define _tr_tally_lit(s, c, flush) \
  81222. { uch cc = (c); \
  81223. s->d_buf[s->last_lit] = 0; \
  81224. s->l_buf[s->last_lit++] = cc; \
  81225. s->dyn_ltree[cc].Freq++; \
  81226. flush = (s->last_lit == s->lit_bufsize-1); \
  81227. }
  81228. # define _tr_tally_dist(s, distance, length, flush) \
  81229. { uch len = (length); \
  81230. ush dist = (distance); \
  81231. s->d_buf[s->last_lit] = dist; \
  81232. s->l_buf[s->last_lit++] = len; \
  81233. dist--; \
  81234. s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
  81235. s->dyn_dtree[d_code(dist)].Freq++; \
  81236. flush = (s->last_lit == s->lit_bufsize-1); \
  81237. }
  81238. #else
  81239. # define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)
  81240. # define _tr_tally_dist(s, distance, length, flush) \
  81241. flush = _tr_tally(s, distance, length)
  81242. #endif
  81243. #endif /* DEFLATE_H */
  81244. /*** End of inlined file: deflate.h ***/
  81245. const char deflate_copyright[] =
  81246. " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly ";
  81247. /*
  81248. If you use the zlib library in a product, an acknowledgment is welcome
  81249. in the documentation of your product. If for some reason you cannot
  81250. include such an acknowledgment, I would appreciate that you keep this
  81251. copyright string in the executable of your product.
  81252. */
  81253. /* ===========================================================================
  81254. * Function prototypes.
  81255. */
  81256. typedef enum {
  81257. need_more, /* block not completed, need more input or more output */
  81258. block_done, /* block flush performed */
  81259. finish_started, /* finish started, need only more output at next deflate */
  81260. finish_done /* finish done, accept no more input or output */
  81261. } block_state;
  81262. typedef block_state (*compress_func) OF((deflate_state *s, int flush));
  81263. /* Compression function. Returns the block state after the call. */
  81264. local void fill_window OF((deflate_state *s));
  81265. local block_state deflate_stored OF((deflate_state *s, int flush));
  81266. local block_state deflate_fast OF((deflate_state *s, int flush));
  81267. #ifndef FASTEST
  81268. local block_state deflate_slow OF((deflate_state *s, int flush));
  81269. #endif
  81270. local void lm_init OF((deflate_state *s));
  81271. local void putShortMSB OF((deflate_state *s, uInt b));
  81272. local void flush_pending OF((z_streamp strm));
  81273. local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size));
  81274. #ifndef FASTEST
  81275. #ifdef ASMV
  81276. void match_init OF((void)); /* asm code initialization */
  81277. uInt longest_match OF((deflate_state *s, IPos cur_match));
  81278. #else
  81279. local uInt longest_match OF((deflate_state *s, IPos cur_match));
  81280. #endif
  81281. #endif
  81282. local uInt longest_match_fast OF((deflate_state *s, IPos cur_match));
  81283. #ifdef DEBUG
  81284. local void check_match OF((deflate_state *s, IPos start, IPos match,
  81285. int length));
  81286. #endif
  81287. /* ===========================================================================
  81288. * Local data
  81289. */
  81290. #define NIL 0
  81291. /* Tail of hash chains */
  81292. #ifndef TOO_FAR
  81293. # define TOO_FAR 4096
  81294. #endif
  81295. /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
  81296. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  81297. /* Minimum amount of lookahead, except at the end of the input file.
  81298. * See deflate.c for comments about the MIN_MATCH+1.
  81299. */
  81300. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  81301. * the desired pack level (0..9). The values given below have been tuned to
  81302. * exclude worst case performance for pathological files. Better values may be
  81303. * found for specific files.
  81304. */
  81305. typedef struct config_s {
  81306. ush good_length; /* reduce lazy search above this match length */
  81307. ush max_lazy; /* do not perform lazy search above this match length */
  81308. ush nice_length; /* quit search above this match length */
  81309. ush max_chain;
  81310. compress_func func;
  81311. } config;
  81312. #ifdef FASTEST
  81313. local const config configuration_table[2] = {
  81314. /* good lazy nice chain */
  81315. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  81316. /* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */
  81317. #else
  81318. local const config configuration_table[10] = {
  81319. /* good lazy nice chain */
  81320. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  81321. /* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
  81322. /* 2 */ {4, 5, 16, 8, deflate_fast},
  81323. /* 3 */ {4, 6, 32, 32, deflate_fast},
  81324. /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
  81325. /* 5 */ {8, 16, 32, 32, deflate_slow},
  81326. /* 6 */ {8, 16, 128, 128, deflate_slow},
  81327. /* 7 */ {8, 32, 128, 256, deflate_slow},
  81328. /* 8 */ {32, 128, 258, 1024, deflate_slow},
  81329. /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
  81330. #endif
  81331. /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
  81332. * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
  81333. * meaning.
  81334. */
  81335. #define EQUAL 0
  81336. /* result of memcmp for equal strings */
  81337. #ifndef NO_DUMMY_DECL
  81338. struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
  81339. #endif
  81340. /* ===========================================================================
  81341. * Update a hash value with the given input byte
  81342. * IN assertion: all calls to to UPDATE_HASH are made with consecutive
  81343. * input characters, so that a running hash key can be computed from the
  81344. * previous key instead of complete recalculation each time.
  81345. */
  81346. #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
  81347. /* ===========================================================================
  81348. * Insert string str in the dictionary and set match_head to the previous head
  81349. * of the hash chain (the most recent string with same hash key). Return
  81350. * the previous length of the hash chain.
  81351. * If this file is compiled with -DFASTEST, the compression level is forced
  81352. * to 1, and no hash chains are maintained.
  81353. * IN assertion: all calls to to INSERT_STRING are made with consecutive
  81354. * input characters and the first MIN_MATCH bytes of str are valid
  81355. * (except for the last MIN_MATCH-1 bytes of the input file).
  81356. */
  81357. #ifdef FASTEST
  81358. #define INSERT_STRING(s, str, match_head) \
  81359. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  81360. match_head = s->head[s->ins_h], \
  81361. s->head[s->ins_h] = (Pos)(str))
  81362. #else
  81363. #define INSERT_STRING(s, str, match_head) \
  81364. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  81365. match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
  81366. s->head[s->ins_h] = (Pos)(str))
  81367. #endif
  81368. /* ===========================================================================
  81369. * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
  81370. * prev[] will be initialized on the fly.
  81371. */
  81372. #define CLEAR_HASH(s) \
  81373. s->head[s->hash_size-1] = NIL; \
  81374. zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
  81375. /* ========================================================================= */
  81376. int ZEXPORT deflateInit_(z_streamp strm, int level, const char *version, int stream_size)
  81377. {
  81378. return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
  81379. Z_DEFAULT_STRATEGY, version, stream_size);
  81380. /* To do: ignore strm->next_in if we use it as window */
  81381. }
  81382. /* ========================================================================= */
  81383. int ZEXPORT deflateInit2_ (z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy, const char *version, int stream_size)
  81384. {
  81385. deflate_state *s;
  81386. int wrap = 1;
  81387. static const char my_version[] = ZLIB_VERSION;
  81388. ushf *overlay;
  81389. /* We overlay pending_buf and d_buf+l_buf. This works since the average
  81390. * output size for (length,distance) codes is <= 24 bits.
  81391. */
  81392. if (version == Z_NULL || version[0] != my_version[0] ||
  81393. stream_size != sizeof(z_stream)) {
  81394. return Z_VERSION_ERROR;
  81395. }
  81396. if (strm == Z_NULL) return Z_STREAM_ERROR;
  81397. strm->msg = Z_NULL;
  81398. if (strm->zalloc == (alloc_func)0) {
  81399. strm->zalloc = zcalloc;
  81400. strm->opaque = (voidpf)0;
  81401. }
  81402. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  81403. #ifdef FASTEST
  81404. if (level != 0) level = 1;
  81405. #else
  81406. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  81407. #endif
  81408. if (windowBits < 0) { /* suppress zlib wrapper */
  81409. wrap = 0;
  81410. windowBits = -windowBits;
  81411. }
  81412. #ifdef GZIP
  81413. else if (windowBits > 15) {
  81414. wrap = 2; /* write gzip wrapper instead */
  81415. windowBits -= 16;
  81416. }
  81417. #endif
  81418. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
  81419. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  81420. strategy < 0 || strategy > Z_FIXED) {
  81421. return Z_STREAM_ERROR;
  81422. }
  81423. if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
  81424. s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
  81425. if (s == Z_NULL) return Z_MEM_ERROR;
  81426. strm->state = (struct internal_state FAR *)s;
  81427. s->strm = strm;
  81428. s->wrap = wrap;
  81429. s->gzhead = Z_NULL;
  81430. s->w_bits = windowBits;
  81431. s->w_size = 1 << s->w_bits;
  81432. s->w_mask = s->w_size - 1;
  81433. s->hash_bits = memLevel + 7;
  81434. s->hash_size = 1 << s->hash_bits;
  81435. s->hash_mask = s->hash_size - 1;
  81436. s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
  81437. s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
  81438. s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
  81439. s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
  81440. s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  81441. overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  81442. s->pending_buf = (uchf *) overlay;
  81443. s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
  81444. if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
  81445. s->pending_buf == Z_NULL) {
  81446. s->status = FINISH_STATE;
  81447. strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);
  81448. deflateEnd (strm);
  81449. return Z_MEM_ERROR;
  81450. }
  81451. s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  81452. s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  81453. s->level = level;
  81454. s->strategy = strategy;
  81455. s->method = (Byte)method;
  81456. return deflateReset(strm);
  81457. }
  81458. /* ========================================================================= */
  81459. int ZEXPORT deflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  81460. {
  81461. deflate_state *s;
  81462. uInt length = dictLength;
  81463. uInt n;
  81464. IPos hash_head = 0;
  81465. if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
  81466. strm->state->wrap == 2 ||
  81467. (strm->state->wrap == 1 && strm->state->status != INIT_STATE))
  81468. return Z_STREAM_ERROR;
  81469. s = strm->state;
  81470. if (s->wrap)
  81471. strm->adler = adler32(strm->adler, dictionary, dictLength);
  81472. if (length < MIN_MATCH) return Z_OK;
  81473. if (length > MAX_DIST(s)) {
  81474. length = MAX_DIST(s);
  81475. dictionary += dictLength - length; /* use the tail of the dictionary */
  81476. }
  81477. zmemcpy(s->window, dictionary, length);
  81478. s->strstart = length;
  81479. s->block_start = (long)length;
  81480. /* Insert all strings in the hash table (except for the last two bytes).
  81481. * s->lookahead stays null, so s->ins_h will be recomputed at the next
  81482. * call of fill_window.
  81483. */
  81484. s->ins_h = s->window[0];
  81485. UPDATE_HASH(s, s->ins_h, s->window[1]);
  81486. for (n = 0; n <= length - MIN_MATCH; n++) {
  81487. INSERT_STRING(s, n, hash_head);
  81488. }
  81489. if (hash_head) hash_head = 0; /* to make compiler happy */
  81490. return Z_OK;
  81491. }
  81492. /* ========================================================================= */
  81493. int ZEXPORT deflateReset (z_streamp strm)
  81494. {
  81495. deflate_state *s;
  81496. if (strm == Z_NULL || strm->state == Z_NULL ||
  81497. strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {
  81498. return Z_STREAM_ERROR;
  81499. }
  81500. strm->total_in = strm->total_out = 0;
  81501. strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
  81502. strm->data_type = Z_UNKNOWN;
  81503. s = (deflate_state *)strm->state;
  81504. s->pending = 0;
  81505. s->pending_out = s->pending_buf;
  81506. if (s->wrap < 0) {
  81507. s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
  81508. }
  81509. s->status = s->wrap ? INIT_STATE : BUSY_STATE;
  81510. strm->adler =
  81511. #ifdef GZIP
  81512. s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
  81513. #endif
  81514. adler32(0L, Z_NULL, 0);
  81515. s->last_flush = Z_NO_FLUSH;
  81516. _tr_init(s);
  81517. lm_init(s);
  81518. return Z_OK;
  81519. }
  81520. /* ========================================================================= */
  81521. int ZEXPORT deflateSetHeader (z_streamp strm, gz_headerp head)
  81522. {
  81523. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81524. if (strm->state->wrap != 2) return Z_STREAM_ERROR;
  81525. strm->state->gzhead = head;
  81526. return Z_OK;
  81527. }
  81528. /* ========================================================================= */
  81529. int ZEXPORT deflatePrime (z_streamp strm, int bits, int value)
  81530. {
  81531. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81532. strm->state->bi_valid = bits;
  81533. strm->state->bi_buf = (ush)(value & ((1 << bits) - 1));
  81534. return Z_OK;
  81535. }
  81536. /* ========================================================================= */
  81537. int ZEXPORT deflateParams (z_streamp strm, int level, int strategy)
  81538. {
  81539. deflate_state *s;
  81540. compress_func func;
  81541. int err = Z_OK;
  81542. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81543. s = strm->state;
  81544. #ifdef FASTEST
  81545. if (level != 0) level = 1;
  81546. #else
  81547. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  81548. #endif
  81549. if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
  81550. return Z_STREAM_ERROR;
  81551. }
  81552. func = configuration_table[s->level].func;
  81553. if (func != configuration_table[level].func && strm->total_in != 0) {
  81554. /* Flush the last buffer: */
  81555. err = deflate(strm, Z_PARTIAL_FLUSH);
  81556. }
  81557. if (s->level != level) {
  81558. s->level = level;
  81559. s->max_lazy_match = configuration_table[level].max_lazy;
  81560. s->good_match = configuration_table[level].good_length;
  81561. s->nice_match = configuration_table[level].nice_length;
  81562. s->max_chain_length = configuration_table[level].max_chain;
  81563. }
  81564. s->strategy = strategy;
  81565. return err;
  81566. }
  81567. /* ========================================================================= */
  81568. int ZEXPORT deflateTune (z_streamp strm, int good_length, int max_lazy, int nice_length, int max_chain)
  81569. {
  81570. deflate_state *s;
  81571. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81572. s = strm->state;
  81573. s->good_match = good_length;
  81574. s->max_lazy_match = max_lazy;
  81575. s->nice_match = nice_length;
  81576. s->max_chain_length = max_chain;
  81577. return Z_OK;
  81578. }
  81579. /* =========================================================================
  81580. * For the default windowBits of 15 and memLevel of 8, this function returns
  81581. * a close to exact, as well as small, upper bound on the compressed size.
  81582. * They are coded as constants here for a reason--if the #define's are
  81583. * changed, then this function needs to be changed as well. The return
  81584. * value for 15 and 8 only works for those exact settings.
  81585. *
  81586. * For any setting other than those defaults for windowBits and memLevel,
  81587. * the value returned is a conservative worst case for the maximum expansion
  81588. * resulting from using fixed blocks instead of stored blocks, which deflate
  81589. * can emit on compressed data for some combinations of the parameters.
  81590. *
  81591. * This function could be more sophisticated to provide closer upper bounds
  81592. * for every combination of windowBits and memLevel, as well as wrap.
  81593. * But even the conservative upper bound of about 14% expansion does not
  81594. * seem onerous for output buffer allocation.
  81595. */
  81596. uLong ZEXPORT deflateBound (z_streamp strm, uLong sourceLen)
  81597. {
  81598. deflate_state *s;
  81599. uLong destLen;
  81600. /* conservative upper bound */
  81601. destLen = sourceLen +
  81602. ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11;
  81603. /* if can't get parameters, return conservative bound */
  81604. if (strm == Z_NULL || strm->state == Z_NULL)
  81605. return destLen;
  81606. /* if not default parameters, return conservative bound */
  81607. s = strm->state;
  81608. if (s->w_bits != 15 || s->hash_bits != 8 + 7)
  81609. return destLen;
  81610. /* default settings: return tight bound for that case */
  81611. return compressBound(sourceLen);
  81612. }
  81613. /* =========================================================================
  81614. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  81615. * IN assertion: the stream state is correct and there is enough room in
  81616. * pending_buf.
  81617. */
  81618. local void putShortMSB (deflate_state *s, uInt b)
  81619. {
  81620. put_byte(s, (Byte)(b >> 8));
  81621. put_byte(s, (Byte)(b & 0xff));
  81622. }
  81623. /* =========================================================================
  81624. * Flush as much pending output as possible. All deflate() output goes
  81625. * through this function so some applications may wish to modify it
  81626. * to avoid allocating a large strm->next_out buffer and copying into it.
  81627. * (See also read_buf()).
  81628. */
  81629. local void flush_pending (z_streamp strm)
  81630. {
  81631. unsigned len = strm->state->pending;
  81632. if (len > strm->avail_out) len = strm->avail_out;
  81633. if (len == 0) return;
  81634. zmemcpy(strm->next_out, strm->state->pending_out, len);
  81635. strm->next_out += len;
  81636. strm->state->pending_out += len;
  81637. strm->total_out += len;
  81638. strm->avail_out -= len;
  81639. strm->state->pending -= len;
  81640. if (strm->state->pending == 0) {
  81641. strm->state->pending_out = strm->state->pending_buf;
  81642. }
  81643. }
  81644. /* ========================================================================= */
  81645. int ZEXPORT deflate (z_streamp strm, int flush)
  81646. {
  81647. int old_flush; /* value of flush param for previous deflate call */
  81648. deflate_state *s;
  81649. if (strm == Z_NULL || strm->state == Z_NULL ||
  81650. flush > Z_FINISH || flush < 0) {
  81651. return Z_STREAM_ERROR;
  81652. }
  81653. s = strm->state;
  81654. if (strm->next_out == Z_NULL ||
  81655. (strm->next_in == Z_NULL && strm->avail_in != 0) ||
  81656. (s->status == FINISH_STATE && flush != Z_FINISH)) {
  81657. ERR_RETURN(strm, Z_STREAM_ERROR);
  81658. }
  81659. if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
  81660. s->strm = strm; /* just in case */
  81661. old_flush = s->last_flush;
  81662. s->last_flush = flush;
  81663. /* Write the header */
  81664. if (s->status == INIT_STATE) {
  81665. #ifdef GZIP
  81666. if (s->wrap == 2) {
  81667. strm->adler = crc32(0L, Z_NULL, 0);
  81668. put_byte(s, 31);
  81669. put_byte(s, 139);
  81670. put_byte(s, 8);
  81671. if (s->gzhead == NULL) {
  81672. put_byte(s, 0);
  81673. put_byte(s, 0);
  81674. put_byte(s, 0);
  81675. put_byte(s, 0);
  81676. put_byte(s, 0);
  81677. put_byte(s, s->level == 9 ? 2 :
  81678. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  81679. 4 : 0));
  81680. put_byte(s, OS_CODE);
  81681. s->status = BUSY_STATE;
  81682. }
  81683. else {
  81684. put_byte(s, (s->gzhead->text ? 1 : 0) +
  81685. (s->gzhead->hcrc ? 2 : 0) +
  81686. (s->gzhead->extra == Z_NULL ? 0 : 4) +
  81687. (s->gzhead->name == Z_NULL ? 0 : 8) +
  81688. (s->gzhead->comment == Z_NULL ? 0 : 16)
  81689. );
  81690. put_byte(s, (Byte)(s->gzhead->time & 0xff));
  81691. put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
  81692. put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
  81693. put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
  81694. put_byte(s, s->level == 9 ? 2 :
  81695. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  81696. 4 : 0));
  81697. put_byte(s, s->gzhead->os & 0xff);
  81698. if (s->gzhead->extra != NULL) {
  81699. put_byte(s, s->gzhead->extra_len & 0xff);
  81700. put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
  81701. }
  81702. if (s->gzhead->hcrc)
  81703. strm->adler = crc32(strm->adler, s->pending_buf,
  81704. s->pending);
  81705. s->gzindex = 0;
  81706. s->status = EXTRA_STATE;
  81707. }
  81708. }
  81709. else
  81710. #endif
  81711. {
  81712. uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
  81713. uInt level_flags;
  81714. if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
  81715. level_flags = 0;
  81716. else if (s->level < 6)
  81717. level_flags = 1;
  81718. else if (s->level == 6)
  81719. level_flags = 2;
  81720. else
  81721. level_flags = 3;
  81722. header |= (level_flags << 6);
  81723. if (s->strstart != 0) header |= PRESET_DICT;
  81724. header += 31 - (header % 31);
  81725. s->status = BUSY_STATE;
  81726. putShortMSB(s, header);
  81727. /* Save the adler32 of the preset dictionary: */
  81728. if (s->strstart != 0) {
  81729. putShortMSB(s, (uInt)(strm->adler >> 16));
  81730. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  81731. }
  81732. strm->adler = adler32(0L, Z_NULL, 0);
  81733. }
  81734. }
  81735. #ifdef GZIP
  81736. if (s->status == EXTRA_STATE) {
  81737. if (s->gzhead->extra != NULL) {
  81738. uInt beg = s->pending; /* start of bytes to update crc */
  81739. while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
  81740. if (s->pending == s->pending_buf_size) {
  81741. if (s->gzhead->hcrc && s->pending > beg)
  81742. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81743. s->pending - beg);
  81744. flush_pending(strm);
  81745. beg = s->pending;
  81746. if (s->pending == s->pending_buf_size)
  81747. break;
  81748. }
  81749. put_byte(s, s->gzhead->extra[s->gzindex]);
  81750. s->gzindex++;
  81751. }
  81752. if (s->gzhead->hcrc && s->pending > beg)
  81753. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81754. s->pending - beg);
  81755. if (s->gzindex == s->gzhead->extra_len) {
  81756. s->gzindex = 0;
  81757. s->status = NAME_STATE;
  81758. }
  81759. }
  81760. else
  81761. s->status = NAME_STATE;
  81762. }
  81763. if (s->status == NAME_STATE) {
  81764. if (s->gzhead->name != NULL) {
  81765. uInt beg = s->pending; /* start of bytes to update crc */
  81766. int val;
  81767. do {
  81768. if (s->pending == s->pending_buf_size) {
  81769. if (s->gzhead->hcrc && s->pending > beg)
  81770. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81771. s->pending - beg);
  81772. flush_pending(strm);
  81773. beg = s->pending;
  81774. if (s->pending == s->pending_buf_size) {
  81775. val = 1;
  81776. break;
  81777. }
  81778. }
  81779. val = s->gzhead->name[s->gzindex++];
  81780. put_byte(s, val);
  81781. } while (val != 0);
  81782. if (s->gzhead->hcrc && s->pending > beg)
  81783. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81784. s->pending - beg);
  81785. if (val == 0) {
  81786. s->gzindex = 0;
  81787. s->status = COMMENT_STATE;
  81788. }
  81789. }
  81790. else
  81791. s->status = COMMENT_STATE;
  81792. }
  81793. if (s->status == COMMENT_STATE) {
  81794. if (s->gzhead->comment != NULL) {
  81795. uInt beg = s->pending; /* start of bytes to update crc */
  81796. int val;
  81797. do {
  81798. if (s->pending == s->pending_buf_size) {
  81799. if (s->gzhead->hcrc && s->pending > beg)
  81800. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81801. s->pending - beg);
  81802. flush_pending(strm);
  81803. beg = s->pending;
  81804. if (s->pending == s->pending_buf_size) {
  81805. val = 1;
  81806. break;
  81807. }
  81808. }
  81809. val = s->gzhead->comment[s->gzindex++];
  81810. put_byte(s, val);
  81811. } while (val != 0);
  81812. if (s->gzhead->hcrc && s->pending > beg)
  81813. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81814. s->pending - beg);
  81815. if (val == 0)
  81816. s->status = HCRC_STATE;
  81817. }
  81818. else
  81819. s->status = HCRC_STATE;
  81820. }
  81821. if (s->status == HCRC_STATE) {
  81822. if (s->gzhead->hcrc) {
  81823. if (s->pending + 2 > s->pending_buf_size)
  81824. flush_pending(strm);
  81825. if (s->pending + 2 <= s->pending_buf_size) {
  81826. put_byte(s, (Byte)(strm->adler & 0xff));
  81827. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  81828. strm->adler = crc32(0L, Z_NULL, 0);
  81829. s->status = BUSY_STATE;
  81830. }
  81831. }
  81832. else
  81833. s->status = BUSY_STATE;
  81834. }
  81835. #endif
  81836. /* Flush as much pending output as possible */
  81837. if (s->pending != 0) {
  81838. flush_pending(strm);
  81839. if (strm->avail_out == 0) {
  81840. /* Since avail_out is 0, deflate will be called again with
  81841. * more output space, but possibly with both pending and
  81842. * avail_in equal to zero. There won't be anything to do,
  81843. * but this is not an error situation so make sure we
  81844. * return OK instead of BUF_ERROR at next call of deflate:
  81845. */
  81846. s->last_flush = -1;
  81847. return Z_OK;
  81848. }
  81849. /* Make sure there is something to do and avoid duplicate consecutive
  81850. * flushes. For repeated and useless calls with Z_FINISH, we keep
  81851. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  81852. */
  81853. } else if (strm->avail_in == 0 && flush <= old_flush &&
  81854. flush != Z_FINISH) {
  81855. ERR_RETURN(strm, Z_BUF_ERROR);
  81856. }
  81857. /* User must not provide more input after the first FINISH: */
  81858. if (s->status == FINISH_STATE && strm->avail_in != 0) {
  81859. ERR_RETURN(strm, Z_BUF_ERROR);
  81860. }
  81861. /* Start a new block or continue the current one.
  81862. */
  81863. if (strm->avail_in != 0 || s->lookahead != 0 ||
  81864. (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
  81865. block_state bstate;
  81866. bstate = (*(configuration_table[s->level].func))(s, flush);
  81867. if (bstate == finish_started || bstate == finish_done) {
  81868. s->status = FINISH_STATE;
  81869. }
  81870. if (bstate == need_more || bstate == finish_started) {
  81871. if (strm->avail_out == 0) {
  81872. s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
  81873. }
  81874. return Z_OK;
  81875. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  81876. * of deflate should use the same flush parameter to make sure
  81877. * that the flush is complete. So we don't have to output an
  81878. * empty block here, this will be done at next call. This also
  81879. * ensures that for a very small output buffer, we emit at most
  81880. * one empty block.
  81881. */
  81882. }
  81883. if (bstate == block_done) {
  81884. if (flush == Z_PARTIAL_FLUSH) {
  81885. _tr_align(s);
  81886. } else { /* FULL_FLUSH or SYNC_FLUSH */
  81887. _tr_stored_block(s, (char*)0, 0L, 0);
  81888. /* For a full flush, this empty block will be recognized
  81889. * as a special marker by inflate_sync().
  81890. */
  81891. if (flush == Z_FULL_FLUSH) {
  81892. CLEAR_HASH(s); /* forget history */
  81893. }
  81894. }
  81895. flush_pending(strm);
  81896. if (strm->avail_out == 0) {
  81897. s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  81898. return Z_OK;
  81899. }
  81900. }
  81901. }
  81902. Assert(strm->avail_out > 0, "bug2");
  81903. if (flush != Z_FINISH) return Z_OK;
  81904. if (s->wrap <= 0) return Z_STREAM_END;
  81905. /* Write the trailer */
  81906. #ifdef GZIP
  81907. if (s->wrap == 2) {
  81908. put_byte(s, (Byte)(strm->adler & 0xff));
  81909. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  81910. put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
  81911. put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
  81912. put_byte(s, (Byte)(strm->total_in & 0xff));
  81913. put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
  81914. put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
  81915. put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
  81916. }
  81917. else
  81918. #endif
  81919. {
  81920. putShortMSB(s, (uInt)(strm->adler >> 16));
  81921. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  81922. }
  81923. flush_pending(strm);
  81924. /* If avail_out is zero, the application will call deflate again
  81925. * to flush the rest.
  81926. */
  81927. if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
  81928. return s->pending != 0 ? Z_OK : Z_STREAM_END;
  81929. }
  81930. /* ========================================================================= */
  81931. int ZEXPORT deflateEnd (z_streamp strm)
  81932. {
  81933. int status;
  81934. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81935. status = strm->state->status;
  81936. if (status != INIT_STATE &&
  81937. status != EXTRA_STATE &&
  81938. status != NAME_STATE &&
  81939. status != COMMENT_STATE &&
  81940. status != HCRC_STATE &&
  81941. status != BUSY_STATE &&
  81942. status != FINISH_STATE) {
  81943. return Z_STREAM_ERROR;
  81944. }
  81945. /* Deallocate in reverse order of allocations: */
  81946. TRY_FREE(strm, strm->state->pending_buf);
  81947. TRY_FREE(strm, strm->state->head);
  81948. TRY_FREE(strm, strm->state->prev);
  81949. TRY_FREE(strm, strm->state->window);
  81950. ZFREE(strm, strm->state);
  81951. strm->state = Z_NULL;
  81952. return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
  81953. }
  81954. /* =========================================================================
  81955. * Copy the source state to the destination state.
  81956. * To simplify the source, this is not supported for 16-bit MSDOS (which
  81957. * doesn't have enough memory anyway to duplicate compression states).
  81958. */
  81959. int ZEXPORT deflateCopy (z_streamp dest, z_streamp source)
  81960. {
  81961. #ifdef MAXSEG_64K
  81962. return Z_STREAM_ERROR;
  81963. #else
  81964. deflate_state *ds;
  81965. deflate_state *ss;
  81966. ushf *overlay;
  81967. if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
  81968. return Z_STREAM_ERROR;
  81969. }
  81970. ss = source->state;
  81971. zmemcpy(dest, source, sizeof(z_stream));
  81972. ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
  81973. if (ds == Z_NULL) return Z_MEM_ERROR;
  81974. dest->state = (struct internal_state FAR *) ds;
  81975. zmemcpy(ds, ss, sizeof(deflate_state));
  81976. ds->strm = dest;
  81977. ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
  81978. ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
  81979. ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
  81980. overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
  81981. ds->pending_buf = (uchf *) overlay;
  81982. if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
  81983. ds->pending_buf == Z_NULL) {
  81984. deflateEnd (dest);
  81985. return Z_MEM_ERROR;
  81986. }
  81987. /* following zmemcpy do not work for 16-bit MSDOS */
  81988. zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
  81989. zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
  81990. zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
  81991. zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
  81992. ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
  81993. ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
  81994. ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
  81995. ds->l_desc.dyn_tree = ds->dyn_ltree;
  81996. ds->d_desc.dyn_tree = ds->dyn_dtree;
  81997. ds->bl_desc.dyn_tree = ds->bl_tree;
  81998. return Z_OK;
  81999. #endif /* MAXSEG_64K */
  82000. }
  82001. /* ===========================================================================
  82002. * Read a new buffer from the current input stream, update the adler32
  82003. * and total number of bytes read. All deflate() input goes through
  82004. * this function so some applications may wish to modify it to avoid
  82005. * allocating a large strm->next_in buffer and copying from it.
  82006. * (See also flush_pending()).
  82007. */
  82008. local int read_buf (z_streamp strm, Bytef *buf, unsigned size)
  82009. {
  82010. unsigned len = strm->avail_in;
  82011. if (len > size) len = size;
  82012. if (len == 0) return 0;
  82013. strm->avail_in -= len;
  82014. if (strm->state->wrap == 1) {
  82015. strm->adler = adler32(strm->adler, strm->next_in, len);
  82016. }
  82017. #ifdef GZIP
  82018. else if (strm->state->wrap == 2) {
  82019. strm->adler = crc32(strm->adler, strm->next_in, len);
  82020. }
  82021. #endif
  82022. zmemcpy(buf, strm->next_in, len);
  82023. strm->next_in += len;
  82024. strm->total_in += len;
  82025. return (int)len;
  82026. }
  82027. /* ===========================================================================
  82028. * Initialize the "longest match" routines for a new zlib stream
  82029. */
  82030. local void lm_init (deflate_state *s)
  82031. {
  82032. s->window_size = (ulg)2L*s->w_size;
  82033. CLEAR_HASH(s);
  82034. /* Set the default configuration parameters:
  82035. */
  82036. s->max_lazy_match = configuration_table[s->level].max_lazy;
  82037. s->good_match = configuration_table[s->level].good_length;
  82038. s->nice_match = configuration_table[s->level].nice_length;
  82039. s->max_chain_length = configuration_table[s->level].max_chain;
  82040. s->strstart = 0;
  82041. s->block_start = 0L;
  82042. s->lookahead = 0;
  82043. s->match_length = s->prev_length = MIN_MATCH-1;
  82044. s->match_available = 0;
  82045. s->ins_h = 0;
  82046. #ifndef FASTEST
  82047. #ifdef ASMV
  82048. match_init(); /* initialize the asm code */
  82049. #endif
  82050. #endif
  82051. }
  82052. #ifndef FASTEST
  82053. /* ===========================================================================
  82054. * Set match_start to the longest match starting at the given string and
  82055. * return its length. Matches shorter or equal to prev_length are discarded,
  82056. * in which case the result is equal to prev_length and match_start is
  82057. * garbage.
  82058. * IN assertions: cur_match is the head of the hash chain for the current
  82059. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  82060. * OUT assertion: the match length is not greater than s->lookahead.
  82061. */
  82062. #ifndef ASMV
  82063. /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
  82064. * match.S. The code will be functionally equivalent.
  82065. */
  82066. local uInt longest_match(deflate_state *s, IPos cur_match)
  82067. {
  82068. unsigned chain_length = s->max_chain_length;/* max hash chain length */
  82069. register Bytef *scan = s->window + s->strstart; /* current string */
  82070. register Bytef *match; /* matched string */
  82071. register int len; /* length of current match */
  82072. int best_len = s->prev_length; /* best match length so far */
  82073. int nice_match = s->nice_match; /* stop if match long enough */
  82074. IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
  82075. s->strstart - (IPos)MAX_DIST(s) : NIL;
  82076. /* Stop when cur_match becomes <= limit. To simplify the code,
  82077. * we prevent matches with the string of window index 0.
  82078. */
  82079. Posf *prev = s->prev;
  82080. uInt wmask = s->w_mask;
  82081. #ifdef UNALIGNED_OK
  82082. /* Compare two bytes at a time. Note: this is not always beneficial.
  82083. * Try with and without -DUNALIGNED_OK to check.
  82084. */
  82085. register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
  82086. register ush scan_start = *(ushf*)scan;
  82087. register ush scan_end = *(ushf*)(scan+best_len-1);
  82088. #else
  82089. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  82090. register Byte scan_end1 = scan[best_len-1];
  82091. register Byte scan_end = scan[best_len];
  82092. #endif
  82093. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  82094. * It is easy to get rid of this optimization if necessary.
  82095. */
  82096. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  82097. /* Do not waste too much time if we already have a good match: */
  82098. if (s->prev_length >= s->good_match) {
  82099. chain_length >>= 2;
  82100. }
  82101. /* Do not look for matches beyond the end of the input. This is necessary
  82102. * to make deflate deterministic.
  82103. */
  82104. if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
  82105. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  82106. do {
  82107. Assert(cur_match < s->strstart, "no future");
  82108. match = s->window + cur_match;
  82109. /* Skip to next match if the match length cannot increase
  82110. * or if the match length is less than 2. Note that the checks below
  82111. * for insufficient lookahead only occur occasionally for performance
  82112. * reasons. Therefore uninitialized memory will be accessed, and
  82113. * conditional jumps will be made that depend on those values.
  82114. * However the length of the match is limited to the lookahead, so
  82115. * the output of deflate is not affected by the uninitialized values.
  82116. */
  82117. #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
  82118. /* This code assumes sizeof(unsigned short) == 2. Do not use
  82119. * UNALIGNED_OK if your compiler uses a different size.
  82120. */
  82121. if (*(ushf*)(match+best_len-1) != scan_end ||
  82122. *(ushf*)match != scan_start) continue;
  82123. /* It is not necessary to compare scan[2] and match[2] since they are
  82124. * always equal when the other bytes match, given that the hash keys
  82125. * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
  82126. * strstart+3, +5, ... up to strstart+257. We check for insufficient
  82127. * lookahead only every 4th comparison; the 128th check will be made
  82128. * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
  82129. * necessary to put more guard bytes at the end of the window, or
  82130. * to check more often for insufficient lookahead.
  82131. */
  82132. Assert(scan[2] == match[2], "scan[2]?");
  82133. scan++, match++;
  82134. do {
  82135. } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  82136. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  82137. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  82138. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  82139. scan < strend);
  82140. /* The funny "do {}" generates better code on most compilers */
  82141. /* Here, scan <= window+strstart+257 */
  82142. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  82143. if (*scan == *match) scan++;
  82144. len = (MAX_MATCH - 1) - (int)(strend-scan);
  82145. scan = strend - (MAX_MATCH-1);
  82146. #else /* UNALIGNED_OK */
  82147. if (match[best_len] != scan_end ||
  82148. match[best_len-1] != scan_end1 ||
  82149. *match != *scan ||
  82150. *++match != scan[1]) continue;
  82151. /* The check at best_len-1 can be removed because it will be made
  82152. * again later. (This heuristic is not always a win.)
  82153. * It is not necessary to compare scan[2] and match[2] since they
  82154. * are always equal when the other bytes match, given that
  82155. * the hash keys are equal and that HASH_BITS >= 8.
  82156. */
  82157. scan += 2, match++;
  82158. Assert(*scan == *match, "match[2]?");
  82159. /* We check for insufficient lookahead only every 8th comparison;
  82160. * the 256th check will be made at strstart+258.
  82161. */
  82162. do {
  82163. } while (*++scan == *++match && *++scan == *++match &&
  82164. *++scan == *++match && *++scan == *++match &&
  82165. *++scan == *++match && *++scan == *++match &&
  82166. *++scan == *++match && *++scan == *++match &&
  82167. scan < strend);
  82168. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  82169. len = MAX_MATCH - (int)(strend - scan);
  82170. scan = strend - MAX_MATCH;
  82171. #endif /* UNALIGNED_OK */
  82172. if (len > best_len) {
  82173. s->match_start = cur_match;
  82174. best_len = len;
  82175. if (len >= nice_match) break;
  82176. #ifdef UNALIGNED_OK
  82177. scan_end = *(ushf*)(scan+best_len-1);
  82178. #else
  82179. scan_end1 = scan[best_len-1];
  82180. scan_end = scan[best_len];
  82181. #endif
  82182. }
  82183. } while ((cur_match = prev[cur_match & wmask]) > limit
  82184. && --chain_length != 0);
  82185. if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
  82186. return s->lookahead;
  82187. }
  82188. #endif /* ASMV */
  82189. #endif /* FASTEST */
  82190. /* ---------------------------------------------------------------------------
  82191. * Optimized version for level == 1 or strategy == Z_RLE only
  82192. */
  82193. local uInt longest_match_fast (deflate_state *s, IPos cur_match)
  82194. {
  82195. register Bytef *scan = s->window + s->strstart; /* current string */
  82196. register Bytef *match; /* matched string */
  82197. register int len; /* length of current match */
  82198. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  82199. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  82200. * It is easy to get rid of this optimization if necessary.
  82201. */
  82202. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  82203. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  82204. Assert(cur_match < s->strstart, "no future");
  82205. match = s->window + cur_match;
  82206. /* Return failure if the match length is less than 2:
  82207. */
  82208. if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
  82209. /* The check at best_len-1 can be removed because it will be made
  82210. * again later. (This heuristic is not always a win.)
  82211. * It is not necessary to compare scan[2] and match[2] since they
  82212. * are always equal when the other bytes match, given that
  82213. * the hash keys are equal and that HASH_BITS >= 8.
  82214. */
  82215. scan += 2, match += 2;
  82216. Assert(*scan == *match, "match[2]?");
  82217. /* We check for insufficient lookahead only every 8th comparison;
  82218. * the 256th check will be made at strstart+258.
  82219. */
  82220. do {
  82221. } while (*++scan == *++match && *++scan == *++match &&
  82222. *++scan == *++match && *++scan == *++match &&
  82223. *++scan == *++match && *++scan == *++match &&
  82224. *++scan == *++match && *++scan == *++match &&
  82225. scan < strend);
  82226. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  82227. len = MAX_MATCH - (int)(strend - scan);
  82228. if (len < MIN_MATCH) return MIN_MATCH - 1;
  82229. s->match_start = cur_match;
  82230. return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
  82231. }
  82232. #ifdef DEBUG
  82233. /* ===========================================================================
  82234. * Check that the match at match_start is indeed a match.
  82235. */
  82236. local void check_match(deflate_state *s, IPos start, IPos match, int length)
  82237. {
  82238. /* check that the match is indeed a match */
  82239. if (zmemcmp(s->window + match,
  82240. s->window + start, length) != EQUAL) {
  82241. fprintf(stderr, " start %u, match %u, length %d\n",
  82242. start, match, length);
  82243. do {
  82244. fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
  82245. } while (--length != 0);
  82246. z_error("invalid match");
  82247. }
  82248. if (z_verbose > 1) {
  82249. fprintf(stderr,"\\[%d,%d]", start-match, length);
  82250. do { putc(s->window[start++], stderr); } while (--length != 0);
  82251. }
  82252. }
  82253. #else
  82254. # define check_match(s, start, match, length)
  82255. #endif /* DEBUG */
  82256. /* ===========================================================================
  82257. * Fill the window when the lookahead becomes insufficient.
  82258. * Updates strstart and lookahead.
  82259. *
  82260. * IN assertion: lookahead < MIN_LOOKAHEAD
  82261. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  82262. * At least one byte has been read, or avail_in == 0; reads are
  82263. * performed for at least two bytes (required for the zip translate_eol
  82264. * option -- not supported here).
  82265. */
  82266. local void fill_window (deflate_state *s)
  82267. {
  82268. register unsigned n, m;
  82269. register Posf *p;
  82270. unsigned more; /* Amount of free space at the end of the window. */
  82271. uInt wsize = s->w_size;
  82272. do {
  82273. more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
  82274. /* Deal with !@#$% 64K limit: */
  82275. if (sizeof(int) <= 2) {
  82276. if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  82277. more = wsize;
  82278. } else if (more == (unsigned)(-1)) {
  82279. /* Very unlikely, but possible on 16 bit machine if
  82280. * strstart == 0 && lookahead == 1 (input done a byte at time)
  82281. */
  82282. more--;
  82283. }
  82284. }
  82285. /* If the window is almost full and there is insufficient lookahead,
  82286. * move the upper half to the lower one to make room in the upper half.
  82287. */
  82288. if (s->strstart >= wsize+MAX_DIST(s)) {
  82289. zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
  82290. s->match_start -= wsize;
  82291. s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
  82292. s->block_start -= (long) wsize;
  82293. /* Slide the hash table (could be avoided with 32 bit values
  82294. at the expense of memory usage). We slide even when level == 0
  82295. to keep the hash table consistent if we switch back to level > 0
  82296. later. (Using level 0 permanently is not an optimal usage of
  82297. zlib, so we don't care about this pathological case.)
  82298. */
  82299. /* %%% avoid this when Z_RLE */
  82300. n = s->hash_size;
  82301. p = &s->head[n];
  82302. do {
  82303. m = *--p;
  82304. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  82305. } while (--n);
  82306. n = wsize;
  82307. #ifndef FASTEST
  82308. p = &s->prev[n];
  82309. do {
  82310. m = *--p;
  82311. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  82312. /* If n is not on any hash chain, prev[n] is garbage but
  82313. * its value will never be used.
  82314. */
  82315. } while (--n);
  82316. #endif
  82317. more += wsize;
  82318. }
  82319. if (s->strm->avail_in == 0) return;
  82320. /* If there was no sliding:
  82321. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  82322. * more == window_size - lookahead - strstart
  82323. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  82324. * => more >= window_size - 2*WSIZE + 2
  82325. * In the BIG_MEM or MMAP case (not yet supported),
  82326. * window_size == input_size + MIN_LOOKAHEAD &&
  82327. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  82328. * Otherwise, window_size == 2*WSIZE so more >= 2.
  82329. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  82330. */
  82331. Assert(more >= 2, "more < 2");
  82332. n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
  82333. s->lookahead += n;
  82334. /* Initialize the hash value now that we have some input: */
  82335. if (s->lookahead >= MIN_MATCH) {
  82336. s->ins_h = s->window[s->strstart];
  82337. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  82338. #if MIN_MATCH != 3
  82339. Call UPDATE_HASH() MIN_MATCH-3 more times
  82340. #endif
  82341. }
  82342. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  82343. * but this is not important since only literal bytes will be emitted.
  82344. */
  82345. } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
  82346. }
  82347. /* ===========================================================================
  82348. * Flush the current block, with given end-of-file flag.
  82349. * IN assertion: strstart is set to the end of the current match.
  82350. */
  82351. #define FLUSH_BLOCK_ONLY(s, eof) { \
  82352. _tr_flush_block(s, (s->block_start >= 0L ? \
  82353. (charf *)&s->window[(unsigned)s->block_start] : \
  82354. (charf *)Z_NULL), \
  82355. (ulg)((long)s->strstart - s->block_start), \
  82356. (eof)); \
  82357. s->block_start = s->strstart; \
  82358. flush_pending(s->strm); \
  82359. Tracev((stderr,"[FLUSH]")); \
  82360. }
  82361. /* Same but force premature exit if necessary. */
  82362. #define FLUSH_BLOCK(s, eof) { \
  82363. FLUSH_BLOCK_ONLY(s, eof); \
  82364. if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
  82365. }
  82366. /* ===========================================================================
  82367. * Copy without compression as much as possible from the input stream, return
  82368. * the current block state.
  82369. * This function does not insert new strings in the dictionary since
  82370. * uncompressible data is probably not useful. This function is used
  82371. * only for the level=0 compression option.
  82372. * NOTE: this function should be optimized to avoid extra copying from
  82373. * window to pending_buf.
  82374. */
  82375. local block_state deflate_stored(deflate_state *s, int flush)
  82376. {
  82377. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  82378. * to pending_buf_size, and each stored block has a 5 byte header:
  82379. */
  82380. ulg max_block_size = 0xffff;
  82381. ulg max_start;
  82382. if (max_block_size > s->pending_buf_size - 5) {
  82383. max_block_size = s->pending_buf_size - 5;
  82384. }
  82385. /* Copy as much as possible from input to output: */
  82386. for (;;) {
  82387. /* Fill the window as much as possible: */
  82388. if (s->lookahead <= 1) {
  82389. Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  82390. s->block_start >= (long)s->w_size, "slide too late");
  82391. fill_window(s);
  82392. if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
  82393. if (s->lookahead == 0) break; /* flush the current block */
  82394. }
  82395. Assert(s->block_start >= 0L, "block gone");
  82396. s->strstart += s->lookahead;
  82397. s->lookahead = 0;
  82398. /* Emit a stored block if pending_buf will be full: */
  82399. max_start = s->block_start + max_block_size;
  82400. if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
  82401. /* strstart == 0 is possible when wraparound on 16-bit machine */
  82402. s->lookahead = (uInt)(s->strstart - max_start);
  82403. s->strstart = (uInt)max_start;
  82404. FLUSH_BLOCK(s, 0);
  82405. }
  82406. /* Flush if we may have to slide, otherwise block_start may become
  82407. * negative and the data will be gone:
  82408. */
  82409. if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
  82410. FLUSH_BLOCK(s, 0);
  82411. }
  82412. }
  82413. FLUSH_BLOCK(s, flush == Z_FINISH);
  82414. return flush == Z_FINISH ? finish_done : block_done;
  82415. }
  82416. /* ===========================================================================
  82417. * Compress as much as possible from the input stream, return the current
  82418. * block state.
  82419. * This function does not perform lazy evaluation of matches and inserts
  82420. * new strings in the dictionary only for unmatched strings or for short
  82421. * matches. It is used only for the fast compression options.
  82422. */
  82423. local block_state deflate_fast(deflate_state *s, int flush)
  82424. {
  82425. IPos hash_head = NIL; /* head of the hash chain */
  82426. int bflush; /* set if current block must be flushed */
  82427. for (;;) {
  82428. /* Make sure that we always have enough lookahead, except
  82429. * at the end of the input file. We need MAX_MATCH bytes
  82430. * for the next match, plus MIN_MATCH bytes to insert the
  82431. * string following the next match.
  82432. */
  82433. if (s->lookahead < MIN_LOOKAHEAD) {
  82434. fill_window(s);
  82435. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  82436. return need_more;
  82437. }
  82438. if (s->lookahead == 0) break; /* flush the current block */
  82439. }
  82440. /* Insert the string window[strstart .. strstart+2] in the
  82441. * dictionary, and set hash_head to the head of the hash chain:
  82442. */
  82443. if (s->lookahead >= MIN_MATCH) {
  82444. INSERT_STRING(s, s->strstart, hash_head);
  82445. }
  82446. /* Find the longest match, discarding those <= prev_length.
  82447. * At this point we have always match_length < MIN_MATCH
  82448. */
  82449. if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
  82450. /* To simplify the code, we prevent matches with the string
  82451. * of window index 0 (in particular we have to avoid a match
  82452. * of the string with itself at the start of the input file).
  82453. */
  82454. #ifdef FASTEST
  82455. if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) ||
  82456. (s->strategy == Z_RLE && s->strstart - hash_head == 1)) {
  82457. s->match_length = longest_match_fast (s, hash_head);
  82458. }
  82459. #else
  82460. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  82461. s->match_length = longest_match (s, hash_head);
  82462. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  82463. s->match_length = longest_match_fast (s, hash_head);
  82464. }
  82465. #endif
  82466. /* longest_match() or longest_match_fast() sets match_start */
  82467. }
  82468. if (s->match_length >= MIN_MATCH) {
  82469. check_match(s, s->strstart, s->match_start, s->match_length);
  82470. _tr_tally_dist(s, s->strstart - s->match_start,
  82471. s->match_length - MIN_MATCH, bflush);
  82472. s->lookahead -= s->match_length;
  82473. /* Insert new strings in the hash table only if the match length
  82474. * is not too large. This saves time but degrades compression.
  82475. */
  82476. #ifndef FASTEST
  82477. if (s->match_length <= s->max_insert_length &&
  82478. s->lookahead >= MIN_MATCH) {
  82479. s->match_length--; /* string at strstart already in table */
  82480. do {
  82481. s->strstart++;
  82482. INSERT_STRING(s, s->strstart, hash_head);
  82483. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  82484. * always MIN_MATCH bytes ahead.
  82485. */
  82486. } while (--s->match_length != 0);
  82487. s->strstart++;
  82488. } else
  82489. #endif
  82490. {
  82491. s->strstart += s->match_length;
  82492. s->match_length = 0;
  82493. s->ins_h = s->window[s->strstart];
  82494. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  82495. #if MIN_MATCH != 3
  82496. Call UPDATE_HASH() MIN_MATCH-3 more times
  82497. #endif
  82498. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  82499. * matter since it will be recomputed at next deflate call.
  82500. */
  82501. }
  82502. } else {
  82503. /* No match, output a literal byte */
  82504. Tracevv((stderr,"%c", s->window[s->strstart]));
  82505. _tr_tally_lit (s, s->window[s->strstart], bflush);
  82506. s->lookahead--;
  82507. s->strstart++;
  82508. }
  82509. if (bflush) FLUSH_BLOCK(s, 0);
  82510. }
  82511. FLUSH_BLOCK(s, flush == Z_FINISH);
  82512. return flush == Z_FINISH ? finish_done : block_done;
  82513. }
  82514. #ifndef FASTEST
  82515. /* ===========================================================================
  82516. * Same as above, but achieves better compression. We use a lazy
  82517. * evaluation for matches: a match is finally adopted only if there is
  82518. * no better match at the next window position.
  82519. */
  82520. local block_state deflate_slow(deflate_state *s, int flush)
  82521. {
  82522. IPos hash_head = NIL; /* head of hash chain */
  82523. int bflush; /* set if current block must be flushed */
  82524. /* Process the input block. */
  82525. for (;;) {
  82526. /* Make sure that we always have enough lookahead, except
  82527. * at the end of the input file. We need MAX_MATCH bytes
  82528. * for the next match, plus MIN_MATCH bytes to insert the
  82529. * string following the next match.
  82530. */
  82531. if (s->lookahead < MIN_LOOKAHEAD) {
  82532. fill_window(s);
  82533. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  82534. return need_more;
  82535. }
  82536. if (s->lookahead == 0) break; /* flush the current block */
  82537. }
  82538. /* Insert the string window[strstart .. strstart+2] in the
  82539. * dictionary, and set hash_head to the head of the hash chain:
  82540. */
  82541. if (s->lookahead >= MIN_MATCH) {
  82542. INSERT_STRING(s, s->strstart, hash_head);
  82543. }
  82544. /* Find the longest match, discarding those <= prev_length.
  82545. */
  82546. s->prev_length = s->match_length, s->prev_match = s->match_start;
  82547. s->match_length = MIN_MATCH-1;
  82548. if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
  82549. s->strstart - hash_head <= MAX_DIST(s)) {
  82550. /* To simplify the code, we prevent matches with the string
  82551. * of window index 0 (in particular we have to avoid a match
  82552. * of the string with itself at the start of the input file).
  82553. */
  82554. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  82555. s->match_length = longest_match (s, hash_head);
  82556. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  82557. s->match_length = longest_match_fast (s, hash_head);
  82558. }
  82559. /* longest_match() or longest_match_fast() sets match_start */
  82560. if (s->match_length <= 5 && (s->strategy == Z_FILTERED
  82561. #if TOO_FAR <= 32767
  82562. || (s->match_length == MIN_MATCH &&
  82563. s->strstart - s->match_start > TOO_FAR)
  82564. #endif
  82565. )) {
  82566. /* If prev_match is also MIN_MATCH, match_start is garbage
  82567. * but we will ignore the current match anyway.
  82568. */
  82569. s->match_length = MIN_MATCH-1;
  82570. }
  82571. }
  82572. /* If there was a match at the previous step and the current
  82573. * match is not better, output the previous match:
  82574. */
  82575. if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
  82576. uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
  82577. /* Do not insert strings in hash table beyond this. */
  82578. check_match(s, s->strstart-1, s->prev_match, s->prev_length);
  82579. _tr_tally_dist(s, s->strstart -1 - s->prev_match,
  82580. s->prev_length - MIN_MATCH, bflush);
  82581. /* Insert in hash table all strings up to the end of the match.
  82582. * strstart-1 and strstart are already inserted. If there is not
  82583. * enough lookahead, the last two strings are not inserted in
  82584. * the hash table.
  82585. */
  82586. s->lookahead -= s->prev_length-1;
  82587. s->prev_length -= 2;
  82588. do {
  82589. if (++s->strstart <= max_insert) {
  82590. INSERT_STRING(s, s->strstart, hash_head);
  82591. }
  82592. } while (--s->prev_length != 0);
  82593. s->match_available = 0;
  82594. s->match_length = MIN_MATCH-1;
  82595. s->strstart++;
  82596. if (bflush) FLUSH_BLOCK(s, 0);
  82597. } else if (s->match_available) {
  82598. /* If there was no match at the previous position, output a
  82599. * single literal. If there was a match but the current match
  82600. * is longer, truncate the previous match to a single literal.
  82601. */
  82602. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  82603. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  82604. if (bflush) {
  82605. FLUSH_BLOCK_ONLY(s, 0);
  82606. }
  82607. s->strstart++;
  82608. s->lookahead--;
  82609. if (s->strm->avail_out == 0) return need_more;
  82610. } else {
  82611. /* There is no previous match to compare with, wait for
  82612. * the next step to decide.
  82613. */
  82614. s->match_available = 1;
  82615. s->strstart++;
  82616. s->lookahead--;
  82617. }
  82618. }
  82619. Assert (flush != Z_NO_FLUSH, "no flush?");
  82620. if (s->match_available) {
  82621. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  82622. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  82623. s->match_available = 0;
  82624. }
  82625. FLUSH_BLOCK(s, flush == Z_FINISH);
  82626. return flush == Z_FINISH ? finish_done : block_done;
  82627. }
  82628. #endif /* FASTEST */
  82629. #if 0
  82630. /* ===========================================================================
  82631. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  82632. * one. Do not maintain a hash table. (It will be regenerated if this run of
  82633. * deflate switches away from Z_RLE.)
  82634. */
  82635. local block_state deflate_rle(s, flush)
  82636. deflate_state *s;
  82637. int flush;
  82638. {
  82639. int bflush; /* set if current block must be flushed */
  82640. uInt run; /* length of run */
  82641. uInt max; /* maximum length of run */
  82642. uInt prev; /* byte at distance one to match */
  82643. Bytef *scan; /* scan for end of run */
  82644. for (;;) {
  82645. /* Make sure that we always have enough lookahead, except
  82646. * at the end of the input file. We need MAX_MATCH bytes
  82647. * for the longest encodable run.
  82648. */
  82649. if (s->lookahead < MAX_MATCH) {
  82650. fill_window(s);
  82651. if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) {
  82652. return need_more;
  82653. }
  82654. if (s->lookahead == 0) break; /* flush the current block */
  82655. }
  82656. /* See how many times the previous byte repeats */
  82657. run = 0;
  82658. if (s->strstart > 0) { /* if there is a previous byte, that is */
  82659. max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH;
  82660. scan = s->window + s->strstart - 1;
  82661. prev = *scan++;
  82662. do {
  82663. if (*scan++ != prev)
  82664. break;
  82665. } while (++run < max);
  82666. }
  82667. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  82668. if (run >= MIN_MATCH) {
  82669. check_match(s, s->strstart, s->strstart - 1, run);
  82670. _tr_tally_dist(s, 1, run - MIN_MATCH, bflush);
  82671. s->lookahead -= run;
  82672. s->strstart += run;
  82673. } else {
  82674. /* No match, output a literal byte */
  82675. Tracevv((stderr,"%c", s->window[s->strstart]));
  82676. _tr_tally_lit (s, s->window[s->strstart], bflush);
  82677. s->lookahead--;
  82678. s->strstart++;
  82679. }
  82680. if (bflush) FLUSH_BLOCK(s, 0);
  82681. }
  82682. FLUSH_BLOCK(s, flush == Z_FINISH);
  82683. return flush == Z_FINISH ? finish_done : block_done;
  82684. }
  82685. #endif
  82686. /*** End of inlined file: deflate.c ***/
  82687. /*** Start of inlined file: inffast.c ***/
  82688. /*** Start of inlined file: inftrees.h ***/
  82689. /* WARNING: this file should *not* be used by applications. It is
  82690. part of the implementation of the compression library and is
  82691. subject to change. Applications should only use zlib.h.
  82692. */
  82693. #ifndef _INFTREES_H_
  82694. #define _INFTREES_H_
  82695. /* Structure for decoding tables. Each entry provides either the
  82696. information needed to do the operation requested by the code that
  82697. indexed that table entry, or it provides a pointer to another
  82698. table that indexes more bits of the code. op indicates whether
  82699. the entry is a pointer to another table, a literal, a length or
  82700. distance, an end-of-block, or an invalid code. For a table
  82701. pointer, the low four bits of op is the number of index bits of
  82702. that table. For a length or distance, the low four bits of op
  82703. is the number of extra bits to get after the code. bits is
  82704. the number of bits in this code or part of the code to drop off
  82705. of the bit buffer. val is the actual byte to output in the case
  82706. of a literal, the base length or distance, or the offset from
  82707. the current table to the next table. Each entry is four bytes. */
  82708. typedef struct {
  82709. unsigned char op; /* operation, extra bits, table bits */
  82710. unsigned char bits; /* bits in this part of the code */
  82711. unsigned short val; /* offset in table or code value */
  82712. } code;
  82713. /* op values as set by inflate_table():
  82714. 00000000 - literal
  82715. 0000tttt - table link, tttt != 0 is the number of table index bits
  82716. 0001eeee - length or distance, eeee is the number of extra bits
  82717. 01100000 - end of block
  82718. 01000000 - invalid code
  82719. */
  82720. /* Maximum size of dynamic tree. The maximum found in a long but non-
  82721. exhaustive search was 1444 code structures (852 for length/literals
  82722. and 592 for distances, the latter actually the result of an
  82723. exhaustive search). The true maximum is not known, but the value
  82724. below is more than safe. */
  82725. #define ENOUGH 2048
  82726. #define MAXD 592
  82727. /* Type of code to build for inftable() */
  82728. typedef enum {
  82729. CODES,
  82730. LENS,
  82731. DISTS
  82732. } codetype;
  82733. extern int inflate_table OF((codetype type, unsigned short FAR *lens,
  82734. unsigned codes, code FAR * FAR *table,
  82735. unsigned FAR *bits, unsigned short FAR *work));
  82736. #endif
  82737. /*** End of inlined file: inftrees.h ***/
  82738. /*** Start of inlined file: inflate.h ***/
  82739. /* WARNING: this file should *not* be used by applications. It is
  82740. part of the implementation of the compression library and is
  82741. subject to change. Applications should only use zlib.h.
  82742. */
  82743. #ifndef _INFLATE_H_
  82744. #define _INFLATE_H_
  82745. /* define NO_GZIP when compiling if you want to disable gzip header and
  82746. trailer decoding by inflate(). NO_GZIP would be used to avoid linking in
  82747. the crc code when it is not needed. For shared libraries, gzip decoding
  82748. should be left enabled. */
  82749. #ifndef NO_GZIP
  82750. # define GUNZIP
  82751. #endif
  82752. /* Possible inflate modes between inflate() calls */
  82753. typedef enum {
  82754. HEAD, /* i: waiting for magic header */
  82755. FLAGS, /* i: waiting for method and flags (gzip) */
  82756. TIME, /* i: waiting for modification time (gzip) */
  82757. OS, /* i: waiting for extra flags and operating system (gzip) */
  82758. EXLEN, /* i: waiting for extra length (gzip) */
  82759. EXTRA, /* i: waiting for extra bytes (gzip) */
  82760. NAME, /* i: waiting for end of file name (gzip) */
  82761. COMMENT, /* i: waiting for end of comment (gzip) */
  82762. HCRC, /* i: waiting for header crc (gzip) */
  82763. DICTID, /* i: waiting for dictionary check value */
  82764. DICT, /* waiting for inflateSetDictionary() call */
  82765. TYPE, /* i: waiting for type bits, including last-flag bit */
  82766. TYPEDO, /* i: same, but skip check to exit inflate on new block */
  82767. STORED, /* i: waiting for stored size (length and complement) */
  82768. COPY, /* i/o: waiting for input or output to copy stored block */
  82769. TABLE, /* i: waiting for dynamic block table lengths */
  82770. LENLENS, /* i: waiting for code length code lengths */
  82771. CODELENS, /* i: waiting for length/lit and distance code lengths */
  82772. LEN, /* i: waiting for length/lit code */
  82773. LENEXT, /* i: waiting for length extra bits */
  82774. DIST, /* i: waiting for distance code */
  82775. DISTEXT, /* i: waiting for distance extra bits */
  82776. MATCH, /* o: waiting for output space to copy string */
  82777. LIT, /* o: waiting for output space to write literal */
  82778. CHECK, /* i: waiting for 32-bit check value */
  82779. LENGTH, /* i: waiting for 32-bit length (gzip) */
  82780. DONE, /* finished check, done -- remain here until reset */
  82781. BAD, /* got a data error -- remain here until reset */
  82782. MEM, /* got an inflate() memory error -- remain here until reset */
  82783. SYNC /* looking for synchronization bytes to restart inflate() */
  82784. } inflate_mode;
  82785. /*
  82786. State transitions between above modes -
  82787. (most modes can go to the BAD or MEM mode -- not shown for clarity)
  82788. Process header:
  82789. HEAD -> (gzip) or (zlib)
  82790. (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME
  82791. NAME -> COMMENT -> HCRC -> TYPE
  82792. (zlib) -> DICTID or TYPE
  82793. DICTID -> DICT -> TYPE
  82794. Read deflate blocks:
  82795. TYPE -> STORED or TABLE or LEN or CHECK
  82796. STORED -> COPY -> TYPE
  82797. TABLE -> LENLENS -> CODELENS -> LEN
  82798. Read deflate codes:
  82799. LEN -> LENEXT or LIT or TYPE
  82800. LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
  82801. LIT -> LEN
  82802. Process trailer:
  82803. CHECK -> LENGTH -> DONE
  82804. */
  82805. /* state maintained between inflate() calls. Approximately 7K bytes. */
  82806. struct inflate_state {
  82807. inflate_mode mode; /* current inflate mode */
  82808. int last; /* true if processing last block */
  82809. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  82810. int havedict; /* true if dictionary provided */
  82811. int flags; /* gzip header method and flags (0 if zlib) */
  82812. unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */
  82813. unsigned long check; /* protected copy of check value */
  82814. unsigned long total; /* protected copy of output count */
  82815. gz_headerp head; /* where to save gzip header information */
  82816. /* sliding window */
  82817. unsigned wbits; /* log base 2 of requested window size */
  82818. unsigned wsize; /* window size or zero if not using window */
  82819. unsigned whave; /* valid bytes in the window */
  82820. unsigned write; /* window write index */
  82821. unsigned char FAR *window; /* allocated sliding window, if needed */
  82822. /* bit accumulator */
  82823. unsigned long hold; /* input bit accumulator */
  82824. unsigned bits; /* number of bits in "in" */
  82825. /* for string and stored block copying */
  82826. unsigned length; /* literal or length of data to copy */
  82827. unsigned offset; /* distance back to copy string from */
  82828. /* for table and code decoding */
  82829. unsigned extra; /* extra bits needed */
  82830. /* fixed and dynamic code tables */
  82831. code const FAR *lencode; /* starting table for length/literal codes */
  82832. code const FAR *distcode; /* starting table for distance codes */
  82833. unsigned lenbits; /* index bits for lencode */
  82834. unsigned distbits; /* index bits for distcode */
  82835. /* dynamic table building */
  82836. unsigned ncode; /* number of code length code lengths */
  82837. unsigned nlen; /* number of length code lengths */
  82838. unsigned ndist; /* number of distance code lengths */
  82839. unsigned have; /* number of code lengths in lens[] */
  82840. code FAR *next; /* next available space in codes[] */
  82841. unsigned short lens[320]; /* temporary storage for code lengths */
  82842. unsigned short work[288]; /* work area for code table building */
  82843. code codes[ENOUGH]; /* space for code tables */
  82844. };
  82845. #endif
  82846. /*** End of inlined file: inflate.h ***/
  82847. /*** Start of inlined file: inffast.h ***/
  82848. /* WARNING: this file should *not* be used by applications. It is
  82849. part of the implementation of the compression library and is
  82850. subject to change. Applications should only use zlib.h.
  82851. */
  82852. void inflate_fast OF((z_streamp strm, unsigned start));
  82853. /*** End of inlined file: inffast.h ***/
  82854. #ifndef ASMINF
  82855. /* Allow machine dependent optimization for post-increment or pre-increment.
  82856. Based on testing to date,
  82857. Pre-increment preferred for:
  82858. - PowerPC G3 (Adler)
  82859. - MIPS R5000 (Randers-Pehrson)
  82860. Post-increment preferred for:
  82861. - none
  82862. No measurable difference:
  82863. - Pentium III (Anderson)
  82864. - M68060 (Nikl)
  82865. */
  82866. #ifdef POSTINC
  82867. # define OFF 0
  82868. # define PUP(a) *(a)++
  82869. #else
  82870. # define OFF 1
  82871. # define PUP(a) *++(a)
  82872. #endif
  82873. /*
  82874. Decode literal, length, and distance codes and write out the resulting
  82875. literal and match bytes until either not enough input or output is
  82876. available, an end-of-block is encountered, or a data error is encountered.
  82877. When large enough input and output buffers are supplied to inflate(), for
  82878. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  82879. inflate execution time is spent in this routine.
  82880. Entry assumptions:
  82881. state->mode == LEN
  82882. strm->avail_in >= 6
  82883. strm->avail_out >= 258
  82884. start >= strm->avail_out
  82885. state->bits < 8
  82886. On return, state->mode is one of:
  82887. LEN -- ran out of enough output space or enough available input
  82888. TYPE -- reached end of block code, inflate() to interpret next block
  82889. BAD -- error in block data
  82890. Notes:
  82891. - The maximum input bits used by a length/distance pair is 15 bits for the
  82892. length code, 5 bits for the length extra, 15 bits for the distance code,
  82893. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  82894. Therefore if strm->avail_in >= 6, then there is enough input to avoid
  82895. checking for available input while decoding.
  82896. - The maximum bytes that a single length/distance pair can output is 258
  82897. bytes, which is the maximum length that can be coded. inflate_fast()
  82898. requires strm->avail_out >= 258 for each loop to avoid checking for
  82899. output space.
  82900. */
  82901. void inflate_fast (z_streamp strm, unsigned start)
  82902. {
  82903. struct inflate_state FAR *state;
  82904. unsigned char FAR *in; /* local strm->next_in */
  82905. unsigned char FAR *last; /* while in < last, enough input available */
  82906. unsigned char FAR *out; /* local strm->next_out */
  82907. unsigned char FAR *beg; /* inflate()'s initial strm->next_out */
  82908. unsigned char FAR *end; /* while out < end, enough space available */
  82909. #ifdef INFLATE_STRICT
  82910. unsigned dmax; /* maximum distance from zlib header */
  82911. #endif
  82912. unsigned wsize; /* window size or zero if not using window */
  82913. unsigned whave; /* valid bytes in the window */
  82914. unsigned write; /* window write index */
  82915. unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */
  82916. unsigned long hold; /* local strm->hold */
  82917. unsigned bits; /* local strm->bits */
  82918. code const FAR *lcode; /* local strm->lencode */
  82919. code const FAR *dcode; /* local strm->distcode */
  82920. unsigned lmask; /* mask for first level of length codes */
  82921. unsigned dmask; /* mask for first level of distance codes */
  82922. code thisx; /* retrieved table entry */
  82923. unsigned op; /* code bits, operation, extra bits, or */
  82924. /* window position, window bytes to copy */
  82925. unsigned len; /* match length, unused bytes */
  82926. unsigned dist; /* match distance */
  82927. unsigned char FAR *from; /* where to copy match from */
  82928. /* copy state to local variables */
  82929. state = (struct inflate_state FAR *)strm->state;
  82930. in = strm->next_in - OFF;
  82931. last = in + (strm->avail_in - 5);
  82932. out = strm->next_out - OFF;
  82933. beg = out - (start - strm->avail_out);
  82934. end = out + (strm->avail_out - 257);
  82935. #ifdef INFLATE_STRICT
  82936. dmax = state->dmax;
  82937. #endif
  82938. wsize = state->wsize;
  82939. whave = state->whave;
  82940. write = state->write;
  82941. window = state->window;
  82942. hold = state->hold;
  82943. bits = state->bits;
  82944. lcode = state->lencode;
  82945. dcode = state->distcode;
  82946. lmask = (1U << state->lenbits) - 1;
  82947. dmask = (1U << state->distbits) - 1;
  82948. /* decode literals and length/distances until end-of-block or not enough
  82949. input data or output space */
  82950. do {
  82951. if (bits < 15) {
  82952. hold += (unsigned long)(PUP(in)) << bits;
  82953. bits += 8;
  82954. hold += (unsigned long)(PUP(in)) << bits;
  82955. bits += 8;
  82956. }
  82957. thisx = lcode[hold & lmask];
  82958. dolen:
  82959. op = (unsigned)(thisx.bits);
  82960. hold >>= op;
  82961. bits -= op;
  82962. op = (unsigned)(thisx.op);
  82963. if (op == 0) { /* literal */
  82964. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  82965. "inflate: literal '%c'\n" :
  82966. "inflate: literal 0x%02x\n", thisx.val));
  82967. PUP(out) = (unsigned char)(thisx.val);
  82968. }
  82969. else if (op & 16) { /* length base */
  82970. len = (unsigned)(thisx.val);
  82971. op &= 15; /* number of extra bits */
  82972. if (op) {
  82973. if (bits < op) {
  82974. hold += (unsigned long)(PUP(in)) << bits;
  82975. bits += 8;
  82976. }
  82977. len += (unsigned)hold & ((1U << op) - 1);
  82978. hold >>= op;
  82979. bits -= op;
  82980. }
  82981. Tracevv((stderr, "inflate: length %u\n", len));
  82982. if (bits < 15) {
  82983. hold += (unsigned long)(PUP(in)) << bits;
  82984. bits += 8;
  82985. hold += (unsigned long)(PUP(in)) << bits;
  82986. bits += 8;
  82987. }
  82988. thisx = dcode[hold & dmask];
  82989. dodist:
  82990. op = (unsigned)(thisx.bits);
  82991. hold >>= op;
  82992. bits -= op;
  82993. op = (unsigned)(thisx.op);
  82994. if (op & 16) { /* distance base */
  82995. dist = (unsigned)(thisx.val);
  82996. op &= 15; /* number of extra bits */
  82997. if (bits < op) {
  82998. hold += (unsigned long)(PUP(in)) << bits;
  82999. bits += 8;
  83000. if (bits < op) {
  83001. hold += (unsigned long)(PUP(in)) << bits;
  83002. bits += 8;
  83003. }
  83004. }
  83005. dist += (unsigned)hold & ((1U << op) - 1);
  83006. #ifdef INFLATE_STRICT
  83007. if (dist > dmax) {
  83008. strm->msg = (char *)"invalid distance too far back";
  83009. state->mode = BAD;
  83010. break;
  83011. }
  83012. #endif
  83013. hold >>= op;
  83014. bits -= op;
  83015. Tracevv((stderr, "inflate: distance %u\n", dist));
  83016. op = (unsigned)(out - beg); /* max distance in output */
  83017. if (dist > op) { /* see if copy from window */
  83018. op = dist - op; /* distance back in window */
  83019. if (op > whave) {
  83020. strm->msg = (char *)"invalid distance too far back";
  83021. state->mode = BAD;
  83022. break;
  83023. }
  83024. from = window - OFF;
  83025. if (write == 0) { /* very common case */
  83026. from += wsize - op;
  83027. if (op < len) { /* some from window */
  83028. len -= op;
  83029. do {
  83030. PUP(out) = PUP(from);
  83031. } while (--op);
  83032. from = out - dist; /* rest from output */
  83033. }
  83034. }
  83035. else if (write < op) { /* wrap around window */
  83036. from += wsize + write - op;
  83037. op -= write;
  83038. if (op < len) { /* some from end of window */
  83039. len -= op;
  83040. do {
  83041. PUP(out) = PUP(from);
  83042. } while (--op);
  83043. from = window - OFF;
  83044. if (write < len) { /* some from start of window */
  83045. op = write;
  83046. len -= op;
  83047. do {
  83048. PUP(out) = PUP(from);
  83049. } while (--op);
  83050. from = out - dist; /* rest from output */
  83051. }
  83052. }
  83053. }
  83054. else { /* contiguous in window */
  83055. from += write - op;
  83056. if (op < len) { /* some from window */
  83057. len -= op;
  83058. do {
  83059. PUP(out) = PUP(from);
  83060. } while (--op);
  83061. from = out - dist; /* rest from output */
  83062. }
  83063. }
  83064. while (len > 2) {
  83065. PUP(out) = PUP(from);
  83066. PUP(out) = PUP(from);
  83067. PUP(out) = PUP(from);
  83068. len -= 3;
  83069. }
  83070. if (len) {
  83071. PUP(out) = PUP(from);
  83072. if (len > 1)
  83073. PUP(out) = PUP(from);
  83074. }
  83075. }
  83076. else {
  83077. from = out - dist; /* copy direct from output */
  83078. do { /* minimum length is three */
  83079. PUP(out) = PUP(from);
  83080. PUP(out) = PUP(from);
  83081. PUP(out) = PUP(from);
  83082. len -= 3;
  83083. } while (len > 2);
  83084. if (len) {
  83085. PUP(out) = PUP(from);
  83086. if (len > 1)
  83087. PUP(out) = PUP(from);
  83088. }
  83089. }
  83090. }
  83091. else if ((op & 64) == 0) { /* 2nd level distance code */
  83092. thisx = dcode[thisx.val + (hold & ((1U << op) - 1))];
  83093. goto dodist;
  83094. }
  83095. else {
  83096. strm->msg = (char *)"invalid distance code";
  83097. state->mode = BAD;
  83098. break;
  83099. }
  83100. }
  83101. else if ((op & 64) == 0) { /* 2nd level length code */
  83102. thisx = lcode[thisx.val + (hold & ((1U << op) - 1))];
  83103. goto dolen;
  83104. }
  83105. else if (op & 32) { /* end-of-block */
  83106. Tracevv((stderr, "inflate: end of block\n"));
  83107. state->mode = TYPE;
  83108. break;
  83109. }
  83110. else {
  83111. strm->msg = (char *)"invalid literal/length code";
  83112. state->mode = BAD;
  83113. break;
  83114. }
  83115. } while (in < last && out < end);
  83116. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  83117. len = bits >> 3;
  83118. in -= len;
  83119. bits -= len << 3;
  83120. hold &= (1U << bits) - 1;
  83121. /* update state and return */
  83122. strm->next_in = in + OFF;
  83123. strm->next_out = out + OFF;
  83124. strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));
  83125. strm->avail_out = (unsigned)(out < end ?
  83126. 257 + (end - out) : 257 - (out - end));
  83127. state->hold = hold;
  83128. state->bits = bits;
  83129. return;
  83130. }
  83131. /*
  83132. inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
  83133. - Using bit fields for code structure
  83134. - Different op definition to avoid & for extra bits (do & for table bits)
  83135. - Three separate decoding do-loops for direct, window, and write == 0
  83136. - Special case for distance > 1 copies to do overlapped load and store copy
  83137. - Explicit branch predictions (based on measured branch probabilities)
  83138. - Deferring match copy and interspersed it with decoding subsequent codes
  83139. - Swapping literal/length else
  83140. - Swapping window/direct else
  83141. - Larger unrolled copy loops (three is about right)
  83142. - Moving len -= 3 statement into middle of loop
  83143. */
  83144. #endif /* !ASMINF */
  83145. /*** End of inlined file: inffast.c ***/
  83146. #undef PULLBYTE
  83147. #undef LOAD
  83148. #undef RESTORE
  83149. #undef INITBITS
  83150. #undef NEEDBITS
  83151. #undef DROPBITS
  83152. #undef BYTEBITS
  83153. /*** Start of inlined file: inflate.c ***/
  83154. /*
  83155. * Change history:
  83156. *
  83157. * 1.2.beta0 24 Nov 2002
  83158. * - First version -- complete rewrite of inflate to simplify code, avoid
  83159. * creation of window when not needed, minimize use of window when it is
  83160. * needed, make inffast.c even faster, implement gzip decoding, and to
  83161. * improve code readability and style over the previous zlib inflate code
  83162. *
  83163. * 1.2.beta1 25 Nov 2002
  83164. * - Use pointers for available input and output checking in inffast.c
  83165. * - Remove input and output counters in inffast.c
  83166. * - Change inffast.c entry and loop from avail_in >= 7 to >= 6
  83167. * - Remove unnecessary second byte pull from length extra in inffast.c
  83168. * - Unroll direct copy to three copies per loop in inffast.c
  83169. *
  83170. * 1.2.beta2 4 Dec 2002
  83171. * - Change external routine names to reduce potential conflicts
  83172. * - Correct filename to inffixed.h for fixed tables in inflate.c
  83173. * - Make hbuf[] unsigned char to match parameter type in inflate.c
  83174. * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)
  83175. * to avoid negation problem on Alphas (64 bit) in inflate.c
  83176. *
  83177. * 1.2.beta3 22 Dec 2002
  83178. * - Add comments on state->bits assertion in inffast.c
  83179. * - Add comments on op field in inftrees.h
  83180. * - Fix bug in reuse of allocated window after inflateReset()
  83181. * - Remove bit fields--back to byte structure for speed
  83182. * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths
  83183. * - Change post-increments to pre-increments in inflate_fast(), PPC biased?
  83184. * - Add compile time option, POSTINC, to use post-increments instead (Intel?)
  83185. * - Make MATCH copy in inflate() much faster for when inflate_fast() not used
  83186. * - Use local copies of stream next and avail values, as well as local bit
  83187. * buffer and bit count in inflate()--for speed when inflate_fast() not used
  83188. *
  83189. * 1.2.beta4 1 Jan 2003
  83190. * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings
  83191. * - Move a comment on output buffer sizes from inffast.c to inflate.c
  83192. * - Add comments in inffast.c to introduce the inflate_fast() routine
  83193. * - Rearrange window copies in inflate_fast() for speed and simplification
  83194. * - Unroll last copy for window match in inflate_fast()
  83195. * - Use local copies of window variables in inflate_fast() for speed
  83196. * - Pull out common write == 0 case for speed in inflate_fast()
  83197. * - Make op and len in inflate_fast() unsigned for consistency
  83198. * - Add FAR to lcode and dcode declarations in inflate_fast()
  83199. * - Simplified bad distance check in inflate_fast()
  83200. * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new
  83201. * source file infback.c to provide a call-back interface to inflate for
  83202. * programs like gzip and unzip -- uses window as output buffer to avoid
  83203. * window copying
  83204. *
  83205. * 1.2.beta5 1 Jan 2003
  83206. * - Improved inflateBack() interface to allow the caller to provide initial
  83207. * input in strm.
  83208. * - Fixed stored blocks bug in inflateBack()
  83209. *
  83210. * 1.2.beta6 4 Jan 2003
  83211. * - Added comments in inffast.c on effectiveness of POSTINC
  83212. * - Typecasting all around to reduce compiler warnings
  83213. * - Changed loops from while (1) or do {} while (1) to for (;;), again to
  83214. * make compilers happy
  83215. * - Changed type of window in inflateBackInit() to unsigned char *
  83216. *
  83217. * 1.2.beta7 27 Jan 2003
  83218. * - Changed many types to unsigned or unsigned short to avoid warnings
  83219. * - Added inflateCopy() function
  83220. *
  83221. * 1.2.0 9 Mar 2003
  83222. * - Changed inflateBack() interface to provide separate opaque descriptors
  83223. * for the in() and out() functions
  83224. * - Changed inflateBack() argument and in_func typedef to swap the length
  83225. * and buffer address return values for the input function
  83226. * - Check next_in and next_out for Z_NULL on entry to inflate()
  83227. *
  83228. * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.
  83229. */
  83230. /*** Start of inlined file: inffast.h ***/
  83231. /* WARNING: this file should *not* be used by applications. It is
  83232. part of the implementation of the compression library and is
  83233. subject to change. Applications should only use zlib.h.
  83234. */
  83235. void inflate_fast OF((z_streamp strm, unsigned start));
  83236. /*** End of inlined file: inffast.h ***/
  83237. #ifdef MAKEFIXED
  83238. # ifndef BUILDFIXED
  83239. # define BUILDFIXED
  83240. # endif
  83241. #endif
  83242. /* function prototypes */
  83243. local void fixedtables OF((struct inflate_state FAR *state));
  83244. local int updatewindow OF((z_streamp strm, unsigned out));
  83245. #ifdef BUILDFIXED
  83246. void makefixed OF((void));
  83247. #endif
  83248. local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf,
  83249. unsigned len));
  83250. int ZEXPORT inflateReset (z_streamp strm)
  83251. {
  83252. struct inflate_state FAR *state;
  83253. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83254. state = (struct inflate_state FAR *)strm->state;
  83255. strm->total_in = strm->total_out = state->total = 0;
  83256. strm->msg = Z_NULL;
  83257. strm->adler = 1; /* to support ill-conceived Java test suite */
  83258. state->mode = HEAD;
  83259. state->last = 0;
  83260. state->havedict = 0;
  83261. state->dmax = 32768U;
  83262. state->head = Z_NULL;
  83263. state->wsize = 0;
  83264. state->whave = 0;
  83265. state->write = 0;
  83266. state->hold = 0;
  83267. state->bits = 0;
  83268. state->lencode = state->distcode = state->next = state->codes;
  83269. Tracev((stderr, "inflate: reset\n"));
  83270. return Z_OK;
  83271. }
  83272. int ZEXPORT inflatePrime (z_streamp strm, int bits, int value)
  83273. {
  83274. struct inflate_state FAR *state;
  83275. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83276. state = (struct inflate_state FAR *)strm->state;
  83277. if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
  83278. value &= (1L << bits) - 1;
  83279. state->hold += value << state->bits;
  83280. state->bits += bits;
  83281. return Z_OK;
  83282. }
  83283. int ZEXPORT inflateInit2_(z_streamp strm, int windowBits, const char *version, int stream_size)
  83284. {
  83285. struct inflate_state FAR *state;
  83286. if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
  83287. stream_size != (int)(sizeof(z_stream)))
  83288. return Z_VERSION_ERROR;
  83289. if (strm == Z_NULL) return Z_STREAM_ERROR;
  83290. strm->msg = Z_NULL; /* in case we return an error */
  83291. if (strm->zalloc == (alloc_func)0) {
  83292. strm->zalloc = zcalloc;
  83293. strm->opaque = (voidpf)0;
  83294. }
  83295. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  83296. state = (struct inflate_state FAR *)
  83297. ZALLOC(strm, 1, sizeof(struct inflate_state));
  83298. if (state == Z_NULL) return Z_MEM_ERROR;
  83299. Tracev((stderr, "inflate: allocated\n"));
  83300. strm->state = (struct internal_state FAR *)state;
  83301. if (windowBits < 0) {
  83302. state->wrap = 0;
  83303. windowBits = -windowBits;
  83304. }
  83305. else {
  83306. state->wrap = (windowBits >> 4) + 1;
  83307. #ifdef GUNZIP
  83308. if (windowBits < 48) windowBits &= 15;
  83309. #endif
  83310. }
  83311. if (windowBits < 8 || windowBits > 15) {
  83312. ZFREE(strm, state);
  83313. strm->state = Z_NULL;
  83314. return Z_STREAM_ERROR;
  83315. }
  83316. state->wbits = (unsigned)windowBits;
  83317. state->window = Z_NULL;
  83318. return inflateReset(strm);
  83319. }
  83320. int ZEXPORT inflateInit_ (z_streamp strm, const char *version, int stream_size)
  83321. {
  83322. return inflateInit2_(strm, DEF_WBITS, version, stream_size);
  83323. }
  83324. /*
  83325. Return state with length and distance decoding tables and index sizes set to
  83326. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  83327. If BUILDFIXED is defined, then instead this routine builds the tables the
  83328. first time it's called, and returns those tables the first time and
  83329. thereafter. This reduces the size of the code by about 2K bytes, in
  83330. exchange for a little execution time. However, BUILDFIXED should not be
  83331. used for threaded applications, since the rewriting of the tables and virgin
  83332. may not be thread-safe.
  83333. */
  83334. local void fixedtables (struct inflate_state FAR *state)
  83335. {
  83336. #ifdef BUILDFIXED
  83337. static int virgin = 1;
  83338. static code *lenfix, *distfix;
  83339. static code fixed[544];
  83340. /* build fixed huffman tables if first call (may not be thread safe) */
  83341. if (virgin) {
  83342. unsigned sym, bits;
  83343. static code *next;
  83344. /* literal/length table */
  83345. sym = 0;
  83346. while (sym < 144) state->lens[sym++] = 8;
  83347. while (sym < 256) state->lens[sym++] = 9;
  83348. while (sym < 280) state->lens[sym++] = 7;
  83349. while (sym < 288) state->lens[sym++] = 8;
  83350. next = fixed;
  83351. lenfix = next;
  83352. bits = 9;
  83353. inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
  83354. /* distance table */
  83355. sym = 0;
  83356. while (sym < 32) state->lens[sym++] = 5;
  83357. distfix = next;
  83358. bits = 5;
  83359. inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
  83360. /* do this just once */
  83361. virgin = 0;
  83362. }
  83363. #else /* !BUILDFIXED */
  83364. /*** Start of inlined file: inffixed.h ***/
  83365. /* WARNING: this file should *not* be used by applications. It
  83366. is part of the implementation of the compression library and
  83367. is subject to change. Applications should only use zlib.h.
  83368. */
  83369. static const code lenfix[512] = {
  83370. {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
  83371. {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
  83372. {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
  83373. {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
  83374. {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
  83375. {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
  83376. {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
  83377. {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
  83378. {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
  83379. {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
  83380. {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
  83381. {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
  83382. {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
  83383. {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
  83384. {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
  83385. {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
  83386. {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
  83387. {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
  83388. {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
  83389. {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
  83390. {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
  83391. {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
  83392. {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
  83393. {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
  83394. {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
  83395. {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
  83396. {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
  83397. {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
  83398. {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
  83399. {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
  83400. {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
  83401. {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
  83402. {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
  83403. {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
  83404. {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
  83405. {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
  83406. {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
  83407. {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
  83408. {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
  83409. {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
  83410. {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
  83411. {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
  83412. {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
  83413. {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
  83414. {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
  83415. {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
  83416. {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
  83417. {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
  83418. {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
  83419. {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
  83420. {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
  83421. {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
  83422. {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
  83423. {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
  83424. {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
  83425. {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
  83426. {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
  83427. {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
  83428. {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
  83429. {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
  83430. {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
  83431. {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
  83432. {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
  83433. {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
  83434. {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
  83435. {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
  83436. {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
  83437. {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
  83438. {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
  83439. {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
  83440. {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
  83441. {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
  83442. {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
  83443. {0,9,255}
  83444. };
  83445. static const code distfix[32] = {
  83446. {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
  83447. {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
  83448. {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
  83449. {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
  83450. {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
  83451. {22,5,193},{64,5,0}
  83452. };
  83453. /*** End of inlined file: inffixed.h ***/
  83454. #endif /* BUILDFIXED */
  83455. state->lencode = lenfix;
  83456. state->lenbits = 9;
  83457. state->distcode = distfix;
  83458. state->distbits = 5;
  83459. }
  83460. #ifdef MAKEFIXED
  83461. #include <stdio.h>
  83462. /*
  83463. Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also
  83464. defines BUILDFIXED, so the tables are built on the fly. makefixed() writes
  83465. those tables to stdout, which would be piped to inffixed.h. A small program
  83466. can simply call makefixed to do this:
  83467. void makefixed(void);
  83468. int main(void)
  83469. {
  83470. makefixed();
  83471. return 0;
  83472. }
  83473. Then that can be linked with zlib built with MAKEFIXED defined and run:
  83474. a.out > inffixed.h
  83475. */
  83476. void makefixed()
  83477. {
  83478. unsigned low, size;
  83479. struct inflate_state state;
  83480. fixedtables(&state);
  83481. puts(" /* inffixed.h -- table for decoding fixed codes");
  83482. puts(" * Generated automatically by makefixed().");
  83483. puts(" */");
  83484. puts("");
  83485. puts(" /* WARNING: this file should *not* be used by applications.");
  83486. puts(" It is part of the implementation of this library and is");
  83487. puts(" subject to change. Applications should only use zlib.h.");
  83488. puts(" */");
  83489. puts("");
  83490. size = 1U << 9;
  83491. printf(" static const code lenfix[%u] = {", size);
  83492. low = 0;
  83493. for (;;) {
  83494. if ((low % 7) == 0) printf("\n ");
  83495. printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits,
  83496. state.lencode[low].val);
  83497. if (++low == size) break;
  83498. putchar(',');
  83499. }
  83500. puts("\n };");
  83501. size = 1U << 5;
  83502. printf("\n static const code distfix[%u] = {", size);
  83503. low = 0;
  83504. for (;;) {
  83505. if ((low % 6) == 0) printf("\n ");
  83506. printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
  83507. state.distcode[low].val);
  83508. if (++low == size) break;
  83509. putchar(',');
  83510. }
  83511. puts("\n };");
  83512. }
  83513. #endif /* MAKEFIXED */
  83514. /*
  83515. Update the window with the last wsize (normally 32K) bytes written before
  83516. returning. If window does not exist yet, create it. This is only called
  83517. when a window is already in use, or when output has been written during this
  83518. inflate call, but the end of the deflate stream has not been reached yet.
  83519. It is also called to create a window for dictionary data when a dictionary
  83520. is loaded.
  83521. Providing output buffers larger than 32K to inflate() should provide a speed
  83522. advantage, since only the last 32K of output is copied to the sliding window
  83523. upon return from inflate(), and since all distances after the first 32K of
  83524. output will fall in the output data, making match copies simpler and faster.
  83525. The advantage may be dependent on the size of the processor's data caches.
  83526. */
  83527. local int updatewindow (z_streamp strm, unsigned out)
  83528. {
  83529. struct inflate_state FAR *state;
  83530. unsigned copy, dist;
  83531. state = (struct inflate_state FAR *)strm->state;
  83532. /* if it hasn't been done already, allocate space for the window */
  83533. if (state->window == Z_NULL) {
  83534. state->window = (unsigned char FAR *)
  83535. ZALLOC(strm, 1U << state->wbits,
  83536. sizeof(unsigned char));
  83537. if (state->window == Z_NULL) return 1;
  83538. }
  83539. /* if window not in use yet, initialize */
  83540. if (state->wsize == 0) {
  83541. state->wsize = 1U << state->wbits;
  83542. state->write = 0;
  83543. state->whave = 0;
  83544. }
  83545. /* copy state->wsize or less output bytes into the circular window */
  83546. copy = out - strm->avail_out;
  83547. if (copy >= state->wsize) {
  83548. zmemcpy(state->window, strm->next_out - state->wsize, state->wsize);
  83549. state->write = 0;
  83550. state->whave = state->wsize;
  83551. }
  83552. else {
  83553. dist = state->wsize - state->write;
  83554. if (dist > copy) dist = copy;
  83555. zmemcpy(state->window + state->write, strm->next_out - copy, dist);
  83556. copy -= dist;
  83557. if (copy) {
  83558. zmemcpy(state->window, strm->next_out - copy, copy);
  83559. state->write = copy;
  83560. state->whave = state->wsize;
  83561. }
  83562. else {
  83563. state->write += dist;
  83564. if (state->write == state->wsize) state->write = 0;
  83565. if (state->whave < state->wsize) state->whave += dist;
  83566. }
  83567. }
  83568. return 0;
  83569. }
  83570. /* Macros for inflate(): */
  83571. /* check function to use adler32() for zlib or crc32() for gzip */
  83572. #ifdef GUNZIP
  83573. # define UPDATE(check, buf, len) \
  83574. (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
  83575. #else
  83576. # define UPDATE(check, buf, len) adler32(check, buf, len)
  83577. #endif
  83578. /* check macros for header crc */
  83579. #ifdef GUNZIP
  83580. # define CRC2(check, word) \
  83581. do { \
  83582. hbuf[0] = (unsigned char)(word); \
  83583. hbuf[1] = (unsigned char)((word) >> 8); \
  83584. check = crc32(check, hbuf, 2); \
  83585. } while (0)
  83586. # define CRC4(check, word) \
  83587. do { \
  83588. hbuf[0] = (unsigned char)(word); \
  83589. hbuf[1] = (unsigned char)((word) >> 8); \
  83590. hbuf[2] = (unsigned char)((word) >> 16); \
  83591. hbuf[3] = (unsigned char)((word) >> 24); \
  83592. check = crc32(check, hbuf, 4); \
  83593. } while (0)
  83594. #endif
  83595. /* Load registers with state in inflate() for speed */
  83596. #define LOAD() \
  83597. do { \
  83598. put = strm->next_out; \
  83599. left = strm->avail_out; \
  83600. next = strm->next_in; \
  83601. have = strm->avail_in; \
  83602. hold = state->hold; \
  83603. bits = state->bits; \
  83604. } while (0)
  83605. /* Restore state from registers in inflate() */
  83606. #define RESTORE() \
  83607. do { \
  83608. strm->next_out = put; \
  83609. strm->avail_out = left; \
  83610. strm->next_in = next; \
  83611. strm->avail_in = have; \
  83612. state->hold = hold; \
  83613. state->bits = bits; \
  83614. } while (0)
  83615. /* Clear the input bit accumulator */
  83616. #define INITBITS() \
  83617. do { \
  83618. hold = 0; \
  83619. bits = 0; \
  83620. } while (0)
  83621. /* Get a byte of input into the bit accumulator, or return from inflate()
  83622. if there is no input available. */
  83623. #define PULLBYTE() \
  83624. do { \
  83625. if (have == 0) goto inf_leave; \
  83626. have--; \
  83627. hold += (unsigned long)(*next++) << bits; \
  83628. bits += 8; \
  83629. } while (0)
  83630. /* Assure that there are at least n bits in the bit accumulator. If there is
  83631. not enough available input to do that, then return from inflate(). */
  83632. #define NEEDBITS(n) \
  83633. do { \
  83634. while (bits < (unsigned)(n)) \
  83635. PULLBYTE(); \
  83636. } while (0)
  83637. /* Return the low n bits of the bit accumulator (n < 16) */
  83638. #define BITS(n) \
  83639. ((unsigned)hold & ((1U << (n)) - 1))
  83640. /* Remove n bits from the bit accumulator */
  83641. #define DROPBITS(n) \
  83642. do { \
  83643. hold >>= (n); \
  83644. bits -= (unsigned)(n); \
  83645. } while (0)
  83646. /* Remove zero to seven bits as needed to go to a byte boundary */
  83647. #define BYTEBITS() \
  83648. do { \
  83649. hold >>= bits & 7; \
  83650. bits -= bits & 7; \
  83651. } while (0)
  83652. /* Reverse the bytes in a 32-bit value */
  83653. #define REVERSE(q) \
  83654. ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
  83655. (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
  83656. /*
  83657. inflate() uses a state machine to process as much input data and generate as
  83658. much output data as possible before returning. The state machine is
  83659. structured roughly as follows:
  83660. for (;;) switch (state) {
  83661. ...
  83662. case STATEn:
  83663. if (not enough input data or output space to make progress)
  83664. return;
  83665. ... make progress ...
  83666. state = STATEm;
  83667. break;
  83668. ...
  83669. }
  83670. so when inflate() is called again, the same case is attempted again, and
  83671. if the appropriate resources are provided, the machine proceeds to the
  83672. next state. The NEEDBITS() macro is usually the way the state evaluates
  83673. whether it can proceed or should return. NEEDBITS() does the return if
  83674. the requested bits are not available. The typical use of the BITS macros
  83675. is:
  83676. NEEDBITS(n);
  83677. ... do something with BITS(n) ...
  83678. DROPBITS(n);
  83679. where NEEDBITS(n) either returns from inflate() if there isn't enough
  83680. input left to load n bits into the accumulator, or it continues. BITS(n)
  83681. gives the low n bits in the accumulator. When done, DROPBITS(n) drops
  83682. the low n bits off the accumulator. INITBITS() clears the accumulator
  83683. and sets the number of available bits to zero. BYTEBITS() discards just
  83684. enough bits to put the accumulator on a byte boundary. After BYTEBITS()
  83685. and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
  83686. NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
  83687. if there is no input available. The decoding of variable length codes uses
  83688. PULLBYTE() directly in order to pull just enough bytes to decode the next
  83689. code, and no more.
  83690. Some states loop until they get enough input, making sure that enough
  83691. state information is maintained to continue the loop where it left off
  83692. if NEEDBITS() returns in the loop. For example, want, need, and keep
  83693. would all have to actually be part of the saved state in case NEEDBITS()
  83694. returns:
  83695. case STATEw:
  83696. while (want < need) {
  83697. NEEDBITS(n);
  83698. keep[want++] = BITS(n);
  83699. DROPBITS(n);
  83700. }
  83701. state = STATEx;
  83702. case STATEx:
  83703. As shown above, if the next state is also the next case, then the break
  83704. is omitted.
  83705. A state may also return if there is not enough output space available to
  83706. complete that state. Those states are copying stored data, writing a
  83707. literal byte, and copying a matching string.
  83708. When returning, a "goto inf_leave" is used to update the total counters,
  83709. update the check value, and determine whether any progress has been made
  83710. during that inflate() call in order to return the proper return code.
  83711. Progress is defined as a change in either strm->avail_in or strm->avail_out.
  83712. When there is a window, goto inf_leave will update the window with the last
  83713. output written. If a goto inf_leave occurs in the middle of decompression
  83714. and there is no window currently, goto inf_leave will create one and copy
  83715. output to the window for the next call of inflate().
  83716. In this implementation, the flush parameter of inflate() only affects the
  83717. return code (per zlib.h). inflate() always writes as much as possible to
  83718. strm->next_out, given the space available and the provided input--the effect
  83719. documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers
  83720. the allocation of and copying into a sliding window until necessary, which
  83721. provides the effect documented in zlib.h for Z_FINISH when the entire input
  83722. stream available. So the only thing the flush parameter actually does is:
  83723. when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it
  83724. will return Z_BUF_ERROR if it has not reached the end of the stream.
  83725. */
  83726. int ZEXPORT inflate (z_streamp strm, int flush)
  83727. {
  83728. struct inflate_state FAR *state;
  83729. unsigned char FAR *next; /* next input */
  83730. unsigned char FAR *put; /* next output */
  83731. unsigned have, left; /* available input and output */
  83732. unsigned long hold; /* bit buffer */
  83733. unsigned bits; /* bits in bit buffer */
  83734. unsigned in, out; /* save starting available input and output */
  83735. unsigned copy; /* number of stored or match bytes to copy */
  83736. unsigned char FAR *from; /* where to copy match bytes from */
  83737. code thisx; /* current decoding table entry */
  83738. code last; /* parent table entry */
  83739. unsigned len; /* length to copy for repeats, bits to drop */
  83740. int ret; /* return code */
  83741. #ifdef GUNZIP
  83742. unsigned char hbuf[4]; /* buffer for gzip header crc calculation */
  83743. #endif
  83744. static const unsigned short order[19] = /* permutation of code lengths */
  83745. {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  83746. if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL ||
  83747. (strm->next_in == Z_NULL && strm->avail_in != 0))
  83748. return Z_STREAM_ERROR;
  83749. state = (struct inflate_state FAR *)strm->state;
  83750. if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */
  83751. LOAD();
  83752. in = have;
  83753. out = left;
  83754. ret = Z_OK;
  83755. for (;;)
  83756. switch (state->mode) {
  83757. case HEAD:
  83758. if (state->wrap == 0) {
  83759. state->mode = TYPEDO;
  83760. break;
  83761. }
  83762. NEEDBITS(16);
  83763. #ifdef GUNZIP
  83764. if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */
  83765. state->check = crc32(0L, Z_NULL, 0);
  83766. CRC2(state->check, hold);
  83767. INITBITS();
  83768. state->mode = FLAGS;
  83769. break;
  83770. }
  83771. state->flags = 0; /* expect zlib header */
  83772. if (state->head != Z_NULL)
  83773. state->head->done = -1;
  83774. if (!(state->wrap & 1) || /* check if zlib header allowed */
  83775. #else
  83776. if (
  83777. #endif
  83778. ((BITS(8) << 8) + (hold >> 8)) % 31) {
  83779. strm->msg = (char *)"incorrect header check";
  83780. state->mode = BAD;
  83781. break;
  83782. }
  83783. if (BITS(4) != Z_DEFLATED) {
  83784. strm->msg = (char *)"unknown compression method";
  83785. state->mode = BAD;
  83786. break;
  83787. }
  83788. DROPBITS(4);
  83789. len = BITS(4) + 8;
  83790. if (len > state->wbits) {
  83791. strm->msg = (char *)"invalid window size";
  83792. state->mode = BAD;
  83793. break;
  83794. }
  83795. state->dmax = 1U << len;
  83796. Tracev((stderr, "inflate: zlib header ok\n"));
  83797. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  83798. state->mode = hold & 0x200 ? DICTID : TYPE;
  83799. INITBITS();
  83800. break;
  83801. #ifdef GUNZIP
  83802. case FLAGS:
  83803. NEEDBITS(16);
  83804. state->flags = (int)(hold);
  83805. if ((state->flags & 0xff) != Z_DEFLATED) {
  83806. strm->msg = (char *)"unknown compression method";
  83807. state->mode = BAD;
  83808. break;
  83809. }
  83810. if (state->flags & 0xe000) {
  83811. strm->msg = (char *)"unknown header flags set";
  83812. state->mode = BAD;
  83813. break;
  83814. }
  83815. if (state->head != Z_NULL)
  83816. state->head->text = (int)((hold >> 8) & 1);
  83817. if (state->flags & 0x0200) CRC2(state->check, hold);
  83818. INITBITS();
  83819. state->mode = TIME;
  83820. case TIME:
  83821. NEEDBITS(32);
  83822. if (state->head != Z_NULL)
  83823. state->head->time = hold;
  83824. if (state->flags & 0x0200) CRC4(state->check, hold);
  83825. INITBITS();
  83826. state->mode = OS;
  83827. case OS:
  83828. NEEDBITS(16);
  83829. if (state->head != Z_NULL) {
  83830. state->head->xflags = (int)(hold & 0xff);
  83831. state->head->os = (int)(hold >> 8);
  83832. }
  83833. if (state->flags & 0x0200) CRC2(state->check, hold);
  83834. INITBITS();
  83835. state->mode = EXLEN;
  83836. case EXLEN:
  83837. if (state->flags & 0x0400) {
  83838. NEEDBITS(16);
  83839. state->length = (unsigned)(hold);
  83840. if (state->head != Z_NULL)
  83841. state->head->extra_len = (unsigned)hold;
  83842. if (state->flags & 0x0200) CRC2(state->check, hold);
  83843. INITBITS();
  83844. }
  83845. else if (state->head != Z_NULL)
  83846. state->head->extra = Z_NULL;
  83847. state->mode = EXTRA;
  83848. case EXTRA:
  83849. if (state->flags & 0x0400) {
  83850. copy = state->length;
  83851. if (copy > have) copy = have;
  83852. if (copy) {
  83853. if (state->head != Z_NULL &&
  83854. state->head->extra != Z_NULL) {
  83855. len = state->head->extra_len - state->length;
  83856. zmemcpy(state->head->extra + len, next,
  83857. len + copy > state->head->extra_max ?
  83858. state->head->extra_max - len : copy);
  83859. }
  83860. if (state->flags & 0x0200)
  83861. state->check = crc32(state->check, next, copy);
  83862. have -= copy;
  83863. next += copy;
  83864. state->length -= copy;
  83865. }
  83866. if (state->length) goto inf_leave;
  83867. }
  83868. state->length = 0;
  83869. state->mode = NAME;
  83870. case NAME:
  83871. if (state->flags & 0x0800) {
  83872. if (have == 0) goto inf_leave;
  83873. copy = 0;
  83874. do {
  83875. len = (unsigned)(next[copy++]);
  83876. if (state->head != Z_NULL &&
  83877. state->head->name != Z_NULL &&
  83878. state->length < state->head->name_max)
  83879. state->head->name[state->length++] = len;
  83880. } while (len && copy < have);
  83881. if (state->flags & 0x0200)
  83882. state->check = crc32(state->check, next, copy);
  83883. have -= copy;
  83884. next += copy;
  83885. if (len) goto inf_leave;
  83886. }
  83887. else if (state->head != Z_NULL)
  83888. state->head->name = Z_NULL;
  83889. state->length = 0;
  83890. state->mode = COMMENT;
  83891. case COMMENT:
  83892. if (state->flags & 0x1000) {
  83893. if (have == 0) goto inf_leave;
  83894. copy = 0;
  83895. do {
  83896. len = (unsigned)(next[copy++]);
  83897. if (state->head != Z_NULL &&
  83898. state->head->comment != Z_NULL &&
  83899. state->length < state->head->comm_max)
  83900. state->head->comment[state->length++] = len;
  83901. } while (len && copy < have);
  83902. if (state->flags & 0x0200)
  83903. state->check = crc32(state->check, next, copy);
  83904. have -= copy;
  83905. next += copy;
  83906. if (len) goto inf_leave;
  83907. }
  83908. else if (state->head != Z_NULL)
  83909. state->head->comment = Z_NULL;
  83910. state->mode = HCRC;
  83911. case HCRC:
  83912. if (state->flags & 0x0200) {
  83913. NEEDBITS(16);
  83914. if (hold != (state->check & 0xffff)) {
  83915. strm->msg = (char *)"header crc mismatch";
  83916. state->mode = BAD;
  83917. break;
  83918. }
  83919. INITBITS();
  83920. }
  83921. if (state->head != Z_NULL) {
  83922. state->head->hcrc = (int)((state->flags >> 9) & 1);
  83923. state->head->done = 1;
  83924. }
  83925. strm->adler = state->check = crc32(0L, Z_NULL, 0);
  83926. state->mode = TYPE;
  83927. break;
  83928. #endif
  83929. case DICTID:
  83930. NEEDBITS(32);
  83931. strm->adler = state->check = REVERSE(hold);
  83932. INITBITS();
  83933. state->mode = DICT;
  83934. case DICT:
  83935. if (state->havedict == 0) {
  83936. RESTORE();
  83937. return Z_NEED_DICT;
  83938. }
  83939. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  83940. state->mode = TYPE;
  83941. case TYPE:
  83942. if (flush == Z_BLOCK) goto inf_leave;
  83943. case TYPEDO:
  83944. if (state->last) {
  83945. BYTEBITS();
  83946. state->mode = CHECK;
  83947. break;
  83948. }
  83949. NEEDBITS(3);
  83950. state->last = BITS(1);
  83951. DROPBITS(1);
  83952. switch (BITS(2)) {
  83953. case 0: /* stored block */
  83954. Tracev((stderr, "inflate: stored block%s\n",
  83955. state->last ? " (last)" : ""));
  83956. state->mode = STORED;
  83957. break;
  83958. case 1: /* fixed block */
  83959. fixedtables(state);
  83960. Tracev((stderr, "inflate: fixed codes block%s\n",
  83961. state->last ? " (last)" : ""));
  83962. state->mode = LEN; /* decode codes */
  83963. break;
  83964. case 2: /* dynamic block */
  83965. Tracev((stderr, "inflate: dynamic codes block%s\n",
  83966. state->last ? " (last)" : ""));
  83967. state->mode = TABLE;
  83968. break;
  83969. case 3:
  83970. strm->msg = (char *)"invalid block type";
  83971. state->mode = BAD;
  83972. }
  83973. DROPBITS(2);
  83974. break;
  83975. case STORED:
  83976. BYTEBITS(); /* go to byte boundary */
  83977. NEEDBITS(32);
  83978. if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
  83979. strm->msg = (char *)"invalid stored block lengths";
  83980. state->mode = BAD;
  83981. break;
  83982. }
  83983. state->length = (unsigned)hold & 0xffff;
  83984. Tracev((stderr, "inflate: stored length %u\n",
  83985. state->length));
  83986. INITBITS();
  83987. state->mode = COPY;
  83988. case COPY:
  83989. copy = state->length;
  83990. if (copy) {
  83991. if (copy > have) copy = have;
  83992. if (copy > left) copy = left;
  83993. if (copy == 0) goto inf_leave;
  83994. zmemcpy(put, next, copy);
  83995. have -= copy;
  83996. next += copy;
  83997. left -= copy;
  83998. put += copy;
  83999. state->length -= copy;
  84000. break;
  84001. }
  84002. Tracev((stderr, "inflate: stored end\n"));
  84003. state->mode = TYPE;
  84004. break;
  84005. case TABLE:
  84006. NEEDBITS(14);
  84007. state->nlen = BITS(5) + 257;
  84008. DROPBITS(5);
  84009. state->ndist = BITS(5) + 1;
  84010. DROPBITS(5);
  84011. state->ncode = BITS(4) + 4;
  84012. DROPBITS(4);
  84013. #ifndef PKZIP_BUG_WORKAROUND
  84014. if (state->nlen > 286 || state->ndist > 30) {
  84015. strm->msg = (char *)"too many length or distance symbols";
  84016. state->mode = BAD;
  84017. break;
  84018. }
  84019. #endif
  84020. Tracev((stderr, "inflate: table sizes ok\n"));
  84021. state->have = 0;
  84022. state->mode = LENLENS;
  84023. case LENLENS:
  84024. while (state->have < state->ncode) {
  84025. NEEDBITS(3);
  84026. state->lens[order[state->have++]] = (unsigned short)BITS(3);
  84027. DROPBITS(3);
  84028. }
  84029. while (state->have < 19)
  84030. state->lens[order[state->have++]] = 0;
  84031. state->next = state->codes;
  84032. state->lencode = (code const FAR *)(state->next);
  84033. state->lenbits = 7;
  84034. ret = inflate_table(CODES, state->lens, 19, &(state->next),
  84035. &(state->lenbits), state->work);
  84036. if (ret) {
  84037. strm->msg = (char *)"invalid code lengths set";
  84038. state->mode = BAD;
  84039. break;
  84040. }
  84041. Tracev((stderr, "inflate: code lengths ok\n"));
  84042. state->have = 0;
  84043. state->mode = CODELENS;
  84044. case CODELENS:
  84045. while (state->have < state->nlen + state->ndist) {
  84046. for (;;) {
  84047. thisx = state->lencode[BITS(state->lenbits)];
  84048. if ((unsigned)(thisx.bits) <= bits) break;
  84049. PULLBYTE();
  84050. }
  84051. if (thisx.val < 16) {
  84052. NEEDBITS(thisx.bits);
  84053. DROPBITS(thisx.bits);
  84054. state->lens[state->have++] = thisx.val;
  84055. }
  84056. else {
  84057. if (thisx.val == 16) {
  84058. NEEDBITS(thisx.bits + 2);
  84059. DROPBITS(thisx.bits);
  84060. if (state->have == 0) {
  84061. strm->msg = (char *)"invalid bit length repeat";
  84062. state->mode = BAD;
  84063. break;
  84064. }
  84065. len = state->lens[state->have - 1];
  84066. copy = 3 + BITS(2);
  84067. DROPBITS(2);
  84068. }
  84069. else if (thisx.val == 17) {
  84070. NEEDBITS(thisx.bits + 3);
  84071. DROPBITS(thisx.bits);
  84072. len = 0;
  84073. copy = 3 + BITS(3);
  84074. DROPBITS(3);
  84075. }
  84076. else {
  84077. NEEDBITS(thisx.bits + 7);
  84078. DROPBITS(thisx.bits);
  84079. len = 0;
  84080. copy = 11 + BITS(7);
  84081. DROPBITS(7);
  84082. }
  84083. if (state->have + copy > state->nlen + state->ndist) {
  84084. strm->msg = (char *)"invalid bit length repeat";
  84085. state->mode = BAD;
  84086. break;
  84087. }
  84088. while (copy--)
  84089. state->lens[state->have++] = (unsigned short)len;
  84090. }
  84091. }
  84092. /* handle error breaks in while */
  84093. if (state->mode == BAD) break;
  84094. /* build code tables */
  84095. state->next = state->codes;
  84096. state->lencode = (code const FAR *)(state->next);
  84097. state->lenbits = 9;
  84098. ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
  84099. &(state->lenbits), state->work);
  84100. if (ret) {
  84101. strm->msg = (char *)"invalid literal/lengths set";
  84102. state->mode = BAD;
  84103. break;
  84104. }
  84105. state->distcode = (code const FAR *)(state->next);
  84106. state->distbits = 6;
  84107. ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
  84108. &(state->next), &(state->distbits), state->work);
  84109. if (ret) {
  84110. strm->msg = (char *)"invalid distances set";
  84111. state->mode = BAD;
  84112. break;
  84113. }
  84114. Tracev((stderr, "inflate: codes ok\n"));
  84115. state->mode = LEN;
  84116. case LEN:
  84117. if (have >= 6 && left >= 258) {
  84118. RESTORE();
  84119. inflate_fast(strm, out);
  84120. LOAD();
  84121. break;
  84122. }
  84123. for (;;) {
  84124. thisx = state->lencode[BITS(state->lenbits)];
  84125. if ((unsigned)(thisx.bits) <= bits) break;
  84126. PULLBYTE();
  84127. }
  84128. if (thisx.op && (thisx.op & 0xf0) == 0) {
  84129. last = thisx;
  84130. for (;;) {
  84131. thisx = state->lencode[last.val +
  84132. (BITS(last.bits + last.op) >> last.bits)];
  84133. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  84134. PULLBYTE();
  84135. }
  84136. DROPBITS(last.bits);
  84137. }
  84138. DROPBITS(thisx.bits);
  84139. state->length = (unsigned)thisx.val;
  84140. if ((int)(thisx.op) == 0) {
  84141. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  84142. "inflate: literal '%c'\n" :
  84143. "inflate: literal 0x%02x\n", thisx.val));
  84144. state->mode = LIT;
  84145. break;
  84146. }
  84147. if (thisx.op & 32) {
  84148. Tracevv((stderr, "inflate: end of block\n"));
  84149. state->mode = TYPE;
  84150. break;
  84151. }
  84152. if (thisx.op & 64) {
  84153. strm->msg = (char *)"invalid literal/length code";
  84154. state->mode = BAD;
  84155. break;
  84156. }
  84157. state->extra = (unsigned)(thisx.op) & 15;
  84158. state->mode = LENEXT;
  84159. case LENEXT:
  84160. if (state->extra) {
  84161. NEEDBITS(state->extra);
  84162. state->length += BITS(state->extra);
  84163. DROPBITS(state->extra);
  84164. }
  84165. Tracevv((stderr, "inflate: length %u\n", state->length));
  84166. state->mode = DIST;
  84167. case DIST:
  84168. for (;;) {
  84169. thisx = state->distcode[BITS(state->distbits)];
  84170. if ((unsigned)(thisx.bits) <= bits) break;
  84171. PULLBYTE();
  84172. }
  84173. if ((thisx.op & 0xf0) == 0) {
  84174. last = thisx;
  84175. for (;;) {
  84176. thisx = state->distcode[last.val +
  84177. (BITS(last.bits + last.op) >> last.bits)];
  84178. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  84179. PULLBYTE();
  84180. }
  84181. DROPBITS(last.bits);
  84182. }
  84183. DROPBITS(thisx.bits);
  84184. if (thisx.op & 64) {
  84185. strm->msg = (char *)"invalid distance code";
  84186. state->mode = BAD;
  84187. break;
  84188. }
  84189. state->offset = (unsigned)thisx.val;
  84190. state->extra = (unsigned)(thisx.op) & 15;
  84191. state->mode = DISTEXT;
  84192. case DISTEXT:
  84193. if (state->extra) {
  84194. NEEDBITS(state->extra);
  84195. state->offset += BITS(state->extra);
  84196. DROPBITS(state->extra);
  84197. }
  84198. #ifdef INFLATE_STRICT
  84199. if (state->offset > state->dmax) {
  84200. strm->msg = (char *)"invalid distance too far back";
  84201. state->mode = BAD;
  84202. break;
  84203. }
  84204. #endif
  84205. if (state->offset > state->whave + out - left) {
  84206. strm->msg = (char *)"invalid distance too far back";
  84207. state->mode = BAD;
  84208. break;
  84209. }
  84210. Tracevv((stderr, "inflate: distance %u\n", state->offset));
  84211. state->mode = MATCH;
  84212. case MATCH:
  84213. if (left == 0) goto inf_leave;
  84214. copy = out - left;
  84215. if (state->offset > copy) { /* copy from window */
  84216. copy = state->offset - copy;
  84217. if (copy > state->write) {
  84218. copy -= state->write;
  84219. from = state->window + (state->wsize - copy);
  84220. }
  84221. else
  84222. from = state->window + (state->write - copy);
  84223. if (copy > state->length) copy = state->length;
  84224. }
  84225. else { /* copy from output */
  84226. from = put - state->offset;
  84227. copy = state->length;
  84228. }
  84229. if (copy > left) copy = left;
  84230. left -= copy;
  84231. state->length -= copy;
  84232. do {
  84233. *put++ = *from++;
  84234. } while (--copy);
  84235. if (state->length == 0) state->mode = LEN;
  84236. break;
  84237. case LIT:
  84238. if (left == 0) goto inf_leave;
  84239. *put++ = (unsigned char)(state->length);
  84240. left--;
  84241. state->mode = LEN;
  84242. break;
  84243. case CHECK:
  84244. if (state->wrap) {
  84245. NEEDBITS(32);
  84246. out -= left;
  84247. strm->total_out += out;
  84248. state->total += out;
  84249. if (out)
  84250. strm->adler = state->check =
  84251. UPDATE(state->check, put - out, out);
  84252. out = left;
  84253. if ((
  84254. #ifdef GUNZIP
  84255. state->flags ? hold :
  84256. #endif
  84257. REVERSE(hold)) != state->check) {
  84258. strm->msg = (char *)"incorrect data check";
  84259. state->mode = BAD;
  84260. break;
  84261. }
  84262. INITBITS();
  84263. Tracev((stderr, "inflate: check matches trailer\n"));
  84264. }
  84265. #ifdef GUNZIP
  84266. state->mode = LENGTH;
  84267. case LENGTH:
  84268. if (state->wrap && state->flags) {
  84269. NEEDBITS(32);
  84270. if (hold != (state->total & 0xffffffffUL)) {
  84271. strm->msg = (char *)"incorrect length check";
  84272. state->mode = BAD;
  84273. break;
  84274. }
  84275. INITBITS();
  84276. Tracev((stderr, "inflate: length matches trailer\n"));
  84277. }
  84278. #endif
  84279. state->mode = DONE;
  84280. case DONE:
  84281. ret = Z_STREAM_END;
  84282. goto inf_leave;
  84283. case BAD:
  84284. ret = Z_DATA_ERROR;
  84285. goto inf_leave;
  84286. case MEM:
  84287. return Z_MEM_ERROR;
  84288. case SYNC:
  84289. default:
  84290. return Z_STREAM_ERROR;
  84291. }
  84292. /*
  84293. Return from inflate(), updating the total counts and the check value.
  84294. If there was no progress during the inflate() call, return a buffer
  84295. error. Call updatewindow() to create and/or update the window state.
  84296. Note: a memory error from inflate() is non-recoverable.
  84297. */
  84298. inf_leave:
  84299. RESTORE();
  84300. if (state->wsize || (state->mode < CHECK && out != strm->avail_out))
  84301. if (updatewindow(strm, out)) {
  84302. state->mode = MEM;
  84303. return Z_MEM_ERROR;
  84304. }
  84305. in -= strm->avail_in;
  84306. out -= strm->avail_out;
  84307. strm->total_in += in;
  84308. strm->total_out += out;
  84309. state->total += out;
  84310. if (state->wrap && out)
  84311. strm->adler = state->check =
  84312. UPDATE(state->check, strm->next_out - out, out);
  84313. strm->data_type = state->bits + (state->last ? 64 : 0) +
  84314. (state->mode == TYPE ? 128 : 0);
  84315. if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
  84316. ret = Z_BUF_ERROR;
  84317. return ret;
  84318. }
  84319. int ZEXPORT inflateEnd (z_streamp strm)
  84320. {
  84321. struct inflate_state FAR *state;
  84322. if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
  84323. return Z_STREAM_ERROR;
  84324. state = (struct inflate_state FAR *)strm->state;
  84325. if (state->window != Z_NULL) ZFREE(strm, state->window);
  84326. ZFREE(strm, strm->state);
  84327. strm->state = Z_NULL;
  84328. Tracev((stderr, "inflate: end\n"));
  84329. return Z_OK;
  84330. }
  84331. int ZEXPORT inflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  84332. {
  84333. struct inflate_state FAR *state;
  84334. unsigned long id_;
  84335. /* check state */
  84336. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84337. state = (struct inflate_state FAR *)strm->state;
  84338. if (state->wrap != 0 && state->mode != DICT)
  84339. return Z_STREAM_ERROR;
  84340. /* check for correct dictionary id */
  84341. if (state->mode == DICT) {
  84342. id_ = adler32(0L, Z_NULL, 0);
  84343. id_ = adler32(id_, dictionary, dictLength);
  84344. if (id_ != state->check)
  84345. return Z_DATA_ERROR;
  84346. }
  84347. /* copy dictionary to window */
  84348. if (updatewindow(strm, strm->avail_out)) {
  84349. state->mode = MEM;
  84350. return Z_MEM_ERROR;
  84351. }
  84352. if (dictLength > state->wsize) {
  84353. zmemcpy(state->window, dictionary + dictLength - state->wsize,
  84354. state->wsize);
  84355. state->whave = state->wsize;
  84356. }
  84357. else {
  84358. zmemcpy(state->window + state->wsize - dictLength, dictionary,
  84359. dictLength);
  84360. state->whave = dictLength;
  84361. }
  84362. state->havedict = 1;
  84363. Tracev((stderr, "inflate: dictionary set\n"));
  84364. return Z_OK;
  84365. }
  84366. int ZEXPORT inflateGetHeader (z_streamp strm, gz_headerp head)
  84367. {
  84368. struct inflate_state FAR *state;
  84369. /* check state */
  84370. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84371. state = (struct inflate_state FAR *)strm->state;
  84372. if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;
  84373. /* save header structure */
  84374. state->head = head;
  84375. head->done = 0;
  84376. return Z_OK;
  84377. }
  84378. /*
  84379. Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found
  84380. or when out of input. When called, *have is the number of pattern bytes
  84381. found in order so far, in 0..3. On return *have is updated to the new
  84382. state. If on return *have equals four, then the pattern was found and the
  84383. return value is how many bytes were read including the last byte of the
  84384. pattern. If *have is less than four, then the pattern has not been found
  84385. yet and the return value is len. In the latter case, syncsearch() can be
  84386. called again with more data and the *have state. *have is initialized to
  84387. zero for the first call.
  84388. */
  84389. local unsigned syncsearch (unsigned FAR *have, unsigned char FAR *buf, unsigned len)
  84390. {
  84391. unsigned got;
  84392. unsigned next;
  84393. got = *have;
  84394. next = 0;
  84395. while (next < len && got < 4) {
  84396. if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
  84397. got++;
  84398. else if (buf[next])
  84399. got = 0;
  84400. else
  84401. got = 4 - got;
  84402. next++;
  84403. }
  84404. *have = got;
  84405. return next;
  84406. }
  84407. int ZEXPORT inflateSync (z_streamp strm)
  84408. {
  84409. unsigned len; /* number of bytes to look at or looked at */
  84410. unsigned long in, out; /* temporary to save total_in and total_out */
  84411. unsigned char buf[4]; /* to restore bit buffer to byte string */
  84412. struct inflate_state FAR *state;
  84413. /* check parameters */
  84414. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84415. state = (struct inflate_state FAR *)strm->state;
  84416. if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;
  84417. /* if first time, start search in bit buffer */
  84418. if (state->mode != SYNC) {
  84419. state->mode = SYNC;
  84420. state->hold <<= state->bits & 7;
  84421. state->bits -= state->bits & 7;
  84422. len = 0;
  84423. while (state->bits >= 8) {
  84424. buf[len++] = (unsigned char)(state->hold);
  84425. state->hold >>= 8;
  84426. state->bits -= 8;
  84427. }
  84428. state->have = 0;
  84429. syncsearch(&(state->have), buf, len);
  84430. }
  84431. /* search available input */
  84432. len = syncsearch(&(state->have), strm->next_in, strm->avail_in);
  84433. strm->avail_in -= len;
  84434. strm->next_in += len;
  84435. strm->total_in += len;
  84436. /* return no joy or set up to restart inflate() on a new block */
  84437. if (state->have != 4) return Z_DATA_ERROR;
  84438. in = strm->total_in; out = strm->total_out;
  84439. inflateReset(strm);
  84440. strm->total_in = in; strm->total_out = out;
  84441. state->mode = TYPE;
  84442. return Z_OK;
  84443. }
  84444. /*
  84445. Returns true if inflate is currently at the end of a block generated by
  84446. Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
  84447. implementation to provide an additional safety check. PPP uses
  84448. Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
  84449. block. When decompressing, PPP checks that at the end of input packet,
  84450. inflate is waiting for these length bytes.
  84451. */
  84452. int ZEXPORT inflateSyncPoint (z_streamp strm)
  84453. {
  84454. struct inflate_state FAR *state;
  84455. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84456. state = (struct inflate_state FAR *)strm->state;
  84457. return state->mode == STORED && state->bits == 0;
  84458. }
  84459. int ZEXPORT inflateCopy(z_streamp dest, z_streamp source)
  84460. {
  84461. struct inflate_state FAR *state;
  84462. struct inflate_state FAR *copy;
  84463. unsigned char FAR *window;
  84464. unsigned wsize;
  84465. /* check input */
  84466. if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL ||
  84467. source->zalloc == (alloc_func)0 || source->zfree == (free_func)0)
  84468. return Z_STREAM_ERROR;
  84469. state = (struct inflate_state FAR *)source->state;
  84470. /* allocate space */
  84471. copy = (struct inflate_state FAR *)
  84472. ZALLOC(source, 1, sizeof(struct inflate_state));
  84473. if (copy == Z_NULL) return Z_MEM_ERROR;
  84474. window = Z_NULL;
  84475. if (state->window != Z_NULL) {
  84476. window = (unsigned char FAR *)
  84477. ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));
  84478. if (window == Z_NULL) {
  84479. ZFREE(source, copy);
  84480. return Z_MEM_ERROR;
  84481. }
  84482. }
  84483. /* copy state */
  84484. zmemcpy(dest, source, sizeof(z_stream));
  84485. zmemcpy(copy, state, sizeof(struct inflate_state));
  84486. if (state->lencode >= state->codes &&
  84487. state->lencode <= state->codes + ENOUGH - 1) {
  84488. copy->lencode = copy->codes + (state->lencode - state->codes);
  84489. copy->distcode = copy->codes + (state->distcode - state->codes);
  84490. }
  84491. copy->next = copy->codes + (state->next - state->codes);
  84492. if (window != Z_NULL) {
  84493. wsize = 1U << state->wbits;
  84494. zmemcpy(window, state->window, wsize);
  84495. }
  84496. copy->window = window;
  84497. dest->state = (struct internal_state FAR *)copy;
  84498. return Z_OK;
  84499. }
  84500. /*** End of inlined file: inflate.c ***/
  84501. /*** Start of inlined file: inftrees.c ***/
  84502. #define MAXBITS 15
  84503. const char inflate_copyright[] =
  84504. " inflate 1.2.3 Copyright 1995-2005 Mark Adler ";
  84505. /*
  84506. If you use the zlib library in a product, an acknowledgment is welcome
  84507. in the documentation of your product. If for some reason you cannot
  84508. include such an acknowledgment, I would appreciate that you keep this
  84509. copyright string in the executable of your product.
  84510. */
  84511. /*
  84512. Build a set of tables to decode the provided canonical Huffman code.
  84513. The code lengths are lens[0..codes-1]. The result starts at *table,
  84514. whose indices are 0..2^bits-1. work is a writable array of at least
  84515. lens shorts, which is used as a work area. type is the type of code
  84516. to be generated, CODES, LENS, or DISTS. On return, zero is success,
  84517. -1 is an invalid code, and +1 means that ENOUGH isn't enough. table
  84518. on return points to the next available entry's address. bits is the
  84519. requested root table index bits, and on return it is the actual root
  84520. table index bits. It will differ if the request is greater than the
  84521. longest code or if it is less than the shortest code.
  84522. */
  84523. int inflate_table (codetype type,
  84524. unsigned short FAR *lens,
  84525. unsigned codes,
  84526. code FAR * FAR *table,
  84527. unsigned FAR *bits,
  84528. unsigned short FAR *work)
  84529. {
  84530. unsigned len; /* a code's length in bits */
  84531. unsigned sym; /* index of code symbols */
  84532. unsigned min, max; /* minimum and maximum code lengths */
  84533. unsigned root; /* number of index bits for root table */
  84534. unsigned curr; /* number of index bits for current table */
  84535. unsigned drop; /* code bits to drop for sub-table */
  84536. int left; /* number of prefix codes available */
  84537. unsigned used; /* code entries in table used */
  84538. unsigned huff; /* Huffman code */
  84539. unsigned incr; /* for incrementing code, index */
  84540. unsigned fill; /* index for replicating entries */
  84541. unsigned low; /* low bits for current root entry */
  84542. unsigned mask; /* mask for low root bits */
  84543. code thisx; /* table entry for duplication */
  84544. code FAR *next; /* next available space in table */
  84545. const unsigned short FAR *base; /* base value table to use */
  84546. const unsigned short FAR *extra; /* extra bits table to use */
  84547. int end; /* use base and extra for symbol > end */
  84548. unsigned short count[MAXBITS+1]; /* number of codes of each length */
  84549. unsigned short offs[MAXBITS+1]; /* offsets in table for each length */
  84550. static const unsigned short lbase[31] = { /* Length codes 257..285 base */
  84551. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  84552. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
  84553. static const unsigned short lext[31] = { /* Length codes 257..285 extra */
  84554. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  84555. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196};
  84556. static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
  84557. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  84558. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  84559. 8193, 12289, 16385, 24577, 0, 0};
  84560. static const unsigned short dext[32] = { /* Distance codes 0..29 extra */
  84561. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  84562. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  84563. 28, 28, 29, 29, 64, 64};
  84564. /*
  84565. Process a set of code lengths to create a canonical Huffman code. The
  84566. code lengths are lens[0..codes-1]. Each length corresponds to the
  84567. symbols 0..codes-1. The Huffman code is generated by first sorting the
  84568. symbols by length from short to long, and retaining the symbol order
  84569. for codes with equal lengths. Then the code starts with all zero bits
  84570. for the first code of the shortest length, and the codes are integer
  84571. increments for the same length, and zeros are appended as the length
  84572. increases. For the deflate format, these bits are stored backwards
  84573. from their more natural integer increment ordering, and so when the
  84574. decoding tables are built in the large loop below, the integer codes
  84575. are incremented backwards.
  84576. This routine assumes, but does not check, that all of the entries in
  84577. lens[] are in the range 0..MAXBITS. The caller must assure this.
  84578. 1..MAXBITS is interpreted as that code length. zero means that that
  84579. symbol does not occur in this code.
  84580. The codes are sorted by computing a count of codes for each length,
  84581. creating from that a table of starting indices for each length in the
  84582. sorted table, and then entering the symbols in order in the sorted
  84583. table. The sorted table is work[], with that space being provided by
  84584. the caller.
  84585. The length counts are used for other purposes as well, i.e. finding
  84586. the minimum and maximum length codes, determining if there are any
  84587. codes at all, checking for a valid set of lengths, and looking ahead
  84588. at length counts to determine sub-table sizes when building the
  84589. decoding tables.
  84590. */
  84591. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  84592. for (len = 0; len <= MAXBITS; len++)
  84593. count[len] = 0;
  84594. for (sym = 0; sym < codes; sym++)
  84595. count[lens[sym]]++;
  84596. /* bound code lengths, force root to be within code lengths */
  84597. root = *bits;
  84598. for (max = MAXBITS; max >= 1; max--)
  84599. if (count[max] != 0) break;
  84600. if (root > max) root = max;
  84601. if (max == 0) { /* no symbols to code at all */
  84602. thisx.op = (unsigned char)64; /* invalid code marker */
  84603. thisx.bits = (unsigned char)1;
  84604. thisx.val = (unsigned short)0;
  84605. *(*table)++ = thisx; /* make a table to force an error */
  84606. *(*table)++ = thisx;
  84607. *bits = 1;
  84608. return 0; /* no symbols, but wait for decoding to report error */
  84609. }
  84610. for (min = 1; min <= MAXBITS; min++)
  84611. if (count[min] != 0) break;
  84612. if (root < min) root = min;
  84613. /* check for an over-subscribed or incomplete set of lengths */
  84614. left = 1;
  84615. for (len = 1; len <= MAXBITS; len++) {
  84616. left <<= 1;
  84617. left -= count[len];
  84618. if (left < 0) return -1; /* over-subscribed */
  84619. }
  84620. if (left > 0 && (type == CODES || max != 1))
  84621. return -1; /* incomplete set */
  84622. /* generate offsets into symbol table for each length for sorting */
  84623. offs[1] = 0;
  84624. for (len = 1; len < MAXBITS; len++)
  84625. offs[len + 1] = offs[len] + count[len];
  84626. /* sort symbols by length, by symbol order within each length */
  84627. for (sym = 0; sym < codes; sym++)
  84628. if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
  84629. /*
  84630. Create and fill in decoding tables. In this loop, the table being
  84631. filled is at next and has curr index bits. The code being used is huff
  84632. with length len. That code is converted to an index by dropping drop
  84633. bits off of the bottom. For codes where len is less than drop + curr,
  84634. those top drop + curr - len bits are incremented through all values to
  84635. fill the table with replicated entries.
  84636. root is the number of index bits for the root table. When len exceeds
  84637. root, sub-tables are created pointed to by the root entry with an index
  84638. of the low root bits of huff. This is saved in low to check for when a
  84639. new sub-table should be started. drop is zero when the root table is
  84640. being filled, and drop is root when sub-tables are being filled.
  84641. When a new sub-table is needed, it is necessary to look ahead in the
  84642. code lengths to determine what size sub-table is needed. The length
  84643. counts are used for this, and so count[] is decremented as codes are
  84644. entered in the tables.
  84645. used keeps track of how many table entries have been allocated from the
  84646. provided *table space. It is checked when a LENS table is being made
  84647. against the space in *table, ENOUGH, minus the maximum space needed by
  84648. the worst case distance code, MAXD. This should never happen, but the
  84649. sufficiency of ENOUGH has not been proven exhaustively, hence the check.
  84650. This assumes that when type == LENS, bits == 9.
  84651. sym increments through all symbols, and the loop terminates when
  84652. all codes of length max, i.e. all codes, have been processed. This
  84653. routine permits incomplete codes, so another loop after this one fills
  84654. in the rest of the decoding tables with invalid code markers.
  84655. */
  84656. /* set up for code type */
  84657. switch (type) {
  84658. case CODES:
  84659. base = extra = work; /* dummy value--not used */
  84660. end = 19;
  84661. break;
  84662. case LENS:
  84663. base = lbase;
  84664. base -= 257;
  84665. extra = lext;
  84666. extra -= 257;
  84667. end = 256;
  84668. break;
  84669. default: /* DISTS */
  84670. base = dbase;
  84671. extra = dext;
  84672. end = -1;
  84673. }
  84674. /* initialize state for loop */
  84675. huff = 0; /* starting code */
  84676. sym = 0; /* starting code symbol */
  84677. len = min; /* starting code length */
  84678. next = *table; /* current table to fill in */
  84679. curr = root; /* current table index bits */
  84680. drop = 0; /* current bits to drop from code for index */
  84681. low = (unsigned)(-1); /* trigger new sub-table when len > root */
  84682. used = 1U << root; /* use root table entries */
  84683. mask = used - 1; /* mask for comparing low */
  84684. /* check available table space */
  84685. if (type == LENS && used >= ENOUGH - MAXD)
  84686. return 1;
  84687. /* process all codes and make table entries */
  84688. for (;;) {
  84689. /* create table entry */
  84690. thisx.bits = (unsigned char)(len - drop);
  84691. if ((int)(work[sym]) < end) {
  84692. thisx.op = (unsigned char)0;
  84693. thisx.val = work[sym];
  84694. }
  84695. else if ((int)(work[sym]) > end) {
  84696. thisx.op = (unsigned char)(extra[work[sym]]);
  84697. thisx.val = base[work[sym]];
  84698. }
  84699. else {
  84700. thisx.op = (unsigned char)(32 + 64); /* end of block */
  84701. thisx.val = 0;
  84702. }
  84703. /* replicate for those indices with low len bits equal to huff */
  84704. incr = 1U << (len - drop);
  84705. fill = 1U << curr;
  84706. min = fill; /* save offset to next table */
  84707. do {
  84708. fill -= incr;
  84709. next[(huff >> drop) + fill] = thisx;
  84710. } while (fill != 0);
  84711. /* backwards increment the len-bit code huff */
  84712. incr = 1U << (len - 1);
  84713. while (huff & incr)
  84714. incr >>= 1;
  84715. if (incr != 0) {
  84716. huff &= incr - 1;
  84717. huff += incr;
  84718. }
  84719. else
  84720. huff = 0;
  84721. /* go to next symbol, update count, len */
  84722. sym++;
  84723. if (--(count[len]) == 0) {
  84724. if (len == max) break;
  84725. len = lens[work[sym]];
  84726. }
  84727. /* create new sub-table if needed */
  84728. if (len > root && (huff & mask) != low) {
  84729. /* if first time, transition to sub-tables */
  84730. if (drop == 0)
  84731. drop = root;
  84732. /* increment past last table */
  84733. next += min; /* here min is 1 << curr */
  84734. /* determine length of next table */
  84735. curr = len - drop;
  84736. left = (int)(1 << curr);
  84737. while (curr + drop < max) {
  84738. left -= count[curr + drop];
  84739. if (left <= 0) break;
  84740. curr++;
  84741. left <<= 1;
  84742. }
  84743. /* check for enough space */
  84744. used += 1U << curr;
  84745. if (type == LENS && used >= ENOUGH - MAXD)
  84746. return 1;
  84747. /* point entry in root table to sub-table */
  84748. low = huff & mask;
  84749. (*table)[low].op = (unsigned char)curr;
  84750. (*table)[low].bits = (unsigned char)root;
  84751. (*table)[low].val = (unsigned short)(next - *table);
  84752. }
  84753. }
  84754. /*
  84755. Fill in rest of table for incomplete codes. This loop is similar to the
  84756. loop above in incrementing huff for table indices. It is assumed that
  84757. len is equal to curr + drop, so there is no loop needed to increment
  84758. through high index bits. When the current sub-table is filled, the loop
  84759. drops back to the root table to fill in any remaining entries there.
  84760. */
  84761. thisx.op = (unsigned char)64; /* invalid code marker */
  84762. thisx.bits = (unsigned char)(len - drop);
  84763. thisx.val = (unsigned short)0;
  84764. while (huff != 0) {
  84765. /* when done with sub-table, drop back to root table */
  84766. if (drop != 0 && (huff & mask) != low) {
  84767. drop = 0;
  84768. len = root;
  84769. next = *table;
  84770. thisx.bits = (unsigned char)len;
  84771. }
  84772. /* put invalid code marker in table */
  84773. next[huff >> drop] = thisx;
  84774. /* backwards increment the len-bit code huff */
  84775. incr = 1U << (len - 1);
  84776. while (huff & incr)
  84777. incr >>= 1;
  84778. if (incr != 0) {
  84779. huff &= incr - 1;
  84780. huff += incr;
  84781. }
  84782. else
  84783. huff = 0;
  84784. }
  84785. /* set return parameters */
  84786. *table += used;
  84787. *bits = root;
  84788. return 0;
  84789. }
  84790. /*** End of inlined file: inftrees.c ***/
  84791. /*** Start of inlined file: trees.c ***/
  84792. /*
  84793. * ALGORITHM
  84794. *
  84795. * The "deflation" process uses several Huffman trees. The more
  84796. * common source values are represented by shorter bit sequences.
  84797. *
  84798. * Each code tree is stored in a compressed form which is itself
  84799. * a Huffman encoding of the lengths of all the code strings (in
  84800. * ascending order by source values). The actual code strings are
  84801. * reconstructed from the lengths in the inflate process, as described
  84802. * in the deflate specification.
  84803. *
  84804. * REFERENCES
  84805. *
  84806. * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
  84807. * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
  84808. *
  84809. * Storer, James A.
  84810. * Data Compression: Methods and Theory, pp. 49-50.
  84811. * Computer Science Press, 1988. ISBN 0-7167-8156-5.
  84812. *
  84813. * Sedgewick, R.
  84814. * Algorithms, p290.
  84815. * Addison-Wesley, 1983. ISBN 0-201-06672-6.
  84816. */
  84817. /* @(#) $Id: trees.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  84818. /* #define GEN_TREES_H */
  84819. #ifdef DEBUG
  84820. # include <ctype.h>
  84821. #endif
  84822. /* ===========================================================================
  84823. * Constants
  84824. */
  84825. #define MAX_BL_BITS 7
  84826. /* Bit length codes must not exceed MAX_BL_BITS bits */
  84827. #define END_BLOCK 256
  84828. /* end of block literal code */
  84829. #define REP_3_6 16
  84830. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  84831. #define REPZ_3_10 17
  84832. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  84833. #define REPZ_11_138 18
  84834. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  84835. local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
  84836. = {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};
  84837. local const int extra_dbits[D_CODES] /* extra bits for each distance code */
  84838. = {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};
  84839. local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
  84840. = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
  84841. local const uch bl_order[BL_CODES]
  84842. = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
  84843. /* The lengths of the bit length codes are sent in order of decreasing
  84844. * probability, to avoid transmitting the lengths for unused bit length codes.
  84845. */
  84846. #define Buf_size (8 * 2*sizeof(char))
  84847. /* Number of bits used within bi_buf. (bi_buf might be implemented on
  84848. * more than 16 bits on some systems.)
  84849. */
  84850. /* ===========================================================================
  84851. * Local data. These are initialized only once.
  84852. */
  84853. #define DIST_CODE_LEN 512 /* see definition of array dist_code below */
  84854. #if defined(GEN_TREES_H) || !defined(STDC)
  84855. /* non ANSI compilers may not accept trees.h */
  84856. local ct_data static_ltree[L_CODES+2];
  84857. /* The static literal tree. Since the bit lengths are imposed, there is no
  84858. * need for the L_CODES extra codes used during heap construction. However
  84859. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  84860. * below).
  84861. */
  84862. local ct_data static_dtree[D_CODES];
  84863. /* The static distance tree. (Actually a trivial tree since all codes use
  84864. * 5 bits.)
  84865. */
  84866. uch _dist_code[DIST_CODE_LEN];
  84867. /* Distance codes. The first 256 values correspond to the distances
  84868. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  84869. * the 15 bit distances.
  84870. */
  84871. uch _length_code[MAX_MATCH-MIN_MATCH+1];
  84872. /* length code for each normalized match length (0 == MIN_MATCH) */
  84873. local int base_length[LENGTH_CODES];
  84874. /* First normalized length for each code (0 = MIN_MATCH) */
  84875. local int base_dist[D_CODES];
  84876. /* First normalized distance for each code (0 = distance of 1) */
  84877. #else
  84878. /*** Start of inlined file: trees.h ***/
  84879. local const ct_data static_ltree[L_CODES+2] = {
  84880. {{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}},
  84881. {{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}},
  84882. {{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}},
  84883. {{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}},
  84884. {{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}},
  84885. {{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}},
  84886. {{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}},
  84887. {{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}},
  84888. {{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}},
  84889. {{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}},
  84890. {{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}},
  84891. {{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}},
  84892. {{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}},
  84893. {{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}},
  84894. {{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}},
  84895. {{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}},
  84896. {{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}},
  84897. {{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}},
  84898. {{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}},
  84899. {{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}},
  84900. {{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}},
  84901. {{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}},
  84902. {{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}},
  84903. {{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}},
  84904. {{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}},
  84905. {{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}},
  84906. {{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}},
  84907. {{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}},
  84908. {{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}},
  84909. {{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}},
  84910. {{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}},
  84911. {{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}},
  84912. {{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}},
  84913. {{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}},
  84914. {{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}},
  84915. {{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}},
  84916. {{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}},
  84917. {{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}},
  84918. {{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}},
  84919. {{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}},
  84920. {{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}},
  84921. {{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}},
  84922. {{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}},
  84923. {{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}},
  84924. {{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}},
  84925. {{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}},
  84926. {{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}},
  84927. {{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}},
  84928. {{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}},
  84929. {{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}},
  84930. {{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}},
  84931. {{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}},
  84932. {{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}},
  84933. {{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}},
  84934. {{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}},
  84935. {{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}},
  84936. {{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}},
  84937. {{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}}
  84938. };
  84939. local const ct_data static_dtree[D_CODES] = {
  84940. {{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}},
  84941. {{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}},
  84942. {{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}},
  84943. {{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}},
  84944. {{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}},
  84945. {{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}
  84946. };
  84947. const uch _dist_code[DIST_CODE_LEN] = {
  84948. 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
  84949. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
  84950. 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
  84951. 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  84952. 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
  84953. 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  84954. 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84955. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84956. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84957. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
  84958. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  84959. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  84960. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
  84961. 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
  84962. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  84963. 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  84964. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  84965. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
  84966. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  84967. 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84968. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84969. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84970. 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84971. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84972. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84973. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
  84974. };
  84975. const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {
  84976. 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
  84977. 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
  84978. 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
  84979. 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  84980. 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
  84981. 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
  84982. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  84983. 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  84984. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  84985. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
  84986. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  84987. 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  84988. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
  84989. };
  84990. local const int base_length[LENGTH_CODES] = {
  84991. 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
  84992. 64, 80, 96, 112, 128, 160, 192, 224, 0
  84993. };
  84994. local const int base_dist[D_CODES] = {
  84995. 0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
  84996. 32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
  84997. 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
  84998. };
  84999. /*** End of inlined file: trees.h ***/
  85000. #endif /* GEN_TREES_H */
  85001. struct static_tree_desc_s {
  85002. const ct_data *static_tree; /* static tree or NULL */
  85003. const intf *extra_bits; /* extra bits for each code or NULL */
  85004. int extra_base; /* base index for extra_bits */
  85005. int elems; /* max number of elements in the tree */
  85006. int max_length; /* max bit length for the codes */
  85007. };
  85008. local static_tree_desc static_l_desc =
  85009. {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
  85010. local static_tree_desc static_d_desc =
  85011. {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS};
  85012. local static_tree_desc static_bl_desc =
  85013. {(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS};
  85014. /* ===========================================================================
  85015. * Local (static) routines in this file.
  85016. */
  85017. local void tr_static_init OF((void));
  85018. local void init_block OF((deflate_state *s));
  85019. local void pqdownheap OF((deflate_state *s, ct_data *tree, int k));
  85020. local void gen_bitlen OF((deflate_state *s, tree_desc *desc));
  85021. local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count));
  85022. local void build_tree OF((deflate_state *s, tree_desc *desc));
  85023. local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code));
  85024. local void send_tree OF((deflate_state *s, ct_data *tree, int max_code));
  85025. local int build_bl_tree OF((deflate_state *s));
  85026. local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
  85027. int blcodes));
  85028. local void compress_block OF((deflate_state *s, ct_data *ltree,
  85029. ct_data *dtree));
  85030. local void set_data_type OF((deflate_state *s));
  85031. local unsigned bi_reverse OF((unsigned value, int length));
  85032. local void bi_windup OF((deflate_state *s));
  85033. local void bi_flush OF((deflate_state *s));
  85034. local void copy_block OF((deflate_state *s, charf *buf, unsigned len,
  85035. int header));
  85036. #ifdef GEN_TREES_H
  85037. local void gen_trees_header OF((void));
  85038. #endif
  85039. #ifndef DEBUG
  85040. # define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
  85041. /* Send a code of the given tree. c and tree must not have side effects */
  85042. #else /* DEBUG */
  85043. # define send_code(s, c, tree) \
  85044. { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
  85045. send_bits(s, tree[c].Code, tree[c].Len); }
  85046. #endif
  85047. /* ===========================================================================
  85048. * Output a short LSB first on the stream.
  85049. * IN assertion: there is enough room in pendingBuf.
  85050. */
  85051. #define put_short(s, w) { \
  85052. put_byte(s, (uch)((w) & 0xff)); \
  85053. put_byte(s, (uch)((ush)(w) >> 8)); \
  85054. }
  85055. /* ===========================================================================
  85056. * Send a value on a given number of bits.
  85057. * IN assertion: length <= 16 and value fits in length bits.
  85058. */
  85059. #ifdef DEBUG
  85060. local void send_bits OF((deflate_state *s, int value, int length));
  85061. local void send_bits (deflate_state *s, int value, int length)
  85062. {
  85063. Tracevv((stderr," l %2d v %4x ", length, value));
  85064. Assert(length > 0 && length <= 15, "invalid length");
  85065. s->bits_sent += (ulg)length;
  85066. /* If not enough room in bi_buf, use (valid) bits from bi_buf and
  85067. * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
  85068. * unused bits in value.
  85069. */
  85070. if (s->bi_valid > (int)Buf_size - length) {
  85071. s->bi_buf |= (value << s->bi_valid);
  85072. put_short(s, s->bi_buf);
  85073. s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
  85074. s->bi_valid += length - Buf_size;
  85075. } else {
  85076. s->bi_buf |= value << s->bi_valid;
  85077. s->bi_valid += length;
  85078. }
  85079. }
  85080. #else /* !DEBUG */
  85081. #define send_bits(s, value, length) \
  85082. { int len = length;\
  85083. if (s->bi_valid > (int)Buf_size - len) {\
  85084. int val = value;\
  85085. s->bi_buf |= (val << s->bi_valid);\
  85086. put_short(s, s->bi_buf);\
  85087. s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
  85088. s->bi_valid += len - Buf_size;\
  85089. } else {\
  85090. s->bi_buf |= (value) << s->bi_valid;\
  85091. s->bi_valid += len;\
  85092. }\
  85093. }
  85094. #endif /* DEBUG */
  85095. /* the arguments must not have side effects */
  85096. /* ===========================================================================
  85097. * Initialize the various 'constant' tables.
  85098. */
  85099. local void tr_static_init()
  85100. {
  85101. #if defined(GEN_TREES_H) || !defined(STDC)
  85102. static int static_init_done = 0;
  85103. int n; /* iterates over tree elements */
  85104. int bits; /* bit counter */
  85105. int length; /* length value */
  85106. int code; /* code value */
  85107. int dist; /* distance index */
  85108. ush bl_count[MAX_BITS+1];
  85109. /* number of codes at each bit length for an optimal tree */
  85110. if (static_init_done) return;
  85111. /* For some embedded targets, global variables are not initialized: */
  85112. static_l_desc.static_tree = static_ltree;
  85113. static_l_desc.extra_bits = extra_lbits;
  85114. static_d_desc.static_tree = static_dtree;
  85115. static_d_desc.extra_bits = extra_dbits;
  85116. static_bl_desc.extra_bits = extra_blbits;
  85117. /* Initialize the mapping length (0..255) -> length code (0..28) */
  85118. length = 0;
  85119. for (code = 0; code < LENGTH_CODES-1; code++) {
  85120. base_length[code] = length;
  85121. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  85122. _length_code[length++] = (uch)code;
  85123. }
  85124. }
  85125. Assert (length == 256, "tr_static_init: length != 256");
  85126. /* Note that the length 255 (match length 258) can be represented
  85127. * in two different ways: code 284 + 5 bits or code 285, so we
  85128. * overwrite length_code[255] to use the best encoding:
  85129. */
  85130. _length_code[length-1] = (uch)code;
  85131. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  85132. dist = 0;
  85133. for (code = 0 ; code < 16; code++) {
  85134. base_dist[code] = dist;
  85135. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  85136. _dist_code[dist++] = (uch)code;
  85137. }
  85138. }
  85139. Assert (dist == 256, "tr_static_init: dist != 256");
  85140. dist >>= 7; /* from now on, all distances are divided by 128 */
  85141. for ( ; code < D_CODES; code++) {
  85142. base_dist[code] = dist << 7;
  85143. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  85144. _dist_code[256 + dist++] = (uch)code;
  85145. }
  85146. }
  85147. Assert (dist == 256, "tr_static_init: 256+dist != 512");
  85148. /* Construct the codes of the static literal tree */
  85149. for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
  85150. n = 0;
  85151. while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
  85152. while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
  85153. while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
  85154. while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
  85155. /* Codes 286 and 287 do not exist, but we must include them in the
  85156. * tree construction to get a canonical Huffman tree (longest code
  85157. * all ones)
  85158. */
  85159. gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
  85160. /* The static distance tree is trivial: */
  85161. for (n = 0; n < D_CODES; n++) {
  85162. static_dtree[n].Len = 5;
  85163. static_dtree[n].Code = bi_reverse((unsigned)n, 5);
  85164. }
  85165. static_init_done = 1;
  85166. # ifdef GEN_TREES_H
  85167. gen_trees_header();
  85168. # endif
  85169. #endif /* defined(GEN_TREES_H) || !defined(STDC) */
  85170. }
  85171. /* ===========================================================================
  85172. * Genererate the file trees.h describing the static trees.
  85173. */
  85174. #ifdef GEN_TREES_H
  85175. # ifndef DEBUG
  85176. # include <stdio.h>
  85177. # endif
  85178. # define SEPARATOR(i, last, width) \
  85179. ((i) == (last)? "\n};\n\n" : \
  85180. ((i) % (width) == (width)-1 ? ",\n" : ", "))
  85181. void gen_trees_header()
  85182. {
  85183. FILE *header = fopen("trees.h", "w");
  85184. int i;
  85185. Assert (header != NULL, "Can't open trees.h");
  85186. fprintf(header,
  85187. "/* header created automatically with -DGEN_TREES_H */\n\n");
  85188. fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
  85189. for (i = 0; i < L_CODES+2; i++) {
  85190. fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
  85191. static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
  85192. }
  85193. fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
  85194. for (i = 0; i < D_CODES; i++) {
  85195. fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
  85196. static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
  85197. }
  85198. fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n");
  85199. for (i = 0; i < DIST_CODE_LEN; i++) {
  85200. fprintf(header, "%2u%s", _dist_code[i],
  85201. SEPARATOR(i, DIST_CODE_LEN-1, 20));
  85202. }
  85203. fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
  85204. for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
  85205. fprintf(header, "%2u%s", _length_code[i],
  85206. SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
  85207. }
  85208. fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
  85209. for (i = 0; i < LENGTH_CODES; i++) {
  85210. fprintf(header, "%1u%s", base_length[i],
  85211. SEPARATOR(i, LENGTH_CODES-1, 20));
  85212. }
  85213. fprintf(header, "local const int base_dist[D_CODES] = {\n");
  85214. for (i = 0; i < D_CODES; i++) {
  85215. fprintf(header, "%5u%s", base_dist[i],
  85216. SEPARATOR(i, D_CODES-1, 10));
  85217. }
  85218. fclose(header);
  85219. }
  85220. #endif /* GEN_TREES_H */
  85221. /* ===========================================================================
  85222. * Initialize the tree data structures for a new zlib stream.
  85223. */
  85224. void _tr_init(deflate_state *s)
  85225. {
  85226. tr_static_init();
  85227. s->l_desc.dyn_tree = s->dyn_ltree;
  85228. s->l_desc.stat_desc = &static_l_desc;
  85229. s->d_desc.dyn_tree = s->dyn_dtree;
  85230. s->d_desc.stat_desc = &static_d_desc;
  85231. s->bl_desc.dyn_tree = s->bl_tree;
  85232. s->bl_desc.stat_desc = &static_bl_desc;
  85233. s->bi_buf = 0;
  85234. s->bi_valid = 0;
  85235. s->last_eob_len = 8; /* enough lookahead for inflate */
  85236. #ifdef DEBUG
  85237. s->compressed_len = 0L;
  85238. s->bits_sent = 0L;
  85239. #endif
  85240. /* Initialize the first block of the first file: */
  85241. init_block(s);
  85242. }
  85243. /* ===========================================================================
  85244. * Initialize a new block.
  85245. */
  85246. local void init_block (deflate_state *s)
  85247. {
  85248. int n; /* iterates over tree elements */
  85249. /* Initialize the trees. */
  85250. for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0;
  85251. for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0;
  85252. for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
  85253. s->dyn_ltree[END_BLOCK].Freq = 1;
  85254. s->opt_len = s->static_len = 0L;
  85255. s->last_lit = s->matches = 0;
  85256. }
  85257. #define SMALLEST 1
  85258. /* Index within the heap array of least frequent node in the Huffman tree */
  85259. /* ===========================================================================
  85260. * Remove the smallest element from the heap and recreate the heap with
  85261. * one less element. Updates heap and heap_len.
  85262. */
  85263. #define pqremove(s, tree, top) \
  85264. {\
  85265. top = s->heap[SMALLEST]; \
  85266. s->heap[SMALLEST] = s->heap[s->heap_len--]; \
  85267. pqdownheap(s, tree, SMALLEST); \
  85268. }
  85269. /* ===========================================================================
  85270. * Compares to subtrees, using the tree depth as tie breaker when
  85271. * the subtrees have equal frequency. This minimizes the worst case length.
  85272. */
  85273. #define smaller(tree, n, m, depth) \
  85274. (tree[n].Freq < tree[m].Freq || \
  85275. (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
  85276. /* ===========================================================================
  85277. * Restore the heap property by moving down the tree starting at node k,
  85278. * exchanging a node with the smallest of its two sons if necessary, stopping
  85279. * when the heap property is re-established (each father smaller than its
  85280. * two sons).
  85281. */
  85282. local void pqdownheap (deflate_state *s,
  85283. ct_data *tree, /* the tree to restore */
  85284. int k) /* node to move down */
  85285. {
  85286. int v = s->heap[k];
  85287. int j = k << 1; /* left son of k */
  85288. while (j <= s->heap_len) {
  85289. /* Set j to the smallest of the two sons: */
  85290. if (j < s->heap_len &&
  85291. smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
  85292. j++;
  85293. }
  85294. /* Exit if v is smaller than both sons */
  85295. if (smaller(tree, v, s->heap[j], s->depth)) break;
  85296. /* Exchange v with the smallest son */
  85297. s->heap[k] = s->heap[j]; k = j;
  85298. /* And continue down the tree, setting j to the left son of k */
  85299. j <<= 1;
  85300. }
  85301. s->heap[k] = v;
  85302. }
  85303. /* ===========================================================================
  85304. * Compute the optimal bit lengths for a tree and update the total bit length
  85305. * for the current block.
  85306. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  85307. * above are the tree nodes sorted by increasing frequency.
  85308. * OUT assertions: the field len is set to the optimal bit length, the
  85309. * array bl_count contains the frequencies for each bit length.
  85310. * The length opt_len is updated; static_len is also updated if stree is
  85311. * not null.
  85312. */
  85313. local void gen_bitlen (deflate_state *s, tree_desc *desc)
  85314. {
  85315. ct_data *tree = desc->dyn_tree;
  85316. int max_code = desc->max_code;
  85317. const ct_data *stree = desc->stat_desc->static_tree;
  85318. const intf *extra = desc->stat_desc->extra_bits;
  85319. int base = desc->stat_desc->extra_base;
  85320. int max_length = desc->stat_desc->max_length;
  85321. int h; /* heap index */
  85322. int n, m; /* iterate over the tree elements */
  85323. int bits; /* bit length */
  85324. int xbits; /* extra bits */
  85325. ush f; /* frequency */
  85326. int overflow = 0; /* number of elements with bit length too large */
  85327. for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
  85328. /* In a first pass, compute the optimal bit lengths (which may
  85329. * overflow in the case of the bit length tree).
  85330. */
  85331. tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
  85332. for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
  85333. n = s->heap[h];
  85334. bits = tree[tree[n].Dad].Len + 1;
  85335. if (bits > max_length) bits = max_length, overflow++;
  85336. tree[n].Len = (ush)bits;
  85337. /* We overwrite tree[n].Dad which is no longer needed */
  85338. if (n > max_code) continue; /* not a leaf node */
  85339. s->bl_count[bits]++;
  85340. xbits = 0;
  85341. if (n >= base) xbits = extra[n-base];
  85342. f = tree[n].Freq;
  85343. s->opt_len += (ulg)f * (bits + xbits);
  85344. if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
  85345. }
  85346. if (overflow == 0) return;
  85347. Trace((stderr,"\nbit length overflow\n"));
  85348. /* This happens for example on obj2 and pic of the Calgary corpus */
  85349. /* Find the first bit length which could increase: */
  85350. do {
  85351. bits = max_length-1;
  85352. while (s->bl_count[bits] == 0) bits--;
  85353. s->bl_count[bits]--; /* move one leaf down the tree */
  85354. s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
  85355. s->bl_count[max_length]--;
  85356. /* The brother of the overflow item also moves one step up,
  85357. * but this does not affect bl_count[max_length]
  85358. */
  85359. overflow -= 2;
  85360. } while (overflow > 0);
  85361. /* Now recompute all bit lengths, scanning in increasing frequency.
  85362. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  85363. * lengths instead of fixing only the wrong ones. This idea is taken
  85364. * from 'ar' written by Haruhiko Okumura.)
  85365. */
  85366. for (bits = max_length; bits != 0; bits--) {
  85367. n = s->bl_count[bits];
  85368. while (n != 0) {
  85369. m = s->heap[--h];
  85370. if (m > max_code) continue;
  85371. if ((unsigned) tree[m].Len != (unsigned) bits) {
  85372. Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  85373. s->opt_len += ((long)bits - (long)tree[m].Len)
  85374. *(long)tree[m].Freq;
  85375. tree[m].Len = (ush)bits;
  85376. }
  85377. n--;
  85378. }
  85379. }
  85380. }
  85381. /* ===========================================================================
  85382. * Generate the codes for a given tree and bit counts (which need not be
  85383. * optimal).
  85384. * IN assertion: the array bl_count contains the bit length statistics for
  85385. * the given tree and the field len is set for all tree elements.
  85386. * OUT assertion: the field code is set for all tree elements of non
  85387. * zero code length.
  85388. */
  85389. local void gen_codes (ct_data *tree, /* the tree to decorate */
  85390. int max_code, /* largest code with non zero frequency */
  85391. ushf *bl_count) /* number of codes at each bit length */
  85392. {
  85393. ush next_code[MAX_BITS+1]; /* next code value for each bit length */
  85394. ush code = 0; /* running code value */
  85395. int bits; /* bit index */
  85396. int n; /* code index */
  85397. /* The distribution counts are first used to generate the code values
  85398. * without bit reversal.
  85399. */
  85400. for (bits = 1; bits <= MAX_BITS; bits++) {
  85401. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  85402. }
  85403. /* Check that the bit counts in bl_count are consistent. The last code
  85404. * must be all ones.
  85405. */
  85406. Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  85407. "inconsistent bit counts");
  85408. Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  85409. for (n = 0; n <= max_code; n++) {
  85410. int len = tree[n].Len;
  85411. if (len == 0) continue;
  85412. /* Now reverse the bits */
  85413. tree[n].Code = bi_reverse(next_code[len]++, len);
  85414. Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  85415. n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  85416. }
  85417. }
  85418. /* ===========================================================================
  85419. * Construct one Huffman tree and assigns the code bit strings and lengths.
  85420. * Update the total bit length for the current block.
  85421. * IN assertion: the field freq is set for all tree elements.
  85422. * OUT assertions: the fields len and code are set to the optimal bit length
  85423. * and corresponding code. The length opt_len is updated; static_len is
  85424. * also updated if stree is not null. The field max_code is set.
  85425. */
  85426. local void build_tree (deflate_state *s,
  85427. tree_desc *desc) /* the tree descriptor */
  85428. {
  85429. ct_data *tree = desc->dyn_tree;
  85430. const ct_data *stree = desc->stat_desc->static_tree;
  85431. int elems = desc->stat_desc->elems;
  85432. int n, m; /* iterate over heap elements */
  85433. int max_code = -1; /* largest code with non zero frequency */
  85434. int node; /* new node being created */
  85435. /* Construct the initial heap, with least frequent element in
  85436. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  85437. * heap[0] is not used.
  85438. */
  85439. s->heap_len = 0, s->heap_max = HEAP_SIZE;
  85440. for (n = 0; n < elems; n++) {
  85441. if (tree[n].Freq != 0) {
  85442. s->heap[++(s->heap_len)] = max_code = n;
  85443. s->depth[n] = 0;
  85444. } else {
  85445. tree[n].Len = 0;
  85446. }
  85447. }
  85448. /* The pkzip format requires that at least one distance code exists,
  85449. * and that at least one bit should be sent even if there is only one
  85450. * possible code. So to avoid special checks later on we force at least
  85451. * two codes of non zero frequency.
  85452. */
  85453. while (s->heap_len < 2) {
  85454. node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
  85455. tree[node].Freq = 1;
  85456. s->depth[node] = 0;
  85457. s->opt_len--; if (stree) s->static_len -= stree[node].Len;
  85458. /* node is 0 or 1 so it does not have extra bits */
  85459. }
  85460. desc->max_code = max_code;
  85461. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  85462. * establish sub-heaps of increasing lengths:
  85463. */
  85464. for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
  85465. /* Construct the Huffman tree by repeatedly combining the least two
  85466. * frequent nodes.
  85467. */
  85468. node = elems; /* next internal node of the tree */
  85469. do {
  85470. pqremove(s, tree, n); /* n = node of least frequency */
  85471. m = s->heap[SMALLEST]; /* m = node of next least frequency */
  85472. s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
  85473. s->heap[--(s->heap_max)] = m;
  85474. /* Create a new node father of n and m */
  85475. tree[node].Freq = tree[n].Freq + tree[m].Freq;
  85476. s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
  85477. s->depth[n] : s->depth[m]) + 1);
  85478. tree[n].Dad = tree[m].Dad = (ush)node;
  85479. #ifdef DUMP_BL_TREE
  85480. if (tree == s->bl_tree) {
  85481. fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
  85482. node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
  85483. }
  85484. #endif
  85485. /* and insert the new node in the heap */
  85486. s->heap[SMALLEST] = node++;
  85487. pqdownheap(s, tree, SMALLEST);
  85488. } while (s->heap_len >= 2);
  85489. s->heap[--(s->heap_max)] = s->heap[SMALLEST];
  85490. /* At this point, the fields freq and dad are set. We can now
  85491. * generate the bit lengths.
  85492. */
  85493. gen_bitlen(s, (tree_desc *)desc);
  85494. /* The field len is now set, we can generate the bit codes */
  85495. gen_codes ((ct_data *)tree, max_code, s->bl_count);
  85496. }
  85497. /* ===========================================================================
  85498. * Scan a literal or distance tree to determine the frequencies of the codes
  85499. * in the bit length tree.
  85500. */
  85501. local void scan_tree (deflate_state *s,
  85502. ct_data *tree, /* the tree to be scanned */
  85503. int max_code) /* and its largest code of non zero frequency */
  85504. {
  85505. int n; /* iterates over all tree elements */
  85506. int prevlen = -1; /* last emitted length */
  85507. int curlen; /* length of current code */
  85508. int nextlen = tree[0].Len; /* length of next code */
  85509. int count = 0; /* repeat count of the current code */
  85510. int max_count = 7; /* max repeat count */
  85511. int min_count = 4; /* min repeat count */
  85512. if (nextlen == 0) max_count = 138, min_count = 3;
  85513. tree[max_code+1].Len = (ush)0xffff; /* guard */
  85514. for (n = 0; n <= max_code; n++) {
  85515. curlen = nextlen; nextlen = tree[n+1].Len;
  85516. if (++count < max_count && curlen == nextlen) {
  85517. continue;
  85518. } else if (count < min_count) {
  85519. s->bl_tree[curlen].Freq += count;
  85520. } else if (curlen != 0) {
  85521. if (curlen != prevlen) s->bl_tree[curlen].Freq++;
  85522. s->bl_tree[REP_3_6].Freq++;
  85523. } else if (count <= 10) {
  85524. s->bl_tree[REPZ_3_10].Freq++;
  85525. } else {
  85526. s->bl_tree[REPZ_11_138].Freq++;
  85527. }
  85528. count = 0; prevlen = curlen;
  85529. if (nextlen == 0) {
  85530. max_count = 138, min_count = 3;
  85531. } else if (curlen == nextlen) {
  85532. max_count = 6, min_count = 3;
  85533. } else {
  85534. max_count = 7, min_count = 4;
  85535. }
  85536. }
  85537. }
  85538. /* ===========================================================================
  85539. * Send a literal or distance tree in compressed form, using the codes in
  85540. * bl_tree.
  85541. */
  85542. local void send_tree (deflate_state *s,
  85543. ct_data *tree, /* the tree to be scanned */
  85544. int max_code) /* and its largest code of non zero frequency */
  85545. {
  85546. int n; /* iterates over all tree elements */
  85547. int prevlen = -1; /* last emitted length */
  85548. int curlen; /* length of current code */
  85549. int nextlen = tree[0].Len; /* length of next code */
  85550. int count = 0; /* repeat count of the current code */
  85551. int max_count = 7; /* max repeat count */
  85552. int min_count = 4; /* min repeat count */
  85553. /* tree[max_code+1].Len = -1; */ /* guard already set */
  85554. if (nextlen == 0) max_count = 138, min_count = 3;
  85555. for (n = 0; n <= max_code; n++) {
  85556. curlen = nextlen; nextlen = tree[n+1].Len;
  85557. if (++count < max_count && curlen == nextlen) {
  85558. continue;
  85559. } else if (count < min_count) {
  85560. do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
  85561. } else if (curlen != 0) {
  85562. if (curlen != prevlen) {
  85563. send_code(s, curlen, s->bl_tree); count--;
  85564. }
  85565. Assert(count >= 3 && count <= 6, " 3_6?");
  85566. send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
  85567. } else if (count <= 10) {
  85568. send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
  85569. } else {
  85570. send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
  85571. }
  85572. count = 0; prevlen = curlen;
  85573. if (nextlen == 0) {
  85574. max_count = 138, min_count = 3;
  85575. } else if (curlen == nextlen) {
  85576. max_count = 6, min_count = 3;
  85577. } else {
  85578. max_count = 7, min_count = 4;
  85579. }
  85580. }
  85581. }
  85582. /* ===========================================================================
  85583. * Construct the Huffman tree for the bit lengths and return the index in
  85584. * bl_order of the last bit length code to send.
  85585. */
  85586. local int build_bl_tree (deflate_state *s)
  85587. {
  85588. int max_blindex; /* index of last bit length code of non zero freq */
  85589. /* Determine the bit length frequencies for literal and distance trees */
  85590. scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
  85591. scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
  85592. /* Build the bit length tree: */
  85593. build_tree(s, (tree_desc *)(&(s->bl_desc)));
  85594. /* opt_len now includes the length of the tree representations, except
  85595. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  85596. */
  85597. /* Determine the number of bit length codes to send. The pkzip format
  85598. * requires that at least 4 bit length codes be sent. (appnote.txt says
  85599. * 3 but the actual value used is 4.)
  85600. */
  85601. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  85602. if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
  85603. }
  85604. /* Update opt_len to include the bit length tree and counts */
  85605. s->opt_len += 3*(max_blindex+1) + 5+5+4;
  85606. Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  85607. s->opt_len, s->static_len));
  85608. return max_blindex;
  85609. }
  85610. /* ===========================================================================
  85611. * Send the header for a block using dynamic Huffman trees: the counts, the
  85612. * lengths of the bit length codes, the literal tree and the distance tree.
  85613. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  85614. */
  85615. local void send_all_trees (deflate_state *s,
  85616. int lcodes, int dcodes, int blcodes) /* number of codes for each tree */
  85617. {
  85618. int rank; /* index in bl_order */
  85619. Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  85620. Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  85621. "too many codes");
  85622. Tracev((stderr, "\nbl counts: "));
  85623. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  85624. send_bits(s, dcodes-1, 5);
  85625. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  85626. for (rank = 0; rank < blcodes; rank++) {
  85627. Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  85628. send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
  85629. }
  85630. Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  85631. send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
  85632. Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  85633. send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
  85634. Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  85635. }
  85636. /* ===========================================================================
  85637. * Send a stored block
  85638. */
  85639. void _tr_stored_block (deflate_state *s, charf *buf, ulg stored_len, int eof)
  85640. {
  85641. send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */
  85642. #ifdef DEBUG
  85643. s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
  85644. s->compressed_len += (stored_len + 4) << 3;
  85645. #endif
  85646. copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
  85647. }
  85648. /* ===========================================================================
  85649. * Send one empty static block to give enough lookahead for inflate.
  85650. * This takes 10 bits, of which 7 may remain in the bit buffer.
  85651. * The current inflate code requires 9 bits of lookahead. If the
  85652. * last two codes for the previous block (real code plus EOB) were coded
  85653. * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
  85654. * the last real code. In this case we send two empty static blocks instead
  85655. * of one. (There are no problems if the previous block is stored or fixed.)
  85656. * To simplify the code, we assume the worst case of last real code encoded
  85657. * on one bit only.
  85658. */
  85659. void _tr_align (deflate_state *s)
  85660. {
  85661. send_bits(s, STATIC_TREES<<1, 3);
  85662. send_code(s, END_BLOCK, static_ltree);
  85663. #ifdef DEBUG
  85664. s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
  85665. #endif
  85666. bi_flush(s);
  85667. /* Of the 10 bits for the empty block, we have already sent
  85668. * (10 - bi_valid) bits. The lookahead for the last real code (before
  85669. * the EOB of the previous block) was thus at least one plus the length
  85670. * of the EOB plus what we have just sent of the empty static block.
  85671. */
  85672. if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
  85673. send_bits(s, STATIC_TREES<<1, 3);
  85674. send_code(s, END_BLOCK, static_ltree);
  85675. #ifdef DEBUG
  85676. s->compressed_len += 10L;
  85677. #endif
  85678. bi_flush(s);
  85679. }
  85680. s->last_eob_len = 7;
  85681. }
  85682. /* ===========================================================================
  85683. * Determine the best encoding for the current block: dynamic trees, static
  85684. * trees or store, and output the encoded block to the zip file.
  85685. */
  85686. void _tr_flush_block (deflate_state *s,
  85687. charf *buf, /* input block, or NULL if too old */
  85688. ulg stored_len, /* length of input block */
  85689. int eof) /* true if this is the last block for a file */
  85690. {
  85691. ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  85692. int max_blindex = 0; /* index of last bit length code of non zero freq */
  85693. /* Build the Huffman trees unless a stored block is forced */
  85694. if (s->level > 0) {
  85695. /* Check if the file is binary or text */
  85696. if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN)
  85697. set_data_type(s);
  85698. /* Construct the literal and distance trees */
  85699. build_tree(s, (tree_desc *)(&(s->l_desc)));
  85700. Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  85701. s->static_len));
  85702. build_tree(s, (tree_desc *)(&(s->d_desc)));
  85703. Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  85704. s->static_len));
  85705. /* At this point, opt_len and static_len are the total bit lengths of
  85706. * the compressed block data, excluding the tree representations.
  85707. */
  85708. /* Build the bit length tree for the above two trees, and get the index
  85709. * in bl_order of the last bit length code to send.
  85710. */
  85711. max_blindex = build_bl_tree(s);
  85712. /* Determine the best encoding. Compute the block lengths in bytes. */
  85713. opt_lenb = (s->opt_len+3+7)>>3;
  85714. static_lenb = (s->static_len+3+7)>>3;
  85715. Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  85716. opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  85717. s->last_lit));
  85718. if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
  85719. } else {
  85720. Assert(buf != (char*)0, "lost buf");
  85721. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  85722. }
  85723. #ifdef FORCE_STORED
  85724. if (buf != (char*)0) { /* force stored block */
  85725. #else
  85726. if (stored_len+4 <= opt_lenb && buf != (char*)0) {
  85727. /* 4: two words for the lengths */
  85728. #endif
  85729. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  85730. * Otherwise we can't have processed more than WSIZE input bytes since
  85731. * the last block flush, because compression would have been
  85732. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  85733. * transform a block into a stored block.
  85734. */
  85735. _tr_stored_block(s, buf, stored_len, eof);
  85736. #ifdef FORCE_STATIC
  85737. } else if (static_lenb >= 0) { /* force static trees */
  85738. #else
  85739. } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
  85740. #endif
  85741. send_bits(s, (STATIC_TREES<<1)+eof, 3);
  85742. compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
  85743. #ifdef DEBUG
  85744. s->compressed_len += 3 + s->static_len;
  85745. #endif
  85746. } else {
  85747. send_bits(s, (DYN_TREES<<1)+eof, 3);
  85748. send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
  85749. max_blindex+1);
  85750. compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
  85751. #ifdef DEBUG
  85752. s->compressed_len += 3 + s->opt_len;
  85753. #endif
  85754. }
  85755. Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  85756. /* The above check is made mod 2^32, for files larger than 512 MB
  85757. * and uLong implemented on 32 bits.
  85758. */
  85759. init_block(s);
  85760. if (eof) {
  85761. bi_windup(s);
  85762. #ifdef DEBUG
  85763. s->compressed_len += 7; /* align on byte boundary */
  85764. #endif
  85765. }
  85766. Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  85767. s->compressed_len-7*eof));
  85768. }
  85769. /* ===========================================================================
  85770. * Save the match info and tally the frequency counts. Return true if
  85771. * the current block must be flushed.
  85772. */
  85773. int _tr_tally (deflate_state *s,
  85774. unsigned dist, /* distance of matched string */
  85775. unsigned lc) /* match length-MIN_MATCH or unmatched char (if dist==0) */
  85776. {
  85777. s->d_buf[s->last_lit] = (ush)dist;
  85778. s->l_buf[s->last_lit++] = (uch)lc;
  85779. if (dist == 0) {
  85780. /* lc is the unmatched char */
  85781. s->dyn_ltree[lc].Freq++;
  85782. } else {
  85783. s->matches++;
  85784. /* Here, lc is the match length - MIN_MATCH */
  85785. dist--; /* dist = match distance - 1 */
  85786. Assert((ush)dist < (ush)MAX_DIST(s) &&
  85787. (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  85788. (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  85789. s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
  85790. s->dyn_dtree[d_code(dist)].Freq++;
  85791. }
  85792. #ifdef TRUNCATE_BLOCK
  85793. /* Try to guess if it is profitable to stop the current block here */
  85794. if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
  85795. /* Compute an upper bound for the compressed length */
  85796. ulg out_length = (ulg)s->last_lit*8L;
  85797. ulg in_length = (ulg)((long)s->strstart - s->block_start);
  85798. int dcode;
  85799. for (dcode = 0; dcode < D_CODES; dcode++) {
  85800. out_length += (ulg)s->dyn_dtree[dcode].Freq *
  85801. (5L+extra_dbits[dcode]);
  85802. }
  85803. out_length >>= 3;
  85804. Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  85805. s->last_lit, in_length, out_length,
  85806. 100L - out_length*100L/in_length));
  85807. if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
  85808. }
  85809. #endif
  85810. return (s->last_lit == s->lit_bufsize-1);
  85811. /* We avoid equality with lit_bufsize because of wraparound at 64K
  85812. * on 16 bit machines and because stored blocks are restricted to
  85813. * 64K-1 bytes.
  85814. */
  85815. }
  85816. /* ===========================================================================
  85817. * Send the block data compressed using the given Huffman trees
  85818. */
  85819. local void compress_block (deflate_state *s,
  85820. ct_data *ltree, /* literal tree */
  85821. ct_data *dtree) /* distance tree */
  85822. {
  85823. unsigned dist; /* distance of matched string */
  85824. int lc; /* match length or unmatched char (if dist == 0) */
  85825. unsigned lx = 0; /* running index in l_buf */
  85826. unsigned code; /* the code to send */
  85827. int extra; /* number of extra bits to send */
  85828. if (s->last_lit != 0) do {
  85829. dist = s->d_buf[lx];
  85830. lc = s->l_buf[lx++];
  85831. if (dist == 0) {
  85832. send_code(s, lc, ltree); /* send a literal byte */
  85833. Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  85834. } else {
  85835. /* Here, lc is the match length - MIN_MATCH */
  85836. code = _length_code[lc];
  85837. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  85838. extra = extra_lbits[code];
  85839. if (extra != 0) {
  85840. lc -= base_length[code];
  85841. send_bits(s, lc, extra); /* send the extra length bits */
  85842. }
  85843. dist--; /* dist is now the match distance - 1 */
  85844. code = d_code(dist);
  85845. Assert (code < D_CODES, "bad d_code");
  85846. send_code(s, code, dtree); /* send the distance code */
  85847. extra = extra_dbits[code];
  85848. if (extra != 0) {
  85849. dist -= base_dist[code];
  85850. send_bits(s, dist, extra); /* send the extra distance bits */
  85851. }
  85852. } /* literal or match pair ? */
  85853. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  85854. Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  85855. "pendingBuf overflow");
  85856. } while (lx < s->last_lit);
  85857. send_code(s, END_BLOCK, ltree);
  85858. s->last_eob_len = ltree[END_BLOCK].Len;
  85859. }
  85860. /* ===========================================================================
  85861. * Set the data type to BINARY or TEXT, using a crude approximation:
  85862. * set it to Z_TEXT if all symbols are either printable characters (33 to 255)
  85863. * or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise.
  85864. * IN assertion: the fields Freq of dyn_ltree are set.
  85865. */
  85866. local void set_data_type (deflate_state *s)
  85867. {
  85868. int n;
  85869. for (n = 0; n < 9; n++)
  85870. if (s->dyn_ltree[n].Freq != 0)
  85871. break;
  85872. if (n == 9)
  85873. for (n = 14; n < 32; n++)
  85874. if (s->dyn_ltree[n].Freq != 0)
  85875. break;
  85876. s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY;
  85877. }
  85878. /* ===========================================================================
  85879. * Reverse the first len bits of a code, using straightforward code (a faster
  85880. * method would use a table)
  85881. * IN assertion: 1 <= len <= 15
  85882. */
  85883. local unsigned bi_reverse (unsigned code, int len)
  85884. {
  85885. register unsigned res = 0;
  85886. do {
  85887. res |= code & 1;
  85888. code >>= 1, res <<= 1;
  85889. } while (--len > 0);
  85890. return res >> 1;
  85891. }
  85892. /* ===========================================================================
  85893. * Flush the bit buffer, keeping at most 7 bits in it.
  85894. */
  85895. local void bi_flush (deflate_state *s)
  85896. {
  85897. if (s->bi_valid == 16) {
  85898. put_short(s, s->bi_buf);
  85899. s->bi_buf = 0;
  85900. s->bi_valid = 0;
  85901. } else if (s->bi_valid >= 8) {
  85902. put_byte(s, (Byte)s->bi_buf);
  85903. s->bi_buf >>= 8;
  85904. s->bi_valid -= 8;
  85905. }
  85906. }
  85907. /* ===========================================================================
  85908. * Flush the bit buffer and align the output on a byte boundary
  85909. */
  85910. local void bi_windup (deflate_state *s)
  85911. {
  85912. if (s->bi_valid > 8) {
  85913. put_short(s, s->bi_buf);
  85914. } else if (s->bi_valid > 0) {
  85915. put_byte(s, (Byte)s->bi_buf);
  85916. }
  85917. s->bi_buf = 0;
  85918. s->bi_valid = 0;
  85919. #ifdef DEBUG
  85920. s->bits_sent = (s->bits_sent+7) & ~7;
  85921. #endif
  85922. }
  85923. /* ===========================================================================
  85924. * Copy a stored block, storing first the length and its
  85925. * one's complement if requested.
  85926. */
  85927. local void copy_block(deflate_state *s,
  85928. charf *buf, /* the input data */
  85929. unsigned len, /* its length */
  85930. int header) /* true if block header must be written */
  85931. {
  85932. bi_windup(s); /* align on byte boundary */
  85933. s->last_eob_len = 8; /* enough lookahead for inflate */
  85934. if (header) {
  85935. put_short(s, (ush)len);
  85936. put_short(s, (ush)~len);
  85937. #ifdef DEBUG
  85938. s->bits_sent += 2*16;
  85939. #endif
  85940. }
  85941. #ifdef DEBUG
  85942. s->bits_sent += (ulg)len<<3;
  85943. #endif
  85944. while (len--) {
  85945. put_byte(s, *buf++);
  85946. }
  85947. }
  85948. /*** End of inlined file: trees.c ***/
  85949. /*** Start of inlined file: zutil.c ***/
  85950. /* @(#) $Id: zutil.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  85951. #ifndef NO_DUMMY_DECL
  85952. struct internal_state {int dummy;}; /* for buggy compilers */
  85953. #endif
  85954. const char * const z_errmsg[10] = {
  85955. "need dictionary", /* Z_NEED_DICT 2 */
  85956. "stream end", /* Z_STREAM_END 1 */
  85957. "", /* Z_OK 0 */
  85958. "file error", /* Z_ERRNO (-1) */
  85959. "stream error", /* Z_STREAM_ERROR (-2) */
  85960. "data error", /* Z_DATA_ERROR (-3) */
  85961. "insufficient memory", /* Z_MEM_ERROR (-4) */
  85962. "buffer error", /* Z_BUF_ERROR (-5) */
  85963. "incompatible version",/* Z_VERSION_ERROR (-6) */
  85964. ""};
  85965. /*const char * ZEXPORT zlibVersion()
  85966. {
  85967. return ZLIB_VERSION;
  85968. }
  85969. uLong ZEXPORT zlibCompileFlags()
  85970. {
  85971. uLong flags;
  85972. flags = 0;
  85973. switch (sizeof(uInt)) {
  85974. case 2: break;
  85975. case 4: flags += 1; break;
  85976. case 8: flags += 2; break;
  85977. default: flags += 3;
  85978. }
  85979. switch (sizeof(uLong)) {
  85980. case 2: break;
  85981. case 4: flags += 1 << 2; break;
  85982. case 8: flags += 2 << 2; break;
  85983. default: flags += 3 << 2;
  85984. }
  85985. switch (sizeof(voidpf)) {
  85986. case 2: break;
  85987. case 4: flags += 1 << 4; break;
  85988. case 8: flags += 2 << 4; break;
  85989. default: flags += 3 << 4;
  85990. }
  85991. switch (sizeof(z_off_t)) {
  85992. case 2: break;
  85993. case 4: flags += 1 << 6; break;
  85994. case 8: flags += 2 << 6; break;
  85995. default: flags += 3 << 6;
  85996. }
  85997. #ifdef DEBUG
  85998. flags += 1 << 8;
  85999. #endif
  86000. #if defined(ASMV) || defined(ASMINF)
  86001. flags += 1 << 9;
  86002. #endif
  86003. #ifdef ZLIB_WINAPI
  86004. flags += 1 << 10;
  86005. #endif
  86006. #ifdef BUILDFIXED
  86007. flags += 1 << 12;
  86008. #endif
  86009. #ifdef DYNAMIC_CRC_TABLE
  86010. flags += 1 << 13;
  86011. #endif
  86012. #ifdef NO_GZCOMPRESS
  86013. flags += 1L << 16;
  86014. #endif
  86015. #ifdef NO_GZIP
  86016. flags += 1L << 17;
  86017. #endif
  86018. #ifdef PKZIP_BUG_WORKAROUND
  86019. flags += 1L << 20;
  86020. #endif
  86021. #ifdef FASTEST
  86022. flags += 1L << 21;
  86023. #endif
  86024. #ifdef STDC
  86025. # ifdef NO_vsnprintf
  86026. flags += 1L << 25;
  86027. # ifdef HAS_vsprintf_void
  86028. flags += 1L << 26;
  86029. # endif
  86030. # else
  86031. # ifdef HAS_vsnprintf_void
  86032. flags += 1L << 26;
  86033. # endif
  86034. # endif
  86035. #else
  86036. flags += 1L << 24;
  86037. # ifdef NO_snprintf
  86038. flags += 1L << 25;
  86039. # ifdef HAS_sprintf_void
  86040. flags += 1L << 26;
  86041. # endif
  86042. # else
  86043. # ifdef HAS_snprintf_void
  86044. flags += 1L << 26;
  86045. # endif
  86046. # endif
  86047. #endif
  86048. return flags;
  86049. }*/
  86050. #ifdef DEBUG
  86051. # ifndef verbose
  86052. # define verbose 0
  86053. # endif
  86054. int z_verbose = verbose;
  86055. void z_error (const char *m)
  86056. {
  86057. fprintf(stderr, "%s\n", m);
  86058. exit(1);
  86059. }
  86060. #endif
  86061. /* exported to allow conversion of error code to string for compress() and
  86062. * uncompress()
  86063. */
  86064. const char * ZEXPORT zError(int err)
  86065. {
  86066. return ERR_MSG(err);
  86067. }
  86068. #if defined(_WIN32_WCE)
  86069. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  86070. * errno. We define it as a global variable to simplify porting.
  86071. * Its value is always 0 and should not be used.
  86072. */
  86073. int errno = 0;
  86074. #endif
  86075. #ifndef HAVE_MEMCPY
  86076. void zmemcpy(dest, source, len)
  86077. Bytef* dest;
  86078. const Bytef* source;
  86079. uInt len;
  86080. {
  86081. if (len == 0) return;
  86082. do {
  86083. *dest++ = *source++; /* ??? to be unrolled */
  86084. } while (--len != 0);
  86085. }
  86086. int zmemcmp(s1, s2, len)
  86087. const Bytef* s1;
  86088. const Bytef* s2;
  86089. uInt len;
  86090. {
  86091. uInt j;
  86092. for (j = 0; j < len; j++) {
  86093. if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1;
  86094. }
  86095. return 0;
  86096. }
  86097. void zmemzero(dest, len)
  86098. Bytef* dest;
  86099. uInt len;
  86100. {
  86101. if (len == 0) return;
  86102. do {
  86103. *dest++ = 0; /* ??? to be unrolled */
  86104. } while (--len != 0);
  86105. }
  86106. #endif
  86107. #ifdef SYS16BIT
  86108. #ifdef __TURBOC__
  86109. /* Turbo C in 16-bit mode */
  86110. # define MY_ZCALLOC
  86111. /* Turbo C malloc() does not allow dynamic allocation of 64K bytes
  86112. * and farmalloc(64K) returns a pointer with an offset of 8, so we
  86113. * must fix the pointer. Warning: the pointer must be put back to its
  86114. * original form in order to free it, use zcfree().
  86115. */
  86116. #define MAX_PTR 10
  86117. /* 10*64K = 640K */
  86118. local int next_ptr = 0;
  86119. typedef struct ptr_table_s {
  86120. voidpf org_ptr;
  86121. voidpf new_ptr;
  86122. } ptr_table;
  86123. local ptr_table table[MAX_PTR];
  86124. /* This table is used to remember the original form of pointers
  86125. * to large buffers (64K). Such pointers are normalized with a zero offset.
  86126. * Since MSDOS is not a preemptive multitasking OS, this table is not
  86127. * protected from concurrent access. This hack doesn't work anyway on
  86128. * a protected system like OS/2. Use Microsoft C instead.
  86129. */
  86130. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  86131. {
  86132. voidpf buf = opaque; /* just to make some compilers happy */
  86133. ulg bsize = (ulg)items*size;
  86134. /* If we allocate less than 65520 bytes, we assume that farmalloc
  86135. * will return a usable pointer which doesn't have to be normalized.
  86136. */
  86137. if (bsize < 65520L) {
  86138. buf = farmalloc(bsize);
  86139. if (*(ush*)&buf != 0) return buf;
  86140. } else {
  86141. buf = farmalloc(bsize + 16L);
  86142. }
  86143. if (buf == NULL || next_ptr >= MAX_PTR) return NULL;
  86144. table[next_ptr].org_ptr = buf;
  86145. /* Normalize the pointer to seg:0 */
  86146. *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4;
  86147. *(ush*)&buf = 0;
  86148. table[next_ptr++].new_ptr = buf;
  86149. return buf;
  86150. }
  86151. void zcfree (voidpf opaque, voidpf ptr)
  86152. {
  86153. int n;
  86154. if (*(ush*)&ptr != 0) { /* object < 64K */
  86155. farfree(ptr);
  86156. return;
  86157. }
  86158. /* Find the original pointer */
  86159. for (n = 0; n < next_ptr; n++) {
  86160. if (ptr != table[n].new_ptr) continue;
  86161. farfree(table[n].org_ptr);
  86162. while (++n < next_ptr) {
  86163. table[n-1] = table[n];
  86164. }
  86165. next_ptr--;
  86166. return;
  86167. }
  86168. ptr = opaque; /* just to make some compilers happy */
  86169. Assert(0, "zcfree: ptr not found");
  86170. }
  86171. #endif /* __TURBOC__ */
  86172. #ifdef M_I86
  86173. /* Microsoft C in 16-bit mode */
  86174. # define MY_ZCALLOC
  86175. #if (!defined(_MSC_VER) || (_MSC_VER <= 600))
  86176. # define _halloc halloc
  86177. # define _hfree hfree
  86178. #endif
  86179. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  86180. {
  86181. if (opaque) opaque = 0; /* to make compiler happy */
  86182. return _halloc((long)items, size);
  86183. }
  86184. void zcfree (voidpf opaque, voidpf ptr)
  86185. {
  86186. if (opaque) opaque = 0; /* to make compiler happy */
  86187. _hfree(ptr);
  86188. }
  86189. #endif /* M_I86 */
  86190. #endif /* SYS16BIT */
  86191. #ifndef MY_ZCALLOC /* Any system without a special alloc function */
  86192. #ifndef STDC
  86193. extern voidp malloc OF((uInt size));
  86194. extern voidp calloc OF((uInt items, uInt size));
  86195. extern void free OF((voidpf ptr));
  86196. #endif
  86197. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  86198. {
  86199. if (opaque) items += size - size; /* make compiler happy */
  86200. return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) :
  86201. (voidpf)calloc(items, size);
  86202. }
  86203. void zcfree (voidpf opaque, voidpf ptr)
  86204. {
  86205. free(ptr);
  86206. if (opaque) return; /* make compiler happy */
  86207. }
  86208. #endif /* MY_ZCALLOC */
  86209. /*** End of inlined file: zutil.c ***/
  86210. #undef Byte
  86211. #else
  86212. #include <zlib.h>
  86213. #endif
  86214. }
  86215. #if JUCE_MSVC
  86216. #pragma warning (pop)
  86217. #endif
  86218. BEGIN_JUCE_NAMESPACE
  86219. // internal helper object that holds the zlib structures so they don't have to be
  86220. // included publicly.
  86221. class GZIPDecompressHelper
  86222. {
  86223. public:
  86224. GZIPDecompressHelper (const bool noWrap)
  86225. : finished (true),
  86226. needsDictionary (false),
  86227. error (true),
  86228. streamIsValid (false),
  86229. data (0),
  86230. dataSize (0)
  86231. {
  86232. using namespace zlibNamespace;
  86233. zerostruct (stream);
  86234. streamIsValid = (inflateInit2 (&stream, noWrap ? -MAX_WBITS : MAX_WBITS) == Z_OK);
  86235. finished = error = ! streamIsValid;
  86236. }
  86237. ~GZIPDecompressHelper()
  86238. {
  86239. using namespace zlibNamespace;
  86240. if (streamIsValid)
  86241. inflateEnd (&stream);
  86242. }
  86243. bool needsInput() const throw() { return dataSize <= 0; }
  86244. void setInput (uint8* const data_, const int size) throw()
  86245. {
  86246. data = data_;
  86247. dataSize = size;
  86248. }
  86249. int doNextBlock (uint8* const dest, const int destSize)
  86250. {
  86251. using namespace zlibNamespace;
  86252. if (streamIsValid && data != 0 && ! finished)
  86253. {
  86254. stream.next_in = data;
  86255. stream.next_out = dest;
  86256. stream.avail_in = dataSize;
  86257. stream.avail_out = destSize;
  86258. switch (inflate (&stream, Z_PARTIAL_FLUSH))
  86259. {
  86260. case Z_STREAM_END:
  86261. finished = true;
  86262. // deliberate fall-through
  86263. case Z_OK:
  86264. data += dataSize - stream.avail_in;
  86265. dataSize = stream.avail_in;
  86266. return destSize - stream.avail_out;
  86267. case Z_NEED_DICT:
  86268. needsDictionary = true;
  86269. data += dataSize - stream.avail_in;
  86270. dataSize = stream.avail_in;
  86271. break;
  86272. case Z_DATA_ERROR:
  86273. case Z_MEM_ERROR:
  86274. error = true;
  86275. default:
  86276. break;
  86277. }
  86278. }
  86279. return 0;
  86280. }
  86281. bool finished, needsDictionary, error, streamIsValid;
  86282. private:
  86283. zlibNamespace::z_stream stream;
  86284. uint8* data;
  86285. int dataSize;
  86286. GZIPDecompressHelper (const GZIPDecompressHelper&);
  86287. GZIPDecompressHelper& operator= (const GZIPDecompressHelper&);
  86288. };
  86289. const int gzipDecompBufferSize = 32768;
  86290. GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream* const sourceStream_,
  86291. const bool deleteSourceWhenDestroyed,
  86292. const bool noWrap_,
  86293. const int64 uncompressedStreamLength_)
  86294. : sourceStream (sourceStream_),
  86295. streamToDelete (deleteSourceWhenDestroyed ? sourceStream_ : 0),
  86296. uncompressedStreamLength (uncompressedStreamLength_),
  86297. noWrap (noWrap_),
  86298. isEof (false),
  86299. activeBufferSize (0),
  86300. originalSourcePos (sourceStream_->getPosition()),
  86301. currentPos (0),
  86302. buffer (gzipDecompBufferSize),
  86303. helper (new GZIPDecompressHelper (noWrap_))
  86304. {
  86305. }
  86306. GZIPDecompressorInputStream::~GZIPDecompressorInputStream()
  86307. {
  86308. }
  86309. int64 GZIPDecompressorInputStream::getTotalLength()
  86310. {
  86311. return uncompressedStreamLength;
  86312. }
  86313. int GZIPDecompressorInputStream::read (void* destBuffer, int howMany)
  86314. {
  86315. if ((howMany > 0) && ! isEof)
  86316. {
  86317. jassert (destBuffer != 0);
  86318. if (destBuffer != 0)
  86319. {
  86320. int numRead = 0;
  86321. uint8* d = static_cast <uint8*> (destBuffer);
  86322. while (! helper->error)
  86323. {
  86324. const int n = helper->doNextBlock (d, howMany);
  86325. currentPos += n;
  86326. if (n == 0)
  86327. {
  86328. if (helper->finished || helper->needsDictionary)
  86329. {
  86330. isEof = true;
  86331. return numRead;
  86332. }
  86333. if (helper->needsInput())
  86334. {
  86335. activeBufferSize = sourceStream->read (buffer, gzipDecompBufferSize);
  86336. if (activeBufferSize > 0)
  86337. {
  86338. helper->setInput (buffer, activeBufferSize);
  86339. }
  86340. else
  86341. {
  86342. isEof = true;
  86343. return numRead;
  86344. }
  86345. }
  86346. }
  86347. else
  86348. {
  86349. numRead += n;
  86350. howMany -= n;
  86351. d += n;
  86352. if (howMany <= 0)
  86353. return numRead;
  86354. }
  86355. }
  86356. }
  86357. }
  86358. return 0;
  86359. }
  86360. bool GZIPDecompressorInputStream::isExhausted()
  86361. {
  86362. return helper->error || isEof;
  86363. }
  86364. int64 GZIPDecompressorInputStream::getPosition()
  86365. {
  86366. return currentPos;
  86367. }
  86368. bool GZIPDecompressorInputStream::setPosition (int64 newPos)
  86369. {
  86370. if (newPos < currentPos)
  86371. {
  86372. // to go backwards, reset the stream and start again..
  86373. isEof = false;
  86374. activeBufferSize = 0;
  86375. currentPos = 0;
  86376. helper = new GZIPDecompressHelper (noWrap);
  86377. sourceStream->setPosition (originalSourcePos);
  86378. }
  86379. skipNextBytes (newPos - currentPos);
  86380. return true;
  86381. }
  86382. END_JUCE_NAMESPACE
  86383. /*** End of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  86384. #endif
  86385. #if JUCE_BUILD_NATIVE && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  86386. /*** Start of inlined file: juce_FlacAudioFormat.cpp ***/
  86387. #if JUCE_USE_FLAC
  86388. #if JUCE_WINDOWS
  86389. #include <windows.h>
  86390. #endif
  86391. namespace FlacNamespace
  86392. {
  86393. #if JUCE_INCLUDE_FLAC_CODE
  86394. #if JUCE_MSVC
  86395. #pragma warning (disable : 4505) // (unreferenced static function removal warning)
  86396. #endif
  86397. #define FLAC__NO_DLL 1
  86398. #if ! defined (SIZE_MAX)
  86399. #define SIZE_MAX 0xffffffff
  86400. #endif
  86401. #define __STDC_LIMIT_MACROS 1
  86402. /*** Start of inlined file: all.h ***/
  86403. #ifndef FLAC__ALL_H
  86404. #define FLAC__ALL_H
  86405. /*** Start of inlined file: export.h ***/
  86406. #ifndef FLAC__EXPORT_H
  86407. #define FLAC__EXPORT_H
  86408. /** \file include/FLAC/export.h
  86409. *
  86410. * \brief
  86411. * This module contains #defines and symbols for exporting function
  86412. * calls, and providing version information and compiled-in features.
  86413. *
  86414. * See the \link flac_export export \endlink module.
  86415. */
  86416. /** \defgroup flac_export FLAC/export.h: export symbols
  86417. * \ingroup flac
  86418. *
  86419. * \brief
  86420. * This module contains #defines and symbols for exporting function
  86421. * calls, and providing version information and compiled-in features.
  86422. *
  86423. * If you are compiling with MSVC and will link to the static library
  86424. * (libFLAC.lib) you should define FLAC__NO_DLL in your project to
  86425. * make sure the symbols are exported properly.
  86426. *
  86427. * \{
  86428. */
  86429. #if defined(FLAC__NO_DLL) || !defined(_MSC_VER)
  86430. #define FLAC_API
  86431. #else
  86432. #ifdef FLAC_API_EXPORTS
  86433. #define FLAC_API _declspec(dllexport)
  86434. #else
  86435. #define FLAC_API _declspec(dllimport)
  86436. #endif
  86437. #endif
  86438. /** These #defines will mirror the libtool-based library version number, see
  86439. * http://www.gnu.org/software/libtool/manual.html#Libtool-versioning
  86440. */
  86441. #define FLAC_API_VERSION_CURRENT 10
  86442. #define FLAC_API_VERSION_REVISION 0 /**< see above */
  86443. #define FLAC_API_VERSION_AGE 2 /**< see above */
  86444. #ifdef __cplusplus
  86445. extern "C" {
  86446. #endif
  86447. /** \c 1 if the library has been compiled with support for Ogg FLAC, else \c 0. */
  86448. extern FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC;
  86449. #ifdef __cplusplus
  86450. }
  86451. #endif
  86452. /* \} */
  86453. #endif
  86454. /*** End of inlined file: export.h ***/
  86455. /*** Start of inlined file: assert.h ***/
  86456. #ifndef FLAC__ASSERT_H
  86457. #define FLAC__ASSERT_H
  86458. /* we need this since some compilers (like MSVC) leave assert()s on release code (and we don't want to use their ASSERT) */
  86459. #ifdef DEBUG
  86460. #include <assert.h>
  86461. #define FLAC__ASSERT(x) assert(x)
  86462. #define FLAC__ASSERT_DECLARATION(x) x
  86463. #else
  86464. #define FLAC__ASSERT(x)
  86465. #define FLAC__ASSERT_DECLARATION(x)
  86466. #endif
  86467. #endif
  86468. /*** End of inlined file: assert.h ***/
  86469. /*** Start of inlined file: callback.h ***/
  86470. #ifndef FLAC__CALLBACK_H
  86471. #define FLAC__CALLBACK_H
  86472. /*** Start of inlined file: ordinals.h ***/
  86473. #ifndef FLAC__ORDINALS_H
  86474. #define FLAC__ORDINALS_H
  86475. #if !(defined(_MSC_VER) || defined(__BORLANDC__) || defined(__EMX__))
  86476. #include <inttypes.h>
  86477. #endif
  86478. typedef signed char FLAC__int8;
  86479. typedef unsigned char FLAC__uint8;
  86480. #if defined(_MSC_VER) || defined(__BORLANDC__)
  86481. typedef __int16 FLAC__int16;
  86482. typedef __int32 FLAC__int32;
  86483. typedef __int64 FLAC__int64;
  86484. typedef unsigned __int16 FLAC__uint16;
  86485. typedef unsigned __int32 FLAC__uint32;
  86486. typedef unsigned __int64 FLAC__uint64;
  86487. #elif defined(__EMX__)
  86488. typedef short FLAC__int16;
  86489. typedef long FLAC__int32;
  86490. typedef long long FLAC__int64;
  86491. typedef unsigned short FLAC__uint16;
  86492. typedef unsigned long FLAC__uint32;
  86493. typedef unsigned long long FLAC__uint64;
  86494. #else
  86495. typedef int16_t FLAC__int16;
  86496. typedef int32_t FLAC__int32;
  86497. typedef int64_t FLAC__int64;
  86498. typedef uint16_t FLAC__uint16;
  86499. typedef uint32_t FLAC__uint32;
  86500. typedef uint64_t FLAC__uint64;
  86501. #endif
  86502. typedef int FLAC__bool;
  86503. typedef FLAC__uint8 FLAC__byte;
  86504. #ifdef true
  86505. #undef true
  86506. #endif
  86507. #ifdef false
  86508. #undef false
  86509. #endif
  86510. #ifndef __cplusplus
  86511. #define true 1
  86512. #define false 0
  86513. #endif
  86514. #endif
  86515. /*** End of inlined file: ordinals.h ***/
  86516. #include <stdlib.h> /* for size_t */
  86517. /** \file include/FLAC/callback.h
  86518. *
  86519. * \brief
  86520. * This module defines the structures for describing I/O callbacks
  86521. * to the other FLAC interfaces.
  86522. *
  86523. * See the detailed documentation for callbacks in the
  86524. * \link flac_callbacks callbacks \endlink module.
  86525. */
  86526. /** \defgroup flac_callbacks FLAC/callback.h: I/O callback structures
  86527. * \ingroup flac
  86528. *
  86529. * \brief
  86530. * This module defines the structures for describing I/O callbacks
  86531. * to the other FLAC interfaces.
  86532. *
  86533. * The purpose of the I/O callback functions is to create a common way
  86534. * for the metadata interfaces to handle I/O.
  86535. *
  86536. * Originally the metadata interfaces required filenames as the way of
  86537. * specifying FLAC files to operate on. This is problematic in some
  86538. * environments so there is an additional option to specify a set of
  86539. * callbacks for doing I/O on the FLAC file, instead of the filename.
  86540. *
  86541. * In addition to the callbacks, a FLAC__IOHandle type is defined as an
  86542. * opaque structure for a data source.
  86543. *
  86544. * The callback function prototypes are similar (but not identical) to the
  86545. * stdio functions fread, fwrite, fseek, ftell, feof, and fclose. If you use
  86546. * stdio streams to implement the callbacks, you can pass fread, fwrite, and
  86547. * fclose anywhere a FLAC__IOCallback_Read, FLAC__IOCallback_Write, or
  86548. * FLAC__IOCallback_Close is required, and a FILE* anywhere a FLAC__IOHandle
  86549. * is required. \warning You generally CANNOT directly use fseek or ftell
  86550. * for FLAC__IOCallback_Seek or FLAC__IOCallback_Tell since on most systems
  86551. * these use 32-bit offsets and FLAC requires 64-bit offsets to deal with
  86552. * large files. You will have to find an equivalent function (e.g. ftello),
  86553. * or write a wrapper. The same is true for feof() since this is usually
  86554. * implemented as a macro, not as a function whose address can be taken.
  86555. *
  86556. * \{
  86557. */
  86558. #ifdef __cplusplus
  86559. extern "C" {
  86560. #endif
  86561. /** This is the opaque handle type used by the callbacks. Typically
  86562. * this is a \c FILE* or address of a file descriptor.
  86563. */
  86564. typedef void* FLAC__IOHandle;
  86565. /** Signature for the read callback.
  86566. * The signature and semantics match POSIX fread() implementations
  86567. * and can generally be used interchangeably.
  86568. *
  86569. * \param ptr The address of the read buffer.
  86570. * \param size The size of the records to be read.
  86571. * \param nmemb The number of records to be read.
  86572. * \param handle The handle to the data source.
  86573. * \retval size_t
  86574. * The number of records read.
  86575. */
  86576. typedef size_t (*FLAC__IOCallback_Read) (void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  86577. /** Signature for the write callback.
  86578. * The signature and semantics match POSIX fwrite() implementations
  86579. * and can generally be used interchangeably.
  86580. *
  86581. * \param ptr The address of the write buffer.
  86582. * \param size The size of the records to be written.
  86583. * \param nmemb The number of records to be written.
  86584. * \param handle The handle to the data source.
  86585. * \retval size_t
  86586. * The number of records written.
  86587. */
  86588. typedef size_t (*FLAC__IOCallback_Write) (const void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  86589. /** Signature for the seek callback.
  86590. * The signature and semantics mostly match POSIX fseek() WITH ONE IMPORTANT
  86591. * EXCEPTION: the offset is a 64-bit type whereas fseek() is generally 'long'
  86592. * and 32-bits wide.
  86593. *
  86594. * \param handle The handle to the data source.
  86595. * \param offset The new position, relative to \a whence
  86596. * \param whence \c SEEK_SET, \c SEEK_CUR, or \c SEEK_END
  86597. * \retval int
  86598. * \c 0 on success, \c -1 on error.
  86599. */
  86600. typedef int (*FLAC__IOCallback_Seek) (FLAC__IOHandle handle, FLAC__int64 offset, int whence);
  86601. /** Signature for the tell callback.
  86602. * The signature and semantics mostly match POSIX ftell() WITH ONE IMPORTANT
  86603. * EXCEPTION: the offset is a 64-bit type whereas ftell() is generally 'long'
  86604. * and 32-bits wide.
  86605. *
  86606. * \param handle The handle to the data source.
  86607. * \retval FLAC__int64
  86608. * The current position on success, \c -1 on error.
  86609. */
  86610. typedef FLAC__int64 (*FLAC__IOCallback_Tell) (FLAC__IOHandle handle);
  86611. /** Signature for the EOF callback.
  86612. * The signature and semantics mostly match POSIX feof() but WATCHOUT:
  86613. * on many systems, feof() is a macro, so in this case a wrapper function
  86614. * must be provided instead.
  86615. *
  86616. * \param handle The handle to the data source.
  86617. * \retval int
  86618. * \c 0 if not at end of file, nonzero if at end of file.
  86619. */
  86620. typedef int (*FLAC__IOCallback_Eof) (FLAC__IOHandle handle);
  86621. /** Signature for the close callback.
  86622. * The signature and semantics match POSIX fclose() implementations
  86623. * and can generally be used interchangeably.
  86624. *
  86625. * \param handle The handle to the data source.
  86626. * \retval int
  86627. * \c 0 on success, \c EOF on error.
  86628. */
  86629. typedef int (*FLAC__IOCallback_Close) (FLAC__IOHandle handle);
  86630. /** A structure for holding a set of callbacks.
  86631. * Each FLAC interface that requires a FLAC__IOCallbacks structure will
  86632. * describe which of the callbacks are required. The ones that are not
  86633. * required may be set to NULL.
  86634. *
  86635. * If the seek requirement for an interface is optional, you can signify that
  86636. * a data sorce is not seekable by setting the \a seek field to \c NULL.
  86637. */
  86638. typedef struct {
  86639. FLAC__IOCallback_Read read;
  86640. FLAC__IOCallback_Write write;
  86641. FLAC__IOCallback_Seek seek;
  86642. FLAC__IOCallback_Tell tell;
  86643. FLAC__IOCallback_Eof eof;
  86644. FLAC__IOCallback_Close close;
  86645. } FLAC__IOCallbacks;
  86646. /* \} */
  86647. #ifdef __cplusplus
  86648. }
  86649. #endif
  86650. #endif
  86651. /*** End of inlined file: callback.h ***/
  86652. /*** Start of inlined file: format.h ***/
  86653. #ifndef FLAC__FORMAT_H
  86654. #define FLAC__FORMAT_H
  86655. #ifdef __cplusplus
  86656. extern "C" {
  86657. #endif
  86658. /** \file include/FLAC/format.h
  86659. *
  86660. * \brief
  86661. * This module contains structure definitions for the representation
  86662. * of FLAC format components in memory. These are the basic
  86663. * structures used by the rest of the interfaces.
  86664. *
  86665. * See the detailed documentation in the
  86666. * \link flac_format format \endlink module.
  86667. */
  86668. /** \defgroup flac_format FLAC/format.h: format components
  86669. * \ingroup flac
  86670. *
  86671. * \brief
  86672. * This module contains structure definitions for the representation
  86673. * of FLAC format components in memory. These are the basic
  86674. * structures used by the rest of the interfaces.
  86675. *
  86676. * First, you should be familiar with the
  86677. * <A HREF="../format.html">FLAC format</A>. Many of the values here
  86678. * follow directly from the specification. As a user of libFLAC, the
  86679. * interesting parts really are the structures that describe the frame
  86680. * header and metadata blocks.
  86681. *
  86682. * The format structures here are very primitive, designed to store
  86683. * information in an efficient way. Reading information from the
  86684. * structures is easy but creating or modifying them directly is
  86685. * more complex. For the most part, as a user of a library, editing
  86686. * is not necessary; however, for metadata blocks it is, so there are
  86687. * convenience functions provided in the \link flac_metadata metadata
  86688. * module \endlink to simplify the manipulation of metadata blocks.
  86689. *
  86690. * \note
  86691. * It's not the best convention, but symbols ending in _LEN are in bits
  86692. * and _LENGTH are in bytes. _LENGTH symbols are \#defines instead of
  86693. * global variables because they are usually used when declaring byte
  86694. * arrays and some compilers require compile-time knowledge of array
  86695. * sizes when declared on the stack.
  86696. *
  86697. * \{
  86698. */
  86699. /*
  86700. Most of the values described in this file are defined by the FLAC
  86701. format specification. There is nothing to tune here.
  86702. */
  86703. /** The largest legal metadata type code. */
  86704. #define FLAC__MAX_METADATA_TYPE_CODE (126u)
  86705. /** The minimum block size, in samples, permitted by the format. */
  86706. #define FLAC__MIN_BLOCK_SIZE (16u)
  86707. /** The maximum block size, in samples, permitted by the format. */
  86708. #define FLAC__MAX_BLOCK_SIZE (65535u)
  86709. /** The maximum block size, in samples, permitted by the FLAC subset for
  86710. * sample rates up to 48kHz. */
  86711. #define FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ (4608u)
  86712. /** The maximum number of channels permitted by the format. */
  86713. #define FLAC__MAX_CHANNELS (8u)
  86714. /** The minimum sample resolution permitted by the format. */
  86715. #define FLAC__MIN_BITS_PER_SAMPLE (4u)
  86716. /** The maximum sample resolution permitted by the format. */
  86717. #define FLAC__MAX_BITS_PER_SAMPLE (32u)
  86718. /** The maximum sample resolution permitted by libFLAC.
  86719. *
  86720. * \warning
  86721. * FLAC__MAX_BITS_PER_SAMPLE is the limit of the FLAC format. However,
  86722. * the reference encoder/decoder is currently limited to 24 bits because
  86723. * of prevalent 32-bit math, so make sure and use this value when
  86724. * appropriate.
  86725. */
  86726. #define FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE (24u)
  86727. /** The maximum sample rate permitted by the format. The value is
  86728. * ((2 ^ 16) - 1) * 10; see <A HREF="../format.html">FLAC format</A>
  86729. * as to why.
  86730. */
  86731. #define FLAC__MAX_SAMPLE_RATE (655350u)
  86732. /** The maximum LPC order permitted by the format. */
  86733. #define FLAC__MAX_LPC_ORDER (32u)
  86734. /** The maximum LPC order permitted by the FLAC subset for sample rates
  86735. * up to 48kHz. */
  86736. #define FLAC__SUBSET_MAX_LPC_ORDER_48000HZ (12u)
  86737. /** The minimum quantized linear predictor coefficient precision
  86738. * permitted by the format.
  86739. */
  86740. #define FLAC__MIN_QLP_COEFF_PRECISION (5u)
  86741. /** The maximum quantized linear predictor coefficient precision
  86742. * permitted by the format.
  86743. */
  86744. #define FLAC__MAX_QLP_COEFF_PRECISION (15u)
  86745. /** The maximum order of the fixed predictors permitted by the format. */
  86746. #define FLAC__MAX_FIXED_ORDER (4u)
  86747. /** The maximum Rice partition order permitted by the format. */
  86748. #define FLAC__MAX_RICE_PARTITION_ORDER (15u)
  86749. /** The maximum Rice partition order permitted by the FLAC Subset. */
  86750. #define FLAC__SUBSET_MAX_RICE_PARTITION_ORDER (8u)
  86751. /** The version string of the release, stamped onto the libraries and binaries.
  86752. *
  86753. * \note
  86754. * This does not correspond to the shared library version number, which
  86755. * is used to determine binary compatibility.
  86756. */
  86757. extern FLAC_API const char *FLAC__VERSION_STRING;
  86758. /** The vendor string inserted by the encoder into the VORBIS_COMMENT block.
  86759. * This is a NUL-terminated ASCII string; when inserted into the
  86760. * VORBIS_COMMENT the trailing null is stripped.
  86761. */
  86762. extern FLAC_API const char *FLAC__VENDOR_STRING;
  86763. /** The byte string representation of the beginning of a FLAC stream. */
  86764. extern FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4]; /* = "fLaC" */
  86765. /** The 32-bit integer big-endian representation of the beginning of
  86766. * a FLAC stream.
  86767. */
  86768. extern FLAC_API const unsigned FLAC__STREAM_SYNC; /* = 0x664C6143 */
  86769. /** The length of the FLAC signature in bits. */
  86770. extern FLAC_API const unsigned FLAC__STREAM_SYNC_LEN; /* = 32 bits */
  86771. /** The length of the FLAC signature in bytes. */
  86772. #define FLAC__STREAM_SYNC_LENGTH (4u)
  86773. /*****************************************************************************
  86774. *
  86775. * Subframe structures
  86776. *
  86777. *****************************************************************************/
  86778. /*****************************************************************************/
  86779. /** An enumeration of the available entropy coding methods. */
  86780. typedef enum {
  86781. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE = 0,
  86782. /**< Residual is coded by partitioning into contexts, each with it's own
  86783. * 4-bit Rice parameter. */
  86784. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 = 1
  86785. /**< Residual is coded by partitioning into contexts, each with it's own
  86786. * 5-bit Rice parameter. */
  86787. } FLAC__EntropyCodingMethodType;
  86788. /** Maps a FLAC__EntropyCodingMethodType to a C string.
  86789. *
  86790. * Using a FLAC__EntropyCodingMethodType as the index to this array will
  86791. * give the string equivalent. The contents should not be modified.
  86792. */
  86793. extern FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[];
  86794. /** Contents of a Rice partitioned residual
  86795. */
  86796. typedef struct {
  86797. unsigned *parameters;
  86798. /**< The Rice parameters for each context. */
  86799. unsigned *raw_bits;
  86800. /**< Widths for escape-coded partitions. Will be non-zero for escaped
  86801. * partitions and zero for unescaped partitions.
  86802. */
  86803. unsigned capacity_by_order;
  86804. /**< The capacity of the \a parameters and \a raw_bits arrays
  86805. * specified as an order, i.e. the number of array elements
  86806. * allocated is 2 ^ \a capacity_by_order.
  86807. */
  86808. } FLAC__EntropyCodingMethod_PartitionedRiceContents;
  86809. /** Header for a Rice partitioned residual. (c.f. <A HREF="../format.html#partitioned_rice">format specification</A>)
  86810. */
  86811. typedef struct {
  86812. unsigned order;
  86813. /**< The partition order, i.e. # of contexts = 2 ^ \a order. */
  86814. const FLAC__EntropyCodingMethod_PartitionedRiceContents *contents;
  86815. /**< The context's Rice parameters and/or raw bits. */
  86816. } FLAC__EntropyCodingMethod_PartitionedRice;
  86817. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN; /**< == 4 (bits) */
  86818. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN; /**< == 4 (bits) */
  86819. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN; /**< == 5 (bits) */
  86820. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN; /**< == 5 (bits) */
  86821. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  86822. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  86823. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER;
  86824. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  86825. /** Header for the entropy coding method. (c.f. <A HREF="../format.html#residual">format specification</A>)
  86826. */
  86827. typedef struct {
  86828. FLAC__EntropyCodingMethodType type;
  86829. union {
  86830. FLAC__EntropyCodingMethod_PartitionedRice partitioned_rice;
  86831. } data;
  86832. } FLAC__EntropyCodingMethod;
  86833. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN; /**< == 2 (bits) */
  86834. /*****************************************************************************/
  86835. /** An enumeration of the available subframe types. */
  86836. typedef enum {
  86837. FLAC__SUBFRAME_TYPE_CONSTANT = 0, /**< constant signal */
  86838. FLAC__SUBFRAME_TYPE_VERBATIM = 1, /**< uncompressed signal */
  86839. FLAC__SUBFRAME_TYPE_FIXED = 2, /**< fixed polynomial prediction */
  86840. FLAC__SUBFRAME_TYPE_LPC = 3 /**< linear prediction */
  86841. } FLAC__SubframeType;
  86842. /** Maps a FLAC__SubframeType to a C string.
  86843. *
  86844. * Using a FLAC__SubframeType as the index to this array will
  86845. * give the string equivalent. The contents should not be modified.
  86846. */
  86847. extern FLAC_API const char * const FLAC__SubframeTypeString[];
  86848. /** CONSTANT subframe. (c.f. <A HREF="../format.html#subframe_constant">format specification</A>)
  86849. */
  86850. typedef struct {
  86851. FLAC__int32 value; /**< The constant signal value. */
  86852. } FLAC__Subframe_Constant;
  86853. /** VERBATIM subframe. (c.f. <A HREF="../format.html#subframe_verbatim">format specification</A>)
  86854. */
  86855. typedef struct {
  86856. const FLAC__int32 *data; /**< A pointer to verbatim signal. */
  86857. } FLAC__Subframe_Verbatim;
  86858. /** FIXED subframe. (c.f. <A HREF="../format.html#subframe_fixed">format specification</A>)
  86859. */
  86860. typedef struct {
  86861. FLAC__EntropyCodingMethod entropy_coding_method;
  86862. /**< The residual coding method. */
  86863. unsigned order;
  86864. /**< The polynomial order. */
  86865. FLAC__int32 warmup[FLAC__MAX_FIXED_ORDER];
  86866. /**< Warmup samples to prime the predictor, length == order. */
  86867. const FLAC__int32 *residual;
  86868. /**< The residual signal, length == (blocksize minus order) samples. */
  86869. } FLAC__Subframe_Fixed;
  86870. /** LPC subframe. (c.f. <A HREF="../format.html#subframe_lpc">format specification</A>)
  86871. */
  86872. typedef struct {
  86873. FLAC__EntropyCodingMethod entropy_coding_method;
  86874. /**< The residual coding method. */
  86875. unsigned order;
  86876. /**< The FIR order. */
  86877. unsigned qlp_coeff_precision;
  86878. /**< Quantized FIR filter coefficient precision in bits. */
  86879. int quantization_level;
  86880. /**< The qlp coeff shift needed. */
  86881. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  86882. /**< FIR filter coefficients. */
  86883. FLAC__int32 warmup[FLAC__MAX_LPC_ORDER];
  86884. /**< Warmup samples to prime the predictor, length == order. */
  86885. const FLAC__int32 *residual;
  86886. /**< The residual signal, length == (blocksize minus order) samples. */
  86887. } FLAC__Subframe_LPC;
  86888. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN; /**< == 4 (bits) */
  86889. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN; /**< == 5 (bits) */
  86890. /** FLAC subframe structure. (c.f. <A HREF="../format.html#subframe">format specification</A>)
  86891. */
  86892. typedef struct {
  86893. FLAC__SubframeType type;
  86894. union {
  86895. FLAC__Subframe_Constant constant;
  86896. FLAC__Subframe_Fixed fixed;
  86897. FLAC__Subframe_LPC lpc;
  86898. FLAC__Subframe_Verbatim verbatim;
  86899. } data;
  86900. unsigned wasted_bits;
  86901. } FLAC__Subframe;
  86902. /** == 1 (bit)
  86903. *
  86904. * This used to be a zero-padding bit (hence the name
  86905. * FLAC__SUBFRAME_ZERO_PAD_LEN) but is now a reserved bit. It still has a
  86906. * mandatory value of \c 0 but in the future may take on the value \c 0 or \c 1
  86907. * to mean something else.
  86908. */
  86909. extern FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN;
  86910. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN; /**< == 6 (bits) */
  86911. extern FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN; /**< == 1 (bit) */
  86912. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK; /**< = 0x00 */
  86913. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK; /**< = 0x02 */
  86914. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK; /**< = 0x10 */
  86915. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK; /**< = 0x40 */
  86916. /*****************************************************************************/
  86917. /*****************************************************************************
  86918. *
  86919. * Frame structures
  86920. *
  86921. *****************************************************************************/
  86922. /** An enumeration of the available channel assignments. */
  86923. typedef enum {
  86924. FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT = 0, /**< independent channels */
  86925. FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE = 1, /**< left+side stereo */
  86926. FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE = 2, /**< right+side stereo */
  86927. FLAC__CHANNEL_ASSIGNMENT_MID_SIDE = 3 /**< mid+side stereo */
  86928. } FLAC__ChannelAssignment;
  86929. /** Maps a FLAC__ChannelAssignment to a C string.
  86930. *
  86931. * Using a FLAC__ChannelAssignment as the index to this array will
  86932. * give the string equivalent. The contents should not be modified.
  86933. */
  86934. extern FLAC_API const char * const FLAC__ChannelAssignmentString[];
  86935. /** An enumeration of the possible frame numbering methods. */
  86936. typedef enum {
  86937. FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER, /**< number contains the frame number */
  86938. FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER /**< number contains the sample number of first sample in frame */
  86939. } FLAC__FrameNumberType;
  86940. /** Maps a FLAC__FrameNumberType to a C string.
  86941. *
  86942. * Using a FLAC__FrameNumberType as the index to this array will
  86943. * give the string equivalent. The contents should not be modified.
  86944. */
  86945. extern FLAC_API const char * const FLAC__FrameNumberTypeString[];
  86946. /** FLAC frame header structure. (c.f. <A HREF="../format.html#frame_header">format specification</A>)
  86947. */
  86948. typedef struct {
  86949. unsigned blocksize;
  86950. /**< The number of samples per subframe. */
  86951. unsigned sample_rate;
  86952. /**< The sample rate in Hz. */
  86953. unsigned channels;
  86954. /**< The number of channels (== number of subframes). */
  86955. FLAC__ChannelAssignment channel_assignment;
  86956. /**< The channel assignment for the frame. */
  86957. unsigned bits_per_sample;
  86958. /**< The sample resolution. */
  86959. FLAC__FrameNumberType number_type;
  86960. /**< The numbering scheme used for the frame. As a convenience, the
  86961. * decoder will always convert a frame number to a sample number because
  86962. * the rules are complex. */
  86963. union {
  86964. FLAC__uint32 frame_number;
  86965. FLAC__uint64 sample_number;
  86966. } number;
  86967. /**< The frame number or sample number of first sample in frame;
  86968. * use the \a number_type value to determine which to use. */
  86969. FLAC__uint8 crc;
  86970. /**< CRC-8 (polynomial = x^8 + x^2 + x^1 + x^0, initialized with 0)
  86971. * of the raw frame header bytes, meaning everything before the CRC byte
  86972. * including the sync code.
  86973. */
  86974. } FLAC__FrameHeader;
  86975. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC; /**< == 0x3ffe; the frame header sync code */
  86976. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN; /**< == 14 (bits) */
  86977. extern FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN; /**< == 1 (bits) */
  86978. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN; /**< == 1 (bits) */
  86979. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN; /**< == 4 (bits) */
  86980. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN; /**< == 4 (bits) */
  86981. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN; /**< == 4 (bits) */
  86982. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN; /**< == 3 (bits) */
  86983. extern FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN; /**< == 1 (bit) */
  86984. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN; /**< == 8 (bits) */
  86985. /** FLAC frame footer structure. (c.f. <A HREF="../format.html#frame_footer">format specification</A>)
  86986. */
  86987. typedef struct {
  86988. FLAC__uint16 crc;
  86989. /**< CRC-16 (polynomial = x^16 + x^15 + x^2 + x^0, initialized with
  86990. * 0) of the bytes before the crc, back to and including the frame header
  86991. * sync code.
  86992. */
  86993. } FLAC__FrameFooter;
  86994. extern FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN; /**< == 16 (bits) */
  86995. /** FLAC frame structure. (c.f. <A HREF="../format.html#frame">format specification</A>)
  86996. */
  86997. typedef struct {
  86998. FLAC__FrameHeader header;
  86999. FLAC__Subframe subframes[FLAC__MAX_CHANNELS];
  87000. FLAC__FrameFooter footer;
  87001. } FLAC__Frame;
  87002. /*****************************************************************************/
  87003. /*****************************************************************************
  87004. *
  87005. * Meta-data structures
  87006. *
  87007. *****************************************************************************/
  87008. /** An enumeration of the available metadata block types. */
  87009. typedef enum {
  87010. FLAC__METADATA_TYPE_STREAMINFO = 0,
  87011. /**< <A HREF="../format.html#metadata_block_streaminfo">STREAMINFO</A> block */
  87012. FLAC__METADATA_TYPE_PADDING = 1,
  87013. /**< <A HREF="../format.html#metadata_block_padding">PADDING</A> block */
  87014. FLAC__METADATA_TYPE_APPLICATION = 2,
  87015. /**< <A HREF="../format.html#metadata_block_application">APPLICATION</A> block */
  87016. FLAC__METADATA_TYPE_SEEKTABLE = 3,
  87017. /**< <A HREF="../format.html#metadata_block_seektable">SEEKTABLE</A> block */
  87018. FLAC__METADATA_TYPE_VORBIS_COMMENT = 4,
  87019. /**< <A HREF="../format.html#metadata_block_vorbis_comment">VORBISCOMMENT</A> block (a.k.a. FLAC tags) */
  87020. FLAC__METADATA_TYPE_CUESHEET = 5,
  87021. /**< <A HREF="../format.html#metadata_block_cuesheet">CUESHEET</A> block */
  87022. FLAC__METADATA_TYPE_PICTURE = 6,
  87023. /**< <A HREF="../format.html#metadata_block_picture">PICTURE</A> block */
  87024. FLAC__METADATA_TYPE_UNDEFINED = 7
  87025. /**< marker to denote beginning of undefined type range; this number will increase as new metadata types are added */
  87026. } FLAC__MetadataType;
  87027. /** Maps a FLAC__MetadataType to a C string.
  87028. *
  87029. * Using a FLAC__MetadataType as the index to this array will
  87030. * give the string equivalent. The contents should not be modified.
  87031. */
  87032. extern FLAC_API const char * const FLAC__MetadataTypeString[];
  87033. /** FLAC STREAMINFO structure. (c.f. <A HREF="../format.html#metadata_block_streaminfo">format specification</A>)
  87034. */
  87035. typedef struct {
  87036. unsigned min_blocksize, max_blocksize;
  87037. unsigned min_framesize, max_framesize;
  87038. unsigned sample_rate;
  87039. unsigned channels;
  87040. unsigned bits_per_sample;
  87041. FLAC__uint64 total_samples;
  87042. FLAC__byte md5sum[16];
  87043. } FLAC__StreamMetadata_StreamInfo;
  87044. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  87045. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  87046. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN; /**< == 24 (bits) */
  87047. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN; /**< == 24 (bits) */
  87048. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN; /**< == 20 (bits) */
  87049. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN; /**< == 3 (bits) */
  87050. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN; /**< == 5 (bits) */
  87051. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN; /**< == 36 (bits) */
  87052. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN; /**< == 128 (bits) */
  87053. /** The total stream length of the STREAMINFO block in bytes. */
  87054. #define FLAC__STREAM_METADATA_STREAMINFO_LENGTH (34u)
  87055. /** FLAC PADDING structure. (c.f. <A HREF="../format.html#metadata_block_padding">format specification</A>)
  87056. */
  87057. typedef struct {
  87058. int dummy;
  87059. /**< Conceptually this is an empty struct since we don't store the
  87060. * padding bytes. Empty structs are not allowed by some C compilers,
  87061. * hence the dummy.
  87062. */
  87063. } FLAC__StreamMetadata_Padding;
  87064. /** FLAC APPLICATION structure. (c.f. <A HREF="../format.html#metadata_block_application">format specification</A>)
  87065. */
  87066. typedef struct {
  87067. FLAC__byte id[4];
  87068. FLAC__byte *data;
  87069. } FLAC__StreamMetadata_Application;
  87070. extern FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN; /**< == 32 (bits) */
  87071. /** SeekPoint structure used in SEEKTABLE blocks. (c.f. <A HREF="../format.html#seekpoint">format specification</A>)
  87072. */
  87073. typedef struct {
  87074. FLAC__uint64 sample_number;
  87075. /**< The sample number of the target frame. */
  87076. FLAC__uint64 stream_offset;
  87077. /**< The offset, in bytes, of the target frame with respect to
  87078. * beginning of the first frame. */
  87079. unsigned frame_samples;
  87080. /**< The number of samples in the target frame. */
  87081. } FLAC__StreamMetadata_SeekPoint;
  87082. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN; /**< == 64 (bits) */
  87083. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN; /**< == 64 (bits) */
  87084. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN; /**< == 16 (bits) */
  87085. /** The total stream length of a seek point in bytes. */
  87086. #define FLAC__STREAM_METADATA_SEEKPOINT_LENGTH (18u)
  87087. /** The value used in the \a sample_number field of
  87088. * FLAC__StreamMetadataSeekPoint used to indicate a placeholder
  87089. * point (== 0xffffffffffffffff).
  87090. */
  87091. extern FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  87092. /** FLAC SEEKTABLE structure. (c.f. <A HREF="../format.html#metadata_block_seektable">format specification</A>)
  87093. *
  87094. * \note From the format specification:
  87095. * - The seek points must be sorted by ascending sample number.
  87096. * - Each seek point's sample number must be the first sample of the
  87097. * target frame.
  87098. * - Each seek point's sample number must be unique within the table.
  87099. * - Existence of a SEEKTABLE block implies a correct setting of
  87100. * total_samples in the stream_info block.
  87101. * - Behavior is undefined when more than one SEEKTABLE block is
  87102. * present in a stream.
  87103. */
  87104. typedef struct {
  87105. unsigned num_points;
  87106. FLAC__StreamMetadata_SeekPoint *points;
  87107. } FLAC__StreamMetadata_SeekTable;
  87108. /** Vorbis comment entry structure used in VORBIS_COMMENT blocks. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  87109. *
  87110. * For convenience, the APIs maintain a trailing NUL character at the end of
  87111. * \a entry which is not counted toward \a length, i.e.
  87112. * \code strlen(entry) == length \endcode
  87113. */
  87114. typedef struct {
  87115. FLAC__uint32 length;
  87116. FLAC__byte *entry;
  87117. } FLAC__StreamMetadata_VorbisComment_Entry;
  87118. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN; /**< == 32 (bits) */
  87119. /** FLAC VORBIS_COMMENT structure. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  87120. */
  87121. typedef struct {
  87122. FLAC__StreamMetadata_VorbisComment_Entry vendor_string;
  87123. FLAC__uint32 num_comments;
  87124. FLAC__StreamMetadata_VorbisComment_Entry *comments;
  87125. } FLAC__StreamMetadata_VorbisComment;
  87126. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN; /**< == 32 (bits) */
  87127. /** FLAC CUESHEET track index structure. (See the
  87128. * <A HREF="../format.html#cuesheet_track_index">format specification</A> for
  87129. * the full description of each field.)
  87130. */
  87131. typedef struct {
  87132. FLAC__uint64 offset;
  87133. /**< Offset in samples, relative to the track offset, of the index
  87134. * point.
  87135. */
  87136. FLAC__byte number;
  87137. /**< The index point number. */
  87138. } FLAC__StreamMetadata_CueSheet_Index;
  87139. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN; /**< == 64 (bits) */
  87140. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN; /**< == 8 (bits) */
  87141. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN; /**< == 3*8 (bits) */
  87142. /** FLAC CUESHEET track structure. (See the
  87143. * <A HREF="../format.html#cuesheet_track">format specification</A> for
  87144. * the full description of each field.)
  87145. */
  87146. typedef struct {
  87147. FLAC__uint64 offset;
  87148. /**< Track offset in samples, relative to the beginning of the FLAC audio stream. */
  87149. FLAC__byte number;
  87150. /**< The track number. */
  87151. char isrc[13];
  87152. /**< Track ISRC. This is a 12-digit alphanumeric code plus a trailing \c NUL byte */
  87153. unsigned type:1;
  87154. /**< The track type: 0 for audio, 1 for non-audio. */
  87155. unsigned pre_emphasis:1;
  87156. /**< The pre-emphasis flag: 0 for no pre-emphasis, 1 for pre-emphasis. */
  87157. FLAC__byte num_indices;
  87158. /**< The number of track index points. */
  87159. FLAC__StreamMetadata_CueSheet_Index *indices;
  87160. /**< NULL if num_indices == 0, else pointer to array of index points. */
  87161. } FLAC__StreamMetadata_CueSheet_Track;
  87162. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN; /**< == 64 (bits) */
  87163. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN; /**< == 8 (bits) */
  87164. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN; /**< == 12*8 (bits) */
  87165. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN; /**< == 1 (bit) */
  87166. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN; /**< == 1 (bit) */
  87167. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN; /**< == 6+13*8 (bits) */
  87168. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN; /**< == 8 (bits) */
  87169. /** FLAC CUESHEET structure. (See the
  87170. * <A HREF="../format.html#metadata_block_cuesheet">format specification</A>
  87171. * for the full description of each field.)
  87172. */
  87173. typedef struct {
  87174. char media_catalog_number[129];
  87175. /**< Media catalog number, in ASCII printable characters 0x20-0x7e. In
  87176. * general, the media catalog number may be 0 to 128 bytes long; any
  87177. * unused characters should be right-padded with NUL characters.
  87178. */
  87179. FLAC__uint64 lead_in;
  87180. /**< The number of lead-in samples. */
  87181. FLAC__bool is_cd;
  87182. /**< \c true if CUESHEET corresponds to a Compact Disc, else \c false. */
  87183. unsigned num_tracks;
  87184. /**< The number of tracks. */
  87185. FLAC__StreamMetadata_CueSheet_Track *tracks;
  87186. /**< NULL if num_tracks == 0, else pointer to array of tracks. */
  87187. } FLAC__StreamMetadata_CueSheet;
  87188. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN; /**< == 128*8 (bits) */
  87189. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN; /**< == 64 (bits) */
  87190. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN; /**< == 1 (bit) */
  87191. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN; /**< == 7+258*8 (bits) */
  87192. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN; /**< == 8 (bits) */
  87193. /** An enumeration of the PICTURE types (see FLAC__StreamMetadataPicture and id3 v2.4 APIC tag). */
  87194. typedef enum {
  87195. FLAC__STREAM_METADATA_PICTURE_TYPE_OTHER = 0, /**< Other */
  87196. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD = 1, /**< 32x32 pixels 'file icon' (PNG only) */
  87197. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON = 2, /**< Other file icon */
  87198. FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER = 3, /**< Cover (front) */
  87199. FLAC__STREAM_METADATA_PICTURE_TYPE_BACK_COVER = 4, /**< Cover (back) */
  87200. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAFLET_PAGE = 5, /**< Leaflet page */
  87201. FLAC__STREAM_METADATA_PICTURE_TYPE_MEDIA = 6, /**< Media (e.g. label side of CD) */
  87202. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAD_ARTIST = 7, /**< Lead artist/lead performer/soloist */
  87203. FLAC__STREAM_METADATA_PICTURE_TYPE_ARTIST = 8, /**< Artist/performer */
  87204. FLAC__STREAM_METADATA_PICTURE_TYPE_CONDUCTOR = 9, /**< Conductor */
  87205. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND = 10, /**< Band/Orchestra */
  87206. FLAC__STREAM_METADATA_PICTURE_TYPE_COMPOSER = 11, /**< Composer */
  87207. FLAC__STREAM_METADATA_PICTURE_TYPE_LYRICIST = 12, /**< Lyricist/text writer */
  87208. FLAC__STREAM_METADATA_PICTURE_TYPE_RECORDING_LOCATION = 13, /**< Recording Location */
  87209. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_RECORDING = 14, /**< During recording */
  87210. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_PERFORMANCE = 15, /**< During performance */
  87211. FLAC__STREAM_METADATA_PICTURE_TYPE_VIDEO_SCREEN_CAPTURE = 16, /**< Movie/video screen capture */
  87212. FLAC__STREAM_METADATA_PICTURE_TYPE_FISH = 17, /**< A bright coloured fish */
  87213. FLAC__STREAM_METADATA_PICTURE_TYPE_ILLUSTRATION = 18, /**< Illustration */
  87214. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND_LOGOTYPE = 19, /**< Band/artist logotype */
  87215. FLAC__STREAM_METADATA_PICTURE_TYPE_PUBLISHER_LOGOTYPE = 20, /**< Publisher/Studio logotype */
  87216. FLAC__STREAM_METADATA_PICTURE_TYPE_UNDEFINED
  87217. } FLAC__StreamMetadata_Picture_Type;
  87218. /** Maps a FLAC__StreamMetadata_Picture_Type to a C string.
  87219. *
  87220. * Using a FLAC__StreamMetadata_Picture_Type as the index to this array
  87221. * will give the string equivalent. The contents should not be
  87222. * modified.
  87223. */
  87224. extern FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[];
  87225. /** FLAC PICTURE structure. (See the
  87226. * <A HREF="../format.html#metadata_block_picture">format specification</A>
  87227. * for the full description of each field.)
  87228. */
  87229. typedef struct {
  87230. FLAC__StreamMetadata_Picture_Type type;
  87231. /**< The kind of picture stored. */
  87232. char *mime_type;
  87233. /**< Picture data's MIME type, in ASCII printable characters
  87234. * 0x20-0x7e, NUL terminated. For best compatibility with players,
  87235. * use picture data of MIME type \c image/jpeg or \c image/png. A
  87236. * MIME type of '-->' is also allowed, in which case the picture
  87237. * data should be a complete URL. In file storage, the MIME type is
  87238. * stored as a 32-bit length followed by the ASCII string with no NUL
  87239. * terminator, but is converted to a plain C string in this structure
  87240. * for convenience.
  87241. */
  87242. FLAC__byte *description;
  87243. /**< Picture's description in UTF-8, NUL terminated. In file storage,
  87244. * the description is stored as a 32-bit length followed by the UTF-8
  87245. * string with no NUL terminator, but is converted to a plain C string
  87246. * in this structure for convenience.
  87247. */
  87248. FLAC__uint32 width;
  87249. /**< Picture's width in pixels. */
  87250. FLAC__uint32 height;
  87251. /**< Picture's height in pixels. */
  87252. FLAC__uint32 depth;
  87253. /**< Picture's color depth in bits-per-pixel. */
  87254. FLAC__uint32 colors;
  87255. /**< For indexed palettes (like GIF), picture's number of colors (the
  87256. * number of palette entries), or \c 0 for non-indexed (i.e. 2^depth).
  87257. */
  87258. FLAC__uint32 data_length;
  87259. /**< Length of binary picture data in bytes. */
  87260. FLAC__byte *data;
  87261. /**< Binary picture data. */
  87262. } FLAC__StreamMetadata_Picture;
  87263. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN; /**< == 32 (bits) */
  87264. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN; /**< == 32 (bits) */
  87265. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN; /**< == 32 (bits) */
  87266. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN; /**< == 32 (bits) */
  87267. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN; /**< == 32 (bits) */
  87268. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN; /**< == 32 (bits) */
  87269. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN; /**< == 32 (bits) */
  87270. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN; /**< == 32 (bits) */
  87271. /** Structure that is used when a metadata block of unknown type is loaded.
  87272. * The contents are opaque. The structure is used only internally to
  87273. * correctly handle unknown metadata.
  87274. */
  87275. typedef struct {
  87276. FLAC__byte *data;
  87277. } FLAC__StreamMetadata_Unknown;
  87278. /** FLAC metadata block structure. (c.f. <A HREF="../format.html#metadata_block">format specification</A>)
  87279. */
  87280. typedef struct {
  87281. FLAC__MetadataType type;
  87282. /**< The type of the metadata block; used determine which member of the
  87283. * \a data union to dereference. If type >= FLAC__METADATA_TYPE_UNDEFINED
  87284. * then \a data.unknown must be used. */
  87285. FLAC__bool is_last;
  87286. /**< \c true if this metadata block is the last, else \a false */
  87287. unsigned length;
  87288. /**< Length, in bytes, of the block data as it appears in the stream. */
  87289. union {
  87290. FLAC__StreamMetadata_StreamInfo stream_info;
  87291. FLAC__StreamMetadata_Padding padding;
  87292. FLAC__StreamMetadata_Application application;
  87293. FLAC__StreamMetadata_SeekTable seek_table;
  87294. FLAC__StreamMetadata_VorbisComment vorbis_comment;
  87295. FLAC__StreamMetadata_CueSheet cue_sheet;
  87296. FLAC__StreamMetadata_Picture picture;
  87297. FLAC__StreamMetadata_Unknown unknown;
  87298. } data;
  87299. /**< Polymorphic block data; use the \a type value to determine which
  87300. * to use. */
  87301. } FLAC__StreamMetadata;
  87302. extern FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN; /**< == 1 (bit) */
  87303. extern FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN; /**< == 7 (bits) */
  87304. extern FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN; /**< == 24 (bits) */
  87305. /** The total stream length of a metadata block header in bytes. */
  87306. #define FLAC__STREAM_METADATA_HEADER_LENGTH (4u)
  87307. /*****************************************************************************/
  87308. /*****************************************************************************
  87309. *
  87310. * Utility functions
  87311. *
  87312. *****************************************************************************/
  87313. /** Tests that a sample rate is valid for FLAC.
  87314. *
  87315. * \param sample_rate The sample rate to test for compliance.
  87316. * \retval FLAC__bool
  87317. * \c true if the given sample rate conforms to the specification, else
  87318. * \c false.
  87319. */
  87320. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate);
  87321. /** Tests that a sample rate is valid for the FLAC subset. The subset rules
  87322. * for valid sample rates are slightly more complex since the rate has to
  87323. * be expressible completely in the frame header.
  87324. *
  87325. * \param sample_rate The sample rate to test for compliance.
  87326. * \retval FLAC__bool
  87327. * \c true if the given sample rate conforms to the specification for the
  87328. * subset, else \c false.
  87329. */
  87330. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate);
  87331. /** Check a Vorbis comment entry name to see if it conforms to the Vorbis
  87332. * comment specification.
  87333. *
  87334. * Vorbis comment names must be composed only of characters from
  87335. * [0x20-0x3C,0x3E-0x7D].
  87336. *
  87337. * \param name A NUL-terminated string to be checked.
  87338. * \assert
  87339. * \code name != NULL \endcode
  87340. * \retval FLAC__bool
  87341. * \c false if entry name is illegal, else \c true.
  87342. */
  87343. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name);
  87344. /** Check a Vorbis comment entry value to see if it conforms to the Vorbis
  87345. * comment specification.
  87346. *
  87347. * Vorbis comment values must be valid UTF-8 sequences.
  87348. *
  87349. * \param value A string to be checked.
  87350. * \param length A the length of \a value in bytes. May be
  87351. * \c (unsigned)(-1) to indicate that \a value is a plain
  87352. * UTF-8 NUL-terminated string.
  87353. * \assert
  87354. * \code value != NULL \endcode
  87355. * \retval FLAC__bool
  87356. * \c false if entry name is illegal, else \c true.
  87357. */
  87358. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length);
  87359. /** Check a Vorbis comment entry to see if it conforms to the Vorbis
  87360. * comment specification.
  87361. *
  87362. * Vorbis comment entries must be of the form 'name=value', and 'name' and
  87363. * 'value' must be legal according to
  87364. * FLAC__format_vorbiscomment_entry_name_is_legal() and
  87365. * FLAC__format_vorbiscomment_entry_value_is_legal() respectively.
  87366. *
  87367. * \param entry An entry to be checked.
  87368. * \param length The length of \a entry in bytes.
  87369. * \assert
  87370. * \code value != NULL \endcode
  87371. * \retval FLAC__bool
  87372. * \c false if entry name is illegal, else \c true.
  87373. */
  87374. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length);
  87375. /** Check a seek table to see if it conforms to the FLAC specification.
  87376. * See the format specification for limits on the contents of the
  87377. * seek table.
  87378. *
  87379. * \param seek_table A pointer to a seek table to be checked.
  87380. * \assert
  87381. * \code seek_table != NULL \endcode
  87382. * \retval FLAC__bool
  87383. * \c false if seek table is illegal, else \c true.
  87384. */
  87385. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table);
  87386. /** Sort a seek table's seek points according to the format specification.
  87387. * This includes a "unique-ification" step to remove duplicates, i.e.
  87388. * seek points with identical \a sample_number values. Duplicate seek
  87389. * points are converted into placeholder points and sorted to the end of
  87390. * the table.
  87391. *
  87392. * \param seek_table A pointer to a seek table to be sorted.
  87393. * \assert
  87394. * \code seek_table != NULL \endcode
  87395. * \retval unsigned
  87396. * The number of duplicate seek points converted into placeholders.
  87397. */
  87398. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table);
  87399. /** Check a cue sheet to see if it conforms to the FLAC specification.
  87400. * See the format specification for limits on the contents of the
  87401. * cue sheet.
  87402. *
  87403. * \param cue_sheet A pointer to an existing cue sheet to be checked.
  87404. * \param check_cd_da_subset If \c true, check CUESHEET against more
  87405. * stringent requirements for a CD-DA (audio) disc.
  87406. * \param violation Address of a pointer to a string. If there is a
  87407. * violation, a pointer to a string explanation of the
  87408. * violation will be returned here. \a violation may be
  87409. * \c NULL if you don't need the returned string. Do not
  87410. * free the returned string; it will always point to static
  87411. * data.
  87412. * \assert
  87413. * \code cue_sheet != NULL \endcode
  87414. * \retval FLAC__bool
  87415. * \c false if cue sheet is illegal, else \c true.
  87416. */
  87417. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation);
  87418. /** Check picture data to see if it conforms to the FLAC specification.
  87419. * See the format specification for limits on the contents of the
  87420. * PICTURE block.
  87421. *
  87422. * \param picture A pointer to existing picture data to be checked.
  87423. * \param violation Address of a pointer to a string. If there is a
  87424. * violation, a pointer to a string explanation of the
  87425. * violation will be returned here. \a violation may be
  87426. * \c NULL if you don't need the returned string. Do not
  87427. * free the returned string; it will always point to static
  87428. * data.
  87429. * \assert
  87430. * \code picture != NULL \endcode
  87431. * \retval FLAC__bool
  87432. * \c false if picture data is illegal, else \c true.
  87433. */
  87434. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation);
  87435. /* \} */
  87436. #ifdef __cplusplus
  87437. }
  87438. #endif
  87439. #endif
  87440. /*** End of inlined file: format.h ***/
  87441. /*** Start of inlined file: metadata.h ***/
  87442. #ifndef FLAC__METADATA_H
  87443. #define FLAC__METADATA_H
  87444. #include <sys/types.h> /* for off_t */
  87445. /* --------------------------------------------------------------------
  87446. (For an example of how all these routines are used, see the source
  87447. code for the unit tests in src/test_libFLAC/metadata_*.c, or
  87448. metaflac in src/metaflac/)
  87449. ------------------------------------------------------------------*/
  87450. /** \file include/FLAC/metadata.h
  87451. *
  87452. * \brief
  87453. * This module provides functions for creating and manipulating FLAC
  87454. * metadata blocks in memory, and three progressively more powerful
  87455. * interfaces for traversing and editing metadata in FLAC files.
  87456. *
  87457. * See the detailed documentation for each interface in the
  87458. * \link flac_metadata metadata \endlink module.
  87459. */
  87460. /** \defgroup flac_metadata FLAC/metadata.h: metadata interfaces
  87461. * \ingroup flac
  87462. *
  87463. * \brief
  87464. * This module provides functions for creating and manipulating FLAC
  87465. * metadata blocks in memory, and three progressively more powerful
  87466. * interfaces for traversing and editing metadata in native FLAC files.
  87467. * Note that currently only the Chain interface (level 2) supports Ogg
  87468. * FLAC files, and it is read-only i.e. no writing back changed
  87469. * metadata to file.
  87470. *
  87471. * There are three metadata interfaces of increasing complexity:
  87472. *
  87473. * Level 0:
  87474. * Read-only access to the STREAMINFO, VORBIS_COMMENT, CUESHEET, and
  87475. * PICTURE blocks.
  87476. *
  87477. * Level 1:
  87478. * Read-write access to all metadata blocks. This level is write-
  87479. * efficient in most cases (more on this below), and uses less memory
  87480. * than level 2.
  87481. *
  87482. * Level 2:
  87483. * Read-write access to all metadata blocks. This level is write-
  87484. * efficient in all cases, but uses more memory since all metadata for
  87485. * the whole file is read into memory and manipulated before writing
  87486. * out again.
  87487. *
  87488. * What do we mean by efficient? Since FLAC metadata appears at the
  87489. * beginning of the file, when writing metadata back to a FLAC file
  87490. * it is possible to grow or shrink the metadata such that the entire
  87491. * file must be rewritten. However, if the size remains the same during
  87492. * changes or PADDING blocks are utilized, only the metadata needs to be
  87493. * overwritten, which is much faster.
  87494. *
  87495. * Efficient means the whole file is rewritten at most one time, and only
  87496. * when necessary. Level 1 is not efficient only in the case that you
  87497. * cause more than one metadata block to grow or shrink beyond what can
  87498. * be accomodated by padding. In this case you should probably use level
  87499. * 2, which allows you to edit all the metadata for a file in memory and
  87500. * write it out all at once.
  87501. *
  87502. * All levels know how to skip over and not disturb an ID3v2 tag at the
  87503. * front of the file.
  87504. *
  87505. * All levels access files via their filenames. In addition, level 2
  87506. * has additional alternative read and write functions that take an I/O
  87507. * handle and callbacks, for situations where access by filename is not
  87508. * possible.
  87509. *
  87510. * In addition to the three interfaces, this module defines functions for
  87511. * creating and manipulating various metadata objects in memory. As we see
  87512. * from the Format module, FLAC metadata blocks in memory are very primitive
  87513. * structures for storing information in an efficient way. Reading
  87514. * information from the structures is easy but creating or modifying them
  87515. * directly is more complex. The metadata object routines here facilitate
  87516. * this by taking care of the consistency and memory management drudgery.
  87517. *
  87518. * Unless you will be using the level 1 or 2 interfaces to modify existing
  87519. * metadata however, you will not probably not need these.
  87520. *
  87521. * From a dependency standpoint, none of the encoders or decoders require
  87522. * the metadata module. This is so that embedded users can strip out the
  87523. * metadata module from libFLAC to reduce the size and complexity.
  87524. */
  87525. #ifdef __cplusplus
  87526. extern "C" {
  87527. #endif
  87528. /** \defgroup flac_metadata_level0 FLAC/metadata.h: metadata level 0 interface
  87529. * \ingroup flac_metadata
  87530. *
  87531. * \brief
  87532. * The level 0 interface consists of individual routines to read the
  87533. * STREAMINFO, VORBIS_COMMENT, CUESHEET, and PICTURE blocks, requiring
  87534. * only a filename.
  87535. *
  87536. * They try to skip any ID3v2 tag at the head of the file.
  87537. *
  87538. * \{
  87539. */
  87540. /** Read the STREAMINFO metadata block of the given FLAC file. This function
  87541. * will try to skip any ID3v2 tag at the head of the file.
  87542. *
  87543. * \param filename The path to the FLAC file to read.
  87544. * \param streaminfo A pointer to space for the STREAMINFO block. Since
  87545. * FLAC__StreamMetadata is a simple structure with no
  87546. * memory allocation involved, you pass the address of
  87547. * an existing structure. It need not be initialized.
  87548. * \assert
  87549. * \code filename != NULL \endcode
  87550. * \code streaminfo != NULL \endcode
  87551. * \retval FLAC__bool
  87552. * \c true if a valid STREAMINFO block was read from \a filename. Returns
  87553. * \c false if there was a memory allocation error, a file decoder error,
  87554. * or the file contained no STREAMINFO block. (A memory allocation error
  87555. * is possible because this function must set up a file decoder.)
  87556. */
  87557. FLAC_API FLAC__bool FLAC__metadata_get_streaminfo(const char *filename, FLAC__StreamMetadata *streaminfo);
  87558. /** Read the VORBIS_COMMENT metadata block of the given FLAC file. This
  87559. * function will try to skip any ID3v2 tag at the head of the file.
  87560. *
  87561. * \param filename The path to the FLAC file to read.
  87562. * \param tags The address where the returned pointer will be
  87563. * stored. The \a tags object must be deleted by
  87564. * the caller using FLAC__metadata_object_delete().
  87565. * \assert
  87566. * \code filename != NULL \endcode
  87567. * \code tags != NULL \endcode
  87568. * \retval FLAC__bool
  87569. * \c true if a valid VORBIS_COMMENT block was read from \a filename,
  87570. * and \a *tags will be set to the address of the metadata structure.
  87571. * Returns \c false if there was a memory allocation error, a file
  87572. * decoder error, or the file contained no VORBIS_COMMENT block, and
  87573. * \a *tags will be set to \c NULL.
  87574. */
  87575. FLAC_API FLAC__bool FLAC__metadata_get_tags(const char *filename, FLAC__StreamMetadata **tags);
  87576. /** Read the CUESHEET metadata block of the given FLAC file. This
  87577. * function will try to skip any ID3v2 tag at the head of the file.
  87578. *
  87579. * \param filename The path to the FLAC file to read.
  87580. * \param cuesheet The address where the returned pointer will be
  87581. * stored. The \a cuesheet object must be deleted by
  87582. * the caller using FLAC__metadata_object_delete().
  87583. * \assert
  87584. * \code filename != NULL \endcode
  87585. * \code cuesheet != NULL \endcode
  87586. * \retval FLAC__bool
  87587. * \c true if a valid CUESHEET block was read from \a filename,
  87588. * and \a *cuesheet will be set to the address of the metadata
  87589. * structure. Returns \c false if there was a memory allocation
  87590. * error, a file decoder error, or the file contained no CUESHEET
  87591. * block, and \a *cuesheet will be set to \c NULL.
  87592. */
  87593. FLAC_API FLAC__bool FLAC__metadata_get_cuesheet(const char *filename, FLAC__StreamMetadata **cuesheet);
  87594. /** Read a PICTURE metadata block of the given FLAC file. This
  87595. * function will try to skip any ID3v2 tag at the head of the file.
  87596. * Since there can be more than one PICTURE block in a file, this
  87597. * function takes a number of parameters that act as constraints to
  87598. * the search. The PICTURE block with the largest area matching all
  87599. * the constraints will be returned, or \a *picture will be set to
  87600. * \c NULL if there was no such block.
  87601. *
  87602. * \param filename The path to the FLAC file to read.
  87603. * \param picture The address where the returned pointer will be
  87604. * stored. The \a picture object must be deleted by
  87605. * the caller using FLAC__metadata_object_delete().
  87606. * \param type The desired picture type. Use \c -1 to mean
  87607. * "any type".
  87608. * \param mime_type The desired MIME type, e.g. "image/jpeg". The
  87609. * string will be matched exactly. Use \c NULL to
  87610. * mean "any MIME type".
  87611. * \param description The desired description. The string will be
  87612. * matched exactly. Use \c NULL to mean "any
  87613. * description".
  87614. * \param max_width The maximum width in pixels desired. Use
  87615. * \c (unsigned)(-1) to mean "any width".
  87616. * \param max_height The maximum height in pixels desired. Use
  87617. * \c (unsigned)(-1) to mean "any height".
  87618. * \param max_depth The maximum color depth in bits-per-pixel desired.
  87619. * Use \c (unsigned)(-1) to mean "any depth".
  87620. * \param max_colors The maximum number of colors desired. Use
  87621. * \c (unsigned)(-1) to mean "any number of colors".
  87622. * \assert
  87623. * \code filename != NULL \endcode
  87624. * \code picture != NULL \endcode
  87625. * \retval FLAC__bool
  87626. * \c true if a valid PICTURE block was read from \a filename,
  87627. * and \a *picture will be set to the address of the metadata
  87628. * structure. Returns \c false if there was a memory allocation
  87629. * error, a file decoder error, or the file contained no PICTURE
  87630. * block, and \a *picture will be set to \c NULL.
  87631. */
  87632. 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);
  87633. /* \} */
  87634. /** \defgroup flac_metadata_level1 FLAC/metadata.h: metadata level 1 interface
  87635. * \ingroup flac_metadata
  87636. *
  87637. * \brief
  87638. * The level 1 interface provides read-write access to FLAC file metadata and
  87639. * operates directly on the FLAC file.
  87640. *
  87641. * The general usage of this interface is:
  87642. *
  87643. * - Create an iterator using FLAC__metadata_simple_iterator_new()
  87644. * - Attach it to a file using FLAC__metadata_simple_iterator_init() and check
  87645. * the exit code. Call FLAC__metadata_simple_iterator_is_writable() to
  87646. * see if the file is writable, or only read access is allowed.
  87647. * - Use FLAC__metadata_simple_iterator_next() and
  87648. * FLAC__metadata_simple_iterator_prev() to traverse the blocks.
  87649. * This is does not read the actual blocks themselves.
  87650. * FLAC__metadata_simple_iterator_next() is relatively fast.
  87651. * FLAC__metadata_simple_iterator_prev() is slower since it needs to search
  87652. * forward from the front of the file.
  87653. * - Use FLAC__metadata_simple_iterator_get_block_type() or
  87654. * FLAC__metadata_simple_iterator_get_block() to access the actual data at
  87655. * the current iterator position. The returned object is yours to modify
  87656. * and free.
  87657. * - Use FLAC__metadata_simple_iterator_set_block() to write a modified block
  87658. * back. You must have write permission to the original file. Make sure to
  87659. * read the whole comment to FLAC__metadata_simple_iterator_set_block()
  87660. * below.
  87661. * - Use FLAC__metadata_simple_iterator_insert_block_after() to add new blocks.
  87662. * Use the object creation functions from
  87663. * \link flac_metadata_object here \endlink to generate new objects.
  87664. * - Use FLAC__metadata_simple_iterator_delete_block() to remove the block
  87665. * currently referred to by the iterator, or replace it with padding.
  87666. * - Destroy the iterator with FLAC__metadata_simple_iterator_delete() when
  87667. * finished.
  87668. *
  87669. * \note
  87670. * The FLAC file remains open the whole time between
  87671. * FLAC__metadata_simple_iterator_init() and
  87672. * FLAC__metadata_simple_iterator_delete(), so make sure you are not altering
  87673. * the file during this time.
  87674. *
  87675. * \note
  87676. * Do not modify the \a is_last, \a length, or \a type fields of returned
  87677. * FLAC__StreamMetadata objects. These are managed automatically.
  87678. *
  87679. * \note
  87680. * If any of the modification functions
  87681. * (FLAC__metadata_simple_iterator_set_block(),
  87682. * FLAC__metadata_simple_iterator_delete_block(),
  87683. * FLAC__metadata_simple_iterator_insert_block_after(), etc.) return \c false,
  87684. * you should delete the iterator as it may no longer be valid.
  87685. *
  87686. * \{
  87687. */
  87688. struct FLAC__Metadata_SimpleIterator;
  87689. /** The opaque structure definition for the level 1 iterator type.
  87690. * See the
  87691. * \link flac_metadata_level1 metadata level 1 module \endlink
  87692. * for a detailed description.
  87693. */
  87694. typedef struct FLAC__Metadata_SimpleIterator FLAC__Metadata_SimpleIterator;
  87695. /** Status type for FLAC__Metadata_SimpleIterator.
  87696. *
  87697. * The iterator's current status can be obtained by calling FLAC__metadata_simple_iterator_status().
  87698. */
  87699. typedef enum {
  87700. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK = 0,
  87701. /**< The iterator is in the normal OK state */
  87702. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT,
  87703. /**< The data passed into a function violated the function's usage criteria */
  87704. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE,
  87705. /**< The iterator could not open the target file */
  87706. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE,
  87707. /**< The iterator could not find the FLAC signature at the start of the file */
  87708. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE,
  87709. /**< The iterator tried to write to a file that was not writable */
  87710. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA,
  87711. /**< The iterator encountered input that does not conform to the FLAC metadata specification */
  87712. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR,
  87713. /**< The iterator encountered an error while reading the FLAC file */
  87714. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR,
  87715. /**< The iterator encountered an error while seeking in the FLAC file */
  87716. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR,
  87717. /**< The iterator encountered an error while writing the FLAC file */
  87718. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR,
  87719. /**< The iterator encountered an error renaming the FLAC file */
  87720. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR,
  87721. /**< The iterator encountered an error removing the temporary file */
  87722. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR,
  87723. /**< Memory allocation failed */
  87724. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR
  87725. /**< The caller violated an assertion or an unexpected error occurred */
  87726. } FLAC__Metadata_SimpleIteratorStatus;
  87727. /** Maps a FLAC__Metadata_SimpleIteratorStatus to a C string.
  87728. *
  87729. * Using a FLAC__Metadata_SimpleIteratorStatus as the index to this array
  87730. * will give the string equivalent. The contents should not be modified.
  87731. */
  87732. extern FLAC_API const char * const FLAC__Metadata_SimpleIteratorStatusString[];
  87733. /** Create a new iterator instance.
  87734. *
  87735. * \retval FLAC__Metadata_SimpleIterator*
  87736. * \c NULL if there was an error allocating memory, else the new instance.
  87737. */
  87738. FLAC_API FLAC__Metadata_SimpleIterator *FLAC__metadata_simple_iterator_new(void);
  87739. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  87740. *
  87741. * \param iterator A pointer to an existing iterator.
  87742. * \assert
  87743. * \code iterator != NULL \endcode
  87744. */
  87745. FLAC_API void FLAC__metadata_simple_iterator_delete(FLAC__Metadata_SimpleIterator *iterator);
  87746. /** Get the current status of the iterator. Call this after a function
  87747. * returns \c false to get the reason for the error. Also resets the status
  87748. * to FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK.
  87749. *
  87750. * \param iterator A pointer to an existing iterator.
  87751. * \assert
  87752. * \code iterator != NULL \endcode
  87753. * \retval FLAC__Metadata_SimpleIteratorStatus
  87754. * The current status of the iterator.
  87755. */
  87756. FLAC_API FLAC__Metadata_SimpleIteratorStatus FLAC__metadata_simple_iterator_status(FLAC__Metadata_SimpleIterator *iterator);
  87757. /** Initialize the iterator to point to the first metadata block in the
  87758. * given FLAC file.
  87759. *
  87760. * \param iterator A pointer to an existing iterator.
  87761. * \param filename The path to the FLAC file.
  87762. * \param read_only If \c true, the FLAC file will be opened
  87763. * in read-only mode; if \c false, the FLAC
  87764. * file will be opened for edit even if no
  87765. * edits are performed.
  87766. * \param preserve_file_stats If \c true, the owner and modification
  87767. * time will be preserved even if the FLAC
  87768. * file is written to.
  87769. * \assert
  87770. * \code iterator != NULL \endcode
  87771. * \code filename != NULL \endcode
  87772. * \retval FLAC__bool
  87773. * \c false if a memory allocation error occurs, the file can't be
  87774. * opened, or another error occurs, else \c true.
  87775. */
  87776. 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);
  87777. /** Returns \c true if the FLAC file is writable. If \c false, calls to
  87778. * FLAC__metadata_simple_iterator_set_block() and
  87779. * FLAC__metadata_simple_iterator_insert_block_after() will fail.
  87780. *
  87781. * \param iterator A pointer to an existing iterator.
  87782. * \assert
  87783. * \code iterator != NULL \endcode
  87784. * \retval FLAC__bool
  87785. * See above.
  87786. */
  87787. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_writable(const FLAC__Metadata_SimpleIterator *iterator);
  87788. /** Moves the iterator forward one metadata block, returning \c false if
  87789. * already at the end.
  87790. *
  87791. * \param iterator A pointer to an existing initialized iterator.
  87792. * \assert
  87793. * \code iterator != NULL \endcode
  87794. * \a iterator has been successfully initialized with
  87795. * FLAC__metadata_simple_iterator_init()
  87796. * \retval FLAC__bool
  87797. * \c false if already at the last metadata block of the chain, else
  87798. * \c true.
  87799. */
  87800. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_next(FLAC__Metadata_SimpleIterator *iterator);
  87801. /** Moves the iterator backward one metadata block, returning \c false if
  87802. * already at the beginning.
  87803. *
  87804. * \param iterator A pointer to an existing initialized iterator.
  87805. * \assert
  87806. * \code iterator != NULL \endcode
  87807. * \a iterator has been successfully initialized with
  87808. * FLAC__metadata_simple_iterator_init()
  87809. * \retval FLAC__bool
  87810. * \c false if already at the first metadata block of the chain, else
  87811. * \c true.
  87812. */
  87813. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_prev(FLAC__Metadata_SimpleIterator *iterator);
  87814. /** Returns a flag telling if the current metadata block is the last.
  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 FLAC__bool
  87822. * \c true if the current metadata block is the last in the file,
  87823. * else \c false.
  87824. */
  87825. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_last(const FLAC__Metadata_SimpleIterator *iterator);
  87826. /** Get the offset of the metadata block at the current position. This
  87827. * avoids reading the actual block data which can save time for large
  87828. * blocks.
  87829. *
  87830. * \param iterator A pointer to an existing initialized iterator.
  87831. * \assert
  87832. * \code iterator != NULL \endcode
  87833. * \a iterator has been successfully initialized with
  87834. * FLAC__metadata_simple_iterator_init()
  87835. * \retval off_t
  87836. * The offset of the metadata block at the current iterator position.
  87837. * This is the byte offset relative to the beginning of the file of
  87838. * the current metadata block's header.
  87839. */
  87840. FLAC_API off_t FLAC__metadata_simple_iterator_get_block_offset(const FLAC__Metadata_SimpleIterator *iterator);
  87841. /** Get the type of the metadata block at the current position. This
  87842. * avoids reading the actual block data which can save time for large
  87843. * blocks.
  87844. *
  87845. * \param iterator A pointer to an existing initialized iterator.
  87846. * \assert
  87847. * \code iterator != NULL \endcode
  87848. * \a iterator has been successfully initialized with
  87849. * FLAC__metadata_simple_iterator_init()
  87850. * \retval FLAC__MetadataType
  87851. * The type of the metadata block at the current iterator position.
  87852. */
  87853. FLAC_API FLAC__MetadataType FLAC__metadata_simple_iterator_get_block_type(const FLAC__Metadata_SimpleIterator *iterator);
  87854. /** Get the length of the metadata block at the current position. This
  87855. * avoids reading the actual block data which can save time for large
  87856. * blocks.
  87857. *
  87858. * \param iterator A pointer to an existing initialized iterator.
  87859. * \assert
  87860. * \code iterator != NULL \endcode
  87861. * \a iterator has been successfully initialized with
  87862. * FLAC__metadata_simple_iterator_init()
  87863. * \retval unsigned
  87864. * The length of the metadata block at the current iterator position.
  87865. * The is same length as that in the
  87866. * <a href="http://flac.sourceforge.net/format.html#metadata_block_header">metadata block header</a>,
  87867. * i.e. the length of the metadata body that follows the header.
  87868. */
  87869. FLAC_API unsigned FLAC__metadata_simple_iterator_get_block_length(const FLAC__Metadata_SimpleIterator *iterator);
  87870. /** Get the application ID of the \c APPLICATION block at the current
  87871. * position. This avoids reading the actual block data which can save
  87872. * time for large blocks.
  87873. *
  87874. * \param iterator A pointer to an existing initialized iterator.
  87875. * \param id A pointer to a buffer of at least \c 4 bytes where
  87876. * the ID will be stored.
  87877. * \assert
  87878. * \code iterator != NULL \endcode
  87879. * \code id != NULL \endcode
  87880. * \a iterator has been successfully initialized with
  87881. * FLAC__metadata_simple_iterator_init()
  87882. * \retval FLAC__bool
  87883. * \c true if the ID was successfully read, else \c false, in which
  87884. * case you should check FLAC__metadata_simple_iterator_status() to
  87885. * find out why. If the status is
  87886. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT, then the
  87887. * current metadata block is not an \c APPLICATION block. Otherwise
  87888. * if the status is
  87889. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR or
  87890. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR, an I/O error
  87891. * occurred and the iterator can no longer be used.
  87892. */
  87893. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_get_application_id(FLAC__Metadata_SimpleIterator *iterator, FLAC__byte *id);
  87894. /** Get the metadata block at the current position. You can modify the
  87895. * block but must use FLAC__metadata_simple_iterator_set_block() to
  87896. * write it back to the FLAC file.
  87897. *
  87898. * You must call FLAC__metadata_object_delete() on the returned object
  87899. * when you are finished with it.
  87900. *
  87901. * \param iterator A pointer to an existing initialized iterator.
  87902. * \assert
  87903. * \code iterator != NULL \endcode
  87904. * \a iterator has been successfully initialized with
  87905. * FLAC__metadata_simple_iterator_init()
  87906. * \retval FLAC__StreamMetadata*
  87907. * The current metadata block, or \c NULL if there was a memory
  87908. * allocation error.
  87909. */
  87910. FLAC_API FLAC__StreamMetadata *FLAC__metadata_simple_iterator_get_block(FLAC__Metadata_SimpleIterator *iterator);
  87911. /** Write a block back to the FLAC file. This function tries to be
  87912. * as efficient as possible; how the block is actually written is
  87913. * shown by the following:
  87914. *
  87915. * Existing block is a STREAMINFO block and the new block is a
  87916. * STREAMINFO block: the new block is written in place. Make sure
  87917. * you know what you're doing when changing the values of a
  87918. * STREAMINFO block.
  87919. *
  87920. * Existing block is a STREAMINFO block and the new block is a
  87921. * not a STREAMINFO block: this is an error since the first block
  87922. * must be a STREAMINFO block. Returns \c false without altering the
  87923. * file.
  87924. *
  87925. * Existing block is not a STREAMINFO block and the new block is a
  87926. * STREAMINFO block: this is an error since there may be only one
  87927. * STREAMINFO block. Returns \c false without altering the file.
  87928. *
  87929. * Existing block and new block are the same length: the existing
  87930. * block will be replaced by the new block, written in place.
  87931. *
  87932. * Existing block is longer than new block: if use_padding is \c true,
  87933. * the existing block will be overwritten in place with the new
  87934. * block followed by a PADDING block, if possible, to make the total
  87935. * size the same as the existing block. Remember that a padding
  87936. * block requires at least four bytes so if the difference in size
  87937. * between the new block and existing block is less than that, the
  87938. * entire file will have to be rewritten, using the new block's
  87939. * exact size. If use_padding is \c false, the entire file will be
  87940. * rewritten, replacing the existing block by the new block.
  87941. *
  87942. * Existing block is shorter than new block: if use_padding is \c true,
  87943. * the function will try and expand the new block into the following
  87944. * PADDING block, if it exists and doing so won't shrink the PADDING
  87945. * block to less than 4 bytes. If there is no following PADDING
  87946. * block, or it will shrink to less than 4 bytes, or use_padding is
  87947. * \c false, the entire file is rewritten, replacing the existing block
  87948. * with the new block. Note that in this case any following PADDING
  87949. * block is preserved as is.
  87950. *
  87951. * After writing the block, the iterator will remain in the same
  87952. * place, i.e. pointing to the new block.
  87953. *
  87954. * \param iterator A pointer to an existing initialized iterator.
  87955. * \param block The block to set.
  87956. * \param use_padding See above.
  87957. * \assert
  87958. * \code iterator != NULL \endcode
  87959. * \a iterator has been successfully initialized with
  87960. * FLAC__metadata_simple_iterator_init()
  87961. * \code block != NULL \endcode
  87962. * \retval FLAC__bool
  87963. * \c true if successful, else \c false.
  87964. */
  87965. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_set_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  87966. /** This is similar to FLAC__metadata_simple_iterator_set_block()
  87967. * except that instead of writing over an existing block, it appends
  87968. * a block after the existing block. \a use_padding is again used to
  87969. * tell the function to try an expand into following padding in an
  87970. * attempt to avoid rewriting the entire file.
  87971. *
  87972. * This function will fail and return \c false if given a STREAMINFO
  87973. * block.
  87974. *
  87975. * After writing the block, the iterator will be pointing to the
  87976. * new block.
  87977. *
  87978. * \param iterator A pointer to an existing initialized iterator.
  87979. * \param block The block to set.
  87980. * \param use_padding See above.
  87981. * \assert
  87982. * \code iterator != NULL \endcode
  87983. * \a iterator has been successfully initialized with
  87984. * FLAC__metadata_simple_iterator_init()
  87985. * \code block != NULL \endcode
  87986. * \retval FLAC__bool
  87987. * \c true if successful, else \c false.
  87988. */
  87989. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_insert_block_after(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  87990. /** Deletes the block at the current position. This will cause the
  87991. * entire FLAC file to be rewritten, unless \a use_padding is \c true,
  87992. * in which case the block will be replaced by an equal-sized PADDING
  87993. * block. The iterator will be left pointing to the block before the
  87994. * one just deleted.
  87995. *
  87996. * You may not delete the STREAMINFO block.
  87997. *
  87998. * \param iterator A pointer to an existing initialized iterator.
  87999. * \param use_padding See above.
  88000. * \assert
  88001. * \code iterator != NULL \endcode
  88002. * \a iterator has been successfully initialized with
  88003. * FLAC__metadata_simple_iterator_init()
  88004. * \retval FLAC__bool
  88005. * \c true if successful, else \c false.
  88006. */
  88007. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_delete_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__bool use_padding);
  88008. /* \} */
  88009. /** \defgroup flac_metadata_level2 FLAC/metadata.h: metadata level 2 interface
  88010. * \ingroup flac_metadata
  88011. *
  88012. * \brief
  88013. * The level 2 interface provides read-write access to FLAC file metadata;
  88014. * all metadata is read into memory, operated on in memory, and then written
  88015. * to file, which is more efficient than level 1 when editing multiple blocks.
  88016. *
  88017. * Currently Ogg FLAC is supported for read only, via
  88018. * FLAC__metadata_chain_read_ogg() but a subsequent
  88019. * FLAC__metadata_chain_write() will fail.
  88020. *
  88021. * The general usage of this interface is:
  88022. *
  88023. * - Create a new chain using FLAC__metadata_chain_new(). A chain is a
  88024. * linked list of FLAC metadata blocks.
  88025. * - Read all metadata into the the chain from a FLAC file using
  88026. * FLAC__metadata_chain_read() or FLAC__metadata_chain_read_ogg() and
  88027. * check the status.
  88028. * - Optionally, consolidate the padding using
  88029. * FLAC__metadata_chain_merge_padding() or
  88030. * FLAC__metadata_chain_sort_padding().
  88031. * - Create a new iterator using FLAC__metadata_iterator_new()
  88032. * - Initialize the iterator to point to the first element in the chain
  88033. * using FLAC__metadata_iterator_init()
  88034. * - Traverse the chain using FLAC__metadata_iterator_next and
  88035. * FLAC__metadata_iterator_prev().
  88036. * - Get a block for reading or modification using
  88037. * FLAC__metadata_iterator_get_block(). The pointer to the object
  88038. * inside the chain is returned, so the block is yours to modify.
  88039. * Changes will be reflected in the FLAC file when you write the
  88040. * chain. You can also add and delete blocks (see functions below).
  88041. * - When done, write out the chain using FLAC__metadata_chain_write().
  88042. * Make sure to read the whole comment to the function below.
  88043. * - Delete the chain using FLAC__metadata_chain_delete().
  88044. *
  88045. * \note
  88046. * Even though the FLAC file is not open while the chain is being
  88047. * manipulated, you must not alter the file externally during
  88048. * this time. The chain assumes the FLAC file will not change
  88049. * between the time of FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg()
  88050. * and FLAC__metadata_chain_write().
  88051. *
  88052. * \note
  88053. * Do not modify the is_last, length, or type fields of returned
  88054. * FLAC__StreamMetadata objects. These are managed automatically.
  88055. *
  88056. * \note
  88057. * The metadata objects returned by FLAC__metadata_iterator_get_block()
  88058. * are owned by the chain; do not FLAC__metadata_object_delete() them.
  88059. * In the same way, blocks passed to FLAC__metadata_iterator_set_block()
  88060. * become owned by the chain and they will be deleted when the chain is
  88061. * deleted.
  88062. *
  88063. * \{
  88064. */
  88065. struct FLAC__Metadata_Chain;
  88066. /** The opaque structure definition for the level 2 chain type.
  88067. */
  88068. typedef struct FLAC__Metadata_Chain FLAC__Metadata_Chain;
  88069. struct FLAC__Metadata_Iterator;
  88070. /** The opaque structure definition for the level 2 iterator type.
  88071. */
  88072. typedef struct FLAC__Metadata_Iterator FLAC__Metadata_Iterator;
  88073. typedef enum {
  88074. FLAC__METADATA_CHAIN_STATUS_OK = 0,
  88075. /**< The chain is in the normal OK state */
  88076. FLAC__METADATA_CHAIN_STATUS_ILLEGAL_INPUT,
  88077. /**< The data passed into a function violated the function's usage criteria */
  88078. FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE,
  88079. /**< The chain could not open the target file */
  88080. FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE,
  88081. /**< The chain could not find the FLAC signature at the start of the file */
  88082. FLAC__METADATA_CHAIN_STATUS_NOT_WRITABLE,
  88083. /**< The chain tried to write to a file that was not writable */
  88084. FLAC__METADATA_CHAIN_STATUS_BAD_METADATA,
  88085. /**< The chain encountered input that does not conform to the FLAC metadata specification */
  88086. FLAC__METADATA_CHAIN_STATUS_READ_ERROR,
  88087. /**< The chain encountered an error while reading the FLAC file */
  88088. FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR,
  88089. /**< The chain encountered an error while seeking in the FLAC file */
  88090. FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR,
  88091. /**< The chain encountered an error while writing the FLAC file */
  88092. FLAC__METADATA_CHAIN_STATUS_RENAME_ERROR,
  88093. /**< The chain encountered an error renaming the FLAC file */
  88094. FLAC__METADATA_CHAIN_STATUS_UNLINK_ERROR,
  88095. /**< The chain encountered an error removing the temporary file */
  88096. FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR,
  88097. /**< Memory allocation failed */
  88098. FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR,
  88099. /**< The caller violated an assertion or an unexpected error occurred */
  88100. FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS,
  88101. /**< One or more of the required callbacks was NULL */
  88102. FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH,
  88103. /**< FLAC__metadata_chain_write() was called on a chain read by
  88104. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  88105. * or
  88106. * FLAC__metadata_chain_write_with_callbacks()/FLAC__metadata_chain_write_with_callbacks_and_tempfile()
  88107. * was called on a chain read by
  88108. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  88109. * Matching read/write methods must always be used. */
  88110. FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL
  88111. /**< FLAC__metadata_chain_write_with_callbacks() was called when the
  88112. * chain write requires a tempfile; use
  88113. * FLAC__metadata_chain_write_with_callbacks_and_tempfile() instead.
  88114. * Or, FLAC__metadata_chain_write_with_callbacks_and_tempfile() was
  88115. * called when the chain write does not require a tempfile; use
  88116. * FLAC__metadata_chain_write_with_callbacks() instead.
  88117. * Always check FLAC__metadata_chain_check_if_tempfile_needed()
  88118. * before writing via callbacks. */
  88119. } FLAC__Metadata_ChainStatus;
  88120. /** Maps a FLAC__Metadata_ChainStatus to a C string.
  88121. *
  88122. * Using a FLAC__Metadata_ChainStatus as the index to this array
  88123. * will give the string equivalent. The contents should not be modified.
  88124. */
  88125. extern FLAC_API const char * const FLAC__Metadata_ChainStatusString[];
  88126. /*********** FLAC__Metadata_Chain ***********/
  88127. /** Create a new chain instance.
  88128. *
  88129. * \retval FLAC__Metadata_Chain*
  88130. * \c NULL if there was an error allocating memory, else the new instance.
  88131. */
  88132. FLAC_API FLAC__Metadata_Chain *FLAC__metadata_chain_new(void);
  88133. /** Free a chain instance. Deletes the object pointed to by \a chain.
  88134. *
  88135. * \param chain A pointer to an existing chain.
  88136. * \assert
  88137. * \code chain != NULL \endcode
  88138. */
  88139. FLAC_API void FLAC__metadata_chain_delete(FLAC__Metadata_Chain *chain);
  88140. /** Get the current status of the chain. Call this after a function
  88141. * returns \c false to get the reason for the error. Also resets the
  88142. * status to FLAC__METADATA_CHAIN_STATUS_OK.
  88143. *
  88144. * \param chain A pointer to an existing chain.
  88145. * \assert
  88146. * \code chain != NULL \endcode
  88147. * \retval FLAC__Metadata_ChainStatus
  88148. * The current status of the chain.
  88149. */
  88150. FLAC_API FLAC__Metadata_ChainStatus FLAC__metadata_chain_status(FLAC__Metadata_Chain *chain);
  88151. /** Read all metadata from a FLAC file into the chain.
  88152. *
  88153. * \param chain A pointer to an existing chain.
  88154. * \param filename The path to the FLAC file to read.
  88155. * \assert
  88156. * \code chain != NULL \endcode
  88157. * \code filename != NULL \endcode
  88158. * \retval FLAC__bool
  88159. * \c true if a valid list of metadata blocks was read from
  88160. * \a filename, else \c false. On failure, check the status with
  88161. * FLAC__metadata_chain_status().
  88162. */
  88163. FLAC_API FLAC__bool FLAC__metadata_chain_read(FLAC__Metadata_Chain *chain, const char *filename);
  88164. /** Read all metadata from an Ogg FLAC file into the chain.
  88165. *
  88166. * \note Ogg FLAC metadata data writing is not supported yet and
  88167. * FLAC__metadata_chain_write() will fail.
  88168. *
  88169. * \param chain A pointer to an existing chain.
  88170. * \param filename The path to the Ogg FLAC file to read.
  88171. * \assert
  88172. * \code chain != NULL \endcode
  88173. * \code filename != NULL \endcode
  88174. * \retval FLAC__bool
  88175. * \c true if a valid list of metadata blocks was read from
  88176. * \a filename, else \c false. On failure, check the status with
  88177. * FLAC__metadata_chain_status().
  88178. */
  88179. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg(FLAC__Metadata_Chain *chain, const char *filename);
  88180. /** Read all metadata from a FLAC stream into the chain via I/O callbacks.
  88181. *
  88182. * The \a handle need only be open for reading, but must be seekable.
  88183. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  88184. * for Windows).
  88185. *
  88186. * \param chain A pointer to an existing chain.
  88187. * \param handle The I/O handle of the FLAC stream to read. The
  88188. * handle will NOT be closed after the metadata is read;
  88189. * that is the duty of the caller.
  88190. * \param callbacks
  88191. * A set of callbacks to use for I/O. The mandatory
  88192. * callbacks are \a read, \a seek, and \a tell.
  88193. * \assert
  88194. * \code chain != NULL \endcode
  88195. * \retval FLAC__bool
  88196. * \c true if a valid list of metadata blocks was read from
  88197. * \a handle, else \c false. On failure, check the status with
  88198. * FLAC__metadata_chain_status().
  88199. */
  88200. FLAC_API FLAC__bool FLAC__metadata_chain_read_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  88201. /** Read all metadata from an Ogg FLAC stream into the chain via I/O callbacks.
  88202. *
  88203. * The \a handle need only be open for reading, but must be seekable.
  88204. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  88205. * for Windows).
  88206. *
  88207. * \note Ogg FLAC metadata data writing is not supported yet and
  88208. * FLAC__metadata_chain_write() will fail.
  88209. *
  88210. * \param chain A pointer to an existing chain.
  88211. * \param handle The I/O handle of the Ogg FLAC stream to read. The
  88212. * handle will NOT be closed after the metadata is read;
  88213. * that is the duty of the caller.
  88214. * \param callbacks
  88215. * A set of callbacks to use for I/O. The mandatory
  88216. * callbacks are \a read, \a seek, and \a tell.
  88217. * \assert
  88218. * \code chain != NULL \endcode
  88219. * \retval FLAC__bool
  88220. * \c true if a valid list of metadata blocks was read from
  88221. * \a handle, else \c false. On failure, check the status with
  88222. * FLAC__metadata_chain_status().
  88223. */
  88224. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  88225. /** Checks if writing the given chain would require the use of a
  88226. * temporary file, or if it could be written in place.
  88227. *
  88228. * Under certain conditions, padding can be utilized so that writing
  88229. * edited metadata back to the FLAC file does not require rewriting the
  88230. * entire file. If rewriting is required, then a temporary workfile is
  88231. * required. When writing metadata using callbacks, you must check
  88232. * this function to know whether to call
  88233. * FLAC__metadata_chain_write_with_callbacks() or
  88234. * FLAC__metadata_chain_write_with_callbacks_and_tempfile(). When
  88235. * writing with FLAC__metadata_chain_write(), the temporary file is
  88236. * handled internally.
  88237. *
  88238. * \param chain A pointer to an existing chain.
  88239. * \param use_padding
  88240. * Whether or not padding will be allowed to be used
  88241. * during the write. The value of \a use_padding given
  88242. * here must match the value later passed to
  88243. * FLAC__metadata_chain_write_with_callbacks() or
  88244. * FLAC__metadata_chain_write_with_callbacks_with_tempfile().
  88245. * \assert
  88246. * \code chain != NULL \endcode
  88247. * \retval FLAC__bool
  88248. * \c true if writing the current chain would require a tempfile, or
  88249. * \c false if metadata can be written in place.
  88250. */
  88251. FLAC_API FLAC__bool FLAC__metadata_chain_check_if_tempfile_needed(FLAC__Metadata_Chain *chain, FLAC__bool use_padding);
  88252. /** Write all metadata out to the FLAC file. This function tries to be as
  88253. * efficient as possible; how the metadata is actually written is shown by
  88254. * the following:
  88255. *
  88256. * If the current chain is the same size as the existing metadata, the new
  88257. * data is written in place.
  88258. *
  88259. * If the current chain is longer than the existing metadata, and
  88260. * \a use_padding is \c true, and the last block is a PADDING block of
  88261. * sufficient length, the function will truncate the final padding block
  88262. * so that the overall size of the metadata is the same as the existing
  88263. * metadata, and then just rewrite the metadata. Otherwise, if not all of
  88264. * the above conditions are met, the entire FLAC file must be rewritten.
  88265. * If you want to use padding this way it is a good idea to call
  88266. * FLAC__metadata_chain_sort_padding() first so that you have the maximum
  88267. * amount of padding to work with, unless you need to preserve ordering
  88268. * of the PADDING blocks for some reason.
  88269. *
  88270. * If the current chain is shorter than the existing metadata, and
  88271. * \a use_padding is \c true, and the final block is a PADDING block, the padding
  88272. * is extended to make the overall size the same as the existing data. If
  88273. * \a use_padding is \c true and the last block is not a PADDING block, a new
  88274. * PADDING block is added to the end of the new data to make it the same
  88275. * size as the existing data (if possible, see the note to
  88276. * FLAC__metadata_simple_iterator_set_block() about the four byte limit)
  88277. * and the new data is written in place. If none of the above apply or
  88278. * \a use_padding is \c false, the entire FLAC file is rewritten.
  88279. *
  88280. * If \a preserve_file_stats is \c true, the owner and modification time will
  88281. * be preserved even if the FLAC file is written.
  88282. *
  88283. * For this write function to be used, the chain must have been read with
  88284. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg(), not
  88285. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks().
  88286. *
  88287. * \param chain A pointer to an existing chain.
  88288. * \param use_padding See above.
  88289. * \param preserve_file_stats See above.
  88290. * \assert
  88291. * \code chain != NULL \endcode
  88292. * \retval FLAC__bool
  88293. * \c true if the write succeeded, else \c false. On failure,
  88294. * check the status with FLAC__metadata_chain_status().
  88295. */
  88296. FLAC_API FLAC__bool FLAC__metadata_chain_write(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__bool preserve_file_stats);
  88297. /** Write all metadata out to a FLAC stream via callbacks.
  88298. *
  88299. * (See FLAC__metadata_chain_write() for the details on how padding is
  88300. * used to write metadata in place if possible.)
  88301. *
  88302. * The \a handle must be open for updating and be seekable. The
  88303. * equivalent minimum stdio fopen() file mode is \c "r+" (or \c "r+b"
  88304. * for Windows).
  88305. *
  88306. * For this write function to be used, the chain must have been read with
  88307. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  88308. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  88309. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  88310. * \c false.
  88311. *
  88312. * \param chain A pointer to an existing chain.
  88313. * \param use_padding See FLAC__metadata_chain_write()
  88314. * \param handle The I/O handle of the FLAC stream to write. The
  88315. * handle will NOT be closed after the metadata is
  88316. * written; that is the duty of the caller.
  88317. * \param callbacks A set of callbacks to use for I/O. The mandatory
  88318. * callbacks are \a write and \a seek.
  88319. * \assert
  88320. * \code chain != NULL \endcode
  88321. * \retval FLAC__bool
  88322. * \c true if the write succeeded, else \c false. On failure,
  88323. * check the status with FLAC__metadata_chain_status().
  88324. */
  88325. FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  88326. /** Write all metadata out to a FLAC stream via callbacks.
  88327. *
  88328. * (See FLAC__metadata_chain_write() for the details on how padding is
  88329. * used to write metadata in place if possible.)
  88330. *
  88331. * This version of the write-with-callbacks function must be used when
  88332. * FLAC__metadata_chain_check_if_tempfile_needed() returns true. In
  88333. * this function, you must supply an I/O handle corresponding to the
  88334. * FLAC file to edit, and a temporary handle to which the new FLAC
  88335. * file will be written. It is the caller's job to move this temporary
  88336. * FLAC file on top of the original FLAC file to complete the metadata
  88337. * edit.
  88338. *
  88339. * The \a handle must be open for reading and be seekable. The
  88340. * equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  88341. * for Windows).
  88342. *
  88343. * The \a temp_handle must be open for writing. The
  88344. * equivalent minimum stdio fopen() file mode is \c "w" (or \c "wb"
  88345. * for Windows). It should be an empty stream, or at least positioned
  88346. * at the start-of-file (in which case it is the caller's duty to
  88347. * truncate it on return).
  88348. *
  88349. * For this write function to be used, the chain must have been read with
  88350. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  88351. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  88352. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  88353. * \c true.
  88354. *
  88355. * \param chain A pointer to an existing chain.
  88356. * \param use_padding See FLAC__metadata_chain_write()
  88357. * \param handle The I/O handle of the original FLAC stream to read.
  88358. * The handle will NOT be closed after the metadata is
  88359. * written; that is the duty of the caller.
  88360. * \param callbacks A set of callbacks to use for I/O on \a handle.
  88361. * The mandatory callbacks are \a read, \a seek, and
  88362. * \a eof.
  88363. * \param temp_handle The I/O handle of the FLAC stream to write. The
  88364. * handle will NOT be closed after the metadata is
  88365. * written; that is the duty of the caller.
  88366. * \param temp_callbacks
  88367. * A set of callbacks to use for I/O on temp_handle.
  88368. * The only mandatory callback is \a write.
  88369. * \assert
  88370. * \code chain != NULL \endcode
  88371. * \retval FLAC__bool
  88372. * \c true if the write succeeded, else \c false. On failure,
  88373. * check the status with FLAC__metadata_chain_status().
  88374. */
  88375. 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);
  88376. /** Merge adjacent PADDING blocks into a single block.
  88377. *
  88378. * \note This function does not write to the FLAC file, it only
  88379. * modifies the chain.
  88380. *
  88381. * \warning Any iterator on the current chain will become invalid after this
  88382. * call. You should delete the iterator and get a new one.
  88383. *
  88384. * \param chain A pointer to an existing chain.
  88385. * \assert
  88386. * \code chain != NULL \endcode
  88387. */
  88388. FLAC_API void FLAC__metadata_chain_merge_padding(FLAC__Metadata_Chain *chain);
  88389. /** This function will move all PADDING blocks to the end on the metadata,
  88390. * then merge them into a single block.
  88391. *
  88392. * \note This function does not write to the FLAC file, it only
  88393. * modifies the chain.
  88394. *
  88395. * \warning Any iterator on the current chain will become invalid after this
  88396. * call. You should delete the iterator and get a new one.
  88397. *
  88398. * \param chain A pointer to an existing chain.
  88399. * \assert
  88400. * \code chain != NULL \endcode
  88401. */
  88402. FLAC_API void FLAC__metadata_chain_sort_padding(FLAC__Metadata_Chain *chain);
  88403. /*********** FLAC__Metadata_Iterator ***********/
  88404. /** Create a new iterator instance.
  88405. *
  88406. * \retval FLAC__Metadata_Iterator*
  88407. * \c NULL if there was an error allocating memory, else the new instance.
  88408. */
  88409. FLAC_API FLAC__Metadata_Iterator *FLAC__metadata_iterator_new(void);
  88410. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  88411. *
  88412. * \param iterator A pointer to an existing iterator.
  88413. * \assert
  88414. * \code iterator != NULL \endcode
  88415. */
  88416. FLAC_API void FLAC__metadata_iterator_delete(FLAC__Metadata_Iterator *iterator);
  88417. /** Initialize the iterator to point to the first metadata block in the
  88418. * given chain.
  88419. *
  88420. * \param iterator A pointer to an existing iterator.
  88421. * \param chain A pointer to an existing and initialized (read) chain.
  88422. * \assert
  88423. * \code iterator != NULL \endcode
  88424. * \code chain != NULL \endcode
  88425. */
  88426. FLAC_API void FLAC__metadata_iterator_init(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Chain *chain);
  88427. /** Moves the iterator forward one metadata block, returning \c false if
  88428. * already at the end.
  88429. *
  88430. * \param iterator A pointer to an existing initialized iterator.
  88431. * \assert
  88432. * \code iterator != NULL \endcode
  88433. * \a iterator has been successfully initialized with
  88434. * FLAC__metadata_iterator_init()
  88435. * \retval FLAC__bool
  88436. * \c false if already at the last metadata block of the chain, else
  88437. * \c true.
  88438. */
  88439. FLAC_API FLAC__bool FLAC__metadata_iterator_next(FLAC__Metadata_Iterator *iterator);
  88440. /** Moves the iterator backward one metadata block, returning \c false if
  88441. * already at the beginning.
  88442. *
  88443. * \param iterator A pointer to an existing initialized iterator.
  88444. * \assert
  88445. * \code iterator != NULL \endcode
  88446. * \a iterator has been successfully initialized with
  88447. * FLAC__metadata_iterator_init()
  88448. * \retval FLAC__bool
  88449. * \c false if already at the first metadata block of the chain, else
  88450. * \c true.
  88451. */
  88452. FLAC_API FLAC__bool FLAC__metadata_iterator_prev(FLAC__Metadata_Iterator *iterator);
  88453. /** Get the type of the metadata block at the current position.
  88454. *
  88455. * \param iterator A pointer to an existing initialized iterator.
  88456. * \assert
  88457. * \code iterator != NULL \endcode
  88458. * \a iterator has been successfully initialized with
  88459. * FLAC__metadata_iterator_init()
  88460. * \retval FLAC__MetadataType
  88461. * The type of the metadata block at the current iterator position.
  88462. */
  88463. FLAC_API FLAC__MetadataType FLAC__metadata_iterator_get_block_type(const FLAC__Metadata_Iterator *iterator);
  88464. /** Get the metadata block at the current position. You can modify
  88465. * the block in place but must write the chain before the changes
  88466. * are reflected to the FLAC file. You do not need to call
  88467. * FLAC__metadata_iterator_set_block() to reflect the changes;
  88468. * the pointer returned by FLAC__metadata_iterator_get_block()
  88469. * points directly into the chain.
  88470. *
  88471. * \warning
  88472. * Do not call FLAC__metadata_object_delete() on the returned object;
  88473. * to delete a block use FLAC__metadata_iterator_delete_block().
  88474. *
  88475. * \param iterator A pointer to an existing initialized iterator.
  88476. * \assert
  88477. * \code iterator != NULL \endcode
  88478. * \a iterator has been successfully initialized with
  88479. * FLAC__metadata_iterator_init()
  88480. * \retval FLAC__StreamMetadata*
  88481. * The current metadata block.
  88482. */
  88483. FLAC_API FLAC__StreamMetadata *FLAC__metadata_iterator_get_block(FLAC__Metadata_Iterator *iterator);
  88484. /** Set the metadata block at the current position, replacing the existing
  88485. * block. The new block passed in becomes owned by the chain and it will be
  88486. * deleted when the chain is deleted.
  88487. *
  88488. * \param iterator A pointer to an existing initialized iterator.
  88489. * \param block A pointer to a metadata block.
  88490. * \assert
  88491. * \code iterator != NULL \endcode
  88492. * \a iterator has been successfully initialized with
  88493. * FLAC__metadata_iterator_init()
  88494. * \code block != NULL \endcode
  88495. * \retval FLAC__bool
  88496. * \c false if the conditions in the above description are not met, or
  88497. * a memory allocation error occurs, otherwise \c true.
  88498. */
  88499. FLAC_API FLAC__bool FLAC__metadata_iterator_set_block(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88500. /** Removes the current block from the chain. If \a replace_with_padding is
  88501. * \c true, the block will instead be replaced with a padding block of equal
  88502. * size. You can not delete the STREAMINFO block. The iterator will be
  88503. * left pointing to the block before the one just "deleted", even if
  88504. * \a replace_with_padding is \c true.
  88505. *
  88506. * \param iterator A pointer to an existing initialized iterator.
  88507. * \param replace_with_padding See above.
  88508. * \assert
  88509. * \code iterator != NULL \endcode
  88510. * \a iterator has been successfully initialized with
  88511. * FLAC__metadata_iterator_init()
  88512. * \retval FLAC__bool
  88513. * \c false if the conditions in the above description are not met,
  88514. * otherwise \c true.
  88515. */
  88516. FLAC_API FLAC__bool FLAC__metadata_iterator_delete_block(FLAC__Metadata_Iterator *iterator, FLAC__bool replace_with_padding);
  88517. /** Insert a new block before the current block. You cannot insert a block
  88518. * before the first STREAMINFO block. You cannot insert a STREAMINFO block
  88519. * as there can be only one, the one that already exists at the head when you
  88520. * read in a chain. The chain takes ownership of the new block and it will be
  88521. * deleted when the chain is deleted. The iterator will be left pointing to
  88522. * the new block.
  88523. *
  88524. * \param iterator A pointer to an existing initialized iterator.
  88525. * \param block A pointer to a metadata block to insert.
  88526. * \assert
  88527. * \code iterator != NULL \endcode
  88528. * \a iterator has been successfully initialized with
  88529. * FLAC__metadata_iterator_init()
  88530. * \retval FLAC__bool
  88531. * \c false if the conditions in the above description are not met, or
  88532. * a memory allocation error occurs, otherwise \c true.
  88533. */
  88534. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_before(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88535. /** Insert a new block after the current block. You cannot insert a STREAMINFO
  88536. * block as there can be only one, the one that already exists at the head when
  88537. * you read in a chain. The chain takes ownership of the new block and it will
  88538. * be deleted when the chain is deleted. The iterator will be left pointing to
  88539. * the new block.
  88540. *
  88541. * \param iterator A pointer to an existing initialized iterator.
  88542. * \param block A pointer to a metadata block to insert.
  88543. * \assert
  88544. * \code iterator != NULL \endcode
  88545. * \a iterator has been successfully initialized with
  88546. * FLAC__metadata_iterator_init()
  88547. * \retval FLAC__bool
  88548. * \c false if the conditions in the above description are not met, or
  88549. * a memory allocation error occurs, otherwise \c true.
  88550. */
  88551. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_after(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88552. /* \} */
  88553. /** \defgroup flac_metadata_object FLAC/metadata.h: metadata object methods
  88554. * \ingroup flac_metadata
  88555. *
  88556. * \brief
  88557. * This module contains methods for manipulating FLAC metadata objects.
  88558. *
  88559. * Since many are variable length we have to be careful about the memory
  88560. * management. We decree that all pointers to data in the object are
  88561. * owned by the object and memory-managed by the object.
  88562. *
  88563. * Use the FLAC__metadata_object_new() and FLAC__metadata_object_delete()
  88564. * functions to create all instances. When using the
  88565. * FLAC__metadata_object_set_*() functions to set pointers to data, set
  88566. * \a copy to \c true to have the function make it's own copy of the data, or
  88567. * to \c false to give the object ownership of your data. In the latter case
  88568. * your pointer must be freeable by free() and will be free()d when the object
  88569. * is FLAC__metadata_object_delete()d. It is legal to pass a null pointer as
  88570. * the data pointer to a FLAC__metadata_object_set_*() function as long as
  88571. * the length argument is 0 and the \a copy argument is \c false.
  88572. *
  88573. * The FLAC__metadata_object_new() and FLAC__metadata_object_clone() function
  88574. * will return \c NULL in the case of a memory allocation error, otherwise a new
  88575. * object. The FLAC__metadata_object_set_*() functions return \c false in the
  88576. * case of a memory allocation error.
  88577. *
  88578. * We don't have the convenience of C++ here, so note that the library relies
  88579. * on you to keep the types straight. In other words, if you pass, for
  88580. * example, a FLAC__StreamMetadata* that represents a STREAMINFO block to
  88581. * FLAC__metadata_object_application_set_data(), you will get an assertion
  88582. * failure.
  88583. *
  88584. * For convenience the FLAC__metadata_object_vorbiscomment_*() functions
  88585. * maintain a trailing NUL on each Vorbis comment entry. This is not counted
  88586. * toward the length or stored in the stream, but it can make working with plain
  88587. * comments (those that don't contain embedded-NULs in the value) easier.
  88588. * Entries passed into these functions have trailing NULs added if missing, and
  88589. * returned entries are guaranteed to have a trailing NUL.
  88590. *
  88591. * The FLAC__metadata_object_vorbiscomment_*() functions that take a Vorbis
  88592. * comment entry/name/value will first validate that it complies with the Vorbis
  88593. * comment specification and return false if it does not.
  88594. *
  88595. * There is no need to recalculate the length field on metadata blocks you
  88596. * have modified. They will be calculated automatically before they are
  88597. * written back to a file.
  88598. *
  88599. * \{
  88600. */
  88601. /** Create a new metadata object instance of the given type.
  88602. *
  88603. * The object will be "empty"; i.e. values and data pointers will be \c 0,
  88604. * with the exception of FLAC__METADATA_TYPE_VORBIS_COMMENT, which will have
  88605. * the vendor string set (but zero comments).
  88606. *
  88607. * Do not pass in a value greater than or equal to
  88608. * \a FLAC__METADATA_TYPE_UNDEFINED unless you really know what you're
  88609. * doing.
  88610. *
  88611. * \param type Type of object to create
  88612. * \retval FLAC__StreamMetadata*
  88613. * \c NULL if there was an error allocating memory or the type code is
  88614. * greater than FLAC__MAX_METADATA_TYPE_CODE, else the new instance.
  88615. */
  88616. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_new(FLAC__MetadataType type);
  88617. /** Create a copy of an existing metadata object.
  88618. *
  88619. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  88620. * object is also copied. The caller takes ownership of the new block and
  88621. * is responsible for freeing it with FLAC__metadata_object_delete().
  88622. *
  88623. * \param object Pointer to object to copy.
  88624. * \assert
  88625. * \code object != NULL \endcode
  88626. * \retval FLAC__StreamMetadata*
  88627. * \c NULL if there was an error allocating memory, else the new instance.
  88628. */
  88629. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_clone(const FLAC__StreamMetadata *object);
  88630. /** Free a metadata object. Deletes the object pointed to by \a object.
  88631. *
  88632. * The delete is a "deep" delete, i.e. dynamically allocated data within the
  88633. * object is also deleted.
  88634. *
  88635. * \param object A pointer to an existing object.
  88636. * \assert
  88637. * \code object != NULL \endcode
  88638. */
  88639. FLAC_API void FLAC__metadata_object_delete(FLAC__StreamMetadata *object);
  88640. /** Compares two metadata objects.
  88641. *
  88642. * The compare is "deep", i.e. dynamically allocated data within the
  88643. * object is also compared.
  88644. *
  88645. * \param block1 A pointer to an existing object.
  88646. * \param block2 A pointer to an existing object.
  88647. * \assert
  88648. * \code block1 != NULL \endcode
  88649. * \code block2 != NULL \endcode
  88650. * \retval FLAC__bool
  88651. * \c true if objects are identical, else \c false.
  88652. */
  88653. FLAC_API FLAC__bool FLAC__metadata_object_is_equal(const FLAC__StreamMetadata *block1, const FLAC__StreamMetadata *block2);
  88654. /** Sets the application data of an APPLICATION block.
  88655. *
  88656. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  88657. * takes ownership of the pointer. The existing data will be freed if this
  88658. * function is successful, otherwise the original data will remain if \a copy
  88659. * is \c true and malloc() fails.
  88660. *
  88661. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  88662. *
  88663. * \param object A pointer to an existing APPLICATION object.
  88664. * \param data A pointer to the data to set.
  88665. * \param length The length of \a data in bytes.
  88666. * \param copy See above.
  88667. * \assert
  88668. * \code object != NULL \endcode
  88669. * \code object->type == FLAC__METADATA_TYPE_APPLICATION \endcode
  88670. * \code (data != NULL && length > 0) ||
  88671. * (data == NULL && length == 0 && copy == false) \endcode
  88672. * \retval FLAC__bool
  88673. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88674. */
  88675. FLAC_API FLAC__bool FLAC__metadata_object_application_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, unsigned length, FLAC__bool copy);
  88676. /** Resize the seekpoint array.
  88677. *
  88678. * If the size shrinks, elements will truncated; if it grows, new placeholder
  88679. * points will be added to the end.
  88680. *
  88681. * \param object A pointer to an existing SEEKTABLE object.
  88682. * \param new_num_points The desired length of the array; may be \c 0.
  88683. * \assert
  88684. * \code object != NULL \endcode
  88685. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88686. * \code (object->data.seek_table.points == NULL && object->data.seek_table.num_points == 0) ||
  88687. * (object->data.seek_table.points != NULL && object->data.seek_table.num_points > 0) \endcode
  88688. * \retval FLAC__bool
  88689. * \c false if memory allocation error, else \c true.
  88690. */
  88691. FLAC_API FLAC__bool FLAC__metadata_object_seektable_resize_points(FLAC__StreamMetadata *object, unsigned new_num_points);
  88692. /** Set a seekpoint in a seektable.
  88693. *
  88694. * \param object A pointer to an existing SEEKTABLE object.
  88695. * \param point_num Index into seekpoint array to set.
  88696. * \param point The point to set.
  88697. * \assert
  88698. * \code object != NULL \endcode
  88699. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88700. * \code object->data.seek_table.num_points > point_num \endcode
  88701. */
  88702. FLAC_API void FLAC__metadata_object_seektable_set_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  88703. /** Insert a seekpoint into a seektable.
  88704. *
  88705. * \param object A pointer to an existing SEEKTABLE object.
  88706. * \param point_num Index into seekpoint array to set.
  88707. * \param point The point to set.
  88708. * \assert
  88709. * \code object != NULL \endcode
  88710. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88711. * \code object->data.seek_table.num_points >= point_num \endcode
  88712. * \retval FLAC__bool
  88713. * \c false if memory allocation error, else \c true.
  88714. */
  88715. FLAC_API FLAC__bool FLAC__metadata_object_seektable_insert_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  88716. /** Delete a seekpoint from a seektable.
  88717. *
  88718. * \param object A pointer to an existing SEEKTABLE object.
  88719. * \param point_num Index into seekpoint array to set.
  88720. * \assert
  88721. * \code object != NULL \endcode
  88722. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88723. * \code object->data.seek_table.num_points > point_num \endcode
  88724. * \retval FLAC__bool
  88725. * \c false if memory allocation error, else \c true.
  88726. */
  88727. FLAC_API FLAC__bool FLAC__metadata_object_seektable_delete_point(FLAC__StreamMetadata *object, unsigned point_num);
  88728. /** Check a seektable to see if it conforms to the FLAC specification.
  88729. * See the format specification for limits on the contents of the
  88730. * seektable.
  88731. *
  88732. * \param object A pointer to an existing SEEKTABLE object.
  88733. * \assert
  88734. * \code object != NULL \endcode
  88735. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88736. * \retval FLAC__bool
  88737. * \c false if seek table is illegal, else \c true.
  88738. */
  88739. FLAC_API FLAC__bool FLAC__metadata_object_seektable_is_legal(const FLAC__StreamMetadata *object);
  88740. /** Append a number of placeholder points to the end of a seek table.
  88741. *
  88742. * \note
  88743. * As with the other ..._seektable_template_... functions, you should
  88744. * call FLAC__metadata_object_seektable_template_sort() when finished
  88745. * to make the seek table legal.
  88746. *
  88747. * \param object A pointer to an existing SEEKTABLE object.
  88748. * \param num The number of placeholder points to append.
  88749. * \assert
  88750. * \code object != NULL \endcode
  88751. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88752. * \retval FLAC__bool
  88753. * \c false if memory allocation fails, else \c true.
  88754. */
  88755. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_placeholders(FLAC__StreamMetadata *object, unsigned num);
  88756. /** Append a specific seek point template to the end of a seek table.
  88757. *
  88758. * \note
  88759. * As with the other ..._seektable_template_... functions, you should
  88760. * call FLAC__metadata_object_seektable_template_sort() when finished
  88761. * to make the seek table legal.
  88762. *
  88763. * \param object A pointer to an existing SEEKTABLE object.
  88764. * \param sample_number The sample number of the seek point template.
  88765. * \assert
  88766. * \code object != NULL \endcode
  88767. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88768. * \retval FLAC__bool
  88769. * \c false if memory allocation fails, else \c true.
  88770. */
  88771. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_point(FLAC__StreamMetadata *object, FLAC__uint64 sample_number);
  88772. /** Append specific seek point templates to the end of a seek table.
  88773. *
  88774. * \note
  88775. * As with the other ..._seektable_template_... functions, you should
  88776. * call FLAC__metadata_object_seektable_template_sort() when finished
  88777. * to make the seek table legal.
  88778. *
  88779. * \param object A pointer to an existing SEEKTABLE object.
  88780. * \param sample_numbers An array of sample numbers for the seek points.
  88781. * \param num The number of seek point templates to append.
  88782. * \assert
  88783. * \code object != NULL \endcode
  88784. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88785. * \retval FLAC__bool
  88786. * \c false if memory allocation fails, else \c true.
  88787. */
  88788. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_points(FLAC__StreamMetadata *object, FLAC__uint64 sample_numbers[], unsigned num);
  88789. /** Append a set of evenly-spaced seek point templates to the end of a
  88790. * seek table.
  88791. *
  88792. * \note
  88793. * As with the other ..._seektable_template_... functions, you should
  88794. * call FLAC__metadata_object_seektable_template_sort() when finished
  88795. * to make the seek table legal.
  88796. *
  88797. * \param object A pointer to an existing SEEKTABLE object.
  88798. * \param num The number of placeholder points to append.
  88799. * \param total_samples The total number of samples to be encoded;
  88800. * the seekpoints will be spaced approximately
  88801. * \a total_samples / \a num samples apart.
  88802. * \assert
  88803. * \code object != NULL \endcode
  88804. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88805. * \code total_samples > 0 \endcode
  88806. * \retval FLAC__bool
  88807. * \c false if memory allocation fails, else \c true.
  88808. */
  88809. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points(FLAC__StreamMetadata *object, unsigned num, FLAC__uint64 total_samples);
  88810. /** Append a set of evenly-spaced seek point templates to the end of a
  88811. * seek table.
  88812. *
  88813. * \note
  88814. * As with the other ..._seektable_template_... functions, you should
  88815. * call FLAC__metadata_object_seektable_template_sort() when finished
  88816. * to make the seek table legal.
  88817. *
  88818. * \param object A pointer to an existing SEEKTABLE object.
  88819. * \param samples The number of samples apart to space the placeholder
  88820. * points. The first point will be at sample \c 0, the
  88821. * second at sample \a samples, then 2*\a samples, and
  88822. * so on. As long as \a samples and \a total_samples
  88823. * are greater than \c 0, there will always be at least
  88824. * one seekpoint at sample \c 0.
  88825. * \param total_samples The total number of samples to be encoded;
  88826. * the seekpoints will be spaced
  88827. * \a samples samples apart.
  88828. * \assert
  88829. * \code object != NULL \endcode
  88830. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88831. * \code samples > 0 \endcode
  88832. * \code total_samples > 0 \endcode
  88833. * \retval FLAC__bool
  88834. * \c false if memory allocation fails, else \c true.
  88835. */
  88836. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points_by_samples(FLAC__StreamMetadata *object, unsigned samples, FLAC__uint64 total_samples);
  88837. /** Sort a seek table's seek points according to the format specification,
  88838. * removing duplicates.
  88839. *
  88840. * \param object A pointer to a seek table to be sorted.
  88841. * \param compact If \c false, behaves like FLAC__format_seektable_sort().
  88842. * If \c true, duplicates are deleted and the seek table is
  88843. * shrunk appropriately; the number of placeholder points
  88844. * present in the seek table will be the same after the call
  88845. * as before.
  88846. * \assert
  88847. * \code object != NULL \endcode
  88848. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88849. * \retval FLAC__bool
  88850. * \c false if realloc() fails, else \c true.
  88851. */
  88852. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_sort(FLAC__StreamMetadata *object, FLAC__bool compact);
  88853. /** Sets the vendor string in a VORBIS_COMMENT block.
  88854. *
  88855. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88856. * one already.
  88857. *
  88858. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88859. * takes ownership of the \c entry.entry pointer.
  88860. *
  88861. * \note If this function returns \c false, the caller still owns the
  88862. * pointer.
  88863. *
  88864. * \param object A pointer to an existing VORBIS_COMMENT object.
  88865. * \param entry The entry to set the vendor string to.
  88866. * \param copy See above.
  88867. * \assert
  88868. * \code object != NULL \endcode
  88869. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \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_vendor_string(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88877. /** Resize the comment array.
  88878. *
  88879. * If the size shrinks, elements will truncated; if it grows, new empty
  88880. * fields will be added to the end.
  88881. *
  88882. * \param object A pointer to an existing VORBIS_COMMENT object.
  88883. * \param new_num_comments The desired length of the array; may be \c 0.
  88884. * \assert
  88885. * \code object != NULL \endcode
  88886. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88887. * \code (object->data.vorbis_comment.comments == NULL && object->data.vorbis_comment.num_comments == 0) ||
  88888. * (object->data.vorbis_comment.comments != NULL && object->data.vorbis_comment.num_comments > 0) \endcode
  88889. * \retval FLAC__bool
  88890. * \c false if memory allocation fails, else \c true.
  88891. */
  88892. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_resize_comments(FLAC__StreamMetadata *object, unsigned new_num_comments);
  88893. /** Sets a comment in a VORBIS_COMMENT block.
  88894. *
  88895. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88896. * one already.
  88897. *
  88898. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88899. * takes ownership of the \c entry.entry pointer.
  88900. *
  88901. * \note If this function returns \c false, the caller still owns the
  88902. * pointer.
  88903. *
  88904. * \param object A pointer to an existing VORBIS_COMMENT object.
  88905. * \param comment_num Index into comment array to set.
  88906. * \param entry The entry to set the comment to.
  88907. * \param copy See above.
  88908. * \assert
  88909. * \code object != NULL \endcode
  88910. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88911. * \code comment_num < object->data.vorbis_comment.num_comments \endcode
  88912. * \code (entry.entry != NULL && entry.length > 0) ||
  88913. * (entry.entry == NULL && entry.length == 0) \endcode
  88914. * \retval FLAC__bool
  88915. * \c false if memory allocation fails or \a entry does not comply with the
  88916. * Vorbis comment specification, else \c true.
  88917. */
  88918. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88919. /** Insert a comment in a VORBIS_COMMENT block at the given index.
  88920. *
  88921. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88922. * one already.
  88923. *
  88924. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88925. * takes ownership of the \c entry.entry pointer.
  88926. *
  88927. * \note If this function returns \c false, the caller still owns the
  88928. * pointer.
  88929. *
  88930. * \param object A pointer to an existing VORBIS_COMMENT object.
  88931. * \param comment_num The index at which to insert the comment. The comments
  88932. * at and after \a comment_num move right one position.
  88933. * To append a comment to the end, set \a comment_num to
  88934. * \c object->data.vorbis_comment.num_comments .
  88935. * \param entry The comment to insert.
  88936. * \param copy See above.
  88937. * \assert
  88938. * \code object != NULL \endcode
  88939. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88940. * \code object->data.vorbis_comment.num_comments >= comment_num \endcode
  88941. * \code (entry.entry != NULL && entry.length > 0) ||
  88942. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  88943. * \retval FLAC__bool
  88944. * \c false if memory allocation fails or \a entry does not comply with the
  88945. * Vorbis comment specification, else \c true.
  88946. */
  88947. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_insert_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88948. /** Appends a comment to a VORBIS_COMMENT block.
  88949. *
  88950. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88951. * one already.
  88952. *
  88953. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88954. * takes ownership of the \c entry.entry pointer.
  88955. *
  88956. * \note If this function returns \c false, the caller still owns the
  88957. * pointer.
  88958. *
  88959. * \param object A pointer to an existing VORBIS_COMMENT object.
  88960. * \param entry The comment to insert.
  88961. * \param copy See above.
  88962. * \assert
  88963. * \code object != NULL \endcode
  88964. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88965. * \code (entry.entry != NULL && entry.length > 0) ||
  88966. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  88967. * \retval FLAC__bool
  88968. * \c false if memory allocation fails or \a entry does not comply with the
  88969. * Vorbis comment specification, else \c true.
  88970. */
  88971. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_append_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88972. /** Replaces comments in a VORBIS_COMMENT block with a new one.
  88973. *
  88974. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88975. * one already.
  88976. *
  88977. * Depending on the the value of \a all, either all or just the first comment
  88978. * whose field name(s) match the given entry's name will be replaced by the
  88979. * given entry. If no comments match, \a entry will simply be appended.
  88980. *
  88981. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88982. * takes ownership of the \c entry.entry pointer.
  88983. *
  88984. * \note If this function returns \c false, the caller still owns the
  88985. * pointer.
  88986. *
  88987. * \param object A pointer to an existing VORBIS_COMMENT object.
  88988. * \param entry The comment to insert.
  88989. * \param all If \c true, all comments whose field name matches
  88990. * \a entry's field name will be removed, and \a entry will
  88991. * be inserted at the position of the first matching
  88992. * comment. If \c false, only the first comment whose
  88993. * field name matches \a entry's field name will be
  88994. * replaced with \a entry.
  88995. * \param copy See above.
  88996. * \assert
  88997. * \code object != NULL \endcode
  88998. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88999. * \code (entry.entry != NULL && entry.length > 0) ||
  89000. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  89001. * \retval FLAC__bool
  89002. * \c false if memory allocation fails or \a entry does not comply with the
  89003. * Vorbis comment specification, else \c true.
  89004. */
  89005. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_replace_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool all, FLAC__bool copy);
  89006. /** Delete a comment in a VORBIS_COMMENT block at the given index.
  89007. *
  89008. * \param object A pointer to an existing VORBIS_COMMENT object.
  89009. * \param comment_num The index of the comment to delete.
  89010. * \assert
  89011. * \code object != NULL \endcode
  89012. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89013. * \code object->data.vorbis_comment.num_comments > comment_num \endcode
  89014. * \retval FLAC__bool
  89015. * \c false if realloc() fails, else \c true.
  89016. */
  89017. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_delete_comment(FLAC__StreamMetadata *object, unsigned comment_num);
  89018. /** Creates a Vorbis comment entry from NUL-terminated name and value strings.
  89019. *
  89020. * On return, the filled-in \a entry->entry pointer will point to malloc()ed
  89021. * memory and shall be owned by the caller. For convenience the entry will
  89022. * have a terminating NUL.
  89023. *
  89024. * \param entry A pointer to a Vorbis comment entry. The entry's
  89025. * \c entry pointer should not point to allocated
  89026. * memory as it will be overwritten.
  89027. * \param field_name The field name in ASCII, \c NUL terminated.
  89028. * \param field_value The field value in UTF-8, \c NUL terminated.
  89029. * \assert
  89030. * \code entry != NULL \endcode
  89031. * \code field_name != NULL \endcode
  89032. * \code field_value != NULL \endcode
  89033. * \retval FLAC__bool
  89034. * \c false if malloc() fails, or if \a field_name or \a field_value does
  89035. * not comply with the Vorbis comment specification, else \c true.
  89036. */
  89037. 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);
  89038. /** Splits a Vorbis comment entry into NUL-terminated name and value strings.
  89039. *
  89040. * The returned pointers to name and value will be allocated by malloc()
  89041. * and shall be owned by the caller.
  89042. *
  89043. * \param entry An existing Vorbis comment entry.
  89044. * \param field_name The address of where the returned pointer to the
  89045. * field name will be stored.
  89046. * \param field_value The address of where the returned pointer to the
  89047. * field value will be stored.
  89048. * \assert
  89049. * \code (entry.entry != NULL && entry.length > 0) \endcode
  89050. * \code memchr(entry.entry, '=', entry.length) != NULL \endcode
  89051. * \code field_name != NULL \endcode
  89052. * \code field_value != NULL \endcode
  89053. * \retval FLAC__bool
  89054. * \c false if memory allocation fails or \a entry does not comply with the
  89055. * Vorbis comment specification, else \c true.
  89056. */
  89057. 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);
  89058. /** Check if the given Vorbis comment entry's field name matches the given
  89059. * field name.
  89060. *
  89061. * \param entry An existing Vorbis comment entry.
  89062. * \param field_name The field name to check.
  89063. * \param field_name_length The length of \a field_name, not including the
  89064. * terminating \c NUL.
  89065. * \assert
  89066. * \code (entry.entry != NULL && entry.length > 0) \endcode
  89067. * \retval FLAC__bool
  89068. * \c true if the field names match, else \c false
  89069. */
  89070. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_matches(const FLAC__StreamMetadata_VorbisComment_Entry entry, const char *field_name, unsigned field_name_length);
  89071. /** Find a Vorbis comment with the given field name.
  89072. *
  89073. * The search begins at entry number \a offset; use an offset of 0 to
  89074. * search from the beginning of the comment array.
  89075. *
  89076. * \param object A pointer to an existing VORBIS_COMMENT object.
  89077. * \param offset The offset into the comment array from where to start
  89078. * the search.
  89079. * \param field_name The field name of the comment to find.
  89080. * \assert
  89081. * \code object != NULL \endcode
  89082. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89083. * \code field_name != NULL \endcode
  89084. * \retval int
  89085. * The offset in the comment array of the first comment whose field
  89086. * name matches \a field_name, or \c -1 if no match was found.
  89087. */
  89088. FLAC_API int FLAC__metadata_object_vorbiscomment_find_entry_from(const FLAC__StreamMetadata *object, unsigned offset, const char *field_name);
  89089. /** Remove first Vorbis comment matching the given field name.
  89090. *
  89091. * \param object A pointer to an existing VORBIS_COMMENT object.
  89092. * \param field_name The field name of comment to delete.
  89093. * \assert
  89094. * \code object != NULL \endcode
  89095. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89096. * \retval int
  89097. * \c -1 for memory allocation error, \c 0 for no matching entries,
  89098. * \c 1 for one matching entry deleted.
  89099. */
  89100. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entry_matching(FLAC__StreamMetadata *object, const char *field_name);
  89101. /** Remove all Vorbis comments matching the given field name.
  89102. *
  89103. * \param object A pointer to an existing VORBIS_COMMENT object.
  89104. * \param field_name The field name of comments to delete.
  89105. * \assert
  89106. * \code object != NULL \endcode
  89107. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89108. * \retval int
  89109. * \c -1 for memory allocation error, \c 0 for no matching entries,
  89110. * else the number of matching entries deleted.
  89111. */
  89112. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entries_matching(FLAC__StreamMetadata *object, const char *field_name);
  89113. /** Create a new CUESHEET track instance.
  89114. *
  89115. * The object will be "empty"; i.e. values and data pointers will be \c 0.
  89116. *
  89117. * \retval FLAC__StreamMetadata_CueSheet_Track*
  89118. * \c NULL if there was an error allocating memory, else the new instance.
  89119. */
  89120. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_new(void);
  89121. /** Create a copy of an existing CUESHEET track object.
  89122. *
  89123. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  89124. * object is also copied. The caller takes ownership of the new object and
  89125. * is responsible for freeing it with
  89126. * FLAC__metadata_object_cuesheet_track_delete().
  89127. *
  89128. * \param object Pointer to object to copy.
  89129. * \assert
  89130. * \code object != NULL \endcode
  89131. * \retval FLAC__StreamMetadata_CueSheet_Track*
  89132. * \c NULL if there was an error allocating memory, else the new instance.
  89133. */
  89134. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_clone(const FLAC__StreamMetadata_CueSheet_Track *object);
  89135. /** Delete a CUESHEET track object
  89136. *
  89137. * \param object A pointer to an existing CUESHEET track object.
  89138. * \assert
  89139. * \code object != NULL \endcode
  89140. */
  89141. FLAC_API void FLAC__metadata_object_cuesheet_track_delete(FLAC__StreamMetadata_CueSheet_Track *object);
  89142. /** Resize a track's index point array.
  89143. *
  89144. * If the size shrinks, elements will truncated; if it grows, new blank
  89145. * indices will be added to the end.
  89146. *
  89147. * \param object A pointer to an existing CUESHEET object.
  89148. * \param track_num The index of the track to modify. NOTE: this is not
  89149. * necessarily the same as the track's \a number field.
  89150. * \param new_num_indices The desired length of the array; may be \c 0.
  89151. * \assert
  89152. * \code object != NULL \endcode
  89153. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89154. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89155. * \code (object->data.cue_sheet.tracks[track_num].indices == NULL && object->data.cue_sheet.tracks[track_num].num_indices == 0) ||
  89156. * (object->data.cue_sheet.tracks[track_num].indices != NULL && object->data.cue_sheet.tracks[track_num].num_indices > 0) \endcode
  89157. * \retval FLAC__bool
  89158. * \c false if memory allocation error, else \c true.
  89159. */
  89160. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_resize_indices(FLAC__StreamMetadata *object, unsigned track_num, unsigned new_num_indices);
  89161. /** Insert an index point in a CUESHEET track at the given index.
  89162. *
  89163. * \param object A pointer to an existing CUESHEET object.
  89164. * \param track_num The index of the track to modify. NOTE: this is not
  89165. * necessarily the same as the track's \a number field.
  89166. * \param index_num The index into the track's index array at which to
  89167. * insert the index point. NOTE: this is not necessarily
  89168. * the same as the index point's \a number field. The
  89169. * indices at and after \a index_num move right one
  89170. * position. To append an index point to the end, set
  89171. * \a index_num to
  89172. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  89173. * \param index The index point to insert.
  89174. * \assert
  89175. * \code object != NULL \endcode
  89176. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89177. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89178. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  89179. * \retval FLAC__bool
  89180. * \c false if realloc() fails, else \c true.
  89181. */
  89182. 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);
  89183. /** Insert a blank index point in a CUESHEET track at the given index.
  89184. *
  89185. * A blank index point is one in which all field values are zero.
  89186. *
  89187. * \param object A pointer to an existing CUESHEET object.
  89188. * \param track_num The index of the track to modify. NOTE: this is not
  89189. * necessarily the same as the track's \a number field.
  89190. * \param index_num The index into the track's index array at which to
  89191. * insert the index point. NOTE: this is not necessarily
  89192. * the same as the index point's \a number field. The
  89193. * indices at and after \a index_num move right one
  89194. * position. To append an index point to the end, set
  89195. * \a index_num to
  89196. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  89197. * \assert
  89198. * \code object != NULL \endcode
  89199. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89200. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89201. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  89202. * \retval FLAC__bool
  89203. * \c false if realloc() fails, else \c true.
  89204. */
  89205. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_insert_blank_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  89206. /** Delete an index point in a CUESHEET track at the given index.
  89207. *
  89208. * \param object A pointer to an existing CUESHEET object.
  89209. * \param track_num The index into the track array of the track to
  89210. * modify. NOTE: this is not necessarily the same
  89211. * as the track's \a number field.
  89212. * \param index_num The index into the track's index array of the index
  89213. * to delete. NOTE: this is not necessarily the same
  89214. * as the index's \a number field.
  89215. * \assert
  89216. * \code object != NULL \endcode
  89217. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89218. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89219. * \code object->data.cue_sheet.tracks[track_num].num_indices > index_num \endcode
  89220. * \retval FLAC__bool
  89221. * \c false if realloc() fails, else \c true.
  89222. */
  89223. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_delete_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  89224. /** Resize the track array.
  89225. *
  89226. * If the size shrinks, elements will truncated; if it grows, new blank
  89227. * tracks will be added to the end.
  89228. *
  89229. * \param object A pointer to an existing CUESHEET object.
  89230. * \param new_num_tracks The desired length of the array; may be \c 0.
  89231. * \assert
  89232. * \code object != NULL \endcode
  89233. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89234. * \code (object->data.cue_sheet.tracks == NULL && object->data.cue_sheet.num_tracks == 0) ||
  89235. * (object->data.cue_sheet.tracks != NULL && object->data.cue_sheet.num_tracks > 0) \endcode
  89236. * \retval FLAC__bool
  89237. * \c false if memory allocation error, else \c true.
  89238. */
  89239. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_resize_tracks(FLAC__StreamMetadata *object, unsigned new_num_tracks);
  89240. /** Sets a track in a CUESHEET block.
  89241. *
  89242. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  89243. * takes ownership of the \a track pointer.
  89244. *
  89245. * \param object A pointer to an existing CUESHEET object.
  89246. * \param track_num Index into track array to set. NOTE: this is not
  89247. * necessarily the same as the track's \a number field.
  89248. * \param track The track to set the track to. You may safely pass in
  89249. * a const pointer if \a copy is \c true.
  89250. * \param copy See above.
  89251. * \assert
  89252. * \code object != NULL \endcode
  89253. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89254. * \code track_num < object->data.cue_sheet.num_tracks \endcode
  89255. * \code (track->indices != NULL && track->num_indices > 0) ||
  89256. * (track->indices == NULL && track->num_indices == 0)
  89257. * \retval FLAC__bool
  89258. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89259. */
  89260. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_set_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  89261. /** Insert a track in a CUESHEET block at the given index.
  89262. *
  89263. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  89264. * takes ownership of the \a track pointer.
  89265. *
  89266. * \param object A pointer to an existing CUESHEET object.
  89267. * \param track_num The index at which to insert the track. NOTE: this
  89268. * is not necessarily the same as the track's \a number
  89269. * field. The tracks at and after \a track_num move right
  89270. * one position. To append a track to the end, set
  89271. * \a track_num to \c object->data.cue_sheet.num_tracks .
  89272. * \param track The track to insert. You may safely pass in a const
  89273. * pointer if \a copy is \c true.
  89274. * \param copy See above.
  89275. * \assert
  89276. * \code object != NULL \endcode
  89277. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89278. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  89279. * \retval FLAC__bool
  89280. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89281. */
  89282. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  89283. /** Insert a blank track in a CUESHEET block at the given index.
  89284. *
  89285. * A blank track is one in which all field values are zero.
  89286. *
  89287. * \param object A pointer to an existing CUESHEET object.
  89288. * \param track_num The index at which to insert the track. NOTE: this
  89289. * is not necessarily the same as the track's \a number
  89290. * field. The tracks at and after \a track_num move right
  89291. * one position. To append a track to the end, set
  89292. * \a track_num to \c object->data.cue_sheet.num_tracks .
  89293. * \assert
  89294. * \code object != NULL \endcode
  89295. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89296. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  89297. * \retval FLAC__bool
  89298. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89299. */
  89300. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_blank_track(FLAC__StreamMetadata *object, unsigned track_num);
  89301. /** Delete a track in a CUESHEET block at the given index.
  89302. *
  89303. * \param object A pointer to an existing CUESHEET object.
  89304. * \param track_num The index into the track array of the track to
  89305. * delete. NOTE: this is not necessarily the same
  89306. * as the track's \a number field.
  89307. * \assert
  89308. * \code object != NULL \endcode
  89309. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89310. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89311. * \retval FLAC__bool
  89312. * \c false if realloc() fails, else \c true.
  89313. */
  89314. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_delete_track(FLAC__StreamMetadata *object, unsigned track_num);
  89315. /** Check a cue sheet to see if it conforms to the FLAC specification.
  89316. * See the format specification for limits on the contents of the
  89317. * cue sheet.
  89318. *
  89319. * \param object A pointer to an existing CUESHEET object.
  89320. * \param check_cd_da_subset If \c true, check CUESHEET against more
  89321. * stringent requirements for a CD-DA (audio) disc.
  89322. * \param violation Address of a pointer to a string. If there is a
  89323. * violation, a pointer to a string explanation of the
  89324. * violation will be returned here. \a violation may be
  89325. * \c NULL if you don't need the returned string. Do not
  89326. * free the returned string; it will always point to static
  89327. * data.
  89328. * \assert
  89329. * \code object != NULL \endcode
  89330. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89331. * \retval FLAC__bool
  89332. * \c false if cue sheet is illegal, else \c true.
  89333. */
  89334. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_is_legal(const FLAC__StreamMetadata *object, FLAC__bool check_cd_da_subset, const char **violation);
  89335. /** Calculate and return the CDDB/freedb ID for a cue sheet. The function
  89336. * assumes the cue sheet corresponds to a CD; the result is undefined
  89337. * if the cuesheet's is_cd bit is not set.
  89338. *
  89339. * \param object A pointer to an existing CUESHEET object.
  89340. * \assert
  89341. * \code object != NULL \endcode
  89342. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89343. * \retval FLAC__uint32
  89344. * The unsigned integer representation of the CDDB/freedb ID
  89345. */
  89346. FLAC_API FLAC__uint32 FLAC__metadata_object_cuesheet_calculate_cddb_id(const FLAC__StreamMetadata *object);
  89347. /** Sets the MIME type of a PICTURE block.
  89348. *
  89349. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  89350. * takes ownership of the pointer. The existing string will be freed if this
  89351. * function is successful, otherwise the original string will remain if \a copy
  89352. * is \c true and malloc() fails.
  89353. *
  89354. * \note It is safe to pass a const pointer to \a mime_type if \a copy is \c true.
  89355. *
  89356. * \param object A pointer to an existing PICTURE object.
  89357. * \param mime_type A pointer to the MIME type string. The string must be
  89358. * ASCII characters 0x20-0x7e, NUL-terminated. No validation
  89359. * is done.
  89360. * \param copy See above.
  89361. * \assert
  89362. * \code object != NULL \endcode
  89363. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89364. * \code (mime_type != NULL) \endcode
  89365. * \retval FLAC__bool
  89366. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89367. */
  89368. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_mime_type(FLAC__StreamMetadata *object, char *mime_type, FLAC__bool copy);
  89369. /** Sets the description of a PICTURE block.
  89370. *
  89371. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  89372. * takes ownership of the pointer. The existing string will be freed if this
  89373. * function is successful, otherwise the original string will remain if \a copy
  89374. * is \c true and malloc() fails.
  89375. *
  89376. * \note It is safe to pass a const pointer to \a description if \a copy is \c true.
  89377. *
  89378. * \param object A pointer to an existing PICTURE object.
  89379. * \param description A pointer to the description string. The string must be
  89380. * valid UTF-8, NUL-terminated. No validation is done.
  89381. * \param copy See above.
  89382. * \assert
  89383. * \code object != NULL \endcode
  89384. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89385. * \code (description != NULL) \endcode
  89386. * \retval FLAC__bool
  89387. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89388. */
  89389. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_description(FLAC__StreamMetadata *object, FLAC__byte *description, FLAC__bool copy);
  89390. /** Sets the picture data of a PICTURE block.
  89391. *
  89392. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  89393. * takes ownership of the pointer. Also sets the \a data_length field of the
  89394. * metadata object to what is passed in as the \a length parameter. The
  89395. * existing data will be freed if this function is successful, otherwise the
  89396. * original data and data_length will remain if \a copy is \c true and
  89397. * malloc() fails.
  89398. *
  89399. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  89400. *
  89401. * \param object A pointer to an existing PICTURE object.
  89402. * \param data A pointer to the data to set.
  89403. * \param length The length of \a data in bytes.
  89404. * \param copy See above.
  89405. * \assert
  89406. * \code object != NULL \endcode
  89407. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89408. * \code (data != NULL && length > 0) ||
  89409. * (data == NULL && length == 0 && copy == false) \endcode
  89410. * \retval FLAC__bool
  89411. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89412. */
  89413. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, FLAC__uint32 length, FLAC__bool copy);
  89414. /** Check a PICTURE block to see if it conforms to the FLAC specification.
  89415. * See the format specification for limits on the contents of the
  89416. * PICTURE block.
  89417. *
  89418. * \param object A pointer to existing PICTURE block to be checked.
  89419. * \param violation Address of a pointer to a string. If there is a
  89420. * violation, a pointer to a string explanation of the
  89421. * violation will be returned here. \a violation may be
  89422. * \c NULL if you don't need the returned string. Do not
  89423. * free the returned string; it will always point to static
  89424. * data.
  89425. * \assert
  89426. * \code object != NULL \endcode
  89427. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89428. * \retval FLAC__bool
  89429. * \c false if PICTURE block is illegal, else \c true.
  89430. */
  89431. FLAC_API FLAC__bool FLAC__metadata_object_picture_is_legal(const FLAC__StreamMetadata *object, const char **violation);
  89432. /* \} */
  89433. #ifdef __cplusplus
  89434. }
  89435. #endif
  89436. #endif
  89437. /*** End of inlined file: metadata.h ***/
  89438. /*** Start of inlined file: stream_decoder.h ***/
  89439. #ifndef FLAC__STREAM_DECODER_H
  89440. #define FLAC__STREAM_DECODER_H
  89441. #include <stdio.h> /* for FILE */
  89442. #ifdef __cplusplus
  89443. extern "C" {
  89444. #endif
  89445. /** \file include/FLAC/stream_decoder.h
  89446. *
  89447. * \brief
  89448. * This module contains the functions which implement the stream
  89449. * decoder.
  89450. *
  89451. * See the detailed documentation in the
  89452. * \link flac_stream_decoder stream decoder \endlink module.
  89453. */
  89454. /** \defgroup flac_decoder FLAC/ \*_decoder.h: decoder interfaces
  89455. * \ingroup flac
  89456. *
  89457. * \brief
  89458. * This module describes the decoder layers provided by libFLAC.
  89459. *
  89460. * The stream decoder can be used to decode complete streams either from
  89461. * the client via callbacks, or directly from a file, depending on how
  89462. * it is initialized. When decoding via callbacks, the client provides
  89463. * callbacks for reading FLAC data and writing decoded samples, and
  89464. * handling metadata and errors. If the client also supplies seek-related
  89465. * callback, the decoder function for sample-accurate seeking within the
  89466. * FLAC input is also available. When decoding from a file, the client
  89467. * needs only supply a filename or open \c FILE* and write/metadata/error
  89468. * callbacks; the rest of the callbacks are supplied internally. For more
  89469. * info see the \link flac_stream_decoder stream decoder \endlink module.
  89470. */
  89471. /** \defgroup flac_stream_decoder FLAC/stream_decoder.h: stream decoder interface
  89472. * \ingroup flac_decoder
  89473. *
  89474. * \brief
  89475. * This module contains the functions which implement the stream
  89476. * decoder.
  89477. *
  89478. * The stream decoder can decode native FLAC, and optionally Ogg FLAC
  89479. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  89480. *
  89481. * The basic usage of this decoder is as follows:
  89482. * - The program creates an instance of a decoder using
  89483. * FLAC__stream_decoder_new().
  89484. * - The program overrides the default settings using
  89485. * FLAC__stream_decoder_set_*() functions.
  89486. * - The program initializes the instance to validate the settings and
  89487. * prepare for decoding using
  89488. * - FLAC__stream_decoder_init_stream() or FLAC__stream_decoder_init_FILE()
  89489. * or FLAC__stream_decoder_init_file() for native FLAC,
  89490. * - FLAC__stream_decoder_init_ogg_stream() or FLAC__stream_decoder_init_ogg_FILE()
  89491. * or FLAC__stream_decoder_init_ogg_file() for Ogg FLAC
  89492. * - The program calls the FLAC__stream_decoder_process_*() functions
  89493. * to decode data, which subsequently calls the callbacks.
  89494. * - The program finishes the decoding with FLAC__stream_decoder_finish(),
  89495. * which flushes the input and output and resets the decoder to the
  89496. * uninitialized state.
  89497. * - The instance may be used again or deleted with
  89498. * FLAC__stream_decoder_delete().
  89499. *
  89500. * In more detail, the program will create a new instance by calling
  89501. * FLAC__stream_decoder_new(), then call FLAC__stream_decoder_set_*()
  89502. * functions to override the default decoder options, and call
  89503. * one of the FLAC__stream_decoder_init_*() functions.
  89504. *
  89505. * There are three initialization functions for native FLAC, one for
  89506. * setting up the decoder to decode FLAC data from the client via
  89507. * callbacks, and two for decoding directly from a FLAC file.
  89508. *
  89509. * For decoding via callbacks, use FLAC__stream_decoder_init_stream().
  89510. * You must also supply several callbacks for handling I/O. Some (like
  89511. * seeking) are optional, depending on the capabilities of the input.
  89512. *
  89513. * For decoding directly from a file, use FLAC__stream_decoder_init_FILE()
  89514. * or FLAC__stream_decoder_init_file(). Then you must only supply an open
  89515. * \c FILE* or filename and fewer callbacks; the decoder will handle
  89516. * the other callbacks internally.
  89517. *
  89518. * There are three similarly-named init functions for decoding from Ogg
  89519. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  89520. * library has been built with Ogg support.
  89521. *
  89522. * Once the decoder is initialized, your program will call one of several
  89523. * functions to start the decoding process:
  89524. *
  89525. * - FLAC__stream_decoder_process_single() - Tells the decoder to process at
  89526. * most one metadata block or audio frame and return, calling either the
  89527. * metadata callback or write callback, respectively, once. If the decoder
  89528. * loses sync it will return with only the error callback being called.
  89529. * - FLAC__stream_decoder_process_until_end_of_metadata() - Tells the decoder
  89530. * to process the stream from the current location and stop upon reaching
  89531. * the first audio frame. The client will get one metadata, write, or error
  89532. * callback per metadata block, audio frame, or sync error, respectively.
  89533. * - FLAC__stream_decoder_process_until_end_of_stream() - Tells the decoder
  89534. * to process the stream from the current location until the read callback
  89535. * returns FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM or
  89536. * FLAC__STREAM_DECODER_READ_STATUS_ABORT. The client will get one metadata,
  89537. * write, or error callback per metadata block, audio frame, or sync error,
  89538. * respectively.
  89539. *
  89540. * When the decoder has finished decoding (normally or through an abort),
  89541. * the instance is finished by calling FLAC__stream_decoder_finish(), which
  89542. * ensures the decoder is in the correct state and frees memory. Then the
  89543. * instance may be deleted with FLAC__stream_decoder_delete() or initialized
  89544. * again to decode another stream.
  89545. *
  89546. * Seeking is exposed through the FLAC__stream_decoder_seek_absolute() method.
  89547. * At any point after the stream decoder has been initialized, the client can
  89548. * call this function to seek to an exact sample within the stream.
  89549. * Subsequently, the first time the write callback is called it will be
  89550. * passed a (possibly partial) block starting at that sample.
  89551. *
  89552. * If the client cannot seek via the callback interface provided, but still
  89553. * has another way of seeking, it can flush the decoder using
  89554. * FLAC__stream_decoder_flush() and start feeding data from the new position
  89555. * through the read callback.
  89556. *
  89557. * The stream decoder also provides MD5 signature checking. If this is
  89558. * turned on before initialization, FLAC__stream_decoder_finish() will
  89559. * report when the decoded MD5 signature does not match the one stored
  89560. * in the STREAMINFO block. MD5 checking is automatically turned off
  89561. * (until the next FLAC__stream_decoder_reset()) if there is no signature
  89562. * in the STREAMINFO block or when a seek is attempted.
  89563. *
  89564. * The FLAC__stream_decoder_set_metadata_*() functions deserve special
  89565. * attention. By default, the decoder only calls the metadata_callback for
  89566. * the STREAMINFO block. These functions allow you to tell the decoder
  89567. * explicitly which blocks to parse and return via the metadata_callback
  89568. * and/or which to skip. Use a FLAC__stream_decoder_set_metadata_respond_all(),
  89569. * FLAC__stream_decoder_set_metadata_ignore() ... or FLAC__stream_decoder_set_metadata_ignore_all(),
  89570. * FLAC__stream_decoder_set_metadata_respond() ... sequence to exactly specify
  89571. * which blocks to return. Remember that metadata blocks can potentially
  89572. * be big (for example, cover art) so filtering out the ones you don't
  89573. * use can reduce the memory requirements of the decoder. Also note the
  89574. * special forms FLAC__stream_decoder_set_metadata_respond_application(id)
  89575. * and FLAC__stream_decoder_set_metadata_ignore_application(id) for
  89576. * filtering APPLICATION blocks based on the application ID.
  89577. *
  89578. * STREAMINFO and SEEKTABLE blocks are always parsed and used internally, but
  89579. * they still can legally be filtered from the metadata_callback.
  89580. *
  89581. * \note
  89582. * The "set" functions may only be called when the decoder is in the
  89583. * state FLAC__STREAM_DECODER_UNINITIALIZED, i.e. after
  89584. * FLAC__stream_decoder_new() or FLAC__stream_decoder_finish(), but
  89585. * before FLAC__stream_decoder_init_*(). If this is the case they will
  89586. * return \c true, otherwise \c false.
  89587. *
  89588. * \note
  89589. * FLAC__stream_decoder_finish() resets all settings to the constructor
  89590. * defaults, including the callbacks.
  89591. *
  89592. * \{
  89593. */
  89594. /** State values for a FLAC__StreamDecoder
  89595. *
  89596. * The decoder's state can be obtained by calling FLAC__stream_decoder_get_state().
  89597. */
  89598. typedef enum {
  89599. FLAC__STREAM_DECODER_SEARCH_FOR_METADATA = 0,
  89600. /**< The decoder is ready to search for metadata. */
  89601. FLAC__STREAM_DECODER_READ_METADATA,
  89602. /**< The decoder is ready to or is in the process of reading metadata. */
  89603. FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC,
  89604. /**< The decoder is ready to or is in the process of searching for the
  89605. * frame sync code.
  89606. */
  89607. FLAC__STREAM_DECODER_READ_FRAME,
  89608. /**< The decoder is ready to or is in the process of reading a frame. */
  89609. FLAC__STREAM_DECODER_END_OF_STREAM,
  89610. /**< The decoder has reached the end of the stream. */
  89611. FLAC__STREAM_DECODER_OGG_ERROR,
  89612. /**< An error occurred in the underlying Ogg layer. */
  89613. FLAC__STREAM_DECODER_SEEK_ERROR,
  89614. /**< An error occurred while seeking. The decoder must be flushed
  89615. * with FLAC__stream_decoder_flush() or reset with
  89616. * FLAC__stream_decoder_reset() before decoding can continue.
  89617. */
  89618. FLAC__STREAM_DECODER_ABORTED,
  89619. /**< The decoder was aborted by the read callback. */
  89620. FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR,
  89621. /**< An error occurred allocating memory. The decoder is in an invalid
  89622. * state and can no longer be used.
  89623. */
  89624. FLAC__STREAM_DECODER_UNINITIALIZED
  89625. /**< The decoder is in the uninitialized state; one of the
  89626. * FLAC__stream_decoder_init_*() functions must be called before samples
  89627. * can be processed.
  89628. */
  89629. } FLAC__StreamDecoderState;
  89630. /** Maps a FLAC__StreamDecoderState to a C string.
  89631. *
  89632. * Using a FLAC__StreamDecoderState as the index to this array
  89633. * will give the string equivalent. The contents should not be modified.
  89634. */
  89635. extern FLAC_API const char * const FLAC__StreamDecoderStateString[];
  89636. /** Possible return values for the FLAC__stream_decoder_init_*() functions.
  89637. */
  89638. typedef enum {
  89639. FLAC__STREAM_DECODER_INIT_STATUS_OK = 0,
  89640. /**< Initialization was successful. */
  89641. FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  89642. /**< The library was not compiled with support for the given container
  89643. * format.
  89644. */
  89645. FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS,
  89646. /**< A required callback was not supplied. */
  89647. FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR,
  89648. /**< An error occurred allocating memory. */
  89649. FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE,
  89650. /**< fopen() failed in FLAC__stream_decoder_init_file() or
  89651. * FLAC__stream_decoder_init_ogg_file(). */
  89652. FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED
  89653. /**< FLAC__stream_decoder_init_*() was called when the decoder was
  89654. * already initialized, usually because
  89655. * FLAC__stream_decoder_finish() was not called.
  89656. */
  89657. } FLAC__StreamDecoderInitStatus;
  89658. /** Maps a FLAC__StreamDecoderInitStatus to a C string.
  89659. *
  89660. * Using a FLAC__StreamDecoderInitStatus as the index to this array
  89661. * will give the string equivalent. The contents should not be modified.
  89662. */
  89663. extern FLAC_API const char * const FLAC__StreamDecoderInitStatusString[];
  89664. /** Return values for the FLAC__StreamDecoder read callback.
  89665. */
  89666. typedef enum {
  89667. FLAC__STREAM_DECODER_READ_STATUS_CONTINUE,
  89668. /**< The read was OK and decoding can continue. */
  89669. FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM,
  89670. /**< The read was attempted while at the end of the stream. Note that
  89671. * the client must only return this value when the read callback was
  89672. * called when already at the end of the stream. Otherwise, if the read
  89673. * itself moves to the end of the stream, the client should still return
  89674. * the data and \c FLAC__STREAM_DECODER_READ_STATUS_CONTINUE, and then on
  89675. * the next read callback it should return
  89676. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM with a byte count
  89677. * of \c 0.
  89678. */
  89679. FLAC__STREAM_DECODER_READ_STATUS_ABORT
  89680. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89681. } FLAC__StreamDecoderReadStatus;
  89682. /** Maps a FLAC__StreamDecoderReadStatus to a C string.
  89683. *
  89684. * Using a FLAC__StreamDecoderReadStatus as the index to this array
  89685. * will give the string equivalent. The contents should not be modified.
  89686. */
  89687. extern FLAC_API const char * const FLAC__StreamDecoderReadStatusString[];
  89688. /** Return values for the FLAC__StreamDecoder seek callback.
  89689. */
  89690. typedef enum {
  89691. FLAC__STREAM_DECODER_SEEK_STATUS_OK,
  89692. /**< The seek was OK and decoding can continue. */
  89693. FLAC__STREAM_DECODER_SEEK_STATUS_ERROR,
  89694. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89695. FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  89696. /**< Client does not support seeking. */
  89697. } FLAC__StreamDecoderSeekStatus;
  89698. /** Maps a FLAC__StreamDecoderSeekStatus to a C string.
  89699. *
  89700. * Using a FLAC__StreamDecoderSeekStatus as the index to this array
  89701. * will give the string equivalent. The contents should not be modified.
  89702. */
  89703. extern FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[];
  89704. /** Return values for the FLAC__StreamDecoder tell callback.
  89705. */
  89706. typedef enum {
  89707. FLAC__STREAM_DECODER_TELL_STATUS_OK,
  89708. /**< The tell was OK and decoding can continue. */
  89709. FLAC__STREAM_DECODER_TELL_STATUS_ERROR,
  89710. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89711. FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  89712. /**< Client does not support telling the position. */
  89713. } FLAC__StreamDecoderTellStatus;
  89714. /** Maps a FLAC__StreamDecoderTellStatus to a C string.
  89715. *
  89716. * Using a FLAC__StreamDecoderTellStatus as the index to this array
  89717. * will give the string equivalent. The contents should not be modified.
  89718. */
  89719. extern FLAC_API const char * const FLAC__StreamDecoderTellStatusString[];
  89720. /** Return values for the FLAC__StreamDecoder length callback.
  89721. */
  89722. typedef enum {
  89723. FLAC__STREAM_DECODER_LENGTH_STATUS_OK,
  89724. /**< The length call was OK and decoding can continue. */
  89725. FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR,
  89726. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89727. FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  89728. /**< Client does not support reporting the length. */
  89729. } FLAC__StreamDecoderLengthStatus;
  89730. /** Maps a FLAC__StreamDecoderLengthStatus to a C string.
  89731. *
  89732. * Using a FLAC__StreamDecoderLengthStatus as the index to this array
  89733. * will give the string equivalent. The contents should not be modified.
  89734. */
  89735. extern FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[];
  89736. /** Return values for the FLAC__StreamDecoder write callback.
  89737. */
  89738. typedef enum {
  89739. FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE,
  89740. /**< The write was OK and decoding can continue. */
  89741. FLAC__STREAM_DECODER_WRITE_STATUS_ABORT
  89742. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89743. } FLAC__StreamDecoderWriteStatus;
  89744. /** Maps a FLAC__StreamDecoderWriteStatus to a C string.
  89745. *
  89746. * Using a FLAC__StreamDecoderWriteStatus as the index to this array
  89747. * will give the string equivalent. The contents should not be modified.
  89748. */
  89749. extern FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[];
  89750. /** Possible values passed back to the FLAC__StreamDecoder error callback.
  89751. * \c FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC is the generic catch-
  89752. * all. The rest could be caused by bad sync (false synchronization on
  89753. * data that is not the start of a frame) or corrupted data. The error
  89754. * itself is the decoder's best guess at what happened assuming a correct
  89755. * sync. For example \c FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER
  89756. * could be caused by a correct sync on the start of a frame, but some
  89757. * data in the frame header was corrupted. Or it could be the result of
  89758. * syncing on a point the stream that looked like the starting of a frame
  89759. * but was not. \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  89760. * could be because the decoder encountered a valid frame made by a future
  89761. * version of the encoder which it cannot parse, or because of a false
  89762. * sync making it appear as though an encountered frame was generated by
  89763. * a future encoder.
  89764. */
  89765. typedef enum {
  89766. FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC,
  89767. /**< An error in the stream caused the decoder to lose synchronization. */
  89768. FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER,
  89769. /**< The decoder encountered a corrupted frame header. */
  89770. FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH,
  89771. /**< The frame's data did not match the CRC in the footer. */
  89772. FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  89773. /**< The decoder encountered reserved fields in use in the stream. */
  89774. } FLAC__StreamDecoderErrorStatus;
  89775. /** Maps a FLAC__StreamDecoderErrorStatus to a C string.
  89776. *
  89777. * Using a FLAC__StreamDecoderErrorStatus as the index to this array
  89778. * will give the string equivalent. The contents should not be modified.
  89779. */
  89780. extern FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[];
  89781. /***********************************************************************
  89782. *
  89783. * class FLAC__StreamDecoder
  89784. *
  89785. ***********************************************************************/
  89786. struct FLAC__StreamDecoderProtected;
  89787. struct FLAC__StreamDecoderPrivate;
  89788. /** The opaque structure definition for the stream decoder type.
  89789. * See the \link flac_stream_decoder stream decoder module \endlink
  89790. * for a detailed description.
  89791. */
  89792. typedef struct {
  89793. struct FLAC__StreamDecoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  89794. struct FLAC__StreamDecoderPrivate *private_; /* avoid the C++ keyword 'private' */
  89795. } FLAC__StreamDecoder;
  89796. /** Signature for the read callback.
  89797. *
  89798. * A function pointer matching this signature must be passed to
  89799. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89800. * called when the decoder needs more input data. The address of the
  89801. * buffer to be filled is supplied, along with the number of bytes the
  89802. * buffer can hold. The callback may choose to supply less data and
  89803. * modify the byte count but must be careful not to overflow the buffer.
  89804. * The callback then returns a status code chosen from
  89805. * FLAC__StreamDecoderReadStatus.
  89806. *
  89807. * Here is an example of a read callback for stdio streams:
  89808. * \code
  89809. * FLAC__StreamDecoderReadStatus read_cb(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  89810. * {
  89811. * FILE *file = ((MyClientData*)client_data)->file;
  89812. * if(*bytes > 0) {
  89813. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  89814. * if(ferror(file))
  89815. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  89816. * else if(*bytes == 0)
  89817. * return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  89818. * else
  89819. * return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  89820. * }
  89821. * else
  89822. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  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 buffer A pointer to a location for the callee to store
  89831. * data to be decoded.
  89832. * \param bytes A pointer to the size of the buffer. On entry
  89833. * to the callback, it contains the maximum number
  89834. * of bytes that may be stored in \a buffer. The
  89835. * callee must set it to the actual number of bytes
  89836. * stored (0 in case of error or end-of-stream) before
  89837. * returning.
  89838. * \param client_data The callee's client data set through
  89839. * FLAC__stream_decoder_init_*().
  89840. * \retval FLAC__StreamDecoderReadStatus
  89841. * The callee's return status. Note that the callback should return
  89842. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM if and only if
  89843. * zero bytes were read and there is no more data to be read.
  89844. */
  89845. typedef FLAC__StreamDecoderReadStatus (*FLAC__StreamDecoderReadCallback)(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  89846. /** Signature for the seek callback.
  89847. *
  89848. * A function pointer matching this signature may be passed to
  89849. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89850. * called when the decoder needs to seek the input stream. The decoder
  89851. * will pass the absolute byte offset to seek to, 0 meaning the
  89852. * beginning of the stream.
  89853. *
  89854. * Here is an example of a seek callback for stdio streams:
  89855. * \code
  89856. * FLAC__StreamDecoderSeekStatus seek_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  89857. * {
  89858. * FILE *file = ((MyClientData*)client_data)->file;
  89859. * if(file == stdin)
  89860. * return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  89861. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  89862. * return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  89863. * else
  89864. * return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  89865. * }
  89866. * \endcode
  89867. *
  89868. * \note In general, FLAC__StreamDecoder functions which change the
  89869. * state should not be called on the \a decoder while in the callback.
  89870. *
  89871. * \param decoder The decoder instance calling the callback.
  89872. * \param absolute_byte_offset The offset from the beginning of the stream
  89873. * to seek to.
  89874. * \param client_data The callee's client data set through
  89875. * FLAC__stream_decoder_init_*().
  89876. * \retval FLAC__StreamDecoderSeekStatus
  89877. * The callee's return status.
  89878. */
  89879. typedef FLAC__StreamDecoderSeekStatus (*FLAC__StreamDecoderSeekCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  89880. /** Signature for the tell callback.
  89881. *
  89882. * A function pointer matching this signature may be passed to
  89883. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89884. * called when the decoder wants to know the current position of the
  89885. * stream. The callback should return the byte offset from the
  89886. * beginning of the stream.
  89887. *
  89888. * Here is an example of a tell callback for stdio streams:
  89889. * \code
  89890. * FLAC__StreamDecoderTellStatus tell_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  89891. * {
  89892. * FILE *file = ((MyClientData*)client_data)->file;
  89893. * off_t pos;
  89894. * if(file == stdin)
  89895. * return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  89896. * else if((pos = ftello(file)) < 0)
  89897. * return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  89898. * else {
  89899. * *absolute_byte_offset = (FLAC__uint64)pos;
  89900. * return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  89901. * }
  89902. * }
  89903. * \endcode
  89904. *
  89905. * \note In general, FLAC__StreamDecoder functions which change the
  89906. * state should not be called on the \a decoder while in the callback.
  89907. *
  89908. * \param decoder The decoder instance calling the callback.
  89909. * \param absolute_byte_offset A pointer to storage for the current offset
  89910. * from the beginning of the stream.
  89911. * \param client_data The callee's client data set through
  89912. * FLAC__stream_decoder_init_*().
  89913. * \retval FLAC__StreamDecoderTellStatus
  89914. * The callee's return status.
  89915. */
  89916. typedef FLAC__StreamDecoderTellStatus (*FLAC__StreamDecoderTellCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  89917. /** Signature for the length callback.
  89918. *
  89919. * A function pointer matching this signature may be passed to
  89920. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89921. * called when the decoder wants to know the total length of the stream
  89922. * in bytes.
  89923. *
  89924. * Here is an example of a length callback for stdio streams:
  89925. * \code
  89926. * FLAC__StreamDecoderLengthStatus length_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  89927. * {
  89928. * FILE *file = ((MyClientData*)client_data)->file;
  89929. * struct stat filestats;
  89930. *
  89931. * if(file == stdin)
  89932. * return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  89933. * else if(fstat(fileno(file), &filestats) != 0)
  89934. * return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  89935. * else {
  89936. * *stream_length = (FLAC__uint64)filestats.st_size;
  89937. * return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  89938. * }
  89939. * }
  89940. * \endcode
  89941. *
  89942. * \note In general, FLAC__StreamDecoder functions which change the
  89943. * state should not be called on the \a decoder while in the callback.
  89944. *
  89945. * \param decoder The decoder instance calling the callback.
  89946. * \param stream_length A pointer to storage for the length of the stream
  89947. * in bytes.
  89948. * \param client_data The callee's client data set through
  89949. * FLAC__stream_decoder_init_*().
  89950. * \retval FLAC__StreamDecoderLengthStatus
  89951. * The callee's return status.
  89952. */
  89953. typedef FLAC__StreamDecoderLengthStatus (*FLAC__StreamDecoderLengthCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  89954. /** Signature for the EOF callback.
  89955. *
  89956. * A function pointer matching this signature may be passed to
  89957. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89958. * called when the decoder needs to know if the end of the stream has
  89959. * been reached.
  89960. *
  89961. * Here is an example of a EOF callback for stdio streams:
  89962. * FLAC__bool eof_cb(const FLAC__StreamDecoder *decoder, void *client_data)
  89963. * \code
  89964. * {
  89965. * FILE *file = ((MyClientData*)client_data)->file;
  89966. * return feof(file)? true : false;
  89967. * }
  89968. * \endcode
  89969. *
  89970. * \note In general, FLAC__StreamDecoder functions which change the
  89971. * state should not be called on the \a decoder while in the callback.
  89972. *
  89973. * \param decoder The decoder instance calling the callback.
  89974. * \param client_data The callee's client data set through
  89975. * FLAC__stream_decoder_init_*().
  89976. * \retval FLAC__bool
  89977. * \c true if the currently at the end of the stream, else \c false.
  89978. */
  89979. typedef FLAC__bool (*FLAC__StreamDecoderEofCallback)(const FLAC__StreamDecoder *decoder, void *client_data);
  89980. /** Signature for the write callback.
  89981. *
  89982. * A function pointer matching this signature must be passed to one of
  89983. * the FLAC__stream_decoder_init_*() functions.
  89984. * The supplied function will be called when the decoder has decoded a
  89985. * single audio frame. The decoder will pass the frame metadata as well
  89986. * as an array of pointers (one for each channel) pointing to the
  89987. * decoded audio.
  89988. *
  89989. * \note In general, FLAC__StreamDecoder functions which change the
  89990. * state should not be called on the \a decoder while in the callback.
  89991. *
  89992. * \param decoder The decoder instance calling the callback.
  89993. * \param frame The description of the decoded frame. See
  89994. * FLAC__Frame.
  89995. * \param buffer An array of pointers to decoded channels of data.
  89996. * Each pointer will point to an array of signed
  89997. * samples of length \a frame->header.blocksize.
  89998. * Channels will be ordered according to the FLAC
  89999. * specification; see the documentation for the
  90000. * <A HREF="../format.html#frame_header">frame header</A>.
  90001. * \param client_data The callee's client data set through
  90002. * FLAC__stream_decoder_init_*().
  90003. * \retval FLAC__StreamDecoderWriteStatus
  90004. * The callee's return status.
  90005. */
  90006. typedef FLAC__StreamDecoderWriteStatus (*FLAC__StreamDecoderWriteCallback)(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  90007. /** Signature for the metadata callback.
  90008. *
  90009. * A function pointer matching this signature must be passed to one of
  90010. * the FLAC__stream_decoder_init_*() functions.
  90011. * The supplied function will be called when the decoder has decoded a
  90012. * metadata block. In a valid FLAC file there will always be one
  90013. * \c STREAMINFO block, followed by zero or more other metadata blocks.
  90014. * These will be supplied by the decoder in the same order as they
  90015. * appear in the stream and always before the first audio frame (i.e.
  90016. * write callback). The metadata block that is passed in must not be
  90017. * modified, and it doesn't live beyond the callback, so you should make
  90018. * a copy of it with FLAC__metadata_object_clone() if you will need it
  90019. * elsewhere. Since metadata blocks can potentially be large, by
  90020. * default the decoder only calls the metadata callback for the
  90021. * \c STREAMINFO block; you can instruct the decoder to pass or filter
  90022. * other blocks with FLAC__stream_decoder_set_metadata_*() calls.
  90023. *
  90024. * \note In general, FLAC__StreamDecoder functions which change the
  90025. * state should not be called on the \a decoder while in the callback.
  90026. *
  90027. * \param decoder The decoder instance calling the callback.
  90028. * \param metadata The decoded metadata block.
  90029. * \param client_data The callee's client data set through
  90030. * FLAC__stream_decoder_init_*().
  90031. */
  90032. typedef void (*FLAC__StreamDecoderMetadataCallback)(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  90033. /** Signature for the error callback.
  90034. *
  90035. * A function pointer matching this signature must be passed to one of
  90036. * the FLAC__stream_decoder_init_*() functions.
  90037. * The supplied function will be called whenever an error occurs during
  90038. * decoding.
  90039. *
  90040. * \note In general, FLAC__StreamDecoder functions which change the
  90041. * state should not be called on the \a decoder while in the callback.
  90042. *
  90043. * \param decoder The decoder instance calling the callback.
  90044. * \param status The error encountered by the decoder.
  90045. * \param client_data The callee's client data set through
  90046. * FLAC__stream_decoder_init_*().
  90047. */
  90048. typedef void (*FLAC__StreamDecoderErrorCallback)(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  90049. /***********************************************************************
  90050. *
  90051. * Class constructor/destructor
  90052. *
  90053. ***********************************************************************/
  90054. /** Create a new stream decoder instance. The instance is created with
  90055. * default settings; see the individual FLAC__stream_decoder_set_*()
  90056. * functions for each setting's default.
  90057. *
  90058. * \retval FLAC__StreamDecoder*
  90059. * \c NULL if there was an error allocating memory, else the new instance.
  90060. */
  90061. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void);
  90062. /** Free a decoder instance. Deletes the object pointed to by \a decoder.
  90063. *
  90064. * \param decoder A pointer to an existing decoder.
  90065. * \assert
  90066. * \code decoder != NULL \endcode
  90067. */
  90068. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder);
  90069. /***********************************************************************
  90070. *
  90071. * Public class method prototypes
  90072. *
  90073. ***********************************************************************/
  90074. /** Set the serial number for the FLAC stream within the Ogg container.
  90075. * The default behavior is to use the serial number of the first Ogg
  90076. * page. Setting a serial number here will explicitly specify which
  90077. * stream is to be decoded.
  90078. *
  90079. * \note
  90080. * This does not need to be set for native FLAC decoding.
  90081. *
  90082. * \default \c use serial number of first page
  90083. * \param decoder A decoder instance to set.
  90084. * \param serial_number See above.
  90085. * \assert
  90086. * \code decoder != NULL \endcode
  90087. * \retval FLAC__bool
  90088. * \c false if the decoder is already initialized, else \c true.
  90089. */
  90090. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long serial_number);
  90091. /** Set the "MD5 signature checking" flag. If \c true, the decoder will
  90092. * compute the MD5 signature of the unencoded audio data while decoding
  90093. * and compare it to the signature from the STREAMINFO block, if it
  90094. * exists, during FLAC__stream_decoder_finish().
  90095. *
  90096. * MD5 signature checking will be turned off (until the next
  90097. * FLAC__stream_decoder_reset()) if there is no signature in the
  90098. * STREAMINFO block or when a seek is attempted.
  90099. *
  90100. * Clients that do not use the MD5 check should leave this off to speed
  90101. * up decoding.
  90102. *
  90103. * \default \c false
  90104. * \param decoder A decoder instance to set.
  90105. * \param value Flag value (see above).
  90106. * \assert
  90107. * \code decoder != NULL \endcode
  90108. * \retval FLAC__bool
  90109. * \c false if the decoder is already initialized, else \c true.
  90110. */
  90111. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value);
  90112. /** Direct the decoder to pass on all metadata blocks of type \a type.
  90113. *
  90114. * \default By default, only the \c STREAMINFO block is returned via the
  90115. * metadata callback.
  90116. * \param decoder A decoder instance to set.
  90117. * \param type See above.
  90118. * \assert
  90119. * \code decoder != NULL \endcode
  90120. * \a type is valid
  90121. * \retval FLAC__bool
  90122. * \c false if the decoder is already initialized, else \c true.
  90123. */
  90124. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  90125. /** Direct the decoder to pass on all APPLICATION metadata blocks of the
  90126. * given \a id.
  90127. *
  90128. * \default By default, only the \c STREAMINFO block is returned via the
  90129. * metadata callback.
  90130. * \param decoder A decoder instance to set.
  90131. * \param id See above.
  90132. * \assert
  90133. * \code decoder != NULL \endcode
  90134. * \code id != NULL \endcode
  90135. * \retval FLAC__bool
  90136. * \c false if the decoder is already initialized, else \c true.
  90137. */
  90138. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  90139. /** Direct the decoder to pass on all metadata blocks of any type.
  90140. *
  90141. * \default By default, only the \c STREAMINFO block is returned via the
  90142. * metadata callback.
  90143. * \param decoder A decoder instance to set.
  90144. * \assert
  90145. * \code decoder != NULL \endcode
  90146. * \retval FLAC__bool
  90147. * \c false if the decoder is already initialized, else \c true.
  90148. */
  90149. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder);
  90150. /** Direct the decoder to filter out all metadata blocks of type \a type.
  90151. *
  90152. * \default By default, only the \c STREAMINFO block is returned via the
  90153. * metadata callback.
  90154. * \param decoder A decoder instance to set.
  90155. * \param type See above.
  90156. * \assert
  90157. * \code decoder != NULL \endcode
  90158. * \a type is valid
  90159. * \retval FLAC__bool
  90160. * \c false if the decoder is already initialized, else \c true.
  90161. */
  90162. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  90163. /** Direct the decoder to filter out all APPLICATION metadata blocks of
  90164. * the given \a id.
  90165. *
  90166. * \default By default, only the \c STREAMINFO block is returned via the
  90167. * metadata callback.
  90168. * \param decoder A decoder instance to set.
  90169. * \param id See above.
  90170. * \assert
  90171. * \code decoder != NULL \endcode
  90172. * \code id != NULL \endcode
  90173. * \retval FLAC__bool
  90174. * \c false if the decoder is already initialized, else \c true.
  90175. */
  90176. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  90177. /** Direct the decoder to filter out all metadata blocks of any type.
  90178. *
  90179. * \default By default, only the \c STREAMINFO block is returned via the
  90180. * metadata callback.
  90181. * \param decoder A decoder instance to set.
  90182. * \assert
  90183. * \code decoder != NULL \endcode
  90184. * \retval FLAC__bool
  90185. * \c false if the decoder is already initialized, else \c true.
  90186. */
  90187. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder);
  90188. /** Get the current decoder state.
  90189. *
  90190. * \param decoder A decoder instance to query.
  90191. * \assert
  90192. * \code decoder != NULL \endcode
  90193. * \retval FLAC__StreamDecoderState
  90194. * The current decoder state.
  90195. */
  90196. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder);
  90197. /** Get the current decoder state as a C string.
  90198. *
  90199. * \param decoder A decoder instance to query.
  90200. * \assert
  90201. * \code decoder != NULL \endcode
  90202. * \retval const char *
  90203. * The decoder state as a C string. Do not modify the contents.
  90204. */
  90205. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder);
  90206. /** Get the "MD5 signature checking" flag.
  90207. * This is the value of the setting, not whether or not the decoder is
  90208. * currently checking the MD5 (remember, it can be turned off automatically
  90209. * by a seek). When the decoder is reset the flag will be restored to the
  90210. * value returned by this function.
  90211. *
  90212. * \param decoder A decoder instance to query.
  90213. * \assert
  90214. * \code decoder != NULL \endcode
  90215. * \retval FLAC__bool
  90216. * See above.
  90217. */
  90218. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder);
  90219. /** Get the total number of samples in the stream being decoded.
  90220. * Will only be valid after decoding has started and will contain the
  90221. * value from the \c STREAMINFO block. A value of \c 0 means "unknown".
  90222. *
  90223. * \param decoder A decoder instance to query.
  90224. * \assert
  90225. * \code decoder != NULL \endcode
  90226. * \retval unsigned
  90227. * See above.
  90228. */
  90229. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder);
  90230. /** Get the current number of channels in the stream being decoded.
  90231. * Will only be valid after decoding has started and will contain the
  90232. * value from the most recently decoded frame header.
  90233. *
  90234. * \param decoder A decoder instance to query.
  90235. * \assert
  90236. * \code decoder != NULL \endcode
  90237. * \retval unsigned
  90238. * See above.
  90239. */
  90240. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder);
  90241. /** Get the current channel assignment in the stream being decoded.
  90242. * Will only be valid after decoding has started and will contain the
  90243. * value from the most recently decoded frame header.
  90244. *
  90245. * \param decoder A decoder instance to query.
  90246. * \assert
  90247. * \code decoder != NULL \endcode
  90248. * \retval FLAC__ChannelAssignment
  90249. * See above.
  90250. */
  90251. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder);
  90252. /** Get the current sample resolution in the stream being decoded.
  90253. * Will only be valid after decoding has started and will contain the
  90254. * value from the most recently decoded frame header.
  90255. *
  90256. * \param decoder A decoder instance to query.
  90257. * \assert
  90258. * \code decoder != NULL \endcode
  90259. * \retval unsigned
  90260. * See above.
  90261. */
  90262. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder);
  90263. /** Get the current sample rate in Hz of the stream being decoded.
  90264. * Will only be valid after decoding has started and will contain the
  90265. * value from the most recently decoded frame header.
  90266. *
  90267. * \param decoder A decoder instance to query.
  90268. * \assert
  90269. * \code decoder != NULL \endcode
  90270. * \retval unsigned
  90271. * See above.
  90272. */
  90273. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder);
  90274. /** Get the current blocksize of the stream being decoded.
  90275. * Will only be valid after decoding has started and will contain the
  90276. * value from the most recently decoded frame header.
  90277. *
  90278. * \param decoder A decoder instance to query.
  90279. * \assert
  90280. * \code decoder != NULL \endcode
  90281. * \retval unsigned
  90282. * See above.
  90283. */
  90284. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder);
  90285. /** Returns the decoder's current read position within the stream.
  90286. * The position is the byte offset from the start of the stream.
  90287. * Bytes before this position have been fully decoded. Note that
  90288. * there may still be undecoded bytes in the decoder's read FIFO.
  90289. * The returned position is correct even after a seek.
  90290. *
  90291. * \warning This function currently only works for native FLAC,
  90292. * not Ogg FLAC streams.
  90293. *
  90294. * \param decoder A decoder instance to query.
  90295. * \param position Address at which to return the desired position.
  90296. * \assert
  90297. * \code decoder != NULL \endcode
  90298. * \code position != NULL \endcode
  90299. * \retval FLAC__bool
  90300. * \c true if successful, \c false if the stream is not native FLAC,
  90301. * or there was an error from the 'tell' callback or it returned
  90302. * \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED.
  90303. */
  90304. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position);
  90305. /** Initialize the decoder instance to decode native FLAC streams.
  90306. *
  90307. * This flavor of initialization sets up the decoder to decode from a
  90308. * native FLAC stream. I/O is performed via callbacks to the client.
  90309. * For decoding from a plain file via filename or open FILE*,
  90310. * FLAC__stream_decoder_init_file() and FLAC__stream_decoder_init_FILE()
  90311. * provide a simpler interface.
  90312. *
  90313. * This function should be called after FLAC__stream_decoder_new() and
  90314. * FLAC__stream_decoder_set_*() but before any of the
  90315. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90316. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90317. * if initialization succeeded.
  90318. *
  90319. * \param decoder An uninitialized decoder instance.
  90320. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  90321. * pointer must not be \c NULL.
  90322. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  90323. * pointer may be \c NULL if seeking is not
  90324. * supported. If \a seek_callback is not \c NULL then a
  90325. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  90326. * Alternatively, a dummy seek callback that just
  90327. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  90328. * may also be supplied, all though this is slightly
  90329. * less efficient for the decoder.
  90330. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  90331. * pointer may be \c NULL if not supported by the client. If
  90332. * \a seek_callback is not \c NULL then a
  90333. * \a tell_callback must also be supplied.
  90334. * Alternatively, a dummy tell callback that just
  90335. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  90336. * may also be supplied, all though this is slightly
  90337. * less efficient for the decoder.
  90338. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  90339. * pointer may be \c NULL if not supported by the client. If
  90340. * \a seek_callback is not \c NULL then a
  90341. * \a length_callback must also be supplied.
  90342. * Alternatively, a dummy length callback that just
  90343. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  90344. * may also be supplied, all though this is slightly
  90345. * less efficient for the decoder.
  90346. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  90347. * pointer may be \c NULL if not supported by the client. If
  90348. * \a seek_callback is not \c NULL then a
  90349. * \a eof_callback must also be supplied.
  90350. * Alternatively, a dummy length callback that just
  90351. * returns \c false
  90352. * may also be supplied, all though this is slightly
  90353. * less efficient for the decoder.
  90354. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90355. * pointer must not be \c NULL.
  90356. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90357. * pointer may be \c NULL if the callback is not
  90358. * desired.
  90359. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90360. * pointer must not be \c NULL.
  90361. * \param client_data This value will be supplied to callbacks in their
  90362. * \a client_data argument.
  90363. * \assert
  90364. * \code decoder != NULL \endcode
  90365. * \retval FLAC__StreamDecoderInitStatus
  90366. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90367. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90368. */
  90369. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  90370. FLAC__StreamDecoder *decoder,
  90371. FLAC__StreamDecoderReadCallback read_callback,
  90372. FLAC__StreamDecoderSeekCallback seek_callback,
  90373. FLAC__StreamDecoderTellCallback tell_callback,
  90374. FLAC__StreamDecoderLengthCallback length_callback,
  90375. FLAC__StreamDecoderEofCallback eof_callback,
  90376. FLAC__StreamDecoderWriteCallback write_callback,
  90377. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90378. FLAC__StreamDecoderErrorCallback error_callback,
  90379. void *client_data
  90380. );
  90381. /** Initialize the decoder instance to decode Ogg FLAC streams.
  90382. *
  90383. * This flavor of initialization sets up the decoder to decode from a
  90384. * FLAC stream in an Ogg container. I/O is performed via callbacks to the
  90385. * client. For decoding from a plain file via filename or open FILE*,
  90386. * FLAC__stream_decoder_init_ogg_file() and FLAC__stream_decoder_init_ogg_FILE()
  90387. * provide a simpler interface.
  90388. *
  90389. * This function should be called after FLAC__stream_decoder_new() and
  90390. * FLAC__stream_decoder_set_*() but before any of the
  90391. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90392. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90393. * if initialization succeeded.
  90394. *
  90395. * \note Support for Ogg FLAC in the library is optional. If this
  90396. * library has been built without support for Ogg FLAC, this function
  90397. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90398. *
  90399. * \param decoder An uninitialized decoder instance.
  90400. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  90401. * pointer must not be \c NULL.
  90402. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  90403. * pointer may be \c NULL if seeking is not
  90404. * supported. If \a seek_callback is not \c NULL then a
  90405. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  90406. * Alternatively, a dummy seek callback that just
  90407. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  90408. * may also be supplied, all though this is slightly
  90409. * less efficient for the decoder.
  90410. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  90411. * pointer may be \c NULL if not supported by the client. If
  90412. * \a seek_callback is not \c NULL then a
  90413. * \a tell_callback must also be supplied.
  90414. * Alternatively, a dummy tell callback that just
  90415. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  90416. * may also be supplied, all though this is slightly
  90417. * less efficient for the decoder.
  90418. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  90419. * pointer may be \c NULL if not supported by the client. If
  90420. * \a seek_callback is not \c NULL then a
  90421. * \a length_callback must also be supplied.
  90422. * Alternatively, a dummy length callback that just
  90423. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  90424. * may also be supplied, all though this is slightly
  90425. * less efficient for the decoder.
  90426. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  90427. * pointer may be \c NULL if not supported by the client. If
  90428. * \a seek_callback is not \c NULL then a
  90429. * \a eof_callback must also be supplied.
  90430. * Alternatively, a dummy length callback that just
  90431. * returns \c false
  90432. * may also be supplied, all though this is slightly
  90433. * less efficient for the decoder.
  90434. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90435. * pointer must not be \c NULL.
  90436. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90437. * pointer may be \c NULL if the callback is not
  90438. * desired.
  90439. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90440. * pointer must not be \c NULL.
  90441. * \param client_data This value will be supplied to callbacks in their
  90442. * \a client_data argument.
  90443. * \assert
  90444. * \code decoder != NULL \endcode
  90445. * \retval FLAC__StreamDecoderInitStatus
  90446. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90447. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90448. */
  90449. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  90450. FLAC__StreamDecoder *decoder,
  90451. FLAC__StreamDecoderReadCallback read_callback,
  90452. FLAC__StreamDecoderSeekCallback seek_callback,
  90453. FLAC__StreamDecoderTellCallback tell_callback,
  90454. FLAC__StreamDecoderLengthCallback length_callback,
  90455. FLAC__StreamDecoderEofCallback eof_callback,
  90456. FLAC__StreamDecoderWriteCallback write_callback,
  90457. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90458. FLAC__StreamDecoderErrorCallback error_callback,
  90459. void *client_data
  90460. );
  90461. /** Initialize the decoder instance to decode native FLAC files.
  90462. *
  90463. * This flavor of initialization sets up the decoder to decode from a
  90464. * plain native FLAC file. For non-stdio streams, you must use
  90465. * FLAC__stream_decoder_init_stream() and provide callbacks for the I/O.
  90466. *
  90467. * This function should be called after FLAC__stream_decoder_new() and
  90468. * FLAC__stream_decoder_set_*() but before any of the
  90469. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90470. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90471. * if initialization succeeded.
  90472. *
  90473. * \param decoder An uninitialized decoder instance.
  90474. * \param file An open FLAC file. The file should have been
  90475. * opened with mode \c "rb" and rewound. The file
  90476. * becomes owned by the decoder and should not be
  90477. * manipulated by the client while decoding.
  90478. * Unless \a file is \c stdin, it will be closed
  90479. * when FLAC__stream_decoder_finish() is called.
  90480. * Note however that seeking will not work when
  90481. * decoding from \c stdout since it is not seekable.
  90482. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90483. * pointer must not be \c NULL.
  90484. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90485. * pointer may be \c NULL if the callback is not
  90486. * desired.
  90487. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90488. * pointer must not be \c NULL.
  90489. * \param client_data This value will be supplied to callbacks in their
  90490. * \a client_data argument.
  90491. * \assert
  90492. * \code decoder != NULL \endcode
  90493. * \code file != NULL \endcode
  90494. * \retval FLAC__StreamDecoderInitStatus
  90495. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90496. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90497. */
  90498. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  90499. FLAC__StreamDecoder *decoder,
  90500. FILE *file,
  90501. FLAC__StreamDecoderWriteCallback write_callback,
  90502. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90503. FLAC__StreamDecoderErrorCallback error_callback,
  90504. void *client_data
  90505. );
  90506. /** Initialize the decoder instance to decode Ogg FLAC files.
  90507. *
  90508. * This flavor of initialization sets up the decoder to decode from a
  90509. * plain Ogg FLAC file. For non-stdio streams, you must use
  90510. * FLAC__stream_decoder_init_ogg_stream() and provide callbacks for the I/O.
  90511. *
  90512. * This function should be called after FLAC__stream_decoder_new() and
  90513. * FLAC__stream_decoder_set_*() but before any of the
  90514. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90515. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90516. * if initialization succeeded.
  90517. *
  90518. * \note Support for Ogg FLAC in the library is optional. If this
  90519. * library has been built without support for Ogg FLAC, this function
  90520. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90521. *
  90522. * \param decoder An uninitialized decoder instance.
  90523. * \param file An open FLAC file. The file should have been
  90524. * opened with mode \c "rb" and rewound. The file
  90525. * becomes owned by the decoder and should not be
  90526. * manipulated by the client while decoding.
  90527. * Unless \a file is \c stdin, it will be closed
  90528. * when FLAC__stream_decoder_finish() is called.
  90529. * Note however that seeking will not work when
  90530. * decoding from \c stdout since it 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. * \code file != NULL \endcode
  90543. * \retval FLAC__StreamDecoderInitStatus
  90544. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90545. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90546. */
  90547. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  90548. FLAC__StreamDecoder *decoder,
  90549. FILE *file,
  90550. FLAC__StreamDecoderWriteCallback write_callback,
  90551. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90552. FLAC__StreamDecoderErrorCallback error_callback,
  90553. void *client_data
  90554. );
  90555. /** Initialize the decoder instance to decode native FLAC files.
  90556. *
  90557. * This flavor of initialization sets up the decoder to decode from a plain
  90558. * native FLAC file. If POSIX fopen() semantics are not sufficient, (for
  90559. * example, with Unicode filenames on Windows), you must use
  90560. * FLAC__stream_decoder_init_FILE(), or FLAC__stream_decoder_init_stream()
  90561. * and provide callbacks for the I/O.
  90562. *
  90563. * This function should be called after FLAC__stream_decoder_new() and
  90564. * FLAC__stream_decoder_set_*() but before any of the
  90565. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90566. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90567. * if initialization succeeded.
  90568. *
  90569. * \param decoder An uninitialized decoder instance.
  90570. * \param filename The name of the file to decode from. The file will
  90571. * be opened with fopen(). Use \c NULL to decode from
  90572. * \c stdin. Note that \c stdin is not seekable.
  90573. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90574. * pointer must not be \c NULL.
  90575. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90576. * pointer may be \c NULL if the callback is not
  90577. * desired.
  90578. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90579. * pointer must not be \c NULL.
  90580. * \param client_data This value will be supplied to callbacks in their
  90581. * \a client_data argument.
  90582. * \assert
  90583. * \code decoder != NULL \endcode
  90584. * \retval FLAC__StreamDecoderInitStatus
  90585. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90586. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90587. */
  90588. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  90589. FLAC__StreamDecoder *decoder,
  90590. const char *filename,
  90591. FLAC__StreamDecoderWriteCallback write_callback,
  90592. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90593. FLAC__StreamDecoderErrorCallback error_callback,
  90594. void *client_data
  90595. );
  90596. /** Initialize the decoder instance to decode Ogg FLAC files.
  90597. *
  90598. * This flavor of initialization sets up the decoder to decode from a plain
  90599. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient, (for
  90600. * example, with Unicode filenames on Windows), you must use
  90601. * FLAC__stream_decoder_init_ogg_FILE(), or FLAC__stream_decoder_init_ogg_stream()
  90602. * and provide callbacks for the I/O.
  90603. *
  90604. * This function should be called after FLAC__stream_decoder_new() and
  90605. * FLAC__stream_decoder_set_*() but before any of the
  90606. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90607. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90608. * if initialization succeeded.
  90609. *
  90610. * \note Support for Ogg FLAC in the library is optional. If this
  90611. * library has been built without support for Ogg FLAC, this function
  90612. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90613. *
  90614. * \param decoder An uninitialized decoder instance.
  90615. * \param filename The name of the file to decode from. The file will
  90616. * be opened with fopen(). Use \c NULL to decode from
  90617. * \c stdin. Note that \c stdin is not seekable.
  90618. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90619. * pointer must not be \c NULL.
  90620. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90621. * pointer may be \c NULL if the callback is not
  90622. * desired.
  90623. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90624. * pointer must not be \c NULL.
  90625. * \param client_data This value will be supplied to callbacks in their
  90626. * \a client_data argument.
  90627. * \assert
  90628. * \code decoder != NULL \endcode
  90629. * \retval FLAC__StreamDecoderInitStatus
  90630. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90631. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90632. */
  90633. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  90634. FLAC__StreamDecoder *decoder,
  90635. const char *filename,
  90636. FLAC__StreamDecoderWriteCallback write_callback,
  90637. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90638. FLAC__StreamDecoderErrorCallback error_callback,
  90639. void *client_data
  90640. );
  90641. /** Finish the decoding process.
  90642. * Flushes the decoding buffer, releases resources, resets the decoder
  90643. * settings to their defaults, and returns the decoder state to
  90644. * FLAC__STREAM_DECODER_UNINITIALIZED.
  90645. *
  90646. * In the event of a prematurely-terminated decode, it is not strictly
  90647. * necessary to call this immediately before FLAC__stream_decoder_delete()
  90648. * but it is good practice to match every FLAC__stream_decoder_init_*()
  90649. * with a FLAC__stream_decoder_finish().
  90650. *
  90651. * \param decoder An uninitialized decoder instance.
  90652. * \assert
  90653. * \code decoder != NULL \endcode
  90654. * \retval FLAC__bool
  90655. * \c false if MD5 checking is on AND a STREAMINFO block was available
  90656. * AND the MD5 signature in the STREAMINFO block was non-zero AND the
  90657. * signature does not match the one computed by the decoder; else
  90658. * \c true.
  90659. */
  90660. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder);
  90661. /** Flush the stream input.
  90662. * The decoder's input buffer will be cleared and the state set to
  90663. * \c FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC. This will also turn
  90664. * off MD5 checking.
  90665. *
  90666. * \param decoder A decoder instance.
  90667. * \assert
  90668. * \code decoder != NULL \endcode
  90669. * \retval FLAC__bool
  90670. * \c true if successful, else \c false if a memory allocation
  90671. * error occurs (in which case the state will be set to
  90672. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR).
  90673. */
  90674. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder);
  90675. /** Reset the decoding process.
  90676. * The decoder's input buffer will be cleared and the state set to
  90677. * \c FLAC__STREAM_DECODER_SEARCH_FOR_METADATA. This is similar to
  90678. * FLAC__stream_decoder_finish() except that the settings are
  90679. * preserved; there is no need to call FLAC__stream_decoder_init_*()
  90680. * before decoding again. MD5 checking will be restored to its original
  90681. * setting.
  90682. *
  90683. * If the decoder is seekable, or was initialized with
  90684. * FLAC__stream_decoder_init*_FILE() or FLAC__stream_decoder_init*_file(),
  90685. * the decoder will also attempt to seek to the beginning of the file.
  90686. * If this rewind fails, this function will return \c false. It follows
  90687. * that FLAC__stream_decoder_reset() cannot be used when decoding from
  90688. * \c stdin.
  90689. *
  90690. * If the decoder was initialized with FLAC__stream_encoder_init*_stream()
  90691. * and is not seekable (i.e. no seek callback was provided or the seek
  90692. * callback returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED), it
  90693. * is the duty of the client to start feeding data from the beginning of
  90694. * the stream on the next FLAC__stream_decoder_process() or
  90695. * FLAC__stream_decoder_process_interleaved() call.
  90696. *
  90697. * \param decoder A decoder instance.
  90698. * \assert
  90699. * \code decoder != NULL \endcode
  90700. * \retval FLAC__bool
  90701. * \c true if successful, else \c false if a memory allocation occurs
  90702. * (in which case the state will be set to
  90703. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR) or a seek error
  90704. * occurs (the state will be unchanged).
  90705. */
  90706. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder);
  90707. /** Decode one metadata block or audio frame.
  90708. * This version instructs the decoder to decode a either a single metadata
  90709. * block or a single frame and stop, unless the callbacks return a fatal
  90710. * error or the read callback returns
  90711. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90712. *
  90713. * As the decoder needs more input it will call the read callback.
  90714. * Depending on what was decoded, the metadata or write callback will be
  90715. * called with the decoded metadata block or audio frame.
  90716. *
  90717. * Unless there is a fatal read error or end of stream, this function
  90718. * will return once one whole frame is decoded. In other words, if the
  90719. * stream is not synchronized or points to a corrupt frame header, the
  90720. * decoder will continue to try and resync until it gets to a valid
  90721. * frame, then decode one frame, then return. If the decoder points to
  90722. * a frame whose frame CRC in the frame footer does not match the
  90723. * computed frame CRC, this function will issue a
  90724. * FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH error to the
  90725. * error callback, and return, having decoded one complete, although
  90726. * corrupt, frame. (Such corrupted frames are sent as silence of the
  90727. * correct length to the write callback.)
  90728. *
  90729. * \param decoder An initialized decoder instance.
  90730. * \assert
  90731. * \code decoder != NULL \endcode
  90732. * \retval FLAC__bool
  90733. * \c false if any fatal read, write, or memory allocation error
  90734. * occurred (meaning decoding must stop), else \c true; for more
  90735. * information about the decoder, check the decoder state with
  90736. * FLAC__stream_decoder_get_state().
  90737. */
  90738. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder);
  90739. /** Decode until the end of the metadata.
  90740. * This version instructs the decoder to decode from the current position
  90741. * and continue until all the metadata has been read, or until the
  90742. * callbacks return a fatal error or the read callback returns
  90743. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90744. *
  90745. * As the decoder needs more input it will call the read callback.
  90746. * As each metadata block is decoded, the metadata callback will be called
  90747. * with the decoded metadata.
  90748. *
  90749. * \param decoder An initialized decoder instance.
  90750. * \assert
  90751. * \code decoder != NULL \endcode
  90752. * \retval FLAC__bool
  90753. * \c false if any fatal read, write, or memory allocation error
  90754. * occurred (meaning decoding must stop), else \c true; for more
  90755. * information about the decoder, check the decoder state with
  90756. * FLAC__stream_decoder_get_state().
  90757. */
  90758. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder);
  90759. /** Decode until the end of the stream.
  90760. * This version instructs the decoder to decode from the current position
  90761. * and continue until the end of stream (the read callback returns
  90762. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM), or until the
  90763. * callbacks return a fatal error.
  90764. *
  90765. * As the decoder needs more input it will call the read callback.
  90766. * As each metadata block and frame is decoded, the metadata or write
  90767. * callback will be called with the decoded metadata or frame.
  90768. *
  90769. * \param decoder An initialized decoder instance.
  90770. * \assert
  90771. * \code decoder != NULL \endcode
  90772. * \retval FLAC__bool
  90773. * \c false if any fatal read, write, or memory allocation error
  90774. * occurred (meaning decoding must stop), else \c true; for more
  90775. * information about the decoder, check the decoder state with
  90776. * FLAC__stream_decoder_get_state().
  90777. */
  90778. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder);
  90779. /** Skip one audio frame.
  90780. * This version instructs the decoder to 'skip' a single frame and stop,
  90781. * unless the callbacks return a fatal error or the read callback returns
  90782. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90783. *
  90784. * The decoding flow is the same as what occurs when
  90785. * FLAC__stream_decoder_process_single() is called to process an audio
  90786. * frame, except that this function does not decode the parsed data into
  90787. * PCM or call the write callback. The integrity of the frame is still
  90788. * checked the same way as in the other process functions.
  90789. *
  90790. * This function will return once one whole frame is skipped, in the
  90791. * same way that FLAC__stream_decoder_process_single() will return once
  90792. * one whole frame is decoded.
  90793. *
  90794. * This function can be used in more quickly determining FLAC frame
  90795. * boundaries when decoding of the actual data is not needed, for
  90796. * example when an application is separating a FLAC stream into frames
  90797. * for editing or storing in a container. To do this, the application
  90798. * can use FLAC__stream_decoder_skip_single_frame() to quickly advance
  90799. * to the next frame, then use
  90800. * FLAC__stream_decoder_get_decode_position() to find the new frame
  90801. * boundary.
  90802. *
  90803. * This function should only be called when the stream has advanced
  90804. * past all the metadata, otherwise it will return \c false.
  90805. *
  90806. * \param decoder An initialized decoder instance not in a metadata
  90807. * state.
  90808. * \assert
  90809. * \code decoder != NULL \endcode
  90810. * \retval FLAC__bool
  90811. * \c false if any fatal read, write, or memory allocation error
  90812. * occurred (meaning decoding must stop), or if the decoder
  90813. * is in the FLAC__STREAM_DECODER_SEARCH_FOR_METADATA or
  90814. * FLAC__STREAM_DECODER_READ_METADATA state, else \c true; for more
  90815. * information about the decoder, check the decoder state with
  90816. * FLAC__stream_decoder_get_state().
  90817. */
  90818. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder);
  90819. /** Flush the input and seek to an absolute sample.
  90820. * Decoding will resume at the given sample. Note that because of
  90821. * this, the next write callback may contain a partial block. The
  90822. * client must support seeking the input or this function will fail
  90823. * and return \c false. Furthermore, if the decoder state is
  90824. * \c FLAC__STREAM_DECODER_SEEK_ERROR, then the decoder must be flushed
  90825. * with FLAC__stream_decoder_flush() or reset with
  90826. * FLAC__stream_decoder_reset() before decoding can continue.
  90827. *
  90828. * \param decoder A decoder instance.
  90829. * \param sample The target sample number to seek to.
  90830. * \assert
  90831. * \code decoder != NULL \endcode
  90832. * \retval FLAC__bool
  90833. * \c true if successful, else \c false.
  90834. */
  90835. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample);
  90836. /* \} */
  90837. #ifdef __cplusplus
  90838. }
  90839. #endif
  90840. #endif
  90841. /*** End of inlined file: stream_decoder.h ***/
  90842. /*** Start of inlined file: stream_encoder.h ***/
  90843. #ifndef FLAC__STREAM_ENCODER_H
  90844. #define FLAC__STREAM_ENCODER_H
  90845. #include <stdio.h> /* for FILE */
  90846. #ifdef __cplusplus
  90847. extern "C" {
  90848. #endif
  90849. /** \file include/FLAC/stream_encoder.h
  90850. *
  90851. * \brief
  90852. * This module contains the functions which implement the stream
  90853. * encoder.
  90854. *
  90855. * See the detailed documentation in the
  90856. * \link flac_stream_encoder stream encoder \endlink module.
  90857. */
  90858. /** \defgroup flac_encoder FLAC/ \*_encoder.h: encoder interfaces
  90859. * \ingroup flac
  90860. *
  90861. * \brief
  90862. * This module describes the encoder layers provided by libFLAC.
  90863. *
  90864. * The stream encoder can be used to encode complete streams either to the
  90865. * client via callbacks, or directly to a file, depending on how it is
  90866. * initialized. When encoding via callbacks, the client provides a write
  90867. * callback which will be called whenever FLAC data is ready to be written.
  90868. * If the client also supplies a seek callback, the encoder will also
  90869. * automatically handle the writing back of metadata discovered while
  90870. * encoding, like stream info, seek points offsets, etc. When encoding to
  90871. * a file, the client needs only supply a filename or open \c FILE* and an
  90872. * optional progress callback for periodic notification of progress; the
  90873. * write and seek callbacks are supplied internally. For more info see the
  90874. * \link flac_stream_encoder stream encoder \endlink module.
  90875. */
  90876. /** \defgroup flac_stream_encoder FLAC/stream_encoder.h: stream encoder interface
  90877. * \ingroup flac_encoder
  90878. *
  90879. * \brief
  90880. * This module contains the functions which implement the stream
  90881. * encoder.
  90882. *
  90883. * The stream encoder can encode to native FLAC, and optionally Ogg FLAC
  90884. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  90885. *
  90886. * The basic usage of this encoder is as follows:
  90887. * - The program creates an instance of an encoder using
  90888. * FLAC__stream_encoder_new().
  90889. * - The program overrides the default settings using
  90890. * FLAC__stream_encoder_set_*() functions. At a minimum, the following
  90891. * functions should be called:
  90892. * - FLAC__stream_encoder_set_channels()
  90893. * - FLAC__stream_encoder_set_bits_per_sample()
  90894. * - FLAC__stream_encoder_set_sample_rate()
  90895. * - FLAC__stream_encoder_set_ogg_serial_number() (if encoding to Ogg FLAC)
  90896. * - FLAC__stream_encoder_set_total_samples_estimate() (if known)
  90897. * - If the application wants to control the compression level or set its own
  90898. * metadata, then the following should also be called:
  90899. * - FLAC__stream_encoder_set_compression_level()
  90900. * - FLAC__stream_encoder_set_verify()
  90901. * - FLAC__stream_encoder_set_metadata()
  90902. * - The rest of the set functions should only be called if the client needs
  90903. * exact control over how the audio is compressed; thorough understanding
  90904. * of the FLAC format is necessary to achieve good results.
  90905. * - The program initializes the instance to validate the settings and
  90906. * prepare for encoding using
  90907. * - FLAC__stream_encoder_init_stream() or FLAC__stream_encoder_init_FILE()
  90908. * or FLAC__stream_encoder_init_file() for native FLAC
  90909. * - FLAC__stream_encoder_init_ogg_stream() or FLAC__stream_encoder_init_ogg_FILE()
  90910. * or FLAC__stream_encoder_init_ogg_file() for Ogg FLAC
  90911. * - The program calls FLAC__stream_encoder_process() or
  90912. * FLAC__stream_encoder_process_interleaved() to encode data, which
  90913. * subsequently calls the callbacks when there is encoder data ready
  90914. * to be written.
  90915. * - The program finishes the encoding with FLAC__stream_encoder_finish(),
  90916. * which causes the encoder to encode any data still in its input pipe,
  90917. * update the metadata with the final encoding statistics if output
  90918. * seeking is possible, and finally reset the encoder to the
  90919. * uninitialized state.
  90920. * - The instance may be used again or deleted with
  90921. * FLAC__stream_encoder_delete().
  90922. *
  90923. * In more detail, the stream encoder functions similarly to the
  90924. * \link flac_stream_decoder stream decoder \endlink, but has fewer
  90925. * callbacks and more options. Typically the client will create a new
  90926. * instance by calling FLAC__stream_encoder_new(), then set the necessary
  90927. * parameters with FLAC__stream_encoder_set_*(), and initialize it by
  90928. * calling one of the FLAC__stream_encoder_init_*() functions.
  90929. *
  90930. * Unlike the decoders, the stream encoder has many options that can
  90931. * affect the speed and compression ratio. When setting these parameters
  90932. * you should have some basic knowledge of the format (see the
  90933. * <A HREF="../documentation.html#format">user-level documentation</A>
  90934. * or the <A HREF="../format.html">formal description</A>). The
  90935. * FLAC__stream_encoder_set_*() functions themselves do not validate the
  90936. * values as many are interdependent. The FLAC__stream_encoder_init_*()
  90937. * functions will do this, so make sure to pay attention to the state
  90938. * returned by FLAC__stream_encoder_init_*() to make sure that it is
  90939. * FLAC__STREAM_ENCODER_INIT_STATUS_OK. Any parameters that are not set
  90940. * before FLAC__stream_encoder_init_*() will take on the defaults from
  90941. * the constructor.
  90942. *
  90943. * There are three initialization functions for native FLAC, one for
  90944. * setting up the encoder to encode FLAC data to the client via
  90945. * callbacks, and two for encoding directly to a file.
  90946. *
  90947. * For encoding via callbacks, use FLAC__stream_encoder_init_stream().
  90948. * You must also supply a write callback which will be called anytime
  90949. * there is raw encoded data to write. If the client can seek the output
  90950. * it is best to also supply seek and tell callbacks, as this allows the
  90951. * encoder to go back after encoding is finished to write back
  90952. * information that was collected while encoding, like seek point offsets,
  90953. * frame sizes, etc.
  90954. *
  90955. * For encoding directly to a file, use FLAC__stream_encoder_init_FILE()
  90956. * or FLAC__stream_encoder_init_file(). Then you must only supply a
  90957. * filename or open \c FILE*; the encoder will handle all the callbacks
  90958. * internally. You may also supply a progress callback for periodic
  90959. * notification of the encoding progress.
  90960. *
  90961. * There are three similarly-named init functions for encoding to Ogg
  90962. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  90963. * library has been built with Ogg support.
  90964. *
  90965. * The call to FLAC__stream_encoder_init_*() currently will also immediately
  90966. * call the write callback several times, once with the \c fLaC signature,
  90967. * and once for each encoded metadata block. Note that for Ogg FLAC
  90968. * encoding you will usually get at least twice the number of callbacks than
  90969. * with native FLAC, one for the Ogg page header and one for the page body.
  90970. *
  90971. * After initializing the instance, the client may feed audio data to the
  90972. * encoder in one of two ways:
  90973. *
  90974. * - Channel separate, through FLAC__stream_encoder_process() - The client
  90975. * will pass an array of pointers to buffers, one for each channel, to
  90976. * the encoder, each of the same length. The samples need not be
  90977. * block-aligned, but each channel should have the same number of samples.
  90978. * - Channel interleaved, through
  90979. * FLAC__stream_encoder_process_interleaved() - The client will pass a single
  90980. * pointer to data that is channel-interleaved (i.e. channel0_sample0,
  90981. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  90982. * Again, the samples need not be block-aligned but they must be
  90983. * sample-aligned, i.e. the first value should be channel0_sample0 and
  90984. * the last value channelN_sampleM.
  90985. *
  90986. * Note that for either process call, each sample in the buffers should be a
  90987. * signed integer, right-justified to the resolution set by
  90988. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the resolution
  90989. * is 16 bits per sample, the samples should all be in the range [-32768,32767].
  90990. *
  90991. * When the client is finished encoding data, it calls
  90992. * FLAC__stream_encoder_finish(), which causes the encoder to encode any
  90993. * data still in its input pipe, and call the metadata callback with the
  90994. * final encoding statistics. Then the instance may be deleted with
  90995. * FLAC__stream_encoder_delete() or initialized again to encode another
  90996. * stream.
  90997. *
  90998. * For programs that write their own metadata, but that do not know the
  90999. * actual metadata until after encoding, it is advantageous to instruct
  91000. * the encoder to write a PADDING block of the correct size, so that
  91001. * instead of rewriting the whole stream after encoding, the program can
  91002. * just overwrite the PADDING block. If only the maximum size of the
  91003. * metadata is known, the program can write a slightly larger padding
  91004. * block, then split it after encoding.
  91005. *
  91006. * Make sure you understand how lengths are calculated. All FLAC metadata
  91007. * blocks have a 4 byte header which contains the type and length. This
  91008. * length does not include the 4 bytes of the header. See the format page
  91009. * for the specification of metadata blocks and their lengths.
  91010. *
  91011. * \note
  91012. * If you are writing the FLAC data to a file via callbacks, make sure it
  91013. * is open for update (e.g. mode "w+" for stdio streams). This is because
  91014. * after the first encoding pass, the encoder will try to seek back to the
  91015. * beginning of the stream, to the STREAMINFO block, to write some data
  91016. * there. (If using FLAC__stream_encoder_init*_file() or
  91017. * FLAC__stream_encoder_init*_FILE(), the file is managed internally.)
  91018. *
  91019. * \note
  91020. * The "set" functions may only be called when the encoder is in the
  91021. * state FLAC__STREAM_ENCODER_UNINITIALIZED, i.e. after
  91022. * FLAC__stream_encoder_new() or FLAC__stream_encoder_finish(), but
  91023. * before FLAC__stream_encoder_init_*(). If this is the case they will
  91024. * return \c true, otherwise \c false.
  91025. *
  91026. * \note
  91027. * FLAC__stream_encoder_finish() resets all settings to the constructor
  91028. * defaults.
  91029. *
  91030. * \{
  91031. */
  91032. /** State values for a FLAC__StreamEncoder.
  91033. *
  91034. * The encoder's state can be obtained by calling FLAC__stream_encoder_get_state().
  91035. *
  91036. * If the encoder gets into any other state besides \c FLAC__STREAM_ENCODER_OK
  91037. * or \c FLAC__STREAM_ENCODER_UNINITIALIZED, it becomes invalid for encoding and
  91038. * must be deleted with FLAC__stream_encoder_delete().
  91039. */
  91040. typedef enum {
  91041. FLAC__STREAM_ENCODER_OK = 0,
  91042. /**< The encoder is in the normal OK state and samples can be processed. */
  91043. FLAC__STREAM_ENCODER_UNINITIALIZED,
  91044. /**< The encoder is in the uninitialized state; one of the
  91045. * FLAC__stream_encoder_init_*() functions must be called before samples
  91046. * can be processed.
  91047. */
  91048. FLAC__STREAM_ENCODER_OGG_ERROR,
  91049. /**< An error occurred in the underlying Ogg layer. */
  91050. FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR,
  91051. /**< An error occurred in the underlying verify stream decoder;
  91052. * check FLAC__stream_encoder_get_verify_decoder_state().
  91053. */
  91054. FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA,
  91055. /**< The verify decoder detected a mismatch between the original
  91056. * audio signal and the decoded audio signal.
  91057. */
  91058. FLAC__STREAM_ENCODER_CLIENT_ERROR,
  91059. /**< One of the callbacks returned a fatal error. */
  91060. FLAC__STREAM_ENCODER_IO_ERROR,
  91061. /**< An I/O error occurred while opening/reading/writing a file.
  91062. * Check \c errno.
  91063. */
  91064. FLAC__STREAM_ENCODER_FRAMING_ERROR,
  91065. /**< An error occurred while writing the stream; usually, the
  91066. * write_callback returned an error.
  91067. */
  91068. FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR
  91069. /**< Memory allocation failed. */
  91070. } FLAC__StreamEncoderState;
  91071. /** Maps a FLAC__StreamEncoderState to a C string.
  91072. *
  91073. * Using a FLAC__StreamEncoderState as the index to this array
  91074. * will give the string equivalent. The contents should not be modified.
  91075. */
  91076. extern FLAC_API const char * const FLAC__StreamEncoderStateString[];
  91077. /** Possible return values for the FLAC__stream_encoder_init_*() functions.
  91078. */
  91079. typedef enum {
  91080. FLAC__STREAM_ENCODER_INIT_STATUS_OK = 0,
  91081. /**< Initialization was successful. */
  91082. FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR,
  91083. /**< General failure to set up encoder; call FLAC__stream_encoder_get_state() for cause. */
  91084. FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  91085. /**< The library was not compiled with support for the given container
  91086. * format.
  91087. */
  91088. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS,
  91089. /**< A required callback was not supplied. */
  91090. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS,
  91091. /**< The encoder has an invalid setting for number of channels. */
  91092. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE,
  91093. /**< The encoder has an invalid setting for bits-per-sample.
  91094. * FLAC supports 4-32 bps but the reference encoder currently supports
  91095. * only up to 24 bps.
  91096. */
  91097. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE,
  91098. /**< The encoder has an invalid setting for the input sample rate. */
  91099. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE,
  91100. /**< The encoder has an invalid setting for the block size. */
  91101. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER,
  91102. /**< The encoder has an invalid setting for the maximum LPC order. */
  91103. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION,
  91104. /**< The encoder has an invalid setting for the precision of the quantized linear predictor coefficients. */
  91105. FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER,
  91106. /**< The specified block size is less than the maximum LPC order. */
  91107. FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE,
  91108. /**< The encoder is bound to the <A HREF="../format.html#subset">Subset</A> but other settings violate it. */
  91109. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA,
  91110. /**< The metadata input to the encoder is invalid, in one of the following ways:
  91111. * - FLAC__stream_encoder_set_metadata() was called with a null pointer but a block count > 0
  91112. * - One of the metadata blocks contains an undefined type
  91113. * - It contains an illegal CUESHEET as checked by FLAC__format_cuesheet_is_legal()
  91114. * - It contains an illegal SEEKTABLE as checked by FLAC__format_seektable_is_legal()
  91115. * - It contains more than one SEEKTABLE block or more than one VORBIS_COMMENT block
  91116. */
  91117. FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED
  91118. /**< FLAC__stream_encoder_init_*() was called when the encoder was
  91119. * already initialized, usually because
  91120. * FLAC__stream_encoder_finish() was not called.
  91121. */
  91122. } FLAC__StreamEncoderInitStatus;
  91123. /** Maps a FLAC__StreamEncoderInitStatus to a C string.
  91124. *
  91125. * Using a FLAC__StreamEncoderInitStatus as the index to this array
  91126. * will give the string equivalent. The contents should not be modified.
  91127. */
  91128. extern FLAC_API const char * const FLAC__StreamEncoderInitStatusString[];
  91129. /** Return values for the FLAC__StreamEncoder read callback.
  91130. */
  91131. typedef enum {
  91132. FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE,
  91133. /**< The read was OK and decoding can continue. */
  91134. FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM,
  91135. /**< The read was attempted at the end of the stream. */
  91136. FLAC__STREAM_ENCODER_READ_STATUS_ABORT,
  91137. /**< An unrecoverable error occurred. */
  91138. FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED
  91139. /**< Client does not support reading back from the output. */
  91140. } FLAC__StreamEncoderReadStatus;
  91141. /** Maps a FLAC__StreamEncoderReadStatus to a C string.
  91142. *
  91143. * Using a FLAC__StreamEncoderReadStatus as the index to this array
  91144. * will give the string equivalent. The contents should not be modified.
  91145. */
  91146. extern FLAC_API const char * const FLAC__StreamEncoderReadStatusString[];
  91147. /** Return values for the FLAC__StreamEncoder write callback.
  91148. */
  91149. typedef enum {
  91150. FLAC__STREAM_ENCODER_WRITE_STATUS_OK = 0,
  91151. /**< The write was OK and encoding can continue. */
  91152. FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR
  91153. /**< An unrecoverable error occurred. The encoder will return from the process call. */
  91154. } FLAC__StreamEncoderWriteStatus;
  91155. /** Maps a FLAC__StreamEncoderWriteStatus to a C string.
  91156. *
  91157. * Using a FLAC__StreamEncoderWriteStatus as the index to this array
  91158. * will give the string equivalent. The contents should not be modified.
  91159. */
  91160. extern FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[];
  91161. /** Return values for the FLAC__StreamEncoder seek callback.
  91162. */
  91163. typedef enum {
  91164. FLAC__STREAM_ENCODER_SEEK_STATUS_OK,
  91165. /**< The seek was OK and encoding can continue. */
  91166. FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR,
  91167. /**< An unrecoverable error occurred. */
  91168. FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  91169. /**< Client does not support seeking. */
  91170. } FLAC__StreamEncoderSeekStatus;
  91171. /** Maps a FLAC__StreamEncoderSeekStatus to a C string.
  91172. *
  91173. * Using a FLAC__StreamEncoderSeekStatus as the index to this array
  91174. * will give the string equivalent. The contents should not be modified.
  91175. */
  91176. extern FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[];
  91177. /** Return values for the FLAC__StreamEncoder tell callback.
  91178. */
  91179. typedef enum {
  91180. FLAC__STREAM_ENCODER_TELL_STATUS_OK,
  91181. /**< The tell was OK and encoding can continue. */
  91182. FLAC__STREAM_ENCODER_TELL_STATUS_ERROR,
  91183. /**< An unrecoverable error occurred. */
  91184. FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  91185. /**< Client does not support seeking. */
  91186. } FLAC__StreamEncoderTellStatus;
  91187. /** Maps a FLAC__StreamEncoderTellStatus to a C string.
  91188. *
  91189. * Using a FLAC__StreamEncoderTellStatus as the index to this array
  91190. * will give the string equivalent. The contents should not be modified.
  91191. */
  91192. extern FLAC_API const char * const FLAC__StreamEncoderTellStatusString[];
  91193. /***********************************************************************
  91194. *
  91195. * class FLAC__StreamEncoder
  91196. *
  91197. ***********************************************************************/
  91198. struct FLAC__StreamEncoderProtected;
  91199. struct FLAC__StreamEncoderPrivate;
  91200. /** The opaque structure definition for the stream encoder type.
  91201. * See the \link flac_stream_encoder stream encoder module \endlink
  91202. * for a detailed description.
  91203. */
  91204. typedef struct {
  91205. struct FLAC__StreamEncoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  91206. struct FLAC__StreamEncoderPrivate *private_; /* avoid the C++ keyword 'private' */
  91207. } FLAC__StreamEncoder;
  91208. /** Signature for the read callback.
  91209. *
  91210. * A function pointer matching this signature must be passed to
  91211. * FLAC__stream_encoder_init_ogg_stream() if seeking is supported.
  91212. * The supplied function will be called when the encoder needs to read back
  91213. * encoded data. This happens during the metadata callback, when the encoder
  91214. * has to read, modify, and rewrite the metadata (e.g. seekpoints) gathered
  91215. * while encoding. The address of the buffer to be filled is supplied, along
  91216. * with the number of bytes the buffer can hold. The callback may choose to
  91217. * supply less data and modify the byte count but must be careful not to
  91218. * overflow the buffer. The callback then returns a status code chosen from
  91219. * FLAC__StreamEncoderReadStatus.
  91220. *
  91221. * Here is an example of a read callback for stdio streams:
  91222. * \code
  91223. * FLAC__StreamEncoderReadStatus read_cb(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  91224. * {
  91225. * FILE *file = ((MyClientData*)client_data)->file;
  91226. * if(*bytes > 0) {
  91227. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  91228. * if(ferror(file))
  91229. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  91230. * else if(*bytes == 0)
  91231. * return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  91232. * else
  91233. * return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  91234. * }
  91235. * else
  91236. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  91237. * }
  91238. * \endcode
  91239. *
  91240. * \note In general, FLAC__StreamEncoder functions which change the
  91241. * state should not be called on the \a encoder while in the callback.
  91242. *
  91243. * \param encoder The encoder instance calling the callback.
  91244. * \param buffer A pointer to a location for the callee to store
  91245. * data to be encoded.
  91246. * \param bytes A pointer to the size of the buffer. On entry
  91247. * to the callback, it contains the maximum number
  91248. * of bytes that may be stored in \a buffer. The
  91249. * callee must set it to the actual number of bytes
  91250. * stored (0 in case of error or end-of-stream) before
  91251. * returning.
  91252. * \param client_data The callee's client data set through
  91253. * FLAC__stream_encoder_set_client_data().
  91254. * \retval FLAC__StreamEncoderReadStatus
  91255. * The callee's return status.
  91256. */
  91257. typedef FLAC__StreamEncoderReadStatus (*FLAC__StreamEncoderReadCallback)(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  91258. /** Signature for the write callback.
  91259. *
  91260. * A function pointer matching this signature must be passed to
  91261. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91262. * by the encoder anytime there is raw encoded data ready to write. It may
  91263. * include metadata mixed with encoded audio frames and the data is not
  91264. * guaranteed to be aligned on frame or metadata block boundaries.
  91265. *
  91266. * The only duty of the callback is to write out the \a bytes worth of data
  91267. * in \a buffer to the current position in the output stream. The arguments
  91268. * \a samples and \a current_frame are purely informational. If \a samples
  91269. * is greater than \c 0, then \a current_frame will hold the current frame
  91270. * number that is being written; otherwise it indicates that the write
  91271. * callback is being called to write metadata.
  91272. *
  91273. * \note
  91274. * Unlike when writing to native FLAC, when writing to Ogg FLAC the
  91275. * write callback will be called twice when writing each audio
  91276. * frame; once for the page header, and once for the page body.
  91277. * When writing the page header, the \a samples argument to the
  91278. * write callback will be \c 0.
  91279. *
  91280. * \note In general, FLAC__StreamEncoder functions which change the
  91281. * state should not be called on the \a encoder while in the callback.
  91282. *
  91283. * \param encoder The encoder instance calling the callback.
  91284. * \param buffer An array of encoded data of length \a bytes.
  91285. * \param bytes The byte length of \a buffer.
  91286. * \param samples The number of samples encoded by \a buffer.
  91287. * \c 0 has a special meaning; see above.
  91288. * \param current_frame The number of the current frame being encoded.
  91289. * \param client_data The callee's client data set through
  91290. * FLAC__stream_encoder_init_*().
  91291. * \retval FLAC__StreamEncoderWriteStatus
  91292. * The callee's return status.
  91293. */
  91294. typedef FLAC__StreamEncoderWriteStatus (*FLAC__StreamEncoderWriteCallback)(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data);
  91295. /** Signature for the seek callback.
  91296. *
  91297. * A function pointer matching this signature may be passed to
  91298. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91299. * when the encoder needs to seek the output stream. The encoder will pass
  91300. * the absolute byte offset to seek to, 0 meaning the beginning of the stream.
  91301. *
  91302. * Here is an example of a seek callback for stdio streams:
  91303. * \code
  91304. * FLAC__StreamEncoderSeekStatus seek_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  91305. * {
  91306. * FILE *file = ((MyClientData*)client_data)->file;
  91307. * if(file == stdin)
  91308. * return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  91309. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  91310. * return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  91311. * else
  91312. * return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  91313. * }
  91314. * \endcode
  91315. *
  91316. * \note In general, FLAC__StreamEncoder functions which change the
  91317. * state should not be called on the \a encoder while in the callback.
  91318. *
  91319. * \param encoder The encoder instance calling the callback.
  91320. * \param absolute_byte_offset The offset from the beginning of the stream
  91321. * to seek to.
  91322. * \param client_data The callee's client data set through
  91323. * FLAC__stream_encoder_init_*().
  91324. * \retval FLAC__StreamEncoderSeekStatus
  91325. * The callee's return status.
  91326. */
  91327. typedef FLAC__StreamEncoderSeekStatus (*FLAC__StreamEncoderSeekCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  91328. /** Signature for the tell callback.
  91329. *
  91330. * A function pointer matching this signature may be passed to
  91331. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91332. * when the encoder needs to know the current position of the output stream.
  91333. *
  91334. * \warning
  91335. * The callback must return the true current byte offset of the output to
  91336. * which the encoder is writing. If you are buffering the output, make
  91337. * sure and take this into account. If you are writing directly to a
  91338. * FILE* from your write callback, ftell() is sufficient. If you are
  91339. * writing directly to a file descriptor from your write callback, you
  91340. * can use lseek(fd, SEEK_CUR, 0). The encoder may later seek back to
  91341. * these points to rewrite metadata after encoding.
  91342. *
  91343. * Here is an example of a tell callback for stdio streams:
  91344. * \code
  91345. * FLAC__StreamEncoderTellStatus tell_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  91346. * {
  91347. * FILE *file = ((MyClientData*)client_data)->file;
  91348. * off_t pos;
  91349. * if(file == stdin)
  91350. * return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  91351. * else if((pos = ftello(file)) < 0)
  91352. * return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  91353. * else {
  91354. * *absolute_byte_offset = (FLAC__uint64)pos;
  91355. * return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  91356. * }
  91357. * }
  91358. * \endcode
  91359. *
  91360. * \note In general, FLAC__StreamEncoder functions which change the
  91361. * state should not be called on the \a encoder while in the callback.
  91362. *
  91363. * \param encoder The encoder instance calling the callback.
  91364. * \param absolute_byte_offset The address at which to store the current
  91365. * position of the output.
  91366. * \param client_data The callee's client data set through
  91367. * FLAC__stream_encoder_init_*().
  91368. * \retval FLAC__StreamEncoderTellStatus
  91369. * The callee's return status.
  91370. */
  91371. typedef FLAC__StreamEncoderTellStatus (*FLAC__StreamEncoderTellCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  91372. /** Signature for the metadata callback.
  91373. *
  91374. * A function pointer matching this signature may be passed to
  91375. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91376. * once at the end of encoding with the populated STREAMINFO structure. This
  91377. * is so the client can seek back to the beginning of the file and write the
  91378. * STREAMINFO block with the correct statistics after encoding (like
  91379. * minimum/maximum frame size and total samples).
  91380. *
  91381. * \note In general, FLAC__StreamEncoder functions which change the
  91382. * state should not be called on the \a encoder while in the callback.
  91383. *
  91384. * \param encoder The encoder instance calling the callback.
  91385. * \param metadata The final populated STREAMINFO block.
  91386. * \param client_data The callee's client data set through
  91387. * FLAC__stream_encoder_init_*().
  91388. */
  91389. typedef void (*FLAC__StreamEncoderMetadataCallback)(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data);
  91390. /** Signature for the progress callback.
  91391. *
  91392. * A function pointer matching this signature may be passed to
  91393. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE().
  91394. * The supplied function will be called when the encoder has finished
  91395. * writing a frame. The \c total_frames_estimate argument to the
  91396. * callback will be based on the value from
  91397. * FLAC__stream_encoder_set_total_samples_estimate().
  91398. *
  91399. * \note In general, FLAC__StreamEncoder functions which change the
  91400. * state should not be called on the \a encoder while in the callback.
  91401. *
  91402. * \param encoder The encoder instance calling the callback.
  91403. * \param bytes_written Bytes written so far.
  91404. * \param samples_written Samples written so far.
  91405. * \param frames_written Frames written so far.
  91406. * \param total_frames_estimate The estimate of the total number of
  91407. * frames to be written.
  91408. * \param client_data The callee's client data set through
  91409. * FLAC__stream_encoder_init_*().
  91410. */
  91411. 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);
  91412. /***********************************************************************
  91413. *
  91414. * Class constructor/destructor
  91415. *
  91416. ***********************************************************************/
  91417. /** Create a new stream encoder instance. The instance is created with
  91418. * default settings; see the individual FLAC__stream_encoder_set_*()
  91419. * functions for each setting's default.
  91420. *
  91421. * \retval FLAC__StreamEncoder*
  91422. * \c NULL if there was an error allocating memory, else the new instance.
  91423. */
  91424. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void);
  91425. /** Free an encoder instance. Deletes the object pointed to by \a encoder.
  91426. *
  91427. * \param encoder A pointer to an existing encoder.
  91428. * \assert
  91429. * \code encoder != NULL \endcode
  91430. */
  91431. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder);
  91432. /***********************************************************************
  91433. *
  91434. * Public class method prototypes
  91435. *
  91436. ***********************************************************************/
  91437. /** Set the serial number for the FLAC stream to use in the Ogg container.
  91438. *
  91439. * \note
  91440. * This does not need to be set for native FLAC encoding.
  91441. *
  91442. * \note
  91443. * It is recommended to set a serial number explicitly as the default of '0'
  91444. * may collide with other streams.
  91445. *
  91446. * \default \c 0
  91447. * \param encoder An encoder instance to set.
  91448. * \param serial_number See above.
  91449. * \assert
  91450. * \code encoder != NULL \endcode
  91451. * \retval FLAC__bool
  91452. * \c false if the encoder is already initialized, else \c true.
  91453. */
  91454. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long serial_number);
  91455. /** Set the "verify" flag. If \c true, the encoder will verify it's own
  91456. * encoded output by feeding it through an internal decoder and comparing
  91457. * the original signal against the decoded signal. If a mismatch occurs,
  91458. * the process call will return \c false. Note that this will slow the
  91459. * encoding process by the extra time required for decoding and comparison.
  91460. *
  91461. * \default \c false
  91462. * \param encoder An encoder instance to set.
  91463. * \param value Flag value (see above).
  91464. * \assert
  91465. * \code encoder != NULL \endcode
  91466. * \retval FLAC__bool
  91467. * \c false if the encoder is already initialized, else \c true.
  91468. */
  91469. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91470. /** Set the <A HREF="../format.html#subset">Subset</A> flag. If \c true,
  91471. * the encoder will comply with the Subset and will check the
  91472. * settings during FLAC__stream_encoder_init_*() to see if all settings
  91473. * comply. If \c false, the settings may take advantage of the full
  91474. * range that the format allows.
  91475. *
  91476. * Make sure you know what it entails before setting this to \c false.
  91477. *
  91478. * \default \c true
  91479. * \param encoder An encoder instance to set.
  91480. * \param value Flag value (see above).
  91481. * \assert
  91482. * \code encoder != NULL \endcode
  91483. * \retval FLAC__bool
  91484. * \c false if the encoder is already initialized, else \c true.
  91485. */
  91486. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91487. /** Set the number of channels to be encoded.
  91488. *
  91489. * \default \c 2
  91490. * \param encoder An encoder instance to set.
  91491. * \param value See above.
  91492. * \assert
  91493. * \code encoder != NULL \endcode
  91494. * \retval FLAC__bool
  91495. * \c false if the encoder is already initialized, else \c true.
  91496. */
  91497. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value);
  91498. /** Set the sample resolution of the input to be encoded.
  91499. *
  91500. * \warning
  91501. * Do not feed the encoder data that is wider than the value you
  91502. * set here or you will generate an invalid stream.
  91503. *
  91504. * \default \c 16
  91505. * \param encoder An encoder instance to set.
  91506. * \param value See above.
  91507. * \assert
  91508. * \code encoder != NULL \endcode
  91509. * \retval FLAC__bool
  91510. * \c false if the encoder is already initialized, else \c true.
  91511. */
  91512. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value);
  91513. /** Set the sample rate (in Hz) of the input to be encoded.
  91514. *
  91515. * \default \c 44100
  91516. * \param encoder An encoder instance to set.
  91517. * \param value See above.
  91518. * \assert
  91519. * \code encoder != NULL \endcode
  91520. * \retval FLAC__bool
  91521. * \c false if the encoder is already initialized, else \c true.
  91522. */
  91523. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value);
  91524. /** Set the compression level
  91525. *
  91526. * The compression level is roughly proportional to the amount of effort
  91527. * the encoder expends to compress the file. A higher level usually
  91528. * means more computation but higher compression. The default level is
  91529. * suitable for most applications.
  91530. *
  91531. * Currently the levels range from \c 0 (fastest, least compression) to
  91532. * \c 8 (slowest, most compression). A value larger than \c 8 will be
  91533. * treated as \c 8.
  91534. *
  91535. * This function automatically calls the following other \c _set_
  91536. * functions with appropriate values, so the client does not need to
  91537. * unless it specifically wants to override them:
  91538. * - FLAC__stream_encoder_set_do_mid_side_stereo()
  91539. * - FLAC__stream_encoder_set_loose_mid_side_stereo()
  91540. * - FLAC__stream_encoder_set_apodization()
  91541. * - FLAC__stream_encoder_set_max_lpc_order()
  91542. * - FLAC__stream_encoder_set_qlp_coeff_precision()
  91543. * - FLAC__stream_encoder_set_do_qlp_coeff_prec_search()
  91544. * - FLAC__stream_encoder_set_do_escape_coding()
  91545. * - FLAC__stream_encoder_set_do_exhaustive_model_search()
  91546. * - FLAC__stream_encoder_set_min_residual_partition_order()
  91547. * - FLAC__stream_encoder_set_max_residual_partition_order()
  91548. * - FLAC__stream_encoder_set_rice_parameter_search_dist()
  91549. *
  91550. * The actual values set for each level are:
  91551. * <table>
  91552. * <tr>
  91553. * <td><b>level</b><td>
  91554. * <td>do mid-side stereo<td>
  91555. * <td>loose mid-side stereo<td>
  91556. * <td>apodization<td>
  91557. * <td>max lpc order<td>
  91558. * <td>qlp coeff precision<td>
  91559. * <td>qlp coeff prec search<td>
  91560. * <td>escape coding<td>
  91561. * <td>exhaustive model search<td>
  91562. * <td>min residual partition order<td>
  91563. * <td>max residual partition order<td>
  91564. * <td>rice parameter search dist<td>
  91565. * </tr>
  91566. * <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>
  91567. * <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>
  91568. * <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>
  91569. * <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>
  91570. * <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>
  91571. * <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>
  91572. * <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>
  91573. * <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>
  91574. * <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>
  91575. * </table>
  91576. *
  91577. * \default \c 5
  91578. * \param encoder An encoder instance to set.
  91579. * \param 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_compression_level(FLAC__StreamEncoder *encoder, unsigned value);
  91586. /** Set the blocksize to use while encoding.
  91587. *
  91588. * The number of samples to use per frame. Use \c 0 to let the encoder
  91589. * estimate a blocksize; this is usually best.
  91590. *
  91591. * \default \c 0
  91592. * \param encoder An encoder instance to set.
  91593. * \param value See above.
  91594. * \assert
  91595. * \code encoder != NULL \endcode
  91596. * \retval FLAC__bool
  91597. * \c false if the encoder is already initialized, else \c true.
  91598. */
  91599. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value);
  91600. /** Set to \c true to enable mid-side encoding on stereo input. The
  91601. * number of channels must be 2 for this to have any effect. Set to
  91602. * \c false to use only independent channel coding.
  91603. *
  91604. * \default \c false
  91605. * \param encoder An encoder instance to set.
  91606. * \param value Flag value (see above).
  91607. * \assert
  91608. * \code encoder != NULL \endcode
  91609. * \retval FLAC__bool
  91610. * \c false if the encoder is already initialized, else \c true.
  91611. */
  91612. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91613. /** Set to \c true to enable adaptive switching between mid-side and
  91614. * left-right encoding on stereo input. Set to \c false to use
  91615. * exhaustive searching. Setting this to \c true requires
  91616. * FLAC__stream_encoder_set_do_mid_side_stereo() to also be set to
  91617. * \c true in order to have any effect.
  91618. *
  91619. * \default \c false
  91620. * \param encoder An encoder instance to set.
  91621. * \param value Flag value (see above).
  91622. * \assert
  91623. * \code encoder != NULL \endcode
  91624. * \retval FLAC__bool
  91625. * \c false if the encoder is already initialized, else \c true.
  91626. */
  91627. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91628. /** Sets the apodization function(s) the encoder will use when windowing
  91629. * audio data for LPC analysis.
  91630. *
  91631. * The \a specification is a plain ASCII string which specifies exactly
  91632. * which functions to use. There may be more than one (up to 32),
  91633. * separated by \c ';' characters. Some functions take one or more
  91634. * comma-separated arguments in parentheses.
  91635. *
  91636. * The available functions are \c bartlett, \c bartlett_hann,
  91637. * \c blackman, \c blackman_harris_4term_92db, \c connes, \c flattop,
  91638. * \c gauss(STDDEV), \c hamming, \c hann, \c kaiser_bessel, \c nuttall,
  91639. * \c rectangle, \c triangle, \c tukey(P), \c welch.
  91640. *
  91641. * For \c gauss(STDDEV), STDDEV specifies the standard deviation
  91642. * (0<STDDEV<=0.5).
  91643. *
  91644. * For \c tukey(P), P specifies the fraction of the window that is
  91645. * tapered (0<=P<=1). P=0 corresponds to \c rectangle and P=1
  91646. * corresponds to \c hann.
  91647. *
  91648. * Example specifications are \c "blackman" or
  91649. * \c "hann;triangle;tukey(0.5);tukey(0.25);tukey(0.125)"
  91650. *
  91651. * Any function that is specified erroneously is silently dropped. Up
  91652. * to 32 functions are kept, the rest are dropped. If the specification
  91653. * is empty the encoder defaults to \c "tukey(0.5)".
  91654. *
  91655. * When more than one function is specified, then for every subframe the
  91656. * encoder will try each of them separately and choose the window that
  91657. * results in the smallest compressed subframe.
  91658. *
  91659. * Note that each function specified causes the encoder to occupy a
  91660. * floating point array in which to store the window.
  91661. *
  91662. * \default \c "tukey(0.5)"
  91663. * \param encoder An encoder instance to set.
  91664. * \param specification See above.
  91665. * \assert
  91666. * \code encoder != NULL \endcode
  91667. * \code specification != NULL \endcode
  91668. * \retval FLAC__bool
  91669. * \c false if the encoder is already initialized, else \c true.
  91670. */
  91671. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification);
  91672. /** Set the maximum LPC order, or \c 0 to use only the fixed predictors.
  91673. *
  91674. * \default \c 0
  91675. * \param encoder An encoder instance to set.
  91676. * \param value See above.
  91677. * \assert
  91678. * \code encoder != NULL \endcode
  91679. * \retval FLAC__bool
  91680. * \c false if the encoder is already initialized, else \c true.
  91681. */
  91682. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value);
  91683. /** Set the precision, in bits, of the quantized linear predictor
  91684. * coefficients, or \c 0 to let the encoder select it based on the
  91685. * blocksize.
  91686. *
  91687. * \note
  91688. * In the current implementation, qlp_coeff_precision + bits_per_sample must
  91689. * be less than 32.
  91690. *
  91691. * \default \c 0
  91692. * \param encoder An encoder instance to set.
  91693. * \param value See above.
  91694. * \assert
  91695. * \code encoder != NULL \endcode
  91696. * \retval FLAC__bool
  91697. * \c false if the encoder is already initialized, else \c true.
  91698. */
  91699. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value);
  91700. /** Set to \c false to use only the specified quantized linear predictor
  91701. * coefficient precision, or \c true to search neighboring precision
  91702. * values and use the best one.
  91703. *
  91704. * \default \c false
  91705. * \param encoder An encoder instance to set.
  91706. * \param value See above.
  91707. * \assert
  91708. * \code encoder != NULL \endcode
  91709. * \retval FLAC__bool
  91710. * \c false if the encoder is already initialized, else \c true.
  91711. */
  91712. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91713. /** Deprecated. Setting this value has no effect.
  91714. *
  91715. * \default \c false
  91716. * \param encoder An encoder instance to set.
  91717. * \param value See above.
  91718. * \assert
  91719. * \code encoder != NULL \endcode
  91720. * \retval FLAC__bool
  91721. * \c false if the encoder is already initialized, else \c true.
  91722. */
  91723. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91724. /** Set to \c false to let the encoder estimate the best model order
  91725. * based on the residual signal energy, or \c true to force the
  91726. * encoder to evaluate all order models and select the best.
  91727. *
  91728. * \default \c false
  91729. * \param encoder An encoder instance to set.
  91730. * \param value See above.
  91731. * \assert
  91732. * \code encoder != NULL \endcode
  91733. * \retval FLAC__bool
  91734. * \c false if the encoder is already initialized, else \c true.
  91735. */
  91736. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91737. /** Set the minimum partition order to search when coding the residual.
  91738. * This is used in tandem with
  91739. * FLAC__stream_encoder_set_max_residual_partition_order().
  91740. *
  91741. * The partition order determines the context size in the residual.
  91742. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  91743. *
  91744. * Set both min and max values to \c 0 to force a single context,
  91745. * whose Rice parameter is based on the residual signal variance.
  91746. * Otherwise, set a min and max order, and the encoder will search
  91747. * all orders, using the mean of each context for its Rice parameter,
  91748. * and use the best.
  91749. *
  91750. * \default \c 0
  91751. * \param encoder An encoder instance to set.
  91752. * \param value See above.
  91753. * \assert
  91754. * \code encoder != NULL \endcode
  91755. * \retval FLAC__bool
  91756. * \c false if the encoder is already initialized, else \c true.
  91757. */
  91758. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  91759. /** Set the maximum partition order to search when coding the residual.
  91760. * This is used in tandem with
  91761. * FLAC__stream_encoder_set_min_residual_partition_order().
  91762. *
  91763. * The partition order determines the context size in the residual.
  91764. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  91765. *
  91766. * Set both min and max values to \c 0 to force a single context,
  91767. * whose Rice parameter is based on the residual signal variance.
  91768. * Otherwise, set a min and max order, and the encoder will search
  91769. * all orders, using the mean of each context for its Rice parameter,
  91770. * and use the best.
  91771. *
  91772. * \default \c 0
  91773. * \param encoder An encoder instance to set.
  91774. * \param value See above.
  91775. * \assert
  91776. * \code encoder != NULL \endcode
  91777. * \retval FLAC__bool
  91778. * \c false if the encoder is already initialized, else \c true.
  91779. */
  91780. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  91781. /** Deprecated. Setting this value has no effect.
  91782. *
  91783. * \default \c 0
  91784. * \param encoder An encoder instance to set.
  91785. * \param value See above.
  91786. * \assert
  91787. * \code encoder != NULL \endcode
  91788. * \retval FLAC__bool
  91789. * \c false if the encoder is already initialized, else \c true.
  91790. */
  91791. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value);
  91792. /** Set an estimate of the total samples that will be encoded.
  91793. * This is merely an estimate and may be set to \c 0 if unknown.
  91794. * This value will be written to the STREAMINFO block before encoding,
  91795. * and can remove the need for the caller to rewrite the value later
  91796. * if the value is known before encoding.
  91797. *
  91798. * \default \c 0
  91799. * \param encoder An encoder instance to set.
  91800. * \param value See above.
  91801. * \assert
  91802. * \code encoder != NULL \endcode
  91803. * \retval FLAC__bool
  91804. * \c false if the encoder is already initialized, else \c true.
  91805. */
  91806. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value);
  91807. /** Set the metadata blocks to be emitted to the stream before encoding.
  91808. * A value of \c NULL, \c 0 implies no metadata; otherwise, supply an
  91809. * array of pointers to metadata blocks. The array is non-const since
  91810. * the encoder may need to change the \a is_last flag inside them, and
  91811. * in some cases update seek point offsets. Otherwise, the encoder will
  91812. * not modify or free the blocks. It is up to the caller to free the
  91813. * metadata blocks after encoding finishes.
  91814. *
  91815. * \note
  91816. * The encoder stores only copies of the pointers in the \a metadata array;
  91817. * the metadata blocks themselves must survive at least until after
  91818. * FLAC__stream_encoder_finish() returns. Do not free the blocks until then.
  91819. *
  91820. * \note
  91821. * The STREAMINFO block is always written and no STREAMINFO block may
  91822. * occur in the supplied array.
  91823. *
  91824. * \note
  91825. * By default the encoder does not create a SEEKTABLE. If one is supplied
  91826. * in the \a metadata array, but the client has specified that it does not
  91827. * support seeking, then the SEEKTABLE will be written verbatim. However
  91828. * by itself this is not very useful as the client will not know the stream
  91829. * offsets for the seekpoints ahead of time. In order to get a proper
  91830. * seektable the client must support seeking. See next note.
  91831. *
  91832. * \note
  91833. * SEEKTABLE blocks are handled specially. Since you will not know
  91834. * the values for the seek point stream offsets, you should pass in
  91835. * a SEEKTABLE 'template', that is, a SEEKTABLE object with the
  91836. * required sample numbers (or placeholder points), with \c 0 for the
  91837. * \a frame_samples and \a stream_offset fields for each point. If the
  91838. * client has specified that it supports seeking by providing a seek
  91839. * callback to FLAC__stream_encoder_init_stream() or both seek AND read
  91840. * callback to FLAC__stream_encoder_init_ogg_stream() (or by using
  91841. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE()),
  91842. * then while it is encoding the encoder will fill the stream offsets in
  91843. * for you and when encoding is finished, it will seek back and write the
  91844. * real values into the SEEKTABLE block in the stream. There are helper
  91845. * routines for manipulating seektable template blocks; see metadata.h:
  91846. * FLAC__metadata_object_seektable_template_*(). If the client does
  91847. * not support seeking, the SEEKTABLE will have inaccurate offsets which
  91848. * will slow down or remove the ability to seek in the FLAC stream.
  91849. *
  91850. * \note
  91851. * The encoder instance \b will modify the first \c SEEKTABLE block
  91852. * as it transforms the template to a valid seektable while encoding,
  91853. * but it is still up to the caller to free all metadata blocks after
  91854. * encoding.
  91855. *
  91856. * \note
  91857. * A VORBIS_COMMENT block may be supplied. The vendor string in it
  91858. * will be ignored. libFLAC will use it's own vendor string. libFLAC
  91859. * will not modify the passed-in VORBIS_COMMENT's vendor string, it
  91860. * will simply write it's own into the stream. If no VORBIS_COMMENT
  91861. * block is present in the \a metadata array, libFLAC will write an
  91862. * empty one, containing only the vendor string.
  91863. *
  91864. * \note The Ogg FLAC mapping requires that the VORBIS_COMMENT block be
  91865. * the second metadata block of the stream. The encoder already supplies
  91866. * the STREAMINFO block automatically. If \a metadata does not contain a
  91867. * VORBIS_COMMENT block, the encoder will supply that too. Otherwise, if
  91868. * \a metadata does contain a VORBIS_COMMENT block and it is not the
  91869. * first, the init function will reorder \a metadata by moving the
  91870. * VORBIS_COMMENT block to the front; the relative ordering of the other
  91871. * blocks will remain as they were.
  91872. *
  91873. * \note The Ogg FLAC mapping limits the number of metadata blocks per
  91874. * stream to \c 65535. If \a num_blocks exceeds this the function will
  91875. * return \c false.
  91876. *
  91877. * \default \c NULL, 0
  91878. * \param encoder An encoder instance to set.
  91879. * \param metadata See above.
  91880. * \param num_blocks See above.
  91881. * \assert
  91882. * \code encoder != NULL \endcode
  91883. * \retval FLAC__bool
  91884. * \c false if the encoder is already initialized, else \c true.
  91885. * \c false if the encoder is already initialized, or if
  91886. * \a num_blocks > 65535 if encoding to Ogg FLAC, else \c true.
  91887. */
  91888. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks);
  91889. /** Get the current encoder state.
  91890. *
  91891. * \param encoder An encoder instance to query.
  91892. * \assert
  91893. * \code encoder != NULL \endcode
  91894. * \retval FLAC__StreamEncoderState
  91895. * The current encoder state.
  91896. */
  91897. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder);
  91898. /** Get the state of the verify stream decoder.
  91899. * Useful when the stream encoder state is
  91900. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR.
  91901. *
  91902. * \param encoder An encoder instance to query.
  91903. * \assert
  91904. * \code encoder != NULL \endcode
  91905. * \retval FLAC__StreamDecoderState
  91906. * The verify stream decoder state.
  91907. */
  91908. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder);
  91909. /** Get the current encoder state as a C string.
  91910. * This version automatically resolves
  91911. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR by getting the
  91912. * verify decoder's state.
  91913. *
  91914. * \param encoder A encoder instance to query.
  91915. * \assert
  91916. * \code encoder != NULL \endcode
  91917. * \retval const char *
  91918. * The encoder state as a C string. Do not modify the contents.
  91919. */
  91920. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder);
  91921. /** Get relevant values about the nature of a verify decoder error.
  91922. * Useful when the stream encoder state is
  91923. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR. The arguments should
  91924. * be addresses in which the stats will be returned, or NULL if value
  91925. * is not desired.
  91926. *
  91927. * \param encoder An encoder instance to query.
  91928. * \param absolute_sample The absolute sample number of the mismatch.
  91929. * \param frame_number The number of the frame in which the mismatch occurred.
  91930. * \param channel The channel in which the mismatch occurred.
  91931. * \param sample The number of the sample (relative to the frame) in
  91932. * which the mismatch occurred.
  91933. * \param expected The expected value for the sample in question.
  91934. * \param got The actual value returned by the decoder.
  91935. * \assert
  91936. * \code encoder != NULL \endcode
  91937. */
  91938. 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);
  91939. /** Get the "verify" flag.
  91940. *
  91941. * \param encoder An encoder instance to query.
  91942. * \assert
  91943. * \code encoder != NULL \endcode
  91944. * \retval FLAC__bool
  91945. * See FLAC__stream_encoder_set_verify().
  91946. */
  91947. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder);
  91948. /** Get the <A HREF="../format.html#subset>Subset</A> flag.
  91949. *
  91950. * \param encoder An encoder instance to query.
  91951. * \assert
  91952. * \code encoder != NULL \endcode
  91953. * \retval FLAC__bool
  91954. * See FLAC__stream_encoder_set_streamable_subset().
  91955. */
  91956. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder);
  91957. /** Get the number of input channels being processed.
  91958. *
  91959. * \param encoder An encoder instance to query.
  91960. * \assert
  91961. * \code encoder != NULL \endcode
  91962. * \retval unsigned
  91963. * See FLAC__stream_encoder_set_channels().
  91964. */
  91965. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder);
  91966. /** Get the input sample resolution setting.
  91967. *
  91968. * \param encoder An encoder instance to query.
  91969. * \assert
  91970. * \code encoder != NULL \endcode
  91971. * \retval unsigned
  91972. * See FLAC__stream_encoder_set_bits_per_sample().
  91973. */
  91974. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder);
  91975. /** Get the input sample rate setting.
  91976. *
  91977. * \param encoder An encoder instance to query.
  91978. * \assert
  91979. * \code encoder != NULL \endcode
  91980. * \retval unsigned
  91981. * See FLAC__stream_encoder_set_sample_rate().
  91982. */
  91983. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder);
  91984. /** Get the blocksize setting.
  91985. *
  91986. * \param encoder An encoder instance to query.
  91987. * \assert
  91988. * \code encoder != NULL \endcode
  91989. * \retval unsigned
  91990. * See FLAC__stream_encoder_set_blocksize().
  91991. */
  91992. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder);
  91993. /** Get the "mid/side stereo coding" flag.
  91994. *
  91995. * \param encoder An encoder instance to query.
  91996. * \assert
  91997. * \code encoder != NULL \endcode
  91998. * \retval FLAC__bool
  91999. * See FLAC__stream_encoder_get_do_mid_side_stereo().
  92000. */
  92001. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  92002. /** Get the "adaptive mid/side switching" flag.
  92003. *
  92004. * \param encoder An encoder instance to query.
  92005. * \assert
  92006. * \code encoder != NULL \endcode
  92007. * \retval FLAC__bool
  92008. * See FLAC__stream_encoder_set_loose_mid_side_stereo().
  92009. */
  92010. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  92011. /** Get the maximum LPC order setting.
  92012. *
  92013. * \param encoder An encoder instance to query.
  92014. * \assert
  92015. * \code encoder != NULL \endcode
  92016. * \retval unsigned
  92017. * See FLAC__stream_encoder_set_max_lpc_order().
  92018. */
  92019. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder);
  92020. /** Get the quantized linear predictor coefficient precision setting.
  92021. *
  92022. * \param encoder An encoder instance to query.
  92023. * \assert
  92024. * \code encoder != NULL \endcode
  92025. * \retval unsigned
  92026. * See FLAC__stream_encoder_set_qlp_coeff_precision().
  92027. */
  92028. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder);
  92029. /** Get the qlp coefficient precision search flag.
  92030. *
  92031. * \param encoder An encoder instance to query.
  92032. * \assert
  92033. * \code encoder != NULL \endcode
  92034. * \retval FLAC__bool
  92035. * See FLAC__stream_encoder_set_do_qlp_coeff_prec_search().
  92036. */
  92037. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder);
  92038. /** Get the "escape coding" flag.
  92039. *
  92040. * \param encoder An encoder instance to query.
  92041. * \assert
  92042. * \code encoder != NULL \endcode
  92043. * \retval FLAC__bool
  92044. * See FLAC__stream_encoder_set_do_escape_coding().
  92045. */
  92046. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder);
  92047. /** Get the exhaustive model search flag.
  92048. *
  92049. * \param encoder An encoder instance to query.
  92050. * \assert
  92051. * \code encoder != NULL \endcode
  92052. * \retval FLAC__bool
  92053. * See FLAC__stream_encoder_set_do_exhaustive_model_search().
  92054. */
  92055. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder);
  92056. /** Get the minimum residual partition order setting.
  92057. *
  92058. * \param encoder An encoder instance to query.
  92059. * \assert
  92060. * \code encoder != NULL \endcode
  92061. * \retval unsigned
  92062. * See FLAC__stream_encoder_set_min_residual_partition_order().
  92063. */
  92064. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder);
  92065. /** Get maximum residual partition order setting.
  92066. *
  92067. * \param encoder An encoder instance to query.
  92068. * \assert
  92069. * \code encoder != NULL \endcode
  92070. * \retval unsigned
  92071. * See FLAC__stream_encoder_set_max_residual_partition_order().
  92072. */
  92073. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder);
  92074. /** Get the Rice parameter search distance setting.
  92075. *
  92076. * \param encoder An encoder instance to query.
  92077. * \assert
  92078. * \code encoder != NULL \endcode
  92079. * \retval unsigned
  92080. * See FLAC__stream_encoder_set_rice_parameter_search_dist().
  92081. */
  92082. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder);
  92083. /** Get the previously set estimate of the total samples to be encoded.
  92084. * The encoder merely mimics back the value given to
  92085. * FLAC__stream_encoder_set_total_samples_estimate() since it has no
  92086. * other way of knowing how many samples the client will encode.
  92087. *
  92088. * \param encoder An encoder instance to set.
  92089. * \assert
  92090. * \code encoder != NULL \endcode
  92091. * \retval FLAC__uint64
  92092. * See FLAC__stream_encoder_get_total_samples_estimate().
  92093. */
  92094. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder);
  92095. /** Initialize the encoder instance to encode native FLAC streams.
  92096. *
  92097. * This flavor of initialization sets up the encoder to encode to a
  92098. * native FLAC stream. I/O is performed via callbacks to the client.
  92099. * For encoding to a plain file via filename or open \c FILE*,
  92100. * FLAC__stream_encoder_init_file() and FLAC__stream_encoder_init_FILE()
  92101. * provide a simpler interface.
  92102. *
  92103. * This function should be called after FLAC__stream_encoder_new() and
  92104. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92105. * or FLAC__stream_encoder_process_interleaved().
  92106. * initialization succeeded.
  92107. *
  92108. * The call to FLAC__stream_encoder_init_stream() currently will also
  92109. * immediately call the write callback several times, once with the \c fLaC
  92110. * signature, and once for each encoded metadata block.
  92111. *
  92112. * \param encoder An uninitialized encoder instance.
  92113. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  92114. * pointer must not be \c NULL.
  92115. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  92116. * pointer may be \c NULL if seeking is not
  92117. * supported. The encoder uses seeking to go back
  92118. * and write some some stream statistics to the
  92119. * STREAMINFO block; this is recommended but not
  92120. * necessary to create a valid FLAC stream. If
  92121. * \a seek_callback is not \c NULL then a
  92122. * \a tell_callback must also be supplied.
  92123. * Alternatively, a dummy seek callback that just
  92124. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  92125. * may also be supplied, all though this is slightly
  92126. * less efficient for the encoder.
  92127. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  92128. * pointer may be \c NULL if seeking is not
  92129. * supported. If \a seek_callback is \c NULL then
  92130. * this argument will be ignored. If
  92131. * \a seek_callback is not \c NULL then a
  92132. * \a tell_callback must also be supplied.
  92133. * Alternatively, a dummy tell callback that just
  92134. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  92135. * may also be supplied, all though this is slightly
  92136. * less efficient for the encoder.
  92137. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  92138. * pointer may be \c NULL if the callback is not
  92139. * desired. If the client provides a seek callback,
  92140. * this function is not necessary as the encoder
  92141. * will automatically seek back and update the
  92142. * STREAMINFO block. It may also be \c NULL if the
  92143. * client does not support seeking, since it will
  92144. * have no way of going back to update the
  92145. * STREAMINFO. However the client can still supply
  92146. * a callback if it would like to know the details
  92147. * from the STREAMINFO.
  92148. * \param client_data This value will be supplied to callbacks in their
  92149. * \a client_data argument.
  92150. * \assert
  92151. * \code encoder != NULL \endcode
  92152. * \retval FLAC__StreamEncoderInitStatus
  92153. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92154. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92155. */
  92156. 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);
  92157. /** Initialize the encoder instance to encode Ogg FLAC streams.
  92158. *
  92159. * This flavor of initialization sets up the encoder to encode to a FLAC
  92160. * stream in an Ogg container. I/O is performed via callbacks to the
  92161. * client. For encoding to a plain file via filename or open \c FILE*,
  92162. * FLAC__stream_encoder_init_ogg_file() and FLAC__stream_encoder_init_ogg_FILE()
  92163. * provide a simpler interface.
  92164. *
  92165. * This function should be called after FLAC__stream_encoder_new() and
  92166. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92167. * or FLAC__stream_encoder_process_interleaved().
  92168. * initialization succeeded.
  92169. *
  92170. * The call to FLAC__stream_encoder_init_ogg_stream() currently will also
  92171. * immediately call the write callback several times to write the metadata
  92172. * packets.
  92173. *
  92174. * \param encoder An uninitialized encoder instance.
  92175. * \param read_callback See FLAC__StreamEncoderReadCallback. This
  92176. * pointer must not be \c NULL if \a seek_callback
  92177. * is non-NULL since they are both needed to be
  92178. * able to write data back to the Ogg FLAC stream
  92179. * in the post-encode phase.
  92180. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  92181. * pointer must not be \c NULL.
  92182. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  92183. * pointer may be \c NULL if seeking is not
  92184. * supported. The encoder uses seeking to go back
  92185. * and write some some stream statistics to the
  92186. * STREAMINFO block; this is recommended but not
  92187. * necessary to create a valid FLAC stream. If
  92188. * \a seek_callback is not \c NULL then a
  92189. * \a tell_callback must also be supplied.
  92190. * Alternatively, a dummy seek callback that just
  92191. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  92192. * may also be supplied, all though this is slightly
  92193. * less efficient for the encoder.
  92194. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  92195. * pointer may be \c NULL if seeking is not
  92196. * supported. If \a seek_callback is \c NULL then
  92197. * this argument will be ignored. If
  92198. * \a seek_callback is not \c NULL then a
  92199. * \a tell_callback must also be supplied.
  92200. * Alternatively, a dummy tell callback that just
  92201. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  92202. * may also be supplied, all though this is slightly
  92203. * less efficient for the encoder.
  92204. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  92205. * pointer may be \c NULL if the callback is not
  92206. * desired. If the client provides a seek callback,
  92207. * this function is not necessary as the encoder
  92208. * will automatically seek back and update the
  92209. * STREAMINFO block. It may also be \c NULL if the
  92210. * client does not support seeking, since it will
  92211. * have no way of going back to update the
  92212. * STREAMINFO. However the client can still supply
  92213. * a callback if it would like to know the details
  92214. * from the STREAMINFO.
  92215. * \param client_data This value will be supplied to callbacks in their
  92216. * \a client_data argument.
  92217. * \assert
  92218. * \code encoder != NULL \endcode
  92219. * \retval FLAC__StreamEncoderInitStatus
  92220. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92221. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92222. */
  92223. 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);
  92224. /** Initialize the encoder instance to encode native FLAC files.
  92225. *
  92226. * This flavor of initialization sets up the encoder to encode to a
  92227. * plain native FLAC file. For non-stdio streams, you must use
  92228. * FLAC__stream_encoder_init_stream() and provide callbacks for the I/O.
  92229. *
  92230. * This function should be called after FLAC__stream_encoder_new() and
  92231. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92232. * or FLAC__stream_encoder_process_interleaved().
  92233. * initialization succeeded.
  92234. *
  92235. * \param encoder An uninitialized encoder instance.
  92236. * \param file An open file. The file should have been opened
  92237. * with mode \c "w+b" and rewound. The file
  92238. * becomes owned by the encoder and should not be
  92239. * manipulated by the client while encoding.
  92240. * Unless \a file is \c stdout, it will be closed
  92241. * when FLAC__stream_encoder_finish() is called.
  92242. * Note however that a proper SEEKTABLE cannot be
  92243. * created when encoding to \c stdout since it is
  92244. * not seekable.
  92245. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92246. * pointer may be \c NULL if the callback is not
  92247. * desired.
  92248. * \param client_data This value will be supplied to callbacks in their
  92249. * \a client_data argument.
  92250. * \assert
  92251. * \code encoder != NULL \endcode
  92252. * \code file != NULL \endcode
  92253. * \retval FLAC__StreamEncoderInitStatus
  92254. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92255. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92256. */
  92257. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92258. /** Initialize the encoder instance to encode Ogg FLAC files.
  92259. *
  92260. * This flavor of initialization sets up the encoder to encode to a
  92261. * plain Ogg FLAC file. For non-stdio streams, you must use
  92262. * FLAC__stream_encoder_init_ogg_stream() and provide callbacks for the I/O.
  92263. *
  92264. * This function should be called after FLAC__stream_encoder_new() and
  92265. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92266. * or FLAC__stream_encoder_process_interleaved().
  92267. * initialization succeeded.
  92268. *
  92269. * \param encoder An uninitialized encoder instance.
  92270. * \param file An open file. The file should have been opened
  92271. * with mode \c "w+b" and rewound. The file
  92272. * becomes owned by the encoder and should not be
  92273. * manipulated by the client while encoding.
  92274. * Unless \a file is \c stdout, it will be closed
  92275. * when FLAC__stream_encoder_finish() is called.
  92276. * Note however that a proper SEEKTABLE cannot be
  92277. * created when encoding to \c stdout since it is
  92278. * not seekable.
  92279. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92280. * pointer may be \c NULL if the callback is not
  92281. * desired.
  92282. * \param client_data This value will be supplied to callbacks in their
  92283. * \a client_data argument.
  92284. * \assert
  92285. * \code encoder != NULL \endcode
  92286. * \code file != NULL \endcode
  92287. * \retval FLAC__StreamEncoderInitStatus
  92288. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92289. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92290. */
  92291. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92292. /** Initialize the encoder instance to encode native FLAC files.
  92293. *
  92294. * This flavor of initialization sets up the encoder to encode to a plain
  92295. * FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  92296. * with Unicode filenames on Windows), you must use
  92297. * FLAC__stream_encoder_init_FILE(), or FLAC__stream_encoder_init_stream()
  92298. * and provide callbacks for the I/O.
  92299. *
  92300. * This function should be called after FLAC__stream_encoder_new() and
  92301. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92302. * or FLAC__stream_encoder_process_interleaved().
  92303. * initialization succeeded.
  92304. *
  92305. * \param encoder An uninitialized encoder instance.
  92306. * \param filename The name of the file to encode to. The file will
  92307. * be opened with fopen(). Use \c NULL to encode to
  92308. * \c stdout. Note however that a proper SEEKTABLE
  92309. * cannot be created when encoding to \c stdout since
  92310. * it is not seekable.
  92311. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92312. * pointer may be \c NULL if the callback is not
  92313. * desired.
  92314. * \param client_data This value will be supplied to callbacks in their
  92315. * \a client_data argument.
  92316. * \assert
  92317. * \code encoder != NULL \endcode
  92318. * \retval FLAC__StreamEncoderInitStatus
  92319. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92320. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92321. */
  92322. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92323. /** Initialize the encoder instance to encode Ogg FLAC files.
  92324. *
  92325. * This flavor of initialization sets up the encoder to encode to a plain
  92326. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  92327. * with Unicode filenames on Windows), you must use
  92328. * FLAC__stream_encoder_init_ogg_FILE(), or FLAC__stream_encoder_init_ogg_stream()
  92329. * and provide callbacks for the I/O.
  92330. *
  92331. * This function should be called after FLAC__stream_encoder_new() and
  92332. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92333. * or FLAC__stream_encoder_process_interleaved().
  92334. * initialization succeeded.
  92335. *
  92336. * \param encoder An uninitialized encoder instance.
  92337. * \param filename The name of the file to encode to. The file will
  92338. * be opened with fopen(). Use \c NULL to encode to
  92339. * \c stdout. Note however that a proper SEEKTABLE
  92340. * cannot be created when encoding to \c stdout since
  92341. * it is not seekable.
  92342. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92343. * pointer may be \c NULL if the callback is not
  92344. * desired.
  92345. * \param client_data This value will be supplied to callbacks in their
  92346. * \a client_data argument.
  92347. * \assert
  92348. * \code encoder != NULL \endcode
  92349. * \retval FLAC__StreamEncoderInitStatus
  92350. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92351. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92352. */
  92353. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92354. /** Finish the encoding process.
  92355. * Flushes the encoding buffer, releases resources, resets the encoder
  92356. * settings to their defaults, and returns the encoder state to
  92357. * FLAC__STREAM_ENCODER_UNINITIALIZED. Note that this can generate
  92358. * one or more write callbacks before returning, and will generate
  92359. * a metadata callback.
  92360. *
  92361. * Note that in the course of processing the last frame, errors can
  92362. * occur, so the caller should be sure to check the return value to
  92363. * ensure the file was encoded properly.
  92364. *
  92365. * In the event of a prematurely-terminated encode, it is not strictly
  92366. * necessary to call this immediately before FLAC__stream_encoder_delete()
  92367. * but it is good practice to match every FLAC__stream_encoder_init_*()
  92368. * with a FLAC__stream_encoder_finish().
  92369. *
  92370. * \param encoder An uninitialized encoder instance.
  92371. * \assert
  92372. * \code encoder != NULL \endcode
  92373. * \retval FLAC__bool
  92374. * \c false if an error occurred processing the last frame; or if verify
  92375. * mode is set (see FLAC__stream_encoder_set_verify()), there was a
  92376. * verify mismatch; else \c true. If \c false, caller should check the
  92377. * state with FLAC__stream_encoder_get_state() for more information
  92378. * about the error.
  92379. */
  92380. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder);
  92381. /** Submit data for encoding.
  92382. * This version allows you to supply the input data via an array of
  92383. * pointers, each pointer pointing to an array of \a samples samples
  92384. * representing one channel. The samples need not be block-aligned,
  92385. * but each channel should have the same number of samples. Each sample
  92386. * should be a signed integer, right-justified to the resolution set by
  92387. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  92388. * resolution is 16 bits per sample, the samples should all be in the
  92389. * range [-32768,32767].
  92390. *
  92391. * For applications where channel order is important, channels must
  92392. * follow the order as described in the
  92393. * <A HREF="../format.html#frame_header">frame header</A>.
  92394. *
  92395. * \param encoder An initialized encoder instance in the OK state.
  92396. * \param buffer An array of pointers to each channel's signal.
  92397. * \param samples The number of samples in one channel.
  92398. * \assert
  92399. * \code encoder != NULL \endcode
  92400. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  92401. * \retval FLAC__bool
  92402. * \c true if successful, else \c false; in this case, check the
  92403. * encoder state with FLAC__stream_encoder_get_state() to see what
  92404. * went wrong.
  92405. */
  92406. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples);
  92407. /** Submit data for encoding.
  92408. * This version allows you to supply the input data where the channels
  92409. * are interleaved into a single array (i.e. channel0_sample0,
  92410. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  92411. * The samples need not be block-aligned but they must be
  92412. * sample-aligned, i.e. the first value should be channel0_sample0
  92413. * and the last value channelN_sampleM. Each sample should be a signed
  92414. * integer, right-justified to the resolution set by
  92415. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  92416. * resolution is 16 bits per sample, the samples should all be in the
  92417. * range [-32768,32767].
  92418. *
  92419. * For applications where channel order is important, channels must
  92420. * follow the order as described in the
  92421. * <A HREF="../format.html#frame_header">frame header</A>.
  92422. *
  92423. * \param encoder An initialized encoder instance in the OK state.
  92424. * \param buffer An array of channel-interleaved data (see above).
  92425. * \param samples The number of samples in one channel, the same as for
  92426. * FLAC__stream_encoder_process(). For example, if
  92427. * encoding two channels, \c 1000 \a samples corresponds
  92428. * to a \a buffer of 2000 values.
  92429. * \assert
  92430. * \code encoder != NULL \endcode
  92431. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  92432. * \retval FLAC__bool
  92433. * \c true if successful, else \c false; in this case, check the
  92434. * encoder state with FLAC__stream_encoder_get_state() to see what
  92435. * went wrong.
  92436. */
  92437. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples);
  92438. /* \} */
  92439. #ifdef __cplusplus
  92440. }
  92441. #endif
  92442. #endif
  92443. /*** End of inlined file: stream_encoder.h ***/
  92444. #ifdef _MSC_VER
  92445. /* OPT: an MSVC built-in would be better */
  92446. static _inline FLAC__uint32 local_swap32_(FLAC__uint32 x)
  92447. {
  92448. x = ((x<<8)&0xFF00FF00) | ((x>>8)&0x00FF00FF);
  92449. return (x>>16) | (x<<16);
  92450. }
  92451. #endif
  92452. #if defined(_MSC_VER) && defined(_X86_)
  92453. /* OPT: an MSVC built-in would be better */
  92454. static void local_swap32_block_(FLAC__uint32 *start, FLAC__uint32 len)
  92455. {
  92456. __asm {
  92457. mov edx, start
  92458. mov ecx, len
  92459. test ecx, ecx
  92460. loop1:
  92461. jz done1
  92462. mov eax, [edx]
  92463. bswap eax
  92464. mov [edx], eax
  92465. add edx, 4
  92466. dec ecx
  92467. jmp short loop1
  92468. done1:
  92469. }
  92470. }
  92471. #endif
  92472. /** \mainpage
  92473. *
  92474. * \section intro Introduction
  92475. *
  92476. * This is the documentation for the FLAC C and C++ APIs. It is
  92477. * highly interconnected; this introduction should give you a top
  92478. * level idea of the structure and how to find the information you
  92479. * need. As a prerequisite you should have at least a basic
  92480. * knowledge of the FLAC format, documented
  92481. * <A HREF="../format.html">here</A>.
  92482. *
  92483. * \section c_api FLAC C API
  92484. *
  92485. * The FLAC C API is the interface to libFLAC, a set of structures
  92486. * describing the components of FLAC streams, and functions for
  92487. * encoding and decoding streams, as well as manipulating FLAC
  92488. * metadata in files. The public include files will be installed
  92489. * in your include area (for example /usr/include/FLAC/...).
  92490. *
  92491. * By writing a little code and linking against libFLAC, it is
  92492. * relatively easy to add FLAC support to another program. The
  92493. * library is licensed under <A HREF="../license.html">Xiph's BSD license</A>.
  92494. * Complete source code of libFLAC as well as the command-line
  92495. * encoder and plugins is available and is a useful source of
  92496. * examples.
  92497. *
  92498. * Aside from encoders and decoders, libFLAC provides a powerful
  92499. * metadata interface for manipulating metadata in FLAC files. It
  92500. * allows the user to add, delete, and modify FLAC metadata blocks
  92501. * and it can automatically take advantage of PADDING blocks to avoid
  92502. * rewriting the entire FLAC file when changing the size of the
  92503. * metadata.
  92504. *
  92505. * libFLAC usually only requires the standard C library and C math
  92506. * library. In particular, threading is not used so there is no
  92507. * dependency on a thread library. However, libFLAC does not use
  92508. * global variables and should be thread-safe.
  92509. *
  92510. * libFLAC also supports encoding to and decoding from Ogg FLAC.
  92511. * However the metadata editing interfaces currently have limited
  92512. * read-only support for Ogg FLAC files.
  92513. *
  92514. * \section cpp_api FLAC C++ API
  92515. *
  92516. * The FLAC C++ API is a set of classes that encapsulate the
  92517. * structures and functions in libFLAC. They provide slightly more
  92518. * functionality with respect to metadata but are otherwise
  92519. * equivalent. For the most part, they share the same usage as
  92520. * their counterparts in libFLAC, and the FLAC C API documentation
  92521. * can be used as a supplement. The public include files
  92522. * for the C++ API will be installed in your include area (for
  92523. * example /usr/include/FLAC++/...).
  92524. *
  92525. * libFLAC++ is also licensed under
  92526. * <A HREF="../license.html">Xiph's BSD license</A>.
  92527. *
  92528. * \section getting_started Getting Started
  92529. *
  92530. * A good starting point for learning the API is to browse through
  92531. * the <A HREF="modules.html">modules</A>. Modules are logical
  92532. * groupings of related functions or classes, which correspond roughly
  92533. * to header files or sections of header files. Each module includes a
  92534. * detailed description of the general usage of its functions or
  92535. * classes.
  92536. *
  92537. * From there you can go on to look at the documentation of
  92538. * individual functions. You can see different views of the individual
  92539. * functions through the links in top bar across this page.
  92540. *
  92541. * If you prefer a more hands-on approach, you can jump right to some
  92542. * <A HREF="../documentation_example_code.html">example code</A>.
  92543. *
  92544. * \section porting_guide Porting Guide
  92545. *
  92546. * Starting with FLAC 1.1.3 a \link porting Porting Guide \endlink
  92547. * has been introduced which gives detailed instructions on how to
  92548. * port your code to newer versions of FLAC.
  92549. *
  92550. * \section embedded_developers Embedded Developers
  92551. *
  92552. * libFLAC has grown larger over time as more functionality has been
  92553. * included, but much of it may be unnecessary for a particular embedded
  92554. * implementation. Unused parts may be pruned by some simple editing of
  92555. * src/libFLAC/Makefile.am. In general, the decoders, encoders, and
  92556. * metadata interface are all independent from each other.
  92557. *
  92558. * It is easiest to just describe the dependencies:
  92559. *
  92560. * - All modules depend on the \link flac_format Format \endlink module.
  92561. * - The decoders and encoders depend on the bitbuffer.
  92562. * - The decoder is independent of the encoder. The encoder uses the
  92563. * decoder because of the verify feature, but this can be removed if
  92564. * not needed.
  92565. * - Parts of the metadata interface require the stream decoder (but not
  92566. * the encoder).
  92567. * - Ogg support is selectable through the compile time macro
  92568. * \c FLAC__HAS_OGG.
  92569. *
  92570. * For example, if your application only requires the stream decoder, no
  92571. * encoder, and no metadata interface, you can remove the stream encoder
  92572. * and the metadata interface, which will greatly reduce the size of the
  92573. * library.
  92574. *
  92575. * Also, there are several places in the libFLAC code with comments marked
  92576. * with "OPT:" where a #define can be changed to enable code that might be
  92577. * faster on a specific platform. Experimenting with these can yield faster
  92578. * binaries.
  92579. */
  92580. /** \defgroup porting Porting Guide for New Versions
  92581. *
  92582. * This module describes differences in the library interfaces from
  92583. * version to version. It assists in the porting of code that uses
  92584. * the libraries to newer versions of FLAC.
  92585. *
  92586. * One simple facility for making porting easier that has been added
  92587. * in FLAC 1.1.3 is a set of \c #defines in \c export.h of each
  92588. * library's includes (e.g. \c include/FLAC/export.h). The
  92589. * \c #defines mirror the libraries'
  92590. * <A HREF="http://www.gnu.org/software/libtool/manual.html#Libtool-versioning">libtool version numbers</A>,
  92591. * e.g. in libFLAC there are \c FLAC_API_VERSION_CURRENT,
  92592. * \c FLAC_API_VERSION_REVISION, and \c FLAC_API_VERSION_AGE.
  92593. * These can be used to support multiple versions of an API during the
  92594. * transition phase, e.g.
  92595. *
  92596. * \code
  92597. * #if !defined(FLAC_API_VERSION_CURRENT) || FLAC_API_VERSION_CURRENT <= 7
  92598. * legacy code
  92599. * #else
  92600. * new code
  92601. * #endif
  92602. * \endcode
  92603. *
  92604. * The the source will work for multiple versions and the legacy code can
  92605. * easily be removed when the transition is complete.
  92606. *
  92607. * Another available symbol is FLAC_API_SUPPORTS_OGG_FLAC (defined in
  92608. * include/FLAC/export.h), which can be used to determine whether or not
  92609. * the library has been compiled with support for Ogg FLAC. This is
  92610. * simpler than trying to call an Ogg init function and catching the
  92611. * error.
  92612. */
  92613. /** \defgroup porting_1_1_2_to_1_1_3 Porting from FLAC 1.1.2 to 1.1.3
  92614. * \ingroup porting
  92615. *
  92616. * \brief
  92617. * This module describes porting from FLAC 1.1.2 to FLAC 1.1.3.
  92618. *
  92619. * The main change between the APIs in 1.1.2 and 1.1.3 is that they have
  92620. * been simplified. First, libOggFLAC has been merged into libFLAC and
  92621. * libOggFLAC++ has been merged into libFLAC++. Second, both the three
  92622. * decoding layers and three encoding layers have been merged into a
  92623. * single stream decoder and stream encoder. That is, the functionality
  92624. * of FLAC__SeekableStreamDecoder and FLAC__FileDecoder has been merged
  92625. * into FLAC__StreamDecoder, and FLAC__SeekableStreamEncoder and
  92626. * FLAC__FileEncoder into FLAC__StreamEncoder. Only the
  92627. * FLAC__StreamDecoder and FLAC__StreamEncoder remain. What this means
  92628. * is there is now a single API that can be used to encode or decode
  92629. * streams to/from native FLAC or Ogg FLAC and the single API can work
  92630. * on both seekable and non-seekable streams.
  92631. *
  92632. * Instead of creating an encoder or decoder of a certain layer, now the
  92633. * client will always create a FLAC__StreamEncoder or
  92634. * FLAC__StreamDecoder. The old layers are now differentiated by the
  92635. * initialization function. For example, for the decoder,
  92636. * FLAC__stream_decoder_init() has been replaced by
  92637. * FLAC__stream_decoder_init_stream(). This init function takes
  92638. * callbacks for the I/O, and the seeking callbacks are optional. This
  92639. * allows the client to use the same object for seekable and
  92640. * non-seekable streams. For decoding a FLAC file directly, the client
  92641. * can use FLAC__stream_decoder_init_file() and pass just a filename
  92642. * and fewer callbacks; most of the other callbacks are supplied
  92643. * internally. For situations where fopen()ing by filename is not
  92644. * possible (e.g. Unicode filenames on Windows) the client can instead
  92645. * open the file itself and supply the FILE* to
  92646. * FLAC__stream_decoder_init_FILE(). The init functions now returns a
  92647. * FLAC__StreamDecoderInitStatus instead of FLAC__StreamDecoderState.
  92648. * Since the callbacks and client data are now passed to the init
  92649. * function, the FLAC__stream_decoder_set_*_callback() functions and
  92650. * FLAC__stream_decoder_set_client_data() are no longer needed. The
  92651. * rest of the calls to the decoder are the same as before.
  92652. *
  92653. * There are counterpart init functions for Ogg FLAC, e.g.
  92654. * FLAC__stream_decoder_init_ogg_stream(). All the rest of the calls
  92655. * and callbacks are the same as for native FLAC.
  92656. *
  92657. * As an example, in FLAC 1.1.2 a seekable stream decoder would have
  92658. * been set up like so:
  92659. *
  92660. * \code
  92661. * FLAC__SeekableStreamDecoder *decoder = FLAC__seekable_stream_decoder_new();
  92662. * if(decoder == NULL) do_something;
  92663. * FLAC__seekable_stream_decoder_set_md5_checking(decoder, true);
  92664. * [... other settings ...]
  92665. * FLAC__seekable_stream_decoder_set_read_callback(decoder, my_read_callback);
  92666. * FLAC__seekable_stream_decoder_set_seek_callback(decoder, my_seek_callback);
  92667. * FLAC__seekable_stream_decoder_set_tell_callback(decoder, my_tell_callback);
  92668. * FLAC__seekable_stream_decoder_set_length_callback(decoder, my_length_callback);
  92669. * FLAC__seekable_stream_decoder_set_eof_callback(decoder, my_eof_callback);
  92670. * FLAC__seekable_stream_decoder_set_write_callback(decoder, my_write_callback);
  92671. * FLAC__seekable_stream_decoder_set_metadata_callback(decoder, my_metadata_callback);
  92672. * FLAC__seekable_stream_decoder_set_error_callback(decoder, my_error_callback);
  92673. * FLAC__seekable_stream_decoder_set_client_data(decoder, my_client_data);
  92674. * if(FLAC__seekable_stream_decoder_init(decoder) != FLAC__SEEKABLE_STREAM_DECODER_OK) do_something;
  92675. * \endcode
  92676. *
  92677. * In FLAC 1.1.3 it is like this:
  92678. *
  92679. * \code
  92680. * FLAC__StreamDecoder *decoder = FLAC__stream_decoder_new();
  92681. * if(decoder == NULL) do_something;
  92682. * FLAC__stream_decoder_set_md5_checking(decoder, true);
  92683. * [... other settings ...]
  92684. * if(FLAC__stream_decoder_init_stream(
  92685. * decoder,
  92686. * my_read_callback,
  92687. * my_seek_callback, // or NULL
  92688. * my_tell_callback, // or NULL
  92689. * my_length_callback, // or NULL
  92690. * my_eof_callback, // or NULL
  92691. * my_write_callback,
  92692. * my_metadata_callback, // or NULL
  92693. * my_error_callback,
  92694. * my_client_data
  92695. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92696. * \endcode
  92697. *
  92698. * or you could do;
  92699. *
  92700. * \code
  92701. * [...]
  92702. * FILE *file = fopen("somefile.flac","rb");
  92703. * if(file == NULL) do_somthing;
  92704. * if(FLAC__stream_decoder_init_FILE(
  92705. * decoder,
  92706. * file,
  92707. * my_write_callback,
  92708. * my_metadata_callback, // or NULL
  92709. * my_error_callback,
  92710. * my_client_data
  92711. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92712. * \endcode
  92713. *
  92714. * or just:
  92715. *
  92716. * \code
  92717. * [...]
  92718. * if(FLAC__stream_decoder_init_file(
  92719. * decoder,
  92720. * "somefile.flac",
  92721. * my_write_callback,
  92722. * my_metadata_callback, // or NULL
  92723. * my_error_callback,
  92724. * my_client_data
  92725. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92726. * \endcode
  92727. *
  92728. * Another small change to the decoder is in how it handles unparseable
  92729. * streams. Before, when the decoder found an unparseable stream
  92730. * (reserved for when the decoder encounters a stream from a future
  92731. * encoder that it can't parse), it changed the state to
  92732. * \c FLAC__STREAM_DECODER_UNPARSEABLE_STREAM. Now the decoder instead
  92733. * drops sync and calls the error callback with a new error code
  92734. * \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM. This is
  92735. * more robust. If your error callback does not discriminate on the the
  92736. * error state, your code does not need to be changed.
  92737. *
  92738. * The encoder now has a new setting:
  92739. * FLAC__stream_encoder_set_apodization(). This is for setting the
  92740. * method used to window the data before LPC analysis. You only need to
  92741. * add a call to this function if the default is not suitable. There
  92742. * are also two new convenience functions that may be useful:
  92743. * FLAC__metadata_object_cuesheet_calculate_cddb_id() and
  92744. * FLAC__metadata_get_cuesheet().
  92745. *
  92746. * The \a bytes parameter to FLAC__StreamDecoderReadCallback,
  92747. * FLAC__StreamEncoderReadCallback, and FLAC__StreamEncoderWriteCallback
  92748. * is now \c size_t instead of \c unsigned.
  92749. */
  92750. /** \defgroup porting_1_1_3_to_1_1_4 Porting from FLAC 1.1.3 to 1.1.4
  92751. * \ingroup porting
  92752. *
  92753. * \brief
  92754. * This module describes porting from FLAC 1.1.3 to FLAC 1.1.4.
  92755. *
  92756. * There were no changes to any of the interfaces from 1.1.3 to 1.1.4.
  92757. * There was a slight change in the implementation of
  92758. * FLAC__stream_encoder_set_metadata(); the function now makes a copy
  92759. * of the \a metadata array of pointers so the client no longer needs
  92760. * to maintain it after the call. The objects themselves that are
  92761. * pointed to by the array are still not copied though and must be
  92762. * maintained until the call to FLAC__stream_encoder_finish().
  92763. */
  92764. /** \defgroup porting_1_1_4_to_1_2_0 Porting from FLAC 1.1.4 to 1.2.0
  92765. * \ingroup porting
  92766. *
  92767. * \brief
  92768. * This module describes porting from FLAC 1.1.4 to FLAC 1.2.0.
  92769. *
  92770. * There were only very minor changes to the interfaces from 1.1.4 to 1.2.0.
  92771. * In libFLAC, \c FLAC__format_sample_rate_is_subset() was added.
  92772. * In libFLAC++, \c FLAC::Decoder::Stream::get_decode_position() was added.
  92773. *
  92774. * Finally, value of the constant \c FLAC__FRAME_HEADER_RESERVED_LEN
  92775. * has changed to reflect the conversion of one of the reserved bits
  92776. * into active use. It used to be \c 2 and now is \c 1. However the
  92777. * FLAC frame header length has not changed, so to skip the proper
  92778. * number of bits, use \c FLAC__FRAME_HEADER_RESERVED_LEN +
  92779. * \c FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN
  92780. */
  92781. /** \defgroup flac FLAC C API
  92782. *
  92783. * The FLAC C API is the interface to libFLAC, a set of structures
  92784. * describing the components of FLAC streams, and functions for
  92785. * encoding and decoding streams, as well as manipulating FLAC
  92786. * metadata in files.
  92787. *
  92788. * You should start with the format components as all other modules
  92789. * are dependent on it.
  92790. */
  92791. #endif
  92792. /*** End of inlined file: all.h ***/
  92793. /*** Start of inlined file: bitmath.c ***/
  92794. /*** Start of inlined file: juce_FlacHeader.h ***/
  92795. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92796. // tasks..
  92797. #define VERSION "1.2.1"
  92798. #define FLAC__NO_DLL 1
  92799. #if JUCE_MSVC
  92800. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92801. #endif
  92802. #if JUCE_MAC
  92803. #define FLAC__SYS_DARWIN 1
  92804. #endif
  92805. /*** End of inlined file: juce_FlacHeader.h ***/
  92806. #if JUCE_USE_FLAC
  92807. #if HAVE_CONFIG_H
  92808. # include <config.h>
  92809. #endif
  92810. /*** Start of inlined file: bitmath.h ***/
  92811. #ifndef FLAC__PRIVATE__BITMATH_H
  92812. #define FLAC__PRIVATE__BITMATH_H
  92813. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v);
  92814. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v);
  92815. unsigned FLAC__bitmath_silog2(int v);
  92816. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v);
  92817. #endif
  92818. /*** End of inlined file: bitmath.h ***/
  92819. /* An example of what FLAC__bitmath_ilog2() computes:
  92820. *
  92821. * ilog2( 0) = assertion failure
  92822. * ilog2( 1) = 0
  92823. * ilog2( 2) = 1
  92824. * ilog2( 3) = 1
  92825. * ilog2( 4) = 2
  92826. * ilog2( 5) = 2
  92827. * ilog2( 6) = 2
  92828. * ilog2( 7) = 2
  92829. * ilog2( 8) = 3
  92830. * ilog2( 9) = 3
  92831. * ilog2(10) = 3
  92832. * ilog2(11) = 3
  92833. * ilog2(12) = 3
  92834. * ilog2(13) = 3
  92835. * ilog2(14) = 3
  92836. * ilog2(15) = 3
  92837. * ilog2(16) = 4
  92838. * ilog2(17) = 4
  92839. * ilog2(18) = 4
  92840. */
  92841. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v)
  92842. {
  92843. unsigned l = 0;
  92844. FLAC__ASSERT(v > 0);
  92845. while(v >>= 1)
  92846. l++;
  92847. return l;
  92848. }
  92849. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v)
  92850. {
  92851. unsigned l = 0;
  92852. FLAC__ASSERT(v > 0);
  92853. while(v >>= 1)
  92854. l++;
  92855. return l;
  92856. }
  92857. /* An example of what FLAC__bitmath_silog2() computes:
  92858. *
  92859. * silog2(-10) = 5
  92860. * silog2(- 9) = 5
  92861. * silog2(- 8) = 4
  92862. * silog2(- 7) = 4
  92863. * silog2(- 6) = 4
  92864. * silog2(- 5) = 4
  92865. * silog2(- 4) = 3
  92866. * silog2(- 3) = 3
  92867. * silog2(- 2) = 2
  92868. * silog2(- 1) = 2
  92869. * silog2( 0) = 0
  92870. * silog2( 1) = 2
  92871. * silog2( 2) = 3
  92872. * silog2( 3) = 3
  92873. * silog2( 4) = 4
  92874. * silog2( 5) = 4
  92875. * silog2( 6) = 4
  92876. * silog2( 7) = 4
  92877. * silog2( 8) = 5
  92878. * silog2( 9) = 5
  92879. * silog2( 10) = 5
  92880. */
  92881. unsigned FLAC__bitmath_silog2(int v)
  92882. {
  92883. while(1) {
  92884. if(v == 0) {
  92885. return 0;
  92886. }
  92887. else if(v > 0) {
  92888. unsigned l = 0;
  92889. while(v) {
  92890. l++;
  92891. v >>= 1;
  92892. }
  92893. return l+1;
  92894. }
  92895. else if(v == -1) {
  92896. return 2;
  92897. }
  92898. else {
  92899. v++;
  92900. v = -v;
  92901. }
  92902. }
  92903. }
  92904. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v)
  92905. {
  92906. while(1) {
  92907. if(v == 0) {
  92908. return 0;
  92909. }
  92910. else if(v > 0) {
  92911. unsigned l = 0;
  92912. while(v) {
  92913. l++;
  92914. v >>= 1;
  92915. }
  92916. return l+1;
  92917. }
  92918. else if(v == -1) {
  92919. return 2;
  92920. }
  92921. else {
  92922. v++;
  92923. v = -v;
  92924. }
  92925. }
  92926. }
  92927. #endif
  92928. /*** End of inlined file: bitmath.c ***/
  92929. /*** Start of inlined file: bitreader.c ***/
  92930. /*** Start of inlined file: juce_FlacHeader.h ***/
  92931. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92932. // tasks..
  92933. #define VERSION "1.2.1"
  92934. #define FLAC__NO_DLL 1
  92935. #if JUCE_MSVC
  92936. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92937. #endif
  92938. #if JUCE_MAC
  92939. #define FLAC__SYS_DARWIN 1
  92940. #endif
  92941. /*** End of inlined file: juce_FlacHeader.h ***/
  92942. #if JUCE_USE_FLAC
  92943. #if HAVE_CONFIG_H
  92944. # include <config.h>
  92945. #endif
  92946. #include <stdlib.h> /* for malloc() */
  92947. #include <string.h> /* for memcpy(), memset() */
  92948. #ifdef _MSC_VER
  92949. #include <winsock.h> /* for ntohl() */
  92950. #elif defined FLAC__SYS_DARWIN
  92951. #include <machine/endian.h> /* for ntohl() */
  92952. #elif defined __MINGW32__
  92953. #include <winsock.h> /* for ntohl() */
  92954. #else
  92955. #include <netinet/in.h> /* for ntohl() */
  92956. #endif
  92957. /*** Start of inlined file: bitreader.h ***/
  92958. #ifndef FLAC__PRIVATE__BITREADER_H
  92959. #define FLAC__PRIVATE__BITREADER_H
  92960. #include <stdio.h> /* for FILE */
  92961. /*** Start of inlined file: cpu.h ***/
  92962. #ifndef FLAC__PRIVATE__CPU_H
  92963. #define FLAC__PRIVATE__CPU_H
  92964. #ifdef HAVE_CONFIG_H
  92965. #include <config.h>
  92966. #endif
  92967. typedef enum {
  92968. FLAC__CPUINFO_TYPE_IA32,
  92969. FLAC__CPUINFO_TYPE_PPC,
  92970. FLAC__CPUINFO_TYPE_UNKNOWN
  92971. } FLAC__CPUInfo_Type;
  92972. typedef struct {
  92973. FLAC__bool cpuid;
  92974. FLAC__bool bswap;
  92975. FLAC__bool cmov;
  92976. FLAC__bool mmx;
  92977. FLAC__bool fxsr;
  92978. FLAC__bool sse;
  92979. FLAC__bool sse2;
  92980. FLAC__bool sse3;
  92981. FLAC__bool ssse3;
  92982. FLAC__bool _3dnow;
  92983. FLAC__bool ext3dnow;
  92984. FLAC__bool extmmx;
  92985. } FLAC__CPUInfo_IA32;
  92986. typedef struct {
  92987. FLAC__bool altivec;
  92988. FLAC__bool ppc64;
  92989. } FLAC__CPUInfo_PPC;
  92990. typedef struct {
  92991. FLAC__bool use_asm;
  92992. FLAC__CPUInfo_Type type;
  92993. union {
  92994. FLAC__CPUInfo_IA32 ia32;
  92995. FLAC__CPUInfo_PPC ppc;
  92996. } data;
  92997. } FLAC__CPUInfo;
  92998. void FLAC__cpu_info(FLAC__CPUInfo *info);
  92999. #ifndef FLAC__NO_ASM
  93000. #ifdef FLAC__CPU_IA32
  93001. #ifdef FLAC__HAS_NASM
  93002. FLAC__uint32 FLAC__cpu_have_cpuid_asm_ia32(void);
  93003. void FLAC__cpu_info_asm_ia32(FLAC__uint32 *flags_edx, FLAC__uint32 *flags_ecx);
  93004. FLAC__uint32 FLAC__cpu_info_extended_amd_asm_ia32(void);
  93005. #endif
  93006. #endif
  93007. #endif
  93008. #endif
  93009. /*** End of inlined file: cpu.h ***/
  93010. /*
  93011. * opaque structure definition
  93012. */
  93013. struct FLAC__BitReader;
  93014. typedef struct FLAC__BitReader FLAC__BitReader;
  93015. typedef FLAC__bool (*FLAC__BitReaderReadCallback)(FLAC__byte buffer[], size_t *bytes, void *client_data);
  93016. /*
  93017. * construction, deletion, initialization, etc functions
  93018. */
  93019. FLAC__BitReader *FLAC__bitreader_new(void);
  93020. void FLAC__bitreader_delete(FLAC__BitReader *br);
  93021. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd);
  93022. void FLAC__bitreader_free(FLAC__BitReader *br); /* does not 'free(br)' */
  93023. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br);
  93024. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out);
  93025. /*
  93026. * CRC functions
  93027. */
  93028. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed);
  93029. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br);
  93030. /*
  93031. * info functions
  93032. */
  93033. FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br);
  93034. unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br);
  93035. unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br);
  93036. /*
  93037. * read functions
  93038. */
  93039. FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits);
  93040. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits);
  93041. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits);
  93042. FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val); /*only for bits=32*/
  93043. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits); /* WATCHOUT: does not CRC the skipped data! */ /*@@@@ add to unit tests */
  93044. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals); /* WATCHOUT: does not CRC the read data! */
  93045. 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! */
  93046. FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val);
  93047. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  93048. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  93049. #ifndef FLAC__NO_ASM
  93050. # ifdef FLAC__CPU_IA32
  93051. # ifdef FLAC__HAS_NASM
  93052. FLAC__bool FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  93053. # endif
  93054. # endif
  93055. #endif
  93056. #if 0 /* UNUSED */
  93057. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  93058. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter);
  93059. #endif
  93060. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen);
  93061. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen);
  93062. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br);
  93063. #endif
  93064. /*** End of inlined file: bitreader.h ***/
  93065. /*** Start of inlined file: crc.h ***/
  93066. #ifndef FLAC__PRIVATE__CRC_H
  93067. #define FLAC__PRIVATE__CRC_H
  93068. /* 8 bit CRC generator, MSB shifted first
  93069. ** polynomial = x^8 + x^2 + x^1 + x^0
  93070. ** init = 0
  93071. */
  93072. extern FLAC__byte const FLAC__crc8_table[256];
  93073. #define FLAC__CRC8_UPDATE(data, crc) (crc) = FLAC__crc8_table[(crc) ^ (data)];
  93074. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc);
  93075. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc);
  93076. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len);
  93077. /* 16 bit CRC generator, MSB shifted first
  93078. ** polynomial = x^16 + x^15 + x^2 + x^0
  93079. ** init = 0
  93080. */
  93081. extern unsigned FLAC__crc16_table[256];
  93082. #define FLAC__CRC16_UPDATE(data, crc) (((((crc)<<8) & 0xffff) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]))
  93083. /* this alternate may be faster on some systems/compilers */
  93084. #if 0
  93085. #define FLAC__CRC16_UPDATE(data, crc) ((((crc)<<8) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]) & 0xffff)
  93086. #endif
  93087. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len);
  93088. #endif
  93089. /*** End of inlined file: crc.h ***/
  93090. /* Things should be fastest when this matches the machine word size */
  93091. /* WATCHOUT: if you change this you must also change the following #defines down to COUNT_ZERO_MSBS below to match */
  93092. /* WATCHOUT: there are a few places where the code will not work unless brword is >= 32 bits wide */
  93093. /* also, some sections currently only have fast versions for 4 or 8 bytes per word */
  93094. typedef FLAC__uint32 brword;
  93095. #define FLAC__BYTES_PER_WORD 4
  93096. #define FLAC__BITS_PER_WORD 32
  93097. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  93098. /* SWAP_BE_WORD_TO_HOST swaps bytes in a brword (which is always big-endian) if necessary to match host byte order */
  93099. #if WORDS_BIGENDIAN
  93100. #define SWAP_BE_WORD_TO_HOST(x) (x)
  93101. #else
  93102. #if defined (_MSC_VER) && defined (_X86_)
  93103. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  93104. #else
  93105. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  93106. #endif
  93107. #endif
  93108. /* counts the # of zero MSBs in a word */
  93109. #define COUNT_ZERO_MSBS(word) ( \
  93110. (word) <= 0xffff ? \
  93111. ( (word) <= 0xff? byte_to_unary_table[word] + 24 : byte_to_unary_table[(word) >> 8] + 16 ) : \
  93112. ( (word) <= 0xffffff? byte_to_unary_table[word >> 16] + 8 : byte_to_unary_table[(word) >> 24] ) \
  93113. )
  93114. /* this alternate might be slightly faster on some systems/compilers: */
  93115. #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])) )
  93116. /*
  93117. * This should be at least twice as large as the largest number of words
  93118. * required to represent any 'number' (in any encoding) you are going to
  93119. * read. With FLAC this is on the order of maybe a few hundred bits.
  93120. * If the buffer is smaller than that, the decoder won't be able to read
  93121. * in a whole number that is in a variable length encoding (e.g. Rice).
  93122. * But to be practical it should be at least 1K bytes.
  93123. *
  93124. * Increase this number to decrease the number of read callbacks, at the
  93125. * expense of using more memory. Or decrease for the reverse effect,
  93126. * keeping in mind the limit from the first paragraph. The optimal size
  93127. * also depends on the CPU cache size and other factors; some twiddling
  93128. * may be necessary to squeeze out the best performance.
  93129. */
  93130. static const unsigned FLAC__BITREADER_DEFAULT_CAPACITY = 65536u / FLAC__BITS_PER_WORD; /* in words */
  93131. static const unsigned char byte_to_unary_table[] = {
  93132. 8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4,
  93133. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  93134. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  93135. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  93136. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93137. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93138. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93139. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
  93148. };
  93149. #ifdef min
  93150. #undef min
  93151. #endif
  93152. #define min(x,y) ((x)<(y)?(x):(y))
  93153. #ifdef max
  93154. #undef max
  93155. #endif
  93156. #define max(x,y) ((x)>(y)?(x):(y))
  93157. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  93158. #ifdef _MSC_VER
  93159. #define FLAC__U64L(x) x
  93160. #else
  93161. #define FLAC__U64L(x) x##LLU
  93162. #endif
  93163. #ifndef FLaC__INLINE
  93164. #define FLaC__INLINE
  93165. #endif
  93166. /* WATCHOUT: assembly routines rely on the order in which these fields are declared */
  93167. struct FLAC__BitReader {
  93168. /* any partially-consumed word at the head will stay right-justified as bits are consumed from the left */
  93169. /* any incomplete word at the tail will be left-justified, and bytes from the read callback are added on the right */
  93170. brword *buffer;
  93171. unsigned capacity; /* in words */
  93172. unsigned words; /* # of completed words in buffer */
  93173. unsigned bytes; /* # of bytes in incomplete word at buffer[words] */
  93174. unsigned consumed_words; /* #words ... */
  93175. unsigned consumed_bits; /* ... + (#bits of head word) already consumed from the front of buffer */
  93176. unsigned read_crc16; /* the running frame CRC */
  93177. unsigned crc16_align; /* the number of bits in the current consumed word that should not be CRC'd */
  93178. FLAC__BitReaderReadCallback read_callback;
  93179. void *client_data;
  93180. FLAC__CPUInfo cpu_info;
  93181. };
  93182. static FLaC__INLINE void crc16_update_word_(FLAC__BitReader *br, brword word)
  93183. {
  93184. register unsigned crc = br->read_crc16;
  93185. #if FLAC__BYTES_PER_WORD == 4
  93186. switch(br->crc16_align) {
  93187. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 24), crc);
  93188. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  93189. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  93190. case 24: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  93191. }
  93192. #elif FLAC__BYTES_PER_WORD == 8
  93193. switch(br->crc16_align) {
  93194. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 56), crc);
  93195. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 48) & 0xff), crc);
  93196. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 40) & 0xff), crc);
  93197. case 24: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 32) & 0xff), crc);
  93198. case 32: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 24) & 0xff), crc);
  93199. case 40: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  93200. case 48: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  93201. case 56: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  93202. }
  93203. #else
  93204. for( ; br->crc16_align < FLAC__BITS_PER_WORD; br->crc16_align += 8)
  93205. crc = FLAC__CRC16_UPDATE((unsigned)((word >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), crc);
  93206. br->read_crc16 = crc;
  93207. #endif
  93208. br->crc16_align = 0;
  93209. }
  93210. /* would be static except it needs to be called by asm routines */
  93211. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br)
  93212. {
  93213. unsigned start, end;
  93214. size_t bytes;
  93215. FLAC__byte *target;
  93216. /* first shift the unconsumed buffer data toward the front as much as possible */
  93217. if(br->consumed_words > 0) {
  93218. start = br->consumed_words;
  93219. end = br->words + (br->bytes? 1:0);
  93220. memmove(br->buffer, br->buffer+start, FLAC__BYTES_PER_WORD * (end - start));
  93221. br->words -= start;
  93222. br->consumed_words = 0;
  93223. }
  93224. /*
  93225. * set the target for reading, taking into account word alignment and endianness
  93226. */
  93227. bytes = (br->capacity - br->words) * FLAC__BYTES_PER_WORD - br->bytes;
  93228. if(bytes == 0)
  93229. return false; /* no space left, buffer is too small; see note for FLAC__BITREADER_DEFAULT_CAPACITY */
  93230. target = ((FLAC__byte*)(br->buffer+br->words)) + br->bytes;
  93231. /* before reading, if the existing reader looks like this (say brword is 32 bits wide)
  93232. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1 (partial tail word is left-justified)
  93233. * buffer[BE]: 11 22 33 44 55 ?? ?? ?? (shown layed out as bytes sequentially in memory)
  93234. * buffer[LE]: 44 33 22 11 ?? ?? ?? 55 (?? being don't-care)
  93235. * ^^-------target, bytes=3
  93236. * on LE machines, have to byteswap the odd tail word so nothing is
  93237. * overwritten:
  93238. */
  93239. #if WORDS_BIGENDIAN
  93240. #else
  93241. if(br->bytes)
  93242. br->buffer[br->words] = SWAP_BE_WORD_TO_HOST(br->buffer[br->words]);
  93243. #endif
  93244. /* now it looks like:
  93245. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1
  93246. * buffer[BE]: 11 22 33 44 55 ?? ?? ??
  93247. * buffer[LE]: 44 33 22 11 55 ?? ?? ??
  93248. * ^^-------target, bytes=3
  93249. */
  93250. /* read in the data; note that the callback may return a smaller number of bytes */
  93251. if(!br->read_callback(target, &bytes, br->client_data))
  93252. return false;
  93253. /* after reading bytes 66 77 88 99 AA BB CC DD EE FF from the client:
  93254. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  93255. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  93256. * buffer[LE]: 44 33 22 11 55 66 77 88 99 AA BB CC DD EE FF ??
  93257. * now have to byteswap on LE machines:
  93258. */
  93259. #if WORDS_BIGENDIAN
  93260. #else
  93261. end = (br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes + (FLAC__BYTES_PER_WORD-1)) / FLAC__BYTES_PER_WORD;
  93262. # if defined(_MSC_VER) && defined (_X86_) && (FLAC__BYTES_PER_WORD == 4)
  93263. if(br->cpu_info.type == FLAC__CPUINFO_TYPE_IA32 && br->cpu_info.data.ia32.bswap) {
  93264. start = br->words;
  93265. local_swap32_block_(br->buffer + start, end - start);
  93266. }
  93267. else
  93268. # endif
  93269. for(start = br->words; start < end; start++)
  93270. br->buffer[start] = SWAP_BE_WORD_TO_HOST(br->buffer[start]);
  93271. #endif
  93272. /* now it looks like:
  93273. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  93274. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  93275. * buffer[LE]: 44 33 22 11 88 77 66 55 CC BB AA 99 ?? FF EE DD
  93276. * finally we'll update the reader values:
  93277. */
  93278. end = br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes;
  93279. br->words = end / FLAC__BYTES_PER_WORD;
  93280. br->bytes = end % FLAC__BYTES_PER_WORD;
  93281. return true;
  93282. }
  93283. /***********************************************************************
  93284. *
  93285. * Class constructor/destructor
  93286. *
  93287. ***********************************************************************/
  93288. FLAC__BitReader *FLAC__bitreader_new(void)
  93289. {
  93290. FLAC__BitReader *br = (FLAC__BitReader*)calloc(1, sizeof(FLAC__BitReader));
  93291. /* calloc() implies:
  93292. memset(br, 0, sizeof(FLAC__BitReader));
  93293. br->buffer = 0;
  93294. br->capacity = 0;
  93295. br->words = br->bytes = 0;
  93296. br->consumed_words = br->consumed_bits = 0;
  93297. br->read_callback = 0;
  93298. br->client_data = 0;
  93299. */
  93300. return br;
  93301. }
  93302. void FLAC__bitreader_delete(FLAC__BitReader *br)
  93303. {
  93304. FLAC__ASSERT(0 != br);
  93305. FLAC__bitreader_free(br);
  93306. free(br);
  93307. }
  93308. /***********************************************************************
  93309. *
  93310. * Public class methods
  93311. *
  93312. ***********************************************************************/
  93313. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd)
  93314. {
  93315. FLAC__ASSERT(0 != br);
  93316. br->words = br->bytes = 0;
  93317. br->consumed_words = br->consumed_bits = 0;
  93318. br->capacity = FLAC__BITREADER_DEFAULT_CAPACITY;
  93319. br->buffer = (brword*)malloc(sizeof(brword) * br->capacity);
  93320. if(br->buffer == 0)
  93321. return false;
  93322. br->read_callback = rcb;
  93323. br->client_data = cd;
  93324. br->cpu_info = cpu;
  93325. return true;
  93326. }
  93327. void FLAC__bitreader_free(FLAC__BitReader *br)
  93328. {
  93329. FLAC__ASSERT(0 != br);
  93330. if(0 != br->buffer)
  93331. free(br->buffer);
  93332. br->buffer = 0;
  93333. br->capacity = 0;
  93334. br->words = br->bytes = 0;
  93335. br->consumed_words = br->consumed_bits = 0;
  93336. br->read_callback = 0;
  93337. br->client_data = 0;
  93338. }
  93339. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br)
  93340. {
  93341. br->words = br->bytes = 0;
  93342. br->consumed_words = br->consumed_bits = 0;
  93343. return true;
  93344. }
  93345. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out)
  93346. {
  93347. unsigned i, j;
  93348. if(br == 0) {
  93349. fprintf(out, "bitreader is NULL\n");
  93350. }
  93351. else {
  93352. 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);
  93353. for(i = 0; i < br->words; i++) {
  93354. fprintf(out, "%08X: ", i);
  93355. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  93356. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  93357. fprintf(out, ".");
  93358. else
  93359. fprintf(out, "%01u", br->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  93360. fprintf(out, "\n");
  93361. }
  93362. if(br->bytes > 0) {
  93363. fprintf(out, "%08X: ", i);
  93364. for(j = 0; j < br->bytes*8; j++)
  93365. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  93366. fprintf(out, ".");
  93367. else
  93368. fprintf(out, "%01u", br->buffer[i] & (1 << (br->bytes*8-j-1)) ? 1:0);
  93369. fprintf(out, "\n");
  93370. }
  93371. }
  93372. }
  93373. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed)
  93374. {
  93375. FLAC__ASSERT(0 != br);
  93376. FLAC__ASSERT(0 != br->buffer);
  93377. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  93378. br->read_crc16 = (unsigned)seed;
  93379. br->crc16_align = br->consumed_bits;
  93380. }
  93381. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br)
  93382. {
  93383. FLAC__ASSERT(0 != br);
  93384. FLAC__ASSERT(0 != br->buffer);
  93385. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  93386. FLAC__ASSERT(br->crc16_align <= br->consumed_bits);
  93387. /* CRC any tail bytes in a partially-consumed word */
  93388. if(br->consumed_bits) {
  93389. const brword tail = br->buffer[br->consumed_words];
  93390. for( ; br->crc16_align < br->consumed_bits; br->crc16_align += 8)
  93391. br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)((tail >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), br->read_crc16);
  93392. }
  93393. return br->read_crc16;
  93394. }
  93395. FLaC__INLINE FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br)
  93396. {
  93397. return ((br->consumed_bits & 7) == 0);
  93398. }
  93399. FLaC__INLINE unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br)
  93400. {
  93401. return 8 - (br->consumed_bits & 7);
  93402. }
  93403. FLaC__INLINE unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br)
  93404. {
  93405. return (br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits;
  93406. }
  93407. FLaC__INLINE FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits)
  93408. {
  93409. FLAC__ASSERT(0 != br);
  93410. FLAC__ASSERT(0 != br->buffer);
  93411. FLAC__ASSERT(bits <= 32);
  93412. FLAC__ASSERT((br->capacity*FLAC__BITS_PER_WORD) * 2 >= bits);
  93413. FLAC__ASSERT(br->consumed_words <= br->words);
  93414. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93415. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93416. if(bits == 0) { /* OPT: investigate if this can ever happen, maybe change to assertion */
  93417. *val = 0;
  93418. return true;
  93419. }
  93420. while((br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits < bits) {
  93421. if(!bitreader_read_from_client_(br))
  93422. return false;
  93423. }
  93424. if(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  93425. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  93426. if(br->consumed_bits) {
  93427. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93428. const unsigned n = FLAC__BITS_PER_WORD - br->consumed_bits;
  93429. const brword word = br->buffer[br->consumed_words];
  93430. if(bits < n) {
  93431. *val = (word & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (n-bits);
  93432. br->consumed_bits += bits;
  93433. return true;
  93434. }
  93435. *val = word & (FLAC__WORD_ALL_ONES >> br->consumed_bits);
  93436. bits -= n;
  93437. crc16_update_word_(br, word);
  93438. br->consumed_words++;
  93439. br->consumed_bits = 0;
  93440. 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 */
  93441. *val <<= bits;
  93442. *val |= (br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits));
  93443. br->consumed_bits = bits;
  93444. }
  93445. return true;
  93446. }
  93447. else {
  93448. const brword word = br->buffer[br->consumed_words];
  93449. if(bits < FLAC__BITS_PER_WORD) {
  93450. *val = word >> (FLAC__BITS_PER_WORD-bits);
  93451. br->consumed_bits = bits;
  93452. return true;
  93453. }
  93454. /* at this point 'bits' must be == FLAC__BITS_PER_WORD; because of previous assertions, it can't be larger */
  93455. *val = word;
  93456. crc16_update_word_(br, word);
  93457. br->consumed_words++;
  93458. return true;
  93459. }
  93460. }
  93461. else {
  93462. /* in this case we're starting our read at a partial tail word;
  93463. * the reader has guaranteed that we have at least 'bits' bits
  93464. * available to read, which makes this case simpler.
  93465. */
  93466. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  93467. if(br->consumed_bits) {
  93468. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93469. FLAC__ASSERT(br->consumed_bits + bits <= br->bytes*8);
  93470. *val = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (FLAC__BITS_PER_WORD-br->consumed_bits-bits);
  93471. br->consumed_bits += bits;
  93472. return true;
  93473. }
  93474. else {
  93475. *val = br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits);
  93476. br->consumed_bits += bits;
  93477. return true;
  93478. }
  93479. }
  93480. }
  93481. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits)
  93482. {
  93483. /* OPT: inline raw uint32 code here, or make into a macro if possible in the .h file */
  93484. if(!FLAC__bitreader_read_raw_uint32(br, (FLAC__uint32*)val, bits))
  93485. return false;
  93486. /* sign-extend: */
  93487. *val <<= (32-bits);
  93488. *val >>= (32-bits);
  93489. return true;
  93490. }
  93491. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits)
  93492. {
  93493. FLAC__uint32 hi, lo;
  93494. if(bits > 32) {
  93495. if(!FLAC__bitreader_read_raw_uint32(br, &hi, bits-32))
  93496. return false;
  93497. if(!FLAC__bitreader_read_raw_uint32(br, &lo, 32))
  93498. return false;
  93499. *val = hi;
  93500. *val <<= 32;
  93501. *val |= lo;
  93502. }
  93503. else {
  93504. if(!FLAC__bitreader_read_raw_uint32(br, &lo, bits))
  93505. return false;
  93506. *val = lo;
  93507. }
  93508. return true;
  93509. }
  93510. FLaC__INLINE FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val)
  93511. {
  93512. FLAC__uint32 x8, x32 = 0;
  93513. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  93514. if(!FLAC__bitreader_read_raw_uint32(br, &x32, 8))
  93515. return false;
  93516. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93517. return false;
  93518. x32 |= (x8 << 8);
  93519. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93520. return false;
  93521. x32 |= (x8 << 16);
  93522. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93523. return false;
  93524. x32 |= (x8 << 24);
  93525. *val = x32;
  93526. return true;
  93527. }
  93528. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits)
  93529. {
  93530. /*
  93531. * OPT: a faster implementation is possible but probably not that useful
  93532. * since this is only called a couple of times in the metadata readers.
  93533. */
  93534. FLAC__ASSERT(0 != br);
  93535. FLAC__ASSERT(0 != br->buffer);
  93536. if(bits > 0) {
  93537. const unsigned n = br->consumed_bits & 7;
  93538. unsigned m;
  93539. FLAC__uint32 x;
  93540. if(n != 0) {
  93541. m = min(8-n, bits);
  93542. if(!FLAC__bitreader_read_raw_uint32(br, &x, m))
  93543. return false;
  93544. bits -= m;
  93545. }
  93546. m = bits / 8;
  93547. if(m > 0) {
  93548. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(br, m))
  93549. return false;
  93550. bits %= 8;
  93551. }
  93552. if(bits > 0) {
  93553. if(!FLAC__bitreader_read_raw_uint32(br, &x, bits))
  93554. return false;
  93555. }
  93556. }
  93557. return true;
  93558. }
  93559. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals)
  93560. {
  93561. FLAC__uint32 x;
  93562. FLAC__ASSERT(0 != br);
  93563. FLAC__ASSERT(0 != br->buffer);
  93564. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  93565. /* step 1: skip over partial head word to get word aligned */
  93566. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  93567. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93568. return false;
  93569. nvals--;
  93570. }
  93571. if(0 == nvals)
  93572. return true;
  93573. /* step 2: skip whole words in chunks */
  93574. while(nvals >= FLAC__BYTES_PER_WORD) {
  93575. if(br->consumed_words < br->words) {
  93576. br->consumed_words++;
  93577. nvals -= FLAC__BYTES_PER_WORD;
  93578. }
  93579. else if(!bitreader_read_from_client_(br))
  93580. return false;
  93581. }
  93582. /* step 3: skip any remainder from partial tail bytes */
  93583. while(nvals) {
  93584. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93585. return false;
  93586. nvals--;
  93587. }
  93588. return true;
  93589. }
  93590. FLAC__bool FLAC__bitreader_read_byte_block_aligned_no_crc(FLAC__BitReader *br, FLAC__byte *val, unsigned nvals)
  93591. {
  93592. FLAC__uint32 x;
  93593. FLAC__ASSERT(0 != br);
  93594. FLAC__ASSERT(0 != br->buffer);
  93595. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  93596. /* step 1: read from partial head word to get word aligned */
  93597. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  93598. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93599. return false;
  93600. *val++ = (FLAC__byte)x;
  93601. nvals--;
  93602. }
  93603. if(0 == nvals)
  93604. return true;
  93605. /* step 2: read whole words in chunks */
  93606. while(nvals >= FLAC__BYTES_PER_WORD) {
  93607. if(br->consumed_words < br->words) {
  93608. const brword word = br->buffer[br->consumed_words++];
  93609. #if FLAC__BYTES_PER_WORD == 4
  93610. val[0] = (FLAC__byte)(word >> 24);
  93611. val[1] = (FLAC__byte)(word >> 16);
  93612. val[2] = (FLAC__byte)(word >> 8);
  93613. val[3] = (FLAC__byte)word;
  93614. #elif FLAC__BYTES_PER_WORD == 8
  93615. val[0] = (FLAC__byte)(word >> 56);
  93616. val[1] = (FLAC__byte)(word >> 48);
  93617. val[2] = (FLAC__byte)(word >> 40);
  93618. val[3] = (FLAC__byte)(word >> 32);
  93619. val[4] = (FLAC__byte)(word >> 24);
  93620. val[5] = (FLAC__byte)(word >> 16);
  93621. val[6] = (FLAC__byte)(word >> 8);
  93622. val[7] = (FLAC__byte)word;
  93623. #else
  93624. for(x = 0; x < FLAC__BYTES_PER_WORD; x++)
  93625. val[x] = (FLAC__byte)(word >> (8*(FLAC__BYTES_PER_WORD-x-1)));
  93626. #endif
  93627. val += FLAC__BYTES_PER_WORD;
  93628. nvals -= FLAC__BYTES_PER_WORD;
  93629. }
  93630. else if(!bitreader_read_from_client_(br))
  93631. return false;
  93632. }
  93633. /* step 3: read any remainder from partial tail bytes */
  93634. while(nvals) {
  93635. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93636. return false;
  93637. *val++ = (FLAC__byte)x;
  93638. nvals--;
  93639. }
  93640. return true;
  93641. }
  93642. FLaC__INLINE FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val)
  93643. #if 0 /* slow but readable version */
  93644. {
  93645. unsigned bit;
  93646. FLAC__ASSERT(0 != br);
  93647. FLAC__ASSERT(0 != br->buffer);
  93648. *val = 0;
  93649. while(1) {
  93650. if(!FLAC__bitreader_read_bit(br, &bit))
  93651. return false;
  93652. if(bit)
  93653. break;
  93654. else
  93655. *val++;
  93656. }
  93657. return true;
  93658. }
  93659. #else
  93660. {
  93661. unsigned i;
  93662. FLAC__ASSERT(0 != br);
  93663. FLAC__ASSERT(0 != br->buffer);
  93664. *val = 0;
  93665. while(1) {
  93666. while(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  93667. brword b = br->buffer[br->consumed_words] << br->consumed_bits;
  93668. if(b) {
  93669. i = COUNT_ZERO_MSBS(b);
  93670. *val += i;
  93671. i++;
  93672. br->consumed_bits += i;
  93673. if(br->consumed_bits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(br->consumed_bits == FLAC__BITS_PER_WORD) */
  93674. crc16_update_word_(br, br->buffer[br->consumed_words]);
  93675. br->consumed_words++;
  93676. br->consumed_bits = 0;
  93677. }
  93678. return true;
  93679. }
  93680. else {
  93681. *val += FLAC__BITS_PER_WORD - br->consumed_bits;
  93682. crc16_update_word_(br, br->buffer[br->consumed_words]);
  93683. br->consumed_words++;
  93684. br->consumed_bits = 0;
  93685. /* didn't find stop bit yet, have to keep going... */
  93686. }
  93687. }
  93688. /* at this point we've eaten up all the whole words; have to try
  93689. * reading through any tail bytes before calling the read callback.
  93690. * this is a repeat of the above logic adjusted for the fact we
  93691. * don't have a whole word. note though if the client is feeding
  93692. * us data a byte at a time (unlikely), br->consumed_bits may not
  93693. * be zero.
  93694. */
  93695. if(br->bytes) {
  93696. const unsigned end = br->bytes * 8;
  93697. brword b = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << br->consumed_bits;
  93698. if(b) {
  93699. i = COUNT_ZERO_MSBS(b);
  93700. *val += i;
  93701. i++;
  93702. br->consumed_bits += i;
  93703. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  93704. return true;
  93705. }
  93706. else {
  93707. *val += end - br->consumed_bits;
  93708. br->consumed_bits += end;
  93709. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  93710. /* didn't find stop bit yet, have to keep going... */
  93711. }
  93712. }
  93713. if(!bitreader_read_from_client_(br))
  93714. return false;
  93715. }
  93716. }
  93717. #endif
  93718. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  93719. {
  93720. FLAC__uint32 lsbs = 0, msbs = 0;
  93721. unsigned uval;
  93722. FLAC__ASSERT(0 != br);
  93723. FLAC__ASSERT(0 != br->buffer);
  93724. FLAC__ASSERT(parameter <= 31);
  93725. /* read the unary MSBs and end bit */
  93726. if(!FLAC__bitreader_read_unary_unsigned(br, (unsigned int*) &msbs))
  93727. return false;
  93728. /* read the binary LSBs */
  93729. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, parameter))
  93730. return false;
  93731. /* compose the value */
  93732. uval = (msbs << parameter) | lsbs;
  93733. if(uval & 1)
  93734. *val = -((int)(uval >> 1)) - 1;
  93735. else
  93736. *val = (int)(uval >> 1);
  93737. return true;
  93738. }
  93739. /* this is by far the most heavily used reader call. it ain't pretty but it's fast */
  93740. /* a lot of the logic is copied, then adapted, from FLAC__bitreader_read_unary_unsigned() and FLAC__bitreader_read_raw_uint32() */
  93741. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter)
  93742. /* OPT: possibly faster version for use with MSVC */
  93743. #ifdef _MSC_VER
  93744. {
  93745. unsigned i;
  93746. unsigned uval = 0;
  93747. unsigned bits; /* the # of binary LSBs left to read to finish a rice codeword */
  93748. /* try and get br->consumed_words and br->consumed_bits into register;
  93749. * must remember to flush them back to *br before calling other
  93750. * bitwriter functions that use them, and before returning */
  93751. register unsigned cwords;
  93752. register unsigned cbits;
  93753. FLAC__ASSERT(0 != br);
  93754. FLAC__ASSERT(0 != br->buffer);
  93755. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93756. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93757. FLAC__ASSERT(parameter < 32);
  93758. /* 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 */
  93759. if(nvals == 0)
  93760. return true;
  93761. cbits = br->consumed_bits;
  93762. cwords = br->consumed_words;
  93763. while(1) {
  93764. /* read unary part */
  93765. while(1) {
  93766. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93767. brword b = br->buffer[cwords] << cbits;
  93768. if(b) {
  93769. #if 0 /* slower, probably due to bad register allocation... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32
  93770. __asm {
  93771. bsr eax, b
  93772. not eax
  93773. and eax, 31
  93774. mov i, eax
  93775. }
  93776. #else
  93777. i = COUNT_ZERO_MSBS(b);
  93778. #endif
  93779. uval += i;
  93780. bits = parameter;
  93781. i++;
  93782. cbits += i;
  93783. if(cbits == FLAC__BITS_PER_WORD) {
  93784. crc16_update_word_(br, br->buffer[cwords]);
  93785. cwords++;
  93786. cbits = 0;
  93787. }
  93788. goto break1;
  93789. }
  93790. else {
  93791. uval += FLAC__BITS_PER_WORD - cbits;
  93792. crc16_update_word_(br, br->buffer[cwords]);
  93793. cwords++;
  93794. cbits = 0;
  93795. /* didn't find stop bit yet, have to keep going... */
  93796. }
  93797. }
  93798. /* at this point we've eaten up all the whole words; have to try
  93799. * reading through any tail bytes before calling the read callback.
  93800. * this is a repeat of the above logic adjusted for the fact we
  93801. * don't have a whole word. note though if the client is feeding
  93802. * us data a byte at a time (unlikely), br->consumed_bits may not
  93803. * be zero.
  93804. */
  93805. if(br->bytes) {
  93806. const unsigned end = br->bytes * 8;
  93807. brword b = (br->buffer[cwords] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << cbits;
  93808. if(b) {
  93809. i = COUNT_ZERO_MSBS(b);
  93810. uval += i;
  93811. bits = parameter;
  93812. i++;
  93813. cbits += i;
  93814. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93815. goto break1;
  93816. }
  93817. else {
  93818. uval += end - cbits;
  93819. cbits += end;
  93820. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93821. /* didn't find stop bit yet, have to keep going... */
  93822. }
  93823. }
  93824. /* flush registers and read; bitreader_read_from_client_() does
  93825. * not touch br->consumed_bits at all but we still need to set
  93826. * it in case it fails and we have to return false.
  93827. */
  93828. br->consumed_bits = cbits;
  93829. br->consumed_words = cwords;
  93830. if(!bitreader_read_from_client_(br))
  93831. return false;
  93832. cwords = br->consumed_words;
  93833. }
  93834. break1:
  93835. /* read binary part */
  93836. FLAC__ASSERT(cwords <= br->words);
  93837. if(bits) {
  93838. while((br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits < bits) {
  93839. /* flush registers and read; bitreader_read_from_client_() does
  93840. * not touch br->consumed_bits at all but we still need to set
  93841. * it in case it fails and we have to return false.
  93842. */
  93843. br->consumed_bits = cbits;
  93844. br->consumed_words = cwords;
  93845. if(!bitreader_read_from_client_(br))
  93846. return false;
  93847. cwords = br->consumed_words;
  93848. }
  93849. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93850. if(cbits) {
  93851. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93852. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  93853. const brword word = br->buffer[cwords];
  93854. if(bits < n) {
  93855. uval <<= bits;
  93856. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-bits);
  93857. cbits += bits;
  93858. goto break2;
  93859. }
  93860. uval <<= n;
  93861. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  93862. bits -= n;
  93863. crc16_update_word_(br, word);
  93864. cwords++;
  93865. cbits = 0;
  93866. 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 */
  93867. uval <<= bits;
  93868. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits));
  93869. cbits = bits;
  93870. }
  93871. goto break2;
  93872. }
  93873. else {
  93874. FLAC__ASSERT(bits < FLAC__BITS_PER_WORD);
  93875. uval <<= bits;
  93876. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  93877. cbits = bits;
  93878. goto break2;
  93879. }
  93880. }
  93881. else {
  93882. /* in this case we're starting our read at a partial tail word;
  93883. * the reader has guaranteed that we have at least 'bits' bits
  93884. * available to read, which makes this case simpler.
  93885. */
  93886. uval <<= bits;
  93887. if(cbits) {
  93888. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93889. FLAC__ASSERT(cbits + bits <= br->bytes*8);
  93890. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-bits);
  93891. cbits += bits;
  93892. goto break2;
  93893. }
  93894. else {
  93895. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  93896. cbits += bits;
  93897. goto break2;
  93898. }
  93899. }
  93900. }
  93901. break2:
  93902. /* compose the value */
  93903. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  93904. /* are we done? */
  93905. --nvals;
  93906. if(nvals == 0) {
  93907. br->consumed_bits = cbits;
  93908. br->consumed_words = cwords;
  93909. return true;
  93910. }
  93911. uval = 0;
  93912. ++vals;
  93913. }
  93914. }
  93915. #else
  93916. {
  93917. unsigned i;
  93918. unsigned uval = 0;
  93919. /* try and get br->consumed_words and br->consumed_bits into register;
  93920. * must remember to flush them back to *br before calling other
  93921. * bitwriter functions that use them, and before returning */
  93922. register unsigned cwords;
  93923. register unsigned cbits;
  93924. unsigned ucbits; /* keep track of the number of unconsumed bits in the buffer */
  93925. FLAC__ASSERT(0 != br);
  93926. FLAC__ASSERT(0 != br->buffer);
  93927. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93928. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93929. FLAC__ASSERT(parameter < 32);
  93930. /* 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 */
  93931. if(nvals == 0)
  93932. return true;
  93933. cbits = br->consumed_bits;
  93934. cwords = br->consumed_words;
  93935. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  93936. while(1) {
  93937. /* read unary part */
  93938. while(1) {
  93939. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93940. brword b = br->buffer[cwords] << cbits;
  93941. if(b) {
  93942. #if 0 /* is not discernably faster... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32 && defined __GNUC__
  93943. asm volatile (
  93944. "bsrl %1, %0;"
  93945. "notl %0;"
  93946. "andl $31, %0;"
  93947. : "=r"(i)
  93948. : "r"(b)
  93949. );
  93950. #else
  93951. i = COUNT_ZERO_MSBS(b);
  93952. #endif
  93953. uval += i;
  93954. cbits += i;
  93955. cbits++; /* skip over stop bit */
  93956. if(cbits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(cbits == FLAC__BITS_PER_WORD) */
  93957. crc16_update_word_(br, br->buffer[cwords]);
  93958. cwords++;
  93959. cbits = 0;
  93960. }
  93961. goto break1;
  93962. }
  93963. else {
  93964. uval += FLAC__BITS_PER_WORD - cbits;
  93965. crc16_update_word_(br, br->buffer[cwords]);
  93966. cwords++;
  93967. cbits = 0;
  93968. /* didn't find stop bit yet, have to keep going... */
  93969. }
  93970. }
  93971. /* at this point we've eaten up all the whole words; have to try
  93972. * reading through any tail bytes before calling the read callback.
  93973. * this is a repeat of the above logic adjusted for the fact we
  93974. * don't have a whole word. note though if the client is feeding
  93975. * us data a byte at a time (unlikely), br->consumed_bits may not
  93976. * be zero.
  93977. */
  93978. if(br->bytes) {
  93979. const unsigned end = br->bytes * 8;
  93980. brword b = (br->buffer[cwords] & ~(FLAC__WORD_ALL_ONES >> end)) << cbits;
  93981. if(b) {
  93982. i = COUNT_ZERO_MSBS(b);
  93983. uval += i;
  93984. cbits += i;
  93985. cbits++; /* skip over stop bit */
  93986. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93987. goto break1;
  93988. }
  93989. else {
  93990. uval += end - cbits;
  93991. cbits += end;
  93992. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93993. /* didn't find stop bit yet, have to keep going... */
  93994. }
  93995. }
  93996. /* flush registers and read; bitreader_read_from_client_() does
  93997. * not touch br->consumed_bits at all but we still need to set
  93998. * it in case it fails and we have to return false.
  93999. */
  94000. br->consumed_bits = cbits;
  94001. br->consumed_words = cwords;
  94002. if(!bitreader_read_from_client_(br))
  94003. return false;
  94004. cwords = br->consumed_words;
  94005. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits + uval;
  94006. /* + uval to offset our count by the # of unary bits already
  94007. * consumed before the read, because we will add these back
  94008. * in all at once at break1
  94009. */
  94010. }
  94011. break1:
  94012. ucbits -= uval;
  94013. ucbits--; /* account for stop bit */
  94014. /* read binary part */
  94015. FLAC__ASSERT(cwords <= br->words);
  94016. if(parameter) {
  94017. while(ucbits < parameter) {
  94018. /* flush registers and read; bitreader_read_from_client_() does
  94019. * not touch br->consumed_bits at all but we still need to set
  94020. * it in case it fails and we have to return false.
  94021. */
  94022. br->consumed_bits = cbits;
  94023. br->consumed_words = cwords;
  94024. if(!bitreader_read_from_client_(br))
  94025. return false;
  94026. cwords = br->consumed_words;
  94027. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  94028. }
  94029. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  94030. if(cbits) {
  94031. /* this also works when consumed_bits==0, it's just slower than necessary for that case */
  94032. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  94033. const brword word = br->buffer[cwords];
  94034. if(parameter < n) {
  94035. uval <<= parameter;
  94036. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-parameter);
  94037. cbits += parameter;
  94038. }
  94039. else {
  94040. uval <<= n;
  94041. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  94042. crc16_update_word_(br, word);
  94043. cwords++;
  94044. cbits = parameter - n;
  94045. 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 */
  94046. uval <<= cbits;
  94047. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits));
  94048. }
  94049. }
  94050. }
  94051. else {
  94052. cbits = parameter;
  94053. uval <<= parameter;
  94054. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  94055. }
  94056. }
  94057. else {
  94058. /* in this case we're starting our read at a partial tail word;
  94059. * the reader has guaranteed that we have at least 'parameter'
  94060. * bits available to read, which makes this case simpler.
  94061. */
  94062. uval <<= parameter;
  94063. if(cbits) {
  94064. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  94065. FLAC__ASSERT(cbits + parameter <= br->bytes*8);
  94066. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-parameter);
  94067. cbits += parameter;
  94068. }
  94069. else {
  94070. cbits = parameter;
  94071. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  94072. }
  94073. }
  94074. }
  94075. ucbits -= parameter;
  94076. /* compose the value */
  94077. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  94078. /* are we done? */
  94079. --nvals;
  94080. if(nvals == 0) {
  94081. br->consumed_bits = cbits;
  94082. br->consumed_words = cwords;
  94083. return true;
  94084. }
  94085. uval = 0;
  94086. ++vals;
  94087. }
  94088. }
  94089. #endif
  94090. #if 0 /* UNUSED */
  94091. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  94092. {
  94093. FLAC__uint32 lsbs = 0, msbs = 0;
  94094. unsigned bit, uval, k;
  94095. FLAC__ASSERT(0 != br);
  94096. FLAC__ASSERT(0 != br->buffer);
  94097. k = FLAC__bitmath_ilog2(parameter);
  94098. /* read the unary MSBs and end bit */
  94099. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  94100. return false;
  94101. /* read the binary LSBs */
  94102. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  94103. return false;
  94104. if(parameter == 1u<<k) {
  94105. /* compose the value */
  94106. uval = (msbs << k) | lsbs;
  94107. }
  94108. else {
  94109. unsigned d = (1 << (k+1)) - parameter;
  94110. if(lsbs >= d) {
  94111. if(!FLAC__bitreader_read_bit(br, &bit))
  94112. return false;
  94113. lsbs <<= 1;
  94114. lsbs |= bit;
  94115. lsbs -= d;
  94116. }
  94117. /* compose the value */
  94118. uval = msbs * parameter + lsbs;
  94119. }
  94120. /* unfold unsigned to signed */
  94121. if(uval & 1)
  94122. *val = -((int)(uval >> 1)) - 1;
  94123. else
  94124. *val = (int)(uval >> 1);
  94125. return true;
  94126. }
  94127. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter)
  94128. {
  94129. FLAC__uint32 lsbs, msbs = 0;
  94130. unsigned bit, k;
  94131. FLAC__ASSERT(0 != br);
  94132. FLAC__ASSERT(0 != br->buffer);
  94133. k = FLAC__bitmath_ilog2(parameter);
  94134. /* read the unary MSBs and end bit */
  94135. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  94136. return false;
  94137. /* read the binary LSBs */
  94138. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  94139. return false;
  94140. if(parameter == 1u<<k) {
  94141. /* compose the value */
  94142. *val = (msbs << k) | lsbs;
  94143. }
  94144. else {
  94145. unsigned d = (1 << (k+1)) - parameter;
  94146. if(lsbs >= d) {
  94147. if(!FLAC__bitreader_read_bit(br, &bit))
  94148. return false;
  94149. lsbs <<= 1;
  94150. lsbs |= bit;
  94151. lsbs -= d;
  94152. }
  94153. /* compose the value */
  94154. *val = msbs * parameter + lsbs;
  94155. }
  94156. return true;
  94157. }
  94158. #endif /* UNUSED */
  94159. /* on return, if *val == 0xffffffff then the utf-8 sequence was invalid, but the return value will be true */
  94160. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen)
  94161. {
  94162. FLAC__uint32 v = 0;
  94163. FLAC__uint32 x;
  94164. unsigned i;
  94165. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94166. return false;
  94167. if(raw)
  94168. raw[(*rawlen)++] = (FLAC__byte)x;
  94169. if(!(x & 0x80)) { /* 0xxxxxxx */
  94170. v = x;
  94171. i = 0;
  94172. }
  94173. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  94174. v = x & 0x1F;
  94175. i = 1;
  94176. }
  94177. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  94178. v = x & 0x0F;
  94179. i = 2;
  94180. }
  94181. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  94182. v = x & 0x07;
  94183. i = 3;
  94184. }
  94185. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  94186. v = x & 0x03;
  94187. i = 4;
  94188. }
  94189. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  94190. v = x & 0x01;
  94191. i = 5;
  94192. }
  94193. else {
  94194. *val = 0xffffffff;
  94195. return true;
  94196. }
  94197. for( ; i; i--) {
  94198. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94199. return false;
  94200. if(raw)
  94201. raw[(*rawlen)++] = (FLAC__byte)x;
  94202. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  94203. *val = 0xffffffff;
  94204. return true;
  94205. }
  94206. v <<= 6;
  94207. v |= (x & 0x3F);
  94208. }
  94209. *val = v;
  94210. return true;
  94211. }
  94212. /* on return, if *val == 0xffffffffffffffff then the utf-8 sequence was invalid, but the return value will be true */
  94213. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen)
  94214. {
  94215. FLAC__uint64 v = 0;
  94216. FLAC__uint32 x;
  94217. unsigned i;
  94218. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94219. return false;
  94220. if(raw)
  94221. raw[(*rawlen)++] = (FLAC__byte)x;
  94222. if(!(x & 0x80)) { /* 0xxxxxxx */
  94223. v = x;
  94224. i = 0;
  94225. }
  94226. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  94227. v = x & 0x1F;
  94228. i = 1;
  94229. }
  94230. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  94231. v = x & 0x0F;
  94232. i = 2;
  94233. }
  94234. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  94235. v = x & 0x07;
  94236. i = 3;
  94237. }
  94238. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  94239. v = x & 0x03;
  94240. i = 4;
  94241. }
  94242. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  94243. v = x & 0x01;
  94244. i = 5;
  94245. }
  94246. else if(x & 0xFE && !(x & 0x01)) { /* 11111110 */
  94247. v = 0;
  94248. i = 6;
  94249. }
  94250. else {
  94251. *val = FLAC__U64L(0xffffffffffffffff);
  94252. return true;
  94253. }
  94254. for( ; i; i--) {
  94255. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94256. return false;
  94257. if(raw)
  94258. raw[(*rawlen)++] = (FLAC__byte)x;
  94259. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  94260. *val = FLAC__U64L(0xffffffffffffffff);
  94261. return true;
  94262. }
  94263. v <<= 6;
  94264. v |= (x & 0x3F);
  94265. }
  94266. *val = v;
  94267. return true;
  94268. }
  94269. #endif
  94270. /*** End of inlined file: bitreader.c ***/
  94271. /*** Start of inlined file: bitwriter.c ***/
  94272. /*** Start of inlined file: juce_FlacHeader.h ***/
  94273. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  94274. // tasks..
  94275. #define VERSION "1.2.1"
  94276. #define FLAC__NO_DLL 1
  94277. #if JUCE_MSVC
  94278. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  94279. #endif
  94280. #if JUCE_MAC
  94281. #define FLAC__SYS_DARWIN 1
  94282. #endif
  94283. /*** End of inlined file: juce_FlacHeader.h ***/
  94284. #if JUCE_USE_FLAC
  94285. #if HAVE_CONFIG_H
  94286. # include <config.h>
  94287. #endif
  94288. #include <stdlib.h> /* for malloc() */
  94289. #include <string.h> /* for memcpy(), memset() */
  94290. #ifdef _MSC_VER
  94291. #include <winsock.h> /* for ntohl() */
  94292. #elif defined FLAC__SYS_DARWIN
  94293. #include <machine/endian.h> /* for ntohl() */
  94294. #elif defined __MINGW32__
  94295. #include <winsock.h> /* for ntohl() */
  94296. #else
  94297. #include <netinet/in.h> /* for ntohl() */
  94298. #endif
  94299. #if 0 /* UNUSED */
  94300. #endif
  94301. /*** Start of inlined file: bitwriter.h ***/
  94302. #ifndef FLAC__PRIVATE__BITWRITER_H
  94303. #define FLAC__PRIVATE__BITWRITER_H
  94304. #include <stdio.h> /* for FILE */
  94305. /*
  94306. * opaque structure definition
  94307. */
  94308. struct FLAC__BitWriter;
  94309. typedef struct FLAC__BitWriter FLAC__BitWriter;
  94310. /*
  94311. * construction, deletion, initialization, etc functions
  94312. */
  94313. FLAC__BitWriter *FLAC__bitwriter_new(void);
  94314. void FLAC__bitwriter_delete(FLAC__BitWriter *bw);
  94315. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw);
  94316. void FLAC__bitwriter_free(FLAC__BitWriter *bw); /* does not 'free(buffer)' */
  94317. void FLAC__bitwriter_clear(FLAC__BitWriter *bw);
  94318. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out);
  94319. /*
  94320. * CRC functions
  94321. *
  94322. * non-const *bw because they have to cal FLAC__bitwriter_get_buffer()
  94323. */
  94324. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc);
  94325. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc);
  94326. /*
  94327. * info functions
  94328. */
  94329. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw);
  94330. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw); /* can be called anytime, returns total # of bits unconsumed */
  94331. /*
  94332. * direct buffer access
  94333. *
  94334. * there may be no calls on the bitwriter between get and release.
  94335. * the bitwriter continues to own the returned buffer.
  94336. * before get, bitwriter MUST be byte aligned: check with FLAC__bitwriter_is_byte_aligned()
  94337. */
  94338. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes);
  94339. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw);
  94340. /*
  94341. * write functions
  94342. */
  94343. FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits);
  94344. FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits);
  94345. FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits);
  94346. FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits);
  94347. FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val); /*only for bits=32*/
  94348. FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals);
  94349. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val);
  94350. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter);
  94351. #if 0 /* UNUSED */
  94352. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter);
  94353. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned val, unsigned parameter);
  94354. #endif
  94355. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter);
  94356. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter);
  94357. #if 0 /* UNUSED */
  94358. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter);
  94359. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned val, unsigned parameter);
  94360. #endif
  94361. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val);
  94362. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val);
  94363. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw);
  94364. #endif
  94365. /*** End of inlined file: bitwriter.h ***/
  94366. /*** Start of inlined file: alloc.h ***/
  94367. #ifndef FLAC__SHARE__ALLOC_H
  94368. #define FLAC__SHARE__ALLOC_H
  94369. #if HAVE_CONFIG_H
  94370. # include <config.h>
  94371. #endif
  94372. /* WATCHOUT: for c++ you may have to #define __STDC_LIMIT_MACROS 1 real early
  94373. * before #including this file, otherwise SIZE_MAX might not be defined
  94374. */
  94375. #include <limits.h> /* for SIZE_MAX */
  94376. #if !defined _MSC_VER && !defined __MINGW32__ && !defined __EMX__
  94377. #include <stdint.h> /* for SIZE_MAX in case limits.h didn't get it */
  94378. #endif
  94379. #include <stdlib.h> /* for size_t, malloc(), etc */
  94380. #ifndef SIZE_MAX
  94381. # ifndef SIZE_T_MAX
  94382. # ifdef _MSC_VER
  94383. # define SIZE_T_MAX UINT_MAX
  94384. # else
  94385. # error
  94386. # endif
  94387. # endif
  94388. # define SIZE_MAX SIZE_T_MAX
  94389. #endif
  94390. #ifndef FLaC__INLINE
  94391. #define FLaC__INLINE
  94392. #endif
  94393. /* avoid malloc()ing 0 bytes, see:
  94394. * https://www.securecoding.cert.org/confluence/display/seccode/MEM04-A.+Do+not+make+assumptions+about+the+result+of+allocating+0+bytes?focusedCommentId=5407003
  94395. */
  94396. static FLaC__INLINE void *safe_malloc_(size_t size)
  94397. {
  94398. /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94399. if(!size)
  94400. size++;
  94401. return malloc(size);
  94402. }
  94403. static FLaC__INLINE void *safe_calloc_(size_t nmemb, size_t size)
  94404. {
  94405. if(!nmemb || !size)
  94406. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94407. return calloc(nmemb, size);
  94408. }
  94409. /*@@@@ there's probably a better way to prevent overflows when allocating untrusted sums but this works for now */
  94410. static FLaC__INLINE void *safe_malloc_add_2op_(size_t size1, size_t size2)
  94411. {
  94412. size2 += size1;
  94413. if(size2 < size1)
  94414. return 0;
  94415. return safe_malloc_(size2);
  94416. }
  94417. static FLaC__INLINE void *safe_malloc_add_3op_(size_t size1, size_t size2, size_t size3)
  94418. {
  94419. size2 += size1;
  94420. if(size2 < size1)
  94421. return 0;
  94422. size3 += size2;
  94423. if(size3 < size2)
  94424. return 0;
  94425. return safe_malloc_(size3);
  94426. }
  94427. static FLaC__INLINE void *safe_malloc_add_4op_(size_t size1, size_t size2, size_t size3, size_t size4)
  94428. {
  94429. size2 += size1;
  94430. if(size2 < size1)
  94431. return 0;
  94432. size3 += size2;
  94433. if(size3 < size2)
  94434. return 0;
  94435. size4 += size3;
  94436. if(size4 < size3)
  94437. return 0;
  94438. return safe_malloc_(size4);
  94439. }
  94440. static FLaC__INLINE void *safe_malloc_mul_2op_(size_t size1, size_t size2)
  94441. #if 0
  94442. needs support for cases where sizeof(size_t) != 4
  94443. {
  94444. /* could be faster #ifdef'ing off SIZEOF_SIZE_T */
  94445. if(sizeof(size_t) == 4) {
  94446. if ((double)size1 * (double)size2 < 4294967296.0)
  94447. return malloc(size1*size2);
  94448. }
  94449. return 0;
  94450. }
  94451. #else
  94452. /* better? */
  94453. {
  94454. if(!size1 || !size2)
  94455. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94456. if(size1 > SIZE_MAX / size2)
  94457. return 0;
  94458. return malloc(size1*size2);
  94459. }
  94460. #endif
  94461. static FLaC__INLINE void *safe_malloc_mul_3op_(size_t size1, size_t size2, size_t size3)
  94462. {
  94463. if(!size1 || !size2 || !size3)
  94464. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94465. if(size1 > SIZE_MAX / size2)
  94466. return 0;
  94467. size1 *= size2;
  94468. if(size1 > SIZE_MAX / size3)
  94469. return 0;
  94470. return malloc(size1*size3);
  94471. }
  94472. /* size1*size2 + size3 */
  94473. static FLaC__INLINE void *safe_malloc_mul2add_(size_t size1, size_t size2, size_t size3)
  94474. {
  94475. if(!size1 || !size2)
  94476. return safe_malloc_(size3);
  94477. if(size1 > SIZE_MAX / size2)
  94478. return 0;
  94479. return safe_malloc_add_2op_(size1*size2, size3);
  94480. }
  94481. /* size1 * (size2 + size3) */
  94482. static FLaC__INLINE void *safe_malloc_muladd2_(size_t size1, size_t size2, size_t size3)
  94483. {
  94484. if(!size1 || (!size2 && !size3))
  94485. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94486. size2 += size3;
  94487. if(size2 < size3)
  94488. return 0;
  94489. return safe_malloc_mul_2op_(size1, size2);
  94490. }
  94491. static FLaC__INLINE void *safe_realloc_add_2op_(void *ptr, size_t size1, size_t size2)
  94492. {
  94493. size2 += size1;
  94494. if(size2 < size1)
  94495. return 0;
  94496. return realloc(ptr, size2);
  94497. }
  94498. static FLaC__INLINE void *safe_realloc_add_3op_(void *ptr, size_t size1, size_t size2, size_t size3)
  94499. {
  94500. size2 += size1;
  94501. if(size2 < size1)
  94502. return 0;
  94503. size3 += size2;
  94504. if(size3 < size2)
  94505. return 0;
  94506. return realloc(ptr, size3);
  94507. }
  94508. static FLaC__INLINE void *safe_realloc_add_4op_(void *ptr, size_t size1, size_t size2, size_t size3, size_t size4)
  94509. {
  94510. size2 += size1;
  94511. if(size2 < size1)
  94512. return 0;
  94513. size3 += size2;
  94514. if(size3 < size2)
  94515. return 0;
  94516. size4 += size3;
  94517. if(size4 < size3)
  94518. return 0;
  94519. return realloc(ptr, size4);
  94520. }
  94521. static FLaC__INLINE void *safe_realloc_mul_2op_(void *ptr, size_t size1, size_t size2)
  94522. {
  94523. if(!size1 || !size2)
  94524. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  94525. if(size1 > SIZE_MAX / size2)
  94526. return 0;
  94527. return realloc(ptr, size1*size2);
  94528. }
  94529. /* size1 * (size2 + size3) */
  94530. static FLaC__INLINE void *safe_realloc_muladd2_(void *ptr, size_t size1, size_t size2, size_t size3)
  94531. {
  94532. if(!size1 || (!size2 && !size3))
  94533. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  94534. size2 += size3;
  94535. if(size2 < size3)
  94536. return 0;
  94537. return safe_realloc_mul_2op_(ptr, size1, size2);
  94538. }
  94539. #endif
  94540. /*** End of inlined file: alloc.h ***/
  94541. /* Things should be fastest when this matches the machine word size */
  94542. /* WATCHOUT: if you change this you must also change the following #defines down to SWAP_BE_WORD_TO_HOST below to match */
  94543. /* WATCHOUT: there are a few places where the code will not work unless bwword is >= 32 bits wide */
  94544. typedef FLAC__uint32 bwword;
  94545. #define FLAC__BYTES_PER_WORD 4
  94546. #define FLAC__BITS_PER_WORD 32
  94547. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  94548. /* SWAP_BE_WORD_TO_HOST swaps bytes in a bwword (which is always big-endian) if necessary to match host byte order */
  94549. #if WORDS_BIGENDIAN
  94550. #define SWAP_BE_WORD_TO_HOST(x) (x)
  94551. #else
  94552. #ifdef _MSC_VER
  94553. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  94554. #else
  94555. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  94556. #endif
  94557. #endif
  94558. /*
  94559. * The default capacity here doesn't matter too much. The buffer always grows
  94560. * to hold whatever is written to it. Usually the encoder will stop adding at
  94561. * a frame or metadata block, then write that out and clear the buffer for the
  94562. * next one.
  94563. */
  94564. static const unsigned FLAC__BITWRITER_DEFAULT_CAPACITY = 32768u / sizeof(bwword); /* size in words */
  94565. /* When growing, increment 4K at a time */
  94566. static const unsigned FLAC__BITWRITER_DEFAULT_INCREMENT = 4096u / sizeof(bwword); /* size in words */
  94567. #define FLAC__WORDS_TO_BITS(words) ((words) * FLAC__BITS_PER_WORD)
  94568. #define FLAC__TOTAL_BITS(bw) (FLAC__WORDS_TO_BITS((bw)->words) + (bw)->bits)
  94569. #ifdef min
  94570. #undef min
  94571. #endif
  94572. #define min(x,y) ((x)<(y)?(x):(y))
  94573. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  94574. #ifdef _MSC_VER
  94575. #define FLAC__U64L(x) x
  94576. #else
  94577. #define FLAC__U64L(x) x##LLU
  94578. #endif
  94579. #ifndef FLaC__INLINE
  94580. #define FLaC__INLINE
  94581. #endif
  94582. struct FLAC__BitWriter {
  94583. bwword *buffer;
  94584. bwword accum; /* accumulator; bits are right-justified; when full, accum is appended to buffer */
  94585. unsigned capacity; /* capacity of buffer in words */
  94586. unsigned words; /* # of complete words in buffer */
  94587. unsigned bits; /* # of used bits in accum */
  94588. };
  94589. /* * WATCHOUT: The current implementation only grows the buffer. */
  94590. static FLAC__bool bitwriter_grow_(FLAC__BitWriter *bw, unsigned bits_to_add)
  94591. {
  94592. unsigned new_capacity;
  94593. bwword *new_buffer;
  94594. FLAC__ASSERT(0 != bw);
  94595. FLAC__ASSERT(0 != bw->buffer);
  94596. /* calculate total words needed to store 'bits_to_add' additional bits */
  94597. new_capacity = bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD);
  94598. /* it's possible (due to pessimism in the growth estimation that
  94599. * leads to this call) that we don't actually need to grow
  94600. */
  94601. if(bw->capacity >= new_capacity)
  94602. return true;
  94603. /* round up capacity increase to the nearest FLAC__BITWRITER_DEFAULT_INCREMENT */
  94604. if((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT)
  94605. new_capacity += FLAC__BITWRITER_DEFAULT_INCREMENT - ((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  94606. /* make sure we got everything right */
  94607. FLAC__ASSERT(0 == (new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  94608. FLAC__ASSERT(new_capacity > bw->capacity);
  94609. FLAC__ASSERT(new_capacity >= bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD));
  94610. new_buffer = (bwword*)safe_realloc_mul_2op_(bw->buffer, sizeof(bwword), /*times*/new_capacity);
  94611. if(new_buffer == 0)
  94612. return false;
  94613. bw->buffer = new_buffer;
  94614. bw->capacity = new_capacity;
  94615. return true;
  94616. }
  94617. /***********************************************************************
  94618. *
  94619. * Class constructor/destructor
  94620. *
  94621. ***********************************************************************/
  94622. FLAC__BitWriter *FLAC__bitwriter_new(void)
  94623. {
  94624. FLAC__BitWriter *bw = (FLAC__BitWriter*)calloc(1, sizeof(FLAC__BitWriter));
  94625. /* note that calloc() sets all members to 0 for us */
  94626. return bw;
  94627. }
  94628. void FLAC__bitwriter_delete(FLAC__BitWriter *bw)
  94629. {
  94630. FLAC__ASSERT(0 != bw);
  94631. FLAC__bitwriter_free(bw);
  94632. free(bw);
  94633. }
  94634. /***********************************************************************
  94635. *
  94636. * Public class methods
  94637. *
  94638. ***********************************************************************/
  94639. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw)
  94640. {
  94641. FLAC__ASSERT(0 != bw);
  94642. bw->words = bw->bits = 0;
  94643. bw->capacity = FLAC__BITWRITER_DEFAULT_CAPACITY;
  94644. bw->buffer = (bwword*)malloc(sizeof(bwword) * bw->capacity);
  94645. if(bw->buffer == 0)
  94646. return false;
  94647. return true;
  94648. }
  94649. void FLAC__bitwriter_free(FLAC__BitWriter *bw)
  94650. {
  94651. FLAC__ASSERT(0 != bw);
  94652. if(0 != bw->buffer)
  94653. free(bw->buffer);
  94654. bw->buffer = 0;
  94655. bw->capacity = 0;
  94656. bw->words = bw->bits = 0;
  94657. }
  94658. void FLAC__bitwriter_clear(FLAC__BitWriter *bw)
  94659. {
  94660. bw->words = bw->bits = 0;
  94661. }
  94662. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out)
  94663. {
  94664. unsigned i, j;
  94665. if(bw == 0) {
  94666. fprintf(out, "bitwriter is NULL\n");
  94667. }
  94668. else {
  94669. fprintf(out, "bitwriter: capacity=%u words=%u bits=%u total_bits=%u\n", bw->capacity, bw->words, bw->bits, FLAC__TOTAL_BITS(bw));
  94670. for(i = 0; i < bw->words; i++) {
  94671. fprintf(out, "%08X: ", i);
  94672. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  94673. fprintf(out, "%01u", bw->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  94674. fprintf(out, "\n");
  94675. }
  94676. if(bw->bits > 0) {
  94677. fprintf(out, "%08X: ", i);
  94678. for(j = 0; j < bw->bits; j++)
  94679. fprintf(out, "%01u", bw->accum & (1 << (bw->bits-j-1)) ? 1:0);
  94680. fprintf(out, "\n");
  94681. }
  94682. }
  94683. }
  94684. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc)
  94685. {
  94686. const FLAC__byte *buffer;
  94687. size_t bytes;
  94688. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  94689. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  94690. return false;
  94691. *crc = (FLAC__uint16)FLAC__crc16(buffer, bytes);
  94692. FLAC__bitwriter_release_buffer(bw);
  94693. return true;
  94694. }
  94695. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc)
  94696. {
  94697. const FLAC__byte *buffer;
  94698. size_t bytes;
  94699. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  94700. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  94701. return false;
  94702. *crc = FLAC__crc8(buffer, bytes);
  94703. FLAC__bitwriter_release_buffer(bw);
  94704. return true;
  94705. }
  94706. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw)
  94707. {
  94708. return ((bw->bits & 7) == 0);
  94709. }
  94710. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw)
  94711. {
  94712. return FLAC__TOTAL_BITS(bw);
  94713. }
  94714. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes)
  94715. {
  94716. FLAC__ASSERT((bw->bits & 7) == 0);
  94717. /* double protection */
  94718. if(bw->bits & 7)
  94719. return false;
  94720. /* if we have bits in the accumulator we have to flush those to the buffer first */
  94721. if(bw->bits) {
  94722. FLAC__ASSERT(bw->words <= bw->capacity);
  94723. if(bw->words == bw->capacity && !bitwriter_grow_(bw, FLAC__BITS_PER_WORD))
  94724. return false;
  94725. /* append bits as complete word to buffer, but don't change bw->accum or bw->bits */
  94726. bw->buffer[bw->words] = SWAP_BE_WORD_TO_HOST(bw->accum << (FLAC__BITS_PER_WORD-bw->bits));
  94727. }
  94728. /* now we can just return what we have */
  94729. *buffer = (FLAC__byte*)bw->buffer;
  94730. *bytes = (FLAC__BYTES_PER_WORD * bw->words) + (bw->bits >> 3);
  94731. return true;
  94732. }
  94733. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw)
  94734. {
  94735. /* nothing to do. in the future, strict checking of a 'writer-is-in-
  94736. * get-mode' flag could be added everywhere and then cleared here
  94737. */
  94738. (void)bw;
  94739. }
  94740. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits)
  94741. {
  94742. unsigned n;
  94743. FLAC__ASSERT(0 != bw);
  94744. FLAC__ASSERT(0 != bw->buffer);
  94745. if(bits == 0)
  94746. return true;
  94747. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94748. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  94749. return false;
  94750. /* first part gets to word alignment */
  94751. if(bw->bits) {
  94752. n = min(FLAC__BITS_PER_WORD - bw->bits, bits);
  94753. bw->accum <<= n;
  94754. bits -= n;
  94755. bw->bits += n;
  94756. if(bw->bits == FLAC__BITS_PER_WORD) {
  94757. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94758. bw->bits = 0;
  94759. }
  94760. else
  94761. return true;
  94762. }
  94763. /* do whole words */
  94764. while(bits >= FLAC__BITS_PER_WORD) {
  94765. bw->buffer[bw->words++] = 0;
  94766. bits -= FLAC__BITS_PER_WORD;
  94767. }
  94768. /* do any leftovers */
  94769. if(bits > 0) {
  94770. bw->accum = 0;
  94771. bw->bits = bits;
  94772. }
  94773. return true;
  94774. }
  94775. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits)
  94776. {
  94777. register unsigned left;
  94778. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  94779. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  94780. FLAC__ASSERT(0 != bw);
  94781. FLAC__ASSERT(0 != bw->buffer);
  94782. FLAC__ASSERT(bits <= 32);
  94783. if(bits == 0)
  94784. return true;
  94785. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94786. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  94787. return false;
  94788. left = FLAC__BITS_PER_WORD - bw->bits;
  94789. if(bits < left) {
  94790. bw->accum <<= bits;
  94791. bw->accum |= val;
  94792. bw->bits += bits;
  94793. }
  94794. 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 */
  94795. bw->accum <<= left;
  94796. bw->accum |= val >> (bw->bits = bits - left);
  94797. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94798. bw->accum = val;
  94799. }
  94800. else {
  94801. bw->accum = val;
  94802. bw->bits = 0;
  94803. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(val);
  94804. }
  94805. return true;
  94806. }
  94807. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits)
  94808. {
  94809. /* zero-out unused bits */
  94810. if(bits < 32)
  94811. val &= (~(0xffffffff << bits));
  94812. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  94813. }
  94814. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits)
  94815. {
  94816. /* this could be a little faster but it's not used for much */
  94817. if(bits > 32) {
  94818. return
  94819. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(val>>32), bits-32) &&
  94820. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 32);
  94821. }
  94822. else
  94823. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  94824. }
  94825. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val)
  94826. {
  94827. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  94828. if(!FLAC__bitwriter_write_raw_uint32(bw, val & 0xff, 8))
  94829. return false;
  94830. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>8) & 0xff, 8))
  94831. return false;
  94832. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>16) & 0xff, 8))
  94833. return false;
  94834. if(!FLAC__bitwriter_write_raw_uint32(bw, val>>24, 8))
  94835. return false;
  94836. return true;
  94837. }
  94838. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals)
  94839. {
  94840. unsigned i;
  94841. /* this could be faster but currently we don't need it to be since it's only used for writing metadata */
  94842. for(i = 0; i < nvals; i++) {
  94843. if(!FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(vals[i]), 8))
  94844. return false;
  94845. }
  94846. return true;
  94847. }
  94848. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val)
  94849. {
  94850. if(val < 32)
  94851. return FLAC__bitwriter_write_raw_uint32(bw, 1, ++val);
  94852. else
  94853. return
  94854. FLAC__bitwriter_write_zeroes(bw, val) &&
  94855. FLAC__bitwriter_write_raw_uint32(bw, 1, 1);
  94856. }
  94857. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter)
  94858. {
  94859. FLAC__uint32 uval;
  94860. FLAC__ASSERT(parameter < sizeof(unsigned)*8);
  94861. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  94862. uval = (val<<1) ^ (val>>31);
  94863. return 1 + parameter + (uval >> parameter);
  94864. }
  94865. #if 0 /* UNUSED */
  94866. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter)
  94867. {
  94868. unsigned bits, msbs, uval;
  94869. unsigned k;
  94870. FLAC__ASSERT(parameter > 0);
  94871. /* fold signed to unsigned */
  94872. if(val < 0)
  94873. uval = (unsigned)(((-(++val)) << 1) + 1);
  94874. else
  94875. uval = (unsigned)(val << 1);
  94876. k = FLAC__bitmath_ilog2(parameter);
  94877. if(parameter == 1u<<k) {
  94878. FLAC__ASSERT(k <= 30);
  94879. msbs = uval >> k;
  94880. bits = 1 + k + msbs;
  94881. }
  94882. else {
  94883. unsigned q, r, d;
  94884. d = (1 << (k+1)) - parameter;
  94885. q = uval / parameter;
  94886. r = uval - (q * parameter);
  94887. bits = 1 + q + k;
  94888. if(r >= d)
  94889. bits++;
  94890. }
  94891. return bits;
  94892. }
  94893. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned uval, unsigned parameter)
  94894. {
  94895. unsigned bits, msbs;
  94896. unsigned k;
  94897. FLAC__ASSERT(parameter > 0);
  94898. k = FLAC__bitmath_ilog2(parameter);
  94899. if(parameter == 1u<<k) {
  94900. FLAC__ASSERT(k <= 30);
  94901. msbs = uval >> k;
  94902. bits = 1 + k + msbs;
  94903. }
  94904. else {
  94905. unsigned q, r, d;
  94906. d = (1 << (k+1)) - parameter;
  94907. q = uval / parameter;
  94908. r = uval - (q * parameter);
  94909. bits = 1 + q + k;
  94910. if(r >= d)
  94911. bits++;
  94912. }
  94913. return bits;
  94914. }
  94915. #endif /* UNUSED */
  94916. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter)
  94917. {
  94918. unsigned total_bits, interesting_bits, msbs;
  94919. FLAC__uint32 uval, pattern;
  94920. FLAC__ASSERT(0 != bw);
  94921. FLAC__ASSERT(0 != bw->buffer);
  94922. FLAC__ASSERT(parameter < 8*sizeof(uval));
  94923. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  94924. uval = (val<<1) ^ (val>>31);
  94925. msbs = uval >> parameter;
  94926. interesting_bits = 1 + parameter;
  94927. total_bits = interesting_bits + msbs;
  94928. pattern = 1 << parameter; /* the unary end bit */
  94929. pattern |= (uval & ((1<<parameter)-1)); /* the binary LSBs */
  94930. if(total_bits <= 32)
  94931. return FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits);
  94932. else
  94933. return
  94934. FLAC__bitwriter_write_zeroes(bw, msbs) && /* write the unary MSBs */
  94935. FLAC__bitwriter_write_raw_uint32(bw, pattern, interesting_bits); /* write the unary end bit and binary LSBs */
  94936. }
  94937. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter)
  94938. {
  94939. const FLAC__uint32 mask1 = FLAC__WORD_ALL_ONES << parameter; /* we val|=mask1 to set the stop bit above it... */
  94940. const FLAC__uint32 mask2 = FLAC__WORD_ALL_ONES >> (31-parameter); /* ...then mask off the bits above the stop bit with val&=mask2*/
  94941. FLAC__uint32 uval;
  94942. unsigned left;
  94943. const unsigned lsbits = 1 + parameter;
  94944. unsigned msbits;
  94945. FLAC__ASSERT(0 != bw);
  94946. FLAC__ASSERT(0 != bw->buffer);
  94947. FLAC__ASSERT(parameter < 8*sizeof(bwword)-1);
  94948. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  94949. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  94950. while(nvals) {
  94951. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  94952. uval = (*vals<<1) ^ (*vals>>31);
  94953. msbits = uval >> parameter;
  94954. #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) */
  94955. if(bw->bits && bw->bits + msbits + lsbits <= FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  94956. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  94957. bw->bits = bw->bits + msbits + lsbits;
  94958. uval |= mask1; /* set stop bit */
  94959. uval &= mask2; /* mask off unused top bits */
  94960. /* NOT: bw->accum <<= msbits + lsbits because msbits+lsbits could be 32, then the shift would be a NOP */
  94961. bw->accum <<= msbits;
  94962. bw->accum <<= lsbits;
  94963. bw->accum |= uval;
  94964. if(bw->bits == FLAC__BITS_PER_WORD) {
  94965. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94966. bw->bits = 0;
  94967. /* burying the capacity check down here means we have to grow the buffer a little if there are more vals to do */
  94968. if(bw->capacity <= bw->words && nvals > 1 && !bitwriter_grow_(bw, 1)) {
  94969. FLAC__ASSERT(bw->capacity == bw->words);
  94970. return false;
  94971. }
  94972. }
  94973. }
  94974. else {
  94975. #elif 1 /*@@@@@@ OPT: try this version with MSVC6 to see if better, not much difference for gcc-4 */
  94976. if(bw->bits && bw->bits + msbits + lsbits < FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  94977. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  94978. bw->bits = bw->bits + msbits + lsbits;
  94979. uval |= mask1; /* set stop bit */
  94980. uval &= mask2; /* mask off unused top bits */
  94981. bw->accum <<= msbits + lsbits;
  94982. bw->accum |= uval;
  94983. }
  94984. else {
  94985. #endif
  94986. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+msbits+lsbits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94987. /* OPT: pessimism may cause flurry of false calls to grow_ which eat up all savings before it */
  94988. if(bw->capacity <= bw->words + bw->bits + msbits + 1/*lsbits always fit in 1 bwword*/ && !bitwriter_grow_(bw, msbits+lsbits))
  94989. return false;
  94990. if(msbits) {
  94991. /* first part gets to word alignment */
  94992. if(bw->bits) {
  94993. left = FLAC__BITS_PER_WORD - bw->bits;
  94994. if(msbits < left) {
  94995. bw->accum <<= msbits;
  94996. bw->bits += msbits;
  94997. goto break1;
  94998. }
  94999. else {
  95000. bw->accum <<= left;
  95001. msbits -= left;
  95002. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  95003. bw->bits = 0;
  95004. }
  95005. }
  95006. /* do whole words */
  95007. while(msbits >= FLAC__BITS_PER_WORD) {
  95008. bw->buffer[bw->words++] = 0;
  95009. msbits -= FLAC__BITS_PER_WORD;
  95010. }
  95011. /* do any leftovers */
  95012. if(msbits > 0) {
  95013. bw->accum = 0;
  95014. bw->bits = msbits;
  95015. }
  95016. }
  95017. break1:
  95018. uval |= mask1; /* set stop bit */
  95019. uval &= mask2; /* mask off unused top bits */
  95020. left = FLAC__BITS_PER_WORD - bw->bits;
  95021. if(lsbits < left) {
  95022. bw->accum <<= lsbits;
  95023. bw->accum |= uval;
  95024. bw->bits += lsbits;
  95025. }
  95026. else {
  95027. /* if bw->bits == 0, left==FLAC__BITS_PER_WORD which will always
  95028. * be > lsbits (because of previous assertions) so it would have
  95029. * triggered the (lsbits<left) case above.
  95030. */
  95031. FLAC__ASSERT(bw->bits);
  95032. FLAC__ASSERT(left < FLAC__BITS_PER_WORD);
  95033. bw->accum <<= left;
  95034. bw->accum |= uval >> (bw->bits = lsbits - left);
  95035. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  95036. bw->accum = uval;
  95037. }
  95038. #if 1
  95039. }
  95040. #endif
  95041. vals++;
  95042. nvals--;
  95043. }
  95044. return true;
  95045. }
  95046. #if 0 /* UNUSED */
  95047. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter)
  95048. {
  95049. unsigned total_bits, msbs, uval;
  95050. unsigned k;
  95051. FLAC__ASSERT(0 != bw);
  95052. FLAC__ASSERT(0 != bw->buffer);
  95053. FLAC__ASSERT(parameter > 0);
  95054. /* fold signed to unsigned */
  95055. if(val < 0)
  95056. uval = (unsigned)(((-(++val)) << 1) + 1);
  95057. else
  95058. uval = (unsigned)(val << 1);
  95059. k = FLAC__bitmath_ilog2(parameter);
  95060. if(parameter == 1u<<k) {
  95061. unsigned pattern;
  95062. FLAC__ASSERT(k <= 30);
  95063. msbs = uval >> k;
  95064. total_bits = 1 + k + msbs;
  95065. pattern = 1 << k; /* the unary end bit */
  95066. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  95067. if(total_bits <= 32) {
  95068. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  95069. return false;
  95070. }
  95071. else {
  95072. /* write the unary MSBs */
  95073. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  95074. return false;
  95075. /* write the unary end bit and binary LSBs */
  95076. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  95077. return false;
  95078. }
  95079. }
  95080. else {
  95081. unsigned q, r, d;
  95082. d = (1 << (k+1)) - parameter;
  95083. q = uval / parameter;
  95084. r = uval - (q * parameter);
  95085. /* write the unary MSBs */
  95086. if(!FLAC__bitwriter_write_zeroes(bw, q))
  95087. return false;
  95088. /* write the unary end bit */
  95089. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  95090. return false;
  95091. /* write the binary LSBs */
  95092. if(r >= d) {
  95093. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  95094. return false;
  95095. }
  95096. else {
  95097. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  95098. return false;
  95099. }
  95100. }
  95101. return true;
  95102. }
  95103. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned uval, unsigned parameter)
  95104. {
  95105. unsigned total_bits, msbs;
  95106. unsigned k;
  95107. FLAC__ASSERT(0 != bw);
  95108. FLAC__ASSERT(0 != bw->buffer);
  95109. FLAC__ASSERT(parameter > 0);
  95110. k = FLAC__bitmath_ilog2(parameter);
  95111. if(parameter == 1u<<k) {
  95112. unsigned pattern;
  95113. FLAC__ASSERT(k <= 30);
  95114. msbs = uval >> k;
  95115. total_bits = 1 + k + msbs;
  95116. pattern = 1 << k; /* the unary end bit */
  95117. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  95118. if(total_bits <= 32) {
  95119. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  95120. return false;
  95121. }
  95122. else {
  95123. /* write the unary MSBs */
  95124. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  95125. return false;
  95126. /* write the unary end bit and binary LSBs */
  95127. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  95128. return false;
  95129. }
  95130. }
  95131. else {
  95132. unsigned q, r, d;
  95133. d = (1 << (k+1)) - parameter;
  95134. q = uval / parameter;
  95135. r = uval - (q * parameter);
  95136. /* write the unary MSBs */
  95137. if(!FLAC__bitwriter_write_zeroes(bw, q))
  95138. return false;
  95139. /* write the unary end bit */
  95140. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  95141. return false;
  95142. /* write the binary LSBs */
  95143. if(r >= d) {
  95144. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  95145. return false;
  95146. }
  95147. else {
  95148. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  95149. return false;
  95150. }
  95151. }
  95152. return true;
  95153. }
  95154. #endif /* UNUSED */
  95155. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val)
  95156. {
  95157. FLAC__bool ok = 1;
  95158. FLAC__ASSERT(0 != bw);
  95159. FLAC__ASSERT(0 != bw->buffer);
  95160. FLAC__ASSERT(!(val & 0x80000000)); /* this version only handles 31 bits */
  95161. if(val < 0x80) {
  95162. return FLAC__bitwriter_write_raw_uint32(bw, val, 8);
  95163. }
  95164. else if(val < 0x800) {
  95165. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (val>>6), 8);
  95166. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95167. }
  95168. else if(val < 0x10000) {
  95169. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (val>>12), 8);
  95170. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95171. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95172. }
  95173. else if(val < 0x200000) {
  95174. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (val>>18), 8);
  95175. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  95176. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95177. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95178. }
  95179. else if(val < 0x4000000) {
  95180. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (val>>24), 8);
  95181. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  95182. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  95183. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95184. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95185. }
  95186. else {
  95187. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (val>>30), 8);
  95188. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>24)&0x3F), 8);
  95189. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  95190. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  95191. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95192. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95193. }
  95194. return ok;
  95195. }
  95196. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val)
  95197. {
  95198. FLAC__bool ok = 1;
  95199. FLAC__ASSERT(0 != bw);
  95200. FLAC__ASSERT(0 != bw->buffer);
  95201. FLAC__ASSERT(!(val & FLAC__U64L(0xFFFFFFF000000000))); /* this version only handles 36 bits */
  95202. if(val < 0x80) {
  95203. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 8);
  95204. }
  95205. else if(val < 0x800) {
  95206. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (FLAC__uint32)(val>>6), 8);
  95207. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95208. }
  95209. else if(val < 0x10000) {
  95210. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (FLAC__uint32)(val>>12), 8);
  95211. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95212. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95213. }
  95214. else if(val < 0x200000) {
  95215. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (FLAC__uint32)(val>>18), 8);
  95216. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95217. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95218. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95219. }
  95220. else if(val < 0x4000000) {
  95221. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (FLAC__uint32)(val>>24), 8);
  95222. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  95223. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95224. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95225. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95226. }
  95227. else if(val < 0x80000000) {
  95228. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (FLAC__uint32)(val>>30), 8);
  95229. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  95230. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  95231. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95232. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95233. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95234. }
  95235. else {
  95236. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFE, 8);
  95237. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>30)&0x3F), 8);
  95238. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  95239. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  95240. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95241. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95242. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95243. }
  95244. return ok;
  95245. }
  95246. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw)
  95247. {
  95248. /* 0-pad to byte boundary */
  95249. if(bw->bits & 7u)
  95250. return FLAC__bitwriter_write_zeroes(bw, 8 - (bw->bits & 7u));
  95251. else
  95252. return true;
  95253. }
  95254. #endif
  95255. /*** End of inlined file: bitwriter.c ***/
  95256. /*** Start of inlined file: cpu.c ***/
  95257. /*** Start of inlined file: juce_FlacHeader.h ***/
  95258. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95259. // tasks..
  95260. #define VERSION "1.2.1"
  95261. #define FLAC__NO_DLL 1
  95262. #if JUCE_MSVC
  95263. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95264. #endif
  95265. #if JUCE_MAC
  95266. #define FLAC__SYS_DARWIN 1
  95267. #endif
  95268. /*** End of inlined file: juce_FlacHeader.h ***/
  95269. #if JUCE_USE_FLAC
  95270. #if HAVE_CONFIG_H
  95271. # include <config.h>
  95272. #endif
  95273. #include <stdlib.h>
  95274. #include <stdio.h>
  95275. #if defined FLAC__CPU_IA32
  95276. # include <signal.h>
  95277. #elif defined FLAC__CPU_PPC
  95278. # if !defined FLAC__NO_ASM
  95279. # if defined FLAC__SYS_DARWIN
  95280. # include <sys/sysctl.h>
  95281. # include <mach/mach.h>
  95282. # include <mach/mach_host.h>
  95283. # include <mach/host_info.h>
  95284. # include <mach/machine.h>
  95285. # ifndef CPU_SUBTYPE_POWERPC_970
  95286. # define CPU_SUBTYPE_POWERPC_970 ((cpu_subtype_t) 100)
  95287. # endif
  95288. # else /* FLAC__SYS_DARWIN */
  95289. # include <signal.h>
  95290. # include <setjmp.h>
  95291. static sigjmp_buf jmpbuf;
  95292. static volatile sig_atomic_t canjump = 0;
  95293. static void sigill_handler (int sig)
  95294. {
  95295. if (!canjump) {
  95296. signal (sig, SIG_DFL);
  95297. raise (sig);
  95298. }
  95299. canjump = 0;
  95300. siglongjmp (jmpbuf, 1);
  95301. }
  95302. # endif /* FLAC__SYS_DARWIN */
  95303. # endif /* FLAC__NO_ASM */
  95304. #endif /* FLAC__CPU_PPC */
  95305. #if defined (__NetBSD__) || defined(__OpenBSD__)
  95306. #include <sys/param.h>
  95307. #include <sys/sysctl.h>
  95308. #include <machine/cpu.h>
  95309. #endif
  95310. #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
  95311. #include <sys/types.h>
  95312. #include <sys/sysctl.h>
  95313. #endif
  95314. #if defined(__APPLE__)
  95315. /* how to get sysctlbyname()? */
  95316. #endif
  95317. /* these are flags in EDX of CPUID AX=00000001 */
  95318. static const unsigned FLAC__CPUINFO_IA32_CPUID_CMOV = 0x00008000;
  95319. static const unsigned FLAC__CPUINFO_IA32_CPUID_MMX = 0x00800000;
  95320. static const unsigned FLAC__CPUINFO_IA32_CPUID_FXSR = 0x01000000;
  95321. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE = 0x02000000;
  95322. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE2 = 0x04000000;
  95323. /* these are flags in ECX of CPUID AX=00000001 */
  95324. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE3 = 0x00000001;
  95325. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSSE3 = 0x00000200;
  95326. /* these are flags in EDX of CPUID AX=80000001 */
  95327. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW = 0x80000000;
  95328. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW = 0x40000000;
  95329. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX = 0x00400000;
  95330. /*
  95331. * Extra stuff needed for detection of OS support for SSE on IA-32
  95332. */
  95333. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM && !defined FLAC__NO_SSE_OS && !defined FLAC__SSE_OS
  95334. # if defined(__linux__)
  95335. /*
  95336. * If the OS doesn't support SSE, we will get here with a SIGILL. We
  95337. * modify the return address to jump over the offending SSE instruction
  95338. * and also the operation following it that indicates the instruction
  95339. * executed successfully. In this way we use no global variables and
  95340. * stay thread-safe.
  95341. *
  95342. * 3 + 3 + 6:
  95343. * 3 bytes for "xorps xmm0,xmm0"
  95344. * 3 bytes for estimate of how long the follwing "inc var" instruction is
  95345. * 6 bytes extra in case our estimate is wrong
  95346. * 12 bytes puts us in the NOP "landing zone"
  95347. */
  95348. # undef USE_OBSOLETE_SIGCONTEXT_FLAVOR /* #define this to use the older signal handler method */
  95349. # ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  95350. static void sigill_handler_sse_os(int signal, struct sigcontext sc)
  95351. {
  95352. (void)signal;
  95353. sc.eip += 3 + 3 + 6;
  95354. }
  95355. # else
  95356. # include <sys/ucontext.h>
  95357. static void sigill_handler_sse_os(int signal, siginfo_t *si, void *uc)
  95358. {
  95359. (void)signal, (void)si;
  95360. ((ucontext_t*)uc)->uc_mcontext.gregs[14/*REG_EIP*/] += 3 + 3 + 6;
  95361. }
  95362. # endif
  95363. # elif defined(_MSC_VER)
  95364. # include <windows.h>
  95365. # undef USE_TRY_CATCH_FLAVOR /* #define this to use the try/catch method for catching illegal opcode exception */
  95366. # ifdef USE_TRY_CATCH_FLAVOR
  95367. # else
  95368. LONG CALLBACK sigill_handler_sse_os(EXCEPTION_POINTERS *ep)
  95369. {
  95370. if(ep->ExceptionRecord->ExceptionCode == EXCEPTION_ILLEGAL_INSTRUCTION) {
  95371. ep->ContextRecord->Eip += 3 + 3 + 6;
  95372. return EXCEPTION_CONTINUE_EXECUTION;
  95373. }
  95374. return EXCEPTION_CONTINUE_SEARCH;
  95375. }
  95376. # endif
  95377. # endif
  95378. #endif
  95379. void FLAC__cpu_info(FLAC__CPUInfo *info)
  95380. {
  95381. /*
  95382. * IA32-specific
  95383. */
  95384. #ifdef FLAC__CPU_IA32
  95385. info->type = FLAC__CPUINFO_TYPE_IA32;
  95386. #if !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  95387. info->use_asm = true; /* we assume a minimum of 80386 with FLAC__CPU_IA32 */
  95388. info->data.ia32.cpuid = FLAC__cpu_have_cpuid_asm_ia32()? true : false;
  95389. info->data.ia32.bswap = info->data.ia32.cpuid; /* CPUID => BSWAP since it came after */
  95390. info->data.ia32.cmov = false;
  95391. info->data.ia32.mmx = false;
  95392. info->data.ia32.fxsr = false;
  95393. info->data.ia32.sse = false;
  95394. info->data.ia32.sse2 = false;
  95395. info->data.ia32.sse3 = false;
  95396. info->data.ia32.ssse3 = false;
  95397. info->data.ia32._3dnow = false;
  95398. info->data.ia32.ext3dnow = false;
  95399. info->data.ia32.extmmx = false;
  95400. if(info->data.ia32.cpuid) {
  95401. /* http://www.sandpile.org/ia32/cpuid.htm */
  95402. FLAC__uint32 flags_edx, flags_ecx;
  95403. FLAC__cpu_info_asm_ia32(&flags_edx, &flags_ecx);
  95404. info->data.ia32.cmov = (flags_edx & FLAC__CPUINFO_IA32_CPUID_CMOV )? true : false;
  95405. info->data.ia32.mmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_MMX )? true : false;
  95406. info->data.ia32.fxsr = (flags_edx & FLAC__CPUINFO_IA32_CPUID_FXSR )? true : false;
  95407. info->data.ia32.sse = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE )? true : false;
  95408. info->data.ia32.sse2 = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE2 )? true : false;
  95409. info->data.ia32.sse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSE3 )? true : false;
  95410. info->data.ia32.ssse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSSE3)? true : false;
  95411. #ifdef FLAC__USE_3DNOW
  95412. flags_edx = FLAC__cpu_info_extended_amd_asm_ia32();
  95413. info->data.ia32._3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW )? true : false;
  95414. info->data.ia32.ext3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW)? true : false;
  95415. info->data.ia32.extmmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX )? true : false;
  95416. #else
  95417. info->data.ia32._3dnow = info->data.ia32.ext3dnow = info->data.ia32.extmmx = false;
  95418. #endif
  95419. #ifdef DEBUG
  95420. fprintf(stderr, "CPU info (IA-32):\n");
  95421. fprintf(stderr, " CPUID ...... %c\n", info->data.ia32.cpuid ? 'Y' : 'n');
  95422. fprintf(stderr, " BSWAP ...... %c\n", info->data.ia32.bswap ? 'Y' : 'n');
  95423. fprintf(stderr, " CMOV ....... %c\n", info->data.ia32.cmov ? 'Y' : 'n');
  95424. fprintf(stderr, " MMX ........ %c\n", info->data.ia32.mmx ? 'Y' : 'n');
  95425. fprintf(stderr, " FXSR ....... %c\n", info->data.ia32.fxsr ? 'Y' : 'n');
  95426. fprintf(stderr, " SSE ........ %c\n", info->data.ia32.sse ? 'Y' : 'n');
  95427. fprintf(stderr, " SSE2 ....... %c\n", info->data.ia32.sse2 ? 'Y' : 'n');
  95428. fprintf(stderr, " SSE3 ....... %c\n", info->data.ia32.sse3 ? 'Y' : 'n');
  95429. fprintf(stderr, " SSSE3 ...... %c\n", info->data.ia32.ssse3 ? 'Y' : 'n');
  95430. fprintf(stderr, " 3DNow! ..... %c\n", info->data.ia32._3dnow ? 'Y' : 'n');
  95431. fprintf(stderr, " 3DNow!-ext . %c\n", info->data.ia32.ext3dnow? 'Y' : 'n');
  95432. fprintf(stderr, " 3DNow!-MMX . %c\n", info->data.ia32.extmmx ? 'Y' : 'n');
  95433. #endif
  95434. /*
  95435. * now have to check for OS support of SSE/SSE2
  95436. */
  95437. if(info->data.ia32.fxsr || info->data.ia32.sse || info->data.ia32.sse2) {
  95438. #if defined FLAC__NO_SSE_OS
  95439. /* assume user knows better than us; turn it off */
  95440. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95441. #elif defined FLAC__SSE_OS
  95442. /* assume user knows better than us; leave as detected above */
  95443. #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__APPLE__)
  95444. int sse = 0;
  95445. size_t len;
  95446. /* at least one of these must work: */
  95447. len = sizeof(sse); sse = sse || (sysctlbyname("hw.instruction_sse", &sse, &len, NULL, 0) == 0 && sse);
  95448. len = sizeof(sse); sse = sse || (sysctlbyname("hw.optional.sse" , &sse, &len, NULL, 0) == 0 && sse); /* __APPLE__ ? */
  95449. if(!sse)
  95450. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95451. #elif defined(__NetBSD__) || defined (__OpenBSD__)
  95452. # if __NetBSD_Version__ >= 105250000 || (defined __OpenBSD__)
  95453. int val = 0, mib[2] = { CTL_MACHDEP, CPU_SSE };
  95454. size_t len = sizeof(val);
  95455. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  95456. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95457. else { /* double-check SSE2 */
  95458. mib[1] = CPU_SSE2;
  95459. len = sizeof(val);
  95460. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  95461. info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95462. }
  95463. # else
  95464. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95465. # endif
  95466. #elif defined(__linux__)
  95467. int sse = 0;
  95468. struct sigaction sigill_save;
  95469. #ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  95470. if(0 == sigaction(SIGILL, NULL, &sigill_save) && signal(SIGILL, (void (*)(int))sigill_handler_sse_os) != SIG_ERR)
  95471. #else
  95472. struct sigaction sigill_sse;
  95473. sigill_sse.sa_sigaction = sigill_handler_sse_os;
  95474. __sigemptyset(&sigill_sse.sa_mask);
  95475. 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 */
  95476. if(0 == sigaction(SIGILL, &sigill_sse, &sigill_save))
  95477. #endif
  95478. {
  95479. /* http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html */
  95480. /* see sigill_handler_sse_os() for an explanation of the following: */
  95481. asm volatile (
  95482. "xorl %0,%0\n\t" /* for some reason, still need to do this to clear 'sse' var */
  95483. "xorps %%xmm0,%%xmm0\n\t" /* will cause SIGILL if unsupported by OS */
  95484. "incl %0\n\t" /* SIGILL handler will jump over this */
  95485. /* landing zone */
  95486. "nop\n\t" /* SIGILL jump lands here if "inc" is 9 bytes */
  95487. "nop\n\t"
  95488. "nop\n\t"
  95489. "nop\n\t"
  95490. "nop\n\t"
  95491. "nop\n\t"
  95492. "nop\n\t" /* SIGILL jump lands here if "inc" is 3 bytes (expected) */
  95493. "nop\n\t"
  95494. "nop" /* SIGILL jump lands here if "inc" is 1 byte */
  95495. : "=r"(sse)
  95496. : "r"(sse)
  95497. );
  95498. sigaction(SIGILL, &sigill_save, NULL);
  95499. }
  95500. if(!sse)
  95501. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95502. #elif defined(_MSC_VER)
  95503. # ifdef USE_TRY_CATCH_FLAVOR
  95504. _try {
  95505. __asm {
  95506. # if _MSC_VER <= 1200
  95507. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  95508. _emit 0x0F
  95509. _emit 0x57
  95510. _emit 0xC0
  95511. # else
  95512. xorps xmm0,xmm0
  95513. # endif
  95514. }
  95515. }
  95516. _except(EXCEPTION_EXECUTE_HANDLER) {
  95517. if (_exception_code() == STATUS_ILLEGAL_INSTRUCTION)
  95518. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95519. }
  95520. # else
  95521. int sse = 0;
  95522. LPTOP_LEVEL_EXCEPTION_FILTER save = SetUnhandledExceptionFilter(sigill_handler_sse_os);
  95523. /* see GCC version above for explanation */
  95524. /* http://msdn2.microsoft.com/en-us/library/4ks26t93.aspx */
  95525. /* http://www.codeproject.com/cpp/gccasm.asp */
  95526. /* http://www.hick.org/~mmiller/msvc_inline_asm.html */
  95527. __asm {
  95528. # if _MSC_VER <= 1200
  95529. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  95530. _emit 0x0F
  95531. _emit 0x57
  95532. _emit 0xC0
  95533. # else
  95534. xorps xmm0,xmm0
  95535. # endif
  95536. inc sse
  95537. nop
  95538. nop
  95539. nop
  95540. nop
  95541. nop
  95542. nop
  95543. nop
  95544. nop
  95545. nop
  95546. }
  95547. SetUnhandledExceptionFilter(save);
  95548. if(!sse)
  95549. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95550. # endif
  95551. #else
  95552. /* no way to test, disable to be safe */
  95553. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95554. #endif
  95555. #ifdef DEBUG
  95556. fprintf(stderr, " SSE OS sup . %c\n", info->data.ia32.sse ? 'Y' : 'n');
  95557. #endif
  95558. }
  95559. }
  95560. #else
  95561. info->use_asm = false;
  95562. #endif
  95563. /*
  95564. * PPC-specific
  95565. */
  95566. #elif defined FLAC__CPU_PPC
  95567. info->type = FLAC__CPUINFO_TYPE_PPC;
  95568. # if !defined FLAC__NO_ASM
  95569. info->use_asm = true;
  95570. # ifdef FLAC__USE_ALTIVEC
  95571. # if defined FLAC__SYS_DARWIN
  95572. {
  95573. int val = 0, mib[2] = { CTL_HW, HW_VECTORUNIT };
  95574. size_t len = sizeof(val);
  95575. info->data.ppc.altivec = !(sysctl(mib, 2, &val, &len, NULL, 0) || !val);
  95576. }
  95577. {
  95578. host_basic_info_data_t hostInfo;
  95579. mach_msg_type_number_t infoCount;
  95580. infoCount = HOST_BASIC_INFO_COUNT;
  95581. host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostInfo, &infoCount);
  95582. info->data.ppc.ppc64 = (hostInfo.cpu_type == CPU_TYPE_POWERPC) && (hostInfo.cpu_subtype == CPU_SUBTYPE_POWERPC_970);
  95583. }
  95584. # else /* FLAC__USE_ALTIVEC && !FLAC__SYS_DARWIN */
  95585. {
  95586. /* no Darwin, do it the brute-force way */
  95587. /* @@@@@@ this is not thread-safe; replace with SSE OS method above or remove */
  95588. info->data.ppc.altivec = 0;
  95589. info->data.ppc.ppc64 = 0;
  95590. signal (SIGILL, sigill_handler);
  95591. canjump = 0;
  95592. if (!sigsetjmp (jmpbuf, 1)) {
  95593. canjump = 1;
  95594. asm volatile (
  95595. "mtspr 256, %0\n\t"
  95596. "vand %%v0, %%v0, %%v0"
  95597. :
  95598. : "r" (-1)
  95599. );
  95600. info->data.ppc.altivec = 1;
  95601. }
  95602. canjump = 0;
  95603. if (!sigsetjmp (jmpbuf, 1)) {
  95604. int x = 0;
  95605. canjump = 1;
  95606. /* PPC64 hardware implements the cntlzd instruction */
  95607. asm volatile ("cntlzd %0, %1" : "=r" (x) : "r" (x) );
  95608. info->data.ppc.ppc64 = 1;
  95609. }
  95610. signal (SIGILL, SIG_DFL); /*@@@@@@ should save and restore old signal */
  95611. }
  95612. # endif
  95613. # else /* !FLAC__USE_ALTIVEC */
  95614. info->data.ppc.altivec = 0;
  95615. info->data.ppc.ppc64 = 0;
  95616. # endif
  95617. # else
  95618. info->use_asm = false;
  95619. # endif
  95620. /*
  95621. * unknown CPI
  95622. */
  95623. #else
  95624. info->type = FLAC__CPUINFO_TYPE_UNKNOWN;
  95625. info->use_asm = false;
  95626. #endif
  95627. }
  95628. #endif
  95629. /*** End of inlined file: cpu.c ***/
  95630. /*** Start of inlined file: crc.c ***/
  95631. /*** Start of inlined file: juce_FlacHeader.h ***/
  95632. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95633. // tasks..
  95634. #define VERSION "1.2.1"
  95635. #define FLAC__NO_DLL 1
  95636. #if JUCE_MSVC
  95637. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95638. #endif
  95639. #if JUCE_MAC
  95640. #define FLAC__SYS_DARWIN 1
  95641. #endif
  95642. /*** End of inlined file: juce_FlacHeader.h ***/
  95643. #if JUCE_USE_FLAC
  95644. #if HAVE_CONFIG_H
  95645. # include <config.h>
  95646. #endif
  95647. /* CRC-8, poly = x^8 + x^2 + x^1 + x^0, init = 0 */
  95648. FLAC__byte const FLAC__crc8_table[256] = {
  95649. 0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15,
  95650. 0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D,
  95651. 0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65,
  95652. 0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D,
  95653. 0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5,
  95654. 0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD,
  95655. 0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85,
  95656. 0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD,
  95657. 0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2,
  95658. 0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA,
  95659. 0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2,
  95660. 0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A,
  95661. 0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32,
  95662. 0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A,
  95663. 0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42,
  95664. 0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A,
  95665. 0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C,
  95666. 0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4,
  95667. 0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC,
  95668. 0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4,
  95669. 0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C,
  95670. 0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44,
  95671. 0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C,
  95672. 0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34,
  95673. 0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B,
  95674. 0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63,
  95675. 0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B,
  95676. 0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13,
  95677. 0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB,
  95678. 0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83,
  95679. 0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB,
  95680. 0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3
  95681. };
  95682. /* CRC-16, poly = x^16 + x^15 + x^2 + x^0, init = 0 */
  95683. unsigned FLAC__crc16_table[256] = {
  95684. 0x0000, 0x8005, 0x800f, 0x000a, 0x801b, 0x001e, 0x0014, 0x8011,
  95685. 0x8033, 0x0036, 0x003c, 0x8039, 0x0028, 0x802d, 0x8027, 0x0022,
  95686. 0x8063, 0x0066, 0x006c, 0x8069, 0x0078, 0x807d, 0x8077, 0x0072,
  95687. 0x0050, 0x8055, 0x805f, 0x005a, 0x804b, 0x004e, 0x0044, 0x8041,
  95688. 0x80c3, 0x00c6, 0x00cc, 0x80c9, 0x00d8, 0x80dd, 0x80d7, 0x00d2,
  95689. 0x00f0, 0x80f5, 0x80ff, 0x00fa, 0x80eb, 0x00ee, 0x00e4, 0x80e1,
  95690. 0x00a0, 0x80a5, 0x80af, 0x00aa, 0x80bb, 0x00be, 0x00b4, 0x80b1,
  95691. 0x8093, 0x0096, 0x009c, 0x8099, 0x0088, 0x808d, 0x8087, 0x0082,
  95692. 0x8183, 0x0186, 0x018c, 0x8189, 0x0198, 0x819d, 0x8197, 0x0192,
  95693. 0x01b0, 0x81b5, 0x81bf, 0x01ba, 0x81ab, 0x01ae, 0x01a4, 0x81a1,
  95694. 0x01e0, 0x81e5, 0x81ef, 0x01ea, 0x81fb, 0x01fe, 0x01f4, 0x81f1,
  95695. 0x81d3, 0x01d6, 0x01dc, 0x81d9, 0x01c8, 0x81cd, 0x81c7, 0x01c2,
  95696. 0x0140, 0x8145, 0x814f, 0x014a, 0x815b, 0x015e, 0x0154, 0x8151,
  95697. 0x8173, 0x0176, 0x017c, 0x8179, 0x0168, 0x816d, 0x8167, 0x0162,
  95698. 0x8123, 0x0126, 0x012c, 0x8129, 0x0138, 0x813d, 0x8137, 0x0132,
  95699. 0x0110, 0x8115, 0x811f, 0x011a, 0x810b, 0x010e, 0x0104, 0x8101,
  95700. 0x8303, 0x0306, 0x030c, 0x8309, 0x0318, 0x831d, 0x8317, 0x0312,
  95701. 0x0330, 0x8335, 0x833f, 0x033a, 0x832b, 0x032e, 0x0324, 0x8321,
  95702. 0x0360, 0x8365, 0x836f, 0x036a, 0x837b, 0x037e, 0x0374, 0x8371,
  95703. 0x8353, 0x0356, 0x035c, 0x8359, 0x0348, 0x834d, 0x8347, 0x0342,
  95704. 0x03c0, 0x83c5, 0x83cf, 0x03ca, 0x83db, 0x03de, 0x03d4, 0x83d1,
  95705. 0x83f3, 0x03f6, 0x03fc, 0x83f9, 0x03e8, 0x83ed, 0x83e7, 0x03e2,
  95706. 0x83a3, 0x03a6, 0x03ac, 0x83a9, 0x03b8, 0x83bd, 0x83b7, 0x03b2,
  95707. 0x0390, 0x8395, 0x839f, 0x039a, 0x838b, 0x038e, 0x0384, 0x8381,
  95708. 0x0280, 0x8285, 0x828f, 0x028a, 0x829b, 0x029e, 0x0294, 0x8291,
  95709. 0x82b3, 0x02b6, 0x02bc, 0x82b9, 0x02a8, 0x82ad, 0x82a7, 0x02a2,
  95710. 0x82e3, 0x02e6, 0x02ec, 0x82e9, 0x02f8, 0x82fd, 0x82f7, 0x02f2,
  95711. 0x02d0, 0x82d5, 0x82df, 0x02da, 0x82cb, 0x02ce, 0x02c4, 0x82c1,
  95712. 0x8243, 0x0246, 0x024c, 0x8249, 0x0258, 0x825d, 0x8257, 0x0252,
  95713. 0x0270, 0x8275, 0x827f, 0x027a, 0x826b, 0x026e, 0x0264, 0x8261,
  95714. 0x0220, 0x8225, 0x822f, 0x022a, 0x823b, 0x023e, 0x0234, 0x8231,
  95715. 0x8213, 0x0216, 0x021c, 0x8219, 0x0208, 0x820d, 0x8207, 0x0202
  95716. };
  95717. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc)
  95718. {
  95719. *crc = FLAC__crc8_table[*crc ^ data];
  95720. }
  95721. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc)
  95722. {
  95723. while(len--)
  95724. *crc = FLAC__crc8_table[*crc ^ *data++];
  95725. }
  95726. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len)
  95727. {
  95728. FLAC__uint8 crc = 0;
  95729. while(len--)
  95730. crc = FLAC__crc8_table[crc ^ *data++];
  95731. return crc;
  95732. }
  95733. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len)
  95734. {
  95735. unsigned crc = 0;
  95736. while(len--)
  95737. crc = ((crc<<8) ^ FLAC__crc16_table[(crc>>8) ^ *data++]) & 0xffff;
  95738. return crc;
  95739. }
  95740. #endif
  95741. /*** End of inlined file: crc.c ***/
  95742. /*** Start of inlined file: fixed.c ***/
  95743. /*** Start of inlined file: juce_FlacHeader.h ***/
  95744. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95745. // tasks..
  95746. #define VERSION "1.2.1"
  95747. #define FLAC__NO_DLL 1
  95748. #if JUCE_MSVC
  95749. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95750. #endif
  95751. #if JUCE_MAC
  95752. #define FLAC__SYS_DARWIN 1
  95753. #endif
  95754. /*** End of inlined file: juce_FlacHeader.h ***/
  95755. #if JUCE_USE_FLAC
  95756. #if HAVE_CONFIG_H
  95757. # include <config.h>
  95758. #endif
  95759. #include <math.h>
  95760. #include <string.h>
  95761. /*** Start of inlined file: fixed.h ***/
  95762. #ifndef FLAC__PRIVATE__FIXED_H
  95763. #define FLAC__PRIVATE__FIXED_H
  95764. #ifdef HAVE_CONFIG_H
  95765. #include <config.h>
  95766. #endif
  95767. /*** Start of inlined file: float.h ***/
  95768. #ifndef FLAC__PRIVATE__FLOAT_H
  95769. #define FLAC__PRIVATE__FLOAT_H
  95770. #ifdef HAVE_CONFIG_H
  95771. #include <config.h>
  95772. #endif
  95773. /*
  95774. * These typedefs make it easier to ensure that integer versions of
  95775. * the library really only contain integer operations. All the code
  95776. * in libFLAC should use FLAC__float and FLAC__double in place of
  95777. * float and double, and be protected by checks of the macro
  95778. * FLAC__INTEGER_ONLY_LIBRARY.
  95779. *
  95780. * FLAC__real is the basic floating point type used in LPC analysis.
  95781. */
  95782. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95783. typedef double FLAC__double;
  95784. typedef float FLAC__float;
  95785. /*
  95786. * WATCHOUT: changing FLAC__real will change the signatures of many
  95787. * functions that have assembly language equivalents and break them.
  95788. */
  95789. typedef float FLAC__real;
  95790. #else
  95791. /*
  95792. * The convention for FLAC__fixedpoint is to use the upper 16 bits
  95793. * for the integer part and lower 16 bits for the fractional part.
  95794. */
  95795. typedef FLAC__int32 FLAC__fixedpoint;
  95796. extern const FLAC__fixedpoint FLAC__FP_ZERO;
  95797. extern const FLAC__fixedpoint FLAC__FP_ONE_HALF;
  95798. extern const FLAC__fixedpoint FLAC__FP_ONE;
  95799. extern const FLAC__fixedpoint FLAC__FP_LN2;
  95800. extern const FLAC__fixedpoint FLAC__FP_E;
  95801. #define FLAC__fixedpoint_trunc(x) ((x)>>16)
  95802. #define FLAC__fixedpoint_mul(x, y) ( (FLAC__fixedpoint) ( ((FLAC__int64)(x)*(FLAC__int64)(y)) >> 16 ) )
  95803. #define FLAC__fixedpoint_div(x, y) ( (FLAC__fixedpoint) ( ( ((FLAC__int64)(x)<<32) / (FLAC__int64)(y) ) >> 16 ) )
  95804. /*
  95805. * FLAC__fixedpoint_log2()
  95806. * --------------------------------------------------------------------
  95807. * Returns the base-2 logarithm of the fixed-point number 'x' using an
  95808. * algorithm by Knuth for x >= 1.0
  95809. *
  95810. * 'fracbits' is the number of fractional bits of 'x'. 'fracbits' must
  95811. * be < 32 and evenly divisible by 4 (0 is OK but not very precise).
  95812. *
  95813. * 'precision' roughly limits the number of iterations that are done;
  95814. * use (unsigned)(-1) for maximum precision.
  95815. *
  95816. * If 'x' is less than one -- that is, x < (1<<fracbits) -- then this
  95817. * function will punt and return 0.
  95818. *
  95819. * The return value will also have 'fracbits' fractional bits.
  95820. */
  95821. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision);
  95822. #endif
  95823. #endif
  95824. /*** End of inlined file: float.h ***/
  95825. /*** Start of inlined file: format.h ***/
  95826. #ifndef FLAC__PRIVATE__FORMAT_H
  95827. #define FLAC__PRIVATE__FORMAT_H
  95828. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order);
  95829. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize);
  95830. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order);
  95831. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  95832. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  95833. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order);
  95834. #endif
  95835. /*** End of inlined file: format.h ***/
  95836. /*
  95837. * FLAC__fixed_compute_best_predictor()
  95838. * --------------------------------------------------------------------
  95839. * Compute the best fixed predictor and the expected bits-per-sample
  95840. * of the residual signal for each order. The _wide() version uses
  95841. * 64-bit integers which is statistically necessary when bits-per-
  95842. * sample + log2(blocksize) > 30
  95843. *
  95844. * IN data[0,data_len-1]
  95845. * IN data_len
  95846. * OUT residual_bits_per_sample[0,FLAC__MAX_FIXED_ORDER]
  95847. */
  95848. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95849. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  95850. # ifndef FLAC__NO_ASM
  95851. # ifdef FLAC__CPU_IA32
  95852. # ifdef FLAC__HAS_NASM
  95853. 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]);
  95854. # endif
  95855. # endif
  95856. # endif
  95857. 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]);
  95858. #else
  95859. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  95860. 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]);
  95861. #endif
  95862. /*
  95863. * FLAC__fixed_compute_residual()
  95864. * --------------------------------------------------------------------
  95865. * Compute the residual signal obtained from sutracting the predicted
  95866. * signal from the original.
  95867. *
  95868. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  95869. * IN data_len length of original signal
  95870. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  95871. * OUT residual[0,data_len-1] residual signal
  95872. */
  95873. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[]);
  95874. /*
  95875. * FLAC__fixed_restore_signal()
  95876. * --------------------------------------------------------------------
  95877. * Restore the original signal by summing the residual and the
  95878. * predictor.
  95879. *
  95880. * IN residual[0,data_len-1] residual signal
  95881. * IN data_len length of original signal
  95882. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  95883. * *** IMPORTANT: the caller must pass in the historical samples:
  95884. * IN data[-order,-1] previously-reconstructed historical samples
  95885. * OUT data[0,data_len-1] original signal
  95886. */
  95887. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[]);
  95888. #endif
  95889. /*** End of inlined file: fixed.h ***/
  95890. #ifndef M_LN2
  95891. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  95892. #define M_LN2 0.69314718055994530942
  95893. #endif
  95894. #ifdef min
  95895. #undef min
  95896. #endif
  95897. #define min(x,y) ((x) < (y)? (x) : (y))
  95898. #ifdef local_abs
  95899. #undef local_abs
  95900. #endif
  95901. #define local_abs(x) ((unsigned)((x)<0? -(x) : (x)))
  95902. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  95903. /* rbps stands for residual bits per sample
  95904. *
  95905. * (ln(2) * err)
  95906. * rbps = log (-----------)
  95907. * 2 ( n )
  95908. */
  95909. static FLAC__fixedpoint local__compute_rbps_integerized(FLAC__uint32 err, FLAC__uint32 n)
  95910. {
  95911. FLAC__uint32 rbps;
  95912. unsigned bits; /* the number of bits required to represent a number */
  95913. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  95914. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  95915. FLAC__ASSERT(err > 0);
  95916. FLAC__ASSERT(n > 0);
  95917. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  95918. if(err <= n)
  95919. return 0;
  95920. /*
  95921. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  95922. * These allow us later to know we won't lose too much precision in the
  95923. * fixed-point division (err<<fracbits)/n.
  95924. */
  95925. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2(err)+1);
  95926. err <<= fracbits;
  95927. err /= n;
  95928. /* err now holds err/n with fracbits fractional bits */
  95929. /*
  95930. * Whittle err down to 16 bits max. 16 significant bits is enough for
  95931. * our purposes.
  95932. */
  95933. FLAC__ASSERT(err > 0);
  95934. bits = FLAC__bitmath_ilog2(err)+1;
  95935. if(bits > 16) {
  95936. err >>= (bits-16);
  95937. fracbits -= (bits-16);
  95938. }
  95939. rbps = (FLAC__uint32)err;
  95940. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  95941. rbps *= FLAC__FP_LN2;
  95942. fracbits += 16;
  95943. FLAC__ASSERT(fracbits >= 0);
  95944. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  95945. {
  95946. const int f = fracbits & 3;
  95947. if(f) {
  95948. rbps >>= f;
  95949. fracbits -= f;
  95950. }
  95951. }
  95952. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  95953. if(rbps == 0)
  95954. return 0;
  95955. /*
  95956. * The return value must have 16 fractional bits. Since the whole part
  95957. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  95958. * must be >= -3, these assertion allows us to be able to shift rbps
  95959. * left if necessary to get 16 fracbits without losing any bits of the
  95960. * whole part of rbps.
  95961. *
  95962. * There is a slight chance due to accumulated error that the whole part
  95963. * will require 6 bits, so we use 6 in the assertion. Really though as
  95964. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  95965. */
  95966. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  95967. FLAC__ASSERT(fracbits >= -3);
  95968. /* now shift the decimal point into place */
  95969. if(fracbits < 16)
  95970. return rbps << (16-fracbits);
  95971. else if(fracbits > 16)
  95972. return rbps >> (fracbits-16);
  95973. else
  95974. return rbps;
  95975. }
  95976. static FLAC__fixedpoint local__compute_rbps_wide_integerized(FLAC__uint64 err, FLAC__uint32 n)
  95977. {
  95978. FLAC__uint32 rbps;
  95979. unsigned bits; /* the number of bits required to represent a number */
  95980. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  95981. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  95982. FLAC__ASSERT(err > 0);
  95983. FLAC__ASSERT(n > 0);
  95984. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  95985. if(err <= n)
  95986. return 0;
  95987. /*
  95988. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  95989. * These allow us later to know we won't lose too much precision in the
  95990. * fixed-point division (err<<fracbits)/n.
  95991. */
  95992. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2_wide(err)+1);
  95993. err <<= fracbits;
  95994. err /= n;
  95995. /* err now holds err/n with fracbits fractional bits */
  95996. /*
  95997. * Whittle err down to 16 bits max. 16 significant bits is enough for
  95998. * our purposes.
  95999. */
  96000. FLAC__ASSERT(err > 0);
  96001. bits = FLAC__bitmath_ilog2_wide(err)+1;
  96002. if(bits > 16) {
  96003. err >>= (bits-16);
  96004. fracbits -= (bits-16);
  96005. }
  96006. rbps = (FLAC__uint32)err;
  96007. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  96008. rbps *= FLAC__FP_LN2;
  96009. fracbits += 16;
  96010. FLAC__ASSERT(fracbits >= 0);
  96011. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  96012. {
  96013. const int f = fracbits & 3;
  96014. if(f) {
  96015. rbps >>= f;
  96016. fracbits -= f;
  96017. }
  96018. }
  96019. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  96020. if(rbps == 0)
  96021. return 0;
  96022. /*
  96023. * The return value must have 16 fractional bits. Since the whole part
  96024. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  96025. * must be >= -3, these assertion allows us to be able to shift rbps
  96026. * left if necessary to get 16 fracbits without losing any bits of the
  96027. * whole part of rbps.
  96028. *
  96029. * There is a slight chance due to accumulated error that the whole part
  96030. * will require 6 bits, so we use 6 in the assertion. Really though as
  96031. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  96032. */
  96033. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  96034. FLAC__ASSERT(fracbits >= -3);
  96035. /* now shift the decimal point into place */
  96036. if(fracbits < 16)
  96037. return rbps << (16-fracbits);
  96038. else if(fracbits > 16)
  96039. return rbps >> (fracbits-16);
  96040. else
  96041. return rbps;
  96042. }
  96043. #endif
  96044. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96045. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  96046. #else
  96047. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  96048. #endif
  96049. {
  96050. FLAC__int32 last_error_0 = data[-1];
  96051. FLAC__int32 last_error_1 = data[-1] - data[-2];
  96052. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  96053. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  96054. FLAC__int32 error, save;
  96055. FLAC__uint32 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  96056. unsigned i, order;
  96057. for(i = 0; i < data_len; i++) {
  96058. error = data[i] ; total_error_0 += local_abs(error); save = error;
  96059. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  96060. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  96061. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  96062. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  96063. }
  96064. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  96065. order = 0;
  96066. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  96067. order = 1;
  96068. else if(total_error_2 < min(total_error_3, total_error_4))
  96069. order = 2;
  96070. else if(total_error_3 < total_error_4)
  96071. order = 3;
  96072. else
  96073. order = 4;
  96074. /* Estimate the expected number of bits per residual signal sample. */
  96075. /* 'total_error*' is linearly related to the variance of the residual */
  96076. /* signal, so we use it directly to compute E(|x|) */
  96077. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  96078. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  96079. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  96080. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  96081. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  96082. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96083. 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);
  96084. 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);
  96085. 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);
  96086. 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);
  96087. 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);
  96088. #else
  96089. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_integerized(total_error_0, data_len) : 0;
  96090. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_integerized(total_error_1, data_len) : 0;
  96091. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_integerized(total_error_2, data_len) : 0;
  96092. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_integerized(total_error_3, data_len) : 0;
  96093. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_integerized(total_error_4, data_len) : 0;
  96094. #endif
  96095. return order;
  96096. }
  96097. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96098. 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])
  96099. #else
  96100. 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])
  96101. #endif
  96102. {
  96103. FLAC__int32 last_error_0 = data[-1];
  96104. FLAC__int32 last_error_1 = data[-1] - data[-2];
  96105. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  96106. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  96107. FLAC__int32 error, save;
  96108. /* total_error_* are 64-bits to avoid overflow when encoding
  96109. * erratic signals when the bits-per-sample and blocksize are
  96110. * large.
  96111. */
  96112. FLAC__uint64 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  96113. unsigned i, order;
  96114. for(i = 0; i < data_len; i++) {
  96115. error = data[i] ; total_error_0 += local_abs(error); save = error;
  96116. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  96117. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  96118. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  96119. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  96120. }
  96121. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  96122. order = 0;
  96123. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  96124. order = 1;
  96125. else if(total_error_2 < min(total_error_3, total_error_4))
  96126. order = 2;
  96127. else if(total_error_3 < total_error_4)
  96128. order = 3;
  96129. else
  96130. order = 4;
  96131. /* Estimate the expected number of bits per residual signal sample. */
  96132. /* 'total_error*' is linearly related to the variance of the residual */
  96133. /* signal, so we use it directly to compute E(|x|) */
  96134. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  96135. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  96136. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  96137. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  96138. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  96139. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96140. #if defined _MSC_VER || defined __MINGW32__
  96141. /* with MSVC you have to spoon feed it the casting */
  96142. 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);
  96143. 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);
  96144. 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);
  96145. 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);
  96146. 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);
  96147. #else
  96148. 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);
  96149. 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);
  96150. 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);
  96151. 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);
  96152. 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);
  96153. #endif
  96154. #else
  96155. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_wide_integerized(total_error_0, data_len) : 0;
  96156. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_wide_integerized(total_error_1, data_len) : 0;
  96157. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_wide_integerized(total_error_2, data_len) : 0;
  96158. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_wide_integerized(total_error_3, data_len) : 0;
  96159. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_wide_integerized(total_error_4, data_len) : 0;
  96160. #endif
  96161. return order;
  96162. }
  96163. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[])
  96164. {
  96165. const int idata_len = (int)data_len;
  96166. int i;
  96167. switch(order) {
  96168. case 0:
  96169. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  96170. memcpy(residual, data, sizeof(residual[0])*data_len);
  96171. break;
  96172. case 1:
  96173. for(i = 0; i < idata_len; i++)
  96174. residual[i] = data[i] - data[i-1];
  96175. break;
  96176. case 2:
  96177. for(i = 0; i < idata_len; i++)
  96178. #if 1 /* OPT: may be faster with some compilers on some systems */
  96179. residual[i] = data[i] - (data[i-1] << 1) + data[i-2];
  96180. #else
  96181. residual[i] = data[i] - 2*data[i-1] + data[i-2];
  96182. #endif
  96183. break;
  96184. case 3:
  96185. for(i = 0; i < idata_len; i++)
  96186. #if 1 /* OPT: may be faster with some compilers on some systems */
  96187. residual[i] = data[i] - (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) - data[i-3];
  96188. #else
  96189. residual[i] = data[i] - 3*data[i-1] + 3*data[i-2] - data[i-3];
  96190. #endif
  96191. break;
  96192. case 4:
  96193. for(i = 0; i < idata_len; i++)
  96194. #if 1 /* OPT: may be faster with some compilers on some systems */
  96195. residual[i] = data[i] - ((data[i-1]+data[i-3])<<2) + ((data[i-2]<<2) + (data[i-2]<<1)) + data[i-4];
  96196. #else
  96197. residual[i] = data[i] - 4*data[i-1] + 6*data[i-2] - 4*data[i-3] + data[i-4];
  96198. #endif
  96199. break;
  96200. default:
  96201. FLAC__ASSERT(0);
  96202. }
  96203. }
  96204. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[])
  96205. {
  96206. int i, idata_len = (int)data_len;
  96207. switch(order) {
  96208. case 0:
  96209. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  96210. memcpy(data, residual, sizeof(residual[0])*data_len);
  96211. break;
  96212. case 1:
  96213. for(i = 0; i < idata_len; i++)
  96214. data[i] = residual[i] + data[i-1];
  96215. break;
  96216. case 2:
  96217. for(i = 0; i < idata_len; i++)
  96218. #if 1 /* OPT: may be faster with some compilers on some systems */
  96219. data[i] = residual[i] + (data[i-1]<<1) - data[i-2];
  96220. #else
  96221. data[i] = residual[i] + 2*data[i-1] - data[i-2];
  96222. #endif
  96223. break;
  96224. case 3:
  96225. for(i = 0; i < idata_len; i++)
  96226. #if 1 /* OPT: may be faster with some compilers on some systems */
  96227. data[i] = residual[i] + (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) + data[i-3];
  96228. #else
  96229. data[i] = residual[i] + 3*data[i-1] - 3*data[i-2] + data[i-3];
  96230. #endif
  96231. break;
  96232. case 4:
  96233. for(i = 0; i < idata_len; i++)
  96234. #if 1 /* OPT: may be faster with some compilers on some systems */
  96235. data[i] = residual[i] + ((data[i-1]+data[i-3])<<2) - ((data[i-2]<<2) + (data[i-2]<<1)) - data[i-4];
  96236. #else
  96237. data[i] = residual[i] + 4*data[i-1] - 6*data[i-2] + 4*data[i-3] - data[i-4];
  96238. #endif
  96239. break;
  96240. default:
  96241. FLAC__ASSERT(0);
  96242. }
  96243. }
  96244. #endif
  96245. /*** End of inlined file: fixed.c ***/
  96246. /*** Start of inlined file: float.c ***/
  96247. /*** Start of inlined file: juce_FlacHeader.h ***/
  96248. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96249. // tasks..
  96250. #define VERSION "1.2.1"
  96251. #define FLAC__NO_DLL 1
  96252. #if JUCE_MSVC
  96253. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96254. #endif
  96255. #if JUCE_MAC
  96256. #define FLAC__SYS_DARWIN 1
  96257. #endif
  96258. /*** End of inlined file: juce_FlacHeader.h ***/
  96259. #if JUCE_USE_FLAC
  96260. #if HAVE_CONFIG_H
  96261. # include <config.h>
  96262. #endif
  96263. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  96264. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  96265. #ifdef _MSC_VER
  96266. #define FLAC__U64L(x) x
  96267. #else
  96268. #define FLAC__U64L(x) x##LLU
  96269. #endif
  96270. const FLAC__fixedpoint FLAC__FP_ZERO = 0;
  96271. const FLAC__fixedpoint FLAC__FP_ONE_HALF = 0x00008000;
  96272. const FLAC__fixedpoint FLAC__FP_ONE = 0x00010000;
  96273. const FLAC__fixedpoint FLAC__FP_LN2 = 45426;
  96274. const FLAC__fixedpoint FLAC__FP_E = 178145;
  96275. /* Lookup tables for Knuth's logarithm algorithm */
  96276. #define LOG2_LOOKUP_PRECISION 16
  96277. static const FLAC__uint32 log2_lookup[][LOG2_LOOKUP_PRECISION] = {
  96278. {
  96279. /*
  96280. * 0 fraction bits
  96281. */
  96282. /* undefined */ 0x00000000,
  96283. /* lg(2/1) = */ 0x00000001,
  96284. /* lg(4/3) = */ 0x00000000,
  96285. /* lg(8/7) = */ 0x00000000,
  96286. /* lg(16/15) = */ 0x00000000,
  96287. /* lg(32/31) = */ 0x00000000,
  96288. /* lg(64/63) = */ 0x00000000,
  96289. /* lg(128/127) = */ 0x00000000,
  96290. /* lg(256/255) = */ 0x00000000,
  96291. /* lg(512/511) = */ 0x00000000,
  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. * 4 fraction bits
  96302. */
  96303. /* undefined */ 0x00000000,
  96304. /* lg(2/1) = */ 0x00000010,
  96305. /* lg(4/3) = */ 0x00000007,
  96306. /* lg(8/7) = */ 0x00000003,
  96307. /* lg(16/15) = */ 0x00000001,
  96308. /* lg(32/31) = */ 0x00000001,
  96309. /* lg(64/63) = */ 0x00000000,
  96310. /* lg(128/127) = */ 0x00000000,
  96311. /* lg(256/255) = */ 0x00000000,
  96312. /* lg(512/511) = */ 0x00000000,
  96313. /* lg(1024/1023) = */ 0x00000000,
  96314. /* lg(2048/2047) = */ 0x00000000,
  96315. /* lg(4096/4095) = */ 0x00000000,
  96316. /* lg(8192/8191) = */ 0x00000000,
  96317. /* lg(16384/16383) = */ 0x00000000,
  96318. /* lg(32768/32767) = */ 0x00000000
  96319. },
  96320. {
  96321. /*
  96322. * 8 fraction bits
  96323. */
  96324. /* undefined */ 0x00000000,
  96325. /* lg(2/1) = */ 0x00000100,
  96326. /* lg(4/3) = */ 0x0000006a,
  96327. /* lg(8/7) = */ 0x00000031,
  96328. /* lg(16/15) = */ 0x00000018,
  96329. /* lg(32/31) = */ 0x0000000c,
  96330. /* lg(64/63) = */ 0x00000006,
  96331. /* lg(128/127) = */ 0x00000003,
  96332. /* lg(256/255) = */ 0x00000001,
  96333. /* lg(512/511) = */ 0x00000001,
  96334. /* lg(1024/1023) = */ 0x00000000,
  96335. /* lg(2048/2047) = */ 0x00000000,
  96336. /* lg(4096/4095) = */ 0x00000000,
  96337. /* lg(8192/8191) = */ 0x00000000,
  96338. /* lg(16384/16383) = */ 0x00000000,
  96339. /* lg(32768/32767) = */ 0x00000000
  96340. },
  96341. {
  96342. /*
  96343. * 12 fraction bits
  96344. */
  96345. /* undefined */ 0x00000000,
  96346. /* lg(2/1) = */ 0x00001000,
  96347. /* lg(4/3) = */ 0x000006a4,
  96348. /* lg(8/7) = */ 0x00000315,
  96349. /* lg(16/15) = */ 0x0000017d,
  96350. /* lg(32/31) = */ 0x000000bc,
  96351. /* lg(64/63) = */ 0x0000005d,
  96352. /* lg(128/127) = */ 0x0000002e,
  96353. /* lg(256/255) = */ 0x00000017,
  96354. /* lg(512/511) = */ 0x0000000c,
  96355. /* lg(1024/1023) = */ 0x00000006,
  96356. /* lg(2048/2047) = */ 0x00000003,
  96357. /* lg(4096/4095) = */ 0x00000001,
  96358. /* lg(8192/8191) = */ 0x00000001,
  96359. /* lg(16384/16383) = */ 0x00000000,
  96360. /* lg(32768/32767) = */ 0x00000000
  96361. },
  96362. {
  96363. /*
  96364. * 16 fraction bits
  96365. */
  96366. /* undefined */ 0x00000000,
  96367. /* lg(2/1) = */ 0x00010000,
  96368. /* lg(4/3) = */ 0x00006a40,
  96369. /* lg(8/7) = */ 0x00003151,
  96370. /* lg(16/15) = */ 0x000017d6,
  96371. /* lg(32/31) = */ 0x00000bba,
  96372. /* lg(64/63) = */ 0x000005d1,
  96373. /* lg(128/127) = */ 0x000002e6,
  96374. /* lg(256/255) = */ 0x00000172,
  96375. /* lg(512/511) = */ 0x000000b9,
  96376. /* lg(1024/1023) = */ 0x0000005c,
  96377. /* lg(2048/2047) = */ 0x0000002e,
  96378. /* lg(4096/4095) = */ 0x00000017,
  96379. /* lg(8192/8191) = */ 0x0000000c,
  96380. /* lg(16384/16383) = */ 0x00000006,
  96381. /* lg(32768/32767) = */ 0x00000003
  96382. },
  96383. {
  96384. /*
  96385. * 20 fraction bits
  96386. */
  96387. /* undefined */ 0x00000000,
  96388. /* lg(2/1) = */ 0x00100000,
  96389. /* lg(4/3) = */ 0x0006a3fe,
  96390. /* lg(8/7) = */ 0x00031513,
  96391. /* lg(16/15) = */ 0x00017d60,
  96392. /* lg(32/31) = */ 0x0000bb9d,
  96393. /* lg(64/63) = */ 0x00005d10,
  96394. /* lg(128/127) = */ 0x00002e59,
  96395. /* lg(256/255) = */ 0x00001721,
  96396. /* lg(512/511) = */ 0x00000b8e,
  96397. /* lg(1024/1023) = */ 0x000005c6,
  96398. /* lg(2048/2047) = */ 0x000002e3,
  96399. /* lg(4096/4095) = */ 0x00000171,
  96400. /* lg(8192/8191) = */ 0x000000b9,
  96401. /* lg(16384/16383) = */ 0x0000005c,
  96402. /* lg(32768/32767) = */ 0x0000002e
  96403. },
  96404. {
  96405. /*
  96406. * 24 fraction bits
  96407. */
  96408. /* undefined */ 0x00000000,
  96409. /* lg(2/1) = */ 0x01000000,
  96410. /* lg(4/3) = */ 0x006a3fe6,
  96411. /* lg(8/7) = */ 0x00315130,
  96412. /* lg(16/15) = */ 0x0017d605,
  96413. /* lg(32/31) = */ 0x000bb9ca,
  96414. /* lg(64/63) = */ 0x0005d0fc,
  96415. /* lg(128/127) = */ 0x0002e58f,
  96416. /* lg(256/255) = */ 0x0001720e,
  96417. /* lg(512/511) = */ 0x0000b8d8,
  96418. /* lg(1024/1023) = */ 0x00005c61,
  96419. /* lg(2048/2047) = */ 0x00002e2d,
  96420. /* lg(4096/4095) = */ 0x00001716,
  96421. /* lg(8192/8191) = */ 0x00000b8b,
  96422. /* lg(16384/16383) = */ 0x000005c5,
  96423. /* lg(32768/32767) = */ 0x000002e3
  96424. },
  96425. {
  96426. /*
  96427. * 28 fraction bits
  96428. */
  96429. /* undefined */ 0x00000000,
  96430. /* lg(2/1) = */ 0x10000000,
  96431. /* lg(4/3) = */ 0x06a3fe5c,
  96432. /* lg(8/7) = */ 0x03151301,
  96433. /* lg(16/15) = */ 0x017d6049,
  96434. /* lg(32/31) = */ 0x00bb9ca6,
  96435. /* lg(64/63) = */ 0x005d0fba,
  96436. /* lg(128/127) = */ 0x002e58f7,
  96437. /* lg(256/255) = */ 0x001720da,
  96438. /* lg(512/511) = */ 0x000b8d87,
  96439. /* lg(1024/1023) = */ 0x0005c60b,
  96440. /* lg(2048/2047) = */ 0x0002e2d7,
  96441. /* lg(4096/4095) = */ 0x00017160,
  96442. /* lg(8192/8191) = */ 0x0000b8ad,
  96443. /* lg(16384/16383) = */ 0x00005c56,
  96444. /* lg(32768/32767) = */ 0x00002e2b
  96445. }
  96446. };
  96447. #if 0
  96448. static const FLAC__uint64 log2_lookup_wide[] = {
  96449. {
  96450. /*
  96451. * 32 fraction bits
  96452. */
  96453. /* undefined */ 0x00000000,
  96454. /* lg(2/1) = */ FLAC__U64L(0x100000000),
  96455. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c6),
  96456. /* lg(8/7) = */ FLAC__U64L(0x31513015),
  96457. /* lg(16/15) = */ FLAC__U64L(0x17d60497),
  96458. /* lg(32/31) = */ FLAC__U64L(0x0bb9ca65),
  96459. /* lg(64/63) = */ FLAC__U64L(0x05d0fba2),
  96460. /* lg(128/127) = */ FLAC__U64L(0x02e58f74),
  96461. /* lg(256/255) = */ FLAC__U64L(0x01720d9c),
  96462. /* lg(512/511) = */ FLAC__U64L(0x00b8d875),
  96463. /* lg(1024/1023) = */ FLAC__U64L(0x005c60aa),
  96464. /* lg(2048/2047) = */ FLAC__U64L(0x002e2d72),
  96465. /* lg(4096/4095) = */ FLAC__U64L(0x00171600),
  96466. /* lg(8192/8191) = */ FLAC__U64L(0x000b8ad2),
  96467. /* lg(16384/16383) = */ FLAC__U64L(0x0005c55d),
  96468. /* lg(32768/32767) = */ FLAC__U64L(0x0002e2ac)
  96469. },
  96470. {
  96471. /*
  96472. * 48 fraction bits
  96473. */
  96474. /* undefined */ 0x00000000,
  96475. /* lg(2/1) = */ FLAC__U64L(0x1000000000000),
  96476. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c60429),
  96477. /* lg(8/7) = */ FLAC__U64L(0x315130157f7a),
  96478. /* lg(16/15) = */ FLAC__U64L(0x17d60496cfbb),
  96479. /* lg(32/31) = */ FLAC__U64L(0xbb9ca64ecac),
  96480. /* lg(64/63) = */ FLAC__U64L(0x5d0fba187cd),
  96481. /* lg(128/127) = */ FLAC__U64L(0x2e58f7441ee),
  96482. /* lg(256/255) = */ FLAC__U64L(0x1720d9c06a8),
  96483. /* lg(512/511) = */ FLAC__U64L(0xb8d8752173),
  96484. /* lg(1024/1023) = */ FLAC__U64L(0x5c60aa252e),
  96485. /* lg(2048/2047) = */ FLAC__U64L(0x2e2d71b0d8),
  96486. /* lg(4096/4095) = */ FLAC__U64L(0x1716001719),
  96487. /* lg(8192/8191) = */ FLAC__U64L(0xb8ad1de1b),
  96488. /* lg(16384/16383) = */ FLAC__U64L(0x5c55d640d),
  96489. /* lg(32768/32767) = */ FLAC__U64L(0x2e2abcf52)
  96490. }
  96491. };
  96492. #endif
  96493. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision)
  96494. {
  96495. const FLAC__uint32 ONE = (1u << fracbits);
  96496. const FLAC__uint32 *table = log2_lookup[fracbits >> 2];
  96497. FLAC__ASSERT(fracbits < 32);
  96498. FLAC__ASSERT((fracbits & 0x3) == 0);
  96499. if(x < ONE)
  96500. return 0;
  96501. if(precision > LOG2_LOOKUP_PRECISION)
  96502. precision = LOG2_LOOKUP_PRECISION;
  96503. /* Knuth's algorithm for computing logarithms, optimized for base-2 with lookup tables */
  96504. {
  96505. FLAC__uint32 y = 0;
  96506. FLAC__uint32 z = x >> 1, k = 1;
  96507. while (x > ONE && k < precision) {
  96508. if (x - z >= ONE) {
  96509. x -= z;
  96510. z = x >> k;
  96511. y += table[k];
  96512. }
  96513. else {
  96514. z >>= 1;
  96515. k++;
  96516. }
  96517. }
  96518. return y;
  96519. }
  96520. }
  96521. #endif /* defined FLAC__INTEGER_ONLY_LIBRARY */
  96522. #endif
  96523. /*** End of inlined file: float.c ***/
  96524. /*** Start of inlined file: format.c ***/
  96525. /*** Start of inlined file: juce_FlacHeader.h ***/
  96526. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96527. // tasks..
  96528. #define VERSION "1.2.1"
  96529. #define FLAC__NO_DLL 1
  96530. #if JUCE_MSVC
  96531. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96532. #endif
  96533. #if JUCE_MAC
  96534. #define FLAC__SYS_DARWIN 1
  96535. #endif
  96536. /*** End of inlined file: juce_FlacHeader.h ***/
  96537. #if JUCE_USE_FLAC
  96538. #if HAVE_CONFIG_H
  96539. # include <config.h>
  96540. #endif
  96541. #include <stdio.h>
  96542. #include <stdlib.h> /* for qsort() */
  96543. #include <string.h> /* for memset() */
  96544. #ifndef FLaC__INLINE
  96545. #define FLaC__INLINE
  96546. #endif
  96547. #ifdef min
  96548. #undef min
  96549. #endif
  96550. #define min(a,b) ((a)<(b)?(a):(b))
  96551. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  96552. #ifdef _MSC_VER
  96553. #define FLAC__U64L(x) x
  96554. #else
  96555. #define FLAC__U64L(x) x##LLU
  96556. #endif
  96557. /* VERSION should come from configure */
  96558. FLAC_API const char *FLAC__VERSION_STRING = VERSION
  96559. ;
  96560. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINW32__
  96561. /* yet one more hack because of MSVC6: */
  96562. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC 1.2.1 20070917";
  96563. #else
  96564. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC " VERSION " 20070917";
  96565. #endif
  96566. FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4] = { 'f','L','a','C' };
  96567. FLAC_API const unsigned FLAC__STREAM_SYNC = 0x664C6143;
  96568. FLAC_API const unsigned FLAC__STREAM_SYNC_LEN = 32; /* bits */
  96569. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN = 16; /* bits */
  96570. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN = 16; /* bits */
  96571. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN = 24; /* bits */
  96572. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN = 24; /* bits */
  96573. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN = 20; /* bits */
  96574. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN = 3; /* bits */
  96575. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN = 5; /* bits */
  96576. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN = 36; /* bits */
  96577. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN = 128; /* bits */
  96578. FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN = 32; /* bits */
  96579. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN = 64; /* bits */
  96580. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN = 64; /* bits */
  96581. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN = 16; /* bits */
  96582. FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER = FLAC__U64L(0xffffffffffffffff);
  96583. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN = 32; /* bits */
  96584. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN = 32; /* bits */
  96585. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN = 64; /* bits */
  96586. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN = 8; /* bits */
  96587. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN = 3*8; /* bits */
  96588. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN = 64; /* bits */
  96589. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN = 8; /* bits */
  96590. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN = 12*8; /* bits */
  96591. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN = 1; /* bit */
  96592. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN = 1; /* bit */
  96593. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN = 6+13*8; /* bits */
  96594. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN = 8; /* bits */
  96595. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN = 128*8; /* bits */
  96596. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN = 64; /* bits */
  96597. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN = 1; /* bit */
  96598. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN = 7+258*8; /* bits */
  96599. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN = 8; /* bits */
  96600. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN = 32; /* bits */
  96601. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN = 32; /* bits */
  96602. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN = 32; /* bits */
  96603. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN = 32; /* bits */
  96604. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN = 32; /* bits */
  96605. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN = 32; /* bits */
  96606. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN = 32; /* bits */
  96607. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN = 32; /* bits */
  96608. FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN = 1; /* bits */
  96609. FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN = 7; /* bits */
  96610. FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN = 24; /* bits */
  96611. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC = 0x3ffe;
  96612. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN = 14; /* bits */
  96613. FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN = 1; /* bits */
  96614. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN = 1; /* bits */
  96615. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN = 4; /* bits */
  96616. FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN = 4; /* bits */
  96617. FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN = 4; /* bits */
  96618. FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN = 3; /* bits */
  96619. FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN = 1; /* bits */
  96620. FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN = 8; /* bits */
  96621. FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN = 16; /* bits */
  96622. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN = 2; /* bits */
  96623. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN = 4; /* bits */
  96624. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN = 4; /* bits */
  96625. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN = 5; /* bits */
  96626. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN = 5; /* bits */
  96627. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER = 15; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  96628. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER = 31; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  96629. FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[] = {
  96630. "PARTITIONED_RICE",
  96631. "PARTITIONED_RICE2"
  96632. };
  96633. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN = 4; /* bits */
  96634. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN = 5; /* bits */
  96635. FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN = 1; /* bits */
  96636. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN = 6; /* bits */
  96637. FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN = 1; /* bits */
  96638. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK = 0x00;
  96639. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK = 0x02;
  96640. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK = 0x10;
  96641. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK = 0x40;
  96642. FLAC_API const char * const FLAC__SubframeTypeString[] = {
  96643. "CONSTANT",
  96644. "VERBATIM",
  96645. "FIXED",
  96646. "LPC"
  96647. };
  96648. FLAC_API const char * const FLAC__ChannelAssignmentString[] = {
  96649. "INDEPENDENT",
  96650. "LEFT_SIDE",
  96651. "RIGHT_SIDE",
  96652. "MID_SIDE"
  96653. };
  96654. FLAC_API const char * const FLAC__FrameNumberTypeString[] = {
  96655. "FRAME_NUMBER_TYPE_FRAME_NUMBER",
  96656. "FRAME_NUMBER_TYPE_SAMPLE_NUMBER"
  96657. };
  96658. FLAC_API const char * const FLAC__MetadataTypeString[] = {
  96659. "STREAMINFO",
  96660. "PADDING",
  96661. "APPLICATION",
  96662. "SEEKTABLE",
  96663. "VORBIS_COMMENT",
  96664. "CUESHEET",
  96665. "PICTURE"
  96666. };
  96667. FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[] = {
  96668. "Other",
  96669. "32x32 pixels 'file icon' (PNG only)",
  96670. "Other file icon",
  96671. "Cover (front)",
  96672. "Cover (back)",
  96673. "Leaflet page",
  96674. "Media (e.g. label side of CD)",
  96675. "Lead artist/lead performer/soloist",
  96676. "Artist/performer",
  96677. "Conductor",
  96678. "Band/Orchestra",
  96679. "Composer",
  96680. "Lyricist/text writer",
  96681. "Recording Location",
  96682. "During recording",
  96683. "During performance",
  96684. "Movie/video screen capture",
  96685. "A bright coloured fish",
  96686. "Illustration",
  96687. "Band/artist logotype",
  96688. "Publisher/Studio logotype"
  96689. };
  96690. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate)
  96691. {
  96692. if(sample_rate == 0 || sample_rate > FLAC__MAX_SAMPLE_RATE) {
  96693. return false;
  96694. }
  96695. else
  96696. return true;
  96697. }
  96698. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate)
  96699. {
  96700. if(
  96701. !FLAC__format_sample_rate_is_valid(sample_rate) ||
  96702. (
  96703. sample_rate >= (1u << 16) &&
  96704. !(sample_rate % 1000 == 0 || sample_rate % 10 == 0)
  96705. )
  96706. ) {
  96707. return false;
  96708. }
  96709. else
  96710. return true;
  96711. }
  96712. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96713. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table)
  96714. {
  96715. unsigned i;
  96716. FLAC__uint64 prev_sample_number = 0;
  96717. FLAC__bool got_prev = false;
  96718. FLAC__ASSERT(0 != seek_table);
  96719. for(i = 0; i < seek_table->num_points; i++) {
  96720. if(got_prev) {
  96721. if(
  96722. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  96723. seek_table->points[i].sample_number <= prev_sample_number
  96724. )
  96725. return false;
  96726. }
  96727. prev_sample_number = seek_table->points[i].sample_number;
  96728. got_prev = true;
  96729. }
  96730. return true;
  96731. }
  96732. /* used as the sort predicate for qsort() */
  96733. static int JUCE_CDECL seekpoint_compare_(const FLAC__StreamMetadata_SeekPoint *l, const FLAC__StreamMetadata_SeekPoint *r)
  96734. {
  96735. /* we don't just 'return l->sample_number - r->sample_number' since the result (FLAC__int64) might overflow an 'int' */
  96736. if(l->sample_number == r->sample_number)
  96737. return 0;
  96738. else if(l->sample_number < r->sample_number)
  96739. return -1;
  96740. else
  96741. return 1;
  96742. }
  96743. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96744. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table)
  96745. {
  96746. unsigned i, j;
  96747. FLAC__bool first;
  96748. FLAC__ASSERT(0 != seek_table);
  96749. /* sort the seekpoints */
  96750. qsort(seek_table->points, seek_table->num_points, sizeof(FLAC__StreamMetadata_SeekPoint), (int (JUCE_CDECL *)(const void *, const void *))seekpoint_compare_);
  96751. /* uniquify the seekpoints */
  96752. first = true;
  96753. for(i = j = 0; i < seek_table->num_points; i++) {
  96754. if(seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER) {
  96755. if(!first) {
  96756. if(seek_table->points[i].sample_number == seek_table->points[j-1].sample_number)
  96757. continue;
  96758. }
  96759. }
  96760. first = false;
  96761. seek_table->points[j++] = seek_table->points[i];
  96762. }
  96763. for(i = j; i < seek_table->num_points; i++) {
  96764. seek_table->points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  96765. seek_table->points[i].stream_offset = 0;
  96766. seek_table->points[i].frame_samples = 0;
  96767. }
  96768. return j;
  96769. }
  96770. /*
  96771. * also disallows non-shortest-form encodings, c.f.
  96772. * http://www.unicode.org/versions/corrigendum1.html
  96773. * and a more clear explanation at the end of this section:
  96774. * http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  96775. */
  96776. static FLaC__INLINE unsigned utf8len_(const FLAC__byte *utf8)
  96777. {
  96778. FLAC__ASSERT(0 != utf8);
  96779. if ((utf8[0] & 0x80) == 0) {
  96780. return 1;
  96781. }
  96782. else if ((utf8[0] & 0xE0) == 0xC0 && (utf8[1] & 0xC0) == 0x80) {
  96783. if ((utf8[0] & 0xFE) == 0xC0) /* overlong sequence check */
  96784. return 0;
  96785. return 2;
  96786. }
  96787. else if ((utf8[0] & 0xF0) == 0xE0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80) {
  96788. if (utf8[0] == 0xE0 && (utf8[1] & 0xE0) == 0x80) /* overlong sequence check */
  96789. return 0;
  96790. /* illegal surrogates check (U+D800...U+DFFF and U+FFFE...U+FFFF) */
  96791. if (utf8[0] == 0xED && (utf8[1] & 0xE0) == 0xA0) /* D800-DFFF */
  96792. return 0;
  96793. if (utf8[0] == 0xEF && utf8[1] == 0xBF && (utf8[2] & 0xFE) == 0xBE) /* FFFE-FFFF */
  96794. return 0;
  96795. return 3;
  96796. }
  96797. else if ((utf8[0] & 0xF8) == 0xF0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80) {
  96798. if (utf8[0] == 0xF0 && (utf8[1] & 0xF0) == 0x80) /* overlong sequence check */
  96799. return 0;
  96800. return 4;
  96801. }
  96802. else if ((utf8[0] & 0xFC) == 0xF8 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80 && (utf8[4] & 0xC0) == 0x80) {
  96803. if (utf8[0] == 0xF8 && (utf8[1] & 0xF8) == 0x80) /* overlong sequence check */
  96804. return 0;
  96805. return 5;
  96806. }
  96807. 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) {
  96808. if (utf8[0] == 0xFC && (utf8[1] & 0xFC) == 0x80) /* overlong sequence check */
  96809. return 0;
  96810. return 6;
  96811. }
  96812. else {
  96813. return 0;
  96814. }
  96815. }
  96816. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name)
  96817. {
  96818. char c;
  96819. for(c = *name; c; c = *(++name))
  96820. if(c < 0x20 || c == 0x3d || c > 0x7d)
  96821. return false;
  96822. return true;
  96823. }
  96824. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length)
  96825. {
  96826. if(length == (unsigned)(-1)) {
  96827. while(*value) {
  96828. unsigned n = utf8len_(value);
  96829. if(n == 0)
  96830. return false;
  96831. value += n;
  96832. }
  96833. }
  96834. else {
  96835. const FLAC__byte *end = value + length;
  96836. while(value < end) {
  96837. unsigned n = utf8len_(value);
  96838. if(n == 0)
  96839. return false;
  96840. value += n;
  96841. }
  96842. if(value != end)
  96843. return false;
  96844. }
  96845. return true;
  96846. }
  96847. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length)
  96848. {
  96849. const FLAC__byte *s, *end;
  96850. for(s = entry, end = s + length; s < end && *s != '='; s++) {
  96851. if(*s < 0x20 || *s > 0x7D)
  96852. return false;
  96853. }
  96854. if(s == end)
  96855. return false;
  96856. s++; /* skip '=' */
  96857. while(s < end) {
  96858. unsigned n = utf8len_(s);
  96859. if(n == 0)
  96860. return false;
  96861. s += n;
  96862. }
  96863. if(s != end)
  96864. return false;
  96865. return true;
  96866. }
  96867. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96868. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation)
  96869. {
  96870. unsigned i, j;
  96871. if(check_cd_da_subset) {
  96872. if(cue_sheet->lead_in < 2 * 44100) {
  96873. if(violation) *violation = "CD-DA cue sheet must have a lead-in length of at least 2 seconds";
  96874. return false;
  96875. }
  96876. if(cue_sheet->lead_in % 588 != 0) {
  96877. if(violation) *violation = "CD-DA cue sheet lead-in length must be evenly divisible by 588 samples";
  96878. return false;
  96879. }
  96880. }
  96881. if(cue_sheet->num_tracks == 0) {
  96882. if(violation) *violation = "cue sheet must have at least one track (the lead-out)";
  96883. return false;
  96884. }
  96885. if(check_cd_da_subset && cue_sheet->tracks[cue_sheet->num_tracks-1].number != 170) {
  96886. if(violation) *violation = "CD-DA cue sheet must have a lead-out track number 170 (0xAA)";
  96887. return false;
  96888. }
  96889. for(i = 0; i < cue_sheet->num_tracks; i++) {
  96890. if(cue_sheet->tracks[i].number == 0) {
  96891. if(violation) *violation = "cue sheet may not have a track number 0";
  96892. return false;
  96893. }
  96894. if(check_cd_da_subset) {
  96895. if(!((cue_sheet->tracks[i].number >= 1 && cue_sheet->tracks[i].number <= 99) || cue_sheet->tracks[i].number == 170)) {
  96896. if(violation) *violation = "CD-DA cue sheet track number must be 1-99 or 170";
  96897. return false;
  96898. }
  96899. }
  96900. if(check_cd_da_subset && cue_sheet->tracks[i].offset % 588 != 0) {
  96901. if(violation) {
  96902. if(i == cue_sheet->num_tracks-1) /* the lead-out track... */
  96903. *violation = "CD-DA cue sheet lead-out offset must be evenly divisible by 588 samples";
  96904. else
  96905. *violation = "CD-DA cue sheet track offset must be evenly divisible by 588 samples";
  96906. }
  96907. return false;
  96908. }
  96909. if(i < cue_sheet->num_tracks - 1) {
  96910. if(cue_sheet->tracks[i].num_indices == 0) {
  96911. if(violation) *violation = "cue sheet track must have at least one index point";
  96912. return false;
  96913. }
  96914. if(cue_sheet->tracks[i].indices[0].number > 1) {
  96915. if(violation) *violation = "cue sheet track's first index number must be 0 or 1";
  96916. return false;
  96917. }
  96918. }
  96919. for(j = 0; j < cue_sheet->tracks[i].num_indices; j++) {
  96920. if(check_cd_da_subset && cue_sheet->tracks[i].indices[j].offset % 588 != 0) {
  96921. if(violation) *violation = "CD-DA cue sheet track index offset must be evenly divisible by 588 samples";
  96922. return false;
  96923. }
  96924. if(j > 0) {
  96925. if(cue_sheet->tracks[i].indices[j].number != cue_sheet->tracks[i].indices[j-1].number + 1) {
  96926. if(violation) *violation = "cue sheet track index numbers must increase by 1";
  96927. return false;
  96928. }
  96929. }
  96930. }
  96931. }
  96932. return true;
  96933. }
  96934. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96935. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation)
  96936. {
  96937. char *p;
  96938. FLAC__byte *b;
  96939. for(p = picture->mime_type; *p; p++) {
  96940. if(*p < 0x20 || *p > 0x7e) {
  96941. if(violation) *violation = "MIME type string must contain only printable ASCII characters (0x20-0x7e)";
  96942. return false;
  96943. }
  96944. }
  96945. for(b = picture->description; *b; ) {
  96946. unsigned n = utf8len_(b);
  96947. if(n == 0) {
  96948. if(violation) *violation = "description string must be valid UTF-8";
  96949. return false;
  96950. }
  96951. b += n;
  96952. }
  96953. return true;
  96954. }
  96955. /*
  96956. * These routines are private to libFLAC
  96957. */
  96958. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order)
  96959. {
  96960. return
  96961. FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(
  96962. FLAC__format_get_max_rice_partition_order_from_blocksize(blocksize),
  96963. blocksize,
  96964. predictor_order
  96965. );
  96966. }
  96967. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize)
  96968. {
  96969. unsigned max_rice_partition_order = 0;
  96970. while(!(blocksize & 1)) {
  96971. max_rice_partition_order++;
  96972. blocksize >>= 1;
  96973. }
  96974. return min(FLAC__MAX_RICE_PARTITION_ORDER, max_rice_partition_order);
  96975. }
  96976. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order)
  96977. {
  96978. unsigned max_rice_partition_order = limit;
  96979. while(max_rice_partition_order > 0 && (blocksize >> max_rice_partition_order) <= predictor_order)
  96980. max_rice_partition_order--;
  96981. FLAC__ASSERT(
  96982. (max_rice_partition_order == 0 && blocksize >= predictor_order) ||
  96983. (max_rice_partition_order > 0 && blocksize >> max_rice_partition_order > predictor_order)
  96984. );
  96985. return max_rice_partition_order;
  96986. }
  96987. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  96988. {
  96989. FLAC__ASSERT(0 != object);
  96990. object->parameters = 0;
  96991. object->raw_bits = 0;
  96992. object->capacity_by_order = 0;
  96993. }
  96994. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  96995. {
  96996. FLAC__ASSERT(0 != object);
  96997. if(0 != object->parameters)
  96998. free(object->parameters);
  96999. if(0 != object->raw_bits)
  97000. free(object->raw_bits);
  97001. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(object);
  97002. }
  97003. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order)
  97004. {
  97005. FLAC__ASSERT(0 != object);
  97006. FLAC__ASSERT(object->capacity_by_order > 0 || (0 == object->parameters && 0 == object->raw_bits));
  97007. if(object->capacity_by_order < max_partition_order) {
  97008. if(0 == (object->parameters = (unsigned*)realloc(object->parameters, sizeof(unsigned)*(1 << max_partition_order))))
  97009. return false;
  97010. if(0 == (object->raw_bits = (unsigned*)realloc(object->raw_bits, sizeof(unsigned)*(1 << max_partition_order))))
  97011. return false;
  97012. memset(object->raw_bits, 0, sizeof(unsigned)*(1 << max_partition_order));
  97013. object->capacity_by_order = max_partition_order;
  97014. }
  97015. return true;
  97016. }
  97017. #endif
  97018. /*** End of inlined file: format.c ***/
  97019. /*** Start of inlined file: lpc_flac.c ***/
  97020. /*** Start of inlined file: juce_FlacHeader.h ***/
  97021. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  97022. // tasks..
  97023. #define VERSION "1.2.1"
  97024. #define FLAC__NO_DLL 1
  97025. #if JUCE_MSVC
  97026. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  97027. #endif
  97028. #if JUCE_MAC
  97029. #define FLAC__SYS_DARWIN 1
  97030. #endif
  97031. /*** End of inlined file: juce_FlacHeader.h ***/
  97032. #if JUCE_USE_FLAC
  97033. #if HAVE_CONFIG_H
  97034. # include <config.h>
  97035. #endif
  97036. #include <math.h>
  97037. /*** Start of inlined file: lpc.h ***/
  97038. #ifndef FLAC__PRIVATE__LPC_H
  97039. #define FLAC__PRIVATE__LPC_H
  97040. #ifdef HAVE_CONFIG_H
  97041. #include <config.h>
  97042. #endif
  97043. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97044. /*
  97045. * FLAC__lpc_window_data()
  97046. * --------------------------------------------------------------------
  97047. * Applies the given window to the data.
  97048. * OPT: asm implementation
  97049. *
  97050. * IN in[0,data_len-1]
  97051. * IN window[0,data_len-1]
  97052. * OUT out[0,lag-1]
  97053. * IN data_len
  97054. */
  97055. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len);
  97056. /*
  97057. * FLAC__lpc_compute_autocorrelation()
  97058. * --------------------------------------------------------------------
  97059. * Compute the autocorrelation for lags between 0 and lag-1.
  97060. * Assumes data[] outside of [0,data_len-1] == 0.
  97061. * Asserts that lag > 0.
  97062. *
  97063. * IN data[0,data_len-1]
  97064. * IN data_len
  97065. * IN 0 < lag <= data_len
  97066. * OUT autoc[0,lag-1]
  97067. */
  97068. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97069. #ifndef FLAC__NO_ASM
  97070. # ifdef FLAC__CPU_IA32
  97071. # ifdef FLAC__HAS_NASM
  97072. void FLAC__lpc_compute_autocorrelation_asm_ia32(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97073. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97074. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97075. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97076. void FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97077. # endif
  97078. # endif
  97079. #endif
  97080. /*
  97081. * FLAC__lpc_compute_lp_coefficients()
  97082. * --------------------------------------------------------------------
  97083. * Computes LP coefficients for orders 1..max_order.
  97084. * Do not call if autoc[0] == 0.0. This means the signal is zero
  97085. * and there is no point in calculating a predictor.
  97086. *
  97087. * IN autoc[0,max_order] autocorrelation values
  97088. * IN 0 < max_order <= FLAC__MAX_LPC_ORDER max LP order to compute
  97089. * OUT lp_coeff[0,max_order-1][0,max_order-1] LP coefficients for each order
  97090. * *** IMPORTANT:
  97091. * *** lp_coeff[0,max_order-1][max_order,FLAC__MAX_LPC_ORDER-1] are untouched
  97092. * OUT error[0,max_order-1] error for each order (more
  97093. * specifically, the variance of
  97094. * the error signal times # of
  97095. * samples in the signal)
  97096. *
  97097. * Example: if max_order is 9, the LP coefficients for order 9 will be
  97098. * in lp_coeff[8][0,8], the LP coefficients for order 8 will be
  97099. * in lp_coeff[7][0,7], etc.
  97100. */
  97101. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[]);
  97102. /*
  97103. * FLAC__lpc_quantize_coefficients()
  97104. * --------------------------------------------------------------------
  97105. * Quantizes the LP coefficients. NOTE: precision + bits_per_sample
  97106. * must be less than 32 (sizeof(FLAC__int32)*8).
  97107. *
  97108. * IN lp_coeff[0,order-1] LP coefficients
  97109. * IN order LP order
  97110. * IN FLAC__MIN_QLP_COEFF_PRECISION < precision
  97111. * desired precision (in bits, including sign
  97112. * bit) of largest coefficient
  97113. * OUT qlp_coeff[0,order-1] quantized coefficients
  97114. * OUT shift # of bits to shift right to get approximated
  97115. * LP coefficients. NOTE: could be negative.
  97116. * RETURN 0 => quantization OK
  97117. * 1 => coefficients require too much shifting for *shift to
  97118. * fit in the LPC subframe header. 'shift' is unset.
  97119. * 2 => coefficients are all zero, which is bad. 'shift' is
  97120. * unset.
  97121. */
  97122. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift);
  97123. /*
  97124. * FLAC__lpc_compute_residual_from_qlp_coefficients()
  97125. * --------------------------------------------------------------------
  97126. * Compute the residual signal obtained from sutracting the predicted
  97127. * signal from the original.
  97128. *
  97129. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  97130. * IN data_len length of original signal
  97131. * IN qlp_coeff[0,order-1] quantized LP coefficients
  97132. * IN order > 0 LP order
  97133. * IN lp_quantization quantization of LP coefficients in bits
  97134. * OUT residual[0,data_len-1] residual signal
  97135. */
  97136. 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[]);
  97137. 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[]);
  97138. #ifndef FLAC__NO_ASM
  97139. # ifdef FLAC__CPU_IA32
  97140. # ifdef FLAC__HAS_NASM
  97141. 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[]);
  97142. 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[]);
  97143. # endif
  97144. # endif
  97145. #endif
  97146. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97147. /*
  97148. * FLAC__lpc_restore_signal()
  97149. * --------------------------------------------------------------------
  97150. * Restore the original signal by summing the residual and the
  97151. * predictor.
  97152. *
  97153. * IN residual[0,data_len-1] residual signal
  97154. * IN data_len length of original signal
  97155. * IN qlp_coeff[0,order-1] quantized LP coefficients
  97156. * IN order > 0 LP order
  97157. * IN lp_quantization quantization of LP coefficients in bits
  97158. * *** IMPORTANT: the caller must pass in the historical samples:
  97159. * IN data[-order,-1] previously-reconstructed historical samples
  97160. * OUT data[0,data_len-1] original signal
  97161. */
  97162. 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[]);
  97163. 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[]);
  97164. #ifndef FLAC__NO_ASM
  97165. # ifdef FLAC__CPU_IA32
  97166. # ifdef FLAC__HAS_NASM
  97167. 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[]);
  97168. 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[]);
  97169. # endif /* FLAC__HAS_NASM */
  97170. # elif defined FLAC__CPU_PPC
  97171. 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[]);
  97172. 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[]);
  97173. # endif/* FLAC__CPU_IA32 || FLAC__CPU_PPC */
  97174. #endif /* FLAC__NO_ASM */
  97175. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97176. /*
  97177. * FLAC__lpc_compute_expected_bits_per_residual_sample()
  97178. * --------------------------------------------------------------------
  97179. * Compute the expected number of bits per residual signal sample
  97180. * based on the LP error (which is related to the residual variance).
  97181. *
  97182. * IN lpc_error >= 0.0 error returned from calculating LP coefficients
  97183. * IN total_samples > 0 # of samples in residual signal
  97184. * RETURN expected bits per sample
  97185. */
  97186. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples);
  97187. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale);
  97188. /*
  97189. * FLAC__lpc_compute_best_order()
  97190. * --------------------------------------------------------------------
  97191. * Compute the best order from the array of signal errors returned
  97192. * during coefficient computation.
  97193. *
  97194. * IN lpc_error[0,max_order-1] >= 0.0 error returned from calculating LP coefficients
  97195. * IN max_order > 0 max LP order
  97196. * IN total_samples > 0 # of samples in residual signal
  97197. * IN overhead_bits_per_order # of bits overhead for each increased LP order
  97198. * (includes warmup sample size and quantized LP coefficient)
  97199. * RETURN [1,max_order] best order
  97200. */
  97201. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order);
  97202. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97203. #endif
  97204. /*** End of inlined file: lpc.h ***/
  97205. #if defined DEBUG || defined FLAC__OVERFLOW_DETECT || defined FLAC__OVERFLOW_DETECT_VERBOSE
  97206. #include <stdio.h>
  97207. #endif
  97208. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97209. #ifndef M_LN2
  97210. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  97211. #define M_LN2 0.69314718055994530942
  97212. #endif
  97213. /* OPT: #undef'ing this may improve the speed on some architectures */
  97214. #define FLAC__LPC_UNROLLED_FILTER_LOOPS
  97215. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len)
  97216. {
  97217. unsigned i;
  97218. for(i = 0; i < data_len; i++)
  97219. out[i] = in[i] * window[i];
  97220. }
  97221. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[])
  97222. {
  97223. /* a readable, but slower, version */
  97224. #if 0
  97225. FLAC__real d;
  97226. unsigned i;
  97227. FLAC__ASSERT(lag > 0);
  97228. FLAC__ASSERT(lag <= data_len);
  97229. /*
  97230. * Technically we should subtract the mean first like so:
  97231. * for(i = 0; i < data_len; i++)
  97232. * data[i] -= mean;
  97233. * but it appears not to make enough of a difference to matter, and
  97234. * most signals are already closely centered around zero
  97235. */
  97236. while(lag--) {
  97237. for(i = lag, d = 0.0; i < data_len; i++)
  97238. d += data[i] * data[i - lag];
  97239. autoc[lag] = d;
  97240. }
  97241. #endif
  97242. /*
  97243. * this version tends to run faster because of better data locality
  97244. * ('data_len' is usually much larger than 'lag')
  97245. */
  97246. FLAC__real d;
  97247. unsigned sample, coeff;
  97248. const unsigned limit = data_len - lag;
  97249. FLAC__ASSERT(lag > 0);
  97250. FLAC__ASSERT(lag <= data_len);
  97251. for(coeff = 0; coeff < lag; coeff++)
  97252. autoc[coeff] = 0.0;
  97253. for(sample = 0; sample <= limit; sample++) {
  97254. d = data[sample];
  97255. for(coeff = 0; coeff < lag; coeff++)
  97256. autoc[coeff] += d * data[sample+coeff];
  97257. }
  97258. for(; sample < data_len; sample++) {
  97259. d = data[sample];
  97260. for(coeff = 0; coeff < data_len - sample; coeff++)
  97261. autoc[coeff] += d * data[sample+coeff];
  97262. }
  97263. }
  97264. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[])
  97265. {
  97266. unsigned i, j;
  97267. FLAC__double r, err, ref[FLAC__MAX_LPC_ORDER], lpc[FLAC__MAX_LPC_ORDER];
  97268. FLAC__ASSERT(0 != max_order);
  97269. FLAC__ASSERT(0 < *max_order);
  97270. FLAC__ASSERT(*max_order <= FLAC__MAX_LPC_ORDER);
  97271. FLAC__ASSERT(autoc[0] != 0.0);
  97272. err = autoc[0];
  97273. for(i = 0; i < *max_order; i++) {
  97274. /* Sum up this iteration's reflection coefficient. */
  97275. r = -autoc[i+1];
  97276. for(j = 0; j < i; j++)
  97277. r -= lpc[j] * autoc[i-j];
  97278. ref[i] = (r/=err);
  97279. /* Update LPC coefficients and total error. */
  97280. lpc[i]=r;
  97281. for(j = 0; j < (i>>1); j++) {
  97282. FLAC__double tmp = lpc[j];
  97283. lpc[j] += r * lpc[i-1-j];
  97284. lpc[i-1-j] += r * tmp;
  97285. }
  97286. if(i & 1)
  97287. lpc[j] += lpc[j] * r;
  97288. err *= (1.0 - r * r);
  97289. /* save this order */
  97290. for(j = 0; j <= i; j++)
  97291. lp_coeff[i][j] = (FLAC__real)(-lpc[j]); /* negate FIR filter coeff to get predictor coeff */
  97292. error[i] = err;
  97293. /* see SF bug #1601812 http://sourceforge.net/tracker/index.php?func=detail&aid=1601812&group_id=13478&atid=113478 */
  97294. if(err == 0.0) {
  97295. *max_order = i+1;
  97296. return;
  97297. }
  97298. }
  97299. }
  97300. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift)
  97301. {
  97302. unsigned i;
  97303. FLAC__double cmax;
  97304. FLAC__int32 qmax, qmin;
  97305. FLAC__ASSERT(precision > 0);
  97306. FLAC__ASSERT(precision >= FLAC__MIN_QLP_COEFF_PRECISION);
  97307. /* drop one bit for the sign; from here on out we consider only |lp_coeff[i]| */
  97308. precision--;
  97309. qmax = 1 << precision;
  97310. qmin = -qmax;
  97311. qmax--;
  97312. /* calc cmax = max( |lp_coeff[i]| ) */
  97313. cmax = 0.0;
  97314. for(i = 0; i < order; i++) {
  97315. const FLAC__double d = fabs(lp_coeff[i]);
  97316. if(d > cmax)
  97317. cmax = d;
  97318. }
  97319. if(cmax <= 0.0) {
  97320. /* => coefficients are all 0, which means our constant-detect didn't work */
  97321. return 2;
  97322. }
  97323. else {
  97324. const int max_shiftlimit = (1 << (FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN-1)) - 1;
  97325. const int min_shiftlimit = -max_shiftlimit - 1;
  97326. int log2cmax;
  97327. (void)frexp(cmax, &log2cmax);
  97328. log2cmax--;
  97329. *shift = (int)precision - log2cmax - 1;
  97330. if(*shift > max_shiftlimit)
  97331. *shift = max_shiftlimit;
  97332. else if(*shift < min_shiftlimit)
  97333. return 1;
  97334. }
  97335. if(*shift >= 0) {
  97336. FLAC__double error = 0.0;
  97337. FLAC__int32 q;
  97338. for(i = 0; i < order; i++) {
  97339. error += lp_coeff[i] * (1 << *shift);
  97340. #if 1 /* unfortunately lround() is C99 */
  97341. if(error >= 0.0)
  97342. q = (FLAC__int32)(error + 0.5);
  97343. else
  97344. q = (FLAC__int32)(error - 0.5);
  97345. #else
  97346. q = lround(error);
  97347. #endif
  97348. #ifdef FLAC__OVERFLOW_DETECT
  97349. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  97350. 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]);
  97351. else if(q < qmin)
  97352. 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]);
  97353. #endif
  97354. if(q > qmax)
  97355. q = qmax;
  97356. else if(q < qmin)
  97357. q = qmin;
  97358. error -= q;
  97359. qlp_coeff[i] = q;
  97360. }
  97361. }
  97362. /* negative shift is very rare but due to design flaw, negative shift is
  97363. * a NOP in the decoder, so it must be handled specially by scaling down
  97364. * coeffs
  97365. */
  97366. else {
  97367. const int nshift = -(*shift);
  97368. FLAC__double error = 0.0;
  97369. FLAC__int32 q;
  97370. #ifdef DEBUG
  97371. fprintf(stderr,"FLAC__lpc_quantize_coefficients: negative shift=%d order=%u cmax=%f\n", *shift, order, cmax);
  97372. #endif
  97373. for(i = 0; i < order; i++) {
  97374. error += lp_coeff[i] / (1 << nshift);
  97375. #if 1 /* unfortunately lround() is C99 */
  97376. if(error >= 0.0)
  97377. q = (FLAC__int32)(error + 0.5);
  97378. else
  97379. q = (FLAC__int32)(error - 0.5);
  97380. #else
  97381. q = lround(error);
  97382. #endif
  97383. #ifdef FLAC__OVERFLOW_DETECT
  97384. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  97385. 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]);
  97386. else if(q < qmin)
  97387. 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]);
  97388. #endif
  97389. if(q > qmax)
  97390. q = qmax;
  97391. else if(q < qmin)
  97392. q = qmin;
  97393. error -= q;
  97394. qlp_coeff[i] = q;
  97395. }
  97396. *shift = 0;
  97397. }
  97398. return 0;
  97399. }
  97400. 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[])
  97401. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97402. {
  97403. FLAC__int64 sumo;
  97404. unsigned i, j;
  97405. FLAC__int32 sum;
  97406. const FLAC__int32 *history;
  97407. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97408. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97409. for(i=0;i<order;i++)
  97410. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97411. fprintf(stderr,"\n");
  97412. #endif
  97413. FLAC__ASSERT(order > 0);
  97414. for(i = 0; i < data_len; i++) {
  97415. sumo = 0;
  97416. sum = 0;
  97417. history = data;
  97418. for(j = 0; j < order; j++) {
  97419. sum += qlp_coeff[j] * (*(--history));
  97420. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  97421. #if defined _MSC_VER
  97422. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  97423. 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);
  97424. #else
  97425. if(sumo > 2147483647ll || sumo < -2147483648ll)
  97426. 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);
  97427. #endif
  97428. }
  97429. *(residual++) = *(data++) - (sum >> lp_quantization);
  97430. }
  97431. /* Here's a slower but clearer version:
  97432. for(i = 0; i < data_len; i++) {
  97433. sum = 0;
  97434. for(j = 0; j < order; j++)
  97435. sum += qlp_coeff[j] * data[i-j-1];
  97436. residual[i] = data[i] - (sum >> lp_quantization);
  97437. }
  97438. */
  97439. }
  97440. #else /* fully unrolled version for normal use */
  97441. {
  97442. int i;
  97443. FLAC__int32 sum;
  97444. FLAC__ASSERT(order > 0);
  97445. FLAC__ASSERT(order <= 32);
  97446. /*
  97447. * We do unique versions up to 12th order since that's the subset limit.
  97448. * Also they are roughly ordered to match frequency of occurrence to
  97449. * minimize branching.
  97450. */
  97451. if(order <= 12) {
  97452. if(order > 8) {
  97453. if(order > 10) {
  97454. if(order == 12) {
  97455. for(i = 0; i < (int)data_len; i++) {
  97456. sum = 0;
  97457. sum += qlp_coeff[11] * data[i-12];
  97458. sum += qlp_coeff[10] * data[i-11];
  97459. sum += qlp_coeff[9] * data[i-10];
  97460. sum += qlp_coeff[8] * data[i-9];
  97461. sum += qlp_coeff[7] * data[i-8];
  97462. sum += qlp_coeff[6] * data[i-7];
  97463. sum += qlp_coeff[5] * data[i-6];
  97464. sum += qlp_coeff[4] * data[i-5];
  97465. sum += qlp_coeff[3] * data[i-4];
  97466. sum += qlp_coeff[2] * data[i-3];
  97467. sum += qlp_coeff[1] * data[i-2];
  97468. sum += qlp_coeff[0] * data[i-1];
  97469. residual[i] = data[i] - (sum >> lp_quantization);
  97470. }
  97471. }
  97472. else { /* order == 11 */
  97473. for(i = 0; i < (int)data_len; i++) {
  97474. sum = 0;
  97475. sum += qlp_coeff[10] * data[i-11];
  97476. sum += qlp_coeff[9] * data[i-10];
  97477. sum += qlp_coeff[8] * data[i-9];
  97478. sum += qlp_coeff[7] * data[i-8];
  97479. sum += qlp_coeff[6] * data[i-7];
  97480. sum += qlp_coeff[5] * data[i-6];
  97481. sum += qlp_coeff[4] * data[i-5];
  97482. sum += qlp_coeff[3] * data[i-4];
  97483. sum += qlp_coeff[2] * data[i-3];
  97484. sum += qlp_coeff[1] * data[i-2];
  97485. sum += qlp_coeff[0] * data[i-1];
  97486. residual[i] = data[i] - (sum >> lp_quantization);
  97487. }
  97488. }
  97489. }
  97490. else {
  97491. if(order == 10) {
  97492. for(i = 0; i < (int)data_len; i++) {
  97493. sum = 0;
  97494. sum += qlp_coeff[9] * data[i-10];
  97495. sum += qlp_coeff[8] * data[i-9];
  97496. sum += qlp_coeff[7] * data[i-8];
  97497. sum += qlp_coeff[6] * data[i-7];
  97498. sum += qlp_coeff[5] * data[i-6];
  97499. sum += qlp_coeff[4] * data[i-5];
  97500. sum += qlp_coeff[3] * data[i-4];
  97501. sum += qlp_coeff[2] * data[i-3];
  97502. sum += qlp_coeff[1] * data[i-2];
  97503. sum += qlp_coeff[0] * data[i-1];
  97504. residual[i] = data[i] - (sum >> lp_quantization);
  97505. }
  97506. }
  97507. else { /* order == 9 */
  97508. for(i = 0; i < (int)data_len; i++) {
  97509. sum = 0;
  97510. sum += qlp_coeff[8] * data[i-9];
  97511. sum += qlp_coeff[7] * data[i-8];
  97512. sum += qlp_coeff[6] * data[i-7];
  97513. sum += qlp_coeff[5] * data[i-6];
  97514. sum += qlp_coeff[4] * data[i-5];
  97515. sum += qlp_coeff[3] * data[i-4];
  97516. sum += qlp_coeff[2] * data[i-3];
  97517. sum += qlp_coeff[1] * data[i-2];
  97518. sum += qlp_coeff[0] * data[i-1];
  97519. residual[i] = data[i] - (sum >> lp_quantization);
  97520. }
  97521. }
  97522. }
  97523. }
  97524. else if(order > 4) {
  97525. if(order > 6) {
  97526. if(order == 8) {
  97527. for(i = 0; i < (int)data_len; i++) {
  97528. sum = 0;
  97529. sum += qlp_coeff[7] * data[i-8];
  97530. sum += qlp_coeff[6] * data[i-7];
  97531. sum += qlp_coeff[5] * data[i-6];
  97532. sum += qlp_coeff[4] * data[i-5];
  97533. sum += qlp_coeff[3] * data[i-4];
  97534. sum += qlp_coeff[2] * data[i-3];
  97535. sum += qlp_coeff[1] * data[i-2];
  97536. sum += qlp_coeff[0] * data[i-1];
  97537. residual[i] = data[i] - (sum >> lp_quantization);
  97538. }
  97539. }
  97540. else { /* order == 7 */
  97541. for(i = 0; i < (int)data_len; i++) {
  97542. sum = 0;
  97543. sum += qlp_coeff[6] * data[i-7];
  97544. sum += qlp_coeff[5] * data[i-6];
  97545. sum += qlp_coeff[4] * data[i-5];
  97546. sum += qlp_coeff[3] * data[i-4];
  97547. sum += qlp_coeff[2] * data[i-3];
  97548. sum += qlp_coeff[1] * data[i-2];
  97549. sum += qlp_coeff[0] * data[i-1];
  97550. residual[i] = data[i] - (sum >> lp_quantization);
  97551. }
  97552. }
  97553. }
  97554. else {
  97555. if(order == 6) {
  97556. for(i = 0; i < (int)data_len; i++) {
  97557. sum = 0;
  97558. sum += qlp_coeff[5] * data[i-6];
  97559. sum += qlp_coeff[4] * data[i-5];
  97560. sum += qlp_coeff[3] * data[i-4];
  97561. sum += qlp_coeff[2] * data[i-3];
  97562. sum += qlp_coeff[1] * data[i-2];
  97563. sum += qlp_coeff[0] * data[i-1];
  97564. residual[i] = data[i] - (sum >> lp_quantization);
  97565. }
  97566. }
  97567. else { /* order == 5 */
  97568. for(i = 0; i < (int)data_len; i++) {
  97569. sum = 0;
  97570. sum += qlp_coeff[4] * data[i-5];
  97571. sum += qlp_coeff[3] * data[i-4];
  97572. sum += qlp_coeff[2] * data[i-3];
  97573. sum += qlp_coeff[1] * data[i-2];
  97574. sum += qlp_coeff[0] * data[i-1];
  97575. residual[i] = data[i] - (sum >> lp_quantization);
  97576. }
  97577. }
  97578. }
  97579. }
  97580. else {
  97581. if(order > 2) {
  97582. if(order == 4) {
  97583. for(i = 0; i < (int)data_len; i++) {
  97584. sum = 0;
  97585. sum += qlp_coeff[3] * data[i-4];
  97586. sum += qlp_coeff[2] * data[i-3];
  97587. sum += qlp_coeff[1] * data[i-2];
  97588. sum += qlp_coeff[0] * data[i-1];
  97589. residual[i] = data[i] - (sum >> lp_quantization);
  97590. }
  97591. }
  97592. else { /* order == 3 */
  97593. for(i = 0; i < (int)data_len; i++) {
  97594. sum = 0;
  97595. sum += qlp_coeff[2] * data[i-3];
  97596. sum += qlp_coeff[1] * data[i-2];
  97597. sum += qlp_coeff[0] * data[i-1];
  97598. residual[i] = data[i] - (sum >> lp_quantization);
  97599. }
  97600. }
  97601. }
  97602. else {
  97603. if(order == 2) {
  97604. for(i = 0; i < (int)data_len; i++) {
  97605. sum = 0;
  97606. sum += qlp_coeff[1] * data[i-2];
  97607. sum += qlp_coeff[0] * data[i-1];
  97608. residual[i] = data[i] - (sum >> lp_quantization);
  97609. }
  97610. }
  97611. else { /* order == 1 */
  97612. for(i = 0; i < (int)data_len; i++)
  97613. residual[i] = data[i] - ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  97614. }
  97615. }
  97616. }
  97617. }
  97618. else { /* order > 12 */
  97619. for(i = 0; i < (int)data_len; i++) {
  97620. sum = 0;
  97621. switch(order) {
  97622. case 32: sum += qlp_coeff[31] * data[i-32];
  97623. case 31: sum += qlp_coeff[30] * data[i-31];
  97624. case 30: sum += qlp_coeff[29] * data[i-30];
  97625. case 29: sum += qlp_coeff[28] * data[i-29];
  97626. case 28: sum += qlp_coeff[27] * data[i-28];
  97627. case 27: sum += qlp_coeff[26] * data[i-27];
  97628. case 26: sum += qlp_coeff[25] * data[i-26];
  97629. case 25: sum += qlp_coeff[24] * data[i-25];
  97630. case 24: sum += qlp_coeff[23] * data[i-24];
  97631. case 23: sum += qlp_coeff[22] * data[i-23];
  97632. case 22: sum += qlp_coeff[21] * data[i-22];
  97633. case 21: sum += qlp_coeff[20] * data[i-21];
  97634. case 20: sum += qlp_coeff[19] * data[i-20];
  97635. case 19: sum += qlp_coeff[18] * data[i-19];
  97636. case 18: sum += qlp_coeff[17] * data[i-18];
  97637. case 17: sum += qlp_coeff[16] * data[i-17];
  97638. case 16: sum += qlp_coeff[15] * data[i-16];
  97639. case 15: sum += qlp_coeff[14] * data[i-15];
  97640. case 14: sum += qlp_coeff[13] * data[i-14];
  97641. case 13: sum += qlp_coeff[12] * data[i-13];
  97642. sum += qlp_coeff[11] * data[i-12];
  97643. sum += qlp_coeff[10] * data[i-11];
  97644. sum += qlp_coeff[ 9] * data[i-10];
  97645. sum += qlp_coeff[ 8] * data[i- 9];
  97646. sum += qlp_coeff[ 7] * data[i- 8];
  97647. sum += qlp_coeff[ 6] * data[i- 7];
  97648. sum += qlp_coeff[ 5] * data[i- 6];
  97649. sum += qlp_coeff[ 4] * data[i- 5];
  97650. sum += qlp_coeff[ 3] * data[i- 4];
  97651. sum += qlp_coeff[ 2] * data[i- 3];
  97652. sum += qlp_coeff[ 1] * data[i- 2];
  97653. sum += qlp_coeff[ 0] * data[i- 1];
  97654. }
  97655. residual[i] = data[i] - (sum >> lp_quantization);
  97656. }
  97657. }
  97658. }
  97659. #endif
  97660. 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[])
  97661. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97662. {
  97663. unsigned i, j;
  97664. FLAC__int64 sum;
  97665. const FLAC__int32 *history;
  97666. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97667. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97668. for(i=0;i<order;i++)
  97669. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97670. fprintf(stderr,"\n");
  97671. #endif
  97672. FLAC__ASSERT(order > 0);
  97673. for(i = 0; i < data_len; i++) {
  97674. sum = 0;
  97675. history = data;
  97676. for(j = 0; j < order; j++)
  97677. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  97678. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  97679. #if defined _MSC_VER
  97680. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  97681. #else
  97682. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  97683. #endif
  97684. break;
  97685. }
  97686. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*data) - (sum >> lp_quantization)) > 32) {
  97687. #if defined _MSC_VER
  97688. 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));
  97689. #else
  97690. 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)));
  97691. #endif
  97692. break;
  97693. }
  97694. *(residual++) = *(data++) - (FLAC__int32)(sum >> lp_quantization);
  97695. }
  97696. }
  97697. #else /* fully unrolled version for normal use */
  97698. {
  97699. int i;
  97700. FLAC__int64 sum;
  97701. FLAC__ASSERT(order > 0);
  97702. FLAC__ASSERT(order <= 32);
  97703. /*
  97704. * We do unique versions up to 12th order since that's the subset limit.
  97705. * Also they are roughly ordered to match frequency of occurrence to
  97706. * minimize branching.
  97707. */
  97708. if(order <= 12) {
  97709. if(order > 8) {
  97710. if(order > 10) {
  97711. if(order == 12) {
  97712. for(i = 0; i < (int)data_len; i++) {
  97713. sum = 0;
  97714. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97715. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97716. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97717. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97718. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97719. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97720. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97721. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97722. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97723. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97724. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97725. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97726. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97727. }
  97728. }
  97729. else { /* order == 11 */
  97730. for(i = 0; i < (int)data_len; i++) {
  97731. sum = 0;
  97732. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97733. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97734. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97735. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97736. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97737. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97738. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97739. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97740. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97741. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97742. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97743. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97744. }
  97745. }
  97746. }
  97747. else {
  97748. if(order == 10) {
  97749. for(i = 0; i < (int)data_len; i++) {
  97750. sum = 0;
  97751. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97752. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97753. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97754. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97755. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97756. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97757. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97758. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97759. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97760. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97761. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97762. }
  97763. }
  97764. else { /* order == 9 */
  97765. for(i = 0; i < (int)data_len; i++) {
  97766. sum = 0;
  97767. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97768. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97769. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97770. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97771. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97772. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97773. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97774. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97775. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97776. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97777. }
  97778. }
  97779. }
  97780. }
  97781. else if(order > 4) {
  97782. if(order > 6) {
  97783. if(order == 8) {
  97784. for(i = 0; i < (int)data_len; i++) {
  97785. sum = 0;
  97786. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97787. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97788. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97789. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97790. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97791. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97792. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97793. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97794. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97795. }
  97796. }
  97797. else { /* order == 7 */
  97798. for(i = 0; i < (int)data_len; i++) {
  97799. sum = 0;
  97800. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97801. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97802. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97803. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97804. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97805. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97806. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97807. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97808. }
  97809. }
  97810. }
  97811. else {
  97812. if(order == 6) {
  97813. for(i = 0; i < (int)data_len; i++) {
  97814. sum = 0;
  97815. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97816. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97817. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97818. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97819. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97820. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97821. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97822. }
  97823. }
  97824. else { /* order == 5 */
  97825. for(i = 0; i < (int)data_len; i++) {
  97826. sum = 0;
  97827. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97828. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97829. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97830. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97831. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97832. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97833. }
  97834. }
  97835. }
  97836. }
  97837. else {
  97838. if(order > 2) {
  97839. if(order == 4) {
  97840. for(i = 0; i < (int)data_len; i++) {
  97841. sum = 0;
  97842. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97843. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97844. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97845. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97846. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97847. }
  97848. }
  97849. else { /* order == 3 */
  97850. for(i = 0; i < (int)data_len; i++) {
  97851. sum = 0;
  97852. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97853. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97854. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97855. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97856. }
  97857. }
  97858. }
  97859. else {
  97860. if(order == 2) {
  97861. for(i = 0; i < (int)data_len; i++) {
  97862. sum = 0;
  97863. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97864. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97865. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97866. }
  97867. }
  97868. else { /* order == 1 */
  97869. for(i = 0; i < (int)data_len; i++)
  97870. residual[i] = data[i] - (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  97871. }
  97872. }
  97873. }
  97874. }
  97875. else { /* order > 12 */
  97876. for(i = 0; i < (int)data_len; i++) {
  97877. sum = 0;
  97878. switch(order) {
  97879. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  97880. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  97881. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  97882. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  97883. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  97884. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  97885. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  97886. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  97887. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  97888. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  97889. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  97890. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  97891. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  97892. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  97893. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  97894. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  97895. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  97896. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  97897. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  97898. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  97899. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97900. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97901. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  97902. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  97903. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  97904. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  97905. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  97906. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  97907. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  97908. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  97909. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  97910. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  97911. }
  97912. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97913. }
  97914. }
  97915. }
  97916. #endif
  97917. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97918. 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[])
  97919. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97920. {
  97921. FLAC__int64 sumo;
  97922. unsigned i, j;
  97923. FLAC__int32 sum;
  97924. const FLAC__int32 *r = residual, *history;
  97925. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97926. fprintf(stderr,"FLAC__lpc_restore_signal: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97927. for(i=0;i<order;i++)
  97928. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97929. fprintf(stderr,"\n");
  97930. #endif
  97931. FLAC__ASSERT(order > 0);
  97932. for(i = 0; i < data_len; i++) {
  97933. sumo = 0;
  97934. sum = 0;
  97935. history = data;
  97936. for(j = 0; j < order; j++) {
  97937. sum += qlp_coeff[j] * (*(--history));
  97938. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  97939. #if defined _MSC_VER
  97940. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  97941. 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);
  97942. #else
  97943. if(sumo > 2147483647ll || sumo < -2147483648ll)
  97944. 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);
  97945. #endif
  97946. }
  97947. *(data++) = *(r++) + (sum >> lp_quantization);
  97948. }
  97949. /* Here's a slower but clearer version:
  97950. for(i = 0; i < data_len; i++) {
  97951. sum = 0;
  97952. for(j = 0; j < order; j++)
  97953. sum += qlp_coeff[j] * data[i-j-1];
  97954. data[i] = residual[i] + (sum >> lp_quantization);
  97955. }
  97956. */
  97957. }
  97958. #else /* fully unrolled version for normal use */
  97959. {
  97960. int i;
  97961. FLAC__int32 sum;
  97962. FLAC__ASSERT(order > 0);
  97963. FLAC__ASSERT(order <= 32);
  97964. /*
  97965. * We do unique versions up to 12th order since that's the subset limit.
  97966. * Also they are roughly ordered to match frequency of occurrence to
  97967. * minimize branching.
  97968. */
  97969. if(order <= 12) {
  97970. if(order > 8) {
  97971. if(order > 10) {
  97972. if(order == 12) {
  97973. for(i = 0; i < (int)data_len; i++) {
  97974. sum = 0;
  97975. sum += qlp_coeff[11] * data[i-12];
  97976. sum += qlp_coeff[10] * data[i-11];
  97977. sum += qlp_coeff[9] * data[i-10];
  97978. sum += qlp_coeff[8] * data[i-9];
  97979. sum += qlp_coeff[7] * data[i-8];
  97980. sum += qlp_coeff[6] * data[i-7];
  97981. sum += qlp_coeff[5] * data[i-6];
  97982. sum += qlp_coeff[4] * data[i-5];
  97983. sum += qlp_coeff[3] * data[i-4];
  97984. sum += qlp_coeff[2] * data[i-3];
  97985. sum += qlp_coeff[1] * data[i-2];
  97986. sum += qlp_coeff[0] * data[i-1];
  97987. data[i] = residual[i] + (sum >> lp_quantization);
  97988. }
  97989. }
  97990. else { /* order == 11 */
  97991. for(i = 0; i < (int)data_len; i++) {
  97992. sum = 0;
  97993. sum += qlp_coeff[10] * data[i-11];
  97994. sum += qlp_coeff[9] * data[i-10];
  97995. sum += qlp_coeff[8] * data[i-9];
  97996. sum += qlp_coeff[7] * data[i-8];
  97997. sum += qlp_coeff[6] * data[i-7];
  97998. sum += qlp_coeff[5] * data[i-6];
  97999. sum += qlp_coeff[4] * data[i-5];
  98000. sum += qlp_coeff[3] * data[i-4];
  98001. sum += qlp_coeff[2] * data[i-3];
  98002. sum += qlp_coeff[1] * data[i-2];
  98003. sum += qlp_coeff[0] * data[i-1];
  98004. data[i] = residual[i] + (sum >> lp_quantization);
  98005. }
  98006. }
  98007. }
  98008. else {
  98009. if(order == 10) {
  98010. for(i = 0; i < (int)data_len; i++) {
  98011. sum = 0;
  98012. sum += qlp_coeff[9] * data[i-10];
  98013. sum += qlp_coeff[8] * data[i-9];
  98014. sum += qlp_coeff[7] * data[i-8];
  98015. sum += qlp_coeff[6] * data[i-7];
  98016. sum += qlp_coeff[5] * data[i-6];
  98017. sum += qlp_coeff[4] * data[i-5];
  98018. sum += qlp_coeff[3] * data[i-4];
  98019. sum += qlp_coeff[2] * data[i-3];
  98020. sum += qlp_coeff[1] * data[i-2];
  98021. sum += qlp_coeff[0] * data[i-1];
  98022. data[i] = residual[i] + (sum >> lp_quantization);
  98023. }
  98024. }
  98025. else { /* order == 9 */
  98026. for(i = 0; i < (int)data_len; i++) {
  98027. sum = 0;
  98028. sum += qlp_coeff[8] * data[i-9];
  98029. sum += qlp_coeff[7] * data[i-8];
  98030. sum += qlp_coeff[6] * data[i-7];
  98031. sum += qlp_coeff[5] * data[i-6];
  98032. sum += qlp_coeff[4] * data[i-5];
  98033. sum += qlp_coeff[3] * data[i-4];
  98034. sum += qlp_coeff[2] * data[i-3];
  98035. sum += qlp_coeff[1] * data[i-2];
  98036. sum += qlp_coeff[0] * data[i-1];
  98037. data[i] = residual[i] + (sum >> lp_quantization);
  98038. }
  98039. }
  98040. }
  98041. }
  98042. else if(order > 4) {
  98043. if(order > 6) {
  98044. if(order == 8) {
  98045. for(i = 0; i < (int)data_len; i++) {
  98046. sum = 0;
  98047. sum += qlp_coeff[7] * data[i-8];
  98048. sum += qlp_coeff[6] * data[i-7];
  98049. sum += qlp_coeff[5] * data[i-6];
  98050. sum += qlp_coeff[4] * data[i-5];
  98051. sum += qlp_coeff[3] * data[i-4];
  98052. sum += qlp_coeff[2] * data[i-3];
  98053. sum += qlp_coeff[1] * data[i-2];
  98054. sum += qlp_coeff[0] * data[i-1];
  98055. data[i] = residual[i] + (sum >> lp_quantization);
  98056. }
  98057. }
  98058. else { /* order == 7 */
  98059. for(i = 0; i < (int)data_len; i++) {
  98060. sum = 0;
  98061. sum += qlp_coeff[6] * data[i-7];
  98062. sum += qlp_coeff[5] * data[i-6];
  98063. sum += qlp_coeff[4] * data[i-5];
  98064. sum += qlp_coeff[3] * data[i-4];
  98065. sum += qlp_coeff[2] * data[i-3];
  98066. sum += qlp_coeff[1] * data[i-2];
  98067. sum += qlp_coeff[0] * data[i-1];
  98068. data[i] = residual[i] + (sum >> lp_quantization);
  98069. }
  98070. }
  98071. }
  98072. else {
  98073. if(order == 6) {
  98074. for(i = 0; i < (int)data_len; i++) {
  98075. sum = 0;
  98076. sum += qlp_coeff[5] * data[i-6];
  98077. sum += qlp_coeff[4] * data[i-5];
  98078. sum += qlp_coeff[3] * data[i-4];
  98079. sum += qlp_coeff[2] * data[i-3];
  98080. sum += qlp_coeff[1] * data[i-2];
  98081. sum += qlp_coeff[0] * data[i-1];
  98082. data[i] = residual[i] + (sum >> lp_quantization);
  98083. }
  98084. }
  98085. else { /* order == 5 */
  98086. for(i = 0; i < (int)data_len; i++) {
  98087. sum = 0;
  98088. sum += qlp_coeff[4] * data[i-5];
  98089. sum += qlp_coeff[3] * data[i-4];
  98090. sum += qlp_coeff[2] * data[i-3];
  98091. sum += qlp_coeff[1] * data[i-2];
  98092. sum += qlp_coeff[0] * data[i-1];
  98093. data[i] = residual[i] + (sum >> lp_quantization);
  98094. }
  98095. }
  98096. }
  98097. }
  98098. else {
  98099. if(order > 2) {
  98100. if(order == 4) {
  98101. for(i = 0; i < (int)data_len; i++) {
  98102. sum = 0;
  98103. sum += qlp_coeff[3] * data[i-4];
  98104. sum += qlp_coeff[2] * data[i-3];
  98105. sum += qlp_coeff[1] * data[i-2];
  98106. sum += qlp_coeff[0] * data[i-1];
  98107. data[i] = residual[i] + (sum >> lp_quantization);
  98108. }
  98109. }
  98110. else { /* order == 3 */
  98111. for(i = 0; i < (int)data_len; i++) {
  98112. sum = 0;
  98113. sum += qlp_coeff[2] * data[i-3];
  98114. sum += qlp_coeff[1] * data[i-2];
  98115. sum += qlp_coeff[0] * data[i-1];
  98116. data[i] = residual[i] + (sum >> lp_quantization);
  98117. }
  98118. }
  98119. }
  98120. else {
  98121. if(order == 2) {
  98122. for(i = 0; i < (int)data_len; i++) {
  98123. sum = 0;
  98124. sum += qlp_coeff[1] * data[i-2];
  98125. sum += qlp_coeff[0] * data[i-1];
  98126. data[i] = residual[i] + (sum >> lp_quantization);
  98127. }
  98128. }
  98129. else { /* order == 1 */
  98130. for(i = 0; i < (int)data_len; i++)
  98131. data[i] = residual[i] + ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  98132. }
  98133. }
  98134. }
  98135. }
  98136. else { /* order > 12 */
  98137. for(i = 0; i < (int)data_len; i++) {
  98138. sum = 0;
  98139. switch(order) {
  98140. case 32: sum += qlp_coeff[31] * data[i-32];
  98141. case 31: sum += qlp_coeff[30] * data[i-31];
  98142. case 30: sum += qlp_coeff[29] * data[i-30];
  98143. case 29: sum += qlp_coeff[28] * data[i-29];
  98144. case 28: sum += qlp_coeff[27] * data[i-28];
  98145. case 27: sum += qlp_coeff[26] * data[i-27];
  98146. case 26: sum += qlp_coeff[25] * data[i-26];
  98147. case 25: sum += qlp_coeff[24] * data[i-25];
  98148. case 24: sum += qlp_coeff[23] * data[i-24];
  98149. case 23: sum += qlp_coeff[22] * data[i-23];
  98150. case 22: sum += qlp_coeff[21] * data[i-22];
  98151. case 21: sum += qlp_coeff[20] * data[i-21];
  98152. case 20: sum += qlp_coeff[19] * data[i-20];
  98153. case 19: sum += qlp_coeff[18] * data[i-19];
  98154. case 18: sum += qlp_coeff[17] * data[i-18];
  98155. case 17: sum += qlp_coeff[16] * data[i-17];
  98156. case 16: sum += qlp_coeff[15] * data[i-16];
  98157. case 15: sum += qlp_coeff[14] * data[i-15];
  98158. case 14: sum += qlp_coeff[13] * data[i-14];
  98159. case 13: sum += qlp_coeff[12] * data[i-13];
  98160. sum += qlp_coeff[11] * data[i-12];
  98161. sum += qlp_coeff[10] * data[i-11];
  98162. sum += qlp_coeff[ 9] * data[i-10];
  98163. sum += qlp_coeff[ 8] * data[i- 9];
  98164. sum += qlp_coeff[ 7] * data[i- 8];
  98165. sum += qlp_coeff[ 6] * data[i- 7];
  98166. sum += qlp_coeff[ 5] * data[i- 6];
  98167. sum += qlp_coeff[ 4] * data[i- 5];
  98168. sum += qlp_coeff[ 3] * data[i- 4];
  98169. sum += qlp_coeff[ 2] * data[i- 3];
  98170. sum += qlp_coeff[ 1] * data[i- 2];
  98171. sum += qlp_coeff[ 0] * data[i- 1];
  98172. }
  98173. data[i] = residual[i] + (sum >> lp_quantization);
  98174. }
  98175. }
  98176. }
  98177. #endif
  98178. 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[])
  98179. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  98180. {
  98181. unsigned i, j;
  98182. FLAC__int64 sum;
  98183. const FLAC__int32 *r = residual, *history;
  98184. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  98185. fprintf(stderr,"FLAC__lpc_restore_signal_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  98186. for(i=0;i<order;i++)
  98187. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  98188. fprintf(stderr,"\n");
  98189. #endif
  98190. FLAC__ASSERT(order > 0);
  98191. for(i = 0; i < data_len; i++) {
  98192. sum = 0;
  98193. history = data;
  98194. for(j = 0; j < order; j++)
  98195. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  98196. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  98197. #ifdef _MSC_VER
  98198. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  98199. #else
  98200. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  98201. #endif
  98202. break;
  98203. }
  98204. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*r) + (sum >> lp_quantization)) > 32) {
  98205. #ifdef _MSC_VER
  98206. 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));
  98207. #else
  98208. 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)));
  98209. #endif
  98210. break;
  98211. }
  98212. *(data++) = *(r++) + (FLAC__int32)(sum >> lp_quantization);
  98213. }
  98214. }
  98215. #else /* fully unrolled version for normal use */
  98216. {
  98217. int i;
  98218. FLAC__int64 sum;
  98219. FLAC__ASSERT(order > 0);
  98220. FLAC__ASSERT(order <= 32);
  98221. /*
  98222. * We do unique versions up to 12th order since that's the subset limit.
  98223. * Also they are roughly ordered to match frequency of occurrence to
  98224. * minimize branching.
  98225. */
  98226. if(order <= 12) {
  98227. if(order > 8) {
  98228. if(order > 10) {
  98229. if(order == 12) {
  98230. for(i = 0; i < (int)data_len; i++) {
  98231. sum = 0;
  98232. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  98233. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98234. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  98235. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98236. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98237. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98238. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98239. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98240. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98241. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98242. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98243. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98244. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98245. }
  98246. }
  98247. else { /* order == 11 */
  98248. for(i = 0; i < (int)data_len; i++) {
  98249. sum = 0;
  98250. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98251. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  98252. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98253. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98254. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98255. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98256. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98257. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98258. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98259. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98260. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98261. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98262. }
  98263. }
  98264. }
  98265. else {
  98266. if(order == 10) {
  98267. for(i = 0; i < (int)data_len; i++) {
  98268. sum = 0;
  98269. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  98270. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98271. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98272. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98273. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98274. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98275. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98276. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98277. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98278. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98279. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98280. }
  98281. }
  98282. else { /* order == 9 */
  98283. for(i = 0; i < (int)data_len; i++) {
  98284. sum = 0;
  98285. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98286. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98287. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98288. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98289. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98290. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98291. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98292. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98293. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98294. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98295. }
  98296. }
  98297. }
  98298. }
  98299. else if(order > 4) {
  98300. if(order > 6) {
  98301. if(order == 8) {
  98302. for(i = 0; i < (int)data_len; i++) {
  98303. sum = 0;
  98304. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98305. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98306. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98307. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98308. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98309. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98310. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98311. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98312. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98313. }
  98314. }
  98315. else { /* order == 7 */
  98316. for(i = 0; i < (int)data_len; i++) {
  98317. sum = 0;
  98318. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98319. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98320. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98321. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98322. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98323. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98324. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98325. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98326. }
  98327. }
  98328. }
  98329. else {
  98330. if(order == 6) {
  98331. for(i = 0; i < (int)data_len; i++) {
  98332. sum = 0;
  98333. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98334. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98335. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98336. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98337. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98338. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98339. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98340. }
  98341. }
  98342. else { /* order == 5 */
  98343. for(i = 0; i < (int)data_len; i++) {
  98344. sum = 0;
  98345. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98346. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98347. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98348. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98349. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98350. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98351. }
  98352. }
  98353. }
  98354. }
  98355. else {
  98356. if(order > 2) {
  98357. if(order == 4) {
  98358. for(i = 0; i < (int)data_len; i++) {
  98359. sum = 0;
  98360. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98361. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98362. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98363. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98364. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98365. }
  98366. }
  98367. else { /* order == 3 */
  98368. for(i = 0; i < (int)data_len; i++) {
  98369. sum = 0;
  98370. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98371. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98372. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98373. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98374. }
  98375. }
  98376. }
  98377. else {
  98378. if(order == 2) {
  98379. for(i = 0; i < (int)data_len; i++) {
  98380. sum = 0;
  98381. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98382. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98383. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98384. }
  98385. }
  98386. else { /* order == 1 */
  98387. for(i = 0; i < (int)data_len; i++)
  98388. data[i] = residual[i] + (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  98389. }
  98390. }
  98391. }
  98392. }
  98393. else { /* order > 12 */
  98394. for(i = 0; i < (int)data_len; i++) {
  98395. sum = 0;
  98396. switch(order) {
  98397. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  98398. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  98399. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  98400. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  98401. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  98402. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  98403. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  98404. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  98405. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  98406. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  98407. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  98408. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  98409. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  98410. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  98411. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  98412. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  98413. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  98414. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  98415. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  98416. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  98417. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  98418. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98419. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  98420. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  98421. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  98422. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  98423. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  98424. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  98425. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  98426. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  98427. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  98428. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  98429. }
  98430. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98431. }
  98432. }
  98433. }
  98434. #endif
  98435. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98436. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples)
  98437. {
  98438. FLAC__double error_scale;
  98439. FLAC__ASSERT(total_samples > 0);
  98440. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  98441. return FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(lpc_error, error_scale);
  98442. }
  98443. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale)
  98444. {
  98445. if(lpc_error > 0.0) {
  98446. FLAC__double bps = (FLAC__double)0.5 * log(error_scale * lpc_error) / M_LN2;
  98447. if(bps >= 0.0)
  98448. return bps;
  98449. else
  98450. return 0.0;
  98451. }
  98452. else if(lpc_error < 0.0) { /* error should not be negative but can happen due to inadequate floating-point resolution */
  98453. return 1e32;
  98454. }
  98455. else {
  98456. return 0.0;
  98457. }
  98458. }
  98459. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order)
  98460. {
  98461. 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 */
  98462. FLAC__double bits, best_bits, error_scale;
  98463. FLAC__ASSERT(max_order > 0);
  98464. FLAC__ASSERT(total_samples > 0);
  98465. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  98466. best_index = 0;
  98467. best_bits = (unsigned)(-1);
  98468. for(index = 0, order = 1; index < max_order; index++, order++) {
  98469. 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);
  98470. if(bits < best_bits) {
  98471. best_index = index;
  98472. best_bits = bits;
  98473. }
  98474. }
  98475. return best_index+1; /* +1 since index of lpc_error[] is order-1 */
  98476. }
  98477. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  98478. #endif
  98479. /*** End of inlined file: lpc_flac.c ***/
  98480. /*** Start of inlined file: md5.c ***/
  98481. /*** Start of inlined file: juce_FlacHeader.h ***/
  98482. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  98483. // tasks..
  98484. #define VERSION "1.2.1"
  98485. #define FLAC__NO_DLL 1
  98486. #if JUCE_MSVC
  98487. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  98488. #endif
  98489. #if JUCE_MAC
  98490. #define FLAC__SYS_DARWIN 1
  98491. #endif
  98492. /*** End of inlined file: juce_FlacHeader.h ***/
  98493. #if JUCE_USE_FLAC
  98494. #if HAVE_CONFIG_H
  98495. # include <config.h>
  98496. #endif
  98497. #include <stdlib.h> /* for malloc() */
  98498. #include <string.h> /* for memcpy() */
  98499. /*** Start of inlined file: md5.h ***/
  98500. #ifndef FLAC__PRIVATE__MD5_H
  98501. #define FLAC__PRIVATE__MD5_H
  98502. /*
  98503. * This is the header file for the MD5 message-digest algorithm.
  98504. * The algorithm is due to Ron Rivest. This code was
  98505. * written by Colin Plumb in 1993, no copyright is claimed.
  98506. * This code is in the public domain; do with it what you wish.
  98507. *
  98508. * Equivalent code is available from RSA Data Security, Inc.
  98509. * This code has been tested against that, and is equivalent,
  98510. * except that you don't need to include two pages of legalese
  98511. * with every copy.
  98512. *
  98513. * To compute the message digest of a chunk of bytes, declare an
  98514. * MD5Context structure, pass it to MD5Init, call MD5Update as
  98515. * needed on buffers full of bytes, and then call MD5Final, which
  98516. * will fill a supplied 16-byte array with the digest.
  98517. *
  98518. * Changed so as no longer to depend on Colin Plumb's `usual.h'
  98519. * header definitions; now uses stuff from dpkg's config.h
  98520. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  98521. * Still in the public domain.
  98522. *
  98523. * Josh Coalson: made some changes to integrate with libFLAC.
  98524. * Still in the public domain, with no warranty.
  98525. */
  98526. typedef struct {
  98527. FLAC__uint32 in[16];
  98528. FLAC__uint32 buf[4];
  98529. FLAC__uint32 bytes[2];
  98530. FLAC__byte *internal_buf;
  98531. size_t capacity;
  98532. } FLAC__MD5Context;
  98533. void FLAC__MD5Init(FLAC__MD5Context *context);
  98534. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *context);
  98535. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample);
  98536. #endif
  98537. /*** End of inlined file: md5.h ***/
  98538. #ifndef FLaC__INLINE
  98539. #define FLaC__INLINE
  98540. #endif
  98541. /*
  98542. * This code implements the MD5 message-digest algorithm.
  98543. * The algorithm is due to Ron Rivest. This code was
  98544. * written by Colin Plumb in 1993, no copyright is claimed.
  98545. * This code is in the public domain; do with it what you wish.
  98546. *
  98547. * Equivalent code is available from RSA Data Security, Inc.
  98548. * This code has been tested against that, and is equivalent,
  98549. * except that you don't need to include two pages of legalese
  98550. * with every copy.
  98551. *
  98552. * To compute the message digest of a chunk of bytes, declare an
  98553. * MD5Context structure, pass it to MD5Init, call MD5Update as
  98554. * needed on buffers full of bytes, and then call MD5Final, which
  98555. * will fill a supplied 16-byte array with the digest.
  98556. *
  98557. * Changed so as no longer to depend on Colin Plumb's `usual.h' header
  98558. * definitions; now uses stuff from dpkg's config.h.
  98559. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  98560. * Still in the public domain.
  98561. *
  98562. * Josh Coalson: made some changes to integrate with libFLAC.
  98563. * Still in the public domain.
  98564. */
  98565. /* The four core functions - F1 is optimized somewhat */
  98566. /* #define F1(x, y, z) (x & y | ~x & z) */
  98567. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  98568. #define F2(x, y, z) F1(z, x, y)
  98569. #define F3(x, y, z) (x ^ y ^ z)
  98570. #define F4(x, y, z) (y ^ (x | ~z))
  98571. /* This is the central step in the MD5 algorithm. */
  98572. #define MD5STEP(f,w,x,y,z,in,s) \
  98573. (w += f(x,y,z) + in, w = (w<<s | w>>(32-s)) + x)
  98574. /*
  98575. * The core of the MD5 algorithm, this alters an existing MD5 hash to
  98576. * reflect the addition of 16 longwords of new data. MD5Update blocks
  98577. * the data and converts bytes into longwords for this routine.
  98578. */
  98579. static void FLAC__MD5Transform(FLAC__uint32 buf[4], FLAC__uint32 const in[16])
  98580. {
  98581. register FLAC__uint32 a, b, c, d;
  98582. a = buf[0];
  98583. b = buf[1];
  98584. c = buf[2];
  98585. d = buf[3];
  98586. MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  98587. MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  98588. MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  98589. MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  98590. MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  98591. MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  98592. MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  98593. MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  98594. MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  98595. MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  98596. MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  98597. MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  98598. MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  98599. MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  98600. MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  98601. MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
  98602. MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  98603. MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  98604. MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  98605. MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  98606. MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  98607. MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  98608. MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  98609. MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  98610. MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  98611. MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  98612. MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  98613. MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  98614. MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  98615. MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  98616. MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  98617. MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
  98618. MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  98619. MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  98620. MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  98621. MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  98622. MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  98623. MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  98624. MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  98625. MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  98626. MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  98627. MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  98628. MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  98629. MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  98630. MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  98631. MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  98632. MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  98633. MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
  98634. MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  98635. MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  98636. MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  98637. MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  98638. MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  98639. MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  98640. MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  98641. MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  98642. MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  98643. MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  98644. MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  98645. MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  98646. MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  98647. MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  98648. MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  98649. MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
  98650. buf[0] += a;
  98651. buf[1] += b;
  98652. buf[2] += c;
  98653. buf[3] += d;
  98654. }
  98655. #if WORDS_BIGENDIAN
  98656. //@@@@@@ OPT: use bswap/intrinsics
  98657. static void byteSwap(FLAC__uint32 *buf, unsigned words)
  98658. {
  98659. register FLAC__uint32 x;
  98660. do {
  98661. x = *buf;
  98662. x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff);
  98663. *buf++ = (x >> 16) | (x << 16);
  98664. } while (--words);
  98665. }
  98666. static void byteSwapX16(FLAC__uint32 *buf)
  98667. {
  98668. register FLAC__uint32 x;
  98669. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98670. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98671. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98672. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98673. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98674. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98675. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98676. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98677. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98678. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98679. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98680. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98681. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98682. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98683. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98684. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf = (x >> 16) | (x << 16);
  98685. }
  98686. #else
  98687. #define byteSwap(buf, words)
  98688. #define byteSwapX16(buf)
  98689. #endif
  98690. /*
  98691. * Update context to reflect the concatenation of another buffer full
  98692. * of bytes.
  98693. */
  98694. static void FLAC__MD5Update(FLAC__MD5Context *ctx, FLAC__byte const *buf, unsigned len)
  98695. {
  98696. FLAC__uint32 t;
  98697. /* Update byte count */
  98698. t = ctx->bytes[0];
  98699. if ((ctx->bytes[0] = t + len) < t)
  98700. ctx->bytes[1]++; /* Carry from low to high */
  98701. t = 64 - (t & 0x3f); /* Space available in ctx->in (at least 1) */
  98702. if (t > len) {
  98703. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, len);
  98704. return;
  98705. }
  98706. /* First chunk is an odd size */
  98707. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, t);
  98708. byteSwapX16(ctx->in);
  98709. FLAC__MD5Transform(ctx->buf, ctx->in);
  98710. buf += t;
  98711. len -= t;
  98712. /* Process data in 64-byte chunks */
  98713. while (len >= 64) {
  98714. memcpy(ctx->in, buf, 64);
  98715. byteSwapX16(ctx->in);
  98716. FLAC__MD5Transform(ctx->buf, ctx->in);
  98717. buf += 64;
  98718. len -= 64;
  98719. }
  98720. /* Handle any remaining bytes of data. */
  98721. memcpy(ctx->in, buf, len);
  98722. }
  98723. /*
  98724. * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  98725. * initialization constants.
  98726. */
  98727. void FLAC__MD5Init(FLAC__MD5Context *ctx)
  98728. {
  98729. ctx->buf[0] = 0x67452301;
  98730. ctx->buf[1] = 0xefcdab89;
  98731. ctx->buf[2] = 0x98badcfe;
  98732. ctx->buf[3] = 0x10325476;
  98733. ctx->bytes[0] = 0;
  98734. ctx->bytes[1] = 0;
  98735. ctx->internal_buf = 0;
  98736. ctx->capacity = 0;
  98737. }
  98738. /*
  98739. * Final wrapup - pad to 64-byte boundary with the bit pattern
  98740. * 1 0* (64-bit count of bits processed, MSB-first)
  98741. */
  98742. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *ctx)
  98743. {
  98744. int count = ctx->bytes[0] & 0x3f; /* Number of bytes in ctx->in */
  98745. FLAC__byte *p = (FLAC__byte *)ctx->in + count;
  98746. /* Set the first char of padding to 0x80. There is always room. */
  98747. *p++ = 0x80;
  98748. /* Bytes of padding needed to make 56 bytes (-8..55) */
  98749. count = 56 - 1 - count;
  98750. if (count < 0) { /* Padding forces an extra block */
  98751. memset(p, 0, count + 8);
  98752. byteSwapX16(ctx->in);
  98753. FLAC__MD5Transform(ctx->buf, ctx->in);
  98754. p = (FLAC__byte *)ctx->in;
  98755. count = 56;
  98756. }
  98757. memset(p, 0, count);
  98758. byteSwap(ctx->in, 14);
  98759. /* Append length in bits and transform */
  98760. ctx->in[14] = ctx->bytes[0] << 3;
  98761. ctx->in[15] = ctx->bytes[1] << 3 | ctx->bytes[0] >> 29;
  98762. FLAC__MD5Transform(ctx->buf, ctx->in);
  98763. byteSwap(ctx->buf, 4);
  98764. memcpy(digest, ctx->buf, 16);
  98765. memset(ctx, 0, sizeof(ctx)); /* In case it's sensitive */
  98766. if(0 != ctx->internal_buf) {
  98767. free(ctx->internal_buf);
  98768. ctx->internal_buf = 0;
  98769. ctx->capacity = 0;
  98770. }
  98771. }
  98772. /*
  98773. * Convert the incoming audio signal to a byte stream
  98774. */
  98775. static void format_input_(FLAC__byte *buf, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  98776. {
  98777. unsigned channel, sample;
  98778. register FLAC__int32 a_word;
  98779. register FLAC__byte *buf_ = buf;
  98780. #if WORDS_BIGENDIAN
  98781. #else
  98782. if(channels == 2 && bytes_per_sample == 2) {
  98783. FLAC__int16 *buf1_ = ((FLAC__int16*)buf_) + 1;
  98784. memcpy(buf_, signal[0], sizeof(FLAC__int32) * samples);
  98785. for(sample = 0; sample < samples; sample++, buf1_+=2)
  98786. *buf1_ = (FLAC__int16)signal[1][sample];
  98787. }
  98788. else if(channels == 1 && bytes_per_sample == 2) {
  98789. FLAC__int16 *buf1_ = (FLAC__int16*)buf_;
  98790. for(sample = 0; sample < samples; sample++)
  98791. *buf1_++ = (FLAC__int16)signal[0][sample];
  98792. }
  98793. else
  98794. #endif
  98795. if(bytes_per_sample == 2) {
  98796. if(channels == 2) {
  98797. for(sample = 0; sample < samples; sample++) {
  98798. a_word = signal[0][sample];
  98799. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98800. *buf_++ = (FLAC__byte)a_word;
  98801. a_word = signal[1][sample];
  98802. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98803. *buf_++ = (FLAC__byte)a_word;
  98804. }
  98805. }
  98806. else if(channels == 1) {
  98807. for(sample = 0; sample < samples; sample++) {
  98808. a_word = signal[0][sample];
  98809. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98810. *buf_++ = (FLAC__byte)a_word;
  98811. }
  98812. }
  98813. else {
  98814. for(sample = 0; sample < samples; sample++) {
  98815. for(channel = 0; channel < channels; channel++) {
  98816. a_word = signal[channel][sample];
  98817. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98818. *buf_++ = (FLAC__byte)a_word;
  98819. }
  98820. }
  98821. }
  98822. }
  98823. else if(bytes_per_sample == 3) {
  98824. if(channels == 2) {
  98825. for(sample = 0; sample < samples; sample++) {
  98826. a_word = signal[0][sample];
  98827. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98828. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98829. *buf_++ = (FLAC__byte)a_word;
  98830. a_word = signal[1][sample];
  98831. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98832. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98833. *buf_++ = (FLAC__byte)a_word;
  98834. }
  98835. }
  98836. else if(channels == 1) {
  98837. for(sample = 0; sample < samples; sample++) {
  98838. a_word = signal[0][sample];
  98839. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98840. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98841. *buf_++ = (FLAC__byte)a_word;
  98842. }
  98843. }
  98844. else {
  98845. for(sample = 0; sample < samples; sample++) {
  98846. for(channel = 0; channel < channels; channel++) {
  98847. a_word = signal[channel][sample];
  98848. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98849. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98850. *buf_++ = (FLAC__byte)a_word;
  98851. }
  98852. }
  98853. }
  98854. }
  98855. else if(bytes_per_sample == 1) {
  98856. if(channels == 2) {
  98857. for(sample = 0; sample < samples; sample++) {
  98858. a_word = signal[0][sample];
  98859. *buf_++ = (FLAC__byte)a_word;
  98860. a_word = signal[1][sample];
  98861. *buf_++ = (FLAC__byte)a_word;
  98862. }
  98863. }
  98864. else if(channels == 1) {
  98865. for(sample = 0; sample < samples; sample++) {
  98866. a_word = signal[0][sample];
  98867. *buf_++ = (FLAC__byte)a_word;
  98868. }
  98869. }
  98870. else {
  98871. for(sample = 0; sample < samples; sample++) {
  98872. for(channel = 0; channel < channels; channel++) {
  98873. a_word = signal[channel][sample];
  98874. *buf_++ = (FLAC__byte)a_word;
  98875. }
  98876. }
  98877. }
  98878. }
  98879. else { /* bytes_per_sample == 4, maybe optimize more later */
  98880. for(sample = 0; sample < samples; sample++) {
  98881. for(channel = 0; channel < channels; channel++) {
  98882. a_word = signal[channel][sample];
  98883. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98884. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98885. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98886. *buf_++ = (FLAC__byte)a_word;
  98887. }
  98888. }
  98889. }
  98890. }
  98891. /*
  98892. * Convert the incoming audio signal to a byte stream and FLAC__MD5Update it.
  98893. */
  98894. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  98895. {
  98896. const size_t bytes_needed = (size_t)channels * (size_t)samples * (size_t)bytes_per_sample;
  98897. /* overflow check */
  98898. if((size_t)channels > SIZE_MAX / (size_t)bytes_per_sample)
  98899. return false;
  98900. if((size_t)channels * (size_t)bytes_per_sample > SIZE_MAX / (size_t)samples)
  98901. return false;
  98902. if(ctx->capacity < bytes_needed) {
  98903. FLAC__byte *tmp = (FLAC__byte*)realloc(ctx->internal_buf, bytes_needed);
  98904. if(0 == tmp) {
  98905. free(ctx->internal_buf);
  98906. if(0 == (ctx->internal_buf = (FLAC__byte*)safe_malloc_(bytes_needed)))
  98907. return false;
  98908. }
  98909. ctx->internal_buf = tmp;
  98910. ctx->capacity = bytes_needed;
  98911. }
  98912. format_input_(ctx->internal_buf, signal, channels, samples, bytes_per_sample);
  98913. FLAC__MD5Update(ctx, ctx->internal_buf, bytes_needed);
  98914. return true;
  98915. }
  98916. #endif
  98917. /*** End of inlined file: md5.c ***/
  98918. /*** Start of inlined file: memory.c ***/
  98919. /*** Start of inlined file: juce_FlacHeader.h ***/
  98920. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  98921. // tasks..
  98922. #define VERSION "1.2.1"
  98923. #define FLAC__NO_DLL 1
  98924. #if JUCE_MSVC
  98925. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  98926. #endif
  98927. #if JUCE_MAC
  98928. #define FLAC__SYS_DARWIN 1
  98929. #endif
  98930. /*** End of inlined file: juce_FlacHeader.h ***/
  98931. #if JUCE_USE_FLAC
  98932. #if HAVE_CONFIG_H
  98933. # include <config.h>
  98934. #endif
  98935. /*** Start of inlined file: memory.h ***/
  98936. #ifndef FLAC__PRIVATE__MEMORY_H
  98937. #define FLAC__PRIVATE__MEMORY_H
  98938. #ifdef HAVE_CONFIG_H
  98939. #include <config.h>
  98940. #endif
  98941. #include <stdlib.h> /* for size_t */
  98942. /* Returns the unaligned address returned by malloc.
  98943. * Use free() on this address to deallocate.
  98944. */
  98945. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address);
  98946. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer);
  98947. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer);
  98948. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer);
  98949. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer);
  98950. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98951. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer);
  98952. #endif
  98953. #endif
  98954. /*** End of inlined file: memory.h ***/
  98955. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address)
  98956. {
  98957. void *x;
  98958. FLAC__ASSERT(0 != aligned_address);
  98959. #ifdef FLAC__ALIGN_MALLOC_DATA
  98960. /* align on 32-byte (256-bit) boundary */
  98961. x = safe_malloc_add_2op_(bytes, /*+*/31);
  98962. #ifdef SIZEOF_VOIDP
  98963. #if SIZEOF_VOIDP == 4
  98964. /* could do *aligned_address = x + ((unsigned) (32 - (((unsigned)x) & 31))) & 31; */
  98965. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  98966. #elif SIZEOF_VOIDP == 8
  98967. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  98968. #else
  98969. # error Unsupported sizeof(void*)
  98970. #endif
  98971. #else
  98972. /* there's got to be a better way to do this right for all archs */
  98973. if(sizeof(void*) == sizeof(unsigned))
  98974. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  98975. else if(sizeof(void*) == sizeof(FLAC__uint64))
  98976. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  98977. else
  98978. return 0;
  98979. #endif
  98980. #else
  98981. x = safe_malloc_(bytes);
  98982. *aligned_address = x;
  98983. #endif
  98984. return x;
  98985. }
  98986. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer)
  98987. {
  98988. FLAC__int32 *pu; /* unaligned pointer */
  98989. union { /* union needed to comply with C99 pointer aliasing rules */
  98990. FLAC__int32 *pa; /* aligned pointer */
  98991. void *pv; /* aligned pointer alias */
  98992. } u;
  98993. FLAC__ASSERT(elements > 0);
  98994. FLAC__ASSERT(0 != unaligned_pointer);
  98995. FLAC__ASSERT(0 != aligned_pointer);
  98996. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98997. pu = (FLAC__int32*)FLAC__memory_alloc_aligned(sizeof(*pu) * (size_t)elements, &u.pv);
  98998. if(0 == pu) {
  98999. return false;
  99000. }
  99001. else {
  99002. if(*unaligned_pointer != 0)
  99003. free(*unaligned_pointer);
  99004. *unaligned_pointer = pu;
  99005. *aligned_pointer = u.pa;
  99006. return true;
  99007. }
  99008. }
  99009. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer)
  99010. {
  99011. FLAC__uint32 *pu; /* unaligned pointer */
  99012. union { /* union needed to comply with C99 pointer aliasing rules */
  99013. FLAC__uint32 *pa; /* aligned pointer */
  99014. void *pv; /* aligned pointer alias */
  99015. } u;
  99016. FLAC__ASSERT(elements > 0);
  99017. FLAC__ASSERT(0 != unaligned_pointer);
  99018. FLAC__ASSERT(0 != aligned_pointer);
  99019. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  99020. pu = (FLAC__uint32*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  99021. if(0 == pu) {
  99022. return false;
  99023. }
  99024. else {
  99025. if(*unaligned_pointer != 0)
  99026. free(*unaligned_pointer);
  99027. *unaligned_pointer = pu;
  99028. *aligned_pointer = u.pa;
  99029. return true;
  99030. }
  99031. }
  99032. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer)
  99033. {
  99034. FLAC__uint64 *pu; /* unaligned pointer */
  99035. union { /* union needed to comply with C99 pointer aliasing rules */
  99036. FLAC__uint64 *pa; /* aligned pointer */
  99037. void *pv; /* aligned pointer alias */
  99038. } u;
  99039. FLAC__ASSERT(elements > 0);
  99040. FLAC__ASSERT(0 != unaligned_pointer);
  99041. FLAC__ASSERT(0 != aligned_pointer);
  99042. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  99043. pu = (FLAC__uint64*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  99044. if(0 == pu) {
  99045. return false;
  99046. }
  99047. else {
  99048. if(*unaligned_pointer != 0)
  99049. free(*unaligned_pointer);
  99050. *unaligned_pointer = pu;
  99051. *aligned_pointer = u.pa;
  99052. return true;
  99053. }
  99054. }
  99055. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer)
  99056. {
  99057. unsigned *pu; /* unaligned pointer */
  99058. union { /* union needed to comply with C99 pointer aliasing rules */
  99059. unsigned *pa; /* aligned pointer */
  99060. void *pv; /* aligned pointer alias */
  99061. } u;
  99062. FLAC__ASSERT(elements > 0);
  99063. FLAC__ASSERT(0 != unaligned_pointer);
  99064. FLAC__ASSERT(0 != aligned_pointer);
  99065. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  99066. pu = (unsigned*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  99067. if(0 == pu) {
  99068. return false;
  99069. }
  99070. else {
  99071. if(*unaligned_pointer != 0)
  99072. free(*unaligned_pointer);
  99073. *unaligned_pointer = pu;
  99074. *aligned_pointer = u.pa;
  99075. return true;
  99076. }
  99077. }
  99078. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99079. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer)
  99080. {
  99081. FLAC__real *pu; /* unaligned pointer */
  99082. union { /* union needed to comply with C99 pointer aliasing rules */
  99083. FLAC__real *pa; /* aligned pointer */
  99084. void *pv; /* aligned pointer alias */
  99085. } u;
  99086. FLAC__ASSERT(elements > 0);
  99087. FLAC__ASSERT(0 != unaligned_pointer);
  99088. FLAC__ASSERT(0 != aligned_pointer);
  99089. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  99090. pu = (FLAC__real*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  99091. if(0 == pu) {
  99092. return false;
  99093. }
  99094. else {
  99095. if(*unaligned_pointer != 0)
  99096. free(*unaligned_pointer);
  99097. *unaligned_pointer = pu;
  99098. *aligned_pointer = u.pa;
  99099. return true;
  99100. }
  99101. }
  99102. #endif
  99103. #endif
  99104. /*** End of inlined file: memory.c ***/
  99105. /*** Start of inlined file: stream_decoder.c ***/
  99106. /*** Start of inlined file: juce_FlacHeader.h ***/
  99107. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  99108. // tasks..
  99109. #define VERSION "1.2.1"
  99110. #define FLAC__NO_DLL 1
  99111. #if JUCE_MSVC
  99112. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  99113. #endif
  99114. #if JUCE_MAC
  99115. #define FLAC__SYS_DARWIN 1
  99116. #endif
  99117. /*** End of inlined file: juce_FlacHeader.h ***/
  99118. #if JUCE_USE_FLAC
  99119. #if HAVE_CONFIG_H
  99120. # include <config.h>
  99121. #endif
  99122. #if defined _MSC_VER || defined __MINGW32__
  99123. #include <io.h> /* for _setmode() */
  99124. #include <fcntl.h> /* for _O_BINARY */
  99125. #endif
  99126. #if defined __CYGWIN__ || defined __EMX__
  99127. #include <io.h> /* for setmode(), O_BINARY */
  99128. #include <fcntl.h> /* for _O_BINARY */
  99129. #endif
  99130. #include <stdio.h>
  99131. #include <stdlib.h> /* for malloc() */
  99132. #include <string.h> /* for memset/memcpy() */
  99133. #include <sys/stat.h> /* for stat() */
  99134. #include <sys/types.h> /* for off_t */
  99135. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  99136. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  99137. #define fseeko fseek
  99138. #define ftello ftell
  99139. #endif
  99140. #endif
  99141. /*** Start of inlined file: stream_decoder.h ***/
  99142. #ifndef FLAC__PROTECTED__STREAM_DECODER_H
  99143. #define FLAC__PROTECTED__STREAM_DECODER_H
  99144. #if FLAC__HAS_OGG
  99145. #include "include/private/ogg_decoder_aspect.h"
  99146. #endif
  99147. typedef struct FLAC__StreamDecoderProtected {
  99148. FLAC__StreamDecoderState state;
  99149. unsigned channels;
  99150. FLAC__ChannelAssignment channel_assignment;
  99151. unsigned bits_per_sample;
  99152. unsigned sample_rate; /* in Hz */
  99153. unsigned blocksize; /* in samples (per channel) */
  99154. FLAC__bool md5_checking; /* if true, generate MD5 signature of decoded data and compare against signature in the STREAMINFO metadata block */
  99155. #if FLAC__HAS_OGG
  99156. FLAC__OggDecoderAspect ogg_decoder_aspect;
  99157. #endif
  99158. } FLAC__StreamDecoderProtected;
  99159. /*
  99160. * return the number of input bytes consumed
  99161. */
  99162. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder);
  99163. #endif
  99164. /*** End of inlined file: stream_decoder.h ***/
  99165. #ifdef max
  99166. #undef max
  99167. #endif
  99168. #define max(a,b) ((a)>(b)?(a):(b))
  99169. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  99170. #ifdef _MSC_VER
  99171. #define FLAC__U64L(x) x
  99172. #else
  99173. #define FLAC__U64L(x) x##LLU
  99174. #endif
  99175. /* technically this should be in an "export.c" but this is convenient enough */
  99176. FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC =
  99177. #if FLAC__HAS_OGG
  99178. 1
  99179. #else
  99180. 0
  99181. #endif
  99182. ;
  99183. /***********************************************************************
  99184. *
  99185. * Private static data
  99186. *
  99187. ***********************************************************************/
  99188. static FLAC__byte ID3V2_TAG_[3] = { 'I', 'D', '3' };
  99189. /***********************************************************************
  99190. *
  99191. * Private class method prototypes
  99192. *
  99193. ***********************************************************************/
  99194. static void set_defaults_dec(FLAC__StreamDecoder *decoder);
  99195. static FILE *get_binary_stdin_(void);
  99196. static FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels);
  99197. static FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id);
  99198. static FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder);
  99199. static FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder);
  99200. static FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  99201. static FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  99202. static FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj);
  99203. static FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj);
  99204. static FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj);
  99205. static FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder);
  99206. static FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder);
  99207. static FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode);
  99208. static FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder);
  99209. static FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  99210. static FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  99211. static FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  99212. static FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  99213. static FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  99214. 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);
  99215. static FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder);
  99216. static FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data);
  99217. #if FLAC__HAS_OGG
  99218. static FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes);
  99219. static FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  99220. #endif
  99221. static FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[]);
  99222. static void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status);
  99223. static FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  99224. #if FLAC__HAS_OGG
  99225. static FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  99226. #endif
  99227. static FLAC__StreamDecoderReadStatus file_read_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  99228. static FLAC__StreamDecoderSeekStatus file_seek_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  99229. static FLAC__StreamDecoderTellStatus file_tell_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  99230. static FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  99231. static FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data);
  99232. /***********************************************************************
  99233. *
  99234. * Private class data
  99235. *
  99236. ***********************************************************************/
  99237. typedef struct FLAC__StreamDecoderPrivate {
  99238. #if FLAC__HAS_OGG
  99239. FLAC__bool is_ogg;
  99240. #endif
  99241. FLAC__StreamDecoderReadCallback read_callback;
  99242. FLAC__StreamDecoderSeekCallback seek_callback;
  99243. FLAC__StreamDecoderTellCallback tell_callback;
  99244. FLAC__StreamDecoderLengthCallback length_callback;
  99245. FLAC__StreamDecoderEofCallback eof_callback;
  99246. FLAC__StreamDecoderWriteCallback write_callback;
  99247. FLAC__StreamDecoderMetadataCallback metadata_callback;
  99248. FLAC__StreamDecoderErrorCallback error_callback;
  99249. /* generic 32-bit datapath: */
  99250. 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[]);
  99251. /* generic 64-bit datapath: */
  99252. 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[]);
  99253. /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit): */
  99254. 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[]);
  99255. /* 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: */
  99256. 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[]);
  99257. FLAC__bool (*local_bitreader_read_rice_signed_block)(FLAC__BitReader *br, int* vals, unsigned nvals, unsigned parameter);
  99258. void *client_data;
  99259. FILE *file; /* only used if FLAC__stream_decoder_init_file()/FLAC__stream_decoder_init_file() called, else NULL */
  99260. FLAC__BitReader *input;
  99261. FLAC__int32 *output[FLAC__MAX_CHANNELS];
  99262. FLAC__int32 *residual[FLAC__MAX_CHANNELS]; /* WATCHOUT: these are the aligned pointers; the real pointers that should be free()'d are residual_unaligned[] below */
  99263. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents[FLAC__MAX_CHANNELS];
  99264. unsigned output_capacity, output_channels;
  99265. FLAC__uint32 fixed_block_size, next_fixed_block_size;
  99266. FLAC__uint64 samples_decoded;
  99267. FLAC__bool has_stream_info, has_seek_table;
  99268. FLAC__StreamMetadata stream_info;
  99269. FLAC__StreamMetadata seek_table;
  99270. FLAC__bool metadata_filter[128]; /* MAGIC number 128 == total number of metadata block types == 1 << 7 */
  99271. FLAC__byte *metadata_filter_ids;
  99272. size_t metadata_filter_ids_count, metadata_filter_ids_capacity; /* units for both are IDs, not bytes */
  99273. FLAC__Frame frame;
  99274. FLAC__bool cached; /* true if there is a byte in lookahead */
  99275. FLAC__CPUInfo cpuinfo;
  99276. FLAC__byte header_warmup[2]; /* contains the sync code and reserved bits */
  99277. FLAC__byte lookahead; /* temp storage when we need to look ahead one byte in the stream */
  99278. /* unaligned (original) pointers to allocated data */
  99279. FLAC__int32 *residual_unaligned[FLAC__MAX_CHANNELS];
  99280. 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 */
  99281. FLAC__bool internal_reset_hack; /* used only during init() so we can call reset to set up the decoder without rewinding the input */
  99282. FLAC__bool is_seeking;
  99283. FLAC__MD5Context md5context;
  99284. FLAC__byte computed_md5sum[16]; /* this is the sum we computed from the decoded data */
  99285. /* (the rest of these are only used for seeking) */
  99286. FLAC__Frame last_frame; /* holds the info of the last frame we seeked to */
  99287. FLAC__uint64 first_frame_offset; /* hint to the seek routine of where in the stream the first audio frame starts */
  99288. FLAC__uint64 target_sample;
  99289. unsigned unparseable_frame_count; /* used to tell whether we're decoding a future version of FLAC or just got a bad sync */
  99290. #if FLAC__HAS_OGG
  99291. FLAC__bool got_a_frame; /* hack needed in Ogg FLAC seek routine to check when process_single() actually writes a frame */
  99292. #endif
  99293. } FLAC__StreamDecoderPrivate;
  99294. /***********************************************************************
  99295. *
  99296. * Public static class data
  99297. *
  99298. ***********************************************************************/
  99299. FLAC_API const char * const FLAC__StreamDecoderStateString[] = {
  99300. "FLAC__STREAM_DECODER_SEARCH_FOR_METADATA",
  99301. "FLAC__STREAM_DECODER_READ_METADATA",
  99302. "FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC",
  99303. "FLAC__STREAM_DECODER_READ_FRAME",
  99304. "FLAC__STREAM_DECODER_END_OF_STREAM",
  99305. "FLAC__STREAM_DECODER_OGG_ERROR",
  99306. "FLAC__STREAM_DECODER_SEEK_ERROR",
  99307. "FLAC__STREAM_DECODER_ABORTED",
  99308. "FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR",
  99309. "FLAC__STREAM_DECODER_UNINITIALIZED"
  99310. };
  99311. FLAC_API const char * const FLAC__StreamDecoderInitStatusString[] = {
  99312. "FLAC__STREAM_DECODER_INIT_STATUS_OK",
  99313. "FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  99314. "FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS",
  99315. "FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR",
  99316. "FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE",
  99317. "FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED"
  99318. };
  99319. FLAC_API const char * const FLAC__StreamDecoderReadStatusString[] = {
  99320. "FLAC__STREAM_DECODER_READ_STATUS_CONTINUE",
  99321. "FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM",
  99322. "FLAC__STREAM_DECODER_READ_STATUS_ABORT"
  99323. };
  99324. FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[] = {
  99325. "FLAC__STREAM_DECODER_SEEK_STATUS_OK",
  99326. "FLAC__STREAM_DECODER_SEEK_STATUS_ERROR",
  99327. "FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED"
  99328. };
  99329. FLAC_API const char * const FLAC__StreamDecoderTellStatusString[] = {
  99330. "FLAC__STREAM_DECODER_TELL_STATUS_OK",
  99331. "FLAC__STREAM_DECODER_TELL_STATUS_ERROR",
  99332. "FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED"
  99333. };
  99334. FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[] = {
  99335. "FLAC__STREAM_DECODER_LENGTH_STATUS_OK",
  99336. "FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR",
  99337. "FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED"
  99338. };
  99339. FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[] = {
  99340. "FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE",
  99341. "FLAC__STREAM_DECODER_WRITE_STATUS_ABORT"
  99342. };
  99343. FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[] = {
  99344. "FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC",
  99345. "FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER",
  99346. "FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH",
  99347. "FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM"
  99348. };
  99349. /***********************************************************************
  99350. *
  99351. * Class constructor/destructor
  99352. *
  99353. ***********************************************************************/
  99354. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void)
  99355. {
  99356. FLAC__StreamDecoder *decoder;
  99357. unsigned i;
  99358. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  99359. decoder = (FLAC__StreamDecoder*)calloc(1, sizeof(FLAC__StreamDecoder));
  99360. if(decoder == 0) {
  99361. return 0;
  99362. }
  99363. decoder->protected_ = (FLAC__StreamDecoderProtected*)calloc(1, sizeof(FLAC__StreamDecoderProtected));
  99364. if(decoder->protected_ == 0) {
  99365. free(decoder);
  99366. return 0;
  99367. }
  99368. decoder->private_ = (FLAC__StreamDecoderPrivate*)calloc(1, sizeof(FLAC__StreamDecoderPrivate));
  99369. if(decoder->private_ == 0) {
  99370. free(decoder->protected_);
  99371. free(decoder);
  99372. return 0;
  99373. }
  99374. decoder->private_->input = FLAC__bitreader_new();
  99375. if(decoder->private_->input == 0) {
  99376. free(decoder->private_);
  99377. free(decoder->protected_);
  99378. free(decoder);
  99379. return 0;
  99380. }
  99381. decoder->private_->metadata_filter_ids_capacity = 16;
  99382. if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)malloc((FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) * decoder->private_->metadata_filter_ids_capacity))) {
  99383. FLAC__bitreader_delete(decoder->private_->input);
  99384. free(decoder->private_);
  99385. free(decoder->protected_);
  99386. free(decoder);
  99387. return 0;
  99388. }
  99389. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99390. decoder->private_->output[i] = 0;
  99391. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  99392. }
  99393. decoder->private_->output_capacity = 0;
  99394. decoder->private_->output_channels = 0;
  99395. decoder->private_->has_seek_table = false;
  99396. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  99397. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&decoder->private_->partitioned_rice_contents[i]);
  99398. decoder->private_->file = 0;
  99399. set_defaults_dec(decoder);
  99400. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  99401. return decoder;
  99402. }
  99403. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder)
  99404. {
  99405. unsigned i;
  99406. FLAC__ASSERT(0 != decoder);
  99407. FLAC__ASSERT(0 != decoder->protected_);
  99408. FLAC__ASSERT(0 != decoder->private_);
  99409. FLAC__ASSERT(0 != decoder->private_->input);
  99410. (void)FLAC__stream_decoder_finish(decoder);
  99411. if(0 != decoder->private_->metadata_filter_ids)
  99412. free(decoder->private_->metadata_filter_ids);
  99413. FLAC__bitreader_delete(decoder->private_->input);
  99414. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  99415. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&decoder->private_->partitioned_rice_contents[i]);
  99416. free(decoder->private_);
  99417. free(decoder->protected_);
  99418. free(decoder);
  99419. }
  99420. /***********************************************************************
  99421. *
  99422. * Public class methods
  99423. *
  99424. ***********************************************************************/
  99425. static FLAC__StreamDecoderInitStatus init_stream_internal_dec(
  99426. FLAC__StreamDecoder *decoder,
  99427. FLAC__StreamDecoderReadCallback read_callback,
  99428. FLAC__StreamDecoderSeekCallback seek_callback,
  99429. FLAC__StreamDecoderTellCallback tell_callback,
  99430. FLAC__StreamDecoderLengthCallback length_callback,
  99431. FLAC__StreamDecoderEofCallback eof_callback,
  99432. FLAC__StreamDecoderWriteCallback write_callback,
  99433. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99434. FLAC__StreamDecoderErrorCallback error_callback,
  99435. void *client_data,
  99436. FLAC__bool is_ogg
  99437. )
  99438. {
  99439. FLAC__ASSERT(0 != decoder);
  99440. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99441. return FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
  99442. #if !FLAC__HAS_OGG
  99443. if(is_ogg)
  99444. return FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  99445. #endif
  99446. if(
  99447. 0 == read_callback ||
  99448. 0 == write_callback ||
  99449. 0 == error_callback ||
  99450. (seek_callback && (0 == tell_callback || 0 == length_callback || 0 == eof_callback))
  99451. )
  99452. return FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
  99453. #if FLAC__HAS_OGG
  99454. decoder->private_->is_ogg = is_ogg;
  99455. if(is_ogg && !FLAC__ogg_decoder_aspect_init(&decoder->protected_->ogg_decoder_aspect))
  99456. return decoder->protected_->state = FLAC__STREAM_DECODER_OGG_ERROR;
  99457. #endif
  99458. /*
  99459. * get the CPU info and set the function pointers
  99460. */
  99461. FLAC__cpu_info(&decoder->private_->cpuinfo);
  99462. /* first default to the non-asm routines */
  99463. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal;
  99464. decoder->private_->local_lpc_restore_signal_64bit = FLAC__lpc_restore_signal_wide;
  99465. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal;
  99466. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal;
  99467. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block;
  99468. /* now override with asm where appropriate */
  99469. #ifndef FLAC__NO_ASM
  99470. if(decoder->private_->cpuinfo.use_asm) {
  99471. #ifdef FLAC__CPU_IA32
  99472. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  99473. #ifdef FLAC__HAS_NASM
  99474. #if 1 /*@@@@@@ OPT: not clearly faster, needs more testing */
  99475. if(decoder->private_->cpuinfo.data.ia32.bswap)
  99476. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap;
  99477. #endif
  99478. if(decoder->private_->cpuinfo.data.ia32.mmx) {
  99479. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  99480. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32_mmx;
  99481. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32_mmx;
  99482. }
  99483. else {
  99484. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  99485. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32;
  99486. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32;
  99487. }
  99488. #endif
  99489. #elif defined FLAC__CPU_PPC
  99490. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_PPC);
  99491. if(decoder->private_->cpuinfo.data.ppc.altivec) {
  99492. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ppc_altivec_16;
  99493. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ppc_altivec_16_order8;
  99494. }
  99495. #endif
  99496. }
  99497. #endif
  99498. /* from here on, errors are fatal */
  99499. if(!FLAC__bitreader_init(decoder->private_->input, decoder->private_->cpuinfo, read_callback_, decoder)) {
  99500. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99501. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  99502. }
  99503. decoder->private_->read_callback = read_callback;
  99504. decoder->private_->seek_callback = seek_callback;
  99505. decoder->private_->tell_callback = tell_callback;
  99506. decoder->private_->length_callback = length_callback;
  99507. decoder->private_->eof_callback = eof_callback;
  99508. decoder->private_->write_callback = write_callback;
  99509. decoder->private_->metadata_callback = metadata_callback;
  99510. decoder->private_->error_callback = error_callback;
  99511. decoder->private_->client_data = client_data;
  99512. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  99513. decoder->private_->samples_decoded = 0;
  99514. decoder->private_->has_stream_info = false;
  99515. decoder->private_->cached = false;
  99516. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  99517. decoder->private_->is_seeking = false;
  99518. decoder->private_->internal_reset_hack = true; /* so the following reset does not try to rewind the input */
  99519. if(!FLAC__stream_decoder_reset(decoder)) {
  99520. /* above call sets the state for us */
  99521. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  99522. }
  99523. return FLAC__STREAM_DECODER_INIT_STATUS_OK;
  99524. }
  99525. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  99526. FLAC__StreamDecoder *decoder,
  99527. FLAC__StreamDecoderReadCallback read_callback,
  99528. FLAC__StreamDecoderSeekCallback seek_callback,
  99529. FLAC__StreamDecoderTellCallback tell_callback,
  99530. FLAC__StreamDecoderLengthCallback length_callback,
  99531. FLAC__StreamDecoderEofCallback eof_callback,
  99532. FLAC__StreamDecoderWriteCallback write_callback,
  99533. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99534. FLAC__StreamDecoderErrorCallback error_callback,
  99535. void *client_data
  99536. )
  99537. {
  99538. return init_stream_internal_dec(
  99539. decoder,
  99540. read_callback,
  99541. seek_callback,
  99542. tell_callback,
  99543. length_callback,
  99544. eof_callback,
  99545. write_callback,
  99546. metadata_callback,
  99547. error_callback,
  99548. client_data,
  99549. /*is_ogg=*/false
  99550. );
  99551. }
  99552. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  99553. FLAC__StreamDecoder *decoder,
  99554. FLAC__StreamDecoderReadCallback read_callback,
  99555. FLAC__StreamDecoderSeekCallback seek_callback,
  99556. FLAC__StreamDecoderTellCallback tell_callback,
  99557. FLAC__StreamDecoderLengthCallback length_callback,
  99558. FLAC__StreamDecoderEofCallback eof_callback,
  99559. FLAC__StreamDecoderWriteCallback write_callback,
  99560. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99561. FLAC__StreamDecoderErrorCallback error_callback,
  99562. void *client_data
  99563. )
  99564. {
  99565. return init_stream_internal_dec(
  99566. decoder,
  99567. read_callback,
  99568. seek_callback,
  99569. tell_callback,
  99570. length_callback,
  99571. eof_callback,
  99572. write_callback,
  99573. metadata_callback,
  99574. error_callback,
  99575. client_data,
  99576. /*is_ogg=*/true
  99577. );
  99578. }
  99579. static FLAC__StreamDecoderInitStatus init_FILE_internal_(
  99580. FLAC__StreamDecoder *decoder,
  99581. FILE *file,
  99582. FLAC__StreamDecoderWriteCallback write_callback,
  99583. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99584. FLAC__StreamDecoderErrorCallback error_callback,
  99585. void *client_data,
  99586. FLAC__bool is_ogg
  99587. )
  99588. {
  99589. FLAC__ASSERT(0 != decoder);
  99590. FLAC__ASSERT(0 != file);
  99591. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99592. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  99593. if(0 == write_callback || 0 == error_callback)
  99594. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  99595. /*
  99596. * To make sure that our file does not go unclosed after an error, we
  99597. * must assign the FILE pointer before any further error can occur in
  99598. * this routine.
  99599. */
  99600. if(file == stdin)
  99601. file = get_binary_stdin_(); /* just to be safe */
  99602. decoder->private_->file = file;
  99603. return init_stream_internal_dec(
  99604. decoder,
  99605. file_read_callback_dec,
  99606. decoder->private_->file == stdin? 0: file_seek_callback_dec,
  99607. decoder->private_->file == stdin? 0: file_tell_callback_dec,
  99608. decoder->private_->file == stdin? 0: file_length_callback_,
  99609. file_eof_callback_,
  99610. write_callback,
  99611. metadata_callback,
  99612. error_callback,
  99613. client_data,
  99614. is_ogg
  99615. );
  99616. }
  99617. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  99618. FLAC__StreamDecoder *decoder,
  99619. FILE *file,
  99620. FLAC__StreamDecoderWriteCallback write_callback,
  99621. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99622. FLAC__StreamDecoderErrorCallback error_callback,
  99623. void *client_data
  99624. )
  99625. {
  99626. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  99627. }
  99628. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  99629. FLAC__StreamDecoder *decoder,
  99630. FILE *file,
  99631. FLAC__StreamDecoderWriteCallback write_callback,
  99632. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99633. FLAC__StreamDecoderErrorCallback error_callback,
  99634. void *client_data
  99635. )
  99636. {
  99637. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  99638. }
  99639. static FLAC__StreamDecoderInitStatus init_file_internal_(
  99640. FLAC__StreamDecoder *decoder,
  99641. const char *filename,
  99642. FLAC__StreamDecoderWriteCallback write_callback,
  99643. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99644. FLAC__StreamDecoderErrorCallback error_callback,
  99645. void *client_data,
  99646. FLAC__bool is_ogg
  99647. )
  99648. {
  99649. FILE *file;
  99650. FLAC__ASSERT(0 != decoder);
  99651. /*
  99652. * To make sure that our file does not go unclosed after an error, we
  99653. * have to do the same entrance checks here that are later performed
  99654. * in FLAC__stream_decoder_init_FILE() before the FILE* is assigned.
  99655. */
  99656. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99657. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  99658. if(0 == write_callback || 0 == error_callback)
  99659. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  99660. file = filename? fopen(filename, "rb") : stdin;
  99661. if(0 == file)
  99662. return FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE;
  99663. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, is_ogg);
  99664. }
  99665. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  99666. FLAC__StreamDecoder *decoder,
  99667. const char *filename,
  99668. FLAC__StreamDecoderWriteCallback write_callback,
  99669. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99670. FLAC__StreamDecoderErrorCallback error_callback,
  99671. void *client_data
  99672. )
  99673. {
  99674. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  99675. }
  99676. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  99677. FLAC__StreamDecoder *decoder,
  99678. const char *filename,
  99679. FLAC__StreamDecoderWriteCallback write_callback,
  99680. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99681. FLAC__StreamDecoderErrorCallback error_callback,
  99682. void *client_data
  99683. )
  99684. {
  99685. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  99686. }
  99687. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder)
  99688. {
  99689. FLAC__bool md5_failed = false;
  99690. unsigned i;
  99691. FLAC__ASSERT(0 != decoder);
  99692. FLAC__ASSERT(0 != decoder->private_);
  99693. FLAC__ASSERT(0 != decoder->protected_);
  99694. if(decoder->protected_->state == FLAC__STREAM_DECODER_UNINITIALIZED)
  99695. return true;
  99696. /* see the comment in FLAC__seekable_stream_decoder_reset() as to why we
  99697. * always call FLAC__MD5Final()
  99698. */
  99699. FLAC__MD5Final(decoder->private_->computed_md5sum, &decoder->private_->md5context);
  99700. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  99701. free(decoder->private_->seek_table.data.seek_table.points);
  99702. decoder->private_->seek_table.data.seek_table.points = 0;
  99703. decoder->private_->has_seek_table = false;
  99704. }
  99705. FLAC__bitreader_free(decoder->private_->input);
  99706. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99707. /* WATCHOUT:
  99708. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  99709. * output arrays have a buffer of up to 3 zeroes in front
  99710. * (at negative indices) for alignment purposes; we use 4
  99711. * to keep the data well-aligned.
  99712. */
  99713. if(0 != decoder->private_->output[i]) {
  99714. free(decoder->private_->output[i]-4);
  99715. decoder->private_->output[i] = 0;
  99716. }
  99717. if(0 != decoder->private_->residual_unaligned[i]) {
  99718. free(decoder->private_->residual_unaligned[i]);
  99719. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  99720. }
  99721. }
  99722. decoder->private_->output_capacity = 0;
  99723. decoder->private_->output_channels = 0;
  99724. #if FLAC__HAS_OGG
  99725. if(decoder->private_->is_ogg)
  99726. FLAC__ogg_decoder_aspect_finish(&decoder->protected_->ogg_decoder_aspect);
  99727. #endif
  99728. if(0 != decoder->private_->file) {
  99729. if(decoder->private_->file != stdin)
  99730. fclose(decoder->private_->file);
  99731. decoder->private_->file = 0;
  99732. }
  99733. if(decoder->private_->do_md5_checking) {
  99734. if(memcmp(decoder->private_->stream_info.data.stream_info.md5sum, decoder->private_->computed_md5sum, 16))
  99735. md5_failed = true;
  99736. }
  99737. decoder->private_->is_seeking = false;
  99738. set_defaults_dec(decoder);
  99739. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  99740. return !md5_failed;
  99741. }
  99742. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long value)
  99743. {
  99744. FLAC__ASSERT(0 != decoder);
  99745. FLAC__ASSERT(0 != decoder->private_);
  99746. FLAC__ASSERT(0 != decoder->protected_);
  99747. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99748. return false;
  99749. #if FLAC__HAS_OGG
  99750. /* can't check decoder->private_->is_ogg since that's not set until init time */
  99751. FLAC__ogg_decoder_aspect_set_serial_number(&decoder->protected_->ogg_decoder_aspect, value);
  99752. return true;
  99753. #else
  99754. (void)value;
  99755. return false;
  99756. #endif
  99757. }
  99758. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value)
  99759. {
  99760. FLAC__ASSERT(0 != decoder);
  99761. FLAC__ASSERT(0 != decoder->protected_);
  99762. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99763. return false;
  99764. decoder->protected_->md5_checking = value;
  99765. return true;
  99766. }
  99767. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  99768. {
  99769. FLAC__ASSERT(0 != decoder);
  99770. FLAC__ASSERT(0 != decoder->private_);
  99771. FLAC__ASSERT(0 != decoder->protected_);
  99772. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  99773. /* double protection */
  99774. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  99775. return false;
  99776. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99777. return false;
  99778. decoder->private_->metadata_filter[type] = true;
  99779. if(type == FLAC__METADATA_TYPE_APPLICATION)
  99780. decoder->private_->metadata_filter_ids_count = 0;
  99781. return true;
  99782. }
  99783. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  99784. {
  99785. FLAC__ASSERT(0 != decoder);
  99786. FLAC__ASSERT(0 != decoder->private_);
  99787. FLAC__ASSERT(0 != decoder->protected_);
  99788. FLAC__ASSERT(0 != id);
  99789. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99790. return false;
  99791. if(decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  99792. return true;
  99793. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  99794. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  99795. 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))) {
  99796. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99797. return false;
  99798. }
  99799. decoder->private_->metadata_filter_ids_capacity *= 2;
  99800. }
  99801. 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));
  99802. decoder->private_->metadata_filter_ids_count++;
  99803. return true;
  99804. }
  99805. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder)
  99806. {
  99807. unsigned i;
  99808. FLAC__ASSERT(0 != decoder);
  99809. FLAC__ASSERT(0 != decoder->private_);
  99810. FLAC__ASSERT(0 != decoder->protected_);
  99811. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99812. return false;
  99813. for(i = 0; i < sizeof(decoder->private_->metadata_filter) / sizeof(decoder->private_->metadata_filter[0]); i++)
  99814. decoder->private_->metadata_filter[i] = true;
  99815. decoder->private_->metadata_filter_ids_count = 0;
  99816. return true;
  99817. }
  99818. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  99819. {
  99820. FLAC__ASSERT(0 != decoder);
  99821. FLAC__ASSERT(0 != decoder->private_);
  99822. FLAC__ASSERT(0 != decoder->protected_);
  99823. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  99824. /* double protection */
  99825. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  99826. return false;
  99827. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99828. return false;
  99829. decoder->private_->metadata_filter[type] = false;
  99830. if(type == FLAC__METADATA_TYPE_APPLICATION)
  99831. decoder->private_->metadata_filter_ids_count = 0;
  99832. return true;
  99833. }
  99834. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  99835. {
  99836. FLAC__ASSERT(0 != decoder);
  99837. FLAC__ASSERT(0 != decoder->private_);
  99838. FLAC__ASSERT(0 != decoder->protected_);
  99839. FLAC__ASSERT(0 != id);
  99840. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99841. return false;
  99842. if(!decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  99843. return true;
  99844. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  99845. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  99846. 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))) {
  99847. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99848. return false;
  99849. }
  99850. decoder->private_->metadata_filter_ids_capacity *= 2;
  99851. }
  99852. 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));
  99853. decoder->private_->metadata_filter_ids_count++;
  99854. return true;
  99855. }
  99856. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder)
  99857. {
  99858. FLAC__ASSERT(0 != decoder);
  99859. FLAC__ASSERT(0 != decoder->private_);
  99860. FLAC__ASSERT(0 != decoder->protected_);
  99861. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99862. return false;
  99863. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  99864. decoder->private_->metadata_filter_ids_count = 0;
  99865. return true;
  99866. }
  99867. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder)
  99868. {
  99869. FLAC__ASSERT(0 != decoder);
  99870. FLAC__ASSERT(0 != decoder->protected_);
  99871. return decoder->protected_->state;
  99872. }
  99873. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder)
  99874. {
  99875. return FLAC__StreamDecoderStateString[decoder->protected_->state];
  99876. }
  99877. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder)
  99878. {
  99879. FLAC__ASSERT(0 != decoder);
  99880. FLAC__ASSERT(0 != decoder->protected_);
  99881. return decoder->protected_->md5_checking;
  99882. }
  99883. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder)
  99884. {
  99885. FLAC__ASSERT(0 != decoder);
  99886. FLAC__ASSERT(0 != decoder->protected_);
  99887. return decoder->private_->has_stream_info? decoder->private_->stream_info.data.stream_info.total_samples : 0;
  99888. }
  99889. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder)
  99890. {
  99891. FLAC__ASSERT(0 != decoder);
  99892. FLAC__ASSERT(0 != decoder->protected_);
  99893. return decoder->protected_->channels;
  99894. }
  99895. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder)
  99896. {
  99897. FLAC__ASSERT(0 != decoder);
  99898. FLAC__ASSERT(0 != decoder->protected_);
  99899. return decoder->protected_->channel_assignment;
  99900. }
  99901. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder)
  99902. {
  99903. FLAC__ASSERT(0 != decoder);
  99904. FLAC__ASSERT(0 != decoder->protected_);
  99905. return decoder->protected_->bits_per_sample;
  99906. }
  99907. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder)
  99908. {
  99909. FLAC__ASSERT(0 != decoder);
  99910. FLAC__ASSERT(0 != decoder->protected_);
  99911. return decoder->protected_->sample_rate;
  99912. }
  99913. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder)
  99914. {
  99915. FLAC__ASSERT(0 != decoder);
  99916. FLAC__ASSERT(0 != decoder->protected_);
  99917. return decoder->protected_->blocksize;
  99918. }
  99919. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position)
  99920. {
  99921. FLAC__ASSERT(0 != decoder);
  99922. FLAC__ASSERT(0 != decoder->private_);
  99923. FLAC__ASSERT(0 != position);
  99924. #if FLAC__HAS_OGG
  99925. if(decoder->private_->is_ogg)
  99926. return false;
  99927. #endif
  99928. if(0 == decoder->private_->tell_callback)
  99929. return false;
  99930. if(decoder->private_->tell_callback(decoder, position, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK)
  99931. return false;
  99932. /* should never happen since all FLAC frames and metadata blocks are byte aligned, but check just in case */
  99933. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input))
  99934. return false;
  99935. FLAC__ASSERT(*position >= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder));
  99936. *position -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder);
  99937. return true;
  99938. }
  99939. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder)
  99940. {
  99941. FLAC__ASSERT(0 != decoder);
  99942. FLAC__ASSERT(0 != decoder->private_);
  99943. FLAC__ASSERT(0 != decoder->protected_);
  99944. decoder->private_->samples_decoded = 0;
  99945. decoder->private_->do_md5_checking = false;
  99946. #if FLAC__HAS_OGG
  99947. if(decoder->private_->is_ogg)
  99948. FLAC__ogg_decoder_aspect_flush(&decoder->protected_->ogg_decoder_aspect);
  99949. #endif
  99950. if(!FLAC__bitreader_clear(decoder->private_->input)) {
  99951. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99952. return false;
  99953. }
  99954. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  99955. return true;
  99956. }
  99957. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder)
  99958. {
  99959. FLAC__ASSERT(0 != decoder);
  99960. FLAC__ASSERT(0 != decoder->private_);
  99961. FLAC__ASSERT(0 != decoder->protected_);
  99962. if(!FLAC__stream_decoder_flush(decoder)) {
  99963. /* above call sets the state for us */
  99964. return false;
  99965. }
  99966. #if FLAC__HAS_OGG
  99967. /*@@@ could go in !internal_reset_hack block below */
  99968. if(decoder->private_->is_ogg)
  99969. FLAC__ogg_decoder_aspect_reset(&decoder->protected_->ogg_decoder_aspect);
  99970. #endif
  99971. /* Rewind if necessary. If FLAC__stream_decoder_init() is calling us,
  99972. * (internal_reset_hack) don't try to rewind since we are already at
  99973. * the beginning of the stream and don't want to fail if the input is
  99974. * not seekable.
  99975. */
  99976. if(!decoder->private_->internal_reset_hack) {
  99977. if(decoder->private_->file == stdin)
  99978. return false; /* can't rewind stdin, reset fails */
  99979. if(decoder->private_->seek_callback && decoder->private_->seek_callback(decoder, 0, decoder->private_->client_data) == FLAC__STREAM_DECODER_SEEK_STATUS_ERROR)
  99980. return false; /* seekable and seek fails, reset fails */
  99981. }
  99982. else
  99983. decoder->private_->internal_reset_hack = false;
  99984. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;
  99985. decoder->private_->has_stream_info = false;
  99986. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  99987. free(decoder->private_->seek_table.data.seek_table.points);
  99988. decoder->private_->seek_table.data.seek_table.points = 0;
  99989. decoder->private_->has_seek_table = false;
  99990. }
  99991. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  99992. /*
  99993. * This goes in reset() and not flush() because according to the spec, a
  99994. * fixed-blocksize stream must stay that way through the whole stream.
  99995. */
  99996. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  99997. /* We initialize the FLAC__MD5Context even though we may never use it. This
  99998. * is because md5 checking may be turned on to start and then turned off if
  99999. * a seek occurs. So we init the context here and finalize it in
  100000. * FLAC__stream_decoder_finish() to make sure things are always cleaned up
  100001. * properly.
  100002. */
  100003. FLAC__MD5Init(&decoder->private_->md5context);
  100004. decoder->private_->first_frame_offset = 0;
  100005. decoder->private_->unparseable_frame_count = 0;
  100006. return true;
  100007. }
  100008. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder)
  100009. {
  100010. FLAC__bool got_a_frame;
  100011. FLAC__ASSERT(0 != decoder);
  100012. FLAC__ASSERT(0 != decoder->protected_);
  100013. while(1) {
  100014. switch(decoder->protected_->state) {
  100015. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  100016. if(!find_metadata_(decoder))
  100017. return false; /* above function sets the status for us */
  100018. break;
  100019. case FLAC__STREAM_DECODER_READ_METADATA:
  100020. if(!read_metadata_(decoder))
  100021. return false; /* above function sets the status for us */
  100022. else
  100023. return true;
  100024. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  100025. if(!frame_sync_(decoder))
  100026. return true; /* above function sets the status for us */
  100027. break;
  100028. case FLAC__STREAM_DECODER_READ_FRAME:
  100029. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/true))
  100030. return false; /* above function sets the status for us */
  100031. if(got_a_frame)
  100032. return true; /* above function sets the status for us */
  100033. break;
  100034. case FLAC__STREAM_DECODER_END_OF_STREAM:
  100035. case FLAC__STREAM_DECODER_ABORTED:
  100036. return true;
  100037. default:
  100038. FLAC__ASSERT(0);
  100039. return false;
  100040. }
  100041. }
  100042. }
  100043. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder)
  100044. {
  100045. FLAC__ASSERT(0 != decoder);
  100046. FLAC__ASSERT(0 != decoder->protected_);
  100047. while(1) {
  100048. switch(decoder->protected_->state) {
  100049. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  100050. if(!find_metadata_(decoder))
  100051. return false; /* above function sets the status for us */
  100052. break;
  100053. case FLAC__STREAM_DECODER_READ_METADATA:
  100054. if(!read_metadata_(decoder))
  100055. return false; /* above function sets the status for us */
  100056. break;
  100057. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  100058. case FLAC__STREAM_DECODER_READ_FRAME:
  100059. case FLAC__STREAM_DECODER_END_OF_STREAM:
  100060. case FLAC__STREAM_DECODER_ABORTED:
  100061. return true;
  100062. default:
  100063. FLAC__ASSERT(0);
  100064. return false;
  100065. }
  100066. }
  100067. }
  100068. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder)
  100069. {
  100070. FLAC__bool dummy;
  100071. FLAC__ASSERT(0 != decoder);
  100072. FLAC__ASSERT(0 != decoder->protected_);
  100073. while(1) {
  100074. switch(decoder->protected_->state) {
  100075. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  100076. if(!find_metadata_(decoder))
  100077. return false; /* above function sets the status for us */
  100078. break;
  100079. case FLAC__STREAM_DECODER_READ_METADATA:
  100080. if(!read_metadata_(decoder))
  100081. return false; /* above function sets the status for us */
  100082. break;
  100083. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  100084. if(!frame_sync_(decoder))
  100085. return true; /* above function sets the status for us */
  100086. break;
  100087. case FLAC__STREAM_DECODER_READ_FRAME:
  100088. if(!read_frame_(decoder, &dummy, /*do_full_decode=*/true))
  100089. return false; /* above function sets the status for us */
  100090. break;
  100091. case FLAC__STREAM_DECODER_END_OF_STREAM:
  100092. case FLAC__STREAM_DECODER_ABORTED:
  100093. return true;
  100094. default:
  100095. FLAC__ASSERT(0);
  100096. return false;
  100097. }
  100098. }
  100099. }
  100100. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder)
  100101. {
  100102. FLAC__bool got_a_frame;
  100103. FLAC__ASSERT(0 != decoder);
  100104. FLAC__ASSERT(0 != decoder->protected_);
  100105. while(1) {
  100106. switch(decoder->protected_->state) {
  100107. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  100108. case FLAC__STREAM_DECODER_READ_METADATA:
  100109. return false; /* above function sets the status for us */
  100110. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  100111. if(!frame_sync_(decoder))
  100112. return true; /* above function sets the status for us */
  100113. break;
  100114. case FLAC__STREAM_DECODER_READ_FRAME:
  100115. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/false))
  100116. return false; /* above function sets the status for us */
  100117. if(got_a_frame)
  100118. return true; /* above function sets the status for us */
  100119. break;
  100120. case FLAC__STREAM_DECODER_END_OF_STREAM:
  100121. case FLAC__STREAM_DECODER_ABORTED:
  100122. return true;
  100123. default:
  100124. FLAC__ASSERT(0);
  100125. return false;
  100126. }
  100127. }
  100128. }
  100129. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample)
  100130. {
  100131. FLAC__uint64 length;
  100132. FLAC__ASSERT(0 != decoder);
  100133. if(
  100134. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA &&
  100135. decoder->protected_->state != FLAC__STREAM_DECODER_READ_METADATA &&
  100136. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC &&
  100137. decoder->protected_->state != FLAC__STREAM_DECODER_READ_FRAME &&
  100138. decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM
  100139. )
  100140. return false;
  100141. if(0 == decoder->private_->seek_callback)
  100142. return false;
  100143. FLAC__ASSERT(decoder->private_->seek_callback);
  100144. FLAC__ASSERT(decoder->private_->tell_callback);
  100145. FLAC__ASSERT(decoder->private_->length_callback);
  100146. FLAC__ASSERT(decoder->private_->eof_callback);
  100147. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder))
  100148. return false;
  100149. decoder->private_->is_seeking = true;
  100150. /* turn off md5 checking if a seek is attempted */
  100151. decoder->private_->do_md5_checking = false;
  100152. /* 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) */
  100153. if(decoder->private_->length_callback(decoder, &length, decoder->private_->client_data) != FLAC__STREAM_DECODER_LENGTH_STATUS_OK) {
  100154. decoder->private_->is_seeking = false;
  100155. return false;
  100156. }
  100157. /* if we haven't finished processing the metadata yet, do that so we have the STREAMINFO, SEEK_TABLE, and first_frame_offset */
  100158. if(
  100159. decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA ||
  100160. decoder->protected_->state == FLAC__STREAM_DECODER_READ_METADATA
  100161. ) {
  100162. if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder)) {
  100163. /* above call sets the state for us */
  100164. decoder->private_->is_seeking = false;
  100165. return false;
  100166. }
  100167. /* check this again in case we didn't know total_samples the first time */
  100168. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder)) {
  100169. decoder->private_->is_seeking = false;
  100170. return false;
  100171. }
  100172. }
  100173. {
  100174. const FLAC__bool ok =
  100175. #if FLAC__HAS_OGG
  100176. decoder->private_->is_ogg?
  100177. seek_to_absolute_sample_ogg_(decoder, length, sample) :
  100178. #endif
  100179. seek_to_absolute_sample_(decoder, length, sample)
  100180. ;
  100181. decoder->private_->is_seeking = false;
  100182. return ok;
  100183. }
  100184. }
  100185. /***********************************************************************
  100186. *
  100187. * Protected class methods
  100188. *
  100189. ***********************************************************************/
  100190. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder)
  100191. {
  100192. FLAC__ASSERT(0 != decoder);
  100193. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100194. FLAC__ASSERT(!(FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) & 7));
  100195. return FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) / 8;
  100196. }
  100197. /***********************************************************************
  100198. *
  100199. * Private class methods
  100200. *
  100201. ***********************************************************************/
  100202. void set_defaults_dec(FLAC__StreamDecoder *decoder)
  100203. {
  100204. #if FLAC__HAS_OGG
  100205. decoder->private_->is_ogg = false;
  100206. #endif
  100207. decoder->private_->read_callback = 0;
  100208. decoder->private_->seek_callback = 0;
  100209. decoder->private_->tell_callback = 0;
  100210. decoder->private_->length_callback = 0;
  100211. decoder->private_->eof_callback = 0;
  100212. decoder->private_->write_callback = 0;
  100213. decoder->private_->metadata_callback = 0;
  100214. decoder->private_->error_callback = 0;
  100215. decoder->private_->client_data = 0;
  100216. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  100217. decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] = true;
  100218. decoder->private_->metadata_filter_ids_count = 0;
  100219. decoder->protected_->md5_checking = false;
  100220. #if FLAC__HAS_OGG
  100221. FLAC__ogg_decoder_aspect_set_defaults(&decoder->protected_->ogg_decoder_aspect);
  100222. #endif
  100223. }
  100224. /*
  100225. * This will forcibly set stdin to binary mode (for OSes that require it)
  100226. */
  100227. FILE *get_binary_stdin_(void)
  100228. {
  100229. /* if something breaks here it is probably due to the presence or
  100230. * absence of an underscore before the identifiers 'setmode',
  100231. * 'fileno', and/or 'O_BINARY'; check your system header files.
  100232. */
  100233. #if defined _MSC_VER || defined __MINGW32__
  100234. _setmode(_fileno(stdin), _O_BINARY);
  100235. #elif defined __CYGWIN__
  100236. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  100237. setmode(_fileno(stdin), _O_BINARY);
  100238. #elif defined __EMX__
  100239. setmode(fileno(stdin), O_BINARY);
  100240. #endif
  100241. return stdin;
  100242. }
  100243. FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels)
  100244. {
  100245. unsigned i;
  100246. FLAC__int32 *tmp;
  100247. if(size <= decoder->private_->output_capacity && channels <= decoder->private_->output_channels)
  100248. return true;
  100249. /* simply using realloc() is not practical because the number of channels may change mid-stream */
  100250. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  100251. if(0 != decoder->private_->output[i]) {
  100252. free(decoder->private_->output[i]-4);
  100253. decoder->private_->output[i] = 0;
  100254. }
  100255. if(0 != decoder->private_->residual_unaligned[i]) {
  100256. free(decoder->private_->residual_unaligned[i]);
  100257. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  100258. }
  100259. }
  100260. for(i = 0; i < channels; i++) {
  100261. /* WATCHOUT:
  100262. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  100263. * output arrays have a buffer of up to 3 zeroes in front
  100264. * (at negative indices) for alignment purposes; we use 4
  100265. * to keep the data well-aligned.
  100266. */
  100267. tmp = (FLAC__int32*)safe_malloc_muladd2_(sizeof(FLAC__int32), /*times (*/size, /*+*/4/*)*/);
  100268. if(tmp == 0) {
  100269. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100270. return false;
  100271. }
  100272. memset(tmp, 0, sizeof(FLAC__int32)*4);
  100273. decoder->private_->output[i] = tmp + 4;
  100274. /* WATCHOUT:
  100275. * minimum of quadword alignment for PPC vector optimizations is REQUIRED:
  100276. */
  100277. if(!FLAC__memory_alloc_aligned_int32_array(size, &decoder->private_->residual_unaligned[i], &decoder->private_->residual[i])) {
  100278. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100279. return false;
  100280. }
  100281. }
  100282. decoder->private_->output_capacity = size;
  100283. decoder->private_->output_channels = channels;
  100284. return true;
  100285. }
  100286. FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id)
  100287. {
  100288. size_t i;
  100289. FLAC__ASSERT(0 != decoder);
  100290. FLAC__ASSERT(0 != decoder->private_);
  100291. for(i = 0; i < decoder->private_->metadata_filter_ids_count; i++)
  100292. if(0 == memcmp(decoder->private_->metadata_filter_ids + i * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)))
  100293. return true;
  100294. return false;
  100295. }
  100296. FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder)
  100297. {
  100298. FLAC__uint32 x;
  100299. unsigned i, id_;
  100300. FLAC__bool first = true;
  100301. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100302. for(i = id_ = 0; i < 4; ) {
  100303. if(decoder->private_->cached) {
  100304. x = (FLAC__uint32)decoder->private_->lookahead;
  100305. decoder->private_->cached = false;
  100306. }
  100307. else {
  100308. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100309. return false; /* read_callback_ sets the state for us */
  100310. }
  100311. if(x == FLAC__STREAM_SYNC_STRING[i]) {
  100312. first = true;
  100313. i++;
  100314. id_ = 0;
  100315. continue;
  100316. }
  100317. if(x == ID3V2_TAG_[id_]) {
  100318. id_++;
  100319. i = 0;
  100320. if(id_ == 3) {
  100321. if(!skip_id3v2_tag_(decoder))
  100322. return false; /* skip_id3v2_tag_ sets the state for us */
  100323. }
  100324. continue;
  100325. }
  100326. id_ = 0;
  100327. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100328. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  100329. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100330. return false; /* read_callback_ sets the state for us */
  100331. /* 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 */
  100332. /* else we have to check if the second byte is the end of a sync code */
  100333. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100334. decoder->private_->lookahead = (FLAC__byte)x;
  100335. decoder->private_->cached = true;
  100336. }
  100337. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  100338. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  100339. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  100340. return true;
  100341. }
  100342. }
  100343. i = 0;
  100344. if(first) {
  100345. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100346. first = false;
  100347. }
  100348. }
  100349. decoder->protected_->state = FLAC__STREAM_DECODER_READ_METADATA;
  100350. return true;
  100351. }
  100352. FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder)
  100353. {
  100354. FLAC__bool is_last;
  100355. FLAC__uint32 i, x, type, length;
  100356. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100357. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_IS_LAST_LEN))
  100358. return false; /* read_callback_ sets the state for us */
  100359. is_last = x? true : false;
  100360. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &type, FLAC__STREAM_METADATA_TYPE_LEN))
  100361. return false; /* read_callback_ sets the state for us */
  100362. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &length, FLAC__STREAM_METADATA_LENGTH_LEN))
  100363. return false; /* read_callback_ sets the state for us */
  100364. if(type == FLAC__METADATA_TYPE_STREAMINFO) {
  100365. if(!read_metadata_streaminfo_(decoder, is_last, length))
  100366. return false;
  100367. decoder->private_->has_stream_info = true;
  100368. 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))
  100369. decoder->private_->do_md5_checking = false;
  100370. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] && decoder->private_->metadata_callback)
  100371. decoder->private_->metadata_callback(decoder, &decoder->private_->stream_info, decoder->private_->client_data);
  100372. }
  100373. else if(type == FLAC__METADATA_TYPE_SEEKTABLE) {
  100374. if(!read_metadata_seektable_(decoder, is_last, length))
  100375. return false;
  100376. decoder->private_->has_seek_table = true;
  100377. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_SEEKTABLE] && decoder->private_->metadata_callback)
  100378. decoder->private_->metadata_callback(decoder, &decoder->private_->seek_table, decoder->private_->client_data);
  100379. }
  100380. else {
  100381. FLAC__bool skip_it = !decoder->private_->metadata_filter[type];
  100382. unsigned real_length = length;
  100383. FLAC__StreamMetadata block;
  100384. block.is_last = is_last;
  100385. block.type = (FLAC__MetadataType)type;
  100386. block.length = length;
  100387. if(type == FLAC__METADATA_TYPE_APPLICATION) {
  100388. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8))
  100389. return false; /* read_callback_ sets the state for us */
  100390. if(real_length < FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) { /* underflow check */
  100391. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;/*@@@@@@ maybe wrong error? need to resync?*/
  100392. return false;
  100393. }
  100394. real_length -= FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8;
  100395. if(decoder->private_->metadata_filter_ids_count > 0 && has_id_filtered_(decoder, block.data.application.id))
  100396. skip_it = !skip_it;
  100397. }
  100398. if(skip_it) {
  100399. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  100400. return false; /* read_callback_ sets the state for us */
  100401. }
  100402. else {
  100403. switch(type) {
  100404. case FLAC__METADATA_TYPE_PADDING:
  100405. /* skip the padding bytes */
  100406. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  100407. return false; /* read_callback_ sets the state for us */
  100408. break;
  100409. case FLAC__METADATA_TYPE_APPLICATION:
  100410. /* remember, we read the ID already */
  100411. if(real_length > 0) {
  100412. if(0 == (block.data.application.data = (FLAC__byte*)malloc(real_length))) {
  100413. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100414. return false;
  100415. }
  100416. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.data, real_length))
  100417. return false; /* read_callback_ sets the state for us */
  100418. }
  100419. else
  100420. block.data.application.data = 0;
  100421. break;
  100422. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  100423. if(!read_metadata_vorbiscomment_(decoder, &block.data.vorbis_comment))
  100424. return false;
  100425. break;
  100426. case FLAC__METADATA_TYPE_CUESHEET:
  100427. if(!read_metadata_cuesheet_(decoder, &block.data.cue_sheet))
  100428. return false;
  100429. break;
  100430. case FLAC__METADATA_TYPE_PICTURE:
  100431. if(!read_metadata_picture_(decoder, &block.data.picture))
  100432. return false;
  100433. break;
  100434. case FLAC__METADATA_TYPE_STREAMINFO:
  100435. case FLAC__METADATA_TYPE_SEEKTABLE:
  100436. FLAC__ASSERT(0);
  100437. break;
  100438. default:
  100439. if(real_length > 0) {
  100440. if(0 == (block.data.unknown.data = (FLAC__byte*)malloc(real_length))) {
  100441. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100442. return false;
  100443. }
  100444. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.unknown.data, real_length))
  100445. return false; /* read_callback_ sets the state for us */
  100446. }
  100447. else
  100448. block.data.unknown.data = 0;
  100449. break;
  100450. }
  100451. if(!decoder->private_->is_seeking && decoder->private_->metadata_callback)
  100452. decoder->private_->metadata_callback(decoder, &block, decoder->private_->client_data);
  100453. /* now we have to free any malloc()ed data in the block */
  100454. switch(type) {
  100455. case FLAC__METADATA_TYPE_PADDING:
  100456. break;
  100457. case FLAC__METADATA_TYPE_APPLICATION:
  100458. if(0 != block.data.application.data)
  100459. free(block.data.application.data);
  100460. break;
  100461. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  100462. if(0 != block.data.vorbis_comment.vendor_string.entry)
  100463. free(block.data.vorbis_comment.vendor_string.entry);
  100464. if(block.data.vorbis_comment.num_comments > 0)
  100465. for(i = 0; i < block.data.vorbis_comment.num_comments; i++)
  100466. if(0 != block.data.vorbis_comment.comments[i].entry)
  100467. free(block.data.vorbis_comment.comments[i].entry);
  100468. if(0 != block.data.vorbis_comment.comments)
  100469. free(block.data.vorbis_comment.comments);
  100470. break;
  100471. case FLAC__METADATA_TYPE_CUESHEET:
  100472. if(block.data.cue_sheet.num_tracks > 0)
  100473. for(i = 0; i < block.data.cue_sheet.num_tracks; i++)
  100474. if(0 != block.data.cue_sheet.tracks[i].indices)
  100475. free(block.data.cue_sheet.tracks[i].indices);
  100476. if(0 != block.data.cue_sheet.tracks)
  100477. free(block.data.cue_sheet.tracks);
  100478. break;
  100479. case FLAC__METADATA_TYPE_PICTURE:
  100480. if(0 != block.data.picture.mime_type)
  100481. free(block.data.picture.mime_type);
  100482. if(0 != block.data.picture.description)
  100483. free(block.data.picture.description);
  100484. if(0 != block.data.picture.data)
  100485. free(block.data.picture.data);
  100486. break;
  100487. case FLAC__METADATA_TYPE_STREAMINFO:
  100488. case FLAC__METADATA_TYPE_SEEKTABLE:
  100489. FLAC__ASSERT(0);
  100490. default:
  100491. if(0 != block.data.unknown.data)
  100492. free(block.data.unknown.data);
  100493. break;
  100494. }
  100495. }
  100496. }
  100497. if(is_last) {
  100498. /* if this fails, it's OK, it's just a hint for the seek routine */
  100499. if(!FLAC__stream_decoder_get_decode_position(decoder, &decoder->private_->first_frame_offset))
  100500. decoder->private_->first_frame_offset = 0;
  100501. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100502. }
  100503. return true;
  100504. }
  100505. FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  100506. {
  100507. FLAC__uint32 x;
  100508. unsigned bits, used_bits = 0;
  100509. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100510. decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO;
  100511. decoder->private_->stream_info.is_last = is_last;
  100512. decoder->private_->stream_info.length = length;
  100513. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN;
  100514. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, bits))
  100515. return false; /* read_callback_ sets the state for us */
  100516. decoder->private_->stream_info.data.stream_info.min_blocksize = x;
  100517. used_bits += bits;
  100518. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN;
  100519. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  100520. return false; /* read_callback_ sets the state for us */
  100521. decoder->private_->stream_info.data.stream_info.max_blocksize = x;
  100522. used_bits += bits;
  100523. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN;
  100524. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  100525. return false; /* read_callback_ sets the state for us */
  100526. decoder->private_->stream_info.data.stream_info.min_framesize = x;
  100527. used_bits += bits;
  100528. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN;
  100529. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  100530. return false; /* read_callback_ sets the state for us */
  100531. decoder->private_->stream_info.data.stream_info.max_framesize = x;
  100532. used_bits += bits;
  100533. bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN;
  100534. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  100535. return false; /* read_callback_ sets the state for us */
  100536. decoder->private_->stream_info.data.stream_info.sample_rate = x;
  100537. used_bits += bits;
  100538. bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN;
  100539. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  100540. return false; /* read_callback_ sets the state for us */
  100541. decoder->private_->stream_info.data.stream_info.channels = x+1;
  100542. used_bits += bits;
  100543. bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN;
  100544. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  100545. return false; /* read_callback_ sets the state for us */
  100546. decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1;
  100547. used_bits += bits;
  100548. bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN;
  100549. 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))
  100550. return false; /* read_callback_ sets the state for us */
  100551. used_bits += bits;
  100552. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16))
  100553. return false; /* read_callback_ sets the state for us */
  100554. used_bits += 16*8;
  100555. /* skip the rest of the block */
  100556. FLAC__ASSERT(used_bits % 8 == 0);
  100557. length -= (used_bits / 8);
  100558. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  100559. return false; /* read_callback_ sets the state for us */
  100560. return true;
  100561. }
  100562. FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  100563. {
  100564. FLAC__uint32 i, x;
  100565. FLAC__uint64 xx;
  100566. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100567. decoder->private_->seek_table.type = FLAC__METADATA_TYPE_SEEKTABLE;
  100568. decoder->private_->seek_table.is_last = is_last;
  100569. decoder->private_->seek_table.length = length;
  100570. decoder->private_->seek_table.data.seek_table.num_points = length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
  100571. /* use realloc since we may pass through here several times (e.g. after seeking) */
  100572. 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)))) {
  100573. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100574. return false;
  100575. }
  100576. for(i = 0; i < decoder->private_->seek_table.data.seek_table.num_points; i++) {
  100577. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  100578. return false; /* read_callback_ sets the state for us */
  100579. decoder->private_->seek_table.data.seek_table.points[i].sample_number = xx;
  100580. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  100581. return false; /* read_callback_ sets the state for us */
  100582. decoder->private_->seek_table.data.seek_table.points[i].stream_offset = xx;
  100583. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  100584. return false; /* read_callback_ sets the state for us */
  100585. decoder->private_->seek_table.data.seek_table.points[i].frame_samples = x;
  100586. }
  100587. length -= (decoder->private_->seek_table.data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH);
  100588. /* if there is a partial point left, skip over it */
  100589. if(length > 0) {
  100590. /*@@@ do a send_error_to_client_() here? there's an argument for either way */
  100591. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  100592. return false; /* read_callback_ sets the state for us */
  100593. }
  100594. return true;
  100595. }
  100596. FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj)
  100597. {
  100598. FLAC__uint32 i;
  100599. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100600. /* read vendor string */
  100601. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  100602. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length))
  100603. return false; /* read_callback_ sets the state for us */
  100604. if(obj->vendor_string.length > 0) {
  100605. if(0 == (obj->vendor_string.entry = (FLAC__byte*)safe_malloc_add_2op_(obj->vendor_string.length, /*+*/1))) {
  100606. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100607. return false;
  100608. }
  100609. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length))
  100610. return false; /* read_callback_ sets the state for us */
  100611. obj->vendor_string.entry[obj->vendor_string.length] = '\0';
  100612. }
  100613. else
  100614. obj->vendor_string.entry = 0;
  100615. /* read num comments */
  100616. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32);
  100617. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->num_comments))
  100618. return false; /* read_callback_ sets the state for us */
  100619. /* read comments */
  100620. if(obj->num_comments > 0) {
  100621. if(0 == (obj->comments = (FLAC__StreamMetadata_VorbisComment_Entry*)safe_malloc_mul_2op_(obj->num_comments, /*times*/sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) {
  100622. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100623. return false;
  100624. }
  100625. for(i = 0; i < obj->num_comments; i++) {
  100626. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  100627. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->comments[i].length))
  100628. return false; /* read_callback_ sets the state for us */
  100629. if(obj->comments[i].length > 0) {
  100630. if(0 == (obj->comments[i].entry = (FLAC__byte*)safe_malloc_add_2op_(obj->comments[i].length, /*+*/1))) {
  100631. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100632. return false;
  100633. }
  100634. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length))
  100635. return false; /* read_callback_ sets the state for us */
  100636. obj->comments[i].entry[obj->comments[i].length] = '\0';
  100637. }
  100638. else
  100639. obj->comments[i].entry = 0;
  100640. }
  100641. }
  100642. else {
  100643. obj->comments = 0;
  100644. }
  100645. return true;
  100646. }
  100647. FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj)
  100648. {
  100649. FLAC__uint32 i, j, x;
  100650. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100651. memset(obj, 0, sizeof(FLAC__StreamMetadata_CueSheet));
  100652. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  100653. 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))
  100654. return false; /* read_callback_ sets the state for us */
  100655. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &obj->lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  100656. return false; /* read_callback_ sets the state for us */
  100657. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  100658. return false; /* read_callback_ sets the state for us */
  100659. obj->is_cd = x? true : false;
  100660. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  100661. return false; /* read_callback_ sets the state for us */
  100662. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  100663. return false; /* read_callback_ sets the state for us */
  100664. obj->num_tracks = x;
  100665. if(obj->num_tracks > 0) {
  100666. if(0 == (obj->tracks = (FLAC__StreamMetadata_CueSheet_Track*)safe_calloc_(obj->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)))) {
  100667. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100668. return false;
  100669. }
  100670. for(i = 0; i < obj->num_tracks; i++) {
  100671. FLAC__StreamMetadata_CueSheet_Track *track = &obj->tracks[i];
  100672. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  100673. return false; /* read_callback_ sets the state for us */
  100674. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  100675. return false; /* read_callback_ sets the state for us */
  100676. track->number = (FLAC__byte)x;
  100677. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  100678. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  100679. return false; /* read_callback_ sets the state for us */
  100680. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  100681. return false; /* read_callback_ sets the state for us */
  100682. track->type = x;
  100683. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  100684. return false; /* read_callback_ sets the state for us */
  100685. track->pre_emphasis = x;
  100686. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  100687. return false; /* read_callback_ sets the state for us */
  100688. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  100689. return false; /* read_callback_ sets the state for us */
  100690. track->num_indices = (FLAC__byte)x;
  100691. if(track->num_indices > 0) {
  100692. if(0 == (track->indices = (FLAC__StreamMetadata_CueSheet_Index*)safe_calloc_(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)))) {
  100693. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100694. return false;
  100695. }
  100696. for(j = 0; j < track->num_indices; j++) {
  100697. FLAC__StreamMetadata_CueSheet_Index *index = &track->indices[j];
  100698. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  100699. return false; /* read_callback_ sets the state for us */
  100700. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  100701. return false; /* read_callback_ sets the state for us */
  100702. index->number = (FLAC__byte)x;
  100703. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  100704. return false; /* read_callback_ sets the state for us */
  100705. }
  100706. }
  100707. }
  100708. }
  100709. return true;
  100710. }
  100711. FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj)
  100712. {
  100713. FLAC__uint32 x;
  100714. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100715. /* read type */
  100716. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  100717. return false; /* read_callback_ sets the state for us */
  100718. obj->type = (FLAC__StreamMetadata_Picture_Type) x;
  100719. /* read MIME type */
  100720. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  100721. return false; /* read_callback_ sets the state for us */
  100722. if(0 == (obj->mime_type = (char*)safe_malloc_add_2op_(x, /*+*/1))) {
  100723. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100724. return false;
  100725. }
  100726. if(x > 0) {
  100727. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->mime_type, x))
  100728. return false; /* read_callback_ sets the state for us */
  100729. }
  100730. obj->mime_type[x] = '\0';
  100731. /* read description */
  100732. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  100733. return false; /* read_callback_ sets the state for us */
  100734. if(0 == (obj->description = (FLAC__byte*)safe_malloc_add_2op_(x, /*+*/1))) {
  100735. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100736. return false;
  100737. }
  100738. if(x > 0) {
  100739. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->description, x))
  100740. return false; /* read_callback_ sets the state for us */
  100741. }
  100742. obj->description[x] = '\0';
  100743. /* read width */
  100744. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  100745. return false; /* read_callback_ sets the state for us */
  100746. /* read height */
  100747. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  100748. return false; /* read_callback_ sets the state for us */
  100749. /* read depth */
  100750. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  100751. return false; /* read_callback_ sets the state for us */
  100752. /* read colors */
  100753. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  100754. return false; /* read_callback_ sets the state for us */
  100755. /* read data */
  100756. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &(obj->data_length), FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  100757. return false; /* read_callback_ sets the state for us */
  100758. if(0 == (obj->data = (FLAC__byte*)safe_malloc_(obj->data_length))) {
  100759. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100760. return false;
  100761. }
  100762. if(obj->data_length > 0) {
  100763. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->data, obj->data_length))
  100764. return false; /* read_callback_ sets the state for us */
  100765. }
  100766. return true;
  100767. }
  100768. FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder)
  100769. {
  100770. FLAC__uint32 x;
  100771. unsigned i, skip;
  100772. /* skip the version and flags bytes */
  100773. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 24))
  100774. return false; /* read_callback_ sets the state for us */
  100775. /* get the size (in bytes) to skip */
  100776. skip = 0;
  100777. for(i = 0; i < 4; i++) {
  100778. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100779. return false; /* read_callback_ sets the state for us */
  100780. skip <<= 7;
  100781. skip |= (x & 0x7f);
  100782. }
  100783. /* skip the rest of the tag */
  100784. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, skip))
  100785. return false; /* read_callback_ sets the state for us */
  100786. return true;
  100787. }
  100788. FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder)
  100789. {
  100790. FLAC__uint32 x;
  100791. FLAC__bool first = true;
  100792. /* If we know the total number of samples in the stream, stop if we've read that many. */
  100793. /* This will stop us, for example, from wasting time trying to sync on an ID3V1 tag. */
  100794. if(FLAC__stream_decoder_get_total_samples(decoder) > 0) {
  100795. if(decoder->private_->samples_decoded >= FLAC__stream_decoder_get_total_samples(decoder)) {
  100796. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  100797. return true;
  100798. }
  100799. }
  100800. /* make sure we're byte aligned */
  100801. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  100802. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  100803. return false; /* read_callback_ sets the state for us */
  100804. }
  100805. while(1) {
  100806. if(decoder->private_->cached) {
  100807. x = (FLAC__uint32)decoder->private_->lookahead;
  100808. decoder->private_->cached = false;
  100809. }
  100810. else {
  100811. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100812. return false; /* read_callback_ sets the state for us */
  100813. }
  100814. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100815. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  100816. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100817. return false; /* read_callback_ sets the state for us */
  100818. /* 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 */
  100819. /* else we have to check if the second byte is the end of a sync code */
  100820. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100821. decoder->private_->lookahead = (FLAC__byte)x;
  100822. decoder->private_->cached = true;
  100823. }
  100824. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  100825. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  100826. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  100827. return true;
  100828. }
  100829. }
  100830. if(first) {
  100831. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100832. first = false;
  100833. }
  100834. }
  100835. return true;
  100836. }
  100837. FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode)
  100838. {
  100839. unsigned channel;
  100840. unsigned i;
  100841. FLAC__int32 mid, side;
  100842. unsigned frame_crc; /* the one we calculate from the input stream */
  100843. FLAC__uint32 x;
  100844. *got_a_frame = false;
  100845. /* init the CRC */
  100846. frame_crc = 0;
  100847. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[0], frame_crc);
  100848. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[1], frame_crc);
  100849. FLAC__bitreader_reset_read_crc16(decoder->private_->input, (FLAC__uint16)frame_crc);
  100850. if(!read_frame_header_(decoder))
  100851. return false;
  100852. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means we didn't sync on a valid header */
  100853. return true;
  100854. if(!allocate_output_(decoder, decoder->private_->frame.header.blocksize, decoder->private_->frame.header.channels))
  100855. return false;
  100856. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  100857. /*
  100858. * first figure the correct bits-per-sample of the subframe
  100859. */
  100860. unsigned bps = decoder->private_->frame.header.bits_per_sample;
  100861. switch(decoder->private_->frame.header.channel_assignment) {
  100862. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  100863. /* no adjustment needed */
  100864. break;
  100865. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  100866. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100867. if(channel == 1)
  100868. bps++;
  100869. break;
  100870. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  100871. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100872. if(channel == 0)
  100873. bps++;
  100874. break;
  100875. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  100876. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100877. if(channel == 1)
  100878. bps++;
  100879. break;
  100880. default:
  100881. FLAC__ASSERT(0);
  100882. }
  100883. /*
  100884. * now read it
  100885. */
  100886. if(!read_subframe_(decoder, channel, bps, do_full_decode))
  100887. return false;
  100888. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  100889. return true;
  100890. }
  100891. if(!read_zero_padding_(decoder))
  100892. return false;
  100893. 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) */
  100894. return true;
  100895. /*
  100896. * Read the frame CRC-16 from the footer and check
  100897. */
  100898. frame_crc = FLAC__bitreader_get_read_crc16(decoder->private_->input);
  100899. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__FRAME_FOOTER_CRC_LEN))
  100900. return false; /* read_callback_ sets the state for us */
  100901. if(frame_crc == x) {
  100902. if(do_full_decode) {
  100903. /* Undo any special channel coding */
  100904. switch(decoder->private_->frame.header.channel_assignment) {
  100905. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  100906. /* do nothing */
  100907. break;
  100908. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  100909. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100910. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  100911. decoder->private_->output[1][i] = decoder->private_->output[0][i] - decoder->private_->output[1][i];
  100912. break;
  100913. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  100914. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100915. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  100916. decoder->private_->output[0][i] += decoder->private_->output[1][i];
  100917. break;
  100918. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  100919. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100920. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  100921. #if 1
  100922. mid = decoder->private_->output[0][i];
  100923. side = decoder->private_->output[1][i];
  100924. mid <<= 1;
  100925. mid |= (side & 1); /* i.e. if 'side' is odd... */
  100926. decoder->private_->output[0][i] = (mid + side) >> 1;
  100927. decoder->private_->output[1][i] = (mid - side) >> 1;
  100928. #else
  100929. /* OPT: without 'side' temp variable */
  100930. mid = (decoder->private_->output[0][i] << 1) | (decoder->private_->output[1][i] & 1); /* i.e. if 'side' is odd... */
  100931. decoder->private_->output[0][i] = (mid + decoder->private_->output[1][i]) >> 1;
  100932. decoder->private_->output[1][i] = (mid - decoder->private_->output[1][i]) >> 1;
  100933. #endif
  100934. }
  100935. break;
  100936. default:
  100937. FLAC__ASSERT(0);
  100938. break;
  100939. }
  100940. }
  100941. }
  100942. else {
  100943. /* Bad frame, emit error and zero the output signal */
  100944. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH);
  100945. if(do_full_decode) {
  100946. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  100947. memset(decoder->private_->output[channel], 0, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  100948. }
  100949. }
  100950. }
  100951. *got_a_frame = true;
  100952. /* we wait to update fixed_block_size until here, when we're sure we've got a proper frame and hence a correct blocksize */
  100953. if(decoder->private_->next_fixed_block_size)
  100954. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size;
  100955. /* put the latest values into the public section of the decoder instance */
  100956. decoder->protected_->channels = decoder->private_->frame.header.channels;
  100957. decoder->protected_->channel_assignment = decoder->private_->frame.header.channel_assignment;
  100958. decoder->protected_->bits_per_sample = decoder->private_->frame.header.bits_per_sample;
  100959. decoder->protected_->sample_rate = decoder->private_->frame.header.sample_rate;
  100960. decoder->protected_->blocksize = decoder->private_->frame.header.blocksize;
  100961. FLAC__ASSERT(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  100962. decoder->private_->samples_decoded = decoder->private_->frame.header.number.sample_number + decoder->private_->frame.header.blocksize;
  100963. /* write it */
  100964. if(do_full_decode) {
  100965. if(write_audio_frame_to_client_(decoder, &decoder->private_->frame, (const FLAC__int32 * const *)decoder->private_->output) != FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE)
  100966. return false;
  100967. }
  100968. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100969. return true;
  100970. }
  100971. FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder)
  100972. {
  100973. FLAC__uint32 x;
  100974. FLAC__uint64 xx;
  100975. unsigned i, blocksize_hint = 0, sample_rate_hint = 0;
  100976. FLAC__byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */
  100977. unsigned raw_header_len;
  100978. FLAC__bool is_unparseable = false;
  100979. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100980. /* init the raw header with the saved bits from synchronization */
  100981. raw_header[0] = decoder->private_->header_warmup[0];
  100982. raw_header[1] = decoder->private_->header_warmup[1];
  100983. raw_header_len = 2;
  100984. /* check to make sure that reserved bit is 0 */
  100985. if(raw_header[1] & 0x02) /* MAGIC NUMBER */
  100986. is_unparseable = true;
  100987. /*
  100988. * Note that along the way as we read the header, we look for a sync
  100989. * code inside. If we find one it would indicate that our original
  100990. * sync was bad since there cannot be a sync code in a valid header.
  100991. *
  100992. * Three kinds of things can go wrong when reading the frame header:
  100993. * 1) We may have sync'ed incorrectly and not landed on a frame header.
  100994. * If we don't find a sync code, it can end up looking like we read
  100995. * a valid but unparseable header, until getting to the frame header
  100996. * CRC. Even then we could get a false positive on the CRC.
  100997. * 2) We may have sync'ed correctly but on an unparseable frame (from a
  100998. * future encoder).
  100999. * 3) We may be on a damaged frame which appears valid but unparseable.
  101000. *
  101001. * For all these reasons, we try and read a complete frame header as
  101002. * long as it seems valid, even if unparseable, up until the frame
  101003. * header CRC.
  101004. */
  101005. /*
  101006. * read in the raw header as bytes so we can CRC it, and parse it on the way
  101007. */
  101008. for(i = 0; i < 2; i++) {
  101009. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101010. return false; /* read_callback_ sets the state for us */
  101011. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  101012. /* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */
  101013. decoder->private_->lookahead = (FLAC__byte)x;
  101014. decoder->private_->cached = true;
  101015. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101016. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101017. return true;
  101018. }
  101019. raw_header[raw_header_len++] = (FLAC__byte)x;
  101020. }
  101021. switch(x = raw_header[2] >> 4) {
  101022. case 0:
  101023. is_unparseable = true;
  101024. break;
  101025. case 1:
  101026. decoder->private_->frame.header.blocksize = 192;
  101027. break;
  101028. case 2:
  101029. case 3:
  101030. case 4:
  101031. case 5:
  101032. decoder->private_->frame.header.blocksize = 576 << (x-2);
  101033. break;
  101034. case 6:
  101035. case 7:
  101036. blocksize_hint = x;
  101037. break;
  101038. case 8:
  101039. case 9:
  101040. case 10:
  101041. case 11:
  101042. case 12:
  101043. case 13:
  101044. case 14:
  101045. case 15:
  101046. decoder->private_->frame.header.blocksize = 256 << (x-8);
  101047. break;
  101048. default:
  101049. FLAC__ASSERT(0);
  101050. break;
  101051. }
  101052. switch(x = raw_header[2] & 0x0f) {
  101053. case 0:
  101054. if(decoder->private_->has_stream_info)
  101055. decoder->private_->frame.header.sample_rate = decoder->private_->stream_info.data.stream_info.sample_rate;
  101056. else
  101057. is_unparseable = true;
  101058. break;
  101059. case 1:
  101060. decoder->private_->frame.header.sample_rate = 88200;
  101061. break;
  101062. case 2:
  101063. decoder->private_->frame.header.sample_rate = 176400;
  101064. break;
  101065. case 3:
  101066. decoder->private_->frame.header.sample_rate = 192000;
  101067. break;
  101068. case 4:
  101069. decoder->private_->frame.header.sample_rate = 8000;
  101070. break;
  101071. case 5:
  101072. decoder->private_->frame.header.sample_rate = 16000;
  101073. break;
  101074. case 6:
  101075. decoder->private_->frame.header.sample_rate = 22050;
  101076. break;
  101077. case 7:
  101078. decoder->private_->frame.header.sample_rate = 24000;
  101079. break;
  101080. case 8:
  101081. decoder->private_->frame.header.sample_rate = 32000;
  101082. break;
  101083. case 9:
  101084. decoder->private_->frame.header.sample_rate = 44100;
  101085. break;
  101086. case 10:
  101087. decoder->private_->frame.header.sample_rate = 48000;
  101088. break;
  101089. case 11:
  101090. decoder->private_->frame.header.sample_rate = 96000;
  101091. break;
  101092. case 12:
  101093. case 13:
  101094. case 14:
  101095. sample_rate_hint = x;
  101096. break;
  101097. case 15:
  101098. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101099. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101100. return true;
  101101. default:
  101102. FLAC__ASSERT(0);
  101103. }
  101104. x = (unsigned)(raw_header[3] >> 4);
  101105. if(x & 8) {
  101106. decoder->private_->frame.header.channels = 2;
  101107. switch(x & 7) {
  101108. case 0:
  101109. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
  101110. break;
  101111. case 1:
  101112. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
  101113. break;
  101114. case 2:
  101115. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
  101116. break;
  101117. default:
  101118. is_unparseable = true;
  101119. break;
  101120. }
  101121. }
  101122. else {
  101123. decoder->private_->frame.header.channels = (unsigned)x + 1;
  101124. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  101125. }
  101126. switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
  101127. case 0:
  101128. if(decoder->private_->has_stream_info)
  101129. decoder->private_->frame.header.bits_per_sample = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  101130. else
  101131. is_unparseable = true;
  101132. break;
  101133. case 1:
  101134. decoder->private_->frame.header.bits_per_sample = 8;
  101135. break;
  101136. case 2:
  101137. decoder->private_->frame.header.bits_per_sample = 12;
  101138. break;
  101139. case 4:
  101140. decoder->private_->frame.header.bits_per_sample = 16;
  101141. break;
  101142. case 5:
  101143. decoder->private_->frame.header.bits_per_sample = 20;
  101144. break;
  101145. case 6:
  101146. decoder->private_->frame.header.bits_per_sample = 24;
  101147. break;
  101148. case 3:
  101149. case 7:
  101150. is_unparseable = true;
  101151. break;
  101152. default:
  101153. FLAC__ASSERT(0);
  101154. break;
  101155. }
  101156. /* check to make sure that reserved bit is 0 */
  101157. if(raw_header[3] & 0x01) /* MAGIC NUMBER */
  101158. is_unparseable = true;
  101159. /* read the frame's starting sample number (or frame number as the case may be) */
  101160. if(
  101161. raw_header[1] & 0x01 ||
  101162. /*@@@ 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 */
  101163. (decoder->private_->has_stream_info && decoder->private_->stream_info.data.stream_info.min_blocksize != decoder->private_->stream_info.data.stream_info.max_blocksize)
  101164. ) { /* variable blocksize */
  101165. if(!FLAC__bitreader_read_utf8_uint64(decoder->private_->input, &xx, raw_header, &raw_header_len))
  101166. return false; /* read_callback_ sets the state for us */
  101167. if(xx == FLAC__U64L(0xffffffffffffffff)) { /* i.e. non-UTF8 code... */
  101168. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  101169. decoder->private_->cached = true;
  101170. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101171. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101172. return true;
  101173. }
  101174. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  101175. decoder->private_->frame.header.number.sample_number = xx;
  101176. }
  101177. else { /* fixed blocksize */
  101178. if(!FLAC__bitreader_read_utf8_uint32(decoder->private_->input, &x, raw_header, &raw_header_len))
  101179. return false; /* read_callback_ sets the state for us */
  101180. if(x == 0xffffffff) { /* i.e. non-UTF8 code... */
  101181. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  101182. decoder->private_->cached = true;
  101183. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101184. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101185. return true;
  101186. }
  101187. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  101188. decoder->private_->frame.header.number.frame_number = x;
  101189. }
  101190. if(blocksize_hint) {
  101191. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101192. return false; /* read_callback_ sets the state for us */
  101193. raw_header[raw_header_len++] = (FLAC__byte)x;
  101194. if(blocksize_hint == 7) {
  101195. FLAC__uint32 _x;
  101196. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  101197. return false; /* read_callback_ sets the state for us */
  101198. raw_header[raw_header_len++] = (FLAC__byte)_x;
  101199. x = (x << 8) | _x;
  101200. }
  101201. decoder->private_->frame.header.blocksize = x+1;
  101202. }
  101203. if(sample_rate_hint) {
  101204. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101205. return false; /* read_callback_ sets the state for us */
  101206. raw_header[raw_header_len++] = (FLAC__byte)x;
  101207. if(sample_rate_hint != 12) {
  101208. FLAC__uint32 _x;
  101209. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  101210. return false; /* read_callback_ sets the state for us */
  101211. raw_header[raw_header_len++] = (FLAC__byte)_x;
  101212. x = (x << 8) | _x;
  101213. }
  101214. if(sample_rate_hint == 12)
  101215. decoder->private_->frame.header.sample_rate = x*1000;
  101216. else if(sample_rate_hint == 13)
  101217. decoder->private_->frame.header.sample_rate = x;
  101218. else
  101219. decoder->private_->frame.header.sample_rate = x*10;
  101220. }
  101221. /* read the CRC-8 byte */
  101222. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101223. return false; /* read_callback_ sets the state for us */
  101224. crc8 = (FLAC__byte)x;
  101225. if(FLAC__crc8(raw_header, raw_header_len) != crc8) {
  101226. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101227. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101228. return true;
  101229. }
  101230. /* calculate the sample number from the frame number if needed */
  101231. decoder->private_->next_fixed_block_size = 0;
  101232. if(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  101233. x = decoder->private_->frame.header.number.frame_number;
  101234. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  101235. if(decoder->private_->fixed_block_size)
  101236. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->fixed_block_size * (FLAC__uint64)x;
  101237. else if(decoder->private_->has_stream_info) {
  101238. if(decoder->private_->stream_info.data.stream_info.min_blocksize == decoder->private_->stream_info.data.stream_info.max_blocksize) {
  101239. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->stream_info.data.stream_info.min_blocksize * (FLAC__uint64)x;
  101240. decoder->private_->next_fixed_block_size = decoder->private_->stream_info.data.stream_info.max_blocksize;
  101241. }
  101242. else
  101243. is_unparseable = true;
  101244. }
  101245. else if(x == 0) {
  101246. decoder->private_->frame.header.number.sample_number = 0;
  101247. decoder->private_->next_fixed_block_size = decoder->private_->frame.header.blocksize;
  101248. }
  101249. else {
  101250. /* can only get here if the stream has invalid frame numbering and no STREAMINFO, so assume it's not the last (possibly short) frame */
  101251. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->frame.header.blocksize * (FLAC__uint64)x;
  101252. }
  101253. }
  101254. if(is_unparseable) {
  101255. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101256. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101257. return true;
  101258. }
  101259. return true;
  101260. }
  101261. FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  101262. {
  101263. FLAC__uint32 x;
  101264. FLAC__bool wasted_bits;
  101265. unsigned i;
  101266. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8)) /* MAGIC NUMBER */
  101267. return false; /* read_callback_ sets the state for us */
  101268. wasted_bits = (x & 1);
  101269. x &= 0xfe;
  101270. if(wasted_bits) {
  101271. unsigned u;
  101272. if(!FLAC__bitreader_read_unary_unsigned(decoder->private_->input, &u))
  101273. return false; /* read_callback_ sets the state for us */
  101274. decoder->private_->frame.subframes[channel].wasted_bits = u+1;
  101275. bps -= decoder->private_->frame.subframes[channel].wasted_bits;
  101276. }
  101277. else
  101278. decoder->private_->frame.subframes[channel].wasted_bits = 0;
  101279. /*
  101280. * Lots of magic numbers here
  101281. */
  101282. if(x & 0x80) {
  101283. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101284. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101285. return true;
  101286. }
  101287. else if(x == 0) {
  101288. if(!read_subframe_constant_(decoder, channel, bps, do_full_decode))
  101289. return false;
  101290. }
  101291. else if(x == 2) {
  101292. if(!read_subframe_verbatim_(decoder, channel, bps, do_full_decode))
  101293. return false;
  101294. }
  101295. else if(x < 16) {
  101296. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101297. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101298. return true;
  101299. }
  101300. else if(x <= 24) {
  101301. if(!read_subframe_fixed_(decoder, channel, bps, (x>>1)&7, do_full_decode))
  101302. return false;
  101303. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  101304. return true;
  101305. }
  101306. else if(x < 64) {
  101307. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101308. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101309. return true;
  101310. }
  101311. else {
  101312. if(!read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1, do_full_decode))
  101313. return false;
  101314. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  101315. return true;
  101316. }
  101317. if(wasted_bits && do_full_decode) {
  101318. x = decoder->private_->frame.subframes[channel].wasted_bits;
  101319. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  101320. decoder->private_->output[channel][i] <<= x;
  101321. }
  101322. return true;
  101323. }
  101324. FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  101325. {
  101326. FLAC__Subframe_Constant *subframe = &decoder->private_->frame.subframes[channel].data.constant;
  101327. FLAC__int32 x;
  101328. unsigned i;
  101329. FLAC__int32 *output = decoder->private_->output[channel];
  101330. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;
  101331. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  101332. return false; /* read_callback_ sets the state for us */
  101333. subframe->value = x;
  101334. /* decode the subframe */
  101335. if(do_full_decode) {
  101336. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  101337. output[i] = x;
  101338. }
  101339. return true;
  101340. }
  101341. FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  101342. {
  101343. FLAC__Subframe_Fixed *subframe = &decoder->private_->frame.subframes[channel].data.fixed;
  101344. FLAC__int32 i32;
  101345. FLAC__uint32 u32;
  101346. unsigned u;
  101347. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;
  101348. subframe->residual = decoder->private_->residual[channel];
  101349. subframe->order = order;
  101350. /* read warm-up samples */
  101351. for(u = 0; u < order; u++) {
  101352. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  101353. return false; /* read_callback_ sets the state for us */
  101354. subframe->warmup[u] = i32;
  101355. }
  101356. /* read entropy coding method info */
  101357. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  101358. return false; /* read_callback_ sets the state for us */
  101359. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  101360. switch(subframe->entropy_coding_method.type) {
  101361. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101362. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101363. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  101364. return false; /* read_callback_ sets the state for us */
  101365. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  101366. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  101367. break;
  101368. default:
  101369. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101370. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101371. return true;
  101372. }
  101373. /* read residual */
  101374. switch(subframe->entropy_coding_method.type) {
  101375. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101376. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101377. 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))
  101378. return false;
  101379. break;
  101380. default:
  101381. FLAC__ASSERT(0);
  101382. }
  101383. /* decode the subframe */
  101384. if(do_full_decode) {
  101385. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  101386. FLAC__fixed_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, order, decoder->private_->output[channel]+order);
  101387. }
  101388. return true;
  101389. }
  101390. FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  101391. {
  101392. FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc;
  101393. FLAC__int32 i32;
  101394. FLAC__uint32 u32;
  101395. unsigned u;
  101396. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC;
  101397. subframe->residual = decoder->private_->residual[channel];
  101398. subframe->order = order;
  101399. /* read warm-up samples */
  101400. for(u = 0; u < order; u++) {
  101401. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  101402. return false; /* read_callback_ sets the state for us */
  101403. subframe->warmup[u] = i32;
  101404. }
  101405. /* read qlp coeff precision */
  101406. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  101407. return false; /* read_callback_ sets the state for us */
  101408. if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) {
  101409. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101410. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101411. return true;
  101412. }
  101413. subframe->qlp_coeff_precision = u32+1;
  101414. /* read qlp shift */
  101415. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  101416. return false; /* read_callback_ sets the state for us */
  101417. subframe->quantization_level = i32;
  101418. /* read quantized lp coefficiencts */
  101419. for(u = 0; u < order; u++) {
  101420. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, subframe->qlp_coeff_precision))
  101421. return false; /* read_callback_ sets the state for us */
  101422. subframe->qlp_coeff[u] = i32;
  101423. }
  101424. /* read entropy coding method info */
  101425. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  101426. return false; /* read_callback_ sets the state for us */
  101427. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  101428. switch(subframe->entropy_coding_method.type) {
  101429. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101430. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101431. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  101432. return false; /* read_callback_ sets the state for us */
  101433. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  101434. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  101435. break;
  101436. default:
  101437. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101438. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101439. return true;
  101440. }
  101441. /* read residual */
  101442. switch(subframe->entropy_coding_method.type) {
  101443. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101444. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101445. 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))
  101446. return false;
  101447. break;
  101448. default:
  101449. FLAC__ASSERT(0);
  101450. }
  101451. /* decode the subframe */
  101452. if(do_full_decode) {
  101453. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  101454. /*@@@@@@ technically not pessimistic enough, should be more like
  101455. if( (FLAC__uint64)order * ((((FLAC__uint64)1)<<bps)-1) * ((1<<subframe->qlp_coeff_precision)-1) < (((FLAC__uint64)-1) << 32) )
  101456. */
  101457. if(bps + subframe->qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  101458. if(bps <= 16 && subframe->qlp_coeff_precision <= 16) {
  101459. if(order <= 8)
  101460. 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);
  101461. else
  101462. 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);
  101463. }
  101464. else
  101465. 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);
  101466. else
  101467. 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);
  101468. }
  101469. return true;
  101470. }
  101471. FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  101472. {
  101473. FLAC__Subframe_Verbatim *subframe = &decoder->private_->frame.subframes[channel].data.verbatim;
  101474. FLAC__int32 x, *residual = decoder->private_->residual[channel];
  101475. unsigned i;
  101476. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;
  101477. subframe->data = residual;
  101478. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  101479. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  101480. return false; /* read_callback_ sets the state for us */
  101481. residual[i] = x;
  101482. }
  101483. /* decode the subframe */
  101484. if(do_full_decode)
  101485. memcpy(decoder->private_->output[channel], subframe->data, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  101486. return true;
  101487. }
  101488. 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)
  101489. {
  101490. FLAC__uint32 rice_parameter;
  101491. int i;
  101492. unsigned partition, sample, u;
  101493. const unsigned partitions = 1u << partition_order;
  101494. const unsigned partition_samples = partition_order > 0? decoder->private_->frame.header.blocksize >> partition_order : decoder->private_->frame.header.blocksize - predictor_order;
  101495. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  101496. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  101497. /* sanity checks */
  101498. if(partition_order == 0) {
  101499. if(decoder->private_->frame.header.blocksize < predictor_order) {
  101500. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101501. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101502. return true;
  101503. }
  101504. }
  101505. else {
  101506. if(partition_samples < predictor_order) {
  101507. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101508. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101509. return true;
  101510. }
  101511. }
  101512. if(!FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order))) {
  101513. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  101514. return false;
  101515. }
  101516. sample = 0;
  101517. for(partition = 0; partition < partitions; partition++) {
  101518. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, plen))
  101519. return false; /* read_callback_ sets the state for us */
  101520. partitioned_rice_contents->parameters[partition] = rice_parameter;
  101521. if(rice_parameter < pesc) {
  101522. partitioned_rice_contents->raw_bits[partition] = 0;
  101523. u = (partition_order == 0 || partition > 0)? partition_samples : partition_samples - predictor_order;
  101524. if(!decoder->private_->local_bitreader_read_rice_signed_block(decoder->private_->input, (int*) residual + sample, u, rice_parameter))
  101525. return false; /* read_callback_ sets the state for us */
  101526. sample += u;
  101527. }
  101528. else {
  101529. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  101530. return false; /* read_callback_ sets the state for us */
  101531. partitioned_rice_contents->raw_bits[partition] = rice_parameter;
  101532. for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
  101533. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, (FLAC__int32*) &i, rice_parameter))
  101534. return false; /* read_callback_ sets the state for us */
  101535. residual[sample] = i;
  101536. }
  101537. }
  101538. }
  101539. return true;
  101540. }
  101541. FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder)
  101542. {
  101543. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  101544. FLAC__uint32 zero = 0;
  101545. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &zero, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  101546. return false; /* read_callback_ sets the state for us */
  101547. if(zero != 0) {
  101548. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101549. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101550. }
  101551. }
  101552. return true;
  101553. }
  101554. FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data)
  101555. {
  101556. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;
  101557. if(
  101558. #if FLAC__HAS_OGG
  101559. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  101560. !decoder->private_->is_ogg &&
  101561. #endif
  101562. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  101563. ) {
  101564. *bytes = 0;
  101565. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  101566. return false;
  101567. }
  101568. else if(*bytes > 0) {
  101569. /* While seeking, it is possible for our seek to land in the
  101570. * middle of audio data that looks exactly like a frame header
  101571. * from a future version of an encoder. When that happens, our
  101572. * error callback will get an
  101573. * FLAC__STREAM_DECODER_UNPARSEABLE_STREAM and increment its
  101574. * unparseable_frame_count. But there is a remote possibility
  101575. * that it is properly synced at such a "future-codec frame",
  101576. * so to make sure, we wait to see many "unparseable" errors in
  101577. * a row before bailing out.
  101578. */
  101579. if(decoder->private_->is_seeking && decoder->private_->unparseable_frame_count > 20) {
  101580. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101581. return false;
  101582. }
  101583. else {
  101584. const FLAC__StreamDecoderReadStatus status =
  101585. #if FLAC__HAS_OGG
  101586. decoder->private_->is_ogg?
  101587. read_callback_ogg_aspect_(decoder, buffer, bytes) :
  101588. #endif
  101589. decoder->private_->read_callback(decoder, buffer, bytes, decoder->private_->client_data)
  101590. ;
  101591. if(status == FLAC__STREAM_DECODER_READ_STATUS_ABORT) {
  101592. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101593. return false;
  101594. }
  101595. else if(*bytes == 0) {
  101596. if(
  101597. status == FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM ||
  101598. (
  101599. #if FLAC__HAS_OGG
  101600. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  101601. !decoder->private_->is_ogg &&
  101602. #endif
  101603. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  101604. )
  101605. ) {
  101606. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  101607. return false;
  101608. }
  101609. else
  101610. return true;
  101611. }
  101612. else
  101613. return true;
  101614. }
  101615. }
  101616. else {
  101617. /* abort to avoid a deadlock */
  101618. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101619. return false;
  101620. }
  101621. /* [1] @@@ HACK NOTE: The end-of-stream checking has to be hacked around
  101622. * for Ogg FLAC. This is because the ogg decoder aspect can lose sync
  101623. * and at the same time hit the end of the stream (for example, seeking
  101624. * to a point that is after the beginning of the last Ogg page). There
  101625. * is no way to report an Ogg sync loss through the callbacks (see note
  101626. * in read_callback_ogg_aspect_()) so it returns CONTINUE with *bytes==0.
  101627. * So to keep the decoder from stopping at this point we gate the call
  101628. * to the eof_callback and let the Ogg decoder aspect set the
  101629. * end-of-stream state when it is needed.
  101630. */
  101631. }
  101632. #if FLAC__HAS_OGG
  101633. FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes)
  101634. {
  101635. switch(FLAC__ogg_decoder_aspect_read_callback_wrapper(&decoder->protected_->ogg_decoder_aspect, buffer, bytes, read_callback_proxy_, decoder, decoder->private_->client_data)) {
  101636. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK:
  101637. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101638. /* we don't really have a way to handle lost sync via read
  101639. * callback so we'll let it pass and let the underlying
  101640. * FLAC decoder catch the error
  101641. */
  101642. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_LOST_SYNC:
  101643. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101644. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM:
  101645. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  101646. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_NOT_FLAC:
  101647. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_UNSUPPORTED_MAPPING_VERSION:
  101648. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT:
  101649. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ERROR:
  101650. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_MEMORY_ALLOCATION_ERROR:
  101651. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101652. default:
  101653. FLAC__ASSERT(0);
  101654. /* double protection */
  101655. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101656. }
  101657. }
  101658. FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  101659. {
  101660. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder*)void_decoder;
  101661. switch(decoder->private_->read_callback(decoder, buffer, bytes, client_data)) {
  101662. case FLAC__STREAM_DECODER_READ_STATUS_CONTINUE:
  101663. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK;
  101664. case FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM:
  101665. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM;
  101666. case FLAC__STREAM_DECODER_READ_STATUS_ABORT:
  101667. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  101668. default:
  101669. /* double protection: */
  101670. FLAC__ASSERT(0);
  101671. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  101672. }
  101673. }
  101674. #endif
  101675. FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
  101676. {
  101677. if(decoder->private_->is_seeking) {
  101678. FLAC__uint64 this_frame_sample = frame->header.number.sample_number;
  101679. FLAC__uint64 next_frame_sample = this_frame_sample + (FLAC__uint64)frame->header.blocksize;
  101680. FLAC__uint64 target_sample = decoder->private_->target_sample;
  101681. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101682. #if FLAC__HAS_OGG
  101683. decoder->private_->got_a_frame = true;
  101684. #endif
  101685. decoder->private_->last_frame = *frame; /* save the frame */
  101686. if(this_frame_sample <= target_sample && target_sample < next_frame_sample) { /* we hit our target frame */
  101687. unsigned delta = (unsigned)(target_sample - this_frame_sample);
  101688. /* kick out of seek mode */
  101689. decoder->private_->is_seeking = false;
  101690. /* shift out the samples before target_sample */
  101691. if(delta > 0) {
  101692. unsigned channel;
  101693. const FLAC__int32 *newbuffer[FLAC__MAX_CHANNELS];
  101694. for(channel = 0; channel < frame->header.channels; channel++)
  101695. newbuffer[channel] = buffer[channel] + delta;
  101696. decoder->private_->last_frame.header.blocksize -= delta;
  101697. decoder->private_->last_frame.header.number.sample_number += (FLAC__uint64)delta;
  101698. /* write the relevant samples */
  101699. return decoder->private_->write_callback(decoder, &decoder->private_->last_frame, newbuffer, decoder->private_->client_data);
  101700. }
  101701. else {
  101702. /* write the relevant samples */
  101703. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  101704. }
  101705. }
  101706. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  101707. }
  101708. /*
  101709. * If we never got STREAMINFO, turn off MD5 checking to save
  101710. * cycles since we don't have a sum to compare to anyway
  101711. */
  101712. if(!decoder->private_->has_stream_info)
  101713. decoder->private_->do_md5_checking = false;
  101714. if(decoder->private_->do_md5_checking) {
  101715. if(!FLAC__MD5Accumulate(&decoder->private_->md5context, buffer, frame->header.channels, frame->header.blocksize, (frame->header.bits_per_sample+7) / 8))
  101716. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  101717. }
  101718. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  101719. }
  101720. void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status)
  101721. {
  101722. if(!decoder->private_->is_seeking)
  101723. decoder->private_->error_callback(decoder, status, decoder->private_->client_data);
  101724. else if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
  101725. decoder->private_->unparseable_frame_count++;
  101726. }
  101727. FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  101728. {
  101729. FLAC__uint64 first_frame_offset = decoder->private_->first_frame_offset, lower_bound, upper_bound, lower_bound_sample, upper_bound_sample, this_frame_sample;
  101730. FLAC__int64 pos = -1;
  101731. int i;
  101732. unsigned approx_bytes_per_frame;
  101733. FLAC__bool first_seek = true;
  101734. const FLAC__uint64 total_samples = FLAC__stream_decoder_get_total_samples(decoder);
  101735. const unsigned min_blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
  101736. const unsigned max_blocksize = decoder->private_->stream_info.data.stream_info.max_blocksize;
  101737. const unsigned max_framesize = decoder->private_->stream_info.data.stream_info.max_framesize;
  101738. const unsigned min_framesize = decoder->private_->stream_info.data.stream_info.min_framesize;
  101739. /* take these from the current frame in case they've changed mid-stream */
  101740. unsigned channels = FLAC__stream_decoder_get_channels(decoder);
  101741. unsigned bps = FLAC__stream_decoder_get_bits_per_sample(decoder);
  101742. const FLAC__StreamMetadata_SeekTable *seek_table = decoder->private_->has_seek_table? &decoder->private_->seek_table.data.seek_table : 0;
  101743. /* use values from stream info if we didn't decode a frame */
  101744. if(channels == 0)
  101745. channels = decoder->private_->stream_info.data.stream_info.channels;
  101746. if(bps == 0)
  101747. bps = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  101748. /* we are just guessing here */
  101749. if(max_framesize > 0)
  101750. approx_bytes_per_frame = (max_framesize + min_framesize) / 2 + 1;
  101751. /*
  101752. * Check if it's a known fixed-blocksize stream. Note that though
  101753. * the spec doesn't allow zeroes in the STREAMINFO block, we may
  101754. * never get a STREAMINFO block when decoding so the value of
  101755. * min_blocksize might be zero.
  101756. */
  101757. else if(min_blocksize == max_blocksize && min_blocksize > 0) {
  101758. /* note there are no () around 'bps/8' to keep precision up since it's an integer calulation */
  101759. approx_bytes_per_frame = min_blocksize * channels * bps/8 + 64;
  101760. }
  101761. else
  101762. approx_bytes_per_frame = 4096 * channels * bps/8 + 64;
  101763. /*
  101764. * First, we set an upper and lower bound on where in the
  101765. * stream we will search. For now we assume the worst case
  101766. * scenario, which is our best guess at the beginning of
  101767. * the first frame and end of the stream.
  101768. */
  101769. lower_bound = first_frame_offset;
  101770. lower_bound_sample = 0;
  101771. upper_bound = stream_length;
  101772. upper_bound_sample = total_samples > 0 ? total_samples : target_sample /*estimate it*/;
  101773. /*
  101774. * Now we refine the bounds if we have a seektable with
  101775. * suitable points. Note that according to the spec they
  101776. * must be ordered by ascending sample number.
  101777. *
  101778. * Note: to protect against invalid seek tables we will ignore points
  101779. * that have frame_samples==0 or sample_number>=total_samples
  101780. */
  101781. if(seek_table) {
  101782. FLAC__uint64 new_lower_bound = lower_bound;
  101783. FLAC__uint64 new_upper_bound = upper_bound;
  101784. FLAC__uint64 new_lower_bound_sample = lower_bound_sample;
  101785. FLAC__uint64 new_upper_bound_sample = upper_bound_sample;
  101786. /* find the closest seek point <= target_sample, if it exists */
  101787. for(i = (int)seek_table->num_points - 1; i >= 0; i--) {
  101788. if(
  101789. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  101790. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  101791. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  101792. seek_table->points[i].sample_number <= target_sample
  101793. )
  101794. break;
  101795. }
  101796. if(i >= 0) { /* i.e. we found a suitable seek point... */
  101797. new_lower_bound = first_frame_offset + seek_table->points[i].stream_offset;
  101798. new_lower_bound_sample = seek_table->points[i].sample_number;
  101799. }
  101800. /* find the closest seek point > target_sample, if it exists */
  101801. for(i = 0; i < (int)seek_table->num_points; i++) {
  101802. if(
  101803. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  101804. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  101805. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  101806. seek_table->points[i].sample_number > target_sample
  101807. )
  101808. break;
  101809. }
  101810. if(i < (int)seek_table->num_points) { /* i.e. we found a suitable seek point... */
  101811. new_upper_bound = first_frame_offset + seek_table->points[i].stream_offset;
  101812. new_upper_bound_sample = seek_table->points[i].sample_number;
  101813. }
  101814. /* final protection against unsorted seek tables; keep original values if bogus */
  101815. if(new_upper_bound >= new_lower_bound) {
  101816. lower_bound = new_lower_bound;
  101817. upper_bound = new_upper_bound;
  101818. lower_bound_sample = new_lower_bound_sample;
  101819. upper_bound_sample = new_upper_bound_sample;
  101820. }
  101821. }
  101822. FLAC__ASSERT(upper_bound_sample >= lower_bound_sample);
  101823. /* there are 2 insidious ways that the following equality occurs, which
  101824. * we need to fix:
  101825. * 1) total_samples is 0 (unknown) and target_sample is 0
  101826. * 2) total_samples is 0 (unknown) and target_sample happens to be
  101827. * exactly equal to the last seek point in the seek table; this
  101828. * means there is no seek point above it, and upper_bound_samples
  101829. * remains equal to the estimate (of target_samples) we made above
  101830. * in either case it does not hurt to move upper_bound_sample up by 1
  101831. */
  101832. if(upper_bound_sample == lower_bound_sample)
  101833. upper_bound_sample++;
  101834. decoder->private_->target_sample = target_sample;
  101835. while(1) {
  101836. /* check if the bounds are still ok */
  101837. if (lower_bound_sample >= upper_bound_sample || lower_bound > upper_bound) {
  101838. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101839. return false;
  101840. }
  101841. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101842. #if defined _MSC_VER || defined __MINGW32__
  101843. /* with VC++ you have to spoon feed it the casting */
  101844. 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;
  101845. #else
  101846. 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;
  101847. #endif
  101848. #else
  101849. /* a little less accurate: */
  101850. if(upper_bound - lower_bound < 0xffffffff)
  101851. 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;
  101852. else /* @@@ WATCHOUT, ~2TB limit */
  101853. 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;
  101854. #endif
  101855. if(pos >= (FLAC__int64)upper_bound)
  101856. pos = (FLAC__int64)upper_bound - 1;
  101857. if(pos < (FLAC__int64)lower_bound)
  101858. pos = (FLAC__int64)lower_bound;
  101859. if(decoder->private_->seek_callback(decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  101860. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101861. return false;
  101862. }
  101863. if(!FLAC__stream_decoder_flush(decoder)) {
  101864. /* above call sets the state for us */
  101865. return false;
  101866. }
  101867. /* Now we need to get a frame. First we need to reset our
  101868. * unparseable_frame_count; if we get too many unparseable
  101869. * frames in a row, the read callback will return
  101870. * FLAC__STREAM_DECODER_READ_STATUS_ABORT, causing
  101871. * FLAC__stream_decoder_process_single() to return false.
  101872. */
  101873. decoder->private_->unparseable_frame_count = 0;
  101874. if(!FLAC__stream_decoder_process_single(decoder)) {
  101875. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101876. return false;
  101877. }
  101878. /* our write callback will change the state when it gets to the target frame */
  101879. /* 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 */
  101880. #if 0
  101881. /*@@@@@@ used to be the following; not clear if the check for end of stream is needed anymore */
  101882. if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_SEEKING && decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM)
  101883. break;
  101884. #endif
  101885. if(!decoder->private_->is_seeking)
  101886. break;
  101887. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101888. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  101889. if (0 == decoder->private_->samples_decoded || (this_frame_sample + decoder->private_->last_frame.header.blocksize >= upper_bound_sample && !first_seek)) {
  101890. if (pos == (FLAC__int64)lower_bound) {
  101891. /* can't move back any more than the first frame, something is fatally wrong */
  101892. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101893. return false;
  101894. }
  101895. /* our last move backwards wasn't big enough, try again */
  101896. approx_bytes_per_frame = approx_bytes_per_frame? approx_bytes_per_frame * 2 : 16;
  101897. continue;
  101898. }
  101899. /* allow one seek over upper bound, so we can get a correct upper_bound_sample for streams with unknown total_samples */
  101900. first_seek = false;
  101901. /* make sure we are not seeking in corrupted stream */
  101902. if (this_frame_sample < lower_bound_sample) {
  101903. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101904. return false;
  101905. }
  101906. /* we need to narrow the search */
  101907. if(target_sample < this_frame_sample) {
  101908. upper_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  101909. /*@@@@@@ what will decode position be if at end of stream? */
  101910. if(!FLAC__stream_decoder_get_decode_position(decoder, &upper_bound)) {
  101911. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101912. return false;
  101913. }
  101914. approx_bytes_per_frame = (unsigned)(2 * (upper_bound - pos) / 3 + 16);
  101915. }
  101916. else { /* target_sample >= this_frame_sample + this frame's blocksize */
  101917. lower_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  101918. if(!FLAC__stream_decoder_get_decode_position(decoder, &lower_bound)) {
  101919. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101920. return false;
  101921. }
  101922. approx_bytes_per_frame = (unsigned)(2 * (lower_bound - pos) / 3 + 16);
  101923. }
  101924. }
  101925. return true;
  101926. }
  101927. #if FLAC__HAS_OGG
  101928. FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  101929. {
  101930. FLAC__uint64 left_pos = 0, right_pos = stream_length;
  101931. FLAC__uint64 left_sample = 0, right_sample = FLAC__stream_decoder_get_total_samples(decoder);
  101932. FLAC__uint64 this_frame_sample = (FLAC__uint64)0 - 1;
  101933. FLAC__uint64 pos = 0; /* only initialized to avoid compiler warning */
  101934. FLAC__bool did_a_seek;
  101935. unsigned iteration = 0;
  101936. /* In the first iterations, we will calculate the target byte position
  101937. * by the distance from the target sample to left_sample and
  101938. * right_sample (let's call it "proportional search"). After that, we
  101939. * will switch to binary search.
  101940. */
  101941. unsigned BINARY_SEARCH_AFTER_ITERATION = 2;
  101942. /* We will switch to a linear search once our current sample is less
  101943. * than this number of samples ahead of the target sample
  101944. */
  101945. static const FLAC__uint64 LINEAR_SEARCH_WITHIN_SAMPLES = FLAC__MAX_BLOCK_SIZE * 2;
  101946. /* If the total number of samples is unknown, use a large value, and
  101947. * force binary search immediately.
  101948. */
  101949. if(right_sample == 0) {
  101950. right_sample = (FLAC__uint64)(-1);
  101951. BINARY_SEARCH_AFTER_ITERATION = 0;
  101952. }
  101953. decoder->private_->target_sample = target_sample;
  101954. for( ; ; iteration++) {
  101955. if (iteration == 0 || this_frame_sample > target_sample || target_sample - this_frame_sample > LINEAR_SEARCH_WITHIN_SAMPLES) {
  101956. if (iteration >= BINARY_SEARCH_AFTER_ITERATION) {
  101957. pos = (right_pos + left_pos) / 2;
  101958. }
  101959. else {
  101960. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101961. #if defined _MSC_VER || defined __MINGW32__
  101962. /* with MSVC you have to spoon feed it the casting */
  101963. 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));
  101964. #else
  101965. pos = (FLAC__uint64)((FLAC__double)(target_sample - left_sample) / (FLAC__double)(right_sample - left_sample) * (FLAC__double)(right_pos - left_pos));
  101966. #endif
  101967. #else
  101968. /* a little less accurate: */
  101969. if ((target_sample-left_sample <= 0xffffffff) && (right_pos-left_pos <= 0xffffffff))
  101970. pos = (FLAC__int64)(((target_sample-left_sample) * (right_pos-left_pos)) / (right_sample-left_sample));
  101971. else /* @@@ WATCHOUT, ~2TB limit */
  101972. pos = (FLAC__int64)((((target_sample-left_sample)>>8) * ((right_pos-left_pos)>>8)) / ((right_sample-left_sample)>>16));
  101973. #endif
  101974. /* @@@ TODO: might want to limit pos to some distance
  101975. * before EOF, to make sure we land before the last frame,
  101976. * thereby getting a this_frame_sample and so having a better
  101977. * estimate.
  101978. */
  101979. }
  101980. /* physical seek */
  101981. if(decoder->private_->seek_callback((FLAC__StreamDecoder*)decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  101982. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101983. return false;
  101984. }
  101985. if(!FLAC__stream_decoder_flush(decoder)) {
  101986. /* above call sets the state for us */
  101987. return false;
  101988. }
  101989. did_a_seek = true;
  101990. }
  101991. else
  101992. did_a_seek = false;
  101993. decoder->private_->got_a_frame = false;
  101994. if(!FLAC__stream_decoder_process_single(decoder)) {
  101995. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101996. return false;
  101997. }
  101998. if(!decoder->private_->got_a_frame) {
  101999. if(did_a_seek) {
  102000. /* this can happen if we seek to a point after the last frame; we drop
  102001. * to binary search right away in this case to avoid any wasted
  102002. * iterations of proportional search.
  102003. */
  102004. right_pos = pos;
  102005. BINARY_SEARCH_AFTER_ITERATION = 0;
  102006. }
  102007. else {
  102008. /* this can probably only happen if total_samples is unknown and the
  102009. * target_sample is past the end of the stream
  102010. */
  102011. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102012. return false;
  102013. }
  102014. }
  102015. /* our write callback will change the state when it gets to the target frame */
  102016. else if(!decoder->private_->is_seeking) {
  102017. break;
  102018. }
  102019. else {
  102020. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  102021. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  102022. if (did_a_seek) {
  102023. if (this_frame_sample <= target_sample) {
  102024. /* The 'equal' case should not happen, since
  102025. * FLAC__stream_decoder_process_single()
  102026. * should recognize that it has hit the
  102027. * target sample and we would exit through
  102028. * the 'break' above.
  102029. */
  102030. FLAC__ASSERT(this_frame_sample != target_sample);
  102031. left_sample = this_frame_sample;
  102032. /* sanity check to avoid infinite loop */
  102033. if (left_pos == pos) {
  102034. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102035. return false;
  102036. }
  102037. left_pos = pos;
  102038. }
  102039. else if(this_frame_sample > target_sample) {
  102040. right_sample = this_frame_sample;
  102041. /* sanity check to avoid infinite loop */
  102042. if (right_pos == pos) {
  102043. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102044. return false;
  102045. }
  102046. right_pos = pos;
  102047. }
  102048. }
  102049. }
  102050. }
  102051. return true;
  102052. }
  102053. #endif
  102054. FLAC__StreamDecoderReadStatus file_read_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  102055. {
  102056. (void)client_data;
  102057. if(*bytes > 0) {
  102058. *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, decoder->private_->file);
  102059. if(ferror(decoder->private_->file))
  102060. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  102061. else if(*bytes == 0)
  102062. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  102063. else
  102064. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  102065. }
  102066. else
  102067. return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */
  102068. }
  102069. FLAC__StreamDecoderSeekStatus file_seek_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  102070. {
  102071. (void)client_data;
  102072. if(decoder->private_->file == stdin)
  102073. return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  102074. else if(fseeko(decoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  102075. return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  102076. else
  102077. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  102078. }
  102079. FLAC__StreamDecoderTellStatus file_tell_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  102080. {
  102081. off_t pos;
  102082. (void)client_data;
  102083. if(decoder->private_->file == stdin)
  102084. return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  102085. else if((pos = ftello(decoder->private_->file)) < 0)
  102086. return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  102087. else {
  102088. *absolute_byte_offset = (FLAC__uint64)pos;
  102089. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  102090. }
  102091. }
  102092. FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  102093. {
  102094. struct stat filestats;
  102095. (void)client_data;
  102096. if(decoder->private_->file == stdin)
  102097. return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  102098. else if(fstat(fileno(decoder->private_->file), &filestats) != 0)
  102099. return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  102100. else {
  102101. *stream_length = (FLAC__uint64)filestats.st_size;
  102102. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  102103. }
  102104. }
  102105. FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data)
  102106. {
  102107. (void)client_data;
  102108. return feof(decoder->private_->file)? true : false;
  102109. }
  102110. #endif
  102111. /*** End of inlined file: stream_decoder.c ***/
  102112. /*** Start of inlined file: stream_encoder.c ***/
  102113. /*** Start of inlined file: juce_FlacHeader.h ***/
  102114. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  102115. // tasks..
  102116. #define VERSION "1.2.1"
  102117. #define FLAC__NO_DLL 1
  102118. #if JUCE_MSVC
  102119. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  102120. #endif
  102121. #if JUCE_MAC
  102122. #define FLAC__SYS_DARWIN 1
  102123. #endif
  102124. /*** End of inlined file: juce_FlacHeader.h ***/
  102125. #if JUCE_USE_FLAC
  102126. #if HAVE_CONFIG_H
  102127. # include <config.h>
  102128. #endif
  102129. #if defined _MSC_VER || defined __MINGW32__
  102130. #include <io.h> /* for _setmode() */
  102131. #include <fcntl.h> /* for _O_BINARY */
  102132. #endif
  102133. #if defined __CYGWIN__ || defined __EMX__
  102134. #include <io.h> /* for setmode(), O_BINARY */
  102135. #include <fcntl.h> /* for _O_BINARY */
  102136. #endif
  102137. #include <limits.h>
  102138. #include <stdio.h>
  102139. #include <stdlib.h> /* for malloc() */
  102140. #include <string.h> /* for memcpy() */
  102141. #include <sys/types.h> /* for off_t */
  102142. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  102143. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  102144. #define fseeko fseek
  102145. #define ftello ftell
  102146. #endif
  102147. #endif
  102148. /*** Start of inlined file: stream_encoder.h ***/
  102149. #ifndef FLAC__PROTECTED__STREAM_ENCODER_H
  102150. #define FLAC__PROTECTED__STREAM_ENCODER_H
  102151. #if FLAC__HAS_OGG
  102152. #include "private/ogg_encoder_aspect.h"
  102153. #endif
  102154. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102155. #define FLAC__MAX_APODIZATION_FUNCTIONS 32
  102156. typedef enum {
  102157. FLAC__APODIZATION_BARTLETT,
  102158. FLAC__APODIZATION_BARTLETT_HANN,
  102159. FLAC__APODIZATION_BLACKMAN,
  102160. FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE,
  102161. FLAC__APODIZATION_CONNES,
  102162. FLAC__APODIZATION_FLATTOP,
  102163. FLAC__APODIZATION_GAUSS,
  102164. FLAC__APODIZATION_HAMMING,
  102165. FLAC__APODIZATION_HANN,
  102166. FLAC__APODIZATION_KAISER_BESSEL,
  102167. FLAC__APODIZATION_NUTTALL,
  102168. FLAC__APODIZATION_RECTANGLE,
  102169. FLAC__APODIZATION_TRIANGLE,
  102170. FLAC__APODIZATION_TUKEY,
  102171. FLAC__APODIZATION_WELCH
  102172. } FLAC__ApodizationFunction;
  102173. typedef struct {
  102174. FLAC__ApodizationFunction type;
  102175. union {
  102176. struct {
  102177. FLAC__real stddev;
  102178. } gauss;
  102179. struct {
  102180. FLAC__real p;
  102181. } tukey;
  102182. } parameters;
  102183. } FLAC__ApodizationSpecification;
  102184. #endif // #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102185. typedef struct FLAC__StreamEncoderProtected {
  102186. FLAC__StreamEncoderState state;
  102187. FLAC__bool verify;
  102188. FLAC__bool streamable_subset;
  102189. FLAC__bool do_md5;
  102190. FLAC__bool do_mid_side_stereo;
  102191. FLAC__bool loose_mid_side_stereo;
  102192. unsigned channels;
  102193. unsigned bits_per_sample;
  102194. unsigned sample_rate;
  102195. unsigned blocksize;
  102196. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102197. unsigned num_apodizations;
  102198. FLAC__ApodizationSpecification apodizations[FLAC__MAX_APODIZATION_FUNCTIONS];
  102199. #endif
  102200. unsigned max_lpc_order;
  102201. unsigned qlp_coeff_precision;
  102202. FLAC__bool do_qlp_coeff_prec_search;
  102203. FLAC__bool do_exhaustive_model_search;
  102204. FLAC__bool do_escape_coding;
  102205. unsigned min_residual_partition_order;
  102206. unsigned max_residual_partition_order;
  102207. unsigned rice_parameter_search_dist;
  102208. FLAC__uint64 total_samples_estimate;
  102209. FLAC__StreamMetadata **metadata;
  102210. unsigned num_metadata_blocks;
  102211. FLAC__uint64 streaminfo_offset, seektable_offset, audio_offset;
  102212. #if FLAC__HAS_OGG
  102213. FLAC__OggEncoderAspect ogg_encoder_aspect;
  102214. #endif
  102215. } FLAC__StreamEncoderProtected;
  102216. #endif
  102217. /*** End of inlined file: stream_encoder.h ***/
  102218. #if FLAC__HAS_OGG
  102219. #include "include/private/ogg_helper.h"
  102220. #include "include/private/ogg_mapping.h"
  102221. #endif
  102222. /*** Start of inlined file: stream_encoder_framing.h ***/
  102223. #ifndef FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  102224. #define FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  102225. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw);
  102226. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw);
  102227. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102228. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102229. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102230. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102231. #endif
  102232. /*** End of inlined file: stream_encoder_framing.h ***/
  102233. /*** Start of inlined file: window.h ***/
  102234. #ifndef FLAC__PRIVATE__WINDOW_H
  102235. #define FLAC__PRIVATE__WINDOW_H
  102236. #ifdef HAVE_CONFIG_H
  102237. #include <config.h>
  102238. #endif
  102239. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102240. /*
  102241. * FLAC__window_*()
  102242. * --------------------------------------------------------------------
  102243. * Calculates window coefficients according to different apodization
  102244. * functions.
  102245. *
  102246. * OUT window[0,L-1]
  102247. * IN L (number of points in window)
  102248. */
  102249. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L);
  102250. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L);
  102251. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L);
  102252. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L);
  102253. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L);
  102254. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L);
  102255. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev); /* 0.0 < stddev <= 0.5 */
  102256. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L);
  102257. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L);
  102258. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L);
  102259. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L);
  102260. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L);
  102261. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L);
  102262. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p);
  102263. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L);
  102264. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  102265. #endif
  102266. /*** End of inlined file: window.h ***/
  102267. #ifndef FLaC__INLINE
  102268. #define FLaC__INLINE
  102269. #endif
  102270. #ifdef min
  102271. #undef min
  102272. #endif
  102273. #define min(x,y) ((x)<(y)?(x):(y))
  102274. #ifdef max
  102275. #undef max
  102276. #endif
  102277. #define max(x,y) ((x)>(y)?(x):(y))
  102278. /* Exact Rice codeword length calculation is off by default. The simple
  102279. * (and fast) estimation (of how many bits a residual value will be
  102280. * encoded with) in this encoder is very good, almost always yielding
  102281. * compression within 0.1% of exact calculation.
  102282. */
  102283. #undef EXACT_RICE_BITS_CALCULATION
  102284. /* Rice parameter searching is off by default. The simple (and fast)
  102285. * parameter estimation in this encoder is very good, almost always
  102286. * yielding compression within 0.1% of the optimal parameters.
  102287. */
  102288. #undef ENABLE_RICE_PARAMETER_SEARCH
  102289. typedef struct {
  102290. FLAC__int32 *data[FLAC__MAX_CHANNELS];
  102291. unsigned size; /* of each data[] in samples */
  102292. unsigned tail;
  102293. } verify_input_fifo;
  102294. typedef struct {
  102295. const FLAC__byte *data;
  102296. unsigned capacity;
  102297. unsigned bytes;
  102298. } verify_output;
  102299. typedef enum {
  102300. ENCODER_IN_MAGIC = 0,
  102301. ENCODER_IN_METADATA = 1,
  102302. ENCODER_IN_AUDIO = 2
  102303. } EncoderStateHint;
  102304. static struct CompressionLevels {
  102305. FLAC__bool do_mid_side_stereo;
  102306. FLAC__bool loose_mid_side_stereo;
  102307. unsigned max_lpc_order;
  102308. unsigned qlp_coeff_precision;
  102309. FLAC__bool do_qlp_coeff_prec_search;
  102310. FLAC__bool do_escape_coding;
  102311. FLAC__bool do_exhaustive_model_search;
  102312. unsigned min_residual_partition_order;
  102313. unsigned max_residual_partition_order;
  102314. unsigned rice_parameter_search_dist;
  102315. } compression_levels_[] = {
  102316. { false, false, 0, 0, false, false, false, 0, 3, 0 },
  102317. { true , true , 0, 0, false, false, false, 0, 3, 0 },
  102318. { true , false, 0, 0, false, false, false, 0, 3, 0 },
  102319. { false, false, 6, 0, false, false, false, 0, 4, 0 },
  102320. { true , true , 8, 0, false, false, false, 0, 4, 0 },
  102321. { true , false, 8, 0, false, false, false, 0, 5, 0 },
  102322. { true , false, 8, 0, false, false, false, 0, 6, 0 },
  102323. { true , false, 8, 0, false, false, true , 0, 6, 0 },
  102324. { true , false, 12, 0, false, false, true , 0, 6, 0 }
  102325. };
  102326. /***********************************************************************
  102327. *
  102328. * Private class method prototypes
  102329. *
  102330. ***********************************************************************/
  102331. static void set_defaults_enc(FLAC__StreamEncoder *encoder);
  102332. static void free_(FLAC__StreamEncoder *encoder);
  102333. static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
  102334. static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
  102335. static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
  102336. static void update_metadata_(const FLAC__StreamEncoder *encoder);
  102337. #if FLAC__HAS_OGG
  102338. static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
  102339. #endif
  102340. static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
  102341. static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
  102342. static FLAC__bool process_subframe_(
  102343. FLAC__StreamEncoder *encoder,
  102344. unsigned min_partition_order,
  102345. unsigned max_partition_order,
  102346. const FLAC__FrameHeader *frame_header,
  102347. unsigned subframe_bps,
  102348. const FLAC__int32 integer_signal[],
  102349. FLAC__Subframe *subframe[2],
  102350. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  102351. FLAC__int32 *residual[2],
  102352. unsigned *best_subframe,
  102353. unsigned *best_bits
  102354. );
  102355. static FLAC__bool add_subframe_(
  102356. FLAC__StreamEncoder *encoder,
  102357. unsigned blocksize,
  102358. unsigned subframe_bps,
  102359. const FLAC__Subframe *subframe,
  102360. FLAC__BitWriter *frame
  102361. );
  102362. static unsigned evaluate_constant_subframe_(
  102363. FLAC__StreamEncoder *encoder,
  102364. const FLAC__int32 signal,
  102365. unsigned blocksize,
  102366. unsigned subframe_bps,
  102367. FLAC__Subframe *subframe
  102368. );
  102369. static unsigned evaluate_fixed_subframe_(
  102370. FLAC__StreamEncoder *encoder,
  102371. const FLAC__int32 signal[],
  102372. FLAC__int32 residual[],
  102373. FLAC__uint64 abs_residual_partition_sums[],
  102374. unsigned raw_bits_per_partition[],
  102375. unsigned blocksize,
  102376. unsigned subframe_bps,
  102377. unsigned order,
  102378. unsigned rice_parameter,
  102379. unsigned rice_parameter_limit,
  102380. unsigned min_partition_order,
  102381. unsigned max_partition_order,
  102382. FLAC__bool do_escape_coding,
  102383. unsigned rice_parameter_search_dist,
  102384. FLAC__Subframe *subframe,
  102385. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  102386. );
  102387. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102388. static unsigned evaluate_lpc_subframe_(
  102389. FLAC__StreamEncoder *encoder,
  102390. const FLAC__int32 signal[],
  102391. FLAC__int32 residual[],
  102392. FLAC__uint64 abs_residual_partition_sums[],
  102393. unsigned raw_bits_per_partition[],
  102394. const FLAC__real lp_coeff[],
  102395. unsigned blocksize,
  102396. unsigned subframe_bps,
  102397. unsigned order,
  102398. unsigned qlp_coeff_precision,
  102399. unsigned rice_parameter,
  102400. unsigned rice_parameter_limit,
  102401. unsigned min_partition_order,
  102402. unsigned max_partition_order,
  102403. FLAC__bool do_escape_coding,
  102404. unsigned rice_parameter_search_dist,
  102405. FLAC__Subframe *subframe,
  102406. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  102407. );
  102408. #endif
  102409. static unsigned evaluate_verbatim_subframe_(
  102410. FLAC__StreamEncoder *encoder,
  102411. const FLAC__int32 signal[],
  102412. unsigned blocksize,
  102413. unsigned subframe_bps,
  102414. FLAC__Subframe *subframe
  102415. );
  102416. static unsigned find_best_partition_order_(
  102417. struct FLAC__StreamEncoderPrivate *private_,
  102418. const FLAC__int32 residual[],
  102419. FLAC__uint64 abs_residual_partition_sums[],
  102420. unsigned raw_bits_per_partition[],
  102421. unsigned residual_samples,
  102422. unsigned predictor_order,
  102423. unsigned rice_parameter,
  102424. unsigned rice_parameter_limit,
  102425. unsigned min_partition_order,
  102426. unsigned max_partition_order,
  102427. unsigned bps,
  102428. FLAC__bool do_escape_coding,
  102429. unsigned rice_parameter_search_dist,
  102430. FLAC__EntropyCodingMethod *best_ecm
  102431. );
  102432. static void precompute_partition_info_sums_(
  102433. const FLAC__int32 residual[],
  102434. FLAC__uint64 abs_residual_partition_sums[],
  102435. unsigned residual_samples,
  102436. unsigned predictor_order,
  102437. unsigned min_partition_order,
  102438. unsigned max_partition_order,
  102439. unsigned bps
  102440. );
  102441. static void precompute_partition_info_escapes_(
  102442. const FLAC__int32 residual[],
  102443. unsigned raw_bits_per_partition[],
  102444. unsigned residual_samples,
  102445. unsigned predictor_order,
  102446. unsigned min_partition_order,
  102447. unsigned max_partition_order
  102448. );
  102449. static FLAC__bool set_partitioned_rice_(
  102450. #ifdef EXACT_RICE_BITS_CALCULATION
  102451. const FLAC__int32 residual[],
  102452. #endif
  102453. const FLAC__uint64 abs_residual_partition_sums[],
  102454. const unsigned raw_bits_per_partition[],
  102455. const unsigned residual_samples,
  102456. const unsigned predictor_order,
  102457. const unsigned suggested_rice_parameter,
  102458. const unsigned rice_parameter_limit,
  102459. const unsigned rice_parameter_search_dist,
  102460. const unsigned partition_order,
  102461. const FLAC__bool search_for_escapes,
  102462. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  102463. unsigned *bits
  102464. );
  102465. static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
  102466. /* verify-related routines: */
  102467. static void append_to_verify_fifo_(
  102468. verify_input_fifo *fifo,
  102469. const FLAC__int32 * const input[],
  102470. unsigned input_offset,
  102471. unsigned channels,
  102472. unsigned wide_samples
  102473. );
  102474. static void append_to_verify_fifo_interleaved_(
  102475. verify_input_fifo *fifo,
  102476. const FLAC__int32 input[],
  102477. unsigned input_offset,
  102478. unsigned channels,
  102479. unsigned wide_samples
  102480. );
  102481. static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  102482. static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  102483. static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  102484. static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  102485. static FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  102486. static FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  102487. static FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  102488. 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);
  102489. static FILE *get_binary_stdout_(void);
  102490. /***********************************************************************
  102491. *
  102492. * Private class data
  102493. *
  102494. ***********************************************************************/
  102495. typedef struct FLAC__StreamEncoderPrivate {
  102496. unsigned input_capacity; /* current size (in samples) of the signal and residual buffers */
  102497. FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS]; /* the integer version of the input signal */
  102498. FLAC__int32 *integer_signal_mid_side[2]; /* the integer version of the mid-side input signal (stereo only) */
  102499. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102500. FLAC__real *real_signal[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) the floating-point version of the input signal */
  102501. FLAC__real *real_signal_mid_side[2]; /* (@@@ currently unused) the floating-point version of the mid-side input signal (stereo only) */
  102502. FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
  102503. FLAC__real *windowed_signal; /* the integer_signal[] * current window[] */
  102504. #endif
  102505. unsigned subframe_bps[FLAC__MAX_CHANNELS]; /* the effective bits per sample of the input signal (stream bps - wasted bits) */
  102506. unsigned subframe_bps_mid_side[2]; /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
  102507. FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
  102508. FLAC__int32 *residual_workspace_mid_side[2][2];
  102509. FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
  102510. FLAC__Subframe subframe_workspace_mid_side[2][2];
  102511. FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
  102512. FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
  102513. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
  102514. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
  102515. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
  102516. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
  102517. unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index (0 or 1) into 2nd dimension of the above workspaces */
  102518. unsigned best_subframe_mid_side[2];
  102519. unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */
  102520. unsigned best_subframe_bits_mid_side[2];
  102521. FLAC__uint64 *abs_residual_partition_sums; /* workspace where the sum of abs(candidate residual) for each partition is stored */
  102522. unsigned *raw_bits_per_partition; /* workspace where the sum of silog2(candidate residual) for each partition is stored */
  102523. FLAC__BitWriter *frame; /* the current frame being worked on */
  102524. unsigned loose_mid_side_stereo_frames; /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
  102525. unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */
  102526. FLAC__ChannelAssignment last_channel_assignment;
  102527. FLAC__StreamMetadata streaminfo; /* scratchpad for STREAMINFO as it is built */
  102528. FLAC__StreamMetadata_SeekTable *seek_table; /* pointer into encoder->protected_->metadata_ where the seek table is */
  102529. unsigned current_sample_number;
  102530. unsigned current_frame_number;
  102531. FLAC__MD5Context md5context;
  102532. FLAC__CPUInfo cpuinfo;
  102533. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102534. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  102535. #else
  102536. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  102537. #endif
  102538. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102539. void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  102540. 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[]);
  102541. 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[]);
  102542. 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[]);
  102543. #endif
  102544. FLAC__bool use_wide_by_block; /* use slow 64-bit versions of some functions because of the block size */
  102545. FLAC__bool use_wide_by_partition; /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
  102546. FLAC__bool use_wide_by_order; /* use slow 64-bit versions of some functions because of the lpc order */
  102547. FLAC__bool disable_constant_subframes;
  102548. FLAC__bool disable_fixed_subframes;
  102549. FLAC__bool disable_verbatim_subframes;
  102550. #if FLAC__HAS_OGG
  102551. FLAC__bool is_ogg;
  102552. #endif
  102553. FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
  102554. FLAC__StreamEncoderSeekCallback seek_callback;
  102555. FLAC__StreamEncoderTellCallback tell_callback;
  102556. FLAC__StreamEncoderWriteCallback write_callback;
  102557. FLAC__StreamEncoderMetadataCallback metadata_callback;
  102558. FLAC__StreamEncoderProgressCallback progress_callback;
  102559. void *client_data;
  102560. unsigned first_seekpoint_to_check;
  102561. FILE *file; /* only used when encoding to a file */
  102562. FLAC__uint64 bytes_written;
  102563. FLAC__uint64 samples_written;
  102564. unsigned frames_written;
  102565. unsigned total_frames_estimate;
  102566. /* unaligned (original) pointers to allocated data */
  102567. FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
  102568. FLAC__int32 *integer_signal_mid_side_unaligned[2];
  102569. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102570. FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) */
  102571. FLAC__real *real_signal_mid_side_unaligned[2]; /* (@@@ currently unused) */
  102572. FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
  102573. FLAC__real *windowed_signal_unaligned;
  102574. #endif
  102575. FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
  102576. FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
  102577. FLAC__uint64 *abs_residual_partition_sums_unaligned;
  102578. unsigned *raw_bits_per_partition_unaligned;
  102579. /*
  102580. * These fields have been moved here from private function local
  102581. * declarations merely to save stack space during encoding.
  102582. */
  102583. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102584. FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
  102585. #endif
  102586. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
  102587. /*
  102588. * The data for the verify section
  102589. */
  102590. struct {
  102591. FLAC__StreamDecoder *decoder;
  102592. EncoderStateHint state_hint;
  102593. FLAC__bool needs_magic_hack;
  102594. verify_input_fifo input_fifo;
  102595. verify_output output;
  102596. struct {
  102597. FLAC__uint64 absolute_sample;
  102598. unsigned frame_number;
  102599. unsigned channel;
  102600. unsigned sample;
  102601. FLAC__int32 expected;
  102602. FLAC__int32 got;
  102603. } error_stats;
  102604. } verify;
  102605. FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
  102606. } FLAC__StreamEncoderPrivate;
  102607. /***********************************************************************
  102608. *
  102609. * Public static class data
  102610. *
  102611. ***********************************************************************/
  102612. FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
  102613. "FLAC__STREAM_ENCODER_OK",
  102614. "FLAC__STREAM_ENCODER_UNINITIALIZED",
  102615. "FLAC__STREAM_ENCODER_OGG_ERROR",
  102616. "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
  102617. "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
  102618. "FLAC__STREAM_ENCODER_CLIENT_ERROR",
  102619. "FLAC__STREAM_ENCODER_IO_ERROR",
  102620. "FLAC__STREAM_ENCODER_FRAMING_ERROR",
  102621. "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
  102622. };
  102623. FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
  102624. "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
  102625. "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
  102626. "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  102627. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
  102628. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
  102629. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
  102630. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
  102631. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
  102632. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
  102633. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
  102634. "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
  102635. "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
  102636. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
  102637. "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
  102638. };
  102639. FLAC_API const char * const FLAC__treamEncoderReadStatusString[] = {
  102640. "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
  102641. "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
  102642. "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
  102643. "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
  102644. };
  102645. FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
  102646. "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
  102647. "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
  102648. };
  102649. FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
  102650. "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
  102651. "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
  102652. "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
  102653. };
  102654. FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
  102655. "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
  102656. "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
  102657. "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
  102658. };
  102659. /* Number of samples that will be overread to watch for end of stream. By
  102660. * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
  102661. * always try to read blocksize+1 samples before encoding a block, so that
  102662. * even if the stream has a total sample count that is an integral multiple
  102663. * of the blocksize, we will still notice when we are encoding the last
  102664. * block. This is needed, for example, to correctly set the end-of-stream
  102665. * marker in Ogg FLAC.
  102666. *
  102667. * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
  102668. * not really any reason to change it.
  102669. */
  102670. static const unsigned OVERREAD_ = 1;
  102671. /***********************************************************************
  102672. *
  102673. * Class constructor/destructor
  102674. *
  102675. */
  102676. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
  102677. {
  102678. FLAC__StreamEncoder *encoder;
  102679. unsigned i;
  102680. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  102681. encoder = (FLAC__StreamEncoder*)calloc(1, sizeof(FLAC__StreamEncoder));
  102682. if(encoder == 0) {
  102683. return 0;
  102684. }
  102685. encoder->protected_ = (FLAC__StreamEncoderProtected*)calloc(1, sizeof(FLAC__StreamEncoderProtected));
  102686. if(encoder->protected_ == 0) {
  102687. free(encoder);
  102688. return 0;
  102689. }
  102690. encoder->private_ = (FLAC__StreamEncoderPrivate*)calloc(1, sizeof(FLAC__StreamEncoderPrivate));
  102691. if(encoder->private_ == 0) {
  102692. free(encoder->protected_);
  102693. free(encoder);
  102694. return 0;
  102695. }
  102696. encoder->private_->frame = FLAC__bitwriter_new();
  102697. if(encoder->private_->frame == 0) {
  102698. free(encoder->private_);
  102699. free(encoder->protected_);
  102700. free(encoder);
  102701. return 0;
  102702. }
  102703. encoder->private_->file = 0;
  102704. set_defaults_enc(encoder);
  102705. encoder->private_->is_being_deleted = false;
  102706. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102707. encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
  102708. encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
  102709. }
  102710. for(i = 0; i < 2; i++) {
  102711. encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
  102712. encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
  102713. }
  102714. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102715. encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
  102716. encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
  102717. }
  102718. for(i = 0; i < 2; i++) {
  102719. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
  102720. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
  102721. }
  102722. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102723. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  102724. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  102725. }
  102726. for(i = 0; i < 2; i++) {
  102727. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  102728. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  102729. }
  102730. for(i = 0; i < 2; i++)
  102731. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
  102732. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  102733. return encoder;
  102734. }
  102735. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
  102736. {
  102737. unsigned i;
  102738. FLAC__ASSERT(0 != encoder);
  102739. FLAC__ASSERT(0 != encoder->protected_);
  102740. FLAC__ASSERT(0 != encoder->private_);
  102741. FLAC__ASSERT(0 != encoder->private_->frame);
  102742. encoder->private_->is_being_deleted = true;
  102743. (void)FLAC__stream_encoder_finish(encoder);
  102744. if(0 != encoder->private_->verify.decoder)
  102745. FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
  102746. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102747. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  102748. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  102749. }
  102750. for(i = 0; i < 2; i++) {
  102751. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  102752. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  102753. }
  102754. for(i = 0; i < 2; i++)
  102755. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
  102756. FLAC__bitwriter_delete(encoder->private_->frame);
  102757. free(encoder->private_);
  102758. free(encoder->protected_);
  102759. free(encoder);
  102760. }
  102761. /***********************************************************************
  102762. *
  102763. * Public class methods
  102764. *
  102765. ***********************************************************************/
  102766. static FLAC__StreamEncoderInitStatus init_stream_internal_enc(
  102767. FLAC__StreamEncoder *encoder,
  102768. FLAC__StreamEncoderReadCallback read_callback,
  102769. FLAC__StreamEncoderWriteCallback write_callback,
  102770. FLAC__StreamEncoderSeekCallback seek_callback,
  102771. FLAC__StreamEncoderTellCallback tell_callback,
  102772. FLAC__StreamEncoderMetadataCallback metadata_callback,
  102773. void *client_data,
  102774. FLAC__bool is_ogg
  102775. )
  102776. {
  102777. unsigned i;
  102778. FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
  102779. FLAC__ASSERT(0 != encoder);
  102780. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102781. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  102782. #if !FLAC__HAS_OGG
  102783. if(is_ogg)
  102784. return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  102785. #endif
  102786. if(0 == write_callback || (seek_callback && 0 == tell_callback))
  102787. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
  102788. if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
  102789. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
  102790. if(encoder->protected_->channels != 2) {
  102791. encoder->protected_->do_mid_side_stereo = false;
  102792. encoder->protected_->loose_mid_side_stereo = false;
  102793. }
  102794. else if(!encoder->protected_->do_mid_side_stereo)
  102795. encoder->protected_->loose_mid_side_stereo = false;
  102796. if(encoder->protected_->bits_per_sample >= 32)
  102797. encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
  102798. if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
  102799. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
  102800. if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
  102801. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
  102802. if(encoder->protected_->blocksize == 0) {
  102803. if(encoder->protected_->max_lpc_order == 0)
  102804. encoder->protected_->blocksize = 1152;
  102805. else
  102806. encoder->protected_->blocksize = 4096;
  102807. }
  102808. if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
  102809. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
  102810. if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
  102811. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
  102812. if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
  102813. return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
  102814. if(encoder->protected_->qlp_coeff_precision == 0) {
  102815. if(encoder->protected_->bits_per_sample < 16) {
  102816. /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
  102817. /* @@@ until then we'll make a guess */
  102818. encoder->protected_->qlp_coeff_precision = max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
  102819. }
  102820. else if(encoder->protected_->bits_per_sample == 16) {
  102821. if(encoder->protected_->blocksize <= 192)
  102822. encoder->protected_->qlp_coeff_precision = 7;
  102823. else if(encoder->protected_->blocksize <= 384)
  102824. encoder->protected_->qlp_coeff_precision = 8;
  102825. else if(encoder->protected_->blocksize <= 576)
  102826. encoder->protected_->qlp_coeff_precision = 9;
  102827. else if(encoder->protected_->blocksize <= 1152)
  102828. encoder->protected_->qlp_coeff_precision = 10;
  102829. else if(encoder->protected_->blocksize <= 2304)
  102830. encoder->protected_->qlp_coeff_precision = 11;
  102831. else if(encoder->protected_->blocksize <= 4608)
  102832. encoder->protected_->qlp_coeff_precision = 12;
  102833. else
  102834. encoder->protected_->qlp_coeff_precision = 13;
  102835. }
  102836. else {
  102837. if(encoder->protected_->blocksize <= 384)
  102838. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
  102839. else if(encoder->protected_->blocksize <= 1152)
  102840. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
  102841. else
  102842. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  102843. }
  102844. FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
  102845. }
  102846. else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
  102847. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
  102848. if(encoder->protected_->streamable_subset) {
  102849. if(
  102850. encoder->protected_->blocksize != 192 &&
  102851. encoder->protected_->blocksize != 576 &&
  102852. encoder->protected_->blocksize != 1152 &&
  102853. encoder->protected_->blocksize != 2304 &&
  102854. encoder->protected_->blocksize != 4608 &&
  102855. encoder->protected_->blocksize != 256 &&
  102856. encoder->protected_->blocksize != 512 &&
  102857. encoder->protected_->blocksize != 1024 &&
  102858. encoder->protected_->blocksize != 2048 &&
  102859. encoder->protected_->blocksize != 4096 &&
  102860. encoder->protected_->blocksize != 8192 &&
  102861. encoder->protected_->blocksize != 16384
  102862. )
  102863. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102864. if(!FLAC__format_sample_rate_is_subset(encoder->protected_->sample_rate))
  102865. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102866. if(
  102867. encoder->protected_->bits_per_sample != 8 &&
  102868. encoder->protected_->bits_per_sample != 12 &&
  102869. encoder->protected_->bits_per_sample != 16 &&
  102870. encoder->protected_->bits_per_sample != 20 &&
  102871. encoder->protected_->bits_per_sample != 24
  102872. )
  102873. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102874. if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
  102875. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102876. if(
  102877. encoder->protected_->sample_rate <= 48000 &&
  102878. (
  102879. encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
  102880. encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
  102881. )
  102882. ) {
  102883. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102884. }
  102885. }
  102886. if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  102887. encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
  102888. if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
  102889. encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
  102890. #if FLAC__HAS_OGG
  102891. /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
  102892. if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
  102893. unsigned i;
  102894. for(i = 1; i < encoder->protected_->num_metadata_blocks; i++) {
  102895. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  102896. FLAC__StreamMetadata *vc = encoder->protected_->metadata[i];
  102897. for( ; i > 0; i--)
  102898. encoder->protected_->metadata[i] = encoder->protected_->metadata[i-1];
  102899. encoder->protected_->metadata[0] = vc;
  102900. break;
  102901. }
  102902. }
  102903. }
  102904. #endif
  102905. /* keep track of any SEEKTABLE block */
  102906. if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
  102907. unsigned i;
  102908. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  102909. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  102910. encoder->private_->seek_table = &encoder->protected_->metadata[i]->data.seek_table;
  102911. break; /* take only the first one */
  102912. }
  102913. }
  102914. }
  102915. /* validate metadata */
  102916. if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
  102917. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102918. metadata_has_seektable = false;
  102919. metadata_has_vorbis_comment = false;
  102920. metadata_picture_has_type1 = false;
  102921. metadata_picture_has_type2 = false;
  102922. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  102923. const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
  102924. if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
  102925. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102926. else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  102927. if(metadata_has_seektable) /* only one is allowed */
  102928. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102929. metadata_has_seektable = true;
  102930. if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
  102931. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102932. }
  102933. else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  102934. if(metadata_has_vorbis_comment) /* only one is allowed */
  102935. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102936. metadata_has_vorbis_comment = true;
  102937. }
  102938. else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
  102939. if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
  102940. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102941. }
  102942. else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
  102943. if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
  102944. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102945. if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
  102946. if(metadata_picture_has_type1) /* there should only be 1 per stream */
  102947. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102948. metadata_picture_has_type1 = true;
  102949. /* standard icon must be 32x32 pixel PNG */
  102950. if(
  102951. m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
  102952. (
  102953. (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
  102954. m->data.picture.width != 32 ||
  102955. m->data.picture.height != 32
  102956. )
  102957. )
  102958. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102959. }
  102960. else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
  102961. if(metadata_picture_has_type2) /* there should only be 1 per stream */
  102962. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102963. metadata_picture_has_type2 = true;
  102964. }
  102965. }
  102966. }
  102967. encoder->private_->input_capacity = 0;
  102968. for(i = 0; i < encoder->protected_->channels; i++) {
  102969. encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
  102970. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102971. encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
  102972. #endif
  102973. }
  102974. for(i = 0; i < 2; i++) {
  102975. encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
  102976. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102977. encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
  102978. #endif
  102979. }
  102980. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102981. for(i = 0; i < encoder->protected_->num_apodizations; i++)
  102982. encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
  102983. encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
  102984. #endif
  102985. for(i = 0; i < encoder->protected_->channels; i++) {
  102986. encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
  102987. encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
  102988. encoder->private_->best_subframe[i] = 0;
  102989. }
  102990. for(i = 0; i < 2; i++) {
  102991. encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
  102992. encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
  102993. encoder->private_->best_subframe_mid_side[i] = 0;
  102994. }
  102995. encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
  102996. encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
  102997. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102998. encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
  102999. #else
  103000. /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
  103001. /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply&divide by hand */
  103002. FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
  103003. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
  103004. FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
  103005. FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
  103006. 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);
  103007. #endif
  103008. if(encoder->private_->loose_mid_side_stereo_frames == 0)
  103009. encoder->private_->loose_mid_side_stereo_frames = 1;
  103010. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  103011. encoder->private_->current_sample_number = 0;
  103012. encoder->private_->current_frame_number = 0;
  103013. encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
  103014. 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? */
  103015. encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
  103016. /*
  103017. * get the CPU info and set the function pointers
  103018. */
  103019. FLAC__cpu_info(&encoder->private_->cpuinfo);
  103020. /* first default to the non-asm routines */
  103021. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103022. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
  103023. #endif
  103024. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
  103025. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103026. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
  103027. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
  103028. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
  103029. #endif
  103030. /* now override with asm where appropriate */
  103031. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103032. # ifndef FLAC__NO_ASM
  103033. if(encoder->private_->cpuinfo.use_asm) {
  103034. # ifdef FLAC__CPU_IA32
  103035. FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  103036. # ifdef FLAC__HAS_NASM
  103037. if(encoder->private_->cpuinfo.data.ia32.sse) {
  103038. if(encoder->protected_->max_lpc_order < 4)
  103039. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
  103040. else if(encoder->protected_->max_lpc_order < 8)
  103041. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
  103042. else if(encoder->protected_->max_lpc_order < 12)
  103043. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
  103044. else
  103045. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  103046. }
  103047. else if(encoder->private_->cpuinfo.data.ia32._3dnow)
  103048. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
  103049. else
  103050. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  103051. if(encoder->private_->cpuinfo.data.ia32.mmx) {
  103052. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  103053. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
  103054. }
  103055. else {
  103056. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  103057. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  103058. }
  103059. if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
  103060. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
  103061. # endif /* FLAC__HAS_NASM */
  103062. # endif /* FLAC__CPU_IA32 */
  103063. }
  103064. # endif /* !FLAC__NO_ASM */
  103065. #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
  103066. /* finally override based on wide-ness if necessary */
  103067. if(encoder->private_->use_wide_by_block) {
  103068. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
  103069. }
  103070. /* set state to OK; from here on, errors are fatal and we'll override the state then */
  103071. encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
  103072. #if FLAC__HAS_OGG
  103073. encoder->private_->is_ogg = is_ogg;
  103074. if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
  103075. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  103076. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103077. }
  103078. #endif
  103079. encoder->private_->read_callback = read_callback;
  103080. encoder->private_->write_callback = write_callback;
  103081. encoder->private_->seek_callback = seek_callback;
  103082. encoder->private_->tell_callback = tell_callback;
  103083. encoder->private_->metadata_callback = metadata_callback;
  103084. encoder->private_->client_data = client_data;
  103085. if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
  103086. /* the above function sets the state for us in case of an error */
  103087. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103088. }
  103089. if(!FLAC__bitwriter_init(encoder->private_->frame)) {
  103090. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  103091. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103092. }
  103093. /*
  103094. * Set up the verify stuff if necessary
  103095. */
  103096. if(encoder->protected_->verify) {
  103097. /*
  103098. * First, set up the fifo which will hold the
  103099. * original signal to compare against
  103100. */
  103101. encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
  103102. for(i = 0; i < encoder->protected_->channels; i++) {
  103103. 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))) {
  103104. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  103105. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103106. }
  103107. }
  103108. encoder->private_->verify.input_fifo.tail = 0;
  103109. /*
  103110. * Now set up a stream decoder for verification
  103111. */
  103112. encoder->private_->verify.decoder = FLAC__stream_decoder_new();
  103113. if(0 == encoder->private_->verify.decoder) {
  103114. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  103115. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103116. }
  103117. 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) {
  103118. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  103119. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103120. }
  103121. }
  103122. encoder->private_->verify.error_stats.absolute_sample = 0;
  103123. encoder->private_->verify.error_stats.frame_number = 0;
  103124. encoder->private_->verify.error_stats.channel = 0;
  103125. encoder->private_->verify.error_stats.sample = 0;
  103126. encoder->private_->verify.error_stats.expected = 0;
  103127. encoder->private_->verify.error_stats.got = 0;
  103128. /*
  103129. * These must be done before we write any metadata, because that
  103130. * calls the write_callback, which uses these values.
  103131. */
  103132. encoder->private_->first_seekpoint_to_check = 0;
  103133. encoder->private_->samples_written = 0;
  103134. encoder->protected_->streaminfo_offset = 0;
  103135. encoder->protected_->seektable_offset = 0;
  103136. encoder->protected_->audio_offset = 0;
  103137. /*
  103138. * write the stream header
  103139. */
  103140. if(encoder->protected_->verify)
  103141. encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
  103142. if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
  103143. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103144. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103145. }
  103146. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103147. /* the above function sets the state for us in case of an error */
  103148. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103149. }
  103150. /*
  103151. * write the STREAMINFO metadata block
  103152. */
  103153. if(encoder->protected_->verify)
  103154. encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
  103155. encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
  103156. encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
  103157. encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
  103158. encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
  103159. encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
  103160. encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
  103161. encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
  103162. encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
  103163. encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
  103164. encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
  103165. encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
  103166. memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
  103167. if(encoder->protected_->do_md5)
  103168. FLAC__MD5Init(&encoder->private_->md5context);
  103169. if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
  103170. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103171. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103172. }
  103173. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103174. /* the above function sets the state for us in case of an error */
  103175. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103176. }
  103177. /*
  103178. * Now that the STREAMINFO block is written, we can init this to an
  103179. * absurdly-high value...
  103180. */
  103181. encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
  103182. /* ... and clear this to 0 */
  103183. encoder->private_->streaminfo.data.stream_info.total_samples = 0;
  103184. /*
  103185. * Check to see if the supplied metadata contains a VORBIS_COMMENT;
  103186. * if not, we will write an empty one (FLAC__add_metadata_block()
  103187. * automatically supplies the vendor string).
  103188. *
  103189. * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
  103190. * the STREAMINFO. (In the case that metadata_has_vorbis_comment is
  103191. * true it will have already insured that the metadata list is properly
  103192. * ordered.)
  103193. */
  103194. if(!metadata_has_vorbis_comment) {
  103195. FLAC__StreamMetadata vorbis_comment;
  103196. vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
  103197. vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
  103198. vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
  103199. vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
  103200. vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
  103201. vorbis_comment.data.vorbis_comment.num_comments = 0;
  103202. vorbis_comment.data.vorbis_comment.comments = 0;
  103203. if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
  103204. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103205. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103206. }
  103207. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103208. /* the above function sets the state for us in case of an error */
  103209. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103210. }
  103211. }
  103212. /*
  103213. * write the user's metadata blocks
  103214. */
  103215. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  103216. encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
  103217. if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
  103218. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103219. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103220. }
  103221. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103222. /* the above function sets the state for us in case of an error */
  103223. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103224. }
  103225. }
  103226. /* now that all the metadata is written, we save the stream offset */
  103227. 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 */
  103228. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103229. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103230. }
  103231. if(encoder->protected_->verify)
  103232. encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
  103233. return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  103234. }
  103235. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
  103236. FLAC__StreamEncoder *encoder,
  103237. FLAC__StreamEncoderWriteCallback write_callback,
  103238. FLAC__StreamEncoderSeekCallback seek_callback,
  103239. FLAC__StreamEncoderTellCallback tell_callback,
  103240. FLAC__StreamEncoderMetadataCallback metadata_callback,
  103241. void *client_data
  103242. )
  103243. {
  103244. return init_stream_internal_enc(
  103245. encoder,
  103246. /*read_callback=*/0,
  103247. write_callback,
  103248. seek_callback,
  103249. tell_callback,
  103250. metadata_callback,
  103251. client_data,
  103252. /*is_ogg=*/false
  103253. );
  103254. }
  103255. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
  103256. FLAC__StreamEncoder *encoder,
  103257. FLAC__StreamEncoderReadCallback read_callback,
  103258. FLAC__StreamEncoderWriteCallback write_callback,
  103259. FLAC__StreamEncoderSeekCallback seek_callback,
  103260. FLAC__StreamEncoderTellCallback tell_callback,
  103261. FLAC__StreamEncoderMetadataCallback metadata_callback,
  103262. void *client_data
  103263. )
  103264. {
  103265. return init_stream_internal_enc(
  103266. encoder,
  103267. read_callback,
  103268. write_callback,
  103269. seek_callback,
  103270. tell_callback,
  103271. metadata_callback,
  103272. client_data,
  103273. /*is_ogg=*/true
  103274. );
  103275. }
  103276. static FLAC__StreamEncoderInitStatus init_FILE_internal_enc(
  103277. FLAC__StreamEncoder *encoder,
  103278. FILE *file,
  103279. FLAC__StreamEncoderProgressCallback progress_callback,
  103280. void *client_data,
  103281. FLAC__bool is_ogg
  103282. )
  103283. {
  103284. FLAC__StreamEncoderInitStatus init_status;
  103285. FLAC__ASSERT(0 != encoder);
  103286. FLAC__ASSERT(0 != file);
  103287. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103288. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  103289. /* double protection */
  103290. if(file == 0) {
  103291. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  103292. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103293. }
  103294. /*
  103295. * To make sure that our file does not go unclosed after an error, we
  103296. * must assign the FILE pointer before any further error can occur in
  103297. * this routine.
  103298. */
  103299. if(file == stdout)
  103300. file = get_binary_stdout_(); /* just to be safe */
  103301. encoder->private_->file = file;
  103302. encoder->private_->progress_callback = progress_callback;
  103303. encoder->private_->bytes_written = 0;
  103304. encoder->private_->samples_written = 0;
  103305. encoder->private_->frames_written = 0;
  103306. init_status = init_stream_internal_enc(
  103307. encoder,
  103308. encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_enc : 0,
  103309. file_write_callback_,
  103310. encoder->private_->file == stdout? 0 : file_seek_callback_enc,
  103311. encoder->private_->file == stdout? 0 : file_tell_callback_enc,
  103312. /*metadata_callback=*/0,
  103313. client_data,
  103314. is_ogg
  103315. );
  103316. if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
  103317. /* the above function sets the state for us in case of an error */
  103318. return init_status;
  103319. }
  103320. {
  103321. unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  103322. FLAC__ASSERT(blocksize != 0);
  103323. encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
  103324. }
  103325. return init_status;
  103326. }
  103327. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
  103328. FLAC__StreamEncoder *encoder,
  103329. FILE *file,
  103330. FLAC__StreamEncoderProgressCallback progress_callback,
  103331. void *client_data
  103332. )
  103333. {
  103334. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
  103335. }
  103336. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
  103337. FLAC__StreamEncoder *encoder,
  103338. FILE *file,
  103339. FLAC__StreamEncoderProgressCallback progress_callback,
  103340. void *client_data
  103341. )
  103342. {
  103343. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
  103344. }
  103345. static FLAC__StreamEncoderInitStatus init_file_internal_enc(
  103346. FLAC__StreamEncoder *encoder,
  103347. const char *filename,
  103348. FLAC__StreamEncoderProgressCallback progress_callback,
  103349. void *client_data,
  103350. FLAC__bool is_ogg
  103351. )
  103352. {
  103353. FILE *file;
  103354. FLAC__ASSERT(0 != encoder);
  103355. /*
  103356. * To make sure that our file does not go unclosed after an error, we
  103357. * have to do the same entrance checks here that are later performed
  103358. * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
  103359. */
  103360. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103361. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  103362. file = filename? fopen(filename, "w+b") : stdout;
  103363. if(file == 0) {
  103364. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  103365. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103366. }
  103367. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, is_ogg);
  103368. }
  103369. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
  103370. FLAC__StreamEncoder *encoder,
  103371. const char *filename,
  103372. FLAC__StreamEncoderProgressCallback progress_callback,
  103373. void *client_data
  103374. )
  103375. {
  103376. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
  103377. }
  103378. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
  103379. FLAC__StreamEncoder *encoder,
  103380. const char *filename,
  103381. FLAC__StreamEncoderProgressCallback progress_callback,
  103382. void *client_data
  103383. )
  103384. {
  103385. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
  103386. }
  103387. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
  103388. {
  103389. FLAC__bool error = false;
  103390. FLAC__ASSERT(0 != encoder);
  103391. FLAC__ASSERT(0 != encoder->private_);
  103392. FLAC__ASSERT(0 != encoder->protected_);
  103393. if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
  103394. return true;
  103395. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
  103396. if(encoder->private_->current_sample_number != 0) {
  103397. const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
  103398. encoder->protected_->blocksize = encoder->private_->current_sample_number;
  103399. if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
  103400. error = true;
  103401. }
  103402. }
  103403. if(encoder->protected_->do_md5)
  103404. FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
  103405. if(!encoder->private_->is_being_deleted) {
  103406. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
  103407. if(encoder->private_->seek_callback) {
  103408. #if FLAC__HAS_OGG
  103409. if(encoder->private_->is_ogg)
  103410. update_ogg_metadata_(encoder);
  103411. else
  103412. #endif
  103413. update_metadata_(encoder);
  103414. /* check if an error occurred while updating metadata */
  103415. if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
  103416. error = true;
  103417. }
  103418. if(encoder->private_->metadata_callback)
  103419. encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
  103420. }
  103421. if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
  103422. if(!error)
  103423. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  103424. error = true;
  103425. }
  103426. }
  103427. if(0 != encoder->private_->file) {
  103428. if(encoder->private_->file != stdout)
  103429. fclose(encoder->private_->file);
  103430. encoder->private_->file = 0;
  103431. }
  103432. #if FLAC__HAS_OGG
  103433. if(encoder->private_->is_ogg)
  103434. FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
  103435. #endif
  103436. free_(encoder);
  103437. set_defaults_enc(encoder);
  103438. if(!error)
  103439. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  103440. return !error;
  103441. }
  103442. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
  103443. {
  103444. FLAC__ASSERT(0 != encoder);
  103445. FLAC__ASSERT(0 != encoder->private_);
  103446. FLAC__ASSERT(0 != encoder->protected_);
  103447. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103448. return false;
  103449. #if FLAC__HAS_OGG
  103450. /* can't check encoder->private_->is_ogg since that's not set until init time */
  103451. FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
  103452. return true;
  103453. #else
  103454. (void)value;
  103455. return false;
  103456. #endif
  103457. }
  103458. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool 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. #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  103466. encoder->protected_->verify = value;
  103467. #endif
  103468. return true;
  103469. }
  103470. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103471. {
  103472. FLAC__ASSERT(0 != encoder);
  103473. FLAC__ASSERT(0 != encoder->private_);
  103474. FLAC__ASSERT(0 != encoder->protected_);
  103475. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103476. return false;
  103477. encoder->protected_->streamable_subset = value;
  103478. return true;
  103479. }
  103480. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103481. {
  103482. FLAC__ASSERT(0 != encoder);
  103483. FLAC__ASSERT(0 != encoder->private_);
  103484. FLAC__ASSERT(0 != encoder->protected_);
  103485. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103486. return false;
  103487. encoder->protected_->do_md5 = value;
  103488. return true;
  103489. }
  103490. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
  103491. {
  103492. FLAC__ASSERT(0 != encoder);
  103493. FLAC__ASSERT(0 != encoder->private_);
  103494. FLAC__ASSERT(0 != encoder->protected_);
  103495. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103496. return false;
  103497. encoder->protected_->channels = value;
  103498. return true;
  103499. }
  103500. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
  103501. {
  103502. FLAC__ASSERT(0 != encoder);
  103503. FLAC__ASSERT(0 != encoder->private_);
  103504. FLAC__ASSERT(0 != encoder->protected_);
  103505. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103506. return false;
  103507. encoder->protected_->bits_per_sample = value;
  103508. return true;
  103509. }
  103510. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
  103511. {
  103512. FLAC__ASSERT(0 != encoder);
  103513. FLAC__ASSERT(0 != encoder->private_);
  103514. FLAC__ASSERT(0 != encoder->protected_);
  103515. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103516. return false;
  103517. encoder->protected_->sample_rate = value;
  103518. return true;
  103519. }
  103520. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
  103521. {
  103522. FLAC__bool ok = true;
  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. if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
  103529. value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
  103530. ok &= FLAC__stream_encoder_set_do_mid_side_stereo (encoder, compression_levels_[value].do_mid_side_stereo);
  103531. ok &= FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, compression_levels_[value].loose_mid_side_stereo);
  103532. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103533. #if 0
  103534. /* was: */
  103535. ok &= FLAC__stream_encoder_set_apodization (encoder, compression_levels_[value].apodization);
  103536. /* but it's too hard to specify the string in a locale-specific way */
  103537. #else
  103538. encoder->protected_->num_apodizations = 1;
  103539. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  103540. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  103541. #endif
  103542. #endif
  103543. ok &= FLAC__stream_encoder_set_max_lpc_order (encoder, compression_levels_[value].max_lpc_order);
  103544. ok &= FLAC__stream_encoder_set_qlp_coeff_precision (encoder, compression_levels_[value].qlp_coeff_precision);
  103545. ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
  103546. ok &= FLAC__stream_encoder_set_do_escape_coding (encoder, compression_levels_[value].do_escape_coding);
  103547. ok &= FLAC__stream_encoder_set_do_exhaustive_model_search (encoder, compression_levels_[value].do_exhaustive_model_search);
  103548. ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
  103549. ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
  103550. ok &= FLAC__stream_encoder_set_rice_parameter_search_dist (encoder, compression_levels_[value].rice_parameter_search_dist);
  103551. return ok;
  103552. }
  103553. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
  103554. {
  103555. FLAC__ASSERT(0 != encoder);
  103556. FLAC__ASSERT(0 != encoder->private_);
  103557. FLAC__ASSERT(0 != encoder->protected_);
  103558. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103559. return false;
  103560. encoder->protected_->blocksize = value;
  103561. return true;
  103562. }
  103563. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103564. {
  103565. FLAC__ASSERT(0 != encoder);
  103566. FLAC__ASSERT(0 != encoder->private_);
  103567. FLAC__ASSERT(0 != encoder->protected_);
  103568. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103569. return false;
  103570. encoder->protected_->do_mid_side_stereo = value;
  103571. return true;
  103572. }
  103573. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103574. {
  103575. FLAC__ASSERT(0 != encoder);
  103576. FLAC__ASSERT(0 != encoder->private_);
  103577. FLAC__ASSERT(0 != encoder->protected_);
  103578. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103579. return false;
  103580. encoder->protected_->loose_mid_side_stereo = value;
  103581. return true;
  103582. }
  103583. /*@@@@add to tests*/
  103584. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
  103585. {
  103586. FLAC__ASSERT(0 != encoder);
  103587. FLAC__ASSERT(0 != encoder->private_);
  103588. FLAC__ASSERT(0 != encoder->protected_);
  103589. FLAC__ASSERT(0 != specification);
  103590. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103591. return false;
  103592. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  103593. (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
  103594. #else
  103595. encoder->protected_->num_apodizations = 0;
  103596. while(1) {
  103597. const char *s = strchr(specification, ';');
  103598. const size_t n = s? (size_t)(s - specification) : strlen(specification);
  103599. if (n==8 && 0 == strncmp("bartlett" , specification, n))
  103600. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
  103601. else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
  103602. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
  103603. else if(n==8 && 0 == strncmp("blackman" , specification, n))
  103604. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
  103605. else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
  103606. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
  103607. else if(n==6 && 0 == strncmp("connes" , specification, n))
  103608. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
  103609. else if(n==7 && 0 == strncmp("flattop" , specification, n))
  103610. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
  103611. else if(n>7 && 0 == strncmp("gauss(" , specification, 6)) {
  103612. FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
  103613. if (stddev > 0.0 && stddev <= 0.5) {
  103614. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
  103615. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
  103616. }
  103617. }
  103618. else if(n==7 && 0 == strncmp("hamming" , specification, n))
  103619. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
  103620. else if(n==4 && 0 == strncmp("hann" , specification, n))
  103621. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
  103622. else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
  103623. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
  103624. else if(n==7 && 0 == strncmp("nuttall" , specification, n))
  103625. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
  103626. else if(n==9 && 0 == strncmp("rectangle" , specification, n))
  103627. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
  103628. else if(n==8 && 0 == strncmp("triangle" , specification, n))
  103629. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
  103630. else if(n>7 && 0 == strncmp("tukey(" , specification, 6)) {
  103631. FLAC__real p = (FLAC__real)strtod(specification+6, 0);
  103632. if (p >= 0.0 && p <= 1.0) {
  103633. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
  103634. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
  103635. }
  103636. }
  103637. else if(n==5 && 0 == strncmp("welch" , specification, n))
  103638. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
  103639. if (encoder->protected_->num_apodizations == 32)
  103640. break;
  103641. if (s)
  103642. specification = s+1;
  103643. else
  103644. break;
  103645. }
  103646. if(encoder->protected_->num_apodizations == 0) {
  103647. encoder->protected_->num_apodizations = 1;
  103648. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  103649. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  103650. }
  103651. #endif
  103652. return true;
  103653. }
  103654. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
  103655. {
  103656. FLAC__ASSERT(0 != encoder);
  103657. FLAC__ASSERT(0 != encoder->private_);
  103658. FLAC__ASSERT(0 != encoder->protected_);
  103659. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103660. return false;
  103661. encoder->protected_->max_lpc_order = value;
  103662. return true;
  103663. }
  103664. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
  103665. {
  103666. FLAC__ASSERT(0 != encoder);
  103667. FLAC__ASSERT(0 != encoder->private_);
  103668. FLAC__ASSERT(0 != encoder->protected_);
  103669. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103670. return false;
  103671. encoder->protected_->qlp_coeff_precision = value;
  103672. return true;
  103673. }
  103674. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103675. {
  103676. FLAC__ASSERT(0 != encoder);
  103677. FLAC__ASSERT(0 != encoder->private_);
  103678. FLAC__ASSERT(0 != encoder->protected_);
  103679. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103680. return false;
  103681. encoder->protected_->do_qlp_coeff_prec_search = value;
  103682. return true;
  103683. }
  103684. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103685. {
  103686. FLAC__ASSERT(0 != encoder);
  103687. FLAC__ASSERT(0 != encoder->private_);
  103688. FLAC__ASSERT(0 != encoder->protected_);
  103689. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103690. return false;
  103691. #if 0
  103692. /*@@@ deprecated: */
  103693. encoder->protected_->do_escape_coding = value;
  103694. #else
  103695. (void)value;
  103696. #endif
  103697. return true;
  103698. }
  103699. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103700. {
  103701. FLAC__ASSERT(0 != encoder);
  103702. FLAC__ASSERT(0 != encoder->private_);
  103703. FLAC__ASSERT(0 != encoder->protected_);
  103704. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103705. return false;
  103706. encoder->protected_->do_exhaustive_model_search = value;
  103707. return true;
  103708. }
  103709. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  103710. {
  103711. FLAC__ASSERT(0 != encoder);
  103712. FLAC__ASSERT(0 != encoder->private_);
  103713. FLAC__ASSERT(0 != encoder->protected_);
  103714. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103715. return false;
  103716. encoder->protected_->min_residual_partition_order = value;
  103717. return true;
  103718. }
  103719. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  103720. {
  103721. FLAC__ASSERT(0 != encoder);
  103722. FLAC__ASSERT(0 != encoder->private_);
  103723. FLAC__ASSERT(0 != encoder->protected_);
  103724. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103725. return false;
  103726. encoder->protected_->max_residual_partition_order = value;
  103727. return true;
  103728. }
  103729. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
  103730. {
  103731. FLAC__ASSERT(0 != encoder);
  103732. FLAC__ASSERT(0 != encoder->private_);
  103733. FLAC__ASSERT(0 != encoder->protected_);
  103734. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103735. return false;
  103736. #if 0
  103737. /*@@@ deprecated: */
  103738. encoder->protected_->rice_parameter_search_dist = value;
  103739. #else
  103740. (void)value;
  103741. #endif
  103742. return true;
  103743. }
  103744. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
  103745. {
  103746. FLAC__ASSERT(0 != encoder);
  103747. FLAC__ASSERT(0 != encoder->private_);
  103748. FLAC__ASSERT(0 != encoder->protected_);
  103749. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103750. return false;
  103751. encoder->protected_->total_samples_estimate = value;
  103752. return true;
  103753. }
  103754. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
  103755. {
  103756. FLAC__ASSERT(0 != encoder);
  103757. FLAC__ASSERT(0 != encoder->private_);
  103758. FLAC__ASSERT(0 != encoder->protected_);
  103759. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103760. return false;
  103761. if(0 == metadata)
  103762. num_blocks = 0;
  103763. if(0 == num_blocks)
  103764. metadata = 0;
  103765. /* realloc() does not do exactly what we want so... */
  103766. if(encoder->protected_->metadata) {
  103767. free(encoder->protected_->metadata);
  103768. encoder->protected_->metadata = 0;
  103769. encoder->protected_->num_metadata_blocks = 0;
  103770. }
  103771. if(num_blocks) {
  103772. FLAC__StreamMetadata **m;
  103773. if(0 == (m = (FLAC__StreamMetadata**)safe_malloc_mul_2op_(sizeof(m[0]), /*times*/num_blocks)))
  103774. return false;
  103775. memcpy(m, metadata, sizeof(m[0]) * num_blocks);
  103776. encoder->protected_->metadata = m;
  103777. encoder->protected_->num_metadata_blocks = num_blocks;
  103778. }
  103779. #if FLAC__HAS_OGG
  103780. if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
  103781. return false;
  103782. #endif
  103783. return true;
  103784. }
  103785. /*
  103786. * These three functions are not static, but not publically exposed in
  103787. * include/FLAC/ either. They are used by the test suite.
  103788. */
  103789. FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103790. {
  103791. FLAC__ASSERT(0 != encoder);
  103792. FLAC__ASSERT(0 != encoder->private_);
  103793. FLAC__ASSERT(0 != encoder->protected_);
  103794. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103795. return false;
  103796. encoder->private_->disable_constant_subframes = value;
  103797. return true;
  103798. }
  103799. FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103800. {
  103801. FLAC__ASSERT(0 != encoder);
  103802. FLAC__ASSERT(0 != encoder->private_);
  103803. FLAC__ASSERT(0 != encoder->protected_);
  103804. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103805. return false;
  103806. encoder->private_->disable_fixed_subframes = value;
  103807. return true;
  103808. }
  103809. FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103810. {
  103811. FLAC__ASSERT(0 != encoder);
  103812. FLAC__ASSERT(0 != encoder->private_);
  103813. FLAC__ASSERT(0 != encoder->protected_);
  103814. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103815. return false;
  103816. encoder->private_->disable_verbatim_subframes = value;
  103817. return true;
  103818. }
  103819. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
  103820. {
  103821. FLAC__ASSERT(0 != encoder);
  103822. FLAC__ASSERT(0 != encoder->private_);
  103823. FLAC__ASSERT(0 != encoder->protected_);
  103824. return encoder->protected_->state;
  103825. }
  103826. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
  103827. {
  103828. FLAC__ASSERT(0 != encoder);
  103829. FLAC__ASSERT(0 != encoder->private_);
  103830. FLAC__ASSERT(0 != encoder->protected_);
  103831. if(encoder->protected_->verify)
  103832. return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
  103833. else
  103834. return FLAC__STREAM_DECODER_UNINITIALIZED;
  103835. }
  103836. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
  103837. {
  103838. FLAC__ASSERT(0 != encoder);
  103839. FLAC__ASSERT(0 != encoder->private_);
  103840. FLAC__ASSERT(0 != encoder->protected_);
  103841. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
  103842. return FLAC__StreamEncoderStateString[encoder->protected_->state];
  103843. else
  103844. return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
  103845. }
  103846. 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)
  103847. {
  103848. FLAC__ASSERT(0 != encoder);
  103849. FLAC__ASSERT(0 != encoder->private_);
  103850. FLAC__ASSERT(0 != encoder->protected_);
  103851. if(0 != absolute_sample)
  103852. *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
  103853. if(0 != frame_number)
  103854. *frame_number = encoder->private_->verify.error_stats.frame_number;
  103855. if(0 != channel)
  103856. *channel = encoder->private_->verify.error_stats.channel;
  103857. if(0 != sample)
  103858. *sample = encoder->private_->verify.error_stats.sample;
  103859. if(0 != expected)
  103860. *expected = encoder->private_->verify.error_stats.expected;
  103861. if(0 != got)
  103862. *got = encoder->private_->verify.error_stats.got;
  103863. }
  103864. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(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_->verify;
  103870. }
  103871. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(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_->streamable_subset;
  103877. }
  103878. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(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_->do_md5;
  103884. }
  103885. FLAC_API unsigned FLAC__stream_encoder_get_channels(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_->channels;
  103891. }
  103892. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(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_->bits_per_sample;
  103898. }
  103899. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(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_->sample_rate;
  103905. }
  103906. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(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_->blocksize;
  103912. }
  103913. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(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_mid_side_stereo;
  103919. }
  103920. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(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_->loose_mid_side_stereo;
  103926. }
  103927. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_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_lpc_order;
  103933. }
  103934. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(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_->qlp_coeff_precision;
  103940. }
  103941. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(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_->do_qlp_coeff_prec_search;
  103947. }
  103948. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
  103949. {
  103950. FLAC__ASSERT(0 != encoder);
  103951. FLAC__ASSERT(0 != encoder->private_);
  103952. FLAC__ASSERT(0 != encoder->protected_);
  103953. return encoder->protected_->do_escape_coding;
  103954. }
  103955. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
  103956. {
  103957. FLAC__ASSERT(0 != encoder);
  103958. FLAC__ASSERT(0 != encoder->private_);
  103959. FLAC__ASSERT(0 != encoder->protected_);
  103960. return encoder->protected_->do_exhaustive_model_search;
  103961. }
  103962. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
  103963. {
  103964. FLAC__ASSERT(0 != encoder);
  103965. FLAC__ASSERT(0 != encoder->private_);
  103966. FLAC__ASSERT(0 != encoder->protected_);
  103967. return encoder->protected_->min_residual_partition_order;
  103968. }
  103969. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
  103970. {
  103971. FLAC__ASSERT(0 != encoder);
  103972. FLAC__ASSERT(0 != encoder->private_);
  103973. FLAC__ASSERT(0 != encoder->protected_);
  103974. return encoder->protected_->max_residual_partition_order;
  103975. }
  103976. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
  103977. {
  103978. FLAC__ASSERT(0 != encoder);
  103979. FLAC__ASSERT(0 != encoder->private_);
  103980. FLAC__ASSERT(0 != encoder->protected_);
  103981. return encoder->protected_->rice_parameter_search_dist;
  103982. }
  103983. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
  103984. {
  103985. FLAC__ASSERT(0 != encoder);
  103986. FLAC__ASSERT(0 != encoder->private_);
  103987. FLAC__ASSERT(0 != encoder->protected_);
  103988. return encoder->protected_->total_samples_estimate;
  103989. }
  103990. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
  103991. {
  103992. unsigned i, j = 0, channel;
  103993. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  103994. FLAC__ASSERT(0 != encoder);
  103995. FLAC__ASSERT(0 != encoder->private_);
  103996. FLAC__ASSERT(0 != encoder->protected_);
  103997. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  103998. do {
  103999. const unsigned n = min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
  104000. if(encoder->protected_->verify)
  104001. append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
  104002. for(channel = 0; channel < channels; channel++)
  104003. memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
  104004. if(encoder->protected_->do_mid_side_stereo) {
  104005. FLAC__ASSERT(channels == 2);
  104006. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  104007. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  104008. encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
  104009. 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' ! */
  104010. }
  104011. }
  104012. else
  104013. j += n;
  104014. encoder->private_->current_sample_number += n;
  104015. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  104016. if(encoder->private_->current_sample_number > blocksize) {
  104017. FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
  104018. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  104019. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  104020. return false;
  104021. /* move unprocessed overread samples to beginnings of arrays */
  104022. for(channel = 0; channel < channels; channel++)
  104023. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  104024. if(encoder->protected_->do_mid_side_stereo) {
  104025. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  104026. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  104027. }
  104028. encoder->private_->current_sample_number = 1;
  104029. }
  104030. } while(j < samples);
  104031. return true;
  104032. }
  104033. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
  104034. {
  104035. unsigned i, j, k, channel;
  104036. FLAC__int32 x, mid, side;
  104037. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  104038. FLAC__ASSERT(0 != encoder);
  104039. FLAC__ASSERT(0 != encoder->private_);
  104040. FLAC__ASSERT(0 != encoder->protected_);
  104041. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104042. j = k = 0;
  104043. /*
  104044. * we have several flavors of the same basic loop, optimized for
  104045. * different conditions:
  104046. */
  104047. if(encoder->protected_->do_mid_side_stereo && channels == 2) {
  104048. /*
  104049. * stereo coding: unroll channel loop
  104050. */
  104051. do {
  104052. if(encoder->protected_->verify)
  104053. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  104054. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  104055. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  104056. encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
  104057. x = buffer[k++];
  104058. encoder->private_->integer_signal[1][i] = x;
  104059. mid += x;
  104060. side -= x;
  104061. mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
  104062. encoder->private_->integer_signal_mid_side[1][i] = side;
  104063. encoder->private_->integer_signal_mid_side[0][i] = mid;
  104064. }
  104065. encoder->private_->current_sample_number = i;
  104066. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  104067. if(i > blocksize) {
  104068. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  104069. return false;
  104070. /* move unprocessed overread samples to beginnings of arrays */
  104071. FLAC__ASSERT(i == blocksize+OVERREAD_);
  104072. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  104073. encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
  104074. encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
  104075. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  104076. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  104077. encoder->private_->current_sample_number = 1;
  104078. }
  104079. } while(j < samples);
  104080. }
  104081. else {
  104082. /*
  104083. * independent channel coding: buffer each channel in inner loop
  104084. */
  104085. do {
  104086. if(encoder->protected_->verify)
  104087. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  104088. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  104089. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  104090. for(channel = 0; channel < channels; channel++)
  104091. encoder->private_->integer_signal[channel][i] = buffer[k++];
  104092. }
  104093. encoder->private_->current_sample_number = i;
  104094. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  104095. if(i > blocksize) {
  104096. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  104097. return false;
  104098. /* move unprocessed overread samples to beginnings of arrays */
  104099. FLAC__ASSERT(i == blocksize+OVERREAD_);
  104100. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  104101. for(channel = 0; channel < channels; channel++)
  104102. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  104103. encoder->private_->current_sample_number = 1;
  104104. }
  104105. } while(j < samples);
  104106. }
  104107. return true;
  104108. }
  104109. /***********************************************************************
  104110. *
  104111. * Private class methods
  104112. *
  104113. ***********************************************************************/
  104114. void set_defaults_enc(FLAC__StreamEncoder *encoder)
  104115. {
  104116. FLAC__ASSERT(0 != encoder);
  104117. #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  104118. encoder->protected_->verify = true;
  104119. #else
  104120. encoder->protected_->verify = false;
  104121. #endif
  104122. encoder->protected_->streamable_subset = true;
  104123. encoder->protected_->do_md5 = true;
  104124. encoder->protected_->do_mid_side_stereo = false;
  104125. encoder->protected_->loose_mid_side_stereo = false;
  104126. encoder->protected_->channels = 2;
  104127. encoder->protected_->bits_per_sample = 16;
  104128. encoder->protected_->sample_rate = 44100;
  104129. encoder->protected_->blocksize = 0;
  104130. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104131. encoder->protected_->num_apodizations = 1;
  104132. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  104133. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  104134. #endif
  104135. encoder->protected_->max_lpc_order = 0;
  104136. encoder->protected_->qlp_coeff_precision = 0;
  104137. encoder->protected_->do_qlp_coeff_prec_search = false;
  104138. encoder->protected_->do_exhaustive_model_search = false;
  104139. encoder->protected_->do_escape_coding = false;
  104140. encoder->protected_->min_residual_partition_order = 0;
  104141. encoder->protected_->max_residual_partition_order = 0;
  104142. encoder->protected_->rice_parameter_search_dist = 0;
  104143. encoder->protected_->total_samples_estimate = 0;
  104144. encoder->protected_->metadata = 0;
  104145. encoder->protected_->num_metadata_blocks = 0;
  104146. encoder->private_->seek_table = 0;
  104147. encoder->private_->disable_constant_subframes = false;
  104148. encoder->private_->disable_fixed_subframes = false;
  104149. encoder->private_->disable_verbatim_subframes = false;
  104150. #if FLAC__HAS_OGG
  104151. encoder->private_->is_ogg = false;
  104152. #endif
  104153. encoder->private_->read_callback = 0;
  104154. encoder->private_->write_callback = 0;
  104155. encoder->private_->seek_callback = 0;
  104156. encoder->private_->tell_callback = 0;
  104157. encoder->private_->metadata_callback = 0;
  104158. encoder->private_->progress_callback = 0;
  104159. encoder->private_->client_data = 0;
  104160. #if FLAC__HAS_OGG
  104161. FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
  104162. #endif
  104163. }
  104164. void free_(FLAC__StreamEncoder *encoder)
  104165. {
  104166. unsigned i, channel;
  104167. FLAC__ASSERT(0 != encoder);
  104168. if(encoder->protected_->metadata) {
  104169. free(encoder->protected_->metadata);
  104170. encoder->protected_->metadata = 0;
  104171. encoder->protected_->num_metadata_blocks = 0;
  104172. }
  104173. for(i = 0; i < encoder->protected_->channels; i++) {
  104174. if(0 != encoder->private_->integer_signal_unaligned[i]) {
  104175. free(encoder->private_->integer_signal_unaligned[i]);
  104176. encoder->private_->integer_signal_unaligned[i] = 0;
  104177. }
  104178. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104179. if(0 != encoder->private_->real_signal_unaligned[i]) {
  104180. free(encoder->private_->real_signal_unaligned[i]);
  104181. encoder->private_->real_signal_unaligned[i] = 0;
  104182. }
  104183. #endif
  104184. }
  104185. for(i = 0; i < 2; i++) {
  104186. if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
  104187. free(encoder->private_->integer_signal_mid_side_unaligned[i]);
  104188. encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
  104189. }
  104190. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104191. if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
  104192. free(encoder->private_->real_signal_mid_side_unaligned[i]);
  104193. encoder->private_->real_signal_mid_side_unaligned[i] = 0;
  104194. }
  104195. #endif
  104196. }
  104197. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104198. for(i = 0; i < encoder->protected_->num_apodizations; i++) {
  104199. if(0 != encoder->private_->window_unaligned[i]) {
  104200. free(encoder->private_->window_unaligned[i]);
  104201. encoder->private_->window_unaligned[i] = 0;
  104202. }
  104203. }
  104204. if(0 != encoder->private_->windowed_signal_unaligned) {
  104205. free(encoder->private_->windowed_signal_unaligned);
  104206. encoder->private_->windowed_signal_unaligned = 0;
  104207. }
  104208. #endif
  104209. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104210. for(i = 0; i < 2; i++) {
  104211. if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
  104212. free(encoder->private_->residual_workspace_unaligned[channel][i]);
  104213. encoder->private_->residual_workspace_unaligned[channel][i] = 0;
  104214. }
  104215. }
  104216. }
  104217. for(channel = 0; channel < 2; channel++) {
  104218. for(i = 0; i < 2; i++) {
  104219. if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
  104220. free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
  104221. encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
  104222. }
  104223. }
  104224. }
  104225. if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
  104226. free(encoder->private_->abs_residual_partition_sums_unaligned);
  104227. encoder->private_->abs_residual_partition_sums_unaligned = 0;
  104228. }
  104229. if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
  104230. free(encoder->private_->raw_bits_per_partition_unaligned);
  104231. encoder->private_->raw_bits_per_partition_unaligned = 0;
  104232. }
  104233. if(encoder->protected_->verify) {
  104234. for(i = 0; i < encoder->protected_->channels; i++) {
  104235. if(0 != encoder->private_->verify.input_fifo.data[i]) {
  104236. free(encoder->private_->verify.input_fifo.data[i]);
  104237. encoder->private_->verify.input_fifo.data[i] = 0;
  104238. }
  104239. }
  104240. }
  104241. FLAC__bitwriter_free(encoder->private_->frame);
  104242. }
  104243. FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
  104244. {
  104245. FLAC__bool ok;
  104246. unsigned i, channel;
  104247. FLAC__ASSERT(new_blocksize > 0);
  104248. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104249. FLAC__ASSERT(encoder->private_->current_sample_number == 0);
  104250. /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
  104251. if(new_blocksize <= encoder->private_->input_capacity)
  104252. return true;
  104253. ok = true;
  104254. /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
  104255. * requires that the input arrays (in our case the integer signals)
  104256. * have a buffer of up to 3 zeroes in front (at negative indices) for
  104257. * alignment purposes; we use 4 in front to keep the data well-aligned.
  104258. */
  104259. for(i = 0; ok && i < encoder->protected_->channels; i++) {
  104260. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
  104261. memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
  104262. encoder->private_->integer_signal[i] += 4;
  104263. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104264. #if 0 /* @@@ currently unused */
  104265. if(encoder->protected_->max_lpc_order > 0)
  104266. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
  104267. #endif
  104268. #endif
  104269. }
  104270. for(i = 0; ok && i < 2; i++) {
  104271. 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]);
  104272. memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
  104273. encoder->private_->integer_signal_mid_side[i] += 4;
  104274. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104275. #if 0 /* @@@ currently unused */
  104276. if(encoder->protected_->max_lpc_order > 0)
  104277. 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]);
  104278. #endif
  104279. #endif
  104280. }
  104281. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104282. if(ok && encoder->protected_->max_lpc_order > 0) {
  104283. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
  104284. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
  104285. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
  104286. }
  104287. #endif
  104288. for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
  104289. for(i = 0; ok && i < 2; i++) {
  104290. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
  104291. }
  104292. }
  104293. for(channel = 0; ok && channel < 2; channel++) {
  104294. for(i = 0; ok && i < 2; i++) {
  104295. 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]);
  104296. }
  104297. }
  104298. /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
  104299. /*@@@ 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) */
  104300. ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
  104301. if(encoder->protected_->do_escape_coding)
  104302. ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
  104303. /* now adjust the windows if the blocksize has changed */
  104304. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104305. if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
  104306. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
  104307. switch(encoder->protected_->apodizations[i].type) {
  104308. case FLAC__APODIZATION_BARTLETT:
  104309. FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
  104310. break;
  104311. case FLAC__APODIZATION_BARTLETT_HANN:
  104312. FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
  104313. break;
  104314. case FLAC__APODIZATION_BLACKMAN:
  104315. FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
  104316. break;
  104317. case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
  104318. FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
  104319. break;
  104320. case FLAC__APODIZATION_CONNES:
  104321. FLAC__window_connes(encoder->private_->window[i], new_blocksize);
  104322. break;
  104323. case FLAC__APODIZATION_FLATTOP:
  104324. FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
  104325. break;
  104326. case FLAC__APODIZATION_GAUSS:
  104327. FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
  104328. break;
  104329. case FLAC__APODIZATION_HAMMING:
  104330. FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
  104331. break;
  104332. case FLAC__APODIZATION_HANN:
  104333. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  104334. break;
  104335. case FLAC__APODIZATION_KAISER_BESSEL:
  104336. FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
  104337. break;
  104338. case FLAC__APODIZATION_NUTTALL:
  104339. FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
  104340. break;
  104341. case FLAC__APODIZATION_RECTANGLE:
  104342. FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
  104343. break;
  104344. case FLAC__APODIZATION_TRIANGLE:
  104345. FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
  104346. break;
  104347. case FLAC__APODIZATION_TUKEY:
  104348. FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
  104349. break;
  104350. case FLAC__APODIZATION_WELCH:
  104351. FLAC__window_welch(encoder->private_->window[i], new_blocksize);
  104352. break;
  104353. default:
  104354. FLAC__ASSERT(0);
  104355. /* double protection */
  104356. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  104357. break;
  104358. }
  104359. }
  104360. }
  104361. #endif
  104362. if(ok)
  104363. encoder->private_->input_capacity = new_blocksize;
  104364. else
  104365. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104366. return ok;
  104367. }
  104368. FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
  104369. {
  104370. const FLAC__byte *buffer;
  104371. size_t bytes;
  104372. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  104373. if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
  104374. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104375. return false;
  104376. }
  104377. if(encoder->protected_->verify) {
  104378. encoder->private_->verify.output.data = buffer;
  104379. encoder->private_->verify.output.bytes = bytes;
  104380. if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
  104381. encoder->private_->verify.needs_magic_hack = true;
  104382. }
  104383. else {
  104384. if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
  104385. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104386. FLAC__bitwriter_clear(encoder->private_->frame);
  104387. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
  104388. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  104389. return false;
  104390. }
  104391. }
  104392. }
  104393. if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104394. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104395. FLAC__bitwriter_clear(encoder->private_->frame);
  104396. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104397. return false;
  104398. }
  104399. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104400. FLAC__bitwriter_clear(encoder->private_->frame);
  104401. if(samples > 0) {
  104402. encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
  104403. encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
  104404. }
  104405. return true;
  104406. }
  104407. FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
  104408. {
  104409. FLAC__StreamEncoderWriteStatus status;
  104410. FLAC__uint64 output_position = 0;
  104411. /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
  104412. if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
  104413. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104414. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  104415. }
  104416. /*
  104417. * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
  104418. */
  104419. if(samples == 0) {
  104420. FLAC__MetadataType type = (FLAC__MetadataType) (buffer[0] & 0x7f);
  104421. if(type == FLAC__METADATA_TYPE_STREAMINFO)
  104422. encoder->protected_->streaminfo_offset = output_position;
  104423. else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
  104424. encoder->protected_->seektable_offset = output_position;
  104425. }
  104426. /*
  104427. * Mark the current seek point if hit (if audio_offset == 0 that
  104428. * means we're still writing metadata and haven't hit the first
  104429. * frame yet)
  104430. */
  104431. if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
  104432. const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  104433. const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
  104434. const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
  104435. FLAC__uint64 test_sample;
  104436. unsigned i;
  104437. for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
  104438. test_sample = encoder->private_->seek_table->points[i].sample_number;
  104439. if(test_sample > frame_last_sample) {
  104440. break;
  104441. }
  104442. else if(test_sample >= frame_first_sample) {
  104443. encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
  104444. encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
  104445. encoder->private_->seek_table->points[i].frame_samples = blocksize;
  104446. encoder->private_->first_seekpoint_to_check++;
  104447. /* DO NOT: "break;" and here's why:
  104448. * The seektable template may contain more than one target
  104449. * sample for any given frame; we will keep looping, generating
  104450. * duplicate seekpoints for them, and we'll clean it up later,
  104451. * just before writing the seektable back to the metadata.
  104452. */
  104453. }
  104454. else {
  104455. encoder->private_->first_seekpoint_to_check++;
  104456. }
  104457. }
  104458. }
  104459. #if FLAC__HAS_OGG
  104460. if(encoder->private_->is_ogg) {
  104461. status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
  104462. &encoder->protected_->ogg_encoder_aspect,
  104463. buffer,
  104464. bytes,
  104465. samples,
  104466. encoder->private_->current_frame_number,
  104467. is_last_block,
  104468. (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
  104469. encoder,
  104470. encoder->private_->client_data
  104471. );
  104472. }
  104473. else
  104474. #endif
  104475. status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
  104476. if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104477. encoder->private_->bytes_written += bytes;
  104478. encoder->private_->samples_written += samples;
  104479. /* we keep a high watermark on the number of frames written because
  104480. * when the encoder goes back to write metadata, 'current_frame'
  104481. * will drop back to 0.
  104482. */
  104483. encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
  104484. }
  104485. else
  104486. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104487. return status;
  104488. }
  104489. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  104490. void update_metadata_(const FLAC__StreamEncoder *encoder)
  104491. {
  104492. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  104493. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  104494. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  104495. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  104496. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  104497. const unsigned bps = metadata->data.stream_info.bits_per_sample;
  104498. FLAC__StreamEncoderSeekStatus seek_status;
  104499. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  104500. /* All this is based on intimate knowledge of the stream header
  104501. * layout, but a change to the header format that would break this
  104502. * would also break all streams encoded in the previous format.
  104503. */
  104504. /*
  104505. * Write MD5 signature
  104506. */
  104507. {
  104508. const unsigned md5_offset =
  104509. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104510. (
  104511. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104512. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104513. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104514. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104515. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104516. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104517. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  104518. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  104519. ) / 8;
  104520. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  104521. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104522. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104523. return;
  104524. }
  104525. if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104526. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104527. return;
  104528. }
  104529. }
  104530. /*
  104531. * Write total samples
  104532. */
  104533. {
  104534. const unsigned total_samples_byte_offset =
  104535. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104536. (
  104537. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104538. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104539. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104540. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104541. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104542. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104543. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  104544. - 4
  104545. ) / 8;
  104546. b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
  104547. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  104548. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  104549. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  104550. b[4] = (FLAC__byte)(samples & 0xFF);
  104551. 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) {
  104552. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104553. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104554. return;
  104555. }
  104556. if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104557. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104558. return;
  104559. }
  104560. }
  104561. /*
  104562. * Write min/max framesize
  104563. */
  104564. {
  104565. const unsigned min_framesize_offset =
  104566. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104567. (
  104568. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104569. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  104570. ) / 8;
  104571. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  104572. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  104573. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  104574. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  104575. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  104576. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  104577. 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) {
  104578. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104579. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104580. return;
  104581. }
  104582. if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104583. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104584. return;
  104585. }
  104586. }
  104587. /*
  104588. * Write seektable
  104589. */
  104590. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  104591. unsigned i;
  104592. FLAC__format_seektable_sort(encoder->private_->seek_table);
  104593. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  104594. 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) {
  104595. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104596. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104597. return;
  104598. }
  104599. for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
  104600. FLAC__uint64 xx;
  104601. unsigned x;
  104602. xx = encoder->private_->seek_table->points[i].sample_number;
  104603. b[7] = (FLAC__byte)xx; xx >>= 8;
  104604. b[6] = (FLAC__byte)xx; xx >>= 8;
  104605. b[5] = (FLAC__byte)xx; xx >>= 8;
  104606. b[4] = (FLAC__byte)xx; xx >>= 8;
  104607. b[3] = (FLAC__byte)xx; xx >>= 8;
  104608. b[2] = (FLAC__byte)xx; xx >>= 8;
  104609. b[1] = (FLAC__byte)xx; xx >>= 8;
  104610. b[0] = (FLAC__byte)xx; xx >>= 8;
  104611. xx = encoder->private_->seek_table->points[i].stream_offset;
  104612. b[15] = (FLAC__byte)xx; xx >>= 8;
  104613. b[14] = (FLAC__byte)xx; xx >>= 8;
  104614. b[13] = (FLAC__byte)xx; xx >>= 8;
  104615. b[12] = (FLAC__byte)xx; xx >>= 8;
  104616. b[11] = (FLAC__byte)xx; xx >>= 8;
  104617. b[10] = (FLAC__byte)xx; xx >>= 8;
  104618. b[9] = (FLAC__byte)xx; xx >>= 8;
  104619. b[8] = (FLAC__byte)xx; xx >>= 8;
  104620. x = encoder->private_->seek_table->points[i].frame_samples;
  104621. b[17] = (FLAC__byte)x; x >>= 8;
  104622. b[16] = (FLAC__byte)x; x >>= 8;
  104623. if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104624. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104625. return;
  104626. }
  104627. }
  104628. }
  104629. }
  104630. #if FLAC__HAS_OGG
  104631. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  104632. void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
  104633. {
  104634. /* the # of bytes in the 1st packet that precede the STREAMINFO */
  104635. static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
  104636. FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
  104637. FLAC__OGG_MAPPING_MAGIC_LENGTH +
  104638. FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
  104639. FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
  104640. FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
  104641. FLAC__STREAM_SYNC_LENGTH
  104642. ;
  104643. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  104644. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  104645. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  104646. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  104647. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  104648. ogg_page page;
  104649. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  104650. FLAC__ASSERT(0 != encoder->private_->seek_callback);
  104651. /* Pre-check that client supports seeking, since we don't want the
  104652. * ogg_helper code to ever have to deal with this condition.
  104653. */
  104654. if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
  104655. return;
  104656. /* All this is based on intimate knowledge of the stream header
  104657. * layout, but a change to the header format that would break this
  104658. * would also break all streams encoded in the previous format.
  104659. */
  104660. /**
  104661. ** Write STREAMINFO stats
  104662. **/
  104663. simple_ogg_page__init(&page);
  104664. if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  104665. simple_ogg_page__clear(&page);
  104666. return; /* state already set */
  104667. }
  104668. /*
  104669. * Write MD5 signature
  104670. */
  104671. {
  104672. const unsigned md5_offset =
  104673. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104674. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104675. (
  104676. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104677. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104678. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104679. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104680. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104681. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104682. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  104683. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  104684. ) / 8;
  104685. if(md5_offset + 16 > (unsigned)page.body_len) {
  104686. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104687. simple_ogg_page__clear(&page);
  104688. return;
  104689. }
  104690. memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
  104691. }
  104692. /*
  104693. * Write total samples
  104694. */
  104695. {
  104696. const unsigned total_samples_byte_offset =
  104697. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104698. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104699. (
  104700. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104701. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104702. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104703. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104704. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104705. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104706. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  104707. - 4
  104708. ) / 8;
  104709. if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
  104710. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104711. simple_ogg_page__clear(&page);
  104712. return;
  104713. }
  104714. b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
  104715. b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
  104716. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  104717. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  104718. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  104719. b[4] = (FLAC__byte)(samples & 0xFF);
  104720. memcpy(page.body + total_samples_byte_offset, b, 5);
  104721. }
  104722. /*
  104723. * Write min/max framesize
  104724. */
  104725. {
  104726. const unsigned min_framesize_offset =
  104727. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104728. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104729. (
  104730. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104731. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  104732. ) / 8;
  104733. if(min_framesize_offset + 6 > (unsigned)page.body_len) {
  104734. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104735. simple_ogg_page__clear(&page);
  104736. return;
  104737. }
  104738. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  104739. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  104740. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  104741. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  104742. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  104743. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  104744. memcpy(page.body + min_framesize_offset, b, 6);
  104745. }
  104746. if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  104747. simple_ogg_page__clear(&page);
  104748. return; /* state already set */
  104749. }
  104750. simple_ogg_page__clear(&page);
  104751. /*
  104752. * Write seektable
  104753. */
  104754. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  104755. unsigned i;
  104756. FLAC__byte *p;
  104757. FLAC__format_seektable_sort(encoder->private_->seek_table);
  104758. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  104759. simple_ogg_page__init(&page);
  104760. if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  104761. simple_ogg_page__clear(&page);
  104762. return; /* state already set */
  104763. }
  104764. if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
  104765. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104766. simple_ogg_page__clear(&page);
  104767. return;
  104768. }
  104769. for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
  104770. FLAC__uint64 xx;
  104771. unsigned x;
  104772. xx = encoder->private_->seek_table->points[i].sample_number;
  104773. b[7] = (FLAC__byte)xx; xx >>= 8;
  104774. b[6] = (FLAC__byte)xx; xx >>= 8;
  104775. b[5] = (FLAC__byte)xx; xx >>= 8;
  104776. b[4] = (FLAC__byte)xx; xx >>= 8;
  104777. b[3] = (FLAC__byte)xx; xx >>= 8;
  104778. b[2] = (FLAC__byte)xx; xx >>= 8;
  104779. b[1] = (FLAC__byte)xx; xx >>= 8;
  104780. b[0] = (FLAC__byte)xx; xx >>= 8;
  104781. xx = encoder->private_->seek_table->points[i].stream_offset;
  104782. b[15] = (FLAC__byte)xx; xx >>= 8;
  104783. b[14] = (FLAC__byte)xx; xx >>= 8;
  104784. b[13] = (FLAC__byte)xx; xx >>= 8;
  104785. b[12] = (FLAC__byte)xx; xx >>= 8;
  104786. b[11] = (FLAC__byte)xx; xx >>= 8;
  104787. b[10] = (FLAC__byte)xx; xx >>= 8;
  104788. b[9] = (FLAC__byte)xx; xx >>= 8;
  104789. b[8] = (FLAC__byte)xx; xx >>= 8;
  104790. x = encoder->private_->seek_table->points[i].frame_samples;
  104791. b[17] = (FLAC__byte)x; x >>= 8;
  104792. b[16] = (FLAC__byte)x; x >>= 8;
  104793. memcpy(p, b, 18);
  104794. }
  104795. if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  104796. simple_ogg_page__clear(&page);
  104797. return; /* state already set */
  104798. }
  104799. simple_ogg_page__clear(&page);
  104800. }
  104801. }
  104802. #endif
  104803. FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
  104804. {
  104805. FLAC__uint16 crc;
  104806. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104807. /*
  104808. * Accumulate raw signal to the MD5 signature
  104809. */
  104810. 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)) {
  104811. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104812. return false;
  104813. }
  104814. /*
  104815. * Process the frame header and subframes into the frame bitbuffer
  104816. */
  104817. if(!process_subframes_(encoder, is_fractional_block)) {
  104818. /* the above function sets the state for us in case of an error */
  104819. return false;
  104820. }
  104821. /*
  104822. * Zero-pad the frame to a byte_boundary
  104823. */
  104824. if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
  104825. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104826. return false;
  104827. }
  104828. /*
  104829. * CRC-16 the whole thing
  104830. */
  104831. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  104832. if(
  104833. !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
  104834. !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
  104835. ) {
  104836. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104837. return false;
  104838. }
  104839. /*
  104840. * Write it
  104841. */
  104842. if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
  104843. /* the above function sets the state for us in case of an error */
  104844. return false;
  104845. }
  104846. /*
  104847. * Get ready for the next frame
  104848. */
  104849. encoder->private_->current_sample_number = 0;
  104850. encoder->private_->current_frame_number++;
  104851. encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
  104852. return true;
  104853. }
  104854. FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
  104855. {
  104856. FLAC__FrameHeader frame_header;
  104857. unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
  104858. FLAC__bool do_independent, do_mid_side;
  104859. /*
  104860. * Calculate the min,max Rice partition orders
  104861. */
  104862. if(is_fractional_block) {
  104863. max_partition_order = 0;
  104864. }
  104865. else {
  104866. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
  104867. max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order);
  104868. }
  104869. min_partition_order = min(min_partition_order, max_partition_order);
  104870. /*
  104871. * Setup the frame
  104872. */
  104873. frame_header.blocksize = encoder->protected_->blocksize;
  104874. frame_header.sample_rate = encoder->protected_->sample_rate;
  104875. frame_header.channels = encoder->protected_->channels;
  104876. frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
  104877. frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
  104878. frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  104879. frame_header.number.frame_number = encoder->private_->current_frame_number;
  104880. /*
  104881. * Figure out what channel assignments to try
  104882. */
  104883. if(encoder->protected_->do_mid_side_stereo) {
  104884. if(encoder->protected_->loose_mid_side_stereo) {
  104885. if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
  104886. do_independent = true;
  104887. do_mid_side = true;
  104888. }
  104889. else {
  104890. do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
  104891. do_mid_side = !do_independent;
  104892. }
  104893. }
  104894. else {
  104895. do_independent = true;
  104896. do_mid_side = true;
  104897. }
  104898. }
  104899. else {
  104900. do_independent = true;
  104901. do_mid_side = false;
  104902. }
  104903. FLAC__ASSERT(do_independent || do_mid_side);
  104904. /*
  104905. * Check for wasted bits; set effective bps for each subframe
  104906. */
  104907. if(do_independent) {
  104908. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104909. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
  104910. encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
  104911. encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
  104912. }
  104913. }
  104914. if(do_mid_side) {
  104915. FLAC__ASSERT(encoder->protected_->channels == 2);
  104916. for(channel = 0; channel < 2; channel++) {
  104917. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
  104918. encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
  104919. encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
  104920. }
  104921. }
  104922. /*
  104923. * First do a normal encoding pass of each independent channel
  104924. */
  104925. if(do_independent) {
  104926. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104927. if(!
  104928. process_subframe_(
  104929. encoder,
  104930. min_partition_order,
  104931. max_partition_order,
  104932. &frame_header,
  104933. encoder->private_->subframe_bps[channel],
  104934. encoder->private_->integer_signal[channel],
  104935. encoder->private_->subframe_workspace_ptr[channel],
  104936. encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
  104937. encoder->private_->residual_workspace[channel],
  104938. encoder->private_->best_subframe+channel,
  104939. encoder->private_->best_subframe_bits+channel
  104940. )
  104941. )
  104942. return false;
  104943. }
  104944. }
  104945. /*
  104946. * Now do mid and side channels if requested
  104947. */
  104948. if(do_mid_side) {
  104949. FLAC__ASSERT(encoder->protected_->channels == 2);
  104950. for(channel = 0; channel < 2; channel++) {
  104951. if(!
  104952. process_subframe_(
  104953. encoder,
  104954. min_partition_order,
  104955. max_partition_order,
  104956. &frame_header,
  104957. encoder->private_->subframe_bps_mid_side[channel],
  104958. encoder->private_->integer_signal_mid_side[channel],
  104959. encoder->private_->subframe_workspace_ptr_mid_side[channel],
  104960. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
  104961. encoder->private_->residual_workspace_mid_side[channel],
  104962. encoder->private_->best_subframe_mid_side+channel,
  104963. encoder->private_->best_subframe_bits_mid_side+channel
  104964. )
  104965. )
  104966. return false;
  104967. }
  104968. }
  104969. /*
  104970. * Compose the frame bitbuffer
  104971. */
  104972. if(do_mid_side) {
  104973. unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
  104974. FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
  104975. FLAC__ChannelAssignment channel_assignment;
  104976. FLAC__ASSERT(encoder->protected_->channels == 2);
  104977. if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
  104978. channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
  104979. }
  104980. else {
  104981. unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
  104982. unsigned min_bits;
  104983. int ca;
  104984. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
  104985. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE == 1);
  104986. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE == 2);
  104987. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE == 3);
  104988. FLAC__ASSERT(do_independent && do_mid_side);
  104989. /* We have to figure out which channel assignent results in the smallest frame */
  104990. bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits [1];
  104991. bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits_mid_side[1];
  104992. bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits [1] + encoder->private_->best_subframe_bits_mid_side[1];
  104993. bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
  104994. channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  104995. min_bits = bits[channel_assignment];
  104996. for(ca = 1; ca <= 3; ca++) {
  104997. if(bits[ca] < min_bits) {
  104998. min_bits = bits[ca];
  104999. channel_assignment = (FLAC__ChannelAssignment)ca;
  105000. }
  105001. }
  105002. }
  105003. frame_header.channel_assignment = channel_assignment;
  105004. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  105005. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105006. return false;
  105007. }
  105008. switch(channel_assignment) {
  105009. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  105010. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  105011. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  105012. break;
  105013. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  105014. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  105015. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  105016. break;
  105017. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  105018. left_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  105019. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  105020. break;
  105021. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  105022. left_subframe = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
  105023. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  105024. break;
  105025. default:
  105026. FLAC__ASSERT(0);
  105027. }
  105028. switch(channel_assignment) {
  105029. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  105030. left_bps = encoder->private_->subframe_bps [0];
  105031. right_bps = encoder->private_->subframe_bps [1];
  105032. break;
  105033. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  105034. left_bps = encoder->private_->subframe_bps [0];
  105035. right_bps = encoder->private_->subframe_bps_mid_side[1];
  105036. break;
  105037. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  105038. left_bps = encoder->private_->subframe_bps_mid_side[1];
  105039. right_bps = encoder->private_->subframe_bps [1];
  105040. break;
  105041. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  105042. left_bps = encoder->private_->subframe_bps_mid_side[0];
  105043. right_bps = encoder->private_->subframe_bps_mid_side[1];
  105044. break;
  105045. default:
  105046. FLAC__ASSERT(0);
  105047. }
  105048. /* note that encoder_add_subframe_ sets the state for us in case of an error */
  105049. if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
  105050. return false;
  105051. if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
  105052. return false;
  105053. }
  105054. else {
  105055. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  105056. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105057. return false;
  105058. }
  105059. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  105060. 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)) {
  105061. /* the above function sets the state for us in case of an error */
  105062. return false;
  105063. }
  105064. }
  105065. }
  105066. if(encoder->protected_->loose_mid_side_stereo) {
  105067. encoder->private_->loose_mid_side_stereo_frame_count++;
  105068. if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
  105069. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  105070. }
  105071. encoder->private_->last_channel_assignment = frame_header.channel_assignment;
  105072. return true;
  105073. }
  105074. FLAC__bool process_subframe_(
  105075. FLAC__StreamEncoder *encoder,
  105076. unsigned min_partition_order,
  105077. unsigned max_partition_order,
  105078. const FLAC__FrameHeader *frame_header,
  105079. unsigned subframe_bps,
  105080. const FLAC__int32 integer_signal[],
  105081. FLAC__Subframe *subframe[2],
  105082. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  105083. FLAC__int32 *residual[2],
  105084. unsigned *best_subframe,
  105085. unsigned *best_bits
  105086. )
  105087. {
  105088. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105089. FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  105090. #else
  105091. FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  105092. #endif
  105093. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105094. FLAC__double lpc_residual_bits_per_sample;
  105095. 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 */
  105096. FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
  105097. unsigned min_lpc_order, max_lpc_order, lpc_order;
  105098. unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
  105099. #endif
  105100. unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
  105101. unsigned rice_parameter;
  105102. unsigned _candidate_bits, _best_bits;
  105103. unsigned _best_subframe;
  105104. /* only use RICE2 partitions if stream bps > 16 */
  105105. 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;
  105106. FLAC__ASSERT(frame_header->blocksize > 0);
  105107. /* verbatim subframe is the baseline against which we measure other compressed subframes */
  105108. _best_subframe = 0;
  105109. if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
  105110. _best_bits = UINT_MAX;
  105111. else
  105112. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  105113. if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
  105114. unsigned signal_is_constant = false;
  105115. 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);
  105116. /* check for constant subframe */
  105117. if(
  105118. !encoder->private_->disable_constant_subframes &&
  105119. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105120. fixed_residual_bits_per_sample[1] == 0.0
  105121. #else
  105122. fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
  105123. #endif
  105124. ) {
  105125. /* the above means it's possible all samples are the same value; now double-check it: */
  105126. unsigned i;
  105127. signal_is_constant = true;
  105128. for(i = 1; i < frame_header->blocksize; i++) {
  105129. if(integer_signal[0] != integer_signal[i]) {
  105130. signal_is_constant = false;
  105131. break;
  105132. }
  105133. }
  105134. }
  105135. if(signal_is_constant) {
  105136. _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
  105137. if(_candidate_bits < _best_bits) {
  105138. _best_subframe = !_best_subframe;
  105139. _best_bits = _candidate_bits;
  105140. }
  105141. }
  105142. else {
  105143. if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
  105144. /* encode fixed */
  105145. if(encoder->protected_->do_exhaustive_model_search) {
  105146. min_fixed_order = 0;
  105147. max_fixed_order = FLAC__MAX_FIXED_ORDER;
  105148. }
  105149. else {
  105150. min_fixed_order = max_fixed_order = guess_fixed_order;
  105151. }
  105152. if(max_fixed_order >= frame_header->blocksize)
  105153. max_fixed_order = frame_header->blocksize - 1;
  105154. for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
  105155. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105156. if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
  105157. continue; /* don't even try */
  105158. 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 */
  105159. #else
  105160. if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
  105161. continue; /* don't even try */
  105162. 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 */
  105163. #endif
  105164. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  105165. if(rice_parameter >= rice_parameter_limit) {
  105166. #ifdef DEBUG_VERBOSE
  105167. fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, rice_parameter_limit - 1);
  105168. #endif
  105169. rice_parameter = rice_parameter_limit - 1;
  105170. }
  105171. _candidate_bits =
  105172. evaluate_fixed_subframe_(
  105173. encoder,
  105174. integer_signal,
  105175. residual[!_best_subframe],
  105176. encoder->private_->abs_residual_partition_sums,
  105177. encoder->private_->raw_bits_per_partition,
  105178. frame_header->blocksize,
  105179. subframe_bps,
  105180. fixed_order,
  105181. rice_parameter,
  105182. rice_parameter_limit,
  105183. min_partition_order,
  105184. max_partition_order,
  105185. encoder->protected_->do_escape_coding,
  105186. encoder->protected_->rice_parameter_search_dist,
  105187. subframe[!_best_subframe],
  105188. partitioned_rice_contents[!_best_subframe]
  105189. );
  105190. if(_candidate_bits < _best_bits) {
  105191. _best_subframe = !_best_subframe;
  105192. _best_bits = _candidate_bits;
  105193. }
  105194. }
  105195. }
  105196. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105197. /* encode lpc */
  105198. if(encoder->protected_->max_lpc_order > 0) {
  105199. if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
  105200. max_lpc_order = frame_header->blocksize-1;
  105201. else
  105202. max_lpc_order = encoder->protected_->max_lpc_order;
  105203. if(max_lpc_order > 0) {
  105204. unsigned a;
  105205. for (a = 0; a < encoder->protected_->num_apodizations; a++) {
  105206. FLAC__lpc_window_data(integer_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
  105207. encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
  105208. /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
  105209. if(autoc[0] != 0.0) {
  105210. FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
  105211. if(encoder->protected_->do_exhaustive_model_search) {
  105212. min_lpc_order = 1;
  105213. }
  105214. else {
  105215. const unsigned guess_lpc_order =
  105216. FLAC__lpc_compute_best_order(
  105217. lpc_error,
  105218. max_lpc_order,
  105219. frame_header->blocksize,
  105220. subframe_bps + (
  105221. encoder->protected_->do_qlp_coeff_prec_search?
  105222. FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
  105223. encoder->protected_->qlp_coeff_precision
  105224. )
  105225. );
  105226. min_lpc_order = max_lpc_order = guess_lpc_order;
  105227. }
  105228. if(max_lpc_order >= frame_header->blocksize)
  105229. max_lpc_order = frame_header->blocksize - 1;
  105230. for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
  105231. lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
  105232. if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
  105233. continue; /* don't even try */
  105234. rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
  105235. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  105236. if(rice_parameter >= rice_parameter_limit) {
  105237. #ifdef DEBUG_VERBOSE
  105238. fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, rice_parameter_limit - 1);
  105239. #endif
  105240. rice_parameter = rice_parameter_limit - 1;
  105241. }
  105242. if(encoder->protected_->do_qlp_coeff_prec_search) {
  105243. min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
  105244. /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
  105245. if(subframe_bps <= 17) {
  105246. max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
  105247. max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision);
  105248. }
  105249. else
  105250. max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  105251. }
  105252. else {
  105253. min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
  105254. }
  105255. for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
  105256. _candidate_bits =
  105257. evaluate_lpc_subframe_(
  105258. encoder,
  105259. integer_signal,
  105260. residual[!_best_subframe],
  105261. encoder->private_->abs_residual_partition_sums,
  105262. encoder->private_->raw_bits_per_partition,
  105263. encoder->private_->lp_coeff[lpc_order-1],
  105264. frame_header->blocksize,
  105265. subframe_bps,
  105266. lpc_order,
  105267. qlp_coeff_precision,
  105268. rice_parameter,
  105269. rice_parameter_limit,
  105270. min_partition_order,
  105271. max_partition_order,
  105272. encoder->protected_->do_escape_coding,
  105273. encoder->protected_->rice_parameter_search_dist,
  105274. subframe[!_best_subframe],
  105275. partitioned_rice_contents[!_best_subframe]
  105276. );
  105277. if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
  105278. if(_candidate_bits < _best_bits) {
  105279. _best_subframe = !_best_subframe;
  105280. _best_bits = _candidate_bits;
  105281. }
  105282. }
  105283. }
  105284. }
  105285. }
  105286. }
  105287. }
  105288. }
  105289. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  105290. }
  105291. }
  105292. /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
  105293. if(_best_bits == UINT_MAX) {
  105294. FLAC__ASSERT(_best_subframe == 0);
  105295. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  105296. }
  105297. *best_subframe = _best_subframe;
  105298. *best_bits = _best_bits;
  105299. return true;
  105300. }
  105301. FLAC__bool add_subframe_(
  105302. FLAC__StreamEncoder *encoder,
  105303. unsigned blocksize,
  105304. unsigned subframe_bps,
  105305. const FLAC__Subframe *subframe,
  105306. FLAC__BitWriter *frame
  105307. )
  105308. {
  105309. switch(subframe->type) {
  105310. case FLAC__SUBFRAME_TYPE_CONSTANT:
  105311. if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
  105312. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105313. return false;
  105314. }
  105315. break;
  105316. case FLAC__SUBFRAME_TYPE_FIXED:
  105317. if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
  105318. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105319. return false;
  105320. }
  105321. break;
  105322. case FLAC__SUBFRAME_TYPE_LPC:
  105323. if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
  105324. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105325. return false;
  105326. }
  105327. break;
  105328. case FLAC__SUBFRAME_TYPE_VERBATIM:
  105329. if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
  105330. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105331. return false;
  105332. }
  105333. break;
  105334. default:
  105335. FLAC__ASSERT(0);
  105336. }
  105337. return true;
  105338. }
  105339. #define SPOTCHECK_ESTIMATE 0
  105340. #if SPOTCHECK_ESTIMATE
  105341. static void spotcheck_subframe_estimate_(
  105342. FLAC__StreamEncoder *encoder,
  105343. unsigned blocksize,
  105344. unsigned subframe_bps,
  105345. const FLAC__Subframe *subframe,
  105346. unsigned estimate
  105347. )
  105348. {
  105349. FLAC__bool ret;
  105350. FLAC__BitWriter *frame = FLAC__bitwriter_new();
  105351. if(frame == 0) {
  105352. fprintf(stderr, "EST: can't allocate frame\n");
  105353. return;
  105354. }
  105355. if(!FLAC__bitwriter_init(frame)) {
  105356. fprintf(stderr, "EST: can't init frame\n");
  105357. return;
  105358. }
  105359. ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
  105360. FLAC__ASSERT(ret);
  105361. {
  105362. const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
  105363. if(estimate != actual)
  105364. 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);
  105365. }
  105366. FLAC__bitwriter_delete(frame);
  105367. }
  105368. #endif
  105369. unsigned evaluate_constant_subframe_(
  105370. FLAC__StreamEncoder *encoder,
  105371. const FLAC__int32 signal,
  105372. unsigned blocksize,
  105373. unsigned subframe_bps,
  105374. FLAC__Subframe *subframe
  105375. )
  105376. {
  105377. unsigned estimate;
  105378. subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
  105379. subframe->data.constant.value = signal;
  105380. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
  105381. #if SPOTCHECK_ESTIMATE
  105382. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105383. #else
  105384. (void)encoder, (void)blocksize;
  105385. #endif
  105386. return estimate;
  105387. }
  105388. unsigned evaluate_fixed_subframe_(
  105389. FLAC__StreamEncoder *encoder,
  105390. const FLAC__int32 signal[],
  105391. FLAC__int32 residual[],
  105392. FLAC__uint64 abs_residual_partition_sums[],
  105393. unsigned raw_bits_per_partition[],
  105394. unsigned blocksize,
  105395. unsigned subframe_bps,
  105396. unsigned order,
  105397. unsigned rice_parameter,
  105398. unsigned rice_parameter_limit,
  105399. unsigned min_partition_order,
  105400. unsigned max_partition_order,
  105401. FLAC__bool do_escape_coding,
  105402. unsigned rice_parameter_search_dist,
  105403. FLAC__Subframe *subframe,
  105404. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  105405. )
  105406. {
  105407. unsigned i, residual_bits, estimate;
  105408. const unsigned residual_samples = blocksize - order;
  105409. FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
  105410. subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
  105411. subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  105412. subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  105413. subframe->data.fixed.residual = residual;
  105414. residual_bits =
  105415. find_best_partition_order_(
  105416. encoder->private_,
  105417. residual,
  105418. abs_residual_partition_sums,
  105419. raw_bits_per_partition,
  105420. residual_samples,
  105421. order,
  105422. rice_parameter,
  105423. rice_parameter_limit,
  105424. min_partition_order,
  105425. max_partition_order,
  105426. subframe_bps,
  105427. do_escape_coding,
  105428. rice_parameter_search_dist,
  105429. &subframe->data.fixed.entropy_coding_method
  105430. );
  105431. subframe->data.fixed.order = order;
  105432. for(i = 0; i < order; i++)
  105433. subframe->data.fixed.warmup[i] = signal[i];
  105434. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
  105435. #if SPOTCHECK_ESTIMATE
  105436. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105437. #endif
  105438. return estimate;
  105439. }
  105440. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105441. unsigned evaluate_lpc_subframe_(
  105442. FLAC__StreamEncoder *encoder,
  105443. const FLAC__int32 signal[],
  105444. FLAC__int32 residual[],
  105445. FLAC__uint64 abs_residual_partition_sums[],
  105446. unsigned raw_bits_per_partition[],
  105447. const FLAC__real lp_coeff[],
  105448. unsigned blocksize,
  105449. unsigned subframe_bps,
  105450. unsigned order,
  105451. unsigned qlp_coeff_precision,
  105452. unsigned rice_parameter,
  105453. unsigned rice_parameter_limit,
  105454. unsigned min_partition_order,
  105455. unsigned max_partition_order,
  105456. FLAC__bool do_escape_coding,
  105457. unsigned rice_parameter_search_dist,
  105458. FLAC__Subframe *subframe,
  105459. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  105460. )
  105461. {
  105462. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  105463. unsigned i, residual_bits, estimate;
  105464. int quantization, ret;
  105465. const unsigned residual_samples = blocksize - order;
  105466. /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
  105467. if(subframe_bps <= 16) {
  105468. FLAC__ASSERT(order > 0);
  105469. FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
  105470. qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
  105471. }
  105472. ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
  105473. if(ret != 0)
  105474. return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
  105475. if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  105476. if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
  105477. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105478. else
  105479. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105480. else
  105481. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105482. subframe->type = FLAC__SUBFRAME_TYPE_LPC;
  105483. subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  105484. subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  105485. subframe->data.lpc.residual = residual;
  105486. residual_bits =
  105487. find_best_partition_order_(
  105488. encoder->private_,
  105489. residual,
  105490. abs_residual_partition_sums,
  105491. raw_bits_per_partition,
  105492. residual_samples,
  105493. order,
  105494. rice_parameter,
  105495. rice_parameter_limit,
  105496. min_partition_order,
  105497. max_partition_order,
  105498. subframe_bps,
  105499. do_escape_coding,
  105500. rice_parameter_search_dist,
  105501. &subframe->data.lpc.entropy_coding_method
  105502. );
  105503. subframe->data.lpc.order = order;
  105504. subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
  105505. subframe->data.lpc.quantization_level = quantization;
  105506. memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
  105507. for(i = 0; i < order; i++)
  105508. subframe->data.lpc.warmup[i] = signal[i];
  105509. 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;
  105510. #if SPOTCHECK_ESTIMATE
  105511. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105512. #endif
  105513. return estimate;
  105514. }
  105515. #endif
  105516. unsigned evaluate_verbatim_subframe_(
  105517. FLAC__StreamEncoder *encoder,
  105518. const FLAC__int32 signal[],
  105519. unsigned blocksize,
  105520. unsigned subframe_bps,
  105521. FLAC__Subframe *subframe
  105522. )
  105523. {
  105524. unsigned estimate;
  105525. subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
  105526. subframe->data.verbatim.data = signal;
  105527. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
  105528. #if SPOTCHECK_ESTIMATE
  105529. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105530. #else
  105531. (void)encoder;
  105532. #endif
  105533. return estimate;
  105534. }
  105535. unsigned find_best_partition_order_(
  105536. FLAC__StreamEncoderPrivate *private_,
  105537. const FLAC__int32 residual[],
  105538. FLAC__uint64 abs_residual_partition_sums[],
  105539. unsigned raw_bits_per_partition[],
  105540. unsigned residual_samples,
  105541. unsigned predictor_order,
  105542. unsigned rice_parameter,
  105543. unsigned rice_parameter_limit,
  105544. unsigned min_partition_order,
  105545. unsigned max_partition_order,
  105546. unsigned bps,
  105547. FLAC__bool do_escape_coding,
  105548. unsigned rice_parameter_search_dist,
  105549. FLAC__EntropyCodingMethod *best_ecm
  105550. )
  105551. {
  105552. unsigned residual_bits, best_residual_bits = 0;
  105553. unsigned best_parameters_index = 0;
  105554. unsigned best_partition_order = 0;
  105555. const unsigned blocksize = residual_samples + predictor_order;
  105556. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
  105557. min_partition_order = min(min_partition_order, max_partition_order);
  105558. precompute_partition_info_sums_(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order, bps);
  105559. if(do_escape_coding)
  105560. precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
  105561. {
  105562. int partition_order;
  105563. unsigned sum;
  105564. for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
  105565. if(!
  105566. set_partitioned_rice_(
  105567. #ifdef EXACT_RICE_BITS_CALCULATION
  105568. residual,
  105569. #endif
  105570. abs_residual_partition_sums+sum,
  105571. raw_bits_per_partition+sum,
  105572. residual_samples,
  105573. predictor_order,
  105574. rice_parameter,
  105575. rice_parameter_limit,
  105576. rice_parameter_search_dist,
  105577. (unsigned)partition_order,
  105578. do_escape_coding,
  105579. &private_->partitioned_rice_contents_extra[!best_parameters_index],
  105580. &residual_bits
  105581. )
  105582. )
  105583. {
  105584. FLAC__ASSERT(best_residual_bits != 0);
  105585. break;
  105586. }
  105587. sum += 1u << partition_order;
  105588. if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
  105589. best_residual_bits = residual_bits;
  105590. best_parameters_index = !best_parameters_index;
  105591. best_partition_order = partition_order;
  105592. }
  105593. }
  105594. }
  105595. best_ecm->data.partitioned_rice.order = best_partition_order;
  105596. {
  105597. /*
  105598. * We are allowed to de-const the pointer based on our special
  105599. * knowledge; it is const to the outside world.
  105600. */
  105601. FLAC__EntropyCodingMethod_PartitionedRiceContents* prc = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_ecm->data.partitioned_rice.contents;
  105602. unsigned partition;
  105603. /* save best parameters and raw_bits */
  105604. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(prc, max(6, best_partition_order));
  105605. memcpy(prc->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partition_order)));
  105606. if(do_escape_coding)
  105607. memcpy(prc->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partition_order)));
  105608. /*
  105609. * Now need to check if the type should be changed to
  105610. * FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 based on the
  105611. * size of the rice parameters.
  105612. */
  105613. for(partition = 0; partition < (1u<<best_partition_order); partition++) {
  105614. if(prc->parameters[partition] >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
  105615. best_ecm->type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2;
  105616. break;
  105617. }
  105618. }
  105619. }
  105620. return best_residual_bits;
  105621. }
  105622. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  105623. extern void precompute_partition_info_sums_32bit_asm_ia32_(
  105624. const FLAC__int32 residual[],
  105625. FLAC__uint64 abs_residual_partition_sums[],
  105626. unsigned blocksize,
  105627. unsigned predictor_order,
  105628. unsigned min_partition_order,
  105629. unsigned max_partition_order
  105630. );
  105631. #endif
  105632. void precompute_partition_info_sums_(
  105633. const FLAC__int32 residual[],
  105634. FLAC__uint64 abs_residual_partition_sums[],
  105635. unsigned residual_samples,
  105636. unsigned predictor_order,
  105637. unsigned min_partition_order,
  105638. unsigned max_partition_order,
  105639. unsigned bps
  105640. )
  105641. {
  105642. const unsigned default_partition_samples = (residual_samples + predictor_order) >> max_partition_order;
  105643. unsigned partitions = 1u << max_partition_order;
  105644. FLAC__ASSERT(default_partition_samples > predictor_order);
  105645. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  105646. /* slightly pessimistic but still catches all common cases */
  105647. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  105648. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  105649. precompute_partition_info_sums_32bit_asm_ia32_(residual, abs_residual_partition_sums, residual_samples + predictor_order, predictor_order, min_partition_order, max_partition_order);
  105650. return;
  105651. }
  105652. #endif
  105653. /* first do max_partition_order */
  105654. {
  105655. unsigned partition, residual_sample, end = (unsigned)(-(int)predictor_order);
  105656. /* slightly pessimistic but still catches all common cases */
  105657. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  105658. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  105659. FLAC__uint32 abs_residual_partition_sum;
  105660. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105661. end += default_partition_samples;
  105662. abs_residual_partition_sum = 0;
  105663. for( ; residual_sample < end; residual_sample++)
  105664. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  105665. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  105666. }
  105667. }
  105668. else { /* have to pessimistically use 64 bits for accumulator */
  105669. FLAC__uint64 abs_residual_partition_sum;
  105670. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105671. end += default_partition_samples;
  105672. abs_residual_partition_sum = 0;
  105673. for( ; residual_sample < end; residual_sample++)
  105674. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  105675. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  105676. }
  105677. }
  105678. }
  105679. /* now merge partitions for lower orders */
  105680. {
  105681. unsigned from_partition = 0, to_partition = partitions;
  105682. int partition_order;
  105683. for(partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
  105684. unsigned i;
  105685. partitions >>= 1;
  105686. for(i = 0; i < partitions; i++) {
  105687. abs_residual_partition_sums[to_partition++] =
  105688. abs_residual_partition_sums[from_partition ] +
  105689. abs_residual_partition_sums[from_partition+1];
  105690. from_partition += 2;
  105691. }
  105692. }
  105693. }
  105694. }
  105695. void precompute_partition_info_escapes_(
  105696. const FLAC__int32 residual[],
  105697. unsigned raw_bits_per_partition[],
  105698. unsigned residual_samples,
  105699. unsigned predictor_order,
  105700. unsigned min_partition_order,
  105701. unsigned max_partition_order
  105702. )
  105703. {
  105704. int partition_order;
  105705. unsigned from_partition, to_partition = 0;
  105706. const unsigned blocksize = residual_samples + predictor_order;
  105707. /* first do max_partition_order */
  105708. for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
  105709. FLAC__int32 r;
  105710. FLAC__uint32 rmax;
  105711. unsigned partition, partition_sample, partition_samples, residual_sample;
  105712. const unsigned partitions = 1u << partition_order;
  105713. const unsigned default_partition_samples = blocksize >> partition_order;
  105714. FLAC__ASSERT(default_partition_samples > predictor_order);
  105715. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105716. partition_samples = default_partition_samples;
  105717. if(partition == 0)
  105718. partition_samples -= predictor_order;
  105719. rmax = 0;
  105720. for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
  105721. r = residual[residual_sample++];
  105722. /* OPT: maybe faster: rmax |= r ^ (r>>31) */
  105723. if(r < 0)
  105724. rmax |= ~r;
  105725. else
  105726. rmax |= r;
  105727. }
  105728. /* now we know all residual values are in the range [-rmax-1,rmax] */
  105729. raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
  105730. }
  105731. to_partition = partitions;
  105732. break; /*@@@ yuck, should remove the 'for' loop instead */
  105733. }
  105734. /* now merge partitions for lower orders */
  105735. for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
  105736. unsigned m;
  105737. unsigned i;
  105738. const unsigned partitions = 1u << partition_order;
  105739. for(i = 0; i < partitions; i++) {
  105740. m = raw_bits_per_partition[from_partition];
  105741. from_partition++;
  105742. raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
  105743. from_partition++;
  105744. to_partition++;
  105745. }
  105746. }
  105747. }
  105748. #ifdef EXACT_RICE_BITS_CALCULATION
  105749. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  105750. const unsigned rice_parameter,
  105751. const unsigned partition_samples,
  105752. const FLAC__int32 *residual
  105753. )
  105754. {
  105755. unsigned i, partition_bits =
  105756. 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 */
  105757. (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
  105758. ;
  105759. for(i = 0; i < partition_samples; i++)
  105760. partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
  105761. return partition_bits;
  105762. }
  105763. #else
  105764. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  105765. const unsigned rice_parameter,
  105766. const unsigned partition_samples,
  105767. const FLAC__uint64 abs_residual_partition_sum
  105768. )
  105769. {
  105770. return
  105771. 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 */
  105772. (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
  105773. (
  105774. rice_parameter?
  105775. (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
  105776. : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
  105777. )
  105778. - (partition_samples >> 1)
  105779. /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
  105780. * The actual number of bits used is closer to the sum(for all i in the partition) of abs(residual[i])>>(rice_parameter-1)
  105781. * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
  105782. * So the subtraction term tries to guess how many extra bits were contributed.
  105783. * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
  105784. */
  105785. ;
  105786. }
  105787. #endif
  105788. FLAC__bool set_partitioned_rice_(
  105789. #ifdef EXACT_RICE_BITS_CALCULATION
  105790. const FLAC__int32 residual[],
  105791. #endif
  105792. const FLAC__uint64 abs_residual_partition_sums[],
  105793. const unsigned raw_bits_per_partition[],
  105794. const unsigned residual_samples,
  105795. const unsigned predictor_order,
  105796. const unsigned suggested_rice_parameter,
  105797. const unsigned rice_parameter_limit,
  105798. const unsigned rice_parameter_search_dist,
  105799. const unsigned partition_order,
  105800. const FLAC__bool search_for_escapes,
  105801. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  105802. unsigned *bits
  105803. )
  105804. {
  105805. unsigned rice_parameter, partition_bits;
  105806. unsigned best_partition_bits, best_rice_parameter = 0;
  105807. unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
  105808. unsigned *parameters, *raw_bits;
  105809. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105810. unsigned min_rice_parameter, max_rice_parameter;
  105811. #else
  105812. (void)rice_parameter_search_dist;
  105813. #endif
  105814. FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  105815. FLAC__ASSERT(rice_parameter_limit <= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  105816. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
  105817. parameters = partitioned_rice_contents->parameters;
  105818. raw_bits = partitioned_rice_contents->raw_bits;
  105819. if(partition_order == 0) {
  105820. best_partition_bits = (unsigned)(-1);
  105821. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105822. if(rice_parameter_search_dist) {
  105823. if(suggested_rice_parameter < rice_parameter_search_dist)
  105824. min_rice_parameter = 0;
  105825. else
  105826. min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
  105827. max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
  105828. if(max_rice_parameter >= rice_parameter_limit) {
  105829. #ifdef DEBUG_VERBOSE
  105830. fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, rice_parameter_limit - 1);
  105831. #endif
  105832. max_rice_parameter = rice_parameter_limit - 1;
  105833. }
  105834. }
  105835. else
  105836. min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
  105837. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  105838. #else
  105839. rice_parameter = suggested_rice_parameter;
  105840. #endif
  105841. #ifdef EXACT_RICE_BITS_CALCULATION
  105842. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
  105843. #else
  105844. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
  105845. #endif
  105846. if(partition_bits < best_partition_bits) {
  105847. best_rice_parameter = rice_parameter;
  105848. best_partition_bits = partition_bits;
  105849. }
  105850. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105851. }
  105852. #endif
  105853. if(search_for_escapes) {
  105854. 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;
  105855. if(partition_bits <= best_partition_bits) {
  105856. raw_bits[0] = raw_bits_per_partition[0];
  105857. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  105858. best_partition_bits = partition_bits;
  105859. }
  105860. else
  105861. raw_bits[0] = 0;
  105862. }
  105863. parameters[0] = best_rice_parameter;
  105864. bits_ += best_partition_bits;
  105865. }
  105866. else {
  105867. unsigned partition, residual_sample;
  105868. unsigned partition_samples;
  105869. FLAC__uint64 mean, k;
  105870. const unsigned partitions = 1u << partition_order;
  105871. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105872. partition_samples = (residual_samples+predictor_order) >> partition_order;
  105873. if(partition == 0) {
  105874. if(partition_samples <= predictor_order)
  105875. return false;
  105876. else
  105877. partition_samples -= predictor_order;
  105878. }
  105879. mean = abs_residual_partition_sums[partition];
  105880. /* we are basically calculating the size in bits of the
  105881. * average residual magnitude in the partition:
  105882. * rice_parameter = floor(log2(mean/partition_samples))
  105883. * 'mean' is not a good name for the variable, it is
  105884. * actually the sum of magnitudes of all residual values
  105885. * in the partition, so the actual mean is
  105886. * mean/partition_samples
  105887. */
  105888. for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
  105889. ;
  105890. if(rice_parameter >= rice_parameter_limit) {
  105891. #ifdef DEBUG_VERBOSE
  105892. fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, rice_parameter_limit - 1);
  105893. #endif
  105894. rice_parameter = rice_parameter_limit - 1;
  105895. }
  105896. best_partition_bits = (unsigned)(-1);
  105897. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105898. if(rice_parameter_search_dist) {
  105899. if(rice_parameter < rice_parameter_search_dist)
  105900. min_rice_parameter = 0;
  105901. else
  105902. min_rice_parameter = rice_parameter - rice_parameter_search_dist;
  105903. max_rice_parameter = rice_parameter + rice_parameter_search_dist;
  105904. if(max_rice_parameter >= rice_parameter_limit) {
  105905. #ifdef DEBUG_VERBOSE
  105906. fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, rice_parameter_limit - 1);
  105907. #endif
  105908. max_rice_parameter = rice_parameter_limit - 1;
  105909. }
  105910. }
  105911. else
  105912. min_rice_parameter = max_rice_parameter = rice_parameter;
  105913. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  105914. #endif
  105915. #ifdef EXACT_RICE_BITS_CALCULATION
  105916. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
  105917. #else
  105918. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
  105919. #endif
  105920. if(partition_bits < best_partition_bits) {
  105921. best_rice_parameter = rice_parameter;
  105922. best_partition_bits = partition_bits;
  105923. }
  105924. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105925. }
  105926. #endif
  105927. if(search_for_escapes) {
  105928. 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;
  105929. if(partition_bits <= best_partition_bits) {
  105930. raw_bits[partition] = raw_bits_per_partition[partition];
  105931. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  105932. best_partition_bits = partition_bits;
  105933. }
  105934. else
  105935. raw_bits[partition] = 0;
  105936. }
  105937. parameters[partition] = best_rice_parameter;
  105938. bits_ += best_partition_bits;
  105939. residual_sample += partition_samples;
  105940. }
  105941. }
  105942. *bits = bits_;
  105943. return true;
  105944. }
  105945. unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
  105946. {
  105947. unsigned i, shift;
  105948. FLAC__int32 x = 0;
  105949. for(i = 0; i < samples && !(x&1); i++)
  105950. x |= signal[i];
  105951. if(x == 0) {
  105952. shift = 0;
  105953. }
  105954. else {
  105955. for(shift = 0; !(x&1); shift++)
  105956. x >>= 1;
  105957. }
  105958. if(shift > 0) {
  105959. for(i = 0; i < samples; i++)
  105960. signal[i] >>= shift;
  105961. }
  105962. return shift;
  105963. }
  105964. void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  105965. {
  105966. unsigned channel;
  105967. for(channel = 0; channel < channels; channel++)
  105968. memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
  105969. fifo->tail += wide_samples;
  105970. FLAC__ASSERT(fifo->tail <= fifo->size);
  105971. }
  105972. void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  105973. {
  105974. unsigned channel;
  105975. unsigned sample, wide_sample;
  105976. unsigned tail = fifo->tail;
  105977. sample = input_offset * channels;
  105978. for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
  105979. for(channel = 0; channel < channels; channel++)
  105980. fifo->data[channel][tail] = input[sample++];
  105981. tail++;
  105982. }
  105983. fifo->tail = tail;
  105984. FLAC__ASSERT(fifo->tail <= fifo->size);
  105985. }
  105986. FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  105987. {
  105988. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  105989. const size_t encoded_bytes = encoder->private_->verify.output.bytes;
  105990. (void)decoder;
  105991. if(encoder->private_->verify.needs_magic_hack) {
  105992. FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
  105993. *bytes = FLAC__STREAM_SYNC_LENGTH;
  105994. memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
  105995. encoder->private_->verify.needs_magic_hack = false;
  105996. }
  105997. else {
  105998. if(encoded_bytes == 0) {
  105999. /*
  106000. * If we get here, a FIFO underflow has occurred,
  106001. * which means there is a bug somewhere.
  106002. */
  106003. FLAC__ASSERT(0);
  106004. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  106005. }
  106006. else if(encoded_bytes < *bytes)
  106007. *bytes = encoded_bytes;
  106008. memcpy(buffer, encoder->private_->verify.output.data, *bytes);
  106009. encoder->private_->verify.output.data += *bytes;
  106010. encoder->private_->verify.output.bytes -= *bytes;
  106011. }
  106012. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  106013. }
  106014. FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
  106015. {
  106016. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
  106017. unsigned channel;
  106018. const unsigned channels = frame->header.channels;
  106019. const unsigned blocksize = frame->header.blocksize;
  106020. const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
  106021. (void)decoder;
  106022. for(channel = 0; channel < channels; channel++) {
  106023. if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
  106024. unsigned i, sample = 0;
  106025. FLAC__int32 expect = 0, got = 0;
  106026. for(i = 0; i < blocksize; i++) {
  106027. if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
  106028. sample = i;
  106029. expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
  106030. got = (FLAC__int32)buffer[channel][i];
  106031. break;
  106032. }
  106033. }
  106034. FLAC__ASSERT(i < blocksize);
  106035. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  106036. encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
  106037. encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
  106038. encoder->private_->verify.error_stats.channel = channel;
  106039. encoder->private_->verify.error_stats.sample = sample;
  106040. encoder->private_->verify.error_stats.expected = expect;
  106041. encoder->private_->verify.error_stats.got = got;
  106042. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  106043. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  106044. }
  106045. }
  106046. /* dequeue the frame from the fifo */
  106047. encoder->private_->verify.input_fifo.tail -= blocksize;
  106048. FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
  106049. for(channel = 0; channel < channels; channel++)
  106050. 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]));
  106051. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  106052. }
  106053. void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
  106054. {
  106055. (void)decoder, (void)metadata, (void)client_data;
  106056. }
  106057. void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
  106058. {
  106059. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  106060. (void)decoder, (void)status;
  106061. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  106062. }
  106063. FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  106064. {
  106065. (void)client_data;
  106066. *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
  106067. if (*bytes == 0) {
  106068. if (feof(encoder->private_->file))
  106069. return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  106070. else if (ferror(encoder->private_->file))
  106071. return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  106072. }
  106073. return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  106074. }
  106075. FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  106076. {
  106077. (void)client_data;
  106078. if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  106079. return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  106080. else
  106081. return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  106082. }
  106083. FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  106084. {
  106085. off_t offset;
  106086. (void)client_data;
  106087. offset = ftello(encoder->private_->file);
  106088. if(offset < 0) {
  106089. return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  106090. }
  106091. else {
  106092. *absolute_byte_offset = (FLAC__uint64)offset;
  106093. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  106094. }
  106095. }
  106096. #ifdef FLAC__VALGRIND_TESTING
  106097. static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
  106098. {
  106099. size_t ret = fwrite(ptr, size, nmemb, stream);
  106100. if(!ferror(stream))
  106101. fflush(stream);
  106102. return ret;
  106103. }
  106104. #else
  106105. #define local__fwrite fwrite
  106106. #endif
  106107. FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
  106108. {
  106109. (void)client_data, (void)current_frame;
  106110. if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
  106111. FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
  106112. #if FLAC__HAS_OGG
  106113. /* We would like to be able to use 'samples > 0' in the
  106114. * clause here but currently because of the nature of our
  106115. * Ogg writing implementation, 'samples' is always 0 (see
  106116. * ogg_encoder_aspect.c). The downside is extra progress
  106117. * callbacks.
  106118. */
  106119. encoder->private_->is_ogg? true :
  106120. #endif
  106121. samples > 0
  106122. );
  106123. if(call_it) {
  106124. /* NOTE: We have to add +bytes, +samples, and +1 to the stats
  106125. * because at this point in the callback chain, the stats
  106126. * have not been updated. Only after we return and control
  106127. * gets back to write_frame_() are the stats updated
  106128. */
  106129. 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);
  106130. }
  106131. return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
  106132. }
  106133. else
  106134. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  106135. }
  106136. /*
  106137. * This will forcibly set stdout to binary mode (for OSes that require it)
  106138. */
  106139. FILE *get_binary_stdout_(void)
  106140. {
  106141. /* if something breaks here it is probably due to the presence or
  106142. * absence of an underscore before the identifiers 'setmode',
  106143. * 'fileno', and/or 'O_BINARY'; check your system header files.
  106144. */
  106145. #if defined _MSC_VER || defined __MINGW32__
  106146. _setmode(_fileno(stdout), _O_BINARY);
  106147. #elif defined __CYGWIN__
  106148. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  106149. setmode(_fileno(stdout), _O_BINARY);
  106150. #elif defined __EMX__
  106151. setmode(fileno(stdout), O_BINARY);
  106152. #endif
  106153. return stdout;
  106154. }
  106155. #endif
  106156. /*** End of inlined file: stream_encoder.c ***/
  106157. /*** Start of inlined file: stream_encoder_framing.c ***/
  106158. /*** Start of inlined file: juce_FlacHeader.h ***/
  106159. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  106160. // tasks..
  106161. #define VERSION "1.2.1"
  106162. #define FLAC__NO_DLL 1
  106163. #if JUCE_MSVC
  106164. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  106165. #endif
  106166. #if JUCE_MAC
  106167. #define FLAC__SYS_DARWIN 1
  106168. #endif
  106169. /*** End of inlined file: juce_FlacHeader.h ***/
  106170. #if JUCE_USE_FLAC
  106171. #if HAVE_CONFIG_H
  106172. # include <config.h>
  106173. #endif
  106174. #include <stdio.h>
  106175. #include <string.h> /* for strlen() */
  106176. #ifdef max
  106177. #undef max
  106178. #endif
  106179. #define max(x,y) ((x)>(y)?(x):(y))
  106180. static FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method);
  106181. 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);
  106182. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw)
  106183. {
  106184. unsigned i, j;
  106185. const unsigned vendor_string_length = (unsigned)strlen(FLAC__VENDOR_STRING);
  106186. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->is_last, FLAC__STREAM_METADATA_IS_LAST_LEN))
  106187. return false;
  106188. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->type, FLAC__STREAM_METADATA_TYPE_LEN))
  106189. return false;
  106190. /*
  106191. * First, for VORBIS_COMMENTs, adjust the length to reflect our vendor string
  106192. */
  106193. i = metadata->length;
  106194. if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  106195. FLAC__ASSERT(metadata->data.vorbis_comment.vendor_string.length == 0 || 0 != metadata->data.vorbis_comment.vendor_string.entry);
  106196. i -= metadata->data.vorbis_comment.vendor_string.length;
  106197. i += vendor_string_length;
  106198. }
  106199. FLAC__ASSERT(i < (1u << FLAC__STREAM_METADATA_LENGTH_LEN));
  106200. if(!FLAC__bitwriter_write_raw_uint32(bw, i, FLAC__STREAM_METADATA_LENGTH_LEN))
  106201. return false;
  106202. switch(metadata->type) {
  106203. case FLAC__METADATA_TYPE_STREAMINFO:
  106204. FLAC__ASSERT(metadata->data.stream_info.min_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN));
  106205. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN))
  106206. return false;
  106207. FLAC__ASSERT(metadata->data.stream_info.max_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN));
  106208. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  106209. return false;
  106210. FLAC__ASSERT(metadata->data.stream_info.min_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN));
  106211. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_framesize, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  106212. return false;
  106213. FLAC__ASSERT(metadata->data.stream_info.max_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN));
  106214. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_framesize, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  106215. return false;
  106216. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(metadata->data.stream_info.sample_rate));
  106217. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.sample_rate, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  106218. return false;
  106219. FLAC__ASSERT(metadata->data.stream_info.channels > 0);
  106220. FLAC__ASSERT(metadata->data.stream_info.channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN));
  106221. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.channels-1, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  106222. return false;
  106223. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample > 0);
  106224. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  106225. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.bits_per_sample-1, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  106226. return false;
  106227. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN))
  106228. return false;
  106229. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.stream_info.md5sum, 16))
  106230. return false;
  106231. break;
  106232. case FLAC__METADATA_TYPE_PADDING:
  106233. if(!FLAC__bitwriter_write_zeroes(bw, metadata->length * 8))
  106234. return false;
  106235. break;
  106236. case FLAC__METADATA_TYPE_APPLICATION:
  106237. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8))
  106238. return false;
  106239. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.data, metadata->length - (FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8)))
  106240. return false;
  106241. break;
  106242. case FLAC__METADATA_TYPE_SEEKTABLE:
  106243. for(i = 0; i < metadata->data.seek_table.num_points; i++) {
  106244. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].sample_number, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  106245. return false;
  106246. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].stream_offset, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  106247. return false;
  106248. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.seek_table.points[i].frame_samples, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  106249. return false;
  106250. }
  106251. break;
  106252. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  106253. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, vendor_string_length))
  106254. return false;
  106255. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)FLAC__VENDOR_STRING, vendor_string_length))
  106256. return false;
  106257. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.num_comments))
  106258. return false;
  106259. for(i = 0; i < metadata->data.vorbis_comment.num_comments; i++) {
  106260. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.comments[i].length))
  106261. return false;
  106262. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.vorbis_comment.comments[i].entry, metadata->data.vorbis_comment.comments[i].length))
  106263. return false;
  106264. }
  106265. break;
  106266. case FLAC__METADATA_TYPE_CUESHEET:
  106267. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  106268. 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))
  106269. return false;
  106270. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.cue_sheet.lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  106271. return false;
  106272. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.is_cd? 1 : 0, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  106273. return false;
  106274. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  106275. return false;
  106276. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.num_tracks, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  106277. return false;
  106278. for(i = 0; i < metadata->data.cue_sheet.num_tracks; i++) {
  106279. const FLAC__StreamMetadata_CueSheet_Track *track = metadata->data.cue_sheet.tracks + i;
  106280. if(!FLAC__bitwriter_write_raw_uint64(bw, track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  106281. return false;
  106282. if(!FLAC__bitwriter_write_raw_uint32(bw, track->number, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  106283. return false;
  106284. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  106285. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  106286. return false;
  106287. if(!FLAC__bitwriter_write_raw_uint32(bw, track->type, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  106288. return false;
  106289. if(!FLAC__bitwriter_write_raw_uint32(bw, track->pre_emphasis, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  106290. return false;
  106291. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  106292. return false;
  106293. if(!FLAC__bitwriter_write_raw_uint32(bw, track->num_indices, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  106294. return false;
  106295. for(j = 0; j < track->num_indices; j++) {
  106296. const FLAC__StreamMetadata_CueSheet_Index *index = track->indices + j;
  106297. if(!FLAC__bitwriter_write_raw_uint64(bw, index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  106298. return false;
  106299. if(!FLAC__bitwriter_write_raw_uint32(bw, index->number, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  106300. return false;
  106301. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  106302. return false;
  106303. }
  106304. }
  106305. break;
  106306. case FLAC__METADATA_TYPE_PICTURE:
  106307. {
  106308. size_t len;
  106309. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.type, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  106310. return false;
  106311. len = strlen(metadata->data.picture.mime_type);
  106312. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  106313. return false;
  106314. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)metadata->data.picture.mime_type, len))
  106315. return false;
  106316. len = strlen((const char *)metadata->data.picture.description);
  106317. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  106318. return false;
  106319. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.description, len))
  106320. return false;
  106321. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  106322. return false;
  106323. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  106324. return false;
  106325. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  106326. return false;
  106327. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  106328. return false;
  106329. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.data_length, FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  106330. return false;
  106331. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.data, metadata->data.picture.data_length))
  106332. return false;
  106333. }
  106334. break;
  106335. default:
  106336. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.unknown.data, metadata->length))
  106337. return false;
  106338. break;
  106339. }
  106340. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  106341. return true;
  106342. }
  106343. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw)
  106344. {
  106345. unsigned u, blocksize_hint, sample_rate_hint;
  106346. FLAC__byte crc;
  106347. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  106348. if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__FRAME_HEADER_SYNC, FLAC__FRAME_HEADER_SYNC_LEN))
  106349. return false;
  106350. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_RESERVED_LEN))
  106351. return false;
  106352. if(!FLAC__bitwriter_write_raw_uint32(bw, (header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER)? 0 : 1, FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN))
  106353. return false;
  106354. FLAC__ASSERT(header->blocksize > 0 && header->blocksize <= FLAC__MAX_BLOCK_SIZE);
  106355. /* when this assertion holds true, any legal blocksize can be expressed in the frame header */
  106356. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535u);
  106357. blocksize_hint = 0;
  106358. switch(header->blocksize) {
  106359. case 192: u = 1; break;
  106360. case 576: u = 2; break;
  106361. case 1152: u = 3; break;
  106362. case 2304: u = 4; break;
  106363. case 4608: u = 5; break;
  106364. case 256: u = 8; break;
  106365. case 512: u = 9; break;
  106366. case 1024: u = 10; break;
  106367. case 2048: u = 11; break;
  106368. case 4096: u = 12; break;
  106369. case 8192: u = 13; break;
  106370. case 16384: u = 14; break;
  106371. case 32768: u = 15; break;
  106372. default:
  106373. if(header->blocksize <= 0x100)
  106374. blocksize_hint = u = 6;
  106375. else
  106376. blocksize_hint = u = 7;
  106377. break;
  106378. }
  106379. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BLOCK_SIZE_LEN))
  106380. return false;
  106381. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(header->sample_rate));
  106382. sample_rate_hint = 0;
  106383. switch(header->sample_rate) {
  106384. case 88200: u = 1; break;
  106385. case 176400: u = 2; break;
  106386. case 192000: u = 3; break;
  106387. case 8000: u = 4; break;
  106388. case 16000: u = 5; break;
  106389. case 22050: u = 6; break;
  106390. case 24000: u = 7; break;
  106391. case 32000: u = 8; break;
  106392. case 44100: u = 9; break;
  106393. case 48000: u = 10; break;
  106394. case 96000: u = 11; break;
  106395. default:
  106396. if(header->sample_rate <= 255000 && header->sample_rate % 1000 == 0)
  106397. sample_rate_hint = u = 12;
  106398. else if(header->sample_rate % 10 == 0)
  106399. sample_rate_hint = u = 14;
  106400. else if(header->sample_rate <= 0xffff)
  106401. sample_rate_hint = u = 13;
  106402. else
  106403. u = 0;
  106404. break;
  106405. }
  106406. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_SAMPLE_RATE_LEN))
  106407. return false;
  106408. FLAC__ASSERT(header->channels > 0 && header->channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN) && header->channels <= FLAC__MAX_CHANNELS);
  106409. switch(header->channel_assignment) {
  106410. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  106411. u = header->channels - 1;
  106412. break;
  106413. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  106414. FLAC__ASSERT(header->channels == 2);
  106415. u = 8;
  106416. break;
  106417. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  106418. FLAC__ASSERT(header->channels == 2);
  106419. u = 9;
  106420. break;
  106421. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  106422. FLAC__ASSERT(header->channels == 2);
  106423. u = 10;
  106424. break;
  106425. default:
  106426. FLAC__ASSERT(0);
  106427. }
  106428. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN))
  106429. return false;
  106430. FLAC__ASSERT(header->bits_per_sample > 0 && header->bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  106431. switch(header->bits_per_sample) {
  106432. case 8 : u = 1; break;
  106433. case 12: u = 2; break;
  106434. case 16: u = 4; break;
  106435. case 20: u = 5; break;
  106436. case 24: u = 6; break;
  106437. default: u = 0; break;
  106438. }
  106439. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN))
  106440. return false;
  106441. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_ZERO_PAD_LEN))
  106442. return false;
  106443. if(header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  106444. if(!FLAC__bitwriter_write_utf8_uint32(bw, header->number.frame_number))
  106445. return false;
  106446. }
  106447. else {
  106448. if(!FLAC__bitwriter_write_utf8_uint64(bw, header->number.sample_number))
  106449. return false;
  106450. }
  106451. if(blocksize_hint)
  106452. if(!FLAC__bitwriter_write_raw_uint32(bw, header->blocksize-1, (blocksize_hint==6)? 8:16))
  106453. return false;
  106454. switch(sample_rate_hint) {
  106455. case 12:
  106456. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 1000, 8))
  106457. return false;
  106458. break;
  106459. case 13:
  106460. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate, 16))
  106461. return false;
  106462. break;
  106463. case 14:
  106464. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 10, 16))
  106465. return false;
  106466. break;
  106467. }
  106468. /* write the CRC */
  106469. if(!FLAC__bitwriter_get_write_crc8(bw, &crc))
  106470. return false;
  106471. if(!FLAC__bitwriter_write_raw_uint32(bw, crc, FLAC__FRAME_HEADER_CRC_LEN))
  106472. return false;
  106473. return true;
  106474. }
  106475. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106476. {
  106477. FLAC__bool ok;
  106478. ok =
  106479. 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) &&
  106480. (wasted_bits? FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1) : true) &&
  106481. FLAC__bitwriter_write_raw_int32(bw, subframe->value, subframe_bps)
  106482. ;
  106483. return ok;
  106484. }
  106485. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106486. {
  106487. unsigned i;
  106488. 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))
  106489. return false;
  106490. if(wasted_bits)
  106491. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106492. return false;
  106493. for(i = 0; i < subframe->order; i++)
  106494. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  106495. return false;
  106496. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  106497. return false;
  106498. switch(subframe->entropy_coding_method.type) {
  106499. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106500. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106501. if(!add_residual_partitioned_rice_(
  106502. bw,
  106503. subframe->residual,
  106504. residual_samples,
  106505. subframe->order,
  106506. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  106507. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  106508. subframe->entropy_coding_method.data.partitioned_rice.order,
  106509. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  106510. ))
  106511. return false;
  106512. break;
  106513. default:
  106514. FLAC__ASSERT(0);
  106515. }
  106516. return true;
  106517. }
  106518. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106519. {
  106520. unsigned i;
  106521. 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))
  106522. return false;
  106523. if(wasted_bits)
  106524. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106525. return false;
  106526. for(i = 0; i < subframe->order; i++)
  106527. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  106528. return false;
  106529. if(!FLAC__bitwriter_write_raw_uint32(bw, subframe->qlp_coeff_precision-1, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  106530. return false;
  106531. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->quantization_level, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  106532. return false;
  106533. for(i = 0; i < subframe->order; i++)
  106534. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->qlp_coeff[i], subframe->qlp_coeff_precision))
  106535. return false;
  106536. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  106537. return false;
  106538. switch(subframe->entropy_coding_method.type) {
  106539. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106540. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106541. if(!add_residual_partitioned_rice_(
  106542. bw,
  106543. subframe->residual,
  106544. residual_samples,
  106545. subframe->order,
  106546. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  106547. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  106548. subframe->entropy_coding_method.data.partitioned_rice.order,
  106549. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  106550. ))
  106551. return false;
  106552. break;
  106553. default:
  106554. FLAC__ASSERT(0);
  106555. }
  106556. return true;
  106557. }
  106558. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106559. {
  106560. unsigned i;
  106561. const FLAC__int32 *signal = subframe->data;
  106562. 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))
  106563. return false;
  106564. if(wasted_bits)
  106565. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106566. return false;
  106567. for(i = 0; i < samples; i++)
  106568. if(!FLAC__bitwriter_write_raw_int32(bw, signal[i], subframe_bps))
  106569. return false;
  106570. return true;
  106571. }
  106572. FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method)
  106573. {
  106574. if(!FLAC__bitwriter_write_raw_uint32(bw, method->type, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  106575. return false;
  106576. switch(method->type) {
  106577. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106578. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106579. if(!FLAC__bitwriter_write_raw_uint32(bw, method->data.partitioned_rice.order, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  106580. return false;
  106581. break;
  106582. default:
  106583. FLAC__ASSERT(0);
  106584. }
  106585. return true;
  106586. }
  106587. 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)
  106588. {
  106589. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  106590. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  106591. if(partition_order == 0) {
  106592. unsigned i;
  106593. if(raw_bits[0] == 0) {
  106594. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[0], plen))
  106595. return false;
  106596. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual, residual_samples, rice_parameters[0]))
  106597. return false;
  106598. }
  106599. else {
  106600. FLAC__ASSERT(rice_parameters[0] == 0);
  106601. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  106602. return false;
  106603. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[0], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  106604. return false;
  106605. for(i = 0; i < residual_samples; i++) {
  106606. if(!FLAC__bitwriter_write_raw_int32(bw, residual[i], raw_bits[0]))
  106607. return false;
  106608. }
  106609. }
  106610. return true;
  106611. }
  106612. else {
  106613. unsigned i, j, k = 0, k_last = 0;
  106614. unsigned partition_samples;
  106615. const unsigned default_partition_samples = (residual_samples+predictor_order) >> partition_order;
  106616. for(i = 0; i < (1u<<partition_order); i++) {
  106617. partition_samples = default_partition_samples;
  106618. if(i == 0)
  106619. partition_samples -= predictor_order;
  106620. k += partition_samples;
  106621. if(raw_bits[i] == 0) {
  106622. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[i], plen))
  106623. return false;
  106624. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual+k_last, k-k_last, rice_parameters[i]))
  106625. return false;
  106626. }
  106627. else {
  106628. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  106629. return false;
  106630. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[i], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  106631. return false;
  106632. for(j = k_last; j < k; j++) {
  106633. if(!FLAC__bitwriter_write_raw_int32(bw, residual[j], raw_bits[i]))
  106634. return false;
  106635. }
  106636. }
  106637. k_last = k;
  106638. }
  106639. return true;
  106640. }
  106641. }
  106642. #endif
  106643. /*** End of inlined file: stream_encoder_framing.c ***/
  106644. /*** Start of inlined file: window_flac.c ***/
  106645. /*** Start of inlined file: juce_FlacHeader.h ***/
  106646. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  106647. // tasks..
  106648. #define VERSION "1.2.1"
  106649. #define FLAC__NO_DLL 1
  106650. #if JUCE_MSVC
  106651. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  106652. #endif
  106653. #if JUCE_MAC
  106654. #define FLAC__SYS_DARWIN 1
  106655. #endif
  106656. /*** End of inlined file: juce_FlacHeader.h ***/
  106657. #if JUCE_USE_FLAC
  106658. #if HAVE_CONFIG_H
  106659. # include <config.h>
  106660. #endif
  106661. #include <math.h>
  106662. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  106663. #ifndef M_PI
  106664. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  106665. #define M_PI 3.14159265358979323846
  106666. #endif
  106667. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L)
  106668. {
  106669. const FLAC__int32 N = L - 1;
  106670. FLAC__int32 n;
  106671. if (L & 1) {
  106672. for (n = 0; n <= N/2; n++)
  106673. window[n] = 2.0f * n / (float)N;
  106674. for (; n <= N; n++)
  106675. window[n] = 2.0f - 2.0f * n / (float)N;
  106676. }
  106677. else {
  106678. for (n = 0; n <= L/2-1; n++)
  106679. window[n] = 2.0f * n / (float)N;
  106680. for (; n <= N; n++)
  106681. window[n] = 2.0f - 2.0f * (N-n) / (float)N;
  106682. }
  106683. }
  106684. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L)
  106685. {
  106686. const FLAC__int32 N = L - 1;
  106687. FLAC__int32 n;
  106688. for (n = 0; n < L; n++)
  106689. 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)));
  106690. }
  106691. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L)
  106692. {
  106693. const FLAC__int32 N = L - 1;
  106694. FLAC__int32 n;
  106695. for (n = 0; n < L; n++)
  106696. window[n] = (FLAC__real)(0.42f - 0.5f * cos(2.0f * M_PI * n / N) + 0.08f * cos(4.0f * M_PI * n / N));
  106697. }
  106698. /* 4-term -92dB side-lobe */
  106699. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L)
  106700. {
  106701. const FLAC__int32 N = L - 1;
  106702. FLAC__int32 n;
  106703. for (n = 0; n <= N; n++)
  106704. 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));
  106705. }
  106706. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L)
  106707. {
  106708. const FLAC__int32 N = L - 1;
  106709. const double N2 = (double)N / 2.;
  106710. FLAC__int32 n;
  106711. for (n = 0; n <= N; n++) {
  106712. double k = ((double)n - N2) / N2;
  106713. k = 1.0f - k * k;
  106714. window[n] = (FLAC__real)(k * k);
  106715. }
  106716. }
  106717. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L)
  106718. {
  106719. const FLAC__int32 N = L - 1;
  106720. FLAC__int32 n;
  106721. for (n = 0; n < L; n++)
  106722. 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));
  106723. }
  106724. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev)
  106725. {
  106726. const FLAC__int32 N = L - 1;
  106727. const double N2 = (double)N / 2.;
  106728. FLAC__int32 n;
  106729. for (n = 0; n <= N; n++) {
  106730. const double k = ((double)n - N2) / (stddev * N2);
  106731. window[n] = (FLAC__real)exp(-0.5f * k * k);
  106732. }
  106733. }
  106734. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L)
  106735. {
  106736. const FLAC__int32 N = L - 1;
  106737. FLAC__int32 n;
  106738. for (n = 0; n < L; n++)
  106739. window[n] = (FLAC__real)(0.54f - 0.46f * cos(2.0f * M_PI * n / N));
  106740. }
  106741. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L)
  106742. {
  106743. const FLAC__int32 N = L - 1;
  106744. FLAC__int32 n;
  106745. for (n = 0; n < L; n++)
  106746. window[n] = (FLAC__real)(0.5f - 0.5f * cos(2.0f * M_PI * n / N));
  106747. }
  106748. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L)
  106749. {
  106750. const FLAC__int32 N = L - 1;
  106751. FLAC__int32 n;
  106752. for (n = 0; n < L; n++)
  106753. 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));
  106754. }
  106755. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L)
  106756. {
  106757. const FLAC__int32 N = L - 1;
  106758. FLAC__int32 n;
  106759. for (n = 0; n < L; n++)
  106760. window[n] = (FLAC__real)(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));
  106761. }
  106762. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L)
  106763. {
  106764. FLAC__int32 n;
  106765. for (n = 0; n < L; n++)
  106766. window[n] = 1.0f;
  106767. }
  106768. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L)
  106769. {
  106770. FLAC__int32 n;
  106771. if (L & 1) {
  106772. for (n = 1; n <= L+1/2; n++)
  106773. window[n-1] = 2.0f * n / ((float)L + 1.0f);
  106774. for (; n <= L; n++)
  106775. window[n-1] = - (float)(2 * (L - n + 1)) / ((float)L + 1.0f);
  106776. }
  106777. else {
  106778. for (n = 1; n <= L/2; n++)
  106779. window[n-1] = 2.0f * n / (float)L;
  106780. for (; n <= L; n++)
  106781. window[n-1] = ((float)(2 * (L - n)) + 1.0f) / (float)L;
  106782. }
  106783. }
  106784. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p)
  106785. {
  106786. if (p <= 0.0)
  106787. FLAC__window_rectangle(window, L);
  106788. else if (p >= 1.0)
  106789. FLAC__window_hann(window, L);
  106790. else {
  106791. const FLAC__int32 Np = (FLAC__int32)(p / 2.0f * L) - 1;
  106792. FLAC__int32 n;
  106793. /* start with rectangle... */
  106794. FLAC__window_rectangle(window, L);
  106795. /* ...replace ends with hann */
  106796. if (Np > 0) {
  106797. for (n = 0; n <= Np; n++) {
  106798. window[n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * n / Np));
  106799. window[L-Np-1+n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * (n+Np) / Np));
  106800. }
  106801. }
  106802. }
  106803. }
  106804. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L)
  106805. {
  106806. const FLAC__int32 N = L - 1;
  106807. const double N2 = (double)N / 2.;
  106808. FLAC__int32 n;
  106809. for (n = 0; n <= N; n++) {
  106810. const double k = ((double)n - N2) / N2;
  106811. window[n] = (FLAC__real)(1.0f - k * k);
  106812. }
  106813. }
  106814. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  106815. #endif
  106816. /*** End of inlined file: window_flac.c ***/
  106817. #else
  106818. #include <FLAC/all.h>
  106819. #endif
  106820. }
  106821. #undef max
  106822. #undef min
  106823. BEGIN_JUCE_NAMESPACE
  106824. static const char* const flacFormatName = "FLAC file";
  106825. static const char* const flacExtensions[] = { ".flac", 0 };
  106826. class FlacReader : public AudioFormatReader
  106827. {
  106828. public:
  106829. FlacReader (InputStream* const in)
  106830. : AudioFormatReader (in, TRANS (flacFormatName)),
  106831. reservoir (2, 0),
  106832. reservoirStart (0),
  106833. samplesInReservoir (0),
  106834. scanningForLength (false)
  106835. {
  106836. using namespace FlacNamespace;
  106837. lengthInSamples = 0;
  106838. decoder = FLAC__stream_decoder_new();
  106839. ok = FLAC__stream_decoder_init_stream (decoder,
  106840. readCallback_, seekCallback_, tellCallback_, lengthCallback_,
  106841. eofCallback_, writeCallback_, metadataCallback_, errorCallback_,
  106842. this) == FLAC__STREAM_DECODER_INIT_STATUS_OK;
  106843. if (ok)
  106844. {
  106845. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  106846. if (lengthInSamples == 0 && sampleRate > 0)
  106847. {
  106848. // the length hasn't been stored in the metadata, so we'll need to
  106849. // work it out the length the hard way, by scanning the whole file..
  106850. scanningForLength = true;
  106851. FLAC__stream_decoder_process_until_end_of_stream (decoder);
  106852. scanningForLength = false;
  106853. const int64 tempLength = lengthInSamples;
  106854. FLAC__stream_decoder_reset (decoder);
  106855. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  106856. lengthInSamples = tempLength;
  106857. }
  106858. }
  106859. }
  106860. ~FlacReader()
  106861. {
  106862. FlacNamespace::FLAC__stream_decoder_delete (decoder);
  106863. }
  106864. void useMetadata (const FlacNamespace::FLAC__StreamMetadata_StreamInfo& info)
  106865. {
  106866. sampleRate = info.sample_rate;
  106867. bitsPerSample = info.bits_per_sample;
  106868. lengthInSamples = (unsigned int) info.total_samples;
  106869. numChannels = info.channels;
  106870. reservoir.setSize (numChannels, 2 * info.max_blocksize, false, false, true);
  106871. }
  106872. // returns the number of samples read
  106873. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  106874. int64 startSampleInFile, int numSamples)
  106875. {
  106876. using namespace FlacNamespace;
  106877. if (! ok)
  106878. return false;
  106879. while (numSamples > 0)
  106880. {
  106881. if (startSampleInFile >= reservoirStart
  106882. && startSampleInFile < reservoirStart + samplesInReservoir)
  106883. {
  106884. const int num = (int) jmin ((int64) numSamples,
  106885. reservoirStart + samplesInReservoir - startSampleInFile);
  106886. jassert (num > 0);
  106887. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  106888. if (destSamples[i] != 0)
  106889. memcpy (destSamples[i] + startOffsetInDestBuffer,
  106890. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  106891. sizeof (int) * num);
  106892. startOffsetInDestBuffer += num;
  106893. startSampleInFile += num;
  106894. numSamples -= num;
  106895. }
  106896. else
  106897. {
  106898. if (startSampleInFile >= (int) lengthInSamples)
  106899. {
  106900. samplesInReservoir = 0;
  106901. }
  106902. else if (startSampleInFile < reservoirStart
  106903. || startSampleInFile > reservoirStart + jmax (samplesInReservoir, 511))
  106904. {
  106905. // had some problems with flac crashing if the read pos is aligned more
  106906. // accurately than this. Probably fixed in newer versions of the library, though.
  106907. reservoirStart = (int) (startSampleInFile & ~511);
  106908. samplesInReservoir = 0;
  106909. FLAC__stream_decoder_seek_absolute (decoder, (FLAC__uint64) reservoirStart);
  106910. }
  106911. else
  106912. {
  106913. reservoirStart += samplesInReservoir;
  106914. samplesInReservoir = 0;
  106915. FLAC__stream_decoder_process_single (decoder);
  106916. }
  106917. if (samplesInReservoir == 0)
  106918. break;
  106919. }
  106920. }
  106921. if (numSamples > 0)
  106922. {
  106923. for (int i = numDestChannels; --i >= 0;)
  106924. if (destSamples[i] != 0)
  106925. zeromem (destSamples[i] + startOffsetInDestBuffer,
  106926. sizeof (int) * numSamples);
  106927. }
  106928. return true;
  106929. }
  106930. void useSamples (const FlacNamespace::FLAC__int32* const buffer[], int numSamples)
  106931. {
  106932. if (scanningForLength)
  106933. {
  106934. lengthInSamples += numSamples;
  106935. }
  106936. else
  106937. {
  106938. if (numSamples > reservoir.getNumSamples())
  106939. reservoir.setSize (numChannels, numSamples, false, false, true);
  106940. const int bitsToShift = 32 - bitsPerSample;
  106941. for (int i = 0; i < (int) numChannels; ++i)
  106942. {
  106943. const FlacNamespace::FLAC__int32* src = buffer[i];
  106944. int n = i;
  106945. while (src == 0 && n > 0)
  106946. src = buffer [--n];
  106947. if (src != 0)
  106948. {
  106949. int* dest = reinterpret_cast<int*> (reservoir.getSampleData(i));
  106950. for (int j = 0; j < numSamples; ++j)
  106951. dest[j] = src[j] << bitsToShift;
  106952. }
  106953. }
  106954. samplesInReservoir = numSamples;
  106955. }
  106956. }
  106957. static FlacNamespace::FLAC__StreamDecoderReadStatus readCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__byte buffer[], size_t* bytes, void* client_data)
  106958. {
  106959. using namespace FlacNamespace;
  106960. *bytes = (size_t) static_cast <const FlacReader*> (client_data)->input->read (buffer, (int) *bytes);
  106961. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  106962. }
  106963. static FlacNamespace::FLAC__StreamDecoderSeekStatus seekCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64 absolute_byte_offset, void* client_data)
  106964. {
  106965. using namespace FlacNamespace;
  106966. static_cast <const FlacReader*> (client_data)->input->setPosition ((int) absolute_byte_offset);
  106967. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  106968. }
  106969. static FlacNamespace::FLAC__StreamDecoderTellStatus tellCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  106970. {
  106971. using namespace FlacNamespace;
  106972. *absolute_byte_offset = static_cast <const FlacReader*> (client_data)->input->getPosition();
  106973. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  106974. }
  106975. static FlacNamespace::FLAC__StreamDecoderLengthStatus lengthCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* stream_length, void* client_data)
  106976. {
  106977. using namespace FlacNamespace;
  106978. *stream_length = static_cast <const FlacReader*> (client_data)->input->getTotalLength();
  106979. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  106980. }
  106981. static FlacNamespace::FLAC__bool eofCallback_ (const FlacNamespace::FLAC__StreamDecoder*, void* client_data)
  106982. {
  106983. return static_cast <const FlacReader*> (client_data)->input->isExhausted();
  106984. }
  106985. static FlacNamespace::FLAC__StreamDecoderWriteStatus writeCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  106986. const FlacNamespace::FLAC__Frame* frame,
  106987. const FlacNamespace::FLAC__int32* const buffer[],
  106988. void* client_data)
  106989. {
  106990. using namespace FlacNamespace;
  106991. static_cast <FlacReader*> (client_data)->useSamples (buffer, frame->header.blocksize);
  106992. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  106993. }
  106994. static void metadataCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  106995. const FlacNamespace::FLAC__StreamMetadata* metadata,
  106996. void* client_data)
  106997. {
  106998. static_cast <FlacReader*> (client_data)->useMetadata (metadata->data.stream_info);
  106999. }
  107000. static void errorCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__StreamDecoderErrorStatus, void*)
  107001. {
  107002. }
  107003. juce_UseDebuggingNewOperator
  107004. private:
  107005. FlacNamespace::FLAC__StreamDecoder* decoder;
  107006. AudioSampleBuffer reservoir;
  107007. int reservoirStart, samplesInReservoir;
  107008. bool ok, scanningForLength;
  107009. FlacReader (const FlacReader&);
  107010. FlacReader& operator= (const FlacReader&);
  107011. };
  107012. class FlacWriter : public AudioFormatWriter
  107013. {
  107014. public:
  107015. FlacWriter (OutputStream* const out, double sampleRate_,
  107016. int numChannels_, int bitsPerSample_, int qualityOptionIndex)
  107017. : AudioFormatWriter (out, TRANS (flacFormatName),
  107018. sampleRate_, numChannels_, bitsPerSample_)
  107019. {
  107020. using namespace FlacNamespace;
  107021. encoder = FLAC__stream_encoder_new();
  107022. if (qualityOptionIndex > 0)
  107023. FLAC__stream_encoder_set_compression_level (encoder, jmin (8, qualityOptionIndex));
  107024. FLAC__stream_encoder_set_do_mid_side_stereo (encoder, numChannels == 2);
  107025. FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, numChannels == 2);
  107026. FLAC__stream_encoder_set_channels (encoder, numChannels);
  107027. FLAC__stream_encoder_set_bits_per_sample (encoder, jmin ((unsigned int) 24, bitsPerSample));
  107028. FLAC__stream_encoder_set_sample_rate (encoder, (unsigned int) sampleRate);
  107029. FLAC__stream_encoder_set_blocksize (encoder, 2048);
  107030. FLAC__stream_encoder_set_do_escape_coding (encoder, true);
  107031. ok = FLAC__stream_encoder_init_stream (encoder,
  107032. encodeWriteCallback, encodeSeekCallback,
  107033. encodeTellCallback, encodeMetadataCallback,
  107034. this) == FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  107035. }
  107036. ~FlacWriter()
  107037. {
  107038. if (ok)
  107039. {
  107040. FlacNamespace::FLAC__stream_encoder_finish (encoder);
  107041. output->flush();
  107042. }
  107043. else
  107044. {
  107045. output = 0; // to stop the base class deleting this, as it needs to be returned
  107046. // to the caller of createWriter()
  107047. }
  107048. FlacNamespace::FLAC__stream_encoder_delete (encoder);
  107049. }
  107050. bool write (const int** samplesToWrite, int numSamples)
  107051. {
  107052. using namespace FlacNamespace;
  107053. if (! ok)
  107054. return false;
  107055. int* buf[3];
  107056. const int bitsToShift = 32 - bitsPerSample;
  107057. if (bitsToShift > 0)
  107058. {
  107059. const int numChannelsToWrite = (samplesToWrite[1] == 0) ? 1 : 2;
  107060. HeapBlock<int> temp (numSamples * numChannelsToWrite);
  107061. buf[0] = temp.getData();
  107062. buf[1] = temp.getData() + numSamples;
  107063. buf[2] = 0;
  107064. for (int i = numChannelsToWrite; --i >= 0;)
  107065. {
  107066. if (samplesToWrite[i] != 0)
  107067. {
  107068. for (int j = 0; j < numSamples; ++j)
  107069. buf [i][j] = (samplesToWrite [i][j] >> bitsToShift);
  107070. }
  107071. }
  107072. samplesToWrite = const_cast<const int**> (buf);
  107073. }
  107074. return FLAC__stream_encoder_process (encoder,
  107075. (const FLAC__int32**) samplesToWrite,
  107076. numSamples) != 0;
  107077. }
  107078. bool writeData (const void* const data, const int size) const
  107079. {
  107080. return output->write (data, size);
  107081. }
  107082. static void packUint32 (FlacNamespace::FLAC__uint32 val, FlacNamespace::FLAC__byte* b, const int bytes)
  107083. {
  107084. using namespace FlacNamespace;
  107085. b += bytes;
  107086. for (int i = 0; i < bytes; ++i)
  107087. {
  107088. *(--b) = (FLAC__byte) (val & 0xff);
  107089. val >>= 8;
  107090. }
  107091. }
  107092. void writeMetaData (const FlacNamespace::FLAC__StreamMetadata* metadata)
  107093. {
  107094. using namespace FlacNamespace;
  107095. const FLAC__StreamMetadata_StreamInfo& info = metadata->data.stream_info;
  107096. unsigned char buffer [FLAC__STREAM_METADATA_STREAMINFO_LENGTH];
  107097. const unsigned int channelsMinus1 = info.channels - 1;
  107098. const unsigned int bitsMinus1 = info.bits_per_sample - 1;
  107099. packUint32 (info.min_blocksize, buffer, 2);
  107100. packUint32 (info.max_blocksize, buffer + 2, 2);
  107101. packUint32 (info.min_framesize, buffer + 4, 3);
  107102. packUint32 (info.max_framesize, buffer + 7, 3);
  107103. buffer[10] = (uint8) ((info.sample_rate >> 12) & 0xff);
  107104. buffer[11] = (uint8) ((info.sample_rate >> 4) & 0xff);
  107105. buffer[12] = (uint8) (((info.sample_rate & 0x0f) << 4) | (channelsMinus1 << 1) | (bitsMinus1 >> 4));
  107106. buffer[13] = (FLAC__byte) (((bitsMinus1 & 0x0f) << 4) | (unsigned int) ((info.total_samples >> 32) & 0x0f));
  107107. packUint32 ((FLAC__uint32) info.total_samples, buffer + 14, 4);
  107108. memcpy (buffer + 18, info.md5sum, 16);
  107109. const bool seekOk = output->setPosition (4);
  107110. (void) seekOk;
  107111. // if this fails, you've given it an output stream that can't seek! It needs
  107112. // to be able to seek back to write the header
  107113. jassert (seekOk);
  107114. output->writeIntBigEndian (FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  107115. output->write (buffer, FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  107116. }
  107117. static FlacNamespace::FLAC__StreamEncoderWriteStatus encodeWriteCallback (const FlacNamespace::FLAC__StreamEncoder*,
  107118. const FlacNamespace::FLAC__byte buffer[],
  107119. size_t bytes,
  107120. unsigned int /*samples*/,
  107121. unsigned int /*current_frame*/,
  107122. void* client_data)
  107123. {
  107124. using namespace FlacNamespace;
  107125. return static_cast <FlacWriter*> (client_data)->writeData (buffer, (int) bytes)
  107126. ? FLAC__STREAM_ENCODER_WRITE_STATUS_OK
  107127. : FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  107128. }
  107129. static FlacNamespace::FLAC__StreamEncoderSeekStatus encodeSeekCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64, void*)
  107130. {
  107131. using namespace FlacNamespace;
  107132. return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  107133. }
  107134. static FlacNamespace::FLAC__StreamEncoderTellStatus encodeTellCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  107135. {
  107136. using namespace FlacNamespace;
  107137. if (client_data == 0)
  107138. return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  107139. *absolute_byte_offset = (FLAC__uint64) static_cast <FlacWriter*> (client_data)->output->getPosition();
  107140. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  107141. }
  107142. static void encodeMetadataCallback (const FlacNamespace::FLAC__StreamEncoder*, const FlacNamespace::FLAC__StreamMetadata* metadata, void* client_data)
  107143. {
  107144. static_cast <FlacWriter*> (client_data)->writeMetaData (metadata);
  107145. }
  107146. juce_UseDebuggingNewOperator
  107147. bool ok;
  107148. private:
  107149. FlacNamespace::FLAC__StreamEncoder* encoder;
  107150. FlacWriter (const FlacWriter&);
  107151. FlacWriter& operator= (const FlacWriter&);
  107152. };
  107153. FlacAudioFormat::FlacAudioFormat()
  107154. : AudioFormat (TRANS (flacFormatName), StringArray (flacExtensions))
  107155. {
  107156. }
  107157. FlacAudioFormat::~FlacAudioFormat()
  107158. {
  107159. }
  107160. const Array <int> FlacAudioFormat::getPossibleSampleRates()
  107161. {
  107162. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 0 };
  107163. return Array <int> (rates);
  107164. }
  107165. const Array <int> FlacAudioFormat::getPossibleBitDepths()
  107166. {
  107167. const int depths[] = { 16, 24, 0 };
  107168. return Array <int> (depths);
  107169. }
  107170. bool FlacAudioFormat::canDoStereo() { return true; }
  107171. bool FlacAudioFormat::canDoMono() { return true; }
  107172. bool FlacAudioFormat::isCompressed() { return true; }
  107173. AudioFormatReader* FlacAudioFormat::createReaderFor (InputStream* in,
  107174. const bool deleteStreamIfOpeningFails)
  107175. {
  107176. ScopedPointer<FlacReader> r (new FlacReader (in));
  107177. if (r->sampleRate != 0)
  107178. return r.release();
  107179. if (! deleteStreamIfOpeningFails)
  107180. r->input = 0;
  107181. return 0;
  107182. }
  107183. AudioFormatWriter* FlacAudioFormat::createWriterFor (OutputStream* out,
  107184. double sampleRate,
  107185. unsigned int numberOfChannels,
  107186. int bitsPerSample,
  107187. const StringPairArray& /*metadataValues*/,
  107188. int qualityOptionIndex)
  107189. {
  107190. if (getPossibleBitDepths().contains (bitsPerSample))
  107191. {
  107192. ScopedPointer<FlacWriter> w (new FlacWriter (out, sampleRate, numberOfChannels, bitsPerSample, qualityOptionIndex));
  107193. if (w->ok)
  107194. return w.release();
  107195. }
  107196. return 0;
  107197. }
  107198. END_JUCE_NAMESPACE
  107199. #endif
  107200. /*** End of inlined file: juce_FlacAudioFormat.cpp ***/
  107201. /*** Start of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  107202. #if JUCE_USE_OGGVORBIS
  107203. #if JUCE_MAC
  107204. #define __MACOSX__ 1
  107205. #endif
  107206. namespace OggVorbisNamespace
  107207. {
  107208. #if JUCE_INCLUDE_OGGVORBIS_CODE
  107209. /*** Start of inlined file: vorbisenc.h ***/
  107210. #ifndef _OV_ENC_H_
  107211. #define _OV_ENC_H_
  107212. #ifdef __cplusplus
  107213. extern "C"
  107214. {
  107215. #endif /* __cplusplus */
  107216. /*** Start of inlined file: codec.h ***/
  107217. #ifndef _vorbis_codec_h_
  107218. #define _vorbis_codec_h_
  107219. #ifdef __cplusplus
  107220. extern "C"
  107221. {
  107222. #endif /* __cplusplus */
  107223. /*** Start of inlined file: ogg.h ***/
  107224. #ifndef _OGG_H
  107225. #define _OGG_H
  107226. #ifdef __cplusplus
  107227. extern "C" {
  107228. #endif
  107229. /*** Start of inlined file: os_types.h ***/
  107230. #ifndef _OS_TYPES_H
  107231. #define _OS_TYPES_H
  107232. /* make it easy on the folks that want to compile the libs with a
  107233. different malloc than stdlib */
  107234. #define _ogg_malloc malloc
  107235. #define _ogg_calloc calloc
  107236. #define _ogg_realloc realloc
  107237. #define _ogg_free free
  107238. #if defined(_WIN32)
  107239. # if defined(__CYGWIN__)
  107240. # include <_G_config.h>
  107241. typedef _G_int64_t ogg_int64_t;
  107242. typedef _G_int32_t ogg_int32_t;
  107243. typedef _G_uint32_t ogg_uint32_t;
  107244. typedef _G_int16_t ogg_int16_t;
  107245. typedef _G_uint16_t ogg_uint16_t;
  107246. # elif defined(__MINGW32__)
  107247. typedef short ogg_int16_t;
  107248. typedef unsigned short ogg_uint16_t;
  107249. typedef int ogg_int32_t;
  107250. typedef unsigned int ogg_uint32_t;
  107251. typedef long long ogg_int64_t;
  107252. typedef unsigned long long ogg_uint64_t;
  107253. # elif defined(__MWERKS__)
  107254. typedef long long ogg_int64_t;
  107255. typedef int ogg_int32_t;
  107256. typedef unsigned int ogg_uint32_t;
  107257. typedef short ogg_int16_t;
  107258. typedef unsigned short ogg_uint16_t;
  107259. # else
  107260. /* MSVC/Borland */
  107261. typedef __int64 ogg_int64_t;
  107262. typedef __int32 ogg_int32_t;
  107263. typedef unsigned __int32 ogg_uint32_t;
  107264. typedef __int16 ogg_int16_t;
  107265. typedef unsigned __int16 ogg_uint16_t;
  107266. # endif
  107267. #elif defined(__MACOS__)
  107268. # include <sys/types.h>
  107269. typedef SInt16 ogg_int16_t;
  107270. typedef UInt16 ogg_uint16_t;
  107271. typedef SInt32 ogg_int32_t;
  107272. typedef UInt32 ogg_uint32_t;
  107273. typedef SInt64 ogg_int64_t;
  107274. #elif defined(__MACOSX__) /* MacOS X Framework build */
  107275. # include <sys/types.h>
  107276. typedef int16_t ogg_int16_t;
  107277. typedef u_int16_t ogg_uint16_t;
  107278. typedef int32_t ogg_int32_t;
  107279. typedef u_int32_t ogg_uint32_t;
  107280. typedef int64_t ogg_int64_t;
  107281. #elif defined(__BEOS__)
  107282. /* Be */
  107283. # include <inttypes.h>
  107284. typedef int16_t ogg_int16_t;
  107285. typedef u_int16_t ogg_uint16_t;
  107286. typedef int32_t ogg_int32_t;
  107287. typedef u_int32_t ogg_uint32_t;
  107288. typedef int64_t ogg_int64_t;
  107289. #elif defined (__EMX__)
  107290. /* OS/2 GCC */
  107291. typedef short ogg_int16_t;
  107292. typedef unsigned short ogg_uint16_t;
  107293. typedef int ogg_int32_t;
  107294. typedef unsigned int ogg_uint32_t;
  107295. typedef long long ogg_int64_t;
  107296. #elif defined (DJGPP)
  107297. /* DJGPP */
  107298. typedef short ogg_int16_t;
  107299. typedef int ogg_int32_t;
  107300. typedef unsigned int ogg_uint32_t;
  107301. typedef long long ogg_int64_t;
  107302. #elif defined(R5900)
  107303. /* PS2 EE */
  107304. typedef long ogg_int64_t;
  107305. typedef int ogg_int32_t;
  107306. typedef unsigned ogg_uint32_t;
  107307. typedef short ogg_int16_t;
  107308. #elif defined(__SYMBIAN32__)
  107309. /* Symbian GCC */
  107310. typedef signed short ogg_int16_t;
  107311. typedef unsigned short ogg_uint16_t;
  107312. typedef signed int ogg_int32_t;
  107313. typedef unsigned int ogg_uint32_t;
  107314. typedef long long int ogg_int64_t;
  107315. #else
  107316. # include <sys/types.h>
  107317. /*** Start of inlined file: config_types.h ***/
  107318. #ifndef __CONFIG_TYPES_H__
  107319. #define __CONFIG_TYPES_H__
  107320. typedef int16_t ogg_int16_t;
  107321. typedef unsigned short ogg_uint16_t;
  107322. typedef int32_t ogg_int32_t;
  107323. typedef unsigned int ogg_uint32_t;
  107324. typedef int64_t ogg_int64_t;
  107325. #endif
  107326. /*** End of inlined file: config_types.h ***/
  107327. #endif
  107328. #endif /* _OS_TYPES_H */
  107329. /*** End of inlined file: os_types.h ***/
  107330. typedef struct {
  107331. long endbyte;
  107332. int endbit;
  107333. unsigned char *buffer;
  107334. unsigned char *ptr;
  107335. long storage;
  107336. } oggpack_buffer;
  107337. /* ogg_page is used to encapsulate the data in one Ogg bitstream page *****/
  107338. typedef struct {
  107339. unsigned char *header;
  107340. long header_len;
  107341. unsigned char *body;
  107342. long body_len;
  107343. } ogg_page;
  107344. ogg_uint32_t ogg_bitreverse(ogg_uint32_t x){
  107345. x= ((x>>16)&0x0000ffffUL) | ((x<<16)&0xffff0000UL);
  107346. x= ((x>> 8)&0x00ff00ffUL) | ((x<< 8)&0xff00ff00UL);
  107347. x= ((x>> 4)&0x0f0f0f0fUL) | ((x<< 4)&0xf0f0f0f0UL);
  107348. x= ((x>> 2)&0x33333333UL) | ((x<< 2)&0xccccccccUL);
  107349. return((x>> 1)&0x55555555UL) | ((x<< 1)&0xaaaaaaaaUL);
  107350. }
  107351. /* ogg_stream_state contains the current encode/decode state of a logical
  107352. Ogg bitstream **********************************************************/
  107353. typedef struct {
  107354. unsigned char *body_data; /* bytes from packet bodies */
  107355. long body_storage; /* storage elements allocated */
  107356. long body_fill; /* elements stored; fill mark */
  107357. long body_returned; /* elements of fill returned */
  107358. int *lacing_vals; /* The values that will go to the segment table */
  107359. ogg_int64_t *granule_vals; /* granulepos values for headers. Not compact
  107360. this way, but it is simple coupled to the
  107361. lacing fifo */
  107362. long lacing_storage;
  107363. long lacing_fill;
  107364. long lacing_packet;
  107365. long lacing_returned;
  107366. unsigned char header[282]; /* working space for header encode */
  107367. int header_fill;
  107368. int e_o_s; /* set when we have buffered the last packet in the
  107369. logical bitstream */
  107370. int b_o_s; /* set after we've written the initial page
  107371. of a logical bitstream */
  107372. long serialno;
  107373. long pageno;
  107374. ogg_int64_t packetno; /* sequence number for decode; the framing
  107375. knows where there's a hole in the data,
  107376. but we need coupling so that the codec
  107377. (which is in a seperate abstraction
  107378. layer) also knows about the gap */
  107379. ogg_int64_t granulepos;
  107380. } ogg_stream_state;
  107381. /* ogg_packet is used to encapsulate the data and metadata belonging
  107382. to a single raw Ogg/Vorbis packet *************************************/
  107383. typedef struct {
  107384. unsigned char *packet;
  107385. long bytes;
  107386. long b_o_s;
  107387. long e_o_s;
  107388. ogg_int64_t granulepos;
  107389. ogg_int64_t packetno; /* sequence number for decode; the framing
  107390. knows where there's a hole in the data,
  107391. but we need coupling so that the codec
  107392. (which is in a seperate abstraction
  107393. layer) also knows about the gap */
  107394. } ogg_packet;
  107395. typedef struct {
  107396. unsigned char *data;
  107397. int storage;
  107398. int fill;
  107399. int returned;
  107400. int unsynced;
  107401. int headerbytes;
  107402. int bodybytes;
  107403. } ogg_sync_state;
  107404. /* Ogg BITSTREAM PRIMITIVES: bitstream ************************/
  107405. extern void oggpack_writeinit(oggpack_buffer *b);
  107406. extern void oggpack_writetrunc(oggpack_buffer *b,long bits);
  107407. extern void oggpack_writealign(oggpack_buffer *b);
  107408. extern void oggpack_writecopy(oggpack_buffer *b,void *source,long bits);
  107409. extern void oggpack_reset(oggpack_buffer *b);
  107410. extern void oggpack_writeclear(oggpack_buffer *b);
  107411. extern void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  107412. extern void oggpack_write(oggpack_buffer *b,unsigned long value,int bits);
  107413. extern long oggpack_look(oggpack_buffer *b,int bits);
  107414. extern long oggpack_look1(oggpack_buffer *b);
  107415. extern void oggpack_adv(oggpack_buffer *b,int bits);
  107416. extern void oggpack_adv1(oggpack_buffer *b);
  107417. extern long oggpack_read(oggpack_buffer *b,int bits);
  107418. extern long oggpack_read1(oggpack_buffer *b);
  107419. extern long oggpack_bytes(oggpack_buffer *b);
  107420. extern long oggpack_bits(oggpack_buffer *b);
  107421. extern unsigned char *oggpack_get_buffer(oggpack_buffer *b);
  107422. extern void oggpackB_writeinit(oggpack_buffer *b);
  107423. extern void oggpackB_writetrunc(oggpack_buffer *b,long bits);
  107424. extern void oggpackB_writealign(oggpack_buffer *b);
  107425. extern void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits);
  107426. extern void oggpackB_reset(oggpack_buffer *b);
  107427. extern void oggpackB_writeclear(oggpack_buffer *b);
  107428. extern void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  107429. extern void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits);
  107430. extern long oggpackB_look(oggpack_buffer *b,int bits);
  107431. extern long oggpackB_look1(oggpack_buffer *b);
  107432. extern void oggpackB_adv(oggpack_buffer *b,int bits);
  107433. extern void oggpackB_adv1(oggpack_buffer *b);
  107434. extern long oggpackB_read(oggpack_buffer *b,int bits);
  107435. extern long oggpackB_read1(oggpack_buffer *b);
  107436. extern long oggpackB_bytes(oggpack_buffer *b);
  107437. extern long oggpackB_bits(oggpack_buffer *b);
  107438. extern unsigned char *oggpackB_get_buffer(oggpack_buffer *b);
  107439. /* Ogg BITSTREAM PRIMITIVES: encoding **************************/
  107440. extern int ogg_stream_packetin(ogg_stream_state *os, ogg_packet *op);
  107441. extern int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og);
  107442. extern int ogg_stream_flush(ogg_stream_state *os, ogg_page *og);
  107443. /* Ogg BITSTREAM PRIMITIVES: decoding **************************/
  107444. extern int ogg_sync_init(ogg_sync_state *oy);
  107445. extern int ogg_sync_clear(ogg_sync_state *oy);
  107446. extern int ogg_sync_reset(ogg_sync_state *oy);
  107447. extern int ogg_sync_destroy(ogg_sync_state *oy);
  107448. extern char *ogg_sync_buffer(ogg_sync_state *oy, long size);
  107449. extern int ogg_sync_wrote(ogg_sync_state *oy, long bytes);
  107450. extern long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og);
  107451. extern int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og);
  107452. extern int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og);
  107453. extern int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op);
  107454. extern int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op);
  107455. /* Ogg BITSTREAM PRIMITIVES: general ***************************/
  107456. extern int ogg_stream_init(ogg_stream_state *os,int serialno);
  107457. extern int ogg_stream_clear(ogg_stream_state *os);
  107458. extern int ogg_stream_reset(ogg_stream_state *os);
  107459. extern int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno);
  107460. extern int ogg_stream_destroy(ogg_stream_state *os);
  107461. extern int ogg_stream_eos(ogg_stream_state *os);
  107462. extern void ogg_page_checksum_set(ogg_page *og);
  107463. extern int ogg_page_version(ogg_page *og);
  107464. extern int ogg_page_continued(ogg_page *og);
  107465. extern int ogg_page_bos(ogg_page *og);
  107466. extern int ogg_page_eos(ogg_page *og);
  107467. extern ogg_int64_t ogg_page_granulepos(ogg_page *og);
  107468. extern int ogg_page_serialno(ogg_page *og);
  107469. extern long ogg_page_pageno(ogg_page *og);
  107470. extern int ogg_page_packets(ogg_page *og);
  107471. extern void ogg_packet_clear(ogg_packet *op);
  107472. #ifdef __cplusplus
  107473. }
  107474. #endif
  107475. #endif /* _OGG_H */
  107476. /*** End of inlined file: ogg.h ***/
  107477. typedef struct vorbis_info{
  107478. int version;
  107479. int channels;
  107480. long rate;
  107481. /* The below bitrate declarations are *hints*.
  107482. Combinations of the three values carry the following implications:
  107483. all three set to the same value:
  107484. implies a fixed rate bitstream
  107485. only nominal set:
  107486. implies a VBR stream that averages the nominal bitrate. No hard
  107487. upper/lower limit
  107488. upper and or lower set:
  107489. implies a VBR bitstream that obeys the bitrate limits. nominal
  107490. may also be set to give a nominal rate.
  107491. none set:
  107492. the coder does not care to speculate.
  107493. */
  107494. long bitrate_upper;
  107495. long bitrate_nominal;
  107496. long bitrate_lower;
  107497. long bitrate_window;
  107498. void *codec_setup;
  107499. } vorbis_info;
  107500. /* vorbis_dsp_state buffers the current vorbis audio
  107501. analysis/synthesis state. The DSP state belongs to a specific
  107502. logical bitstream ****************************************************/
  107503. typedef struct vorbis_dsp_state{
  107504. int analysisp;
  107505. vorbis_info *vi;
  107506. float **pcm;
  107507. float **pcmret;
  107508. int pcm_storage;
  107509. int pcm_current;
  107510. int pcm_returned;
  107511. int preextrapolate;
  107512. int eofflag;
  107513. long lW;
  107514. long W;
  107515. long nW;
  107516. long centerW;
  107517. ogg_int64_t granulepos;
  107518. ogg_int64_t sequence;
  107519. ogg_int64_t glue_bits;
  107520. ogg_int64_t time_bits;
  107521. ogg_int64_t floor_bits;
  107522. ogg_int64_t res_bits;
  107523. void *backend_state;
  107524. } vorbis_dsp_state;
  107525. typedef struct vorbis_block{
  107526. /* necessary stream state for linking to the framing abstraction */
  107527. float **pcm; /* this is a pointer into local storage */
  107528. oggpack_buffer opb;
  107529. long lW;
  107530. long W;
  107531. long nW;
  107532. int pcmend;
  107533. int mode;
  107534. int eofflag;
  107535. ogg_int64_t granulepos;
  107536. ogg_int64_t sequence;
  107537. vorbis_dsp_state *vd; /* For read-only access of configuration */
  107538. /* local storage to avoid remallocing; it's up to the mapping to
  107539. structure it */
  107540. void *localstore;
  107541. long localtop;
  107542. long localalloc;
  107543. long totaluse;
  107544. struct alloc_chain *reap;
  107545. /* bitmetrics for the frame */
  107546. long glue_bits;
  107547. long time_bits;
  107548. long floor_bits;
  107549. long res_bits;
  107550. void *internal;
  107551. } vorbis_block;
  107552. /* vorbis_block is a single block of data to be processed as part of
  107553. the analysis/synthesis stream; it belongs to a specific logical
  107554. bitstream, but is independant from other vorbis_blocks belonging to
  107555. that logical bitstream. *************************************************/
  107556. struct alloc_chain{
  107557. void *ptr;
  107558. struct alloc_chain *next;
  107559. };
  107560. /* vorbis_info contains all the setup information specific to the
  107561. specific compression/decompression mode in progress (eg,
  107562. psychoacoustic settings, channel setup, options, codebook
  107563. etc). vorbis_info and substructures are in backends.h.
  107564. *********************************************************************/
  107565. /* the comments are not part of vorbis_info so that vorbis_info can be
  107566. static storage */
  107567. typedef struct vorbis_comment{
  107568. /* unlimited user comment fields. libvorbis writes 'libvorbis'
  107569. whatever vendor is set to in encode */
  107570. char **user_comments;
  107571. int *comment_lengths;
  107572. int comments;
  107573. char *vendor;
  107574. } vorbis_comment;
  107575. /* libvorbis encodes in two abstraction layers; first we perform DSP
  107576. and produce a packet (see docs/analysis.txt). The packet is then
  107577. coded into a framed OggSquish bitstream by the second layer (see
  107578. docs/framing.txt). Decode is the reverse process; we sync/frame
  107579. the bitstream and extract individual packets, then decode the
  107580. packet back into PCM audio.
  107581. The extra framing/packetizing is used in streaming formats, such as
  107582. files. Over the net (such as with UDP), the framing and
  107583. packetization aren't necessary as they're provided by the transport
  107584. and the streaming layer is not used */
  107585. /* Vorbis PRIMITIVES: general ***************************************/
  107586. extern void vorbis_info_init(vorbis_info *vi);
  107587. extern void vorbis_info_clear(vorbis_info *vi);
  107588. extern int vorbis_info_blocksize(vorbis_info *vi,int zo);
  107589. extern void vorbis_comment_init(vorbis_comment *vc);
  107590. extern void vorbis_comment_add(vorbis_comment *vc, char *comment);
  107591. extern void vorbis_comment_add_tag(vorbis_comment *vc,
  107592. const char *tag, char *contents);
  107593. extern char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count);
  107594. extern int vorbis_comment_query_count(vorbis_comment *vc, char *tag);
  107595. extern void vorbis_comment_clear(vorbis_comment *vc);
  107596. extern int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb);
  107597. extern int vorbis_block_clear(vorbis_block *vb);
  107598. extern void vorbis_dsp_clear(vorbis_dsp_state *v);
  107599. extern double vorbis_granule_time(vorbis_dsp_state *v,
  107600. ogg_int64_t granulepos);
  107601. /* Vorbis PRIMITIVES: analysis/DSP layer ****************************/
  107602. extern int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi);
  107603. extern int vorbis_commentheader_out(vorbis_comment *vc, ogg_packet *op);
  107604. extern int vorbis_analysis_headerout(vorbis_dsp_state *v,
  107605. vorbis_comment *vc,
  107606. ogg_packet *op,
  107607. ogg_packet *op_comm,
  107608. ogg_packet *op_code);
  107609. extern float **vorbis_analysis_buffer(vorbis_dsp_state *v,int vals);
  107610. extern int vorbis_analysis_wrote(vorbis_dsp_state *v,int vals);
  107611. extern int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb);
  107612. extern int vorbis_analysis(vorbis_block *vb,ogg_packet *op);
  107613. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  107614. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,
  107615. ogg_packet *op);
  107616. /* Vorbis PRIMITIVES: synthesis layer *******************************/
  107617. extern int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,
  107618. ogg_packet *op);
  107619. extern int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi);
  107620. extern int vorbis_synthesis_restart(vorbis_dsp_state *v);
  107621. extern int vorbis_synthesis(vorbis_block *vb,ogg_packet *op);
  107622. extern int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op);
  107623. extern int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb);
  107624. extern int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm);
  107625. extern int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm);
  107626. extern int vorbis_synthesis_read(vorbis_dsp_state *v,int samples);
  107627. extern long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op);
  107628. extern int vorbis_synthesis_halfrate(vorbis_info *v,int flag);
  107629. extern int vorbis_synthesis_halfrate_p(vorbis_info *v);
  107630. /* Vorbis ERRORS and return codes ***********************************/
  107631. #define OV_FALSE -1
  107632. #define OV_EOF -2
  107633. #define OV_HOLE -3
  107634. #define OV_EREAD -128
  107635. #define OV_EFAULT -129
  107636. #define OV_EIMPL -130
  107637. #define OV_EINVAL -131
  107638. #define OV_ENOTVORBIS -132
  107639. #define OV_EBADHEADER -133
  107640. #define OV_EVERSION -134
  107641. #define OV_ENOTAUDIO -135
  107642. #define OV_EBADPACKET -136
  107643. #define OV_EBADLINK -137
  107644. #define OV_ENOSEEK -138
  107645. #ifdef __cplusplus
  107646. }
  107647. #endif /* __cplusplus */
  107648. #endif
  107649. /*** End of inlined file: codec.h ***/
  107650. extern int vorbis_encode_init(vorbis_info *vi,
  107651. long channels,
  107652. long rate,
  107653. long max_bitrate,
  107654. long nominal_bitrate,
  107655. long min_bitrate);
  107656. extern int vorbis_encode_setup_managed(vorbis_info *vi,
  107657. long channels,
  107658. long rate,
  107659. long max_bitrate,
  107660. long nominal_bitrate,
  107661. long min_bitrate);
  107662. extern int vorbis_encode_setup_vbr(vorbis_info *vi,
  107663. long channels,
  107664. long rate,
  107665. float quality /* quality level from 0. (lo) to 1. (hi) */
  107666. );
  107667. extern int vorbis_encode_init_vbr(vorbis_info *vi,
  107668. long channels,
  107669. long rate,
  107670. float base_quality /* quality level from 0. (lo) to 1. (hi) */
  107671. );
  107672. extern int vorbis_encode_setup_init(vorbis_info *vi);
  107673. extern int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg);
  107674. /* deprecated rate management supported only for compatability */
  107675. #define OV_ECTL_RATEMANAGE_GET 0x10
  107676. #define OV_ECTL_RATEMANAGE_SET 0x11
  107677. #define OV_ECTL_RATEMANAGE_AVG 0x12
  107678. #define OV_ECTL_RATEMANAGE_HARD 0x13
  107679. struct ovectl_ratemanage_arg {
  107680. int management_active;
  107681. long bitrate_hard_min;
  107682. long bitrate_hard_max;
  107683. double bitrate_hard_window;
  107684. long bitrate_av_lo;
  107685. long bitrate_av_hi;
  107686. double bitrate_av_window;
  107687. double bitrate_av_window_center;
  107688. };
  107689. /* new rate setup */
  107690. #define OV_ECTL_RATEMANAGE2_GET 0x14
  107691. #define OV_ECTL_RATEMANAGE2_SET 0x15
  107692. struct ovectl_ratemanage2_arg {
  107693. int management_active;
  107694. long bitrate_limit_min_kbps;
  107695. long bitrate_limit_max_kbps;
  107696. long bitrate_limit_reservoir_bits;
  107697. double bitrate_limit_reservoir_bias;
  107698. long bitrate_average_kbps;
  107699. double bitrate_average_damping;
  107700. };
  107701. #define OV_ECTL_LOWPASS_GET 0x20
  107702. #define OV_ECTL_LOWPASS_SET 0x21
  107703. #define OV_ECTL_IBLOCK_GET 0x30
  107704. #define OV_ECTL_IBLOCK_SET 0x31
  107705. #ifdef __cplusplus
  107706. }
  107707. #endif /* __cplusplus */
  107708. #endif
  107709. /*** End of inlined file: vorbisenc.h ***/
  107710. /*** Start of inlined file: vorbisfile.h ***/
  107711. #ifndef _OV_FILE_H_
  107712. #define _OV_FILE_H_
  107713. #ifdef __cplusplus
  107714. extern "C"
  107715. {
  107716. #endif /* __cplusplus */
  107717. #include <stdio.h>
  107718. /* The function prototypes for the callbacks are basically the same as for
  107719. * the stdio functions fread, fseek, fclose, ftell.
  107720. * The one difference is that the FILE * arguments have been replaced with
  107721. * a void * - this is to be used as a pointer to whatever internal data these
  107722. * functions might need. In the stdio case, it's just a FILE * cast to a void *
  107723. *
  107724. * If you use other functions, check the docs for these functions and return
  107725. * the right values. For seek_func(), you *MUST* return -1 if the stream is
  107726. * unseekable
  107727. */
  107728. typedef struct {
  107729. size_t (*read_func) (void *ptr, size_t size, size_t nmemb, void *datasource);
  107730. int (*seek_func) (void *datasource, ogg_int64_t offset, int whence);
  107731. int (*close_func) (void *datasource);
  107732. long (*tell_func) (void *datasource);
  107733. } ov_callbacks;
  107734. #define NOTOPEN 0
  107735. #define PARTOPEN 1
  107736. #define OPENED 2
  107737. #define STREAMSET 3
  107738. #define INITSET 4
  107739. typedef struct OggVorbis_File {
  107740. void *datasource; /* Pointer to a FILE *, etc. */
  107741. int seekable;
  107742. ogg_int64_t offset;
  107743. ogg_int64_t end;
  107744. ogg_sync_state oy;
  107745. /* If the FILE handle isn't seekable (eg, a pipe), only the current
  107746. stream appears */
  107747. int links;
  107748. ogg_int64_t *offsets;
  107749. ogg_int64_t *dataoffsets;
  107750. long *serialnos;
  107751. ogg_int64_t *pcmlengths; /* overloaded to maintain binary
  107752. compatability; x2 size, stores both
  107753. beginning and end values */
  107754. vorbis_info *vi;
  107755. vorbis_comment *vc;
  107756. /* Decoding working state local storage */
  107757. ogg_int64_t pcm_offset;
  107758. int ready_state;
  107759. long current_serialno;
  107760. int current_link;
  107761. double bittrack;
  107762. double samptrack;
  107763. ogg_stream_state os; /* take physical pages, weld into a logical
  107764. stream of packets */
  107765. vorbis_dsp_state vd; /* central working state for the packet->PCM decoder */
  107766. vorbis_block vb; /* local working space for packet->PCM decode */
  107767. ov_callbacks callbacks;
  107768. } OggVorbis_File;
  107769. extern int ov_clear(OggVorbis_File *vf);
  107770. extern int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  107771. extern int ov_open_callbacks(void *datasource, OggVorbis_File *vf,
  107772. char *initial, long ibytes, ov_callbacks callbacks);
  107773. extern int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  107774. extern int ov_test_callbacks(void *datasource, OggVorbis_File *vf,
  107775. char *initial, long ibytes, ov_callbacks callbacks);
  107776. extern int ov_test_open(OggVorbis_File *vf);
  107777. extern long ov_bitrate(OggVorbis_File *vf,int i);
  107778. extern long ov_bitrate_instant(OggVorbis_File *vf);
  107779. extern long ov_streams(OggVorbis_File *vf);
  107780. extern long ov_seekable(OggVorbis_File *vf);
  107781. extern long ov_serialnumber(OggVorbis_File *vf,int i);
  107782. extern ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i);
  107783. extern ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i);
  107784. extern double ov_time_total(OggVorbis_File *vf,int i);
  107785. extern int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos);
  107786. extern int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos);
  107787. extern int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos);
  107788. extern int ov_time_seek(OggVorbis_File *vf,double pos);
  107789. extern int ov_time_seek_page(OggVorbis_File *vf,double pos);
  107790. extern int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107791. extern int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107792. extern int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107793. extern int ov_time_seek_lap(OggVorbis_File *vf,double pos);
  107794. extern int ov_time_seek_page_lap(OggVorbis_File *vf,double pos);
  107795. extern ogg_int64_t ov_raw_tell(OggVorbis_File *vf);
  107796. extern ogg_int64_t ov_pcm_tell(OggVorbis_File *vf);
  107797. extern double ov_time_tell(OggVorbis_File *vf);
  107798. extern vorbis_info *ov_info(OggVorbis_File *vf,int link);
  107799. extern vorbis_comment *ov_comment(OggVorbis_File *vf,int link);
  107800. extern long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int samples,
  107801. int *bitstream);
  107802. extern long ov_read(OggVorbis_File *vf,char *buffer,int length,
  107803. int bigendianp,int word,int sgned,int *bitstream);
  107804. extern int ov_crosslap(OggVorbis_File *vf1,OggVorbis_File *vf2);
  107805. extern int ov_halfrate(OggVorbis_File *vf,int flag);
  107806. extern int ov_halfrate_p(OggVorbis_File *vf);
  107807. #ifdef __cplusplus
  107808. }
  107809. #endif /* __cplusplus */
  107810. #endif
  107811. /*** End of inlined file: vorbisfile.h ***/
  107812. /*** Start of inlined file: bitwise.c ***/
  107813. /* We're 'LSb' endian; if we write a word but read individual bits,
  107814. then we'll read the lsb first */
  107815. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  107816. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107817. // tasks..
  107818. #if JUCE_MSVC
  107819. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107820. #endif
  107821. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  107822. #if JUCE_USE_OGGVORBIS
  107823. #include <string.h>
  107824. #include <stdlib.h>
  107825. #define BUFFER_INCREMENT 256
  107826. static const unsigned long mask[]=
  107827. {0x00000000,0x00000001,0x00000003,0x00000007,0x0000000f,
  107828. 0x0000001f,0x0000003f,0x0000007f,0x000000ff,0x000001ff,
  107829. 0x000003ff,0x000007ff,0x00000fff,0x00001fff,0x00003fff,
  107830. 0x00007fff,0x0000ffff,0x0001ffff,0x0003ffff,0x0007ffff,
  107831. 0x000fffff,0x001fffff,0x003fffff,0x007fffff,0x00ffffff,
  107832. 0x01ffffff,0x03ffffff,0x07ffffff,0x0fffffff,0x1fffffff,
  107833. 0x3fffffff,0x7fffffff,0xffffffff };
  107834. static const unsigned int mask8B[]=
  107835. {0x00,0x80,0xc0,0xe0,0xf0,0xf8,0xfc,0xfe,0xff};
  107836. void oggpack_writeinit(oggpack_buffer *b){
  107837. memset(b,0,sizeof(*b));
  107838. b->ptr=b->buffer=(unsigned char*) _ogg_malloc(BUFFER_INCREMENT);
  107839. b->buffer[0]='\0';
  107840. b->storage=BUFFER_INCREMENT;
  107841. }
  107842. void oggpackB_writeinit(oggpack_buffer *b){
  107843. oggpack_writeinit(b);
  107844. }
  107845. void oggpack_writetrunc(oggpack_buffer *b,long bits){
  107846. long bytes=bits>>3;
  107847. bits-=bytes*8;
  107848. b->ptr=b->buffer+bytes;
  107849. b->endbit=bits;
  107850. b->endbyte=bytes;
  107851. *b->ptr&=mask[bits];
  107852. }
  107853. void oggpackB_writetrunc(oggpack_buffer *b,long bits){
  107854. long bytes=bits>>3;
  107855. bits-=bytes*8;
  107856. b->ptr=b->buffer+bytes;
  107857. b->endbit=bits;
  107858. b->endbyte=bytes;
  107859. *b->ptr&=mask8B[bits];
  107860. }
  107861. /* Takes only up to 32 bits. */
  107862. void oggpack_write(oggpack_buffer *b,unsigned long value,int bits){
  107863. if(b->endbyte+4>=b->storage){
  107864. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  107865. b->storage+=BUFFER_INCREMENT;
  107866. b->ptr=b->buffer+b->endbyte;
  107867. }
  107868. value&=mask[bits];
  107869. bits+=b->endbit;
  107870. b->ptr[0]|=value<<b->endbit;
  107871. if(bits>=8){
  107872. b->ptr[1]=(unsigned char)(value>>(8-b->endbit));
  107873. if(bits>=16){
  107874. b->ptr[2]=(unsigned char)(value>>(16-b->endbit));
  107875. if(bits>=24){
  107876. b->ptr[3]=(unsigned char)(value>>(24-b->endbit));
  107877. if(bits>=32){
  107878. if(b->endbit)
  107879. b->ptr[4]=(unsigned char)(value>>(32-b->endbit));
  107880. else
  107881. b->ptr[4]=0;
  107882. }
  107883. }
  107884. }
  107885. }
  107886. b->endbyte+=bits/8;
  107887. b->ptr+=bits/8;
  107888. b->endbit=bits&7;
  107889. }
  107890. /* Takes only up to 32 bits. */
  107891. void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits){
  107892. if(b->endbyte+4>=b->storage){
  107893. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  107894. b->storage+=BUFFER_INCREMENT;
  107895. b->ptr=b->buffer+b->endbyte;
  107896. }
  107897. value=(value&mask[bits])<<(32-bits);
  107898. bits+=b->endbit;
  107899. b->ptr[0]|=value>>(24+b->endbit);
  107900. if(bits>=8){
  107901. b->ptr[1]=(unsigned char)(value>>(16+b->endbit));
  107902. if(bits>=16){
  107903. b->ptr[2]=(unsigned char)(value>>(8+b->endbit));
  107904. if(bits>=24){
  107905. b->ptr[3]=(unsigned char)(value>>(b->endbit));
  107906. if(bits>=32){
  107907. if(b->endbit)
  107908. b->ptr[4]=(unsigned char)(value<<(8-b->endbit));
  107909. else
  107910. b->ptr[4]=0;
  107911. }
  107912. }
  107913. }
  107914. }
  107915. b->endbyte+=bits/8;
  107916. b->ptr+=bits/8;
  107917. b->endbit=bits&7;
  107918. }
  107919. void oggpack_writealign(oggpack_buffer *b){
  107920. int bits=8-b->endbit;
  107921. if(bits<8)
  107922. oggpack_write(b,0,bits);
  107923. }
  107924. void oggpackB_writealign(oggpack_buffer *b){
  107925. int bits=8-b->endbit;
  107926. if(bits<8)
  107927. oggpackB_write(b,0,bits);
  107928. }
  107929. static void oggpack_writecopy_helper(oggpack_buffer *b,
  107930. void *source,
  107931. long bits,
  107932. void (*w)(oggpack_buffer *,
  107933. unsigned long,
  107934. int),
  107935. int msb){
  107936. unsigned char *ptr=(unsigned char *)source;
  107937. long bytes=bits/8;
  107938. bits-=bytes*8;
  107939. if(b->endbit){
  107940. int i;
  107941. /* unaligned copy. Do it the hard way. */
  107942. for(i=0;i<bytes;i++)
  107943. w(b,(unsigned long)(ptr[i]),8);
  107944. }else{
  107945. /* aligned block copy */
  107946. if(b->endbyte+bytes+1>=b->storage){
  107947. b->storage=b->endbyte+bytes+BUFFER_INCREMENT;
  107948. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage);
  107949. b->ptr=b->buffer+b->endbyte;
  107950. }
  107951. memmove(b->ptr,source,bytes);
  107952. b->ptr+=bytes;
  107953. b->endbyte+=bytes;
  107954. *b->ptr=0;
  107955. }
  107956. if(bits){
  107957. if(msb)
  107958. w(b,(unsigned long)(ptr[bytes]>>(8-bits)),bits);
  107959. else
  107960. w(b,(unsigned long)(ptr[bytes]),bits);
  107961. }
  107962. }
  107963. void oggpack_writecopy(oggpack_buffer *b,void *source,long bits){
  107964. oggpack_writecopy_helper(b,source,bits,oggpack_write,0);
  107965. }
  107966. void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits){
  107967. oggpack_writecopy_helper(b,source,bits,oggpackB_write,1);
  107968. }
  107969. void oggpack_reset(oggpack_buffer *b){
  107970. b->ptr=b->buffer;
  107971. b->buffer[0]=0;
  107972. b->endbit=b->endbyte=0;
  107973. }
  107974. void oggpackB_reset(oggpack_buffer *b){
  107975. oggpack_reset(b);
  107976. }
  107977. void oggpack_writeclear(oggpack_buffer *b){
  107978. _ogg_free(b->buffer);
  107979. memset(b,0,sizeof(*b));
  107980. }
  107981. void oggpackB_writeclear(oggpack_buffer *b){
  107982. oggpack_writeclear(b);
  107983. }
  107984. void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  107985. memset(b,0,sizeof(*b));
  107986. b->buffer=b->ptr=buf;
  107987. b->storage=bytes;
  107988. }
  107989. void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  107990. oggpack_readinit(b,buf,bytes);
  107991. }
  107992. /* Read in bits without advancing the bitptr; bits <= 32 */
  107993. long oggpack_look(oggpack_buffer *b,int bits){
  107994. unsigned long ret;
  107995. unsigned long m=mask[bits];
  107996. bits+=b->endbit;
  107997. if(b->endbyte+4>=b->storage){
  107998. /* not the main path */
  107999. if(b->endbyte*8+bits>b->storage*8)return(-1);
  108000. }
  108001. ret=b->ptr[0]>>b->endbit;
  108002. if(bits>8){
  108003. ret|=b->ptr[1]<<(8-b->endbit);
  108004. if(bits>16){
  108005. ret|=b->ptr[2]<<(16-b->endbit);
  108006. if(bits>24){
  108007. ret|=b->ptr[3]<<(24-b->endbit);
  108008. if(bits>32 && b->endbit)
  108009. ret|=b->ptr[4]<<(32-b->endbit);
  108010. }
  108011. }
  108012. }
  108013. return(m&ret);
  108014. }
  108015. /* Read in bits without advancing the bitptr; bits <= 32 */
  108016. long oggpackB_look(oggpack_buffer *b,int bits){
  108017. unsigned long ret;
  108018. int m=32-bits;
  108019. bits+=b->endbit;
  108020. if(b->endbyte+4>=b->storage){
  108021. /* not the main path */
  108022. if(b->endbyte*8+bits>b->storage*8)return(-1);
  108023. }
  108024. ret=b->ptr[0]<<(24+b->endbit);
  108025. if(bits>8){
  108026. ret|=b->ptr[1]<<(16+b->endbit);
  108027. if(bits>16){
  108028. ret|=b->ptr[2]<<(8+b->endbit);
  108029. if(bits>24){
  108030. ret|=b->ptr[3]<<(b->endbit);
  108031. if(bits>32 && b->endbit)
  108032. ret|=b->ptr[4]>>(8-b->endbit);
  108033. }
  108034. }
  108035. }
  108036. return ((ret&0xffffffff)>>(m>>1))>>((m+1)>>1);
  108037. }
  108038. long oggpack_look1(oggpack_buffer *b){
  108039. if(b->endbyte>=b->storage)return(-1);
  108040. return((b->ptr[0]>>b->endbit)&1);
  108041. }
  108042. long oggpackB_look1(oggpack_buffer *b){
  108043. if(b->endbyte>=b->storage)return(-1);
  108044. return((b->ptr[0]>>(7-b->endbit))&1);
  108045. }
  108046. void oggpack_adv(oggpack_buffer *b,int bits){
  108047. bits+=b->endbit;
  108048. b->ptr+=bits/8;
  108049. b->endbyte+=bits/8;
  108050. b->endbit=bits&7;
  108051. }
  108052. void oggpackB_adv(oggpack_buffer *b,int bits){
  108053. oggpack_adv(b,bits);
  108054. }
  108055. void oggpack_adv1(oggpack_buffer *b){
  108056. if(++(b->endbit)>7){
  108057. b->endbit=0;
  108058. b->ptr++;
  108059. b->endbyte++;
  108060. }
  108061. }
  108062. void oggpackB_adv1(oggpack_buffer *b){
  108063. oggpack_adv1(b);
  108064. }
  108065. /* bits <= 32 */
  108066. long oggpack_read(oggpack_buffer *b,int bits){
  108067. long ret;
  108068. unsigned long m=mask[bits];
  108069. bits+=b->endbit;
  108070. if(b->endbyte+4>=b->storage){
  108071. /* not the main path */
  108072. ret=-1L;
  108073. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  108074. }
  108075. ret=b->ptr[0]>>b->endbit;
  108076. if(bits>8){
  108077. ret|=b->ptr[1]<<(8-b->endbit);
  108078. if(bits>16){
  108079. ret|=b->ptr[2]<<(16-b->endbit);
  108080. if(bits>24){
  108081. ret|=b->ptr[3]<<(24-b->endbit);
  108082. if(bits>32 && b->endbit){
  108083. ret|=b->ptr[4]<<(32-b->endbit);
  108084. }
  108085. }
  108086. }
  108087. }
  108088. ret&=m;
  108089. overflow:
  108090. b->ptr+=bits/8;
  108091. b->endbyte+=bits/8;
  108092. b->endbit=bits&7;
  108093. return(ret);
  108094. }
  108095. /* bits <= 32 */
  108096. long oggpackB_read(oggpack_buffer *b,int bits){
  108097. long ret;
  108098. long m=32-bits;
  108099. bits+=b->endbit;
  108100. if(b->endbyte+4>=b->storage){
  108101. /* not the main path */
  108102. ret=-1L;
  108103. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  108104. }
  108105. ret=b->ptr[0]<<(24+b->endbit);
  108106. if(bits>8){
  108107. ret|=b->ptr[1]<<(16+b->endbit);
  108108. if(bits>16){
  108109. ret|=b->ptr[2]<<(8+b->endbit);
  108110. if(bits>24){
  108111. ret|=b->ptr[3]<<(b->endbit);
  108112. if(bits>32 && b->endbit)
  108113. ret|=b->ptr[4]>>(8-b->endbit);
  108114. }
  108115. }
  108116. }
  108117. ret=((ret&0xffffffffUL)>>(m>>1))>>((m+1)>>1);
  108118. overflow:
  108119. b->ptr+=bits/8;
  108120. b->endbyte+=bits/8;
  108121. b->endbit=bits&7;
  108122. return(ret);
  108123. }
  108124. long oggpack_read1(oggpack_buffer *b){
  108125. long ret;
  108126. if(b->endbyte>=b->storage){
  108127. /* not the main path */
  108128. ret=-1L;
  108129. goto overflow;
  108130. }
  108131. ret=(b->ptr[0]>>b->endbit)&1;
  108132. overflow:
  108133. b->endbit++;
  108134. if(b->endbit>7){
  108135. b->endbit=0;
  108136. b->ptr++;
  108137. b->endbyte++;
  108138. }
  108139. return(ret);
  108140. }
  108141. long oggpackB_read1(oggpack_buffer *b){
  108142. long ret;
  108143. if(b->endbyte>=b->storage){
  108144. /* not the main path */
  108145. ret=-1L;
  108146. goto overflow;
  108147. }
  108148. ret=(b->ptr[0]>>(7-b->endbit))&1;
  108149. overflow:
  108150. b->endbit++;
  108151. if(b->endbit>7){
  108152. b->endbit=0;
  108153. b->ptr++;
  108154. b->endbyte++;
  108155. }
  108156. return(ret);
  108157. }
  108158. long oggpack_bytes(oggpack_buffer *b){
  108159. return(b->endbyte+(b->endbit+7)/8);
  108160. }
  108161. long oggpack_bits(oggpack_buffer *b){
  108162. return(b->endbyte*8+b->endbit);
  108163. }
  108164. long oggpackB_bytes(oggpack_buffer *b){
  108165. return oggpack_bytes(b);
  108166. }
  108167. long oggpackB_bits(oggpack_buffer *b){
  108168. return oggpack_bits(b);
  108169. }
  108170. unsigned char *oggpack_get_buffer(oggpack_buffer *b){
  108171. return(b->buffer);
  108172. }
  108173. unsigned char *oggpackB_get_buffer(oggpack_buffer *b){
  108174. return oggpack_get_buffer(b);
  108175. }
  108176. /* Self test of the bitwise routines; everything else is based on
  108177. them, so they damned well better be solid. */
  108178. #ifdef _V_SELFTEST
  108179. #include <stdio.h>
  108180. static int ilog(unsigned int v){
  108181. int ret=0;
  108182. while(v){
  108183. ret++;
  108184. v>>=1;
  108185. }
  108186. return(ret);
  108187. }
  108188. oggpack_buffer o;
  108189. oggpack_buffer r;
  108190. void report(char *in){
  108191. fprintf(stderr,"%s",in);
  108192. exit(1);
  108193. }
  108194. void cliptest(unsigned long *b,int vals,int bits,int *comp,int compsize){
  108195. long bytes,i;
  108196. unsigned char *buffer;
  108197. oggpack_reset(&o);
  108198. for(i=0;i<vals;i++)
  108199. oggpack_write(&o,b[i],bits?bits:ilog(b[i]));
  108200. buffer=oggpack_get_buffer(&o);
  108201. bytes=oggpack_bytes(&o);
  108202. if(bytes!=compsize)report("wrong number of bytes!\n");
  108203. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  108204. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  108205. report("wrote incorrect value!\n");
  108206. }
  108207. oggpack_readinit(&r,buffer,bytes);
  108208. for(i=0;i<vals;i++){
  108209. int tbit=bits?bits:ilog(b[i]);
  108210. if(oggpack_look(&r,tbit)==-1)
  108211. report("out of data!\n");
  108212. if(oggpack_look(&r,tbit)!=(b[i]&mask[tbit]))
  108213. report("looked at incorrect value!\n");
  108214. if(tbit==1)
  108215. if(oggpack_look1(&r)!=(b[i]&mask[tbit]))
  108216. report("looked at single bit incorrect value!\n");
  108217. if(tbit==1){
  108218. if(oggpack_read1(&r)!=(b[i]&mask[tbit]))
  108219. report("read incorrect single bit value!\n");
  108220. }else{
  108221. if(oggpack_read(&r,tbit)!=(b[i]&mask[tbit]))
  108222. report("read incorrect value!\n");
  108223. }
  108224. }
  108225. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108226. }
  108227. void cliptestB(unsigned long *b,int vals,int bits,int *comp,int compsize){
  108228. long bytes,i;
  108229. unsigned char *buffer;
  108230. oggpackB_reset(&o);
  108231. for(i=0;i<vals;i++)
  108232. oggpackB_write(&o,b[i],bits?bits:ilog(b[i]));
  108233. buffer=oggpackB_get_buffer(&o);
  108234. bytes=oggpackB_bytes(&o);
  108235. if(bytes!=compsize)report("wrong number of bytes!\n");
  108236. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  108237. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  108238. report("wrote incorrect value!\n");
  108239. }
  108240. oggpackB_readinit(&r,buffer,bytes);
  108241. for(i=0;i<vals;i++){
  108242. int tbit=bits?bits:ilog(b[i]);
  108243. if(oggpackB_look(&r,tbit)==-1)
  108244. report("out of data!\n");
  108245. if(oggpackB_look(&r,tbit)!=(b[i]&mask[tbit]))
  108246. report("looked at incorrect value!\n");
  108247. if(tbit==1)
  108248. if(oggpackB_look1(&r)!=(b[i]&mask[tbit]))
  108249. report("looked at single bit incorrect value!\n");
  108250. if(tbit==1){
  108251. if(oggpackB_read1(&r)!=(b[i]&mask[tbit]))
  108252. report("read incorrect single bit value!\n");
  108253. }else{
  108254. if(oggpackB_read(&r,tbit)!=(b[i]&mask[tbit]))
  108255. report("read incorrect value!\n");
  108256. }
  108257. }
  108258. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108259. }
  108260. int main(void){
  108261. unsigned char *buffer;
  108262. long bytes,i;
  108263. static unsigned long testbuffer1[]=
  108264. {18,12,103948,4325,543,76,432,52,3,65,4,56,32,42,34,21,1,23,32,546,456,7,
  108265. 567,56,8,8,55,3,52,342,341,4,265,7,67,86,2199,21,7,1,5,1,4};
  108266. int test1size=43;
  108267. static unsigned long testbuffer2[]=
  108268. {216531625L,1237861823,56732452,131,3212421,12325343,34547562,12313212,
  108269. 1233432,534,5,346435231,14436467,7869299,76326614,167548585,
  108270. 85525151,0,12321,1,349528352};
  108271. int test2size=21;
  108272. static unsigned long testbuffer3[]=
  108273. {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,
  108274. 0,1,30,1,1,1,0,0,1,0,0,0,12,0,11,0,1,0,0,1};
  108275. int test3size=56;
  108276. static unsigned long large[]=
  108277. {2136531625L,2137861823,56732452,131,3212421,12325343,34547562,12313212,
  108278. 1233432,534,5,2146435231,14436467,7869299,76326614,167548585,
  108279. 85525151,0,12321,1,2146528352};
  108280. int onesize=33;
  108281. static int one[33]={146,25,44,151,195,15,153,176,233,131,196,65,85,172,47,40,
  108282. 34,242,223,136,35,222,211,86,171,50,225,135,214,75,172,
  108283. 223,4};
  108284. static int oneB[33]={150,101,131,33,203,15,204,216,105,193,156,65,84,85,222,
  108285. 8,139,145,227,126,34,55,244,171,85,100,39,195,173,18,
  108286. 245,251,128};
  108287. int twosize=6;
  108288. static int two[6]={61,255,255,251,231,29};
  108289. static int twoB[6]={247,63,255,253,249,120};
  108290. int threesize=54;
  108291. static int three[54]={169,2,232,252,91,132,156,36,89,13,123,176,144,32,254,
  108292. 142,224,85,59,121,144,79,124,23,67,90,90,216,79,23,83,
  108293. 58,135,196,61,55,129,183,54,101,100,170,37,127,126,10,
  108294. 100,52,4,14,18,86,77,1};
  108295. static int threeB[54]={206,128,42,153,57,8,183,251,13,89,36,30,32,144,183,
  108296. 130,59,240,121,59,85,223,19,228,180,134,33,107,74,98,
  108297. 233,253,196,135,63,2,110,114,50,155,90,127,37,170,104,
  108298. 200,20,254,4,58,106,176,144,0};
  108299. int foursize=38;
  108300. static int four[38]={18,6,163,252,97,194,104,131,32,1,7,82,137,42,129,11,72,
  108301. 132,60,220,112,8,196,109,64,179,86,9,137,195,208,122,169,
  108302. 28,2,133,0,1};
  108303. static int fourB[38]={36,48,102,83,243,24,52,7,4,35,132,10,145,21,2,93,2,41,
  108304. 1,219,184,16,33,184,54,149,170,132,18,30,29,98,229,67,
  108305. 129,10,4,32};
  108306. int fivesize=45;
  108307. static int five[45]={169,2,126,139,144,172,30,4,80,72,240,59,130,218,73,62,
  108308. 241,24,210,44,4,20,0,248,116,49,135,100,110,130,181,169,
  108309. 84,75,159,2,1,0,132,192,8,0,0,18,22};
  108310. static int fiveB[45]={1,84,145,111,245,100,128,8,56,36,40,71,126,78,213,226,
  108311. 124,105,12,0,133,128,0,162,233,242,67,152,77,205,77,
  108312. 172,150,169,129,79,128,0,6,4,32,0,27,9,0};
  108313. int sixsize=7;
  108314. static int six[7]={17,177,170,242,169,19,148};
  108315. static int sixB[7]={136,141,85,79,149,200,41};
  108316. /* Test read/write together */
  108317. /* Later we test against pregenerated bitstreams */
  108318. oggpack_writeinit(&o);
  108319. fprintf(stderr,"\nSmall preclipped packing (LSb): ");
  108320. cliptest(testbuffer1,test1size,0,one,onesize);
  108321. fprintf(stderr,"ok.");
  108322. fprintf(stderr,"\nNull bit call (LSb): ");
  108323. cliptest(testbuffer3,test3size,0,two,twosize);
  108324. fprintf(stderr,"ok.");
  108325. fprintf(stderr,"\nLarge preclipped packing (LSb): ");
  108326. cliptest(testbuffer2,test2size,0,three,threesize);
  108327. fprintf(stderr,"ok.");
  108328. fprintf(stderr,"\n32 bit preclipped packing (LSb): ");
  108329. oggpack_reset(&o);
  108330. for(i=0;i<test2size;i++)
  108331. oggpack_write(&o,large[i],32);
  108332. buffer=oggpack_get_buffer(&o);
  108333. bytes=oggpack_bytes(&o);
  108334. oggpack_readinit(&r,buffer,bytes);
  108335. for(i=0;i<test2size;i++){
  108336. if(oggpack_look(&r,32)==-1)report("out of data. failed!");
  108337. if(oggpack_look(&r,32)!=large[i]){
  108338. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpack_look(&r,32),large[i],
  108339. oggpack_look(&r,32),large[i]);
  108340. report("read incorrect value!\n");
  108341. }
  108342. oggpack_adv(&r,32);
  108343. }
  108344. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108345. fprintf(stderr,"ok.");
  108346. fprintf(stderr,"\nSmall unclipped packing (LSb): ");
  108347. cliptest(testbuffer1,test1size,7,four,foursize);
  108348. fprintf(stderr,"ok.");
  108349. fprintf(stderr,"\nLarge unclipped packing (LSb): ");
  108350. cliptest(testbuffer2,test2size,17,five,fivesize);
  108351. fprintf(stderr,"ok.");
  108352. fprintf(stderr,"\nSingle bit unclipped packing (LSb): ");
  108353. cliptest(testbuffer3,test3size,1,six,sixsize);
  108354. fprintf(stderr,"ok.");
  108355. fprintf(stderr,"\nTesting read past end (LSb): ");
  108356. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108357. for(i=0;i<64;i++){
  108358. if(oggpack_read(&r,1)!=0){
  108359. fprintf(stderr,"failed; got -1 prematurely.\n");
  108360. exit(1);
  108361. }
  108362. }
  108363. if(oggpack_look(&r,1)!=-1 ||
  108364. oggpack_read(&r,1)!=-1){
  108365. fprintf(stderr,"failed; read past end without -1.\n");
  108366. exit(1);
  108367. }
  108368. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108369. if(oggpack_read(&r,30)!=0 || oggpack_read(&r,16)!=0){
  108370. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  108371. exit(1);
  108372. }
  108373. if(oggpack_look(&r,18)!=0 ||
  108374. oggpack_look(&r,18)!=0){
  108375. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  108376. exit(1);
  108377. }
  108378. if(oggpack_look(&r,19)!=-1 ||
  108379. oggpack_look(&r,19)!=-1){
  108380. fprintf(stderr,"failed; read past end without -1.\n");
  108381. exit(1);
  108382. }
  108383. if(oggpack_look(&r,32)!=-1 ||
  108384. oggpack_look(&r,32)!=-1){
  108385. fprintf(stderr,"failed; read past end without -1.\n");
  108386. exit(1);
  108387. }
  108388. oggpack_writeclear(&o);
  108389. fprintf(stderr,"ok.\n");
  108390. /********** lazy, cut-n-paste retest with MSb packing ***********/
  108391. /* Test read/write together */
  108392. /* Later we test against pregenerated bitstreams */
  108393. oggpackB_writeinit(&o);
  108394. fprintf(stderr,"\nSmall preclipped packing (MSb): ");
  108395. cliptestB(testbuffer1,test1size,0,oneB,onesize);
  108396. fprintf(stderr,"ok.");
  108397. fprintf(stderr,"\nNull bit call (MSb): ");
  108398. cliptestB(testbuffer3,test3size,0,twoB,twosize);
  108399. fprintf(stderr,"ok.");
  108400. fprintf(stderr,"\nLarge preclipped packing (MSb): ");
  108401. cliptestB(testbuffer2,test2size,0,threeB,threesize);
  108402. fprintf(stderr,"ok.");
  108403. fprintf(stderr,"\n32 bit preclipped packing (MSb): ");
  108404. oggpackB_reset(&o);
  108405. for(i=0;i<test2size;i++)
  108406. oggpackB_write(&o,large[i],32);
  108407. buffer=oggpackB_get_buffer(&o);
  108408. bytes=oggpackB_bytes(&o);
  108409. oggpackB_readinit(&r,buffer,bytes);
  108410. for(i=0;i<test2size;i++){
  108411. if(oggpackB_look(&r,32)==-1)report("out of data. failed!");
  108412. if(oggpackB_look(&r,32)!=large[i]){
  108413. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpackB_look(&r,32),large[i],
  108414. oggpackB_look(&r,32),large[i]);
  108415. report("read incorrect value!\n");
  108416. }
  108417. oggpackB_adv(&r,32);
  108418. }
  108419. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108420. fprintf(stderr,"ok.");
  108421. fprintf(stderr,"\nSmall unclipped packing (MSb): ");
  108422. cliptestB(testbuffer1,test1size,7,fourB,foursize);
  108423. fprintf(stderr,"ok.");
  108424. fprintf(stderr,"\nLarge unclipped packing (MSb): ");
  108425. cliptestB(testbuffer2,test2size,17,fiveB,fivesize);
  108426. fprintf(stderr,"ok.");
  108427. fprintf(stderr,"\nSingle bit unclipped packing (MSb): ");
  108428. cliptestB(testbuffer3,test3size,1,sixB,sixsize);
  108429. fprintf(stderr,"ok.");
  108430. fprintf(stderr,"\nTesting read past end (MSb): ");
  108431. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108432. for(i=0;i<64;i++){
  108433. if(oggpackB_read(&r,1)!=0){
  108434. fprintf(stderr,"failed; got -1 prematurely.\n");
  108435. exit(1);
  108436. }
  108437. }
  108438. if(oggpackB_look(&r,1)!=-1 ||
  108439. oggpackB_read(&r,1)!=-1){
  108440. fprintf(stderr,"failed; read past end without -1.\n");
  108441. exit(1);
  108442. }
  108443. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108444. if(oggpackB_read(&r,30)!=0 || oggpackB_read(&r,16)!=0){
  108445. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  108446. exit(1);
  108447. }
  108448. if(oggpackB_look(&r,18)!=0 ||
  108449. oggpackB_look(&r,18)!=0){
  108450. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  108451. exit(1);
  108452. }
  108453. if(oggpackB_look(&r,19)!=-1 ||
  108454. oggpackB_look(&r,19)!=-1){
  108455. fprintf(stderr,"failed; read past end without -1.\n");
  108456. exit(1);
  108457. }
  108458. if(oggpackB_look(&r,32)!=-1 ||
  108459. oggpackB_look(&r,32)!=-1){
  108460. fprintf(stderr,"failed; read past end without -1.\n");
  108461. exit(1);
  108462. }
  108463. oggpackB_writeclear(&o);
  108464. fprintf(stderr,"ok.\n\n");
  108465. return(0);
  108466. }
  108467. #endif /* _V_SELFTEST */
  108468. #undef BUFFER_INCREMENT
  108469. #endif
  108470. /*** End of inlined file: bitwise.c ***/
  108471. /*** Start of inlined file: framing.c ***/
  108472. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  108473. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  108474. // tasks..
  108475. #if JUCE_MSVC
  108476. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  108477. #endif
  108478. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  108479. #if JUCE_USE_OGGVORBIS
  108480. #include <stdlib.h>
  108481. #include <string.h>
  108482. /* A complete description of Ogg framing exists in docs/framing.html */
  108483. int ogg_page_version(ogg_page *og){
  108484. return((int)(og->header[4]));
  108485. }
  108486. int ogg_page_continued(ogg_page *og){
  108487. return((int)(og->header[5]&0x01));
  108488. }
  108489. int ogg_page_bos(ogg_page *og){
  108490. return((int)(og->header[5]&0x02));
  108491. }
  108492. int ogg_page_eos(ogg_page *og){
  108493. return((int)(og->header[5]&0x04));
  108494. }
  108495. ogg_int64_t ogg_page_granulepos(ogg_page *og){
  108496. unsigned char *page=og->header;
  108497. ogg_int64_t granulepos=page[13]&(0xff);
  108498. granulepos= (granulepos<<8)|(page[12]&0xff);
  108499. granulepos= (granulepos<<8)|(page[11]&0xff);
  108500. granulepos= (granulepos<<8)|(page[10]&0xff);
  108501. granulepos= (granulepos<<8)|(page[9]&0xff);
  108502. granulepos= (granulepos<<8)|(page[8]&0xff);
  108503. granulepos= (granulepos<<8)|(page[7]&0xff);
  108504. granulepos= (granulepos<<8)|(page[6]&0xff);
  108505. return(granulepos);
  108506. }
  108507. int ogg_page_serialno(ogg_page *og){
  108508. return(og->header[14] |
  108509. (og->header[15]<<8) |
  108510. (og->header[16]<<16) |
  108511. (og->header[17]<<24));
  108512. }
  108513. long ogg_page_pageno(ogg_page *og){
  108514. return(og->header[18] |
  108515. (og->header[19]<<8) |
  108516. (og->header[20]<<16) |
  108517. (og->header[21]<<24));
  108518. }
  108519. /* returns the number of packets that are completed on this page (if
  108520. the leading packet is begun on a previous page, but ends on this
  108521. page, it's counted */
  108522. /* NOTE:
  108523. If a page consists of a packet begun on a previous page, and a new
  108524. packet begun (but not completed) on this page, the return will be:
  108525. ogg_page_packets(page) ==1,
  108526. ogg_page_continued(page) !=0
  108527. If a page happens to be a single packet that was begun on a
  108528. previous page, and spans to the next page (in the case of a three or
  108529. more page packet), the return will be:
  108530. ogg_page_packets(page) ==0,
  108531. ogg_page_continued(page) !=0
  108532. */
  108533. int ogg_page_packets(ogg_page *og){
  108534. int i,n=og->header[26],count=0;
  108535. for(i=0;i<n;i++)
  108536. if(og->header[27+i]<255)count++;
  108537. return(count);
  108538. }
  108539. #if 0
  108540. /* helper to initialize lookup for direct-table CRC (illustrative; we
  108541. use the static init below) */
  108542. static ogg_uint32_t _ogg_crc_entry(unsigned long index){
  108543. int i;
  108544. unsigned long r;
  108545. r = index << 24;
  108546. for (i=0; i<8; i++)
  108547. if (r & 0x80000000UL)
  108548. r = (r << 1) ^ 0x04c11db7; /* The same as the ethernet generator
  108549. polynomial, although we use an
  108550. unreflected alg and an init/final
  108551. of 0, not 0xffffffff */
  108552. else
  108553. r<<=1;
  108554. return (r & 0xffffffffUL);
  108555. }
  108556. #endif
  108557. static const ogg_uint32_t crc_lookup[256]={
  108558. 0x00000000,0x04c11db7,0x09823b6e,0x0d4326d9,
  108559. 0x130476dc,0x17c56b6b,0x1a864db2,0x1e475005,
  108560. 0x2608edb8,0x22c9f00f,0x2f8ad6d6,0x2b4bcb61,
  108561. 0x350c9b64,0x31cd86d3,0x3c8ea00a,0x384fbdbd,
  108562. 0x4c11db70,0x48d0c6c7,0x4593e01e,0x4152fda9,
  108563. 0x5f15adac,0x5bd4b01b,0x569796c2,0x52568b75,
  108564. 0x6a1936c8,0x6ed82b7f,0x639b0da6,0x675a1011,
  108565. 0x791d4014,0x7ddc5da3,0x709f7b7a,0x745e66cd,
  108566. 0x9823b6e0,0x9ce2ab57,0x91a18d8e,0x95609039,
  108567. 0x8b27c03c,0x8fe6dd8b,0x82a5fb52,0x8664e6e5,
  108568. 0xbe2b5b58,0xbaea46ef,0xb7a96036,0xb3687d81,
  108569. 0xad2f2d84,0xa9ee3033,0xa4ad16ea,0xa06c0b5d,
  108570. 0xd4326d90,0xd0f37027,0xddb056fe,0xd9714b49,
  108571. 0xc7361b4c,0xc3f706fb,0xceb42022,0xca753d95,
  108572. 0xf23a8028,0xf6fb9d9f,0xfbb8bb46,0xff79a6f1,
  108573. 0xe13ef6f4,0xe5ffeb43,0xe8bccd9a,0xec7dd02d,
  108574. 0x34867077,0x30476dc0,0x3d044b19,0x39c556ae,
  108575. 0x278206ab,0x23431b1c,0x2e003dc5,0x2ac12072,
  108576. 0x128e9dcf,0x164f8078,0x1b0ca6a1,0x1fcdbb16,
  108577. 0x018aeb13,0x054bf6a4,0x0808d07d,0x0cc9cdca,
  108578. 0x7897ab07,0x7c56b6b0,0x71159069,0x75d48dde,
  108579. 0x6b93dddb,0x6f52c06c,0x6211e6b5,0x66d0fb02,
  108580. 0x5e9f46bf,0x5a5e5b08,0x571d7dd1,0x53dc6066,
  108581. 0x4d9b3063,0x495a2dd4,0x44190b0d,0x40d816ba,
  108582. 0xaca5c697,0xa864db20,0xa527fdf9,0xa1e6e04e,
  108583. 0xbfa1b04b,0xbb60adfc,0xb6238b25,0xb2e29692,
  108584. 0x8aad2b2f,0x8e6c3698,0x832f1041,0x87ee0df6,
  108585. 0x99a95df3,0x9d684044,0x902b669d,0x94ea7b2a,
  108586. 0xe0b41de7,0xe4750050,0xe9362689,0xedf73b3e,
  108587. 0xf3b06b3b,0xf771768c,0xfa325055,0xfef34de2,
  108588. 0xc6bcf05f,0xc27dede8,0xcf3ecb31,0xcbffd686,
  108589. 0xd5b88683,0xd1799b34,0xdc3abded,0xd8fba05a,
  108590. 0x690ce0ee,0x6dcdfd59,0x608edb80,0x644fc637,
  108591. 0x7a089632,0x7ec98b85,0x738aad5c,0x774bb0eb,
  108592. 0x4f040d56,0x4bc510e1,0x46863638,0x42472b8f,
  108593. 0x5c007b8a,0x58c1663d,0x558240e4,0x51435d53,
  108594. 0x251d3b9e,0x21dc2629,0x2c9f00f0,0x285e1d47,
  108595. 0x36194d42,0x32d850f5,0x3f9b762c,0x3b5a6b9b,
  108596. 0x0315d626,0x07d4cb91,0x0a97ed48,0x0e56f0ff,
  108597. 0x1011a0fa,0x14d0bd4d,0x19939b94,0x1d528623,
  108598. 0xf12f560e,0xf5ee4bb9,0xf8ad6d60,0xfc6c70d7,
  108599. 0xe22b20d2,0xe6ea3d65,0xeba91bbc,0xef68060b,
  108600. 0xd727bbb6,0xd3e6a601,0xdea580d8,0xda649d6f,
  108601. 0xc423cd6a,0xc0e2d0dd,0xcda1f604,0xc960ebb3,
  108602. 0xbd3e8d7e,0xb9ff90c9,0xb4bcb610,0xb07daba7,
  108603. 0xae3afba2,0xaafbe615,0xa7b8c0cc,0xa379dd7b,
  108604. 0x9b3660c6,0x9ff77d71,0x92b45ba8,0x9675461f,
  108605. 0x8832161a,0x8cf30bad,0x81b02d74,0x857130c3,
  108606. 0x5d8a9099,0x594b8d2e,0x5408abf7,0x50c9b640,
  108607. 0x4e8ee645,0x4a4ffbf2,0x470cdd2b,0x43cdc09c,
  108608. 0x7b827d21,0x7f436096,0x7200464f,0x76c15bf8,
  108609. 0x68860bfd,0x6c47164a,0x61043093,0x65c52d24,
  108610. 0x119b4be9,0x155a565e,0x18197087,0x1cd86d30,
  108611. 0x029f3d35,0x065e2082,0x0b1d065b,0x0fdc1bec,
  108612. 0x3793a651,0x3352bbe6,0x3e119d3f,0x3ad08088,
  108613. 0x2497d08d,0x2056cd3a,0x2d15ebe3,0x29d4f654,
  108614. 0xc5a92679,0xc1683bce,0xcc2b1d17,0xc8ea00a0,
  108615. 0xd6ad50a5,0xd26c4d12,0xdf2f6bcb,0xdbee767c,
  108616. 0xe3a1cbc1,0xe760d676,0xea23f0af,0xeee2ed18,
  108617. 0xf0a5bd1d,0xf464a0aa,0xf9278673,0xfde69bc4,
  108618. 0x89b8fd09,0x8d79e0be,0x803ac667,0x84fbdbd0,
  108619. 0x9abc8bd5,0x9e7d9662,0x933eb0bb,0x97ffad0c,
  108620. 0xafb010b1,0xab710d06,0xa6322bdf,0xa2f33668,
  108621. 0xbcb4666d,0xb8757bda,0xb5365d03,0xb1f740b4};
  108622. /* init the encode/decode logical stream state */
  108623. int ogg_stream_init(ogg_stream_state *os,int serialno){
  108624. if(os){
  108625. memset(os,0,sizeof(*os));
  108626. os->body_storage=16*1024;
  108627. os->body_data=(unsigned char*) _ogg_malloc(os->body_storage*sizeof(*os->body_data));
  108628. os->lacing_storage=1024;
  108629. os->lacing_vals=(int*) _ogg_malloc(os->lacing_storage*sizeof(*os->lacing_vals));
  108630. os->granule_vals=(ogg_int64_t*) _ogg_malloc(os->lacing_storage*sizeof(*os->granule_vals));
  108631. os->serialno=serialno;
  108632. return(0);
  108633. }
  108634. return(-1);
  108635. }
  108636. /* _clear does not free os, only the non-flat storage within */
  108637. int ogg_stream_clear(ogg_stream_state *os){
  108638. if(os){
  108639. if(os->body_data)_ogg_free(os->body_data);
  108640. if(os->lacing_vals)_ogg_free(os->lacing_vals);
  108641. if(os->granule_vals)_ogg_free(os->granule_vals);
  108642. memset(os,0,sizeof(*os));
  108643. }
  108644. return(0);
  108645. }
  108646. int ogg_stream_destroy(ogg_stream_state *os){
  108647. if(os){
  108648. ogg_stream_clear(os);
  108649. _ogg_free(os);
  108650. }
  108651. return(0);
  108652. }
  108653. /* Helpers for ogg_stream_encode; this keeps the structure and
  108654. what's happening fairly clear */
  108655. static void _os_body_expand(ogg_stream_state *os,int needed){
  108656. if(os->body_storage<=os->body_fill+needed){
  108657. os->body_storage+=(needed+1024);
  108658. os->body_data=(unsigned char*) _ogg_realloc(os->body_data,os->body_storage*sizeof(*os->body_data));
  108659. }
  108660. }
  108661. static void _os_lacing_expand(ogg_stream_state *os,int needed){
  108662. if(os->lacing_storage<=os->lacing_fill+needed){
  108663. os->lacing_storage+=(needed+32);
  108664. os->lacing_vals=(int*)_ogg_realloc(os->lacing_vals,os->lacing_storage*sizeof(*os->lacing_vals));
  108665. os->granule_vals=(ogg_int64_t*)_ogg_realloc(os->granule_vals,os->lacing_storage*sizeof(*os->granule_vals));
  108666. }
  108667. }
  108668. /* checksum the page */
  108669. /* Direct table CRC; note that this will be faster in the future if we
  108670. perform the checksum silmultaneously with other copies */
  108671. void ogg_page_checksum_set(ogg_page *og){
  108672. if(og){
  108673. ogg_uint32_t crc_reg=0;
  108674. int i;
  108675. /* safety; needed for API behavior, but not framing code */
  108676. og->header[22]=0;
  108677. og->header[23]=0;
  108678. og->header[24]=0;
  108679. og->header[25]=0;
  108680. for(i=0;i<og->header_len;i++)
  108681. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->header[i]];
  108682. for(i=0;i<og->body_len;i++)
  108683. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->body[i]];
  108684. og->header[22]=(unsigned char)(crc_reg&0xff);
  108685. og->header[23]=(unsigned char)((crc_reg>>8)&0xff);
  108686. og->header[24]=(unsigned char)((crc_reg>>16)&0xff);
  108687. og->header[25]=(unsigned char)((crc_reg>>24)&0xff);
  108688. }
  108689. }
  108690. /* submit data to the internal buffer of the framing engine */
  108691. int ogg_stream_packetin(ogg_stream_state *os,ogg_packet *op){
  108692. int lacing_vals=op->bytes/255+1,i;
  108693. if(os->body_returned){
  108694. /* advance packet data according to the body_returned pointer. We
  108695. had to keep it around to return a pointer into the buffer last
  108696. call */
  108697. os->body_fill-=os->body_returned;
  108698. if(os->body_fill)
  108699. memmove(os->body_data,os->body_data+os->body_returned,
  108700. os->body_fill);
  108701. os->body_returned=0;
  108702. }
  108703. /* make sure we have the buffer storage */
  108704. _os_body_expand(os,op->bytes);
  108705. _os_lacing_expand(os,lacing_vals);
  108706. /* Copy in the submitted packet. Yes, the copy is a waste; this is
  108707. the liability of overly clean abstraction for the time being. It
  108708. will actually be fairly easy to eliminate the extra copy in the
  108709. future */
  108710. memcpy(os->body_data+os->body_fill,op->packet,op->bytes);
  108711. os->body_fill+=op->bytes;
  108712. /* Store lacing vals for this packet */
  108713. for(i=0;i<lacing_vals-1;i++){
  108714. os->lacing_vals[os->lacing_fill+i]=255;
  108715. os->granule_vals[os->lacing_fill+i]=os->granulepos;
  108716. }
  108717. os->lacing_vals[os->lacing_fill+i]=(op->bytes)%255;
  108718. os->granulepos=os->granule_vals[os->lacing_fill+i]=op->granulepos;
  108719. /* flag the first segment as the beginning of the packet */
  108720. os->lacing_vals[os->lacing_fill]|= 0x100;
  108721. os->lacing_fill+=lacing_vals;
  108722. /* for the sake of completeness */
  108723. os->packetno++;
  108724. if(op->e_o_s)os->e_o_s=1;
  108725. return(0);
  108726. }
  108727. /* This will flush remaining packets into a page (returning nonzero),
  108728. even if there is not enough data to trigger a flush normally
  108729. (undersized page). If there are no packets or partial packets to
  108730. flush, ogg_stream_flush returns 0. Note that ogg_stream_flush will
  108731. try to flush a normal sized page like ogg_stream_pageout; a call to
  108732. ogg_stream_flush does not guarantee that all packets have flushed.
  108733. Only a return value of 0 from ogg_stream_flush indicates all packet
  108734. data is flushed into pages.
  108735. since ogg_stream_flush will flush the last page in a stream even if
  108736. it's undersized, you almost certainly want to use ogg_stream_pageout
  108737. (and *not* ogg_stream_flush) unless you specifically need to flush
  108738. an page regardless of size in the middle of a stream. */
  108739. int ogg_stream_flush(ogg_stream_state *os,ogg_page *og){
  108740. int i;
  108741. int vals=0;
  108742. int maxvals=(os->lacing_fill>255?255:os->lacing_fill);
  108743. int bytes=0;
  108744. long acc=0;
  108745. ogg_int64_t granule_pos=-1;
  108746. if(maxvals==0)return(0);
  108747. /* construct a page */
  108748. /* decide how many segments to include */
  108749. /* If this is the initial header case, the first page must only include
  108750. the initial header packet */
  108751. if(os->b_o_s==0){ /* 'initial header page' case */
  108752. granule_pos=0;
  108753. for(vals=0;vals<maxvals;vals++){
  108754. if((os->lacing_vals[vals]&0x0ff)<255){
  108755. vals++;
  108756. break;
  108757. }
  108758. }
  108759. }else{
  108760. for(vals=0;vals<maxvals;vals++){
  108761. if(acc>4096)break;
  108762. acc+=os->lacing_vals[vals]&0x0ff;
  108763. if((os->lacing_vals[vals]&0xff)<255)
  108764. granule_pos=os->granule_vals[vals];
  108765. }
  108766. }
  108767. /* construct the header in temp storage */
  108768. memcpy(os->header,"OggS",4);
  108769. /* stream structure version */
  108770. os->header[4]=0x00;
  108771. /* continued packet flag? */
  108772. os->header[5]=0x00;
  108773. if((os->lacing_vals[0]&0x100)==0)os->header[5]|=0x01;
  108774. /* first page flag? */
  108775. if(os->b_o_s==0)os->header[5]|=0x02;
  108776. /* last page flag? */
  108777. if(os->e_o_s && os->lacing_fill==vals)os->header[5]|=0x04;
  108778. os->b_o_s=1;
  108779. /* 64 bits of PCM position */
  108780. for(i=6;i<14;i++){
  108781. os->header[i]=(unsigned char)(granule_pos&0xff);
  108782. granule_pos>>=8;
  108783. }
  108784. /* 32 bits of stream serial number */
  108785. {
  108786. long serialno=os->serialno;
  108787. for(i=14;i<18;i++){
  108788. os->header[i]=(unsigned char)(serialno&0xff);
  108789. serialno>>=8;
  108790. }
  108791. }
  108792. /* 32 bits of page counter (we have both counter and page header
  108793. because this val can roll over) */
  108794. if(os->pageno==-1)os->pageno=0; /* because someone called
  108795. stream_reset; this would be a
  108796. strange thing to do in an
  108797. encode stream, but it has
  108798. plausible uses */
  108799. {
  108800. long pageno=os->pageno++;
  108801. for(i=18;i<22;i++){
  108802. os->header[i]=(unsigned char)(pageno&0xff);
  108803. pageno>>=8;
  108804. }
  108805. }
  108806. /* zero for computation; filled in later */
  108807. os->header[22]=0;
  108808. os->header[23]=0;
  108809. os->header[24]=0;
  108810. os->header[25]=0;
  108811. /* segment table */
  108812. os->header[26]=(unsigned char)(vals&0xff);
  108813. for(i=0;i<vals;i++)
  108814. bytes+=os->header[i+27]=(unsigned char)(os->lacing_vals[i]&0xff);
  108815. /* set pointers in the ogg_page struct */
  108816. og->header=os->header;
  108817. og->header_len=os->header_fill=vals+27;
  108818. og->body=os->body_data+os->body_returned;
  108819. og->body_len=bytes;
  108820. /* advance the lacing data and set the body_returned pointer */
  108821. os->lacing_fill-=vals;
  108822. memmove(os->lacing_vals,os->lacing_vals+vals,os->lacing_fill*sizeof(*os->lacing_vals));
  108823. memmove(os->granule_vals,os->granule_vals+vals,os->lacing_fill*sizeof(*os->granule_vals));
  108824. os->body_returned+=bytes;
  108825. /* calculate the checksum */
  108826. ogg_page_checksum_set(og);
  108827. /* done */
  108828. return(1);
  108829. }
  108830. /* This constructs pages from buffered packet segments. The pointers
  108831. returned are to static buffers; do not free. The returned buffers are
  108832. good only until the next call (using the same ogg_stream_state) */
  108833. int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og){
  108834. if((os->e_o_s&&os->lacing_fill) || /* 'were done, now flush' case */
  108835. os->body_fill-os->body_returned > 4096 ||/* 'page nominal size' case */
  108836. os->lacing_fill>=255 || /* 'segment table full' case */
  108837. (os->lacing_fill&&!os->b_o_s)){ /* 'initial header page' case */
  108838. return(ogg_stream_flush(os,og));
  108839. }
  108840. /* not enough data to construct a page and not end of stream */
  108841. return(0);
  108842. }
  108843. int ogg_stream_eos(ogg_stream_state *os){
  108844. return os->e_o_s;
  108845. }
  108846. /* DECODING PRIMITIVES: packet streaming layer **********************/
  108847. /* This has two layers to place more of the multi-serialno and paging
  108848. control in the application's hands. First, we expose a data buffer
  108849. using ogg_sync_buffer(). The app either copies into the
  108850. buffer, or passes it directly to read(), etc. We then call
  108851. ogg_sync_wrote() to tell how many bytes we just added.
  108852. Pages are returned (pointers into the buffer in ogg_sync_state)
  108853. by ogg_sync_pageout(). The page is then submitted to
  108854. ogg_stream_pagein() along with the appropriate
  108855. ogg_stream_state* (ie, matching serialno). We then get raw
  108856. packets out calling ogg_stream_packetout() with a
  108857. ogg_stream_state. */
  108858. /* initialize the struct to a known state */
  108859. int ogg_sync_init(ogg_sync_state *oy){
  108860. if(oy){
  108861. memset(oy,0,sizeof(*oy));
  108862. }
  108863. return(0);
  108864. }
  108865. /* clear non-flat storage within */
  108866. int ogg_sync_clear(ogg_sync_state *oy){
  108867. if(oy){
  108868. if(oy->data)_ogg_free(oy->data);
  108869. ogg_sync_init(oy);
  108870. }
  108871. return(0);
  108872. }
  108873. int ogg_sync_destroy(ogg_sync_state *oy){
  108874. if(oy){
  108875. ogg_sync_clear(oy);
  108876. _ogg_free(oy);
  108877. }
  108878. return(0);
  108879. }
  108880. char *ogg_sync_buffer(ogg_sync_state *oy, long size){
  108881. /* first, clear out any space that has been previously returned */
  108882. if(oy->returned){
  108883. oy->fill-=oy->returned;
  108884. if(oy->fill>0)
  108885. memmove(oy->data,oy->data+oy->returned,oy->fill);
  108886. oy->returned=0;
  108887. }
  108888. if(size>oy->storage-oy->fill){
  108889. /* We need to extend the internal buffer */
  108890. long newsize=size+oy->fill+4096; /* an extra page to be nice */
  108891. if(oy->data)
  108892. oy->data=(unsigned char*) _ogg_realloc(oy->data,newsize);
  108893. else
  108894. oy->data=(unsigned char*) _ogg_malloc(newsize);
  108895. oy->storage=newsize;
  108896. }
  108897. /* expose a segment at least as large as requested at the fill mark */
  108898. return((char *)oy->data+oy->fill);
  108899. }
  108900. int ogg_sync_wrote(ogg_sync_state *oy, long bytes){
  108901. if(oy->fill+bytes>oy->storage)return(-1);
  108902. oy->fill+=bytes;
  108903. return(0);
  108904. }
  108905. /* sync the stream. This is meant to be useful for finding page
  108906. boundaries.
  108907. return values for this:
  108908. -n) skipped n bytes
  108909. 0) page not ready; more data (no bytes skipped)
  108910. n) page synced at current location; page length n bytes
  108911. */
  108912. long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og){
  108913. unsigned char *page=oy->data+oy->returned;
  108914. unsigned char *next;
  108915. long bytes=oy->fill-oy->returned;
  108916. if(oy->headerbytes==0){
  108917. int headerbytes,i;
  108918. if(bytes<27)return(0); /* not enough for a header */
  108919. /* verify capture pattern */
  108920. if(memcmp(page,"OggS",4))goto sync_fail;
  108921. headerbytes=page[26]+27;
  108922. if(bytes<headerbytes)return(0); /* not enough for header + seg table */
  108923. /* count up body length in the segment table */
  108924. for(i=0;i<page[26];i++)
  108925. oy->bodybytes+=page[27+i];
  108926. oy->headerbytes=headerbytes;
  108927. }
  108928. if(oy->bodybytes+oy->headerbytes>bytes)return(0);
  108929. /* The whole test page is buffered. Verify the checksum */
  108930. {
  108931. /* Grab the checksum bytes, set the header field to zero */
  108932. char chksum[4];
  108933. ogg_page log;
  108934. memcpy(chksum,page+22,4);
  108935. memset(page+22,0,4);
  108936. /* set up a temp page struct and recompute the checksum */
  108937. log.header=page;
  108938. log.header_len=oy->headerbytes;
  108939. log.body=page+oy->headerbytes;
  108940. log.body_len=oy->bodybytes;
  108941. ogg_page_checksum_set(&log);
  108942. /* Compare */
  108943. if(memcmp(chksum,page+22,4)){
  108944. /* D'oh. Mismatch! Corrupt page (or miscapture and not a page
  108945. at all) */
  108946. /* replace the computed checksum with the one actually read in */
  108947. memcpy(page+22,chksum,4);
  108948. /* Bad checksum. Lose sync */
  108949. goto sync_fail;
  108950. }
  108951. }
  108952. /* yes, have a whole page all ready to go */
  108953. {
  108954. unsigned char *page=oy->data+oy->returned;
  108955. long bytes;
  108956. if(og){
  108957. og->header=page;
  108958. og->header_len=oy->headerbytes;
  108959. og->body=page+oy->headerbytes;
  108960. og->body_len=oy->bodybytes;
  108961. }
  108962. oy->unsynced=0;
  108963. oy->returned+=(bytes=oy->headerbytes+oy->bodybytes);
  108964. oy->headerbytes=0;
  108965. oy->bodybytes=0;
  108966. return(bytes);
  108967. }
  108968. sync_fail:
  108969. oy->headerbytes=0;
  108970. oy->bodybytes=0;
  108971. /* search for possible capture */
  108972. next=(unsigned char*)memchr(page+1,'O',bytes-1);
  108973. if(!next)
  108974. next=oy->data+oy->fill;
  108975. oy->returned=next-oy->data;
  108976. return(-(next-page));
  108977. }
  108978. /* sync the stream and get a page. Keep trying until we find a page.
  108979. Supress 'sync errors' after reporting the first.
  108980. return values:
  108981. -1) recapture (hole in data)
  108982. 0) need more data
  108983. 1) page returned
  108984. Returns pointers into buffered data; invalidated by next call to
  108985. _stream, _clear, _init, or _buffer */
  108986. int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og){
  108987. /* all we need to do is verify a page at the head of the stream
  108988. buffer. If it doesn't verify, we look for the next potential
  108989. frame */
  108990. for(;;){
  108991. long ret=ogg_sync_pageseek(oy,og);
  108992. if(ret>0){
  108993. /* have a page */
  108994. return(1);
  108995. }
  108996. if(ret==0){
  108997. /* need more data */
  108998. return(0);
  108999. }
  109000. /* head did not start a synced page... skipped some bytes */
  109001. if(!oy->unsynced){
  109002. oy->unsynced=1;
  109003. return(-1);
  109004. }
  109005. /* loop. keep looking */
  109006. }
  109007. }
  109008. /* add the incoming page to the stream state; we decompose the page
  109009. into packet segments here as well. */
  109010. int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og){
  109011. unsigned char *header=og->header;
  109012. unsigned char *body=og->body;
  109013. long bodysize=og->body_len;
  109014. int segptr=0;
  109015. int version=ogg_page_version(og);
  109016. int continued=ogg_page_continued(og);
  109017. int bos=ogg_page_bos(og);
  109018. int eos=ogg_page_eos(og);
  109019. ogg_int64_t granulepos=ogg_page_granulepos(og);
  109020. int serialno=ogg_page_serialno(og);
  109021. long pageno=ogg_page_pageno(og);
  109022. int segments=header[26];
  109023. /* clean up 'returned data' */
  109024. {
  109025. long lr=os->lacing_returned;
  109026. long br=os->body_returned;
  109027. /* body data */
  109028. if(br){
  109029. os->body_fill-=br;
  109030. if(os->body_fill)
  109031. memmove(os->body_data,os->body_data+br,os->body_fill);
  109032. os->body_returned=0;
  109033. }
  109034. if(lr){
  109035. /* segment table */
  109036. if(os->lacing_fill-lr){
  109037. memmove(os->lacing_vals,os->lacing_vals+lr,
  109038. (os->lacing_fill-lr)*sizeof(*os->lacing_vals));
  109039. memmove(os->granule_vals,os->granule_vals+lr,
  109040. (os->lacing_fill-lr)*sizeof(*os->granule_vals));
  109041. }
  109042. os->lacing_fill-=lr;
  109043. os->lacing_packet-=lr;
  109044. os->lacing_returned=0;
  109045. }
  109046. }
  109047. /* check the serial number */
  109048. if(serialno!=os->serialno)return(-1);
  109049. if(version>0)return(-1);
  109050. _os_lacing_expand(os,segments+1);
  109051. /* are we in sequence? */
  109052. if(pageno!=os->pageno){
  109053. int i;
  109054. /* unroll previous partial packet (if any) */
  109055. for(i=os->lacing_packet;i<os->lacing_fill;i++)
  109056. os->body_fill-=os->lacing_vals[i]&0xff;
  109057. os->lacing_fill=os->lacing_packet;
  109058. /* make a note of dropped data in segment table */
  109059. if(os->pageno!=-1){
  109060. os->lacing_vals[os->lacing_fill++]=0x400;
  109061. os->lacing_packet++;
  109062. }
  109063. }
  109064. /* are we a 'continued packet' page? If so, we may need to skip
  109065. some segments */
  109066. if(continued){
  109067. if(os->lacing_fill<1 ||
  109068. os->lacing_vals[os->lacing_fill-1]==0x400){
  109069. bos=0;
  109070. for(;segptr<segments;segptr++){
  109071. int val=header[27+segptr];
  109072. body+=val;
  109073. bodysize-=val;
  109074. if(val<255){
  109075. segptr++;
  109076. break;
  109077. }
  109078. }
  109079. }
  109080. }
  109081. if(bodysize){
  109082. _os_body_expand(os,bodysize);
  109083. memcpy(os->body_data+os->body_fill,body,bodysize);
  109084. os->body_fill+=bodysize;
  109085. }
  109086. {
  109087. int saved=-1;
  109088. while(segptr<segments){
  109089. int val=header[27+segptr];
  109090. os->lacing_vals[os->lacing_fill]=val;
  109091. os->granule_vals[os->lacing_fill]=-1;
  109092. if(bos){
  109093. os->lacing_vals[os->lacing_fill]|=0x100;
  109094. bos=0;
  109095. }
  109096. if(val<255)saved=os->lacing_fill;
  109097. os->lacing_fill++;
  109098. segptr++;
  109099. if(val<255)os->lacing_packet=os->lacing_fill;
  109100. }
  109101. /* set the granulepos on the last granuleval of the last full packet */
  109102. if(saved!=-1){
  109103. os->granule_vals[saved]=granulepos;
  109104. }
  109105. }
  109106. if(eos){
  109107. os->e_o_s=1;
  109108. if(os->lacing_fill>0)
  109109. os->lacing_vals[os->lacing_fill-1]|=0x200;
  109110. }
  109111. os->pageno=pageno+1;
  109112. return(0);
  109113. }
  109114. /* clear things to an initial state. Good to call, eg, before seeking */
  109115. int ogg_sync_reset(ogg_sync_state *oy){
  109116. oy->fill=0;
  109117. oy->returned=0;
  109118. oy->unsynced=0;
  109119. oy->headerbytes=0;
  109120. oy->bodybytes=0;
  109121. return(0);
  109122. }
  109123. int ogg_stream_reset(ogg_stream_state *os){
  109124. os->body_fill=0;
  109125. os->body_returned=0;
  109126. os->lacing_fill=0;
  109127. os->lacing_packet=0;
  109128. os->lacing_returned=0;
  109129. os->header_fill=0;
  109130. os->e_o_s=0;
  109131. os->b_o_s=0;
  109132. os->pageno=-1;
  109133. os->packetno=0;
  109134. os->granulepos=0;
  109135. return(0);
  109136. }
  109137. int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno){
  109138. ogg_stream_reset(os);
  109139. os->serialno=serialno;
  109140. return(0);
  109141. }
  109142. static int _packetout(ogg_stream_state *os,ogg_packet *op,int adv){
  109143. /* The last part of decode. We have the stream broken into packet
  109144. segments. Now we need to group them into packets (or return the
  109145. out of sync markers) */
  109146. int ptr=os->lacing_returned;
  109147. if(os->lacing_packet<=ptr)return(0);
  109148. if(os->lacing_vals[ptr]&0x400){
  109149. /* we need to tell the codec there's a gap; it might need to
  109150. handle previous packet dependencies. */
  109151. os->lacing_returned++;
  109152. os->packetno++;
  109153. return(-1);
  109154. }
  109155. if(!op && !adv)return(1); /* just using peek as an inexpensive way
  109156. to ask if there's a whole packet
  109157. waiting */
  109158. /* Gather the whole packet. We'll have no holes or a partial packet */
  109159. {
  109160. int size=os->lacing_vals[ptr]&0xff;
  109161. int bytes=size;
  109162. int eos=os->lacing_vals[ptr]&0x200; /* last packet of the stream? */
  109163. int bos=os->lacing_vals[ptr]&0x100; /* first packet of the stream? */
  109164. while(size==255){
  109165. int val=os->lacing_vals[++ptr];
  109166. size=val&0xff;
  109167. if(val&0x200)eos=0x200;
  109168. bytes+=size;
  109169. }
  109170. if(op){
  109171. op->e_o_s=eos;
  109172. op->b_o_s=bos;
  109173. op->packet=os->body_data+os->body_returned;
  109174. op->packetno=os->packetno;
  109175. op->granulepos=os->granule_vals[ptr];
  109176. op->bytes=bytes;
  109177. }
  109178. if(adv){
  109179. os->body_returned+=bytes;
  109180. os->lacing_returned=ptr+1;
  109181. os->packetno++;
  109182. }
  109183. }
  109184. return(1);
  109185. }
  109186. int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op){
  109187. return _packetout(os,op,1);
  109188. }
  109189. int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op){
  109190. return _packetout(os,op,0);
  109191. }
  109192. void ogg_packet_clear(ogg_packet *op) {
  109193. _ogg_free(op->packet);
  109194. memset(op, 0, sizeof(*op));
  109195. }
  109196. #ifdef _V_SELFTEST
  109197. #include <stdio.h>
  109198. ogg_stream_state os_en, os_de;
  109199. ogg_sync_state oy;
  109200. void checkpacket(ogg_packet *op,int len, int no, int pos){
  109201. long j;
  109202. static int sequence=0;
  109203. static int lastno=0;
  109204. if(op->bytes!=len){
  109205. fprintf(stderr,"incorrect packet length!\n");
  109206. exit(1);
  109207. }
  109208. if(op->granulepos!=pos){
  109209. fprintf(stderr,"incorrect packet position!\n");
  109210. exit(1);
  109211. }
  109212. /* packet number just follows sequence/gap; adjust the input number
  109213. for that */
  109214. if(no==0){
  109215. sequence=0;
  109216. }else{
  109217. sequence++;
  109218. if(no>lastno+1)
  109219. sequence++;
  109220. }
  109221. lastno=no;
  109222. if(op->packetno!=sequence){
  109223. fprintf(stderr,"incorrect packet sequence %ld != %d\n",
  109224. (long)(op->packetno),sequence);
  109225. exit(1);
  109226. }
  109227. /* Test data */
  109228. for(j=0;j<op->bytes;j++)
  109229. if(op->packet[j]!=((j+no)&0xff)){
  109230. fprintf(stderr,"body data mismatch (1) at pos %ld: %x!=%lx!\n\n",
  109231. j,op->packet[j],(j+no)&0xff);
  109232. exit(1);
  109233. }
  109234. }
  109235. void check_page(unsigned char *data,const int *header,ogg_page *og){
  109236. long j;
  109237. /* Test data */
  109238. for(j=0;j<og->body_len;j++)
  109239. if(og->body[j]!=data[j]){
  109240. fprintf(stderr,"body data mismatch (2) at pos %ld: %x!=%x!\n\n",
  109241. j,data[j],og->body[j]);
  109242. exit(1);
  109243. }
  109244. /* Test header */
  109245. for(j=0;j<og->header_len;j++){
  109246. if(og->header[j]!=header[j]){
  109247. fprintf(stderr,"header content mismatch at pos %ld:\n",j);
  109248. for(j=0;j<header[26]+27;j++)
  109249. fprintf(stderr," (%ld)%02x:%02x",j,header[j],og->header[j]);
  109250. fprintf(stderr,"\n");
  109251. exit(1);
  109252. }
  109253. }
  109254. if(og->header_len!=header[26]+27){
  109255. fprintf(stderr,"header length incorrect! (%ld!=%d)\n",
  109256. og->header_len,header[26]+27);
  109257. exit(1);
  109258. }
  109259. }
  109260. void print_header(ogg_page *og){
  109261. int j;
  109262. fprintf(stderr,"\nHEADER:\n");
  109263. fprintf(stderr," capture: %c %c %c %c version: %d flags: %x\n",
  109264. og->header[0],og->header[1],og->header[2],og->header[3],
  109265. (int)og->header[4],(int)og->header[5]);
  109266. fprintf(stderr," granulepos: %d serialno: %d pageno: %ld\n",
  109267. (og->header[9]<<24)|(og->header[8]<<16)|
  109268. (og->header[7]<<8)|og->header[6],
  109269. (og->header[17]<<24)|(og->header[16]<<16)|
  109270. (og->header[15]<<8)|og->header[14],
  109271. ((long)(og->header[21])<<24)|(og->header[20]<<16)|
  109272. (og->header[19]<<8)|og->header[18]);
  109273. fprintf(stderr," checksum: %02x:%02x:%02x:%02x\n segments: %d (",
  109274. (int)og->header[22],(int)og->header[23],
  109275. (int)og->header[24],(int)og->header[25],
  109276. (int)og->header[26]);
  109277. for(j=27;j<og->header_len;j++)
  109278. fprintf(stderr,"%d ",(int)og->header[j]);
  109279. fprintf(stderr,")\n\n");
  109280. }
  109281. void copy_page(ogg_page *og){
  109282. unsigned char *temp=_ogg_malloc(og->header_len);
  109283. memcpy(temp,og->header,og->header_len);
  109284. og->header=temp;
  109285. temp=_ogg_malloc(og->body_len);
  109286. memcpy(temp,og->body,og->body_len);
  109287. og->body=temp;
  109288. }
  109289. void free_page(ogg_page *og){
  109290. _ogg_free (og->header);
  109291. _ogg_free (og->body);
  109292. }
  109293. void error(void){
  109294. fprintf(stderr,"error!\n");
  109295. exit(1);
  109296. }
  109297. /* 17 only */
  109298. const int head1_0[] = {0x4f,0x67,0x67,0x53,0,0x06,
  109299. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109300. 0x01,0x02,0x03,0x04,0,0,0,0,
  109301. 0x15,0xed,0xec,0x91,
  109302. 1,
  109303. 17};
  109304. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  109305. const int head1_1[] = {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. 0x59,0x10,0x6c,0x2c,
  109309. 1,
  109310. 17};
  109311. const int head2_1[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109312. 0x07,0x18,0x00,0x00,0x00,0x00,0x00,0x00,
  109313. 0x01,0x02,0x03,0x04,1,0,0,0,
  109314. 0x89,0x33,0x85,0xce,
  109315. 13,
  109316. 254,255,0,255,1,255,245,255,255,0,
  109317. 255,255,90};
  109318. /* nil packets; beginning,middle,end */
  109319. const int head1_2[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109320. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109321. 0x01,0x02,0x03,0x04,0,0,0,0,
  109322. 0xff,0x7b,0x23,0x17,
  109323. 1,
  109324. 0};
  109325. const int head2_2[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109326. 0x07,0x28,0x00,0x00,0x00,0x00,0x00,0x00,
  109327. 0x01,0x02,0x03,0x04,1,0,0,0,
  109328. 0x5c,0x3f,0x66,0xcb,
  109329. 17,
  109330. 17,254,255,0,0,255,1,0,255,245,255,255,0,
  109331. 255,255,90,0};
  109332. /* large initial packet */
  109333. const int head1_3[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109334. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109335. 0x01,0x02,0x03,0x04,0,0,0,0,
  109336. 0x01,0x27,0x31,0xaa,
  109337. 18,
  109338. 255,255,255,255,255,255,255,255,
  109339. 255,255,255,255,255,255,255,255,255,10};
  109340. const int head2_3[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109341. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  109342. 0x01,0x02,0x03,0x04,1,0,0,0,
  109343. 0x7f,0x4e,0x8a,0xd2,
  109344. 4,
  109345. 255,4,255,0};
  109346. /* continuing packet test */
  109347. const int head1_4[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109348. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109349. 0x01,0x02,0x03,0x04,0,0,0,0,
  109350. 0xff,0x7b,0x23,0x17,
  109351. 1,
  109352. 0};
  109353. const int head2_4[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109354. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  109355. 0x01,0x02,0x03,0x04,1,0,0,0,
  109356. 0x54,0x05,0x51,0xc8,
  109357. 17,
  109358. 255,255,255,255,255,255,255,255,
  109359. 255,255,255,255,255,255,255,255,255};
  109360. const int head3_4[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109361. 0x07,0x0c,0x00,0x00,0x00,0x00,0x00,0x00,
  109362. 0x01,0x02,0x03,0x04,2,0,0,0,
  109363. 0xc8,0xc3,0xcb,0xed,
  109364. 5,
  109365. 10,255,4,255,0};
  109366. /* page with the 255 segment limit */
  109367. const int head1_5[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109368. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109369. 0x01,0x02,0x03,0x04,0,0,0,0,
  109370. 0xff,0x7b,0x23,0x17,
  109371. 1,
  109372. 0};
  109373. const int head2_5[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109374. 0x07,0xfc,0x03,0x00,0x00,0x00,0x00,0x00,
  109375. 0x01,0x02,0x03,0x04,1,0,0,0,
  109376. 0xed,0x2a,0x2e,0xa7,
  109377. 255,
  109378. 10,10,10,10,10,10,10,10,
  109379. 10,10,10,10,10,10,10,10,
  109380. 10,10,10,10,10,10,10,10,
  109381. 10,10,10,10,10,10,10,10,
  109382. 10,10,10,10,10,10,10,10,
  109383. 10,10,10,10,10,10,10,10,
  109384. 10,10,10,10,10,10,10,10,
  109385. 10,10,10,10,10,10,10,10,
  109386. 10,10,10,10,10,10,10,10,
  109387. 10,10,10,10,10,10,10,10,
  109388. 10,10,10,10,10,10,10,10,
  109389. 10,10,10,10,10,10,10,10,
  109390. 10,10,10,10,10,10,10,10,
  109391. 10,10,10,10,10,10,10,10,
  109392. 10,10,10,10,10,10,10,10,
  109393. 10,10,10,10,10,10,10,10,
  109394. 10,10,10,10,10,10,10,10,
  109395. 10,10,10,10,10,10,10,10,
  109396. 10,10,10,10,10,10,10,10,
  109397. 10,10,10,10,10,10,10,10,
  109398. 10,10,10,10,10,10,10,10,
  109399. 10,10,10,10,10,10,10,10,
  109400. 10,10,10,10,10,10,10,10,
  109401. 10,10,10,10,10,10,10,10,
  109402. 10,10,10,10,10,10,10,10,
  109403. 10,10,10,10,10,10,10,10,
  109404. 10,10,10,10,10,10,10,10,
  109405. 10,10,10,10,10,10,10,10,
  109406. 10,10,10,10,10,10,10,10,
  109407. 10,10,10,10,10,10,10,10,
  109408. 10,10,10,10,10,10,10,10,
  109409. 10,10,10,10,10,10,10};
  109410. const int head3_5[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109411. 0x07,0x00,0x04,0x00,0x00,0x00,0x00,0x00,
  109412. 0x01,0x02,0x03,0x04,2,0,0,0,
  109413. 0x6c,0x3b,0x82,0x3d,
  109414. 1,
  109415. 50};
  109416. /* packet that overspans over an entire page */
  109417. const int head1_6[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109418. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109419. 0x01,0x02,0x03,0x04,0,0,0,0,
  109420. 0xff,0x7b,0x23,0x17,
  109421. 1,
  109422. 0};
  109423. const int head2_6[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109424. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  109425. 0x01,0x02,0x03,0x04,1,0,0,0,
  109426. 0x3c,0xd9,0x4d,0x3f,
  109427. 17,
  109428. 100,255,255,255,255,255,255,255,255,
  109429. 255,255,255,255,255,255,255,255};
  109430. const int head3_6[] = {0x4f,0x67,0x67,0x53,0,0x01,
  109431. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  109432. 0x01,0x02,0x03,0x04,2,0,0,0,
  109433. 0x01,0xd2,0xe5,0xe5,
  109434. 17,
  109435. 255,255,255,255,255,255,255,255,
  109436. 255,255,255,255,255,255,255,255,255};
  109437. const int head4_6[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109438. 0x07,0x10,0x00,0x00,0x00,0x00,0x00,0x00,
  109439. 0x01,0x02,0x03,0x04,3,0,0,0,
  109440. 0xef,0xdd,0x88,0xde,
  109441. 7,
  109442. 255,255,75,255,4,255,0};
  109443. /* packet that overspans over an entire page */
  109444. const int head1_7[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109445. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109446. 0x01,0x02,0x03,0x04,0,0,0,0,
  109447. 0xff,0x7b,0x23,0x17,
  109448. 1,
  109449. 0};
  109450. const int head2_7[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109451. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  109452. 0x01,0x02,0x03,0x04,1,0,0,0,
  109453. 0x3c,0xd9,0x4d,0x3f,
  109454. 17,
  109455. 100,255,255,255,255,255,255,255,255,
  109456. 255,255,255,255,255,255,255,255};
  109457. const int head3_7[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109458. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  109459. 0x01,0x02,0x03,0x04,2,0,0,0,
  109460. 0xd4,0xe0,0x60,0xe5,
  109461. 1,0};
  109462. void test_pack(const int *pl, const int **headers, int byteskip,
  109463. int pageskip, int packetskip){
  109464. unsigned char *data=_ogg_malloc(1024*1024); /* for scripted test cases only */
  109465. long inptr=0;
  109466. long outptr=0;
  109467. long deptr=0;
  109468. long depacket=0;
  109469. long granule_pos=7,pageno=0;
  109470. int i,j,packets,pageout=pageskip;
  109471. int eosflag=0;
  109472. int bosflag=0;
  109473. int byteskipcount=0;
  109474. ogg_stream_reset(&os_en);
  109475. ogg_stream_reset(&os_de);
  109476. ogg_sync_reset(&oy);
  109477. for(packets=0;packets<packetskip;packets++)
  109478. depacket+=pl[packets];
  109479. for(packets=0;;packets++)if(pl[packets]==-1)break;
  109480. for(i=0;i<packets;i++){
  109481. /* construct a test packet */
  109482. ogg_packet op;
  109483. int len=pl[i];
  109484. op.packet=data+inptr;
  109485. op.bytes=len;
  109486. op.e_o_s=(pl[i+1]<0?1:0);
  109487. op.granulepos=granule_pos;
  109488. granule_pos+=1024;
  109489. for(j=0;j<len;j++)data[inptr++]=i+j;
  109490. /* submit the test packet */
  109491. ogg_stream_packetin(&os_en,&op);
  109492. /* retrieve any finished pages */
  109493. {
  109494. ogg_page og;
  109495. while(ogg_stream_pageout(&os_en,&og)){
  109496. /* We have a page. Check it carefully */
  109497. fprintf(stderr,"%ld, ",pageno);
  109498. if(headers[pageno]==NULL){
  109499. fprintf(stderr,"coded too many pages!\n");
  109500. exit(1);
  109501. }
  109502. check_page(data+outptr,headers[pageno],&og);
  109503. outptr+=og.body_len;
  109504. pageno++;
  109505. if(pageskip){
  109506. bosflag=1;
  109507. pageskip--;
  109508. deptr+=og.body_len;
  109509. }
  109510. /* have a complete page; submit it to sync/decode */
  109511. {
  109512. ogg_page og_de;
  109513. ogg_packet op_de,op_de2;
  109514. char *buf=ogg_sync_buffer(&oy,og.header_len+og.body_len);
  109515. char *next=buf;
  109516. byteskipcount+=og.header_len;
  109517. if(byteskipcount>byteskip){
  109518. memcpy(next,og.header,byteskipcount-byteskip);
  109519. next+=byteskipcount-byteskip;
  109520. byteskipcount=byteskip;
  109521. }
  109522. byteskipcount+=og.body_len;
  109523. if(byteskipcount>byteskip){
  109524. memcpy(next,og.body,byteskipcount-byteskip);
  109525. next+=byteskipcount-byteskip;
  109526. byteskipcount=byteskip;
  109527. }
  109528. ogg_sync_wrote(&oy,next-buf);
  109529. while(1){
  109530. int ret=ogg_sync_pageout(&oy,&og_de);
  109531. if(ret==0)break;
  109532. if(ret<0)continue;
  109533. /* got a page. Happy happy. Verify that it's good. */
  109534. fprintf(stderr,"(%ld), ",pageout);
  109535. check_page(data+deptr,headers[pageout],&og_de);
  109536. deptr+=og_de.body_len;
  109537. pageout++;
  109538. /* submit it to deconstitution */
  109539. ogg_stream_pagein(&os_de,&og_de);
  109540. /* packets out? */
  109541. while(ogg_stream_packetpeek(&os_de,&op_de2)>0){
  109542. ogg_stream_packetpeek(&os_de,NULL);
  109543. ogg_stream_packetout(&os_de,&op_de); /* just catching them all */
  109544. /* verify peek and out match */
  109545. if(memcmp(&op_de,&op_de2,sizeof(op_de))){
  109546. fprintf(stderr,"packetout != packetpeek! pos=%ld\n",
  109547. depacket);
  109548. exit(1);
  109549. }
  109550. /* verify the packet! */
  109551. /* check data */
  109552. if(memcmp(data+depacket,op_de.packet,op_de.bytes)){
  109553. fprintf(stderr,"packet data mismatch in decode! pos=%ld\n",
  109554. depacket);
  109555. exit(1);
  109556. }
  109557. /* check bos flag */
  109558. if(bosflag==0 && op_de.b_o_s==0){
  109559. fprintf(stderr,"b_o_s flag not set on packet!\n");
  109560. exit(1);
  109561. }
  109562. if(bosflag && op_de.b_o_s){
  109563. fprintf(stderr,"b_o_s flag incorrectly set on packet!\n");
  109564. exit(1);
  109565. }
  109566. bosflag=1;
  109567. depacket+=op_de.bytes;
  109568. /* check eos flag */
  109569. if(eosflag){
  109570. fprintf(stderr,"Multiple decoded packets with eos flag!\n");
  109571. exit(1);
  109572. }
  109573. if(op_de.e_o_s)eosflag=1;
  109574. /* check granulepos flag */
  109575. if(op_de.granulepos!=-1){
  109576. fprintf(stderr," granule:%ld ",(long)op_de.granulepos);
  109577. }
  109578. }
  109579. }
  109580. }
  109581. }
  109582. }
  109583. }
  109584. _ogg_free(data);
  109585. if(headers[pageno]!=NULL){
  109586. fprintf(stderr,"did not write last page!\n");
  109587. exit(1);
  109588. }
  109589. if(headers[pageout]!=NULL){
  109590. fprintf(stderr,"did not decode last page!\n");
  109591. exit(1);
  109592. }
  109593. if(inptr!=outptr){
  109594. fprintf(stderr,"encoded page data incomplete!\n");
  109595. exit(1);
  109596. }
  109597. if(inptr!=deptr){
  109598. fprintf(stderr,"decoded page data incomplete!\n");
  109599. exit(1);
  109600. }
  109601. if(inptr!=depacket){
  109602. fprintf(stderr,"decoded packet data incomplete!\n");
  109603. exit(1);
  109604. }
  109605. if(!eosflag){
  109606. fprintf(stderr,"Never got a packet with EOS set!\n");
  109607. exit(1);
  109608. }
  109609. fprintf(stderr,"ok.\n");
  109610. }
  109611. int main(void){
  109612. ogg_stream_init(&os_en,0x04030201);
  109613. ogg_stream_init(&os_de,0x04030201);
  109614. ogg_sync_init(&oy);
  109615. /* Exercise each code path in the framing code. Also verify that
  109616. the checksums are working. */
  109617. {
  109618. /* 17 only */
  109619. const int packets[]={17, -1};
  109620. const int *headret[]={head1_0,NULL};
  109621. fprintf(stderr,"testing single page encoding... ");
  109622. test_pack(packets,headret,0,0,0);
  109623. }
  109624. {
  109625. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  109626. const int packets[]={17, 254, 255, 256, 500, 510, 600, -1};
  109627. const int *headret[]={head1_1,head2_1,NULL};
  109628. fprintf(stderr,"testing basic page encoding... ");
  109629. test_pack(packets,headret,0,0,0);
  109630. }
  109631. {
  109632. /* nil packets; beginning,middle,end */
  109633. const int packets[]={0,17, 254, 255, 0, 256, 0, 500, 510, 600, 0, -1};
  109634. const int *headret[]={head1_2,head2_2,NULL};
  109635. fprintf(stderr,"testing basic nil packets... ");
  109636. test_pack(packets,headret,0,0,0);
  109637. }
  109638. {
  109639. /* large initial packet */
  109640. const int packets[]={4345,259,255,-1};
  109641. const int *headret[]={head1_3,head2_3,NULL};
  109642. fprintf(stderr,"testing initial-packet lacing > 4k... ");
  109643. test_pack(packets,headret,0,0,0);
  109644. }
  109645. {
  109646. /* continuing packet test */
  109647. const int packets[]={0,4345,259,255,-1};
  109648. const int *headret[]={head1_4,head2_4,head3_4,NULL};
  109649. fprintf(stderr,"testing single packet page span... ");
  109650. test_pack(packets,headret,0,0,0);
  109651. }
  109652. /* page with the 255 segment limit */
  109653. {
  109654. const int packets[]={0,10,10,10,10,10,10,10,10,
  109655. 10,10,10,10,10,10,10,10,
  109656. 10,10,10,10,10,10,10,10,
  109657. 10,10,10,10,10,10,10,10,
  109658. 10,10,10,10,10,10,10,10,
  109659. 10,10,10,10,10,10,10,10,
  109660. 10,10,10,10,10,10,10,10,
  109661. 10,10,10,10,10,10,10,10,
  109662. 10,10,10,10,10,10,10,10,
  109663. 10,10,10,10,10,10,10,10,
  109664. 10,10,10,10,10,10,10,10,
  109665. 10,10,10,10,10,10,10,10,
  109666. 10,10,10,10,10,10,10,10,
  109667. 10,10,10,10,10,10,10,10,
  109668. 10,10,10,10,10,10,10,10,
  109669. 10,10,10,10,10,10,10,10,
  109670. 10,10,10,10,10,10,10,10,
  109671. 10,10,10,10,10,10,10,10,
  109672. 10,10,10,10,10,10,10,10,
  109673. 10,10,10,10,10,10,10,10,
  109674. 10,10,10,10,10,10,10,10,
  109675. 10,10,10,10,10,10,10,10,
  109676. 10,10,10,10,10,10,10,10,
  109677. 10,10,10,10,10,10,10,10,
  109678. 10,10,10,10,10,10,10,10,
  109679. 10,10,10,10,10,10,10,10,
  109680. 10,10,10,10,10,10,10,10,
  109681. 10,10,10,10,10,10,10,10,
  109682. 10,10,10,10,10,10,10,10,
  109683. 10,10,10,10,10,10,10,10,
  109684. 10,10,10,10,10,10,10,10,
  109685. 10,10,10,10,10,10,10,50,-1};
  109686. const int *headret[]={head1_5,head2_5,head3_5,NULL};
  109687. fprintf(stderr,"testing max packet segments... ");
  109688. test_pack(packets,headret,0,0,0);
  109689. }
  109690. {
  109691. /* packet that overspans over an entire page */
  109692. const int packets[]={0,100,9000,259,255,-1};
  109693. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  109694. fprintf(stderr,"testing very large packets... ");
  109695. test_pack(packets,headret,0,0,0);
  109696. }
  109697. {
  109698. /* test for the libogg 1.1.1 resync in large continuation bug
  109699. found by Josh Coalson) */
  109700. const int packets[]={0,100,9000,259,255,-1};
  109701. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  109702. fprintf(stderr,"testing continuation resync in very large packets... ");
  109703. test_pack(packets,headret,100,2,3);
  109704. }
  109705. {
  109706. /* term only page. why not? */
  109707. const int packets[]={0,100,4080,-1};
  109708. const int *headret[]={head1_7,head2_7,head3_7,NULL};
  109709. fprintf(stderr,"testing zero data page (1 nil packet)... ");
  109710. test_pack(packets,headret,0,0,0);
  109711. }
  109712. {
  109713. /* build a bunch of pages for testing */
  109714. unsigned char *data=_ogg_malloc(1024*1024);
  109715. int pl[]={0,100,4079,2956,2057,76,34,912,0,234,1000,1000,1000,300,-1};
  109716. int inptr=0,i,j;
  109717. ogg_page og[5];
  109718. ogg_stream_reset(&os_en);
  109719. for(i=0;pl[i]!=-1;i++){
  109720. ogg_packet op;
  109721. int len=pl[i];
  109722. op.packet=data+inptr;
  109723. op.bytes=len;
  109724. op.e_o_s=(pl[i+1]<0?1:0);
  109725. op.granulepos=(i+1)*1000;
  109726. for(j=0;j<len;j++)data[inptr++]=i+j;
  109727. ogg_stream_packetin(&os_en,&op);
  109728. }
  109729. _ogg_free(data);
  109730. /* retrieve finished pages */
  109731. for(i=0;i<5;i++){
  109732. if(ogg_stream_pageout(&os_en,&og[i])==0){
  109733. fprintf(stderr,"Too few pages output building sync tests!\n");
  109734. exit(1);
  109735. }
  109736. copy_page(&og[i]);
  109737. }
  109738. /* Test lost pages on pagein/packetout: no rollback */
  109739. {
  109740. ogg_page temp;
  109741. ogg_packet test;
  109742. fprintf(stderr,"Testing loss of pages... ");
  109743. ogg_sync_reset(&oy);
  109744. ogg_stream_reset(&os_de);
  109745. for(i=0;i<5;i++){
  109746. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  109747. og[i].header_len);
  109748. ogg_sync_wrote(&oy,og[i].header_len);
  109749. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  109750. ogg_sync_wrote(&oy,og[i].body_len);
  109751. }
  109752. ogg_sync_pageout(&oy,&temp);
  109753. ogg_stream_pagein(&os_de,&temp);
  109754. ogg_sync_pageout(&oy,&temp);
  109755. ogg_stream_pagein(&os_de,&temp);
  109756. ogg_sync_pageout(&oy,&temp);
  109757. /* skip */
  109758. ogg_sync_pageout(&oy,&temp);
  109759. ogg_stream_pagein(&os_de,&temp);
  109760. /* do we get the expected results/packets? */
  109761. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109762. checkpacket(&test,0,0,0);
  109763. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109764. checkpacket(&test,100,1,-1);
  109765. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109766. checkpacket(&test,4079,2,3000);
  109767. if(ogg_stream_packetout(&os_de,&test)!=-1){
  109768. fprintf(stderr,"Error: loss of page did not return error\n");
  109769. exit(1);
  109770. }
  109771. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109772. checkpacket(&test,76,5,-1);
  109773. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109774. checkpacket(&test,34,6,-1);
  109775. fprintf(stderr,"ok.\n");
  109776. }
  109777. /* Test lost pages on pagein/packetout: rollback with continuation */
  109778. {
  109779. ogg_page temp;
  109780. ogg_packet test;
  109781. fprintf(stderr,"Testing loss of pages (rollback required)... ");
  109782. ogg_sync_reset(&oy);
  109783. ogg_stream_reset(&os_de);
  109784. for(i=0;i<5;i++){
  109785. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  109786. og[i].header_len);
  109787. ogg_sync_wrote(&oy,og[i].header_len);
  109788. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  109789. ogg_sync_wrote(&oy,og[i].body_len);
  109790. }
  109791. ogg_sync_pageout(&oy,&temp);
  109792. ogg_stream_pagein(&os_de,&temp);
  109793. ogg_sync_pageout(&oy,&temp);
  109794. ogg_stream_pagein(&os_de,&temp);
  109795. ogg_sync_pageout(&oy,&temp);
  109796. ogg_stream_pagein(&os_de,&temp);
  109797. ogg_sync_pageout(&oy,&temp);
  109798. /* skip */
  109799. ogg_sync_pageout(&oy,&temp);
  109800. ogg_stream_pagein(&os_de,&temp);
  109801. /* do we get the expected results/packets? */
  109802. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109803. checkpacket(&test,0,0,0);
  109804. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109805. checkpacket(&test,100,1,-1);
  109806. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109807. checkpacket(&test,4079,2,3000);
  109808. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109809. checkpacket(&test,2956,3,4000);
  109810. if(ogg_stream_packetout(&os_de,&test)!=-1){
  109811. fprintf(stderr,"Error: loss of page did not return error\n");
  109812. exit(1);
  109813. }
  109814. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109815. checkpacket(&test,300,13,14000);
  109816. fprintf(stderr,"ok.\n");
  109817. }
  109818. /* the rest only test sync */
  109819. {
  109820. ogg_page og_de;
  109821. /* Test fractional page inputs: incomplete capture */
  109822. fprintf(stderr,"Testing sync on partial inputs... ");
  109823. ogg_sync_reset(&oy);
  109824. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109825. 3);
  109826. ogg_sync_wrote(&oy,3);
  109827. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109828. /* Test fractional page inputs: incomplete fixed header */
  109829. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+3,
  109830. 20);
  109831. ogg_sync_wrote(&oy,20);
  109832. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109833. /* Test fractional page inputs: incomplete header */
  109834. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+23,
  109835. 5);
  109836. ogg_sync_wrote(&oy,5);
  109837. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109838. /* Test fractional page inputs: incomplete body */
  109839. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+28,
  109840. og[1].header_len-28);
  109841. ogg_sync_wrote(&oy,og[1].header_len-28);
  109842. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109843. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,1000);
  109844. ogg_sync_wrote(&oy,1000);
  109845. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109846. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body+1000,
  109847. og[1].body_len-1000);
  109848. ogg_sync_wrote(&oy,og[1].body_len-1000);
  109849. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109850. fprintf(stderr,"ok.\n");
  109851. }
  109852. /* Test fractional page inputs: page + incomplete capture */
  109853. {
  109854. ogg_page og_de;
  109855. fprintf(stderr,"Testing sync on 1+partial inputs... ");
  109856. ogg_sync_reset(&oy);
  109857. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109858. og[1].header_len);
  109859. ogg_sync_wrote(&oy,og[1].header_len);
  109860. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109861. og[1].body_len);
  109862. ogg_sync_wrote(&oy,og[1].body_len);
  109863. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109864. 20);
  109865. ogg_sync_wrote(&oy,20);
  109866. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109867. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109868. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+20,
  109869. og[1].header_len-20);
  109870. ogg_sync_wrote(&oy,og[1].header_len-20);
  109871. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109872. og[1].body_len);
  109873. ogg_sync_wrote(&oy,og[1].body_len);
  109874. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109875. fprintf(stderr,"ok.\n");
  109876. }
  109877. /* Test recapture: garbage + page */
  109878. {
  109879. ogg_page og_de;
  109880. fprintf(stderr,"Testing search for capture... ");
  109881. ogg_sync_reset(&oy);
  109882. /* 'garbage' */
  109883. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109884. og[1].body_len);
  109885. ogg_sync_wrote(&oy,og[1].body_len);
  109886. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109887. og[1].header_len);
  109888. ogg_sync_wrote(&oy,og[1].header_len);
  109889. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109890. og[1].body_len);
  109891. ogg_sync_wrote(&oy,og[1].body_len);
  109892. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  109893. 20);
  109894. ogg_sync_wrote(&oy,20);
  109895. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109896. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109897. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109898. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header+20,
  109899. og[2].header_len-20);
  109900. ogg_sync_wrote(&oy,og[2].header_len-20);
  109901. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  109902. og[2].body_len);
  109903. ogg_sync_wrote(&oy,og[2].body_len);
  109904. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109905. fprintf(stderr,"ok.\n");
  109906. }
  109907. /* Test recapture: page + garbage + page */
  109908. {
  109909. ogg_page og_de;
  109910. fprintf(stderr,"Testing recapture... ");
  109911. ogg_sync_reset(&oy);
  109912. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109913. og[1].header_len);
  109914. ogg_sync_wrote(&oy,og[1].header_len);
  109915. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109916. og[1].body_len);
  109917. ogg_sync_wrote(&oy,og[1].body_len);
  109918. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  109919. og[2].header_len);
  109920. ogg_sync_wrote(&oy,og[2].header_len);
  109921. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  109922. og[2].header_len);
  109923. ogg_sync_wrote(&oy,og[2].header_len);
  109924. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109925. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  109926. og[2].body_len-5);
  109927. ogg_sync_wrote(&oy,og[2].body_len-5);
  109928. memcpy(ogg_sync_buffer(&oy,og[3].header_len),og[3].header,
  109929. og[3].header_len);
  109930. ogg_sync_wrote(&oy,og[3].header_len);
  109931. memcpy(ogg_sync_buffer(&oy,og[3].body_len),og[3].body,
  109932. og[3].body_len);
  109933. ogg_sync_wrote(&oy,og[3].body_len);
  109934. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109935. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109936. fprintf(stderr,"ok.\n");
  109937. }
  109938. /* Free page data that was previously copied */
  109939. {
  109940. for(i=0;i<5;i++){
  109941. free_page(&og[i]);
  109942. }
  109943. }
  109944. }
  109945. return(0);
  109946. }
  109947. #endif
  109948. #endif
  109949. /*** End of inlined file: framing.c ***/
  109950. /*** Start of inlined file: analysis.c ***/
  109951. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  109952. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109953. // tasks..
  109954. #if JUCE_MSVC
  109955. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109956. #endif
  109957. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  109958. #if JUCE_USE_OGGVORBIS
  109959. #include <stdio.h>
  109960. #include <string.h>
  109961. #include <math.h>
  109962. /*** Start of inlined file: codec_internal.h ***/
  109963. #ifndef _V_CODECI_H_
  109964. #define _V_CODECI_H_
  109965. /*** Start of inlined file: envelope.h ***/
  109966. #ifndef _V_ENVELOPE_
  109967. #define _V_ENVELOPE_
  109968. /*** Start of inlined file: mdct.h ***/
  109969. #ifndef _OGG_mdct_H_
  109970. #define _OGG_mdct_H_
  109971. /*#define MDCT_INTEGERIZED <- be warned there could be some hurt left here*/
  109972. #ifdef MDCT_INTEGERIZED
  109973. #define DATA_TYPE int
  109974. #define REG_TYPE register int
  109975. #define TRIGBITS 14
  109976. #define cPI3_8 6270
  109977. #define cPI2_8 11585
  109978. #define cPI1_8 15137
  109979. #define FLOAT_CONV(x) ((int)((x)*(1<<TRIGBITS)+.5))
  109980. #define MULT_NORM(x) ((x)>>TRIGBITS)
  109981. #define HALVE(x) ((x)>>1)
  109982. #else
  109983. #define DATA_TYPE float
  109984. #define REG_TYPE float
  109985. #define cPI3_8 .38268343236508977175F
  109986. #define cPI2_8 .70710678118654752441F
  109987. #define cPI1_8 .92387953251128675613F
  109988. #define FLOAT_CONV(x) (x)
  109989. #define MULT_NORM(x) (x)
  109990. #define HALVE(x) ((x)*.5f)
  109991. #endif
  109992. typedef struct {
  109993. int n;
  109994. int log2n;
  109995. DATA_TYPE *trig;
  109996. int *bitrev;
  109997. DATA_TYPE scale;
  109998. } mdct_lookup;
  109999. extern void mdct_init(mdct_lookup *lookup,int n);
  110000. extern void mdct_clear(mdct_lookup *l);
  110001. extern void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  110002. extern void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  110003. #endif
  110004. /*** End of inlined file: mdct.h ***/
  110005. #define VE_PRE 16
  110006. #define VE_WIN 4
  110007. #define VE_POST 2
  110008. #define VE_AMP (VE_PRE+VE_POST-1)
  110009. #define VE_BANDS 7
  110010. #define VE_NEARDC 15
  110011. #define VE_MINSTRETCH 2 /* a bit less than short block */
  110012. #define VE_MAXSTRETCH 12 /* one-third full block */
  110013. typedef struct {
  110014. float ampbuf[VE_AMP];
  110015. int ampptr;
  110016. float nearDC[VE_NEARDC];
  110017. float nearDC_acc;
  110018. float nearDC_partialacc;
  110019. int nearptr;
  110020. } envelope_filter_state;
  110021. typedef struct {
  110022. int begin;
  110023. int end;
  110024. float *window;
  110025. float total;
  110026. } envelope_band;
  110027. typedef struct {
  110028. int ch;
  110029. int winlength;
  110030. int searchstep;
  110031. float minenergy;
  110032. mdct_lookup mdct;
  110033. float *mdct_win;
  110034. envelope_band band[VE_BANDS];
  110035. envelope_filter_state *filter;
  110036. int stretch;
  110037. int *mark;
  110038. long storage;
  110039. long current;
  110040. long curmark;
  110041. long cursor;
  110042. } envelope_lookup;
  110043. extern void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi);
  110044. extern void _ve_envelope_clear(envelope_lookup *e);
  110045. extern long _ve_envelope_search(vorbis_dsp_state *v);
  110046. extern void _ve_envelope_shift(envelope_lookup *e,long shift);
  110047. extern int _ve_envelope_mark(vorbis_dsp_state *v);
  110048. #endif
  110049. /*** End of inlined file: envelope.h ***/
  110050. /*** Start of inlined file: codebook.h ***/
  110051. #ifndef _V_CODEBOOK_H_
  110052. #define _V_CODEBOOK_H_
  110053. /* This structure encapsulates huffman and VQ style encoding books; it
  110054. doesn't do anything specific to either.
  110055. valuelist/quantlist are nonNULL (and q_* significant) only if
  110056. there's entry->value mapping to be done.
  110057. If encode-side mapping must be done (and thus the entry needs to be
  110058. hunted), the auxiliary encode pointer will point to a decision
  110059. tree. This is true of both VQ and huffman, but is mostly useful
  110060. with VQ.
  110061. */
  110062. typedef struct static_codebook{
  110063. long dim; /* codebook dimensions (elements per vector) */
  110064. long entries; /* codebook entries */
  110065. long *lengthlist; /* codeword lengths in bits */
  110066. /* mapping ***************************************************************/
  110067. int maptype; /* 0=none
  110068. 1=implicitly populated values from map column
  110069. 2=listed arbitrary values */
  110070. /* The below does a linear, single monotonic sequence mapping. */
  110071. long q_min; /* packed 32 bit float; quant value 0 maps to minval */
  110072. long q_delta; /* packed 32 bit float; val 1 - val 0 == delta */
  110073. int q_quant; /* bits: 0 < quant <= 16 */
  110074. int q_sequencep; /* bitflag */
  110075. long *quantlist; /* map == 1: (int)(entries^(1/dim)) element column map
  110076. map == 2: list of dim*entries quantized entry vals
  110077. */
  110078. /* encode helpers ********************************************************/
  110079. struct encode_aux_nearestmatch *nearest_tree;
  110080. struct encode_aux_threshmatch *thresh_tree;
  110081. struct encode_aux_pigeonhole *pigeon_tree;
  110082. int allocedp;
  110083. } static_codebook;
  110084. /* this structures an arbitrary trained book to quickly find the
  110085. nearest cell match */
  110086. typedef struct encode_aux_nearestmatch{
  110087. /* pre-calculated partitioning tree */
  110088. long *ptr0;
  110089. long *ptr1;
  110090. long *p; /* decision points (each is an entry) */
  110091. long *q; /* decision points (each is an entry) */
  110092. long aux; /* number of tree entries */
  110093. long alloc;
  110094. } encode_aux_nearestmatch;
  110095. /* assumes a maptype of 1; encode side only, so that's OK */
  110096. typedef struct encode_aux_threshmatch{
  110097. float *quantthresh;
  110098. long *quantmap;
  110099. int quantvals;
  110100. int threshvals;
  110101. } encode_aux_threshmatch;
  110102. typedef struct encode_aux_pigeonhole{
  110103. float min;
  110104. float del;
  110105. int mapentries;
  110106. int quantvals;
  110107. long *pigeonmap;
  110108. long fittotal;
  110109. long *fitlist;
  110110. long *fitmap;
  110111. long *fitlength;
  110112. } encode_aux_pigeonhole;
  110113. typedef struct codebook{
  110114. long dim; /* codebook dimensions (elements per vector) */
  110115. long entries; /* codebook entries */
  110116. long used_entries; /* populated codebook entries */
  110117. const static_codebook *c;
  110118. /* for encode, the below are entry-ordered, fully populated */
  110119. /* for decode, the below are ordered by bitreversed codeword and only
  110120. used entries are populated */
  110121. float *valuelist; /* list of dim*entries actual entry values */
  110122. ogg_uint32_t *codelist; /* list of bitstream codewords for each entry */
  110123. int *dec_index; /* only used if sparseness collapsed */
  110124. char *dec_codelengths;
  110125. ogg_uint32_t *dec_firsttable;
  110126. int dec_firsttablen;
  110127. int dec_maxlength;
  110128. } codebook;
  110129. extern void vorbis_staticbook_clear(static_codebook *b);
  110130. extern void vorbis_staticbook_destroy(static_codebook *b);
  110131. extern int vorbis_book_init_encode(codebook *dest,const static_codebook *source);
  110132. extern int vorbis_book_init_decode(codebook *dest,const static_codebook *source);
  110133. extern void vorbis_book_clear(codebook *b);
  110134. extern float *_book_unquantize(const static_codebook *b,int n,int *map);
  110135. extern float *_book_logdist(const static_codebook *b,float *vals);
  110136. extern float _float32_unpack(long val);
  110137. extern long _float32_pack(float val);
  110138. extern int _best(codebook *book, float *a, int step);
  110139. extern int _ilog(unsigned int v);
  110140. extern long _book_maptype1_quantvals(const static_codebook *b);
  110141. extern int vorbis_book_besterror(codebook *book,float *a,int step,int addmul);
  110142. extern long vorbis_book_codeword(codebook *book,int entry);
  110143. extern long vorbis_book_codelen(codebook *book,int entry);
  110144. extern int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *b);
  110145. extern int vorbis_staticbook_unpack(oggpack_buffer *b,static_codebook *c);
  110146. extern int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b);
  110147. extern int vorbis_book_errorv(codebook *book, float *a);
  110148. extern int vorbis_book_encodev(codebook *book, int best,float *a,
  110149. oggpack_buffer *b);
  110150. extern long vorbis_book_decode(codebook *book, oggpack_buffer *b);
  110151. extern long vorbis_book_decodevs_add(codebook *book, float *a,
  110152. oggpack_buffer *b,int n);
  110153. extern long vorbis_book_decodev_set(codebook *book, float *a,
  110154. oggpack_buffer *b,int n);
  110155. extern long vorbis_book_decodev_add(codebook *book, float *a,
  110156. oggpack_buffer *b,int n);
  110157. extern long vorbis_book_decodevv_add(codebook *book, float **a,
  110158. long off,int ch,
  110159. oggpack_buffer *b,int n);
  110160. #endif
  110161. /*** End of inlined file: codebook.h ***/
  110162. #define BLOCKTYPE_IMPULSE 0
  110163. #define BLOCKTYPE_PADDING 1
  110164. #define BLOCKTYPE_TRANSITION 0
  110165. #define BLOCKTYPE_LONG 1
  110166. #define PACKETBLOBS 15
  110167. typedef struct vorbis_block_internal{
  110168. float **pcmdelay; /* this is a pointer into local storage */
  110169. float ampmax;
  110170. int blocktype;
  110171. oggpack_buffer *packetblob[PACKETBLOBS]; /* initialized, must be freed;
  110172. blob [PACKETBLOBS/2] points to
  110173. the oggpack_buffer in the
  110174. main vorbis_block */
  110175. } vorbis_block_internal;
  110176. typedef void vorbis_look_floor;
  110177. typedef void vorbis_look_residue;
  110178. typedef void vorbis_look_transform;
  110179. /* mode ************************************************************/
  110180. typedef struct {
  110181. int blockflag;
  110182. int windowtype;
  110183. int transformtype;
  110184. int mapping;
  110185. } vorbis_info_mode;
  110186. typedef void vorbis_info_floor;
  110187. typedef void vorbis_info_residue;
  110188. typedef void vorbis_info_mapping;
  110189. /*** Start of inlined file: psy.h ***/
  110190. #ifndef _V_PSY_H_
  110191. #define _V_PSY_H_
  110192. /*** Start of inlined file: smallft.h ***/
  110193. #ifndef _V_SMFT_H_
  110194. #define _V_SMFT_H_
  110195. typedef struct {
  110196. int n;
  110197. float *trigcache;
  110198. int *splitcache;
  110199. } drft_lookup;
  110200. extern void drft_forward(drft_lookup *l,float *data);
  110201. extern void drft_backward(drft_lookup *l,float *data);
  110202. extern void drft_init(drft_lookup *l,int n);
  110203. extern void drft_clear(drft_lookup *l);
  110204. #endif
  110205. /*** End of inlined file: smallft.h ***/
  110206. /*** Start of inlined file: backends.h ***/
  110207. /* this is exposed up here because we need it for static modes.
  110208. Lookups for each backend aren't exposed because there's no reason
  110209. to do so */
  110210. #ifndef _vorbis_backend_h_
  110211. #define _vorbis_backend_h_
  110212. /* this would all be simpler/shorter with templates, but.... */
  110213. /* Floor backend generic *****************************************/
  110214. typedef struct{
  110215. void (*pack) (vorbis_info_floor *,oggpack_buffer *);
  110216. vorbis_info_floor *(*unpack)(vorbis_info *,oggpack_buffer *);
  110217. vorbis_look_floor *(*look) (vorbis_dsp_state *,vorbis_info_floor *);
  110218. void (*free_info) (vorbis_info_floor *);
  110219. void (*free_look) (vorbis_look_floor *);
  110220. void *(*inverse1) (struct vorbis_block *,vorbis_look_floor *);
  110221. int (*inverse2) (struct vorbis_block *,vorbis_look_floor *,
  110222. void *buffer,float *);
  110223. } vorbis_func_floor;
  110224. typedef struct{
  110225. int order;
  110226. long rate;
  110227. long barkmap;
  110228. int ampbits;
  110229. int ampdB;
  110230. int numbooks; /* <= 16 */
  110231. int books[16];
  110232. float lessthan; /* encode-only config setting hacks for libvorbis */
  110233. float greaterthan; /* encode-only config setting hacks for libvorbis */
  110234. } vorbis_info_floor0;
  110235. #define VIF_POSIT 63
  110236. #define VIF_CLASS 16
  110237. #define VIF_PARTS 31
  110238. typedef struct{
  110239. int partitions; /* 0 to 31 */
  110240. int partitionclass[VIF_PARTS]; /* 0 to 15 */
  110241. int class_dim[VIF_CLASS]; /* 1 to 8 */
  110242. int class_subs[VIF_CLASS]; /* 0,1,2,3 (bits: 1<<n poss) */
  110243. int class_book[VIF_CLASS]; /* subs ^ dim entries */
  110244. int class_subbook[VIF_CLASS][8]; /* [VIF_CLASS][subs] */
  110245. int mult; /* 1 2 3 or 4 */
  110246. int postlist[VIF_POSIT+2]; /* first two implicit */
  110247. /* encode side analysis parameters */
  110248. float maxover;
  110249. float maxunder;
  110250. float maxerr;
  110251. float twofitweight;
  110252. float twofitatten;
  110253. int n;
  110254. } vorbis_info_floor1;
  110255. /* Residue backend generic *****************************************/
  110256. typedef struct{
  110257. void (*pack) (vorbis_info_residue *,oggpack_buffer *);
  110258. vorbis_info_residue *(*unpack)(vorbis_info *,oggpack_buffer *);
  110259. vorbis_look_residue *(*look) (vorbis_dsp_state *,
  110260. vorbis_info_residue *);
  110261. void (*free_info) (vorbis_info_residue *);
  110262. void (*free_look) (vorbis_look_residue *);
  110263. long **(*classx) (struct vorbis_block *,vorbis_look_residue *,
  110264. float **,int *,int);
  110265. int (*forward) (oggpack_buffer *,struct vorbis_block *,
  110266. vorbis_look_residue *,
  110267. float **,float **,int *,int,long **);
  110268. int (*inverse) (struct vorbis_block *,vorbis_look_residue *,
  110269. float **,int *,int);
  110270. } vorbis_func_residue;
  110271. typedef struct vorbis_info_residue0{
  110272. /* block-partitioned VQ coded straight residue */
  110273. long begin;
  110274. long end;
  110275. /* first stage (lossless partitioning) */
  110276. int grouping; /* group n vectors per partition */
  110277. int partitions; /* possible codebooks for a partition */
  110278. int groupbook; /* huffbook for partitioning */
  110279. int secondstages[64]; /* expanded out to pointers in lookup */
  110280. int booklist[256]; /* list of second stage books */
  110281. float classmetric1[64];
  110282. float classmetric2[64];
  110283. } vorbis_info_residue0;
  110284. /* Mapping backend generic *****************************************/
  110285. typedef struct{
  110286. void (*pack) (vorbis_info *,vorbis_info_mapping *,
  110287. oggpack_buffer *);
  110288. vorbis_info_mapping *(*unpack)(vorbis_info *,oggpack_buffer *);
  110289. void (*free_info) (vorbis_info_mapping *);
  110290. int (*forward) (struct vorbis_block *vb);
  110291. int (*inverse) (struct vorbis_block *vb,vorbis_info_mapping *);
  110292. } vorbis_func_mapping;
  110293. typedef struct vorbis_info_mapping0{
  110294. int submaps; /* <= 16 */
  110295. int chmuxlist[256]; /* up to 256 channels in a Vorbis stream */
  110296. int floorsubmap[16]; /* [mux] submap to floors */
  110297. int residuesubmap[16]; /* [mux] submap to residue */
  110298. int coupling_steps;
  110299. int coupling_mag[256];
  110300. int coupling_ang[256];
  110301. } vorbis_info_mapping0;
  110302. #endif
  110303. /*** End of inlined file: backends.h ***/
  110304. #ifndef EHMER_MAX
  110305. #define EHMER_MAX 56
  110306. #endif
  110307. /* psychoacoustic setup ********************************************/
  110308. #define P_BANDS 17 /* 62Hz to 16kHz */
  110309. #define P_LEVELS 8 /* 30dB to 100dB */
  110310. #define P_LEVEL_0 30. /* 30 dB */
  110311. #define P_NOISECURVES 3
  110312. #define NOISE_COMPAND_LEVELS 40
  110313. typedef struct vorbis_info_psy{
  110314. int blockflag;
  110315. float ath_adjatt;
  110316. float ath_maxatt;
  110317. float tone_masteratt[P_NOISECURVES];
  110318. float tone_centerboost;
  110319. float tone_decay;
  110320. float tone_abs_limit;
  110321. float toneatt[P_BANDS];
  110322. int noisemaskp;
  110323. float noisemaxsupp;
  110324. float noisewindowlo;
  110325. float noisewindowhi;
  110326. int noisewindowlomin;
  110327. int noisewindowhimin;
  110328. int noisewindowfixed;
  110329. float noiseoff[P_NOISECURVES][P_BANDS];
  110330. float noisecompand[NOISE_COMPAND_LEVELS];
  110331. float max_curve_dB;
  110332. int normal_channel_p;
  110333. int normal_point_p;
  110334. int normal_start;
  110335. int normal_partition;
  110336. double normal_thresh;
  110337. } vorbis_info_psy;
  110338. typedef struct{
  110339. int eighth_octave_lines;
  110340. /* for block long/short tuning; encode only */
  110341. float preecho_thresh[VE_BANDS];
  110342. float postecho_thresh[VE_BANDS];
  110343. float stretch_penalty;
  110344. float preecho_minenergy;
  110345. float ampmax_att_per_sec;
  110346. /* channel coupling config */
  110347. int coupling_pkHz[PACKETBLOBS];
  110348. int coupling_pointlimit[2][PACKETBLOBS];
  110349. int coupling_prepointamp[PACKETBLOBS];
  110350. int coupling_postpointamp[PACKETBLOBS];
  110351. int sliding_lowpass[2][PACKETBLOBS];
  110352. } vorbis_info_psy_global;
  110353. typedef struct {
  110354. float ampmax;
  110355. int channels;
  110356. vorbis_info_psy_global *gi;
  110357. int coupling_pointlimit[2][P_NOISECURVES];
  110358. } vorbis_look_psy_global;
  110359. typedef struct {
  110360. int n;
  110361. struct vorbis_info_psy *vi;
  110362. float ***tonecurves;
  110363. float **noiseoffset;
  110364. float *ath;
  110365. long *octave; /* in n.ocshift format */
  110366. long *bark;
  110367. long firstoc;
  110368. long shiftoc;
  110369. int eighth_octave_lines; /* power of two, please */
  110370. int total_octave_lines;
  110371. long rate; /* cache it */
  110372. float m_val; /* Masking compensation value */
  110373. } vorbis_look_psy;
  110374. extern void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  110375. vorbis_info_psy_global *gi,int n,long rate);
  110376. extern void _vp_psy_clear(vorbis_look_psy *p);
  110377. extern void *_vi_psy_dup(void *source);
  110378. extern void _vi_psy_free(vorbis_info_psy *i);
  110379. extern vorbis_info_psy *_vi_psy_copy(vorbis_info_psy *i);
  110380. extern void _vp_remove_floor(vorbis_look_psy *p,
  110381. float *mdct,
  110382. int *icodedflr,
  110383. float *residue,
  110384. int sliding_lowpass);
  110385. extern void _vp_noisemask(vorbis_look_psy *p,
  110386. float *logmdct,
  110387. float *logmask);
  110388. extern void _vp_tonemask(vorbis_look_psy *p,
  110389. float *logfft,
  110390. float *logmask,
  110391. float global_specmax,
  110392. float local_specmax);
  110393. extern void _vp_offset_and_mix(vorbis_look_psy *p,
  110394. float *noise,
  110395. float *tone,
  110396. int offset_select,
  110397. float *logmask,
  110398. float *mdct,
  110399. float *logmdct);
  110400. extern float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd);
  110401. extern float **_vp_quantize_couple_memo(vorbis_block *vb,
  110402. vorbis_info_psy_global *g,
  110403. vorbis_look_psy *p,
  110404. vorbis_info_mapping0 *vi,
  110405. float **mdct);
  110406. extern void _vp_couple(int blobno,
  110407. vorbis_info_psy_global *g,
  110408. vorbis_look_psy *p,
  110409. vorbis_info_mapping0 *vi,
  110410. float **res,
  110411. float **mag_memo,
  110412. int **mag_sort,
  110413. int **ifloor,
  110414. int *nonzero,
  110415. int sliding_lowpass);
  110416. extern void _vp_noise_normalize(vorbis_look_psy *p,
  110417. float *in,float *out,int *sortedindex);
  110418. extern void _vp_noise_normalize_sort(vorbis_look_psy *p,
  110419. float *magnitudes,int *sortedindex);
  110420. extern int **_vp_quantize_couple_sort(vorbis_block *vb,
  110421. vorbis_look_psy *p,
  110422. vorbis_info_mapping0 *vi,
  110423. float **mags);
  110424. extern void hf_reduction(vorbis_info_psy_global *g,
  110425. vorbis_look_psy *p,
  110426. vorbis_info_mapping0 *vi,
  110427. float **mdct);
  110428. #endif
  110429. /*** End of inlined file: psy.h ***/
  110430. /*** Start of inlined file: bitrate.h ***/
  110431. #ifndef _V_BITRATE_H_
  110432. #define _V_BITRATE_H_
  110433. /*** Start of inlined file: os.h ***/
  110434. #ifndef _OS_H
  110435. #define _OS_H
  110436. /********************************************************************
  110437. * *
  110438. * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. *
  110439. * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
  110440. * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
  110441. * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
  110442. * *
  110443. * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2002 *
  110444. * by the XIPHOPHORUS Company http://www.xiph.org/ *
  110445. * *
  110446. ********************************************************************
  110447. function: #ifdef jail to whip a few platforms into the UNIX ideal.
  110448. last mod: $Id: os.h,v 1.1 2007/06/07 17:49:18 jules_rms Exp $
  110449. ********************************************************************/
  110450. #ifdef HAVE_CONFIG_H
  110451. #include "config.h"
  110452. #endif
  110453. #include <math.h>
  110454. /*** Start of inlined file: misc.h ***/
  110455. #ifndef _V_RANDOM_H_
  110456. #define _V_RANDOM_H_
  110457. extern int analysis_noisy;
  110458. extern void *_vorbis_block_alloc(vorbis_block *vb,long bytes);
  110459. extern void _vorbis_block_ripcord(vorbis_block *vb);
  110460. extern void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  110461. ogg_int64_t off);
  110462. #ifdef DEBUG_MALLOC
  110463. #define _VDBG_GRAPHFILE "malloc.m"
  110464. extern void *_VDBG_malloc(void *ptr,long bytes,char *file,long line);
  110465. extern void _VDBG_free(void *ptr,char *file,long line);
  110466. #ifndef MISC_C
  110467. #undef _ogg_malloc
  110468. #undef _ogg_calloc
  110469. #undef _ogg_realloc
  110470. #undef _ogg_free
  110471. #define _ogg_malloc(x) _VDBG_malloc(NULL,(x),__FILE__,__LINE__)
  110472. #define _ogg_calloc(x,y) _VDBG_malloc(NULL,(x)*(y),__FILE__,__LINE__)
  110473. #define _ogg_realloc(x,y) _VDBG_malloc((x),(y),__FILE__,__LINE__)
  110474. #define _ogg_free(x) _VDBG_free((x),__FILE__,__LINE__)
  110475. #endif
  110476. #endif
  110477. #endif
  110478. /*** End of inlined file: misc.h ***/
  110479. #ifndef _V_IFDEFJAIL_H_
  110480. # define _V_IFDEFJAIL_H_
  110481. # ifdef __GNUC__
  110482. # define STIN static __inline__
  110483. # elif _WIN32
  110484. # define STIN static __inline
  110485. # else
  110486. # define STIN static
  110487. # endif
  110488. #ifdef DJGPP
  110489. # define rint(x) (floor((x)+0.5f))
  110490. #endif
  110491. #ifndef M_PI
  110492. # define M_PI (3.1415926536f)
  110493. #endif
  110494. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  110495. # include <malloc.h>
  110496. # define rint(x) (floor((x)+0.5f))
  110497. # define NO_FLOAT_MATH_LIB
  110498. # define FAST_HYPOT(a, b) sqrt((a)*(a) + (b)*(b))
  110499. #endif
  110500. #if defined(__SYMBIAN32__) && defined(__WINS__)
  110501. void *_alloca(size_t size);
  110502. # define alloca _alloca
  110503. #endif
  110504. #ifndef FAST_HYPOT
  110505. # define FAST_HYPOT hypot
  110506. #endif
  110507. #endif
  110508. #ifdef HAVE_ALLOCA_H
  110509. # include <alloca.h>
  110510. #endif
  110511. #ifdef USE_MEMORY_H
  110512. # include <memory.h>
  110513. #endif
  110514. #ifndef min
  110515. # define min(x,y) ((x)>(y)?(y):(x))
  110516. #endif
  110517. #ifndef max
  110518. # define max(x,y) ((x)<(y)?(y):(x))
  110519. #endif
  110520. #if defined(__i386__) && defined(__GNUC__) && !defined(__BEOS__)
  110521. # define VORBIS_FPU_CONTROL
  110522. /* both GCC and MSVC are kinda stupid about rounding/casting to int.
  110523. Because of encapsulation constraints (GCC can't see inside the asm
  110524. block and so we end up doing stupid things like a store/load that
  110525. is collectively a noop), we do it this way */
  110526. /* we must set up the fpu before this works!! */
  110527. typedef ogg_int16_t vorbis_fpu_control;
  110528. static inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  110529. ogg_int16_t ret;
  110530. ogg_int16_t temp;
  110531. __asm__ __volatile__("fnstcw %0\n\t"
  110532. "movw %0,%%dx\n\t"
  110533. "orw $62463,%%dx\n\t"
  110534. "movw %%dx,%1\n\t"
  110535. "fldcw %1\n\t":"=m"(ret):"m"(temp): "dx");
  110536. *fpu=ret;
  110537. }
  110538. static inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  110539. __asm__ __volatile__("fldcw %0":: "m"(fpu));
  110540. }
  110541. /* assumes the FPU is in round mode! */
  110542. static inline int vorbis_ftoi(double f){ /* yes, double! Otherwise,
  110543. we get extra fst/fld to
  110544. truncate precision */
  110545. int i;
  110546. __asm__("fistl %0": "=m"(i) : "t"(f));
  110547. return(i);
  110548. }
  110549. #endif
  110550. #if defined(_WIN32) && defined(_X86_) && !defined(__GNUC__) && !defined(__BORLANDC__)
  110551. # define VORBIS_FPU_CONTROL
  110552. typedef ogg_int16_t vorbis_fpu_control;
  110553. static __inline int vorbis_ftoi(double f){
  110554. int i;
  110555. __asm{
  110556. fld f
  110557. fistp i
  110558. }
  110559. return i;
  110560. }
  110561. static __inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  110562. }
  110563. static __inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  110564. }
  110565. #endif
  110566. #ifndef VORBIS_FPU_CONTROL
  110567. typedef int vorbis_fpu_control;
  110568. static int vorbis_ftoi(double f){
  110569. return (int)(f+.5);
  110570. }
  110571. /* We don't have special code for this compiler/arch, so do it the slow way */
  110572. # define vorbis_fpu_setround(vorbis_fpu_control) {}
  110573. # define vorbis_fpu_restore(vorbis_fpu_control) {}
  110574. #endif
  110575. #endif /* _OS_H */
  110576. /*** End of inlined file: os.h ***/
  110577. /* encode side bitrate tracking */
  110578. typedef struct bitrate_manager_state {
  110579. int managed;
  110580. long avg_reservoir;
  110581. long minmax_reservoir;
  110582. long avg_bitsper;
  110583. long min_bitsper;
  110584. long max_bitsper;
  110585. long short_per_long;
  110586. double avgfloat;
  110587. vorbis_block *vb;
  110588. int choice;
  110589. } bitrate_manager_state;
  110590. typedef struct bitrate_manager_info{
  110591. long avg_rate;
  110592. long min_rate;
  110593. long max_rate;
  110594. long reservoir_bits;
  110595. double reservoir_bias;
  110596. double slew_damp;
  110597. } bitrate_manager_info;
  110598. extern void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bs);
  110599. extern void vorbis_bitrate_clear(bitrate_manager_state *bs);
  110600. extern int vorbis_bitrate_managed(vorbis_block *vb);
  110601. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  110602. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd, ogg_packet *op);
  110603. #endif
  110604. /*** End of inlined file: bitrate.h ***/
  110605. static int ilog(unsigned int v){
  110606. int ret=0;
  110607. while(v){
  110608. ret++;
  110609. v>>=1;
  110610. }
  110611. return(ret);
  110612. }
  110613. static int ilog2(unsigned int v){
  110614. int ret=0;
  110615. if(v)--v;
  110616. while(v){
  110617. ret++;
  110618. v>>=1;
  110619. }
  110620. return(ret);
  110621. }
  110622. typedef struct private_state {
  110623. /* local lookup storage */
  110624. envelope_lookup *ve; /* envelope lookup */
  110625. int window[2];
  110626. vorbis_look_transform **transform[2]; /* block, type */
  110627. drft_lookup fft_look[2];
  110628. int modebits;
  110629. vorbis_look_floor **flr;
  110630. vorbis_look_residue **residue;
  110631. vorbis_look_psy *psy;
  110632. vorbis_look_psy_global *psy_g_look;
  110633. /* local storage, only used on the encoding side. This way the
  110634. application does not need to worry about freeing some packets'
  110635. memory and not others'; packet storage is always tracked.
  110636. Cleared next call to a _dsp_ function */
  110637. unsigned char *header;
  110638. unsigned char *header1;
  110639. unsigned char *header2;
  110640. bitrate_manager_state bms;
  110641. ogg_int64_t sample_count;
  110642. } private_state;
  110643. /* codec_setup_info contains all the setup information specific to the
  110644. specific compression/decompression mode in progress (eg,
  110645. psychoacoustic settings, channel setup, options, codebook
  110646. etc).
  110647. *********************************************************************/
  110648. /*** Start of inlined file: highlevel.h ***/
  110649. typedef struct highlevel_byblocktype {
  110650. double tone_mask_setting;
  110651. double tone_peaklimit_setting;
  110652. double noise_bias_setting;
  110653. double noise_compand_setting;
  110654. } highlevel_byblocktype;
  110655. typedef struct highlevel_encode_setup {
  110656. void *setup;
  110657. int set_in_stone;
  110658. double base_setting;
  110659. double long_setting;
  110660. double short_setting;
  110661. double impulse_noisetune;
  110662. int managed;
  110663. long bitrate_min;
  110664. long bitrate_av;
  110665. double bitrate_av_damp;
  110666. long bitrate_max;
  110667. long bitrate_reservoir;
  110668. double bitrate_reservoir_bias;
  110669. int impulse_block_p;
  110670. int noise_normalize_p;
  110671. double stereo_point_setting;
  110672. double lowpass_kHz;
  110673. double ath_floating_dB;
  110674. double ath_absolute_dB;
  110675. double amplitude_track_dBpersec;
  110676. double trigger_setting;
  110677. highlevel_byblocktype block[4]; /* padding, impulse, transition, long */
  110678. } highlevel_encode_setup;
  110679. /*** End of inlined file: highlevel.h ***/
  110680. typedef struct codec_setup_info {
  110681. /* Vorbis supports only short and long blocks, but allows the
  110682. encoder to choose the sizes */
  110683. long blocksizes[2];
  110684. /* modes are the primary means of supporting on-the-fly different
  110685. blocksizes, different channel mappings (LR or M/A),
  110686. different residue backends, etc. Each mode consists of a
  110687. blocksize flag and a mapping (along with the mapping setup */
  110688. int modes;
  110689. int maps;
  110690. int floors;
  110691. int residues;
  110692. int books;
  110693. int psys; /* encode only */
  110694. vorbis_info_mode *mode_param[64];
  110695. int map_type[64];
  110696. vorbis_info_mapping *map_param[64];
  110697. int floor_type[64];
  110698. vorbis_info_floor *floor_param[64];
  110699. int residue_type[64];
  110700. vorbis_info_residue *residue_param[64];
  110701. static_codebook *book_param[256];
  110702. codebook *fullbooks;
  110703. vorbis_info_psy *psy_param[4]; /* encode only */
  110704. vorbis_info_psy_global psy_g_param;
  110705. bitrate_manager_info bi;
  110706. highlevel_encode_setup hi; /* used only by vorbisenc.c. It's a
  110707. highly redundant structure, but
  110708. improves clarity of program flow. */
  110709. int halfrate_flag; /* painless downsample for decode */
  110710. } codec_setup_info;
  110711. extern vorbis_look_psy_global *_vp_global_look(vorbis_info *vi);
  110712. extern void _vp_global_free(vorbis_look_psy_global *look);
  110713. #endif
  110714. /*** End of inlined file: codec_internal.h ***/
  110715. /*** Start of inlined file: registry.h ***/
  110716. #ifndef _V_REG_H_
  110717. #define _V_REG_H_
  110718. #define VI_TRANSFORMB 1
  110719. #define VI_WINDOWB 1
  110720. #define VI_TIMEB 1
  110721. #define VI_FLOORB 2
  110722. #define VI_RESB 3
  110723. #define VI_MAPB 1
  110724. extern vorbis_func_floor *_floor_P[];
  110725. extern vorbis_func_residue *_residue_P[];
  110726. extern vorbis_func_mapping *_mapping_P[];
  110727. #endif
  110728. /*** End of inlined file: registry.h ***/
  110729. /*** Start of inlined file: scales.h ***/
  110730. #ifndef _V_SCALES_H_
  110731. #define _V_SCALES_H_
  110732. #include <math.h>
  110733. /* 20log10(x) */
  110734. #define VORBIS_IEEE_FLOAT32 1
  110735. #ifdef VORBIS_IEEE_FLOAT32
  110736. static float unitnorm(float x){
  110737. union {
  110738. ogg_uint32_t i;
  110739. float f;
  110740. } ix;
  110741. ix.f = x;
  110742. ix.i = (ix.i & 0x80000000U) | (0x3f800000U);
  110743. return ix.f;
  110744. }
  110745. /* Segher was off (too high) by ~ .3 decibel. Center the conversion correctly. */
  110746. static float todB(const float *x){
  110747. union {
  110748. ogg_uint32_t i;
  110749. float f;
  110750. } ix;
  110751. ix.f = *x;
  110752. ix.i = ix.i&0x7fffffff;
  110753. return (float)(ix.i * 7.17711438e-7f -764.6161886f);
  110754. }
  110755. #define todB_nn(x) todB(x)
  110756. #else
  110757. static float unitnorm(float x){
  110758. if(x<0)return(-1.f);
  110759. return(1.f);
  110760. }
  110761. #define todB(x) (*(x)==0?-400.f:log(*(x)**(x))*4.34294480f)
  110762. #define todB_nn(x) (*(x)==0.f?-400.f:log(*(x))*8.6858896f)
  110763. #endif
  110764. #define fromdB(x) (exp((x)*.11512925f))
  110765. /* The bark scale equations are approximations, since the original
  110766. table was somewhat hand rolled. The below are chosen to have the
  110767. best possible fit to the rolled tables, thus their somewhat odd
  110768. appearance (these are more accurate and over a longer range than
  110769. the oft-quoted bark equations found in the texts I have). The
  110770. approximations are valid from 0 - 30kHz (nyquist) or so.
  110771. all f in Hz, z in Bark */
  110772. #define toBARK(n) (13.1f*atan(.00074f*(n))+2.24f*atan((n)*(n)*1.85e-8f)+1e-4f*(n))
  110773. #define fromBARK(z) (102.f*(z)-2.f*pow(z,2.f)+.4f*pow(z,3.f)+pow(1.46f,z)-1.f)
  110774. #define toMEL(n) (log(1.f+(n)*.001f)*1442.695f)
  110775. #define fromMEL(m) (1000.f*exp((m)/1442.695f)-1000.f)
  110776. /* Frequency to octave. We arbitrarily declare 63.5 Hz to be octave
  110777. 0.0 */
  110778. #define toOC(n) (log(n)*1.442695f-5.965784f)
  110779. #define fromOC(o) (exp(((o)+5.965784f)*.693147f))
  110780. #endif
  110781. /*** End of inlined file: scales.h ***/
  110782. int analysis_noisy=1;
  110783. /* decides between modes, dispatches to the appropriate mapping. */
  110784. int vorbis_analysis(vorbis_block *vb, ogg_packet *op){
  110785. int ret,i;
  110786. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  110787. vb->glue_bits=0;
  110788. vb->time_bits=0;
  110789. vb->floor_bits=0;
  110790. vb->res_bits=0;
  110791. /* first things first. Make sure encode is ready */
  110792. for(i=0;i<PACKETBLOBS;i++)
  110793. oggpack_reset(vbi->packetblob[i]);
  110794. /* we only have one mapping type (0), and we let the mapping code
  110795. itself figure out what soft mode to use. This allows easier
  110796. bitrate management */
  110797. if((ret=_mapping_P[0]->forward(vb)))
  110798. return(ret);
  110799. if(op){
  110800. if(vorbis_bitrate_managed(vb))
  110801. /* The app is using a bitmanaged mode... but not using the
  110802. bitrate management interface. */
  110803. return(OV_EINVAL);
  110804. op->packet=oggpack_get_buffer(&vb->opb);
  110805. op->bytes=oggpack_bytes(&vb->opb);
  110806. op->b_o_s=0;
  110807. op->e_o_s=vb->eofflag;
  110808. op->granulepos=vb->granulepos;
  110809. op->packetno=vb->sequence; /* for sake of completeness */
  110810. }
  110811. return(0);
  110812. }
  110813. /* there was no great place to put this.... */
  110814. void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,ogg_int64_t off){
  110815. int j;
  110816. FILE *of;
  110817. char buffer[80];
  110818. /* if(i==5870){*/
  110819. sprintf(buffer,"%s_%d.m",base,i);
  110820. of=fopen(buffer,"w");
  110821. if(!of)perror("failed to open data dump file");
  110822. for(j=0;j<n;j++){
  110823. if(bark){
  110824. float b=toBARK((4000.f*j/n)+.25);
  110825. fprintf(of,"%f ",b);
  110826. }else
  110827. if(off!=0)
  110828. fprintf(of,"%f ",(double)(j+off)/8000.);
  110829. else
  110830. fprintf(of,"%f ",(double)j);
  110831. if(dB){
  110832. float val;
  110833. if(v[j]==0.)
  110834. val=-140.;
  110835. else
  110836. val=todB(v+j);
  110837. fprintf(of,"%f\n",val);
  110838. }else{
  110839. fprintf(of,"%f\n",v[j]);
  110840. }
  110841. }
  110842. fclose(of);
  110843. /* } */
  110844. }
  110845. void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  110846. ogg_int64_t off){
  110847. if(analysis_noisy)_analysis_output_always(base,i,v,n,bark,dB,off);
  110848. }
  110849. #endif
  110850. /*** End of inlined file: analysis.c ***/
  110851. /*** Start of inlined file: bitrate.c ***/
  110852. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  110853. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110854. // tasks..
  110855. #if JUCE_MSVC
  110856. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110857. #endif
  110858. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  110859. #if JUCE_USE_OGGVORBIS
  110860. #include <stdlib.h>
  110861. #include <string.h>
  110862. #include <math.h>
  110863. /* compute bitrate tracking setup */
  110864. void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bm){
  110865. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  110866. bitrate_manager_info *bi=&ci->bi;
  110867. memset(bm,0,sizeof(*bm));
  110868. if(bi && (bi->reservoir_bits>0)){
  110869. long ratesamples=vi->rate;
  110870. int halfsamples=ci->blocksizes[0]>>1;
  110871. bm->short_per_long=ci->blocksizes[1]/ci->blocksizes[0];
  110872. bm->managed=1;
  110873. bm->avg_bitsper= rint(1.*bi->avg_rate*halfsamples/ratesamples);
  110874. bm->min_bitsper= rint(1.*bi->min_rate*halfsamples/ratesamples);
  110875. bm->max_bitsper= rint(1.*bi->max_rate*halfsamples/ratesamples);
  110876. bm->avgfloat=PACKETBLOBS/2;
  110877. /* not a necessary fix, but one that leads to a more balanced
  110878. typical initialization */
  110879. {
  110880. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  110881. bm->minmax_reservoir=desired_fill;
  110882. bm->avg_reservoir=desired_fill;
  110883. }
  110884. }
  110885. }
  110886. void vorbis_bitrate_clear(bitrate_manager_state *bm){
  110887. memset(bm,0,sizeof(*bm));
  110888. return;
  110889. }
  110890. int vorbis_bitrate_managed(vorbis_block *vb){
  110891. vorbis_dsp_state *vd=vb->vd;
  110892. private_state *b=(private_state*)vd->backend_state;
  110893. bitrate_manager_state *bm=&b->bms;
  110894. if(bm && bm->managed)return(1);
  110895. return(0);
  110896. }
  110897. /* finish taking in the block we just processed */
  110898. int vorbis_bitrate_addblock(vorbis_block *vb){
  110899. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  110900. vorbis_dsp_state *vd=vb->vd;
  110901. private_state *b=(private_state*)vd->backend_state;
  110902. bitrate_manager_state *bm=&b->bms;
  110903. vorbis_info *vi=vd->vi;
  110904. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110905. bitrate_manager_info *bi=&ci->bi;
  110906. int choice=rint(bm->avgfloat);
  110907. long this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110908. long min_target_bits=(vb->W?bm->min_bitsper*bm->short_per_long:bm->min_bitsper);
  110909. long max_target_bits=(vb->W?bm->max_bitsper*bm->short_per_long:bm->max_bitsper);
  110910. int samples=ci->blocksizes[vb->W]>>1;
  110911. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  110912. if(!bm->managed){
  110913. /* not a bitrate managed stream, but for API simplicity, we'll
  110914. buffer the packet to keep the code path clean */
  110915. if(bm->vb)return(-1); /* one has been submitted without
  110916. being claimed */
  110917. bm->vb=vb;
  110918. return(0);
  110919. }
  110920. bm->vb=vb;
  110921. /* look ahead for avg floater */
  110922. if(bm->avg_bitsper>0){
  110923. double slew=0.;
  110924. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  110925. double slewlimit= 15./bi->slew_damp;
  110926. /* choosing a new floater:
  110927. if we're over target, we slew down
  110928. if we're under target, we slew up
  110929. choose slew as follows: look through packetblobs of this frame
  110930. and set slew as the first in the appropriate direction that
  110931. gives us the slew we want. This may mean no slew if delta is
  110932. already favorable.
  110933. Then limit slew to slew max */
  110934. if(bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  110935. while(choice>0 && this_bits>avg_target_bits &&
  110936. bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  110937. choice--;
  110938. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110939. }
  110940. }else if(bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  110941. while(choice+1<PACKETBLOBS && this_bits<avg_target_bits &&
  110942. bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  110943. choice++;
  110944. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110945. }
  110946. }
  110947. slew=rint(choice-bm->avgfloat)/samples*vi->rate;
  110948. if(slew<-slewlimit)slew=-slewlimit;
  110949. if(slew>slewlimit)slew=slewlimit;
  110950. choice=rint(bm->avgfloat+= slew/vi->rate*samples);
  110951. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110952. }
  110953. /* enforce min(if used) on the current floater (if used) */
  110954. if(bm->min_bitsper>0){
  110955. /* do we need to force the bitrate up? */
  110956. if(this_bits<min_target_bits){
  110957. while(bm->minmax_reservoir-(min_target_bits-this_bits)<0){
  110958. choice++;
  110959. if(choice>=PACKETBLOBS)break;
  110960. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110961. }
  110962. }
  110963. }
  110964. /* enforce max (if used) on the current floater (if used) */
  110965. if(bm->max_bitsper>0){
  110966. /* do we need to force the bitrate down? */
  110967. if(this_bits>max_target_bits){
  110968. while(bm->minmax_reservoir+(this_bits-max_target_bits)>bi->reservoir_bits){
  110969. choice--;
  110970. if(choice<0)break;
  110971. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110972. }
  110973. }
  110974. }
  110975. /* Choice of packetblobs now made based on floater, and min/max
  110976. requirements. Now boundary check extreme choices */
  110977. if(choice<0){
  110978. /* choosing a smaller packetblob is insufficient to trim bitrate.
  110979. frame will need to be truncated */
  110980. long maxsize=(max_target_bits+(bi->reservoir_bits-bm->minmax_reservoir))/8;
  110981. bm->choice=choice=0;
  110982. if(oggpack_bytes(vbi->packetblob[choice])>maxsize){
  110983. oggpack_writetrunc(vbi->packetblob[choice],maxsize*8);
  110984. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110985. }
  110986. }else{
  110987. long minsize=(min_target_bits-bm->minmax_reservoir+7)/8;
  110988. if(choice>=PACKETBLOBS)
  110989. choice=PACKETBLOBS-1;
  110990. bm->choice=choice;
  110991. /* prop up bitrate according to demand. pad this frame out with zeroes */
  110992. minsize-=oggpack_bytes(vbi->packetblob[choice]);
  110993. while(minsize-->0)oggpack_write(vbi->packetblob[choice],0,8);
  110994. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110995. }
  110996. /* now we have the final packet and the final packet size. Update statistics */
  110997. /* min and max reservoir */
  110998. if(bm->min_bitsper>0 || bm->max_bitsper>0){
  110999. if(max_target_bits>0 && this_bits>max_target_bits){
  111000. bm->minmax_reservoir+=(this_bits-max_target_bits);
  111001. }else if(min_target_bits>0 && this_bits<min_target_bits){
  111002. bm->minmax_reservoir+=(this_bits-min_target_bits);
  111003. }else{
  111004. /* inbetween; we want to take reservoir toward but not past desired_fill */
  111005. if(bm->minmax_reservoir>desired_fill){
  111006. if(max_target_bits>0){ /* logical bulletproofing against initialization state */
  111007. bm->minmax_reservoir+=(this_bits-max_target_bits);
  111008. if(bm->minmax_reservoir<desired_fill)bm->minmax_reservoir=desired_fill;
  111009. }else{
  111010. bm->minmax_reservoir=desired_fill;
  111011. }
  111012. }else{
  111013. if(min_target_bits>0){ /* logical bulletproofing against initialization state */
  111014. bm->minmax_reservoir+=(this_bits-min_target_bits);
  111015. if(bm->minmax_reservoir>desired_fill)bm->minmax_reservoir=desired_fill;
  111016. }else{
  111017. bm->minmax_reservoir=desired_fill;
  111018. }
  111019. }
  111020. }
  111021. }
  111022. /* avg reservoir */
  111023. if(bm->avg_bitsper>0){
  111024. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  111025. bm->avg_reservoir+=this_bits-avg_target_bits;
  111026. }
  111027. return(0);
  111028. }
  111029. int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,ogg_packet *op){
  111030. private_state *b=(private_state*)vd->backend_state;
  111031. bitrate_manager_state *bm=&b->bms;
  111032. vorbis_block *vb=bm->vb;
  111033. int choice=PACKETBLOBS/2;
  111034. if(!vb)return 0;
  111035. if(op){
  111036. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  111037. if(vorbis_bitrate_managed(vb))
  111038. choice=bm->choice;
  111039. op->packet=oggpack_get_buffer(vbi->packetblob[choice]);
  111040. op->bytes=oggpack_bytes(vbi->packetblob[choice]);
  111041. op->b_o_s=0;
  111042. op->e_o_s=vb->eofflag;
  111043. op->granulepos=vb->granulepos;
  111044. op->packetno=vb->sequence; /* for sake of completeness */
  111045. }
  111046. bm->vb=0;
  111047. return(1);
  111048. }
  111049. #endif
  111050. /*** End of inlined file: bitrate.c ***/
  111051. /*** Start of inlined file: block.c ***/
  111052. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111053. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111054. // tasks..
  111055. #if JUCE_MSVC
  111056. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111057. #endif
  111058. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111059. #if JUCE_USE_OGGVORBIS
  111060. #include <stdio.h>
  111061. #include <stdlib.h>
  111062. #include <string.h>
  111063. /*** Start of inlined file: window.h ***/
  111064. #ifndef _V_WINDOW_
  111065. #define _V_WINDOW_
  111066. extern float *_vorbis_window_get(int n);
  111067. extern void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  111068. int lW,int W,int nW);
  111069. #endif
  111070. /*** End of inlined file: window.h ***/
  111071. /*** Start of inlined file: lpc.h ***/
  111072. #ifndef _V_LPC_H_
  111073. #define _V_LPC_H_
  111074. /* simple linear scale LPC code */
  111075. extern float vorbis_lpc_from_data(float *data,float *lpc,int n,int m);
  111076. extern void vorbis_lpc_predict(float *coeff,float *prime,int m,
  111077. float *data,long n);
  111078. #endif
  111079. /*** End of inlined file: lpc.h ***/
  111080. /* pcm accumulator examples (not exhaustive):
  111081. <-------------- lW ---------------->
  111082. <--------------- W ---------------->
  111083. : .....|..... _______________ |
  111084. : .''' | '''_--- | |\ |
  111085. :.....''' |_____--- '''......| | \_______|
  111086. :.................|__________________|_______|__|______|
  111087. |<------ Sl ------>| > Sr < |endW
  111088. |beginSl |endSl | |endSr
  111089. |beginW |endlW |beginSr
  111090. |< lW >|
  111091. <--------------- W ---------------->
  111092. | | .. ______________ |
  111093. | | ' `/ | ---_ |
  111094. |___.'___/`. | ---_____|
  111095. |_______|__|_______|_________________|
  111096. | >|Sl|< |<------ Sr ----->|endW
  111097. | | |endSl |beginSr |endSr
  111098. |beginW | |endlW
  111099. mult[0] |beginSl mult[n]
  111100. <-------------- lW ----------------->
  111101. |<--W-->|
  111102. : .............. ___ | |
  111103. : .''' |`/ \ | |
  111104. :.....''' |/`....\|...|
  111105. :.........................|___|___|___|
  111106. |Sl |Sr |endW
  111107. | | |endSr
  111108. | |beginSr
  111109. | |endSl
  111110. |beginSl
  111111. |beginW
  111112. */
  111113. /* block abstraction setup *********************************************/
  111114. #ifndef WORD_ALIGN
  111115. #define WORD_ALIGN 8
  111116. #endif
  111117. int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb){
  111118. int i;
  111119. memset(vb,0,sizeof(*vb));
  111120. vb->vd=v;
  111121. vb->localalloc=0;
  111122. vb->localstore=NULL;
  111123. if(v->analysisp){
  111124. vorbis_block_internal *vbi=(vorbis_block_internal*)
  111125. (vb->internal=(vorbis_block_internal*)_ogg_calloc(1,sizeof(vorbis_block_internal)));
  111126. vbi->ampmax=-9999;
  111127. for(i=0;i<PACKETBLOBS;i++){
  111128. if(i==PACKETBLOBS/2){
  111129. vbi->packetblob[i]=&vb->opb;
  111130. }else{
  111131. vbi->packetblob[i]=
  111132. (oggpack_buffer*) _ogg_calloc(1,sizeof(oggpack_buffer));
  111133. }
  111134. oggpack_writeinit(vbi->packetblob[i]);
  111135. }
  111136. }
  111137. return(0);
  111138. }
  111139. void *_vorbis_block_alloc(vorbis_block *vb,long bytes){
  111140. bytes=(bytes+(WORD_ALIGN-1)) & ~(WORD_ALIGN-1);
  111141. if(bytes+vb->localtop>vb->localalloc){
  111142. /* can't just _ogg_realloc... there are outstanding pointers */
  111143. if(vb->localstore){
  111144. struct alloc_chain *link=(struct alloc_chain*)_ogg_malloc(sizeof(*link));
  111145. vb->totaluse+=vb->localtop;
  111146. link->next=vb->reap;
  111147. link->ptr=vb->localstore;
  111148. vb->reap=link;
  111149. }
  111150. /* highly conservative */
  111151. vb->localalloc=bytes;
  111152. vb->localstore=_ogg_malloc(vb->localalloc);
  111153. vb->localtop=0;
  111154. }
  111155. {
  111156. void *ret=(void *)(((char *)vb->localstore)+vb->localtop);
  111157. vb->localtop+=bytes;
  111158. return ret;
  111159. }
  111160. }
  111161. /* reap the chain, pull the ripcord */
  111162. void _vorbis_block_ripcord(vorbis_block *vb){
  111163. /* reap the chain */
  111164. struct alloc_chain *reap=vb->reap;
  111165. while(reap){
  111166. struct alloc_chain *next=reap->next;
  111167. _ogg_free(reap->ptr);
  111168. memset(reap,0,sizeof(*reap));
  111169. _ogg_free(reap);
  111170. reap=next;
  111171. }
  111172. /* consolidate storage */
  111173. if(vb->totaluse){
  111174. vb->localstore=_ogg_realloc(vb->localstore,vb->totaluse+vb->localalloc);
  111175. vb->localalloc+=vb->totaluse;
  111176. vb->totaluse=0;
  111177. }
  111178. /* pull the ripcord */
  111179. vb->localtop=0;
  111180. vb->reap=NULL;
  111181. }
  111182. int vorbis_block_clear(vorbis_block *vb){
  111183. int i;
  111184. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  111185. _vorbis_block_ripcord(vb);
  111186. if(vb->localstore)_ogg_free(vb->localstore);
  111187. if(vbi){
  111188. for(i=0;i<PACKETBLOBS;i++){
  111189. oggpack_writeclear(vbi->packetblob[i]);
  111190. if(i!=PACKETBLOBS/2)_ogg_free(vbi->packetblob[i]);
  111191. }
  111192. _ogg_free(vbi);
  111193. }
  111194. memset(vb,0,sizeof(*vb));
  111195. return(0);
  111196. }
  111197. /* Analysis side code, but directly related to blocking. Thus it's
  111198. here and not in analysis.c (which is for analysis transforms only).
  111199. The init is here because some of it is shared */
  111200. static int _vds_shared_init(vorbis_dsp_state *v,vorbis_info *vi,int encp){
  111201. int i;
  111202. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111203. private_state *b=NULL;
  111204. int hs;
  111205. if(ci==NULL) return 1;
  111206. hs=ci->halfrate_flag;
  111207. memset(v,0,sizeof(*v));
  111208. b=(private_state*) (v->backend_state=(private_state*)_ogg_calloc(1,sizeof(*b)));
  111209. v->vi=vi;
  111210. b->modebits=ilog2(ci->modes);
  111211. b->transform[0]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[0]));
  111212. b->transform[1]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[1]));
  111213. /* MDCT is tranform 0 */
  111214. b->transform[0][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  111215. b->transform[1][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  111216. mdct_init((mdct_lookup*)b->transform[0][0],ci->blocksizes[0]>>hs);
  111217. mdct_init((mdct_lookup*)b->transform[1][0],ci->blocksizes[1]>>hs);
  111218. /* Vorbis I uses only window type 0 */
  111219. b->window[0]=ilog2(ci->blocksizes[0])-6;
  111220. b->window[1]=ilog2(ci->blocksizes[1])-6;
  111221. if(encp){ /* encode/decode differ here */
  111222. /* analysis always needs an fft */
  111223. drft_init(&b->fft_look[0],ci->blocksizes[0]);
  111224. drft_init(&b->fft_look[1],ci->blocksizes[1]);
  111225. /* finish the codebooks */
  111226. if(!ci->fullbooks){
  111227. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  111228. for(i=0;i<ci->books;i++)
  111229. vorbis_book_init_encode(ci->fullbooks+i,ci->book_param[i]);
  111230. }
  111231. b->psy=(vorbis_look_psy*)_ogg_calloc(ci->psys,sizeof(*b->psy));
  111232. for(i=0;i<ci->psys;i++){
  111233. _vp_psy_init(b->psy+i,
  111234. ci->psy_param[i],
  111235. &ci->psy_g_param,
  111236. ci->blocksizes[ci->psy_param[i]->blockflag]/2,
  111237. vi->rate);
  111238. }
  111239. v->analysisp=1;
  111240. }else{
  111241. /* finish the codebooks */
  111242. if(!ci->fullbooks){
  111243. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  111244. for(i=0;i<ci->books;i++){
  111245. vorbis_book_init_decode(ci->fullbooks+i,ci->book_param[i]);
  111246. /* decode codebooks are now standalone after init */
  111247. vorbis_staticbook_destroy(ci->book_param[i]);
  111248. ci->book_param[i]=NULL;
  111249. }
  111250. }
  111251. }
  111252. /* initialize the storage vectors. blocksize[1] is small for encode,
  111253. but the correct size for decode */
  111254. v->pcm_storage=ci->blocksizes[1];
  111255. v->pcm=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcm));
  111256. v->pcmret=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcmret));
  111257. {
  111258. int i;
  111259. for(i=0;i<vi->channels;i++)
  111260. v->pcm[i]=(float*)_ogg_calloc(v->pcm_storage,sizeof(*v->pcm[i]));
  111261. }
  111262. /* all 1 (large block) or 0 (small block) */
  111263. /* explicitly set for the sake of clarity */
  111264. v->lW=0; /* previous window size */
  111265. v->W=0; /* current window size */
  111266. /* all vector indexes */
  111267. v->centerW=ci->blocksizes[1]/2;
  111268. v->pcm_current=v->centerW;
  111269. /* initialize all the backend lookups */
  111270. b->flr=(vorbis_look_floor**)_ogg_calloc(ci->floors,sizeof(*b->flr));
  111271. b->residue=(vorbis_look_residue**)_ogg_calloc(ci->residues,sizeof(*b->residue));
  111272. for(i=0;i<ci->floors;i++)
  111273. b->flr[i]=_floor_P[ci->floor_type[i]]->
  111274. look(v,ci->floor_param[i]);
  111275. for(i=0;i<ci->residues;i++)
  111276. b->residue[i]=_residue_P[ci->residue_type[i]]->
  111277. look(v,ci->residue_param[i]);
  111278. return 0;
  111279. }
  111280. /* arbitrary settings and spec-mandated numbers get filled in here */
  111281. int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi){
  111282. private_state *b=NULL;
  111283. if(_vds_shared_init(v,vi,1))return 1;
  111284. b=(private_state*)v->backend_state;
  111285. b->psy_g_look=_vp_global_look(vi);
  111286. /* Initialize the envelope state storage */
  111287. b->ve=(envelope_lookup*)_ogg_calloc(1,sizeof(*b->ve));
  111288. _ve_envelope_init(b->ve,vi);
  111289. vorbis_bitrate_init(vi,&b->bms);
  111290. /* compressed audio packets start after the headers
  111291. with sequence number 3 */
  111292. v->sequence=3;
  111293. return(0);
  111294. }
  111295. void vorbis_dsp_clear(vorbis_dsp_state *v){
  111296. int i;
  111297. if(v){
  111298. vorbis_info *vi=v->vi;
  111299. codec_setup_info *ci=(codec_setup_info*)(vi?vi->codec_setup:NULL);
  111300. private_state *b=(private_state*)v->backend_state;
  111301. if(b){
  111302. if(b->ve){
  111303. _ve_envelope_clear(b->ve);
  111304. _ogg_free(b->ve);
  111305. }
  111306. if(b->transform[0]){
  111307. mdct_clear((mdct_lookup*) b->transform[0][0]);
  111308. _ogg_free(b->transform[0][0]);
  111309. _ogg_free(b->transform[0]);
  111310. }
  111311. if(b->transform[1]){
  111312. mdct_clear((mdct_lookup*) b->transform[1][0]);
  111313. _ogg_free(b->transform[1][0]);
  111314. _ogg_free(b->transform[1]);
  111315. }
  111316. if(b->flr){
  111317. for(i=0;i<ci->floors;i++)
  111318. _floor_P[ci->floor_type[i]]->
  111319. free_look(b->flr[i]);
  111320. _ogg_free(b->flr);
  111321. }
  111322. if(b->residue){
  111323. for(i=0;i<ci->residues;i++)
  111324. _residue_P[ci->residue_type[i]]->
  111325. free_look(b->residue[i]);
  111326. _ogg_free(b->residue);
  111327. }
  111328. if(b->psy){
  111329. for(i=0;i<ci->psys;i++)
  111330. _vp_psy_clear(b->psy+i);
  111331. _ogg_free(b->psy);
  111332. }
  111333. if(b->psy_g_look)_vp_global_free(b->psy_g_look);
  111334. vorbis_bitrate_clear(&b->bms);
  111335. drft_clear(&b->fft_look[0]);
  111336. drft_clear(&b->fft_look[1]);
  111337. }
  111338. if(v->pcm){
  111339. for(i=0;i<vi->channels;i++)
  111340. if(v->pcm[i])_ogg_free(v->pcm[i]);
  111341. _ogg_free(v->pcm);
  111342. if(v->pcmret)_ogg_free(v->pcmret);
  111343. }
  111344. if(b){
  111345. /* free header, header1, header2 */
  111346. if(b->header)_ogg_free(b->header);
  111347. if(b->header1)_ogg_free(b->header1);
  111348. if(b->header2)_ogg_free(b->header2);
  111349. _ogg_free(b);
  111350. }
  111351. memset(v,0,sizeof(*v));
  111352. }
  111353. }
  111354. float **vorbis_analysis_buffer(vorbis_dsp_state *v, int vals){
  111355. int i;
  111356. vorbis_info *vi=v->vi;
  111357. private_state *b=(private_state*)v->backend_state;
  111358. /* free header, header1, header2 */
  111359. if(b->header)_ogg_free(b->header);b->header=NULL;
  111360. if(b->header1)_ogg_free(b->header1);b->header1=NULL;
  111361. if(b->header2)_ogg_free(b->header2);b->header2=NULL;
  111362. /* Do we have enough storage space for the requested buffer? If not,
  111363. expand the PCM (and envelope) storage */
  111364. if(v->pcm_current+vals>=v->pcm_storage){
  111365. v->pcm_storage=v->pcm_current+vals*2;
  111366. for(i=0;i<vi->channels;i++){
  111367. v->pcm[i]=(float*)_ogg_realloc(v->pcm[i],v->pcm_storage*sizeof(*v->pcm[i]));
  111368. }
  111369. }
  111370. for(i=0;i<vi->channels;i++)
  111371. v->pcmret[i]=v->pcm[i]+v->pcm_current;
  111372. return(v->pcmret);
  111373. }
  111374. static void _preextrapolate_helper(vorbis_dsp_state *v){
  111375. int i;
  111376. int order=32;
  111377. float *lpc=(float*)alloca(order*sizeof(*lpc));
  111378. float *work=(float*)alloca(v->pcm_current*sizeof(*work));
  111379. long j;
  111380. v->preextrapolate=1;
  111381. if(v->pcm_current-v->centerW>order*2){ /* safety */
  111382. for(i=0;i<v->vi->channels;i++){
  111383. /* need to run the extrapolation in reverse! */
  111384. for(j=0;j<v->pcm_current;j++)
  111385. work[j]=v->pcm[i][v->pcm_current-j-1];
  111386. /* prime as above */
  111387. vorbis_lpc_from_data(work,lpc,v->pcm_current-v->centerW,order);
  111388. /* run the predictor filter */
  111389. vorbis_lpc_predict(lpc,work+v->pcm_current-v->centerW-order,
  111390. order,
  111391. work+v->pcm_current-v->centerW,
  111392. v->centerW);
  111393. for(j=0;j<v->pcm_current;j++)
  111394. v->pcm[i][v->pcm_current-j-1]=work[j];
  111395. }
  111396. }
  111397. }
  111398. /* call with val<=0 to set eof */
  111399. int vorbis_analysis_wrote(vorbis_dsp_state *v, int vals){
  111400. vorbis_info *vi=v->vi;
  111401. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111402. if(vals<=0){
  111403. int order=32;
  111404. int i;
  111405. float *lpc=(float*) alloca(order*sizeof(*lpc));
  111406. /* if it wasn't done earlier (very short sample) */
  111407. if(!v->preextrapolate)
  111408. _preextrapolate_helper(v);
  111409. /* We're encoding the end of the stream. Just make sure we have
  111410. [at least] a few full blocks of zeroes at the end. */
  111411. /* actually, we don't want zeroes; that could drop a large
  111412. amplitude off a cliff, creating spread spectrum noise that will
  111413. suck to encode. Extrapolate for the sake of cleanliness. */
  111414. vorbis_analysis_buffer(v,ci->blocksizes[1]*3);
  111415. v->eofflag=v->pcm_current;
  111416. v->pcm_current+=ci->blocksizes[1]*3;
  111417. for(i=0;i<vi->channels;i++){
  111418. if(v->eofflag>order*2){
  111419. /* extrapolate with LPC to fill in */
  111420. long n;
  111421. /* make a predictor filter */
  111422. n=v->eofflag;
  111423. if(n>ci->blocksizes[1])n=ci->blocksizes[1];
  111424. vorbis_lpc_from_data(v->pcm[i]+v->eofflag-n,lpc,n,order);
  111425. /* run the predictor filter */
  111426. vorbis_lpc_predict(lpc,v->pcm[i]+v->eofflag-order,order,
  111427. v->pcm[i]+v->eofflag,v->pcm_current-v->eofflag);
  111428. }else{
  111429. /* not enough data to extrapolate (unlikely to happen due to
  111430. guarding the overlap, but bulletproof in case that
  111431. assumtion goes away). zeroes will do. */
  111432. memset(v->pcm[i]+v->eofflag,0,
  111433. (v->pcm_current-v->eofflag)*sizeof(*v->pcm[i]));
  111434. }
  111435. }
  111436. }else{
  111437. if(v->pcm_current+vals>v->pcm_storage)
  111438. return(OV_EINVAL);
  111439. v->pcm_current+=vals;
  111440. /* we may want to reverse extrapolate the beginning of a stream
  111441. too... in case we're beginning on a cliff! */
  111442. /* clumsy, but simple. It only runs once, so simple is good. */
  111443. if(!v->preextrapolate && v->pcm_current-v->centerW>ci->blocksizes[1])
  111444. _preextrapolate_helper(v);
  111445. }
  111446. return(0);
  111447. }
  111448. /* do the deltas, envelope shaping, pre-echo and determine the size of
  111449. the next block on which to continue analysis */
  111450. int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb){
  111451. int i;
  111452. vorbis_info *vi=v->vi;
  111453. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111454. private_state *b=(private_state*)v->backend_state;
  111455. vorbis_look_psy_global *g=b->psy_g_look;
  111456. long beginW=v->centerW-ci->blocksizes[v->W]/2,centerNext;
  111457. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  111458. /* check to see if we're started... */
  111459. if(!v->preextrapolate)return(0);
  111460. /* check to see if we're done... */
  111461. if(v->eofflag==-1)return(0);
  111462. /* By our invariant, we have lW, W and centerW set. Search for
  111463. the next boundary so we can determine nW (the next window size)
  111464. which lets us compute the shape of the current block's window */
  111465. /* we do an envelope search even on a single blocksize; we may still
  111466. be throwing more bits at impulses, and envelope search handles
  111467. marking impulses too. */
  111468. {
  111469. long bp=_ve_envelope_search(v);
  111470. if(bp==-1){
  111471. if(v->eofflag==0)return(0); /* not enough data currently to search for a
  111472. full long block */
  111473. v->nW=0;
  111474. }else{
  111475. if(ci->blocksizes[0]==ci->blocksizes[1])
  111476. v->nW=0;
  111477. else
  111478. v->nW=bp;
  111479. }
  111480. }
  111481. centerNext=v->centerW+ci->blocksizes[v->W]/4+ci->blocksizes[v->nW]/4;
  111482. {
  111483. /* center of next block + next block maximum right side. */
  111484. long blockbound=centerNext+ci->blocksizes[v->nW]/2;
  111485. if(v->pcm_current<blockbound)return(0); /* not enough data yet;
  111486. although this check is
  111487. less strict that the
  111488. _ve_envelope_search,
  111489. the search is not run
  111490. if we only use one
  111491. block size */
  111492. }
  111493. /* fill in the block. Note that for a short window, lW and nW are *short*
  111494. regardless of actual settings in the stream */
  111495. _vorbis_block_ripcord(vb);
  111496. vb->lW=v->lW;
  111497. vb->W=v->W;
  111498. vb->nW=v->nW;
  111499. if(v->W){
  111500. if(!v->lW || !v->nW){
  111501. vbi->blocktype=BLOCKTYPE_TRANSITION;
  111502. /*fprintf(stderr,"-");*/
  111503. }else{
  111504. vbi->blocktype=BLOCKTYPE_LONG;
  111505. /*fprintf(stderr,"_");*/
  111506. }
  111507. }else{
  111508. if(_ve_envelope_mark(v)){
  111509. vbi->blocktype=BLOCKTYPE_IMPULSE;
  111510. /*fprintf(stderr,"|");*/
  111511. }else{
  111512. vbi->blocktype=BLOCKTYPE_PADDING;
  111513. /*fprintf(stderr,".");*/
  111514. }
  111515. }
  111516. vb->vd=v;
  111517. vb->sequence=v->sequence++;
  111518. vb->granulepos=v->granulepos;
  111519. vb->pcmend=ci->blocksizes[v->W];
  111520. /* copy the vectors; this uses the local storage in vb */
  111521. /* this tracks 'strongest peak' for later psychoacoustics */
  111522. /* moved to the global psy state; clean this mess up */
  111523. if(vbi->ampmax>g->ampmax)g->ampmax=vbi->ampmax;
  111524. g->ampmax=_vp_ampmax_decay(g->ampmax,v);
  111525. vbi->ampmax=g->ampmax;
  111526. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  111527. vbi->pcmdelay=(float**)_vorbis_block_alloc(vb,sizeof(*vbi->pcmdelay)*vi->channels);
  111528. for(i=0;i<vi->channels;i++){
  111529. vbi->pcmdelay[i]=
  111530. (float*) _vorbis_block_alloc(vb,(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  111531. memcpy(vbi->pcmdelay[i],v->pcm[i],(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  111532. vb->pcm[i]=vbi->pcmdelay[i]+beginW;
  111533. /* before we added the delay
  111534. vb->pcm[i]=_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  111535. memcpy(vb->pcm[i],v->pcm[i]+beginW,ci->blocksizes[v->W]*sizeof(*vb->pcm[i]));
  111536. */
  111537. }
  111538. /* handle eof detection: eof==0 means that we've not yet received EOF
  111539. eof>0 marks the last 'real' sample in pcm[]
  111540. eof<0 'no more to do'; doesn't get here */
  111541. if(v->eofflag){
  111542. if(v->centerW>=v->eofflag){
  111543. v->eofflag=-1;
  111544. vb->eofflag=1;
  111545. return(1);
  111546. }
  111547. }
  111548. /* advance storage vectors and clean up */
  111549. {
  111550. int new_centerNext=ci->blocksizes[1]/2;
  111551. int movementW=centerNext-new_centerNext;
  111552. if(movementW>0){
  111553. _ve_envelope_shift(b->ve,movementW);
  111554. v->pcm_current-=movementW;
  111555. for(i=0;i<vi->channels;i++)
  111556. memmove(v->pcm[i],v->pcm[i]+movementW,
  111557. v->pcm_current*sizeof(*v->pcm[i]));
  111558. v->lW=v->W;
  111559. v->W=v->nW;
  111560. v->centerW=new_centerNext;
  111561. if(v->eofflag){
  111562. v->eofflag-=movementW;
  111563. if(v->eofflag<=0)v->eofflag=-1;
  111564. /* do not add padding to end of stream! */
  111565. if(v->centerW>=v->eofflag){
  111566. v->granulepos+=movementW-(v->centerW-v->eofflag);
  111567. }else{
  111568. v->granulepos+=movementW;
  111569. }
  111570. }else{
  111571. v->granulepos+=movementW;
  111572. }
  111573. }
  111574. }
  111575. /* done */
  111576. return(1);
  111577. }
  111578. int vorbis_synthesis_restart(vorbis_dsp_state *v){
  111579. vorbis_info *vi=v->vi;
  111580. codec_setup_info *ci;
  111581. int hs;
  111582. if(!v->backend_state)return -1;
  111583. if(!vi)return -1;
  111584. ci=(codec_setup_info*) vi->codec_setup;
  111585. if(!ci)return -1;
  111586. hs=ci->halfrate_flag;
  111587. v->centerW=ci->blocksizes[1]>>(hs+1);
  111588. v->pcm_current=v->centerW>>hs;
  111589. v->pcm_returned=-1;
  111590. v->granulepos=-1;
  111591. v->sequence=-1;
  111592. v->eofflag=0;
  111593. ((private_state *)(v->backend_state))->sample_count=-1;
  111594. return(0);
  111595. }
  111596. int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi){
  111597. if(_vds_shared_init(v,vi,0)) return 1;
  111598. vorbis_synthesis_restart(v);
  111599. return 0;
  111600. }
  111601. /* Unlike in analysis, the window is only partially applied for each
  111602. block. The time domain envelope is not yet handled at the point of
  111603. calling (as it relies on the previous block). */
  111604. int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb){
  111605. vorbis_info *vi=v->vi;
  111606. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111607. private_state *b=(private_state*)v->backend_state;
  111608. int hs=ci->halfrate_flag;
  111609. int i,j;
  111610. if(!vb)return(OV_EINVAL);
  111611. if(v->pcm_current>v->pcm_returned && v->pcm_returned!=-1)return(OV_EINVAL);
  111612. v->lW=v->W;
  111613. v->W=vb->W;
  111614. v->nW=-1;
  111615. if((v->sequence==-1)||
  111616. (v->sequence+1 != vb->sequence)){
  111617. v->granulepos=-1; /* out of sequence; lose count */
  111618. b->sample_count=-1;
  111619. }
  111620. v->sequence=vb->sequence;
  111621. if(vb->pcm){ /* no pcm to process if vorbis_synthesis_trackonly
  111622. was called on block */
  111623. int n=ci->blocksizes[v->W]>>(hs+1);
  111624. int n0=ci->blocksizes[0]>>(hs+1);
  111625. int n1=ci->blocksizes[1]>>(hs+1);
  111626. int thisCenter;
  111627. int prevCenter;
  111628. v->glue_bits+=vb->glue_bits;
  111629. v->time_bits+=vb->time_bits;
  111630. v->floor_bits+=vb->floor_bits;
  111631. v->res_bits+=vb->res_bits;
  111632. if(v->centerW){
  111633. thisCenter=n1;
  111634. prevCenter=0;
  111635. }else{
  111636. thisCenter=0;
  111637. prevCenter=n1;
  111638. }
  111639. /* v->pcm is now used like a two-stage double buffer. We don't want
  111640. to have to constantly shift *or* adjust memory usage. Don't
  111641. accept a new block until the old is shifted out */
  111642. for(j=0;j<vi->channels;j++){
  111643. /* the overlap/add section */
  111644. if(v->lW){
  111645. if(v->W){
  111646. /* large/large */
  111647. float *w=_vorbis_window_get(b->window[1]-hs);
  111648. float *pcm=v->pcm[j]+prevCenter;
  111649. float *p=vb->pcm[j];
  111650. for(i=0;i<n1;i++)
  111651. pcm[i]=pcm[i]*w[n1-i-1] + p[i]*w[i];
  111652. }else{
  111653. /* large/small */
  111654. float *w=_vorbis_window_get(b->window[0]-hs);
  111655. float *pcm=v->pcm[j]+prevCenter+n1/2-n0/2;
  111656. float *p=vb->pcm[j];
  111657. for(i=0;i<n0;i++)
  111658. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111659. }
  111660. }else{
  111661. if(v->W){
  111662. /* small/large */
  111663. float *w=_vorbis_window_get(b->window[0]-hs);
  111664. float *pcm=v->pcm[j]+prevCenter;
  111665. float *p=vb->pcm[j]+n1/2-n0/2;
  111666. for(i=0;i<n0;i++)
  111667. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111668. for(;i<n1/2+n0/2;i++)
  111669. pcm[i]=p[i];
  111670. }else{
  111671. /* small/small */
  111672. float *w=_vorbis_window_get(b->window[0]-hs);
  111673. float *pcm=v->pcm[j]+prevCenter;
  111674. float *p=vb->pcm[j];
  111675. for(i=0;i<n0;i++)
  111676. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111677. }
  111678. }
  111679. /* the copy section */
  111680. {
  111681. float *pcm=v->pcm[j]+thisCenter;
  111682. float *p=vb->pcm[j]+n;
  111683. for(i=0;i<n;i++)
  111684. pcm[i]=p[i];
  111685. }
  111686. }
  111687. if(v->centerW)
  111688. v->centerW=0;
  111689. else
  111690. v->centerW=n1;
  111691. /* deal with initial packet state; we do this using the explicit
  111692. pcm_returned==-1 flag otherwise we're sensitive to first block
  111693. being short or long */
  111694. if(v->pcm_returned==-1){
  111695. v->pcm_returned=thisCenter;
  111696. v->pcm_current=thisCenter;
  111697. }else{
  111698. v->pcm_returned=prevCenter;
  111699. v->pcm_current=prevCenter+
  111700. ((ci->blocksizes[v->lW]/4+
  111701. ci->blocksizes[v->W]/4)>>hs);
  111702. }
  111703. }
  111704. /* track the frame number... This is for convenience, but also
  111705. making sure our last packet doesn't end with added padding. If
  111706. the last packet is partial, the number of samples we'll have to
  111707. return will be past the vb->granulepos.
  111708. This is not foolproof! It will be confused if we begin
  111709. decoding at the last page after a seek or hole. In that case,
  111710. we don't have a starting point to judge where the last frame
  111711. is. For this reason, vorbisfile will always try to make sure
  111712. it reads the last two marked pages in proper sequence */
  111713. if(b->sample_count==-1){
  111714. b->sample_count=0;
  111715. }else{
  111716. b->sample_count+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  111717. }
  111718. if(v->granulepos==-1){
  111719. if(vb->granulepos!=-1){ /* only set if we have a position to set to */
  111720. v->granulepos=vb->granulepos;
  111721. /* is this a short page? */
  111722. if(b->sample_count>v->granulepos){
  111723. /* corner case; if this is both the first and last audio page,
  111724. then spec says the end is cut, not beginning */
  111725. if(vb->eofflag){
  111726. /* trim the end */
  111727. /* no preceeding granulepos; assume we started at zero (we'd
  111728. have to in a short single-page stream) */
  111729. /* granulepos could be -1 due to a seek, but that would result
  111730. in a long count, not short count */
  111731. v->pcm_current-=(b->sample_count-v->granulepos)>>hs;
  111732. }else{
  111733. /* trim the beginning */
  111734. v->pcm_returned+=(b->sample_count-v->granulepos)>>hs;
  111735. if(v->pcm_returned>v->pcm_current)
  111736. v->pcm_returned=v->pcm_current;
  111737. }
  111738. }
  111739. }
  111740. }else{
  111741. v->granulepos+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  111742. if(vb->granulepos!=-1 && v->granulepos!=vb->granulepos){
  111743. if(v->granulepos>vb->granulepos){
  111744. long extra=v->granulepos-vb->granulepos;
  111745. if(extra)
  111746. if(vb->eofflag){
  111747. /* partial last frame. Strip the extra samples off */
  111748. v->pcm_current-=extra>>hs;
  111749. } /* else {Shouldn't happen *unless* the bitstream is out of
  111750. spec. Either way, believe the bitstream } */
  111751. } /* else {Shouldn't happen *unless* the bitstream is out of
  111752. spec. Either way, believe the bitstream } */
  111753. v->granulepos=vb->granulepos;
  111754. }
  111755. }
  111756. /* Update, cleanup */
  111757. if(vb->eofflag)v->eofflag=1;
  111758. return(0);
  111759. }
  111760. /* pcm==NULL indicates we just want the pending samples, no more */
  111761. int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm){
  111762. vorbis_info *vi=v->vi;
  111763. if(v->pcm_returned>-1 && v->pcm_returned<v->pcm_current){
  111764. if(pcm){
  111765. int i;
  111766. for(i=0;i<vi->channels;i++)
  111767. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  111768. *pcm=v->pcmret;
  111769. }
  111770. return(v->pcm_current-v->pcm_returned);
  111771. }
  111772. return(0);
  111773. }
  111774. int vorbis_synthesis_read(vorbis_dsp_state *v,int n){
  111775. if(n && v->pcm_returned+n>v->pcm_current)return(OV_EINVAL);
  111776. v->pcm_returned+=n;
  111777. return(0);
  111778. }
  111779. /* intended for use with a specific vorbisfile feature; we want access
  111780. to the [usually synthetic/postextrapolated] buffer and lapping at
  111781. the end of a decode cycle, specifically, a half-short-block worth.
  111782. This funtion works like pcmout above, except it will also expose
  111783. this implicit buffer data not normally decoded. */
  111784. int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm){
  111785. vorbis_info *vi=v->vi;
  111786. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  111787. int hs=ci->halfrate_flag;
  111788. int n=ci->blocksizes[v->W]>>(hs+1);
  111789. int n0=ci->blocksizes[0]>>(hs+1);
  111790. int n1=ci->blocksizes[1]>>(hs+1);
  111791. int i,j;
  111792. if(v->pcm_returned<0)return 0;
  111793. /* our returned data ends at pcm_returned; because the synthesis pcm
  111794. buffer is a two-fragment ring, that means our data block may be
  111795. fragmented by buffering, wrapping or a short block not filling
  111796. out a buffer. To simplify things, we unfragment if it's at all
  111797. possibly needed. Otherwise, we'd need to call lapout more than
  111798. once as well as hold additional dsp state. Opt for
  111799. simplicity. */
  111800. /* centerW was advanced by blockin; it would be the center of the
  111801. *next* block */
  111802. if(v->centerW==n1){
  111803. /* the data buffer wraps; swap the halves */
  111804. /* slow, sure, small */
  111805. for(j=0;j<vi->channels;j++){
  111806. float *p=v->pcm[j];
  111807. for(i=0;i<n1;i++){
  111808. float temp=p[i];
  111809. p[i]=p[i+n1];
  111810. p[i+n1]=temp;
  111811. }
  111812. }
  111813. v->pcm_current-=n1;
  111814. v->pcm_returned-=n1;
  111815. v->centerW=0;
  111816. }
  111817. /* solidify buffer into contiguous space */
  111818. if((v->lW^v->W)==1){
  111819. /* long/short or short/long */
  111820. for(j=0;j<vi->channels;j++){
  111821. float *s=v->pcm[j];
  111822. float *d=v->pcm[j]+(n1-n0)/2;
  111823. for(i=(n1+n0)/2-1;i>=0;--i)
  111824. d[i]=s[i];
  111825. }
  111826. v->pcm_returned+=(n1-n0)/2;
  111827. v->pcm_current+=(n1-n0)/2;
  111828. }else{
  111829. if(v->lW==0){
  111830. /* short/short */
  111831. for(j=0;j<vi->channels;j++){
  111832. float *s=v->pcm[j];
  111833. float *d=v->pcm[j]+n1-n0;
  111834. for(i=n0-1;i>=0;--i)
  111835. d[i]=s[i];
  111836. }
  111837. v->pcm_returned+=n1-n0;
  111838. v->pcm_current+=n1-n0;
  111839. }
  111840. }
  111841. if(pcm){
  111842. int i;
  111843. for(i=0;i<vi->channels;i++)
  111844. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  111845. *pcm=v->pcmret;
  111846. }
  111847. return(n1+n-v->pcm_returned);
  111848. }
  111849. float *vorbis_window(vorbis_dsp_state *v,int W){
  111850. vorbis_info *vi=v->vi;
  111851. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  111852. int hs=ci->halfrate_flag;
  111853. private_state *b=(private_state*)v->backend_state;
  111854. if(b->window[W]-1<0)return NULL;
  111855. return _vorbis_window_get(b->window[W]-hs);
  111856. }
  111857. #endif
  111858. /*** End of inlined file: block.c ***/
  111859. /*** Start of inlined file: codebook.c ***/
  111860. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111861. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111862. // tasks..
  111863. #if JUCE_MSVC
  111864. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111865. #endif
  111866. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111867. #if JUCE_USE_OGGVORBIS
  111868. #include <stdlib.h>
  111869. #include <string.h>
  111870. #include <math.h>
  111871. /* packs the given codebook into the bitstream **************************/
  111872. int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *opb){
  111873. long i,j;
  111874. int ordered=0;
  111875. /* first the basic parameters */
  111876. oggpack_write(opb,0x564342,24);
  111877. oggpack_write(opb,c->dim,16);
  111878. oggpack_write(opb,c->entries,24);
  111879. /* pack the codewords. There are two packings; length ordered and
  111880. length random. Decide between the two now. */
  111881. for(i=1;i<c->entries;i++)
  111882. if(c->lengthlist[i-1]==0 || c->lengthlist[i]<c->lengthlist[i-1])break;
  111883. if(i==c->entries)ordered=1;
  111884. if(ordered){
  111885. /* length ordered. We only need to say how many codewords of
  111886. each length. The actual codewords are generated
  111887. deterministically */
  111888. long count=0;
  111889. oggpack_write(opb,1,1); /* ordered */
  111890. oggpack_write(opb,c->lengthlist[0]-1,5); /* 1 to 32 */
  111891. for(i=1;i<c->entries;i++){
  111892. long thisx=c->lengthlist[i];
  111893. long last=c->lengthlist[i-1];
  111894. if(thisx>last){
  111895. for(j=last;j<thisx;j++){
  111896. oggpack_write(opb,i-count,_ilog(c->entries-count));
  111897. count=i;
  111898. }
  111899. }
  111900. }
  111901. oggpack_write(opb,i-count,_ilog(c->entries-count));
  111902. }else{
  111903. /* length random. Again, we don't code the codeword itself, just
  111904. the length. This time, though, we have to encode each length */
  111905. oggpack_write(opb,0,1); /* unordered */
  111906. /* algortihmic mapping has use for 'unused entries', which we tag
  111907. here. The algorithmic mapping happens as usual, but the unused
  111908. entry has no codeword. */
  111909. for(i=0;i<c->entries;i++)
  111910. if(c->lengthlist[i]==0)break;
  111911. if(i==c->entries){
  111912. oggpack_write(opb,0,1); /* no unused entries */
  111913. for(i=0;i<c->entries;i++)
  111914. oggpack_write(opb,c->lengthlist[i]-1,5);
  111915. }else{
  111916. oggpack_write(opb,1,1); /* we have unused entries; thus we tag */
  111917. for(i=0;i<c->entries;i++){
  111918. if(c->lengthlist[i]==0){
  111919. oggpack_write(opb,0,1);
  111920. }else{
  111921. oggpack_write(opb,1,1);
  111922. oggpack_write(opb,c->lengthlist[i]-1,5);
  111923. }
  111924. }
  111925. }
  111926. }
  111927. /* is the entry number the desired return value, or do we have a
  111928. mapping? If we have a mapping, what type? */
  111929. oggpack_write(opb,c->maptype,4);
  111930. switch(c->maptype){
  111931. case 0:
  111932. /* no mapping */
  111933. break;
  111934. case 1:case 2:
  111935. /* implicitly populated value mapping */
  111936. /* explicitly populated value mapping */
  111937. if(!c->quantlist){
  111938. /* no quantlist? error */
  111939. return(-1);
  111940. }
  111941. /* values that define the dequantization */
  111942. oggpack_write(opb,c->q_min,32);
  111943. oggpack_write(opb,c->q_delta,32);
  111944. oggpack_write(opb,c->q_quant-1,4);
  111945. oggpack_write(opb,c->q_sequencep,1);
  111946. {
  111947. int quantvals;
  111948. switch(c->maptype){
  111949. case 1:
  111950. /* a single column of (c->entries/c->dim) quantized values for
  111951. building a full value list algorithmically (square lattice) */
  111952. quantvals=_book_maptype1_quantvals(c);
  111953. break;
  111954. case 2:
  111955. /* every value (c->entries*c->dim total) specified explicitly */
  111956. quantvals=c->entries*c->dim;
  111957. break;
  111958. default: /* NOT_REACHABLE */
  111959. quantvals=-1;
  111960. }
  111961. /* quantized values */
  111962. for(i=0;i<quantvals;i++)
  111963. oggpack_write(opb,labs(c->quantlist[i]),c->q_quant);
  111964. }
  111965. break;
  111966. default:
  111967. /* error case; we don't have any other map types now */
  111968. return(-1);
  111969. }
  111970. return(0);
  111971. }
  111972. /* unpacks a codebook from the packet buffer into the codebook struct,
  111973. readies the codebook auxiliary structures for decode *************/
  111974. int vorbis_staticbook_unpack(oggpack_buffer *opb,static_codebook *s){
  111975. long i,j;
  111976. memset(s,0,sizeof(*s));
  111977. s->allocedp=1;
  111978. /* make sure alignment is correct */
  111979. if(oggpack_read(opb,24)!=0x564342)goto _eofout;
  111980. /* first the basic parameters */
  111981. s->dim=oggpack_read(opb,16);
  111982. s->entries=oggpack_read(opb,24);
  111983. if(s->entries==-1)goto _eofout;
  111984. /* codeword ordering.... length ordered or unordered? */
  111985. switch((int)oggpack_read(opb,1)){
  111986. case 0:
  111987. /* unordered */
  111988. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  111989. /* allocated but unused entries? */
  111990. if(oggpack_read(opb,1)){
  111991. /* yes, unused entries */
  111992. for(i=0;i<s->entries;i++){
  111993. if(oggpack_read(opb,1)){
  111994. long num=oggpack_read(opb,5);
  111995. if(num==-1)goto _eofout;
  111996. s->lengthlist[i]=num+1;
  111997. }else
  111998. s->lengthlist[i]=0;
  111999. }
  112000. }else{
  112001. /* all entries used; no tagging */
  112002. for(i=0;i<s->entries;i++){
  112003. long num=oggpack_read(opb,5);
  112004. if(num==-1)goto _eofout;
  112005. s->lengthlist[i]=num+1;
  112006. }
  112007. }
  112008. break;
  112009. case 1:
  112010. /* ordered */
  112011. {
  112012. long length=oggpack_read(opb,5)+1;
  112013. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  112014. for(i=0;i<s->entries;){
  112015. long num=oggpack_read(opb,_ilog(s->entries-i));
  112016. if(num==-1)goto _eofout;
  112017. for(j=0;j<num && i<s->entries;j++,i++)
  112018. s->lengthlist[i]=length;
  112019. length++;
  112020. }
  112021. }
  112022. break;
  112023. default:
  112024. /* EOF */
  112025. return(-1);
  112026. }
  112027. /* Do we have a mapping to unpack? */
  112028. switch((s->maptype=oggpack_read(opb,4))){
  112029. case 0:
  112030. /* no mapping */
  112031. break;
  112032. case 1: case 2:
  112033. /* implicitly populated value mapping */
  112034. /* explicitly populated value mapping */
  112035. s->q_min=oggpack_read(opb,32);
  112036. s->q_delta=oggpack_read(opb,32);
  112037. s->q_quant=oggpack_read(opb,4)+1;
  112038. s->q_sequencep=oggpack_read(opb,1);
  112039. {
  112040. int quantvals=0;
  112041. switch(s->maptype){
  112042. case 1:
  112043. quantvals=_book_maptype1_quantvals(s);
  112044. break;
  112045. case 2:
  112046. quantvals=s->entries*s->dim;
  112047. break;
  112048. }
  112049. /* quantized values */
  112050. s->quantlist=(long*)_ogg_malloc(sizeof(*s->quantlist)*quantvals);
  112051. for(i=0;i<quantvals;i++)
  112052. s->quantlist[i]=oggpack_read(opb,s->q_quant);
  112053. if(quantvals&&s->quantlist[quantvals-1]==-1)goto _eofout;
  112054. }
  112055. break;
  112056. default:
  112057. goto _errout;
  112058. }
  112059. /* all set */
  112060. return(0);
  112061. _errout:
  112062. _eofout:
  112063. vorbis_staticbook_clear(s);
  112064. return(-1);
  112065. }
  112066. /* returns the number of bits ************************************************/
  112067. int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b){
  112068. oggpack_write(b,book->codelist[a],book->c->lengthlist[a]);
  112069. return(book->c->lengthlist[a]);
  112070. }
  112071. /* One the encode side, our vector writers are each designed for a
  112072. specific purpose, and the encoder is not flexible without modification:
  112073. The LSP vector coder uses a single stage nearest-match with no
  112074. interleave, so no step and no error return. This is specced by floor0
  112075. and doesn't change.
  112076. Residue0 encoding interleaves, uses multiple stages, and each stage
  112077. peels of a specific amount of resolution from a lattice (thus we want
  112078. to match by threshold, not nearest match). Residue doesn't *have* to
  112079. be encoded that way, but to change it, one will need to add more
  112080. infrastructure on the encode side (decode side is specced and simpler) */
  112081. /* floor0 LSP (single stage, non interleaved, nearest match) */
  112082. /* returns entry number and *modifies a* to the quantization value *****/
  112083. int vorbis_book_errorv(codebook *book,float *a){
  112084. int dim=book->dim,k;
  112085. int best=_best(book,a,1);
  112086. for(k=0;k<dim;k++)
  112087. a[k]=(book->valuelist+best*dim)[k];
  112088. return(best);
  112089. }
  112090. /* returns the number of bits and *modifies a* to the quantization value *****/
  112091. int vorbis_book_encodev(codebook *book,int best,float *a,oggpack_buffer *b){
  112092. int k,dim=book->dim;
  112093. for(k=0;k<dim;k++)
  112094. a[k]=(book->valuelist+best*dim)[k];
  112095. return(vorbis_book_encode(book,best,b));
  112096. }
  112097. /* the 'eliminate the decode tree' optimization actually requires the
  112098. codewords to be MSb first, not LSb. This is an annoying inelegancy
  112099. (and one of the first places where carefully thought out design
  112100. turned out to be wrong; Vorbis II and future Ogg codecs should go
  112101. to an MSb bitpacker), but not actually the huge hit it appears to
  112102. be. The first-stage decode table catches most words so that
  112103. bitreverse is not in the main execution path. */
  112104. STIN long decode_packed_entry_number(codebook *book, oggpack_buffer *b){
  112105. int read=book->dec_maxlength;
  112106. long lo,hi;
  112107. long lok = oggpack_look(b,book->dec_firsttablen);
  112108. if (lok >= 0) {
  112109. long entry = book->dec_firsttable[lok];
  112110. if(entry&0x80000000UL){
  112111. lo=(entry>>15)&0x7fff;
  112112. hi=book->used_entries-(entry&0x7fff);
  112113. }else{
  112114. oggpack_adv(b, book->dec_codelengths[entry-1]);
  112115. return(entry-1);
  112116. }
  112117. }else{
  112118. lo=0;
  112119. hi=book->used_entries;
  112120. }
  112121. lok = oggpack_look(b, read);
  112122. while(lok<0 && read>1)
  112123. lok = oggpack_look(b, --read);
  112124. if(lok<0)return -1;
  112125. /* bisect search for the codeword in the ordered list */
  112126. {
  112127. ogg_uint32_t testword=ogg_bitreverse((ogg_uint32_t)lok);
  112128. while(hi-lo>1){
  112129. long p=(hi-lo)>>1;
  112130. long test=book->codelist[lo+p]>testword;
  112131. lo+=p&(test-1);
  112132. hi-=p&(-test);
  112133. }
  112134. if(book->dec_codelengths[lo]<=read){
  112135. oggpack_adv(b, book->dec_codelengths[lo]);
  112136. return(lo);
  112137. }
  112138. }
  112139. oggpack_adv(b, read);
  112140. return(-1);
  112141. }
  112142. /* Decode side is specced and easier, because we don't need to find
  112143. matches using different criteria; we simply read and map. There are
  112144. two things we need to do 'depending':
  112145. We may need to support interleave. We don't really, but it's
  112146. convenient to do it here rather than rebuild the vector later.
  112147. Cascades may be additive or multiplicitive; this is not inherent in
  112148. the codebook, but set in the code using the codebook. Like
  112149. interleaving, it's easiest to do it here.
  112150. addmul==0 -> declarative (set the value)
  112151. addmul==1 -> additive
  112152. addmul==2 -> multiplicitive */
  112153. /* returns the [original, not compacted] entry number or -1 on eof *********/
  112154. long vorbis_book_decode(codebook *book, oggpack_buffer *b){
  112155. long packed_entry=decode_packed_entry_number(book,b);
  112156. if(packed_entry>=0)
  112157. return(book->dec_index[packed_entry]);
  112158. /* if there's no dec_index, the codebook unpacking isn't collapsed */
  112159. return(packed_entry);
  112160. }
  112161. /* returns 0 on OK or -1 on eof *************************************/
  112162. long vorbis_book_decodevs_add(codebook *book,float *a,oggpack_buffer *b,int n){
  112163. int step=n/book->dim;
  112164. long *entry = (long*)alloca(sizeof(*entry)*step);
  112165. float **t = (float**)alloca(sizeof(*t)*step);
  112166. int i,j,o;
  112167. for (i = 0; i < step; i++) {
  112168. entry[i]=decode_packed_entry_number(book,b);
  112169. if(entry[i]==-1)return(-1);
  112170. t[i] = book->valuelist+entry[i]*book->dim;
  112171. }
  112172. for(i=0,o=0;i<book->dim;i++,o+=step)
  112173. for (j=0;j<step;j++)
  112174. a[o+j]+=t[j][i];
  112175. return(0);
  112176. }
  112177. long vorbis_book_decodev_add(codebook *book,float *a,oggpack_buffer *b,int n){
  112178. int i,j,entry;
  112179. float *t;
  112180. if(book->dim>8){
  112181. for(i=0;i<n;){
  112182. entry = decode_packed_entry_number(book,b);
  112183. if(entry==-1)return(-1);
  112184. t = book->valuelist+entry*book->dim;
  112185. for (j=0;j<book->dim;)
  112186. a[i++]+=t[j++];
  112187. }
  112188. }else{
  112189. for(i=0;i<n;){
  112190. entry = decode_packed_entry_number(book,b);
  112191. if(entry==-1)return(-1);
  112192. t = book->valuelist+entry*book->dim;
  112193. j=0;
  112194. switch((int)book->dim){
  112195. case 8:
  112196. a[i++]+=t[j++];
  112197. case 7:
  112198. a[i++]+=t[j++];
  112199. case 6:
  112200. a[i++]+=t[j++];
  112201. case 5:
  112202. a[i++]+=t[j++];
  112203. case 4:
  112204. a[i++]+=t[j++];
  112205. case 3:
  112206. a[i++]+=t[j++];
  112207. case 2:
  112208. a[i++]+=t[j++];
  112209. case 1:
  112210. a[i++]+=t[j++];
  112211. case 0:
  112212. break;
  112213. }
  112214. }
  112215. }
  112216. return(0);
  112217. }
  112218. long vorbis_book_decodev_set(codebook *book,float *a,oggpack_buffer *b,int n){
  112219. int i,j,entry;
  112220. float *t;
  112221. for(i=0;i<n;){
  112222. entry = decode_packed_entry_number(book,b);
  112223. if(entry==-1)return(-1);
  112224. t = book->valuelist+entry*book->dim;
  112225. for (j=0;j<book->dim;)
  112226. a[i++]=t[j++];
  112227. }
  112228. return(0);
  112229. }
  112230. long vorbis_book_decodevv_add(codebook *book,float **a,long offset,int ch,
  112231. oggpack_buffer *b,int n){
  112232. long i,j,entry;
  112233. int chptr=0;
  112234. for(i=offset/ch;i<(offset+n)/ch;){
  112235. entry = decode_packed_entry_number(book,b);
  112236. if(entry==-1)return(-1);
  112237. {
  112238. const float *t = book->valuelist+entry*book->dim;
  112239. for (j=0;j<book->dim;j++){
  112240. a[chptr++][i]+=t[j];
  112241. if(chptr==ch){
  112242. chptr=0;
  112243. i++;
  112244. }
  112245. }
  112246. }
  112247. }
  112248. return(0);
  112249. }
  112250. #ifdef _V_SELFTEST
  112251. /* Simple enough; pack a few candidate codebooks, unpack them. Code a
  112252. number of vectors through (keeping track of the quantized values),
  112253. and decode using the unpacked book. quantized version of in should
  112254. exactly equal out */
  112255. #include <stdio.h>
  112256. #include "vorbis/book/lsp20_0.vqh"
  112257. #include "vorbis/book/res0a_13.vqh"
  112258. #define TESTSIZE 40
  112259. float test1[TESTSIZE]={
  112260. 0.105939f,
  112261. 0.215373f,
  112262. 0.429117f,
  112263. 0.587974f,
  112264. 0.181173f,
  112265. 0.296583f,
  112266. 0.515707f,
  112267. 0.715261f,
  112268. 0.162327f,
  112269. 0.263834f,
  112270. 0.342876f,
  112271. 0.406025f,
  112272. 0.103571f,
  112273. 0.223561f,
  112274. 0.368513f,
  112275. 0.540313f,
  112276. 0.136672f,
  112277. 0.395882f,
  112278. 0.587183f,
  112279. 0.652476f,
  112280. 0.114338f,
  112281. 0.417300f,
  112282. 0.525486f,
  112283. 0.698679f,
  112284. 0.147492f,
  112285. 0.324481f,
  112286. 0.643089f,
  112287. 0.757582f,
  112288. 0.139556f,
  112289. 0.215795f,
  112290. 0.324559f,
  112291. 0.399387f,
  112292. 0.120236f,
  112293. 0.267420f,
  112294. 0.446940f,
  112295. 0.608760f,
  112296. 0.115587f,
  112297. 0.287234f,
  112298. 0.571081f,
  112299. 0.708603f,
  112300. };
  112301. float test3[TESTSIZE]={
  112302. 0,1,-2,3,4,-5,6,7,8,9,
  112303. 8,-2,7,-1,4,6,8,3,1,-9,
  112304. 10,11,12,13,14,15,26,17,18,19,
  112305. 30,-25,-30,-1,-5,-32,4,3,-2,0};
  112306. static_codebook *testlist[]={&_vq_book_lsp20_0,
  112307. &_vq_book_res0a_13,NULL};
  112308. float *testvec[]={test1,test3};
  112309. int main(){
  112310. oggpack_buffer write;
  112311. oggpack_buffer read;
  112312. long ptr=0,i;
  112313. oggpack_writeinit(&write);
  112314. fprintf(stderr,"Testing codebook abstraction...:\n");
  112315. while(testlist[ptr]){
  112316. codebook c;
  112317. static_codebook s;
  112318. float *qv=alloca(sizeof(*qv)*TESTSIZE);
  112319. float *iv=alloca(sizeof(*iv)*TESTSIZE);
  112320. memcpy(qv,testvec[ptr],sizeof(*qv)*TESTSIZE);
  112321. memset(iv,0,sizeof(*iv)*TESTSIZE);
  112322. fprintf(stderr,"\tpacking/coding %ld... ",ptr);
  112323. /* pack the codebook, write the testvector */
  112324. oggpack_reset(&write);
  112325. vorbis_book_init_encode(&c,testlist[ptr]); /* get it into memory
  112326. we can write */
  112327. vorbis_staticbook_pack(testlist[ptr],&write);
  112328. fprintf(stderr,"Codebook size %ld bytes... ",oggpack_bytes(&write));
  112329. for(i=0;i<TESTSIZE;i+=c.dim){
  112330. int best=_best(&c,qv+i,1);
  112331. vorbis_book_encodev(&c,best,qv+i,&write);
  112332. }
  112333. vorbis_book_clear(&c);
  112334. fprintf(stderr,"OK.\n");
  112335. fprintf(stderr,"\tunpacking/decoding %ld... ",ptr);
  112336. /* transfer the write data to a read buffer and unpack/read */
  112337. oggpack_readinit(&read,oggpack_get_buffer(&write),oggpack_bytes(&write));
  112338. if(vorbis_staticbook_unpack(&read,&s)){
  112339. fprintf(stderr,"Error unpacking codebook.\n");
  112340. exit(1);
  112341. }
  112342. if(vorbis_book_init_decode(&c,&s)){
  112343. fprintf(stderr,"Error initializing codebook.\n");
  112344. exit(1);
  112345. }
  112346. for(i=0;i<TESTSIZE;i+=c.dim)
  112347. if(vorbis_book_decodev_set(&c,iv+i,&read,c.dim)==-1){
  112348. fprintf(stderr,"Error reading codebook test data (EOP).\n");
  112349. exit(1);
  112350. }
  112351. for(i=0;i<TESTSIZE;i++)
  112352. if(fabs(qv[i]-iv[i])>.000001){
  112353. fprintf(stderr,"read (%g) != written (%g) at position (%ld)\n",
  112354. iv[i],qv[i],i);
  112355. exit(1);
  112356. }
  112357. fprintf(stderr,"OK\n");
  112358. ptr++;
  112359. }
  112360. /* The above is the trivial stuff; now try unquantizing a log scale codebook */
  112361. exit(0);
  112362. }
  112363. #endif
  112364. #endif
  112365. /*** End of inlined file: codebook.c ***/
  112366. /*** Start of inlined file: envelope.c ***/
  112367. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112368. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112369. // tasks..
  112370. #if JUCE_MSVC
  112371. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112372. #endif
  112373. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112374. #if JUCE_USE_OGGVORBIS
  112375. #include <stdlib.h>
  112376. #include <string.h>
  112377. #include <stdio.h>
  112378. #include <math.h>
  112379. void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi){
  112380. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112381. vorbis_info_psy_global *gi=&ci->psy_g_param;
  112382. int ch=vi->channels;
  112383. int i,j;
  112384. int n=e->winlength=128;
  112385. e->searchstep=64; /* not random */
  112386. e->minenergy=gi->preecho_minenergy;
  112387. e->ch=ch;
  112388. e->storage=128;
  112389. e->cursor=ci->blocksizes[1]/2;
  112390. e->mdct_win=(float*)_ogg_calloc(n,sizeof(*e->mdct_win));
  112391. mdct_init(&e->mdct,n);
  112392. for(i=0;i<n;i++){
  112393. e->mdct_win[i]=sin(i/(n-1.)*M_PI);
  112394. e->mdct_win[i]*=e->mdct_win[i];
  112395. }
  112396. /* magic follows */
  112397. e->band[0].begin=2; e->band[0].end=4;
  112398. e->band[1].begin=4; e->band[1].end=5;
  112399. e->band[2].begin=6; e->band[2].end=6;
  112400. e->band[3].begin=9; e->band[3].end=8;
  112401. e->band[4].begin=13; e->band[4].end=8;
  112402. e->band[5].begin=17; e->band[5].end=8;
  112403. e->band[6].begin=22; e->band[6].end=8;
  112404. for(j=0;j<VE_BANDS;j++){
  112405. n=e->band[j].end;
  112406. e->band[j].window=(float*)_ogg_malloc(n*sizeof(*e->band[0].window));
  112407. for(i=0;i<n;i++){
  112408. e->band[j].window[i]=sin((i+.5)/n*M_PI);
  112409. e->band[j].total+=e->band[j].window[i];
  112410. }
  112411. e->band[j].total=1./e->band[j].total;
  112412. }
  112413. e->filter=(envelope_filter_state*)_ogg_calloc(VE_BANDS*ch,sizeof(*e->filter));
  112414. e->mark=(int*)_ogg_calloc(e->storage,sizeof(*e->mark));
  112415. }
  112416. void _ve_envelope_clear(envelope_lookup *e){
  112417. int i;
  112418. mdct_clear(&e->mdct);
  112419. for(i=0;i<VE_BANDS;i++)
  112420. _ogg_free(e->band[i].window);
  112421. _ogg_free(e->mdct_win);
  112422. _ogg_free(e->filter);
  112423. _ogg_free(e->mark);
  112424. memset(e,0,sizeof(*e));
  112425. }
  112426. /* fairly straight threshhold-by-band based until we find something
  112427. that works better and isn't patented. */
  112428. static int _ve_amp(envelope_lookup *ve,
  112429. vorbis_info_psy_global *gi,
  112430. float *data,
  112431. envelope_band *bands,
  112432. envelope_filter_state *filters,
  112433. long pos){
  112434. long n=ve->winlength;
  112435. int ret=0;
  112436. long i,j;
  112437. float decay;
  112438. /* we want to have a 'minimum bar' for energy, else we're just
  112439. basing blocks on quantization noise that outweighs the signal
  112440. itself (for low power signals) */
  112441. float minV=ve->minenergy;
  112442. float *vec=(float*) alloca(n*sizeof(*vec));
  112443. /* stretch is used to gradually lengthen the number of windows
  112444. considered prevoius-to-potential-trigger */
  112445. int stretch=max(VE_MINSTRETCH,ve->stretch/2);
  112446. float penalty=gi->stretch_penalty-(ve->stretch/2-VE_MINSTRETCH);
  112447. if(penalty<0.f)penalty=0.f;
  112448. if(penalty>gi->stretch_penalty)penalty=gi->stretch_penalty;
  112449. /*_analysis_output_always("lpcm",seq2,data,n,0,0,
  112450. totalshift+pos*ve->searchstep);*/
  112451. /* window and transform */
  112452. for(i=0;i<n;i++)
  112453. vec[i]=data[i]*ve->mdct_win[i];
  112454. mdct_forward(&ve->mdct,vec,vec);
  112455. /*_analysis_output_always("mdct",seq2,vec,n/2,0,1,0); */
  112456. /* near-DC spreading function; this has nothing to do with
  112457. psychoacoustics, just sidelobe leakage and window size */
  112458. {
  112459. float temp=vec[0]*vec[0]+.7*vec[1]*vec[1]+.2*vec[2]*vec[2];
  112460. int ptr=filters->nearptr;
  112461. /* the accumulation is regularly refreshed from scratch to avoid
  112462. floating point creep */
  112463. if(ptr==0){
  112464. decay=filters->nearDC_acc=filters->nearDC_partialacc+temp;
  112465. filters->nearDC_partialacc=temp;
  112466. }else{
  112467. decay=filters->nearDC_acc+=temp;
  112468. filters->nearDC_partialacc+=temp;
  112469. }
  112470. filters->nearDC_acc-=filters->nearDC[ptr];
  112471. filters->nearDC[ptr]=temp;
  112472. decay*=(1./(VE_NEARDC+1));
  112473. filters->nearptr++;
  112474. if(filters->nearptr>=VE_NEARDC)filters->nearptr=0;
  112475. decay=todB(&decay)*.5-15.f;
  112476. }
  112477. /* perform spreading and limiting, also smooth the spectrum. yes,
  112478. the MDCT results in all real coefficients, but it still *behaves*
  112479. like real/imaginary pairs */
  112480. for(i=0;i<n/2;i+=2){
  112481. float val=vec[i]*vec[i]+vec[i+1]*vec[i+1];
  112482. val=todB(&val)*.5f;
  112483. if(val<decay)val=decay;
  112484. if(val<minV)val=minV;
  112485. vec[i>>1]=val;
  112486. decay-=8.;
  112487. }
  112488. /*_analysis_output_always("spread",seq2++,vec,n/4,0,0,0);*/
  112489. /* perform preecho/postecho triggering by band */
  112490. for(j=0;j<VE_BANDS;j++){
  112491. float acc=0.;
  112492. float valmax,valmin;
  112493. /* accumulate amplitude */
  112494. for(i=0;i<bands[j].end;i++)
  112495. acc+=vec[i+bands[j].begin]*bands[j].window[i];
  112496. acc*=bands[j].total;
  112497. /* convert amplitude to delta */
  112498. {
  112499. int p,thisx=filters[j].ampptr;
  112500. float postmax,postmin,premax=-99999.f,premin=99999.f;
  112501. p=thisx;
  112502. p--;
  112503. if(p<0)p+=VE_AMP;
  112504. postmax=max(acc,filters[j].ampbuf[p]);
  112505. postmin=min(acc,filters[j].ampbuf[p]);
  112506. for(i=0;i<stretch;i++){
  112507. p--;
  112508. if(p<0)p+=VE_AMP;
  112509. premax=max(premax,filters[j].ampbuf[p]);
  112510. premin=min(premin,filters[j].ampbuf[p]);
  112511. }
  112512. valmin=postmin-premin;
  112513. valmax=postmax-premax;
  112514. /*filters[j].markers[pos]=valmax;*/
  112515. filters[j].ampbuf[thisx]=acc;
  112516. filters[j].ampptr++;
  112517. if(filters[j].ampptr>=VE_AMP)filters[j].ampptr=0;
  112518. }
  112519. /* look at min/max, decide trigger */
  112520. if(valmax>gi->preecho_thresh[j]+penalty){
  112521. ret|=1;
  112522. ret|=4;
  112523. }
  112524. if(valmin<gi->postecho_thresh[j]-penalty)ret|=2;
  112525. }
  112526. return(ret);
  112527. }
  112528. #if 0
  112529. static int seq=0;
  112530. static ogg_int64_t totalshift=-1024;
  112531. #endif
  112532. long _ve_envelope_search(vorbis_dsp_state *v){
  112533. vorbis_info *vi=v->vi;
  112534. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  112535. vorbis_info_psy_global *gi=&ci->psy_g_param;
  112536. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  112537. long i,j;
  112538. int first=ve->current/ve->searchstep;
  112539. int last=v->pcm_current/ve->searchstep-VE_WIN;
  112540. if(first<0)first=0;
  112541. /* make sure we have enough storage to match the PCM */
  112542. if(last+VE_WIN+VE_POST>ve->storage){
  112543. ve->storage=last+VE_WIN+VE_POST; /* be sure */
  112544. ve->mark=(int*)_ogg_realloc(ve->mark,ve->storage*sizeof(*ve->mark));
  112545. }
  112546. for(j=first;j<last;j++){
  112547. int ret=0;
  112548. ve->stretch++;
  112549. if(ve->stretch>VE_MAXSTRETCH*2)
  112550. ve->stretch=VE_MAXSTRETCH*2;
  112551. for(i=0;i<ve->ch;i++){
  112552. float *pcm=v->pcm[i]+ve->searchstep*(j);
  112553. ret|=_ve_amp(ve,gi,pcm,ve->band,ve->filter+i*VE_BANDS,j);
  112554. }
  112555. ve->mark[j+VE_POST]=0;
  112556. if(ret&1){
  112557. ve->mark[j]=1;
  112558. ve->mark[j+1]=1;
  112559. }
  112560. if(ret&2){
  112561. ve->mark[j]=1;
  112562. if(j>0)ve->mark[j-1]=1;
  112563. }
  112564. if(ret&4)ve->stretch=-1;
  112565. }
  112566. ve->current=last*ve->searchstep;
  112567. {
  112568. long centerW=v->centerW;
  112569. long testW=
  112570. centerW+
  112571. ci->blocksizes[v->W]/4+
  112572. ci->blocksizes[1]/2+
  112573. ci->blocksizes[0]/4;
  112574. j=ve->cursor;
  112575. while(j<ve->current-(ve->searchstep)){/* account for postecho
  112576. working back one window */
  112577. if(j>=testW)return(1);
  112578. ve->cursor=j;
  112579. if(ve->mark[j/ve->searchstep]){
  112580. if(j>centerW){
  112581. #if 0
  112582. if(j>ve->curmark){
  112583. float *marker=alloca(v->pcm_current*sizeof(*marker));
  112584. int l,m;
  112585. memset(marker,0,sizeof(*marker)*v->pcm_current);
  112586. fprintf(stderr,"mark! seq=%d, cursor:%fs time:%fs\n",
  112587. seq,
  112588. (totalshift+ve->cursor)/44100.,
  112589. (totalshift+j)/44100.);
  112590. _analysis_output_always("pcmL",seq,v->pcm[0],v->pcm_current,0,0,totalshift);
  112591. _analysis_output_always("pcmR",seq,v->pcm[1],v->pcm_current,0,0,totalshift);
  112592. _analysis_output_always("markL",seq,v->pcm[0],j,0,0,totalshift);
  112593. _analysis_output_always("markR",seq,v->pcm[1],j,0,0,totalshift);
  112594. for(m=0;m<VE_BANDS;m++){
  112595. char buf[80];
  112596. sprintf(buf,"delL%d",m);
  112597. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m].markers[l]*.1;
  112598. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  112599. }
  112600. for(m=0;m<VE_BANDS;m++){
  112601. char buf[80];
  112602. sprintf(buf,"delR%d",m);
  112603. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m+VE_BANDS].markers[l]*.1;
  112604. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  112605. }
  112606. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->mark[l]*.4;
  112607. _analysis_output_always("mark",seq,marker,v->pcm_current,0,0,totalshift);
  112608. seq++;
  112609. }
  112610. #endif
  112611. ve->curmark=j;
  112612. if(j>=testW)return(1);
  112613. return(0);
  112614. }
  112615. }
  112616. j+=ve->searchstep;
  112617. }
  112618. }
  112619. return(-1);
  112620. }
  112621. int _ve_envelope_mark(vorbis_dsp_state *v){
  112622. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  112623. vorbis_info *vi=v->vi;
  112624. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112625. long centerW=v->centerW;
  112626. long beginW=centerW-ci->blocksizes[v->W]/4;
  112627. long endW=centerW+ci->blocksizes[v->W]/4;
  112628. if(v->W){
  112629. beginW-=ci->blocksizes[v->lW]/4;
  112630. endW+=ci->blocksizes[v->nW]/4;
  112631. }else{
  112632. beginW-=ci->blocksizes[0]/4;
  112633. endW+=ci->blocksizes[0]/4;
  112634. }
  112635. if(ve->curmark>=beginW && ve->curmark<endW)return(1);
  112636. {
  112637. long first=beginW/ve->searchstep;
  112638. long last=endW/ve->searchstep;
  112639. long i;
  112640. for(i=first;i<last;i++)
  112641. if(ve->mark[i])return(1);
  112642. }
  112643. return(0);
  112644. }
  112645. void _ve_envelope_shift(envelope_lookup *e,long shift){
  112646. int smallsize=e->current/e->searchstep+VE_POST; /* adjust for placing marks
  112647. ahead of ve->current */
  112648. int smallshift=shift/e->searchstep;
  112649. memmove(e->mark,e->mark+smallshift,(smallsize-smallshift)*sizeof(*e->mark));
  112650. #if 0
  112651. for(i=0;i<VE_BANDS*e->ch;i++)
  112652. memmove(e->filter[i].markers,
  112653. e->filter[i].markers+smallshift,
  112654. (1024-smallshift)*sizeof(*(*e->filter).markers));
  112655. totalshift+=shift;
  112656. #endif
  112657. e->current-=shift;
  112658. if(e->curmark>=0)
  112659. e->curmark-=shift;
  112660. e->cursor-=shift;
  112661. }
  112662. #endif
  112663. /*** End of inlined file: envelope.c ***/
  112664. /*** Start of inlined file: floor0.c ***/
  112665. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112666. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112667. // tasks..
  112668. #if JUCE_MSVC
  112669. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112670. #endif
  112671. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112672. #if JUCE_USE_OGGVORBIS
  112673. #include <stdlib.h>
  112674. #include <string.h>
  112675. #include <math.h>
  112676. /*** Start of inlined file: lsp.h ***/
  112677. #ifndef _V_LSP_H_
  112678. #define _V_LSP_H_
  112679. extern int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m);
  112680. extern void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,
  112681. float *lsp,int m,
  112682. float amp,float ampoffset);
  112683. #endif
  112684. /*** End of inlined file: lsp.h ***/
  112685. #include <stdio.h>
  112686. typedef struct {
  112687. int ln;
  112688. int m;
  112689. int **linearmap;
  112690. int n[2];
  112691. vorbis_info_floor0 *vi;
  112692. long bits;
  112693. long frames;
  112694. } vorbis_look_floor0;
  112695. /***********************************************/
  112696. static void floor0_free_info(vorbis_info_floor *i){
  112697. vorbis_info_floor0 *info=(vorbis_info_floor0 *)i;
  112698. if(info){
  112699. memset(info,0,sizeof(*info));
  112700. _ogg_free(info);
  112701. }
  112702. }
  112703. static void floor0_free_look(vorbis_look_floor *i){
  112704. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112705. if(look){
  112706. if(look->linearmap){
  112707. if(look->linearmap[0])_ogg_free(look->linearmap[0]);
  112708. if(look->linearmap[1])_ogg_free(look->linearmap[1]);
  112709. _ogg_free(look->linearmap);
  112710. }
  112711. memset(look,0,sizeof(*look));
  112712. _ogg_free(look);
  112713. }
  112714. }
  112715. static vorbis_info_floor *floor0_unpack (vorbis_info *vi,oggpack_buffer *opb){
  112716. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112717. int j;
  112718. vorbis_info_floor0 *info=(vorbis_info_floor0*)_ogg_malloc(sizeof(*info));
  112719. info->order=oggpack_read(opb,8);
  112720. info->rate=oggpack_read(opb,16);
  112721. info->barkmap=oggpack_read(opb,16);
  112722. info->ampbits=oggpack_read(opb,6);
  112723. info->ampdB=oggpack_read(opb,8);
  112724. info->numbooks=oggpack_read(opb,4)+1;
  112725. if(info->order<1)goto err_out;
  112726. if(info->rate<1)goto err_out;
  112727. if(info->barkmap<1)goto err_out;
  112728. if(info->numbooks<1)goto err_out;
  112729. for(j=0;j<info->numbooks;j++){
  112730. info->books[j]=oggpack_read(opb,8);
  112731. if(info->books[j]<0 || info->books[j]>=ci->books)goto err_out;
  112732. }
  112733. return(info);
  112734. err_out:
  112735. floor0_free_info(info);
  112736. return(NULL);
  112737. }
  112738. /* initialize Bark scale and normalization lookups. We could do this
  112739. with static tables, but Vorbis allows a number of possible
  112740. combinations, so it's best to do it computationally.
  112741. The below is authoritative in terms of defining scale mapping.
  112742. Note that the scale depends on the sampling rate as well as the
  112743. linear block and mapping sizes */
  112744. static void floor0_map_lazy_init(vorbis_block *vb,
  112745. vorbis_info_floor *infoX,
  112746. vorbis_look_floor0 *look){
  112747. if(!look->linearmap[vb->W]){
  112748. vorbis_dsp_state *vd=vb->vd;
  112749. vorbis_info *vi=vd->vi;
  112750. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112751. vorbis_info_floor0 *info=(vorbis_info_floor0 *)infoX;
  112752. int W=vb->W;
  112753. int n=ci->blocksizes[W]/2,j;
  112754. /* we choose a scaling constant so that:
  112755. floor(bark(rate/2-1)*C)=mapped-1
  112756. floor(bark(rate/2)*C)=mapped */
  112757. float scale=look->ln/toBARK(info->rate/2.f);
  112758. /* the mapping from a linear scale to a smaller bark scale is
  112759. straightforward. We do *not* make sure that the linear mapping
  112760. does not skip bark-scale bins; the decoder simply skips them and
  112761. the encoder may do what it wishes in filling them. They're
  112762. necessary in some mapping combinations to keep the scale spacing
  112763. accurate */
  112764. look->linearmap[W]=(int*)_ogg_malloc((n+1)*sizeof(**look->linearmap));
  112765. for(j=0;j<n;j++){
  112766. int val=floor( toBARK((info->rate/2.f)/n*j)
  112767. *scale); /* bark numbers represent band edges */
  112768. if(val>=look->ln)val=look->ln-1; /* guard against the approximation */
  112769. look->linearmap[W][j]=val;
  112770. }
  112771. look->linearmap[W][j]=-1;
  112772. look->n[W]=n;
  112773. }
  112774. }
  112775. static vorbis_look_floor *floor0_look(vorbis_dsp_state *vd,
  112776. vorbis_info_floor *i){
  112777. vorbis_info_floor0 *info=(vorbis_info_floor0*)i;
  112778. vorbis_look_floor0 *look=(vorbis_look_floor0*)_ogg_calloc(1,sizeof(*look));
  112779. look->m=info->order;
  112780. look->ln=info->barkmap;
  112781. look->vi=info;
  112782. look->linearmap=(int**)_ogg_calloc(2,sizeof(*look->linearmap));
  112783. return look;
  112784. }
  112785. static void *floor0_inverse1(vorbis_block *vb,vorbis_look_floor *i){
  112786. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112787. vorbis_info_floor0 *info=look->vi;
  112788. int j,k;
  112789. int ampraw=oggpack_read(&vb->opb,info->ampbits);
  112790. if(ampraw>0){ /* also handles the -1 out of data case */
  112791. long maxval=(1<<info->ampbits)-1;
  112792. float amp=(float)ampraw/maxval*info->ampdB;
  112793. int booknum=oggpack_read(&vb->opb,_ilog(info->numbooks));
  112794. if(booknum!=-1 && booknum<info->numbooks){ /* be paranoid */
  112795. codec_setup_info *ci=(codec_setup_info *)vb->vd->vi->codec_setup;
  112796. codebook *b=ci->fullbooks+info->books[booknum];
  112797. float last=0.f;
  112798. /* the additional b->dim is a guard against any possible stack
  112799. smash; b->dim is provably more than we can overflow the
  112800. vector */
  112801. float *lsp=(float*)_vorbis_block_alloc(vb,sizeof(*lsp)*(look->m+b->dim+1));
  112802. for(j=0;j<look->m;j+=b->dim)
  112803. if(vorbis_book_decodev_set(b,lsp+j,&vb->opb,b->dim)==-1)goto eop;
  112804. for(j=0;j<look->m;){
  112805. for(k=0;k<b->dim;k++,j++)lsp[j]+=last;
  112806. last=lsp[j-1];
  112807. }
  112808. lsp[look->m]=amp;
  112809. return(lsp);
  112810. }
  112811. }
  112812. eop:
  112813. return(NULL);
  112814. }
  112815. static int floor0_inverse2(vorbis_block *vb,vorbis_look_floor *i,
  112816. void *memo,float *out){
  112817. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112818. vorbis_info_floor0 *info=look->vi;
  112819. floor0_map_lazy_init(vb,info,look);
  112820. if(memo){
  112821. float *lsp=(float *)memo;
  112822. float amp=lsp[look->m];
  112823. /* take the coefficients back to a spectral envelope curve */
  112824. vorbis_lsp_to_curve(out,
  112825. look->linearmap[vb->W],
  112826. look->n[vb->W],
  112827. look->ln,
  112828. lsp,look->m,amp,(float)info->ampdB);
  112829. return(1);
  112830. }
  112831. memset(out,0,sizeof(*out)*look->n[vb->W]);
  112832. return(0);
  112833. }
  112834. /* export hooks */
  112835. vorbis_func_floor floor0_exportbundle={
  112836. NULL,&floor0_unpack,&floor0_look,&floor0_free_info,
  112837. &floor0_free_look,&floor0_inverse1,&floor0_inverse2
  112838. };
  112839. #endif
  112840. /*** End of inlined file: floor0.c ***/
  112841. /*** Start of inlined file: floor1.c ***/
  112842. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112843. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112844. // tasks..
  112845. #if JUCE_MSVC
  112846. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112847. #endif
  112848. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112849. #if JUCE_USE_OGGVORBIS
  112850. #include <stdlib.h>
  112851. #include <string.h>
  112852. #include <math.h>
  112853. #include <stdio.h>
  112854. #define floor1_rangedB 140 /* floor 1 fixed at -140dB to 0dB range */
  112855. typedef struct {
  112856. int sorted_index[VIF_POSIT+2];
  112857. int forward_index[VIF_POSIT+2];
  112858. int reverse_index[VIF_POSIT+2];
  112859. int hineighbor[VIF_POSIT];
  112860. int loneighbor[VIF_POSIT];
  112861. int posts;
  112862. int n;
  112863. int quant_q;
  112864. vorbis_info_floor1 *vi;
  112865. long phrasebits;
  112866. long postbits;
  112867. long frames;
  112868. } vorbis_look_floor1;
  112869. typedef struct lsfit_acc{
  112870. long x0;
  112871. long x1;
  112872. long xa;
  112873. long ya;
  112874. long x2a;
  112875. long y2a;
  112876. long xya;
  112877. long an;
  112878. } lsfit_acc;
  112879. /***********************************************/
  112880. static void floor1_free_info(vorbis_info_floor *i){
  112881. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  112882. if(info){
  112883. memset(info,0,sizeof(*info));
  112884. _ogg_free(info);
  112885. }
  112886. }
  112887. static void floor1_free_look(vorbis_look_floor *i){
  112888. vorbis_look_floor1 *look=(vorbis_look_floor1 *)i;
  112889. if(look){
  112890. /*fprintf(stderr,"floor 1 bit usage %f:%f (%f total)\n",
  112891. (float)look->phrasebits/look->frames,
  112892. (float)look->postbits/look->frames,
  112893. (float)(look->postbits+look->phrasebits)/look->frames);*/
  112894. memset(look,0,sizeof(*look));
  112895. _ogg_free(look);
  112896. }
  112897. }
  112898. static void floor1_pack (vorbis_info_floor *i,oggpack_buffer *opb){
  112899. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  112900. int j,k;
  112901. int count=0;
  112902. int rangebits;
  112903. int maxposit=info->postlist[1];
  112904. int maxclass=-1;
  112905. /* save out partitions */
  112906. oggpack_write(opb,info->partitions,5); /* only 0 to 31 legal */
  112907. for(j=0;j<info->partitions;j++){
  112908. oggpack_write(opb,info->partitionclass[j],4); /* only 0 to 15 legal */
  112909. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  112910. }
  112911. /* save out partition classes */
  112912. for(j=0;j<maxclass+1;j++){
  112913. oggpack_write(opb,info->class_dim[j]-1,3); /* 1 to 8 */
  112914. oggpack_write(opb,info->class_subs[j],2); /* 0 to 3 */
  112915. if(info->class_subs[j])oggpack_write(opb,info->class_book[j],8);
  112916. for(k=0;k<(1<<info->class_subs[j]);k++)
  112917. oggpack_write(opb,info->class_subbook[j][k]+1,8);
  112918. }
  112919. /* save out the post list */
  112920. oggpack_write(opb,info->mult-1,2); /* only 1,2,3,4 legal now */
  112921. oggpack_write(opb,ilog2(maxposit),4);
  112922. rangebits=ilog2(maxposit);
  112923. for(j=0,k=0;j<info->partitions;j++){
  112924. count+=info->class_dim[info->partitionclass[j]];
  112925. for(;k<count;k++)
  112926. oggpack_write(opb,info->postlist[k+2],rangebits);
  112927. }
  112928. }
  112929. static vorbis_info_floor *floor1_unpack (vorbis_info *vi,oggpack_buffer *opb){
  112930. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112931. int j,k,count=0,maxclass=-1,rangebits;
  112932. vorbis_info_floor1 *info=(vorbis_info_floor1*)_ogg_calloc(1,sizeof(*info));
  112933. /* read partitions */
  112934. info->partitions=oggpack_read(opb,5); /* only 0 to 31 legal */
  112935. for(j=0;j<info->partitions;j++){
  112936. info->partitionclass[j]=oggpack_read(opb,4); /* only 0 to 15 legal */
  112937. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  112938. }
  112939. /* read partition classes */
  112940. for(j=0;j<maxclass+1;j++){
  112941. info->class_dim[j]=oggpack_read(opb,3)+1; /* 1 to 8 */
  112942. info->class_subs[j]=oggpack_read(opb,2); /* 0,1,2,3 bits */
  112943. if(info->class_subs[j]<0)
  112944. goto err_out;
  112945. if(info->class_subs[j])info->class_book[j]=oggpack_read(opb,8);
  112946. if(info->class_book[j]<0 || info->class_book[j]>=ci->books)
  112947. goto err_out;
  112948. for(k=0;k<(1<<info->class_subs[j]);k++){
  112949. info->class_subbook[j][k]=oggpack_read(opb,8)-1;
  112950. if(info->class_subbook[j][k]<-1 || info->class_subbook[j][k]>=ci->books)
  112951. goto err_out;
  112952. }
  112953. }
  112954. /* read the post list */
  112955. info->mult=oggpack_read(opb,2)+1; /* only 1,2,3,4 legal now */
  112956. rangebits=oggpack_read(opb,4);
  112957. for(j=0,k=0;j<info->partitions;j++){
  112958. count+=info->class_dim[info->partitionclass[j]];
  112959. for(;k<count;k++){
  112960. int t=info->postlist[k+2]=oggpack_read(opb,rangebits);
  112961. if(t<0 || t>=(1<<rangebits))
  112962. goto err_out;
  112963. }
  112964. }
  112965. info->postlist[0]=0;
  112966. info->postlist[1]=1<<rangebits;
  112967. return(info);
  112968. err_out:
  112969. floor1_free_info(info);
  112970. return(NULL);
  112971. }
  112972. static int JUCE_CDECL icomp(const void *a,const void *b){
  112973. return(**(int **)a-**(int **)b);
  112974. }
  112975. static vorbis_look_floor *floor1_look(vorbis_dsp_state *vd,
  112976. vorbis_info_floor *in){
  112977. int *sortpointer[VIF_POSIT+2];
  112978. vorbis_info_floor1 *info=(vorbis_info_floor1*)in;
  112979. vorbis_look_floor1 *look=(vorbis_look_floor1*)_ogg_calloc(1,sizeof(*look));
  112980. int i,j,n=0;
  112981. look->vi=info;
  112982. look->n=info->postlist[1];
  112983. /* we drop each position value in-between already decoded values,
  112984. and use linear interpolation to predict each new value past the
  112985. edges. The positions are read in the order of the position
  112986. list... we precompute the bounding positions in the lookup. Of
  112987. course, the neighbors can change (if a position is declined), but
  112988. this is an initial mapping */
  112989. for(i=0;i<info->partitions;i++)n+=info->class_dim[info->partitionclass[i]];
  112990. n+=2;
  112991. look->posts=n;
  112992. /* also store a sorted position index */
  112993. for(i=0;i<n;i++)sortpointer[i]=info->postlist+i;
  112994. qsort(sortpointer,n,sizeof(*sortpointer),icomp);
  112995. /* points from sort order back to range number */
  112996. for(i=0;i<n;i++)look->forward_index[i]=sortpointer[i]-info->postlist;
  112997. /* points from range order to sorted position */
  112998. for(i=0;i<n;i++)look->reverse_index[look->forward_index[i]]=i;
  112999. /* we actually need the post values too */
  113000. for(i=0;i<n;i++)look->sorted_index[i]=info->postlist[look->forward_index[i]];
  113001. /* quantize values to multiplier spec */
  113002. switch(info->mult){
  113003. case 1: /* 1024 -> 256 */
  113004. look->quant_q=256;
  113005. break;
  113006. case 2: /* 1024 -> 128 */
  113007. look->quant_q=128;
  113008. break;
  113009. case 3: /* 1024 -> 86 */
  113010. look->quant_q=86;
  113011. break;
  113012. case 4: /* 1024 -> 64 */
  113013. look->quant_q=64;
  113014. break;
  113015. }
  113016. /* discover our neighbors for decode where we don't use fit flags
  113017. (that would push the neighbors outward) */
  113018. for(i=0;i<n-2;i++){
  113019. int lo=0;
  113020. int hi=1;
  113021. int lx=0;
  113022. int hx=look->n;
  113023. int currentx=info->postlist[i+2];
  113024. for(j=0;j<i+2;j++){
  113025. int x=info->postlist[j];
  113026. if(x>lx && x<currentx){
  113027. lo=j;
  113028. lx=x;
  113029. }
  113030. if(x<hx && x>currentx){
  113031. hi=j;
  113032. hx=x;
  113033. }
  113034. }
  113035. look->loneighbor[i]=lo;
  113036. look->hineighbor[i]=hi;
  113037. }
  113038. return(look);
  113039. }
  113040. static int render_point(int x0,int x1,int y0,int y1,int x){
  113041. y0&=0x7fff; /* mask off flag */
  113042. y1&=0x7fff;
  113043. {
  113044. int dy=y1-y0;
  113045. int adx=x1-x0;
  113046. int ady=abs(dy);
  113047. int err=ady*(x-x0);
  113048. int off=err/adx;
  113049. if(dy<0)return(y0-off);
  113050. return(y0+off);
  113051. }
  113052. }
  113053. static int vorbis_dBquant(const float *x){
  113054. int i= *x*7.3142857f+1023.5f;
  113055. if(i>1023)return(1023);
  113056. if(i<0)return(0);
  113057. return i;
  113058. }
  113059. static float FLOOR1_fromdB_LOOKUP[256]={
  113060. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  113061. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  113062. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  113063. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  113064. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  113065. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  113066. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  113067. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  113068. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  113069. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  113070. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  113071. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  113072. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  113073. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  113074. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  113075. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  113076. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  113077. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  113078. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  113079. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  113080. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  113081. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  113082. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  113083. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  113084. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  113085. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  113086. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  113087. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  113088. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  113089. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  113090. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  113091. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  113092. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  113093. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  113094. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  113095. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  113096. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  113097. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  113098. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  113099. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  113100. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  113101. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  113102. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  113103. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  113104. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  113105. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  113106. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  113107. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  113108. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  113109. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  113110. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  113111. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  113112. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  113113. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  113114. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  113115. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  113116. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  113117. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  113118. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  113119. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  113120. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  113121. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  113122. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  113123. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  113124. };
  113125. static void render_line(int x0,int x1,int y0,int y1,float *d){
  113126. int dy=y1-y0;
  113127. int adx=x1-x0;
  113128. int ady=abs(dy);
  113129. int base=dy/adx;
  113130. int sy=(dy<0?base-1:base+1);
  113131. int x=x0;
  113132. int y=y0;
  113133. int err=0;
  113134. ady-=abs(base*adx);
  113135. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  113136. while(++x<x1){
  113137. err=err+ady;
  113138. if(err>=adx){
  113139. err-=adx;
  113140. y+=sy;
  113141. }else{
  113142. y+=base;
  113143. }
  113144. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  113145. }
  113146. }
  113147. static void render_line0(int x0,int x1,int y0,int y1,int *d){
  113148. int dy=y1-y0;
  113149. int adx=x1-x0;
  113150. int ady=abs(dy);
  113151. int base=dy/adx;
  113152. int sy=(dy<0?base-1:base+1);
  113153. int x=x0;
  113154. int y=y0;
  113155. int err=0;
  113156. ady-=abs(base*adx);
  113157. d[x]=y;
  113158. while(++x<x1){
  113159. err=err+ady;
  113160. if(err>=adx){
  113161. err-=adx;
  113162. y+=sy;
  113163. }else{
  113164. y+=base;
  113165. }
  113166. d[x]=y;
  113167. }
  113168. }
  113169. /* the floor has already been filtered to only include relevant sections */
  113170. static int accumulate_fit(const float *flr,const float *mdct,
  113171. int x0, int x1,lsfit_acc *a,
  113172. int n,vorbis_info_floor1 *info){
  113173. long i;
  113174. 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;
  113175. memset(a,0,sizeof(*a));
  113176. a->x0=x0;
  113177. a->x1=x1;
  113178. if(x1>=n)x1=n-1;
  113179. for(i=x0;i<=x1;i++){
  113180. int quantized=vorbis_dBquant(flr+i);
  113181. if(quantized){
  113182. if(mdct[i]+info->twofitatten>=flr[i]){
  113183. xa += i;
  113184. ya += quantized;
  113185. x2a += i*i;
  113186. y2a += quantized*quantized;
  113187. xya += i*quantized;
  113188. na++;
  113189. }else{
  113190. xb += i;
  113191. yb += quantized;
  113192. x2b += i*i;
  113193. y2b += quantized*quantized;
  113194. xyb += i*quantized;
  113195. nb++;
  113196. }
  113197. }
  113198. }
  113199. xb+=xa;
  113200. yb+=ya;
  113201. x2b+=x2a;
  113202. y2b+=y2a;
  113203. xyb+=xya;
  113204. nb+=na;
  113205. /* weight toward the actually used frequencies if we meet the threshhold */
  113206. {
  113207. int weight=nb*info->twofitweight/(na+1);
  113208. a->xa=xa*weight+xb;
  113209. a->ya=ya*weight+yb;
  113210. a->x2a=x2a*weight+x2b;
  113211. a->y2a=y2a*weight+y2b;
  113212. a->xya=xya*weight+xyb;
  113213. a->an=na*weight+nb;
  113214. }
  113215. return(na);
  113216. }
  113217. static void fit_line(lsfit_acc *a,int fits,int *y0,int *y1){
  113218. long x=0,y=0,x2=0,y2=0,xy=0,an=0,i;
  113219. long x0=a[0].x0;
  113220. long x1=a[fits-1].x1;
  113221. for(i=0;i<fits;i++){
  113222. x+=a[i].xa;
  113223. y+=a[i].ya;
  113224. x2+=a[i].x2a;
  113225. y2+=a[i].y2a;
  113226. xy+=a[i].xya;
  113227. an+=a[i].an;
  113228. }
  113229. if(*y0>=0){
  113230. x+= x0;
  113231. y+= *y0;
  113232. x2+= x0 * x0;
  113233. y2+= *y0 * *y0;
  113234. xy+= *y0 * x0;
  113235. an++;
  113236. }
  113237. if(*y1>=0){
  113238. x+= x1;
  113239. y+= *y1;
  113240. x2+= x1 * x1;
  113241. y2+= *y1 * *y1;
  113242. xy+= *y1 * x1;
  113243. an++;
  113244. }
  113245. if(an){
  113246. /* need 64 bit multiplies, which C doesn't give portably as int */
  113247. double fx=x;
  113248. double fy=y;
  113249. double fx2=x2;
  113250. double fxy=xy;
  113251. double denom=1./(an*fx2-fx*fx);
  113252. double a=(fy*fx2-fxy*fx)*denom;
  113253. double b=(an*fxy-fx*fy)*denom;
  113254. *y0=rint(a+b*x0);
  113255. *y1=rint(a+b*x1);
  113256. /* limit to our range! */
  113257. if(*y0>1023)*y0=1023;
  113258. if(*y1>1023)*y1=1023;
  113259. if(*y0<0)*y0=0;
  113260. if(*y1<0)*y1=0;
  113261. }else{
  113262. *y0=0;
  113263. *y1=0;
  113264. }
  113265. }
  113266. /*static void fit_line_point(lsfit_acc *a,int fits,int *y0,int *y1){
  113267. long y=0;
  113268. int i;
  113269. for(i=0;i<fits && y==0;i++)
  113270. y+=a[i].ya;
  113271. *y0=*y1=y;
  113272. }*/
  113273. static int inspect_error(int x0,int x1,int y0,int y1,const float *mask,
  113274. const float *mdct,
  113275. vorbis_info_floor1 *info){
  113276. int dy=y1-y0;
  113277. int adx=x1-x0;
  113278. int ady=abs(dy);
  113279. int base=dy/adx;
  113280. int sy=(dy<0?base-1:base+1);
  113281. int x=x0;
  113282. int y=y0;
  113283. int err=0;
  113284. int val=vorbis_dBquant(mask+x);
  113285. int mse=0;
  113286. int n=0;
  113287. ady-=abs(base*adx);
  113288. mse=(y-val);
  113289. mse*=mse;
  113290. n++;
  113291. if(mdct[x]+info->twofitatten>=mask[x]){
  113292. if(y+info->maxover<val)return(1);
  113293. if(y-info->maxunder>val)return(1);
  113294. }
  113295. while(++x<x1){
  113296. err=err+ady;
  113297. if(err>=adx){
  113298. err-=adx;
  113299. y+=sy;
  113300. }else{
  113301. y+=base;
  113302. }
  113303. val=vorbis_dBquant(mask+x);
  113304. mse+=((y-val)*(y-val));
  113305. n++;
  113306. if(mdct[x]+info->twofitatten>=mask[x]){
  113307. if(val){
  113308. if(y+info->maxover<val)return(1);
  113309. if(y-info->maxunder>val)return(1);
  113310. }
  113311. }
  113312. }
  113313. if(info->maxover*info->maxover/n>info->maxerr)return(0);
  113314. if(info->maxunder*info->maxunder/n>info->maxerr)return(0);
  113315. if(mse/n>info->maxerr)return(1);
  113316. return(0);
  113317. }
  113318. static int post_Y(int *A,int *B,int pos){
  113319. if(A[pos]<0)
  113320. return B[pos];
  113321. if(B[pos]<0)
  113322. return A[pos];
  113323. return (A[pos]+B[pos])>>1;
  113324. }
  113325. int *floor1_fit(vorbis_block *vb,void *look_,
  113326. const float *logmdct, /* in */
  113327. const float *logmask){
  113328. long i,j;
  113329. vorbis_look_floor1 *look = (vorbis_look_floor1*) look_;
  113330. vorbis_info_floor1 *info=look->vi;
  113331. long n=look->n;
  113332. long posts=look->posts;
  113333. long nonzero=0;
  113334. lsfit_acc fits[VIF_POSIT+1];
  113335. int fit_valueA[VIF_POSIT+2]; /* index by range list position */
  113336. int fit_valueB[VIF_POSIT+2]; /* index by range list position */
  113337. int loneighbor[VIF_POSIT+2]; /* sorted index of range list position (+2) */
  113338. int hineighbor[VIF_POSIT+2];
  113339. int *output=NULL;
  113340. int memo[VIF_POSIT+2];
  113341. for(i=0;i<posts;i++)fit_valueA[i]=-200; /* mark all unused */
  113342. for(i=0;i<posts;i++)fit_valueB[i]=-200; /* mark all unused */
  113343. for(i=0;i<posts;i++)loneighbor[i]=0; /* 0 for the implicit 0 post */
  113344. for(i=0;i<posts;i++)hineighbor[i]=1; /* 1 for the implicit post at n */
  113345. for(i=0;i<posts;i++)memo[i]=-1; /* no neighbor yet */
  113346. /* quantize the relevant floor points and collect them into line fit
  113347. structures (one per minimal division) at the same time */
  113348. if(posts==0){
  113349. nonzero+=accumulate_fit(logmask,logmdct,0,n,fits,n,info);
  113350. }else{
  113351. for(i=0;i<posts-1;i++)
  113352. nonzero+=accumulate_fit(logmask,logmdct,look->sorted_index[i],
  113353. look->sorted_index[i+1],fits+i,
  113354. n,info);
  113355. }
  113356. if(nonzero){
  113357. /* start by fitting the implicit base case.... */
  113358. int y0=-200;
  113359. int y1=-200;
  113360. fit_line(fits,posts-1,&y0,&y1);
  113361. fit_valueA[0]=y0;
  113362. fit_valueB[0]=y0;
  113363. fit_valueB[1]=y1;
  113364. fit_valueA[1]=y1;
  113365. /* Non degenerate case */
  113366. /* start progressive splitting. This is a greedy, non-optimal
  113367. algorithm, but simple and close enough to the best
  113368. answer. */
  113369. for(i=2;i<posts;i++){
  113370. int sortpos=look->reverse_index[i];
  113371. int ln=loneighbor[sortpos];
  113372. int hn=hineighbor[sortpos];
  113373. /* eliminate repeat searches of a particular range with a memo */
  113374. if(memo[ln]!=hn){
  113375. /* haven't performed this error search yet */
  113376. int lsortpos=look->reverse_index[ln];
  113377. int hsortpos=look->reverse_index[hn];
  113378. memo[ln]=hn;
  113379. {
  113380. /* A note: we want to bound/minimize *local*, not global, error */
  113381. int lx=info->postlist[ln];
  113382. int hx=info->postlist[hn];
  113383. int ly=post_Y(fit_valueA,fit_valueB,ln);
  113384. int hy=post_Y(fit_valueA,fit_valueB,hn);
  113385. if(ly==-1 || hy==-1){
  113386. exit(1);
  113387. }
  113388. if(inspect_error(lx,hx,ly,hy,logmask,logmdct,info)){
  113389. /* outside error bounds/begin search area. Split it. */
  113390. int ly0=-200;
  113391. int ly1=-200;
  113392. int hy0=-200;
  113393. int hy1=-200;
  113394. fit_line(fits+lsortpos,sortpos-lsortpos,&ly0,&ly1);
  113395. fit_line(fits+sortpos,hsortpos-sortpos,&hy0,&hy1);
  113396. /* store new edge values */
  113397. fit_valueB[ln]=ly0;
  113398. if(ln==0)fit_valueA[ln]=ly0;
  113399. fit_valueA[i]=ly1;
  113400. fit_valueB[i]=hy0;
  113401. fit_valueA[hn]=hy1;
  113402. if(hn==1)fit_valueB[hn]=hy1;
  113403. if(ly1>=0 || hy0>=0){
  113404. /* store new neighbor values */
  113405. for(j=sortpos-1;j>=0;j--)
  113406. if(hineighbor[j]==hn)
  113407. hineighbor[j]=i;
  113408. else
  113409. break;
  113410. for(j=sortpos+1;j<posts;j++)
  113411. if(loneighbor[j]==ln)
  113412. loneighbor[j]=i;
  113413. else
  113414. break;
  113415. }
  113416. }else{
  113417. fit_valueA[i]=-200;
  113418. fit_valueB[i]=-200;
  113419. }
  113420. }
  113421. }
  113422. }
  113423. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  113424. output[0]=post_Y(fit_valueA,fit_valueB,0);
  113425. output[1]=post_Y(fit_valueA,fit_valueB,1);
  113426. /* fill in posts marked as not using a fit; we will zero
  113427. back out to 'unused' when encoding them so long as curve
  113428. interpolation doesn't force them into use */
  113429. for(i=2;i<posts;i++){
  113430. int ln=look->loneighbor[i-2];
  113431. int hn=look->hineighbor[i-2];
  113432. int x0=info->postlist[ln];
  113433. int x1=info->postlist[hn];
  113434. int y0=output[ln];
  113435. int y1=output[hn];
  113436. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  113437. int vx=post_Y(fit_valueA,fit_valueB,i);
  113438. if(vx>=0 && predicted!=vx){
  113439. output[i]=vx;
  113440. }else{
  113441. output[i]= predicted|0x8000;
  113442. }
  113443. }
  113444. }
  113445. return(output);
  113446. }
  113447. int *floor1_interpolate_fit(vorbis_block *vb,void *look_,
  113448. int *A,int *B,
  113449. int del){
  113450. long i;
  113451. vorbis_look_floor1* look = (vorbis_look_floor1*) look_;
  113452. long posts=look->posts;
  113453. int *output=NULL;
  113454. if(A && B){
  113455. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  113456. for(i=0;i<posts;i++){
  113457. output[i]=((65536-del)*(A[i]&0x7fff)+del*(B[i]&0x7fff)+32768)>>16;
  113458. if(A[i]&0x8000 && B[i]&0x8000)output[i]|=0x8000;
  113459. }
  113460. }
  113461. return(output);
  113462. }
  113463. int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  113464. void*look_,
  113465. int *post,int *ilogmask){
  113466. long i,j;
  113467. vorbis_look_floor1 *look = (vorbis_look_floor1 *) look_;
  113468. vorbis_info_floor1 *info=look->vi;
  113469. long posts=look->posts;
  113470. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113471. int out[VIF_POSIT+2];
  113472. static_codebook **sbooks=ci->book_param;
  113473. codebook *books=ci->fullbooks;
  113474. static long seq=0;
  113475. /* quantize values to multiplier spec */
  113476. if(post){
  113477. for(i=0;i<posts;i++){
  113478. int val=post[i]&0x7fff;
  113479. switch(info->mult){
  113480. case 1: /* 1024 -> 256 */
  113481. val>>=2;
  113482. break;
  113483. case 2: /* 1024 -> 128 */
  113484. val>>=3;
  113485. break;
  113486. case 3: /* 1024 -> 86 */
  113487. val/=12;
  113488. break;
  113489. case 4: /* 1024 -> 64 */
  113490. val>>=4;
  113491. break;
  113492. }
  113493. post[i]=val | (post[i]&0x8000);
  113494. }
  113495. out[0]=post[0];
  113496. out[1]=post[1];
  113497. /* find prediction values for each post and subtract them */
  113498. for(i=2;i<posts;i++){
  113499. int ln=look->loneighbor[i-2];
  113500. int hn=look->hineighbor[i-2];
  113501. int x0=info->postlist[ln];
  113502. int x1=info->postlist[hn];
  113503. int y0=post[ln];
  113504. int y1=post[hn];
  113505. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  113506. if((post[i]&0x8000) || (predicted==post[i])){
  113507. post[i]=predicted|0x8000; /* in case there was roundoff jitter
  113508. in interpolation */
  113509. out[i]=0;
  113510. }else{
  113511. int headroom=(look->quant_q-predicted<predicted?
  113512. look->quant_q-predicted:predicted);
  113513. int val=post[i]-predicted;
  113514. /* at this point the 'deviation' value is in the range +/- max
  113515. range, but the real, unique range can always be mapped to
  113516. only [0-maxrange). So we want to wrap the deviation into
  113517. this limited range, but do it in the way that least screws
  113518. an essentially gaussian probability distribution. */
  113519. if(val<0)
  113520. if(val<-headroom)
  113521. val=headroom-val-1;
  113522. else
  113523. val=-1-(val<<1);
  113524. else
  113525. if(val>=headroom)
  113526. val= val+headroom;
  113527. else
  113528. val<<=1;
  113529. out[i]=val;
  113530. post[ln]&=0x7fff;
  113531. post[hn]&=0x7fff;
  113532. }
  113533. }
  113534. /* we have everything we need. pack it out */
  113535. /* mark nontrivial floor */
  113536. oggpack_write(opb,1,1);
  113537. /* beginning/end post */
  113538. look->frames++;
  113539. look->postbits+=ilog(look->quant_q-1)*2;
  113540. oggpack_write(opb,out[0],ilog(look->quant_q-1));
  113541. oggpack_write(opb,out[1],ilog(look->quant_q-1));
  113542. /* partition by partition */
  113543. for(i=0,j=2;i<info->partitions;i++){
  113544. int classx=info->partitionclass[i];
  113545. int cdim=info->class_dim[classx];
  113546. int csubbits=info->class_subs[classx];
  113547. int csub=1<<csubbits;
  113548. int bookas[8]={0,0,0,0,0,0,0,0};
  113549. int cval=0;
  113550. int cshift=0;
  113551. int k,l;
  113552. /* generate the partition's first stage cascade value */
  113553. if(csubbits){
  113554. int maxval[8];
  113555. for(k=0;k<csub;k++){
  113556. int booknum=info->class_subbook[classx][k];
  113557. if(booknum<0){
  113558. maxval[k]=1;
  113559. }else{
  113560. maxval[k]=sbooks[info->class_subbook[classx][k]]->entries;
  113561. }
  113562. }
  113563. for(k=0;k<cdim;k++){
  113564. for(l=0;l<csub;l++){
  113565. int val=out[j+k];
  113566. if(val<maxval[l]){
  113567. bookas[k]=l;
  113568. break;
  113569. }
  113570. }
  113571. cval|= bookas[k]<<cshift;
  113572. cshift+=csubbits;
  113573. }
  113574. /* write it */
  113575. look->phrasebits+=
  113576. vorbis_book_encode(books+info->class_book[classx],cval,opb);
  113577. #ifdef TRAIN_FLOOR1
  113578. {
  113579. FILE *of;
  113580. char buffer[80];
  113581. sprintf(buffer,"line_%dx%ld_class%d.vqd",
  113582. vb->pcmend/2,posts-2,class);
  113583. of=fopen(buffer,"a");
  113584. fprintf(of,"%d\n",cval);
  113585. fclose(of);
  113586. }
  113587. #endif
  113588. }
  113589. /* write post values */
  113590. for(k=0;k<cdim;k++){
  113591. int book=info->class_subbook[classx][bookas[k]];
  113592. if(book>=0){
  113593. /* hack to allow training with 'bad' books */
  113594. if(out[j+k]<(books+book)->entries)
  113595. look->postbits+=vorbis_book_encode(books+book,
  113596. out[j+k],opb);
  113597. /*else
  113598. fprintf(stderr,"+!");*/
  113599. #ifdef TRAIN_FLOOR1
  113600. {
  113601. FILE *of;
  113602. char buffer[80];
  113603. sprintf(buffer,"line_%dx%ld_%dsub%d.vqd",
  113604. vb->pcmend/2,posts-2,class,bookas[k]);
  113605. of=fopen(buffer,"a");
  113606. fprintf(of,"%d\n",out[j+k]);
  113607. fclose(of);
  113608. }
  113609. #endif
  113610. }
  113611. }
  113612. j+=cdim;
  113613. }
  113614. {
  113615. /* generate quantized floor equivalent to what we'd unpack in decode */
  113616. /* render the lines */
  113617. int hx=0;
  113618. int lx=0;
  113619. int ly=post[0]*info->mult;
  113620. for(j=1;j<look->posts;j++){
  113621. int current=look->forward_index[j];
  113622. int hy=post[current]&0x7fff;
  113623. if(hy==post[current]){
  113624. hy*=info->mult;
  113625. hx=info->postlist[current];
  113626. render_line0(lx,hx,ly,hy,ilogmask);
  113627. lx=hx;
  113628. ly=hy;
  113629. }
  113630. }
  113631. for(j=hx;j<vb->pcmend/2;j++)ilogmask[j]=ly; /* be certain */
  113632. seq++;
  113633. return(1);
  113634. }
  113635. }else{
  113636. oggpack_write(opb,0,1);
  113637. memset(ilogmask,0,vb->pcmend/2*sizeof(*ilogmask));
  113638. seq++;
  113639. return(0);
  113640. }
  113641. }
  113642. static void *floor1_inverse1(vorbis_block *vb,vorbis_look_floor *in){
  113643. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  113644. vorbis_info_floor1 *info=look->vi;
  113645. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113646. int i,j,k;
  113647. codebook *books=ci->fullbooks;
  113648. /* unpack wrapped/predicted values from stream */
  113649. if(oggpack_read(&vb->opb,1)==1){
  113650. int *fit_value=(int*)_vorbis_block_alloc(vb,(look->posts)*sizeof(*fit_value));
  113651. fit_value[0]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  113652. fit_value[1]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  113653. /* partition by partition */
  113654. for(i=0,j=2;i<info->partitions;i++){
  113655. int classx=info->partitionclass[i];
  113656. int cdim=info->class_dim[classx];
  113657. int csubbits=info->class_subs[classx];
  113658. int csub=1<<csubbits;
  113659. int cval=0;
  113660. /* decode the partition's first stage cascade value */
  113661. if(csubbits){
  113662. cval=vorbis_book_decode(books+info->class_book[classx],&vb->opb);
  113663. if(cval==-1)goto eop;
  113664. }
  113665. for(k=0;k<cdim;k++){
  113666. int book=info->class_subbook[classx][cval&(csub-1)];
  113667. cval>>=csubbits;
  113668. if(book>=0){
  113669. if((fit_value[j+k]=vorbis_book_decode(books+book,&vb->opb))==-1)
  113670. goto eop;
  113671. }else{
  113672. fit_value[j+k]=0;
  113673. }
  113674. }
  113675. j+=cdim;
  113676. }
  113677. /* unwrap positive values and reconsitute via linear interpolation */
  113678. for(i=2;i<look->posts;i++){
  113679. int predicted=render_point(info->postlist[look->loneighbor[i-2]],
  113680. info->postlist[look->hineighbor[i-2]],
  113681. fit_value[look->loneighbor[i-2]],
  113682. fit_value[look->hineighbor[i-2]],
  113683. info->postlist[i]);
  113684. int hiroom=look->quant_q-predicted;
  113685. int loroom=predicted;
  113686. int room=(hiroom<loroom?hiroom:loroom)<<1;
  113687. int val=fit_value[i];
  113688. if(val){
  113689. if(val>=room){
  113690. if(hiroom>loroom){
  113691. val = val-loroom;
  113692. }else{
  113693. val = -1-(val-hiroom);
  113694. }
  113695. }else{
  113696. if(val&1){
  113697. val= -((val+1)>>1);
  113698. }else{
  113699. val>>=1;
  113700. }
  113701. }
  113702. fit_value[i]=val+predicted;
  113703. fit_value[look->loneighbor[i-2]]&=0x7fff;
  113704. fit_value[look->hineighbor[i-2]]&=0x7fff;
  113705. }else{
  113706. fit_value[i]=predicted|0x8000;
  113707. }
  113708. }
  113709. return(fit_value);
  113710. }
  113711. eop:
  113712. return(NULL);
  113713. }
  113714. static int floor1_inverse2(vorbis_block *vb,vorbis_look_floor *in,void *memo,
  113715. float *out){
  113716. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  113717. vorbis_info_floor1 *info=look->vi;
  113718. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113719. int n=ci->blocksizes[vb->W]/2;
  113720. int j;
  113721. if(memo){
  113722. /* render the lines */
  113723. int *fit_value=(int *)memo;
  113724. int hx=0;
  113725. int lx=0;
  113726. int ly=fit_value[0]*info->mult;
  113727. for(j=1;j<look->posts;j++){
  113728. int current=look->forward_index[j];
  113729. int hy=fit_value[current]&0x7fff;
  113730. if(hy==fit_value[current]){
  113731. hy*=info->mult;
  113732. hx=info->postlist[current];
  113733. render_line(lx,hx,ly,hy,out);
  113734. lx=hx;
  113735. ly=hy;
  113736. }
  113737. }
  113738. for(j=hx;j<n;j++)out[j]*=FLOOR1_fromdB_LOOKUP[ly]; /* be certain */
  113739. return(1);
  113740. }
  113741. memset(out,0,sizeof(*out)*n);
  113742. return(0);
  113743. }
  113744. /* export hooks */
  113745. vorbis_func_floor floor1_exportbundle={
  113746. &floor1_pack,&floor1_unpack,&floor1_look,&floor1_free_info,
  113747. &floor1_free_look,&floor1_inverse1,&floor1_inverse2
  113748. };
  113749. #endif
  113750. /*** End of inlined file: floor1.c ***/
  113751. /*** Start of inlined file: info.c ***/
  113752. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113753. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113754. // tasks..
  113755. #if JUCE_MSVC
  113756. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113757. #endif
  113758. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113759. #if JUCE_USE_OGGVORBIS
  113760. /* general handling of the header and the vorbis_info structure (and
  113761. substructures) */
  113762. #include <stdlib.h>
  113763. #include <string.h>
  113764. #include <ctype.h>
  113765. static void _v_writestring(oggpack_buffer *o, const char *s, int bytes){
  113766. while(bytes--){
  113767. oggpack_write(o,*s++,8);
  113768. }
  113769. }
  113770. static void _v_readstring(oggpack_buffer *o,char *buf,int bytes){
  113771. while(bytes--){
  113772. *buf++=oggpack_read(o,8);
  113773. }
  113774. }
  113775. void vorbis_comment_init(vorbis_comment *vc){
  113776. memset(vc,0,sizeof(*vc));
  113777. }
  113778. void vorbis_comment_add(vorbis_comment *vc,char *comment){
  113779. vc->user_comments=(char**)_ogg_realloc(vc->user_comments,
  113780. (vc->comments+2)*sizeof(*vc->user_comments));
  113781. vc->comment_lengths=(int*)_ogg_realloc(vc->comment_lengths,
  113782. (vc->comments+2)*sizeof(*vc->comment_lengths));
  113783. vc->comment_lengths[vc->comments]=strlen(comment);
  113784. vc->user_comments[vc->comments]=(char*)_ogg_malloc(vc->comment_lengths[vc->comments]+1);
  113785. strcpy(vc->user_comments[vc->comments], comment);
  113786. vc->comments++;
  113787. vc->user_comments[vc->comments]=NULL;
  113788. }
  113789. void vorbis_comment_add_tag(vorbis_comment *vc, const char *tag, char *contents){
  113790. char *comment=(char*)alloca(strlen(tag)+strlen(contents)+2); /* +2 for = and \0 */
  113791. strcpy(comment, tag);
  113792. strcat(comment, "=");
  113793. strcat(comment, contents);
  113794. vorbis_comment_add(vc, comment);
  113795. }
  113796. /* This is more or less the same as strncasecmp - but that doesn't exist
  113797. * everywhere, and this is a fairly trivial function, so we include it */
  113798. static int tagcompare(const char *s1, const char *s2, int n){
  113799. int c=0;
  113800. while(c < n){
  113801. if(toupper(s1[c]) != toupper(s2[c]))
  113802. return !0;
  113803. c++;
  113804. }
  113805. return 0;
  113806. }
  113807. char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count){
  113808. long i;
  113809. int found = 0;
  113810. int taglen = strlen(tag)+1; /* +1 for the = we append */
  113811. char *fulltag = (char*)alloca(taglen+ 1);
  113812. strcpy(fulltag, tag);
  113813. strcat(fulltag, "=");
  113814. for(i=0;i<vc->comments;i++){
  113815. if(!tagcompare(vc->user_comments[i], fulltag, taglen)){
  113816. if(count == found)
  113817. /* We return a pointer to the data, not a copy */
  113818. return vc->user_comments[i] + taglen;
  113819. else
  113820. found++;
  113821. }
  113822. }
  113823. return NULL; /* didn't find anything */
  113824. }
  113825. int vorbis_comment_query_count(vorbis_comment *vc, char *tag){
  113826. int i,count=0;
  113827. int taglen = strlen(tag)+1; /* +1 for the = we append */
  113828. char *fulltag = (char*)alloca(taglen+1);
  113829. strcpy(fulltag,tag);
  113830. strcat(fulltag, "=");
  113831. for(i=0;i<vc->comments;i++){
  113832. if(!tagcompare(vc->user_comments[i], fulltag, taglen))
  113833. count++;
  113834. }
  113835. return count;
  113836. }
  113837. void vorbis_comment_clear(vorbis_comment *vc){
  113838. if(vc){
  113839. long i;
  113840. for(i=0;i<vc->comments;i++)
  113841. if(vc->user_comments[i])_ogg_free(vc->user_comments[i]);
  113842. if(vc->user_comments)_ogg_free(vc->user_comments);
  113843. if(vc->comment_lengths)_ogg_free(vc->comment_lengths);
  113844. if(vc->vendor)_ogg_free(vc->vendor);
  113845. }
  113846. memset(vc,0,sizeof(*vc));
  113847. }
  113848. /* blocksize 0 is guaranteed to be short, 1 is guarantted to be long.
  113849. They may be equal, but short will never ge greater than long */
  113850. int vorbis_info_blocksize(vorbis_info *vi,int zo){
  113851. codec_setup_info *ci = (codec_setup_info*)vi->codec_setup;
  113852. return ci ? ci->blocksizes[zo] : -1;
  113853. }
  113854. /* used by synthesis, which has a full, alloced vi */
  113855. void vorbis_info_init(vorbis_info *vi){
  113856. memset(vi,0,sizeof(*vi));
  113857. vi->codec_setup=_ogg_calloc(1,sizeof(codec_setup_info));
  113858. }
  113859. void vorbis_info_clear(vorbis_info *vi){
  113860. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113861. int i;
  113862. if(ci){
  113863. for(i=0;i<ci->modes;i++)
  113864. if(ci->mode_param[i])_ogg_free(ci->mode_param[i]);
  113865. for(i=0;i<ci->maps;i++) /* unpack does the range checking */
  113866. _mapping_P[ci->map_type[i]]->free_info(ci->map_param[i]);
  113867. for(i=0;i<ci->floors;i++) /* unpack does the range checking */
  113868. _floor_P[ci->floor_type[i]]->free_info(ci->floor_param[i]);
  113869. for(i=0;i<ci->residues;i++) /* unpack does the range checking */
  113870. _residue_P[ci->residue_type[i]]->free_info(ci->residue_param[i]);
  113871. for(i=0;i<ci->books;i++){
  113872. if(ci->book_param[i]){
  113873. /* knows if the book was not alloced */
  113874. vorbis_staticbook_destroy(ci->book_param[i]);
  113875. }
  113876. if(ci->fullbooks)
  113877. vorbis_book_clear(ci->fullbooks+i);
  113878. }
  113879. if(ci->fullbooks)
  113880. _ogg_free(ci->fullbooks);
  113881. for(i=0;i<ci->psys;i++)
  113882. _vi_psy_free(ci->psy_param[i]);
  113883. _ogg_free(ci);
  113884. }
  113885. memset(vi,0,sizeof(*vi));
  113886. }
  113887. /* Header packing/unpacking ********************************************/
  113888. static int _vorbis_unpack_info(vorbis_info *vi,oggpack_buffer *opb){
  113889. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113890. if(!ci)return(OV_EFAULT);
  113891. vi->version=oggpack_read(opb,32);
  113892. if(vi->version!=0)return(OV_EVERSION);
  113893. vi->channels=oggpack_read(opb,8);
  113894. vi->rate=oggpack_read(opb,32);
  113895. vi->bitrate_upper=oggpack_read(opb,32);
  113896. vi->bitrate_nominal=oggpack_read(opb,32);
  113897. vi->bitrate_lower=oggpack_read(opb,32);
  113898. ci->blocksizes[0]=1<<oggpack_read(opb,4);
  113899. ci->blocksizes[1]=1<<oggpack_read(opb,4);
  113900. if(vi->rate<1)goto err_out;
  113901. if(vi->channels<1)goto err_out;
  113902. if(ci->blocksizes[0]<8)goto err_out;
  113903. if(ci->blocksizes[1]<ci->blocksizes[0])goto err_out;
  113904. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  113905. return(0);
  113906. err_out:
  113907. vorbis_info_clear(vi);
  113908. return(OV_EBADHEADER);
  113909. }
  113910. static int _vorbis_unpack_comment(vorbis_comment *vc,oggpack_buffer *opb){
  113911. int i;
  113912. int vendorlen=oggpack_read(opb,32);
  113913. if(vendorlen<0)goto err_out;
  113914. vc->vendor=(char*)_ogg_calloc(vendorlen+1,1);
  113915. _v_readstring(opb,vc->vendor,vendorlen);
  113916. vc->comments=oggpack_read(opb,32);
  113917. if(vc->comments<0)goto err_out;
  113918. vc->user_comments=(char**)_ogg_calloc(vc->comments+1,sizeof(*vc->user_comments));
  113919. vc->comment_lengths=(int*)_ogg_calloc(vc->comments+1, sizeof(*vc->comment_lengths));
  113920. for(i=0;i<vc->comments;i++){
  113921. int len=oggpack_read(opb,32);
  113922. if(len<0)goto err_out;
  113923. vc->comment_lengths[i]=len;
  113924. vc->user_comments[i]=(char*)_ogg_calloc(len+1,1);
  113925. _v_readstring(opb,vc->user_comments[i],len);
  113926. }
  113927. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  113928. return(0);
  113929. err_out:
  113930. vorbis_comment_clear(vc);
  113931. return(OV_EBADHEADER);
  113932. }
  113933. /* all of the real encoding details are here. The modes, books,
  113934. everything */
  113935. static int _vorbis_unpack_books(vorbis_info *vi,oggpack_buffer *opb){
  113936. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113937. int i;
  113938. if(!ci)return(OV_EFAULT);
  113939. /* codebooks */
  113940. ci->books=oggpack_read(opb,8)+1;
  113941. /*ci->book_param=_ogg_calloc(ci->books,sizeof(*ci->book_param));*/
  113942. for(i=0;i<ci->books;i++){
  113943. ci->book_param[i]=(static_codebook*)_ogg_calloc(1,sizeof(*ci->book_param[i]));
  113944. if(vorbis_staticbook_unpack(opb,ci->book_param[i]))goto err_out;
  113945. }
  113946. /* time backend settings; hooks are unused */
  113947. {
  113948. int times=oggpack_read(opb,6)+1;
  113949. for(i=0;i<times;i++){
  113950. int test=oggpack_read(opb,16);
  113951. if(test<0 || test>=VI_TIMEB)goto err_out;
  113952. }
  113953. }
  113954. /* floor backend settings */
  113955. ci->floors=oggpack_read(opb,6)+1;
  113956. /*ci->floor_type=_ogg_malloc(ci->floors*sizeof(*ci->floor_type));*/
  113957. /*ci->floor_param=_ogg_calloc(ci->floors,sizeof(void *));*/
  113958. for(i=0;i<ci->floors;i++){
  113959. ci->floor_type[i]=oggpack_read(opb,16);
  113960. if(ci->floor_type[i]<0 || ci->floor_type[i]>=VI_FLOORB)goto err_out;
  113961. ci->floor_param[i]=_floor_P[ci->floor_type[i]]->unpack(vi,opb);
  113962. if(!ci->floor_param[i])goto err_out;
  113963. }
  113964. /* residue backend settings */
  113965. ci->residues=oggpack_read(opb,6)+1;
  113966. /*ci->residue_type=_ogg_malloc(ci->residues*sizeof(*ci->residue_type));*/
  113967. /*ci->residue_param=_ogg_calloc(ci->residues,sizeof(void *));*/
  113968. for(i=0;i<ci->residues;i++){
  113969. ci->residue_type[i]=oggpack_read(opb,16);
  113970. if(ci->residue_type[i]<0 || ci->residue_type[i]>=VI_RESB)goto err_out;
  113971. ci->residue_param[i]=_residue_P[ci->residue_type[i]]->unpack(vi,opb);
  113972. if(!ci->residue_param[i])goto err_out;
  113973. }
  113974. /* map backend settings */
  113975. ci->maps=oggpack_read(opb,6)+1;
  113976. /*ci->map_type=_ogg_malloc(ci->maps*sizeof(*ci->map_type));*/
  113977. /*ci->map_param=_ogg_calloc(ci->maps,sizeof(void *));*/
  113978. for(i=0;i<ci->maps;i++){
  113979. ci->map_type[i]=oggpack_read(opb,16);
  113980. if(ci->map_type[i]<0 || ci->map_type[i]>=VI_MAPB)goto err_out;
  113981. ci->map_param[i]=_mapping_P[ci->map_type[i]]->unpack(vi,opb);
  113982. if(!ci->map_param[i])goto err_out;
  113983. }
  113984. /* mode settings */
  113985. ci->modes=oggpack_read(opb,6)+1;
  113986. /*vi->mode_param=_ogg_calloc(vi->modes,sizeof(void *));*/
  113987. for(i=0;i<ci->modes;i++){
  113988. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*ci->mode_param[i]));
  113989. ci->mode_param[i]->blockflag=oggpack_read(opb,1);
  113990. ci->mode_param[i]->windowtype=oggpack_read(opb,16);
  113991. ci->mode_param[i]->transformtype=oggpack_read(opb,16);
  113992. ci->mode_param[i]->mapping=oggpack_read(opb,8);
  113993. if(ci->mode_param[i]->windowtype>=VI_WINDOWB)goto err_out;
  113994. if(ci->mode_param[i]->transformtype>=VI_WINDOWB)goto err_out;
  113995. if(ci->mode_param[i]->mapping>=ci->maps)goto err_out;
  113996. }
  113997. if(oggpack_read(opb,1)!=1)goto err_out; /* top level EOP check */
  113998. return(0);
  113999. err_out:
  114000. vorbis_info_clear(vi);
  114001. return(OV_EBADHEADER);
  114002. }
  114003. /* The Vorbis header is in three packets; the initial small packet in
  114004. the first page that identifies basic parameters, a second packet
  114005. with bitstream comments and a third packet that holds the
  114006. codebook. */
  114007. int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,ogg_packet *op){
  114008. oggpack_buffer opb;
  114009. if(op){
  114010. oggpack_readinit(&opb,op->packet,op->bytes);
  114011. /* Which of the three types of header is this? */
  114012. /* Also verify header-ness, vorbis */
  114013. {
  114014. char buffer[6];
  114015. int packtype=oggpack_read(&opb,8);
  114016. memset(buffer,0,6);
  114017. _v_readstring(&opb,buffer,6);
  114018. if(memcmp(buffer,"vorbis",6)){
  114019. /* not a vorbis header */
  114020. return(OV_ENOTVORBIS);
  114021. }
  114022. switch(packtype){
  114023. case 0x01: /* least significant *bit* is read first */
  114024. if(!op->b_o_s){
  114025. /* Not the initial packet */
  114026. return(OV_EBADHEADER);
  114027. }
  114028. if(vi->rate!=0){
  114029. /* previously initialized info header */
  114030. return(OV_EBADHEADER);
  114031. }
  114032. return(_vorbis_unpack_info(vi,&opb));
  114033. case 0x03: /* least significant *bit* is read first */
  114034. if(vi->rate==0){
  114035. /* um... we didn't get the initial header */
  114036. return(OV_EBADHEADER);
  114037. }
  114038. return(_vorbis_unpack_comment(vc,&opb));
  114039. case 0x05: /* least significant *bit* is read first */
  114040. if(vi->rate==0 || vc->vendor==NULL){
  114041. /* um... we didn;t get the initial header or comments yet */
  114042. return(OV_EBADHEADER);
  114043. }
  114044. return(_vorbis_unpack_books(vi,&opb));
  114045. default:
  114046. /* Not a valid vorbis header type */
  114047. return(OV_EBADHEADER);
  114048. break;
  114049. }
  114050. }
  114051. }
  114052. return(OV_EBADHEADER);
  114053. }
  114054. /* pack side **********************************************************/
  114055. static int _vorbis_pack_info(oggpack_buffer *opb,vorbis_info *vi){
  114056. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114057. if(!ci)return(OV_EFAULT);
  114058. /* preamble */
  114059. oggpack_write(opb,0x01,8);
  114060. _v_writestring(opb,"vorbis", 6);
  114061. /* basic information about the stream */
  114062. oggpack_write(opb,0x00,32);
  114063. oggpack_write(opb,vi->channels,8);
  114064. oggpack_write(opb,vi->rate,32);
  114065. oggpack_write(opb,vi->bitrate_upper,32);
  114066. oggpack_write(opb,vi->bitrate_nominal,32);
  114067. oggpack_write(opb,vi->bitrate_lower,32);
  114068. oggpack_write(opb,ilog2(ci->blocksizes[0]),4);
  114069. oggpack_write(opb,ilog2(ci->blocksizes[1]),4);
  114070. oggpack_write(opb,1,1);
  114071. return(0);
  114072. }
  114073. static int _vorbis_pack_comment(oggpack_buffer *opb,vorbis_comment *vc){
  114074. char temp[]="Xiph.Org libVorbis I 20050304";
  114075. int bytes = strlen(temp);
  114076. /* preamble */
  114077. oggpack_write(opb,0x03,8);
  114078. _v_writestring(opb,"vorbis", 6);
  114079. /* vendor */
  114080. oggpack_write(opb,bytes,32);
  114081. _v_writestring(opb,temp, bytes);
  114082. /* comments */
  114083. oggpack_write(opb,vc->comments,32);
  114084. if(vc->comments){
  114085. int i;
  114086. for(i=0;i<vc->comments;i++){
  114087. if(vc->user_comments[i]){
  114088. oggpack_write(opb,vc->comment_lengths[i],32);
  114089. _v_writestring(opb,vc->user_comments[i], vc->comment_lengths[i]);
  114090. }else{
  114091. oggpack_write(opb,0,32);
  114092. }
  114093. }
  114094. }
  114095. oggpack_write(opb,1,1);
  114096. return(0);
  114097. }
  114098. static int _vorbis_pack_books(oggpack_buffer *opb,vorbis_info *vi){
  114099. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114100. int i;
  114101. if(!ci)return(OV_EFAULT);
  114102. oggpack_write(opb,0x05,8);
  114103. _v_writestring(opb,"vorbis", 6);
  114104. /* books */
  114105. oggpack_write(opb,ci->books-1,8);
  114106. for(i=0;i<ci->books;i++)
  114107. if(vorbis_staticbook_pack(ci->book_param[i],opb))goto err_out;
  114108. /* times; hook placeholders */
  114109. oggpack_write(opb,0,6);
  114110. oggpack_write(opb,0,16);
  114111. /* floors */
  114112. oggpack_write(opb,ci->floors-1,6);
  114113. for(i=0;i<ci->floors;i++){
  114114. oggpack_write(opb,ci->floor_type[i],16);
  114115. if(_floor_P[ci->floor_type[i]]->pack)
  114116. _floor_P[ci->floor_type[i]]->pack(ci->floor_param[i],opb);
  114117. else
  114118. goto err_out;
  114119. }
  114120. /* residues */
  114121. oggpack_write(opb,ci->residues-1,6);
  114122. for(i=0;i<ci->residues;i++){
  114123. oggpack_write(opb,ci->residue_type[i],16);
  114124. _residue_P[ci->residue_type[i]]->pack(ci->residue_param[i],opb);
  114125. }
  114126. /* maps */
  114127. oggpack_write(opb,ci->maps-1,6);
  114128. for(i=0;i<ci->maps;i++){
  114129. oggpack_write(opb,ci->map_type[i],16);
  114130. _mapping_P[ci->map_type[i]]->pack(vi,ci->map_param[i],opb);
  114131. }
  114132. /* modes */
  114133. oggpack_write(opb,ci->modes-1,6);
  114134. for(i=0;i<ci->modes;i++){
  114135. oggpack_write(opb,ci->mode_param[i]->blockflag,1);
  114136. oggpack_write(opb,ci->mode_param[i]->windowtype,16);
  114137. oggpack_write(opb,ci->mode_param[i]->transformtype,16);
  114138. oggpack_write(opb,ci->mode_param[i]->mapping,8);
  114139. }
  114140. oggpack_write(opb,1,1);
  114141. return(0);
  114142. err_out:
  114143. return(-1);
  114144. }
  114145. int vorbis_commentheader_out(vorbis_comment *vc,
  114146. ogg_packet *op){
  114147. oggpack_buffer opb;
  114148. oggpack_writeinit(&opb);
  114149. if(_vorbis_pack_comment(&opb,vc)) return OV_EIMPL;
  114150. op->packet = (unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114151. memcpy(op->packet, opb.buffer, oggpack_bytes(&opb));
  114152. op->bytes=oggpack_bytes(&opb);
  114153. op->b_o_s=0;
  114154. op->e_o_s=0;
  114155. op->granulepos=0;
  114156. op->packetno=1;
  114157. return 0;
  114158. }
  114159. int vorbis_analysis_headerout(vorbis_dsp_state *v,
  114160. vorbis_comment *vc,
  114161. ogg_packet *op,
  114162. ogg_packet *op_comm,
  114163. ogg_packet *op_code){
  114164. int ret=OV_EIMPL;
  114165. vorbis_info *vi=v->vi;
  114166. oggpack_buffer opb;
  114167. private_state *b=(private_state*)v->backend_state;
  114168. if(!b){
  114169. ret=OV_EFAULT;
  114170. goto err_out;
  114171. }
  114172. /* first header packet **********************************************/
  114173. oggpack_writeinit(&opb);
  114174. if(_vorbis_pack_info(&opb,vi))goto err_out;
  114175. /* build the packet */
  114176. if(b->header)_ogg_free(b->header);
  114177. b->header=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114178. memcpy(b->header,opb.buffer,oggpack_bytes(&opb));
  114179. op->packet=b->header;
  114180. op->bytes=oggpack_bytes(&opb);
  114181. op->b_o_s=1;
  114182. op->e_o_s=0;
  114183. op->granulepos=0;
  114184. op->packetno=0;
  114185. /* second header packet (comments) **********************************/
  114186. oggpack_reset(&opb);
  114187. if(_vorbis_pack_comment(&opb,vc))goto err_out;
  114188. if(b->header1)_ogg_free(b->header1);
  114189. b->header1=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114190. memcpy(b->header1,opb.buffer,oggpack_bytes(&opb));
  114191. op_comm->packet=b->header1;
  114192. op_comm->bytes=oggpack_bytes(&opb);
  114193. op_comm->b_o_s=0;
  114194. op_comm->e_o_s=0;
  114195. op_comm->granulepos=0;
  114196. op_comm->packetno=1;
  114197. /* third header packet (modes/codebooks) ****************************/
  114198. oggpack_reset(&opb);
  114199. if(_vorbis_pack_books(&opb,vi))goto err_out;
  114200. if(b->header2)_ogg_free(b->header2);
  114201. b->header2=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114202. memcpy(b->header2,opb.buffer,oggpack_bytes(&opb));
  114203. op_code->packet=b->header2;
  114204. op_code->bytes=oggpack_bytes(&opb);
  114205. op_code->b_o_s=0;
  114206. op_code->e_o_s=0;
  114207. op_code->granulepos=0;
  114208. op_code->packetno=2;
  114209. oggpack_writeclear(&opb);
  114210. return(0);
  114211. err_out:
  114212. oggpack_writeclear(&opb);
  114213. memset(op,0,sizeof(*op));
  114214. memset(op_comm,0,sizeof(*op_comm));
  114215. memset(op_code,0,sizeof(*op_code));
  114216. if(b->header)_ogg_free(b->header);
  114217. if(b->header1)_ogg_free(b->header1);
  114218. if(b->header2)_ogg_free(b->header2);
  114219. b->header=NULL;
  114220. b->header1=NULL;
  114221. b->header2=NULL;
  114222. return(ret);
  114223. }
  114224. double vorbis_granule_time(vorbis_dsp_state *v,ogg_int64_t granulepos){
  114225. if(granulepos>=0)
  114226. return((double)granulepos/v->vi->rate);
  114227. return(-1);
  114228. }
  114229. #endif
  114230. /*** End of inlined file: info.c ***/
  114231. /*** Start of inlined file: lpc.c ***/
  114232. /* Some of these routines (autocorrelator, LPC coefficient estimator)
  114233. are derived from code written by Jutta Degener and Carsten Bormann;
  114234. thus we include their copyright below. The entirety of this file
  114235. is freely redistributable on the condition that both of these
  114236. copyright notices are preserved without modification. */
  114237. /* Preserved Copyright: *********************************************/
  114238. /* Copyright 1992, 1993, 1994 by Jutta Degener and Carsten Bormann,
  114239. Technische Universita"t Berlin
  114240. Any use of this software is permitted provided that this notice is not
  114241. removed and that neither the authors nor the Technische Universita"t
  114242. Berlin are deemed to have made any representations as to the
  114243. suitability of this software for any purpose nor are held responsible
  114244. for any defects of this software. THERE IS ABSOLUTELY NO WARRANTY FOR
  114245. THIS SOFTWARE.
  114246. As a matter of courtesy, the authors request to be informed about uses
  114247. this software has found, about bugs in this software, and about any
  114248. improvements that may be of general interest.
  114249. Berlin, 28.11.1994
  114250. Jutta Degener
  114251. Carsten Bormann
  114252. *********************************************************************/
  114253. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114254. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114255. // tasks..
  114256. #if JUCE_MSVC
  114257. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114258. #endif
  114259. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114260. #if JUCE_USE_OGGVORBIS
  114261. #include <stdlib.h>
  114262. #include <string.h>
  114263. #include <math.h>
  114264. /* Autocorrelation LPC coeff generation algorithm invented by
  114265. N. Levinson in 1947, modified by J. Durbin in 1959. */
  114266. /* Input : n elements of time doamin data
  114267. Output: m lpc coefficients, excitation energy */
  114268. float vorbis_lpc_from_data(float *data,float *lpci,int n,int m){
  114269. double *aut=(double*)alloca(sizeof(*aut)*(m+1));
  114270. double *lpc=(double*)alloca(sizeof(*lpc)*(m));
  114271. double error;
  114272. int i,j;
  114273. /* autocorrelation, p+1 lag coefficients */
  114274. j=m+1;
  114275. while(j--){
  114276. double d=0; /* double needed for accumulator depth */
  114277. for(i=j;i<n;i++)d+=(double)data[i]*data[i-j];
  114278. aut[j]=d;
  114279. }
  114280. /* Generate lpc coefficients from autocorr values */
  114281. error=aut[0];
  114282. for(i=0;i<m;i++){
  114283. double r= -aut[i+1];
  114284. if(error==0){
  114285. memset(lpci,0,m*sizeof(*lpci));
  114286. return 0;
  114287. }
  114288. /* Sum up this iteration's reflection coefficient; note that in
  114289. Vorbis we don't save it. If anyone wants to recycle this code
  114290. and needs reflection coefficients, save the results of 'r' from
  114291. each iteration. */
  114292. for(j=0;j<i;j++)r-=lpc[j]*aut[i-j];
  114293. r/=error;
  114294. /* Update LPC coefficients and total error */
  114295. lpc[i]=r;
  114296. for(j=0;j<i/2;j++){
  114297. double tmp=lpc[j];
  114298. lpc[j]+=r*lpc[i-1-j];
  114299. lpc[i-1-j]+=r*tmp;
  114300. }
  114301. if(i%2)lpc[j]+=lpc[j]*r;
  114302. error*=1.f-r*r;
  114303. }
  114304. for(j=0;j<m;j++)lpci[j]=(float)lpc[j];
  114305. /* we need the error value to know how big an impulse to hit the
  114306. filter with later */
  114307. return error;
  114308. }
  114309. void vorbis_lpc_predict(float *coeff,float *prime,int m,
  114310. float *data,long n){
  114311. /* in: coeff[0...m-1] LPC coefficients
  114312. prime[0...m-1] initial values (allocated size of n+m-1)
  114313. out: data[0...n-1] data samples */
  114314. long i,j,o,p;
  114315. float y;
  114316. float *work=(float*)alloca(sizeof(*work)*(m+n));
  114317. if(!prime)
  114318. for(i=0;i<m;i++)
  114319. work[i]=0.f;
  114320. else
  114321. for(i=0;i<m;i++)
  114322. work[i]=prime[i];
  114323. for(i=0;i<n;i++){
  114324. y=0;
  114325. o=i;
  114326. p=m;
  114327. for(j=0;j<m;j++)
  114328. y-=work[o++]*coeff[--p];
  114329. data[i]=work[o]=y;
  114330. }
  114331. }
  114332. #endif
  114333. /*** End of inlined file: lpc.c ***/
  114334. /*** Start of inlined file: lsp.c ***/
  114335. /* Note that the lpc-lsp conversion finds the roots of polynomial with
  114336. an iterative root polisher (CACM algorithm 283). It *is* possible
  114337. to confuse this algorithm into not converging; that should only
  114338. happen with absurdly closely spaced roots (very sharp peaks in the
  114339. LPC f response) which in turn should be impossible in our use of
  114340. the code. If this *does* happen anyway, it's a bug in the floor
  114341. finder; find the cause of the confusion (probably a single bin
  114342. spike or accidental near-float-limit resolution problems) and
  114343. correct it. */
  114344. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114345. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114346. // tasks..
  114347. #if JUCE_MSVC
  114348. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114349. #endif
  114350. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114351. #if JUCE_USE_OGGVORBIS
  114352. #include <math.h>
  114353. #include <string.h>
  114354. #include <stdlib.h>
  114355. /*** Start of inlined file: lookup.h ***/
  114356. #ifndef _V_LOOKUP_H_
  114357. #ifdef FLOAT_LOOKUP
  114358. extern float vorbis_coslook(float a);
  114359. extern float vorbis_invsqlook(float a);
  114360. extern float vorbis_invsq2explook(int a);
  114361. extern float vorbis_fromdBlook(float a);
  114362. #endif
  114363. #ifdef INT_LOOKUP
  114364. extern long vorbis_invsqlook_i(long a,long e);
  114365. extern long vorbis_coslook_i(long a);
  114366. extern float vorbis_fromdBlook_i(long a);
  114367. #endif
  114368. #endif
  114369. /*** End of inlined file: lookup.h ***/
  114370. /* three possible LSP to f curve functions; the exact computation
  114371. (float), a lookup based float implementation, and an integer
  114372. implementation. The float lookup is likely the optimal choice on
  114373. any machine with an FPU. The integer implementation is *not* fixed
  114374. point (due to the need for a large dynamic range and thus a
  114375. seperately tracked exponent) and thus much more complex than the
  114376. relatively simple float implementations. It's mostly for future
  114377. work on a fully fixed point implementation for processors like the
  114378. ARM family. */
  114379. /* undefine both for the 'old' but more precise implementation */
  114380. #define FLOAT_LOOKUP
  114381. #undef INT_LOOKUP
  114382. #ifdef FLOAT_LOOKUP
  114383. /*** Start of inlined file: lookup.c ***/
  114384. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114385. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114386. // tasks..
  114387. #if JUCE_MSVC
  114388. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114389. #endif
  114390. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114391. #if JUCE_USE_OGGVORBIS
  114392. #include <math.h>
  114393. /*** Start of inlined file: lookup.h ***/
  114394. #ifndef _V_LOOKUP_H_
  114395. #ifdef FLOAT_LOOKUP
  114396. extern float vorbis_coslook(float a);
  114397. extern float vorbis_invsqlook(float a);
  114398. extern float vorbis_invsq2explook(int a);
  114399. extern float vorbis_fromdBlook(float a);
  114400. #endif
  114401. #ifdef INT_LOOKUP
  114402. extern long vorbis_invsqlook_i(long a,long e);
  114403. extern long vorbis_coslook_i(long a);
  114404. extern float vorbis_fromdBlook_i(long a);
  114405. #endif
  114406. #endif
  114407. /*** End of inlined file: lookup.h ***/
  114408. /*** Start of inlined file: lookup_data.h ***/
  114409. #ifndef _V_LOOKUP_DATA_H_
  114410. #ifdef FLOAT_LOOKUP
  114411. #define COS_LOOKUP_SZ 128
  114412. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  114413. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  114414. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  114415. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  114416. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  114417. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  114418. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  114419. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  114420. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  114421. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  114422. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  114423. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  114424. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  114425. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  114426. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  114427. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  114428. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  114429. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  114430. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  114431. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  114432. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  114433. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  114434. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  114435. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  114436. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  114437. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  114438. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  114439. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  114440. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  114441. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  114442. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  114443. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  114444. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  114445. -1.0000000000000f,
  114446. };
  114447. #define INVSQ_LOOKUP_SZ 32
  114448. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  114449. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  114450. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  114451. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  114452. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  114453. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  114454. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  114455. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  114456. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  114457. 1.000000000000f,
  114458. };
  114459. #define INVSQ2EXP_LOOKUP_MIN (-32)
  114460. #define INVSQ2EXP_LOOKUP_MAX 32
  114461. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  114462. INVSQ2EXP_LOOKUP_MIN+1]={
  114463. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  114464. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  114465. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  114466. 1024.f, 724.0773439f, 512.f, 362.038672f,
  114467. 256.f, 181.019336f, 128.f, 90.50966799f,
  114468. 64.f, 45.254834f, 32.f, 22.627417f,
  114469. 16.f, 11.3137085f, 8.f, 5.656854249f,
  114470. 4.f, 2.828427125f, 2.f, 1.414213562f,
  114471. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  114472. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  114473. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  114474. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  114475. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  114476. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  114477. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  114478. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  114479. 1.525878906e-05f,
  114480. };
  114481. #endif
  114482. #define FROMdB_LOOKUP_SZ 35
  114483. #define FROMdB2_LOOKUP_SZ 32
  114484. #define FROMdB_SHIFT 5
  114485. #define FROMdB2_SHIFT 3
  114486. #define FROMdB2_MASK 31
  114487. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  114488. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  114489. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  114490. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  114491. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  114492. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  114493. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  114494. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  114495. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  114496. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  114497. };
  114498. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  114499. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  114500. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  114501. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  114502. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  114503. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  114504. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  114505. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  114506. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  114507. };
  114508. #ifdef INT_LOOKUP
  114509. #define INVSQ_LOOKUP_I_SHIFT 10
  114510. #define INVSQ_LOOKUP_I_MASK 1023
  114511. static long INVSQ_LOOKUP_I[64+1]={
  114512. 92682l, 91966l, 91267l, 90583l,
  114513. 89915l, 89261l, 88621l, 87995l,
  114514. 87381l, 86781l, 86192l, 85616l,
  114515. 85051l, 84497l, 83953l, 83420l,
  114516. 82897l, 82384l, 81880l, 81385l,
  114517. 80899l, 80422l, 79953l, 79492l,
  114518. 79039l, 78594l, 78156l, 77726l,
  114519. 77302l, 76885l, 76475l, 76072l,
  114520. 75674l, 75283l, 74898l, 74519l,
  114521. 74146l, 73778l, 73415l, 73058l,
  114522. 72706l, 72359l, 72016l, 71679l,
  114523. 71347l, 71019l, 70695l, 70376l,
  114524. 70061l, 69750l, 69444l, 69141l,
  114525. 68842l, 68548l, 68256l, 67969l,
  114526. 67685l, 67405l, 67128l, 66855l,
  114527. 66585l, 66318l, 66054l, 65794l,
  114528. 65536l,
  114529. };
  114530. #define COS_LOOKUP_I_SHIFT 9
  114531. #define COS_LOOKUP_I_MASK 511
  114532. #define COS_LOOKUP_I_SZ 128
  114533. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  114534. 16384l, 16379l, 16364l, 16340l,
  114535. 16305l, 16261l, 16207l, 16143l,
  114536. 16069l, 15986l, 15893l, 15791l,
  114537. 15679l, 15557l, 15426l, 15286l,
  114538. 15137l, 14978l, 14811l, 14635l,
  114539. 14449l, 14256l, 14053l, 13842l,
  114540. 13623l, 13395l, 13160l, 12916l,
  114541. 12665l, 12406l, 12140l, 11866l,
  114542. 11585l, 11297l, 11003l, 10702l,
  114543. 10394l, 10080l, 9760l, 9434l,
  114544. 9102l, 8765l, 8423l, 8076l,
  114545. 7723l, 7366l, 7005l, 6639l,
  114546. 6270l, 5897l, 5520l, 5139l,
  114547. 4756l, 4370l, 3981l, 3590l,
  114548. 3196l, 2801l, 2404l, 2006l,
  114549. 1606l, 1205l, 804l, 402l,
  114550. 0l, -401l, -803l, -1204l,
  114551. -1605l, -2005l, -2403l, -2800l,
  114552. -3195l, -3589l, -3980l, -4369l,
  114553. -4755l, -5138l, -5519l, -5896l,
  114554. -6269l, -6638l, -7004l, -7365l,
  114555. -7722l, -8075l, -8422l, -8764l,
  114556. -9101l, -9433l, -9759l, -10079l,
  114557. -10393l, -10701l, -11002l, -11296l,
  114558. -11584l, -11865l, -12139l, -12405l,
  114559. -12664l, -12915l, -13159l, -13394l,
  114560. -13622l, -13841l, -14052l, -14255l,
  114561. -14448l, -14634l, -14810l, -14977l,
  114562. -15136l, -15285l, -15425l, -15556l,
  114563. -15678l, -15790l, -15892l, -15985l,
  114564. -16068l, -16142l, -16206l, -16260l,
  114565. -16304l, -16339l, -16363l, -16378l,
  114566. -16383l,
  114567. };
  114568. #endif
  114569. #endif
  114570. /*** End of inlined file: lookup_data.h ***/
  114571. #ifdef FLOAT_LOOKUP
  114572. /* interpolated lookup based cos function, domain 0 to PI only */
  114573. float vorbis_coslook(float a){
  114574. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  114575. int i=vorbis_ftoi(d-.5);
  114576. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  114577. }
  114578. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114579. float vorbis_invsqlook(float a){
  114580. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  114581. int i=vorbis_ftoi(d-.5f);
  114582. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  114583. }
  114584. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114585. float vorbis_invsq2explook(int a){
  114586. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  114587. }
  114588. #include <stdio.h>
  114589. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114590. float vorbis_fromdBlook(float a){
  114591. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  114592. return (i<0)?1.f:
  114593. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114594. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114595. }
  114596. #endif
  114597. #ifdef INT_LOOKUP
  114598. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  114599. 16.16 format
  114600. returns in m.8 format */
  114601. long vorbis_invsqlook_i(long a,long e){
  114602. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  114603. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  114604. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  114605. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  114606. d)>>16); /* result 1.16 */
  114607. e+=32;
  114608. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  114609. e=(e>>1)-8;
  114610. return(val>>e);
  114611. }
  114612. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114613. /* a is in n.12 format */
  114614. float vorbis_fromdBlook_i(long a){
  114615. int i=(-a)>>(12-FROMdB2_SHIFT);
  114616. return (i<0)?1.f:
  114617. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114618. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114619. }
  114620. /* interpolated lookup based cos function, domain 0 to PI only */
  114621. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  114622. long vorbis_coslook_i(long a){
  114623. int i=a>>COS_LOOKUP_I_SHIFT;
  114624. int d=a&COS_LOOKUP_I_MASK;
  114625. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  114626. COS_LOOKUP_I_SHIFT);
  114627. }
  114628. #endif
  114629. #endif
  114630. /*** End of inlined file: lookup.c ***/
  114631. /* catch this in the build system; we #include for
  114632. compilers (like gcc) that can't inline across
  114633. modules */
  114634. /* side effect: changes *lsp to cosines of lsp */
  114635. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114636. float amp,float ampoffset){
  114637. int i;
  114638. float wdel=M_PI/ln;
  114639. vorbis_fpu_control fpu;
  114640. (void) fpu; // to avoid an unused variable warning
  114641. vorbis_fpu_setround(&fpu);
  114642. for(i=0;i<m;i++)lsp[i]=vorbis_coslook(lsp[i]);
  114643. i=0;
  114644. while(i<n){
  114645. int k=map[i];
  114646. int qexp;
  114647. float p=.7071067812f;
  114648. float q=.7071067812f;
  114649. float w=vorbis_coslook(wdel*k);
  114650. float *ftmp=lsp;
  114651. int c=m>>1;
  114652. do{
  114653. q*=ftmp[0]-w;
  114654. p*=ftmp[1]-w;
  114655. ftmp+=2;
  114656. }while(--c);
  114657. if(m&1){
  114658. /* odd order filter; slightly assymetric */
  114659. /* the last coefficient */
  114660. q*=ftmp[0]-w;
  114661. q*=q;
  114662. p*=p*(1.f-w*w);
  114663. }else{
  114664. /* even order filter; still symmetric */
  114665. q*=q*(1.f+w);
  114666. p*=p*(1.f-w);
  114667. }
  114668. q=frexp(p+q,&qexp);
  114669. q=vorbis_fromdBlook(amp*
  114670. vorbis_invsqlook(q)*
  114671. vorbis_invsq2explook(qexp+m)-
  114672. ampoffset);
  114673. do{
  114674. curve[i++]*=q;
  114675. }while(map[i]==k);
  114676. }
  114677. vorbis_fpu_restore(fpu);
  114678. }
  114679. #else
  114680. #ifdef INT_LOOKUP
  114681. /*** Start of inlined file: lookup.c ***/
  114682. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114683. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114684. // tasks..
  114685. #if JUCE_MSVC
  114686. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114687. #endif
  114688. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114689. #if JUCE_USE_OGGVORBIS
  114690. #include <math.h>
  114691. /*** Start of inlined file: lookup.h ***/
  114692. #ifndef _V_LOOKUP_H_
  114693. #ifdef FLOAT_LOOKUP
  114694. extern float vorbis_coslook(float a);
  114695. extern float vorbis_invsqlook(float a);
  114696. extern float vorbis_invsq2explook(int a);
  114697. extern float vorbis_fromdBlook(float a);
  114698. #endif
  114699. #ifdef INT_LOOKUP
  114700. extern long vorbis_invsqlook_i(long a,long e);
  114701. extern long vorbis_coslook_i(long a);
  114702. extern float vorbis_fromdBlook_i(long a);
  114703. #endif
  114704. #endif
  114705. /*** End of inlined file: lookup.h ***/
  114706. /*** Start of inlined file: lookup_data.h ***/
  114707. #ifndef _V_LOOKUP_DATA_H_
  114708. #ifdef FLOAT_LOOKUP
  114709. #define COS_LOOKUP_SZ 128
  114710. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  114711. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  114712. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  114713. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  114714. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  114715. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  114716. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  114717. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  114718. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  114719. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  114720. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  114721. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  114722. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  114723. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  114724. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  114725. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  114726. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  114727. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  114728. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  114729. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  114730. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  114731. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  114732. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  114733. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  114734. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  114735. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  114736. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  114737. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  114738. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  114739. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  114740. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  114741. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  114742. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  114743. -1.0000000000000f,
  114744. };
  114745. #define INVSQ_LOOKUP_SZ 32
  114746. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  114747. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  114748. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  114749. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  114750. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  114751. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  114752. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  114753. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  114754. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  114755. 1.000000000000f,
  114756. };
  114757. #define INVSQ2EXP_LOOKUP_MIN (-32)
  114758. #define INVSQ2EXP_LOOKUP_MAX 32
  114759. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  114760. INVSQ2EXP_LOOKUP_MIN+1]={
  114761. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  114762. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  114763. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  114764. 1024.f, 724.0773439f, 512.f, 362.038672f,
  114765. 256.f, 181.019336f, 128.f, 90.50966799f,
  114766. 64.f, 45.254834f, 32.f, 22.627417f,
  114767. 16.f, 11.3137085f, 8.f, 5.656854249f,
  114768. 4.f, 2.828427125f, 2.f, 1.414213562f,
  114769. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  114770. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  114771. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  114772. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  114773. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  114774. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  114775. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  114776. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  114777. 1.525878906e-05f,
  114778. };
  114779. #endif
  114780. #define FROMdB_LOOKUP_SZ 35
  114781. #define FROMdB2_LOOKUP_SZ 32
  114782. #define FROMdB_SHIFT 5
  114783. #define FROMdB2_SHIFT 3
  114784. #define FROMdB2_MASK 31
  114785. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  114786. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  114787. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  114788. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  114789. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  114790. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  114791. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  114792. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  114793. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  114794. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  114795. };
  114796. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  114797. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  114798. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  114799. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  114800. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  114801. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  114802. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  114803. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  114804. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  114805. };
  114806. #ifdef INT_LOOKUP
  114807. #define INVSQ_LOOKUP_I_SHIFT 10
  114808. #define INVSQ_LOOKUP_I_MASK 1023
  114809. static long INVSQ_LOOKUP_I[64+1]={
  114810. 92682l, 91966l, 91267l, 90583l,
  114811. 89915l, 89261l, 88621l, 87995l,
  114812. 87381l, 86781l, 86192l, 85616l,
  114813. 85051l, 84497l, 83953l, 83420l,
  114814. 82897l, 82384l, 81880l, 81385l,
  114815. 80899l, 80422l, 79953l, 79492l,
  114816. 79039l, 78594l, 78156l, 77726l,
  114817. 77302l, 76885l, 76475l, 76072l,
  114818. 75674l, 75283l, 74898l, 74519l,
  114819. 74146l, 73778l, 73415l, 73058l,
  114820. 72706l, 72359l, 72016l, 71679l,
  114821. 71347l, 71019l, 70695l, 70376l,
  114822. 70061l, 69750l, 69444l, 69141l,
  114823. 68842l, 68548l, 68256l, 67969l,
  114824. 67685l, 67405l, 67128l, 66855l,
  114825. 66585l, 66318l, 66054l, 65794l,
  114826. 65536l,
  114827. };
  114828. #define COS_LOOKUP_I_SHIFT 9
  114829. #define COS_LOOKUP_I_MASK 511
  114830. #define COS_LOOKUP_I_SZ 128
  114831. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  114832. 16384l, 16379l, 16364l, 16340l,
  114833. 16305l, 16261l, 16207l, 16143l,
  114834. 16069l, 15986l, 15893l, 15791l,
  114835. 15679l, 15557l, 15426l, 15286l,
  114836. 15137l, 14978l, 14811l, 14635l,
  114837. 14449l, 14256l, 14053l, 13842l,
  114838. 13623l, 13395l, 13160l, 12916l,
  114839. 12665l, 12406l, 12140l, 11866l,
  114840. 11585l, 11297l, 11003l, 10702l,
  114841. 10394l, 10080l, 9760l, 9434l,
  114842. 9102l, 8765l, 8423l, 8076l,
  114843. 7723l, 7366l, 7005l, 6639l,
  114844. 6270l, 5897l, 5520l, 5139l,
  114845. 4756l, 4370l, 3981l, 3590l,
  114846. 3196l, 2801l, 2404l, 2006l,
  114847. 1606l, 1205l, 804l, 402l,
  114848. 0l, -401l, -803l, -1204l,
  114849. -1605l, -2005l, -2403l, -2800l,
  114850. -3195l, -3589l, -3980l, -4369l,
  114851. -4755l, -5138l, -5519l, -5896l,
  114852. -6269l, -6638l, -7004l, -7365l,
  114853. -7722l, -8075l, -8422l, -8764l,
  114854. -9101l, -9433l, -9759l, -10079l,
  114855. -10393l, -10701l, -11002l, -11296l,
  114856. -11584l, -11865l, -12139l, -12405l,
  114857. -12664l, -12915l, -13159l, -13394l,
  114858. -13622l, -13841l, -14052l, -14255l,
  114859. -14448l, -14634l, -14810l, -14977l,
  114860. -15136l, -15285l, -15425l, -15556l,
  114861. -15678l, -15790l, -15892l, -15985l,
  114862. -16068l, -16142l, -16206l, -16260l,
  114863. -16304l, -16339l, -16363l, -16378l,
  114864. -16383l,
  114865. };
  114866. #endif
  114867. #endif
  114868. /*** End of inlined file: lookup_data.h ***/
  114869. #ifdef FLOAT_LOOKUP
  114870. /* interpolated lookup based cos function, domain 0 to PI only */
  114871. float vorbis_coslook(float a){
  114872. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  114873. int i=vorbis_ftoi(d-.5);
  114874. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  114875. }
  114876. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114877. float vorbis_invsqlook(float a){
  114878. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  114879. int i=vorbis_ftoi(d-.5f);
  114880. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  114881. }
  114882. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114883. float vorbis_invsq2explook(int a){
  114884. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  114885. }
  114886. #include <stdio.h>
  114887. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114888. float vorbis_fromdBlook(float a){
  114889. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  114890. return (i<0)?1.f:
  114891. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114892. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114893. }
  114894. #endif
  114895. #ifdef INT_LOOKUP
  114896. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  114897. 16.16 format
  114898. returns in m.8 format */
  114899. long vorbis_invsqlook_i(long a,long e){
  114900. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  114901. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  114902. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  114903. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  114904. d)>>16); /* result 1.16 */
  114905. e+=32;
  114906. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  114907. e=(e>>1)-8;
  114908. return(val>>e);
  114909. }
  114910. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114911. /* a is in n.12 format */
  114912. float vorbis_fromdBlook_i(long a){
  114913. int i=(-a)>>(12-FROMdB2_SHIFT);
  114914. return (i<0)?1.f:
  114915. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114916. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114917. }
  114918. /* interpolated lookup based cos function, domain 0 to PI only */
  114919. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  114920. long vorbis_coslook_i(long a){
  114921. int i=a>>COS_LOOKUP_I_SHIFT;
  114922. int d=a&COS_LOOKUP_I_MASK;
  114923. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  114924. COS_LOOKUP_I_SHIFT);
  114925. }
  114926. #endif
  114927. #endif
  114928. /*** End of inlined file: lookup.c ***/
  114929. /* catch this in the build system; we #include for
  114930. compilers (like gcc) that can't inline across
  114931. modules */
  114932. static int MLOOP_1[64]={
  114933. 0,10,11,11, 12,12,12,12, 13,13,13,13, 13,13,13,13,
  114934. 14,14,14,14, 14,14,14,14, 14,14,14,14, 14,14,14,14,
  114935. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  114936. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  114937. };
  114938. static int MLOOP_2[64]={
  114939. 0,4,5,5, 6,6,6,6, 7,7,7,7, 7,7,7,7,
  114940. 8,8,8,8, 8,8,8,8, 8,8,8,8, 8,8,8,8,
  114941. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  114942. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  114943. };
  114944. static int MLOOP_3[8]={0,1,2,2,3,3,3,3};
  114945. /* side effect: changes *lsp to cosines of lsp */
  114946. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114947. float amp,float ampoffset){
  114948. /* 0 <= m < 256 */
  114949. /* set up for using all int later */
  114950. int i;
  114951. int ampoffseti=rint(ampoffset*4096.f);
  114952. int ampi=rint(amp*16.f);
  114953. long *ilsp=alloca(m*sizeof(*ilsp));
  114954. for(i=0;i<m;i++)ilsp[i]=vorbis_coslook_i(lsp[i]/M_PI*65536.f+.5f);
  114955. i=0;
  114956. while(i<n){
  114957. int j,k=map[i];
  114958. unsigned long pi=46341; /* 2**-.5 in 0.16 */
  114959. unsigned long qi=46341;
  114960. int qexp=0,shift;
  114961. long wi=vorbis_coslook_i(k*65536/ln);
  114962. qi*=labs(ilsp[0]-wi);
  114963. pi*=labs(ilsp[1]-wi);
  114964. for(j=3;j<m;j+=2){
  114965. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114966. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114967. shift=MLOOP_3[(pi|qi)>>16];
  114968. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  114969. pi=(pi>>shift)*labs(ilsp[j]-wi);
  114970. qexp+=shift;
  114971. }
  114972. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114973. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114974. shift=MLOOP_3[(pi|qi)>>16];
  114975. /* pi,qi normalized collectively, both tracked using qexp */
  114976. if(m&1){
  114977. /* odd order filter; slightly assymetric */
  114978. /* the last coefficient */
  114979. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  114980. pi=(pi>>shift)<<14;
  114981. qexp+=shift;
  114982. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114983. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114984. shift=MLOOP_3[(pi|qi)>>16];
  114985. pi>>=shift;
  114986. qi>>=shift;
  114987. qexp+=shift-14*((m+1)>>1);
  114988. pi=((pi*pi)>>16);
  114989. qi=((qi*qi)>>16);
  114990. qexp=qexp*2+m;
  114991. pi*=(1<<14)-((wi*wi)>>14);
  114992. qi+=pi>>14;
  114993. }else{
  114994. /* even order filter; still symmetric */
  114995. /* p*=p(1-w), q*=q(1+w), let normalization drift because it isn't
  114996. worth tracking step by step */
  114997. pi>>=shift;
  114998. qi>>=shift;
  114999. qexp+=shift-7*m;
  115000. pi=((pi*pi)>>16);
  115001. qi=((qi*qi)>>16);
  115002. qexp=qexp*2+m;
  115003. pi*=(1<<14)-wi;
  115004. qi*=(1<<14)+wi;
  115005. qi=(qi+pi)>>14;
  115006. }
  115007. /* we've let the normalization drift because it wasn't important;
  115008. however, for the lookup, things must be normalized again. We
  115009. need at most one right shift or a number of left shifts */
  115010. if(qi&0xffff0000){ /* checks for 1.xxxxxxxxxxxxxxxx */
  115011. qi>>=1; qexp++;
  115012. }else
  115013. while(qi && !(qi&0x8000)){ /* checks for 0.0xxxxxxxxxxxxxxx or less*/
  115014. qi<<=1; qexp--;
  115015. }
  115016. amp=vorbis_fromdBlook_i(ampi* /* n.4 */
  115017. vorbis_invsqlook_i(qi,qexp)-
  115018. /* m.8, m+n<=8 */
  115019. ampoffseti); /* 8.12[0] */
  115020. curve[i]*=amp;
  115021. while(map[++i]==k)curve[i]*=amp;
  115022. }
  115023. }
  115024. #else
  115025. /* old, nonoptimized but simple version for any poor sap who needs to
  115026. figure out what the hell this code does, or wants the other
  115027. fraction of a dB precision */
  115028. /* side effect: changes *lsp to cosines of lsp */
  115029. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  115030. float amp,float ampoffset){
  115031. int i;
  115032. float wdel=M_PI/ln;
  115033. for(i=0;i<m;i++)lsp[i]=2.f*cos(lsp[i]);
  115034. i=0;
  115035. while(i<n){
  115036. int j,k=map[i];
  115037. float p=.5f;
  115038. float q=.5f;
  115039. float w=2.f*cos(wdel*k);
  115040. for(j=1;j<m;j+=2){
  115041. q *= w-lsp[j-1];
  115042. p *= w-lsp[j];
  115043. }
  115044. if(j==m){
  115045. /* odd order filter; slightly assymetric */
  115046. /* the last coefficient */
  115047. q*=w-lsp[j-1];
  115048. p*=p*(4.f-w*w);
  115049. q*=q;
  115050. }else{
  115051. /* even order filter; still symmetric */
  115052. p*=p*(2.f-w);
  115053. q*=q*(2.f+w);
  115054. }
  115055. q=fromdB(amp/sqrt(p+q)-ampoffset);
  115056. curve[i]*=q;
  115057. while(map[++i]==k)curve[i]*=q;
  115058. }
  115059. }
  115060. #endif
  115061. #endif
  115062. static void cheby(float *g, int ord) {
  115063. int i, j;
  115064. g[0] *= .5f;
  115065. for(i=2; i<= ord; i++) {
  115066. for(j=ord; j >= i; j--) {
  115067. g[j-2] -= g[j];
  115068. g[j] += g[j];
  115069. }
  115070. }
  115071. }
  115072. static int JUCE_CDECL comp(const void *a,const void *b){
  115073. return (*(float *)a<*(float *)b)-(*(float *)a>*(float *)b);
  115074. }
  115075. /* Newton-Raphson-Maehly actually functioned as a decent root finder,
  115076. but there are root sets for which it gets into limit cycles
  115077. (exacerbated by zero suppression) and fails. We can't afford to
  115078. fail, even if the failure is 1 in 100,000,000, so we now use
  115079. Laguerre and later polish with Newton-Raphson (which can then
  115080. afford to fail) */
  115081. #define EPSILON 10e-7
  115082. static int Laguerre_With_Deflation(float *a,int ord,float *r){
  115083. int i,m;
  115084. double lastdelta=0.f;
  115085. double *defl=(double*)alloca(sizeof(*defl)*(ord+1));
  115086. for(i=0;i<=ord;i++)defl[i]=a[i];
  115087. for(m=ord;m>0;m--){
  115088. double newx=0.f,delta;
  115089. /* iterate a root */
  115090. while(1){
  115091. double p=defl[m],pp=0.f,ppp=0.f,denom;
  115092. /* eval the polynomial and its first two derivatives */
  115093. for(i=m;i>0;i--){
  115094. ppp = newx*ppp + pp;
  115095. pp = newx*pp + p;
  115096. p = newx*p + defl[i-1];
  115097. }
  115098. /* Laguerre's method */
  115099. denom=(m-1) * ((m-1)*pp*pp - m*p*ppp);
  115100. if(denom<0)
  115101. return(-1); /* complex root! The LPC generator handed us a bad filter */
  115102. if(pp>0){
  115103. denom = pp + sqrt(denom);
  115104. if(denom<EPSILON)denom=EPSILON;
  115105. }else{
  115106. denom = pp - sqrt(denom);
  115107. if(denom>-(EPSILON))denom=-(EPSILON);
  115108. }
  115109. delta = m*p/denom;
  115110. newx -= delta;
  115111. if(delta<0.f)delta*=-1;
  115112. if(fabs(delta/newx)<10e-12)break;
  115113. lastdelta=delta;
  115114. }
  115115. r[m-1]=newx;
  115116. /* forward deflation */
  115117. for(i=m;i>0;i--)
  115118. defl[i-1]+=newx*defl[i];
  115119. defl++;
  115120. }
  115121. return(0);
  115122. }
  115123. /* for spit-and-polish only */
  115124. static int Newton_Raphson(float *a,int ord,float *r){
  115125. int i, k, count=0;
  115126. double error=1.f;
  115127. double *root=(double*)alloca(ord*sizeof(*root));
  115128. for(i=0; i<ord;i++) root[i] = r[i];
  115129. while(error>1e-20){
  115130. error=0;
  115131. for(i=0; i<ord; i++) { /* Update each point. */
  115132. double pp=0.,delta;
  115133. double rooti=root[i];
  115134. double p=a[ord];
  115135. for(k=ord-1; k>= 0; k--) {
  115136. pp= pp* rooti + p;
  115137. p = p * rooti + a[k];
  115138. }
  115139. delta = p/pp;
  115140. root[i] -= delta;
  115141. error+= delta*delta;
  115142. }
  115143. if(count>40)return(-1);
  115144. count++;
  115145. }
  115146. /* Replaced the original bubble sort with a real sort. With your
  115147. help, we can eliminate the bubble sort in our lifetime. --Monty */
  115148. for(i=0; i<ord;i++) r[i] = root[i];
  115149. return(0);
  115150. }
  115151. /* Convert lpc coefficients to lsp coefficients */
  115152. int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m){
  115153. int order2=(m+1)>>1;
  115154. int g1_order,g2_order;
  115155. float *g1=(float*)alloca(sizeof(*g1)*(order2+1));
  115156. float *g2=(float*)alloca(sizeof(*g2)*(order2+1));
  115157. float *g1r=(float*)alloca(sizeof(*g1r)*(order2+1));
  115158. float *g2r=(float*)alloca(sizeof(*g2r)*(order2+1));
  115159. int i;
  115160. /* even and odd are slightly different base cases */
  115161. g1_order=(m+1)>>1;
  115162. g2_order=(m) >>1;
  115163. /* Compute the lengths of the x polynomials. */
  115164. /* Compute the first half of K & R F1 & F2 polynomials. */
  115165. /* Compute half of the symmetric and antisymmetric polynomials. */
  115166. /* Remove the roots at +1 and -1. */
  115167. g1[g1_order] = 1.f;
  115168. for(i=1;i<=g1_order;i++) g1[g1_order-i] = lpc[i-1]+lpc[m-i];
  115169. g2[g2_order] = 1.f;
  115170. for(i=1;i<=g2_order;i++) g2[g2_order-i] = lpc[i-1]-lpc[m-i];
  115171. if(g1_order>g2_order){
  115172. for(i=2; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+2];
  115173. }else{
  115174. for(i=1; i<=g1_order;i++) g1[g1_order-i] -= g1[g1_order-i+1];
  115175. for(i=1; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+1];
  115176. }
  115177. /* Convert into polynomials in cos(alpha) */
  115178. cheby(g1,g1_order);
  115179. cheby(g2,g2_order);
  115180. /* Find the roots of the 2 even polynomials.*/
  115181. if(Laguerre_With_Deflation(g1,g1_order,g1r) ||
  115182. Laguerre_With_Deflation(g2,g2_order,g2r))
  115183. return(-1);
  115184. Newton_Raphson(g1,g1_order,g1r); /* if it fails, it leaves g1r alone */
  115185. Newton_Raphson(g2,g2_order,g2r); /* if it fails, it leaves g2r alone */
  115186. qsort(g1r,g1_order,sizeof(*g1r),comp);
  115187. qsort(g2r,g2_order,sizeof(*g2r),comp);
  115188. for(i=0;i<g1_order;i++)
  115189. lsp[i*2] = acos(g1r[i]);
  115190. for(i=0;i<g2_order;i++)
  115191. lsp[i*2+1] = acos(g2r[i]);
  115192. return(0);
  115193. }
  115194. #endif
  115195. /*** End of inlined file: lsp.c ***/
  115196. /*** Start of inlined file: mapping0.c ***/
  115197. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  115198. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115199. // tasks..
  115200. #if JUCE_MSVC
  115201. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115202. #endif
  115203. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  115204. #if JUCE_USE_OGGVORBIS
  115205. #include <stdlib.h>
  115206. #include <stdio.h>
  115207. #include <string.h>
  115208. #include <math.h>
  115209. /* simplistic, wasteful way of doing this (unique lookup for each
  115210. mode/submapping); there should be a central repository for
  115211. identical lookups. That will require minor work, so I'm putting it
  115212. off as low priority.
  115213. Why a lookup for each backend in a given mode? Because the
  115214. blocksize is set by the mode, and low backend lookups may require
  115215. parameters from other areas of the mode/mapping */
  115216. static void mapping0_free_info(vorbis_info_mapping *i){
  115217. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)i;
  115218. if(info){
  115219. memset(info,0,sizeof(*info));
  115220. _ogg_free(info);
  115221. }
  115222. }
  115223. static int ilog3(unsigned int v){
  115224. int ret=0;
  115225. if(v)--v;
  115226. while(v){
  115227. ret++;
  115228. v>>=1;
  115229. }
  115230. return(ret);
  115231. }
  115232. static void mapping0_pack(vorbis_info *vi,vorbis_info_mapping *vm,
  115233. oggpack_buffer *opb){
  115234. int i;
  115235. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)vm;
  115236. /* another 'we meant to do it this way' hack... up to beta 4, we
  115237. packed 4 binary zeros here to signify one submapping in use. We
  115238. now redefine that to mean four bitflags that indicate use of
  115239. deeper features; bit0:submappings, bit1:coupling,
  115240. bit2,3:reserved. This is backward compatable with all actual uses
  115241. of the beta code. */
  115242. if(info->submaps>1){
  115243. oggpack_write(opb,1,1);
  115244. oggpack_write(opb,info->submaps-1,4);
  115245. }else
  115246. oggpack_write(opb,0,1);
  115247. if(info->coupling_steps>0){
  115248. oggpack_write(opb,1,1);
  115249. oggpack_write(opb,info->coupling_steps-1,8);
  115250. for(i=0;i<info->coupling_steps;i++){
  115251. oggpack_write(opb,info->coupling_mag[i],ilog3(vi->channels));
  115252. oggpack_write(opb,info->coupling_ang[i],ilog3(vi->channels));
  115253. }
  115254. }else
  115255. oggpack_write(opb,0,1);
  115256. oggpack_write(opb,0,2); /* 2,3:reserved */
  115257. /* we don't write the channel submappings if we only have one... */
  115258. if(info->submaps>1){
  115259. for(i=0;i<vi->channels;i++)
  115260. oggpack_write(opb,info->chmuxlist[i],4);
  115261. }
  115262. for(i=0;i<info->submaps;i++){
  115263. oggpack_write(opb,0,8); /* time submap unused */
  115264. oggpack_write(opb,info->floorsubmap[i],8);
  115265. oggpack_write(opb,info->residuesubmap[i],8);
  115266. }
  115267. }
  115268. /* also responsible for range checking */
  115269. static vorbis_info_mapping *mapping0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  115270. int i;
  115271. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)_ogg_calloc(1,sizeof(*info));
  115272. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  115273. memset(info,0,sizeof(*info));
  115274. if(oggpack_read(opb,1))
  115275. info->submaps=oggpack_read(opb,4)+1;
  115276. else
  115277. info->submaps=1;
  115278. if(oggpack_read(opb,1)){
  115279. info->coupling_steps=oggpack_read(opb,8)+1;
  115280. for(i=0;i<info->coupling_steps;i++){
  115281. int testM=info->coupling_mag[i]=oggpack_read(opb,ilog3(vi->channels));
  115282. int testA=info->coupling_ang[i]=oggpack_read(opb,ilog3(vi->channels));
  115283. if(testM<0 ||
  115284. testA<0 ||
  115285. testM==testA ||
  115286. testM>=vi->channels ||
  115287. testA>=vi->channels) goto err_out;
  115288. }
  115289. }
  115290. if(oggpack_read(opb,2)>0)goto err_out; /* 2,3:reserved */
  115291. if(info->submaps>1){
  115292. for(i=0;i<vi->channels;i++){
  115293. info->chmuxlist[i]=oggpack_read(opb,4);
  115294. if(info->chmuxlist[i]>=info->submaps)goto err_out;
  115295. }
  115296. }
  115297. for(i=0;i<info->submaps;i++){
  115298. oggpack_read(opb,8); /* time submap unused */
  115299. info->floorsubmap[i]=oggpack_read(opb,8);
  115300. if(info->floorsubmap[i]>=ci->floors)goto err_out;
  115301. info->residuesubmap[i]=oggpack_read(opb,8);
  115302. if(info->residuesubmap[i]>=ci->residues)goto err_out;
  115303. }
  115304. return info;
  115305. err_out:
  115306. mapping0_free_info(info);
  115307. return(NULL);
  115308. }
  115309. #if 0
  115310. static long seq=0;
  115311. static ogg_int64_t total=0;
  115312. static float FLOOR1_fromdB_LOOKUP[256]={
  115313. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  115314. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  115315. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  115316. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  115317. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  115318. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  115319. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  115320. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  115321. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  115322. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  115323. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  115324. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  115325. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  115326. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  115327. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  115328. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  115329. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  115330. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  115331. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  115332. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  115333. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  115334. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  115335. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  115336. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  115337. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  115338. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  115339. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  115340. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  115341. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  115342. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  115343. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  115344. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  115345. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  115346. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  115347. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  115348. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  115349. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  115350. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  115351. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  115352. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  115353. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  115354. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  115355. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  115356. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  115357. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  115358. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  115359. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  115360. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  115361. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  115362. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  115363. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  115364. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  115365. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  115366. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  115367. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  115368. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  115369. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  115370. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  115371. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  115372. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  115373. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  115374. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  115375. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  115376. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  115377. };
  115378. #endif
  115379. extern int *floor1_fit(vorbis_block *vb,void *look,
  115380. const float *logmdct, /* in */
  115381. const float *logmask);
  115382. extern int *floor1_interpolate_fit(vorbis_block *vb,void *look,
  115383. int *A,int *B,
  115384. int del);
  115385. extern int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  115386. void*look,
  115387. int *post,int *ilogmask);
  115388. static int mapping0_forward(vorbis_block *vb){
  115389. vorbis_dsp_state *vd=vb->vd;
  115390. vorbis_info *vi=vd->vi;
  115391. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  115392. private_state *b=(private_state*)vb->vd->backend_state;
  115393. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  115394. int n=vb->pcmend;
  115395. int i,j,k;
  115396. int *nonzero = (int*) alloca(sizeof(*nonzero)*vi->channels);
  115397. float **gmdct = (float**) _vorbis_block_alloc(vb,vi->channels*sizeof(*gmdct));
  115398. int **ilogmaskch= (int**) _vorbis_block_alloc(vb,vi->channels*sizeof(*ilogmaskch));
  115399. int ***floor_posts = (int***) _vorbis_block_alloc(vb,vi->channels*sizeof(*floor_posts));
  115400. float global_ampmax=vbi->ampmax;
  115401. float *local_ampmax=(float*)alloca(sizeof(*local_ampmax)*vi->channels);
  115402. int blocktype=vbi->blocktype;
  115403. int modenumber=vb->W;
  115404. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)ci->map_param[modenumber];
  115405. vorbis_look_psy *psy_look=
  115406. b->psy+blocktype+(vb->W?2:0);
  115407. vb->mode=modenumber;
  115408. for(i=0;i<vi->channels;i++){
  115409. float scale=4.f/n;
  115410. float scale_dB;
  115411. float *pcm =vb->pcm[i];
  115412. float *logfft =pcm;
  115413. gmdct[i]=(float*)_vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  115414. scale_dB=todB(&scale) + .345; /* + .345 is a hack; the original
  115415. todB estimation used on IEEE 754
  115416. compliant machines had a bug that
  115417. returned dB values about a third
  115418. of a decibel too high. The bug
  115419. was harmless because tunings
  115420. implicitly took that into
  115421. account. However, fixing the bug
  115422. in the estimator requires
  115423. changing all the tunings as well.
  115424. For now, it's easier to sync
  115425. things back up here, and
  115426. recalibrate the tunings in the
  115427. next major model upgrade. */
  115428. #if 0
  115429. if(vi->channels==2)
  115430. if(i==0)
  115431. _analysis_output("pcmL",seq,pcm,n,0,0,total-n/2);
  115432. else
  115433. _analysis_output("pcmR",seq,pcm,n,0,0,total-n/2);
  115434. #endif
  115435. /* window the PCM data */
  115436. _vorbis_apply_window(pcm,b->window,ci->blocksizes,vb->lW,vb->W,vb->nW);
  115437. #if 0
  115438. if(vi->channels==2)
  115439. if(i==0)
  115440. _analysis_output("windowedL",seq,pcm,n,0,0,total-n/2);
  115441. else
  115442. _analysis_output("windowedR",seq,pcm,n,0,0,total-n/2);
  115443. #endif
  115444. /* transform the PCM data */
  115445. /* only MDCT right now.... */
  115446. mdct_forward((mdct_lookup*) b->transform[vb->W][0],pcm,gmdct[i]);
  115447. /* FFT yields more accurate tonal estimation (not phase sensitive) */
  115448. drft_forward(&b->fft_look[vb->W],pcm);
  115449. logfft[0]=scale_dB+todB(pcm) + .345; /* + .345 is a hack; the
  115450. original todB estimation used on
  115451. IEEE 754 compliant machines had a
  115452. bug that returned dB values about
  115453. a third of a decibel too high.
  115454. The bug was harmless because
  115455. tunings implicitly took that into
  115456. account. However, fixing the bug
  115457. in the estimator requires
  115458. changing all the tunings as well.
  115459. For now, it's easier to sync
  115460. things back up here, and
  115461. recalibrate the tunings in the
  115462. next major model upgrade. */
  115463. local_ampmax[i]=logfft[0];
  115464. for(j=1;j<n-1;j+=2){
  115465. float temp=pcm[j]*pcm[j]+pcm[j+1]*pcm[j+1];
  115466. temp=logfft[(j+1)>>1]=scale_dB+.5f*todB(&temp) + .345; /* +
  115467. .345 is a hack; the original todB
  115468. estimation used on IEEE 754
  115469. compliant machines had a bug that
  115470. returned dB values about a third
  115471. of a decibel too high. The bug
  115472. was harmless because tunings
  115473. implicitly took that into
  115474. account. However, fixing the bug
  115475. in the estimator requires
  115476. changing all the tunings as well.
  115477. For now, it's easier to sync
  115478. things back up here, and
  115479. recalibrate the tunings in the
  115480. next major model upgrade. */
  115481. if(temp>local_ampmax[i])local_ampmax[i]=temp;
  115482. }
  115483. if(local_ampmax[i]>0.f)local_ampmax[i]=0.f;
  115484. if(local_ampmax[i]>global_ampmax)global_ampmax=local_ampmax[i];
  115485. #if 0
  115486. if(vi->channels==2){
  115487. if(i==0){
  115488. _analysis_output("fftL",seq,logfft,n/2,1,0,0);
  115489. }else{
  115490. _analysis_output("fftR",seq,logfft,n/2,1,0,0);
  115491. }
  115492. }
  115493. #endif
  115494. }
  115495. {
  115496. float *noise = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*noise));
  115497. float *tone = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*tone));
  115498. for(i=0;i<vi->channels;i++){
  115499. /* the encoder setup assumes that all the modes used by any
  115500. specific bitrate tweaking use the same floor */
  115501. int submap=info->chmuxlist[i];
  115502. /* the following makes things clearer to *me* anyway */
  115503. float *mdct =gmdct[i];
  115504. float *logfft =vb->pcm[i];
  115505. float *logmdct =logfft+n/2;
  115506. float *logmask =logfft;
  115507. vb->mode=modenumber;
  115508. floor_posts[i]=(int**) _vorbis_block_alloc(vb,PACKETBLOBS*sizeof(**floor_posts));
  115509. memset(floor_posts[i],0,sizeof(**floor_posts)*PACKETBLOBS);
  115510. for(j=0;j<n/2;j++)
  115511. logmdct[j]=todB(mdct+j) + .345; /* + .345 is a hack; the original
  115512. todB estimation used on IEEE 754
  115513. compliant machines had a bug that
  115514. returned dB values about a third
  115515. of a decibel too high. The bug
  115516. was harmless because tunings
  115517. implicitly took that into
  115518. account. However, fixing the bug
  115519. in the estimator requires
  115520. changing all the tunings as well.
  115521. For now, it's easier to sync
  115522. things back up here, and
  115523. recalibrate the tunings in the
  115524. next major model upgrade. */
  115525. #if 0
  115526. if(vi->channels==2){
  115527. if(i==0)
  115528. _analysis_output("mdctL",seq,logmdct,n/2,1,0,0);
  115529. else
  115530. _analysis_output("mdctR",seq,logmdct,n/2,1,0,0);
  115531. }else{
  115532. _analysis_output("mdct",seq,logmdct,n/2,1,0,0);
  115533. }
  115534. #endif
  115535. /* first step; noise masking. Not only does 'noise masking'
  115536. give us curves from which we can decide how much resolution
  115537. to give noise parts of the spectrum, it also implicitly hands
  115538. us a tonality estimate (the larger the value in the
  115539. 'noise_depth' vector, the more tonal that area is) */
  115540. _vp_noisemask(psy_look,
  115541. logmdct,
  115542. noise); /* noise does not have by-frequency offset
  115543. bias applied yet */
  115544. #if 0
  115545. if(vi->channels==2){
  115546. if(i==0)
  115547. _analysis_output("noiseL",seq,noise,n/2,1,0,0);
  115548. else
  115549. _analysis_output("noiseR",seq,noise,n/2,1,0,0);
  115550. }
  115551. #endif
  115552. /* second step: 'all the other crap'; all the stuff that isn't
  115553. computed/fit for bitrate management goes in the second psy
  115554. vector. This includes tone masking, peak limiting and ATH */
  115555. _vp_tonemask(psy_look,
  115556. logfft,
  115557. tone,
  115558. global_ampmax,
  115559. local_ampmax[i]);
  115560. #if 0
  115561. if(vi->channels==2){
  115562. if(i==0)
  115563. _analysis_output("toneL",seq,tone,n/2,1,0,0);
  115564. else
  115565. _analysis_output("toneR",seq,tone,n/2,1,0,0);
  115566. }
  115567. #endif
  115568. /* third step; we offset the noise vectors, overlay tone
  115569. masking. We then do a floor1-specific line fit. If we're
  115570. performing bitrate management, the line fit is performed
  115571. multiple times for up/down tweakage on demand. */
  115572. #if 0
  115573. {
  115574. float aotuv[psy_look->n];
  115575. #endif
  115576. _vp_offset_and_mix(psy_look,
  115577. noise,
  115578. tone,
  115579. 1,
  115580. logmask,
  115581. mdct,
  115582. logmdct);
  115583. #if 0
  115584. if(vi->channels==2){
  115585. if(i==0)
  115586. _analysis_output("aotuvM1_L",seq,aotuv,psy_look->n,1,1,0);
  115587. else
  115588. _analysis_output("aotuvM1_R",seq,aotuv,psy_look->n,1,1,0);
  115589. }
  115590. }
  115591. #endif
  115592. #if 0
  115593. if(vi->channels==2){
  115594. if(i==0)
  115595. _analysis_output("mask1L",seq,logmask,n/2,1,0,0);
  115596. else
  115597. _analysis_output("mask1R",seq,logmask,n/2,1,0,0);
  115598. }
  115599. #endif
  115600. /* this algorithm is hardwired to floor 1 for now; abort out if
  115601. we're *not* floor1. This won't happen unless someone has
  115602. broken the encode setup lib. Guard it anyway. */
  115603. if(ci->floor_type[info->floorsubmap[submap]]!=1)return(-1);
  115604. floor_posts[i][PACKETBLOBS/2]=
  115605. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115606. logmdct,
  115607. logmask);
  115608. /* are we managing bitrate? If so, perform two more fits for
  115609. later rate tweaking (fits represent hi/lo) */
  115610. if(vorbis_bitrate_managed(vb) && floor_posts[i][PACKETBLOBS/2]){
  115611. /* higher rate by way of lower noise curve */
  115612. _vp_offset_and_mix(psy_look,
  115613. noise,
  115614. tone,
  115615. 2,
  115616. logmask,
  115617. mdct,
  115618. logmdct);
  115619. #if 0
  115620. if(vi->channels==2){
  115621. if(i==0)
  115622. _analysis_output("mask2L",seq,logmask,n/2,1,0,0);
  115623. else
  115624. _analysis_output("mask2R",seq,logmask,n/2,1,0,0);
  115625. }
  115626. #endif
  115627. floor_posts[i][PACKETBLOBS-1]=
  115628. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115629. logmdct,
  115630. logmask);
  115631. /* lower rate by way of higher noise curve */
  115632. _vp_offset_and_mix(psy_look,
  115633. noise,
  115634. tone,
  115635. 0,
  115636. logmask,
  115637. mdct,
  115638. logmdct);
  115639. #if 0
  115640. if(vi->channels==2)
  115641. if(i==0)
  115642. _analysis_output("mask0L",seq,logmask,n/2,1,0,0);
  115643. else
  115644. _analysis_output("mask0R",seq,logmask,n/2,1,0,0);
  115645. #endif
  115646. floor_posts[i][0]=
  115647. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115648. logmdct,
  115649. logmask);
  115650. /* we also interpolate a range of intermediate curves for
  115651. intermediate rates */
  115652. for(k=1;k<PACKETBLOBS/2;k++)
  115653. floor_posts[i][k]=
  115654. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  115655. floor_posts[i][0],
  115656. floor_posts[i][PACKETBLOBS/2],
  115657. k*65536/(PACKETBLOBS/2));
  115658. for(k=PACKETBLOBS/2+1;k<PACKETBLOBS-1;k++)
  115659. floor_posts[i][k]=
  115660. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  115661. floor_posts[i][PACKETBLOBS/2],
  115662. floor_posts[i][PACKETBLOBS-1],
  115663. (k-PACKETBLOBS/2)*65536/(PACKETBLOBS/2));
  115664. }
  115665. }
  115666. }
  115667. vbi->ampmax=global_ampmax;
  115668. /*
  115669. the next phases are performed once for vbr-only and PACKETBLOB
  115670. times for bitrate managed modes.
  115671. 1) encode actual mode being used
  115672. 2) encode the floor for each channel, compute coded mask curve/res
  115673. 3) normalize and couple.
  115674. 4) encode residue
  115675. 5) save packet bytes to the packetblob vector
  115676. */
  115677. /* iterate over the many masking curve fits we've created */
  115678. {
  115679. float **res_bundle=(float**) alloca(sizeof(*res_bundle)*vi->channels);
  115680. float **couple_bundle=(float**) alloca(sizeof(*couple_bundle)*vi->channels);
  115681. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  115682. int **sortindex=(int**) alloca(sizeof(*sortindex)*vi->channels);
  115683. float **mag_memo;
  115684. int **mag_sort;
  115685. if(info->coupling_steps){
  115686. mag_memo=_vp_quantize_couple_memo(vb,
  115687. &ci->psy_g_param,
  115688. psy_look,
  115689. info,
  115690. gmdct);
  115691. mag_sort=_vp_quantize_couple_sort(vb,
  115692. psy_look,
  115693. info,
  115694. mag_memo);
  115695. hf_reduction(&ci->psy_g_param,
  115696. psy_look,
  115697. info,
  115698. mag_memo);
  115699. }
  115700. memset(sortindex,0,sizeof(*sortindex)*vi->channels);
  115701. if(psy_look->vi->normal_channel_p){
  115702. for(i=0;i<vi->channels;i++){
  115703. float *mdct =gmdct[i];
  115704. sortindex[i]=(int*) alloca(sizeof(**sortindex)*n/2);
  115705. _vp_noise_normalize_sort(psy_look,mdct,sortindex[i]);
  115706. }
  115707. }
  115708. for(k=(vorbis_bitrate_managed(vb)?0:PACKETBLOBS/2);
  115709. k<=(vorbis_bitrate_managed(vb)?PACKETBLOBS-1:PACKETBLOBS/2);
  115710. k++){
  115711. oggpack_buffer *opb=vbi->packetblob[k];
  115712. /* start out our new packet blob with packet type and mode */
  115713. /* Encode the packet type */
  115714. oggpack_write(opb,0,1);
  115715. /* Encode the modenumber */
  115716. /* Encode frame mode, pre,post windowsize, then dispatch */
  115717. oggpack_write(opb,modenumber,b->modebits);
  115718. if(vb->W){
  115719. oggpack_write(opb,vb->lW,1);
  115720. oggpack_write(opb,vb->nW,1);
  115721. }
  115722. /* encode floor, compute masking curve, sep out residue */
  115723. for(i=0;i<vi->channels;i++){
  115724. int submap=info->chmuxlist[i];
  115725. float *mdct =gmdct[i];
  115726. float *res =vb->pcm[i];
  115727. int *ilogmask=ilogmaskch[i]=
  115728. (int*) _vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  115729. nonzero[i]=floor1_encode(opb,vb,b->flr[info->floorsubmap[submap]],
  115730. floor_posts[i][k],
  115731. ilogmask);
  115732. #if 0
  115733. {
  115734. char buf[80];
  115735. sprintf(buf,"maskI%c%d",i?'R':'L',k);
  115736. float work[n/2];
  115737. for(j=0;j<n/2;j++)
  115738. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]];
  115739. _analysis_output(buf,seq,work,n/2,1,1,0);
  115740. }
  115741. #endif
  115742. _vp_remove_floor(psy_look,
  115743. mdct,
  115744. ilogmask,
  115745. res,
  115746. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  115747. _vp_noise_normalize(psy_look,res,res+n/2,sortindex[i]);
  115748. #if 0
  115749. {
  115750. char buf[80];
  115751. float work[n/2];
  115752. for(j=0;j<n/2;j++)
  115753. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]]*(res+n/2)[j];
  115754. sprintf(buf,"resI%c%d",i?'R':'L',k);
  115755. _analysis_output(buf,seq,work,n/2,1,1,0);
  115756. }
  115757. #endif
  115758. }
  115759. /* our iteration is now based on masking curve, not prequant and
  115760. coupling. Only one prequant/coupling step */
  115761. /* quantize/couple */
  115762. /* incomplete implementation that assumes the tree is all depth
  115763. one, or no tree at all */
  115764. if(info->coupling_steps){
  115765. _vp_couple(k,
  115766. &ci->psy_g_param,
  115767. psy_look,
  115768. info,
  115769. vb->pcm,
  115770. mag_memo,
  115771. mag_sort,
  115772. ilogmaskch,
  115773. nonzero,
  115774. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  115775. }
  115776. /* classify and encode by submap */
  115777. for(i=0;i<info->submaps;i++){
  115778. int ch_in_bundle=0;
  115779. long **classifications;
  115780. int resnum=info->residuesubmap[i];
  115781. for(j=0;j<vi->channels;j++){
  115782. if(info->chmuxlist[j]==i){
  115783. zerobundle[ch_in_bundle]=0;
  115784. if(nonzero[j])zerobundle[ch_in_bundle]=1;
  115785. res_bundle[ch_in_bundle]=vb->pcm[j];
  115786. couple_bundle[ch_in_bundle++]=vb->pcm[j]+n/2;
  115787. }
  115788. }
  115789. classifications=_residue_P[ci->residue_type[resnum]]->
  115790. classx(vb,b->residue[resnum],couple_bundle,zerobundle,ch_in_bundle);
  115791. _residue_P[ci->residue_type[resnum]]->
  115792. forward(opb,vb,b->residue[resnum],
  115793. couple_bundle,NULL,zerobundle,ch_in_bundle,classifications);
  115794. }
  115795. /* ok, done encoding. Next protopacket. */
  115796. }
  115797. }
  115798. #if 0
  115799. seq++;
  115800. total+=ci->blocksizes[vb->W]/4+ci->blocksizes[vb->nW]/4;
  115801. #endif
  115802. return(0);
  115803. }
  115804. static int mapping0_inverse(vorbis_block *vb,vorbis_info_mapping *l){
  115805. vorbis_dsp_state *vd=vb->vd;
  115806. vorbis_info *vi=vd->vi;
  115807. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  115808. private_state *b=(private_state*)vd->backend_state;
  115809. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)l;
  115810. int i,j;
  115811. long n=vb->pcmend=ci->blocksizes[vb->W];
  115812. float **pcmbundle=(float**) alloca(sizeof(*pcmbundle)*vi->channels);
  115813. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  115814. int *nonzero =(int*) alloca(sizeof(*nonzero)*vi->channels);
  115815. void **floormemo=(void**) alloca(sizeof(*floormemo)*vi->channels);
  115816. /* recover the spectral envelope; store it in the PCM vector for now */
  115817. for(i=0;i<vi->channels;i++){
  115818. int submap=info->chmuxlist[i];
  115819. floormemo[i]=_floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  115820. inverse1(vb,b->flr[info->floorsubmap[submap]]);
  115821. if(floormemo[i])
  115822. nonzero[i]=1;
  115823. else
  115824. nonzero[i]=0;
  115825. memset(vb->pcm[i],0,sizeof(*vb->pcm[i])*n/2);
  115826. }
  115827. /* channel coupling can 'dirty' the nonzero listing */
  115828. for(i=0;i<info->coupling_steps;i++){
  115829. if(nonzero[info->coupling_mag[i]] ||
  115830. nonzero[info->coupling_ang[i]]){
  115831. nonzero[info->coupling_mag[i]]=1;
  115832. nonzero[info->coupling_ang[i]]=1;
  115833. }
  115834. }
  115835. /* recover the residue into our working vectors */
  115836. for(i=0;i<info->submaps;i++){
  115837. int ch_in_bundle=0;
  115838. for(j=0;j<vi->channels;j++){
  115839. if(info->chmuxlist[j]==i){
  115840. if(nonzero[j])
  115841. zerobundle[ch_in_bundle]=1;
  115842. else
  115843. zerobundle[ch_in_bundle]=0;
  115844. pcmbundle[ch_in_bundle++]=vb->pcm[j];
  115845. }
  115846. }
  115847. _residue_P[ci->residue_type[info->residuesubmap[i]]]->
  115848. inverse(vb,b->residue[info->residuesubmap[i]],
  115849. pcmbundle,zerobundle,ch_in_bundle);
  115850. }
  115851. /* channel coupling */
  115852. for(i=info->coupling_steps-1;i>=0;i--){
  115853. float *pcmM=vb->pcm[info->coupling_mag[i]];
  115854. float *pcmA=vb->pcm[info->coupling_ang[i]];
  115855. for(j=0;j<n/2;j++){
  115856. float mag=pcmM[j];
  115857. float ang=pcmA[j];
  115858. if(mag>0)
  115859. if(ang>0){
  115860. pcmM[j]=mag;
  115861. pcmA[j]=mag-ang;
  115862. }else{
  115863. pcmA[j]=mag;
  115864. pcmM[j]=mag+ang;
  115865. }
  115866. else
  115867. if(ang>0){
  115868. pcmM[j]=mag;
  115869. pcmA[j]=mag+ang;
  115870. }else{
  115871. pcmA[j]=mag;
  115872. pcmM[j]=mag-ang;
  115873. }
  115874. }
  115875. }
  115876. /* compute and apply spectral envelope */
  115877. for(i=0;i<vi->channels;i++){
  115878. float *pcm=vb->pcm[i];
  115879. int submap=info->chmuxlist[i];
  115880. _floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  115881. inverse2(vb,b->flr[info->floorsubmap[submap]],
  115882. floormemo[i],pcm);
  115883. }
  115884. /* transform the PCM data; takes PCM vector, vb; modifies PCM vector */
  115885. /* only MDCT right now.... */
  115886. for(i=0;i<vi->channels;i++){
  115887. float *pcm=vb->pcm[i];
  115888. mdct_backward((mdct_lookup*) b->transform[vb->W][0],pcm,pcm);
  115889. }
  115890. /* all done! */
  115891. return(0);
  115892. }
  115893. /* export hooks */
  115894. vorbis_func_mapping mapping0_exportbundle={
  115895. &mapping0_pack,
  115896. &mapping0_unpack,
  115897. &mapping0_free_info,
  115898. &mapping0_forward,
  115899. &mapping0_inverse
  115900. };
  115901. #endif
  115902. /*** End of inlined file: mapping0.c ***/
  115903. /*** Start of inlined file: mdct.c ***/
  115904. /* this can also be run as an integer transform by uncommenting a
  115905. define in mdct.h; the integerization is a first pass and although
  115906. it's likely stable for Vorbis, the dynamic range is constrained and
  115907. roundoff isn't done (so it's noisy). Consider it functional, but
  115908. only a starting point. There's no point on a machine with an FPU */
  115909. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  115910. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115911. // tasks..
  115912. #if JUCE_MSVC
  115913. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115914. #endif
  115915. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  115916. #if JUCE_USE_OGGVORBIS
  115917. #include <stdio.h>
  115918. #include <stdlib.h>
  115919. #include <string.h>
  115920. #include <math.h>
  115921. /* build lookups for trig functions; also pre-figure scaling and
  115922. some window function algebra. */
  115923. void mdct_init(mdct_lookup *lookup,int n){
  115924. int *bitrev=(int*) _ogg_malloc(sizeof(*bitrev)*(n/4));
  115925. DATA_TYPE *T=(DATA_TYPE*) _ogg_malloc(sizeof(*T)*(n+n/4));
  115926. int i;
  115927. int n2=n>>1;
  115928. int log2n=lookup->log2n=rint(log((float)n)/log(2.f));
  115929. lookup->n=n;
  115930. lookup->trig=T;
  115931. lookup->bitrev=bitrev;
  115932. /* trig lookups... */
  115933. for(i=0;i<n/4;i++){
  115934. T[i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i)));
  115935. T[i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i)));
  115936. T[n2+i*2]=FLOAT_CONV(cos((M_PI/(2*n))*(2*i+1)));
  115937. T[n2+i*2+1]=FLOAT_CONV(sin((M_PI/(2*n))*(2*i+1)));
  115938. }
  115939. for(i=0;i<n/8;i++){
  115940. T[n+i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i+2))*.5);
  115941. T[n+i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i+2))*.5);
  115942. }
  115943. /* bitreverse lookup... */
  115944. {
  115945. int mask=(1<<(log2n-1))-1,i,j;
  115946. int msb=1<<(log2n-2);
  115947. for(i=0;i<n/8;i++){
  115948. int acc=0;
  115949. for(j=0;msb>>j;j++)
  115950. if((msb>>j)&i)acc|=1<<j;
  115951. bitrev[i*2]=((~acc)&mask)-1;
  115952. bitrev[i*2+1]=acc;
  115953. }
  115954. }
  115955. lookup->scale=FLOAT_CONV(4.f/n);
  115956. }
  115957. /* 8 point butterfly (in place, 4 register) */
  115958. STIN void mdct_butterfly_8(DATA_TYPE *x){
  115959. REG_TYPE r0 = x[6] + x[2];
  115960. REG_TYPE r1 = x[6] - x[2];
  115961. REG_TYPE r2 = x[4] + x[0];
  115962. REG_TYPE r3 = x[4] - x[0];
  115963. x[6] = r0 + r2;
  115964. x[4] = r0 - r2;
  115965. r0 = x[5] - x[1];
  115966. r2 = x[7] - x[3];
  115967. x[0] = r1 + r0;
  115968. x[2] = r1 - r0;
  115969. r0 = x[5] + x[1];
  115970. r1 = x[7] + x[3];
  115971. x[3] = r2 + r3;
  115972. x[1] = r2 - r3;
  115973. x[7] = r1 + r0;
  115974. x[5] = r1 - r0;
  115975. }
  115976. /* 16 point butterfly (in place, 4 register) */
  115977. STIN void mdct_butterfly_16(DATA_TYPE *x){
  115978. REG_TYPE r0 = x[1] - x[9];
  115979. REG_TYPE r1 = x[0] - x[8];
  115980. x[8] += x[0];
  115981. x[9] += x[1];
  115982. x[0] = MULT_NORM((r0 + r1) * cPI2_8);
  115983. x[1] = MULT_NORM((r0 - r1) * cPI2_8);
  115984. r0 = x[3] - x[11];
  115985. r1 = x[10] - x[2];
  115986. x[10] += x[2];
  115987. x[11] += x[3];
  115988. x[2] = r0;
  115989. x[3] = r1;
  115990. r0 = x[12] - x[4];
  115991. r1 = x[13] - x[5];
  115992. x[12] += x[4];
  115993. x[13] += x[5];
  115994. x[4] = MULT_NORM((r0 - r1) * cPI2_8);
  115995. x[5] = MULT_NORM((r0 + r1) * cPI2_8);
  115996. r0 = x[14] - x[6];
  115997. r1 = x[15] - x[7];
  115998. x[14] += x[6];
  115999. x[15] += x[7];
  116000. x[6] = r0;
  116001. x[7] = r1;
  116002. mdct_butterfly_8(x);
  116003. mdct_butterfly_8(x+8);
  116004. }
  116005. /* 32 point butterfly (in place, 4 register) */
  116006. STIN void mdct_butterfly_32(DATA_TYPE *x){
  116007. REG_TYPE r0 = x[30] - x[14];
  116008. REG_TYPE r1 = x[31] - x[15];
  116009. x[30] += x[14];
  116010. x[31] += x[15];
  116011. x[14] = r0;
  116012. x[15] = r1;
  116013. r0 = x[28] - x[12];
  116014. r1 = x[29] - x[13];
  116015. x[28] += x[12];
  116016. x[29] += x[13];
  116017. x[12] = MULT_NORM( r0 * cPI1_8 - r1 * cPI3_8 );
  116018. x[13] = MULT_NORM( r0 * cPI3_8 + r1 * cPI1_8 );
  116019. r0 = x[26] - x[10];
  116020. r1 = x[27] - x[11];
  116021. x[26] += x[10];
  116022. x[27] += x[11];
  116023. x[10] = MULT_NORM(( r0 - r1 ) * cPI2_8);
  116024. x[11] = MULT_NORM(( r0 + r1 ) * cPI2_8);
  116025. r0 = x[24] - x[8];
  116026. r1 = x[25] - x[9];
  116027. x[24] += x[8];
  116028. x[25] += x[9];
  116029. x[8] = MULT_NORM( r0 * cPI3_8 - r1 * cPI1_8 );
  116030. x[9] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  116031. r0 = x[22] - x[6];
  116032. r1 = x[7] - x[23];
  116033. x[22] += x[6];
  116034. x[23] += x[7];
  116035. x[6] = r1;
  116036. x[7] = r0;
  116037. r0 = x[4] - x[20];
  116038. r1 = x[5] - x[21];
  116039. x[20] += x[4];
  116040. x[21] += x[5];
  116041. x[4] = MULT_NORM( r1 * cPI1_8 + r0 * cPI3_8 );
  116042. x[5] = MULT_NORM( r1 * cPI3_8 - r0 * cPI1_8 );
  116043. r0 = x[2] - x[18];
  116044. r1 = x[3] - x[19];
  116045. x[18] += x[2];
  116046. x[19] += x[3];
  116047. x[2] = MULT_NORM(( r1 + r0 ) * cPI2_8);
  116048. x[3] = MULT_NORM(( r1 - r0 ) * cPI2_8);
  116049. r0 = x[0] - x[16];
  116050. r1 = x[1] - x[17];
  116051. x[16] += x[0];
  116052. x[17] += x[1];
  116053. x[0] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  116054. x[1] = MULT_NORM( r1 * cPI1_8 - r0 * cPI3_8 );
  116055. mdct_butterfly_16(x);
  116056. mdct_butterfly_16(x+16);
  116057. }
  116058. /* N point first stage butterfly (in place, 2 register) */
  116059. STIN void mdct_butterfly_first(DATA_TYPE *T,
  116060. DATA_TYPE *x,
  116061. int points){
  116062. DATA_TYPE *x1 = x + points - 8;
  116063. DATA_TYPE *x2 = x + (points>>1) - 8;
  116064. REG_TYPE r0;
  116065. REG_TYPE r1;
  116066. do{
  116067. r0 = x1[6] - x2[6];
  116068. r1 = x1[7] - x2[7];
  116069. x1[6] += x2[6];
  116070. x1[7] += x2[7];
  116071. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116072. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116073. r0 = x1[4] - x2[4];
  116074. r1 = x1[5] - x2[5];
  116075. x1[4] += x2[4];
  116076. x1[5] += x2[5];
  116077. x2[4] = MULT_NORM(r1 * T[5] + r0 * T[4]);
  116078. x2[5] = MULT_NORM(r1 * T[4] - r0 * T[5]);
  116079. r0 = x1[2] - x2[2];
  116080. r1 = x1[3] - x2[3];
  116081. x1[2] += x2[2];
  116082. x1[3] += x2[3];
  116083. x2[2] = MULT_NORM(r1 * T[9] + r0 * T[8]);
  116084. x2[3] = MULT_NORM(r1 * T[8] - r0 * T[9]);
  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[13] + r0 * T[12]);
  116090. x2[1] = MULT_NORM(r1 * T[12] - r0 * T[13]);
  116091. x1-=8;
  116092. x2-=8;
  116093. T+=16;
  116094. }while(x2>=x);
  116095. }
  116096. /* N/stage point generic N stage butterfly (in place, 2 register) */
  116097. STIN void mdct_butterfly_generic(DATA_TYPE *T,
  116098. DATA_TYPE *x,
  116099. int points,
  116100. int trigint){
  116101. DATA_TYPE *x1 = x + points - 8;
  116102. DATA_TYPE *x2 = x + (points>>1) - 8;
  116103. REG_TYPE r0;
  116104. REG_TYPE r1;
  116105. do{
  116106. r0 = x1[6] - x2[6];
  116107. r1 = x1[7] - x2[7];
  116108. x1[6] += x2[6];
  116109. x1[7] += x2[7];
  116110. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116111. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116112. T+=trigint;
  116113. r0 = x1[4] - x2[4];
  116114. r1 = x1[5] - x2[5];
  116115. x1[4] += x2[4];
  116116. x1[5] += x2[5];
  116117. x2[4] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116118. x2[5] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116119. T+=trigint;
  116120. r0 = x1[2] - x2[2];
  116121. r1 = x1[3] - x2[3];
  116122. x1[2] += x2[2];
  116123. x1[3] += x2[3];
  116124. x2[2] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116125. x2[3] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116126. T+=trigint;
  116127. r0 = x1[0] - x2[0];
  116128. r1 = x1[1] - x2[1];
  116129. x1[0] += x2[0];
  116130. x1[1] += x2[1];
  116131. x2[0] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116132. x2[1] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116133. T+=trigint;
  116134. x1-=8;
  116135. x2-=8;
  116136. }while(x2>=x);
  116137. }
  116138. STIN void mdct_butterflies(mdct_lookup *init,
  116139. DATA_TYPE *x,
  116140. int points){
  116141. DATA_TYPE *T=init->trig;
  116142. int stages=init->log2n-5;
  116143. int i,j;
  116144. if(--stages>0){
  116145. mdct_butterfly_first(T,x,points);
  116146. }
  116147. for(i=1;--stages>0;i++){
  116148. for(j=0;j<(1<<i);j++)
  116149. mdct_butterfly_generic(T,x+(points>>i)*j,points>>i,4<<i);
  116150. }
  116151. for(j=0;j<points;j+=32)
  116152. mdct_butterfly_32(x+j);
  116153. }
  116154. void mdct_clear(mdct_lookup *l){
  116155. if(l){
  116156. if(l->trig)_ogg_free(l->trig);
  116157. if(l->bitrev)_ogg_free(l->bitrev);
  116158. memset(l,0,sizeof(*l));
  116159. }
  116160. }
  116161. STIN void mdct_bitreverse(mdct_lookup *init,
  116162. DATA_TYPE *x){
  116163. int n = init->n;
  116164. int *bit = init->bitrev;
  116165. DATA_TYPE *w0 = x;
  116166. DATA_TYPE *w1 = x = w0+(n>>1);
  116167. DATA_TYPE *T = init->trig+n;
  116168. do{
  116169. DATA_TYPE *x0 = x+bit[0];
  116170. DATA_TYPE *x1 = x+bit[1];
  116171. REG_TYPE r0 = x0[1] - x1[1];
  116172. REG_TYPE r1 = x0[0] + x1[0];
  116173. REG_TYPE r2 = MULT_NORM(r1 * T[0] + r0 * T[1]);
  116174. REG_TYPE r3 = MULT_NORM(r1 * T[1] - r0 * T[0]);
  116175. w1 -= 4;
  116176. r0 = HALVE(x0[1] + x1[1]);
  116177. r1 = HALVE(x0[0] - x1[0]);
  116178. w0[0] = r0 + r2;
  116179. w1[2] = r0 - r2;
  116180. w0[1] = r1 + r3;
  116181. w1[3] = r3 - r1;
  116182. x0 = x+bit[2];
  116183. x1 = x+bit[3];
  116184. r0 = x0[1] - x1[1];
  116185. r1 = x0[0] + x1[0];
  116186. r2 = MULT_NORM(r1 * T[2] + r0 * T[3]);
  116187. r3 = MULT_NORM(r1 * T[3] - r0 * T[2]);
  116188. r0 = HALVE(x0[1] + x1[1]);
  116189. r1 = HALVE(x0[0] - x1[0]);
  116190. w0[2] = r0 + r2;
  116191. w1[0] = r0 - r2;
  116192. w0[3] = r1 + r3;
  116193. w1[1] = r3 - r1;
  116194. T += 4;
  116195. bit += 4;
  116196. w0 += 4;
  116197. }while(w0<w1);
  116198. }
  116199. void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  116200. int n=init->n;
  116201. int n2=n>>1;
  116202. int n4=n>>2;
  116203. /* rotate */
  116204. DATA_TYPE *iX = in+n2-7;
  116205. DATA_TYPE *oX = out+n2+n4;
  116206. DATA_TYPE *T = init->trig+n4;
  116207. do{
  116208. oX -= 4;
  116209. oX[0] = MULT_NORM(-iX[2] * T[3] - iX[0] * T[2]);
  116210. oX[1] = MULT_NORM (iX[0] * T[3] - iX[2] * T[2]);
  116211. oX[2] = MULT_NORM(-iX[6] * T[1] - iX[4] * T[0]);
  116212. oX[3] = MULT_NORM (iX[4] * T[1] - iX[6] * T[0]);
  116213. iX -= 8;
  116214. T += 4;
  116215. }while(iX>=in);
  116216. iX = in+n2-8;
  116217. oX = out+n2+n4;
  116218. T = init->trig+n4;
  116219. do{
  116220. T -= 4;
  116221. oX[0] = MULT_NORM (iX[4] * T[3] + iX[6] * T[2]);
  116222. oX[1] = MULT_NORM (iX[4] * T[2] - iX[6] * T[3]);
  116223. oX[2] = MULT_NORM (iX[0] * T[1] + iX[2] * T[0]);
  116224. oX[3] = MULT_NORM (iX[0] * T[0] - iX[2] * T[1]);
  116225. iX -= 8;
  116226. oX += 4;
  116227. }while(iX>=in);
  116228. mdct_butterflies(init,out+n2,n2);
  116229. mdct_bitreverse(init,out);
  116230. /* roatate + window */
  116231. {
  116232. DATA_TYPE *oX1=out+n2+n4;
  116233. DATA_TYPE *oX2=out+n2+n4;
  116234. DATA_TYPE *iX =out;
  116235. T =init->trig+n2;
  116236. do{
  116237. oX1-=4;
  116238. oX1[3] = MULT_NORM (iX[0] * T[1] - iX[1] * T[0]);
  116239. oX2[0] = -MULT_NORM (iX[0] * T[0] + iX[1] * T[1]);
  116240. oX1[2] = MULT_NORM (iX[2] * T[3] - iX[3] * T[2]);
  116241. oX2[1] = -MULT_NORM (iX[2] * T[2] + iX[3] * T[3]);
  116242. oX1[1] = MULT_NORM (iX[4] * T[5] - iX[5] * T[4]);
  116243. oX2[2] = -MULT_NORM (iX[4] * T[4] + iX[5] * T[5]);
  116244. oX1[0] = MULT_NORM (iX[6] * T[7] - iX[7] * T[6]);
  116245. oX2[3] = -MULT_NORM (iX[6] * T[6] + iX[7] * T[7]);
  116246. oX2+=4;
  116247. iX += 8;
  116248. T += 8;
  116249. }while(iX<oX1);
  116250. iX=out+n2+n4;
  116251. oX1=out+n4;
  116252. oX2=oX1;
  116253. do{
  116254. oX1-=4;
  116255. iX-=4;
  116256. oX2[0] = -(oX1[3] = iX[3]);
  116257. oX2[1] = -(oX1[2] = iX[2]);
  116258. oX2[2] = -(oX1[1] = iX[1]);
  116259. oX2[3] = -(oX1[0] = iX[0]);
  116260. oX2+=4;
  116261. }while(oX2<iX);
  116262. iX=out+n2+n4;
  116263. oX1=out+n2+n4;
  116264. oX2=out+n2;
  116265. do{
  116266. oX1-=4;
  116267. oX1[0]= iX[3];
  116268. oX1[1]= iX[2];
  116269. oX1[2]= iX[1];
  116270. oX1[3]= iX[0];
  116271. iX+=4;
  116272. }while(oX1>oX2);
  116273. }
  116274. }
  116275. void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  116276. int n=init->n;
  116277. int n2=n>>1;
  116278. int n4=n>>2;
  116279. int n8=n>>3;
  116280. DATA_TYPE *w=(DATA_TYPE*) alloca(n*sizeof(*w)); /* forward needs working space */
  116281. DATA_TYPE *w2=w+n2;
  116282. /* rotate */
  116283. /* window + rotate + step 1 */
  116284. REG_TYPE r0;
  116285. REG_TYPE r1;
  116286. DATA_TYPE *x0=in+n2+n4;
  116287. DATA_TYPE *x1=x0+1;
  116288. DATA_TYPE *T=init->trig+n2;
  116289. int i=0;
  116290. for(i=0;i<n8;i+=2){
  116291. x0 -=4;
  116292. T-=2;
  116293. r0= x0[2] + x1[0];
  116294. r1= x0[0] + x1[2];
  116295. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  116296. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  116297. x1 +=4;
  116298. }
  116299. x1=in+1;
  116300. for(;i<n2-n8;i+=2){
  116301. T-=2;
  116302. x0 -=4;
  116303. r0= x0[2] - x1[0];
  116304. r1= x0[0] - x1[2];
  116305. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  116306. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  116307. x1 +=4;
  116308. }
  116309. x0=in+n;
  116310. for(;i<n2;i+=2){
  116311. T-=2;
  116312. x0 -=4;
  116313. r0= -x0[2] - x1[0];
  116314. r1= -x0[0] - x1[2];
  116315. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  116316. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  116317. x1 +=4;
  116318. }
  116319. mdct_butterflies(init,w+n2,n2);
  116320. mdct_bitreverse(init,w);
  116321. /* roatate + window */
  116322. T=init->trig+n2;
  116323. x0=out+n2;
  116324. for(i=0;i<n4;i++){
  116325. x0--;
  116326. out[i] =MULT_NORM((w[0]*T[0]+w[1]*T[1])*init->scale);
  116327. x0[0] =MULT_NORM((w[0]*T[1]-w[1]*T[0])*init->scale);
  116328. w+=2;
  116329. T+=2;
  116330. }
  116331. }
  116332. #endif
  116333. /*** End of inlined file: mdct.c ***/
  116334. /*** Start of inlined file: psy.c ***/
  116335. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  116336. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  116337. // tasks..
  116338. #if JUCE_MSVC
  116339. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  116340. #endif
  116341. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  116342. #if JUCE_USE_OGGVORBIS
  116343. #include <stdlib.h>
  116344. #include <math.h>
  116345. #include <string.h>
  116346. /*** Start of inlined file: masking.h ***/
  116347. #ifndef _V_MASKING_H_
  116348. #define _V_MASKING_H_
  116349. /* more detailed ATH; the bass if flat to save stressing the floor
  116350. overly for only a bin or two of savings. */
  116351. #define MAX_ATH 88
  116352. static float ATH[]={
  116353. /*15*/ -51, -52, -53, -54, -55, -56, -57, -58,
  116354. /*31*/ -59, -60, -61, -62, -63, -64, -65, -66,
  116355. /*63*/ -67, -68, -69, -70, -71, -72, -73, -74,
  116356. /*125*/ -75, -76, -77, -78, -80, -81, -82, -83,
  116357. /*250*/ -84, -85, -86, -87, -88, -88, -89, -89,
  116358. /*500*/ -90, -91, -91, -92, -93, -94, -95, -96,
  116359. /*1k*/ -96, -97, -98, -98, -99, -99,-100,-100,
  116360. /*2k*/ -101,-102,-103,-104,-106,-107,-107,-107,
  116361. /*4k*/ -107,-105,-103,-102,-101, -99, -98, -96,
  116362. /*8k*/ -95, -95, -96, -97, -96, -95, -93, -90,
  116363. /*16k*/ -80, -70, -50, -40, -30, -30, -30, -30
  116364. };
  116365. /* The tone masking curves from Ehmer's and Fielder's papers have been
  116366. replaced by an empirically collected data set. The previously
  116367. published values were, far too often, simply on crack. */
  116368. #define EHMER_OFFSET 16
  116369. #define EHMER_MAX 56
  116370. /* masking tones from -50 to 0dB, 62.5 through 16kHz at half octaves
  116371. test tones from -2 octaves to +5 octaves sampled at eighth octaves */
  116372. /* (Vorbis 0dB, the loudest possible tone, is assumed to be ~100dB SPL
  116373. for collection of these curves) */
  116374. static float tonemasks[P_BANDS][6][EHMER_MAX]={
  116375. /* 62.5 Hz */
  116376. {{ -60, -60, -60, -60, -60, -60, -60, -60,
  116377. -60, -60, -60, -60, -62, -62, -65, -73,
  116378. -69, -68, -68, -67, -70, -70, -72, -74,
  116379. -75, -79, -79, -80, -83, -88, -93, -100,
  116380. -110, -999, -999, -999, -999, -999, -999, -999,
  116381. -999, -999, -999, -999, -999, -999, -999, -999,
  116382. -999, -999, -999, -999, -999, -999, -999, -999},
  116383. { -48, -48, -48, -48, -48, -48, -48, -48,
  116384. -48, -48, -48, -48, -48, -53, -61, -66,
  116385. -66, -68, -67, -70, -76, -76, -72, -73,
  116386. -75, -76, -78, -79, -83, -88, -93, -100,
  116387. -110, -999, -999, -999, -999, -999, -999, -999,
  116388. -999, -999, -999, -999, -999, -999, -999, -999,
  116389. -999, -999, -999, -999, -999, -999, -999, -999},
  116390. { -37, -37, -37, -37, -37, -37, -37, -37,
  116391. -38, -40, -42, -46, -48, -53, -55, -62,
  116392. -65, -58, -56, -56, -61, -60, -65, -67,
  116393. -69, -71, -77, -77, -78, -80, -82, -84,
  116394. -88, -93, -98, -106, -112, -999, -999, -999,
  116395. -999, -999, -999, -999, -999, -999, -999, -999,
  116396. -999, -999, -999, -999, -999, -999, -999, -999},
  116397. { -25, -25, -25, -25, -25, -25, -25, -25,
  116398. -25, -26, -27, -29, -32, -38, -48, -52,
  116399. -52, -50, -48, -48, -51, -52, -54, -60,
  116400. -67, -67, -66, -68, -69, -73, -73, -76,
  116401. -80, -81, -81, -85, -85, -86, -88, -93,
  116402. -100, -110, -999, -999, -999, -999, -999, -999,
  116403. -999, -999, -999, -999, -999, -999, -999, -999},
  116404. { -16, -16, -16, -16, -16, -16, -16, -16,
  116405. -17, -19, -20, -22, -26, -28, -31, -40,
  116406. -47, -39, -39, -40, -42, -43, -47, -51,
  116407. -57, -52, -55, -55, -60, -58, -62, -63,
  116408. -70, -67, -69, -72, -73, -77, -80, -82,
  116409. -83, -87, -90, -94, -98, -104, -115, -999,
  116410. -999, -999, -999, -999, -999, -999, -999, -999},
  116411. { -8, -8, -8, -8, -8, -8, -8, -8,
  116412. -8, -8, -10, -11, -15, -19, -25, -30,
  116413. -34, -31, -30, -31, -29, -32, -35, -42,
  116414. -48, -42, -44, -46, -50, -50, -51, -52,
  116415. -59, -54, -55, -55, -58, -62, -63, -66,
  116416. -72, -73, -76, -75, -78, -80, -80, -81,
  116417. -84, -88, -90, -94, -98, -101, -106, -110}},
  116418. /* 88Hz */
  116419. {{ -66, -66, -66, -66, -66, -66, -66, -66,
  116420. -66, -66, -66, -66, -66, -67, -67, -67,
  116421. -76, -72, -71, -74, -76, -76, -75, -78,
  116422. -79, -79, -81, -83, -86, -89, -93, -97,
  116423. -100, -105, -110, -999, -999, -999, -999, -999,
  116424. -999, -999, -999, -999, -999, -999, -999, -999,
  116425. -999, -999, -999, -999, -999, -999, -999, -999},
  116426. { -47, -47, -47, -47, -47, -47, -47, -47,
  116427. -47, -47, -47, -48, -51, -55, -59, -66,
  116428. -66, -66, -67, -66, -68, -69, -70, -74,
  116429. -79, -77, -77, -78, -80, -81, -82, -84,
  116430. -86, -88, -91, -95, -100, -108, -116, -999,
  116431. -999, -999, -999, -999, -999, -999, -999, -999,
  116432. -999, -999, -999, -999, -999, -999, -999, -999},
  116433. { -36, -36, -36, -36, -36, -36, -36, -36,
  116434. -36, -37, -37, -41, -44, -48, -51, -58,
  116435. -62, -60, -57, -59, -59, -60, -63, -65,
  116436. -72, -71, -70, -72, -74, -77, -76, -78,
  116437. -81, -81, -80, -83, -86, -91, -96, -100,
  116438. -105, -110, -999, -999, -999, -999, -999, -999,
  116439. -999, -999, -999, -999, -999, -999, -999, -999},
  116440. { -28, -28, -28, -28, -28, -28, -28, -28,
  116441. -28, -30, -32, -32, -33, -35, -41, -49,
  116442. -50, -49, -47, -48, -48, -52, -51, -57,
  116443. -65, -61, -59, -61, -64, -69, -70, -74,
  116444. -77, -77, -78, -81, -84, -85, -87, -90,
  116445. -92, -96, -100, -107, -112, -999, -999, -999,
  116446. -999, -999, -999, -999, -999, -999, -999, -999},
  116447. { -19, -19, -19, -19, -19, -19, -19, -19,
  116448. -20, -21, -23, -27, -30, -35, -36, -41,
  116449. -46, -44, -42, -40, -41, -41, -43, -48,
  116450. -55, -53, -52, -53, -56, -59, -58, -60,
  116451. -67, -66, -69, -71, -72, -75, -79, -81,
  116452. -84, -87, -90, -93, -97, -101, -107, -114,
  116453. -999, -999, -999, -999, -999, -999, -999, -999},
  116454. { -9, -9, -9, -9, -9, -9, -9, -9,
  116455. -11, -12, -12, -15, -16, -20, -23, -30,
  116456. -37, -34, -33, -34, -31, -32, -32, -38,
  116457. -47, -44, -41, -40, -47, -49, -46, -46,
  116458. -58, -50, -50, -54, -58, -62, -64, -67,
  116459. -67, -70, -72, -76, -79, -83, -87, -91,
  116460. -96, -100, -104, -110, -999, -999, -999, -999}},
  116461. /* 125 Hz */
  116462. {{ -62, -62, -62, -62, -62, -62, -62, -62,
  116463. -62, -62, -63, -64, -66, -67, -66, -68,
  116464. -75, -72, -76, -75, -76, -78, -79, -82,
  116465. -84, -85, -90, -94, -101, -110, -999, -999,
  116466. -999, -999, -999, -999, -999, -999, -999, -999,
  116467. -999, -999, -999, -999, -999, -999, -999, -999,
  116468. -999, -999, -999, -999, -999, -999, -999, -999},
  116469. { -59, -59, -59, -59, -59, -59, -59, -59,
  116470. -59, -59, -59, -60, -60, -61, -63, -66,
  116471. -71, -68, -70, -70, -71, -72, -72, -75,
  116472. -81, -78, -79, -82, -83, -86, -90, -97,
  116473. -103, -113, -999, -999, -999, -999, -999, -999,
  116474. -999, -999, -999, -999, -999, -999, -999, -999,
  116475. -999, -999, -999, -999, -999, -999, -999, -999},
  116476. { -53, -53, -53, -53, -53, -53, -53, -53,
  116477. -53, -54, -55, -57, -56, -57, -55, -61,
  116478. -65, -60, -60, -62, -63, -63, -66, -68,
  116479. -74, -73, -75, -75, -78, -80, -80, -82,
  116480. -85, -90, -96, -101, -108, -999, -999, -999,
  116481. -999, -999, -999, -999, -999, -999, -999, -999,
  116482. -999, -999, -999, -999, -999, -999, -999, -999},
  116483. { -46, -46, -46, -46, -46, -46, -46, -46,
  116484. -46, -46, -47, -47, -47, -47, -48, -51,
  116485. -57, -51, -49, -50, -51, -53, -54, -59,
  116486. -66, -60, -62, -67, -67, -70, -72, -75,
  116487. -76, -78, -81, -85, -88, -94, -97, -104,
  116488. -112, -999, -999, -999, -999, -999, -999, -999,
  116489. -999, -999, -999, -999, -999, -999, -999, -999},
  116490. { -36, -36, -36, -36, -36, -36, -36, -36,
  116491. -39, -41, -42, -42, -39, -38, -41, -43,
  116492. -52, -44, -40, -39, -37, -37, -40, -47,
  116493. -54, -50, -48, -50, -55, -61, -59, -62,
  116494. -66, -66, -66, -69, -69, -73, -74, -74,
  116495. -75, -77, -79, -82, -87, -91, -95, -100,
  116496. -108, -115, -999, -999, -999, -999, -999, -999},
  116497. { -28, -26, -24, -22, -20, -20, -23, -29,
  116498. -30, -31, -28, -27, -28, -28, -28, -35,
  116499. -40, -33, -32, -29, -30, -30, -30, -37,
  116500. -45, -41, -37, -38, -45, -47, -47, -48,
  116501. -53, -49, -48, -50, -49, -49, -51, -52,
  116502. -58, -56, -57, -56, -60, -61, -62, -70,
  116503. -72, -74, -78, -83, -88, -93, -100, -106}},
  116504. /* 177 Hz */
  116505. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116506. -999, -110, -105, -100, -95, -91, -87, -83,
  116507. -80, -78, -76, -78, -78, -81, -83, -85,
  116508. -86, -85, -86, -87, -90, -97, -107, -999,
  116509. -999, -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, -110, -105, -100, -95, -90,
  116513. -85, -81, -77, -73, -70, -67, -67, -68,
  116514. -75, -73, -70, -69, -70, -72, -75, -79,
  116515. -84, -83, -84, -86, -88, -89, -89, -93,
  116516. -98, -105, -112, -999, -999, -999, -999, -999,
  116517. -999, -999, -999, -999, -999, -999, -999, -999,
  116518. -999, -999, -999, -999, -999, -999, -999, -999},
  116519. {-105, -100, -95, -90, -85, -80, -76, -71,
  116520. -68, -68, -65, -63, -63, -62, -62, -64,
  116521. -65, -64, -61, -62, -63, -64, -66, -68,
  116522. -73, -73, -74, -75, -76, -81, -83, -85,
  116523. -88, -89, -92, -95, -100, -108, -999, -999,
  116524. -999, -999, -999, -999, -999, -999, -999, -999,
  116525. -999, -999, -999, -999, -999, -999, -999, -999},
  116526. { -80, -75, -71, -68, -65, -63, -62, -61,
  116527. -61, -61, -61, -59, -56, -57, -53, -50,
  116528. -58, -52, -50, -50, -52, -53, -54, -58,
  116529. -67, -63, -67, -68, -72, -75, -78, -80,
  116530. -81, -81, -82, -85, -89, -90, -93, -97,
  116531. -101, -107, -114, -999, -999, -999, -999, -999,
  116532. -999, -999, -999, -999, -999, -999, -999, -999},
  116533. { -65, -61, -59, -57, -56, -55, -55, -56,
  116534. -56, -57, -55, -53, -52, -47, -44, -44,
  116535. -50, -44, -41, -39, -39, -42, -40, -46,
  116536. -51, -49, -50, -53, -54, -63, -60, -61,
  116537. -62, -66, -66, -66, -70, -73, -74, -75,
  116538. -76, -75, -79, -85, -89, -91, -96, -102,
  116539. -110, -999, -999, -999, -999, -999, -999, -999},
  116540. { -52, -50, -49, -49, -48, -48, -48, -49,
  116541. -50, -50, -49, -46, -43, -39, -35, -33,
  116542. -38, -36, -32, -29, -32, -32, -32, -35,
  116543. -44, -39, -38, -38, -46, -50, -45, -46,
  116544. -53, -50, -50, -50, -54, -54, -53, -53,
  116545. -56, -57, -59, -66, -70, -72, -74, -79,
  116546. -83, -85, -90, -97, -114, -999, -999, -999}},
  116547. /* 250 Hz */
  116548. {{-999, -999, -999, -999, -999, -999, -110, -105,
  116549. -100, -95, -90, -86, -80, -75, -75, -79,
  116550. -80, -79, -80, -81, -82, -88, -95, -103,
  116551. -110, -999, -999, -999, -999, -999, -999, -999,
  116552. -999, -999, -999, -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, -108, -103, -98, -93,
  116556. -88, -83, -79, -78, -75, -71, -67, -68,
  116557. -73, -73, -72, -73, -75, -77, -80, -82,
  116558. -88, -93, -100, -107, -114, -999, -999, -999,
  116559. -999, -999, -999, -999, -999, -999, -999, -999,
  116560. -999, -999, -999, -999, -999, -999, -999, -999,
  116561. -999, -999, -999, -999, -999, -999, -999, -999},
  116562. {-999, -999, -999, -110, -105, -101, -96, -90,
  116563. -86, -81, -77, -73, -69, -66, -61, -62,
  116564. -66, -64, -62, -65, -66, -70, -72, -76,
  116565. -81, -80, -84, -90, -95, -102, -110, -999,
  116566. -999, -999, -999, -999, -999, -999, -999, -999,
  116567. -999, -999, -999, -999, -999, -999, -999, -999,
  116568. -999, -999, -999, -999, -999, -999, -999, -999},
  116569. {-999, -999, -999, -107, -103, -97, -92, -88,
  116570. -83, -79, -74, -70, -66, -59, -53, -58,
  116571. -62, -55, -54, -54, -54, -58, -61, -62,
  116572. -72, -70, -72, -75, -78, -80, -81, -80,
  116573. -83, -83, -88, -93, -100, -107, -115, -999,
  116574. -999, -999, -999, -999, -999, -999, -999, -999,
  116575. -999, -999, -999, -999, -999, -999, -999, -999},
  116576. {-999, -999, -999, -105, -100, -95, -90, -85,
  116577. -80, -75, -70, -66, -62, -56, -48, -44,
  116578. -48, -46, -46, -43, -46, -48, -48, -51,
  116579. -58, -58, -59, -60, -62, -62, -61, -61,
  116580. -65, -64, -65, -68, -70, -74, -75, -78,
  116581. -81, -86, -95, -110, -999, -999, -999, -999,
  116582. -999, -999, -999, -999, -999, -999, -999, -999},
  116583. {-999, -999, -105, -100, -95, -90, -85, -80,
  116584. -75, -70, -65, -61, -55, -49, -39, -33,
  116585. -40, -35, -32, -38, -40, -33, -35, -37,
  116586. -46, -41, -45, -44, -46, -42, -45, -46,
  116587. -52, -50, -50, -50, -54, -54, -55, -57,
  116588. -62, -64, -66, -68, -70, -76, -81, -90,
  116589. -100, -110, -999, -999, -999, -999, -999, -999}},
  116590. /* 354 hz */
  116591. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116592. -105, -98, -90, -85, -82, -83, -80, -78,
  116593. -84, -79, -80, -83, -87, -89, -91, -93,
  116594. -99, -106, -117, -999, -999, -999, -999, -999,
  116595. -999, -999, -999, -999, -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. -105, -98, -90, -85, -80, -75, -70, -68,
  116600. -74, -72, -74, -77, -80, -82, -85, -87,
  116601. -92, -89, -91, -95, -100, -106, -112, -999,
  116602. -999, -999, -999, -999, -999, -999, -999, -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. -105, -98, -90, -83, -75, -71, -63, -64,
  116607. -67, -62, -64, -67, -70, -73, -77, -81,
  116608. -84, -83, -85, -89, -90, -93, -98, -104,
  116609. -109, -114, -999, -999, -999, -999, -999, -999,
  116610. -999, -999, -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. -103, -96, -88, -81, -75, -68, -58, -54,
  116614. -56, -54, -56, -56, -58, -60, -63, -66,
  116615. -74, -69, -72, -72, -75, -74, -77, -81,
  116616. -81, -82, -84, -87, -93, -96, -99, -104,
  116617. -110, -999, -999, -999, -999, -999, -999, -999,
  116618. -999, -999, -999, -999, -999, -999, -999, -999},
  116619. {-999, -999, -999, -999, -999, -108, -102, -96,
  116620. -91, -85, -80, -74, -68, -60, -51, -46,
  116621. -48, -46, -43, -45, -47, -47, -49, -48,
  116622. -56, -53, -55, -58, -57, -63, -58, -60,
  116623. -66, -64, -67, -70, -70, -74, -77, -84,
  116624. -86, -89, -91, -93, -94, -101, -109, -118,
  116625. -999, -999, -999, -999, -999, -999, -999, -999},
  116626. {-999, -999, -999, -108, -103, -98, -93, -88,
  116627. -83, -78, -73, -68, -60, -53, -44, -35,
  116628. -38, -38, -34, -34, -36, -40, -41, -44,
  116629. -51, -45, -46, -47, -46, -54, -50, -49,
  116630. -50, -50, -50, -51, -54, -57, -58, -60,
  116631. -66, -66, -66, -64, -65, -68, -77, -82,
  116632. -87, -95, -110, -999, -999, -999, -999, -999}},
  116633. /* 500 Hz */
  116634. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116635. -107, -102, -97, -92, -87, -83, -78, -75,
  116636. -82, -79, -83, -85, -89, -92, -95, -98,
  116637. -101, -105, -109, -113, -999, -999, -999, -999,
  116638. -999, -999, -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, -106,
  116642. -100, -95, -90, -86, -81, -78, -74, -69,
  116643. -74, -74, -76, -79, -83, -84, -86, -89,
  116644. -92, -97, -93, -100, -103, -107, -110, -999,
  116645. -999, -999, -999, -999, -999, -999, -999, -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, -106, -100,
  116649. -95, -90, -87, -83, -80, -75, -69, -60,
  116650. -66, -66, -68, -70, -74, -78, -79, -81,
  116651. -81, -83, -84, -87, -93, -96, -99, -103,
  116652. -107, -110, -999, -999, -999, -999, -999, -999,
  116653. -999, -999, -999, -999, -999, -999, -999, -999,
  116654. -999, -999, -999, -999, -999, -999, -999, -999},
  116655. {-999, -999, -999, -999, -999, -108, -103, -98,
  116656. -93, -89, -85, -82, -78, -71, -62, -55,
  116657. -58, -58, -54, -54, -55, -59, -61, -62,
  116658. -70, -66, -66, -67, -70, -72, -75, -78,
  116659. -84, -84, -84, -88, -91, -90, -95, -98,
  116660. -102, -103, -106, -110, -999, -999, -999, -999,
  116661. -999, -999, -999, -999, -999, -999, -999, -999},
  116662. {-999, -999, -999, -999, -108, -103, -98, -94,
  116663. -90, -87, -82, -79, -73, -67, -58, -47,
  116664. -50, -45, -41, -45, -48, -44, -44, -49,
  116665. -54, -51, -48, -47, -49, -50, -51, -57,
  116666. -58, -60, -63, -69, -70, -69, -71, -74,
  116667. -78, -82, -90, -95, -101, -105, -110, -999,
  116668. -999, -999, -999, -999, -999, -999, -999, -999},
  116669. {-999, -999, -999, -105, -101, -97, -93, -90,
  116670. -85, -80, -77, -72, -65, -56, -48, -37,
  116671. -40, -36, -34, -40, -50, -47, -38, -41,
  116672. -47, -38, -35, -39, -38, -43, -40, -45,
  116673. -50, -45, -44, -47, -50, -55, -48, -48,
  116674. -52, -66, -70, -76, -82, -90, -97, -105,
  116675. -110, -999, -999, -999, -999, -999, -999, -999}},
  116676. /* 707 Hz */
  116677. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116678. -999, -108, -103, -98, -93, -86, -79, -76,
  116679. -83, -81, -85, -87, -89, -93, -98, -102,
  116680. -107, -112, -999, -999, -999, -999, -999, -999,
  116681. -999, -999, -999, -999, -999, -999, -999, -999,
  116682. -999, -999, -999, -999, -999, -999, -999, -999,
  116683. -999, -999, -999, -999, -999, -999, -999, -999},
  116684. {-999, -999, -999, -999, -999, -999, -999, -999,
  116685. -999, -108, -103, -98, -93, -86, -79, -71,
  116686. -77, -74, -77, -79, -81, -84, -85, -90,
  116687. -92, -93, -92, -98, -101, -108, -112, -999,
  116688. -999, -999, -999, -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. -108, -103, -98, -93, -87, -78, -68, -65,
  116693. -66, -62, -65, -67, -70, -73, -75, -78,
  116694. -82, -82, -83, -84, -91, -93, -98, -102,
  116695. -106, -110, -999, -999, -999, -999, -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. -105, -100, -95, -90, -82, -74, -62, -57,
  116700. -58, -56, -51, -52, -52, -54, -54, -58,
  116701. -66, -59, -60, -63, -66, -69, -73, -79,
  116702. -83, -84, -80, -81, -81, -82, -88, -92,
  116703. -98, -105, -113, -999, -999, -999, -999, -999,
  116704. -999, -999, -999, -999, -999, -999, -999, -999},
  116705. {-999, -999, -999, -999, -999, -999, -999, -107,
  116706. -102, -97, -92, -84, -79, -69, -57, -47,
  116707. -52, -47, -44, -45, -50, -52, -42, -42,
  116708. -53, -43, -43, -48, -51, -56, -55, -52,
  116709. -57, -59, -61, -62, -67, -71, -78, -83,
  116710. -86, -94, -98, -103, -110, -999, -999, -999,
  116711. -999, -999, -999, -999, -999, -999, -999, -999},
  116712. {-999, -999, -999, -999, -999, -999, -105, -100,
  116713. -95, -90, -84, -78, -70, -61, -51, -41,
  116714. -40, -38, -40, -46, -52, -51, -41, -40,
  116715. -46, -40, -38, -38, -41, -46, -41, -46,
  116716. -47, -43, -43, -45, -41, -45, -56, -67,
  116717. -68, -83, -87, -90, -95, -102, -107, -113,
  116718. -999, -999, -999, -999, -999, -999, -999, -999}},
  116719. /* 1000 Hz */
  116720. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116721. -999, -109, -105, -101, -96, -91, -84, -77,
  116722. -82, -82, -85, -89, -94, -100, -106, -110,
  116723. -999, -999, -999, -999, -999, -999, -999, -999,
  116724. -999, -999, -999, -999, -999, -999, -999, -999,
  116725. -999, -999, -999, -999, -999, -999, -999, -999,
  116726. -999, -999, -999, -999, -999, -999, -999, -999},
  116727. {-999, -999, -999, -999, -999, -999, -999, -999,
  116728. -999, -106, -103, -98, -92, -85, -80, -71,
  116729. -75, -72, -76, -80, -84, -86, -89, -93,
  116730. -100, -107, -113, -999, -999, -999, -999, -999,
  116731. -999, -999, -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, -107,
  116735. -104, -101, -97, -92, -88, -84, -80, -64,
  116736. -66, -63, -64, -66, -69, -73, -77, -83,
  116737. -83, -86, -91, -98, -104, -111, -999, -999,
  116738. -999, -999, -999, -999, -999, -999, -999, -999,
  116739. -999, -999, -999, -999, -999, -999, -999, -999,
  116740. -999, -999, -999, -999, -999, -999, -999, -999},
  116741. {-999, -999, -999, -999, -999, -999, -999, -107,
  116742. -104, -101, -97, -92, -90, -84, -74, -57,
  116743. -58, -52, -55, -54, -50, -52, -50, -52,
  116744. -63, -62, -69, -76, -77, -78, -78, -79,
  116745. -82, -88, -94, -100, -106, -111, -999, -999,
  116746. -999, -999, -999, -999, -999, -999, -999, -999,
  116747. -999, -999, -999, -999, -999, -999, -999, -999},
  116748. {-999, -999, -999, -999, -999, -999, -106, -102,
  116749. -98, -95, -90, -85, -83, -78, -70, -50,
  116750. -50, -41, -44, -49, -47, -50, -50, -44,
  116751. -55, -46, -47, -48, -48, -54, -49, -49,
  116752. -58, -62, -71, -81, -87, -92, -97, -102,
  116753. -108, -114, -999, -999, -999, -999, -999, -999,
  116754. -999, -999, -999, -999, -999, -999, -999, -999},
  116755. {-999, -999, -999, -999, -999, -999, -106, -102,
  116756. -98, -95, -90, -85, -83, -78, -70, -45,
  116757. -43, -41, -47, -50, -51, -50, -49, -45,
  116758. -47, -41, -44, -41, -39, -43, -38, -37,
  116759. -40, -41, -44, -50, -58, -65, -73, -79,
  116760. -85, -92, -97, -101, -105, -109, -113, -999,
  116761. -999, -999, -999, -999, -999, -999, -999, -999}},
  116762. /* 1414 Hz */
  116763. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116764. -999, -999, -999, -107, -100, -95, -87, -81,
  116765. -85, -83, -88, -93, -100, -107, -114, -999,
  116766. -999, -999, -999, -999, -999, -999, -999, -999,
  116767. -999, -999, -999, -999, -999, -999, -999, -999,
  116768. -999, -999, -999, -999, -999, -999, -999, -999,
  116769. -999, -999, -999, -999, -999, -999, -999, -999},
  116770. {-999, -999, -999, -999, -999, -999, -999, -999,
  116771. -999, -999, -107, -101, -95, -88, -83, -76,
  116772. -73, -72, -79, -84, -90, -95, -100, -105,
  116773. -110, -115, -999, -999, -999, -999, -999, -999,
  116774. -999, -999, -999, -999, -999, -999, -999, -999,
  116775. -999, -999, -999, -999, -999, -999, -999, -999,
  116776. -999, -999, -999, -999, -999, -999, -999, -999},
  116777. {-999, -999, -999, -999, -999, -999, -999, -999,
  116778. -999, -999, -104, -98, -92, -87, -81, -70,
  116779. -65, -62, -67, -71, -74, -80, -85, -91,
  116780. -95, -99, -103, -108, -111, -114, -999, -999,
  116781. -999, -999, -999, -999, -999, -999, -999, -999,
  116782. -999, -999, -999, -999, -999, -999, -999, -999,
  116783. -999, -999, -999, -999, -999, -999, -999, -999},
  116784. {-999, -999, -999, -999, -999, -999, -999, -999,
  116785. -999, -999, -103, -97, -90, -85, -76, -60,
  116786. -56, -54, -60, -62, -61, -56, -63, -65,
  116787. -73, -74, -77, -75, -78, -81, -86, -87,
  116788. -88, -91, -94, -98, -103, -110, -999, -999,
  116789. -999, -999, -999, -999, -999, -999, -999, -999,
  116790. -999, -999, -999, -999, -999, -999, -999, -999},
  116791. {-999, -999, -999, -999, -999, -999, -999, -105,
  116792. -100, -97, -92, -86, -81, -79, -70, -57,
  116793. -51, -47, -51, -58, -60, -56, -53, -50,
  116794. -58, -52, -50, -50, -53, -55, -64, -69,
  116795. -71, -85, -82, -78, -81, -85, -95, -102,
  116796. -112, -999, -999, -999, -999, -999, -999, -999,
  116797. -999, -999, -999, -999, -999, -999, -999, -999},
  116798. {-999, -999, -999, -999, -999, -999, -999, -105,
  116799. -100, -97, -92, -85, -83, -79, -72, -49,
  116800. -40, -43, -43, -54, -56, -51, -50, -40,
  116801. -43, -38, -36, -35, -37, -38, -37, -44,
  116802. -54, -60, -57, -60, -70, -75, -84, -92,
  116803. -103, -112, -999, -999, -999, -999, -999, -999,
  116804. -999, -999, -999, -999, -999, -999, -999, -999}},
  116805. /* 2000 Hz */
  116806. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116807. -999, -999, -999, -110, -102, -95, -89, -82,
  116808. -83, -84, -90, -92, -99, -107, -113, -999,
  116809. -999, -999, -999, -999, -999, -999, -999, -999,
  116810. -999, -999, -999, -999, -999, -999, -999, -999,
  116811. -999, -999, -999, -999, -999, -999, -999, -999,
  116812. -999, -999, -999, -999, -999, -999, -999, -999},
  116813. {-999, -999, -999, -999, -999, -999, -999, -999,
  116814. -999, -999, -107, -101, -95, -89, -83, -72,
  116815. -74, -78, -85, -88, -88, -90, -92, -98,
  116816. -105, -111, -999, -999, -999, -999, -999, -999,
  116817. -999, -999, -999, -999, -999, -999, -999, -999,
  116818. -999, -999, -999, -999, -999, -999, -999, -999,
  116819. -999, -999, -999, -999, -999, -999, -999, -999},
  116820. {-999, -999, -999, -999, -999, -999, -999, -999,
  116821. -999, -109, -103, -97, -93, -87, -81, -70,
  116822. -70, -67, -75, -73, -76, -79, -81, -83,
  116823. -88, -89, -97, -103, -110, -999, -999, -999,
  116824. -999, -999, -999, -999, -999, -999, -999, -999,
  116825. -999, -999, -999, -999, -999, -999, -999, -999,
  116826. -999, -999, -999, -999, -999, -999, -999, -999},
  116827. {-999, -999, -999, -999, -999, -999, -999, -999,
  116828. -999, -107, -100, -94, -88, -83, -75, -63,
  116829. -59, -59, -63, -66, -60, -62, -67, -67,
  116830. -77, -76, -81, -88, -86, -92, -96, -102,
  116831. -109, -116, -999, -999, -999, -999, -999, -999,
  116832. -999, -999, -999, -999, -999, -999, -999, -999,
  116833. -999, -999, -999, -999, -999, -999, -999, -999},
  116834. {-999, -999, -999, -999, -999, -999, -999, -999,
  116835. -999, -105, -98, -92, -86, -81, -73, -56,
  116836. -52, -47, -55, -60, -58, -52, -51, -45,
  116837. -49, -50, -53, -54, -61, -71, -70, -69,
  116838. -78, -79, -87, -90, -96, -104, -112, -999,
  116839. -999, -999, -999, -999, -999, -999, -999, -999,
  116840. -999, -999, -999, -999, -999, -999, -999, -999},
  116841. {-999, -999, -999, -999, -999, -999, -999, -999,
  116842. -999, -103, -96, -90, -86, -78, -70, -51,
  116843. -42, -47, -48, -55, -54, -54, -53, -42,
  116844. -35, -28, -33, -38, -37, -44, -47, -49,
  116845. -54, -63, -68, -78, -82, -89, -94, -99,
  116846. -104, -109, -114, -999, -999, -999, -999, -999,
  116847. -999, -999, -999, -999, -999, -999, -999, -999}},
  116848. /* 2828 Hz */
  116849. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116850. -999, -999, -999, -999, -110, -100, -90, -79,
  116851. -85, -81, -82, -82, -89, -94, -99, -103,
  116852. -109, -115, -999, -999, -999, -999, -999, -999,
  116853. -999, -999, -999, -999, -999, -999, -999, -999,
  116854. -999, -999, -999, -999, -999, -999, -999, -999,
  116855. -999, -999, -999, -999, -999, -999, -999, -999},
  116856. {-999, -999, -999, -999, -999, -999, -999, -999,
  116857. -999, -999, -999, -999, -105, -97, -85, -72,
  116858. -74, -70, -70, -70, -76, -85, -91, -93,
  116859. -97, -103, -109, -115, -999, -999, -999, -999,
  116860. -999, -999, -999, -999, -999, -999, -999, -999,
  116861. -999, -999, -999, -999, -999, -999, -999, -999,
  116862. -999, -999, -999, -999, -999, -999, -999, -999},
  116863. {-999, -999, -999, -999, -999, -999, -999, -999,
  116864. -999, -999, -999, -999, -112, -93, -81, -68,
  116865. -62, -60, -60, -57, -63, -70, -77, -82,
  116866. -90, -93, -98, -104, -109, -113, -999, -999,
  116867. -999, -999, -999, -999, -999, -999, -999, -999,
  116868. -999, -999, -999, -999, -999, -999, -999, -999,
  116869. -999, -999, -999, -999, -999, -999, -999, -999},
  116870. {-999, -999, -999, -999, -999, -999, -999, -999,
  116871. -999, -999, -999, -113, -100, -93, -84, -63,
  116872. -58, -48, -53, -54, -52, -52, -57, -64,
  116873. -66, -76, -83, -81, -85, -85, -90, -95,
  116874. -98, -101, -103, -106, -108, -111, -999, -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, -105, -95, -86, -74, -53,
  116879. -50, -38, -43, -49, -43, -42, -39, -39,
  116880. -46, -52, -57, -56, -72, -69, -74, -81,
  116881. -87, -92, -94, -97, -99, -102, -105, -108,
  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, -108, -99, -90, -76, -66, -45,
  116886. -43, -41, -44, -47, -43, -47, -40, -30,
  116887. -31, -31, -39, -33, -40, -41, -43, -53,
  116888. -59, -70, -73, -77, -79, -82, -84, -87,
  116889. -999, -999, -999, -999, -999, -999, -999, -999,
  116890. -999, -999, -999, -999, -999, -999, -999, -999}},
  116891. /* 4000 Hz */
  116892. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116893. -999, -999, -999, -999, -999, -110, -91, -76,
  116894. -75, -85, -93, -98, -104, -110, -999, -999,
  116895. -999, -999, -999, -999, -999, -999, -999, -999,
  116896. -999, -999, -999, -999, -999, -999, -999, -999,
  116897. -999, -999, -999, -999, -999, -999, -999, -999,
  116898. -999, -999, -999, -999, -999, -999, -999, -999},
  116899. {-999, -999, -999, -999, -999, -999, -999, -999,
  116900. -999, -999, -999, -999, -999, -110, -91, -70,
  116901. -70, -75, -86, -89, -94, -98, -101, -106,
  116902. -110, -999, -999, -999, -999, -999, -999, -999,
  116903. -999, -999, -999, -999, -999, -999, -999, -999,
  116904. -999, -999, -999, -999, -999, -999, -999, -999,
  116905. -999, -999, -999, -999, -999, -999, -999, -999},
  116906. {-999, -999, -999, -999, -999, -999, -999, -999,
  116907. -999, -999, -999, -999, -110, -95, -80, -60,
  116908. -65, -64, -74, -83, -88, -91, -95, -99,
  116909. -103, -107, -110, -999, -999, -999, -999, -999,
  116910. -999, -999, -999, -999, -999, -999, -999, -999,
  116911. -999, -999, -999, -999, -999, -999, -999, -999,
  116912. -999, -999, -999, -999, -999, -999, -999, -999},
  116913. {-999, -999, -999, -999, -999, -999, -999, -999,
  116914. -999, -999, -999, -999, -110, -95, -80, -58,
  116915. -55, -49, -66, -68, -71, -78, -78, -80,
  116916. -88, -85, -89, -97, -100, -105, -110, -999,
  116917. -999, -999, -999, -999, -999, -999, -999, -999,
  116918. -999, -999, -999, -999, -999, -999, -999, -999,
  116919. -999, -999, -999, -999, -999, -999, -999, -999},
  116920. {-999, -999, -999, -999, -999, -999, -999, -999,
  116921. -999, -999, -999, -999, -110, -95, -80, -53,
  116922. -52, -41, -59, -59, -49, -58, -56, -63,
  116923. -86, -79, -90, -93, -98, -103, -107, -112,
  116924. -999, -999, -999, -999, -999, -999, -999, -999,
  116925. -999, -999, -999, -999, -999, -999, -999, -999,
  116926. -999, -999, -999, -999, -999, -999, -999, -999},
  116927. {-999, -999, -999, -999, -999, -999, -999, -999,
  116928. -999, -999, -999, -110, -97, -91, -73, -45,
  116929. -40, -33, -53, -61, -49, -54, -50, -50,
  116930. -60, -52, -67, -74, -81, -92, -96, -100,
  116931. -105, -110, -999, -999, -999, -999, -999, -999,
  116932. -999, -999, -999, -999, -999, -999, -999, -999,
  116933. -999, -999, -999, -999, -999, -999, -999, -999}},
  116934. /* 5657 Hz */
  116935. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116936. -999, -999, -999, -113, -106, -99, -92, -77,
  116937. -80, -88, -97, -106, -115, -999, -999, -999,
  116938. -999, -999, -999, -999, -999, -999, -999, -999,
  116939. -999, -999, -999, -999, -999, -999, -999, -999,
  116940. -999, -999, -999, -999, -999, -999, -999, -999,
  116941. -999, -999, -999, -999, -999, -999, -999, -999},
  116942. {-999, -999, -999, -999, -999, -999, -999, -999,
  116943. -999, -999, -116, -109, -102, -95, -89, -74,
  116944. -72, -88, -87, -95, -102, -109, -116, -999,
  116945. -999, -999, -999, -999, -999, -999, -999, -999,
  116946. -999, -999, -999, -999, -999, -999, -999, -999,
  116947. -999, -999, -999, -999, -999, -999, -999, -999,
  116948. -999, -999, -999, -999, -999, -999, -999, -999},
  116949. {-999, -999, -999, -999, -999, -999, -999, -999,
  116950. -999, -999, -116, -109, -102, -95, -89, -75,
  116951. -66, -74, -77, -78, -86, -87, -90, -96,
  116952. -105, -115, -999, -999, -999, -999, -999, -999,
  116953. -999, -999, -999, -999, -999, -999, -999, -999,
  116954. -999, -999, -999, -999, -999, -999, -999, -999,
  116955. -999, -999, -999, -999, -999, -999, -999, -999},
  116956. {-999, -999, -999, -999, -999, -999, -999, -999,
  116957. -999, -999, -115, -108, -101, -94, -88, -66,
  116958. -56, -61, -70, -65, -78, -72, -83, -84,
  116959. -93, -98, -105, -110, -999, -999, -999, -999,
  116960. -999, -999, -999, -999, -999, -999, -999, -999,
  116961. -999, -999, -999, -999, -999, -999, -999, -999,
  116962. -999, -999, -999, -999, -999, -999, -999, -999},
  116963. {-999, -999, -999, -999, -999, -999, -999, -999,
  116964. -999, -999, -110, -105, -95, -89, -82, -57,
  116965. -52, -52, -59, -56, -59, -58, -69, -67,
  116966. -88, -82, -82, -89, -94, -100, -108, -999,
  116967. -999, -999, -999, -999, -999, -999, -999, -999,
  116968. -999, -999, -999, -999, -999, -999, -999, -999,
  116969. -999, -999, -999, -999, -999, -999, -999, -999},
  116970. {-999, -999, -999, -999, -999, -999, -999, -999,
  116971. -999, -110, -101, -96, -90, -83, -77, -54,
  116972. -43, -38, -50, -48, -52, -48, -42, -42,
  116973. -51, -52, -53, -59, -65, -71, -78, -85,
  116974. -95, -999, -999, -999, -999, -999, -999, -999,
  116975. -999, -999, -999, -999, -999, -999, -999, -999,
  116976. -999, -999, -999, -999, -999, -999, -999, -999}},
  116977. /* 8000 Hz */
  116978. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116979. -999, -999, -999, -999, -120, -105, -86, -68,
  116980. -78, -79, -90, -100, -110, -999, -999, -999,
  116981. -999, -999, -999, -999, -999, -999, -999, -999,
  116982. -999, -999, -999, -999, -999, -999, -999, -999,
  116983. -999, -999, -999, -999, -999, -999, -999, -999,
  116984. -999, -999, -999, -999, -999, -999, -999, -999},
  116985. {-999, -999, -999, -999, -999, -999, -999, -999,
  116986. -999, -999, -999, -999, -120, -105, -86, -66,
  116987. -73, -77, -88, -96, -105, -115, -999, -999,
  116988. -999, -999, -999, -999, -999, -999, -999, -999,
  116989. -999, -999, -999, -999, -999, -999, -999, -999,
  116990. -999, -999, -999, -999, -999, -999, -999, -999,
  116991. -999, -999, -999, -999, -999, -999, -999, -999},
  116992. {-999, -999, -999, -999, -999, -999, -999, -999,
  116993. -999, -999, -999, -120, -105, -92, -80, -61,
  116994. -64, -68, -80, -87, -92, -100, -110, -999,
  116995. -999, -999, -999, -999, -999, -999, -999, -999,
  116996. -999, -999, -999, -999, -999, -999, -999, -999,
  116997. -999, -999, -999, -999, -999, -999, -999, -999,
  116998. -999, -999, -999, -999, -999, -999, -999, -999},
  116999. {-999, -999, -999, -999, -999, -999, -999, -999,
  117000. -999, -999, -999, -120, -104, -91, -79, -52,
  117001. -60, -54, -64, -69, -77, -80, -82, -84,
  117002. -85, -87, -88, -90, -999, -999, -999, -999,
  117003. -999, -999, -999, -999, -999, -999, -999, -999,
  117004. -999, -999, -999, -999, -999, -999, -999, -999,
  117005. -999, -999, -999, -999, -999, -999, -999, -999},
  117006. {-999, -999, -999, -999, -999, -999, -999, -999,
  117007. -999, -999, -999, -118, -100, -87, -77, -49,
  117008. -50, -44, -58, -61, -61, -67, -65, -62,
  117009. -62, -62, -65, -68, -999, -999, -999, -999,
  117010. -999, -999, -999, -999, -999, -999, -999, -999,
  117011. -999, -999, -999, -999, -999, -999, -999, -999,
  117012. -999, -999, -999, -999, -999, -999, -999, -999},
  117013. {-999, -999, -999, -999, -999, -999, -999, -999,
  117014. -999, -999, -999, -115, -98, -84, -62, -49,
  117015. -44, -38, -46, -49, -49, -46, -39, -37,
  117016. -39, -40, -42, -43, -999, -999, -999, -999,
  117017. -999, -999, -999, -999, -999, -999, -999, -999,
  117018. -999, -999, -999, -999, -999, -999, -999, -999,
  117019. -999, -999, -999, -999, -999, -999, -999, -999}},
  117020. /* 11314 Hz */
  117021. {{-999, -999, -999, -999, -999, -999, -999, -999,
  117022. -999, -999, -999, -999, -999, -110, -88, -74,
  117023. -77, -82, -82, -85, -90, -94, -99, -104,
  117024. -999, -999, -999, -999, -999, -999, -999, -999,
  117025. -999, -999, -999, -999, -999, -999, -999, -999,
  117026. -999, -999, -999, -999, -999, -999, -999, -999,
  117027. -999, -999, -999, -999, -999, -999, -999, -999},
  117028. {-999, -999, -999, -999, -999, -999, -999, -999,
  117029. -999, -999, -999, -999, -999, -110, -88, -66,
  117030. -70, -81, -80, -81, -84, -88, -91, -93,
  117031. -999, -999, -999, -999, -999, -999, -999, -999,
  117032. -999, -999, -999, -999, -999, -999, -999, -999,
  117033. -999, -999, -999, -999, -999, -999, -999, -999,
  117034. -999, -999, -999, -999, -999, -999, -999, -999},
  117035. {-999, -999, -999, -999, -999, -999, -999, -999,
  117036. -999, -999, -999, -999, -999, -110, -88, -61,
  117037. -63, -70, -71, -74, -77, -80, -83, -85,
  117038. -999, -999, -999, -999, -999, -999, -999, -999,
  117039. -999, -999, -999, -999, -999, -999, -999, -999,
  117040. -999, -999, -999, -999, -999, -999, -999, -999,
  117041. -999, -999, -999, -999, -999, -999, -999, -999},
  117042. {-999, -999, -999, -999, -999, -999, -999, -999,
  117043. -999, -999, -999, -999, -999, -110, -86, -62,
  117044. -63, -62, -62, -58, -52, -50, -50, -52,
  117045. -54, -999, -999, -999, -999, -999, -999, -999,
  117046. -999, -999, -999, -999, -999, -999, -999, -999,
  117047. -999, -999, -999, -999, -999, -999, -999, -999,
  117048. -999, -999, -999, -999, -999, -999, -999, -999},
  117049. {-999, -999, -999, -999, -999, -999, -999, -999,
  117050. -999, -999, -999, -999, -118, -108, -84, -53,
  117051. -50, -50, -50, -55, -47, -45, -40, -40,
  117052. -40, -999, -999, -999, -999, -999, -999, -999,
  117053. -999, -999, -999, -999, -999, -999, -999, -999,
  117054. -999, -999, -999, -999, -999, -999, -999, -999,
  117055. -999, -999, -999, -999, -999, -999, -999, -999},
  117056. {-999, -999, -999, -999, -999, -999, -999, -999,
  117057. -999, -999, -999, -999, -118, -100, -73, -43,
  117058. -37, -42, -43, -53, -38, -37, -35, -35,
  117059. -38, -999, -999, -999, -999, -999, -999, -999,
  117060. -999, -999, -999, -999, -999, -999, -999, -999,
  117061. -999, -999, -999, -999, -999, -999, -999, -999,
  117062. -999, -999, -999, -999, -999, -999, -999, -999}},
  117063. /* 16000 Hz */
  117064. {{-999, -999, -999, -999, -999, -999, -999, -999,
  117065. -999, -999, -999, -110, -100, -91, -84, -74,
  117066. -80, -80, -80, -80, -80, -999, -999, -999,
  117067. -999, -999, -999, -999, -999, -999, -999, -999,
  117068. -999, -999, -999, -999, -999, -999, -999, -999,
  117069. -999, -999, -999, -999, -999, -999, -999, -999,
  117070. -999, -999, -999, -999, -999, -999, -999, -999},
  117071. {-999, -999, -999, -999, -999, -999, -999, -999,
  117072. -999, -999, -999, -110, -100, -91, -84, -74,
  117073. -68, -68, -68, -68, -68, -999, -999, -999,
  117074. -999, -999, -999, -999, -999, -999, -999, -999,
  117075. -999, -999, -999, -999, -999, -999, -999, -999,
  117076. -999, -999, -999, -999, -999, -999, -999, -999,
  117077. -999, -999, -999, -999, -999, -999, -999, -999},
  117078. {-999, -999, -999, -999, -999, -999, -999, -999,
  117079. -999, -999, -999, -110, -100, -86, -78, -70,
  117080. -60, -45, -30, -21, -999, -999, -999, -999,
  117081. -999, -999, -999, -999, -999, -999, -999, -999,
  117082. -999, -999, -999, -999, -999, -999, -999, -999,
  117083. -999, -999, -999, -999, -999, -999, -999, -999,
  117084. -999, -999, -999, -999, -999, -999, -999, -999},
  117085. {-999, -999, -999, -999, -999, -999, -999, -999,
  117086. -999, -999, -999, -110, -100, -87, -78, -67,
  117087. -48, -38, -29, -21, -999, -999, -999, -999,
  117088. -999, -999, -999, -999, -999, -999, -999, -999,
  117089. -999, -999, -999, -999, -999, -999, -999, -999,
  117090. -999, -999, -999, -999, -999, -999, -999, -999,
  117091. -999, -999, -999, -999, -999, -999, -999, -999},
  117092. {-999, -999, -999, -999, -999, -999, -999, -999,
  117093. -999, -999, -999, -110, -100, -86, -69, -56,
  117094. -45, -35, -33, -29, -999, -999, -999, -999,
  117095. -999, -999, -999, -999, -999, -999, -999, -999,
  117096. -999, -999, -999, -999, -999, -999, -999, -999,
  117097. -999, -999, -999, -999, -999, -999, -999, -999,
  117098. -999, -999, -999, -999, -999, -999, -999, -999},
  117099. {-999, -999, -999, -999, -999, -999, -999, -999,
  117100. -999, -999, -999, -110, -100, -83, -71, -48,
  117101. -27, -38, -37, -34, -999, -999, -999, -999,
  117102. -999, -999, -999, -999, -999, -999, -999, -999,
  117103. -999, -999, -999, -999, -999, -999, -999, -999,
  117104. -999, -999, -999, -999, -999, -999, -999, -999,
  117105. -999, -999, -999, -999, -999, -999, -999, -999}}
  117106. };
  117107. #endif
  117108. /*** End of inlined file: masking.h ***/
  117109. #define NEGINF -9999.f
  117110. static double stereo_threshholds[]={0.0, .5, 1.0, 1.5, 2.5, 4.5, 8.5, 16.5, 9e10};
  117111. static double stereo_threshholds_limited[]={0.0, .5, 1.0, 1.5, 2.0, 2.5, 4.5, 8.5, 9e10};
  117112. vorbis_look_psy_global *_vp_global_look(vorbis_info *vi){
  117113. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  117114. vorbis_info_psy_global *gi=&ci->psy_g_param;
  117115. vorbis_look_psy_global *look=(vorbis_look_psy_global*)_ogg_calloc(1,sizeof(*look));
  117116. look->channels=vi->channels;
  117117. look->ampmax=-9999.;
  117118. look->gi=gi;
  117119. return(look);
  117120. }
  117121. void _vp_global_free(vorbis_look_psy_global *look){
  117122. if(look){
  117123. memset(look,0,sizeof(*look));
  117124. _ogg_free(look);
  117125. }
  117126. }
  117127. void _vi_gpsy_free(vorbis_info_psy_global *i){
  117128. if(i){
  117129. memset(i,0,sizeof(*i));
  117130. _ogg_free(i);
  117131. }
  117132. }
  117133. void _vi_psy_free(vorbis_info_psy *i){
  117134. if(i){
  117135. memset(i,0,sizeof(*i));
  117136. _ogg_free(i);
  117137. }
  117138. }
  117139. static void min_curve(float *c,
  117140. float *c2){
  117141. int i;
  117142. for(i=0;i<EHMER_MAX;i++)if(c2[i]<c[i])c[i]=c2[i];
  117143. }
  117144. static void max_curve(float *c,
  117145. float *c2){
  117146. int i;
  117147. for(i=0;i<EHMER_MAX;i++)if(c2[i]>c[i])c[i]=c2[i];
  117148. }
  117149. static void attenuate_curve(float *c,float att){
  117150. int i;
  117151. for(i=0;i<EHMER_MAX;i++)
  117152. c[i]+=att;
  117153. }
  117154. static float ***setup_tone_curves(float curveatt_dB[P_BANDS],float binHz,int n,
  117155. float center_boost, float center_decay_rate){
  117156. int i,j,k,m;
  117157. float ath[EHMER_MAX];
  117158. float workc[P_BANDS][P_LEVELS][EHMER_MAX];
  117159. float athc[P_LEVELS][EHMER_MAX];
  117160. float *brute_buffer=(float*) alloca(n*sizeof(*brute_buffer));
  117161. float ***ret=(float***) _ogg_malloc(sizeof(*ret)*P_BANDS);
  117162. memset(workc,0,sizeof(workc));
  117163. for(i=0;i<P_BANDS;i++){
  117164. /* we add back in the ATH to avoid low level curves falling off to
  117165. -infinity and unnecessarily cutting off high level curves in the
  117166. curve limiting (last step). */
  117167. /* A half-band's settings must be valid over the whole band, and
  117168. it's better to mask too little than too much */
  117169. int ath_offset=i*4;
  117170. for(j=0;j<EHMER_MAX;j++){
  117171. float min=999.;
  117172. for(k=0;k<4;k++)
  117173. if(j+k+ath_offset<MAX_ATH){
  117174. if(min>ATH[j+k+ath_offset])min=ATH[j+k+ath_offset];
  117175. }else{
  117176. if(min>ATH[MAX_ATH-1])min=ATH[MAX_ATH-1];
  117177. }
  117178. ath[j]=min;
  117179. }
  117180. /* copy curves into working space, replicate the 50dB curve to 30
  117181. and 40, replicate the 100dB curve to 110 */
  117182. for(j=0;j<6;j++)
  117183. memcpy(workc[i][j+2],tonemasks[i][j],EHMER_MAX*sizeof(*tonemasks[i][j]));
  117184. memcpy(workc[i][0],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  117185. memcpy(workc[i][1],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  117186. /* apply centered curve boost/decay */
  117187. for(j=0;j<P_LEVELS;j++){
  117188. for(k=0;k<EHMER_MAX;k++){
  117189. float adj=center_boost+abs(EHMER_OFFSET-k)*center_decay_rate;
  117190. if(adj<0. && center_boost>0)adj=0.;
  117191. if(adj>0. && center_boost<0)adj=0.;
  117192. workc[i][j][k]+=adj;
  117193. }
  117194. }
  117195. /* normalize curves so the driving amplitude is 0dB */
  117196. /* make temp curves with the ATH overlayed */
  117197. for(j=0;j<P_LEVELS;j++){
  117198. attenuate_curve(workc[i][j],curveatt_dB[i]+100.-(j<2?2:j)*10.-P_LEVEL_0);
  117199. memcpy(athc[j],ath,EHMER_MAX*sizeof(**athc));
  117200. attenuate_curve(athc[j],+100.-j*10.f-P_LEVEL_0);
  117201. max_curve(athc[j],workc[i][j]);
  117202. }
  117203. /* Now limit the louder curves.
  117204. the idea is this: We don't know what the playback attenuation
  117205. will be; 0dB SL moves every time the user twiddles the volume
  117206. knob. So that means we have to use a single 'most pessimal' curve
  117207. for all masking amplitudes, right? Wrong. The *loudest* sound
  117208. can be in (we assume) a range of ...+100dB] SL. However, sounds
  117209. 20dB down will be in a range ...+80], 40dB down is from ...+60],
  117210. etc... */
  117211. for(j=1;j<P_LEVELS;j++){
  117212. min_curve(athc[j],athc[j-1]);
  117213. min_curve(workc[i][j],athc[j]);
  117214. }
  117215. }
  117216. for(i=0;i<P_BANDS;i++){
  117217. int hi_curve,lo_curve,bin;
  117218. ret[i]=(float**)_ogg_malloc(sizeof(**ret)*P_LEVELS);
  117219. /* low frequency curves are measured with greater resolution than
  117220. the MDCT/FFT will actually give us; we want the curve applied
  117221. to the tone data to be pessimistic and thus apply the minimum
  117222. masking possible for a given bin. That means that a single bin
  117223. could span more than one octave and that the curve will be a
  117224. composite of multiple octaves. It also may mean that a single
  117225. bin may span > an eighth of an octave and that the eighth
  117226. octave values may also be composited. */
  117227. /* which octave curves will we be compositing? */
  117228. bin=floor(fromOC(i*.5)/binHz);
  117229. lo_curve= ceil(toOC(bin*binHz+1)*2);
  117230. hi_curve= floor(toOC((bin+1)*binHz)*2);
  117231. if(lo_curve>i)lo_curve=i;
  117232. if(lo_curve<0)lo_curve=0;
  117233. if(hi_curve>=P_BANDS)hi_curve=P_BANDS-1;
  117234. for(m=0;m<P_LEVELS;m++){
  117235. ret[i][m]=(float*)_ogg_malloc(sizeof(***ret)*(EHMER_MAX+2));
  117236. for(j=0;j<n;j++)brute_buffer[j]=999.;
  117237. /* render the curve into bins, then pull values back into curve.
  117238. The point is that any inherent subsampling aliasing results in
  117239. a safe minimum */
  117240. for(k=lo_curve;k<=hi_curve;k++){
  117241. int l=0;
  117242. for(j=0;j<EHMER_MAX;j++){
  117243. int lo_bin= fromOC(j*.125+k*.5-2.0625)/binHz;
  117244. int hi_bin= fromOC(j*.125+k*.5-1.9375)/binHz+1;
  117245. if(lo_bin<0)lo_bin=0;
  117246. if(lo_bin>n)lo_bin=n;
  117247. if(lo_bin<l)l=lo_bin;
  117248. if(hi_bin<0)hi_bin=0;
  117249. if(hi_bin>n)hi_bin=n;
  117250. for(;l<hi_bin && l<n;l++)
  117251. if(brute_buffer[l]>workc[k][m][j])
  117252. brute_buffer[l]=workc[k][m][j];
  117253. }
  117254. for(;l<n;l++)
  117255. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  117256. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  117257. }
  117258. /* be equally paranoid about being valid up to next half ocatve */
  117259. if(i+1<P_BANDS){
  117260. int l=0;
  117261. k=i+1;
  117262. for(j=0;j<EHMER_MAX;j++){
  117263. int lo_bin= fromOC(j*.125+i*.5-2.0625)/binHz;
  117264. int hi_bin= fromOC(j*.125+i*.5-1.9375)/binHz+1;
  117265. if(lo_bin<0)lo_bin=0;
  117266. if(lo_bin>n)lo_bin=n;
  117267. if(lo_bin<l)l=lo_bin;
  117268. if(hi_bin<0)hi_bin=0;
  117269. if(hi_bin>n)hi_bin=n;
  117270. for(;l<hi_bin && l<n;l++)
  117271. if(brute_buffer[l]>workc[k][m][j])
  117272. brute_buffer[l]=workc[k][m][j];
  117273. }
  117274. for(;l<n;l++)
  117275. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  117276. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  117277. }
  117278. for(j=0;j<EHMER_MAX;j++){
  117279. int bin=fromOC(j*.125+i*.5-2.)/binHz;
  117280. if(bin<0){
  117281. ret[i][m][j+2]=-999.;
  117282. }else{
  117283. if(bin>=n){
  117284. ret[i][m][j+2]=-999.;
  117285. }else{
  117286. ret[i][m][j+2]=brute_buffer[bin];
  117287. }
  117288. }
  117289. }
  117290. /* add fenceposts */
  117291. for(j=0;j<EHMER_OFFSET;j++)
  117292. if(ret[i][m][j+2]>-200.f)break;
  117293. ret[i][m][0]=j;
  117294. for(j=EHMER_MAX-1;j>EHMER_OFFSET+1;j--)
  117295. if(ret[i][m][j+2]>-200.f)
  117296. break;
  117297. ret[i][m][1]=j;
  117298. }
  117299. }
  117300. return(ret);
  117301. }
  117302. void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  117303. vorbis_info_psy_global *gi,int n,long rate){
  117304. long i,j,lo=-99,hi=1;
  117305. long maxoc;
  117306. memset(p,0,sizeof(*p));
  117307. p->eighth_octave_lines=gi->eighth_octave_lines;
  117308. p->shiftoc=rint(log(gi->eighth_octave_lines*8.f)/log(2.f))-1;
  117309. p->firstoc=toOC(.25f*rate*.5/n)*(1<<(p->shiftoc+1))-gi->eighth_octave_lines;
  117310. maxoc=toOC((n+.25f)*rate*.5/n)*(1<<(p->shiftoc+1))+.5f;
  117311. p->total_octave_lines=maxoc-p->firstoc+1;
  117312. p->ath=(float*)_ogg_malloc(n*sizeof(*p->ath));
  117313. p->octave=(long*)_ogg_malloc(n*sizeof(*p->octave));
  117314. p->bark=(long*)_ogg_malloc(n*sizeof(*p->bark));
  117315. p->vi=vi;
  117316. p->n=n;
  117317. p->rate=rate;
  117318. /* AoTuV HF weighting */
  117319. p->m_val = 1.;
  117320. if(rate < 26000) p->m_val = 0;
  117321. else if(rate < 38000) p->m_val = .94; /* 32kHz */
  117322. else if(rate > 46000) p->m_val = 1.275; /* 48kHz */
  117323. /* set up the lookups for a given blocksize and sample rate */
  117324. for(i=0,j=0;i<MAX_ATH-1;i++){
  117325. int endpos=rint(fromOC((i+1)*.125-2.)*2*n/rate);
  117326. float base=ATH[i];
  117327. if(j<endpos){
  117328. float delta=(ATH[i+1]-base)/(endpos-j);
  117329. for(;j<endpos && j<n;j++){
  117330. p->ath[j]=base+100.;
  117331. base+=delta;
  117332. }
  117333. }
  117334. }
  117335. for(i=0;i<n;i++){
  117336. float bark=toBARK(rate/(2*n)*i);
  117337. for(;lo+vi->noisewindowlomin<i &&
  117338. toBARK(rate/(2*n)*lo)<(bark-vi->noisewindowlo);lo++);
  117339. for(;hi<=n && (hi<i+vi->noisewindowhimin ||
  117340. toBARK(rate/(2*n)*hi)<(bark+vi->noisewindowhi));hi++);
  117341. p->bark[i]=((lo-1)<<16)+(hi-1);
  117342. }
  117343. for(i=0;i<n;i++)
  117344. p->octave[i]=toOC((i+.25f)*.5*rate/n)*(1<<(p->shiftoc+1))+.5f;
  117345. p->tonecurves=setup_tone_curves(vi->toneatt,rate*.5/n,n,
  117346. vi->tone_centerboost,vi->tone_decay);
  117347. /* set up rolling noise median */
  117348. p->noiseoffset=(float**)_ogg_malloc(P_NOISECURVES*sizeof(*p->noiseoffset));
  117349. for(i=0;i<P_NOISECURVES;i++)
  117350. p->noiseoffset[i]=(float*)_ogg_malloc(n*sizeof(**p->noiseoffset));
  117351. for(i=0;i<n;i++){
  117352. float halfoc=toOC((i+.5)*rate/(2.*n))*2.;
  117353. int inthalfoc;
  117354. float del;
  117355. if(halfoc<0)halfoc=0;
  117356. if(halfoc>=P_BANDS-1)halfoc=P_BANDS-1;
  117357. inthalfoc=(int)halfoc;
  117358. del=halfoc-inthalfoc;
  117359. for(j=0;j<P_NOISECURVES;j++)
  117360. p->noiseoffset[j][i]=
  117361. p->vi->noiseoff[j][inthalfoc]*(1.-del) +
  117362. p->vi->noiseoff[j][inthalfoc+1]*del;
  117363. }
  117364. #if 0
  117365. {
  117366. static int ls=0;
  117367. _analysis_output_always("noiseoff0",ls,p->noiseoffset[0],n,1,0,0);
  117368. _analysis_output_always("noiseoff1",ls,p->noiseoffset[1],n,1,0,0);
  117369. _analysis_output_always("noiseoff2",ls++,p->noiseoffset[2],n,1,0,0);
  117370. }
  117371. #endif
  117372. }
  117373. void _vp_psy_clear(vorbis_look_psy *p){
  117374. int i,j;
  117375. if(p){
  117376. if(p->ath)_ogg_free(p->ath);
  117377. if(p->octave)_ogg_free(p->octave);
  117378. if(p->bark)_ogg_free(p->bark);
  117379. if(p->tonecurves){
  117380. for(i=0;i<P_BANDS;i++){
  117381. for(j=0;j<P_LEVELS;j++){
  117382. _ogg_free(p->tonecurves[i][j]);
  117383. }
  117384. _ogg_free(p->tonecurves[i]);
  117385. }
  117386. _ogg_free(p->tonecurves);
  117387. }
  117388. if(p->noiseoffset){
  117389. for(i=0;i<P_NOISECURVES;i++){
  117390. _ogg_free(p->noiseoffset[i]);
  117391. }
  117392. _ogg_free(p->noiseoffset);
  117393. }
  117394. memset(p,0,sizeof(*p));
  117395. }
  117396. }
  117397. /* octave/(8*eighth_octave_lines) x scale and dB y scale */
  117398. static void seed_curve(float *seed,
  117399. const float **curves,
  117400. float amp,
  117401. int oc, int n,
  117402. int linesper,float dBoffset){
  117403. int i,post1;
  117404. int seedptr;
  117405. const float *posts,*curve;
  117406. int choice=(int)((amp+dBoffset-P_LEVEL_0)*.1f);
  117407. choice=max(choice,0);
  117408. choice=min(choice,P_LEVELS-1);
  117409. posts=curves[choice];
  117410. curve=posts+2;
  117411. post1=(int)posts[1];
  117412. seedptr=oc+(posts[0]-EHMER_OFFSET)*linesper-(linesper>>1);
  117413. for(i=posts[0];i<post1;i++){
  117414. if(seedptr>0){
  117415. float lin=amp+curve[i];
  117416. if(seed[seedptr]<lin)seed[seedptr]=lin;
  117417. }
  117418. seedptr+=linesper;
  117419. if(seedptr>=n)break;
  117420. }
  117421. }
  117422. static void seed_loop(vorbis_look_psy *p,
  117423. const float ***curves,
  117424. const float *f,
  117425. const float *flr,
  117426. float *seed,
  117427. float specmax){
  117428. vorbis_info_psy *vi=p->vi;
  117429. long n=p->n,i;
  117430. float dBoffset=vi->max_curve_dB-specmax;
  117431. /* prime the working vector with peak values */
  117432. for(i=0;i<n;i++){
  117433. float max=f[i];
  117434. long oc=p->octave[i];
  117435. while(i+1<n && p->octave[i+1]==oc){
  117436. i++;
  117437. if(f[i]>max)max=f[i];
  117438. }
  117439. if(max+6.f>flr[i]){
  117440. oc=oc>>p->shiftoc;
  117441. if(oc>=P_BANDS)oc=P_BANDS-1;
  117442. if(oc<0)oc=0;
  117443. seed_curve(seed,
  117444. curves[oc],
  117445. max,
  117446. p->octave[i]-p->firstoc,
  117447. p->total_octave_lines,
  117448. p->eighth_octave_lines,
  117449. dBoffset);
  117450. }
  117451. }
  117452. }
  117453. static void seed_chase(float *seeds, int linesper, long n){
  117454. long *posstack=(long*)alloca(n*sizeof(*posstack));
  117455. float *ampstack=(float*)alloca(n*sizeof(*ampstack));
  117456. long stack=0;
  117457. long pos=0;
  117458. long i;
  117459. for(i=0;i<n;i++){
  117460. if(stack<2){
  117461. posstack[stack]=i;
  117462. ampstack[stack++]=seeds[i];
  117463. }else{
  117464. while(1){
  117465. if(seeds[i]<ampstack[stack-1]){
  117466. posstack[stack]=i;
  117467. ampstack[stack++]=seeds[i];
  117468. break;
  117469. }else{
  117470. if(i<posstack[stack-1]+linesper){
  117471. if(stack>1 && ampstack[stack-1]<=ampstack[stack-2] &&
  117472. i<posstack[stack-2]+linesper){
  117473. /* we completely overlap, making stack-1 irrelevant. pop it */
  117474. stack--;
  117475. continue;
  117476. }
  117477. }
  117478. posstack[stack]=i;
  117479. ampstack[stack++]=seeds[i];
  117480. break;
  117481. }
  117482. }
  117483. }
  117484. }
  117485. /* the stack now contains only the positions that are relevant. Scan
  117486. 'em straight through */
  117487. for(i=0;i<stack;i++){
  117488. long endpos;
  117489. if(i<stack-1 && ampstack[i+1]>ampstack[i]){
  117490. endpos=posstack[i+1];
  117491. }else{
  117492. endpos=posstack[i]+linesper+1; /* +1 is important, else bin 0 is
  117493. discarded in short frames */
  117494. }
  117495. if(endpos>n)endpos=n;
  117496. for(;pos<endpos;pos++)
  117497. seeds[pos]=ampstack[i];
  117498. }
  117499. /* there. Linear time. I now remember this was on a problem set I
  117500. had in Grad Skool... I didn't solve it at the time ;-) */
  117501. }
  117502. /* bleaugh, this is more complicated than it needs to be */
  117503. #include<stdio.h>
  117504. static void max_seeds(vorbis_look_psy *p,
  117505. float *seed,
  117506. float *flr){
  117507. long n=p->total_octave_lines;
  117508. int linesper=p->eighth_octave_lines;
  117509. long linpos=0;
  117510. long pos;
  117511. seed_chase(seed,linesper,n); /* for masking */
  117512. pos=p->octave[0]-p->firstoc-(linesper>>1);
  117513. while(linpos+1<p->n){
  117514. float minV=seed[pos];
  117515. long end=((p->octave[linpos]+p->octave[linpos+1])>>1)-p->firstoc;
  117516. if(minV>p->vi->tone_abs_limit)minV=p->vi->tone_abs_limit;
  117517. while(pos+1<=end){
  117518. pos++;
  117519. if((seed[pos]>NEGINF && seed[pos]<minV) || minV==NEGINF)
  117520. minV=seed[pos];
  117521. }
  117522. end=pos+p->firstoc;
  117523. for(;linpos<p->n && p->octave[linpos]<=end;linpos++)
  117524. if(flr[linpos]<minV)flr[linpos]=minV;
  117525. }
  117526. {
  117527. float minV=seed[p->total_octave_lines-1];
  117528. for(;linpos<p->n;linpos++)
  117529. if(flr[linpos]<minV)flr[linpos]=minV;
  117530. }
  117531. }
  117532. static void bark_noise_hybridmp(int n,const long *b,
  117533. const float *f,
  117534. float *noise,
  117535. const float offset,
  117536. const int fixed){
  117537. float *N=(float*) alloca(n*sizeof(*N));
  117538. float *X=(float*) alloca(n*sizeof(*N));
  117539. float *XX=(float*) alloca(n*sizeof(*N));
  117540. float *Y=(float*) alloca(n*sizeof(*N));
  117541. float *XY=(float*) alloca(n*sizeof(*N));
  117542. float tN, tX, tXX, tY, tXY;
  117543. int i;
  117544. int lo, hi;
  117545. float R, A, B, D;
  117546. float w, x, y;
  117547. tN = tX = tXX = tY = tXY = 0.f;
  117548. y = f[0] + offset;
  117549. if (y < 1.f) y = 1.f;
  117550. w = y * y * .5;
  117551. tN += w;
  117552. tX += w;
  117553. tY += w * y;
  117554. N[0] = tN;
  117555. X[0] = tX;
  117556. XX[0] = tXX;
  117557. Y[0] = tY;
  117558. XY[0] = tXY;
  117559. for (i = 1, x = 1.f; i < n; i++, x += 1.f) {
  117560. y = f[i] + offset;
  117561. if (y < 1.f) y = 1.f;
  117562. w = y * y;
  117563. tN += w;
  117564. tX += w * x;
  117565. tXX += w * x * x;
  117566. tY += w * y;
  117567. tXY += w * x * y;
  117568. N[i] = tN;
  117569. X[i] = tX;
  117570. XX[i] = tXX;
  117571. Y[i] = tY;
  117572. XY[i] = tXY;
  117573. }
  117574. for (i = 0, x = 0.f;; i++, x += 1.f) {
  117575. lo = b[i] >> 16;
  117576. if( lo>=0 ) break;
  117577. hi = b[i] & 0xffff;
  117578. tN = N[hi] + N[-lo];
  117579. tX = X[hi] - X[-lo];
  117580. tXX = XX[hi] + XX[-lo];
  117581. tY = Y[hi] + Y[-lo];
  117582. tXY = XY[hi] - XY[-lo];
  117583. A = tY * tXX - tX * tXY;
  117584. B = tN * tXY - tX * tY;
  117585. D = tN * tXX - tX * tX;
  117586. R = (A + x * B) / D;
  117587. if (R < 0.f)
  117588. R = 0.f;
  117589. noise[i] = R - offset;
  117590. }
  117591. for ( ;; i++, x += 1.f) {
  117592. lo = b[i] >> 16;
  117593. hi = b[i] & 0xffff;
  117594. if(hi>=n)break;
  117595. tN = N[hi] - N[lo];
  117596. tX = X[hi] - X[lo];
  117597. tXX = XX[hi] - XX[lo];
  117598. tY = Y[hi] - Y[lo];
  117599. tXY = XY[hi] - XY[lo];
  117600. A = tY * tXX - tX * tXY;
  117601. B = tN * tXY - tX * tY;
  117602. D = tN * tXX - tX * tX;
  117603. R = (A + x * B) / D;
  117604. if (R < 0.f) R = 0.f;
  117605. noise[i] = R - offset;
  117606. }
  117607. for ( ; i < n; i++, x += 1.f) {
  117608. R = (A + x * B) / D;
  117609. if (R < 0.f) R = 0.f;
  117610. noise[i] = R - offset;
  117611. }
  117612. if (fixed <= 0) return;
  117613. for (i = 0, x = 0.f;; i++, x += 1.f) {
  117614. hi = i + fixed / 2;
  117615. lo = hi - fixed;
  117616. if(lo>=0)break;
  117617. tN = N[hi] + N[-lo];
  117618. tX = X[hi] - X[-lo];
  117619. tXX = XX[hi] + XX[-lo];
  117620. tY = Y[hi] + Y[-lo];
  117621. tXY = XY[hi] - XY[-lo];
  117622. A = tY * tXX - tX * tXY;
  117623. B = tN * tXY - tX * tY;
  117624. D = tN * tXX - tX * tX;
  117625. R = (A + x * B) / D;
  117626. if (R - offset < noise[i]) noise[i] = R - offset;
  117627. }
  117628. for ( ;; i++, x += 1.f) {
  117629. hi = i + fixed / 2;
  117630. lo = hi - fixed;
  117631. if(hi>=n)break;
  117632. tN = N[hi] - N[lo];
  117633. tX = X[hi] - X[lo];
  117634. tXX = XX[hi] - XX[lo];
  117635. tY = Y[hi] - Y[lo];
  117636. tXY = XY[hi] - XY[lo];
  117637. A = tY * tXX - tX * tXY;
  117638. B = tN * tXY - tX * tY;
  117639. D = tN * tXX - tX * tX;
  117640. R = (A + x * B) / D;
  117641. if (R - offset < noise[i]) noise[i] = R - offset;
  117642. }
  117643. for ( ; i < n; i++, x += 1.f) {
  117644. R = (A + x * B) / D;
  117645. if (R - offset < noise[i]) noise[i] = R - offset;
  117646. }
  117647. }
  117648. static float FLOOR1_fromdB_INV_LOOKUP[256]={
  117649. 0.F, 8.81683e+06F, 8.27882e+06F, 7.77365e+06F,
  117650. 7.29930e+06F, 6.85389e+06F, 6.43567e+06F, 6.04296e+06F,
  117651. 5.67422e+06F, 5.32798e+06F, 5.00286e+06F, 4.69759e+06F,
  117652. 4.41094e+06F, 4.14178e+06F, 3.88905e+06F, 3.65174e+06F,
  117653. 3.42891e+06F, 3.21968e+06F, 3.02321e+06F, 2.83873e+06F,
  117654. 2.66551e+06F, 2.50286e+06F, 2.35014e+06F, 2.20673e+06F,
  117655. 2.07208e+06F, 1.94564e+06F, 1.82692e+06F, 1.71544e+06F,
  117656. 1.61076e+06F, 1.51247e+06F, 1.42018e+06F, 1.33352e+06F,
  117657. 1.25215e+06F, 1.17574e+06F, 1.10400e+06F, 1.03663e+06F,
  117658. 973377.F, 913981.F, 858210.F, 805842.F,
  117659. 756669.F, 710497.F, 667142.F, 626433.F,
  117660. 588208.F, 552316.F, 518613.F, 486967.F,
  117661. 457252.F, 429351.F, 403152.F, 378551.F,
  117662. 355452.F, 333762.F, 313396.F, 294273.F,
  117663. 276316.F, 259455.F, 243623.F, 228757.F,
  117664. 214798.F, 201691.F, 189384.F, 177828.F,
  117665. 166977.F, 156788.F, 147221.F, 138237.F,
  117666. 129802.F, 121881.F, 114444.F, 107461.F,
  117667. 100903.F, 94746.3F, 88964.9F, 83536.2F,
  117668. 78438.8F, 73652.5F, 69158.2F, 64938.1F,
  117669. 60975.6F, 57254.9F, 53761.2F, 50480.6F,
  117670. 47400.3F, 44507.9F, 41792.0F, 39241.9F,
  117671. 36847.3F, 34598.9F, 32487.7F, 30505.3F,
  117672. 28643.8F, 26896.0F, 25254.8F, 23713.7F,
  117673. 22266.7F, 20908.0F, 19632.2F, 18434.2F,
  117674. 17309.4F, 16253.1F, 15261.4F, 14330.1F,
  117675. 13455.7F, 12634.6F, 11863.7F, 11139.7F,
  117676. 10460.0F, 9821.72F, 9222.39F, 8659.64F,
  117677. 8131.23F, 7635.06F, 7169.17F, 6731.70F,
  117678. 6320.93F, 5935.23F, 5573.06F, 5232.99F,
  117679. 4913.67F, 4613.84F, 4332.30F, 4067.94F,
  117680. 3819.72F, 3586.64F, 3367.78F, 3162.28F,
  117681. 2969.31F, 2788.13F, 2617.99F, 2458.24F,
  117682. 2308.24F, 2167.39F, 2035.14F, 1910.95F,
  117683. 1794.35F, 1684.85F, 1582.04F, 1485.51F,
  117684. 1394.86F, 1309.75F, 1229.83F, 1154.78F,
  117685. 1084.32F, 1018.15F, 956.024F, 897.687F,
  117686. 842.910F, 791.475F, 743.179F, 697.830F,
  117687. 655.249F, 615.265F, 577.722F, 542.469F,
  117688. 509.367F, 478.286F, 449.101F, 421.696F,
  117689. 395.964F, 371.803F, 349.115F, 327.812F,
  117690. 307.809F, 289.026F, 271.390F, 254.830F,
  117691. 239.280F, 224.679F, 210.969F, 198.096F,
  117692. 186.008F, 174.658F, 164.000F, 153.993F,
  117693. 144.596F, 135.773F, 127.488F, 119.708F,
  117694. 112.404F, 105.545F, 99.1046F, 93.0572F,
  117695. 87.3788F, 82.0469F, 77.0404F, 72.3394F,
  117696. 67.9252F, 63.7804F, 59.8885F, 56.2341F,
  117697. 52.8027F, 49.5807F, 46.5553F, 43.7144F,
  117698. 41.0470F, 38.5423F, 36.1904F, 33.9821F,
  117699. 31.9085F, 29.9614F, 28.1332F, 26.4165F,
  117700. 24.8045F, 23.2910F, 21.8697F, 20.5352F,
  117701. 19.2822F, 18.1056F, 17.0008F, 15.9634F,
  117702. 14.9893F, 14.0746F, 13.2158F, 12.4094F,
  117703. 11.6522F, 10.9411F, 10.2735F, 9.64662F,
  117704. 9.05798F, 8.50526F, 7.98626F, 7.49894F,
  117705. 7.04135F, 6.61169F, 6.20824F, 5.82941F,
  117706. 5.47370F, 5.13970F, 4.82607F, 4.53158F,
  117707. 4.25507F, 3.99542F, 3.75162F, 3.52269F,
  117708. 3.30774F, 3.10590F, 2.91638F, 2.73842F,
  117709. 2.57132F, 2.41442F, 2.26709F, 2.12875F,
  117710. 1.99885F, 1.87688F, 1.76236F, 1.65482F,
  117711. 1.55384F, 1.45902F, 1.36999F, 1.28640F,
  117712. 1.20790F, 1.13419F, 1.06499F, 1.F
  117713. };
  117714. void _vp_remove_floor(vorbis_look_psy *p,
  117715. float *mdct,
  117716. int *codedflr,
  117717. float *residue,
  117718. int sliding_lowpass){
  117719. int i,n=p->n;
  117720. if(sliding_lowpass>n)sliding_lowpass=n;
  117721. for(i=0;i<sliding_lowpass;i++){
  117722. residue[i]=
  117723. mdct[i]*FLOOR1_fromdB_INV_LOOKUP[codedflr[i]];
  117724. }
  117725. for(;i<n;i++)
  117726. residue[i]=0.;
  117727. }
  117728. void _vp_noisemask(vorbis_look_psy *p,
  117729. float *logmdct,
  117730. float *logmask){
  117731. int i,n=p->n;
  117732. float *work=(float*) alloca(n*sizeof(*work));
  117733. bark_noise_hybridmp(n,p->bark,logmdct,logmask,
  117734. 140.,-1);
  117735. for(i=0;i<n;i++)work[i]=logmdct[i]-logmask[i];
  117736. bark_noise_hybridmp(n,p->bark,work,logmask,0.,
  117737. p->vi->noisewindowfixed);
  117738. for(i=0;i<n;i++)work[i]=logmdct[i]-work[i];
  117739. #if 0
  117740. {
  117741. static int seq=0;
  117742. float work2[n];
  117743. for(i=0;i<n;i++){
  117744. work2[i]=logmask[i]+work[i];
  117745. }
  117746. if(seq&1)
  117747. _analysis_output("median2R",seq/2,work,n,1,0,0);
  117748. else
  117749. _analysis_output("median2L",seq/2,work,n,1,0,0);
  117750. if(seq&1)
  117751. _analysis_output("envelope2R",seq/2,work2,n,1,0,0);
  117752. else
  117753. _analysis_output("envelope2L",seq/2,work2,n,1,0,0);
  117754. seq++;
  117755. }
  117756. #endif
  117757. for(i=0;i<n;i++){
  117758. int dB=logmask[i]+.5;
  117759. if(dB>=NOISE_COMPAND_LEVELS)dB=NOISE_COMPAND_LEVELS-1;
  117760. if(dB<0)dB=0;
  117761. logmask[i]= work[i]+p->vi->noisecompand[dB];
  117762. }
  117763. }
  117764. void _vp_tonemask(vorbis_look_psy *p,
  117765. float *logfft,
  117766. float *logmask,
  117767. float global_specmax,
  117768. float local_specmax){
  117769. int i,n=p->n;
  117770. float *seed=(float*) alloca(sizeof(*seed)*p->total_octave_lines);
  117771. float att=local_specmax+p->vi->ath_adjatt;
  117772. for(i=0;i<p->total_octave_lines;i++)seed[i]=NEGINF;
  117773. /* set the ATH (floating below localmax, not global max by a
  117774. specified att) */
  117775. if(att<p->vi->ath_maxatt)att=p->vi->ath_maxatt;
  117776. for(i=0;i<n;i++)
  117777. logmask[i]=p->ath[i]+att;
  117778. /* tone masking */
  117779. seed_loop(p,(const float ***)p->tonecurves,logfft,logmask,seed,global_specmax);
  117780. max_seeds(p,seed,logmask);
  117781. }
  117782. void _vp_offset_and_mix(vorbis_look_psy *p,
  117783. float *noise,
  117784. float *tone,
  117785. int offset_select,
  117786. float *logmask,
  117787. float *mdct,
  117788. float *logmdct){
  117789. int i,n=p->n;
  117790. float de, coeffi, cx;/* AoTuV */
  117791. float toneatt=p->vi->tone_masteratt[offset_select];
  117792. cx = p->m_val;
  117793. for(i=0;i<n;i++){
  117794. float val= noise[i]+p->noiseoffset[offset_select][i];
  117795. if(val>p->vi->noisemaxsupp)val=p->vi->noisemaxsupp;
  117796. logmask[i]=max(val,tone[i]+toneatt);
  117797. /* AoTuV */
  117798. /** @ M1 **
  117799. The following codes improve a noise problem.
  117800. A fundamental idea uses the value of masking and carries out
  117801. the relative compensation of the MDCT.
  117802. However, this code is not perfect and all noise problems cannot be solved.
  117803. by Aoyumi @ 2004/04/18
  117804. */
  117805. if(offset_select == 1) {
  117806. coeffi = -17.2; /* coeffi is a -17.2dB threshold */
  117807. val = val - logmdct[i]; /* val == mdct line value relative to floor in dB */
  117808. if(val > coeffi){
  117809. /* mdct value is > -17.2 dB below floor */
  117810. de = 1.0-((val-coeffi)*0.005*cx);
  117811. /* pro-rated attenuation:
  117812. -0.00 dB boost if mdct value is -17.2dB (relative to floor)
  117813. -0.77 dB boost if mdct value is 0dB (relative to floor)
  117814. -1.64 dB boost if mdct value is +17.2dB (relative to floor)
  117815. etc... */
  117816. if(de < 0) de = 0.0001;
  117817. }else
  117818. /* mdct value is <= -17.2 dB below floor */
  117819. de = 1.0-((val-coeffi)*0.0003*cx);
  117820. /* pro-rated attenuation:
  117821. +0.00 dB atten if mdct value is -17.2dB (relative to floor)
  117822. +0.45 dB atten if mdct value is -34.4dB (relative to floor)
  117823. etc... */
  117824. mdct[i] *= de;
  117825. }
  117826. }
  117827. }
  117828. float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd){
  117829. vorbis_info *vi=vd->vi;
  117830. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  117831. vorbis_info_psy_global *gi=&ci->psy_g_param;
  117832. int n=ci->blocksizes[vd->W]/2;
  117833. float secs=(float)n/vi->rate;
  117834. amp+=secs*gi->ampmax_att_per_sec;
  117835. if(amp<-9999)amp=-9999;
  117836. return(amp);
  117837. }
  117838. static void couple_lossless(float A, float B,
  117839. float *qA, float *qB){
  117840. int test1=fabs(*qA)>fabs(*qB);
  117841. test1-= fabs(*qA)<fabs(*qB);
  117842. if(!test1)test1=((fabs(A)>fabs(B))<<1)-1;
  117843. if(test1==1){
  117844. *qB=(*qA>0.f?*qA-*qB:*qB-*qA);
  117845. }else{
  117846. float temp=*qB;
  117847. *qB=(*qB>0.f?*qA-*qB:*qB-*qA);
  117848. *qA=temp;
  117849. }
  117850. if(*qB>fabs(*qA)*1.9999f){
  117851. *qB= -fabs(*qA)*2.f;
  117852. *qA= -*qA;
  117853. }
  117854. }
  117855. static float hypot_lookup[32]={
  117856. -0.009935, -0.011245, -0.012726, -0.014397,
  117857. -0.016282, -0.018407, -0.020800, -0.023494,
  117858. -0.026522, -0.029923, -0.033737, -0.038010,
  117859. -0.042787, -0.048121, -0.054064, -0.060671,
  117860. -0.068000, -0.076109, -0.085054, -0.094892,
  117861. -0.105675, -0.117451, -0.130260, -0.144134,
  117862. -0.159093, -0.175146, -0.192286, -0.210490,
  117863. -0.229718, -0.249913, -0.271001, -0.292893};
  117864. static void precomputed_couple_point(float premag,
  117865. int floorA,int floorB,
  117866. float *mag, float *ang){
  117867. int test=(floorA>floorB)-1;
  117868. int offset=31-abs(floorA-floorB);
  117869. float floormag=hypot_lookup[((offset<0)-1)&offset]+1.f;
  117870. floormag*=FLOOR1_fromdB_INV_LOOKUP[(floorB&test)|(floorA&(~test))];
  117871. *mag=premag*floormag;
  117872. *ang=0.f;
  117873. }
  117874. /* just like below, this is currently set up to only do
  117875. single-step-depth coupling. Otherwise, we'd have to do more
  117876. copying (which will be inevitable later) */
  117877. /* doing the real circular magnitude calculation is audibly superior
  117878. to (A+B)/sqrt(2) */
  117879. static float dipole_hypot(float a, float b){
  117880. if(a>0.){
  117881. if(b>0.)return sqrt(a*a+b*b);
  117882. if(a>-b)return sqrt(a*a-b*b);
  117883. return -sqrt(b*b-a*a);
  117884. }
  117885. if(b<0.)return -sqrt(a*a+b*b);
  117886. if(-a>b)return -sqrt(a*a-b*b);
  117887. return sqrt(b*b-a*a);
  117888. }
  117889. static float round_hypot(float a, float b){
  117890. if(a>0.){
  117891. if(b>0.)return sqrt(a*a+b*b);
  117892. if(a>-b)return sqrt(a*a+b*b);
  117893. return -sqrt(b*b+a*a);
  117894. }
  117895. if(b<0.)return -sqrt(a*a+b*b);
  117896. if(-a>b)return -sqrt(a*a+b*b);
  117897. return sqrt(b*b+a*a);
  117898. }
  117899. /* revert to round hypot for now */
  117900. float **_vp_quantize_couple_memo(vorbis_block *vb,
  117901. vorbis_info_psy_global *g,
  117902. vorbis_look_psy *p,
  117903. vorbis_info_mapping0 *vi,
  117904. float **mdct){
  117905. int i,j,n=p->n;
  117906. float **ret=(float**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  117907. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  117908. for(i=0;i<vi->coupling_steps;i++){
  117909. float *mdctM=mdct[vi->coupling_mag[i]];
  117910. float *mdctA=mdct[vi->coupling_ang[i]];
  117911. ret[i]=(float*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  117912. for(j=0;j<limit;j++)
  117913. ret[i][j]=dipole_hypot(mdctM[j],mdctA[j]);
  117914. for(;j<n;j++)
  117915. ret[i][j]=round_hypot(mdctM[j],mdctA[j]);
  117916. }
  117917. return(ret);
  117918. }
  117919. /* this is for per-channel noise normalization */
  117920. static int JUCE_CDECL apsort(const void *a, const void *b){
  117921. float f1=fabs(**(float**)a);
  117922. float f2=fabs(**(float**)b);
  117923. return (f1<f2)-(f1>f2);
  117924. }
  117925. int **_vp_quantize_couple_sort(vorbis_block *vb,
  117926. vorbis_look_psy *p,
  117927. vorbis_info_mapping0 *vi,
  117928. float **mags){
  117929. if(p->vi->normal_point_p){
  117930. int i,j,k,n=p->n;
  117931. int **ret=(int**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  117932. int partition=p->vi->normal_partition;
  117933. float **work=(float**) alloca(sizeof(*work)*partition);
  117934. for(i=0;i<vi->coupling_steps;i++){
  117935. ret[i]=(int*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  117936. for(j=0;j<n;j+=partition){
  117937. for(k=0;k<partition;k++)work[k]=mags[i]+k+j;
  117938. qsort(work,partition,sizeof(*work),apsort);
  117939. for(k=0;k<partition;k++)ret[i][k+j]=work[k]-mags[i];
  117940. }
  117941. }
  117942. return(ret);
  117943. }
  117944. return(NULL);
  117945. }
  117946. void _vp_noise_normalize_sort(vorbis_look_psy *p,
  117947. float *magnitudes,int *sortedindex){
  117948. int i,j,n=p->n;
  117949. vorbis_info_psy *vi=p->vi;
  117950. int partition=vi->normal_partition;
  117951. float **work=(float**) alloca(sizeof(*work)*partition);
  117952. int start=vi->normal_start;
  117953. for(j=start;j<n;j+=partition){
  117954. if(j+partition>n)partition=n-j;
  117955. for(i=0;i<partition;i++)work[i]=magnitudes+i+j;
  117956. qsort(work,partition,sizeof(*work),apsort);
  117957. for(i=0;i<partition;i++){
  117958. sortedindex[i+j-start]=work[i]-magnitudes;
  117959. }
  117960. }
  117961. }
  117962. void _vp_noise_normalize(vorbis_look_psy *p,
  117963. float *in,float *out,int *sortedindex){
  117964. int flag=0,i,j=0,n=p->n;
  117965. vorbis_info_psy *vi=p->vi;
  117966. int partition=vi->normal_partition;
  117967. int start=vi->normal_start;
  117968. if(start>n)start=n;
  117969. if(vi->normal_channel_p){
  117970. for(;j<start;j++)
  117971. out[j]=rint(in[j]);
  117972. for(;j+partition<=n;j+=partition){
  117973. float acc=0.;
  117974. int k;
  117975. for(i=j;i<j+partition;i++)
  117976. acc+=in[i]*in[i];
  117977. for(i=0;i<partition;i++){
  117978. k=sortedindex[i+j-start];
  117979. if(in[k]*in[k]>=.25f){
  117980. out[k]=rint(in[k]);
  117981. acc-=in[k]*in[k];
  117982. flag=1;
  117983. }else{
  117984. if(acc<vi->normal_thresh)break;
  117985. out[k]=unitnorm(in[k]);
  117986. acc-=1.;
  117987. }
  117988. }
  117989. for(;i<partition;i++){
  117990. k=sortedindex[i+j-start];
  117991. out[k]=0.;
  117992. }
  117993. }
  117994. }
  117995. for(;j<n;j++)
  117996. out[j]=rint(in[j]);
  117997. }
  117998. void _vp_couple(int blobno,
  117999. vorbis_info_psy_global *g,
  118000. vorbis_look_psy *p,
  118001. vorbis_info_mapping0 *vi,
  118002. float **res,
  118003. float **mag_memo,
  118004. int **mag_sort,
  118005. int **ifloor,
  118006. int *nonzero,
  118007. int sliding_lowpass){
  118008. int i,j,k,n=p->n;
  118009. /* perform any requested channel coupling */
  118010. /* point stereo can only be used in a first stage (in this encoder)
  118011. because of the dependency on floor lookups */
  118012. for(i=0;i<vi->coupling_steps;i++){
  118013. /* once we're doing multistage coupling in which a channel goes
  118014. through more than one coupling step, the floor vector
  118015. magnitudes will also have to be recalculated an propogated
  118016. along with PCM. Right now, we're not (that will wait until 5.1
  118017. most likely), so the code isn't here yet. The memory management
  118018. here is all assuming single depth couplings anyway. */
  118019. /* make sure coupling a zero and a nonzero channel results in two
  118020. nonzero channels. */
  118021. if(nonzero[vi->coupling_mag[i]] ||
  118022. nonzero[vi->coupling_ang[i]]){
  118023. float *rM=res[vi->coupling_mag[i]];
  118024. float *rA=res[vi->coupling_ang[i]];
  118025. float *qM=rM+n;
  118026. float *qA=rA+n;
  118027. int *floorM=ifloor[vi->coupling_mag[i]];
  118028. int *floorA=ifloor[vi->coupling_ang[i]];
  118029. float prepoint=stereo_threshholds[g->coupling_prepointamp[blobno]];
  118030. float postpoint=stereo_threshholds[g->coupling_postpointamp[blobno]];
  118031. int partition=(p->vi->normal_point_p?p->vi->normal_partition:p->n);
  118032. int limit=g->coupling_pointlimit[p->vi->blockflag][blobno];
  118033. int pointlimit=limit;
  118034. nonzero[vi->coupling_mag[i]]=1;
  118035. nonzero[vi->coupling_ang[i]]=1;
  118036. /* The threshold of a stereo is changed with the size of n */
  118037. if(n > 1000)
  118038. postpoint=stereo_threshholds_limited[g->coupling_postpointamp[blobno]];
  118039. for(j=0;j<p->n;j+=partition){
  118040. float acc=0.f;
  118041. for(k=0;k<partition;k++){
  118042. int l=k+j;
  118043. if(l<sliding_lowpass){
  118044. if((l>=limit && fabs(rM[l])<postpoint && fabs(rA[l])<postpoint) ||
  118045. (fabs(rM[l])<prepoint && fabs(rA[l])<prepoint)){
  118046. precomputed_couple_point(mag_memo[i][l],
  118047. floorM[l],floorA[l],
  118048. qM+l,qA+l);
  118049. if(rint(qM[l])==0.f)acc+=qM[l]*qM[l];
  118050. }else{
  118051. couple_lossless(rM[l],rA[l],qM+l,qA+l);
  118052. }
  118053. }else{
  118054. qM[l]=0.;
  118055. qA[l]=0.;
  118056. }
  118057. }
  118058. if(p->vi->normal_point_p){
  118059. for(k=0;k<partition && acc>=p->vi->normal_thresh;k++){
  118060. int l=mag_sort[i][j+k];
  118061. if(l<sliding_lowpass && l>=pointlimit && rint(qM[l])==0.f){
  118062. qM[l]=unitnorm(qM[l]);
  118063. acc-=1.f;
  118064. }
  118065. }
  118066. }
  118067. }
  118068. }
  118069. }
  118070. }
  118071. /* AoTuV */
  118072. /** @ M2 **
  118073. The boost problem by the combination of noise normalization and point stereo is eased.
  118074. However, this is a temporary patch.
  118075. by Aoyumi @ 2004/04/18
  118076. */
  118077. void hf_reduction(vorbis_info_psy_global *g,
  118078. vorbis_look_psy *p,
  118079. vorbis_info_mapping0 *vi,
  118080. float **mdct){
  118081. int i,j,n=p->n, de=0.3*p->m_val;
  118082. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  118083. for(i=0; i<vi->coupling_steps; i++){
  118084. /* for(j=start; j<limit; j++){} // ???*/
  118085. for(j=limit; j<n; j++)
  118086. mdct[i][j] *= (1.0 - de*((float)(j-limit) / (float)(n-limit)));
  118087. }
  118088. }
  118089. #endif
  118090. /*** End of inlined file: psy.c ***/
  118091. /*** Start of inlined file: registry.c ***/
  118092. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  118093. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  118094. // tasks..
  118095. #if JUCE_MSVC
  118096. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  118097. #endif
  118098. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  118099. #if JUCE_USE_OGGVORBIS
  118100. /* seems like major overkill now; the backend numbers will grow into
  118101. the infrastructure soon enough */
  118102. extern vorbis_func_floor floor0_exportbundle;
  118103. extern vorbis_func_floor floor1_exportbundle;
  118104. extern vorbis_func_residue residue0_exportbundle;
  118105. extern vorbis_func_residue residue1_exportbundle;
  118106. extern vorbis_func_residue residue2_exportbundle;
  118107. extern vorbis_func_mapping mapping0_exportbundle;
  118108. vorbis_func_floor *_floor_P[]={
  118109. &floor0_exportbundle,
  118110. &floor1_exportbundle,
  118111. };
  118112. vorbis_func_residue *_residue_P[]={
  118113. &residue0_exportbundle,
  118114. &residue1_exportbundle,
  118115. &residue2_exportbundle,
  118116. };
  118117. vorbis_func_mapping *_mapping_P[]={
  118118. &mapping0_exportbundle,
  118119. };
  118120. #endif
  118121. /*** End of inlined file: registry.c ***/
  118122. /*** Start of inlined file: res0.c ***/
  118123. /* Slow, slow, slow, simpleminded and did I mention it was slow? The
  118124. encode/decode loops are coded for clarity and performance is not
  118125. yet even a nagging little idea lurking in the shadows. Oh and BTW,
  118126. it's slow. */
  118127. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  118128. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  118129. // tasks..
  118130. #if JUCE_MSVC
  118131. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  118132. #endif
  118133. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  118134. #if JUCE_USE_OGGVORBIS
  118135. #include <stdlib.h>
  118136. #include <string.h>
  118137. #include <math.h>
  118138. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  118139. #include <stdio.h>
  118140. #endif
  118141. typedef struct {
  118142. vorbis_info_residue0 *info;
  118143. int parts;
  118144. int stages;
  118145. codebook *fullbooks;
  118146. codebook *phrasebook;
  118147. codebook ***partbooks;
  118148. int partvals;
  118149. int **decodemap;
  118150. long postbits;
  118151. long phrasebits;
  118152. long frames;
  118153. #if defined(TRAIN_RES) || defined(TRAIN_RESAUX)
  118154. int train_seq;
  118155. long *training_data[8][64];
  118156. float training_max[8][64];
  118157. float training_min[8][64];
  118158. float tmin;
  118159. float tmax;
  118160. #endif
  118161. } vorbis_look_residue0;
  118162. void res0_free_info(vorbis_info_residue *i){
  118163. vorbis_info_residue0 *info=(vorbis_info_residue0 *)i;
  118164. if(info){
  118165. memset(info,0,sizeof(*info));
  118166. _ogg_free(info);
  118167. }
  118168. }
  118169. void res0_free_look(vorbis_look_residue *i){
  118170. int j;
  118171. if(i){
  118172. vorbis_look_residue0 *look=(vorbis_look_residue0 *)i;
  118173. #ifdef TRAIN_RES
  118174. {
  118175. int j,k,l;
  118176. for(j=0;j<look->parts;j++){
  118177. /*fprintf(stderr,"partition %d: ",j);*/
  118178. for(k=0;k<8;k++)
  118179. if(look->training_data[k][j]){
  118180. char buffer[80];
  118181. FILE *of;
  118182. codebook *statebook=look->partbooks[j][k];
  118183. /* long and short into the same bucket by current convention */
  118184. sprintf(buffer,"res_part%d_pass%d.vqd",j,k);
  118185. of=fopen(buffer,"a");
  118186. for(l=0;l<statebook->entries;l++)
  118187. fprintf(of,"%d:%ld\n",l,look->training_data[k][j][l]);
  118188. fclose(of);
  118189. /*fprintf(stderr,"%d(%.2f|%.2f) ",k,
  118190. look->training_min[k][j],look->training_max[k][j]);*/
  118191. _ogg_free(look->training_data[k][j]);
  118192. look->training_data[k][j]=NULL;
  118193. }
  118194. /*fprintf(stderr,"\n");*/
  118195. }
  118196. }
  118197. fprintf(stderr,"min/max residue: %g::%g\n",look->tmin,look->tmax);
  118198. /*fprintf(stderr,"residue bit usage %f:%f (%f total)\n",
  118199. (float)look->phrasebits/look->frames,
  118200. (float)look->postbits/look->frames,
  118201. (float)(look->postbits+look->phrasebits)/look->frames);*/
  118202. #endif
  118203. /*vorbis_info_residue0 *info=look->info;
  118204. fprintf(stderr,
  118205. "%ld frames encoded in %ld phrasebits and %ld residue bits "
  118206. "(%g/frame) \n",look->frames,look->phrasebits,
  118207. look->resbitsflat,
  118208. (look->phrasebits+look->resbitsflat)/(float)look->frames);
  118209. for(j=0;j<look->parts;j++){
  118210. long acc=0;
  118211. fprintf(stderr,"\t[%d] == ",j);
  118212. for(k=0;k<look->stages;k++)
  118213. if((info->secondstages[j]>>k)&1){
  118214. fprintf(stderr,"%ld,",look->resbits[j][k]);
  118215. acc+=look->resbits[j][k];
  118216. }
  118217. fprintf(stderr,":: (%ld vals) %1.2fbits/sample\n",look->resvals[j],
  118218. acc?(float)acc/(look->resvals[j]*info->grouping):0);
  118219. }
  118220. fprintf(stderr,"\n");*/
  118221. for(j=0;j<look->parts;j++)
  118222. if(look->partbooks[j])_ogg_free(look->partbooks[j]);
  118223. _ogg_free(look->partbooks);
  118224. for(j=0;j<look->partvals;j++)
  118225. _ogg_free(look->decodemap[j]);
  118226. _ogg_free(look->decodemap);
  118227. memset(look,0,sizeof(*look));
  118228. _ogg_free(look);
  118229. }
  118230. }
  118231. static int icount(unsigned int v){
  118232. int ret=0;
  118233. while(v){
  118234. ret+=v&1;
  118235. v>>=1;
  118236. }
  118237. return(ret);
  118238. }
  118239. void res0_pack(vorbis_info_residue *vr,oggpack_buffer *opb){
  118240. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  118241. int j,acc=0;
  118242. oggpack_write(opb,info->begin,24);
  118243. oggpack_write(opb,info->end,24);
  118244. oggpack_write(opb,info->grouping-1,24); /* residue vectors to group and
  118245. code with a partitioned book */
  118246. oggpack_write(opb,info->partitions-1,6); /* possible partition choices */
  118247. oggpack_write(opb,info->groupbook,8); /* group huffman book */
  118248. /* secondstages is a bitmask; as encoding progresses pass by pass, a
  118249. bitmask of one indicates this partition class has bits to write
  118250. this pass */
  118251. for(j=0;j<info->partitions;j++){
  118252. if(ilog(info->secondstages[j])>3){
  118253. /* yes, this is a minor hack due to not thinking ahead */
  118254. oggpack_write(opb,info->secondstages[j],3);
  118255. oggpack_write(opb,1,1);
  118256. oggpack_write(opb,info->secondstages[j]>>3,5);
  118257. }else
  118258. oggpack_write(opb,info->secondstages[j],4); /* trailing zero */
  118259. acc+=icount(info->secondstages[j]);
  118260. }
  118261. for(j=0;j<acc;j++)
  118262. oggpack_write(opb,info->booklist[j],8);
  118263. }
  118264. /* vorbis_info is for range checking */
  118265. vorbis_info_residue *res0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  118266. int j,acc=0;
  118267. vorbis_info_residue0 *info=(vorbis_info_residue0*) _ogg_calloc(1,sizeof(*info));
  118268. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  118269. info->begin=oggpack_read(opb,24);
  118270. info->end=oggpack_read(opb,24);
  118271. info->grouping=oggpack_read(opb,24)+1;
  118272. info->partitions=oggpack_read(opb,6)+1;
  118273. info->groupbook=oggpack_read(opb,8);
  118274. for(j=0;j<info->partitions;j++){
  118275. int cascade=oggpack_read(opb,3);
  118276. if(oggpack_read(opb,1))
  118277. cascade|=(oggpack_read(opb,5)<<3);
  118278. info->secondstages[j]=cascade;
  118279. acc+=icount(cascade);
  118280. }
  118281. for(j=0;j<acc;j++)
  118282. info->booklist[j]=oggpack_read(opb,8);
  118283. if(info->groupbook>=ci->books)goto errout;
  118284. for(j=0;j<acc;j++)
  118285. if(info->booklist[j]>=ci->books)goto errout;
  118286. return(info);
  118287. errout:
  118288. res0_free_info(info);
  118289. return(NULL);
  118290. }
  118291. vorbis_look_residue *res0_look(vorbis_dsp_state *vd,
  118292. vorbis_info_residue *vr){
  118293. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  118294. vorbis_look_residue0 *look=(vorbis_look_residue0 *)_ogg_calloc(1,sizeof(*look));
  118295. codec_setup_info *ci=(codec_setup_info*)vd->vi->codec_setup;
  118296. int j,k,acc=0;
  118297. int dim;
  118298. int maxstage=0;
  118299. look->info=info;
  118300. look->parts=info->partitions;
  118301. look->fullbooks=ci->fullbooks;
  118302. look->phrasebook=ci->fullbooks+info->groupbook;
  118303. dim=look->phrasebook->dim;
  118304. look->partbooks=(codebook***)_ogg_calloc(look->parts,sizeof(*look->partbooks));
  118305. for(j=0;j<look->parts;j++){
  118306. int stages=ilog(info->secondstages[j]);
  118307. if(stages){
  118308. if(stages>maxstage)maxstage=stages;
  118309. look->partbooks[j]=(codebook**) _ogg_calloc(stages,sizeof(*look->partbooks[j]));
  118310. for(k=0;k<stages;k++)
  118311. if(info->secondstages[j]&(1<<k)){
  118312. look->partbooks[j][k]=ci->fullbooks+info->booklist[acc++];
  118313. #ifdef TRAIN_RES
  118314. look->training_data[k][j]=_ogg_calloc(look->partbooks[j][k]->entries,
  118315. sizeof(***look->training_data));
  118316. #endif
  118317. }
  118318. }
  118319. }
  118320. look->partvals=rint(pow((float)look->parts,(float)dim));
  118321. look->stages=maxstage;
  118322. look->decodemap=(int**)_ogg_malloc(look->partvals*sizeof(*look->decodemap));
  118323. for(j=0;j<look->partvals;j++){
  118324. long val=j;
  118325. long mult=look->partvals/look->parts;
  118326. look->decodemap[j]=(int*)_ogg_malloc(dim*sizeof(*look->decodemap[j]));
  118327. for(k=0;k<dim;k++){
  118328. long deco=val/mult;
  118329. val-=deco*mult;
  118330. mult/=look->parts;
  118331. look->decodemap[j][k]=deco;
  118332. }
  118333. }
  118334. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  118335. {
  118336. static int train_seq=0;
  118337. look->train_seq=train_seq++;
  118338. }
  118339. #endif
  118340. return(look);
  118341. }
  118342. /* break an abstraction and copy some code for performance purposes */
  118343. static int local_book_besterror(codebook *book,float *a){
  118344. int dim=book->dim,i,k,o;
  118345. int best=0;
  118346. encode_aux_threshmatch *tt=book->c->thresh_tree;
  118347. /* find the quant val of each scalar */
  118348. for(k=0,o=dim;k<dim;++k){
  118349. float val=a[--o];
  118350. i=tt->threshvals>>1;
  118351. if(val<tt->quantthresh[i]){
  118352. if(val<tt->quantthresh[i-1]){
  118353. for(--i;i>0;--i)
  118354. if(val>=tt->quantthresh[i-1])
  118355. break;
  118356. }
  118357. }else{
  118358. for(++i;i<tt->threshvals-1;++i)
  118359. if(val<tt->quantthresh[i])break;
  118360. }
  118361. best=(best*tt->quantvals)+tt->quantmap[i];
  118362. }
  118363. /* regular lattices are easy :-) */
  118364. if(book->c->lengthlist[best]<=0){
  118365. const static_codebook *c=book->c;
  118366. int i,j;
  118367. float bestf=0.f;
  118368. float *e=book->valuelist;
  118369. best=-1;
  118370. for(i=0;i<book->entries;i++){
  118371. if(c->lengthlist[i]>0){
  118372. float thisx=0.f;
  118373. for(j=0;j<dim;j++){
  118374. float val=(e[j]-a[j]);
  118375. thisx+=val*val;
  118376. }
  118377. if(best==-1 || thisx<bestf){
  118378. bestf=thisx;
  118379. best=i;
  118380. }
  118381. }
  118382. e+=dim;
  118383. }
  118384. }
  118385. {
  118386. float *ptr=book->valuelist+best*dim;
  118387. for(i=0;i<dim;i++)
  118388. *a++ -= *ptr++;
  118389. }
  118390. return(best);
  118391. }
  118392. static int _encodepart(oggpack_buffer *opb,float *vec, int n,
  118393. codebook *book,long *acc){
  118394. int i,bits=0;
  118395. int dim=book->dim;
  118396. int step=n/dim;
  118397. for(i=0;i<step;i++){
  118398. int entry=local_book_besterror(book,vec+i*dim);
  118399. #ifdef TRAIN_RES
  118400. acc[entry]++;
  118401. #endif
  118402. bits+=vorbis_book_encode(book,entry,opb);
  118403. }
  118404. return(bits);
  118405. }
  118406. static long **_01class(vorbis_block *vb,vorbis_look_residue *vl,
  118407. float **in,int ch){
  118408. long i,j,k;
  118409. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118410. vorbis_info_residue0 *info=look->info;
  118411. /* move all this setup out later */
  118412. int samples_per_partition=info->grouping;
  118413. int possible_partitions=info->partitions;
  118414. int n=info->end-info->begin;
  118415. int partvals=n/samples_per_partition;
  118416. long **partword=(long**)_vorbis_block_alloc(vb,ch*sizeof(*partword));
  118417. float scale=100./samples_per_partition;
  118418. /* we find the partition type for each partition of each
  118419. channel. We'll go back and do the interleaved encoding in a
  118420. bit. For now, clarity */
  118421. for(i=0;i<ch;i++){
  118422. partword[i]=(long*)_vorbis_block_alloc(vb,n/samples_per_partition*sizeof(*partword[i]));
  118423. memset(partword[i],0,n/samples_per_partition*sizeof(*partword[i]));
  118424. }
  118425. for(i=0;i<partvals;i++){
  118426. int offset=i*samples_per_partition+info->begin;
  118427. for(j=0;j<ch;j++){
  118428. float max=0.;
  118429. float ent=0.;
  118430. for(k=0;k<samples_per_partition;k++){
  118431. if(fabs(in[j][offset+k])>max)max=fabs(in[j][offset+k]);
  118432. ent+=fabs(rint(in[j][offset+k]));
  118433. }
  118434. ent*=scale;
  118435. for(k=0;k<possible_partitions-1;k++)
  118436. if(max<=info->classmetric1[k] &&
  118437. (info->classmetric2[k]<0 || (int)ent<info->classmetric2[k]))
  118438. break;
  118439. partword[j][i]=k;
  118440. }
  118441. }
  118442. #ifdef TRAIN_RESAUX
  118443. {
  118444. FILE *of;
  118445. char buffer[80];
  118446. for(i=0;i<ch;i++){
  118447. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  118448. of=fopen(buffer,"a");
  118449. for(j=0;j<partvals;j++)
  118450. fprintf(of,"%ld, ",partword[i][j]);
  118451. fprintf(of,"\n");
  118452. fclose(of);
  118453. }
  118454. }
  118455. #endif
  118456. look->frames++;
  118457. return(partword);
  118458. }
  118459. /* designed for stereo or other modes where the partition size is an
  118460. integer multiple of the number of channels encoded in the current
  118461. submap */
  118462. static long **_2class(vorbis_block *vb,vorbis_look_residue *vl,float **in,
  118463. int ch){
  118464. long i,j,k,l;
  118465. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118466. vorbis_info_residue0 *info=look->info;
  118467. /* move all this setup out later */
  118468. int samples_per_partition=info->grouping;
  118469. int possible_partitions=info->partitions;
  118470. int n=info->end-info->begin;
  118471. int partvals=n/samples_per_partition;
  118472. long **partword=(long**)_vorbis_block_alloc(vb,sizeof(*partword));
  118473. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  118474. FILE *of;
  118475. char buffer[80];
  118476. #endif
  118477. partword[0]=(long*)_vorbis_block_alloc(vb,n*ch/samples_per_partition*sizeof(*partword[0]));
  118478. memset(partword[0],0,n*ch/samples_per_partition*sizeof(*partword[0]));
  118479. for(i=0,l=info->begin/ch;i<partvals;i++){
  118480. float magmax=0.f;
  118481. float angmax=0.f;
  118482. for(j=0;j<samples_per_partition;j+=ch){
  118483. if(fabs(in[0][l])>magmax)magmax=fabs(in[0][l]);
  118484. for(k=1;k<ch;k++)
  118485. if(fabs(in[k][l])>angmax)angmax=fabs(in[k][l]);
  118486. l++;
  118487. }
  118488. for(j=0;j<possible_partitions-1;j++)
  118489. if(magmax<=info->classmetric1[j] &&
  118490. angmax<=info->classmetric2[j])
  118491. break;
  118492. partword[0][i]=j;
  118493. }
  118494. #ifdef TRAIN_RESAUX
  118495. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  118496. of=fopen(buffer,"a");
  118497. for(i=0;i<partvals;i++)
  118498. fprintf(of,"%ld, ",partword[0][i]);
  118499. fprintf(of,"\n");
  118500. fclose(of);
  118501. #endif
  118502. look->frames++;
  118503. return(partword);
  118504. }
  118505. static int _01forward(oggpack_buffer *opb,
  118506. vorbis_block *vb,vorbis_look_residue *vl,
  118507. float **in,int ch,
  118508. long **partword,
  118509. int (*encode)(oggpack_buffer *,float *,int,
  118510. codebook *,long *)){
  118511. long i,j,k,s;
  118512. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118513. vorbis_info_residue0 *info=look->info;
  118514. /* move all this setup out later */
  118515. int samples_per_partition=info->grouping;
  118516. int possible_partitions=info->partitions;
  118517. int partitions_per_word=look->phrasebook->dim;
  118518. int n=info->end-info->begin;
  118519. int partvals=n/samples_per_partition;
  118520. long resbits[128];
  118521. long resvals[128];
  118522. #ifdef TRAIN_RES
  118523. for(i=0;i<ch;i++)
  118524. for(j=info->begin;j<info->end;j++){
  118525. if(in[i][j]>look->tmax)look->tmax=in[i][j];
  118526. if(in[i][j]<look->tmin)look->tmin=in[i][j];
  118527. }
  118528. #endif
  118529. memset(resbits,0,sizeof(resbits));
  118530. memset(resvals,0,sizeof(resvals));
  118531. /* we code the partition words for each channel, then the residual
  118532. words for a partition per channel until we've written all the
  118533. residual words for that partition word. Then write the next
  118534. partition channel words... */
  118535. for(s=0;s<look->stages;s++){
  118536. for(i=0;i<partvals;){
  118537. /* first we encode a partition codeword for each channel */
  118538. if(s==0){
  118539. for(j=0;j<ch;j++){
  118540. long val=partword[j][i];
  118541. for(k=1;k<partitions_per_word;k++){
  118542. val*=possible_partitions;
  118543. if(i+k<partvals)
  118544. val+=partword[j][i+k];
  118545. }
  118546. /* training hack */
  118547. if(val<look->phrasebook->entries)
  118548. look->phrasebits+=vorbis_book_encode(look->phrasebook,val,opb);
  118549. #if 0 /*def TRAIN_RES*/
  118550. else
  118551. fprintf(stderr,"!");
  118552. #endif
  118553. }
  118554. }
  118555. /* now we encode interleaved residual values for the partitions */
  118556. for(k=0;k<partitions_per_word && i<partvals;k++,i++){
  118557. long offset=i*samples_per_partition+info->begin;
  118558. for(j=0;j<ch;j++){
  118559. if(s==0)resvals[partword[j][i]]+=samples_per_partition;
  118560. if(info->secondstages[partword[j][i]]&(1<<s)){
  118561. codebook *statebook=look->partbooks[partword[j][i]][s];
  118562. if(statebook){
  118563. int ret;
  118564. long *accumulator=NULL;
  118565. #ifdef TRAIN_RES
  118566. accumulator=look->training_data[s][partword[j][i]];
  118567. {
  118568. int l;
  118569. float *samples=in[j]+offset;
  118570. for(l=0;l<samples_per_partition;l++){
  118571. if(samples[l]<look->training_min[s][partword[j][i]])
  118572. look->training_min[s][partword[j][i]]=samples[l];
  118573. if(samples[l]>look->training_max[s][partword[j][i]])
  118574. look->training_max[s][partword[j][i]]=samples[l];
  118575. }
  118576. }
  118577. #endif
  118578. ret=encode(opb,in[j]+offset,samples_per_partition,
  118579. statebook,accumulator);
  118580. look->postbits+=ret;
  118581. resbits[partword[j][i]]+=ret;
  118582. }
  118583. }
  118584. }
  118585. }
  118586. }
  118587. }
  118588. /*{
  118589. long total=0;
  118590. long totalbits=0;
  118591. fprintf(stderr,"%d :: ",vb->mode);
  118592. for(k=0;k<possible_partitions;k++){
  118593. fprintf(stderr,"%ld/%1.2g, ",resvals[k],(float)resbits[k]/resvals[k]);
  118594. total+=resvals[k];
  118595. totalbits+=resbits[k];
  118596. }
  118597. fprintf(stderr,":: %ld:%1.2g\n",total,(double)totalbits/total);
  118598. }*/
  118599. return(0);
  118600. }
  118601. /* a truncated packet here just means 'stop working'; it's not an error */
  118602. static int _01inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118603. float **in,int ch,
  118604. long (*decodepart)(codebook *, float *,
  118605. oggpack_buffer *,int)){
  118606. long i,j,k,l,s;
  118607. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118608. vorbis_info_residue0 *info=look->info;
  118609. /* move all this setup out later */
  118610. int samples_per_partition=info->grouping;
  118611. int partitions_per_word=look->phrasebook->dim;
  118612. int n=info->end-info->begin;
  118613. int partvals=n/samples_per_partition;
  118614. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  118615. int ***partword=(int***)alloca(ch*sizeof(*partword));
  118616. for(j=0;j<ch;j++)
  118617. partword[j]=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword[j]));
  118618. for(s=0;s<look->stages;s++){
  118619. /* each loop decodes on partition codeword containing
  118620. partitions_pre_word partitions */
  118621. for(i=0,l=0;i<partvals;l++){
  118622. if(s==0){
  118623. /* fetch the partition word for each channel */
  118624. for(j=0;j<ch;j++){
  118625. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  118626. if(temp==-1)goto eopbreak;
  118627. partword[j][l]=look->decodemap[temp];
  118628. if(partword[j][l]==NULL)goto errout;
  118629. }
  118630. }
  118631. /* now we decode residual values for the partitions */
  118632. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  118633. for(j=0;j<ch;j++){
  118634. long offset=info->begin+i*samples_per_partition;
  118635. if(info->secondstages[partword[j][l][k]]&(1<<s)){
  118636. codebook *stagebook=look->partbooks[partword[j][l][k]][s];
  118637. if(stagebook){
  118638. if(decodepart(stagebook,in[j]+offset,&vb->opb,
  118639. samples_per_partition)==-1)goto eopbreak;
  118640. }
  118641. }
  118642. }
  118643. }
  118644. }
  118645. errout:
  118646. eopbreak:
  118647. return(0);
  118648. }
  118649. #if 0
  118650. /* residue 0 and 1 are just slight variants of one another. 0 is
  118651. interleaved, 1 is not */
  118652. long **res0_class(vorbis_block *vb,vorbis_look_residue *vl,
  118653. float **in,int *nonzero,int ch){
  118654. /* we encode only the nonzero parts of a bundle */
  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(_01class(vb,vl,in,used,_interleaved_testhack));*/
  118661. return(_01class(vb,vl,in,used));
  118662. else
  118663. return(0);
  118664. }
  118665. int res0_forward(vorbis_block *vb,vorbis_look_residue *vl,
  118666. float **in,float **out,int *nonzero,int ch,
  118667. long **partword){
  118668. /* we encode only the nonzero parts of a bundle */
  118669. int i,j,used=0,n=vb->pcmend/2;
  118670. for(i=0;i<ch;i++)
  118671. if(nonzero[i]){
  118672. if(out)
  118673. for(j=0;j<n;j++)
  118674. out[i][j]+=in[i][j];
  118675. in[used++]=in[i];
  118676. }
  118677. if(used){
  118678. int ret=_01forward(vb,vl,in,used,partword,
  118679. _interleaved_encodepart);
  118680. if(out){
  118681. used=0;
  118682. for(i=0;i<ch;i++)
  118683. if(nonzero[i]){
  118684. for(j=0;j<n;j++)
  118685. out[i][j]-=in[used][j];
  118686. used++;
  118687. }
  118688. }
  118689. return(ret);
  118690. }else{
  118691. return(0);
  118692. }
  118693. }
  118694. #endif
  118695. int res0_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118696. float **in,int *nonzero,int ch){
  118697. int i,used=0;
  118698. for(i=0;i<ch;i++)
  118699. if(nonzero[i])
  118700. in[used++]=in[i];
  118701. if(used)
  118702. return(_01inverse(vb,vl,in,used,vorbis_book_decodevs_add));
  118703. else
  118704. return(0);
  118705. }
  118706. int res1_forward(oggpack_buffer *opb,vorbis_block *vb,vorbis_look_residue *vl,
  118707. float **in,float **out,int *nonzero,int ch,
  118708. long **partword){
  118709. int i,j,used=0,n=vb->pcmend/2;
  118710. for(i=0;i<ch;i++)
  118711. if(nonzero[i]){
  118712. if(out)
  118713. for(j=0;j<n;j++)
  118714. out[i][j]+=in[i][j];
  118715. in[used++]=in[i];
  118716. }
  118717. if(used){
  118718. int ret=_01forward(opb,vb,vl,in,used,partword,_encodepart);
  118719. if(out){
  118720. used=0;
  118721. for(i=0;i<ch;i++)
  118722. if(nonzero[i]){
  118723. for(j=0;j<n;j++)
  118724. out[i][j]-=in[used][j];
  118725. used++;
  118726. }
  118727. }
  118728. return(ret);
  118729. }else{
  118730. return(0);
  118731. }
  118732. }
  118733. long **res1_class(vorbis_block *vb,vorbis_look_residue *vl,
  118734. float **in,int *nonzero,int ch){
  118735. int i,used=0;
  118736. for(i=0;i<ch;i++)
  118737. if(nonzero[i])
  118738. in[used++]=in[i];
  118739. if(used)
  118740. return(_01class(vb,vl,in,used));
  118741. else
  118742. return(0);
  118743. }
  118744. int res1_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118745. float **in,int *nonzero,int ch){
  118746. int i,used=0;
  118747. for(i=0;i<ch;i++)
  118748. if(nonzero[i])
  118749. in[used++]=in[i];
  118750. if(used)
  118751. return(_01inverse(vb,vl,in,used,vorbis_book_decodev_add));
  118752. else
  118753. return(0);
  118754. }
  118755. long **res2_class(vorbis_block *vb,vorbis_look_residue *vl,
  118756. float **in,int *nonzero,int ch){
  118757. int i,used=0;
  118758. for(i=0;i<ch;i++)
  118759. if(nonzero[i])used++;
  118760. if(used)
  118761. return(_2class(vb,vl,in,ch));
  118762. else
  118763. return(0);
  118764. }
  118765. /* res2 is slightly more different; all the channels are interleaved
  118766. into a single vector and encoded. */
  118767. int res2_forward(oggpack_buffer *opb,
  118768. vorbis_block *vb,vorbis_look_residue *vl,
  118769. float **in,float **out,int *nonzero,int ch,
  118770. long **partword){
  118771. long i,j,k,n=vb->pcmend/2,used=0;
  118772. /* don't duplicate the code; use a working vector hack for now and
  118773. reshape ourselves into a single channel res1 */
  118774. /* ugly; reallocs for each coupling pass :-( */
  118775. float *work=(float*)_vorbis_block_alloc(vb,ch*n*sizeof(*work));
  118776. for(i=0;i<ch;i++){
  118777. float *pcm=in[i];
  118778. if(nonzero[i])used++;
  118779. for(j=0,k=i;j<n;j++,k+=ch)
  118780. work[k]=pcm[j];
  118781. }
  118782. if(used){
  118783. int ret=_01forward(opb,vb,vl,&work,1,partword,_encodepart);
  118784. /* update the sofar vector */
  118785. if(out){
  118786. for(i=0;i<ch;i++){
  118787. float *pcm=in[i];
  118788. float *sofar=out[i];
  118789. for(j=0,k=i;j<n;j++,k+=ch)
  118790. sofar[j]+=pcm[j]-work[k];
  118791. }
  118792. }
  118793. return(ret);
  118794. }else{
  118795. return(0);
  118796. }
  118797. }
  118798. /* duplicate code here as speed is somewhat more important */
  118799. int res2_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118800. float **in,int *nonzero,int ch){
  118801. long i,k,l,s;
  118802. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118803. vorbis_info_residue0 *info=look->info;
  118804. /* move all this setup out later */
  118805. int samples_per_partition=info->grouping;
  118806. int partitions_per_word=look->phrasebook->dim;
  118807. int n=info->end-info->begin;
  118808. int partvals=n/samples_per_partition;
  118809. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  118810. int **partword=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword));
  118811. for(i=0;i<ch;i++)if(nonzero[i])break;
  118812. if(i==ch)return(0); /* no nonzero vectors */
  118813. for(s=0;s<look->stages;s++){
  118814. for(i=0,l=0;i<partvals;l++){
  118815. if(s==0){
  118816. /* fetch the partition word */
  118817. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  118818. if(temp==-1)goto eopbreak;
  118819. partword[l]=look->decodemap[temp];
  118820. if(partword[l]==NULL)goto errout;
  118821. }
  118822. /* now we decode residual values for the partitions */
  118823. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  118824. if(info->secondstages[partword[l][k]]&(1<<s)){
  118825. codebook *stagebook=look->partbooks[partword[l][k]][s];
  118826. if(stagebook){
  118827. if(vorbis_book_decodevv_add(stagebook,in,
  118828. i*samples_per_partition+info->begin,ch,
  118829. &vb->opb,samples_per_partition)==-1)
  118830. goto eopbreak;
  118831. }
  118832. }
  118833. }
  118834. }
  118835. errout:
  118836. eopbreak:
  118837. return(0);
  118838. }
  118839. vorbis_func_residue residue0_exportbundle={
  118840. NULL,
  118841. &res0_unpack,
  118842. &res0_look,
  118843. &res0_free_info,
  118844. &res0_free_look,
  118845. NULL,
  118846. NULL,
  118847. &res0_inverse
  118848. };
  118849. vorbis_func_residue residue1_exportbundle={
  118850. &res0_pack,
  118851. &res0_unpack,
  118852. &res0_look,
  118853. &res0_free_info,
  118854. &res0_free_look,
  118855. &res1_class,
  118856. &res1_forward,
  118857. &res1_inverse
  118858. };
  118859. vorbis_func_residue residue2_exportbundle={
  118860. &res0_pack,
  118861. &res0_unpack,
  118862. &res0_look,
  118863. &res0_free_info,
  118864. &res0_free_look,
  118865. &res2_class,
  118866. &res2_forward,
  118867. &res2_inverse
  118868. };
  118869. #endif
  118870. /*** End of inlined file: res0.c ***/
  118871. /*** Start of inlined file: sharedbook.c ***/
  118872. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  118873. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  118874. // tasks..
  118875. #if JUCE_MSVC
  118876. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  118877. #endif
  118878. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  118879. #if JUCE_USE_OGGVORBIS
  118880. #include <stdlib.h>
  118881. #include <math.h>
  118882. #include <string.h>
  118883. /**** pack/unpack helpers ******************************************/
  118884. int _ilog(unsigned int v){
  118885. int ret=0;
  118886. while(v){
  118887. ret++;
  118888. v>>=1;
  118889. }
  118890. return(ret);
  118891. }
  118892. /* 32 bit float (not IEEE; nonnormalized mantissa +
  118893. biased exponent) : neeeeeee eeemmmmm mmmmmmmm mmmmmmmm
  118894. Why not IEEE? It's just not that important here. */
  118895. #define VQ_FEXP 10
  118896. #define VQ_FMAN 21
  118897. #define VQ_FEXP_BIAS 768 /* bias toward values smaller than 1. */
  118898. /* doesn't currently guard under/overflow */
  118899. long _float32_pack(float val){
  118900. int sign=0;
  118901. long exp;
  118902. long mant;
  118903. if(val<0){
  118904. sign=0x80000000;
  118905. val= -val;
  118906. }
  118907. exp= floor(log(val)/log(2.f));
  118908. mant=rint(ldexp(val,(VQ_FMAN-1)-exp));
  118909. exp=(exp+VQ_FEXP_BIAS)<<VQ_FMAN;
  118910. return(sign|exp|mant);
  118911. }
  118912. float _float32_unpack(long val){
  118913. double mant=val&0x1fffff;
  118914. int sign=val&0x80000000;
  118915. long exp =(val&0x7fe00000L)>>VQ_FMAN;
  118916. if(sign)mant= -mant;
  118917. return(ldexp(mant,exp-(VQ_FMAN-1)-VQ_FEXP_BIAS));
  118918. }
  118919. /* given a list of word lengths, generate a list of codewords. Works
  118920. for length ordered or unordered, always assigns the lowest valued
  118921. codewords first. Extended to handle unused entries (length 0) */
  118922. ogg_uint32_t *_make_words(long *l,long n,long sparsecount){
  118923. long i,j,count=0;
  118924. ogg_uint32_t marker[33];
  118925. ogg_uint32_t *r=(ogg_uint32_t*)_ogg_malloc((sparsecount?sparsecount:n)*sizeof(*r));
  118926. memset(marker,0,sizeof(marker));
  118927. for(i=0;i<n;i++){
  118928. long length=l[i];
  118929. if(length>0){
  118930. ogg_uint32_t entry=marker[length];
  118931. /* when we claim a node for an entry, we also claim the nodes
  118932. below it (pruning off the imagined tree that may have dangled
  118933. from it) as well as blocking the use of any nodes directly
  118934. above for leaves */
  118935. /* update ourself */
  118936. if(length<32 && (entry>>length)){
  118937. /* error condition; the lengths must specify an overpopulated tree */
  118938. _ogg_free(r);
  118939. return(NULL);
  118940. }
  118941. r[count++]=entry;
  118942. /* Look to see if the next shorter marker points to the node
  118943. above. if so, update it and repeat. */
  118944. {
  118945. for(j=length;j>0;j--){
  118946. if(marker[j]&1){
  118947. /* have to jump branches */
  118948. if(j==1)
  118949. marker[1]++;
  118950. else
  118951. marker[j]=marker[j-1]<<1;
  118952. break; /* invariant says next upper marker would already
  118953. have been moved if it was on the same path */
  118954. }
  118955. marker[j]++;
  118956. }
  118957. }
  118958. /* prune the tree; the implicit invariant says all the longer
  118959. markers were dangling from our just-taken node. Dangle them
  118960. from our *new* node. */
  118961. for(j=length+1;j<33;j++)
  118962. if((marker[j]>>1) == entry){
  118963. entry=marker[j];
  118964. marker[j]=marker[j-1]<<1;
  118965. }else
  118966. break;
  118967. }else
  118968. if(sparsecount==0)count++;
  118969. }
  118970. /* bitreverse the words because our bitwise packer/unpacker is LSb
  118971. endian */
  118972. for(i=0,count=0;i<n;i++){
  118973. ogg_uint32_t temp=0;
  118974. for(j=0;j<l[i];j++){
  118975. temp<<=1;
  118976. temp|=(r[count]>>j)&1;
  118977. }
  118978. if(sparsecount){
  118979. if(l[i])
  118980. r[count++]=temp;
  118981. }else
  118982. r[count++]=temp;
  118983. }
  118984. return(r);
  118985. }
  118986. /* there might be a straightforward one-line way to do the below
  118987. that's portable and totally safe against roundoff, but I haven't
  118988. thought of it. Therefore, we opt on the side of caution */
  118989. long _book_maptype1_quantvals(const static_codebook *b){
  118990. long vals=floor(pow((float)b->entries,1.f/b->dim));
  118991. /* the above *should* be reliable, but we'll not assume that FP is
  118992. ever reliable when bitstream sync is at stake; verify via integer
  118993. means that vals really is the greatest value of dim for which
  118994. vals^b->bim <= b->entries */
  118995. /* treat the above as an initial guess */
  118996. while(1){
  118997. long acc=1;
  118998. long acc1=1;
  118999. int i;
  119000. for(i=0;i<b->dim;i++){
  119001. acc*=vals;
  119002. acc1*=vals+1;
  119003. }
  119004. if(acc<=b->entries && acc1>b->entries){
  119005. return(vals);
  119006. }else{
  119007. if(acc>b->entries){
  119008. vals--;
  119009. }else{
  119010. vals++;
  119011. }
  119012. }
  119013. }
  119014. }
  119015. /* unpack the quantized list of values for encode/decode ***********/
  119016. /* we need to deal with two map types: in map type 1, the values are
  119017. generated algorithmically (each column of the vector counts through
  119018. the values in the quant vector). in map type 2, all the values came
  119019. in in an explicit list. Both value lists must be unpacked */
  119020. float *_book_unquantize(const static_codebook *b,int n,int *sparsemap){
  119021. long j,k,count=0;
  119022. if(b->maptype==1 || b->maptype==2){
  119023. int quantvals;
  119024. float mindel=_float32_unpack(b->q_min);
  119025. float delta=_float32_unpack(b->q_delta);
  119026. float *r=(float*)_ogg_calloc(n*b->dim,sizeof(*r));
  119027. /* maptype 1 and 2 both use a quantized value vector, but
  119028. different sizes */
  119029. switch(b->maptype){
  119030. case 1:
  119031. /* most of the time, entries%dimensions == 0, but we need to be
  119032. well defined. We define that the possible vales at each
  119033. scalar is values == entries/dim. If entries%dim != 0, we'll
  119034. have 'too few' values (values*dim<entries), which means that
  119035. we'll have 'left over' entries; left over entries use zeroed
  119036. values (and are wasted). So don't generate codebooks like
  119037. that */
  119038. quantvals=_book_maptype1_quantvals(b);
  119039. for(j=0;j<b->entries;j++){
  119040. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  119041. float last=0.f;
  119042. int indexdiv=1;
  119043. for(k=0;k<b->dim;k++){
  119044. int index= (j/indexdiv)%quantvals;
  119045. float val=b->quantlist[index];
  119046. val=fabs(val)*delta+mindel+last;
  119047. if(b->q_sequencep)last=val;
  119048. if(sparsemap)
  119049. r[sparsemap[count]*b->dim+k]=val;
  119050. else
  119051. r[count*b->dim+k]=val;
  119052. indexdiv*=quantvals;
  119053. }
  119054. count++;
  119055. }
  119056. }
  119057. break;
  119058. case 2:
  119059. for(j=0;j<b->entries;j++){
  119060. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  119061. float last=0.f;
  119062. for(k=0;k<b->dim;k++){
  119063. float val=b->quantlist[j*b->dim+k];
  119064. val=fabs(val)*delta+mindel+last;
  119065. if(b->q_sequencep)last=val;
  119066. if(sparsemap)
  119067. r[sparsemap[count]*b->dim+k]=val;
  119068. else
  119069. r[count*b->dim+k]=val;
  119070. }
  119071. count++;
  119072. }
  119073. }
  119074. break;
  119075. }
  119076. return(r);
  119077. }
  119078. return(NULL);
  119079. }
  119080. void vorbis_staticbook_clear(static_codebook *b){
  119081. if(b->allocedp){
  119082. if(b->quantlist)_ogg_free(b->quantlist);
  119083. if(b->lengthlist)_ogg_free(b->lengthlist);
  119084. if(b->nearest_tree){
  119085. _ogg_free(b->nearest_tree->ptr0);
  119086. _ogg_free(b->nearest_tree->ptr1);
  119087. _ogg_free(b->nearest_tree->p);
  119088. _ogg_free(b->nearest_tree->q);
  119089. memset(b->nearest_tree,0,sizeof(*b->nearest_tree));
  119090. _ogg_free(b->nearest_tree);
  119091. }
  119092. if(b->thresh_tree){
  119093. _ogg_free(b->thresh_tree->quantthresh);
  119094. _ogg_free(b->thresh_tree->quantmap);
  119095. memset(b->thresh_tree,0,sizeof(*b->thresh_tree));
  119096. _ogg_free(b->thresh_tree);
  119097. }
  119098. memset(b,0,sizeof(*b));
  119099. }
  119100. }
  119101. void vorbis_staticbook_destroy(static_codebook *b){
  119102. if(b->allocedp){
  119103. vorbis_staticbook_clear(b);
  119104. _ogg_free(b);
  119105. }
  119106. }
  119107. void vorbis_book_clear(codebook *b){
  119108. /* static book is not cleared; we're likely called on the lookup and
  119109. the static codebook belongs to the info struct */
  119110. if(b->valuelist)_ogg_free(b->valuelist);
  119111. if(b->codelist)_ogg_free(b->codelist);
  119112. if(b->dec_index)_ogg_free(b->dec_index);
  119113. if(b->dec_codelengths)_ogg_free(b->dec_codelengths);
  119114. if(b->dec_firsttable)_ogg_free(b->dec_firsttable);
  119115. memset(b,0,sizeof(*b));
  119116. }
  119117. int vorbis_book_init_encode(codebook *c,const static_codebook *s){
  119118. memset(c,0,sizeof(*c));
  119119. c->c=s;
  119120. c->entries=s->entries;
  119121. c->used_entries=s->entries;
  119122. c->dim=s->dim;
  119123. c->codelist=_make_words(s->lengthlist,s->entries,0);
  119124. c->valuelist=_book_unquantize(s,s->entries,NULL);
  119125. return(0);
  119126. }
  119127. static int JUCE_CDECL sort32a(const void *a,const void *b){
  119128. return ( **(ogg_uint32_t **)a>**(ogg_uint32_t **)b)-
  119129. ( **(ogg_uint32_t **)a<**(ogg_uint32_t **)b);
  119130. }
  119131. /* decode codebook arrangement is more heavily optimized than encode */
  119132. int vorbis_book_init_decode(codebook *c,const static_codebook *s){
  119133. int i,j,n=0,tabn;
  119134. int *sortindex;
  119135. memset(c,0,sizeof(*c));
  119136. /* count actually used entries */
  119137. for(i=0;i<s->entries;i++)
  119138. if(s->lengthlist[i]>0)
  119139. n++;
  119140. c->entries=s->entries;
  119141. c->used_entries=n;
  119142. c->dim=s->dim;
  119143. /* two different remappings go on here.
  119144. First, we collapse the likely sparse codebook down only to
  119145. actually represented values/words. This collapsing needs to be
  119146. indexed as map-valueless books are used to encode original entry
  119147. positions as integers.
  119148. Second, we reorder all vectors, including the entry index above,
  119149. by sorted bitreversed codeword to allow treeless decode. */
  119150. {
  119151. /* perform sort */
  119152. ogg_uint32_t *codes=_make_words(s->lengthlist,s->entries,c->used_entries);
  119153. ogg_uint32_t **codep=(ogg_uint32_t**)alloca(sizeof(*codep)*n);
  119154. if(codes==NULL)goto err_out;
  119155. for(i=0;i<n;i++){
  119156. codes[i]=ogg_bitreverse(codes[i]);
  119157. codep[i]=codes+i;
  119158. }
  119159. qsort(codep,n,sizeof(*codep),sort32a);
  119160. sortindex=(int*)alloca(n*sizeof(*sortindex));
  119161. c->codelist=(ogg_uint32_t*)_ogg_malloc(n*sizeof(*c->codelist));
  119162. /* the index is a reverse index */
  119163. for(i=0;i<n;i++){
  119164. int position=codep[i]-codes;
  119165. sortindex[position]=i;
  119166. }
  119167. for(i=0;i<n;i++)
  119168. c->codelist[sortindex[i]]=codes[i];
  119169. _ogg_free(codes);
  119170. }
  119171. c->valuelist=_book_unquantize(s,n,sortindex);
  119172. c->dec_index=(int*)_ogg_malloc(n*sizeof(*c->dec_index));
  119173. for(n=0,i=0;i<s->entries;i++)
  119174. if(s->lengthlist[i]>0)
  119175. c->dec_index[sortindex[n++]]=i;
  119176. c->dec_codelengths=(char*)_ogg_malloc(n*sizeof(*c->dec_codelengths));
  119177. for(n=0,i=0;i<s->entries;i++)
  119178. if(s->lengthlist[i]>0)
  119179. c->dec_codelengths[sortindex[n++]]=s->lengthlist[i];
  119180. c->dec_firsttablen=_ilog(c->used_entries)-4; /* this is magic */
  119181. if(c->dec_firsttablen<5)c->dec_firsttablen=5;
  119182. if(c->dec_firsttablen>8)c->dec_firsttablen=8;
  119183. tabn=1<<c->dec_firsttablen;
  119184. c->dec_firsttable=(ogg_uint32_t*)_ogg_calloc(tabn,sizeof(*c->dec_firsttable));
  119185. c->dec_maxlength=0;
  119186. for(i=0;i<n;i++){
  119187. if(c->dec_maxlength<c->dec_codelengths[i])
  119188. c->dec_maxlength=c->dec_codelengths[i];
  119189. if(c->dec_codelengths[i]<=c->dec_firsttablen){
  119190. ogg_uint32_t orig=ogg_bitreverse(c->codelist[i]);
  119191. for(j=0;j<(1<<(c->dec_firsttablen-c->dec_codelengths[i]));j++)
  119192. c->dec_firsttable[orig|(j<<c->dec_codelengths[i])]=i+1;
  119193. }
  119194. }
  119195. /* now fill in 'unused' entries in the firsttable with hi/lo search
  119196. hints for the non-direct-hits */
  119197. {
  119198. ogg_uint32_t mask=0xfffffffeUL<<(31-c->dec_firsttablen);
  119199. long lo=0,hi=0;
  119200. for(i=0;i<tabn;i++){
  119201. ogg_uint32_t word=i<<(32-c->dec_firsttablen);
  119202. if(c->dec_firsttable[ogg_bitreverse(word)]==0){
  119203. while((lo+1)<n && c->codelist[lo+1]<=word)lo++;
  119204. while( hi<n && word>=(c->codelist[hi]&mask))hi++;
  119205. /* we only actually have 15 bits per hint to play with here.
  119206. In order to overflow gracefully (nothing breaks, efficiency
  119207. just drops), encode as the difference from the extremes. */
  119208. {
  119209. unsigned long loval=lo;
  119210. unsigned long hival=n-hi;
  119211. if(loval>0x7fff)loval=0x7fff;
  119212. if(hival>0x7fff)hival=0x7fff;
  119213. c->dec_firsttable[ogg_bitreverse(word)]=
  119214. 0x80000000UL | (loval<<15) | hival;
  119215. }
  119216. }
  119217. }
  119218. }
  119219. return(0);
  119220. err_out:
  119221. vorbis_book_clear(c);
  119222. return(-1);
  119223. }
  119224. static float _dist(int el,float *ref, float *b,int step){
  119225. int i;
  119226. float acc=0.f;
  119227. for(i=0;i<el;i++){
  119228. float val=(ref[i]-b[i*step]);
  119229. acc+=val*val;
  119230. }
  119231. return(acc);
  119232. }
  119233. int _best(codebook *book, float *a, int step){
  119234. encode_aux_threshmatch *tt=book->c->thresh_tree;
  119235. #if 0
  119236. encode_aux_nearestmatch *nt=book->c->nearest_tree;
  119237. encode_aux_pigeonhole *pt=book->c->pigeon_tree;
  119238. #endif
  119239. int dim=book->dim;
  119240. int k,o;
  119241. /*int savebest=-1;
  119242. float saverr;*/
  119243. /* do we have a threshhold encode hint? */
  119244. if(tt){
  119245. int index=0,i;
  119246. /* find the quant val of each scalar */
  119247. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  119248. i=tt->threshvals>>1;
  119249. if(a[o]<tt->quantthresh[i]){
  119250. for(;i>0;i--)
  119251. if(a[o]>=tt->quantthresh[i-1])
  119252. break;
  119253. }else{
  119254. for(i++;i<tt->threshvals-1;i++)
  119255. if(a[o]<tt->quantthresh[i])break;
  119256. }
  119257. index=(index*tt->quantvals)+tt->quantmap[i];
  119258. }
  119259. /* regular lattices are easy :-) */
  119260. if(book->c->lengthlist[index]>0) /* is this unused? If so, we'll
  119261. use a decision tree after all
  119262. and fall through*/
  119263. return(index);
  119264. }
  119265. #if 0
  119266. /* do we have a pigeonhole encode hint? */
  119267. if(pt){
  119268. const static_codebook *c=book->c;
  119269. int i,besti=-1;
  119270. float best=0.f;
  119271. int entry=0;
  119272. /* dealing with sequentialness is a pain in the ass */
  119273. if(c->q_sequencep){
  119274. int pv;
  119275. long mul=1;
  119276. float qlast=0;
  119277. for(k=0,o=0;k<dim;k++,o+=step){
  119278. pv=(int)((a[o]-qlast-pt->min)/pt->del);
  119279. if(pv<0 || pv>=pt->mapentries)break;
  119280. entry+=pt->pigeonmap[pv]*mul;
  119281. mul*=pt->quantvals;
  119282. qlast+=pv*pt->del+pt->min;
  119283. }
  119284. }else{
  119285. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  119286. int pv=(int)((a[o]-pt->min)/pt->del);
  119287. if(pv<0 || pv>=pt->mapentries)break;
  119288. entry=entry*pt->quantvals+pt->pigeonmap[pv];
  119289. }
  119290. }
  119291. /* must be within the pigeonholable range; if we quant outside (or
  119292. in an entry that we define no list for), brute force it */
  119293. if(k==dim && pt->fitlength[entry]){
  119294. /* search the abbreviated list */
  119295. long *list=pt->fitlist+pt->fitmap[entry];
  119296. for(i=0;i<pt->fitlength[entry];i++){
  119297. float this=_dist(dim,book->valuelist+list[i]*dim,a,step);
  119298. if(besti==-1 || this<best){
  119299. best=this;
  119300. besti=list[i];
  119301. }
  119302. }
  119303. return(besti);
  119304. }
  119305. }
  119306. if(nt){
  119307. /* optimized using the decision tree */
  119308. while(1){
  119309. float c=0.f;
  119310. float *p=book->valuelist+nt->p[ptr];
  119311. float *q=book->valuelist+nt->q[ptr];
  119312. for(k=0,o=0;k<dim;k++,o+=step)
  119313. c+=(p[k]-q[k])*(a[o]-(p[k]+q[k])*.5);
  119314. if(c>0.f) /* in A */
  119315. ptr= -nt->ptr0[ptr];
  119316. else /* in B */
  119317. ptr= -nt->ptr1[ptr];
  119318. if(ptr<=0)break;
  119319. }
  119320. return(-ptr);
  119321. }
  119322. #endif
  119323. /* brute force it! */
  119324. {
  119325. const static_codebook *c=book->c;
  119326. int i,besti=-1;
  119327. float best=0.f;
  119328. float *e=book->valuelist;
  119329. for(i=0;i<book->entries;i++){
  119330. if(c->lengthlist[i]>0){
  119331. float thisx=_dist(dim,e,a,step);
  119332. if(besti==-1 || thisx<best){
  119333. best=thisx;
  119334. besti=i;
  119335. }
  119336. }
  119337. e+=dim;
  119338. }
  119339. /*if(savebest!=-1 && savebest!=besti){
  119340. fprintf(stderr,"brute force/pigeonhole disagreement:\n"
  119341. "original:");
  119342. for(i=0;i<dim*step;i+=step)fprintf(stderr,"%g,",a[i]);
  119343. fprintf(stderr,"\n"
  119344. "pigeonhole (entry %d, err %g):",savebest,saverr);
  119345. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  119346. (book->valuelist+savebest*dim)[i]);
  119347. fprintf(stderr,"\n"
  119348. "bruteforce (entry %d, err %g):",besti,best);
  119349. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  119350. (book->valuelist+besti*dim)[i]);
  119351. fprintf(stderr,"\n");
  119352. }*/
  119353. return(besti);
  119354. }
  119355. }
  119356. long vorbis_book_codeword(codebook *book,int entry){
  119357. if(book->c) /* only use with encode; decode optimizations are
  119358. allowed to break this */
  119359. return book->codelist[entry];
  119360. return -1;
  119361. }
  119362. long vorbis_book_codelen(codebook *book,int entry){
  119363. if(book->c) /* only use with encode; decode optimizations are
  119364. allowed to break this */
  119365. return book->c->lengthlist[entry];
  119366. return -1;
  119367. }
  119368. #ifdef _V_SELFTEST
  119369. /* Unit tests of the dequantizer; this stuff will be OK
  119370. cross-platform, I simply want to be sure that special mapping cases
  119371. actually work properly; a bug could go unnoticed for a while */
  119372. #include <stdio.h>
  119373. /* cases:
  119374. no mapping
  119375. full, explicit mapping
  119376. algorithmic mapping
  119377. nonsequential
  119378. sequential
  119379. */
  119380. static long full_quantlist1[]={0,1,2,3, 4,5,6,7, 8,3,6,1};
  119381. static long partial_quantlist1[]={0,7,2};
  119382. /* no mapping */
  119383. static_codebook test1={
  119384. 4,16,
  119385. NULL,
  119386. 0,
  119387. 0,0,0,0,
  119388. NULL,
  119389. NULL,NULL
  119390. };
  119391. static float *test1_result=NULL;
  119392. /* linear, full mapping, nonsequential */
  119393. static_codebook test2={
  119394. 4,3,
  119395. NULL,
  119396. 2,
  119397. -533200896,1611661312,4,0,
  119398. full_quantlist1,
  119399. NULL,NULL
  119400. };
  119401. static float test2_result[]={-3,-2,-1,0, 1,2,3,4, 5,0,3,-2};
  119402. /* linear, full mapping, sequential */
  119403. static_codebook test3={
  119404. 4,3,
  119405. NULL,
  119406. 2,
  119407. -533200896,1611661312,4,1,
  119408. full_quantlist1,
  119409. NULL,NULL
  119410. };
  119411. static float test3_result[]={-3,-5,-6,-6, 1,3,6,10, 5,5,8,6};
  119412. /* linear, algorithmic mapping, nonsequential */
  119413. static_codebook test4={
  119414. 3,27,
  119415. NULL,
  119416. 1,
  119417. -533200896,1611661312,4,0,
  119418. partial_quantlist1,
  119419. NULL,NULL
  119420. };
  119421. static float test4_result[]={-3,-3,-3, 4,-3,-3, -1,-3,-3,
  119422. -3, 4,-3, 4, 4,-3, -1, 4,-3,
  119423. -3,-1,-3, 4,-1,-3, -1,-1,-3,
  119424. -3,-3, 4, 4,-3, 4, -1,-3, 4,
  119425. -3, 4, 4, 4, 4, 4, -1, 4, 4,
  119426. -3,-1, 4, 4,-1, 4, -1,-1, 4,
  119427. -3,-3,-1, 4,-3,-1, -1,-3,-1,
  119428. -3, 4,-1, 4, 4,-1, -1, 4,-1,
  119429. -3,-1,-1, 4,-1,-1, -1,-1,-1};
  119430. /* linear, algorithmic mapping, sequential */
  119431. static_codebook test5={
  119432. 3,27,
  119433. NULL,
  119434. 1,
  119435. -533200896,1611661312,4,1,
  119436. partial_quantlist1,
  119437. NULL,NULL
  119438. };
  119439. static float test5_result[]={-3,-6,-9, 4, 1,-2, -1,-4,-7,
  119440. -3, 1,-2, 4, 8, 5, -1, 3, 0,
  119441. -3,-4,-7, 4, 3, 0, -1,-2,-5,
  119442. -3,-6,-2, 4, 1, 5, -1,-4, 0,
  119443. -3, 1, 5, 4, 8,12, -1, 3, 7,
  119444. -3,-4, 0, 4, 3, 7, -1,-2, 2,
  119445. -3,-6,-7, 4, 1, 0, -1,-4,-5,
  119446. -3, 1, 0, 4, 8, 7, -1, 3, 2,
  119447. -3,-4,-5, 4, 3, 2, -1,-2,-3};
  119448. void run_test(static_codebook *b,float *comp){
  119449. float *out=_book_unquantize(b,b->entries,NULL);
  119450. int i;
  119451. if(comp){
  119452. if(!out){
  119453. fprintf(stderr,"_book_unquantize incorrectly returned NULL\n");
  119454. exit(1);
  119455. }
  119456. for(i=0;i<b->entries*b->dim;i++)
  119457. if(fabs(out[i]-comp[i])>.0001){
  119458. fprintf(stderr,"disagreement in unquantized and reference data:\n"
  119459. "position %d, %g != %g\n",i,out[i],comp[i]);
  119460. exit(1);
  119461. }
  119462. }else{
  119463. if(out){
  119464. fprintf(stderr,"_book_unquantize returned a value array: \n"
  119465. " correct result should have been NULL\n");
  119466. exit(1);
  119467. }
  119468. }
  119469. }
  119470. int main(){
  119471. /* run the nine dequant tests, and compare to the hand-rolled results */
  119472. fprintf(stderr,"Dequant test 1... ");
  119473. run_test(&test1,test1_result);
  119474. fprintf(stderr,"OK\nDequant test 2... ");
  119475. run_test(&test2,test2_result);
  119476. fprintf(stderr,"OK\nDequant test 3... ");
  119477. run_test(&test3,test3_result);
  119478. fprintf(stderr,"OK\nDequant test 4... ");
  119479. run_test(&test4,test4_result);
  119480. fprintf(stderr,"OK\nDequant test 5... ");
  119481. run_test(&test5,test5_result);
  119482. fprintf(stderr,"OK\n\n");
  119483. return(0);
  119484. }
  119485. #endif
  119486. #endif
  119487. /*** End of inlined file: sharedbook.c ***/
  119488. /*** Start of inlined file: smallft.c ***/
  119489. /* FFT implementation from OggSquish, minus cosine transforms,
  119490. * minus all but radix 2/4 case. In Vorbis we only need this
  119491. * cut-down version.
  119492. *
  119493. * To do more than just power-of-two sized vectors, see the full
  119494. * version I wrote for NetLib.
  119495. *
  119496. * Note that the packing is a little strange; rather than the FFT r/i
  119497. * packing following R_0, I_n, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1,
  119498. * it follows R_0, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1, I_n like the
  119499. * FORTRAN version
  119500. */
  119501. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  119502. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  119503. // tasks..
  119504. #if JUCE_MSVC
  119505. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  119506. #endif
  119507. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  119508. #if JUCE_USE_OGGVORBIS
  119509. #include <stdlib.h>
  119510. #include <string.h>
  119511. #include <math.h>
  119512. static void drfti1(int n, float *wa, int *ifac){
  119513. static int ntryh[4] = { 4,2,3,5 };
  119514. static float tpi = 6.28318530717958648f;
  119515. float arg,argh,argld,fi;
  119516. int ntry=0,i,j=-1;
  119517. int k1, l1, l2, ib;
  119518. int ld, ii, ip, is, nq, nr;
  119519. int ido, ipm, nfm1;
  119520. int nl=n;
  119521. int nf=0;
  119522. L101:
  119523. j++;
  119524. if (j < 4)
  119525. ntry=ntryh[j];
  119526. else
  119527. ntry+=2;
  119528. L104:
  119529. nq=nl/ntry;
  119530. nr=nl-ntry*nq;
  119531. if (nr!=0) goto L101;
  119532. nf++;
  119533. ifac[nf+1]=ntry;
  119534. nl=nq;
  119535. if(ntry!=2)goto L107;
  119536. if(nf==1)goto L107;
  119537. for (i=1;i<nf;i++){
  119538. ib=nf-i+1;
  119539. ifac[ib+1]=ifac[ib];
  119540. }
  119541. ifac[2] = 2;
  119542. L107:
  119543. if(nl!=1)goto L104;
  119544. ifac[0]=n;
  119545. ifac[1]=nf;
  119546. argh=tpi/n;
  119547. is=0;
  119548. nfm1=nf-1;
  119549. l1=1;
  119550. if(nfm1==0)return;
  119551. for (k1=0;k1<nfm1;k1++){
  119552. ip=ifac[k1+2];
  119553. ld=0;
  119554. l2=l1*ip;
  119555. ido=n/l2;
  119556. ipm=ip-1;
  119557. for (j=0;j<ipm;j++){
  119558. ld+=l1;
  119559. i=is;
  119560. argld=(float)ld*argh;
  119561. fi=0.f;
  119562. for (ii=2;ii<ido;ii+=2){
  119563. fi+=1.f;
  119564. arg=fi*argld;
  119565. wa[i++]=cos(arg);
  119566. wa[i++]=sin(arg);
  119567. }
  119568. is+=ido;
  119569. }
  119570. l1=l2;
  119571. }
  119572. }
  119573. static void fdrffti(int n, float *wsave, int *ifac){
  119574. if (n == 1) return;
  119575. drfti1(n, wsave+n, ifac);
  119576. }
  119577. static void dradf2(int ido,int l1,float *cc,float *ch,float *wa1){
  119578. int i,k;
  119579. float ti2,tr2;
  119580. int t0,t1,t2,t3,t4,t5,t6;
  119581. t1=0;
  119582. t0=(t2=l1*ido);
  119583. t3=ido<<1;
  119584. for(k=0;k<l1;k++){
  119585. ch[t1<<1]=cc[t1]+cc[t2];
  119586. ch[(t1<<1)+t3-1]=cc[t1]-cc[t2];
  119587. t1+=ido;
  119588. t2+=ido;
  119589. }
  119590. if(ido<2)return;
  119591. if(ido==2)goto L105;
  119592. t1=0;
  119593. t2=t0;
  119594. for(k=0;k<l1;k++){
  119595. t3=t2;
  119596. t4=(t1<<1)+(ido<<1);
  119597. t5=t1;
  119598. t6=t1+t1;
  119599. for(i=2;i<ido;i+=2){
  119600. t3+=2;
  119601. t4-=2;
  119602. t5+=2;
  119603. t6+=2;
  119604. tr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  119605. ti2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  119606. ch[t6]=cc[t5]+ti2;
  119607. ch[t4]=ti2-cc[t5];
  119608. ch[t6-1]=cc[t5-1]+tr2;
  119609. ch[t4-1]=cc[t5-1]-tr2;
  119610. }
  119611. t1+=ido;
  119612. t2+=ido;
  119613. }
  119614. if(ido%2==1)return;
  119615. L105:
  119616. t3=(t2=(t1=ido)-1);
  119617. t2+=t0;
  119618. for(k=0;k<l1;k++){
  119619. ch[t1]=-cc[t2];
  119620. ch[t1-1]=cc[t3];
  119621. t1+=ido<<1;
  119622. t2+=ido;
  119623. t3+=ido;
  119624. }
  119625. }
  119626. static void dradf4(int ido,int l1,float *cc,float *ch,float *wa1,
  119627. float *wa2,float *wa3){
  119628. static float hsqt2 = .70710678118654752f;
  119629. int i,k,t0,t1,t2,t3,t4,t5,t6;
  119630. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  119631. t0=l1*ido;
  119632. t1=t0;
  119633. t4=t1<<1;
  119634. t2=t1+(t1<<1);
  119635. t3=0;
  119636. for(k=0;k<l1;k++){
  119637. tr1=cc[t1]+cc[t2];
  119638. tr2=cc[t3]+cc[t4];
  119639. ch[t5=t3<<2]=tr1+tr2;
  119640. ch[(ido<<2)+t5-1]=tr2-tr1;
  119641. ch[(t5+=(ido<<1))-1]=cc[t3]-cc[t4];
  119642. ch[t5]=cc[t2]-cc[t1];
  119643. t1+=ido;
  119644. t2+=ido;
  119645. t3+=ido;
  119646. t4+=ido;
  119647. }
  119648. if(ido<2)return;
  119649. if(ido==2)goto L105;
  119650. t1=0;
  119651. for(k=0;k<l1;k++){
  119652. t2=t1;
  119653. t4=t1<<2;
  119654. t5=(t6=ido<<1)+t4;
  119655. for(i=2;i<ido;i+=2){
  119656. t3=(t2+=2);
  119657. t4+=2;
  119658. t5-=2;
  119659. t3+=t0;
  119660. cr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  119661. ci2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  119662. t3+=t0;
  119663. cr3=wa2[i-2]*cc[t3-1]+wa2[i-1]*cc[t3];
  119664. ci3=wa2[i-2]*cc[t3]-wa2[i-1]*cc[t3-1];
  119665. t3+=t0;
  119666. cr4=wa3[i-2]*cc[t3-1]+wa3[i-1]*cc[t3];
  119667. ci4=wa3[i-2]*cc[t3]-wa3[i-1]*cc[t3-1];
  119668. tr1=cr2+cr4;
  119669. tr4=cr4-cr2;
  119670. ti1=ci2+ci4;
  119671. ti4=ci2-ci4;
  119672. ti2=cc[t2]+ci3;
  119673. ti3=cc[t2]-ci3;
  119674. tr2=cc[t2-1]+cr3;
  119675. tr3=cc[t2-1]-cr3;
  119676. ch[t4-1]=tr1+tr2;
  119677. ch[t4]=ti1+ti2;
  119678. ch[t5-1]=tr3-ti4;
  119679. ch[t5]=tr4-ti3;
  119680. ch[t4+t6-1]=ti4+tr3;
  119681. ch[t4+t6]=tr4+ti3;
  119682. ch[t5+t6-1]=tr2-tr1;
  119683. ch[t5+t6]=ti1-ti2;
  119684. }
  119685. t1+=ido;
  119686. }
  119687. if(ido&1)return;
  119688. L105:
  119689. t2=(t1=t0+ido-1)+(t0<<1);
  119690. t3=ido<<2;
  119691. t4=ido;
  119692. t5=ido<<1;
  119693. t6=ido;
  119694. for(k=0;k<l1;k++){
  119695. ti1=-hsqt2*(cc[t1]+cc[t2]);
  119696. tr1=hsqt2*(cc[t1]-cc[t2]);
  119697. ch[t4-1]=tr1+cc[t6-1];
  119698. ch[t4+t5-1]=cc[t6-1]-tr1;
  119699. ch[t4]=ti1-cc[t1+t0];
  119700. ch[t4+t5]=ti1+cc[t1+t0];
  119701. t1+=ido;
  119702. t2+=ido;
  119703. t4+=t3;
  119704. t6+=ido;
  119705. }
  119706. }
  119707. static void dradfg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  119708. float *c2,float *ch,float *ch2,float *wa){
  119709. static float tpi=6.283185307179586f;
  119710. int idij,ipph,i,j,k,l,ic,ik,is;
  119711. int t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  119712. float dc2,ai1,ai2,ar1,ar2,ds2;
  119713. int nbd;
  119714. float dcp,arg,dsp,ar1h,ar2h;
  119715. int idp2,ipp2;
  119716. arg=tpi/(float)ip;
  119717. dcp=cos(arg);
  119718. dsp=sin(arg);
  119719. ipph=(ip+1)>>1;
  119720. ipp2=ip;
  119721. idp2=ido;
  119722. nbd=(ido-1)>>1;
  119723. t0=l1*ido;
  119724. t10=ip*ido;
  119725. if(ido==1)goto L119;
  119726. for(ik=0;ik<idl1;ik++)ch2[ik]=c2[ik];
  119727. t1=0;
  119728. for(j=1;j<ip;j++){
  119729. t1+=t0;
  119730. t2=t1;
  119731. for(k=0;k<l1;k++){
  119732. ch[t2]=c1[t2];
  119733. t2+=ido;
  119734. }
  119735. }
  119736. is=-ido;
  119737. t1=0;
  119738. if(nbd>l1){
  119739. for(j=1;j<ip;j++){
  119740. t1+=t0;
  119741. is+=ido;
  119742. t2= -ido+t1;
  119743. for(k=0;k<l1;k++){
  119744. idij=is-1;
  119745. t2+=ido;
  119746. t3=t2;
  119747. for(i=2;i<ido;i+=2){
  119748. idij+=2;
  119749. t3+=2;
  119750. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  119751. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  119752. }
  119753. }
  119754. }
  119755. }else{
  119756. for(j=1;j<ip;j++){
  119757. is+=ido;
  119758. idij=is-1;
  119759. t1+=t0;
  119760. t2=t1;
  119761. for(i=2;i<ido;i+=2){
  119762. idij+=2;
  119763. t2+=2;
  119764. t3=t2;
  119765. for(k=0;k<l1;k++){
  119766. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  119767. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  119768. t3+=ido;
  119769. }
  119770. }
  119771. }
  119772. }
  119773. t1=0;
  119774. t2=ipp2*t0;
  119775. if(nbd<l1){
  119776. for(j=1;j<ipph;j++){
  119777. t1+=t0;
  119778. t2-=t0;
  119779. t3=t1;
  119780. t4=t2;
  119781. for(i=2;i<ido;i+=2){
  119782. t3+=2;
  119783. t4+=2;
  119784. t5=t3-ido;
  119785. t6=t4-ido;
  119786. for(k=0;k<l1;k++){
  119787. t5+=ido;
  119788. t6+=ido;
  119789. c1[t5-1]=ch[t5-1]+ch[t6-1];
  119790. c1[t6-1]=ch[t5]-ch[t6];
  119791. c1[t5]=ch[t5]+ch[t6];
  119792. c1[t6]=ch[t6-1]-ch[t5-1];
  119793. }
  119794. }
  119795. }
  119796. }else{
  119797. for(j=1;j<ipph;j++){
  119798. t1+=t0;
  119799. t2-=t0;
  119800. t3=t1;
  119801. t4=t2;
  119802. for(k=0;k<l1;k++){
  119803. t5=t3;
  119804. t6=t4;
  119805. for(i=2;i<ido;i+=2){
  119806. t5+=2;
  119807. t6+=2;
  119808. c1[t5-1]=ch[t5-1]+ch[t6-1];
  119809. c1[t6-1]=ch[t5]-ch[t6];
  119810. c1[t5]=ch[t5]+ch[t6];
  119811. c1[t6]=ch[t6-1]-ch[t5-1];
  119812. }
  119813. t3+=ido;
  119814. t4+=ido;
  119815. }
  119816. }
  119817. }
  119818. L119:
  119819. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  119820. t1=0;
  119821. t2=ipp2*idl1;
  119822. for(j=1;j<ipph;j++){
  119823. t1+=t0;
  119824. t2-=t0;
  119825. t3=t1-ido;
  119826. t4=t2-ido;
  119827. for(k=0;k<l1;k++){
  119828. t3+=ido;
  119829. t4+=ido;
  119830. c1[t3]=ch[t3]+ch[t4];
  119831. c1[t4]=ch[t4]-ch[t3];
  119832. }
  119833. }
  119834. ar1=1.f;
  119835. ai1=0.f;
  119836. t1=0;
  119837. t2=ipp2*idl1;
  119838. t3=(ip-1)*idl1;
  119839. for(l=1;l<ipph;l++){
  119840. t1+=idl1;
  119841. t2-=idl1;
  119842. ar1h=dcp*ar1-dsp*ai1;
  119843. ai1=dcp*ai1+dsp*ar1;
  119844. ar1=ar1h;
  119845. t4=t1;
  119846. t5=t2;
  119847. t6=t3;
  119848. t7=idl1;
  119849. for(ik=0;ik<idl1;ik++){
  119850. ch2[t4++]=c2[ik]+ar1*c2[t7++];
  119851. ch2[t5++]=ai1*c2[t6++];
  119852. }
  119853. dc2=ar1;
  119854. ds2=ai1;
  119855. ar2=ar1;
  119856. ai2=ai1;
  119857. t4=idl1;
  119858. t5=(ipp2-1)*idl1;
  119859. for(j=2;j<ipph;j++){
  119860. t4+=idl1;
  119861. t5-=idl1;
  119862. ar2h=dc2*ar2-ds2*ai2;
  119863. ai2=dc2*ai2+ds2*ar2;
  119864. ar2=ar2h;
  119865. t6=t1;
  119866. t7=t2;
  119867. t8=t4;
  119868. t9=t5;
  119869. for(ik=0;ik<idl1;ik++){
  119870. ch2[t6++]+=ar2*c2[t8++];
  119871. ch2[t7++]+=ai2*c2[t9++];
  119872. }
  119873. }
  119874. }
  119875. t1=0;
  119876. for(j=1;j<ipph;j++){
  119877. t1+=idl1;
  119878. t2=t1;
  119879. for(ik=0;ik<idl1;ik++)ch2[ik]+=c2[t2++];
  119880. }
  119881. if(ido<l1)goto L132;
  119882. t1=0;
  119883. t2=0;
  119884. for(k=0;k<l1;k++){
  119885. t3=t1;
  119886. t4=t2;
  119887. for(i=0;i<ido;i++)cc[t4++]=ch[t3++];
  119888. t1+=ido;
  119889. t2+=t10;
  119890. }
  119891. goto L135;
  119892. L132:
  119893. for(i=0;i<ido;i++){
  119894. t1=i;
  119895. t2=i;
  119896. for(k=0;k<l1;k++){
  119897. cc[t2]=ch[t1];
  119898. t1+=ido;
  119899. t2+=t10;
  119900. }
  119901. }
  119902. L135:
  119903. t1=0;
  119904. t2=ido<<1;
  119905. t3=0;
  119906. t4=ipp2*t0;
  119907. for(j=1;j<ipph;j++){
  119908. t1+=t2;
  119909. t3+=t0;
  119910. t4-=t0;
  119911. t5=t1;
  119912. t6=t3;
  119913. t7=t4;
  119914. for(k=0;k<l1;k++){
  119915. cc[t5-1]=ch[t6];
  119916. cc[t5]=ch[t7];
  119917. t5+=t10;
  119918. t6+=ido;
  119919. t7+=ido;
  119920. }
  119921. }
  119922. if(ido==1)return;
  119923. if(nbd<l1)goto L141;
  119924. t1=-ido;
  119925. t3=0;
  119926. t4=0;
  119927. t5=ipp2*t0;
  119928. for(j=1;j<ipph;j++){
  119929. t1+=t2;
  119930. t3+=t2;
  119931. t4+=t0;
  119932. t5-=t0;
  119933. t6=t1;
  119934. t7=t3;
  119935. t8=t4;
  119936. t9=t5;
  119937. for(k=0;k<l1;k++){
  119938. for(i=2;i<ido;i+=2){
  119939. ic=idp2-i;
  119940. cc[i+t7-1]=ch[i+t8-1]+ch[i+t9-1];
  119941. cc[ic+t6-1]=ch[i+t8-1]-ch[i+t9-1];
  119942. cc[i+t7]=ch[i+t8]+ch[i+t9];
  119943. cc[ic+t6]=ch[i+t9]-ch[i+t8];
  119944. }
  119945. t6+=t10;
  119946. t7+=t10;
  119947. t8+=ido;
  119948. t9+=ido;
  119949. }
  119950. }
  119951. return;
  119952. L141:
  119953. t1=-ido;
  119954. t3=0;
  119955. t4=0;
  119956. t5=ipp2*t0;
  119957. for(j=1;j<ipph;j++){
  119958. t1+=t2;
  119959. t3+=t2;
  119960. t4+=t0;
  119961. t5-=t0;
  119962. for(i=2;i<ido;i+=2){
  119963. t6=idp2+t1-i;
  119964. t7=i+t3;
  119965. t8=i+t4;
  119966. t9=i+t5;
  119967. for(k=0;k<l1;k++){
  119968. cc[t7-1]=ch[t8-1]+ch[t9-1];
  119969. cc[t6-1]=ch[t8-1]-ch[t9-1];
  119970. cc[t7]=ch[t8]+ch[t9];
  119971. cc[t6]=ch[t9]-ch[t8];
  119972. t6+=t10;
  119973. t7+=t10;
  119974. t8+=ido;
  119975. t9+=ido;
  119976. }
  119977. }
  119978. }
  119979. }
  119980. static void drftf1(int n,float *c,float *ch,float *wa,int *ifac){
  119981. int i,k1,l1,l2;
  119982. int na,kh,nf;
  119983. int ip,iw,ido,idl1,ix2,ix3;
  119984. nf=ifac[1];
  119985. na=1;
  119986. l2=n;
  119987. iw=n;
  119988. for(k1=0;k1<nf;k1++){
  119989. kh=nf-k1;
  119990. ip=ifac[kh+1];
  119991. l1=l2/ip;
  119992. ido=n/l2;
  119993. idl1=ido*l1;
  119994. iw-=(ip-1)*ido;
  119995. na=1-na;
  119996. if(ip!=4)goto L102;
  119997. ix2=iw+ido;
  119998. ix3=ix2+ido;
  119999. if(na!=0)
  120000. dradf4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120001. else
  120002. dradf4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120003. goto L110;
  120004. L102:
  120005. if(ip!=2)goto L104;
  120006. if(na!=0)goto L103;
  120007. dradf2(ido,l1,c,ch,wa+iw-1);
  120008. goto L110;
  120009. L103:
  120010. dradf2(ido,l1,ch,c,wa+iw-1);
  120011. goto L110;
  120012. L104:
  120013. if(ido==1)na=1-na;
  120014. if(na!=0)goto L109;
  120015. dradfg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  120016. na=1;
  120017. goto L110;
  120018. L109:
  120019. dradfg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  120020. na=0;
  120021. L110:
  120022. l2=l1;
  120023. }
  120024. if(na==1)return;
  120025. for(i=0;i<n;i++)c[i]=ch[i];
  120026. }
  120027. static void dradb2(int ido,int l1,float *cc,float *ch,float *wa1){
  120028. int i,k,t0,t1,t2,t3,t4,t5,t6;
  120029. float ti2,tr2;
  120030. t0=l1*ido;
  120031. t1=0;
  120032. t2=0;
  120033. t3=(ido<<1)-1;
  120034. for(k=0;k<l1;k++){
  120035. ch[t1]=cc[t2]+cc[t3+t2];
  120036. ch[t1+t0]=cc[t2]-cc[t3+t2];
  120037. t2=(t1+=ido)<<1;
  120038. }
  120039. if(ido<2)return;
  120040. if(ido==2)goto L105;
  120041. t1=0;
  120042. t2=0;
  120043. for(k=0;k<l1;k++){
  120044. t3=t1;
  120045. t5=(t4=t2)+(ido<<1);
  120046. t6=t0+t1;
  120047. for(i=2;i<ido;i+=2){
  120048. t3+=2;
  120049. t4+=2;
  120050. t5-=2;
  120051. t6+=2;
  120052. ch[t3-1]=cc[t4-1]+cc[t5-1];
  120053. tr2=cc[t4-1]-cc[t5-1];
  120054. ch[t3]=cc[t4]-cc[t5];
  120055. ti2=cc[t4]+cc[t5];
  120056. ch[t6-1]=wa1[i-2]*tr2-wa1[i-1]*ti2;
  120057. ch[t6]=wa1[i-2]*ti2+wa1[i-1]*tr2;
  120058. }
  120059. t2=(t1+=ido)<<1;
  120060. }
  120061. if(ido%2==1)return;
  120062. L105:
  120063. t1=ido-1;
  120064. t2=ido-1;
  120065. for(k=0;k<l1;k++){
  120066. ch[t1]=cc[t2]+cc[t2];
  120067. ch[t1+t0]=-(cc[t2+1]+cc[t2+1]);
  120068. t1+=ido;
  120069. t2+=ido<<1;
  120070. }
  120071. }
  120072. static void dradb3(int ido,int l1,float *cc,float *ch,float *wa1,
  120073. float *wa2){
  120074. static float taur = -.5f;
  120075. static float taui = .8660254037844386f;
  120076. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  120077. float ci2,ci3,di2,di3,cr2,cr3,dr2,dr3,ti2,tr2;
  120078. t0=l1*ido;
  120079. t1=0;
  120080. t2=t0<<1;
  120081. t3=ido<<1;
  120082. t4=ido+(ido<<1);
  120083. t5=0;
  120084. for(k=0;k<l1;k++){
  120085. tr2=cc[t3-1]+cc[t3-1];
  120086. cr2=cc[t5]+(taur*tr2);
  120087. ch[t1]=cc[t5]+tr2;
  120088. ci3=taui*(cc[t3]+cc[t3]);
  120089. ch[t1+t0]=cr2-ci3;
  120090. ch[t1+t2]=cr2+ci3;
  120091. t1+=ido;
  120092. t3+=t4;
  120093. t5+=t4;
  120094. }
  120095. if(ido==1)return;
  120096. t1=0;
  120097. t3=ido<<1;
  120098. for(k=0;k<l1;k++){
  120099. t7=t1+(t1<<1);
  120100. t6=(t5=t7+t3);
  120101. t8=t1;
  120102. t10=(t9=t1+t0)+t0;
  120103. for(i=2;i<ido;i+=2){
  120104. t5+=2;
  120105. t6-=2;
  120106. t7+=2;
  120107. t8+=2;
  120108. t9+=2;
  120109. t10+=2;
  120110. tr2=cc[t5-1]+cc[t6-1];
  120111. cr2=cc[t7-1]+(taur*tr2);
  120112. ch[t8-1]=cc[t7-1]+tr2;
  120113. ti2=cc[t5]-cc[t6];
  120114. ci2=cc[t7]+(taur*ti2);
  120115. ch[t8]=cc[t7]+ti2;
  120116. cr3=taui*(cc[t5-1]-cc[t6-1]);
  120117. ci3=taui*(cc[t5]+cc[t6]);
  120118. dr2=cr2-ci3;
  120119. dr3=cr2+ci3;
  120120. di2=ci2+cr3;
  120121. di3=ci2-cr3;
  120122. ch[t9-1]=wa1[i-2]*dr2-wa1[i-1]*di2;
  120123. ch[t9]=wa1[i-2]*di2+wa1[i-1]*dr2;
  120124. ch[t10-1]=wa2[i-2]*dr3-wa2[i-1]*di3;
  120125. ch[t10]=wa2[i-2]*di3+wa2[i-1]*dr3;
  120126. }
  120127. t1+=ido;
  120128. }
  120129. }
  120130. static void dradb4(int ido,int l1,float *cc,float *ch,float *wa1,
  120131. float *wa2,float *wa3){
  120132. static float sqrt2=1.414213562373095f;
  120133. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8;
  120134. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  120135. t0=l1*ido;
  120136. t1=0;
  120137. t2=ido<<2;
  120138. t3=0;
  120139. t6=ido<<1;
  120140. for(k=0;k<l1;k++){
  120141. t4=t3+t6;
  120142. t5=t1;
  120143. tr3=cc[t4-1]+cc[t4-1];
  120144. tr4=cc[t4]+cc[t4];
  120145. tr1=cc[t3]-cc[(t4+=t6)-1];
  120146. tr2=cc[t3]+cc[t4-1];
  120147. ch[t5]=tr2+tr3;
  120148. ch[t5+=t0]=tr1-tr4;
  120149. ch[t5+=t0]=tr2-tr3;
  120150. ch[t5+=t0]=tr1+tr4;
  120151. t1+=ido;
  120152. t3+=t2;
  120153. }
  120154. if(ido<2)return;
  120155. if(ido==2)goto L105;
  120156. t1=0;
  120157. for(k=0;k<l1;k++){
  120158. t5=(t4=(t3=(t2=t1<<2)+t6))+t6;
  120159. t7=t1;
  120160. for(i=2;i<ido;i+=2){
  120161. t2+=2;
  120162. t3+=2;
  120163. t4-=2;
  120164. t5-=2;
  120165. t7+=2;
  120166. ti1=cc[t2]+cc[t5];
  120167. ti2=cc[t2]-cc[t5];
  120168. ti3=cc[t3]-cc[t4];
  120169. tr4=cc[t3]+cc[t4];
  120170. tr1=cc[t2-1]-cc[t5-1];
  120171. tr2=cc[t2-1]+cc[t5-1];
  120172. ti4=cc[t3-1]-cc[t4-1];
  120173. tr3=cc[t3-1]+cc[t4-1];
  120174. ch[t7-1]=tr2+tr3;
  120175. cr3=tr2-tr3;
  120176. ch[t7]=ti2+ti3;
  120177. ci3=ti2-ti3;
  120178. cr2=tr1-tr4;
  120179. cr4=tr1+tr4;
  120180. ci2=ti1+ti4;
  120181. ci4=ti1-ti4;
  120182. ch[(t8=t7+t0)-1]=wa1[i-2]*cr2-wa1[i-1]*ci2;
  120183. ch[t8]=wa1[i-2]*ci2+wa1[i-1]*cr2;
  120184. ch[(t8+=t0)-1]=wa2[i-2]*cr3-wa2[i-1]*ci3;
  120185. ch[t8]=wa2[i-2]*ci3+wa2[i-1]*cr3;
  120186. ch[(t8+=t0)-1]=wa3[i-2]*cr4-wa3[i-1]*ci4;
  120187. ch[t8]=wa3[i-2]*ci4+wa3[i-1]*cr4;
  120188. }
  120189. t1+=ido;
  120190. }
  120191. if(ido%2 == 1)return;
  120192. L105:
  120193. t1=ido;
  120194. t2=ido<<2;
  120195. t3=ido-1;
  120196. t4=ido+(ido<<1);
  120197. for(k=0;k<l1;k++){
  120198. t5=t3;
  120199. ti1=cc[t1]+cc[t4];
  120200. ti2=cc[t4]-cc[t1];
  120201. tr1=cc[t1-1]-cc[t4-1];
  120202. tr2=cc[t1-1]+cc[t4-1];
  120203. ch[t5]=tr2+tr2;
  120204. ch[t5+=t0]=sqrt2*(tr1-ti1);
  120205. ch[t5+=t0]=ti2+ti2;
  120206. ch[t5+=t0]=-sqrt2*(tr1+ti1);
  120207. t3+=ido;
  120208. t1+=t2;
  120209. t4+=t2;
  120210. }
  120211. }
  120212. static void dradbg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  120213. float *c2,float *ch,float *ch2,float *wa){
  120214. static float tpi=6.283185307179586f;
  120215. int idij,ipph,i,j,k,l,ik,is,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,
  120216. t11,t12;
  120217. float dc2,ai1,ai2,ar1,ar2,ds2;
  120218. int nbd;
  120219. float dcp,arg,dsp,ar1h,ar2h;
  120220. int ipp2;
  120221. t10=ip*ido;
  120222. t0=l1*ido;
  120223. arg=tpi/(float)ip;
  120224. dcp=cos(arg);
  120225. dsp=sin(arg);
  120226. nbd=(ido-1)>>1;
  120227. ipp2=ip;
  120228. ipph=(ip+1)>>1;
  120229. if(ido<l1)goto L103;
  120230. t1=0;
  120231. t2=0;
  120232. for(k=0;k<l1;k++){
  120233. t3=t1;
  120234. t4=t2;
  120235. for(i=0;i<ido;i++){
  120236. ch[t3]=cc[t4];
  120237. t3++;
  120238. t4++;
  120239. }
  120240. t1+=ido;
  120241. t2+=t10;
  120242. }
  120243. goto L106;
  120244. L103:
  120245. t1=0;
  120246. for(i=0;i<ido;i++){
  120247. t2=t1;
  120248. t3=t1;
  120249. for(k=0;k<l1;k++){
  120250. ch[t2]=cc[t3];
  120251. t2+=ido;
  120252. t3+=t10;
  120253. }
  120254. t1++;
  120255. }
  120256. L106:
  120257. t1=0;
  120258. t2=ipp2*t0;
  120259. t7=(t5=ido<<1);
  120260. for(j=1;j<ipph;j++){
  120261. t1+=t0;
  120262. t2-=t0;
  120263. t3=t1;
  120264. t4=t2;
  120265. t6=t5;
  120266. for(k=0;k<l1;k++){
  120267. ch[t3]=cc[t6-1]+cc[t6-1];
  120268. ch[t4]=cc[t6]+cc[t6];
  120269. t3+=ido;
  120270. t4+=ido;
  120271. t6+=t10;
  120272. }
  120273. t5+=t7;
  120274. }
  120275. if (ido == 1)goto L116;
  120276. if(nbd<l1)goto L112;
  120277. t1=0;
  120278. t2=ipp2*t0;
  120279. t7=0;
  120280. for(j=1;j<ipph;j++){
  120281. t1+=t0;
  120282. t2-=t0;
  120283. t3=t1;
  120284. t4=t2;
  120285. t7+=(ido<<1);
  120286. t8=t7;
  120287. for(k=0;k<l1;k++){
  120288. t5=t3;
  120289. t6=t4;
  120290. t9=t8;
  120291. t11=t8;
  120292. for(i=2;i<ido;i+=2){
  120293. t5+=2;
  120294. t6+=2;
  120295. t9+=2;
  120296. t11-=2;
  120297. ch[t5-1]=cc[t9-1]+cc[t11-1];
  120298. ch[t6-1]=cc[t9-1]-cc[t11-1];
  120299. ch[t5]=cc[t9]-cc[t11];
  120300. ch[t6]=cc[t9]+cc[t11];
  120301. }
  120302. t3+=ido;
  120303. t4+=ido;
  120304. t8+=t10;
  120305. }
  120306. }
  120307. goto L116;
  120308. L112:
  120309. t1=0;
  120310. t2=ipp2*t0;
  120311. t7=0;
  120312. for(j=1;j<ipph;j++){
  120313. t1+=t0;
  120314. t2-=t0;
  120315. t3=t1;
  120316. t4=t2;
  120317. t7+=(ido<<1);
  120318. t8=t7;
  120319. t9=t7;
  120320. for(i=2;i<ido;i+=2){
  120321. t3+=2;
  120322. t4+=2;
  120323. t8+=2;
  120324. t9-=2;
  120325. t5=t3;
  120326. t6=t4;
  120327. t11=t8;
  120328. t12=t9;
  120329. for(k=0;k<l1;k++){
  120330. ch[t5-1]=cc[t11-1]+cc[t12-1];
  120331. ch[t6-1]=cc[t11-1]-cc[t12-1];
  120332. ch[t5]=cc[t11]-cc[t12];
  120333. ch[t6]=cc[t11]+cc[t12];
  120334. t5+=ido;
  120335. t6+=ido;
  120336. t11+=t10;
  120337. t12+=t10;
  120338. }
  120339. }
  120340. }
  120341. L116:
  120342. ar1=1.f;
  120343. ai1=0.f;
  120344. t1=0;
  120345. t9=(t2=ipp2*idl1);
  120346. t3=(ip-1)*idl1;
  120347. for(l=1;l<ipph;l++){
  120348. t1+=idl1;
  120349. t2-=idl1;
  120350. ar1h=dcp*ar1-dsp*ai1;
  120351. ai1=dcp*ai1+dsp*ar1;
  120352. ar1=ar1h;
  120353. t4=t1;
  120354. t5=t2;
  120355. t6=0;
  120356. t7=idl1;
  120357. t8=t3;
  120358. for(ik=0;ik<idl1;ik++){
  120359. c2[t4++]=ch2[t6++]+ar1*ch2[t7++];
  120360. c2[t5++]=ai1*ch2[t8++];
  120361. }
  120362. dc2=ar1;
  120363. ds2=ai1;
  120364. ar2=ar1;
  120365. ai2=ai1;
  120366. t6=idl1;
  120367. t7=t9-idl1;
  120368. for(j=2;j<ipph;j++){
  120369. t6+=idl1;
  120370. t7-=idl1;
  120371. ar2h=dc2*ar2-ds2*ai2;
  120372. ai2=dc2*ai2+ds2*ar2;
  120373. ar2=ar2h;
  120374. t4=t1;
  120375. t5=t2;
  120376. t11=t6;
  120377. t12=t7;
  120378. for(ik=0;ik<idl1;ik++){
  120379. c2[t4++]+=ar2*ch2[t11++];
  120380. c2[t5++]+=ai2*ch2[t12++];
  120381. }
  120382. }
  120383. }
  120384. t1=0;
  120385. for(j=1;j<ipph;j++){
  120386. t1+=idl1;
  120387. t2=t1;
  120388. for(ik=0;ik<idl1;ik++)ch2[ik]+=ch2[t2++];
  120389. }
  120390. t1=0;
  120391. t2=ipp2*t0;
  120392. for(j=1;j<ipph;j++){
  120393. t1+=t0;
  120394. t2-=t0;
  120395. t3=t1;
  120396. t4=t2;
  120397. for(k=0;k<l1;k++){
  120398. ch[t3]=c1[t3]-c1[t4];
  120399. ch[t4]=c1[t3]+c1[t4];
  120400. t3+=ido;
  120401. t4+=ido;
  120402. }
  120403. }
  120404. if(ido==1)goto L132;
  120405. if(nbd<l1)goto L128;
  120406. t1=0;
  120407. t2=ipp2*t0;
  120408. for(j=1;j<ipph;j++){
  120409. t1+=t0;
  120410. t2-=t0;
  120411. t3=t1;
  120412. t4=t2;
  120413. for(k=0;k<l1;k++){
  120414. t5=t3;
  120415. t6=t4;
  120416. for(i=2;i<ido;i+=2){
  120417. t5+=2;
  120418. t6+=2;
  120419. ch[t5-1]=c1[t5-1]-c1[t6];
  120420. ch[t6-1]=c1[t5-1]+c1[t6];
  120421. ch[t5]=c1[t5]+c1[t6-1];
  120422. ch[t6]=c1[t5]-c1[t6-1];
  120423. }
  120424. t3+=ido;
  120425. t4+=ido;
  120426. }
  120427. }
  120428. goto L132;
  120429. L128:
  120430. t1=0;
  120431. t2=ipp2*t0;
  120432. for(j=1;j<ipph;j++){
  120433. t1+=t0;
  120434. t2-=t0;
  120435. t3=t1;
  120436. t4=t2;
  120437. for(i=2;i<ido;i+=2){
  120438. t3+=2;
  120439. t4+=2;
  120440. t5=t3;
  120441. t6=t4;
  120442. for(k=0;k<l1;k++){
  120443. ch[t5-1]=c1[t5-1]-c1[t6];
  120444. ch[t6-1]=c1[t5-1]+c1[t6];
  120445. ch[t5]=c1[t5]+c1[t6-1];
  120446. ch[t6]=c1[t5]-c1[t6-1];
  120447. t5+=ido;
  120448. t6+=ido;
  120449. }
  120450. }
  120451. }
  120452. L132:
  120453. if(ido==1)return;
  120454. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  120455. t1=0;
  120456. for(j=1;j<ip;j++){
  120457. t2=(t1+=t0);
  120458. for(k=0;k<l1;k++){
  120459. c1[t2]=ch[t2];
  120460. t2+=ido;
  120461. }
  120462. }
  120463. if(nbd>l1)goto L139;
  120464. is= -ido-1;
  120465. t1=0;
  120466. for(j=1;j<ip;j++){
  120467. is+=ido;
  120468. t1+=t0;
  120469. idij=is;
  120470. t2=t1;
  120471. for(i=2;i<ido;i+=2){
  120472. t2+=2;
  120473. idij+=2;
  120474. t3=t2;
  120475. for(k=0;k<l1;k++){
  120476. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  120477. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  120478. t3+=ido;
  120479. }
  120480. }
  120481. }
  120482. return;
  120483. L139:
  120484. is= -ido-1;
  120485. t1=0;
  120486. for(j=1;j<ip;j++){
  120487. is+=ido;
  120488. t1+=t0;
  120489. t2=t1;
  120490. for(k=0;k<l1;k++){
  120491. idij=is;
  120492. t3=t2;
  120493. for(i=2;i<ido;i+=2){
  120494. idij+=2;
  120495. t3+=2;
  120496. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  120497. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  120498. }
  120499. t2+=ido;
  120500. }
  120501. }
  120502. }
  120503. static void drftb1(int n, float *c, float *ch, float *wa, int *ifac){
  120504. int i,k1,l1,l2;
  120505. int na;
  120506. int nf,ip,iw,ix2,ix3,ido,idl1;
  120507. nf=ifac[1];
  120508. na=0;
  120509. l1=1;
  120510. iw=1;
  120511. for(k1=0;k1<nf;k1++){
  120512. ip=ifac[k1 + 2];
  120513. l2=ip*l1;
  120514. ido=n/l2;
  120515. idl1=ido*l1;
  120516. if(ip!=4)goto L103;
  120517. ix2=iw+ido;
  120518. ix3=ix2+ido;
  120519. if(na!=0)
  120520. dradb4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120521. else
  120522. dradb4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120523. na=1-na;
  120524. goto L115;
  120525. L103:
  120526. if(ip!=2)goto L106;
  120527. if(na!=0)
  120528. dradb2(ido,l1,ch,c,wa+iw-1);
  120529. else
  120530. dradb2(ido,l1,c,ch,wa+iw-1);
  120531. na=1-na;
  120532. goto L115;
  120533. L106:
  120534. if(ip!=3)goto L109;
  120535. ix2=iw+ido;
  120536. if(na!=0)
  120537. dradb3(ido,l1,ch,c,wa+iw-1,wa+ix2-1);
  120538. else
  120539. dradb3(ido,l1,c,ch,wa+iw-1,wa+ix2-1);
  120540. na=1-na;
  120541. goto L115;
  120542. L109:
  120543. /* The radix five case can be translated later..... */
  120544. /* if(ip!=5)goto L112;
  120545. ix2=iw+ido;
  120546. ix3=ix2+ido;
  120547. ix4=ix3+ido;
  120548. if(na!=0)
  120549. dradb5(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  120550. else
  120551. dradb5(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  120552. na=1-na;
  120553. goto L115;
  120554. L112:*/
  120555. if(na!=0)
  120556. dradbg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  120557. else
  120558. dradbg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  120559. if(ido==1)na=1-na;
  120560. L115:
  120561. l1=l2;
  120562. iw+=(ip-1)*ido;
  120563. }
  120564. if(na==0)return;
  120565. for(i=0;i<n;i++)c[i]=ch[i];
  120566. }
  120567. void drft_forward(drft_lookup *l,float *data){
  120568. if(l->n==1)return;
  120569. drftf1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  120570. }
  120571. void drft_backward(drft_lookup *l,float *data){
  120572. if (l->n==1)return;
  120573. drftb1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  120574. }
  120575. void drft_init(drft_lookup *l,int n){
  120576. l->n=n;
  120577. l->trigcache=(float*)_ogg_calloc(3*n,sizeof(*l->trigcache));
  120578. l->splitcache=(int*)_ogg_calloc(32,sizeof(*l->splitcache));
  120579. fdrffti(n, l->trigcache, l->splitcache);
  120580. }
  120581. void drft_clear(drft_lookup *l){
  120582. if(l){
  120583. if(l->trigcache)_ogg_free(l->trigcache);
  120584. if(l->splitcache)_ogg_free(l->splitcache);
  120585. memset(l,0,sizeof(*l));
  120586. }
  120587. }
  120588. #endif
  120589. /*** End of inlined file: smallft.c ***/
  120590. /*** Start of inlined file: synthesis.c ***/
  120591. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  120592. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  120593. // tasks..
  120594. #if JUCE_MSVC
  120595. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  120596. #endif
  120597. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  120598. #if JUCE_USE_OGGVORBIS
  120599. #include <stdio.h>
  120600. int vorbis_synthesis(vorbis_block *vb,ogg_packet *op){
  120601. vorbis_dsp_state *vd=vb->vd;
  120602. private_state *b=(private_state*)vd->backend_state;
  120603. vorbis_info *vi=vd->vi;
  120604. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  120605. oggpack_buffer *opb=&vb->opb;
  120606. int type,mode,i;
  120607. /* first things first. Make sure decode is ready */
  120608. _vorbis_block_ripcord(vb);
  120609. oggpack_readinit(opb,op->packet,op->bytes);
  120610. /* Check the packet type */
  120611. if(oggpack_read(opb,1)!=0){
  120612. /* Oops. This is not an audio data packet */
  120613. return(OV_ENOTAUDIO);
  120614. }
  120615. /* read our mode and pre/post windowsize */
  120616. mode=oggpack_read(opb,b->modebits);
  120617. if(mode==-1)return(OV_EBADPACKET);
  120618. vb->mode=mode;
  120619. vb->W=ci->mode_param[mode]->blockflag;
  120620. if(vb->W){
  120621. /* this doesn;t get mapped through mode selection as it's used
  120622. only for window selection */
  120623. vb->lW=oggpack_read(opb,1);
  120624. vb->nW=oggpack_read(opb,1);
  120625. if(vb->nW==-1) return(OV_EBADPACKET);
  120626. }else{
  120627. vb->lW=0;
  120628. vb->nW=0;
  120629. }
  120630. /* more setup */
  120631. vb->granulepos=op->granulepos;
  120632. vb->sequence=op->packetno;
  120633. vb->eofflag=op->e_o_s;
  120634. /* alloc pcm passback storage */
  120635. vb->pcmend=ci->blocksizes[vb->W];
  120636. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  120637. for(i=0;i<vi->channels;i++)
  120638. vb->pcm[i]=(float*)_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  120639. /* unpack_header enforces range checking */
  120640. type=ci->map_type[ci->mode_param[mode]->mapping];
  120641. return(_mapping_P[type]->inverse(vb,ci->map_param[ci->mode_param[mode]->
  120642. mapping]));
  120643. }
  120644. /* used to track pcm position without actually performing decode.
  120645. Useful for sequential 'fast forward' */
  120646. int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op){
  120647. vorbis_dsp_state *vd=vb->vd;
  120648. private_state *b=(private_state*)vd->backend_state;
  120649. vorbis_info *vi=vd->vi;
  120650. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120651. oggpack_buffer *opb=&vb->opb;
  120652. int mode;
  120653. /* first things first. Make sure decode is ready */
  120654. _vorbis_block_ripcord(vb);
  120655. oggpack_readinit(opb,op->packet,op->bytes);
  120656. /* Check the packet type */
  120657. if(oggpack_read(opb,1)!=0){
  120658. /* Oops. This is not an audio data packet */
  120659. return(OV_ENOTAUDIO);
  120660. }
  120661. /* read our mode and pre/post windowsize */
  120662. mode=oggpack_read(opb,b->modebits);
  120663. if(mode==-1)return(OV_EBADPACKET);
  120664. vb->mode=mode;
  120665. vb->W=ci->mode_param[mode]->blockflag;
  120666. if(vb->W){
  120667. vb->lW=oggpack_read(opb,1);
  120668. vb->nW=oggpack_read(opb,1);
  120669. if(vb->nW==-1) return(OV_EBADPACKET);
  120670. }else{
  120671. vb->lW=0;
  120672. vb->nW=0;
  120673. }
  120674. /* more setup */
  120675. vb->granulepos=op->granulepos;
  120676. vb->sequence=op->packetno;
  120677. vb->eofflag=op->e_o_s;
  120678. /* no pcm */
  120679. vb->pcmend=0;
  120680. vb->pcm=NULL;
  120681. return(0);
  120682. }
  120683. long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op){
  120684. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120685. oggpack_buffer opb;
  120686. int mode;
  120687. oggpack_readinit(&opb,op->packet,op->bytes);
  120688. /* Check the packet type */
  120689. if(oggpack_read(&opb,1)!=0){
  120690. /* Oops. This is not an audio data packet */
  120691. return(OV_ENOTAUDIO);
  120692. }
  120693. {
  120694. int modebits=0;
  120695. int v=ci->modes;
  120696. while(v>1){
  120697. modebits++;
  120698. v>>=1;
  120699. }
  120700. /* read our mode and pre/post windowsize */
  120701. mode=oggpack_read(&opb,modebits);
  120702. }
  120703. if(mode==-1)return(OV_EBADPACKET);
  120704. return(ci->blocksizes[ci->mode_param[mode]->blockflag]);
  120705. }
  120706. int vorbis_synthesis_halfrate(vorbis_info *vi,int flag){
  120707. /* set / clear half-sample-rate mode */
  120708. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120709. /* right now, our MDCT can't handle < 64 sample windows. */
  120710. if(ci->blocksizes[0]<=64 && flag)return -1;
  120711. ci->halfrate_flag=(flag?1:0);
  120712. return 0;
  120713. }
  120714. int vorbis_synthesis_halfrate_p(vorbis_info *vi){
  120715. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120716. return ci->halfrate_flag;
  120717. }
  120718. #endif
  120719. /*** End of inlined file: synthesis.c ***/
  120720. /*** Start of inlined file: vorbisenc.c ***/
  120721. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  120722. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  120723. // tasks..
  120724. #if JUCE_MSVC
  120725. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  120726. #endif
  120727. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  120728. #if JUCE_USE_OGGVORBIS
  120729. #include <stdlib.h>
  120730. #include <string.h>
  120731. #include <math.h>
  120732. /* careful with this; it's using static array sizing to make managing
  120733. all the modes a little less annoying. If we use a residue backend
  120734. with > 12 partition types, or a different division of iteration,
  120735. this needs to be updated. */
  120736. typedef struct {
  120737. static_codebook *books[12][3];
  120738. } static_bookblock;
  120739. typedef struct {
  120740. int res_type;
  120741. int limit_type; /* 0 lowpass limited, 1 point stereo limited */
  120742. vorbis_info_residue0 *res;
  120743. static_codebook *book_aux;
  120744. static_codebook *book_aux_managed;
  120745. static_bookblock *books_base;
  120746. static_bookblock *books_base_managed;
  120747. } vorbis_residue_template;
  120748. typedef struct {
  120749. vorbis_info_mapping0 *map;
  120750. vorbis_residue_template *res;
  120751. } vorbis_mapping_template;
  120752. typedef struct vp_adjblock{
  120753. int block[P_BANDS];
  120754. } vp_adjblock;
  120755. typedef struct {
  120756. int data[NOISE_COMPAND_LEVELS];
  120757. } compandblock;
  120758. /* high level configuration information for setting things up
  120759. step-by-step with the detailed vorbis_encode_ctl interface.
  120760. There's a fair amount of redundancy such that interactive setup
  120761. does not directly deal with any vorbis_info or codec_setup_info
  120762. initialization; it's all stored (until full init) in this highlevel
  120763. setup, then flushed out to the real codec setup structs later. */
  120764. typedef struct {
  120765. int att[P_NOISECURVES];
  120766. float boost;
  120767. float decay;
  120768. } att3;
  120769. typedef struct { int data[P_NOISECURVES]; } adj3;
  120770. typedef struct {
  120771. int pre[PACKETBLOBS];
  120772. int post[PACKETBLOBS];
  120773. float kHz[PACKETBLOBS];
  120774. float lowpasskHz[PACKETBLOBS];
  120775. } adj_stereo;
  120776. typedef struct {
  120777. int lo;
  120778. int hi;
  120779. int fixed;
  120780. } noiseguard;
  120781. typedef struct {
  120782. int data[P_NOISECURVES][17];
  120783. } noise3;
  120784. typedef struct {
  120785. int mappings;
  120786. double *rate_mapping;
  120787. double *quality_mapping;
  120788. int coupling_restriction;
  120789. long samplerate_min_restriction;
  120790. long samplerate_max_restriction;
  120791. int *blocksize_short;
  120792. int *blocksize_long;
  120793. att3 *psy_tone_masteratt;
  120794. int *psy_tone_0dB;
  120795. int *psy_tone_dBsuppress;
  120796. vp_adjblock *psy_tone_adj_impulse;
  120797. vp_adjblock *psy_tone_adj_long;
  120798. vp_adjblock *psy_tone_adj_other;
  120799. noiseguard *psy_noiseguards;
  120800. noise3 *psy_noise_bias_impulse;
  120801. noise3 *psy_noise_bias_padding;
  120802. noise3 *psy_noise_bias_trans;
  120803. noise3 *psy_noise_bias_long;
  120804. int *psy_noise_dBsuppress;
  120805. compandblock *psy_noise_compand;
  120806. double *psy_noise_compand_short_mapping;
  120807. double *psy_noise_compand_long_mapping;
  120808. int *psy_noise_normal_start[2];
  120809. int *psy_noise_normal_partition[2];
  120810. double *psy_noise_normal_thresh;
  120811. int *psy_ath_float;
  120812. int *psy_ath_abs;
  120813. double *psy_lowpass;
  120814. vorbis_info_psy_global *global_params;
  120815. double *global_mapping;
  120816. adj_stereo *stereo_modes;
  120817. static_codebook ***floor_books;
  120818. vorbis_info_floor1 *floor_params;
  120819. int *floor_short_mapping;
  120820. int *floor_long_mapping;
  120821. vorbis_mapping_template *maps;
  120822. } ve_setup_data_template;
  120823. /* a few static coder conventions */
  120824. static vorbis_info_mode _mode_template[2]={
  120825. {0,0,0,0},
  120826. {1,0,0,1}
  120827. };
  120828. static vorbis_info_mapping0 _map_nominal[2]={
  120829. {1, {0,0}, {0}, {0}, 1,{0},{1}},
  120830. {1, {0,0}, {1}, {1}, 1,{0},{1}}
  120831. };
  120832. /*** Start of inlined file: setup_44.h ***/
  120833. /*** Start of inlined file: floor_all.h ***/
  120834. /*** Start of inlined file: floor_books.h ***/
  120835. static long _huff_lengthlist_line_256x7_0sub1[] = {
  120836. 0, 2, 3, 3, 3, 3, 4, 3, 4,
  120837. };
  120838. static static_codebook _huff_book_line_256x7_0sub1 = {
  120839. 1, 9,
  120840. _huff_lengthlist_line_256x7_0sub1,
  120841. 0, 0, 0, 0, 0,
  120842. NULL,
  120843. NULL,
  120844. NULL,
  120845. NULL,
  120846. 0
  120847. };
  120848. static long _huff_lengthlist_line_256x7_0sub2[] = {
  120849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 4, 3, 5, 3,
  120850. 6, 3, 6, 4, 6, 4, 7, 5, 7,
  120851. };
  120852. static static_codebook _huff_book_line_256x7_0sub2 = {
  120853. 1, 25,
  120854. _huff_lengthlist_line_256x7_0sub2,
  120855. 0, 0, 0, 0, 0,
  120856. NULL,
  120857. NULL,
  120858. NULL,
  120859. NULL,
  120860. 0
  120861. };
  120862. static long _huff_lengthlist_line_256x7_0sub3[] = {
  120863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 2, 5, 3, 5, 3,
  120865. 6, 3, 6, 4, 7, 6, 7, 8, 7, 9, 8, 9, 9, 9,10, 9,
  120866. 11,13,11,13,10,10,13,13,13,13,13,13,12,12,12,12,
  120867. };
  120868. static static_codebook _huff_book_line_256x7_0sub3 = {
  120869. 1, 64,
  120870. _huff_lengthlist_line_256x7_0sub3,
  120871. 0, 0, 0, 0, 0,
  120872. NULL,
  120873. NULL,
  120874. NULL,
  120875. NULL,
  120876. 0
  120877. };
  120878. static long _huff_lengthlist_line_256x7_1sub1[] = {
  120879. 0, 3, 3, 3, 3, 2, 4, 3, 4,
  120880. };
  120881. static static_codebook _huff_book_line_256x7_1sub1 = {
  120882. 1, 9,
  120883. _huff_lengthlist_line_256x7_1sub1,
  120884. 0, 0, 0, 0, 0,
  120885. NULL,
  120886. NULL,
  120887. NULL,
  120888. NULL,
  120889. 0
  120890. };
  120891. static long _huff_lengthlist_line_256x7_1sub2[] = {
  120892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 3, 4, 3, 4, 4,
  120893. 5, 4, 6, 5, 6, 7, 6, 8, 8,
  120894. };
  120895. static static_codebook _huff_book_line_256x7_1sub2 = {
  120896. 1, 25,
  120897. _huff_lengthlist_line_256x7_1sub2,
  120898. 0, 0, 0, 0, 0,
  120899. NULL,
  120900. NULL,
  120901. NULL,
  120902. NULL,
  120903. 0
  120904. };
  120905. static long _huff_lengthlist_line_256x7_1sub3[] = {
  120906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 4, 3, 6, 3, 7,
  120908. 3, 8, 5, 8, 6, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120909. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7,
  120910. };
  120911. static static_codebook _huff_book_line_256x7_1sub3 = {
  120912. 1, 64,
  120913. _huff_lengthlist_line_256x7_1sub3,
  120914. 0, 0, 0, 0, 0,
  120915. NULL,
  120916. NULL,
  120917. NULL,
  120918. NULL,
  120919. 0
  120920. };
  120921. static long _huff_lengthlist_line_256x7_class0[] = {
  120922. 7, 5, 5, 9, 9, 6, 6, 9,12, 8, 7, 8,11, 8, 9,15,
  120923. 6, 3, 3, 7, 7, 4, 3, 6, 9, 6, 5, 6, 8, 6, 8,15,
  120924. 8, 5, 5, 9, 8, 5, 4, 6,10, 7, 5, 5,11, 8, 7,15,
  120925. 14,15,13,13,13,13, 8,11,15,10, 7, 6,11, 9,10,15,
  120926. };
  120927. static static_codebook _huff_book_line_256x7_class0 = {
  120928. 1, 64,
  120929. _huff_lengthlist_line_256x7_class0,
  120930. 0, 0, 0, 0, 0,
  120931. NULL,
  120932. NULL,
  120933. NULL,
  120934. NULL,
  120935. 0
  120936. };
  120937. static long _huff_lengthlist_line_256x7_class1[] = {
  120938. 5, 6, 8,15, 6, 9,10,15,10,11,12,15,15,15,15,15,
  120939. 4, 6, 7,15, 6, 7, 8,15, 9, 8, 9,15,15,15,15,15,
  120940. 6, 8, 9,15, 7, 7, 8,15,10, 9,10,15,15,15,15,15,
  120941. 15,13,15,15,15,10,11,15,15,13,13,15,15,15,15,15,
  120942. 4, 6, 7,15, 6, 8, 9,15,10,10,12,15,15,15,15,15,
  120943. 2, 5, 6,15, 5, 6, 7,15, 8, 6, 7,15,15,15,15,15,
  120944. 5, 6, 8,15, 5, 6, 7,15, 9, 6, 7,15,15,15,15,15,
  120945. 14,12,13,15,12,10,11,15,15,15,15,15,15,15,15,15,
  120946. 7, 8, 9,15, 9,10,10,15,15,14,14,15,15,15,15,15,
  120947. 5, 6, 7,15, 7, 8, 9,15,12, 9,10,15,15,15,15,15,
  120948. 7, 7, 9,15, 7, 7, 8,15,12, 8, 9,15,15,15,15,15,
  120949. 13,13,14,15,12,11,12,15,15,15,15,15,15,15,15,15,
  120950. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  120951. 13,13,13,15,15,15,15,15,15,15,15,15,15,15,15,15,
  120952. 15,12,13,15,15,12,13,15,15,14,15,15,15,15,15,15,
  120953. 15,15,15,15,15,15,13,15,15,15,15,15,15,15,15,15,
  120954. };
  120955. static static_codebook _huff_book_line_256x7_class1 = {
  120956. 1, 256,
  120957. _huff_lengthlist_line_256x7_class1,
  120958. 0, 0, 0, 0, 0,
  120959. NULL,
  120960. NULL,
  120961. NULL,
  120962. NULL,
  120963. 0
  120964. };
  120965. static long _huff_lengthlist_line_512x17_0sub0[] = {
  120966. 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  120967. 5, 6, 5, 6, 6, 6, 6, 5, 6, 6, 7, 6, 7, 6, 7, 6,
  120968. 7, 6, 8, 7, 8, 7, 8, 7, 8, 7, 8, 7, 9, 7, 9, 7,
  120969. 9, 7, 9, 8, 9, 8,10, 8,10, 8,10, 7,10, 6,10, 8,
  120970. 10, 8,11, 7,10, 7,11, 8,11,11,12,12,11,11,12,11,
  120971. 13,11,13,11,13,12,15,12,13,13,14,14,14,14,14,15,
  120972. 15,15,16,14,17,19,19,18,18,18,18,18,18,18,18,18,
  120973. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  120974. };
  120975. static static_codebook _huff_book_line_512x17_0sub0 = {
  120976. 1, 128,
  120977. _huff_lengthlist_line_512x17_0sub0,
  120978. 0, 0, 0, 0, 0,
  120979. NULL,
  120980. NULL,
  120981. NULL,
  120982. NULL,
  120983. 0
  120984. };
  120985. static long _huff_lengthlist_line_512x17_1sub0[] = {
  120986. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  120987. 6, 5, 6, 6, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 8, 7,
  120988. };
  120989. static static_codebook _huff_book_line_512x17_1sub0 = {
  120990. 1, 32,
  120991. _huff_lengthlist_line_512x17_1sub0,
  120992. 0, 0, 0, 0, 0,
  120993. NULL,
  120994. NULL,
  120995. NULL,
  120996. NULL,
  120997. 0
  120998. };
  120999. static long _huff_lengthlist_line_512x17_1sub1[] = {
  121000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121002. 4, 3, 5, 3, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 6, 5,
  121003. 6, 5, 7, 5, 8, 6, 8, 6, 8, 6, 8, 6, 8, 7, 9, 7,
  121004. 9, 7,11, 9,11,11,12,11,14,12,14,16,14,16,13,16,
  121005. 14,16,12,15,13,16,14,16,13,14,12,15,13,15,13,13,
  121006. 13,15,12,14,14,15,13,15,12,15,15,15,15,15,15,15,
  121007. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  121008. };
  121009. static static_codebook _huff_book_line_512x17_1sub1 = {
  121010. 1, 128,
  121011. _huff_lengthlist_line_512x17_1sub1,
  121012. 0, 0, 0, 0, 0,
  121013. NULL,
  121014. NULL,
  121015. NULL,
  121016. NULL,
  121017. 0
  121018. };
  121019. static long _huff_lengthlist_line_512x17_2sub1[] = {
  121020. 0, 4, 5, 4, 4, 4, 5, 4, 4, 4, 5, 4, 5, 4, 5, 3,
  121021. 5, 3,
  121022. };
  121023. static static_codebook _huff_book_line_512x17_2sub1 = {
  121024. 1, 18,
  121025. _huff_lengthlist_line_512x17_2sub1,
  121026. 0, 0, 0, 0, 0,
  121027. NULL,
  121028. NULL,
  121029. NULL,
  121030. NULL,
  121031. 0
  121032. };
  121033. static long _huff_lengthlist_line_512x17_2sub2[] = {
  121034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121035. 0, 0, 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 6, 4, 6, 5,
  121036. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 7, 8, 7, 9, 7,
  121037. 9, 8,
  121038. };
  121039. static static_codebook _huff_book_line_512x17_2sub2 = {
  121040. 1, 50,
  121041. _huff_lengthlist_line_512x17_2sub2,
  121042. 0, 0, 0, 0, 0,
  121043. NULL,
  121044. NULL,
  121045. NULL,
  121046. NULL,
  121047. 0
  121048. };
  121049. static long _huff_lengthlist_line_512x17_2sub3[] = {
  121050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121053. 0, 0, 3, 3, 3, 3, 4, 3, 4, 4, 5, 5, 6, 6, 7, 7,
  121054. 7, 8, 8,11, 8, 9, 9, 9,10,11,11,11, 9,10,10,11,
  121055. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121056. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121057. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121058. };
  121059. static static_codebook _huff_book_line_512x17_2sub3 = {
  121060. 1, 128,
  121061. _huff_lengthlist_line_512x17_2sub3,
  121062. 0, 0, 0, 0, 0,
  121063. NULL,
  121064. NULL,
  121065. NULL,
  121066. NULL,
  121067. 0
  121068. };
  121069. static long _huff_lengthlist_line_512x17_3sub1[] = {
  121070. 0, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 5, 4, 5,
  121071. 5, 5,
  121072. };
  121073. static static_codebook _huff_book_line_512x17_3sub1 = {
  121074. 1, 18,
  121075. _huff_lengthlist_line_512x17_3sub1,
  121076. 0, 0, 0, 0, 0,
  121077. NULL,
  121078. NULL,
  121079. NULL,
  121080. NULL,
  121081. 0
  121082. };
  121083. static long _huff_lengthlist_line_512x17_3sub2[] = {
  121084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121085. 0, 0, 2, 3, 3, 4, 3, 5, 4, 6, 4, 6, 5, 7, 6, 7,
  121086. 6, 8, 6, 8, 7, 9, 8,10, 8,12, 9,13,10,15,10,15,
  121087. 11,14,
  121088. };
  121089. static static_codebook _huff_book_line_512x17_3sub2 = {
  121090. 1, 50,
  121091. _huff_lengthlist_line_512x17_3sub2,
  121092. 0, 0, 0, 0, 0,
  121093. NULL,
  121094. NULL,
  121095. NULL,
  121096. NULL,
  121097. 0
  121098. };
  121099. static long _huff_lengthlist_line_512x17_3sub3[] = {
  121100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121103. 0, 0, 4, 8, 4, 8, 4, 8, 4, 8, 5, 8, 5, 8, 6, 8,
  121104. 4, 8, 4, 8, 5, 8, 5, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121105. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121106. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121107. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121108. };
  121109. static static_codebook _huff_book_line_512x17_3sub3 = {
  121110. 1, 128,
  121111. _huff_lengthlist_line_512x17_3sub3,
  121112. 0, 0, 0, 0, 0,
  121113. NULL,
  121114. NULL,
  121115. NULL,
  121116. NULL,
  121117. 0
  121118. };
  121119. static long _huff_lengthlist_line_512x17_class1[] = {
  121120. 1, 2, 3, 6, 5, 4, 7, 7,
  121121. };
  121122. static static_codebook _huff_book_line_512x17_class1 = {
  121123. 1, 8,
  121124. _huff_lengthlist_line_512x17_class1,
  121125. 0, 0, 0, 0, 0,
  121126. NULL,
  121127. NULL,
  121128. NULL,
  121129. NULL,
  121130. 0
  121131. };
  121132. static long _huff_lengthlist_line_512x17_class2[] = {
  121133. 3, 3, 3,14, 5, 4, 4,11, 8, 6, 6,10,17,12,11,17,
  121134. 6, 5, 5,15, 5, 3, 4,11, 8, 5, 5, 8,16, 9,10,14,
  121135. 10, 8, 9,17, 8, 6, 6,13,10, 7, 7,10,16,11,13,14,
  121136. 17,17,17,17,17,16,16,16,16,15,16,16,16,16,16,16,
  121137. };
  121138. static static_codebook _huff_book_line_512x17_class2 = {
  121139. 1, 64,
  121140. _huff_lengthlist_line_512x17_class2,
  121141. 0, 0, 0, 0, 0,
  121142. NULL,
  121143. NULL,
  121144. NULL,
  121145. NULL,
  121146. 0
  121147. };
  121148. static long _huff_lengthlist_line_512x17_class3[] = {
  121149. 2, 4, 6,17, 4, 5, 7,17, 8, 7,10,17,17,17,17,17,
  121150. 3, 4, 6,15, 3, 3, 6,15, 7, 6, 9,17,17,17,17,17,
  121151. 6, 8,10,17, 6, 6, 8,16, 9, 8,10,17,17,15,16,17,
  121152. 17,17,17,17,12,15,15,16,12,15,15,16,16,16,16,16,
  121153. };
  121154. static static_codebook _huff_book_line_512x17_class3 = {
  121155. 1, 64,
  121156. _huff_lengthlist_line_512x17_class3,
  121157. 0, 0, 0, 0, 0,
  121158. NULL,
  121159. NULL,
  121160. NULL,
  121161. NULL,
  121162. 0
  121163. };
  121164. static long _huff_lengthlist_line_128x4_class0[] = {
  121165. 7, 7, 7,11, 6, 6, 7,11, 7, 6, 6,10,12,10,10,13,
  121166. 7, 7, 8,11, 7, 7, 7,11, 7, 6, 7,10,11,10,10,13,
  121167. 10,10, 9,12, 9, 9, 9,11, 8, 8, 8,11,13,11,10,14,
  121168. 15,15,14,15,15,14,13,14,15,12,12,17,17,17,17,17,
  121169. 7, 7, 6, 9, 6, 6, 6, 9, 7, 6, 6, 8,11,11,10,12,
  121170. 7, 7, 7, 9, 7, 6, 6, 9, 7, 6, 6, 9,13,10,10,11,
  121171. 10, 9, 8,10, 9, 8, 8,10, 8, 8, 7, 9,13,12,10,11,
  121172. 17,14,14,13,15,14,12,13,17,13,12,15,17,17,14,17,
  121173. 7, 6, 6, 7, 6, 6, 5, 7, 6, 6, 6, 6,11, 9, 9, 9,
  121174. 7, 7, 6, 7, 7, 6, 6, 7, 6, 6, 6, 6,10, 9, 8, 9,
  121175. 10, 9, 8, 8, 9, 8, 7, 8, 8, 7, 6, 8,11,10, 9,10,
  121176. 17,17,12,15,15,15,12,14,14,14,10,12,15,13,12,13,
  121177. 11,10, 8,10,11,10, 8, 8,10, 9, 7, 7,10, 9, 9,11,
  121178. 11,11, 9,10,11,10, 8, 9,10, 8, 6, 8,10, 9, 9,11,
  121179. 14,13,10,12,12,11,10,10, 8, 7, 8,10,10,11,11,12,
  121180. 17,17,15,17,17,17,17,17,17,13,12,17,17,17,14,17,
  121181. };
  121182. static static_codebook _huff_book_line_128x4_class0 = {
  121183. 1, 256,
  121184. _huff_lengthlist_line_128x4_class0,
  121185. 0, 0, 0, 0, 0,
  121186. NULL,
  121187. NULL,
  121188. NULL,
  121189. NULL,
  121190. 0
  121191. };
  121192. static long _huff_lengthlist_line_128x4_0sub0[] = {
  121193. 2, 2, 2, 2,
  121194. };
  121195. static static_codebook _huff_book_line_128x4_0sub0 = {
  121196. 1, 4,
  121197. _huff_lengthlist_line_128x4_0sub0,
  121198. 0, 0, 0, 0, 0,
  121199. NULL,
  121200. NULL,
  121201. NULL,
  121202. NULL,
  121203. 0
  121204. };
  121205. static long _huff_lengthlist_line_128x4_0sub1[] = {
  121206. 0, 0, 0, 0, 3, 2, 3, 2, 3, 3,
  121207. };
  121208. static static_codebook _huff_book_line_128x4_0sub1 = {
  121209. 1, 10,
  121210. _huff_lengthlist_line_128x4_0sub1,
  121211. 0, 0, 0, 0, 0,
  121212. NULL,
  121213. NULL,
  121214. NULL,
  121215. NULL,
  121216. 0
  121217. };
  121218. static long _huff_lengthlist_line_128x4_0sub2[] = {
  121219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 4, 3, 4, 3,
  121220. 4, 4, 5, 4, 5, 4, 6, 5, 6,
  121221. };
  121222. static static_codebook _huff_book_line_128x4_0sub2 = {
  121223. 1, 25,
  121224. _huff_lengthlist_line_128x4_0sub2,
  121225. 0, 0, 0, 0, 0,
  121226. NULL,
  121227. NULL,
  121228. NULL,
  121229. NULL,
  121230. 0
  121231. };
  121232. static long _huff_lengthlist_line_128x4_0sub3[] = {
  121233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  121235. 5, 4, 6, 5, 6, 5, 7, 6, 6, 7, 7, 9, 9,11,11,16,
  121236. 11,14,10,11,11,13,16,15,15,15,15,15,15,15,15,15,
  121237. };
  121238. static static_codebook _huff_book_line_128x4_0sub3 = {
  121239. 1, 64,
  121240. _huff_lengthlist_line_128x4_0sub3,
  121241. 0, 0, 0, 0, 0,
  121242. NULL,
  121243. NULL,
  121244. NULL,
  121245. NULL,
  121246. 0
  121247. };
  121248. static long _huff_lengthlist_line_256x4_class0[] = {
  121249. 6, 7, 7,12, 6, 6, 7,12, 7, 6, 6,10,15,12,11,13,
  121250. 7, 7, 8,13, 7, 7, 8,12, 7, 7, 7,11,12,12,11,13,
  121251. 10, 9, 9,11, 9, 9, 9,10,10, 8, 8,12,14,12,12,14,
  121252. 11,11,12,14,11,12,11,15,15,12,13,15,15,15,15,15,
  121253. 6, 6, 7,10, 6, 6, 6,11, 7, 6, 6, 9,14,12,11,13,
  121254. 7, 7, 7,10, 6, 6, 7, 9, 7, 7, 6,10,13,12,10,12,
  121255. 9, 9, 9,11, 9, 9, 8, 9, 9, 8, 8,10,13,12,10,12,
  121256. 12,12,11,13,12,12,11,12,15,13,12,15,15,15,14,14,
  121257. 6, 6, 6, 8, 6, 6, 5, 6, 7, 7, 6, 5,11,10, 9, 8,
  121258. 7, 6, 6, 7, 6, 6, 5, 6, 7, 7, 6, 6,11,10, 9, 8,
  121259. 8, 8, 8, 9, 8, 8, 7, 8, 8, 8, 6, 7,11,10, 9, 9,
  121260. 14,11,10,14,14,11,10,15,13,11, 9,11,15,12,12,11,
  121261. 11, 9, 8, 8,10, 9, 8, 9,11,10, 9, 8,12,11,12,11,
  121262. 13,10, 8, 9,11,10, 8, 9,10, 9, 8, 9,10, 8,12,12,
  121263. 15,11,10,10,13,11,10,10, 8, 8, 7,12,10, 9,11,12,
  121264. 15,12,11,15,13,11,11,15,12,14,11,13,15,15,13,13,
  121265. };
  121266. static static_codebook _huff_book_line_256x4_class0 = {
  121267. 1, 256,
  121268. _huff_lengthlist_line_256x4_class0,
  121269. 0, 0, 0, 0, 0,
  121270. NULL,
  121271. NULL,
  121272. NULL,
  121273. NULL,
  121274. 0
  121275. };
  121276. static long _huff_lengthlist_line_256x4_0sub0[] = {
  121277. 2, 2, 2, 2,
  121278. };
  121279. static static_codebook _huff_book_line_256x4_0sub0 = {
  121280. 1, 4,
  121281. _huff_lengthlist_line_256x4_0sub0,
  121282. 0, 0, 0, 0, 0,
  121283. NULL,
  121284. NULL,
  121285. NULL,
  121286. NULL,
  121287. 0
  121288. };
  121289. static long _huff_lengthlist_line_256x4_0sub1[] = {
  121290. 0, 0, 0, 0, 2, 2, 3, 3, 3, 3,
  121291. };
  121292. static static_codebook _huff_book_line_256x4_0sub1 = {
  121293. 1, 10,
  121294. _huff_lengthlist_line_256x4_0sub1,
  121295. 0, 0, 0, 0, 0,
  121296. NULL,
  121297. NULL,
  121298. NULL,
  121299. NULL,
  121300. 0
  121301. };
  121302. static long _huff_lengthlist_line_256x4_0sub2[] = {
  121303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 3, 4, 3, 4, 3,
  121304. 5, 3, 5, 4, 5, 4, 6, 4, 6,
  121305. };
  121306. static static_codebook _huff_book_line_256x4_0sub2 = {
  121307. 1, 25,
  121308. _huff_lengthlist_line_256x4_0sub2,
  121309. 0, 0, 0, 0, 0,
  121310. NULL,
  121311. NULL,
  121312. NULL,
  121313. NULL,
  121314. 0
  121315. };
  121316. static long _huff_lengthlist_line_256x4_0sub3[] = {
  121317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  121319. 6, 4, 7, 4, 7, 5, 7, 6, 7, 6, 7, 8,10,13,13,13,
  121320. 13,13,13,13,13,13,13,13,13,13,13,12,12,12,12,12,
  121321. };
  121322. static static_codebook _huff_book_line_256x4_0sub3 = {
  121323. 1, 64,
  121324. _huff_lengthlist_line_256x4_0sub3,
  121325. 0, 0, 0, 0, 0,
  121326. NULL,
  121327. NULL,
  121328. NULL,
  121329. NULL,
  121330. 0
  121331. };
  121332. static long _huff_lengthlist_line_128x7_class0[] = {
  121333. 10, 7, 8,13, 9, 6, 7,11,10, 8, 8,12,17,17,17,17,
  121334. 7, 5, 5, 9, 6, 4, 4, 8, 8, 5, 5, 8,16,14,13,16,
  121335. 7, 5, 5, 7, 6, 3, 3, 5, 8, 5, 4, 7,14,12,12,15,
  121336. 10, 7, 8, 9, 7, 5, 5, 6, 9, 6, 5, 5,15,12, 9,10,
  121337. };
  121338. static static_codebook _huff_book_line_128x7_class0 = {
  121339. 1, 64,
  121340. _huff_lengthlist_line_128x7_class0,
  121341. 0, 0, 0, 0, 0,
  121342. NULL,
  121343. NULL,
  121344. NULL,
  121345. NULL,
  121346. 0
  121347. };
  121348. static long _huff_lengthlist_line_128x7_class1[] = {
  121349. 8,13,17,17, 8,11,17,17,11,13,17,17,17,17,17,17,
  121350. 6,10,16,17, 6,10,15,17, 8,10,16,17,17,17,17,17,
  121351. 9,13,15,17, 8,11,17,17,10,12,17,17,17,17,17,17,
  121352. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  121353. 6,11,15,17, 7,10,15,17, 8,10,17,17,17,15,17,17,
  121354. 4, 8,13,17, 4, 7,13,17, 6, 8,15,17,16,15,17,17,
  121355. 6,11,15,17, 6, 9,13,17, 8,10,17,17,15,17,17,17,
  121356. 16,17,17,17,12,14,15,17,13,14,15,17,17,17,17,17,
  121357. 5,10,14,17, 5, 9,14,17, 7, 9,15,17,15,15,17,17,
  121358. 3, 7,12,17, 3, 6,11,17, 5, 7,13,17,12,12,17,17,
  121359. 5, 9,14,17, 3, 7,11,17, 5, 8,13,17,13,11,16,17,
  121360. 12,17,17,17, 9,14,15,17,10,11,14,17,16,14,17,17,
  121361. 8,12,17,17, 8,12,17,17,10,12,17,17,17,17,17,17,
  121362. 5,10,17,17, 5, 9,15,17, 7, 9,17,17,13,13,17,17,
  121363. 7,11,17,17, 6,10,15,17, 7, 9,15,17,12,11,17,17,
  121364. 12,15,17,17,11,14,17,17,11,10,15,17,17,16,17,17,
  121365. };
  121366. static static_codebook _huff_book_line_128x7_class1 = {
  121367. 1, 256,
  121368. _huff_lengthlist_line_128x7_class1,
  121369. 0, 0, 0, 0, 0,
  121370. NULL,
  121371. NULL,
  121372. NULL,
  121373. NULL,
  121374. 0
  121375. };
  121376. static long _huff_lengthlist_line_128x7_0sub1[] = {
  121377. 0, 3, 3, 3, 3, 3, 3, 3, 3,
  121378. };
  121379. static static_codebook _huff_book_line_128x7_0sub1 = {
  121380. 1, 9,
  121381. _huff_lengthlist_line_128x7_0sub1,
  121382. 0, 0, 0, 0, 0,
  121383. NULL,
  121384. NULL,
  121385. NULL,
  121386. NULL,
  121387. 0
  121388. };
  121389. static long _huff_lengthlist_line_128x7_0sub2[] = {
  121390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 4, 4, 4,
  121391. 5, 4, 5, 4, 5, 4, 6, 4, 6,
  121392. };
  121393. static static_codebook _huff_book_line_128x7_0sub2 = {
  121394. 1, 25,
  121395. _huff_lengthlist_line_128x7_0sub2,
  121396. 0, 0, 0, 0, 0,
  121397. NULL,
  121398. NULL,
  121399. NULL,
  121400. NULL,
  121401. 0
  121402. };
  121403. static long _huff_lengthlist_line_128x7_0sub3[] = {
  121404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 3, 5, 3, 5, 4,
  121406. 5, 4, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121407. 7, 8, 9,11,13,13,13,13,13,13,13,13,13,13,13,13,
  121408. };
  121409. static static_codebook _huff_book_line_128x7_0sub3 = {
  121410. 1, 64,
  121411. _huff_lengthlist_line_128x7_0sub3,
  121412. 0, 0, 0, 0, 0,
  121413. NULL,
  121414. NULL,
  121415. NULL,
  121416. NULL,
  121417. 0
  121418. };
  121419. static long _huff_lengthlist_line_128x7_1sub1[] = {
  121420. 0, 3, 3, 2, 3, 3, 4, 3, 4,
  121421. };
  121422. static static_codebook _huff_book_line_128x7_1sub1 = {
  121423. 1, 9,
  121424. _huff_lengthlist_line_128x7_1sub1,
  121425. 0, 0, 0, 0, 0,
  121426. NULL,
  121427. NULL,
  121428. NULL,
  121429. NULL,
  121430. 0
  121431. };
  121432. static long _huff_lengthlist_line_128x7_1sub2[] = {
  121433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 6, 3, 6, 3,
  121434. 6, 3, 7, 3, 8, 4, 9, 4, 9,
  121435. };
  121436. static static_codebook _huff_book_line_128x7_1sub2 = {
  121437. 1, 25,
  121438. _huff_lengthlist_line_128x7_1sub2,
  121439. 0, 0, 0, 0, 0,
  121440. NULL,
  121441. NULL,
  121442. NULL,
  121443. NULL,
  121444. 0
  121445. };
  121446. static long _huff_lengthlist_line_128x7_1sub3[] = {
  121447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 7, 2, 7, 3, 8, 4,
  121449. 9, 5, 9, 8,10,11,11,12,14,14,14,14,14,14,14,14,
  121450. 14,14,14,14,14,14,14,14,14,14,14,14,13,13,13,13,
  121451. };
  121452. static static_codebook _huff_book_line_128x7_1sub3 = {
  121453. 1, 64,
  121454. _huff_lengthlist_line_128x7_1sub3,
  121455. 0, 0, 0, 0, 0,
  121456. NULL,
  121457. NULL,
  121458. NULL,
  121459. NULL,
  121460. 0
  121461. };
  121462. static long _huff_lengthlist_line_128x11_class1[] = {
  121463. 1, 6, 3, 7, 2, 4, 5, 7,
  121464. };
  121465. static static_codebook _huff_book_line_128x11_class1 = {
  121466. 1, 8,
  121467. _huff_lengthlist_line_128x11_class1,
  121468. 0, 0, 0, 0, 0,
  121469. NULL,
  121470. NULL,
  121471. NULL,
  121472. NULL,
  121473. 0
  121474. };
  121475. static long _huff_lengthlist_line_128x11_class2[] = {
  121476. 1, 6,12,16, 4,12,15,16, 9,15,16,16,16,16,16,16,
  121477. 2, 5,11,16, 5,11,13,16, 9,13,16,16,16,16,16,16,
  121478. 4, 8,12,16, 5, 9,12,16, 9,13,15,16,16,16,16,16,
  121479. 15,16,16,16,11,14,13,16,12,15,16,16,16,16,16,15,
  121480. };
  121481. static static_codebook _huff_book_line_128x11_class2 = {
  121482. 1, 64,
  121483. _huff_lengthlist_line_128x11_class2,
  121484. 0, 0, 0, 0, 0,
  121485. NULL,
  121486. NULL,
  121487. NULL,
  121488. NULL,
  121489. 0
  121490. };
  121491. static long _huff_lengthlist_line_128x11_class3[] = {
  121492. 7, 6, 9,17, 7, 6, 8,17,12, 9,11,16,16,16,16,16,
  121493. 5, 4, 7,16, 5, 3, 6,14, 9, 6, 8,15,16,16,16,16,
  121494. 5, 4, 6,13, 3, 2, 4,11, 7, 4, 6,13,16,11,10,14,
  121495. 12,12,12,16, 9, 7,10,15,12, 9,11,16,16,15,15,16,
  121496. };
  121497. static static_codebook _huff_book_line_128x11_class3 = {
  121498. 1, 64,
  121499. _huff_lengthlist_line_128x11_class3,
  121500. 0, 0, 0, 0, 0,
  121501. NULL,
  121502. NULL,
  121503. NULL,
  121504. NULL,
  121505. 0
  121506. };
  121507. static long _huff_lengthlist_line_128x11_0sub0[] = {
  121508. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121509. 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 6, 6, 6, 7, 6,
  121510. 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6, 8, 7,
  121511. 8, 7, 8, 7, 8, 7, 9, 7, 9, 8, 9, 8, 9, 8,10, 8,
  121512. 10, 9,10, 9,10, 9,11, 9,11, 9,10,10,11,10,11,10,
  121513. 11,11,11,11,11,11,12,13,14,14,14,15,15,16,16,16,
  121514. 17,15,16,15,16,16,17,17,16,17,17,17,17,17,17,17,
  121515. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  121516. };
  121517. static static_codebook _huff_book_line_128x11_0sub0 = {
  121518. 1, 128,
  121519. _huff_lengthlist_line_128x11_0sub0,
  121520. 0, 0, 0, 0, 0,
  121521. NULL,
  121522. NULL,
  121523. NULL,
  121524. NULL,
  121525. 0
  121526. };
  121527. static long _huff_lengthlist_line_128x11_1sub0[] = {
  121528. 2, 5, 5, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  121529. 6, 5, 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6,
  121530. };
  121531. static static_codebook _huff_book_line_128x11_1sub0 = {
  121532. 1, 32,
  121533. _huff_lengthlist_line_128x11_1sub0,
  121534. 0, 0, 0, 0, 0,
  121535. NULL,
  121536. NULL,
  121537. NULL,
  121538. NULL,
  121539. 0
  121540. };
  121541. static long _huff_lengthlist_line_128x11_1sub1[] = {
  121542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121544. 5, 3, 5, 3, 6, 4, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  121545. 8, 4, 9, 5, 9, 5, 9, 5, 9, 6,10, 6,10, 6,11, 7,
  121546. 10, 7,10, 8,11, 9,11, 9,11,10,11,11,12,11,11,12,
  121547. 15,15,12,14,11,14,12,14,11,14,13,14,12,14,11,14,
  121548. 11,14,12,14,11,14,11,14,13,13,14,14,14,14,14,14,
  121549. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  121550. };
  121551. static static_codebook _huff_book_line_128x11_1sub1 = {
  121552. 1, 128,
  121553. _huff_lengthlist_line_128x11_1sub1,
  121554. 0, 0, 0, 0, 0,
  121555. NULL,
  121556. NULL,
  121557. NULL,
  121558. NULL,
  121559. 0
  121560. };
  121561. static long _huff_lengthlist_line_128x11_2sub1[] = {
  121562. 0, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4,
  121563. 5, 5,
  121564. };
  121565. static static_codebook _huff_book_line_128x11_2sub1 = {
  121566. 1, 18,
  121567. _huff_lengthlist_line_128x11_2sub1,
  121568. 0, 0, 0, 0, 0,
  121569. NULL,
  121570. NULL,
  121571. NULL,
  121572. NULL,
  121573. 0
  121574. };
  121575. static long _huff_lengthlist_line_128x11_2sub2[] = {
  121576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121577. 0, 0, 3, 3, 3, 4, 4, 4, 4, 5, 4, 5, 4, 6, 5, 7,
  121578. 5, 7, 6, 8, 6, 8, 6, 9, 7, 9, 7,10, 7, 9, 8,11,
  121579. 8,11,
  121580. };
  121581. static static_codebook _huff_book_line_128x11_2sub2 = {
  121582. 1, 50,
  121583. _huff_lengthlist_line_128x11_2sub2,
  121584. 0, 0, 0, 0, 0,
  121585. NULL,
  121586. NULL,
  121587. NULL,
  121588. NULL,
  121589. 0
  121590. };
  121591. static long _huff_lengthlist_line_128x11_2sub3[] = {
  121592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121595. 0, 0, 4, 8, 3, 8, 4, 8, 4, 8, 6, 8, 5, 8, 4, 8,
  121596. 4, 8, 6, 8, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121597. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121598. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121599. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121600. };
  121601. static static_codebook _huff_book_line_128x11_2sub3 = {
  121602. 1, 128,
  121603. _huff_lengthlist_line_128x11_2sub3,
  121604. 0, 0, 0, 0, 0,
  121605. NULL,
  121606. NULL,
  121607. NULL,
  121608. NULL,
  121609. 0
  121610. };
  121611. static long _huff_lengthlist_line_128x11_3sub1[] = {
  121612. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4,
  121613. 5, 4,
  121614. };
  121615. static static_codebook _huff_book_line_128x11_3sub1 = {
  121616. 1, 18,
  121617. _huff_lengthlist_line_128x11_3sub1,
  121618. 0, 0, 0, 0, 0,
  121619. NULL,
  121620. NULL,
  121621. NULL,
  121622. NULL,
  121623. 0
  121624. };
  121625. static long _huff_lengthlist_line_128x11_3sub2[] = {
  121626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121627. 0, 0, 5, 3, 5, 4, 6, 4, 6, 4, 7, 4, 7, 4, 8, 4,
  121628. 8, 4, 9, 4, 9, 4,10, 4,10, 5,10, 5,11, 5,12, 6,
  121629. 12, 6,
  121630. };
  121631. static static_codebook _huff_book_line_128x11_3sub2 = {
  121632. 1, 50,
  121633. _huff_lengthlist_line_128x11_3sub2,
  121634. 0, 0, 0, 0, 0,
  121635. NULL,
  121636. NULL,
  121637. NULL,
  121638. NULL,
  121639. 0
  121640. };
  121641. static long _huff_lengthlist_line_128x11_3sub3[] = {
  121642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121645. 0, 0, 7, 1, 6, 3, 7, 3, 8, 4, 8, 5, 8, 8, 8, 9,
  121646. 7, 8, 8, 7, 7, 7, 8, 9,10, 9, 9,10,10,10,10,10,
  121647. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121648. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121649. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  121650. };
  121651. static static_codebook _huff_book_line_128x11_3sub3 = {
  121652. 1, 128,
  121653. _huff_lengthlist_line_128x11_3sub3,
  121654. 0, 0, 0, 0, 0,
  121655. NULL,
  121656. NULL,
  121657. NULL,
  121658. NULL,
  121659. 0
  121660. };
  121661. static long _huff_lengthlist_line_128x17_class1[] = {
  121662. 1, 3, 4, 7, 2, 5, 6, 7,
  121663. };
  121664. static static_codebook _huff_book_line_128x17_class1 = {
  121665. 1, 8,
  121666. _huff_lengthlist_line_128x17_class1,
  121667. 0, 0, 0, 0, 0,
  121668. NULL,
  121669. NULL,
  121670. NULL,
  121671. NULL,
  121672. 0
  121673. };
  121674. static long _huff_lengthlist_line_128x17_class2[] = {
  121675. 1, 4,10,19, 3, 8,13,19, 7,12,19,19,19,19,19,19,
  121676. 2, 6,11,19, 8,13,19,19, 9,11,19,19,19,19,19,19,
  121677. 6, 7,13,19, 9,13,19,19,10,13,18,18,18,18,18,18,
  121678. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  121679. };
  121680. static static_codebook _huff_book_line_128x17_class2 = {
  121681. 1, 64,
  121682. _huff_lengthlist_line_128x17_class2,
  121683. 0, 0, 0, 0, 0,
  121684. NULL,
  121685. NULL,
  121686. NULL,
  121687. NULL,
  121688. 0
  121689. };
  121690. static long _huff_lengthlist_line_128x17_class3[] = {
  121691. 3, 6,10,17, 4, 8,11,20, 8,10,11,20,20,20,20,20,
  121692. 2, 4, 8,18, 4, 6, 8,17, 7, 8,10,20,20,17,20,20,
  121693. 3, 5, 8,17, 3, 4, 6,17, 8, 8,10,17,17,12,16,20,
  121694. 13,13,15,20,10,10,12,20,15,14,15,20,20,20,19,19,
  121695. };
  121696. static static_codebook _huff_book_line_128x17_class3 = {
  121697. 1, 64,
  121698. _huff_lengthlist_line_128x17_class3,
  121699. 0, 0, 0, 0, 0,
  121700. NULL,
  121701. NULL,
  121702. NULL,
  121703. NULL,
  121704. 0
  121705. };
  121706. static long _huff_lengthlist_line_128x17_0sub0[] = {
  121707. 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121708. 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5,
  121709. 8, 5, 8, 5, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6, 9, 6,
  121710. 9, 6, 9, 7, 9, 7, 9, 7, 9, 7,10, 7,10, 8,10, 8,
  121711. 10, 8,10, 8,10, 8,11, 8,11, 8,11, 8,11, 8,11, 9,
  121712. 12, 9,12, 9,12, 9,12, 9,12,10,12,10,13,11,13,11,
  121713. 14,12,14,13,15,14,16,14,17,15,18,16,20,20,20,20,
  121714. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121715. };
  121716. static static_codebook _huff_book_line_128x17_0sub0 = {
  121717. 1, 128,
  121718. _huff_lengthlist_line_128x17_0sub0,
  121719. 0, 0, 0, 0, 0,
  121720. NULL,
  121721. NULL,
  121722. NULL,
  121723. NULL,
  121724. 0
  121725. };
  121726. static long _huff_lengthlist_line_128x17_1sub0[] = {
  121727. 2, 5, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  121728. 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7,
  121729. };
  121730. static static_codebook _huff_book_line_128x17_1sub0 = {
  121731. 1, 32,
  121732. _huff_lengthlist_line_128x17_1sub0,
  121733. 0, 0, 0, 0, 0,
  121734. NULL,
  121735. NULL,
  121736. NULL,
  121737. NULL,
  121738. 0
  121739. };
  121740. static long _huff_lengthlist_line_128x17_1sub1[] = {
  121741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121743. 4, 3, 5, 3, 5, 3, 6, 3, 6, 4, 6, 4, 7, 4, 7, 5,
  121744. 8, 5, 8, 6, 9, 7, 9, 7, 9, 8,10, 9,10, 9,11,10,
  121745. 11,11,11,11,11,11,12,12,12,13,12,13,12,14,12,15,
  121746. 12,14,12,16,13,17,13,17,14,17,14,16,13,17,14,17,
  121747. 14,17,15,17,15,15,16,17,17,17,17,17,17,17,17,17,
  121748. 17,17,17,17,17,17,16,16,16,16,16,16,16,16,16,16,
  121749. };
  121750. static static_codebook _huff_book_line_128x17_1sub1 = {
  121751. 1, 128,
  121752. _huff_lengthlist_line_128x17_1sub1,
  121753. 0, 0, 0, 0, 0,
  121754. NULL,
  121755. NULL,
  121756. NULL,
  121757. NULL,
  121758. 0
  121759. };
  121760. static long _huff_lengthlist_line_128x17_2sub1[] = {
  121761. 0, 4, 5, 4, 6, 4, 8, 3, 9, 3, 9, 2, 9, 3, 8, 4,
  121762. 9, 4,
  121763. };
  121764. static static_codebook _huff_book_line_128x17_2sub1 = {
  121765. 1, 18,
  121766. _huff_lengthlist_line_128x17_2sub1,
  121767. 0, 0, 0, 0, 0,
  121768. NULL,
  121769. NULL,
  121770. NULL,
  121771. NULL,
  121772. 0
  121773. };
  121774. static long _huff_lengthlist_line_128x17_2sub2[] = {
  121775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121776. 0, 0, 5, 1, 5, 3, 5, 3, 5, 4, 7, 5,10, 7,10, 7,
  121777. 12,10,14,10,14, 9,14,11,14,14,14,13,13,13,13,13,
  121778. 13,13,
  121779. };
  121780. static static_codebook _huff_book_line_128x17_2sub2 = {
  121781. 1, 50,
  121782. _huff_lengthlist_line_128x17_2sub2,
  121783. 0, 0, 0, 0, 0,
  121784. NULL,
  121785. NULL,
  121786. NULL,
  121787. NULL,
  121788. 0
  121789. };
  121790. static long _huff_lengthlist_line_128x17_2sub3[] = {
  121791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121794. 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121795. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6,
  121796. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121797. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121798. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121799. };
  121800. static static_codebook _huff_book_line_128x17_2sub3 = {
  121801. 1, 128,
  121802. _huff_lengthlist_line_128x17_2sub3,
  121803. 0, 0, 0, 0, 0,
  121804. NULL,
  121805. NULL,
  121806. NULL,
  121807. NULL,
  121808. 0
  121809. };
  121810. static long _huff_lengthlist_line_128x17_3sub1[] = {
  121811. 0, 4, 4, 4, 4, 4, 4, 4, 5, 3, 5, 3, 5, 4, 6, 4,
  121812. 6, 4,
  121813. };
  121814. static static_codebook _huff_book_line_128x17_3sub1 = {
  121815. 1, 18,
  121816. _huff_lengthlist_line_128x17_3sub1,
  121817. 0, 0, 0, 0, 0,
  121818. NULL,
  121819. NULL,
  121820. NULL,
  121821. NULL,
  121822. 0
  121823. };
  121824. static long _huff_lengthlist_line_128x17_3sub2[] = {
  121825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121826. 0, 0, 5, 3, 6, 3, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  121827. 8, 4, 8, 4, 8, 4, 9, 4, 9, 5,10, 5,10, 7,10, 8,
  121828. 10, 8,
  121829. };
  121830. static static_codebook _huff_book_line_128x17_3sub2 = {
  121831. 1, 50,
  121832. _huff_lengthlist_line_128x17_3sub2,
  121833. 0, 0, 0, 0, 0,
  121834. NULL,
  121835. NULL,
  121836. NULL,
  121837. NULL,
  121838. 0
  121839. };
  121840. static long _huff_lengthlist_line_128x17_3sub3[] = {
  121841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121844. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 4, 7, 5, 8, 5,11,
  121845. 6,10, 6,12, 7,12, 7,12, 8,12, 8,12,10,12,12,12,
  121846. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121847. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121848. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121849. };
  121850. static static_codebook _huff_book_line_128x17_3sub3 = {
  121851. 1, 128,
  121852. _huff_lengthlist_line_128x17_3sub3,
  121853. 0, 0, 0, 0, 0,
  121854. NULL,
  121855. NULL,
  121856. NULL,
  121857. NULL,
  121858. 0
  121859. };
  121860. static long _huff_lengthlist_line_1024x27_class1[] = {
  121861. 2,10, 8,14, 7,12,11,14, 1, 5, 3, 7, 4, 9, 7,13,
  121862. };
  121863. static static_codebook _huff_book_line_1024x27_class1 = {
  121864. 1, 16,
  121865. _huff_lengthlist_line_1024x27_class1,
  121866. 0, 0, 0, 0, 0,
  121867. NULL,
  121868. NULL,
  121869. NULL,
  121870. NULL,
  121871. 0
  121872. };
  121873. static long _huff_lengthlist_line_1024x27_class2[] = {
  121874. 1, 4, 2, 6, 3, 7, 5, 7,
  121875. };
  121876. static static_codebook _huff_book_line_1024x27_class2 = {
  121877. 1, 8,
  121878. _huff_lengthlist_line_1024x27_class2,
  121879. 0, 0, 0, 0, 0,
  121880. NULL,
  121881. NULL,
  121882. NULL,
  121883. NULL,
  121884. 0
  121885. };
  121886. static long _huff_lengthlist_line_1024x27_class3[] = {
  121887. 1, 5, 7,21, 5, 8, 9,21,10, 9,12,20,20,16,20,20,
  121888. 4, 8, 9,20, 6, 8, 9,20,11,11,13,20,20,15,17,20,
  121889. 9,11,14,20, 8,10,15,20,11,13,15,20,20,20,20,20,
  121890. 20,20,20,20,13,20,20,20,18,18,20,20,20,20,20,20,
  121891. 3, 6, 8,20, 6, 7, 9,20,10, 9,12,20,20,20,20,20,
  121892. 5, 7, 9,20, 6, 6, 9,20,10, 9,12,20,20,20,20,20,
  121893. 8,10,13,20, 8, 9,12,20,11,10,12,20,20,20,20,20,
  121894. 18,20,20,20,15,17,18,20,18,17,18,20,20,20,20,20,
  121895. 7,10,12,20, 8, 9,11,20,14,13,14,20,20,20,20,20,
  121896. 6, 9,12,20, 7, 8,11,20,12,11,13,20,20,20,20,20,
  121897. 9,11,15,20, 8,10,14,20,12,11,14,20,20,20,20,20,
  121898. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121899. 11,16,18,20,15,15,17,20,20,17,20,20,20,20,20,20,
  121900. 9,14,16,20,12,12,15,20,17,15,18,20,20,20,20,20,
  121901. 16,19,18,20,15,16,20,20,17,17,20,20,20,20,20,20,
  121902. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121903. };
  121904. static static_codebook _huff_book_line_1024x27_class3 = {
  121905. 1, 256,
  121906. _huff_lengthlist_line_1024x27_class3,
  121907. 0, 0, 0, 0, 0,
  121908. NULL,
  121909. NULL,
  121910. NULL,
  121911. NULL,
  121912. 0
  121913. };
  121914. static long _huff_lengthlist_line_1024x27_class4[] = {
  121915. 2, 3, 7,13, 4, 4, 7,15, 8, 6, 9,17,21,16,15,21,
  121916. 2, 5, 7,11, 5, 5, 7,14, 9, 7,10,16,17,15,16,21,
  121917. 4, 7,10,17, 7, 7, 9,15,11, 9,11,16,21,18,15,21,
  121918. 18,21,21,21,15,17,17,19,21,19,18,20,21,21,21,20,
  121919. };
  121920. static static_codebook _huff_book_line_1024x27_class4 = {
  121921. 1, 64,
  121922. _huff_lengthlist_line_1024x27_class4,
  121923. 0, 0, 0, 0, 0,
  121924. NULL,
  121925. NULL,
  121926. NULL,
  121927. NULL,
  121928. 0
  121929. };
  121930. static long _huff_lengthlist_line_1024x27_0sub0[] = {
  121931. 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121932. 6, 5, 6, 5, 6, 5, 6, 5, 7, 5, 7, 5, 7, 5, 7, 5,
  121933. 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,10, 6,10, 6,11, 6,
  121934. 11, 7,11, 7,12, 7,12, 7,12, 7,12, 7,12, 7,12, 7,
  121935. 12, 7,12, 8,13, 8,12, 8,12, 8,13, 8,13, 9,13, 9,
  121936. 13, 9,13, 9,12,10,12,10,13,10,14,11,14,12,14,13,
  121937. 14,13,14,14,15,16,15,15,15,14,15,17,21,22,22,21,
  121938. 22,22,22,22,22,22,21,21,21,21,21,21,21,21,21,21,
  121939. };
  121940. static static_codebook _huff_book_line_1024x27_0sub0 = {
  121941. 1, 128,
  121942. _huff_lengthlist_line_1024x27_0sub0,
  121943. 0, 0, 0, 0, 0,
  121944. NULL,
  121945. NULL,
  121946. NULL,
  121947. NULL,
  121948. 0
  121949. };
  121950. static long _huff_lengthlist_line_1024x27_1sub0[] = {
  121951. 2, 5, 5, 4, 5, 4, 5, 4, 5, 4, 6, 5, 6, 5, 6, 5,
  121952. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,
  121953. };
  121954. static static_codebook _huff_book_line_1024x27_1sub0 = {
  121955. 1, 32,
  121956. _huff_lengthlist_line_1024x27_1sub0,
  121957. 0, 0, 0, 0, 0,
  121958. NULL,
  121959. NULL,
  121960. NULL,
  121961. NULL,
  121962. 0
  121963. };
  121964. static long _huff_lengthlist_line_1024x27_1sub1[] = {
  121965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121967. 8, 5, 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4,
  121968. 9, 4, 9, 4, 9, 4, 8, 4, 8, 4, 9, 5, 9, 5, 9, 5,
  121969. 9, 5, 9, 6,10, 6,10, 7,10, 8,11, 9,11,11,12,13,
  121970. 12,14,13,15,13,15,14,16,14,17,15,17,15,15,16,16,
  121971. 15,16,16,16,15,18,16,15,17,17,19,19,19,19,19,19,
  121972. 19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,
  121973. };
  121974. static static_codebook _huff_book_line_1024x27_1sub1 = {
  121975. 1, 128,
  121976. _huff_lengthlist_line_1024x27_1sub1,
  121977. 0, 0, 0, 0, 0,
  121978. NULL,
  121979. NULL,
  121980. NULL,
  121981. NULL,
  121982. 0
  121983. };
  121984. static long _huff_lengthlist_line_1024x27_2sub0[] = {
  121985. 1, 5, 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121986. 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 9, 8,10, 9,10, 9,
  121987. };
  121988. static static_codebook _huff_book_line_1024x27_2sub0 = {
  121989. 1, 32,
  121990. _huff_lengthlist_line_1024x27_2sub0,
  121991. 0, 0, 0, 0, 0,
  121992. NULL,
  121993. NULL,
  121994. NULL,
  121995. NULL,
  121996. 0
  121997. };
  121998. static long _huff_lengthlist_line_1024x27_2sub1[] = {
  121999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122001. 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 5, 5, 6, 5, 6, 5,
  122002. 7, 5, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 9, 8, 9, 9,
  122003. 9, 9,10,10,10,11, 9,12, 9,12, 9,15,10,14, 9,13,
  122004. 10,13,10,12,10,12,10,13,10,12,11,13,11,14,12,13,
  122005. 13,14,14,13,14,15,14,16,13,13,14,16,16,16,16,16,
  122006. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,15,15,
  122007. };
  122008. static static_codebook _huff_book_line_1024x27_2sub1 = {
  122009. 1, 128,
  122010. _huff_lengthlist_line_1024x27_2sub1,
  122011. 0, 0, 0, 0, 0,
  122012. NULL,
  122013. NULL,
  122014. NULL,
  122015. NULL,
  122016. 0
  122017. };
  122018. static long _huff_lengthlist_line_1024x27_3sub1[] = {
  122019. 0, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4, 4, 5,
  122020. 5, 5,
  122021. };
  122022. static static_codebook _huff_book_line_1024x27_3sub1 = {
  122023. 1, 18,
  122024. _huff_lengthlist_line_1024x27_3sub1,
  122025. 0, 0, 0, 0, 0,
  122026. NULL,
  122027. NULL,
  122028. NULL,
  122029. NULL,
  122030. 0
  122031. };
  122032. static long _huff_lengthlist_line_1024x27_3sub2[] = {
  122033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122034. 0, 0, 3, 3, 4, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6,
  122035. 5, 7, 5, 8, 6, 8, 6, 9, 7,10, 7,10, 8,10, 8,11,
  122036. 9,11,
  122037. };
  122038. static static_codebook _huff_book_line_1024x27_3sub2 = {
  122039. 1, 50,
  122040. _huff_lengthlist_line_1024x27_3sub2,
  122041. 0, 0, 0, 0, 0,
  122042. NULL,
  122043. NULL,
  122044. NULL,
  122045. NULL,
  122046. 0
  122047. };
  122048. static long _huff_lengthlist_line_1024x27_3sub3[] = {
  122049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122052. 0, 0, 3, 7, 3, 8, 3,10, 3, 8, 3, 9, 3, 8, 4, 9,
  122053. 4, 9, 5, 9, 6,10, 6, 9, 7,11, 7,12, 9,13,10,13,
  122054. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  122055. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  122056. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  122057. };
  122058. static static_codebook _huff_book_line_1024x27_3sub3 = {
  122059. 1, 128,
  122060. _huff_lengthlist_line_1024x27_3sub3,
  122061. 0, 0, 0, 0, 0,
  122062. NULL,
  122063. NULL,
  122064. NULL,
  122065. NULL,
  122066. 0
  122067. };
  122068. static long _huff_lengthlist_line_1024x27_4sub1[] = {
  122069. 0, 4, 5, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4,
  122070. 5, 4,
  122071. };
  122072. static static_codebook _huff_book_line_1024x27_4sub1 = {
  122073. 1, 18,
  122074. _huff_lengthlist_line_1024x27_4sub1,
  122075. 0, 0, 0, 0, 0,
  122076. NULL,
  122077. NULL,
  122078. NULL,
  122079. NULL,
  122080. 0
  122081. };
  122082. static long _huff_lengthlist_line_1024x27_4sub2[] = {
  122083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122084. 0, 0, 4, 2, 4, 2, 5, 3, 5, 4, 6, 6, 6, 7, 7, 8,
  122085. 7, 8, 7, 8, 7, 9, 8, 9, 8, 9, 8,10, 8,11, 9,12,
  122086. 9,12,
  122087. };
  122088. static static_codebook _huff_book_line_1024x27_4sub2 = {
  122089. 1, 50,
  122090. _huff_lengthlist_line_1024x27_4sub2,
  122091. 0, 0, 0, 0, 0,
  122092. NULL,
  122093. NULL,
  122094. NULL,
  122095. NULL,
  122096. 0
  122097. };
  122098. static long _huff_lengthlist_line_1024x27_4sub3[] = {
  122099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122102. 0, 0, 2, 5, 2, 6, 3, 6, 4, 7, 4, 7, 5, 9, 5,11,
  122103. 6,11, 6,11, 7,11, 6,11, 6,11, 9,11, 8,11,11,11,
  122104. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122105. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122106. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  122107. };
  122108. static static_codebook _huff_book_line_1024x27_4sub3 = {
  122109. 1, 128,
  122110. _huff_lengthlist_line_1024x27_4sub3,
  122111. 0, 0, 0, 0, 0,
  122112. NULL,
  122113. NULL,
  122114. NULL,
  122115. NULL,
  122116. 0
  122117. };
  122118. static long _huff_lengthlist_line_2048x27_class1[] = {
  122119. 2, 6, 8, 9, 7,11,13,13, 1, 3, 5, 5, 6, 6,12,10,
  122120. };
  122121. static static_codebook _huff_book_line_2048x27_class1 = {
  122122. 1, 16,
  122123. _huff_lengthlist_line_2048x27_class1,
  122124. 0, 0, 0, 0, 0,
  122125. NULL,
  122126. NULL,
  122127. NULL,
  122128. NULL,
  122129. 0
  122130. };
  122131. static long _huff_lengthlist_line_2048x27_class2[] = {
  122132. 1, 2, 3, 6, 4, 7, 5, 7,
  122133. };
  122134. static static_codebook _huff_book_line_2048x27_class2 = {
  122135. 1, 8,
  122136. _huff_lengthlist_line_2048x27_class2,
  122137. 0, 0, 0, 0, 0,
  122138. NULL,
  122139. NULL,
  122140. NULL,
  122141. NULL,
  122142. 0
  122143. };
  122144. static long _huff_lengthlist_line_2048x27_class3[] = {
  122145. 3, 3, 6,16, 5, 5, 7,16, 9, 8,11,16,16,16,16,16,
  122146. 5, 5, 8,16, 5, 5, 7,16, 8, 7, 9,16,16,16,16,16,
  122147. 9, 9,12,16, 6, 8,11,16, 9,10,11,16,16,16,16,16,
  122148. 16,16,16,16,13,16,16,16,15,16,16,16,16,16,16,16,
  122149. 5, 4, 7,16, 6, 5, 8,16, 9, 8,10,16,16,16,16,16,
  122150. 5, 5, 7,15, 5, 4, 6,15, 7, 6, 8,16,16,16,16,16,
  122151. 9, 9,11,15, 7, 7, 9,16, 8, 8, 9,16,16,16,16,16,
  122152. 16,16,16,16,15,15,15,16,15,15,14,16,16,16,16,16,
  122153. 8, 8,11,16, 8, 9,10,16,11,10,14,16,16,16,16,16,
  122154. 6, 8,10,16, 6, 7,10,16, 8, 8,11,16,14,16,16,16,
  122155. 10,11,14,16, 9, 9,11,16,10,10,11,16,16,16,16,16,
  122156. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  122157. 16,16,16,16,15,16,16,16,16,16,16,16,16,16,16,16,
  122158. 12,16,15,16,12,14,16,16,16,16,16,16,16,16,16,16,
  122159. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  122160. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  122161. };
  122162. static static_codebook _huff_book_line_2048x27_class3 = {
  122163. 1, 256,
  122164. _huff_lengthlist_line_2048x27_class3,
  122165. 0, 0, 0, 0, 0,
  122166. NULL,
  122167. NULL,
  122168. NULL,
  122169. NULL,
  122170. 0
  122171. };
  122172. static long _huff_lengthlist_line_2048x27_class4[] = {
  122173. 2, 4, 7,13, 4, 5, 7,15, 8, 7,10,16,16,14,16,16,
  122174. 2, 4, 7,16, 3, 4, 7,14, 8, 8,10,16,16,16,15,16,
  122175. 6, 8,11,16, 7, 7, 9,16,11, 9,13,16,16,16,15,16,
  122176. 16,16,16,16,14,16,16,16,16,16,16,16,16,16,16,16,
  122177. };
  122178. static static_codebook _huff_book_line_2048x27_class4 = {
  122179. 1, 64,
  122180. _huff_lengthlist_line_2048x27_class4,
  122181. 0, 0, 0, 0, 0,
  122182. NULL,
  122183. NULL,
  122184. NULL,
  122185. NULL,
  122186. 0
  122187. };
  122188. static long _huff_lengthlist_line_2048x27_0sub0[] = {
  122189. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  122190. 6, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5, 8, 5, 9, 5,
  122191. 9, 6,10, 6,10, 6,11, 6,11, 6,11, 6,11, 6,11, 6,
  122192. 11, 6,11, 6,12, 7,11, 7,11, 7,11, 7,11, 7,10, 7,
  122193. 11, 7,11, 7,12, 7,11, 8,11, 8,11, 8,11, 8,13, 8,
  122194. 12, 9,11, 9,11, 9,11,10,12,10,12, 9,12,10,12,11,
  122195. 14,12,16,12,12,11,14,16,17,17,17,17,17,17,17,17,
  122196. 17,17,17,17,17,17,17,17,17,17,17,17,16,16,16,16,
  122197. };
  122198. static static_codebook _huff_book_line_2048x27_0sub0 = {
  122199. 1, 128,
  122200. _huff_lengthlist_line_2048x27_0sub0,
  122201. 0, 0, 0, 0, 0,
  122202. NULL,
  122203. NULL,
  122204. NULL,
  122205. NULL,
  122206. 0
  122207. };
  122208. static long _huff_lengthlist_line_2048x27_1sub0[] = {
  122209. 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  122210. 5, 5, 6, 6, 6, 6, 6, 6, 7, 6, 7, 6, 7, 6, 7, 6,
  122211. };
  122212. static static_codebook _huff_book_line_2048x27_1sub0 = {
  122213. 1, 32,
  122214. _huff_lengthlist_line_2048x27_1sub0,
  122215. 0, 0, 0, 0, 0,
  122216. NULL,
  122217. NULL,
  122218. NULL,
  122219. NULL,
  122220. 0
  122221. };
  122222. static long _huff_lengthlist_line_2048x27_1sub1[] = {
  122223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122225. 6, 5, 7, 5, 7, 4, 7, 4, 8, 4, 8, 4, 8, 4, 8, 3,
  122226. 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 5, 9, 5, 9, 6,
  122227. 9, 7, 9, 8, 9, 9, 9,10, 9,11, 9,14, 9,15,10,15,
  122228. 10,15,10,15,10,15,11,15,10,14,12,14,11,14,13,14,
  122229. 13,15,15,15,12,15,15,15,13,15,13,15,13,15,15,15,
  122230. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,14,
  122231. };
  122232. static static_codebook _huff_book_line_2048x27_1sub1 = {
  122233. 1, 128,
  122234. _huff_lengthlist_line_2048x27_1sub1,
  122235. 0, 0, 0, 0, 0,
  122236. NULL,
  122237. NULL,
  122238. NULL,
  122239. NULL,
  122240. 0
  122241. };
  122242. static long _huff_lengthlist_line_2048x27_2sub0[] = {
  122243. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  122244. 6, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  122245. };
  122246. static static_codebook _huff_book_line_2048x27_2sub0 = {
  122247. 1, 32,
  122248. _huff_lengthlist_line_2048x27_2sub0,
  122249. 0, 0, 0, 0, 0,
  122250. NULL,
  122251. NULL,
  122252. NULL,
  122253. NULL,
  122254. 0
  122255. };
  122256. static long _huff_lengthlist_line_2048x27_2sub1[] = {
  122257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122259. 3, 4, 3, 4, 3, 4, 4, 5, 4, 5, 5, 5, 6, 6, 6, 7,
  122260. 6, 8, 6, 8, 6, 9, 7,10, 7,10, 7,10, 7,12, 7,12,
  122261. 7,12, 9,12,11,12,10,12,10,12,11,12,12,12,10,12,
  122262. 10,12,10,12, 9,12,11,12,12,12,12,12,11,12,11,12,
  122263. 12,12,12,12,12,12,12,12,10,10,12,12,12,12,12,10,
  122264. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  122265. };
  122266. static static_codebook _huff_book_line_2048x27_2sub1 = {
  122267. 1, 128,
  122268. _huff_lengthlist_line_2048x27_2sub1,
  122269. 0, 0, 0, 0, 0,
  122270. NULL,
  122271. NULL,
  122272. NULL,
  122273. NULL,
  122274. 0
  122275. };
  122276. static long _huff_lengthlist_line_2048x27_3sub1[] = {
  122277. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  122278. 5, 5,
  122279. };
  122280. static static_codebook _huff_book_line_2048x27_3sub1 = {
  122281. 1, 18,
  122282. _huff_lengthlist_line_2048x27_3sub1,
  122283. 0, 0, 0, 0, 0,
  122284. NULL,
  122285. NULL,
  122286. NULL,
  122287. NULL,
  122288. 0
  122289. };
  122290. static long _huff_lengthlist_line_2048x27_3sub2[] = {
  122291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122292. 0, 0, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6,
  122293. 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7, 9, 9,11, 9,12,
  122294. 10,12,
  122295. };
  122296. static static_codebook _huff_book_line_2048x27_3sub2 = {
  122297. 1, 50,
  122298. _huff_lengthlist_line_2048x27_3sub2,
  122299. 0, 0, 0, 0, 0,
  122300. NULL,
  122301. NULL,
  122302. NULL,
  122303. NULL,
  122304. 0
  122305. };
  122306. static long _huff_lengthlist_line_2048x27_3sub3[] = {
  122307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122310. 0, 0, 3, 6, 3, 7, 3, 7, 5, 7, 7, 7, 7, 7, 6, 7,
  122311. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122312. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122313. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122314. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122315. };
  122316. static static_codebook _huff_book_line_2048x27_3sub3 = {
  122317. 1, 128,
  122318. _huff_lengthlist_line_2048x27_3sub3,
  122319. 0, 0, 0, 0, 0,
  122320. NULL,
  122321. NULL,
  122322. NULL,
  122323. NULL,
  122324. 0
  122325. };
  122326. static long _huff_lengthlist_line_2048x27_4sub1[] = {
  122327. 0, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4, 5, 4, 5, 4,
  122328. 4, 5,
  122329. };
  122330. static static_codebook _huff_book_line_2048x27_4sub1 = {
  122331. 1, 18,
  122332. _huff_lengthlist_line_2048x27_4sub1,
  122333. 0, 0, 0, 0, 0,
  122334. NULL,
  122335. NULL,
  122336. NULL,
  122337. NULL,
  122338. 0
  122339. };
  122340. static long _huff_lengthlist_line_2048x27_4sub2[] = {
  122341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122342. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 5, 6, 5, 6, 5, 7,
  122343. 6, 6, 6, 7, 7, 7, 8, 9, 9, 9,12,10,11,10,10,12,
  122344. 10,10,
  122345. };
  122346. static static_codebook _huff_book_line_2048x27_4sub2 = {
  122347. 1, 50,
  122348. _huff_lengthlist_line_2048x27_4sub2,
  122349. 0, 0, 0, 0, 0,
  122350. NULL,
  122351. NULL,
  122352. NULL,
  122353. NULL,
  122354. 0
  122355. };
  122356. static long _huff_lengthlist_line_2048x27_4sub3[] = {
  122357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122360. 0, 0, 3, 6, 5, 7, 5, 7, 7, 7, 7, 7, 5, 7, 5, 7,
  122361. 5, 7, 5, 7, 7, 7, 7, 7, 4, 7, 7, 7, 7, 7, 7, 7,
  122362. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122363. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122364. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  122365. };
  122366. static static_codebook _huff_book_line_2048x27_4sub3 = {
  122367. 1, 128,
  122368. _huff_lengthlist_line_2048x27_4sub3,
  122369. 0, 0, 0, 0, 0,
  122370. NULL,
  122371. NULL,
  122372. NULL,
  122373. NULL,
  122374. 0
  122375. };
  122376. static long _huff_lengthlist_line_256x4low_class0[] = {
  122377. 4, 5, 6,11, 5, 5, 6,10, 7, 7, 6, 6,14,13, 9, 9,
  122378. 6, 6, 6,10, 6, 6, 6, 9, 8, 7, 7, 9,14,12, 8,11,
  122379. 8, 7, 7,11, 8, 8, 7,11, 9, 9, 7, 9,13,11, 9,13,
  122380. 19,19,18,19,15,16,16,19,11,11,10,13,10,10, 9,15,
  122381. 5, 5, 6,13, 6, 6, 6,11, 8, 7, 6, 7,14,11,10,11,
  122382. 6, 6, 6,12, 7, 6, 6,11, 8, 7, 7,11,13,11, 9,11,
  122383. 9, 7, 6,12, 8, 7, 6,12, 9, 8, 8,11,13,10, 7,13,
  122384. 19,19,17,19,17,14,14,19,12,10, 8,12,13,10, 9,16,
  122385. 7, 8, 7,12, 7, 7, 7,11, 8, 7, 7, 8,12,12,11,11,
  122386. 8, 8, 7,12, 8, 7, 6,11, 8, 7, 7,10,10,11,10,11,
  122387. 9, 8, 8,13, 9, 8, 7,12,10, 9, 7,11, 9, 8, 7,11,
  122388. 18,18,15,18,18,16,17,18,15,11,10,18,11, 9, 9,18,
  122389. 16,16,13,16,12,11,10,16,12,11, 9, 6,15,12,11,13,
  122390. 16,16,14,14,13,11,12,16,12, 9, 9,13,13,10,10,12,
  122391. 17,18,17,17,14,15,14,16,14,12,14,15,12,10,11,12,
  122392. 18,18,18,18,18,18,18,18,18,12,13,18,16,11, 9,18,
  122393. };
  122394. static static_codebook _huff_book_line_256x4low_class0 = {
  122395. 1, 256,
  122396. _huff_lengthlist_line_256x4low_class0,
  122397. 0, 0, 0, 0, 0,
  122398. NULL,
  122399. NULL,
  122400. NULL,
  122401. NULL,
  122402. 0
  122403. };
  122404. static long _huff_lengthlist_line_256x4low_0sub0[] = {
  122405. 1, 3, 2, 3,
  122406. };
  122407. static static_codebook _huff_book_line_256x4low_0sub0 = {
  122408. 1, 4,
  122409. _huff_lengthlist_line_256x4low_0sub0,
  122410. 0, 0, 0, 0, 0,
  122411. NULL,
  122412. NULL,
  122413. NULL,
  122414. NULL,
  122415. 0
  122416. };
  122417. static long _huff_lengthlist_line_256x4low_0sub1[] = {
  122418. 0, 0, 0, 0, 2, 3, 2, 3, 3, 3,
  122419. };
  122420. static static_codebook _huff_book_line_256x4low_0sub1 = {
  122421. 1, 10,
  122422. _huff_lengthlist_line_256x4low_0sub1,
  122423. 0, 0, 0, 0, 0,
  122424. NULL,
  122425. NULL,
  122426. NULL,
  122427. NULL,
  122428. 0
  122429. };
  122430. static long _huff_lengthlist_line_256x4low_0sub2[] = {
  122431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 3, 4,
  122432. 4, 4, 4, 4, 5, 5, 5, 6, 6,
  122433. };
  122434. static static_codebook _huff_book_line_256x4low_0sub2 = {
  122435. 1, 25,
  122436. _huff_lengthlist_line_256x4low_0sub2,
  122437. 0, 0, 0, 0, 0,
  122438. NULL,
  122439. NULL,
  122440. NULL,
  122441. NULL,
  122442. 0
  122443. };
  122444. static long _huff_lengthlist_line_256x4low_0sub3[] = {
  122445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 2, 4, 3, 5, 4,
  122447. 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 7, 8, 6, 9,
  122448. 7,12,11,16,13,16,12,15,13,15,12,14,12,15,15,15,
  122449. };
  122450. static static_codebook _huff_book_line_256x4low_0sub3 = {
  122451. 1, 64,
  122452. _huff_lengthlist_line_256x4low_0sub3,
  122453. 0, 0, 0, 0, 0,
  122454. NULL,
  122455. NULL,
  122456. NULL,
  122457. NULL,
  122458. 0
  122459. };
  122460. /*** End of inlined file: floor_books.h ***/
  122461. static static_codebook *_floor_128x4_books[]={
  122462. &_huff_book_line_128x4_class0,
  122463. &_huff_book_line_128x4_0sub0,
  122464. &_huff_book_line_128x4_0sub1,
  122465. &_huff_book_line_128x4_0sub2,
  122466. &_huff_book_line_128x4_0sub3,
  122467. };
  122468. static static_codebook *_floor_256x4_books[]={
  122469. &_huff_book_line_256x4_class0,
  122470. &_huff_book_line_256x4_0sub0,
  122471. &_huff_book_line_256x4_0sub1,
  122472. &_huff_book_line_256x4_0sub2,
  122473. &_huff_book_line_256x4_0sub3,
  122474. };
  122475. static static_codebook *_floor_128x7_books[]={
  122476. &_huff_book_line_128x7_class0,
  122477. &_huff_book_line_128x7_class1,
  122478. &_huff_book_line_128x7_0sub1,
  122479. &_huff_book_line_128x7_0sub2,
  122480. &_huff_book_line_128x7_0sub3,
  122481. &_huff_book_line_128x7_1sub1,
  122482. &_huff_book_line_128x7_1sub2,
  122483. &_huff_book_line_128x7_1sub3,
  122484. };
  122485. static static_codebook *_floor_256x7_books[]={
  122486. &_huff_book_line_256x7_class0,
  122487. &_huff_book_line_256x7_class1,
  122488. &_huff_book_line_256x7_0sub1,
  122489. &_huff_book_line_256x7_0sub2,
  122490. &_huff_book_line_256x7_0sub3,
  122491. &_huff_book_line_256x7_1sub1,
  122492. &_huff_book_line_256x7_1sub2,
  122493. &_huff_book_line_256x7_1sub3,
  122494. };
  122495. static static_codebook *_floor_128x11_books[]={
  122496. &_huff_book_line_128x11_class1,
  122497. &_huff_book_line_128x11_class2,
  122498. &_huff_book_line_128x11_class3,
  122499. &_huff_book_line_128x11_0sub0,
  122500. &_huff_book_line_128x11_1sub0,
  122501. &_huff_book_line_128x11_1sub1,
  122502. &_huff_book_line_128x11_2sub1,
  122503. &_huff_book_line_128x11_2sub2,
  122504. &_huff_book_line_128x11_2sub3,
  122505. &_huff_book_line_128x11_3sub1,
  122506. &_huff_book_line_128x11_3sub2,
  122507. &_huff_book_line_128x11_3sub3,
  122508. };
  122509. static static_codebook *_floor_128x17_books[]={
  122510. &_huff_book_line_128x17_class1,
  122511. &_huff_book_line_128x17_class2,
  122512. &_huff_book_line_128x17_class3,
  122513. &_huff_book_line_128x17_0sub0,
  122514. &_huff_book_line_128x17_1sub0,
  122515. &_huff_book_line_128x17_1sub1,
  122516. &_huff_book_line_128x17_2sub1,
  122517. &_huff_book_line_128x17_2sub2,
  122518. &_huff_book_line_128x17_2sub3,
  122519. &_huff_book_line_128x17_3sub1,
  122520. &_huff_book_line_128x17_3sub2,
  122521. &_huff_book_line_128x17_3sub3,
  122522. };
  122523. static static_codebook *_floor_256x4low_books[]={
  122524. &_huff_book_line_256x4low_class0,
  122525. &_huff_book_line_256x4low_0sub0,
  122526. &_huff_book_line_256x4low_0sub1,
  122527. &_huff_book_line_256x4low_0sub2,
  122528. &_huff_book_line_256x4low_0sub3,
  122529. };
  122530. static static_codebook *_floor_1024x27_books[]={
  122531. &_huff_book_line_1024x27_class1,
  122532. &_huff_book_line_1024x27_class2,
  122533. &_huff_book_line_1024x27_class3,
  122534. &_huff_book_line_1024x27_class4,
  122535. &_huff_book_line_1024x27_0sub0,
  122536. &_huff_book_line_1024x27_1sub0,
  122537. &_huff_book_line_1024x27_1sub1,
  122538. &_huff_book_line_1024x27_2sub0,
  122539. &_huff_book_line_1024x27_2sub1,
  122540. &_huff_book_line_1024x27_3sub1,
  122541. &_huff_book_line_1024x27_3sub2,
  122542. &_huff_book_line_1024x27_3sub3,
  122543. &_huff_book_line_1024x27_4sub1,
  122544. &_huff_book_line_1024x27_4sub2,
  122545. &_huff_book_line_1024x27_4sub3,
  122546. };
  122547. static static_codebook *_floor_2048x27_books[]={
  122548. &_huff_book_line_2048x27_class1,
  122549. &_huff_book_line_2048x27_class2,
  122550. &_huff_book_line_2048x27_class3,
  122551. &_huff_book_line_2048x27_class4,
  122552. &_huff_book_line_2048x27_0sub0,
  122553. &_huff_book_line_2048x27_1sub0,
  122554. &_huff_book_line_2048x27_1sub1,
  122555. &_huff_book_line_2048x27_2sub0,
  122556. &_huff_book_line_2048x27_2sub1,
  122557. &_huff_book_line_2048x27_3sub1,
  122558. &_huff_book_line_2048x27_3sub2,
  122559. &_huff_book_line_2048x27_3sub3,
  122560. &_huff_book_line_2048x27_4sub1,
  122561. &_huff_book_line_2048x27_4sub2,
  122562. &_huff_book_line_2048x27_4sub3,
  122563. };
  122564. static static_codebook *_floor_512x17_books[]={
  122565. &_huff_book_line_512x17_class1,
  122566. &_huff_book_line_512x17_class2,
  122567. &_huff_book_line_512x17_class3,
  122568. &_huff_book_line_512x17_0sub0,
  122569. &_huff_book_line_512x17_1sub0,
  122570. &_huff_book_line_512x17_1sub1,
  122571. &_huff_book_line_512x17_2sub1,
  122572. &_huff_book_line_512x17_2sub2,
  122573. &_huff_book_line_512x17_2sub3,
  122574. &_huff_book_line_512x17_3sub1,
  122575. &_huff_book_line_512x17_3sub2,
  122576. &_huff_book_line_512x17_3sub3,
  122577. };
  122578. static static_codebook **_floor_books[10]={
  122579. _floor_128x4_books,
  122580. _floor_256x4_books,
  122581. _floor_128x7_books,
  122582. _floor_256x7_books,
  122583. _floor_128x11_books,
  122584. _floor_128x17_books,
  122585. _floor_256x4low_books,
  122586. _floor_1024x27_books,
  122587. _floor_2048x27_books,
  122588. _floor_512x17_books,
  122589. };
  122590. static vorbis_info_floor1 _floor[10]={
  122591. /* 128 x 4 */
  122592. {
  122593. 1,{0},{4},{2},{0},
  122594. {{1,2,3,4}},
  122595. 4,{0,128, 33,8,16,70},
  122596. 60,30,500, 1.,18., -1
  122597. },
  122598. /* 256 x 4 */
  122599. {
  122600. 1,{0},{4},{2},{0},
  122601. {{1,2,3,4}},
  122602. 4,{0,256, 66,16,32,140},
  122603. 60,30,500, 1.,18., -1
  122604. },
  122605. /* 128 x 7 */
  122606. {
  122607. 2,{0,1},{3,4},{2,2},{0,1},
  122608. {{-1,2,3,4},{-1,5,6,7}},
  122609. 4,{0,128, 14,4,58, 2,8,28,90},
  122610. 60,30,500, 1.,18., -1
  122611. },
  122612. /* 256 x 7 */
  122613. {
  122614. 2,{0,1},{3,4},{2,2},{0,1},
  122615. {{-1,2,3,4},{-1,5,6,7}},
  122616. 4,{0,256, 28,8,116, 4,16,56,180},
  122617. 60,30,500, 1.,18., -1
  122618. },
  122619. /* 128 x 11 */
  122620. {
  122621. 4,{0,1,2,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122622. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122623. 2,{0,128, 8,33, 4,16,70, 2,6,12, 23,46,90},
  122624. 60,30,500, 1,18., -1
  122625. },
  122626. /* 128 x 17 */
  122627. {
  122628. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122629. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122630. 2,{0,128, 12,46, 4,8,16, 23,33,70, 2,6,10, 14,19,28, 39,58,90},
  122631. 60,30,500, 1,18., -1
  122632. },
  122633. /* 256 x 4 (low bitrate version) */
  122634. {
  122635. 1,{0},{4},{2},{0},
  122636. {{1,2,3,4}},
  122637. 4,{0,256, 66,16,32,140},
  122638. 60,30,500, 1.,18., -1
  122639. },
  122640. /* 1024 x 27 */
  122641. {
  122642. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  122643. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  122644. 2,{0,1024, 93,23,372, 6,46,186,750, 14,33,65, 130,260,556,
  122645. 3,10,18,28, 39,55,79,111, 158,220,312, 464,650,850},
  122646. 60,30,500, 3,18., -1 /* lowpass */
  122647. },
  122648. /* 2048 x 27 */
  122649. {
  122650. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  122651. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  122652. 2,{0,2048, 186,46,744, 12,92,372,1500, 28,66,130, 260,520,1112,
  122653. 6,20,36,56, 78,110,158,222, 316,440,624, 928,1300,1700},
  122654. 60,30,500, 3,18., -1 /* lowpass */
  122655. },
  122656. /* 512 x 17 */
  122657. {
  122658. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122659. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122660. 2,{0,512, 46,186, 16,33,65, 93,130,278,
  122661. 7,23,39, 55,79,110, 156,232,360},
  122662. 60,30,500, 1,18., -1 /* lowpass! */
  122663. },
  122664. };
  122665. /*** End of inlined file: floor_all.h ***/
  122666. /*** Start of inlined file: residue_44.h ***/
  122667. /*** Start of inlined file: res_books_stereo.h ***/
  122668. static long _vq_quantlist__16c0_s_p1_0[] = {
  122669. 1,
  122670. 0,
  122671. 2,
  122672. };
  122673. static long _vq_lengthlist__16c0_s_p1_0[] = {
  122674. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  122675. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122679. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0,
  122680. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122684. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  122685. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 8, 0, 0, 0, 0,
  122720. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  122721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0, 0,
  122725. 0, 0, 0, 9, 9,12, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  122726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0,
  122730. 0, 0, 0, 0, 9,12,10, 0, 0, 0, 0, 0, 0,10,11,12,
  122731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  122766. 0, 0, 0, 0, 8,10,10, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  122771. 0, 0, 0, 0, 0, 9,10,12, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,12,
  122776. 0, 0, 0, 0, 0, 0, 9,12, 9, 0, 0, 0, 0, 0, 0, 0,
  122777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123084. 0,
  123085. };
  123086. static float _vq_quantthresh__16c0_s_p1_0[] = {
  123087. -0.5, 0.5,
  123088. };
  123089. static long _vq_quantmap__16c0_s_p1_0[] = {
  123090. 1, 0, 2,
  123091. };
  123092. static encode_aux_threshmatch _vq_auxt__16c0_s_p1_0 = {
  123093. _vq_quantthresh__16c0_s_p1_0,
  123094. _vq_quantmap__16c0_s_p1_0,
  123095. 3,
  123096. 3
  123097. };
  123098. static static_codebook _16c0_s_p1_0 = {
  123099. 8, 6561,
  123100. _vq_lengthlist__16c0_s_p1_0,
  123101. 1, -535822336, 1611661312, 2, 0,
  123102. _vq_quantlist__16c0_s_p1_0,
  123103. NULL,
  123104. &_vq_auxt__16c0_s_p1_0,
  123105. NULL,
  123106. 0
  123107. };
  123108. static long _vq_quantlist__16c0_s_p2_0[] = {
  123109. 2,
  123110. 1,
  123111. 3,
  123112. 0,
  123113. 4,
  123114. };
  123115. static long _vq_lengthlist__16c0_s_p2_0[] = {
  123116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123155. 0,
  123156. };
  123157. static float _vq_quantthresh__16c0_s_p2_0[] = {
  123158. -1.5, -0.5, 0.5, 1.5,
  123159. };
  123160. static long _vq_quantmap__16c0_s_p2_0[] = {
  123161. 3, 1, 0, 2, 4,
  123162. };
  123163. static encode_aux_threshmatch _vq_auxt__16c0_s_p2_0 = {
  123164. _vq_quantthresh__16c0_s_p2_0,
  123165. _vq_quantmap__16c0_s_p2_0,
  123166. 5,
  123167. 5
  123168. };
  123169. static static_codebook _16c0_s_p2_0 = {
  123170. 4, 625,
  123171. _vq_lengthlist__16c0_s_p2_0,
  123172. 1, -533725184, 1611661312, 3, 0,
  123173. _vq_quantlist__16c0_s_p2_0,
  123174. NULL,
  123175. &_vq_auxt__16c0_s_p2_0,
  123176. NULL,
  123177. 0
  123178. };
  123179. static long _vq_quantlist__16c0_s_p3_0[] = {
  123180. 2,
  123181. 1,
  123182. 3,
  123183. 0,
  123184. 4,
  123185. };
  123186. static long _vq_lengthlist__16c0_s_p3_0[] = {
  123187. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 7, 6, 0, 0,
  123189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123190. 0, 0, 4, 6, 6, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  123192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123193. 0, 0, 0, 0, 6, 6, 6, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  123194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123226. 0,
  123227. };
  123228. static float _vq_quantthresh__16c0_s_p3_0[] = {
  123229. -1.5, -0.5, 0.5, 1.5,
  123230. };
  123231. static long _vq_quantmap__16c0_s_p3_0[] = {
  123232. 3, 1, 0, 2, 4,
  123233. };
  123234. static encode_aux_threshmatch _vq_auxt__16c0_s_p3_0 = {
  123235. _vq_quantthresh__16c0_s_p3_0,
  123236. _vq_quantmap__16c0_s_p3_0,
  123237. 5,
  123238. 5
  123239. };
  123240. static static_codebook _16c0_s_p3_0 = {
  123241. 4, 625,
  123242. _vq_lengthlist__16c0_s_p3_0,
  123243. 1, -533725184, 1611661312, 3, 0,
  123244. _vq_quantlist__16c0_s_p3_0,
  123245. NULL,
  123246. &_vq_auxt__16c0_s_p3_0,
  123247. NULL,
  123248. 0
  123249. };
  123250. static long _vq_quantlist__16c0_s_p4_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_p4_0[] = {
  123262. 1, 3, 2, 7, 8, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  123263. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  123264. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  123265. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  123266. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123267. 0,
  123268. };
  123269. static float _vq_quantthresh__16c0_s_p4_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_p4_0[] = {
  123273. 7, 5, 3, 1, 0, 2, 4, 6,
  123274. 8,
  123275. };
  123276. static encode_aux_threshmatch _vq_auxt__16c0_s_p4_0 = {
  123277. _vq_quantthresh__16c0_s_p4_0,
  123278. _vq_quantmap__16c0_s_p4_0,
  123279. 9,
  123280. 9
  123281. };
  123282. static static_codebook _16c0_s_p4_0 = {
  123283. 2, 81,
  123284. _vq_lengthlist__16c0_s_p4_0,
  123285. 1, -531628032, 1611661312, 4, 0,
  123286. _vq_quantlist__16c0_s_p4_0,
  123287. NULL,
  123288. &_vq_auxt__16c0_s_p4_0,
  123289. NULL,
  123290. 0
  123291. };
  123292. static long _vq_quantlist__16c0_s_p5_0[] = {
  123293. 4,
  123294. 3,
  123295. 5,
  123296. 2,
  123297. 6,
  123298. 1,
  123299. 7,
  123300. 0,
  123301. 8,
  123302. };
  123303. static long _vq_lengthlist__16c0_s_p5_0[] = {
  123304. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  123305. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 8, 0, 0, 0, 7, 7,
  123306. 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0, 0, 0,
  123307. 8, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  123308. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  123309. 10,
  123310. };
  123311. static float _vq_quantthresh__16c0_s_p5_0[] = {
  123312. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123313. };
  123314. static long _vq_quantmap__16c0_s_p5_0[] = {
  123315. 7, 5, 3, 1, 0, 2, 4, 6,
  123316. 8,
  123317. };
  123318. static encode_aux_threshmatch _vq_auxt__16c0_s_p5_0 = {
  123319. _vq_quantthresh__16c0_s_p5_0,
  123320. _vq_quantmap__16c0_s_p5_0,
  123321. 9,
  123322. 9
  123323. };
  123324. static static_codebook _16c0_s_p5_0 = {
  123325. 2, 81,
  123326. _vq_lengthlist__16c0_s_p5_0,
  123327. 1, -531628032, 1611661312, 4, 0,
  123328. _vq_quantlist__16c0_s_p5_0,
  123329. NULL,
  123330. &_vq_auxt__16c0_s_p5_0,
  123331. NULL,
  123332. 0
  123333. };
  123334. static long _vq_quantlist__16c0_s_p6_0[] = {
  123335. 8,
  123336. 7,
  123337. 9,
  123338. 6,
  123339. 10,
  123340. 5,
  123341. 11,
  123342. 4,
  123343. 12,
  123344. 3,
  123345. 13,
  123346. 2,
  123347. 14,
  123348. 1,
  123349. 15,
  123350. 0,
  123351. 16,
  123352. };
  123353. static long _vq_lengthlist__16c0_s_p6_0[] = {
  123354. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  123355. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  123356. 11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  123357. 11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  123358. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  123359. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  123360. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  123361. 10,11,11,12,12,12,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  123362. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10,10,10,
  123363. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  123364. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  123365. 9,10,10,11,11,12,12,13,13,13,14, 0, 0, 0, 0, 0,
  123366. 10,10,10,11,11,11,12,12,13,13,13,14, 0, 0, 0, 0,
  123367. 0, 0, 0,10,10,11,11,12,12,13,13,14,14, 0, 0, 0,
  123368. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  123369. 0, 0, 0, 0, 0,11,11,12,12,12,13,13,14,15,14, 0,
  123370. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,14,14,15,
  123371. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,13,14,
  123372. 14,
  123373. };
  123374. static float _vq_quantthresh__16c0_s_p6_0[] = {
  123375. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  123376. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  123377. };
  123378. static long _vq_quantmap__16c0_s_p6_0[] = {
  123379. 15, 13, 11, 9, 7, 5, 3, 1,
  123380. 0, 2, 4, 6, 8, 10, 12, 14,
  123381. 16,
  123382. };
  123383. static encode_aux_threshmatch _vq_auxt__16c0_s_p6_0 = {
  123384. _vq_quantthresh__16c0_s_p6_0,
  123385. _vq_quantmap__16c0_s_p6_0,
  123386. 17,
  123387. 17
  123388. };
  123389. static static_codebook _16c0_s_p6_0 = {
  123390. 2, 289,
  123391. _vq_lengthlist__16c0_s_p6_0,
  123392. 1, -529530880, 1611661312, 5, 0,
  123393. _vq_quantlist__16c0_s_p6_0,
  123394. NULL,
  123395. &_vq_auxt__16c0_s_p6_0,
  123396. NULL,
  123397. 0
  123398. };
  123399. static long _vq_quantlist__16c0_s_p7_0[] = {
  123400. 1,
  123401. 0,
  123402. 2,
  123403. };
  123404. static long _vq_lengthlist__16c0_s_p7_0[] = {
  123405. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,11,10,10,11,
  123406. 11,10, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  123407. 11,11,11,10, 6, 9, 9,11,12,12,11, 9, 9, 6, 9,10,
  123408. 11,12,12,11, 9,10, 7,11,11,11,11,11,12,13,12, 6,
  123409. 9,10,11,10,10,12,13,13, 6,10, 9,11,10,10,11,12,
  123410. 13,
  123411. };
  123412. static float _vq_quantthresh__16c0_s_p7_0[] = {
  123413. -5.5, 5.5,
  123414. };
  123415. static long _vq_quantmap__16c0_s_p7_0[] = {
  123416. 1, 0, 2,
  123417. };
  123418. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_0 = {
  123419. _vq_quantthresh__16c0_s_p7_0,
  123420. _vq_quantmap__16c0_s_p7_0,
  123421. 3,
  123422. 3
  123423. };
  123424. static static_codebook _16c0_s_p7_0 = {
  123425. 4, 81,
  123426. _vq_lengthlist__16c0_s_p7_0,
  123427. 1, -529137664, 1618345984, 2, 0,
  123428. _vq_quantlist__16c0_s_p7_0,
  123429. NULL,
  123430. &_vq_auxt__16c0_s_p7_0,
  123431. NULL,
  123432. 0
  123433. };
  123434. static long _vq_quantlist__16c0_s_p7_1[] = {
  123435. 5,
  123436. 4,
  123437. 6,
  123438. 3,
  123439. 7,
  123440. 2,
  123441. 8,
  123442. 1,
  123443. 9,
  123444. 0,
  123445. 10,
  123446. };
  123447. static long _vq_lengthlist__16c0_s_p7_1[] = {
  123448. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7,
  123449. 8, 8, 8, 9, 9, 9,10,10,10, 6, 7, 8, 8, 8, 8, 9,
  123450. 8,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10, 7,
  123451. 7, 8, 8, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9, 9,
  123452. 9, 9,11,11,11, 8, 8, 9, 9, 9, 9, 9,10,10,11,11,
  123453. 9, 9, 9, 9, 9, 9, 9,10,11,11,11,10,11, 9, 9, 9,
  123454. 9,10, 9,11,11,11,10,11,10,10, 9, 9,10,10,11,11,
  123455. 11,11,11, 9, 9, 9, 9,10,10,
  123456. };
  123457. static float _vq_quantthresh__16c0_s_p7_1[] = {
  123458. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  123459. 3.5, 4.5,
  123460. };
  123461. static long _vq_quantmap__16c0_s_p7_1[] = {
  123462. 9, 7, 5, 3, 1, 0, 2, 4,
  123463. 6, 8, 10,
  123464. };
  123465. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_1 = {
  123466. _vq_quantthresh__16c0_s_p7_1,
  123467. _vq_quantmap__16c0_s_p7_1,
  123468. 11,
  123469. 11
  123470. };
  123471. static static_codebook _16c0_s_p7_1 = {
  123472. 2, 121,
  123473. _vq_lengthlist__16c0_s_p7_1,
  123474. 1, -531365888, 1611661312, 4, 0,
  123475. _vq_quantlist__16c0_s_p7_1,
  123476. NULL,
  123477. &_vq_auxt__16c0_s_p7_1,
  123478. NULL,
  123479. 0
  123480. };
  123481. static long _vq_quantlist__16c0_s_p8_0[] = {
  123482. 6,
  123483. 5,
  123484. 7,
  123485. 4,
  123486. 8,
  123487. 3,
  123488. 9,
  123489. 2,
  123490. 10,
  123491. 1,
  123492. 11,
  123493. 0,
  123494. 12,
  123495. };
  123496. static long _vq_lengthlist__16c0_s_p8_0[] = {
  123497. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8,10,10, 6, 5, 6,
  123498. 8, 8, 8, 8, 8, 8, 8, 9,10,10, 7, 6, 6, 8, 8, 8,
  123499. 8, 8, 8, 8, 8,10,10, 0, 8, 8, 8, 8, 9, 8, 9, 9,
  123500. 9,10,10,10, 0, 9, 8, 8, 8, 9, 9, 8, 8, 9, 9,10,
  123501. 10, 0,12,11, 8, 8, 9, 9, 9, 9,10,10,11,10, 0,12,
  123502. 13, 8, 8, 9,10, 9, 9,11,11,11,12, 0, 0, 0, 8, 8,
  123503. 8, 8,10, 9,12,13,12,14, 0, 0, 0, 8, 8, 8, 9,10,
  123504. 10,12,12,13,14, 0, 0, 0,13,13, 9, 9,11,11, 0, 0,
  123505. 14, 0, 0, 0, 0,14,14,10,10,12,11,12,14,14,14, 0,
  123506. 0, 0, 0, 0,11,11,13,13,14,13,14,14, 0, 0, 0, 0,
  123507. 0,12,13,13,12,13,14,14,14,
  123508. };
  123509. static float _vq_quantthresh__16c0_s_p8_0[] = {
  123510. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  123511. 12.5, 17.5, 22.5, 27.5,
  123512. };
  123513. static long _vq_quantmap__16c0_s_p8_0[] = {
  123514. 11, 9, 7, 5, 3, 1, 0, 2,
  123515. 4, 6, 8, 10, 12,
  123516. };
  123517. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_0 = {
  123518. _vq_quantthresh__16c0_s_p8_0,
  123519. _vq_quantmap__16c0_s_p8_0,
  123520. 13,
  123521. 13
  123522. };
  123523. static static_codebook _16c0_s_p8_0 = {
  123524. 2, 169,
  123525. _vq_lengthlist__16c0_s_p8_0,
  123526. 1, -526516224, 1616117760, 4, 0,
  123527. _vq_quantlist__16c0_s_p8_0,
  123528. NULL,
  123529. &_vq_auxt__16c0_s_p8_0,
  123530. NULL,
  123531. 0
  123532. };
  123533. static long _vq_quantlist__16c0_s_p8_1[] = {
  123534. 2,
  123535. 1,
  123536. 3,
  123537. 0,
  123538. 4,
  123539. };
  123540. static long _vq_lengthlist__16c0_s_p8_1[] = {
  123541. 1, 4, 3, 5, 5, 7, 7, 7, 6, 6, 7, 7, 7, 5, 5, 7,
  123542. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  123543. };
  123544. static float _vq_quantthresh__16c0_s_p8_1[] = {
  123545. -1.5, -0.5, 0.5, 1.5,
  123546. };
  123547. static long _vq_quantmap__16c0_s_p8_1[] = {
  123548. 3, 1, 0, 2, 4,
  123549. };
  123550. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_1 = {
  123551. _vq_quantthresh__16c0_s_p8_1,
  123552. _vq_quantmap__16c0_s_p8_1,
  123553. 5,
  123554. 5
  123555. };
  123556. static static_codebook _16c0_s_p8_1 = {
  123557. 2, 25,
  123558. _vq_lengthlist__16c0_s_p8_1,
  123559. 1, -533725184, 1611661312, 3, 0,
  123560. _vq_quantlist__16c0_s_p8_1,
  123561. NULL,
  123562. &_vq_auxt__16c0_s_p8_1,
  123563. NULL,
  123564. 0
  123565. };
  123566. static long _vq_quantlist__16c0_s_p9_0[] = {
  123567. 1,
  123568. 0,
  123569. 2,
  123570. };
  123571. static long _vq_lengthlist__16c0_s_p9_0[] = {
  123572. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123573. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123574. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123575. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123576. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123577. 7,
  123578. };
  123579. static float _vq_quantthresh__16c0_s_p9_0[] = {
  123580. -157.5, 157.5,
  123581. };
  123582. static long _vq_quantmap__16c0_s_p9_0[] = {
  123583. 1, 0, 2,
  123584. };
  123585. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_0 = {
  123586. _vq_quantthresh__16c0_s_p9_0,
  123587. _vq_quantmap__16c0_s_p9_0,
  123588. 3,
  123589. 3
  123590. };
  123591. static static_codebook _16c0_s_p9_0 = {
  123592. 4, 81,
  123593. _vq_lengthlist__16c0_s_p9_0,
  123594. 1, -518803456, 1628680192, 2, 0,
  123595. _vq_quantlist__16c0_s_p9_0,
  123596. NULL,
  123597. &_vq_auxt__16c0_s_p9_0,
  123598. NULL,
  123599. 0
  123600. };
  123601. static long _vq_quantlist__16c0_s_p9_1[] = {
  123602. 7,
  123603. 6,
  123604. 8,
  123605. 5,
  123606. 9,
  123607. 4,
  123608. 10,
  123609. 3,
  123610. 11,
  123611. 2,
  123612. 12,
  123613. 1,
  123614. 13,
  123615. 0,
  123616. 14,
  123617. };
  123618. static long _vq_lengthlist__16c0_s_p9_1[] = {
  123619. 1, 5, 5, 5, 5, 9,11,11,10,10,10,10,10,10,10, 7,
  123620. 6, 6, 6, 6,10,10,10,10,10,10,10,10,10,10, 7, 6,
  123621. 6, 6, 6,10, 9,10,10,10,10,10,10,10,10,10, 7, 7,
  123622. 8, 9,10,10,10,10,10,10,10,10,10,10,10, 8, 7,10,
  123623. 10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123624. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123625. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123626. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123627. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123628. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123629. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123630. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123631. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123632. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123633. 10,
  123634. };
  123635. static float _vq_quantthresh__16c0_s_p9_1[] = {
  123636. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  123637. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  123638. };
  123639. static long _vq_quantmap__16c0_s_p9_1[] = {
  123640. 13, 11, 9, 7, 5, 3, 1, 0,
  123641. 2, 4, 6, 8, 10, 12, 14,
  123642. };
  123643. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_1 = {
  123644. _vq_quantthresh__16c0_s_p9_1,
  123645. _vq_quantmap__16c0_s_p9_1,
  123646. 15,
  123647. 15
  123648. };
  123649. static static_codebook _16c0_s_p9_1 = {
  123650. 2, 225,
  123651. _vq_lengthlist__16c0_s_p9_1,
  123652. 1, -520986624, 1620377600, 4, 0,
  123653. _vq_quantlist__16c0_s_p9_1,
  123654. NULL,
  123655. &_vq_auxt__16c0_s_p9_1,
  123656. NULL,
  123657. 0
  123658. };
  123659. static long _vq_quantlist__16c0_s_p9_2[] = {
  123660. 10,
  123661. 9,
  123662. 11,
  123663. 8,
  123664. 12,
  123665. 7,
  123666. 13,
  123667. 6,
  123668. 14,
  123669. 5,
  123670. 15,
  123671. 4,
  123672. 16,
  123673. 3,
  123674. 17,
  123675. 2,
  123676. 18,
  123677. 1,
  123678. 19,
  123679. 0,
  123680. 20,
  123681. };
  123682. static long _vq_lengthlist__16c0_s_p9_2[] = {
  123683. 1, 5, 5, 7, 8, 8, 7, 9, 9, 9,12,12,11,12,12,10,
  123684. 10,11,12,12,12,11,12,12, 8, 9, 8, 7, 9,10,10,11,
  123685. 11,10,11,12,10,12,10,12,12,12,11,12,11, 9, 8, 8,
  123686. 9,10, 9, 8, 9,10,12,12,11,11,12,11,10,11,12,11,
  123687. 12,12, 8, 9, 9, 9,10,11,12,11,12,11,11,11,11,12,
  123688. 12,11,11,12,12,11,11, 9, 9, 8, 9, 9,11, 9, 9,10,
  123689. 9,11,11,11,11,12,11,11,10,12,12,12, 9,12,11,10,
  123690. 11,11,11,11,12,12,12,11,11,11,12,10,12,12,12,10,
  123691. 10, 9,10, 9,10,10, 9, 9, 9,10,10,12,10,11,11, 9,
  123692. 11,11,10,11,11,11,10,10,10, 9, 9,10,10, 9, 9,10,
  123693. 11,11,10,11,10,11,10,11,11,10,11,11,11,10, 9,10,
  123694. 10, 9,10, 9, 9,11, 9, 9,11,10,10,11,11,10,10,11,
  123695. 10,11, 8, 9,11,11,10, 9,10,11,11,10,11,11,10,10,
  123696. 10,11,10, 9,10,10,11, 9,10,10, 9,11,10,10,10,10,
  123697. 11,10,11,11, 9,11,10,11,10,10,11,11,10,10,10, 9,
  123698. 10,10,11,11,11, 9,10,10,10,10,10,11,10,10,10, 9,
  123699. 10,10,11,10,10,10,10,10, 9,10,11,10,10,10,10,11,
  123700. 11,11,10,10,10,10,10,11,10,11,10,11,10,10,10, 9,
  123701. 11,11,10,10,10,11,11,10,10,10,10,10,10,10,10,11,
  123702. 11, 9,10,10,10,11,10,11,10,10,10,11, 9,10,11,10,
  123703. 11,10,10, 9,10,10,10,11,10,11,10,10,10,10,10,11,
  123704. 11,10,11,11,10,10,11,11,10, 9, 9,10,10,10,10,10,
  123705. 9,11, 9,10,10,10,11,11,10,10,10,10,11,11,11,10,
  123706. 9, 9,10,10,11,10,10,10,10,10,11,11,11,10,10,10,
  123707. 11,11,11, 9,10,10,10,10, 9,10, 9,10,11,10,11,10,
  123708. 10,11,11,10,11,11,11,11,11,10,11,10,10,10, 9,11,
  123709. 11,10,11,11,11,11,11,11,11,11,11,10,11,10,10,10,
  123710. 10,11,10,10,11, 9,10,10,10,
  123711. };
  123712. static float _vq_quantthresh__16c0_s_p9_2[] = {
  123713. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  123714. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  123715. 6.5, 7.5, 8.5, 9.5,
  123716. };
  123717. static long _vq_quantmap__16c0_s_p9_2[] = {
  123718. 19, 17, 15, 13, 11, 9, 7, 5,
  123719. 3, 1, 0, 2, 4, 6, 8, 10,
  123720. 12, 14, 16, 18, 20,
  123721. };
  123722. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_2 = {
  123723. _vq_quantthresh__16c0_s_p9_2,
  123724. _vq_quantmap__16c0_s_p9_2,
  123725. 21,
  123726. 21
  123727. };
  123728. static static_codebook _16c0_s_p9_2 = {
  123729. 2, 441,
  123730. _vq_lengthlist__16c0_s_p9_2,
  123731. 1, -529268736, 1611661312, 5, 0,
  123732. _vq_quantlist__16c0_s_p9_2,
  123733. NULL,
  123734. &_vq_auxt__16c0_s_p9_2,
  123735. NULL,
  123736. 0
  123737. };
  123738. static long _huff_lengthlist__16c0_s_single[] = {
  123739. 3, 4,19, 7, 9, 7, 8,11, 9,12, 4, 1,19, 6, 7, 7,
  123740. 8,10,11,13,18,18,18,18,18,18,18,18,18,18, 8, 6,
  123741. 18, 8, 9, 9,11,12,14,18, 9, 6,18, 9, 7, 8, 9,11,
  123742. 12,18, 7, 6,18, 8, 7, 7, 7, 9,11,17, 8, 8,18, 9,
  123743. 7, 6, 6, 8,11,17,10,10,18,12, 9, 8, 7, 9,12,18,
  123744. 13,15,18,15,13,11,10,11,15,18,14,18,18,18,18,18,
  123745. 16,16,18,18,
  123746. };
  123747. static static_codebook _huff_book__16c0_s_single = {
  123748. 2, 100,
  123749. _huff_lengthlist__16c0_s_single,
  123750. 0, 0, 0, 0, 0,
  123751. NULL,
  123752. NULL,
  123753. NULL,
  123754. NULL,
  123755. 0
  123756. };
  123757. static long _huff_lengthlist__16c1_s_long[] = {
  123758. 2, 5,20, 7,10, 7, 8,10,11,11, 4, 2,20, 5, 8, 6,
  123759. 7, 9,10,10,20,20,20,20,19,19,19,19,19,19, 7, 5,
  123760. 19, 6,10, 7, 9,11,13,17,11, 8,19,10, 7, 7, 8,10,
  123761. 11,15, 7, 5,19, 7, 7, 5, 6, 9,11,16, 7, 6,19, 8,
  123762. 7, 6, 6, 7, 9,13, 9, 9,19,11, 9, 8, 6, 7, 8,13,
  123763. 12,14,19,16,13,10, 9, 8, 9,13,14,17,19,18,18,17,
  123764. 12,11,11,13,
  123765. };
  123766. static static_codebook _huff_book__16c1_s_long = {
  123767. 2, 100,
  123768. _huff_lengthlist__16c1_s_long,
  123769. 0, 0, 0, 0, 0,
  123770. NULL,
  123771. NULL,
  123772. NULL,
  123773. NULL,
  123774. 0
  123775. };
  123776. static long _vq_quantlist__16c1_s_p1_0[] = {
  123777. 1,
  123778. 0,
  123779. 2,
  123780. };
  123781. static long _vq_lengthlist__16c1_s_p1_0[] = {
  123782. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  123783. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123787. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  123788. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123792. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  123793. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 7, 0, 0, 0, 0,
  123828. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  123829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  123833. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  123834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  123838. 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  123839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  123874. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  123879. 0, 0, 0, 0, 0, 8, 9,11, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  123884. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  123885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124192. 0,
  124193. };
  124194. static float _vq_quantthresh__16c1_s_p1_0[] = {
  124195. -0.5, 0.5,
  124196. };
  124197. static long _vq_quantmap__16c1_s_p1_0[] = {
  124198. 1, 0, 2,
  124199. };
  124200. static encode_aux_threshmatch _vq_auxt__16c1_s_p1_0 = {
  124201. _vq_quantthresh__16c1_s_p1_0,
  124202. _vq_quantmap__16c1_s_p1_0,
  124203. 3,
  124204. 3
  124205. };
  124206. static static_codebook _16c1_s_p1_0 = {
  124207. 8, 6561,
  124208. _vq_lengthlist__16c1_s_p1_0,
  124209. 1, -535822336, 1611661312, 2, 0,
  124210. _vq_quantlist__16c1_s_p1_0,
  124211. NULL,
  124212. &_vq_auxt__16c1_s_p1_0,
  124213. NULL,
  124214. 0
  124215. };
  124216. static long _vq_quantlist__16c1_s_p2_0[] = {
  124217. 2,
  124218. 1,
  124219. 3,
  124220. 0,
  124221. 4,
  124222. };
  124223. static long _vq_lengthlist__16c1_s_p2_0[] = {
  124224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124263. 0,
  124264. };
  124265. static float _vq_quantthresh__16c1_s_p2_0[] = {
  124266. -1.5, -0.5, 0.5, 1.5,
  124267. };
  124268. static long _vq_quantmap__16c1_s_p2_0[] = {
  124269. 3, 1, 0, 2, 4,
  124270. };
  124271. static encode_aux_threshmatch _vq_auxt__16c1_s_p2_0 = {
  124272. _vq_quantthresh__16c1_s_p2_0,
  124273. _vq_quantmap__16c1_s_p2_0,
  124274. 5,
  124275. 5
  124276. };
  124277. static static_codebook _16c1_s_p2_0 = {
  124278. 4, 625,
  124279. _vq_lengthlist__16c1_s_p2_0,
  124280. 1, -533725184, 1611661312, 3, 0,
  124281. _vq_quantlist__16c1_s_p2_0,
  124282. NULL,
  124283. &_vq_auxt__16c1_s_p2_0,
  124284. NULL,
  124285. 0
  124286. };
  124287. static long _vq_quantlist__16c1_s_p3_0[] = {
  124288. 2,
  124289. 1,
  124290. 3,
  124291. 0,
  124292. 4,
  124293. };
  124294. static long _vq_lengthlist__16c1_s_p3_0[] = {
  124295. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  124297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124298. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 7, 9, 9,
  124300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124301. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  124302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124334. 0,
  124335. };
  124336. static float _vq_quantthresh__16c1_s_p3_0[] = {
  124337. -1.5, -0.5, 0.5, 1.5,
  124338. };
  124339. static long _vq_quantmap__16c1_s_p3_0[] = {
  124340. 3, 1, 0, 2, 4,
  124341. };
  124342. static encode_aux_threshmatch _vq_auxt__16c1_s_p3_0 = {
  124343. _vq_quantthresh__16c1_s_p3_0,
  124344. _vq_quantmap__16c1_s_p3_0,
  124345. 5,
  124346. 5
  124347. };
  124348. static static_codebook _16c1_s_p3_0 = {
  124349. 4, 625,
  124350. _vq_lengthlist__16c1_s_p3_0,
  124351. 1, -533725184, 1611661312, 3, 0,
  124352. _vq_quantlist__16c1_s_p3_0,
  124353. NULL,
  124354. &_vq_auxt__16c1_s_p3_0,
  124355. NULL,
  124356. 0
  124357. };
  124358. static long _vq_quantlist__16c1_s_p4_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_p4_0[] = {
  124370. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  124371. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  124372. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  124373. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 0, 0, 0,
  124374. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124375. 0,
  124376. };
  124377. static float _vq_quantthresh__16c1_s_p4_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_p4_0[] = {
  124381. 7, 5, 3, 1, 0, 2, 4, 6,
  124382. 8,
  124383. };
  124384. static encode_aux_threshmatch _vq_auxt__16c1_s_p4_0 = {
  124385. _vq_quantthresh__16c1_s_p4_0,
  124386. _vq_quantmap__16c1_s_p4_0,
  124387. 9,
  124388. 9
  124389. };
  124390. static static_codebook _16c1_s_p4_0 = {
  124391. 2, 81,
  124392. _vq_lengthlist__16c1_s_p4_0,
  124393. 1, -531628032, 1611661312, 4, 0,
  124394. _vq_quantlist__16c1_s_p4_0,
  124395. NULL,
  124396. &_vq_auxt__16c1_s_p4_0,
  124397. NULL,
  124398. 0
  124399. };
  124400. static long _vq_quantlist__16c1_s_p5_0[] = {
  124401. 4,
  124402. 3,
  124403. 5,
  124404. 2,
  124405. 6,
  124406. 1,
  124407. 7,
  124408. 0,
  124409. 8,
  124410. };
  124411. static long _vq_lengthlist__16c1_s_p5_0[] = {
  124412. 1, 3, 3, 5, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  124413. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 8, 8,
  124414. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  124415. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  124416. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  124417. 10,
  124418. };
  124419. static float _vq_quantthresh__16c1_s_p5_0[] = {
  124420. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124421. };
  124422. static long _vq_quantmap__16c1_s_p5_0[] = {
  124423. 7, 5, 3, 1, 0, 2, 4, 6,
  124424. 8,
  124425. };
  124426. static encode_aux_threshmatch _vq_auxt__16c1_s_p5_0 = {
  124427. _vq_quantthresh__16c1_s_p5_0,
  124428. _vq_quantmap__16c1_s_p5_0,
  124429. 9,
  124430. 9
  124431. };
  124432. static static_codebook _16c1_s_p5_0 = {
  124433. 2, 81,
  124434. _vq_lengthlist__16c1_s_p5_0,
  124435. 1, -531628032, 1611661312, 4, 0,
  124436. _vq_quantlist__16c1_s_p5_0,
  124437. NULL,
  124438. &_vq_auxt__16c1_s_p5_0,
  124439. NULL,
  124440. 0
  124441. };
  124442. static long _vq_quantlist__16c1_s_p6_0[] = {
  124443. 8,
  124444. 7,
  124445. 9,
  124446. 6,
  124447. 10,
  124448. 5,
  124449. 11,
  124450. 4,
  124451. 12,
  124452. 3,
  124453. 13,
  124454. 2,
  124455. 14,
  124456. 1,
  124457. 15,
  124458. 0,
  124459. 16,
  124460. };
  124461. static long _vq_lengthlist__16c1_s_p6_0[] = {
  124462. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,12,
  124463. 12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  124464. 12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  124465. 11,12,12, 0, 0, 0, 8, 8, 8, 9,10, 9,10,10,10,10,
  124466. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,11,
  124467. 11,11,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  124468. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  124469. 10,11,11,12,12,13,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  124470. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  124471. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  124472. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  124473. 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0,
  124474. 10,10,11,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0,
  124475. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  124476. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  124477. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0,
  124478. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  124479. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  124480. 14,
  124481. };
  124482. static float _vq_quantthresh__16c1_s_p6_0[] = {
  124483. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  124484. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  124485. };
  124486. static long _vq_quantmap__16c1_s_p6_0[] = {
  124487. 15, 13, 11, 9, 7, 5, 3, 1,
  124488. 0, 2, 4, 6, 8, 10, 12, 14,
  124489. 16,
  124490. };
  124491. static encode_aux_threshmatch _vq_auxt__16c1_s_p6_0 = {
  124492. _vq_quantthresh__16c1_s_p6_0,
  124493. _vq_quantmap__16c1_s_p6_0,
  124494. 17,
  124495. 17
  124496. };
  124497. static static_codebook _16c1_s_p6_0 = {
  124498. 2, 289,
  124499. _vq_lengthlist__16c1_s_p6_0,
  124500. 1, -529530880, 1611661312, 5, 0,
  124501. _vq_quantlist__16c1_s_p6_0,
  124502. NULL,
  124503. &_vq_auxt__16c1_s_p6_0,
  124504. NULL,
  124505. 0
  124506. };
  124507. static long _vq_quantlist__16c1_s_p7_0[] = {
  124508. 1,
  124509. 0,
  124510. 2,
  124511. };
  124512. static long _vq_lengthlist__16c1_s_p7_0[] = {
  124513. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9,10,10,
  124514. 10, 9, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  124515. 11,11,10,10, 6,10, 9,11,11,11,11,10,10, 6,10,10,
  124516. 11,11,11,11,10,10, 7,11,11,11,11,11,12,12,11, 6,
  124517. 10,10,11,10,10,11,11,11, 6,10,10,10,11,10,11,11,
  124518. 11,
  124519. };
  124520. static float _vq_quantthresh__16c1_s_p7_0[] = {
  124521. -5.5, 5.5,
  124522. };
  124523. static long _vq_quantmap__16c1_s_p7_0[] = {
  124524. 1, 0, 2,
  124525. };
  124526. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_0 = {
  124527. _vq_quantthresh__16c1_s_p7_0,
  124528. _vq_quantmap__16c1_s_p7_0,
  124529. 3,
  124530. 3
  124531. };
  124532. static static_codebook _16c1_s_p7_0 = {
  124533. 4, 81,
  124534. _vq_lengthlist__16c1_s_p7_0,
  124535. 1, -529137664, 1618345984, 2, 0,
  124536. _vq_quantlist__16c1_s_p7_0,
  124537. NULL,
  124538. &_vq_auxt__16c1_s_p7_0,
  124539. NULL,
  124540. 0
  124541. };
  124542. static long _vq_quantlist__16c1_s_p7_1[] = {
  124543. 5,
  124544. 4,
  124545. 6,
  124546. 3,
  124547. 7,
  124548. 2,
  124549. 8,
  124550. 1,
  124551. 9,
  124552. 0,
  124553. 10,
  124554. };
  124555. static long _vq_lengthlist__16c1_s_p7_1[] = {
  124556. 2, 3, 3, 5, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  124557. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  124558. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  124559. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  124560. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  124561. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  124562. 8, 9, 9,10,10,10,10,10, 9, 9, 8, 8, 9, 9,10,10,
  124563. 10,10,10, 8, 8, 8, 8, 9, 9,
  124564. };
  124565. static float _vq_quantthresh__16c1_s_p7_1[] = {
  124566. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124567. 3.5, 4.5,
  124568. };
  124569. static long _vq_quantmap__16c1_s_p7_1[] = {
  124570. 9, 7, 5, 3, 1, 0, 2, 4,
  124571. 6, 8, 10,
  124572. };
  124573. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_1 = {
  124574. _vq_quantthresh__16c1_s_p7_1,
  124575. _vq_quantmap__16c1_s_p7_1,
  124576. 11,
  124577. 11
  124578. };
  124579. static static_codebook _16c1_s_p7_1 = {
  124580. 2, 121,
  124581. _vq_lengthlist__16c1_s_p7_1,
  124582. 1, -531365888, 1611661312, 4, 0,
  124583. _vq_quantlist__16c1_s_p7_1,
  124584. NULL,
  124585. &_vq_auxt__16c1_s_p7_1,
  124586. NULL,
  124587. 0
  124588. };
  124589. static long _vq_quantlist__16c1_s_p8_0[] = {
  124590. 6,
  124591. 5,
  124592. 7,
  124593. 4,
  124594. 8,
  124595. 3,
  124596. 9,
  124597. 2,
  124598. 10,
  124599. 1,
  124600. 11,
  124601. 0,
  124602. 12,
  124603. };
  124604. static long _vq_lengthlist__16c1_s_p8_0[] = {
  124605. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  124606. 7, 8, 8, 9, 8, 8, 9, 9,10,11, 6, 5, 5, 8, 8, 9,
  124607. 9, 8, 8, 9,10,10,11, 0, 8, 8, 8, 9, 9, 9, 9, 9,
  124608. 10,10,11,11, 0, 9, 9, 9, 8, 9, 9, 9, 9,10,10,11,
  124609. 11, 0,13,13, 9, 9,10,10,10,10,11,11,12,12, 0,14,
  124610. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  124611. 9, 9,11,11,12,12,13,12, 0, 0, 0,10,10, 9, 9,10,
  124612. 10,12,12,13,13, 0, 0, 0,13,14,11,10,11,11,12,12,
  124613. 13,14, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  124614. 0, 0, 0, 0,12,12,12,12,13,13,14,15, 0, 0, 0, 0,
  124615. 0,12,12,12,12,13,13,14,15,
  124616. };
  124617. static float _vq_quantthresh__16c1_s_p8_0[] = {
  124618. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  124619. 12.5, 17.5, 22.5, 27.5,
  124620. };
  124621. static long _vq_quantmap__16c1_s_p8_0[] = {
  124622. 11, 9, 7, 5, 3, 1, 0, 2,
  124623. 4, 6, 8, 10, 12,
  124624. };
  124625. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_0 = {
  124626. _vq_quantthresh__16c1_s_p8_0,
  124627. _vq_quantmap__16c1_s_p8_0,
  124628. 13,
  124629. 13
  124630. };
  124631. static static_codebook _16c1_s_p8_0 = {
  124632. 2, 169,
  124633. _vq_lengthlist__16c1_s_p8_0,
  124634. 1, -526516224, 1616117760, 4, 0,
  124635. _vq_quantlist__16c1_s_p8_0,
  124636. NULL,
  124637. &_vq_auxt__16c1_s_p8_0,
  124638. NULL,
  124639. 0
  124640. };
  124641. static long _vq_quantlist__16c1_s_p8_1[] = {
  124642. 2,
  124643. 1,
  124644. 3,
  124645. 0,
  124646. 4,
  124647. };
  124648. static long _vq_lengthlist__16c1_s_p8_1[] = {
  124649. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  124650. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  124651. };
  124652. static float _vq_quantthresh__16c1_s_p8_1[] = {
  124653. -1.5, -0.5, 0.5, 1.5,
  124654. };
  124655. static long _vq_quantmap__16c1_s_p8_1[] = {
  124656. 3, 1, 0, 2, 4,
  124657. };
  124658. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_1 = {
  124659. _vq_quantthresh__16c1_s_p8_1,
  124660. _vq_quantmap__16c1_s_p8_1,
  124661. 5,
  124662. 5
  124663. };
  124664. static static_codebook _16c1_s_p8_1 = {
  124665. 2, 25,
  124666. _vq_lengthlist__16c1_s_p8_1,
  124667. 1, -533725184, 1611661312, 3, 0,
  124668. _vq_quantlist__16c1_s_p8_1,
  124669. NULL,
  124670. &_vq_auxt__16c1_s_p8_1,
  124671. NULL,
  124672. 0
  124673. };
  124674. static long _vq_quantlist__16c1_s_p9_0[] = {
  124675. 6,
  124676. 5,
  124677. 7,
  124678. 4,
  124679. 8,
  124680. 3,
  124681. 9,
  124682. 2,
  124683. 10,
  124684. 1,
  124685. 11,
  124686. 0,
  124687. 12,
  124688. };
  124689. static long _vq_lengthlist__16c1_s_p9_0[] = {
  124690. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124691. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124692. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124693. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124694. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124695. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124696. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124697. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124698. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124699. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124700. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124701. };
  124702. static float _vq_quantthresh__16c1_s_p9_0[] = {
  124703. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  124704. 787.5, 1102.5, 1417.5, 1732.5,
  124705. };
  124706. static long _vq_quantmap__16c1_s_p9_0[] = {
  124707. 11, 9, 7, 5, 3, 1, 0, 2,
  124708. 4, 6, 8, 10, 12,
  124709. };
  124710. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_0 = {
  124711. _vq_quantthresh__16c1_s_p9_0,
  124712. _vq_quantmap__16c1_s_p9_0,
  124713. 13,
  124714. 13
  124715. };
  124716. static static_codebook _16c1_s_p9_0 = {
  124717. 2, 169,
  124718. _vq_lengthlist__16c1_s_p9_0,
  124719. 1, -513964032, 1628680192, 4, 0,
  124720. _vq_quantlist__16c1_s_p9_0,
  124721. NULL,
  124722. &_vq_auxt__16c1_s_p9_0,
  124723. NULL,
  124724. 0
  124725. };
  124726. static long _vq_quantlist__16c1_s_p9_1[] = {
  124727. 7,
  124728. 6,
  124729. 8,
  124730. 5,
  124731. 9,
  124732. 4,
  124733. 10,
  124734. 3,
  124735. 11,
  124736. 2,
  124737. 12,
  124738. 1,
  124739. 13,
  124740. 0,
  124741. 14,
  124742. };
  124743. static long _vq_lengthlist__16c1_s_p9_1[] = {
  124744. 1, 4, 4, 4, 4, 8, 8,12,13,14,14,14,14,14,14, 6,
  124745. 6, 6, 6, 6,10, 9,14,14,14,14,14,14,14,14, 7, 6,
  124746. 5, 6, 6,10, 9,12,13,13,13,13,13,13,13,13, 7, 7,
  124747. 9, 9,11,11,12,13,13,13,13,13,13,13,13, 7, 7, 8,
  124748. 8,11,12,13,13,13,13,13,13,13,13,13,12,12,10,10,
  124749. 13,12,13,13,13,13,13,13,13,13,13,12,12,10,10,13,
  124750. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,13,12,
  124751. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  124752. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124753. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  124754. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124755. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124756. 13,13,13,13,13,13,13,13,13,12,13,13,13,13,13,13,
  124757. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124758. 13,
  124759. };
  124760. static float _vq_quantthresh__16c1_s_p9_1[] = {
  124761. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  124762. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  124763. };
  124764. static long _vq_quantmap__16c1_s_p9_1[] = {
  124765. 13, 11, 9, 7, 5, 3, 1, 0,
  124766. 2, 4, 6, 8, 10, 12, 14,
  124767. };
  124768. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_1 = {
  124769. _vq_quantthresh__16c1_s_p9_1,
  124770. _vq_quantmap__16c1_s_p9_1,
  124771. 15,
  124772. 15
  124773. };
  124774. static static_codebook _16c1_s_p9_1 = {
  124775. 2, 225,
  124776. _vq_lengthlist__16c1_s_p9_1,
  124777. 1, -520986624, 1620377600, 4, 0,
  124778. _vq_quantlist__16c1_s_p9_1,
  124779. NULL,
  124780. &_vq_auxt__16c1_s_p9_1,
  124781. NULL,
  124782. 0
  124783. };
  124784. static long _vq_quantlist__16c1_s_p9_2[] = {
  124785. 10,
  124786. 9,
  124787. 11,
  124788. 8,
  124789. 12,
  124790. 7,
  124791. 13,
  124792. 6,
  124793. 14,
  124794. 5,
  124795. 15,
  124796. 4,
  124797. 16,
  124798. 3,
  124799. 17,
  124800. 2,
  124801. 18,
  124802. 1,
  124803. 19,
  124804. 0,
  124805. 20,
  124806. };
  124807. static long _vq_lengthlist__16c1_s_p9_2[] = {
  124808. 1, 4, 4, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9,10,
  124809. 10,10, 9,10,10,11,12,12, 8, 8, 8, 8, 9, 9, 9, 9,
  124810. 10,10,10,10,10,11,11,10,12,11,11,13,11, 7, 7, 8,
  124811. 8, 8, 8, 9, 9, 9,10,10,10,10, 9,10,10,11,11,12,
  124812. 11,11, 8, 8, 8, 8, 9, 9,10,10,10,10,11,11,11,11,
  124813. 11,11,11,12,11,12,12, 8, 8, 9, 9, 9, 9, 9,10,10,
  124814. 10,10,10,10,11,11,11,11,11,11,12,11, 9, 9, 9, 9,
  124815. 10,10,10,10,11,10,11,11,11,11,11,11,12,12,12,12,
  124816. 11, 9, 9, 9, 9,10,10,10,10,11,11,11,11,11,11,11,
  124817. 11,11,12,12,12,13, 9,10,10, 9,11,10,10,10,10,11,
  124818. 11,11,11,11,10,11,12,11,12,12,11,12,11,10, 9,10,
  124819. 10,11,10,11,11,11,11,11,11,11,11,11,12,12,11,12,
  124820. 12,12,10,10,10,11,10,11,11,11,11,11,11,11,11,11,
  124821. 11,11,12,13,12,12,11, 9,10,10,11,11,10,11,11,11,
  124822. 12,11,11,11,11,11,12,12,13,13,12,13,10,10,12,10,
  124823. 11,11,11,11,11,11,11,11,11,12,12,11,13,12,12,12,
  124824. 12,13,12,11,11,11,11,11,11,12,11,12,11,11,11,11,
  124825. 12,12,13,12,11,12,12,11,11,11,11,11,12,11,11,11,
  124826. 11,12,11,11,12,11,12,13,13,12,12,12,12,11,11,11,
  124827. 11,11,12,11,11,12,11,12,11,11,11,11,13,12,12,12,
  124828. 12,13,11,11,11,12,12,11,11,11,12,11,12,12,12,11,
  124829. 12,13,12,11,11,12,12,11,12,11,11,11,12,12,11,12,
  124830. 11,11,11,12,12,12,12,13,12,13,12,12,12,12,11,11,
  124831. 12,11,11,11,11,11,11,12,12,12,13,12,11,13,13,12,
  124832. 12,11,12,10,11,11,11,11,12,11,12,12,11,12,12,13,
  124833. 12,12,13,12,12,12,12,12,11,12,12,12,11,12,11,11,
  124834. 11,12,13,12,13,13,13,13,13,12,13,13,12,12,13,11,
  124835. 11,11,11,11,12,11,11,12,11,
  124836. };
  124837. static float _vq_quantthresh__16c1_s_p9_2[] = {
  124838. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  124839. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  124840. 6.5, 7.5, 8.5, 9.5,
  124841. };
  124842. static long _vq_quantmap__16c1_s_p9_2[] = {
  124843. 19, 17, 15, 13, 11, 9, 7, 5,
  124844. 3, 1, 0, 2, 4, 6, 8, 10,
  124845. 12, 14, 16, 18, 20,
  124846. };
  124847. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_2 = {
  124848. _vq_quantthresh__16c1_s_p9_2,
  124849. _vq_quantmap__16c1_s_p9_2,
  124850. 21,
  124851. 21
  124852. };
  124853. static static_codebook _16c1_s_p9_2 = {
  124854. 2, 441,
  124855. _vq_lengthlist__16c1_s_p9_2,
  124856. 1, -529268736, 1611661312, 5, 0,
  124857. _vq_quantlist__16c1_s_p9_2,
  124858. NULL,
  124859. &_vq_auxt__16c1_s_p9_2,
  124860. NULL,
  124861. 0
  124862. };
  124863. static long _huff_lengthlist__16c1_s_short[] = {
  124864. 5, 6,17, 8,12, 9,10,10,12,13, 5, 2,17, 4, 9, 5,
  124865. 7, 8,11,13,16,16,16,16,16,16,16,16,16,16, 6, 4,
  124866. 16, 5,10, 5, 7,10,14,16,13, 9,16,11, 8, 7, 8, 9,
  124867. 13,16, 7, 4,16, 5, 7, 4, 6, 8,11,13, 8, 6,16, 7,
  124868. 8, 5, 5, 7, 9,13, 9, 8,16, 9, 8, 6, 6, 7, 9,13,
  124869. 11,11,16,10,10, 7, 7, 7, 9,13,13,13,16,13,13, 9,
  124870. 9, 9,10,13,
  124871. };
  124872. static static_codebook _huff_book__16c1_s_short = {
  124873. 2, 100,
  124874. _huff_lengthlist__16c1_s_short,
  124875. 0, 0, 0, 0, 0,
  124876. NULL,
  124877. NULL,
  124878. NULL,
  124879. NULL,
  124880. 0
  124881. };
  124882. static long _huff_lengthlist__16c2_s_long[] = {
  124883. 4, 7, 9, 9, 9, 8, 9,10,15,19, 5, 4, 5, 6, 7, 7,
  124884. 8, 9,14,16, 6, 5, 4, 5, 6, 7, 8,10,12,19, 7, 6,
  124885. 5, 4, 5, 6, 7, 9,11,18, 8, 7, 6, 5, 5, 5, 7, 9,
  124886. 10,17, 8, 7, 7, 5, 5, 5, 6, 7,12,18, 8, 8, 8, 7,
  124887. 7, 5, 5, 7,12,18, 8, 9,10, 9, 9, 7, 6, 7,12,17,
  124888. 14,18,16,16,15,12,11,10,12,18,15,17,18,18,18,15,
  124889. 14,14,16,18,
  124890. };
  124891. static static_codebook _huff_book__16c2_s_long = {
  124892. 2, 100,
  124893. _huff_lengthlist__16c2_s_long,
  124894. 0, 0, 0, 0, 0,
  124895. NULL,
  124896. NULL,
  124897. NULL,
  124898. NULL,
  124899. 0
  124900. };
  124901. static long _vq_quantlist__16c2_s_p1_0[] = {
  124902. 1,
  124903. 0,
  124904. 2,
  124905. };
  124906. static long _vq_lengthlist__16c2_s_p1_0[] = {
  124907. 1, 3, 3, 0, 0, 0, 0, 0, 0, 4, 5, 5, 0, 0, 0, 0,
  124908. 0, 0, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  124913. };
  124914. static float _vq_quantthresh__16c2_s_p1_0[] = {
  124915. -0.5, 0.5,
  124916. };
  124917. static long _vq_quantmap__16c2_s_p1_0[] = {
  124918. 1, 0, 2,
  124919. };
  124920. static encode_aux_threshmatch _vq_auxt__16c2_s_p1_0 = {
  124921. _vq_quantthresh__16c2_s_p1_0,
  124922. _vq_quantmap__16c2_s_p1_0,
  124923. 3,
  124924. 3
  124925. };
  124926. static static_codebook _16c2_s_p1_0 = {
  124927. 4, 81,
  124928. _vq_lengthlist__16c2_s_p1_0,
  124929. 1, -535822336, 1611661312, 2, 0,
  124930. _vq_quantlist__16c2_s_p1_0,
  124931. NULL,
  124932. &_vq_auxt__16c2_s_p1_0,
  124933. NULL,
  124934. 0
  124935. };
  124936. static long _vq_quantlist__16c2_s_p2_0[] = {
  124937. 2,
  124938. 1,
  124939. 3,
  124940. 0,
  124941. 4,
  124942. };
  124943. static long _vq_lengthlist__16c2_s_p2_0[] = {
  124944. 2, 4, 3, 7, 7, 0, 0, 0, 7, 8, 0, 0, 0, 8, 8, 0,
  124945. 0, 0, 8, 8, 0, 0, 0, 8, 8, 4, 5, 4, 8, 8, 0, 0,
  124946. 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0,
  124947. 9, 9, 4, 4, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8,
  124948. 8, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 7, 8, 8,10,10,
  124949. 0, 0, 0,12,11, 0, 0, 0,11,11, 0, 0, 0,14,13, 0,
  124950. 0, 0,14,13, 7, 8, 8, 9,10, 0, 0, 0,11,12, 0, 0,
  124951. 0,11,11, 0, 0, 0,14,14, 0, 0, 0,13,14, 0, 0, 0,
  124952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124956. 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8,11,11, 0, 0, 0,
  124957. 11,11, 0, 0, 0,12,11, 0, 0, 0,12,12, 0, 0, 0,13,
  124958. 13, 8, 8, 8,11,11, 0, 0, 0,11,11, 0, 0, 0,11,12,
  124959. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  124960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124964. 0, 0, 0, 0, 0, 8, 8, 8,12,11, 0, 0, 0,12,11, 0,
  124965. 0, 0,11,11, 0, 0, 0,13,13, 0, 0, 0,13,12, 8, 8,
  124966. 8,11,12, 0, 0, 0,11,12, 0, 0, 0,11,11, 0, 0, 0,
  124967. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124972. 0, 0, 8, 9, 9,14,13, 0, 0, 0,13,12, 0, 0, 0,13,
  124973. 13, 0, 0, 0,13,12, 0, 0, 0,13,13, 8, 9, 9,13,14,
  124974. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,13, 0,
  124975. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8,
  124980. 9, 9,14,13, 0, 0, 0,13,13, 0, 0, 0,13,12, 0, 0,
  124981. 0,13,13, 0, 0, 0,13,12, 8, 9, 9,14,14, 0, 0, 0,
  124982. 13,13, 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,
  124983. 13,
  124984. };
  124985. static float _vq_quantthresh__16c2_s_p2_0[] = {
  124986. -1.5, -0.5, 0.5, 1.5,
  124987. };
  124988. static long _vq_quantmap__16c2_s_p2_0[] = {
  124989. 3, 1, 0, 2, 4,
  124990. };
  124991. static encode_aux_threshmatch _vq_auxt__16c2_s_p2_0 = {
  124992. _vq_quantthresh__16c2_s_p2_0,
  124993. _vq_quantmap__16c2_s_p2_0,
  124994. 5,
  124995. 5
  124996. };
  124997. static static_codebook _16c2_s_p2_0 = {
  124998. 4, 625,
  124999. _vq_lengthlist__16c2_s_p2_0,
  125000. 1, -533725184, 1611661312, 3, 0,
  125001. _vq_quantlist__16c2_s_p2_0,
  125002. NULL,
  125003. &_vq_auxt__16c2_s_p2_0,
  125004. NULL,
  125005. 0
  125006. };
  125007. static long _vq_quantlist__16c2_s_p3_0[] = {
  125008. 4,
  125009. 3,
  125010. 5,
  125011. 2,
  125012. 6,
  125013. 1,
  125014. 7,
  125015. 0,
  125016. 8,
  125017. };
  125018. static long _vq_lengthlist__16c2_s_p3_0[] = {
  125019. 1, 3, 3, 6, 6, 7, 7, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  125020. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  125021. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  125022. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 9, 9,10,10, 0,
  125023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125024. 0,
  125025. };
  125026. static float _vq_quantthresh__16c2_s_p3_0[] = {
  125027. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  125028. };
  125029. static long _vq_quantmap__16c2_s_p3_0[] = {
  125030. 7, 5, 3, 1, 0, 2, 4, 6,
  125031. 8,
  125032. };
  125033. static encode_aux_threshmatch _vq_auxt__16c2_s_p3_0 = {
  125034. _vq_quantthresh__16c2_s_p3_0,
  125035. _vq_quantmap__16c2_s_p3_0,
  125036. 9,
  125037. 9
  125038. };
  125039. static static_codebook _16c2_s_p3_0 = {
  125040. 2, 81,
  125041. _vq_lengthlist__16c2_s_p3_0,
  125042. 1, -531628032, 1611661312, 4, 0,
  125043. _vq_quantlist__16c2_s_p3_0,
  125044. NULL,
  125045. &_vq_auxt__16c2_s_p3_0,
  125046. NULL,
  125047. 0
  125048. };
  125049. static long _vq_quantlist__16c2_s_p4_0[] = {
  125050. 8,
  125051. 7,
  125052. 9,
  125053. 6,
  125054. 10,
  125055. 5,
  125056. 11,
  125057. 4,
  125058. 12,
  125059. 3,
  125060. 13,
  125061. 2,
  125062. 14,
  125063. 1,
  125064. 15,
  125065. 0,
  125066. 16,
  125067. };
  125068. static long _vq_lengthlist__16c2_s_p4_0[] = {
  125069. 2, 3, 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,
  125070. 10, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  125071. 11,11, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  125072. 10,10,11, 0, 0, 0, 6, 6, 8, 8, 8, 8, 9, 9,10,10,
  125073. 10,11,11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,
  125074. 10,11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,
  125075. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9,
  125076. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  125077. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  125078. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  125079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125087. 0,
  125088. };
  125089. static float _vq_quantthresh__16c2_s_p4_0[] = {
  125090. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  125091. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  125092. };
  125093. static long _vq_quantmap__16c2_s_p4_0[] = {
  125094. 15, 13, 11, 9, 7, 5, 3, 1,
  125095. 0, 2, 4, 6, 8, 10, 12, 14,
  125096. 16,
  125097. };
  125098. static encode_aux_threshmatch _vq_auxt__16c2_s_p4_0 = {
  125099. _vq_quantthresh__16c2_s_p4_0,
  125100. _vq_quantmap__16c2_s_p4_0,
  125101. 17,
  125102. 17
  125103. };
  125104. static static_codebook _16c2_s_p4_0 = {
  125105. 2, 289,
  125106. _vq_lengthlist__16c2_s_p4_0,
  125107. 1, -529530880, 1611661312, 5, 0,
  125108. _vq_quantlist__16c2_s_p4_0,
  125109. NULL,
  125110. &_vq_auxt__16c2_s_p4_0,
  125111. NULL,
  125112. 0
  125113. };
  125114. static long _vq_quantlist__16c2_s_p5_0[] = {
  125115. 1,
  125116. 0,
  125117. 2,
  125118. };
  125119. static long _vq_lengthlist__16c2_s_p5_0[] = {
  125120. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6,10,10,10,10,
  125121. 10,10, 4, 7, 6,10,10,10,10,10,10, 5, 9, 9, 9,12,
  125122. 11,10,11,12, 7,10,10,12,12,12,12,12,12, 7,10,10,
  125123. 11,12,12,12,12,13, 6,10,10,10,12,12,10,12,12, 7,
  125124. 10,10,11,13,12,12,12,12, 7,10,10,11,12,12,12,12,
  125125. 12,
  125126. };
  125127. static float _vq_quantthresh__16c2_s_p5_0[] = {
  125128. -5.5, 5.5,
  125129. };
  125130. static long _vq_quantmap__16c2_s_p5_0[] = {
  125131. 1, 0, 2,
  125132. };
  125133. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_0 = {
  125134. _vq_quantthresh__16c2_s_p5_0,
  125135. _vq_quantmap__16c2_s_p5_0,
  125136. 3,
  125137. 3
  125138. };
  125139. static static_codebook _16c2_s_p5_0 = {
  125140. 4, 81,
  125141. _vq_lengthlist__16c2_s_p5_0,
  125142. 1, -529137664, 1618345984, 2, 0,
  125143. _vq_quantlist__16c2_s_p5_0,
  125144. NULL,
  125145. &_vq_auxt__16c2_s_p5_0,
  125146. NULL,
  125147. 0
  125148. };
  125149. static long _vq_quantlist__16c2_s_p5_1[] = {
  125150. 5,
  125151. 4,
  125152. 6,
  125153. 3,
  125154. 7,
  125155. 2,
  125156. 8,
  125157. 1,
  125158. 9,
  125159. 0,
  125160. 10,
  125161. };
  125162. static long _vq_lengthlist__16c2_s_p5_1[] = {
  125163. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11, 6, 6,
  125164. 7, 7, 8, 8, 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8,
  125165. 8,11,11,11, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  125166. 6, 8, 8, 8, 8, 9, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  125167. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 9,11,11,11,
  125168. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,11,11, 8, 8, 8,
  125169. 8, 8, 8,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  125170. 11,11,11, 7, 7, 8, 8, 8, 8,
  125171. };
  125172. static float _vq_quantthresh__16c2_s_p5_1[] = {
  125173. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125174. 3.5, 4.5,
  125175. };
  125176. static long _vq_quantmap__16c2_s_p5_1[] = {
  125177. 9, 7, 5, 3, 1, 0, 2, 4,
  125178. 6, 8, 10,
  125179. };
  125180. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_1 = {
  125181. _vq_quantthresh__16c2_s_p5_1,
  125182. _vq_quantmap__16c2_s_p5_1,
  125183. 11,
  125184. 11
  125185. };
  125186. static static_codebook _16c2_s_p5_1 = {
  125187. 2, 121,
  125188. _vq_lengthlist__16c2_s_p5_1,
  125189. 1, -531365888, 1611661312, 4, 0,
  125190. _vq_quantlist__16c2_s_p5_1,
  125191. NULL,
  125192. &_vq_auxt__16c2_s_p5_1,
  125193. NULL,
  125194. 0
  125195. };
  125196. static long _vq_quantlist__16c2_s_p6_0[] = {
  125197. 6,
  125198. 5,
  125199. 7,
  125200. 4,
  125201. 8,
  125202. 3,
  125203. 9,
  125204. 2,
  125205. 10,
  125206. 1,
  125207. 11,
  125208. 0,
  125209. 12,
  125210. };
  125211. static long _vq_lengthlist__16c2_s_p6_0[] = {
  125212. 1, 4, 4, 7, 6, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  125213. 7, 7, 9, 9, 9, 9,11,11,12,12, 6, 5, 5, 7, 7, 9,
  125214. 9,10,10,11,11,12,12, 0, 6, 6, 7, 7, 9, 9,10,10,
  125215. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,12,12,
  125216. 12, 0,11,11, 8, 8,10,10,11,11,12,12,13,13, 0,11,
  125217. 12, 8, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  125218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125222. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125223. };
  125224. static float _vq_quantthresh__16c2_s_p6_0[] = {
  125225. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  125226. 12.5, 17.5, 22.5, 27.5,
  125227. };
  125228. static long _vq_quantmap__16c2_s_p6_0[] = {
  125229. 11, 9, 7, 5, 3, 1, 0, 2,
  125230. 4, 6, 8, 10, 12,
  125231. };
  125232. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_0 = {
  125233. _vq_quantthresh__16c2_s_p6_0,
  125234. _vq_quantmap__16c2_s_p6_0,
  125235. 13,
  125236. 13
  125237. };
  125238. static static_codebook _16c2_s_p6_0 = {
  125239. 2, 169,
  125240. _vq_lengthlist__16c2_s_p6_0,
  125241. 1, -526516224, 1616117760, 4, 0,
  125242. _vq_quantlist__16c2_s_p6_0,
  125243. NULL,
  125244. &_vq_auxt__16c2_s_p6_0,
  125245. NULL,
  125246. 0
  125247. };
  125248. static long _vq_quantlist__16c2_s_p6_1[] = {
  125249. 2,
  125250. 1,
  125251. 3,
  125252. 0,
  125253. 4,
  125254. };
  125255. static long _vq_lengthlist__16c2_s_p6_1[] = {
  125256. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  125257. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  125258. };
  125259. static float _vq_quantthresh__16c2_s_p6_1[] = {
  125260. -1.5, -0.5, 0.5, 1.5,
  125261. };
  125262. static long _vq_quantmap__16c2_s_p6_1[] = {
  125263. 3, 1, 0, 2, 4,
  125264. };
  125265. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_1 = {
  125266. _vq_quantthresh__16c2_s_p6_1,
  125267. _vq_quantmap__16c2_s_p6_1,
  125268. 5,
  125269. 5
  125270. };
  125271. static static_codebook _16c2_s_p6_1 = {
  125272. 2, 25,
  125273. _vq_lengthlist__16c2_s_p6_1,
  125274. 1, -533725184, 1611661312, 3, 0,
  125275. _vq_quantlist__16c2_s_p6_1,
  125276. NULL,
  125277. &_vq_auxt__16c2_s_p6_1,
  125278. NULL,
  125279. 0
  125280. };
  125281. static long _vq_quantlist__16c2_s_p7_0[] = {
  125282. 6,
  125283. 5,
  125284. 7,
  125285. 4,
  125286. 8,
  125287. 3,
  125288. 9,
  125289. 2,
  125290. 10,
  125291. 1,
  125292. 11,
  125293. 0,
  125294. 12,
  125295. };
  125296. static long _vq_lengthlist__16c2_s_p7_0[] = {
  125297. 1, 4, 4, 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  125298. 8, 8, 9, 9,10,10,11,11,12,12, 6, 5, 5, 8, 8, 9,
  125299. 9,10,10,11,11,12,13,18, 6, 6, 7, 7, 9, 9,10,10,
  125300. 12,12,13,13,18, 6, 6, 7, 7, 9, 9,10,10,12,12,13,
  125301. 13,18,11,10, 8, 8,10,10,11,11,12,12,13,13,18,11,
  125302. 11, 8, 8,10,10,11,11,12,13,13,13,18,18,18,10,11,
  125303. 11,11,12,12,13,13,14,14,18,18,18,11,11,11,11,12,
  125304. 12,13,13,14,14,18,18,18,14,14,12,12,12,12,14,14,
  125305. 15,14,18,18,18,15,15,11,12,12,12,13,13,15,15,18,
  125306. 18,18,18,18,13,13,13,13,13,14,17,16,18,18,18,18,
  125307. 18,13,14,13,13,14,13,15,14,
  125308. };
  125309. static float _vq_quantthresh__16c2_s_p7_0[] = {
  125310. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  125311. 27.5, 38.5, 49.5, 60.5,
  125312. };
  125313. static long _vq_quantmap__16c2_s_p7_0[] = {
  125314. 11, 9, 7, 5, 3, 1, 0, 2,
  125315. 4, 6, 8, 10, 12,
  125316. };
  125317. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_0 = {
  125318. _vq_quantthresh__16c2_s_p7_0,
  125319. _vq_quantmap__16c2_s_p7_0,
  125320. 13,
  125321. 13
  125322. };
  125323. static static_codebook _16c2_s_p7_0 = {
  125324. 2, 169,
  125325. _vq_lengthlist__16c2_s_p7_0,
  125326. 1, -523206656, 1618345984, 4, 0,
  125327. _vq_quantlist__16c2_s_p7_0,
  125328. NULL,
  125329. &_vq_auxt__16c2_s_p7_0,
  125330. NULL,
  125331. 0
  125332. };
  125333. static long _vq_quantlist__16c2_s_p7_1[] = {
  125334. 5,
  125335. 4,
  125336. 6,
  125337. 3,
  125338. 7,
  125339. 2,
  125340. 8,
  125341. 1,
  125342. 9,
  125343. 0,
  125344. 10,
  125345. };
  125346. static long _vq_lengthlist__16c2_s_p7_1[] = {
  125347. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 9, 9, 6, 6,
  125348. 7, 7, 8, 8, 8, 8, 9, 9, 9, 6, 6, 7, 7, 8, 8, 8,
  125349. 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7,
  125350. 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  125351. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  125352. 7, 7, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 9, 7, 7, 7,
  125353. 7, 8, 8, 9, 9, 9, 9, 9, 8, 8, 7, 7, 8, 8, 9, 9,
  125354. 9, 9, 9, 7, 7, 7, 7, 8, 8,
  125355. };
  125356. static float _vq_quantthresh__16c2_s_p7_1[] = {
  125357. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125358. 3.5, 4.5,
  125359. };
  125360. static long _vq_quantmap__16c2_s_p7_1[] = {
  125361. 9, 7, 5, 3, 1, 0, 2, 4,
  125362. 6, 8, 10,
  125363. };
  125364. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_1 = {
  125365. _vq_quantthresh__16c2_s_p7_1,
  125366. _vq_quantmap__16c2_s_p7_1,
  125367. 11,
  125368. 11
  125369. };
  125370. static static_codebook _16c2_s_p7_1 = {
  125371. 2, 121,
  125372. _vq_lengthlist__16c2_s_p7_1,
  125373. 1, -531365888, 1611661312, 4, 0,
  125374. _vq_quantlist__16c2_s_p7_1,
  125375. NULL,
  125376. &_vq_auxt__16c2_s_p7_1,
  125377. NULL,
  125378. 0
  125379. };
  125380. static long _vq_quantlist__16c2_s_p8_0[] = {
  125381. 7,
  125382. 6,
  125383. 8,
  125384. 5,
  125385. 9,
  125386. 4,
  125387. 10,
  125388. 3,
  125389. 11,
  125390. 2,
  125391. 12,
  125392. 1,
  125393. 13,
  125394. 0,
  125395. 14,
  125396. };
  125397. static long _vq_lengthlist__16c2_s_p8_0[] = {
  125398. 1, 4, 4, 7, 6, 7, 7, 6, 6, 8, 8, 9, 9,10,10, 6,
  125399. 6, 6, 8, 8, 9, 8, 8, 8, 9, 9,11,10,11,11, 7, 6,
  125400. 6, 8, 8, 9, 8, 7, 7, 9, 9,10,10,12,11,14, 8, 8,
  125401. 8, 9, 9, 9, 9, 9,10, 9,10,10,11,13,14, 8, 8, 8,
  125402. 8, 9, 9, 8, 8, 9, 9,10,10,11,12,14,13,11, 9, 9,
  125403. 9, 9, 9, 9, 9,10,11,10,13,12,14,11,13, 8, 9, 9,
  125404. 9, 9, 9,10,10,11,10,13,12,14,14,14, 8, 9, 9, 9,
  125405. 11,11,11,11,11,12,13,13,14,14,14, 9, 8, 9, 9,10,
  125406. 10,12,10,11,12,12,14,14,14,14,11,12,10,10,12,12,
  125407. 12,12,13,14,12,12,14,14,14,12,12, 9,10,11,11,12,
  125408. 14,12,14,14,14,14,14,14,14,14,11,11,12,11,12,14,
  125409. 14,14,14,14,14,14,14,14,14,12,11,11,11,11,14,14,
  125410. 14,14,14,14,14,14,14,14,14,14,13,12,14,14,14,14,
  125411. 14,14,14,14,14,14,14,14,14,12,12,12,13,14,14,13,
  125412. 13,
  125413. };
  125414. static float _vq_quantthresh__16c2_s_p8_0[] = {
  125415. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  125416. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  125417. };
  125418. static long _vq_quantmap__16c2_s_p8_0[] = {
  125419. 13, 11, 9, 7, 5, 3, 1, 0,
  125420. 2, 4, 6, 8, 10, 12, 14,
  125421. };
  125422. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_0 = {
  125423. _vq_quantthresh__16c2_s_p8_0,
  125424. _vq_quantmap__16c2_s_p8_0,
  125425. 15,
  125426. 15
  125427. };
  125428. static static_codebook _16c2_s_p8_0 = {
  125429. 2, 225,
  125430. _vq_lengthlist__16c2_s_p8_0,
  125431. 1, -520986624, 1620377600, 4, 0,
  125432. _vq_quantlist__16c2_s_p8_0,
  125433. NULL,
  125434. &_vq_auxt__16c2_s_p8_0,
  125435. NULL,
  125436. 0
  125437. };
  125438. static long _vq_quantlist__16c2_s_p8_1[] = {
  125439. 10,
  125440. 9,
  125441. 11,
  125442. 8,
  125443. 12,
  125444. 7,
  125445. 13,
  125446. 6,
  125447. 14,
  125448. 5,
  125449. 15,
  125450. 4,
  125451. 16,
  125452. 3,
  125453. 17,
  125454. 2,
  125455. 18,
  125456. 1,
  125457. 19,
  125458. 0,
  125459. 20,
  125460. };
  125461. static long _vq_lengthlist__16c2_s_p8_1[] = {
  125462. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  125463. 8, 8, 8, 8, 8,11,12,11, 7, 7, 8, 8, 8, 8, 9, 9,
  125464. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,11,11,10, 7, 7, 8,
  125465. 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  125466. 11,11, 8, 7, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 9,10,
  125467. 10, 9,10,10,11,11,12, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  125468. 9, 9, 9,10, 9,10,10,10,10,11,11,11, 8, 8, 9, 9,
  125469. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  125470. 11, 8, 8, 9, 8, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,
  125471. 10, 9,10,11,11,11, 9, 9, 9, 9,10, 9, 9, 9,10,10,
  125472. 9,10, 9,10,10,10,10,10,11,12,11,11,11, 9, 9, 9,
  125473. 9, 9,10,10, 9,10,10,10,10,10,10,10,10,12,11,13,
  125474. 13,11, 9, 9, 9, 9,10,10, 9,10,10,10,10,11,10,10,
  125475. 10,10,11,12,11,12,11, 9, 9, 9,10,10, 9,10,10,10,
  125476. 10,10,10,10,10,10,10,11,11,11,12,11, 9,10,10,10,
  125477. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,12,12,
  125478. 11,11,11,10, 9,10,10,10,10,10,10,10,10,11,10,10,
  125479. 10,11,11,11,11,11,11,11,10,10,10,11,10,10,10,10,
  125480. 10,10,10,10,10,10,11,11,11,11,12,12,11,10,10,10,
  125481. 10,10,10,10,10,11,10,10,10,11,10,12,11,11,12,11,
  125482. 11,11,10,10,10,10,10,11,10,10,10,10,10,11,10,10,
  125483. 11,11,11,12,11,12,11,11,12,10,10,10,10,10,10,10,
  125484. 11,10,10,11,10,12,11,11,11,12,11,11,11,11,10,10,
  125485. 10,10,10,10,10,11,11,11,10,11,12,11,11,11,12,11,
  125486. 12,11,12,10,11,10,10,10,10,11,10,10,10,10,10,10,
  125487. 12,11,11,11,11,11,12,12,10,10,10,10,10,11,10,10,
  125488. 11,10,11,11,11,11,11,11,11,11,11,11,11,11,12,11,
  125489. 10,11,10,10,10,10,10,10,10,
  125490. };
  125491. static float _vq_quantthresh__16c2_s_p8_1[] = {
  125492. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  125493. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  125494. 6.5, 7.5, 8.5, 9.5,
  125495. };
  125496. static long _vq_quantmap__16c2_s_p8_1[] = {
  125497. 19, 17, 15, 13, 11, 9, 7, 5,
  125498. 3, 1, 0, 2, 4, 6, 8, 10,
  125499. 12, 14, 16, 18, 20,
  125500. };
  125501. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_1 = {
  125502. _vq_quantthresh__16c2_s_p8_1,
  125503. _vq_quantmap__16c2_s_p8_1,
  125504. 21,
  125505. 21
  125506. };
  125507. static static_codebook _16c2_s_p8_1 = {
  125508. 2, 441,
  125509. _vq_lengthlist__16c2_s_p8_1,
  125510. 1, -529268736, 1611661312, 5, 0,
  125511. _vq_quantlist__16c2_s_p8_1,
  125512. NULL,
  125513. &_vq_auxt__16c2_s_p8_1,
  125514. NULL,
  125515. 0
  125516. };
  125517. static long _vq_quantlist__16c2_s_p9_0[] = {
  125518. 6,
  125519. 5,
  125520. 7,
  125521. 4,
  125522. 8,
  125523. 3,
  125524. 9,
  125525. 2,
  125526. 10,
  125527. 1,
  125528. 11,
  125529. 0,
  125530. 12,
  125531. };
  125532. static long _vq_lengthlist__16c2_s_p9_0[] = {
  125533. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125534. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125535. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125536. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125537. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125538. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125539. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125540. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125541. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125542. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125543. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125544. };
  125545. static float _vq_quantthresh__16c2_s_p9_0[] = {
  125546. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5,
  125547. 2327.5, 3258.5, 4189.5, 5120.5,
  125548. };
  125549. static long _vq_quantmap__16c2_s_p9_0[] = {
  125550. 11, 9, 7, 5, 3, 1, 0, 2,
  125551. 4, 6, 8, 10, 12,
  125552. };
  125553. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_0 = {
  125554. _vq_quantthresh__16c2_s_p9_0,
  125555. _vq_quantmap__16c2_s_p9_0,
  125556. 13,
  125557. 13
  125558. };
  125559. static static_codebook _16c2_s_p9_0 = {
  125560. 2, 169,
  125561. _vq_lengthlist__16c2_s_p9_0,
  125562. 1, -510275072, 1631393792, 4, 0,
  125563. _vq_quantlist__16c2_s_p9_0,
  125564. NULL,
  125565. &_vq_auxt__16c2_s_p9_0,
  125566. NULL,
  125567. 0
  125568. };
  125569. static long _vq_quantlist__16c2_s_p9_1[] = {
  125570. 8,
  125571. 7,
  125572. 9,
  125573. 6,
  125574. 10,
  125575. 5,
  125576. 11,
  125577. 4,
  125578. 12,
  125579. 3,
  125580. 13,
  125581. 2,
  125582. 14,
  125583. 1,
  125584. 15,
  125585. 0,
  125586. 16,
  125587. };
  125588. static long _vq_lengthlist__16c2_s_p9_1[] = {
  125589. 1, 5, 5, 9, 8, 7, 7, 7, 6,10,11,11,11,11,11,11,
  125590. 11, 8, 7, 6, 8, 8,10, 9,10,10,10, 9,11,10,10,10,
  125591. 10,10, 8, 6, 6, 8, 8, 9, 8, 9, 8, 9,10,10,10,10,
  125592. 10,10,10,10, 8,10, 9, 9, 9, 9,10,10,10,10,10,10,
  125593. 10,10,10,10,10, 8, 9, 9, 9,10,10, 9,10,10,10,10,
  125594. 10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,10,10,10,
  125595. 10,10,10,10,10,10,10,10, 9, 8, 8, 9, 9,10,10,10,
  125596. 10,10,10,10,10,10,10,10,10,10, 9,10, 9, 9,10,10,
  125597. 10,10,10,10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,
  125598. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  125599. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125600. 8,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125601. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125602. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125603. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125604. 10,10,10,10, 9,10, 9,10,10,10,10,10,10,10,10,10,
  125605. 10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,
  125606. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125607. 10,
  125608. };
  125609. static float _vq_quantthresh__16c2_s_p9_1[] = {
  125610. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -24.5,
  125611. 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5, 367.5,
  125612. };
  125613. static long _vq_quantmap__16c2_s_p9_1[] = {
  125614. 15, 13, 11, 9, 7, 5, 3, 1,
  125615. 0, 2, 4, 6, 8, 10, 12, 14,
  125616. 16,
  125617. };
  125618. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_1 = {
  125619. _vq_quantthresh__16c2_s_p9_1,
  125620. _vq_quantmap__16c2_s_p9_1,
  125621. 17,
  125622. 17
  125623. };
  125624. static static_codebook _16c2_s_p9_1 = {
  125625. 2, 289,
  125626. _vq_lengthlist__16c2_s_p9_1,
  125627. 1, -518488064, 1622704128, 5, 0,
  125628. _vq_quantlist__16c2_s_p9_1,
  125629. NULL,
  125630. &_vq_auxt__16c2_s_p9_1,
  125631. NULL,
  125632. 0
  125633. };
  125634. static long _vq_quantlist__16c2_s_p9_2[] = {
  125635. 13,
  125636. 12,
  125637. 14,
  125638. 11,
  125639. 15,
  125640. 10,
  125641. 16,
  125642. 9,
  125643. 17,
  125644. 8,
  125645. 18,
  125646. 7,
  125647. 19,
  125648. 6,
  125649. 20,
  125650. 5,
  125651. 21,
  125652. 4,
  125653. 22,
  125654. 3,
  125655. 23,
  125656. 2,
  125657. 24,
  125658. 1,
  125659. 25,
  125660. 0,
  125661. 26,
  125662. };
  125663. static long _vq_lengthlist__16c2_s_p9_2[] = {
  125664. 1, 4, 4, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  125665. 7, 7, 7, 7, 8, 7, 8, 7, 7, 4, 4,
  125666. };
  125667. static float _vq_quantthresh__16c2_s_p9_2[] = {
  125668. -12.5, -11.5, -10.5, -9.5, -8.5, -7.5, -6.5, -5.5,
  125669. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125670. 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5,
  125671. 11.5, 12.5,
  125672. };
  125673. static long _vq_quantmap__16c2_s_p9_2[] = {
  125674. 25, 23, 21, 19, 17, 15, 13, 11,
  125675. 9, 7, 5, 3, 1, 0, 2, 4,
  125676. 6, 8, 10, 12, 14, 16, 18, 20,
  125677. 22, 24, 26,
  125678. };
  125679. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_2 = {
  125680. _vq_quantthresh__16c2_s_p9_2,
  125681. _vq_quantmap__16c2_s_p9_2,
  125682. 27,
  125683. 27
  125684. };
  125685. static static_codebook _16c2_s_p9_2 = {
  125686. 1, 27,
  125687. _vq_lengthlist__16c2_s_p9_2,
  125688. 1, -528875520, 1611661312, 5, 0,
  125689. _vq_quantlist__16c2_s_p9_2,
  125690. NULL,
  125691. &_vq_auxt__16c2_s_p9_2,
  125692. NULL,
  125693. 0
  125694. };
  125695. static long _huff_lengthlist__16c2_s_short[] = {
  125696. 7,10,11,11,11,14,15,15,17,14, 8, 6, 7, 7, 8, 9,
  125697. 11,11,14,17, 9, 6, 6, 6, 7, 7,10,11,15,16, 9, 6,
  125698. 6, 4, 4, 5, 8, 9,12,16,10, 6, 6, 4, 4, 4, 6, 9,
  125699. 13,16,10, 7, 6, 5, 4, 3, 5, 7,13,16,11, 9, 8, 7,
  125700. 6, 5, 5, 6,12,15,10,10,10, 9, 7, 6, 6, 7,11,15,
  125701. 13,13,13,13,11,10,10, 9,12,16,16,16,16,14,16,15,
  125702. 15,12,14,14,
  125703. };
  125704. static static_codebook _huff_book__16c2_s_short = {
  125705. 2, 100,
  125706. _huff_lengthlist__16c2_s_short,
  125707. 0, 0, 0, 0, 0,
  125708. NULL,
  125709. NULL,
  125710. NULL,
  125711. NULL,
  125712. 0
  125713. };
  125714. static long _vq_quantlist__8c0_s_p1_0[] = {
  125715. 1,
  125716. 0,
  125717. 2,
  125718. };
  125719. static long _vq_lengthlist__8c0_s_p1_0[] = {
  125720. 1, 5, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  125721. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125725. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  125726. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125730. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  125731. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 8, 0, 0, 0, 0,
  125766. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  125767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0, 0,
  125771. 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  125772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9,10, 0, 0,
  125776. 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  125777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  125812. 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  125817. 0, 0, 0, 0, 0, 9,10,11, 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, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  125822. 0, 0, 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 0,
  125823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126130. 0,
  126131. };
  126132. static float _vq_quantthresh__8c0_s_p1_0[] = {
  126133. -0.5, 0.5,
  126134. };
  126135. static long _vq_quantmap__8c0_s_p1_0[] = {
  126136. 1, 0, 2,
  126137. };
  126138. static encode_aux_threshmatch _vq_auxt__8c0_s_p1_0 = {
  126139. _vq_quantthresh__8c0_s_p1_0,
  126140. _vq_quantmap__8c0_s_p1_0,
  126141. 3,
  126142. 3
  126143. };
  126144. static static_codebook _8c0_s_p1_0 = {
  126145. 8, 6561,
  126146. _vq_lengthlist__8c0_s_p1_0,
  126147. 1, -535822336, 1611661312, 2, 0,
  126148. _vq_quantlist__8c0_s_p1_0,
  126149. NULL,
  126150. &_vq_auxt__8c0_s_p1_0,
  126151. NULL,
  126152. 0
  126153. };
  126154. static long _vq_quantlist__8c0_s_p2_0[] = {
  126155. 2,
  126156. 1,
  126157. 3,
  126158. 0,
  126159. 4,
  126160. };
  126161. static long _vq_lengthlist__8c0_s_p2_0[] = {
  126162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126201. 0,
  126202. };
  126203. static float _vq_quantthresh__8c0_s_p2_0[] = {
  126204. -1.5, -0.5, 0.5, 1.5,
  126205. };
  126206. static long _vq_quantmap__8c0_s_p2_0[] = {
  126207. 3, 1, 0, 2, 4,
  126208. };
  126209. static encode_aux_threshmatch _vq_auxt__8c0_s_p2_0 = {
  126210. _vq_quantthresh__8c0_s_p2_0,
  126211. _vq_quantmap__8c0_s_p2_0,
  126212. 5,
  126213. 5
  126214. };
  126215. static static_codebook _8c0_s_p2_0 = {
  126216. 4, 625,
  126217. _vq_lengthlist__8c0_s_p2_0,
  126218. 1, -533725184, 1611661312, 3, 0,
  126219. _vq_quantlist__8c0_s_p2_0,
  126220. NULL,
  126221. &_vq_auxt__8c0_s_p2_0,
  126222. NULL,
  126223. 0
  126224. };
  126225. static long _vq_quantlist__8c0_s_p3_0[] = {
  126226. 2,
  126227. 1,
  126228. 3,
  126229. 0,
  126230. 4,
  126231. };
  126232. static long _vq_lengthlist__8c0_s_p3_0[] = {
  126233. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 6, 7, 7, 0, 0,
  126235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126236. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 8, 8,
  126238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126239. 0, 0, 0, 0, 6, 7, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  126240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126272. 0,
  126273. };
  126274. static float _vq_quantthresh__8c0_s_p3_0[] = {
  126275. -1.5, -0.5, 0.5, 1.5,
  126276. };
  126277. static long _vq_quantmap__8c0_s_p3_0[] = {
  126278. 3, 1, 0, 2, 4,
  126279. };
  126280. static encode_aux_threshmatch _vq_auxt__8c0_s_p3_0 = {
  126281. _vq_quantthresh__8c0_s_p3_0,
  126282. _vq_quantmap__8c0_s_p3_0,
  126283. 5,
  126284. 5
  126285. };
  126286. static static_codebook _8c0_s_p3_0 = {
  126287. 4, 625,
  126288. _vq_lengthlist__8c0_s_p3_0,
  126289. 1, -533725184, 1611661312, 3, 0,
  126290. _vq_quantlist__8c0_s_p3_0,
  126291. NULL,
  126292. &_vq_auxt__8c0_s_p3_0,
  126293. NULL,
  126294. 0
  126295. };
  126296. static long _vq_quantlist__8c0_s_p4_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_p4_0[] = {
  126308. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  126309. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  126310. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  126311. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  126312. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126313. 0,
  126314. };
  126315. static float _vq_quantthresh__8c0_s_p4_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_p4_0[] = {
  126319. 7, 5, 3, 1, 0, 2, 4, 6,
  126320. 8,
  126321. };
  126322. static encode_aux_threshmatch _vq_auxt__8c0_s_p4_0 = {
  126323. _vq_quantthresh__8c0_s_p4_0,
  126324. _vq_quantmap__8c0_s_p4_0,
  126325. 9,
  126326. 9
  126327. };
  126328. static static_codebook _8c0_s_p4_0 = {
  126329. 2, 81,
  126330. _vq_lengthlist__8c0_s_p4_0,
  126331. 1, -531628032, 1611661312, 4, 0,
  126332. _vq_quantlist__8c0_s_p4_0,
  126333. NULL,
  126334. &_vq_auxt__8c0_s_p4_0,
  126335. NULL,
  126336. 0
  126337. };
  126338. static long _vq_quantlist__8c0_s_p5_0[] = {
  126339. 4,
  126340. 3,
  126341. 5,
  126342. 2,
  126343. 6,
  126344. 1,
  126345. 7,
  126346. 0,
  126347. 8,
  126348. };
  126349. static long _vq_lengthlist__8c0_s_p5_0[] = {
  126350. 1, 3, 3, 5, 5, 7, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  126351. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 9, 0, 0, 0, 8, 8,
  126352. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8, 9, 9, 0, 0, 0,
  126353. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  126354. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  126355. 10,
  126356. };
  126357. static float _vq_quantthresh__8c0_s_p5_0[] = {
  126358. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126359. };
  126360. static long _vq_quantmap__8c0_s_p5_0[] = {
  126361. 7, 5, 3, 1, 0, 2, 4, 6,
  126362. 8,
  126363. };
  126364. static encode_aux_threshmatch _vq_auxt__8c0_s_p5_0 = {
  126365. _vq_quantthresh__8c0_s_p5_0,
  126366. _vq_quantmap__8c0_s_p5_0,
  126367. 9,
  126368. 9
  126369. };
  126370. static static_codebook _8c0_s_p5_0 = {
  126371. 2, 81,
  126372. _vq_lengthlist__8c0_s_p5_0,
  126373. 1, -531628032, 1611661312, 4, 0,
  126374. _vq_quantlist__8c0_s_p5_0,
  126375. NULL,
  126376. &_vq_auxt__8c0_s_p5_0,
  126377. NULL,
  126378. 0
  126379. };
  126380. static long _vq_quantlist__8c0_s_p6_0[] = {
  126381. 8,
  126382. 7,
  126383. 9,
  126384. 6,
  126385. 10,
  126386. 5,
  126387. 11,
  126388. 4,
  126389. 12,
  126390. 3,
  126391. 13,
  126392. 2,
  126393. 14,
  126394. 1,
  126395. 15,
  126396. 0,
  126397. 16,
  126398. };
  126399. static long _vq_lengthlist__8c0_s_p6_0[] = {
  126400. 1, 3, 3, 6, 6, 8, 8, 9, 9, 8, 8,10, 9,10,10,11,
  126401. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  126402. 11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  126403. 11,12,11, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,10,10,
  126404. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,11,
  126405. 10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,10,
  126406. 11,11,11,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,
  126407. 10,11,11,12,12,13,13, 0, 0, 0,10,10,10,10,11,11,
  126408. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10, 9,10,
  126409. 11,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  126410. 10, 9,10,11,12,12,13,13,14,13, 0, 0, 0, 0, 0, 9,
  126411. 9, 9,10,10,10,11,11,13,12,13,13, 0, 0, 0, 0, 0,
  126412. 10,10,10,10,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  126413. 0, 0, 0,10,10,11,11,12,12,13,13,13,14, 0, 0, 0,
  126414. 0, 0, 0, 0,11,11,11,11,12,12,13,14,14,14, 0, 0,
  126415. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,14,13, 0,
  126416. 0, 0, 0, 0, 0, 0,11,11,12,12,13,13,14,14,14,14,
  126417. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  126418. 14,
  126419. };
  126420. static float _vq_quantthresh__8c0_s_p6_0[] = {
  126421. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  126422. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  126423. };
  126424. static long _vq_quantmap__8c0_s_p6_0[] = {
  126425. 15, 13, 11, 9, 7, 5, 3, 1,
  126426. 0, 2, 4, 6, 8, 10, 12, 14,
  126427. 16,
  126428. };
  126429. static encode_aux_threshmatch _vq_auxt__8c0_s_p6_0 = {
  126430. _vq_quantthresh__8c0_s_p6_0,
  126431. _vq_quantmap__8c0_s_p6_0,
  126432. 17,
  126433. 17
  126434. };
  126435. static static_codebook _8c0_s_p6_0 = {
  126436. 2, 289,
  126437. _vq_lengthlist__8c0_s_p6_0,
  126438. 1, -529530880, 1611661312, 5, 0,
  126439. _vq_quantlist__8c0_s_p6_0,
  126440. NULL,
  126441. &_vq_auxt__8c0_s_p6_0,
  126442. NULL,
  126443. 0
  126444. };
  126445. static long _vq_quantlist__8c0_s_p7_0[] = {
  126446. 1,
  126447. 0,
  126448. 2,
  126449. };
  126450. static long _vq_lengthlist__8c0_s_p7_0[] = {
  126451. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,11, 9,10,12,
  126452. 9,10, 4, 7, 7,10,10,10,11, 9, 9, 6,11,10,11,11,
  126453. 12,11,11,11, 6,10,10,11,11,12,11,10,10, 6, 9,10,
  126454. 11,11,11,11,10,10, 7,10,11,12,11,11,12,11,12, 6,
  126455. 9, 9,10, 9, 9,11,10,10, 6, 9, 9,10,10,10,11,10,
  126456. 10,
  126457. };
  126458. static float _vq_quantthresh__8c0_s_p7_0[] = {
  126459. -5.5, 5.5,
  126460. };
  126461. static long _vq_quantmap__8c0_s_p7_0[] = {
  126462. 1, 0, 2,
  126463. };
  126464. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_0 = {
  126465. _vq_quantthresh__8c0_s_p7_0,
  126466. _vq_quantmap__8c0_s_p7_0,
  126467. 3,
  126468. 3
  126469. };
  126470. static static_codebook _8c0_s_p7_0 = {
  126471. 4, 81,
  126472. _vq_lengthlist__8c0_s_p7_0,
  126473. 1, -529137664, 1618345984, 2, 0,
  126474. _vq_quantlist__8c0_s_p7_0,
  126475. NULL,
  126476. &_vq_auxt__8c0_s_p7_0,
  126477. NULL,
  126478. 0
  126479. };
  126480. static long _vq_quantlist__8c0_s_p7_1[] = {
  126481. 5,
  126482. 4,
  126483. 6,
  126484. 3,
  126485. 7,
  126486. 2,
  126487. 8,
  126488. 1,
  126489. 9,
  126490. 0,
  126491. 10,
  126492. };
  126493. static long _vq_lengthlist__8c0_s_p7_1[] = {
  126494. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10, 7, 7,
  126495. 8, 8, 9, 9, 9, 9,10,10, 9, 7, 7, 8, 8, 9, 9, 9,
  126496. 9,10,10,10, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10, 8,
  126497. 8, 9, 9, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9,10,
  126498. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,11,10,11,
  126499. 9, 9, 9, 9,10,10,10,10,11,11,11,10,10, 9, 9,10,
  126500. 10,10, 9,11,10,10,10,10,10,10, 9, 9,10,10,11,11,
  126501. 10,10,10, 9, 9, 9,10,10,10,
  126502. };
  126503. static float _vq_quantthresh__8c0_s_p7_1[] = {
  126504. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  126505. 3.5, 4.5,
  126506. };
  126507. static long _vq_quantmap__8c0_s_p7_1[] = {
  126508. 9, 7, 5, 3, 1, 0, 2, 4,
  126509. 6, 8, 10,
  126510. };
  126511. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_1 = {
  126512. _vq_quantthresh__8c0_s_p7_1,
  126513. _vq_quantmap__8c0_s_p7_1,
  126514. 11,
  126515. 11
  126516. };
  126517. static static_codebook _8c0_s_p7_1 = {
  126518. 2, 121,
  126519. _vq_lengthlist__8c0_s_p7_1,
  126520. 1, -531365888, 1611661312, 4, 0,
  126521. _vq_quantlist__8c0_s_p7_1,
  126522. NULL,
  126523. &_vq_auxt__8c0_s_p7_1,
  126524. NULL,
  126525. 0
  126526. };
  126527. static long _vq_quantlist__8c0_s_p8_0[] = {
  126528. 6,
  126529. 5,
  126530. 7,
  126531. 4,
  126532. 8,
  126533. 3,
  126534. 9,
  126535. 2,
  126536. 10,
  126537. 1,
  126538. 11,
  126539. 0,
  126540. 12,
  126541. };
  126542. static long _vq_lengthlist__8c0_s_p8_0[] = {
  126543. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 6, 6,
  126544. 7, 7, 8, 8, 7, 7, 8, 9,10,10, 7, 6, 6, 7, 7, 8,
  126545. 7, 7, 7, 9, 9,10,12, 0, 8, 8, 8, 8, 8, 9, 8, 8,
  126546. 9, 9,10,10, 0, 8, 8, 8, 8, 8, 9, 8, 9, 9, 9,11,
  126547. 10, 0, 0,13, 9, 8, 9, 9, 9, 9,10,10,11,11, 0,13,
  126548. 0, 9, 9, 9, 9, 9, 9,11,10,11,11, 0, 0, 0, 8, 9,
  126549. 10, 9,10,10,13,11,12,12, 0, 0, 0, 8, 9, 9, 9,10,
  126550. 10,13,12,12,13, 0, 0, 0,12, 0,10,10,12,11,10,11,
  126551. 12,12, 0, 0, 0,13,13,10,10,10,11,12, 0,13, 0, 0,
  126552. 0, 0, 0, 0,13,11, 0,12,12,12,13,12, 0, 0, 0, 0,
  126553. 0, 0,13,13,11,13,13,11,12,
  126554. };
  126555. static float _vq_quantthresh__8c0_s_p8_0[] = {
  126556. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  126557. 12.5, 17.5, 22.5, 27.5,
  126558. };
  126559. static long _vq_quantmap__8c0_s_p8_0[] = {
  126560. 11, 9, 7, 5, 3, 1, 0, 2,
  126561. 4, 6, 8, 10, 12,
  126562. };
  126563. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_0 = {
  126564. _vq_quantthresh__8c0_s_p8_0,
  126565. _vq_quantmap__8c0_s_p8_0,
  126566. 13,
  126567. 13
  126568. };
  126569. static static_codebook _8c0_s_p8_0 = {
  126570. 2, 169,
  126571. _vq_lengthlist__8c0_s_p8_0,
  126572. 1, -526516224, 1616117760, 4, 0,
  126573. _vq_quantlist__8c0_s_p8_0,
  126574. NULL,
  126575. &_vq_auxt__8c0_s_p8_0,
  126576. NULL,
  126577. 0
  126578. };
  126579. static long _vq_quantlist__8c0_s_p8_1[] = {
  126580. 2,
  126581. 1,
  126582. 3,
  126583. 0,
  126584. 4,
  126585. };
  126586. static long _vq_lengthlist__8c0_s_p8_1[] = {
  126587. 1, 3, 4, 5, 5, 7, 6, 6, 6, 5, 7, 7, 7, 6, 6, 7,
  126588. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  126589. };
  126590. static float _vq_quantthresh__8c0_s_p8_1[] = {
  126591. -1.5, -0.5, 0.5, 1.5,
  126592. };
  126593. static long _vq_quantmap__8c0_s_p8_1[] = {
  126594. 3, 1, 0, 2, 4,
  126595. };
  126596. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_1 = {
  126597. _vq_quantthresh__8c0_s_p8_1,
  126598. _vq_quantmap__8c0_s_p8_1,
  126599. 5,
  126600. 5
  126601. };
  126602. static static_codebook _8c0_s_p8_1 = {
  126603. 2, 25,
  126604. _vq_lengthlist__8c0_s_p8_1,
  126605. 1, -533725184, 1611661312, 3, 0,
  126606. _vq_quantlist__8c0_s_p8_1,
  126607. NULL,
  126608. &_vq_auxt__8c0_s_p8_1,
  126609. NULL,
  126610. 0
  126611. };
  126612. static long _vq_quantlist__8c0_s_p9_0[] = {
  126613. 1,
  126614. 0,
  126615. 2,
  126616. };
  126617. static long _vq_lengthlist__8c0_s_p9_0[] = {
  126618. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  126619. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  126620. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126621. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126622. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126623. 7,
  126624. };
  126625. static float _vq_quantthresh__8c0_s_p9_0[] = {
  126626. -157.5, 157.5,
  126627. };
  126628. static long _vq_quantmap__8c0_s_p9_0[] = {
  126629. 1, 0, 2,
  126630. };
  126631. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_0 = {
  126632. _vq_quantthresh__8c0_s_p9_0,
  126633. _vq_quantmap__8c0_s_p9_0,
  126634. 3,
  126635. 3
  126636. };
  126637. static static_codebook _8c0_s_p9_0 = {
  126638. 4, 81,
  126639. _vq_lengthlist__8c0_s_p9_0,
  126640. 1, -518803456, 1628680192, 2, 0,
  126641. _vq_quantlist__8c0_s_p9_0,
  126642. NULL,
  126643. &_vq_auxt__8c0_s_p9_0,
  126644. NULL,
  126645. 0
  126646. };
  126647. static long _vq_quantlist__8c0_s_p9_1[] = {
  126648. 7,
  126649. 6,
  126650. 8,
  126651. 5,
  126652. 9,
  126653. 4,
  126654. 10,
  126655. 3,
  126656. 11,
  126657. 2,
  126658. 12,
  126659. 1,
  126660. 13,
  126661. 0,
  126662. 14,
  126663. };
  126664. static long _vq_lengthlist__8c0_s_p9_1[] = {
  126665. 1, 4, 4, 5, 5,10, 8,11,11,11,11,11,11,11,11, 6,
  126666. 6, 6, 7, 6,11,10,11,11,11,11,11,11,11,11, 7, 5,
  126667. 6, 6, 6, 8, 7,11,11,11,11,11,11,11,11,11, 7, 8,
  126668. 8, 8, 9, 9,11,11,11,11,11,11,11,11,11, 9, 8, 7,
  126669. 8, 9,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  126670. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  126671. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126672. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126673. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126674. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126675. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126676. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126677. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126678. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126679. 11,
  126680. };
  126681. static float _vq_quantthresh__8c0_s_p9_1[] = {
  126682. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  126683. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  126684. };
  126685. static long _vq_quantmap__8c0_s_p9_1[] = {
  126686. 13, 11, 9, 7, 5, 3, 1, 0,
  126687. 2, 4, 6, 8, 10, 12, 14,
  126688. };
  126689. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_1 = {
  126690. _vq_quantthresh__8c0_s_p9_1,
  126691. _vq_quantmap__8c0_s_p9_1,
  126692. 15,
  126693. 15
  126694. };
  126695. static static_codebook _8c0_s_p9_1 = {
  126696. 2, 225,
  126697. _vq_lengthlist__8c0_s_p9_1,
  126698. 1, -520986624, 1620377600, 4, 0,
  126699. _vq_quantlist__8c0_s_p9_1,
  126700. NULL,
  126701. &_vq_auxt__8c0_s_p9_1,
  126702. NULL,
  126703. 0
  126704. };
  126705. static long _vq_quantlist__8c0_s_p9_2[] = {
  126706. 10,
  126707. 9,
  126708. 11,
  126709. 8,
  126710. 12,
  126711. 7,
  126712. 13,
  126713. 6,
  126714. 14,
  126715. 5,
  126716. 15,
  126717. 4,
  126718. 16,
  126719. 3,
  126720. 17,
  126721. 2,
  126722. 18,
  126723. 1,
  126724. 19,
  126725. 0,
  126726. 20,
  126727. };
  126728. static long _vq_lengthlist__8c0_s_p9_2[] = {
  126729. 1, 5, 5, 7, 7, 8, 7, 8, 8,10,10, 9, 9,10,10,10,
  126730. 11,11,10,12,11,12,12,12, 9, 8, 8, 8, 8, 8, 9,10,
  126731. 10,10,10,11,11,11,10,11,11,12,12,11,12, 8, 8, 7,
  126732. 7, 8, 9,10,10,10, 9,10,10, 9,10,10,11,11,11,11,
  126733. 11,11, 9, 9, 9, 9, 8, 9,10,10,11,10,10,11,11,12,
  126734. 10,10,12,12,11,11,10, 9, 9,10, 8, 9,10,10,10, 9,
  126735. 10,10,11,11,10,11,10,10,10,12,12,12, 9,10, 9,10,
  126736. 9, 9,10,10,11,11,11,11,10,10,10,11,12,11,12,11,
  126737. 12,10,11,10,11, 9,10, 9,10, 9,10,10, 9,10,10,11,
  126738. 10,11,11,11,11,12,11, 9,10,10,10,10,11,11,11,11,
  126739. 11,10,11,11,11,11,10,12,10,12,12,11,12,10,10,11,
  126740. 10, 9,11,10,11, 9,10,11,10,10,10,11,11,11,11,12,
  126741. 12,10, 9, 9,11,10, 9,12,11,10,12,12,11,11,11,11,
  126742. 10,11,11,12,11,10,12, 9,11,10,11,10,10,11,10,11,
  126743. 9,10,10,10,11,12,11,11,12,11,10,10,11,11, 9,10,
  126744. 10,12,10,11,10,10,10, 9,10,10,10,10, 9,10,10,11,
  126745. 11,11,11,12,11,10,10,10,10,11,11,10,11,11, 9,11,
  126746. 10,12,10,12,11,10,11,10,10,10,11,10,10,11,11,10,
  126747. 11,10,10,10,10,11,11,12,10,10,10,11,10,11,12,11,
  126748. 10,11,10,10,11,11,10,12,10, 9,10,10,11,11,11,10,
  126749. 12,10,10,11,11,11,10,10,11,10,10,10,11,10,11,10,
  126750. 12,11,11,10,10,10,12,10,10,11, 9,10,11,11,11,10,
  126751. 10,11,10,10, 9,11,11,12,12,11,12,11,11,11,11,11,
  126752. 11, 9,10,11,10,12,10,10,10,10,11,10,10,11,10,10,
  126753. 12,10,10,10,10,10, 9,12,10,10,10,10,12, 9,11,10,
  126754. 10,11,10,12,12,10,12,12,12,10,10,10,10, 9,10,11,
  126755. 10,10,12,10,10,12,11,10,11,10,10,12,11,10,12,10,
  126756. 10,11, 9,11,10, 9,10, 9,10,
  126757. };
  126758. static float _vq_quantthresh__8c0_s_p9_2[] = {
  126759. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  126760. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  126761. 6.5, 7.5, 8.5, 9.5,
  126762. };
  126763. static long _vq_quantmap__8c0_s_p9_2[] = {
  126764. 19, 17, 15, 13, 11, 9, 7, 5,
  126765. 3, 1, 0, 2, 4, 6, 8, 10,
  126766. 12, 14, 16, 18, 20,
  126767. };
  126768. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_2 = {
  126769. _vq_quantthresh__8c0_s_p9_2,
  126770. _vq_quantmap__8c0_s_p9_2,
  126771. 21,
  126772. 21
  126773. };
  126774. static static_codebook _8c0_s_p9_2 = {
  126775. 2, 441,
  126776. _vq_lengthlist__8c0_s_p9_2,
  126777. 1, -529268736, 1611661312, 5, 0,
  126778. _vq_quantlist__8c0_s_p9_2,
  126779. NULL,
  126780. &_vq_auxt__8c0_s_p9_2,
  126781. NULL,
  126782. 0
  126783. };
  126784. static long _huff_lengthlist__8c0_s_single[] = {
  126785. 4, 5,18, 7,10, 6, 7, 8, 9,10, 5, 2,18, 5, 7, 5,
  126786. 6, 7, 8,11,17,17,17,17,17,17,17,17,17,17, 7, 4,
  126787. 17, 6, 9, 6, 8,10,12,15,11, 7,17, 9, 6, 6, 7, 9,
  126788. 11,15, 6, 4,17, 6, 6, 4, 5, 8,11,16, 6, 6,17, 8,
  126789. 6, 5, 6, 9,13,16, 8, 9,17,11, 9, 8, 8,11,13,17,
  126790. 9,12,17,15,14,13,12,13,14,17,12,15,17,17,17,17,
  126791. 17,16,17,17,
  126792. };
  126793. static static_codebook _huff_book__8c0_s_single = {
  126794. 2, 100,
  126795. _huff_lengthlist__8c0_s_single,
  126796. 0, 0, 0, 0, 0,
  126797. NULL,
  126798. NULL,
  126799. NULL,
  126800. NULL,
  126801. 0
  126802. };
  126803. static long _vq_quantlist__8c1_s_p1_0[] = {
  126804. 1,
  126805. 0,
  126806. 2,
  126807. };
  126808. static long _vq_lengthlist__8c1_s_p1_0[] = {
  126809. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  126810. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126814. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  126815. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126819. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  126820. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 8, 0, 0, 0, 0,
  126855. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  126856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  126860. 0, 0, 0, 8, 8,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  126861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  126865. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  126866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  126901. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  126906. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  126911. 0, 0, 0, 0, 0, 0, 8,10, 8, 0, 0, 0, 0, 0, 0, 0,
  126912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127219. 0,
  127220. };
  127221. static float _vq_quantthresh__8c1_s_p1_0[] = {
  127222. -0.5, 0.5,
  127223. };
  127224. static long _vq_quantmap__8c1_s_p1_0[] = {
  127225. 1, 0, 2,
  127226. };
  127227. static encode_aux_threshmatch _vq_auxt__8c1_s_p1_0 = {
  127228. _vq_quantthresh__8c1_s_p1_0,
  127229. _vq_quantmap__8c1_s_p1_0,
  127230. 3,
  127231. 3
  127232. };
  127233. static static_codebook _8c1_s_p1_0 = {
  127234. 8, 6561,
  127235. _vq_lengthlist__8c1_s_p1_0,
  127236. 1, -535822336, 1611661312, 2, 0,
  127237. _vq_quantlist__8c1_s_p1_0,
  127238. NULL,
  127239. &_vq_auxt__8c1_s_p1_0,
  127240. NULL,
  127241. 0
  127242. };
  127243. static long _vq_quantlist__8c1_s_p2_0[] = {
  127244. 2,
  127245. 1,
  127246. 3,
  127247. 0,
  127248. 4,
  127249. };
  127250. static long _vq_lengthlist__8c1_s_p2_0[] = {
  127251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127290. 0,
  127291. };
  127292. static float _vq_quantthresh__8c1_s_p2_0[] = {
  127293. -1.5, -0.5, 0.5, 1.5,
  127294. };
  127295. static long _vq_quantmap__8c1_s_p2_0[] = {
  127296. 3, 1, 0, 2, 4,
  127297. };
  127298. static encode_aux_threshmatch _vq_auxt__8c1_s_p2_0 = {
  127299. _vq_quantthresh__8c1_s_p2_0,
  127300. _vq_quantmap__8c1_s_p2_0,
  127301. 5,
  127302. 5
  127303. };
  127304. static static_codebook _8c1_s_p2_0 = {
  127305. 4, 625,
  127306. _vq_lengthlist__8c1_s_p2_0,
  127307. 1, -533725184, 1611661312, 3, 0,
  127308. _vq_quantlist__8c1_s_p2_0,
  127309. NULL,
  127310. &_vq_auxt__8c1_s_p2_0,
  127311. NULL,
  127312. 0
  127313. };
  127314. static long _vq_quantlist__8c1_s_p3_0[] = {
  127315. 2,
  127316. 1,
  127317. 3,
  127318. 0,
  127319. 4,
  127320. };
  127321. static long _vq_lengthlist__8c1_s_p3_0[] = {
  127322. 2, 4, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  127324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127325. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 7, 7,
  127327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127328. 0, 0, 0, 0, 6, 6, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  127329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127361. 0,
  127362. };
  127363. static float _vq_quantthresh__8c1_s_p3_0[] = {
  127364. -1.5, -0.5, 0.5, 1.5,
  127365. };
  127366. static long _vq_quantmap__8c1_s_p3_0[] = {
  127367. 3, 1, 0, 2, 4,
  127368. };
  127369. static encode_aux_threshmatch _vq_auxt__8c1_s_p3_0 = {
  127370. _vq_quantthresh__8c1_s_p3_0,
  127371. _vq_quantmap__8c1_s_p3_0,
  127372. 5,
  127373. 5
  127374. };
  127375. static static_codebook _8c1_s_p3_0 = {
  127376. 4, 625,
  127377. _vq_lengthlist__8c1_s_p3_0,
  127378. 1, -533725184, 1611661312, 3, 0,
  127379. _vq_quantlist__8c1_s_p3_0,
  127380. NULL,
  127381. &_vq_auxt__8c1_s_p3_0,
  127382. NULL,
  127383. 0
  127384. };
  127385. static long _vq_quantlist__8c1_s_p4_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_p4_0[] = {
  127397. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  127398. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  127399. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  127400. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  127401. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127402. 0,
  127403. };
  127404. static float _vq_quantthresh__8c1_s_p4_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_p4_0[] = {
  127408. 7, 5, 3, 1, 0, 2, 4, 6,
  127409. 8,
  127410. };
  127411. static encode_aux_threshmatch _vq_auxt__8c1_s_p4_0 = {
  127412. _vq_quantthresh__8c1_s_p4_0,
  127413. _vq_quantmap__8c1_s_p4_0,
  127414. 9,
  127415. 9
  127416. };
  127417. static static_codebook _8c1_s_p4_0 = {
  127418. 2, 81,
  127419. _vq_lengthlist__8c1_s_p4_0,
  127420. 1, -531628032, 1611661312, 4, 0,
  127421. _vq_quantlist__8c1_s_p4_0,
  127422. NULL,
  127423. &_vq_auxt__8c1_s_p4_0,
  127424. NULL,
  127425. 0
  127426. };
  127427. static long _vq_quantlist__8c1_s_p5_0[] = {
  127428. 4,
  127429. 3,
  127430. 5,
  127431. 2,
  127432. 6,
  127433. 1,
  127434. 7,
  127435. 0,
  127436. 8,
  127437. };
  127438. static long _vq_lengthlist__8c1_s_p5_0[] = {
  127439. 1, 3, 3, 4, 5, 6, 6, 8, 8, 0, 0, 0, 8, 8, 7, 7,
  127440. 9, 9, 0, 0, 0, 8, 8, 7, 7, 9, 9, 0, 0, 0, 9,10,
  127441. 8, 8, 9, 9, 0, 0, 0,10,10, 8, 8, 9, 9, 0, 0, 0,
  127442. 11,10, 8, 8,10,10, 0, 0, 0,11,11, 8, 8,10,10, 0,
  127443. 0, 0,12,12, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  127444. 10,
  127445. };
  127446. static float _vq_quantthresh__8c1_s_p5_0[] = {
  127447. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127448. };
  127449. static long _vq_quantmap__8c1_s_p5_0[] = {
  127450. 7, 5, 3, 1, 0, 2, 4, 6,
  127451. 8,
  127452. };
  127453. static encode_aux_threshmatch _vq_auxt__8c1_s_p5_0 = {
  127454. _vq_quantthresh__8c1_s_p5_0,
  127455. _vq_quantmap__8c1_s_p5_0,
  127456. 9,
  127457. 9
  127458. };
  127459. static static_codebook _8c1_s_p5_0 = {
  127460. 2, 81,
  127461. _vq_lengthlist__8c1_s_p5_0,
  127462. 1, -531628032, 1611661312, 4, 0,
  127463. _vq_quantlist__8c1_s_p5_0,
  127464. NULL,
  127465. &_vq_auxt__8c1_s_p5_0,
  127466. NULL,
  127467. 0
  127468. };
  127469. static long _vq_quantlist__8c1_s_p6_0[] = {
  127470. 8,
  127471. 7,
  127472. 9,
  127473. 6,
  127474. 10,
  127475. 5,
  127476. 11,
  127477. 4,
  127478. 12,
  127479. 3,
  127480. 13,
  127481. 2,
  127482. 14,
  127483. 1,
  127484. 15,
  127485. 0,
  127486. 16,
  127487. };
  127488. static long _vq_lengthlist__8c1_s_p6_0[] = {
  127489. 1, 3, 3, 5, 5, 8, 8, 8, 8, 9, 9,10,10,11,11,11,
  127490. 11, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11,
  127491. 12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  127492. 11,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,11,
  127493. 12,12,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,
  127494. 11,12,12,12,12, 0, 0, 0,10,10, 9, 9,10,10,10,10,
  127495. 11,11,12,12,13,13, 0, 0, 0,10,10, 9, 9,10,10,10,
  127496. 10,11,11,12,12,13,13, 0, 0, 0,11,11, 9, 9,10,10,
  127497. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  127498. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  127499. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  127500. 9,10,10,11,11,12,11,12,12,13,13, 0, 0, 0, 0, 0,
  127501. 10,10,11,11,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  127502. 0, 0, 0,11,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  127503. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  127504. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,13, 0,
  127505. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  127506. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  127507. 14,
  127508. };
  127509. static float _vq_quantthresh__8c1_s_p6_0[] = {
  127510. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  127511. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  127512. };
  127513. static long _vq_quantmap__8c1_s_p6_0[] = {
  127514. 15, 13, 11, 9, 7, 5, 3, 1,
  127515. 0, 2, 4, 6, 8, 10, 12, 14,
  127516. 16,
  127517. };
  127518. static encode_aux_threshmatch _vq_auxt__8c1_s_p6_0 = {
  127519. _vq_quantthresh__8c1_s_p6_0,
  127520. _vq_quantmap__8c1_s_p6_0,
  127521. 17,
  127522. 17
  127523. };
  127524. static static_codebook _8c1_s_p6_0 = {
  127525. 2, 289,
  127526. _vq_lengthlist__8c1_s_p6_0,
  127527. 1, -529530880, 1611661312, 5, 0,
  127528. _vq_quantlist__8c1_s_p6_0,
  127529. NULL,
  127530. &_vq_auxt__8c1_s_p6_0,
  127531. NULL,
  127532. 0
  127533. };
  127534. static long _vq_quantlist__8c1_s_p7_0[] = {
  127535. 1,
  127536. 0,
  127537. 2,
  127538. };
  127539. static long _vq_lengthlist__8c1_s_p7_0[] = {
  127540. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  127541. 9, 9, 5, 7, 7,10, 9, 9,10, 9, 9, 6,10,10,10,10,
  127542. 10,11,10,10, 6, 9, 9,10, 9,10,11,10,10, 6, 9, 9,
  127543. 10, 9, 9,11, 9,10, 7,10,10,11,11,11,11,10,10, 6,
  127544. 9, 9,10,10,10,11, 9, 9, 6, 9, 9,10,10,10,10, 9,
  127545. 9,
  127546. };
  127547. static float _vq_quantthresh__8c1_s_p7_0[] = {
  127548. -5.5, 5.5,
  127549. };
  127550. static long _vq_quantmap__8c1_s_p7_0[] = {
  127551. 1, 0, 2,
  127552. };
  127553. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_0 = {
  127554. _vq_quantthresh__8c1_s_p7_0,
  127555. _vq_quantmap__8c1_s_p7_0,
  127556. 3,
  127557. 3
  127558. };
  127559. static static_codebook _8c1_s_p7_0 = {
  127560. 4, 81,
  127561. _vq_lengthlist__8c1_s_p7_0,
  127562. 1, -529137664, 1618345984, 2, 0,
  127563. _vq_quantlist__8c1_s_p7_0,
  127564. NULL,
  127565. &_vq_auxt__8c1_s_p7_0,
  127566. NULL,
  127567. 0
  127568. };
  127569. static long _vq_quantlist__8c1_s_p7_1[] = {
  127570. 5,
  127571. 4,
  127572. 6,
  127573. 3,
  127574. 7,
  127575. 2,
  127576. 8,
  127577. 1,
  127578. 9,
  127579. 0,
  127580. 10,
  127581. };
  127582. static long _vq_lengthlist__8c1_s_p7_1[] = {
  127583. 2, 3, 3, 5, 5, 7, 7, 7, 7, 7, 7,10,10, 9, 7, 7,
  127584. 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8,
  127585. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  127586. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  127587. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  127588. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  127589. 8, 8, 8,10,10,10,10,10, 8, 8, 8, 8, 8, 8,10,10,
  127590. 10,10,10, 8, 8, 8, 8, 8, 8,
  127591. };
  127592. static float _vq_quantthresh__8c1_s_p7_1[] = {
  127593. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  127594. 3.5, 4.5,
  127595. };
  127596. static long _vq_quantmap__8c1_s_p7_1[] = {
  127597. 9, 7, 5, 3, 1, 0, 2, 4,
  127598. 6, 8, 10,
  127599. };
  127600. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_1 = {
  127601. _vq_quantthresh__8c1_s_p7_1,
  127602. _vq_quantmap__8c1_s_p7_1,
  127603. 11,
  127604. 11
  127605. };
  127606. static static_codebook _8c1_s_p7_1 = {
  127607. 2, 121,
  127608. _vq_lengthlist__8c1_s_p7_1,
  127609. 1, -531365888, 1611661312, 4, 0,
  127610. _vq_quantlist__8c1_s_p7_1,
  127611. NULL,
  127612. &_vq_auxt__8c1_s_p7_1,
  127613. NULL,
  127614. 0
  127615. };
  127616. static long _vq_quantlist__8c1_s_p8_0[] = {
  127617. 6,
  127618. 5,
  127619. 7,
  127620. 4,
  127621. 8,
  127622. 3,
  127623. 9,
  127624. 2,
  127625. 10,
  127626. 1,
  127627. 11,
  127628. 0,
  127629. 12,
  127630. };
  127631. static long _vq_lengthlist__8c1_s_p8_0[] = {
  127632. 1, 4, 4, 6, 6, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5,
  127633. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  127634. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  127635. 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  127636. 11, 0,12,12, 9, 9, 9, 9,10, 9,10,11,11,11, 0,13,
  127637. 12, 9, 8, 9, 9,10,10,11,11,12,11, 0, 0, 0, 9, 9,
  127638. 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10, 9, 9,10,
  127639. 10,11,11,12,12, 0, 0, 0,13,13,10,10,11,11,12,11,
  127640. 13,12, 0, 0, 0,14,14,10,10,11,10,11,11,12,12, 0,
  127641. 0, 0, 0, 0,12,12,11,11,12,12,13,13, 0, 0, 0, 0,
  127642. 0,12,12,11,10,12,11,13,12,
  127643. };
  127644. static float _vq_quantthresh__8c1_s_p8_0[] = {
  127645. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  127646. 12.5, 17.5, 22.5, 27.5,
  127647. };
  127648. static long _vq_quantmap__8c1_s_p8_0[] = {
  127649. 11, 9, 7, 5, 3, 1, 0, 2,
  127650. 4, 6, 8, 10, 12,
  127651. };
  127652. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_0 = {
  127653. _vq_quantthresh__8c1_s_p8_0,
  127654. _vq_quantmap__8c1_s_p8_0,
  127655. 13,
  127656. 13
  127657. };
  127658. static static_codebook _8c1_s_p8_0 = {
  127659. 2, 169,
  127660. _vq_lengthlist__8c1_s_p8_0,
  127661. 1, -526516224, 1616117760, 4, 0,
  127662. _vq_quantlist__8c1_s_p8_0,
  127663. NULL,
  127664. &_vq_auxt__8c1_s_p8_0,
  127665. NULL,
  127666. 0
  127667. };
  127668. static long _vq_quantlist__8c1_s_p8_1[] = {
  127669. 2,
  127670. 1,
  127671. 3,
  127672. 0,
  127673. 4,
  127674. };
  127675. static long _vq_lengthlist__8c1_s_p8_1[] = {
  127676. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  127677. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  127678. };
  127679. static float _vq_quantthresh__8c1_s_p8_1[] = {
  127680. -1.5, -0.5, 0.5, 1.5,
  127681. };
  127682. static long _vq_quantmap__8c1_s_p8_1[] = {
  127683. 3, 1, 0, 2, 4,
  127684. };
  127685. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_1 = {
  127686. _vq_quantthresh__8c1_s_p8_1,
  127687. _vq_quantmap__8c1_s_p8_1,
  127688. 5,
  127689. 5
  127690. };
  127691. static static_codebook _8c1_s_p8_1 = {
  127692. 2, 25,
  127693. _vq_lengthlist__8c1_s_p8_1,
  127694. 1, -533725184, 1611661312, 3, 0,
  127695. _vq_quantlist__8c1_s_p8_1,
  127696. NULL,
  127697. &_vq_auxt__8c1_s_p8_1,
  127698. NULL,
  127699. 0
  127700. };
  127701. static long _vq_quantlist__8c1_s_p9_0[] = {
  127702. 6,
  127703. 5,
  127704. 7,
  127705. 4,
  127706. 8,
  127707. 3,
  127708. 9,
  127709. 2,
  127710. 10,
  127711. 1,
  127712. 11,
  127713. 0,
  127714. 12,
  127715. };
  127716. static long _vq_lengthlist__8c1_s_p9_0[] = {
  127717. 1, 3, 3,10,10,10,10,10,10,10,10,10,10, 5, 6, 6,
  127718. 10,10,10,10,10,10,10,10,10,10, 6, 7, 8,10,10,10,
  127719. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127720. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127721. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127722. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127723. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127724. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127725. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127726. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127727. 10,10,10,10,10, 9, 9, 9, 9,
  127728. };
  127729. static float _vq_quantthresh__8c1_s_p9_0[] = {
  127730. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  127731. 787.5, 1102.5, 1417.5, 1732.5,
  127732. };
  127733. static long _vq_quantmap__8c1_s_p9_0[] = {
  127734. 11, 9, 7, 5, 3, 1, 0, 2,
  127735. 4, 6, 8, 10, 12,
  127736. };
  127737. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_0 = {
  127738. _vq_quantthresh__8c1_s_p9_0,
  127739. _vq_quantmap__8c1_s_p9_0,
  127740. 13,
  127741. 13
  127742. };
  127743. static static_codebook _8c1_s_p9_0 = {
  127744. 2, 169,
  127745. _vq_lengthlist__8c1_s_p9_0,
  127746. 1, -513964032, 1628680192, 4, 0,
  127747. _vq_quantlist__8c1_s_p9_0,
  127748. NULL,
  127749. &_vq_auxt__8c1_s_p9_0,
  127750. NULL,
  127751. 0
  127752. };
  127753. static long _vq_quantlist__8c1_s_p9_1[] = {
  127754. 7,
  127755. 6,
  127756. 8,
  127757. 5,
  127758. 9,
  127759. 4,
  127760. 10,
  127761. 3,
  127762. 11,
  127763. 2,
  127764. 12,
  127765. 1,
  127766. 13,
  127767. 0,
  127768. 14,
  127769. };
  127770. static long _vq_lengthlist__8c1_s_p9_1[] = {
  127771. 1, 4, 4, 5, 5, 7, 7, 9, 9,11,11,12,12,13,13, 6,
  127772. 5, 5, 6, 6, 9, 9,10,10,12,12,12,13,15,14, 6, 5,
  127773. 5, 7, 7, 9, 9,10,10,12,12,12,13,14,13,17, 7, 7,
  127774. 8, 8,10,10,11,11,12,13,13,13,13,13,17, 7, 7, 8,
  127775. 8,10,10,11,11,13,13,13,13,14,14,17,11,11, 9, 9,
  127776. 11,11,12,12,12,13,13,14,15,13,17,12,12, 9, 9,11,
  127777. 11,12,12,13,13,13,13,14,16,17,17,17,11,12,12,12,
  127778. 13,13,13,14,15,14,15,15,17,17,17,12,12,11,11,13,
  127779. 13,14,14,15,14,15,15,17,17,17,15,15,13,13,14,14,
  127780. 15,14,15,15,16,15,17,17,17,15,15,13,13,13,14,14,
  127781. 15,15,15,15,16,17,17,17,17,16,14,15,14,14,15,14,
  127782. 14,15,15,15,17,17,17,17,17,14,14,16,14,15,15,15,
  127783. 15,15,15,17,17,17,17,17,17,16,16,15,17,15,15,14,
  127784. 17,15,17,16,17,17,17,17,16,15,14,15,15,15,15,15,
  127785. 15,
  127786. };
  127787. static float _vq_quantthresh__8c1_s_p9_1[] = {
  127788. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  127789. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  127790. };
  127791. static long _vq_quantmap__8c1_s_p9_1[] = {
  127792. 13, 11, 9, 7, 5, 3, 1, 0,
  127793. 2, 4, 6, 8, 10, 12, 14,
  127794. };
  127795. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_1 = {
  127796. _vq_quantthresh__8c1_s_p9_1,
  127797. _vq_quantmap__8c1_s_p9_1,
  127798. 15,
  127799. 15
  127800. };
  127801. static static_codebook _8c1_s_p9_1 = {
  127802. 2, 225,
  127803. _vq_lengthlist__8c1_s_p9_1,
  127804. 1, -520986624, 1620377600, 4, 0,
  127805. _vq_quantlist__8c1_s_p9_1,
  127806. NULL,
  127807. &_vq_auxt__8c1_s_p9_1,
  127808. NULL,
  127809. 0
  127810. };
  127811. static long _vq_quantlist__8c1_s_p9_2[] = {
  127812. 10,
  127813. 9,
  127814. 11,
  127815. 8,
  127816. 12,
  127817. 7,
  127818. 13,
  127819. 6,
  127820. 14,
  127821. 5,
  127822. 15,
  127823. 4,
  127824. 16,
  127825. 3,
  127826. 17,
  127827. 2,
  127828. 18,
  127829. 1,
  127830. 19,
  127831. 0,
  127832. 20,
  127833. };
  127834. static long _vq_lengthlist__8c1_s_p9_2[] = {
  127835. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  127836. 9, 9, 9, 9, 9,11,11,12, 7, 7, 7, 7, 8, 8, 9, 9,
  127837. 9, 9,10,10,10,10,10,10,10,10,11,11,11, 7, 7, 7,
  127838. 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,11,
  127839. 11,12, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,
  127840. 10,10,10,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  127841. 9,10,10,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  127842. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,11,11,
  127843. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  127844. 10,10,10,11,12,11, 9, 9, 8, 9, 9, 9, 9, 9,10,10,
  127845. 10,10,10,10,10,10,10,10,11,11,11,11,11, 8, 8, 9,
  127846. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,11,12,11,
  127847. 12,11, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  127848. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  127849. 10,10,10,10,10,10,10,12,11,12,11,11, 9, 9, 9,10,
  127850. 10,10,10,10,10,10,10,10,10,10,10,10,12,11,11,11,
  127851. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127852. 11,11,11,12,11,11,12,11,10,10,10,10,10,10,10,10,
  127853. 10,10,10,10,11,10,11,11,11,11,11,11,11,10,10,10,
  127854. 10,10,10,10,10,10,10,10,10,10,10,11,11,12,11,12,
  127855. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127856. 11,11,12,11,12,11,11,11,11,10,10,10,10,10,10,10,
  127857. 10,10,10,10,10,11,11,12,11,11,12,11,11,12,10,10,
  127858. 11,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  127859. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,12,
  127860. 12,11,12,11,11,12,12,12,11,11,10,10,10,10,10,10,
  127861. 10,10,10,11,12,12,11,12,12,11,12,11,11,11,11,10,
  127862. 10,10,10,10,10,10,10,10,10,
  127863. };
  127864. static float _vq_quantthresh__8c1_s_p9_2[] = {
  127865. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  127866. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  127867. 6.5, 7.5, 8.5, 9.5,
  127868. };
  127869. static long _vq_quantmap__8c1_s_p9_2[] = {
  127870. 19, 17, 15, 13, 11, 9, 7, 5,
  127871. 3, 1, 0, 2, 4, 6, 8, 10,
  127872. 12, 14, 16, 18, 20,
  127873. };
  127874. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_2 = {
  127875. _vq_quantthresh__8c1_s_p9_2,
  127876. _vq_quantmap__8c1_s_p9_2,
  127877. 21,
  127878. 21
  127879. };
  127880. static static_codebook _8c1_s_p9_2 = {
  127881. 2, 441,
  127882. _vq_lengthlist__8c1_s_p9_2,
  127883. 1, -529268736, 1611661312, 5, 0,
  127884. _vq_quantlist__8c1_s_p9_2,
  127885. NULL,
  127886. &_vq_auxt__8c1_s_p9_2,
  127887. NULL,
  127888. 0
  127889. };
  127890. static long _huff_lengthlist__8c1_s_single[] = {
  127891. 4, 6,18, 8,11, 8, 8, 9, 9,10, 4, 4,18, 5, 9, 5,
  127892. 6, 7, 8,10,18,18,18,18,17,17,17,17,17,17, 7, 5,
  127893. 17, 6,11, 6, 7, 8, 9,12,12, 9,17,12, 8, 8, 9,10,
  127894. 10,13, 7, 5,17, 6, 8, 4, 5, 6, 8,10, 6, 5,17, 6,
  127895. 8, 5, 4, 5, 7, 9, 7, 7,17, 8, 9, 6, 5, 5, 6, 8,
  127896. 8, 8,17, 9,11, 8, 6, 6, 6, 7, 9,10,17,12,12,10,
  127897. 9, 7, 7, 8,
  127898. };
  127899. static static_codebook _huff_book__8c1_s_single = {
  127900. 2, 100,
  127901. _huff_lengthlist__8c1_s_single,
  127902. 0, 0, 0, 0, 0,
  127903. NULL,
  127904. NULL,
  127905. NULL,
  127906. NULL,
  127907. 0
  127908. };
  127909. static long _huff_lengthlist__44c2_s_long[] = {
  127910. 6, 6,12,10,10,10, 9,10,12,12, 6, 1,10, 5, 6, 6,
  127911. 7, 9,11,14,12, 9, 8,11, 7, 8, 9,11,13,15,10, 5,
  127912. 12, 7, 8, 7, 9,12,14,15,10, 6, 7, 8, 5, 6, 7, 9,
  127913. 12,14, 9, 6, 8, 7, 6, 6, 7, 9,12,12, 9, 7, 9, 9,
  127914. 7, 6, 6, 7,10,10,10, 9,10,11, 8, 7, 6, 6, 8,10,
  127915. 12,11,13,13,11,10, 8, 8, 8,10,11,13,15,15,14,13,
  127916. 10, 8, 8, 9,
  127917. };
  127918. static static_codebook _huff_book__44c2_s_long = {
  127919. 2, 100,
  127920. _huff_lengthlist__44c2_s_long,
  127921. 0, 0, 0, 0, 0,
  127922. NULL,
  127923. NULL,
  127924. NULL,
  127925. NULL,
  127926. 0
  127927. };
  127928. static long _vq_quantlist__44c2_s_p1_0[] = {
  127929. 1,
  127930. 0,
  127931. 2,
  127932. };
  127933. static long _vq_lengthlist__44c2_s_p1_0[] = {
  127934. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  127935. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127939. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  127940. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127944. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  127945. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 7, 0, 0, 0, 0,
  127980. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  127981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  127985. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  127986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  127990. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  127991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  128026. 0, 0, 0, 0, 7, 8, 8, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  128031. 0, 0, 0, 0, 0, 8, 8, 9, 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, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  128036. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  128037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128344. 0,
  128345. };
  128346. static float _vq_quantthresh__44c2_s_p1_0[] = {
  128347. -0.5, 0.5,
  128348. };
  128349. static long _vq_quantmap__44c2_s_p1_0[] = {
  128350. 1, 0, 2,
  128351. };
  128352. static encode_aux_threshmatch _vq_auxt__44c2_s_p1_0 = {
  128353. _vq_quantthresh__44c2_s_p1_0,
  128354. _vq_quantmap__44c2_s_p1_0,
  128355. 3,
  128356. 3
  128357. };
  128358. static static_codebook _44c2_s_p1_0 = {
  128359. 8, 6561,
  128360. _vq_lengthlist__44c2_s_p1_0,
  128361. 1, -535822336, 1611661312, 2, 0,
  128362. _vq_quantlist__44c2_s_p1_0,
  128363. NULL,
  128364. &_vq_auxt__44c2_s_p1_0,
  128365. NULL,
  128366. 0
  128367. };
  128368. static long _vq_quantlist__44c2_s_p2_0[] = {
  128369. 2,
  128370. 1,
  128371. 3,
  128372. 0,
  128373. 4,
  128374. };
  128375. static long _vq_lengthlist__44c2_s_p2_0[] = {
  128376. 1, 4, 4, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0,
  128377. 8, 8, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  128378. 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  128379. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0,
  128380. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128385. 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,11,11, 0, 0,
  128386. 0,11,11, 0, 0, 0,12,11, 0, 0, 0, 0, 0, 0, 0, 7,
  128387. 8, 8, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0, 0,11,
  128388. 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128393. 0, 0, 0, 6, 8, 8, 0, 0, 0,11,11, 0, 0, 0,11,11,
  128394. 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0,
  128395. 0, 0,10,11, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0,
  128396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128401. 8, 9, 9, 0, 0, 0,11,12, 0, 0, 0,11,12, 0, 0, 0,
  128402. 12,11, 0, 0, 0, 0, 0, 0, 0, 8,10, 9, 0, 0, 0,12,
  128403. 11, 0, 0, 0,12,11, 0, 0, 0,11,12, 0, 0, 0, 0, 0,
  128404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128415. 0,
  128416. };
  128417. static float _vq_quantthresh__44c2_s_p2_0[] = {
  128418. -1.5, -0.5, 0.5, 1.5,
  128419. };
  128420. static long _vq_quantmap__44c2_s_p2_0[] = {
  128421. 3, 1, 0, 2, 4,
  128422. };
  128423. static encode_aux_threshmatch _vq_auxt__44c2_s_p2_0 = {
  128424. _vq_quantthresh__44c2_s_p2_0,
  128425. _vq_quantmap__44c2_s_p2_0,
  128426. 5,
  128427. 5
  128428. };
  128429. static static_codebook _44c2_s_p2_0 = {
  128430. 4, 625,
  128431. _vq_lengthlist__44c2_s_p2_0,
  128432. 1, -533725184, 1611661312, 3, 0,
  128433. _vq_quantlist__44c2_s_p2_0,
  128434. NULL,
  128435. &_vq_auxt__44c2_s_p2_0,
  128436. NULL,
  128437. 0
  128438. };
  128439. static long _vq_quantlist__44c2_s_p3_0[] = {
  128440. 2,
  128441. 1,
  128442. 3,
  128443. 0,
  128444. 4,
  128445. };
  128446. static long _vq_lengthlist__44c2_s_p3_0[] = {
  128447. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  128449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128450. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  128452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128453. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  128454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128486. 0,
  128487. };
  128488. static float _vq_quantthresh__44c2_s_p3_0[] = {
  128489. -1.5, -0.5, 0.5, 1.5,
  128490. };
  128491. static long _vq_quantmap__44c2_s_p3_0[] = {
  128492. 3, 1, 0, 2, 4,
  128493. };
  128494. static encode_aux_threshmatch _vq_auxt__44c2_s_p3_0 = {
  128495. _vq_quantthresh__44c2_s_p3_0,
  128496. _vq_quantmap__44c2_s_p3_0,
  128497. 5,
  128498. 5
  128499. };
  128500. static static_codebook _44c2_s_p3_0 = {
  128501. 4, 625,
  128502. _vq_lengthlist__44c2_s_p3_0,
  128503. 1, -533725184, 1611661312, 3, 0,
  128504. _vq_quantlist__44c2_s_p3_0,
  128505. NULL,
  128506. &_vq_auxt__44c2_s_p3_0,
  128507. NULL,
  128508. 0
  128509. };
  128510. static long _vq_quantlist__44c2_s_p4_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_p4_0[] = {
  128522. 1, 3, 3, 6, 6, 0, 0, 0, 0, 0, 6, 6, 6, 6, 0, 0,
  128523. 0, 0, 0, 6, 6, 6, 6, 0, 0, 0, 0, 0, 7, 7, 6, 6,
  128524. 0, 0, 0, 0, 0, 0, 0, 6, 7, 0, 0, 0, 0, 0, 0, 0,
  128525. 7, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  128526. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128527. 0,
  128528. };
  128529. static float _vq_quantthresh__44c2_s_p4_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_p4_0[] = {
  128533. 7, 5, 3, 1, 0, 2, 4, 6,
  128534. 8,
  128535. };
  128536. static encode_aux_threshmatch _vq_auxt__44c2_s_p4_0 = {
  128537. _vq_quantthresh__44c2_s_p4_0,
  128538. _vq_quantmap__44c2_s_p4_0,
  128539. 9,
  128540. 9
  128541. };
  128542. static static_codebook _44c2_s_p4_0 = {
  128543. 2, 81,
  128544. _vq_lengthlist__44c2_s_p4_0,
  128545. 1, -531628032, 1611661312, 4, 0,
  128546. _vq_quantlist__44c2_s_p4_0,
  128547. NULL,
  128548. &_vq_auxt__44c2_s_p4_0,
  128549. NULL,
  128550. 0
  128551. };
  128552. static long _vq_quantlist__44c2_s_p5_0[] = {
  128553. 4,
  128554. 3,
  128555. 5,
  128556. 2,
  128557. 6,
  128558. 1,
  128559. 7,
  128560. 0,
  128561. 8,
  128562. };
  128563. static long _vq_lengthlist__44c2_s_p5_0[] = {
  128564. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 7, 7, 7, 7, 7, 7,
  128565. 9, 9, 0, 7, 7, 7, 7, 7, 7, 9, 9, 0, 8, 8, 7, 7,
  128566. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  128567. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  128568. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  128569. 11,
  128570. };
  128571. static float _vq_quantthresh__44c2_s_p5_0[] = {
  128572. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128573. };
  128574. static long _vq_quantmap__44c2_s_p5_0[] = {
  128575. 7, 5, 3, 1, 0, 2, 4, 6,
  128576. 8,
  128577. };
  128578. static encode_aux_threshmatch _vq_auxt__44c2_s_p5_0 = {
  128579. _vq_quantthresh__44c2_s_p5_0,
  128580. _vq_quantmap__44c2_s_p5_0,
  128581. 9,
  128582. 9
  128583. };
  128584. static static_codebook _44c2_s_p5_0 = {
  128585. 2, 81,
  128586. _vq_lengthlist__44c2_s_p5_0,
  128587. 1, -531628032, 1611661312, 4, 0,
  128588. _vq_quantlist__44c2_s_p5_0,
  128589. NULL,
  128590. &_vq_auxt__44c2_s_p5_0,
  128591. NULL,
  128592. 0
  128593. };
  128594. static long _vq_quantlist__44c2_s_p6_0[] = {
  128595. 8,
  128596. 7,
  128597. 9,
  128598. 6,
  128599. 10,
  128600. 5,
  128601. 11,
  128602. 4,
  128603. 12,
  128604. 3,
  128605. 13,
  128606. 2,
  128607. 14,
  128608. 1,
  128609. 15,
  128610. 0,
  128611. 16,
  128612. };
  128613. static long _vq_lengthlist__44c2_s_p6_0[] = {
  128614. 1, 4, 3, 6, 6, 8, 8, 9, 9, 9, 9, 9, 9,10,10,11,
  128615. 11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  128616. 12,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  128617. 11,11,12, 0, 8, 8, 7, 7, 9, 9,10,10, 9, 9,10,10,
  128618. 11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10, 9,10,
  128619. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  128620. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  128621. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  128622. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  128623. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  128624. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  128625. 9,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  128626. 10,10,10,10,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  128627. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  128628. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  128629. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  128630. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  128631. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  128632. 14,
  128633. };
  128634. static float _vq_quantthresh__44c2_s_p6_0[] = {
  128635. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128636. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128637. };
  128638. static long _vq_quantmap__44c2_s_p6_0[] = {
  128639. 15, 13, 11, 9, 7, 5, 3, 1,
  128640. 0, 2, 4, 6, 8, 10, 12, 14,
  128641. 16,
  128642. };
  128643. static encode_aux_threshmatch _vq_auxt__44c2_s_p6_0 = {
  128644. _vq_quantthresh__44c2_s_p6_0,
  128645. _vq_quantmap__44c2_s_p6_0,
  128646. 17,
  128647. 17
  128648. };
  128649. static static_codebook _44c2_s_p6_0 = {
  128650. 2, 289,
  128651. _vq_lengthlist__44c2_s_p6_0,
  128652. 1, -529530880, 1611661312, 5, 0,
  128653. _vq_quantlist__44c2_s_p6_0,
  128654. NULL,
  128655. &_vq_auxt__44c2_s_p6_0,
  128656. NULL,
  128657. 0
  128658. };
  128659. static long _vq_quantlist__44c2_s_p7_0[] = {
  128660. 1,
  128661. 0,
  128662. 2,
  128663. };
  128664. static long _vq_lengthlist__44c2_s_p7_0[] = {
  128665. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  128666. 9, 9, 4, 7, 7,10, 9, 9,10, 9, 9, 7,10,10,11,10,
  128667. 11,11,10,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  128668. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 6,
  128669. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,12,10,
  128670. 11,
  128671. };
  128672. static float _vq_quantthresh__44c2_s_p7_0[] = {
  128673. -5.5, 5.5,
  128674. };
  128675. static long _vq_quantmap__44c2_s_p7_0[] = {
  128676. 1, 0, 2,
  128677. };
  128678. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_0 = {
  128679. _vq_quantthresh__44c2_s_p7_0,
  128680. _vq_quantmap__44c2_s_p7_0,
  128681. 3,
  128682. 3
  128683. };
  128684. static static_codebook _44c2_s_p7_0 = {
  128685. 4, 81,
  128686. _vq_lengthlist__44c2_s_p7_0,
  128687. 1, -529137664, 1618345984, 2, 0,
  128688. _vq_quantlist__44c2_s_p7_0,
  128689. NULL,
  128690. &_vq_auxt__44c2_s_p7_0,
  128691. NULL,
  128692. 0
  128693. };
  128694. static long _vq_quantlist__44c2_s_p7_1[] = {
  128695. 5,
  128696. 4,
  128697. 6,
  128698. 3,
  128699. 7,
  128700. 2,
  128701. 8,
  128702. 1,
  128703. 9,
  128704. 0,
  128705. 10,
  128706. };
  128707. static long _vq_lengthlist__44c2_s_p7_1[] = {
  128708. 2, 3, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 7, 7, 6, 6,
  128709. 7, 7, 8, 8, 8, 8, 9, 6, 6, 6, 6, 7, 7, 8, 8, 8,
  128710. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  128711. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  128712. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  128713. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  128714. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  128715. 10,10,10, 8, 8, 8, 8, 8, 8,
  128716. };
  128717. static float _vq_quantthresh__44c2_s_p7_1[] = {
  128718. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  128719. 3.5, 4.5,
  128720. };
  128721. static long _vq_quantmap__44c2_s_p7_1[] = {
  128722. 9, 7, 5, 3, 1, 0, 2, 4,
  128723. 6, 8, 10,
  128724. };
  128725. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_1 = {
  128726. _vq_quantthresh__44c2_s_p7_1,
  128727. _vq_quantmap__44c2_s_p7_1,
  128728. 11,
  128729. 11
  128730. };
  128731. static static_codebook _44c2_s_p7_1 = {
  128732. 2, 121,
  128733. _vq_lengthlist__44c2_s_p7_1,
  128734. 1, -531365888, 1611661312, 4, 0,
  128735. _vq_quantlist__44c2_s_p7_1,
  128736. NULL,
  128737. &_vq_auxt__44c2_s_p7_1,
  128738. NULL,
  128739. 0
  128740. };
  128741. static long _vq_quantlist__44c2_s_p8_0[] = {
  128742. 6,
  128743. 5,
  128744. 7,
  128745. 4,
  128746. 8,
  128747. 3,
  128748. 9,
  128749. 2,
  128750. 10,
  128751. 1,
  128752. 11,
  128753. 0,
  128754. 12,
  128755. };
  128756. static long _vq_lengthlist__44c2_s_p8_0[] = {
  128757. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  128758. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  128759. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  128760. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  128761. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  128762. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  128763. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  128764. 11,12,12,12,12, 0, 0, 0,14,14,10,11,11,11,12,12,
  128765. 13,13, 0, 0, 0,14,14,11,10,11,11,13,12,13,13, 0,
  128766. 0, 0, 0, 0,12,12,11,12,13,12,14,14, 0, 0, 0, 0,
  128767. 0,12,12,12,12,13,12,14,14,
  128768. };
  128769. static float _vq_quantthresh__44c2_s_p8_0[] = {
  128770. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  128771. 12.5, 17.5, 22.5, 27.5,
  128772. };
  128773. static long _vq_quantmap__44c2_s_p8_0[] = {
  128774. 11, 9, 7, 5, 3, 1, 0, 2,
  128775. 4, 6, 8, 10, 12,
  128776. };
  128777. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_0 = {
  128778. _vq_quantthresh__44c2_s_p8_0,
  128779. _vq_quantmap__44c2_s_p8_0,
  128780. 13,
  128781. 13
  128782. };
  128783. static static_codebook _44c2_s_p8_0 = {
  128784. 2, 169,
  128785. _vq_lengthlist__44c2_s_p8_0,
  128786. 1, -526516224, 1616117760, 4, 0,
  128787. _vq_quantlist__44c2_s_p8_0,
  128788. NULL,
  128789. &_vq_auxt__44c2_s_p8_0,
  128790. NULL,
  128791. 0
  128792. };
  128793. static long _vq_quantlist__44c2_s_p8_1[] = {
  128794. 2,
  128795. 1,
  128796. 3,
  128797. 0,
  128798. 4,
  128799. };
  128800. static long _vq_lengthlist__44c2_s_p8_1[] = {
  128801. 2, 4, 4, 5, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  128802. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  128803. };
  128804. static float _vq_quantthresh__44c2_s_p8_1[] = {
  128805. -1.5, -0.5, 0.5, 1.5,
  128806. };
  128807. static long _vq_quantmap__44c2_s_p8_1[] = {
  128808. 3, 1, 0, 2, 4,
  128809. };
  128810. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_1 = {
  128811. _vq_quantthresh__44c2_s_p8_1,
  128812. _vq_quantmap__44c2_s_p8_1,
  128813. 5,
  128814. 5
  128815. };
  128816. static static_codebook _44c2_s_p8_1 = {
  128817. 2, 25,
  128818. _vq_lengthlist__44c2_s_p8_1,
  128819. 1, -533725184, 1611661312, 3, 0,
  128820. _vq_quantlist__44c2_s_p8_1,
  128821. NULL,
  128822. &_vq_auxt__44c2_s_p8_1,
  128823. NULL,
  128824. 0
  128825. };
  128826. static long _vq_quantlist__44c2_s_p9_0[] = {
  128827. 6,
  128828. 5,
  128829. 7,
  128830. 4,
  128831. 8,
  128832. 3,
  128833. 9,
  128834. 2,
  128835. 10,
  128836. 1,
  128837. 11,
  128838. 0,
  128839. 12,
  128840. };
  128841. static long _vq_lengthlist__44c2_s_p9_0[] = {
  128842. 1, 5, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  128843. 11,11,11,11,11,11,11,11,11,11, 2, 8, 7,11,11,11,
  128844. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128845. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  128846. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128847. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128848. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128849. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128850. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128851. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128852. 11,11,11,11,11,11,11,11,11,
  128853. };
  128854. static float _vq_quantthresh__44c2_s_p9_0[] = {
  128855. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  128856. 552.5, 773.5, 994.5, 1215.5,
  128857. };
  128858. static long _vq_quantmap__44c2_s_p9_0[] = {
  128859. 11, 9, 7, 5, 3, 1, 0, 2,
  128860. 4, 6, 8, 10, 12,
  128861. };
  128862. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_0 = {
  128863. _vq_quantthresh__44c2_s_p9_0,
  128864. _vq_quantmap__44c2_s_p9_0,
  128865. 13,
  128866. 13
  128867. };
  128868. static static_codebook _44c2_s_p9_0 = {
  128869. 2, 169,
  128870. _vq_lengthlist__44c2_s_p9_0,
  128871. 1, -514541568, 1627103232, 4, 0,
  128872. _vq_quantlist__44c2_s_p9_0,
  128873. NULL,
  128874. &_vq_auxt__44c2_s_p9_0,
  128875. NULL,
  128876. 0
  128877. };
  128878. static long _vq_quantlist__44c2_s_p9_1[] = {
  128879. 6,
  128880. 5,
  128881. 7,
  128882. 4,
  128883. 8,
  128884. 3,
  128885. 9,
  128886. 2,
  128887. 10,
  128888. 1,
  128889. 11,
  128890. 0,
  128891. 12,
  128892. };
  128893. static long _vq_lengthlist__44c2_s_p9_1[] = {
  128894. 1, 4, 4, 6, 6, 7, 6, 8, 8,10, 9,10,10, 6, 5, 5,
  128895. 7, 7, 8, 7,10, 9,11,11,12,13, 6, 5, 5, 7, 7, 8,
  128896. 8,10,10,11,11,13,13,18, 8, 8, 8, 8, 9, 9,10,10,
  128897. 12,12,12,13,18, 8, 8, 8, 8, 9, 9,10,10,12,12,13,
  128898. 13,18,11,11, 8, 8,10,10,11,11,12,11,13,12,18,11,
  128899. 11, 9, 7,10,10,11,11,11,12,12,13,17,17,17,10,10,
  128900. 11,11,12,12,12,10,12,12,17,17,17,11,10,11,10,13,
  128901. 12,11,12,12,12,17,17,17,15,14,11,11,12,11,13,10,
  128902. 13,12,17,17,17,14,14,12,10,11,11,13,13,13,13,17,
  128903. 17,16,17,16,13,13,12,10,13,10,14,13,17,16,17,16,
  128904. 17,13,12,12,10,13,11,14,14,
  128905. };
  128906. static float _vq_quantthresh__44c2_s_p9_1[] = {
  128907. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  128908. 42.5, 59.5, 76.5, 93.5,
  128909. };
  128910. static long _vq_quantmap__44c2_s_p9_1[] = {
  128911. 11, 9, 7, 5, 3, 1, 0, 2,
  128912. 4, 6, 8, 10, 12,
  128913. };
  128914. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_1 = {
  128915. _vq_quantthresh__44c2_s_p9_1,
  128916. _vq_quantmap__44c2_s_p9_1,
  128917. 13,
  128918. 13
  128919. };
  128920. static static_codebook _44c2_s_p9_1 = {
  128921. 2, 169,
  128922. _vq_lengthlist__44c2_s_p9_1,
  128923. 1, -522616832, 1620115456, 4, 0,
  128924. _vq_quantlist__44c2_s_p9_1,
  128925. NULL,
  128926. &_vq_auxt__44c2_s_p9_1,
  128927. NULL,
  128928. 0
  128929. };
  128930. static long _vq_quantlist__44c2_s_p9_2[] = {
  128931. 8,
  128932. 7,
  128933. 9,
  128934. 6,
  128935. 10,
  128936. 5,
  128937. 11,
  128938. 4,
  128939. 12,
  128940. 3,
  128941. 13,
  128942. 2,
  128943. 14,
  128944. 1,
  128945. 15,
  128946. 0,
  128947. 16,
  128948. };
  128949. static long _vq_lengthlist__44c2_s_p9_2[] = {
  128950. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  128951. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  128952. 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  128953. 9, 9, 9,10, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  128954. 9, 9, 9, 9,10,10,10, 8, 7, 8, 8, 8, 8, 9, 9, 9,
  128955. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  128956. 9, 9,10, 9, 9, 9,10,11,10, 8, 8, 8, 8, 9, 9, 9,
  128957. 9, 9, 9, 9,10,10,10,10,11,10, 8, 8, 9, 9, 9, 9,
  128958. 9, 9,10, 9, 9,10, 9,10,11,10,11,11,11, 8, 8, 9,
  128959. 9, 9, 9, 9, 9, 9, 9,10,10,11,11,11,11,11, 9, 9,
  128960. 9, 9, 9, 9,10, 9, 9, 9,10,10,11,11,11,11,11, 9,
  128961. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,11,11,11,11,11,
  128962. 9, 9, 9, 9,10,10, 9, 9, 9,10,10,10,11,11,11,11,
  128963. 11,11,11, 9, 9, 9,10, 9, 9,10,10,10,10,11,11,10,
  128964. 11,11,11,11,10, 9,10,10, 9, 9, 9, 9,10,10,11,10,
  128965. 11,11,11,11,11, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  128966. 10,11,11,11,11,11,10,10, 9, 9,10, 9,10,10,10,10,
  128967. 10,10,10,11,11,11,11,11,11, 9, 9,10, 9,10, 9,10,
  128968. 10,
  128969. };
  128970. static float _vq_quantthresh__44c2_s_p9_2[] = {
  128971. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128972. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128973. };
  128974. static long _vq_quantmap__44c2_s_p9_2[] = {
  128975. 15, 13, 11, 9, 7, 5, 3, 1,
  128976. 0, 2, 4, 6, 8, 10, 12, 14,
  128977. 16,
  128978. };
  128979. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_2 = {
  128980. _vq_quantthresh__44c2_s_p9_2,
  128981. _vq_quantmap__44c2_s_p9_2,
  128982. 17,
  128983. 17
  128984. };
  128985. static static_codebook _44c2_s_p9_2 = {
  128986. 2, 289,
  128987. _vq_lengthlist__44c2_s_p9_2,
  128988. 1, -529530880, 1611661312, 5, 0,
  128989. _vq_quantlist__44c2_s_p9_2,
  128990. NULL,
  128991. &_vq_auxt__44c2_s_p9_2,
  128992. NULL,
  128993. 0
  128994. };
  128995. static long _huff_lengthlist__44c2_s_short[] = {
  128996. 11, 9,13,12,12,11,12,12,13,15, 8, 2,11, 4, 8, 5,
  128997. 7,10,12,15,13, 7,10, 9, 8, 8,10,13,17,17,11, 4,
  128998. 12, 5, 9, 5, 8,11,14,16,12, 6, 8, 7, 6, 6, 8,11,
  128999. 13,16,11, 4, 9, 5, 6, 4, 6,10,13,16,11, 6,11, 7,
  129000. 7, 6, 7,10,13,15,13, 9,12, 9, 8, 6, 8,10,12,14,
  129001. 14,10,10, 8, 6, 5, 6, 9,11,13,15,11,11, 9, 6, 5,
  129002. 6, 8, 9,12,
  129003. };
  129004. static static_codebook _huff_book__44c2_s_short = {
  129005. 2, 100,
  129006. _huff_lengthlist__44c2_s_short,
  129007. 0, 0, 0, 0, 0,
  129008. NULL,
  129009. NULL,
  129010. NULL,
  129011. NULL,
  129012. 0
  129013. };
  129014. static long _huff_lengthlist__44c3_s_long[] = {
  129015. 5, 6,11,11,11,11,10,10,12,11, 5, 2,11, 5, 6, 6,
  129016. 7, 9,11,13,13,10, 7,11, 6, 7, 8, 9,10,12,11, 5,
  129017. 11, 6, 8, 7, 9,11,14,15,11, 6, 6, 8, 4, 5, 7, 8,
  129018. 10,13,10, 5, 7, 7, 5, 5, 6, 8,10,11,10, 7, 7, 8,
  129019. 6, 5, 5, 7, 9, 9,11, 8, 8,11, 8, 7, 6, 6, 7, 9,
  129020. 12,11,10,13, 9, 9, 7, 7, 7, 9,11,13,12,15,12,11,
  129021. 9, 8, 8, 8,
  129022. };
  129023. static static_codebook _huff_book__44c3_s_long = {
  129024. 2, 100,
  129025. _huff_lengthlist__44c3_s_long,
  129026. 0, 0, 0, 0, 0,
  129027. NULL,
  129028. NULL,
  129029. NULL,
  129030. NULL,
  129031. 0
  129032. };
  129033. static long _vq_quantlist__44c3_s_p1_0[] = {
  129034. 1,
  129035. 0,
  129036. 2,
  129037. };
  129038. static long _vq_lengthlist__44c3_s_p1_0[] = {
  129039. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  129040. 0, 0, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129044. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  129045. 0, 0, 0, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129049. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  129050. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 7, 0, 0, 0, 0,
  129085. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  129086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  129090. 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  129091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  129095. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  129096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  129131. 0, 0, 0, 0, 7, 8, 8, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  129136. 0, 0, 0, 0, 0, 7, 8, 9, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  129141. 0, 0, 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 0,
  129142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129449. 0,
  129450. };
  129451. static float _vq_quantthresh__44c3_s_p1_0[] = {
  129452. -0.5, 0.5,
  129453. };
  129454. static long _vq_quantmap__44c3_s_p1_0[] = {
  129455. 1, 0, 2,
  129456. };
  129457. static encode_aux_threshmatch _vq_auxt__44c3_s_p1_0 = {
  129458. _vq_quantthresh__44c3_s_p1_0,
  129459. _vq_quantmap__44c3_s_p1_0,
  129460. 3,
  129461. 3
  129462. };
  129463. static static_codebook _44c3_s_p1_0 = {
  129464. 8, 6561,
  129465. _vq_lengthlist__44c3_s_p1_0,
  129466. 1, -535822336, 1611661312, 2, 0,
  129467. _vq_quantlist__44c3_s_p1_0,
  129468. NULL,
  129469. &_vq_auxt__44c3_s_p1_0,
  129470. NULL,
  129471. 0
  129472. };
  129473. static long _vq_quantlist__44c3_s_p2_0[] = {
  129474. 2,
  129475. 1,
  129476. 3,
  129477. 0,
  129478. 4,
  129479. };
  129480. static long _vq_lengthlist__44c3_s_p2_0[] = {
  129481. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  129482. 7, 8, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  129483. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  129484. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  129485. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129490. 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0,
  129491. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  129492. 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  129493. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129498. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  129499. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  129500. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  129501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129506. 8,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  129507. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  129508. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  129509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129520. 0,
  129521. };
  129522. static float _vq_quantthresh__44c3_s_p2_0[] = {
  129523. -1.5, -0.5, 0.5, 1.5,
  129524. };
  129525. static long _vq_quantmap__44c3_s_p2_0[] = {
  129526. 3, 1, 0, 2, 4,
  129527. };
  129528. static encode_aux_threshmatch _vq_auxt__44c3_s_p2_0 = {
  129529. _vq_quantthresh__44c3_s_p2_0,
  129530. _vq_quantmap__44c3_s_p2_0,
  129531. 5,
  129532. 5
  129533. };
  129534. static static_codebook _44c3_s_p2_0 = {
  129535. 4, 625,
  129536. _vq_lengthlist__44c3_s_p2_0,
  129537. 1, -533725184, 1611661312, 3, 0,
  129538. _vq_quantlist__44c3_s_p2_0,
  129539. NULL,
  129540. &_vq_auxt__44c3_s_p2_0,
  129541. NULL,
  129542. 0
  129543. };
  129544. static long _vq_quantlist__44c3_s_p3_0[] = {
  129545. 2,
  129546. 1,
  129547. 3,
  129548. 0,
  129549. 4,
  129550. };
  129551. static long _vq_lengthlist__44c3_s_p3_0[] = {
  129552. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  129554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129555. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  129557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129558. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  129559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129591. 0,
  129592. };
  129593. static float _vq_quantthresh__44c3_s_p3_0[] = {
  129594. -1.5, -0.5, 0.5, 1.5,
  129595. };
  129596. static long _vq_quantmap__44c3_s_p3_0[] = {
  129597. 3, 1, 0, 2, 4,
  129598. };
  129599. static encode_aux_threshmatch _vq_auxt__44c3_s_p3_0 = {
  129600. _vq_quantthresh__44c3_s_p3_0,
  129601. _vq_quantmap__44c3_s_p3_0,
  129602. 5,
  129603. 5
  129604. };
  129605. static static_codebook _44c3_s_p3_0 = {
  129606. 4, 625,
  129607. _vq_lengthlist__44c3_s_p3_0,
  129608. 1, -533725184, 1611661312, 3, 0,
  129609. _vq_quantlist__44c3_s_p3_0,
  129610. NULL,
  129611. &_vq_auxt__44c3_s_p3_0,
  129612. NULL,
  129613. 0
  129614. };
  129615. static long _vq_quantlist__44c3_s_p4_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_p4_0[] = {
  129627. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  129628. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  129629. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  129630. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  129631. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129632. 0,
  129633. };
  129634. static float _vq_quantthresh__44c3_s_p4_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_p4_0[] = {
  129638. 7, 5, 3, 1, 0, 2, 4, 6,
  129639. 8,
  129640. };
  129641. static encode_aux_threshmatch _vq_auxt__44c3_s_p4_0 = {
  129642. _vq_quantthresh__44c3_s_p4_0,
  129643. _vq_quantmap__44c3_s_p4_0,
  129644. 9,
  129645. 9
  129646. };
  129647. static static_codebook _44c3_s_p4_0 = {
  129648. 2, 81,
  129649. _vq_lengthlist__44c3_s_p4_0,
  129650. 1, -531628032, 1611661312, 4, 0,
  129651. _vq_quantlist__44c3_s_p4_0,
  129652. NULL,
  129653. &_vq_auxt__44c3_s_p4_0,
  129654. NULL,
  129655. 0
  129656. };
  129657. static long _vq_quantlist__44c3_s_p5_0[] = {
  129658. 4,
  129659. 3,
  129660. 5,
  129661. 2,
  129662. 6,
  129663. 1,
  129664. 7,
  129665. 0,
  129666. 8,
  129667. };
  129668. static long _vq_lengthlist__44c3_s_p5_0[] = {
  129669. 1, 3, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 7, 8,
  129670. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  129671. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  129672. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  129673. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  129674. 11,
  129675. };
  129676. static float _vq_quantthresh__44c3_s_p5_0[] = {
  129677. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129678. };
  129679. static long _vq_quantmap__44c3_s_p5_0[] = {
  129680. 7, 5, 3, 1, 0, 2, 4, 6,
  129681. 8,
  129682. };
  129683. static encode_aux_threshmatch _vq_auxt__44c3_s_p5_0 = {
  129684. _vq_quantthresh__44c3_s_p5_0,
  129685. _vq_quantmap__44c3_s_p5_0,
  129686. 9,
  129687. 9
  129688. };
  129689. static static_codebook _44c3_s_p5_0 = {
  129690. 2, 81,
  129691. _vq_lengthlist__44c3_s_p5_0,
  129692. 1, -531628032, 1611661312, 4, 0,
  129693. _vq_quantlist__44c3_s_p5_0,
  129694. NULL,
  129695. &_vq_auxt__44c3_s_p5_0,
  129696. NULL,
  129697. 0
  129698. };
  129699. static long _vq_quantlist__44c3_s_p6_0[] = {
  129700. 8,
  129701. 7,
  129702. 9,
  129703. 6,
  129704. 10,
  129705. 5,
  129706. 11,
  129707. 4,
  129708. 12,
  129709. 3,
  129710. 13,
  129711. 2,
  129712. 14,
  129713. 1,
  129714. 15,
  129715. 0,
  129716. 16,
  129717. };
  129718. static long _vq_lengthlist__44c3_s_p6_0[] = {
  129719. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  129720. 10, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  129721. 11,11, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  129722. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  129723. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  129724. 10,11,11,11,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  129725. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  129726. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  129727. 10,10,11,10,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  129728. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 8,
  129729. 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8,
  129730. 8, 9, 9,10,10,11,11,12,11,12,12, 0, 0, 0, 0, 0,
  129731. 9,10,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0,
  129732. 0, 0, 0,10,10,10,10,11,11,12,12,13,13, 0, 0, 0,
  129733. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  129734. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  129735. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13,
  129736. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  129737. 13,
  129738. };
  129739. static float _vq_quantthresh__44c3_s_p6_0[] = {
  129740. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129741. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129742. };
  129743. static long _vq_quantmap__44c3_s_p6_0[] = {
  129744. 15, 13, 11, 9, 7, 5, 3, 1,
  129745. 0, 2, 4, 6, 8, 10, 12, 14,
  129746. 16,
  129747. };
  129748. static encode_aux_threshmatch _vq_auxt__44c3_s_p6_0 = {
  129749. _vq_quantthresh__44c3_s_p6_0,
  129750. _vq_quantmap__44c3_s_p6_0,
  129751. 17,
  129752. 17
  129753. };
  129754. static static_codebook _44c3_s_p6_0 = {
  129755. 2, 289,
  129756. _vq_lengthlist__44c3_s_p6_0,
  129757. 1, -529530880, 1611661312, 5, 0,
  129758. _vq_quantlist__44c3_s_p6_0,
  129759. NULL,
  129760. &_vq_auxt__44c3_s_p6_0,
  129761. NULL,
  129762. 0
  129763. };
  129764. static long _vq_quantlist__44c3_s_p7_0[] = {
  129765. 1,
  129766. 0,
  129767. 2,
  129768. };
  129769. static long _vq_lengthlist__44c3_s_p7_0[] = {
  129770. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  129771. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  129772. 10,12,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  129773. 11,10,10,11,10,10, 7,11,11,11,11,11,12,11,11, 6,
  129774. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  129775. 10,
  129776. };
  129777. static float _vq_quantthresh__44c3_s_p7_0[] = {
  129778. -5.5, 5.5,
  129779. };
  129780. static long _vq_quantmap__44c3_s_p7_0[] = {
  129781. 1, 0, 2,
  129782. };
  129783. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_0 = {
  129784. _vq_quantthresh__44c3_s_p7_0,
  129785. _vq_quantmap__44c3_s_p7_0,
  129786. 3,
  129787. 3
  129788. };
  129789. static static_codebook _44c3_s_p7_0 = {
  129790. 4, 81,
  129791. _vq_lengthlist__44c3_s_p7_0,
  129792. 1, -529137664, 1618345984, 2, 0,
  129793. _vq_quantlist__44c3_s_p7_0,
  129794. NULL,
  129795. &_vq_auxt__44c3_s_p7_0,
  129796. NULL,
  129797. 0
  129798. };
  129799. static long _vq_quantlist__44c3_s_p7_1[] = {
  129800. 5,
  129801. 4,
  129802. 6,
  129803. 3,
  129804. 7,
  129805. 2,
  129806. 8,
  129807. 1,
  129808. 9,
  129809. 0,
  129810. 10,
  129811. };
  129812. static long _vq_lengthlist__44c3_s_p7_1[] = {
  129813. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  129814. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  129815. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  129816. 7, 8, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  129817. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  129818. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  129819. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  129820. 10,10,10, 8, 8, 8, 8, 8, 8,
  129821. };
  129822. static float _vq_quantthresh__44c3_s_p7_1[] = {
  129823. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  129824. 3.5, 4.5,
  129825. };
  129826. static long _vq_quantmap__44c3_s_p7_1[] = {
  129827. 9, 7, 5, 3, 1, 0, 2, 4,
  129828. 6, 8, 10,
  129829. };
  129830. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_1 = {
  129831. _vq_quantthresh__44c3_s_p7_1,
  129832. _vq_quantmap__44c3_s_p7_1,
  129833. 11,
  129834. 11
  129835. };
  129836. static static_codebook _44c3_s_p7_1 = {
  129837. 2, 121,
  129838. _vq_lengthlist__44c3_s_p7_1,
  129839. 1, -531365888, 1611661312, 4, 0,
  129840. _vq_quantlist__44c3_s_p7_1,
  129841. NULL,
  129842. &_vq_auxt__44c3_s_p7_1,
  129843. NULL,
  129844. 0
  129845. };
  129846. static long _vq_quantlist__44c3_s_p8_0[] = {
  129847. 6,
  129848. 5,
  129849. 7,
  129850. 4,
  129851. 8,
  129852. 3,
  129853. 9,
  129854. 2,
  129855. 10,
  129856. 1,
  129857. 11,
  129858. 0,
  129859. 12,
  129860. };
  129861. static long _vq_lengthlist__44c3_s_p8_0[] = {
  129862. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  129863. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  129864. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  129865. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  129866. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,12, 0,13,
  129867. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  129868. 10,10,11,11,12,12,12,12, 0, 0, 0,10,10,10,10,11,
  129869. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  129870. 13,13, 0, 0, 0,14,14,11,11,11,11,12,12,13,13, 0,
  129871. 0, 0, 0, 0,12,12,12,12,13,13,14,13, 0, 0, 0, 0,
  129872. 0,13,13,12,12,13,12,14,13,
  129873. };
  129874. static float _vq_quantthresh__44c3_s_p8_0[] = {
  129875. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  129876. 12.5, 17.5, 22.5, 27.5,
  129877. };
  129878. static long _vq_quantmap__44c3_s_p8_0[] = {
  129879. 11, 9, 7, 5, 3, 1, 0, 2,
  129880. 4, 6, 8, 10, 12,
  129881. };
  129882. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_0 = {
  129883. _vq_quantthresh__44c3_s_p8_0,
  129884. _vq_quantmap__44c3_s_p8_0,
  129885. 13,
  129886. 13
  129887. };
  129888. static static_codebook _44c3_s_p8_0 = {
  129889. 2, 169,
  129890. _vq_lengthlist__44c3_s_p8_0,
  129891. 1, -526516224, 1616117760, 4, 0,
  129892. _vq_quantlist__44c3_s_p8_0,
  129893. NULL,
  129894. &_vq_auxt__44c3_s_p8_0,
  129895. NULL,
  129896. 0
  129897. };
  129898. static long _vq_quantlist__44c3_s_p8_1[] = {
  129899. 2,
  129900. 1,
  129901. 3,
  129902. 0,
  129903. 4,
  129904. };
  129905. static long _vq_lengthlist__44c3_s_p8_1[] = {
  129906. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  129907. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  129908. };
  129909. static float _vq_quantthresh__44c3_s_p8_1[] = {
  129910. -1.5, -0.5, 0.5, 1.5,
  129911. };
  129912. static long _vq_quantmap__44c3_s_p8_1[] = {
  129913. 3, 1, 0, 2, 4,
  129914. };
  129915. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_1 = {
  129916. _vq_quantthresh__44c3_s_p8_1,
  129917. _vq_quantmap__44c3_s_p8_1,
  129918. 5,
  129919. 5
  129920. };
  129921. static static_codebook _44c3_s_p8_1 = {
  129922. 2, 25,
  129923. _vq_lengthlist__44c3_s_p8_1,
  129924. 1, -533725184, 1611661312, 3, 0,
  129925. _vq_quantlist__44c3_s_p8_1,
  129926. NULL,
  129927. &_vq_auxt__44c3_s_p8_1,
  129928. NULL,
  129929. 0
  129930. };
  129931. static long _vq_quantlist__44c3_s_p9_0[] = {
  129932. 6,
  129933. 5,
  129934. 7,
  129935. 4,
  129936. 8,
  129937. 3,
  129938. 9,
  129939. 2,
  129940. 10,
  129941. 1,
  129942. 11,
  129943. 0,
  129944. 12,
  129945. };
  129946. static long _vq_lengthlist__44c3_s_p9_0[] = {
  129947. 1, 4, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  129948. 12,12,12,12,12,12,12,12,12,12, 2, 9, 7,12,12,12,
  129949. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129950. 12,12,12,12,12,12,11,12,12,12,12,12,12,12,12,12,
  129951. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129952. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129953. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129954. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129955. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  129956. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129957. 11,11,11,11,11,11,11,11,11,
  129958. };
  129959. static float _vq_quantthresh__44c3_s_p9_0[] = {
  129960. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  129961. 637.5, 892.5, 1147.5, 1402.5,
  129962. };
  129963. static long _vq_quantmap__44c3_s_p9_0[] = {
  129964. 11, 9, 7, 5, 3, 1, 0, 2,
  129965. 4, 6, 8, 10, 12,
  129966. };
  129967. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_0 = {
  129968. _vq_quantthresh__44c3_s_p9_0,
  129969. _vq_quantmap__44c3_s_p9_0,
  129970. 13,
  129971. 13
  129972. };
  129973. static static_codebook _44c3_s_p9_0 = {
  129974. 2, 169,
  129975. _vq_lengthlist__44c3_s_p9_0,
  129976. 1, -514332672, 1627381760, 4, 0,
  129977. _vq_quantlist__44c3_s_p9_0,
  129978. NULL,
  129979. &_vq_auxt__44c3_s_p9_0,
  129980. NULL,
  129981. 0
  129982. };
  129983. static long _vq_quantlist__44c3_s_p9_1[] = {
  129984. 7,
  129985. 6,
  129986. 8,
  129987. 5,
  129988. 9,
  129989. 4,
  129990. 10,
  129991. 3,
  129992. 11,
  129993. 2,
  129994. 12,
  129995. 1,
  129996. 13,
  129997. 0,
  129998. 14,
  129999. };
  130000. static long _vq_lengthlist__44c3_s_p9_1[] = {
  130001. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 9,10,10,10,10, 6,
  130002. 5, 5, 7, 7, 8, 8,10, 8,11,10,12,12,13,13, 6, 5,
  130003. 5, 7, 7, 8, 8,10, 9,11,11,12,12,13,12,18, 8, 8,
  130004. 8, 8, 9, 9,10, 9,11,10,12,12,13,13,18, 8, 8, 8,
  130005. 8, 9, 9,10,10,11,11,13,12,14,13,18,11,11, 9, 9,
  130006. 10,10,11,11,11,12,13,12,13,14,18,11,11, 9, 8,11,
  130007. 10,11,11,11,11,12,12,14,13,18,18,18,10,11,10,11,
  130008. 12,12,12,12,13,12,14,13,18,18,18,10,11,11, 9,12,
  130009. 11,12,12,12,13,13,13,18,18,17,14,14,11,11,12,12,
  130010. 13,12,14,12,14,13,18,18,18,14,14,11,10,12, 9,12,
  130011. 13,13,13,13,13,18,18,17,16,18,13,13,12,12,13,11,
  130012. 14,12,14,14,17,18,18,17,18,13,12,13,10,12,11,14,
  130013. 14,14,14,17,18,18,18,18,15,16,12,12,13,10,14,12,
  130014. 14,15,18,18,18,16,17,16,14,12,11,13,10,13,13,14,
  130015. 15,
  130016. };
  130017. static float _vq_quantthresh__44c3_s_p9_1[] = {
  130018. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  130019. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  130020. };
  130021. static long _vq_quantmap__44c3_s_p9_1[] = {
  130022. 13, 11, 9, 7, 5, 3, 1, 0,
  130023. 2, 4, 6, 8, 10, 12, 14,
  130024. };
  130025. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_1 = {
  130026. _vq_quantthresh__44c3_s_p9_1,
  130027. _vq_quantmap__44c3_s_p9_1,
  130028. 15,
  130029. 15
  130030. };
  130031. static static_codebook _44c3_s_p9_1 = {
  130032. 2, 225,
  130033. _vq_lengthlist__44c3_s_p9_1,
  130034. 1, -522338304, 1620115456, 4, 0,
  130035. _vq_quantlist__44c3_s_p9_1,
  130036. NULL,
  130037. &_vq_auxt__44c3_s_p9_1,
  130038. NULL,
  130039. 0
  130040. };
  130041. static long _vq_quantlist__44c3_s_p9_2[] = {
  130042. 8,
  130043. 7,
  130044. 9,
  130045. 6,
  130046. 10,
  130047. 5,
  130048. 11,
  130049. 4,
  130050. 12,
  130051. 3,
  130052. 13,
  130053. 2,
  130054. 14,
  130055. 1,
  130056. 15,
  130057. 0,
  130058. 16,
  130059. };
  130060. static long _vq_lengthlist__44c3_s_p9_2[] = {
  130061. 2, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  130062. 8,10, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 8, 9, 9, 9,
  130063. 9, 9,10, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  130064. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  130065. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  130066. 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  130067. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  130068. 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 9, 9, 9, 9, 9,
  130069. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 9, 9, 9,
  130070. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  130071. 9, 9, 9, 9,10,10, 9, 9,10, 9,11,10,11,11,11, 9,
  130072. 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,11,11,11,11,11,
  130073. 9, 9, 9, 9,10,10, 9, 9, 9, 9,10, 9,11,11,11,11,
  130074. 11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11,
  130075. 11,11,11,11,10, 9,10,10, 9,10, 9, 9,10, 9,11,10,
  130076. 10,11,11,11,11, 9,10, 9, 9, 9, 9,10,10,10,10,11,
  130077. 11,11,11,11,11,10,10,10, 9, 9,10, 9,10, 9,10,10,
  130078. 10,10,11,11,11,11,11,11,11, 9, 9, 9, 9, 9,10,10,
  130079. 10,
  130080. };
  130081. static float _vq_quantthresh__44c3_s_p9_2[] = {
  130082. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130083. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130084. };
  130085. static long _vq_quantmap__44c3_s_p9_2[] = {
  130086. 15, 13, 11, 9, 7, 5, 3, 1,
  130087. 0, 2, 4, 6, 8, 10, 12, 14,
  130088. 16,
  130089. };
  130090. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_2 = {
  130091. _vq_quantthresh__44c3_s_p9_2,
  130092. _vq_quantmap__44c3_s_p9_2,
  130093. 17,
  130094. 17
  130095. };
  130096. static static_codebook _44c3_s_p9_2 = {
  130097. 2, 289,
  130098. _vq_lengthlist__44c3_s_p9_2,
  130099. 1, -529530880, 1611661312, 5, 0,
  130100. _vq_quantlist__44c3_s_p9_2,
  130101. NULL,
  130102. &_vq_auxt__44c3_s_p9_2,
  130103. NULL,
  130104. 0
  130105. };
  130106. static long _huff_lengthlist__44c3_s_short[] = {
  130107. 10, 9,13,11,14,10,12,13,13,14, 7, 2,12, 5,10, 5,
  130108. 7,10,12,14,12, 6, 9, 8, 7, 7, 9,11,13,16,10, 4,
  130109. 12, 5,10, 6, 8,12,14,16,12, 6, 8, 7, 6, 5, 7,11,
  130110. 12,16,10, 4, 8, 5, 6, 4, 6, 9,13,16,10, 6,10, 7,
  130111. 7, 6, 7, 9,13,15,12, 9,11, 9, 8, 6, 7,10,12,14,
  130112. 14,11,10, 9, 6, 5, 6, 9,11,13,15,13,11,10, 6, 5,
  130113. 6, 8, 9,11,
  130114. };
  130115. static static_codebook _huff_book__44c3_s_short = {
  130116. 2, 100,
  130117. _huff_lengthlist__44c3_s_short,
  130118. 0, 0, 0, 0, 0,
  130119. NULL,
  130120. NULL,
  130121. NULL,
  130122. NULL,
  130123. 0
  130124. };
  130125. static long _huff_lengthlist__44c4_s_long[] = {
  130126. 4, 7,11,11,11,11,10,11,12,11, 5, 2,11, 5, 6, 6,
  130127. 7, 9,11,12,11, 9, 6,10, 6, 7, 8, 9,10,11,11, 5,
  130128. 11, 7, 8, 8, 9,11,13,14,11, 6, 5, 8, 4, 5, 7, 8,
  130129. 10,11,10, 6, 7, 7, 5, 5, 6, 8, 9,11,10, 7, 8, 9,
  130130. 6, 6, 6, 7, 8, 9,11, 9, 9,11, 7, 7, 6, 6, 7, 9,
  130131. 12,12,10,13, 9, 8, 7, 7, 7, 8,11,13,11,14,11,10,
  130132. 9, 8, 7, 7,
  130133. };
  130134. static static_codebook _huff_book__44c4_s_long = {
  130135. 2, 100,
  130136. _huff_lengthlist__44c4_s_long,
  130137. 0, 0, 0, 0, 0,
  130138. NULL,
  130139. NULL,
  130140. NULL,
  130141. NULL,
  130142. 0
  130143. };
  130144. static long _vq_quantlist__44c4_s_p1_0[] = {
  130145. 1,
  130146. 0,
  130147. 2,
  130148. };
  130149. static long _vq_lengthlist__44c4_s_p1_0[] = {
  130150. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  130151. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130155. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  130156. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130160. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  130161. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 7, 0, 0, 0, 0,
  130196. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  130197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  130201. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  130202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  130206. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  130207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  130242. 0, 0, 0, 0, 7, 8, 8, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  130247. 0, 0, 0, 0, 0, 8, 8, 9, 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, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  130252. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  130253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130560. 0,
  130561. };
  130562. static float _vq_quantthresh__44c4_s_p1_0[] = {
  130563. -0.5, 0.5,
  130564. };
  130565. static long _vq_quantmap__44c4_s_p1_0[] = {
  130566. 1, 0, 2,
  130567. };
  130568. static encode_aux_threshmatch _vq_auxt__44c4_s_p1_0 = {
  130569. _vq_quantthresh__44c4_s_p1_0,
  130570. _vq_quantmap__44c4_s_p1_0,
  130571. 3,
  130572. 3
  130573. };
  130574. static static_codebook _44c4_s_p1_0 = {
  130575. 8, 6561,
  130576. _vq_lengthlist__44c4_s_p1_0,
  130577. 1, -535822336, 1611661312, 2, 0,
  130578. _vq_quantlist__44c4_s_p1_0,
  130579. NULL,
  130580. &_vq_auxt__44c4_s_p1_0,
  130581. NULL,
  130582. 0
  130583. };
  130584. static long _vq_quantlist__44c4_s_p2_0[] = {
  130585. 2,
  130586. 1,
  130587. 3,
  130588. 0,
  130589. 4,
  130590. };
  130591. static long _vq_lengthlist__44c4_s_p2_0[] = {
  130592. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  130593. 7, 7, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  130594. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  130595. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  130596. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130601. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 7, 7, 0, 0,
  130602. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  130603. 7, 8, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  130604. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130609. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  130610. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  130611. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  130612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130617. 7,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  130618. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  130619. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  130620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130631. 0,
  130632. };
  130633. static float _vq_quantthresh__44c4_s_p2_0[] = {
  130634. -1.5, -0.5, 0.5, 1.5,
  130635. };
  130636. static long _vq_quantmap__44c4_s_p2_0[] = {
  130637. 3, 1, 0, 2, 4,
  130638. };
  130639. static encode_aux_threshmatch _vq_auxt__44c4_s_p2_0 = {
  130640. _vq_quantthresh__44c4_s_p2_0,
  130641. _vq_quantmap__44c4_s_p2_0,
  130642. 5,
  130643. 5
  130644. };
  130645. static static_codebook _44c4_s_p2_0 = {
  130646. 4, 625,
  130647. _vq_lengthlist__44c4_s_p2_0,
  130648. 1, -533725184, 1611661312, 3, 0,
  130649. _vq_quantlist__44c4_s_p2_0,
  130650. NULL,
  130651. &_vq_auxt__44c4_s_p2_0,
  130652. NULL,
  130653. 0
  130654. };
  130655. static long _vq_quantlist__44c4_s_p3_0[] = {
  130656. 2,
  130657. 1,
  130658. 3,
  130659. 0,
  130660. 4,
  130661. };
  130662. static long _vq_lengthlist__44c4_s_p3_0[] = {
  130663. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 4, 6, 6, 0, 0,
  130665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130666. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  130668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130669. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  130670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130702. 0,
  130703. };
  130704. static float _vq_quantthresh__44c4_s_p3_0[] = {
  130705. -1.5, -0.5, 0.5, 1.5,
  130706. };
  130707. static long _vq_quantmap__44c4_s_p3_0[] = {
  130708. 3, 1, 0, 2, 4,
  130709. };
  130710. static encode_aux_threshmatch _vq_auxt__44c4_s_p3_0 = {
  130711. _vq_quantthresh__44c4_s_p3_0,
  130712. _vq_quantmap__44c4_s_p3_0,
  130713. 5,
  130714. 5
  130715. };
  130716. static static_codebook _44c4_s_p3_0 = {
  130717. 4, 625,
  130718. _vq_lengthlist__44c4_s_p3_0,
  130719. 1, -533725184, 1611661312, 3, 0,
  130720. _vq_quantlist__44c4_s_p3_0,
  130721. NULL,
  130722. &_vq_auxt__44c4_s_p3_0,
  130723. NULL,
  130724. 0
  130725. };
  130726. static long _vq_quantlist__44c4_s_p4_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_p4_0[] = {
  130738. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  130739. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  130740. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  130741. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  130742. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130743. 0,
  130744. };
  130745. static float _vq_quantthresh__44c4_s_p4_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_p4_0[] = {
  130749. 7, 5, 3, 1, 0, 2, 4, 6,
  130750. 8,
  130751. };
  130752. static encode_aux_threshmatch _vq_auxt__44c4_s_p4_0 = {
  130753. _vq_quantthresh__44c4_s_p4_0,
  130754. _vq_quantmap__44c4_s_p4_0,
  130755. 9,
  130756. 9
  130757. };
  130758. static static_codebook _44c4_s_p4_0 = {
  130759. 2, 81,
  130760. _vq_lengthlist__44c4_s_p4_0,
  130761. 1, -531628032, 1611661312, 4, 0,
  130762. _vq_quantlist__44c4_s_p4_0,
  130763. NULL,
  130764. &_vq_auxt__44c4_s_p4_0,
  130765. NULL,
  130766. 0
  130767. };
  130768. static long _vq_quantlist__44c4_s_p5_0[] = {
  130769. 4,
  130770. 3,
  130771. 5,
  130772. 2,
  130773. 6,
  130774. 1,
  130775. 7,
  130776. 0,
  130777. 8,
  130778. };
  130779. static long _vq_lengthlist__44c4_s_p5_0[] = {
  130780. 2, 3, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  130781. 9, 9, 0, 4, 5, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  130782. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10, 9, 0, 0, 0,
  130783. 9, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  130784. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,10,
  130785. 10,
  130786. };
  130787. static float _vq_quantthresh__44c4_s_p5_0[] = {
  130788. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130789. };
  130790. static long _vq_quantmap__44c4_s_p5_0[] = {
  130791. 7, 5, 3, 1, 0, 2, 4, 6,
  130792. 8,
  130793. };
  130794. static encode_aux_threshmatch _vq_auxt__44c4_s_p5_0 = {
  130795. _vq_quantthresh__44c4_s_p5_0,
  130796. _vq_quantmap__44c4_s_p5_0,
  130797. 9,
  130798. 9
  130799. };
  130800. static static_codebook _44c4_s_p5_0 = {
  130801. 2, 81,
  130802. _vq_lengthlist__44c4_s_p5_0,
  130803. 1, -531628032, 1611661312, 4, 0,
  130804. _vq_quantlist__44c4_s_p5_0,
  130805. NULL,
  130806. &_vq_auxt__44c4_s_p5_0,
  130807. NULL,
  130808. 0
  130809. };
  130810. static long _vq_quantlist__44c4_s_p6_0[] = {
  130811. 8,
  130812. 7,
  130813. 9,
  130814. 6,
  130815. 10,
  130816. 5,
  130817. 11,
  130818. 4,
  130819. 12,
  130820. 3,
  130821. 13,
  130822. 2,
  130823. 14,
  130824. 1,
  130825. 15,
  130826. 0,
  130827. 16,
  130828. };
  130829. static long _vq_lengthlist__44c4_s_p6_0[] = {
  130830. 2, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  130831. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  130832. 11,11, 0, 4, 4, 7, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  130833. 11,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  130834. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  130835. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  130836. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  130837. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  130838. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  130839. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  130840. 9,10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9,
  130841. 9, 9, 9,10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0,
  130842. 10,10,10,10,11,11,11,11,12,12,13,12, 0, 0, 0, 0,
  130843. 0, 0, 0,10,10,11,11,11,11,12,12,12,12, 0, 0, 0,
  130844. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  130845. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  130846. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,13,13,
  130847. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,
  130848. 13,
  130849. };
  130850. static float _vq_quantthresh__44c4_s_p6_0[] = {
  130851. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130852. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130853. };
  130854. static long _vq_quantmap__44c4_s_p6_0[] = {
  130855. 15, 13, 11, 9, 7, 5, 3, 1,
  130856. 0, 2, 4, 6, 8, 10, 12, 14,
  130857. 16,
  130858. };
  130859. static encode_aux_threshmatch _vq_auxt__44c4_s_p6_0 = {
  130860. _vq_quantthresh__44c4_s_p6_0,
  130861. _vq_quantmap__44c4_s_p6_0,
  130862. 17,
  130863. 17
  130864. };
  130865. static static_codebook _44c4_s_p6_0 = {
  130866. 2, 289,
  130867. _vq_lengthlist__44c4_s_p6_0,
  130868. 1, -529530880, 1611661312, 5, 0,
  130869. _vq_quantlist__44c4_s_p6_0,
  130870. NULL,
  130871. &_vq_auxt__44c4_s_p6_0,
  130872. NULL,
  130873. 0
  130874. };
  130875. static long _vq_quantlist__44c4_s_p7_0[] = {
  130876. 1,
  130877. 0,
  130878. 2,
  130879. };
  130880. static long _vq_lengthlist__44c4_s_p7_0[] = {
  130881. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  130882. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  130883. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  130884. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  130885. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  130886. 10,
  130887. };
  130888. static float _vq_quantthresh__44c4_s_p7_0[] = {
  130889. -5.5, 5.5,
  130890. };
  130891. static long _vq_quantmap__44c4_s_p7_0[] = {
  130892. 1, 0, 2,
  130893. };
  130894. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_0 = {
  130895. _vq_quantthresh__44c4_s_p7_0,
  130896. _vq_quantmap__44c4_s_p7_0,
  130897. 3,
  130898. 3
  130899. };
  130900. static static_codebook _44c4_s_p7_0 = {
  130901. 4, 81,
  130902. _vq_lengthlist__44c4_s_p7_0,
  130903. 1, -529137664, 1618345984, 2, 0,
  130904. _vq_quantlist__44c4_s_p7_0,
  130905. NULL,
  130906. &_vq_auxt__44c4_s_p7_0,
  130907. NULL,
  130908. 0
  130909. };
  130910. static long _vq_quantlist__44c4_s_p7_1[] = {
  130911. 5,
  130912. 4,
  130913. 6,
  130914. 3,
  130915. 7,
  130916. 2,
  130917. 8,
  130918. 1,
  130919. 9,
  130920. 0,
  130921. 10,
  130922. };
  130923. static long _vq_lengthlist__44c4_s_p7_1[] = {
  130924. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  130925. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  130926. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  130927. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  130928. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  130929. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  130930. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  130931. 10,10,10, 8, 8, 8, 8, 9, 9,
  130932. };
  130933. static float _vq_quantthresh__44c4_s_p7_1[] = {
  130934. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  130935. 3.5, 4.5,
  130936. };
  130937. static long _vq_quantmap__44c4_s_p7_1[] = {
  130938. 9, 7, 5, 3, 1, 0, 2, 4,
  130939. 6, 8, 10,
  130940. };
  130941. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_1 = {
  130942. _vq_quantthresh__44c4_s_p7_1,
  130943. _vq_quantmap__44c4_s_p7_1,
  130944. 11,
  130945. 11
  130946. };
  130947. static static_codebook _44c4_s_p7_1 = {
  130948. 2, 121,
  130949. _vq_lengthlist__44c4_s_p7_1,
  130950. 1, -531365888, 1611661312, 4, 0,
  130951. _vq_quantlist__44c4_s_p7_1,
  130952. NULL,
  130953. &_vq_auxt__44c4_s_p7_1,
  130954. NULL,
  130955. 0
  130956. };
  130957. static long _vq_quantlist__44c4_s_p8_0[] = {
  130958. 6,
  130959. 5,
  130960. 7,
  130961. 4,
  130962. 8,
  130963. 3,
  130964. 9,
  130965. 2,
  130966. 10,
  130967. 1,
  130968. 11,
  130969. 0,
  130970. 12,
  130971. };
  130972. static long _vq_lengthlist__44c4_s_p8_0[] = {
  130973. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  130974. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  130975. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  130976. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  130977. 11, 0,12,12, 9, 9, 9, 9,10,10,10,10,11,11, 0,13,
  130978. 13, 9, 9,10, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  130979. 10,10,10,10,11,11,12,12, 0, 0, 0,10,10,10,10,10,
  130980. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  130981. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,13, 0,
  130982. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  130983. 0,13,12,12,12,12,12,13,13,
  130984. };
  130985. static float _vq_quantthresh__44c4_s_p8_0[] = {
  130986. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  130987. 12.5, 17.5, 22.5, 27.5,
  130988. };
  130989. static long _vq_quantmap__44c4_s_p8_0[] = {
  130990. 11, 9, 7, 5, 3, 1, 0, 2,
  130991. 4, 6, 8, 10, 12,
  130992. };
  130993. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_0 = {
  130994. _vq_quantthresh__44c4_s_p8_0,
  130995. _vq_quantmap__44c4_s_p8_0,
  130996. 13,
  130997. 13
  130998. };
  130999. static static_codebook _44c4_s_p8_0 = {
  131000. 2, 169,
  131001. _vq_lengthlist__44c4_s_p8_0,
  131002. 1, -526516224, 1616117760, 4, 0,
  131003. _vq_quantlist__44c4_s_p8_0,
  131004. NULL,
  131005. &_vq_auxt__44c4_s_p8_0,
  131006. NULL,
  131007. 0
  131008. };
  131009. static long _vq_quantlist__44c4_s_p8_1[] = {
  131010. 2,
  131011. 1,
  131012. 3,
  131013. 0,
  131014. 4,
  131015. };
  131016. static long _vq_lengthlist__44c4_s_p8_1[] = {
  131017. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 5, 4, 5, 5, 6,
  131018. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  131019. };
  131020. static float _vq_quantthresh__44c4_s_p8_1[] = {
  131021. -1.5, -0.5, 0.5, 1.5,
  131022. };
  131023. static long _vq_quantmap__44c4_s_p8_1[] = {
  131024. 3, 1, 0, 2, 4,
  131025. };
  131026. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_1 = {
  131027. _vq_quantthresh__44c4_s_p8_1,
  131028. _vq_quantmap__44c4_s_p8_1,
  131029. 5,
  131030. 5
  131031. };
  131032. static static_codebook _44c4_s_p8_1 = {
  131033. 2, 25,
  131034. _vq_lengthlist__44c4_s_p8_1,
  131035. 1, -533725184, 1611661312, 3, 0,
  131036. _vq_quantlist__44c4_s_p8_1,
  131037. NULL,
  131038. &_vq_auxt__44c4_s_p8_1,
  131039. NULL,
  131040. 0
  131041. };
  131042. static long _vq_quantlist__44c4_s_p9_0[] = {
  131043. 6,
  131044. 5,
  131045. 7,
  131046. 4,
  131047. 8,
  131048. 3,
  131049. 9,
  131050. 2,
  131051. 10,
  131052. 1,
  131053. 11,
  131054. 0,
  131055. 12,
  131056. };
  131057. static long _vq_lengthlist__44c4_s_p9_0[] = {
  131058. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 4, 7, 7,
  131059. 12,12,12,12,12,12,12,12,12,12, 3, 8, 8,12,12,12,
  131060. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131061. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131062. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131063. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131064. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131065. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131066. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131067. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131068. 12,12,12,12,12,12,12,12,12,
  131069. };
  131070. static float _vq_quantthresh__44c4_s_p9_0[] = {
  131071. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  131072. 787.5, 1102.5, 1417.5, 1732.5,
  131073. };
  131074. static long _vq_quantmap__44c4_s_p9_0[] = {
  131075. 11, 9, 7, 5, 3, 1, 0, 2,
  131076. 4, 6, 8, 10, 12,
  131077. };
  131078. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_0 = {
  131079. _vq_quantthresh__44c4_s_p9_0,
  131080. _vq_quantmap__44c4_s_p9_0,
  131081. 13,
  131082. 13
  131083. };
  131084. static static_codebook _44c4_s_p9_0 = {
  131085. 2, 169,
  131086. _vq_lengthlist__44c4_s_p9_0,
  131087. 1, -513964032, 1628680192, 4, 0,
  131088. _vq_quantlist__44c4_s_p9_0,
  131089. NULL,
  131090. &_vq_auxt__44c4_s_p9_0,
  131091. NULL,
  131092. 0
  131093. };
  131094. static long _vq_quantlist__44c4_s_p9_1[] = {
  131095. 7,
  131096. 6,
  131097. 8,
  131098. 5,
  131099. 9,
  131100. 4,
  131101. 10,
  131102. 3,
  131103. 11,
  131104. 2,
  131105. 12,
  131106. 1,
  131107. 13,
  131108. 0,
  131109. 14,
  131110. };
  131111. static long _vq_lengthlist__44c4_s_p9_1[] = {
  131112. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,10,10, 6,
  131113. 5, 5, 7, 7, 9, 8,10, 9,11,10,12,12,13,13, 6, 5,
  131114. 5, 7, 7, 9, 9,10,10,11,11,12,12,12,13,19, 8, 8,
  131115. 8, 8, 9, 9,10,10,12,11,12,12,13,13,19, 8, 8, 8,
  131116. 8, 9, 9,11,11,12,12,13,13,13,13,19,12,12, 9, 9,
  131117. 11,11,11,11,12,11,13,12,13,13,18,12,12, 9, 9,11,
  131118. 10,11,11,12,12,12,13,13,14,19,18,18,11,11,11,11,
  131119. 12,12,13,12,13,13,14,14,16,18,18,11,11,11,10,12,
  131120. 11,13,13,13,13,13,14,17,18,18,14,15,11,12,12,13,
  131121. 13,13,13,14,14,14,18,18,18,15,15,12,10,13,10,13,
  131122. 13,13,13,13,14,18,17,18,17,18,12,13,12,13,13,13,
  131123. 14,14,16,14,18,17,18,18,17,13,12,13,10,12,12,14,
  131124. 14,14,14,17,18,18,18,18,14,15,12,12,13,12,14,14,
  131125. 15,15,18,18,18,17,18,15,14,12,11,12,12,14,14,14,
  131126. 15,
  131127. };
  131128. static float _vq_quantthresh__44c4_s_p9_1[] = {
  131129. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  131130. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  131131. };
  131132. static long _vq_quantmap__44c4_s_p9_1[] = {
  131133. 13, 11, 9, 7, 5, 3, 1, 0,
  131134. 2, 4, 6, 8, 10, 12, 14,
  131135. };
  131136. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_1 = {
  131137. _vq_quantthresh__44c4_s_p9_1,
  131138. _vq_quantmap__44c4_s_p9_1,
  131139. 15,
  131140. 15
  131141. };
  131142. static static_codebook _44c4_s_p9_1 = {
  131143. 2, 225,
  131144. _vq_lengthlist__44c4_s_p9_1,
  131145. 1, -520986624, 1620377600, 4, 0,
  131146. _vq_quantlist__44c4_s_p9_1,
  131147. NULL,
  131148. &_vq_auxt__44c4_s_p9_1,
  131149. NULL,
  131150. 0
  131151. };
  131152. static long _vq_quantlist__44c4_s_p9_2[] = {
  131153. 10,
  131154. 9,
  131155. 11,
  131156. 8,
  131157. 12,
  131158. 7,
  131159. 13,
  131160. 6,
  131161. 14,
  131162. 5,
  131163. 15,
  131164. 4,
  131165. 16,
  131166. 3,
  131167. 17,
  131168. 2,
  131169. 18,
  131170. 1,
  131171. 19,
  131172. 0,
  131173. 20,
  131174. };
  131175. static long _vq_lengthlist__44c4_s_p9_2[] = {
  131176. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  131177. 8, 9, 9, 9, 9,11, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  131178. 9, 9, 9, 9, 9, 9,10,10,10,10,11, 6, 6, 7, 7, 8,
  131179. 8, 8, 8, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  131180. 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  131181. 10,10,10,10,12,11,11, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  131182. 9,10,10,10,10,10,10,10,10,12,11,12, 8, 8, 8, 8,
  131183. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  131184. 11, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,
  131185. 10,10,10,11,11,12, 9, 9, 9, 9, 9, 9,10, 9,10,10,
  131186. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  131187. 9,10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,
  131188. 11,11, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  131189. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  131190. 10,10,10,10,10,10,10,11,11,11,12,12,10,10,10,10,
  131191. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,12,
  131192. 11,11,11, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  131193. 10,11,12,11,11,11,11,11,10,10,10,10,10,10,10,10,
  131194. 10,10,10,10,10,10,11,11,11,12,11,11,11,10,10,10,
  131195. 10,10,10,10,10,10,10,10,10,10,10,12,11,11,12,11,
  131196. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131197. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  131198. 10,10,10,10,10,11,11,11,11,12,12,11,11,11,11,11,
  131199. 11,11,10,10,10,10,10,10,10,10,12,12,12,11,11,11,
  131200. 12,11,11,11,10,10,10,10,10,10,10,10,10,10,10,12,
  131201. 11,12,12,12,12,12,11,12,11,11,10,10,10,10,10,10,
  131202. 10,10,10,10,12,12,12,12,11,11,11,11,11,11,11,10,
  131203. 10,10,10,10,10,10,10,10,10,
  131204. };
  131205. static float _vq_quantthresh__44c4_s_p9_2[] = {
  131206. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  131207. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  131208. 6.5, 7.5, 8.5, 9.5,
  131209. };
  131210. static long _vq_quantmap__44c4_s_p9_2[] = {
  131211. 19, 17, 15, 13, 11, 9, 7, 5,
  131212. 3, 1, 0, 2, 4, 6, 8, 10,
  131213. 12, 14, 16, 18, 20,
  131214. };
  131215. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_2 = {
  131216. _vq_quantthresh__44c4_s_p9_2,
  131217. _vq_quantmap__44c4_s_p9_2,
  131218. 21,
  131219. 21
  131220. };
  131221. static static_codebook _44c4_s_p9_2 = {
  131222. 2, 441,
  131223. _vq_lengthlist__44c4_s_p9_2,
  131224. 1, -529268736, 1611661312, 5, 0,
  131225. _vq_quantlist__44c4_s_p9_2,
  131226. NULL,
  131227. &_vq_auxt__44c4_s_p9_2,
  131228. NULL,
  131229. 0
  131230. };
  131231. static long _huff_lengthlist__44c4_s_short[] = {
  131232. 4, 7,14,10,15,10,12,15,16,15, 4, 2,11, 5,10, 6,
  131233. 8,11,14,14,14,10, 7,11, 6, 8,10,11,13,15, 9, 4,
  131234. 11, 5, 9, 6, 9,12,14,15,14, 9, 6, 9, 4, 5, 7,10,
  131235. 12,13, 9, 5, 7, 6, 5, 5, 7,10,13,13,10, 8, 9, 8,
  131236. 7, 6, 8,10,14,14,13,11,10,10, 7, 7, 8,11,14,15,
  131237. 13,12, 9, 9, 6, 5, 7,10,14,17,15,13,11,10, 6, 6,
  131238. 7, 9,12,17,
  131239. };
  131240. static static_codebook _huff_book__44c4_s_short = {
  131241. 2, 100,
  131242. _huff_lengthlist__44c4_s_short,
  131243. 0, 0, 0, 0, 0,
  131244. NULL,
  131245. NULL,
  131246. NULL,
  131247. NULL,
  131248. 0
  131249. };
  131250. static long _huff_lengthlist__44c5_s_long[] = {
  131251. 3, 8, 9,13,10,12,12,12,12,12, 6, 4, 6, 8, 6, 8,
  131252. 10,10,11,12, 8, 5, 4,10, 4, 7, 8, 9,10,11,13, 8,
  131253. 10, 8, 9, 9,11,12,13,14,10, 6, 4, 9, 3, 5, 6, 8,
  131254. 10,11,11, 8, 6, 9, 5, 5, 6, 7, 9,11,12, 9, 7,11,
  131255. 6, 6, 6, 7, 8,10,12,11, 9,12, 7, 7, 6, 6, 7, 9,
  131256. 13,12,10,13, 9, 8, 7, 7, 7, 8,11,15,11,15,11,10,
  131257. 9, 8, 7, 7,
  131258. };
  131259. static static_codebook _huff_book__44c5_s_long = {
  131260. 2, 100,
  131261. _huff_lengthlist__44c5_s_long,
  131262. 0, 0, 0, 0, 0,
  131263. NULL,
  131264. NULL,
  131265. NULL,
  131266. NULL,
  131267. 0
  131268. };
  131269. static long _vq_quantlist__44c5_s_p1_0[] = {
  131270. 1,
  131271. 0,
  131272. 2,
  131273. };
  131274. static long _vq_lengthlist__44c5_s_p1_0[] = {
  131275. 2, 4, 4, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  131276. 0, 0, 4, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131280. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  131281. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131285. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  131286. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 4, 7, 7, 0, 0, 0, 0,
  131321. 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  131322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  131326. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  131327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  131331. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  131332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  131367. 0, 0, 0, 0, 7, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  131372. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  131377. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  131378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131685. 0,
  131686. };
  131687. static float _vq_quantthresh__44c5_s_p1_0[] = {
  131688. -0.5, 0.5,
  131689. };
  131690. static long _vq_quantmap__44c5_s_p1_0[] = {
  131691. 1, 0, 2,
  131692. };
  131693. static encode_aux_threshmatch _vq_auxt__44c5_s_p1_0 = {
  131694. _vq_quantthresh__44c5_s_p1_0,
  131695. _vq_quantmap__44c5_s_p1_0,
  131696. 3,
  131697. 3
  131698. };
  131699. static static_codebook _44c5_s_p1_0 = {
  131700. 8, 6561,
  131701. _vq_lengthlist__44c5_s_p1_0,
  131702. 1, -535822336, 1611661312, 2, 0,
  131703. _vq_quantlist__44c5_s_p1_0,
  131704. NULL,
  131705. &_vq_auxt__44c5_s_p1_0,
  131706. NULL,
  131707. 0
  131708. };
  131709. static long _vq_quantlist__44c5_s_p2_0[] = {
  131710. 2,
  131711. 1,
  131712. 3,
  131713. 0,
  131714. 4,
  131715. };
  131716. static long _vq_lengthlist__44c5_s_p2_0[] = {
  131717. 2, 4, 4, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  131718. 8, 7, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  131719. 8, 0, 0, 0, 8, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  131720. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 7, 8, 0,
  131721. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131726. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 8, 8, 0, 0,
  131727. 0, 8, 8, 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5,
  131728. 7, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,
  131729. 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131734. 0, 0, 0, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8,
  131735. 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0,
  131736. 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,10, 0, 0,
  131737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131742. 8,10,10, 0, 0, 0,10,10, 0, 0, 0, 9,10, 0, 0, 0,
  131743. 11,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0,10,
  131744. 10, 0, 0, 0,10,10, 0, 0, 0,10,11, 0, 0, 0, 0, 0,
  131745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131756. 0,
  131757. };
  131758. static float _vq_quantthresh__44c5_s_p2_0[] = {
  131759. -1.5, -0.5, 0.5, 1.5,
  131760. };
  131761. static long _vq_quantmap__44c5_s_p2_0[] = {
  131762. 3, 1, 0, 2, 4,
  131763. };
  131764. static encode_aux_threshmatch _vq_auxt__44c5_s_p2_0 = {
  131765. _vq_quantthresh__44c5_s_p2_0,
  131766. _vq_quantmap__44c5_s_p2_0,
  131767. 5,
  131768. 5
  131769. };
  131770. static static_codebook _44c5_s_p2_0 = {
  131771. 4, 625,
  131772. _vq_lengthlist__44c5_s_p2_0,
  131773. 1, -533725184, 1611661312, 3, 0,
  131774. _vq_quantlist__44c5_s_p2_0,
  131775. NULL,
  131776. &_vq_auxt__44c5_s_p2_0,
  131777. NULL,
  131778. 0
  131779. };
  131780. static long _vq_quantlist__44c5_s_p3_0[] = {
  131781. 2,
  131782. 1,
  131783. 3,
  131784. 0,
  131785. 4,
  131786. };
  131787. static long _vq_lengthlist__44c5_s_p3_0[] = {
  131788. 2, 4, 3, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 6, 6, 0, 0,
  131790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131791. 0, 0, 3, 5, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  131793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131794. 0, 0, 0, 0, 5, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  131795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131827. 0,
  131828. };
  131829. static float _vq_quantthresh__44c5_s_p3_0[] = {
  131830. -1.5, -0.5, 0.5, 1.5,
  131831. };
  131832. static long _vq_quantmap__44c5_s_p3_0[] = {
  131833. 3, 1, 0, 2, 4,
  131834. };
  131835. static encode_aux_threshmatch _vq_auxt__44c5_s_p3_0 = {
  131836. _vq_quantthresh__44c5_s_p3_0,
  131837. _vq_quantmap__44c5_s_p3_0,
  131838. 5,
  131839. 5
  131840. };
  131841. static static_codebook _44c5_s_p3_0 = {
  131842. 4, 625,
  131843. _vq_lengthlist__44c5_s_p3_0,
  131844. 1, -533725184, 1611661312, 3, 0,
  131845. _vq_quantlist__44c5_s_p3_0,
  131846. NULL,
  131847. &_vq_auxt__44c5_s_p3_0,
  131848. NULL,
  131849. 0
  131850. };
  131851. static long _vq_quantlist__44c5_s_p4_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_p4_0[] = {
  131863. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  131864. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  131865. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  131866. 7, 7, 0, 0, 0, 0, 0, 0, 0, 8, 7, 0, 0, 0, 0, 0,
  131867. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131868. 0,
  131869. };
  131870. static float _vq_quantthresh__44c5_s_p4_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_p4_0[] = {
  131874. 7, 5, 3, 1, 0, 2, 4, 6,
  131875. 8,
  131876. };
  131877. static encode_aux_threshmatch _vq_auxt__44c5_s_p4_0 = {
  131878. _vq_quantthresh__44c5_s_p4_0,
  131879. _vq_quantmap__44c5_s_p4_0,
  131880. 9,
  131881. 9
  131882. };
  131883. static static_codebook _44c5_s_p4_0 = {
  131884. 2, 81,
  131885. _vq_lengthlist__44c5_s_p4_0,
  131886. 1, -531628032, 1611661312, 4, 0,
  131887. _vq_quantlist__44c5_s_p4_0,
  131888. NULL,
  131889. &_vq_auxt__44c5_s_p4_0,
  131890. NULL,
  131891. 0
  131892. };
  131893. static long _vq_quantlist__44c5_s_p5_0[] = {
  131894. 4,
  131895. 3,
  131896. 5,
  131897. 2,
  131898. 6,
  131899. 1,
  131900. 7,
  131901. 0,
  131902. 8,
  131903. };
  131904. static long _vq_lengthlist__44c5_s_p5_0[] = {
  131905. 2, 4, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  131906. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  131907. 7, 7, 9, 9, 0, 0, 0, 7, 6, 7, 7, 9, 9, 0, 0, 0,
  131908. 8, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  131909. 0, 0, 9, 9, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  131910. 10,
  131911. };
  131912. static float _vq_quantthresh__44c5_s_p5_0[] = {
  131913. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131914. };
  131915. static long _vq_quantmap__44c5_s_p5_0[] = {
  131916. 7, 5, 3, 1, 0, 2, 4, 6,
  131917. 8,
  131918. };
  131919. static encode_aux_threshmatch _vq_auxt__44c5_s_p5_0 = {
  131920. _vq_quantthresh__44c5_s_p5_0,
  131921. _vq_quantmap__44c5_s_p5_0,
  131922. 9,
  131923. 9
  131924. };
  131925. static static_codebook _44c5_s_p5_0 = {
  131926. 2, 81,
  131927. _vq_lengthlist__44c5_s_p5_0,
  131928. 1, -531628032, 1611661312, 4, 0,
  131929. _vq_quantlist__44c5_s_p5_0,
  131930. NULL,
  131931. &_vq_auxt__44c5_s_p5_0,
  131932. NULL,
  131933. 0
  131934. };
  131935. static long _vq_quantlist__44c5_s_p6_0[] = {
  131936. 8,
  131937. 7,
  131938. 9,
  131939. 6,
  131940. 10,
  131941. 5,
  131942. 11,
  131943. 4,
  131944. 12,
  131945. 3,
  131946. 13,
  131947. 2,
  131948. 14,
  131949. 1,
  131950. 15,
  131951. 0,
  131952. 16,
  131953. };
  131954. static long _vq_lengthlist__44c5_s_p6_0[] = {
  131955. 2, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,11,
  131956. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  131957. 12,12, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  131958. 11,12,12, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  131959. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  131960. 10,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  131961. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 9,10,10,10,
  131962. 10,11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,
  131963. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  131964. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  131965. 10,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9,
  131966. 9, 9,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  131967. 10,10,10,10,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  131968. 0, 0, 0,10,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  131969. 0, 0, 0, 0,11,11,11,11,12,12,12,13,13,13, 0, 0,
  131970. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  131971. 0, 0, 0, 0, 0, 0,12,12,12,12,13,12,13,13,13,13,
  131972. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  131973. 13,
  131974. };
  131975. static float _vq_quantthresh__44c5_s_p6_0[] = {
  131976. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  131977. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  131978. };
  131979. static long _vq_quantmap__44c5_s_p6_0[] = {
  131980. 15, 13, 11, 9, 7, 5, 3, 1,
  131981. 0, 2, 4, 6, 8, 10, 12, 14,
  131982. 16,
  131983. };
  131984. static encode_aux_threshmatch _vq_auxt__44c5_s_p6_0 = {
  131985. _vq_quantthresh__44c5_s_p6_0,
  131986. _vq_quantmap__44c5_s_p6_0,
  131987. 17,
  131988. 17
  131989. };
  131990. static static_codebook _44c5_s_p6_0 = {
  131991. 2, 289,
  131992. _vq_lengthlist__44c5_s_p6_0,
  131993. 1, -529530880, 1611661312, 5, 0,
  131994. _vq_quantlist__44c5_s_p6_0,
  131995. NULL,
  131996. &_vq_auxt__44c5_s_p6_0,
  131997. NULL,
  131998. 0
  131999. };
  132000. static long _vq_quantlist__44c5_s_p7_0[] = {
  132001. 1,
  132002. 0,
  132003. 2,
  132004. };
  132005. static long _vq_lengthlist__44c5_s_p7_0[] = {
  132006. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  132007. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  132008. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  132009. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  132010. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  132011. 10,
  132012. };
  132013. static float _vq_quantthresh__44c5_s_p7_0[] = {
  132014. -5.5, 5.5,
  132015. };
  132016. static long _vq_quantmap__44c5_s_p7_0[] = {
  132017. 1, 0, 2,
  132018. };
  132019. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_0 = {
  132020. _vq_quantthresh__44c5_s_p7_0,
  132021. _vq_quantmap__44c5_s_p7_0,
  132022. 3,
  132023. 3
  132024. };
  132025. static static_codebook _44c5_s_p7_0 = {
  132026. 4, 81,
  132027. _vq_lengthlist__44c5_s_p7_0,
  132028. 1, -529137664, 1618345984, 2, 0,
  132029. _vq_quantlist__44c5_s_p7_0,
  132030. NULL,
  132031. &_vq_auxt__44c5_s_p7_0,
  132032. NULL,
  132033. 0
  132034. };
  132035. static long _vq_quantlist__44c5_s_p7_1[] = {
  132036. 5,
  132037. 4,
  132038. 6,
  132039. 3,
  132040. 7,
  132041. 2,
  132042. 8,
  132043. 1,
  132044. 9,
  132045. 0,
  132046. 10,
  132047. };
  132048. static long _vq_lengthlist__44c5_s_p7_1[] = {
  132049. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6,
  132050. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  132051. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  132052. 7, 8, 8, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  132053. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  132054. 8, 8, 8, 8, 8, 8, 8, 9,10,10,10,10,10, 8, 8, 8,
  132055. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  132056. 10,10,10, 8, 8, 8, 8, 8, 8,
  132057. };
  132058. static float _vq_quantthresh__44c5_s_p7_1[] = {
  132059. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132060. 3.5, 4.5,
  132061. };
  132062. static long _vq_quantmap__44c5_s_p7_1[] = {
  132063. 9, 7, 5, 3, 1, 0, 2, 4,
  132064. 6, 8, 10,
  132065. };
  132066. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_1 = {
  132067. _vq_quantthresh__44c5_s_p7_1,
  132068. _vq_quantmap__44c5_s_p7_1,
  132069. 11,
  132070. 11
  132071. };
  132072. static static_codebook _44c5_s_p7_1 = {
  132073. 2, 121,
  132074. _vq_lengthlist__44c5_s_p7_1,
  132075. 1, -531365888, 1611661312, 4, 0,
  132076. _vq_quantlist__44c5_s_p7_1,
  132077. NULL,
  132078. &_vq_auxt__44c5_s_p7_1,
  132079. NULL,
  132080. 0
  132081. };
  132082. static long _vq_quantlist__44c5_s_p8_0[] = {
  132083. 6,
  132084. 5,
  132085. 7,
  132086. 4,
  132087. 8,
  132088. 3,
  132089. 9,
  132090. 2,
  132091. 10,
  132092. 1,
  132093. 11,
  132094. 0,
  132095. 12,
  132096. };
  132097. static long _vq_lengthlist__44c5_s_p8_0[] = {
  132098. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  132099. 7, 7, 8, 8, 8, 9,10,10,10,10, 7, 5, 5, 7, 7, 8,
  132100. 8, 9, 9,10,10,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  132101. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  132102. 11, 0,12,12, 9, 9, 9,10,10,10,10,10,11,11, 0,13,
  132103. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  132104. 10,10,10,10,11,11,11,11, 0, 0, 0,10,10,10,10,10,
  132105. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  132106. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,12, 0,
  132107. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  132108. 0,12,12,12,12,12,12,13,13,
  132109. };
  132110. static float _vq_quantthresh__44c5_s_p8_0[] = {
  132111. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  132112. 12.5, 17.5, 22.5, 27.5,
  132113. };
  132114. static long _vq_quantmap__44c5_s_p8_0[] = {
  132115. 11, 9, 7, 5, 3, 1, 0, 2,
  132116. 4, 6, 8, 10, 12,
  132117. };
  132118. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_0 = {
  132119. _vq_quantthresh__44c5_s_p8_0,
  132120. _vq_quantmap__44c5_s_p8_0,
  132121. 13,
  132122. 13
  132123. };
  132124. static static_codebook _44c5_s_p8_0 = {
  132125. 2, 169,
  132126. _vq_lengthlist__44c5_s_p8_0,
  132127. 1, -526516224, 1616117760, 4, 0,
  132128. _vq_quantlist__44c5_s_p8_0,
  132129. NULL,
  132130. &_vq_auxt__44c5_s_p8_0,
  132131. NULL,
  132132. 0
  132133. };
  132134. static long _vq_quantlist__44c5_s_p8_1[] = {
  132135. 2,
  132136. 1,
  132137. 3,
  132138. 0,
  132139. 4,
  132140. };
  132141. static long _vq_lengthlist__44c5_s_p8_1[] = {
  132142. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  132143. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  132144. };
  132145. static float _vq_quantthresh__44c5_s_p8_1[] = {
  132146. -1.5, -0.5, 0.5, 1.5,
  132147. };
  132148. static long _vq_quantmap__44c5_s_p8_1[] = {
  132149. 3, 1, 0, 2, 4,
  132150. };
  132151. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_1 = {
  132152. _vq_quantthresh__44c5_s_p8_1,
  132153. _vq_quantmap__44c5_s_p8_1,
  132154. 5,
  132155. 5
  132156. };
  132157. static static_codebook _44c5_s_p8_1 = {
  132158. 2, 25,
  132159. _vq_lengthlist__44c5_s_p8_1,
  132160. 1, -533725184, 1611661312, 3, 0,
  132161. _vq_quantlist__44c5_s_p8_1,
  132162. NULL,
  132163. &_vq_auxt__44c5_s_p8_1,
  132164. NULL,
  132165. 0
  132166. };
  132167. static long _vq_quantlist__44c5_s_p9_0[] = {
  132168. 7,
  132169. 6,
  132170. 8,
  132171. 5,
  132172. 9,
  132173. 4,
  132174. 10,
  132175. 3,
  132176. 11,
  132177. 2,
  132178. 12,
  132179. 1,
  132180. 13,
  132181. 0,
  132182. 14,
  132183. };
  132184. static long _vq_lengthlist__44c5_s_p9_0[] = {
  132185. 1, 3, 3,13,13,13,13,13,13,13,13,13,13,13,13, 4,
  132186. 7, 7,13,13,13,13,13,13,13,13,13,13,13,13, 3, 8,
  132187. 6,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132188. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132189. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132190. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132191. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132192. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132193. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132194. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132195. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132196. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132197. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132198. 13,13,13,13,13,13,13,13,13,12,12,12,12,12,12,12,
  132199. 12,
  132200. };
  132201. static float _vq_quantthresh__44c5_s_p9_0[] = {
  132202. -2320.5, -1963.5, -1606.5, -1249.5, -892.5, -535.5, -178.5, 178.5,
  132203. 535.5, 892.5, 1249.5, 1606.5, 1963.5, 2320.5,
  132204. };
  132205. static long _vq_quantmap__44c5_s_p9_0[] = {
  132206. 13, 11, 9, 7, 5, 3, 1, 0,
  132207. 2, 4, 6, 8, 10, 12, 14,
  132208. };
  132209. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_0 = {
  132210. _vq_quantthresh__44c5_s_p9_0,
  132211. _vq_quantmap__44c5_s_p9_0,
  132212. 15,
  132213. 15
  132214. };
  132215. static static_codebook _44c5_s_p9_0 = {
  132216. 2, 225,
  132217. _vq_lengthlist__44c5_s_p9_0,
  132218. 1, -512522752, 1628852224, 4, 0,
  132219. _vq_quantlist__44c5_s_p9_0,
  132220. NULL,
  132221. &_vq_auxt__44c5_s_p9_0,
  132222. NULL,
  132223. 0
  132224. };
  132225. static long _vq_quantlist__44c5_s_p9_1[] = {
  132226. 8,
  132227. 7,
  132228. 9,
  132229. 6,
  132230. 10,
  132231. 5,
  132232. 11,
  132233. 4,
  132234. 12,
  132235. 3,
  132236. 13,
  132237. 2,
  132238. 14,
  132239. 1,
  132240. 15,
  132241. 0,
  132242. 16,
  132243. };
  132244. static long _vq_lengthlist__44c5_s_p9_1[] = {
  132245. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,11,10,11,
  132246. 11, 6, 5, 5, 7, 7, 8, 9,10,10,11,10,12,11,12,11,
  132247. 13,12, 6, 5, 5, 7, 7, 9, 9,10,10,11,11,12,12,13,
  132248. 12,13,13,18, 8, 8, 8, 8, 9, 9,10,11,11,11,12,11,
  132249. 13,11,13,12,18, 8, 8, 8, 8,10,10,11,11,12,12,13,
  132250. 13,13,13,13,14,18,12,12, 9, 9,11,11,11,11,12,12,
  132251. 13,12,13,12,13,13,20,13,12, 9, 9,11,11,11,11,12,
  132252. 12,13,13,13,14,14,13,20,18,19,11,12,11,11,12,12,
  132253. 13,13,13,13,13,13,14,13,18,19,19,12,11,11,11,12,
  132254. 12,13,12,13,13,13,14,14,13,18,17,19,14,15,12,12,
  132255. 12,13,13,13,14,14,14,14,14,14,19,19,19,16,15,12,
  132256. 11,13,12,14,14,14,13,13,14,14,14,19,18,19,18,19,
  132257. 13,13,13,13,14,14,14,13,14,14,14,14,18,17,19,19,
  132258. 19,13,13,13,11,13,11,13,14,14,14,14,14,19,17,17,
  132259. 18,18,16,16,13,13,13,13,14,13,15,15,14,14,19,19,
  132260. 17,17,18,16,16,13,11,14,10,13,12,14,14,14,14,19,
  132261. 19,19,19,19,18,17,13,14,13,11,14,13,14,14,15,15,
  132262. 19,19,19,17,19,18,18,14,13,12,11,14,11,15,15,15,
  132263. 15,
  132264. };
  132265. static float _vq_quantthresh__44c5_s_p9_1[] = {
  132266. -157.5, -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5,
  132267. 10.5, 31.5, 52.5, 73.5, 94.5, 115.5, 136.5, 157.5,
  132268. };
  132269. static long _vq_quantmap__44c5_s_p9_1[] = {
  132270. 15, 13, 11, 9, 7, 5, 3, 1,
  132271. 0, 2, 4, 6, 8, 10, 12, 14,
  132272. 16,
  132273. };
  132274. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_1 = {
  132275. _vq_quantthresh__44c5_s_p9_1,
  132276. _vq_quantmap__44c5_s_p9_1,
  132277. 17,
  132278. 17
  132279. };
  132280. static static_codebook _44c5_s_p9_1 = {
  132281. 2, 289,
  132282. _vq_lengthlist__44c5_s_p9_1,
  132283. 1, -520814592, 1620377600, 5, 0,
  132284. _vq_quantlist__44c5_s_p9_1,
  132285. NULL,
  132286. &_vq_auxt__44c5_s_p9_1,
  132287. NULL,
  132288. 0
  132289. };
  132290. static long _vq_quantlist__44c5_s_p9_2[] = {
  132291. 10,
  132292. 9,
  132293. 11,
  132294. 8,
  132295. 12,
  132296. 7,
  132297. 13,
  132298. 6,
  132299. 14,
  132300. 5,
  132301. 15,
  132302. 4,
  132303. 16,
  132304. 3,
  132305. 17,
  132306. 2,
  132307. 18,
  132308. 1,
  132309. 19,
  132310. 0,
  132311. 20,
  132312. };
  132313. static long _vq_lengthlist__44c5_s_p9_2[] = {
  132314. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  132315. 8, 8, 8, 8, 9,11, 5, 6, 7, 7, 8, 7, 8, 8, 8, 8,
  132316. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11, 5, 5, 7, 7, 7,
  132317. 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  132318. 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  132319. 9,10, 9,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  132320. 9, 9, 9,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  132321. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,11,11,
  132322. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  132323. 10,10,10,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132324. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  132325. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,11,11,11,
  132326. 11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,
  132327. 10,10,11,11,11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,
  132328. 10,10,10,10,10,10,10,11,11,11,11,11, 9, 9,10, 9,
  132329. 10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,
  132330. 11,11,11, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  132331. 10,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  132332. 10,10,10,10,10,10,11,11,11,11,11,11,11,10,10,10,
  132333. 10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,
  132334. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132335. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  132336. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  132337. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  132338. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,11,
  132339. 11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  132340. 10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,10,
  132341. 10,10,10,10,10,10,10,10,10,
  132342. };
  132343. static float _vq_quantthresh__44c5_s_p9_2[] = {
  132344. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  132345. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  132346. 6.5, 7.5, 8.5, 9.5,
  132347. };
  132348. static long _vq_quantmap__44c5_s_p9_2[] = {
  132349. 19, 17, 15, 13, 11, 9, 7, 5,
  132350. 3, 1, 0, 2, 4, 6, 8, 10,
  132351. 12, 14, 16, 18, 20,
  132352. };
  132353. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_2 = {
  132354. _vq_quantthresh__44c5_s_p9_2,
  132355. _vq_quantmap__44c5_s_p9_2,
  132356. 21,
  132357. 21
  132358. };
  132359. static static_codebook _44c5_s_p9_2 = {
  132360. 2, 441,
  132361. _vq_lengthlist__44c5_s_p9_2,
  132362. 1, -529268736, 1611661312, 5, 0,
  132363. _vq_quantlist__44c5_s_p9_2,
  132364. NULL,
  132365. &_vq_auxt__44c5_s_p9_2,
  132366. NULL,
  132367. 0
  132368. };
  132369. static long _huff_lengthlist__44c5_s_short[] = {
  132370. 5, 8,10,14,11,11,12,16,15,17, 5, 5, 7, 9, 7, 8,
  132371. 10,13,17,17, 7, 5, 5,10, 5, 7, 8,11,13,15,10, 8,
  132372. 10, 8, 8, 8,11,15,18,18, 8, 5, 5, 8, 3, 4, 6,10,
  132373. 14,16, 9, 7, 6, 7, 4, 3, 5, 9,14,18,10, 9, 8,10,
  132374. 6, 5, 6, 9,14,18,12,12,11,12, 8, 7, 8,11,14,18,
  132375. 14,13,12,10, 7, 5, 6, 9,14,18,14,14,13,10, 6, 5,
  132376. 6, 8,11,16,
  132377. };
  132378. static static_codebook _huff_book__44c5_s_short = {
  132379. 2, 100,
  132380. _huff_lengthlist__44c5_s_short,
  132381. 0, 0, 0, 0, 0,
  132382. NULL,
  132383. NULL,
  132384. NULL,
  132385. NULL,
  132386. 0
  132387. };
  132388. static long _huff_lengthlist__44c6_s_long[] = {
  132389. 3, 8,11,13,14,14,13,13,16,14, 6, 3, 4, 7, 9, 9,
  132390. 10,11,14,13,10, 4, 3, 5, 7, 7, 9,10,13,15,12, 7,
  132391. 4, 4, 6, 6, 8,10,13,15,12, 8, 6, 6, 6, 6, 8,10,
  132392. 13,14,11, 9, 7, 6, 6, 6, 7, 8,12,11,13,10, 9, 8,
  132393. 7, 6, 6, 7,11,11,13,11,10, 9, 9, 7, 7, 6,10,11,
  132394. 13,13,13,13,13,11, 9, 8,10,12,12,15,15,16,15,12,
  132395. 11,10,10,12,
  132396. };
  132397. static static_codebook _huff_book__44c6_s_long = {
  132398. 2, 100,
  132399. _huff_lengthlist__44c6_s_long,
  132400. 0, 0, 0, 0, 0,
  132401. NULL,
  132402. NULL,
  132403. NULL,
  132404. NULL,
  132405. 0
  132406. };
  132407. static long _vq_quantlist__44c6_s_p1_0[] = {
  132408. 1,
  132409. 0,
  132410. 2,
  132411. };
  132412. static long _vq_lengthlist__44c6_s_p1_0[] = {
  132413. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  132414. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  132415. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  132416. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  132417. 9, 9, 0, 8, 8, 0, 8, 8, 5, 9, 9, 0, 8, 8, 0, 8,
  132418. 8,
  132419. };
  132420. static float _vq_quantthresh__44c6_s_p1_0[] = {
  132421. -0.5, 0.5,
  132422. };
  132423. static long _vq_quantmap__44c6_s_p1_0[] = {
  132424. 1, 0, 2,
  132425. };
  132426. static encode_aux_threshmatch _vq_auxt__44c6_s_p1_0 = {
  132427. _vq_quantthresh__44c6_s_p1_0,
  132428. _vq_quantmap__44c6_s_p1_0,
  132429. 3,
  132430. 3
  132431. };
  132432. static static_codebook _44c6_s_p1_0 = {
  132433. 4, 81,
  132434. _vq_lengthlist__44c6_s_p1_0,
  132435. 1, -535822336, 1611661312, 2, 0,
  132436. _vq_quantlist__44c6_s_p1_0,
  132437. NULL,
  132438. &_vq_auxt__44c6_s_p1_0,
  132439. NULL,
  132440. 0
  132441. };
  132442. static long _vq_quantlist__44c6_s_p2_0[] = {
  132443. 2,
  132444. 1,
  132445. 3,
  132446. 0,
  132447. 4,
  132448. };
  132449. static long _vq_lengthlist__44c6_s_p2_0[] = {
  132450. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  132451. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  132452. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  132453. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  132454. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,11,
  132455. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  132456. 0, 0,14,13, 8, 9, 9,11,11, 0,11,11,12,12, 0,10,
  132457. 11,12,12, 0,14,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  132458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132459. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  132460. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  132461. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  132462. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  132463. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  132464. 13, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,12,12,
  132465. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  132466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132467. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  132468. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,11,
  132469. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,11,
  132470. 0, 0, 0,10,11, 8,10,10,12,12, 0,10,10,12,12, 0,
  132471. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,14,13, 8,10,
  132472. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  132473. 13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132475. 7,10,10,14,13, 0, 9, 9,13,12, 0, 9, 9,12,12, 0,
  132476. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  132477. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  132478. 12,12, 9,11,11,14,13, 0,11,10,14,13, 0,11,11,13,
  132479. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  132480. 0,10,11,13,14, 0,11,11,13,13, 0,12,12,13,13, 0,
  132481. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  132486. 11,11,14,14, 0,11,11,13,13, 0,11,10,13,13, 0,12,
  132487. 12,13,13, 0, 0, 0,13,13, 9,11,11,14,14, 0,11,11,
  132488. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  132489. 13,
  132490. };
  132491. static float _vq_quantthresh__44c6_s_p2_0[] = {
  132492. -1.5, -0.5, 0.5, 1.5,
  132493. };
  132494. static long _vq_quantmap__44c6_s_p2_0[] = {
  132495. 3, 1, 0, 2, 4,
  132496. };
  132497. static encode_aux_threshmatch _vq_auxt__44c6_s_p2_0 = {
  132498. _vq_quantthresh__44c6_s_p2_0,
  132499. _vq_quantmap__44c6_s_p2_0,
  132500. 5,
  132501. 5
  132502. };
  132503. static static_codebook _44c6_s_p2_0 = {
  132504. 4, 625,
  132505. _vq_lengthlist__44c6_s_p2_0,
  132506. 1, -533725184, 1611661312, 3, 0,
  132507. _vq_quantlist__44c6_s_p2_0,
  132508. NULL,
  132509. &_vq_auxt__44c6_s_p2_0,
  132510. NULL,
  132511. 0
  132512. };
  132513. static long _vq_quantlist__44c6_s_p3_0[] = {
  132514. 4,
  132515. 3,
  132516. 5,
  132517. 2,
  132518. 6,
  132519. 1,
  132520. 7,
  132521. 0,
  132522. 8,
  132523. };
  132524. static long _vq_lengthlist__44c6_s_p3_0[] = {
  132525. 2, 3, 4, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  132526. 9,10, 0, 4, 4, 6, 6, 7, 7,10, 9, 0, 5, 5, 7, 7,
  132527. 8, 8,10,10, 0, 0, 0, 7, 6, 8, 8,10,10, 0, 0, 0,
  132528. 7, 7, 9, 9,11,11, 0, 0, 0, 7, 7, 9, 9,11,11, 0,
  132529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132530. 0,
  132531. };
  132532. static float _vq_quantthresh__44c6_s_p3_0[] = {
  132533. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132534. };
  132535. static long _vq_quantmap__44c6_s_p3_0[] = {
  132536. 7, 5, 3, 1, 0, 2, 4, 6,
  132537. 8,
  132538. };
  132539. static encode_aux_threshmatch _vq_auxt__44c6_s_p3_0 = {
  132540. _vq_quantthresh__44c6_s_p3_0,
  132541. _vq_quantmap__44c6_s_p3_0,
  132542. 9,
  132543. 9
  132544. };
  132545. static static_codebook _44c6_s_p3_0 = {
  132546. 2, 81,
  132547. _vq_lengthlist__44c6_s_p3_0,
  132548. 1, -531628032, 1611661312, 4, 0,
  132549. _vq_quantlist__44c6_s_p3_0,
  132550. NULL,
  132551. &_vq_auxt__44c6_s_p3_0,
  132552. NULL,
  132553. 0
  132554. };
  132555. static long _vq_quantlist__44c6_s_p4_0[] = {
  132556. 8,
  132557. 7,
  132558. 9,
  132559. 6,
  132560. 10,
  132561. 5,
  132562. 11,
  132563. 4,
  132564. 12,
  132565. 3,
  132566. 13,
  132567. 2,
  132568. 14,
  132569. 1,
  132570. 15,
  132571. 0,
  132572. 16,
  132573. };
  132574. static long _vq_lengthlist__44c6_s_p4_0[] = {
  132575. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,10,10,
  132576. 10, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  132577. 11,11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  132578. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  132579. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  132580. 10,11,11,11,11, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  132581. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,
  132582. 10,11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  132583. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  132584. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  132585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132593. 0,
  132594. };
  132595. static float _vq_quantthresh__44c6_s_p4_0[] = {
  132596. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132597. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132598. };
  132599. static long _vq_quantmap__44c6_s_p4_0[] = {
  132600. 15, 13, 11, 9, 7, 5, 3, 1,
  132601. 0, 2, 4, 6, 8, 10, 12, 14,
  132602. 16,
  132603. };
  132604. static encode_aux_threshmatch _vq_auxt__44c6_s_p4_0 = {
  132605. _vq_quantthresh__44c6_s_p4_0,
  132606. _vq_quantmap__44c6_s_p4_0,
  132607. 17,
  132608. 17
  132609. };
  132610. static static_codebook _44c6_s_p4_0 = {
  132611. 2, 289,
  132612. _vq_lengthlist__44c6_s_p4_0,
  132613. 1, -529530880, 1611661312, 5, 0,
  132614. _vq_quantlist__44c6_s_p4_0,
  132615. NULL,
  132616. &_vq_auxt__44c6_s_p4_0,
  132617. NULL,
  132618. 0
  132619. };
  132620. static long _vq_quantlist__44c6_s_p5_0[] = {
  132621. 1,
  132622. 0,
  132623. 2,
  132624. };
  132625. static long _vq_lengthlist__44c6_s_p5_0[] = {
  132626. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6, 9, 9,10,10,
  132627. 10, 9, 4, 6, 6, 9,10, 9,10, 9,10, 6, 9, 9,10,12,
  132628. 11,10,11,11, 7,10, 9,11,12,12,12,12,12, 7,10,10,
  132629. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  132630. 9,10,11,12,12,12,12,12, 7,10, 9,12,12,12,12,12,
  132631. 12,
  132632. };
  132633. static float _vq_quantthresh__44c6_s_p5_0[] = {
  132634. -5.5, 5.5,
  132635. };
  132636. static long _vq_quantmap__44c6_s_p5_0[] = {
  132637. 1, 0, 2,
  132638. };
  132639. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_0 = {
  132640. _vq_quantthresh__44c6_s_p5_0,
  132641. _vq_quantmap__44c6_s_p5_0,
  132642. 3,
  132643. 3
  132644. };
  132645. static static_codebook _44c6_s_p5_0 = {
  132646. 4, 81,
  132647. _vq_lengthlist__44c6_s_p5_0,
  132648. 1, -529137664, 1618345984, 2, 0,
  132649. _vq_quantlist__44c6_s_p5_0,
  132650. NULL,
  132651. &_vq_auxt__44c6_s_p5_0,
  132652. NULL,
  132653. 0
  132654. };
  132655. static long _vq_quantlist__44c6_s_p5_1[] = {
  132656. 5,
  132657. 4,
  132658. 6,
  132659. 3,
  132660. 7,
  132661. 2,
  132662. 8,
  132663. 1,
  132664. 9,
  132665. 0,
  132666. 10,
  132667. };
  132668. static long _vq_lengthlist__44c6_s_p5_1[] = {
  132669. 3, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  132670. 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6, 7, 7, 8, 8, 8,
  132671. 8,11, 6, 6, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  132672. 6, 7, 8, 8, 8, 8, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  132673. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 8,11,11,11,
  132674. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,10,10, 8, 8, 8,
  132675. 8, 8, 8,11,11,11,10,10, 8, 8, 8, 8, 8, 8,11,11,
  132676. 11,10,10, 7, 7, 8, 8, 8, 8,
  132677. };
  132678. static float _vq_quantthresh__44c6_s_p5_1[] = {
  132679. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132680. 3.5, 4.5,
  132681. };
  132682. static long _vq_quantmap__44c6_s_p5_1[] = {
  132683. 9, 7, 5, 3, 1, 0, 2, 4,
  132684. 6, 8, 10,
  132685. };
  132686. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_1 = {
  132687. _vq_quantthresh__44c6_s_p5_1,
  132688. _vq_quantmap__44c6_s_p5_1,
  132689. 11,
  132690. 11
  132691. };
  132692. static static_codebook _44c6_s_p5_1 = {
  132693. 2, 121,
  132694. _vq_lengthlist__44c6_s_p5_1,
  132695. 1, -531365888, 1611661312, 4, 0,
  132696. _vq_quantlist__44c6_s_p5_1,
  132697. NULL,
  132698. &_vq_auxt__44c6_s_p5_1,
  132699. NULL,
  132700. 0
  132701. };
  132702. static long _vq_quantlist__44c6_s_p6_0[] = {
  132703. 6,
  132704. 5,
  132705. 7,
  132706. 4,
  132707. 8,
  132708. 3,
  132709. 9,
  132710. 2,
  132711. 10,
  132712. 1,
  132713. 11,
  132714. 0,
  132715. 12,
  132716. };
  132717. static long _vq_lengthlist__44c6_s_p6_0[] = {
  132718. 1, 4, 4, 6, 6, 8, 8, 8, 8,10, 9,10,10, 6, 5, 5,
  132719. 7, 7, 9, 9, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 9,
  132720. 9,10, 9,11,10,11,11, 0, 6, 6, 7, 7, 9, 9,10,10,
  132721. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  132722. 12, 0,11,11, 8, 8,10,10,11,11,12,12,12,12, 0,11,
  132723. 12, 9, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  132724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132728. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132729. };
  132730. static float _vq_quantthresh__44c6_s_p6_0[] = {
  132731. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  132732. 12.5, 17.5, 22.5, 27.5,
  132733. };
  132734. static long _vq_quantmap__44c6_s_p6_0[] = {
  132735. 11, 9, 7, 5, 3, 1, 0, 2,
  132736. 4, 6, 8, 10, 12,
  132737. };
  132738. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_0 = {
  132739. _vq_quantthresh__44c6_s_p6_0,
  132740. _vq_quantmap__44c6_s_p6_0,
  132741. 13,
  132742. 13
  132743. };
  132744. static static_codebook _44c6_s_p6_0 = {
  132745. 2, 169,
  132746. _vq_lengthlist__44c6_s_p6_0,
  132747. 1, -526516224, 1616117760, 4, 0,
  132748. _vq_quantlist__44c6_s_p6_0,
  132749. NULL,
  132750. &_vq_auxt__44c6_s_p6_0,
  132751. NULL,
  132752. 0
  132753. };
  132754. static long _vq_quantlist__44c6_s_p6_1[] = {
  132755. 2,
  132756. 1,
  132757. 3,
  132758. 0,
  132759. 4,
  132760. };
  132761. static long _vq_lengthlist__44c6_s_p6_1[] = {
  132762. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  132763. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  132764. };
  132765. static float _vq_quantthresh__44c6_s_p6_1[] = {
  132766. -1.5, -0.5, 0.5, 1.5,
  132767. };
  132768. static long _vq_quantmap__44c6_s_p6_1[] = {
  132769. 3, 1, 0, 2, 4,
  132770. };
  132771. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_1 = {
  132772. _vq_quantthresh__44c6_s_p6_1,
  132773. _vq_quantmap__44c6_s_p6_1,
  132774. 5,
  132775. 5
  132776. };
  132777. static static_codebook _44c6_s_p6_1 = {
  132778. 2, 25,
  132779. _vq_lengthlist__44c6_s_p6_1,
  132780. 1, -533725184, 1611661312, 3, 0,
  132781. _vq_quantlist__44c6_s_p6_1,
  132782. NULL,
  132783. &_vq_auxt__44c6_s_p6_1,
  132784. NULL,
  132785. 0
  132786. };
  132787. static long _vq_quantlist__44c6_s_p7_0[] = {
  132788. 6,
  132789. 5,
  132790. 7,
  132791. 4,
  132792. 8,
  132793. 3,
  132794. 9,
  132795. 2,
  132796. 10,
  132797. 1,
  132798. 11,
  132799. 0,
  132800. 12,
  132801. };
  132802. static long _vq_lengthlist__44c6_s_p7_0[] = {
  132803. 1, 4, 4, 6, 6, 8, 8, 8, 8,10,10,11,10, 6, 5, 5,
  132804. 7, 7, 8, 8, 9, 9,10,10,12,11, 6, 5, 5, 7, 7, 8,
  132805. 8, 9, 9,10,10,12,11,21, 7, 7, 7, 7, 9, 9,10,10,
  132806. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  132807. 12,21,12,12, 9, 9,10,10,11,11,11,11,12,12,21,12,
  132808. 12, 9, 9,10,10,11,11,12,12,12,12,21,21,21,11,11,
  132809. 10,10,11,12,12,12,13,13,21,21,21,11,11,10,10,12,
  132810. 12,12,12,13,13,21,21,21,15,15,11,11,12,12,13,13,
  132811. 13,13,21,21,21,15,16,11,11,12,12,13,13,14,14,21,
  132812. 21,21,21,20,13,13,13,13,13,13,14,14,20,20,20,20,
  132813. 20,13,13,13,13,13,13,14,14,
  132814. };
  132815. static float _vq_quantthresh__44c6_s_p7_0[] = {
  132816. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  132817. 27.5, 38.5, 49.5, 60.5,
  132818. };
  132819. static long _vq_quantmap__44c6_s_p7_0[] = {
  132820. 11, 9, 7, 5, 3, 1, 0, 2,
  132821. 4, 6, 8, 10, 12,
  132822. };
  132823. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_0 = {
  132824. _vq_quantthresh__44c6_s_p7_0,
  132825. _vq_quantmap__44c6_s_p7_0,
  132826. 13,
  132827. 13
  132828. };
  132829. static static_codebook _44c6_s_p7_0 = {
  132830. 2, 169,
  132831. _vq_lengthlist__44c6_s_p7_0,
  132832. 1, -523206656, 1618345984, 4, 0,
  132833. _vq_quantlist__44c6_s_p7_0,
  132834. NULL,
  132835. &_vq_auxt__44c6_s_p7_0,
  132836. NULL,
  132837. 0
  132838. };
  132839. static long _vq_quantlist__44c6_s_p7_1[] = {
  132840. 5,
  132841. 4,
  132842. 6,
  132843. 3,
  132844. 7,
  132845. 2,
  132846. 8,
  132847. 1,
  132848. 9,
  132849. 0,
  132850. 10,
  132851. };
  132852. static long _vq_lengthlist__44c6_s_p7_1[] = {
  132853. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 9, 5, 5, 6, 6,
  132854. 7, 7, 7, 7, 8, 7, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7,
  132855. 7, 9, 6, 6, 7, 7, 7, 7, 8, 7, 7, 8, 9, 9, 9, 7,
  132856. 7, 7, 7, 7, 7, 7, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  132857. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  132858. 8, 8, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 8, 8, 8, 7,
  132859. 7, 8, 8, 9, 9, 9, 8, 8, 8, 8, 7, 7, 8, 8, 9, 9,
  132860. 9, 8, 8, 7, 7, 7, 7, 8, 8,
  132861. };
  132862. static float _vq_quantthresh__44c6_s_p7_1[] = {
  132863. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132864. 3.5, 4.5,
  132865. };
  132866. static long _vq_quantmap__44c6_s_p7_1[] = {
  132867. 9, 7, 5, 3, 1, 0, 2, 4,
  132868. 6, 8, 10,
  132869. };
  132870. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_1 = {
  132871. _vq_quantthresh__44c6_s_p7_1,
  132872. _vq_quantmap__44c6_s_p7_1,
  132873. 11,
  132874. 11
  132875. };
  132876. static static_codebook _44c6_s_p7_1 = {
  132877. 2, 121,
  132878. _vq_lengthlist__44c6_s_p7_1,
  132879. 1, -531365888, 1611661312, 4, 0,
  132880. _vq_quantlist__44c6_s_p7_1,
  132881. NULL,
  132882. &_vq_auxt__44c6_s_p7_1,
  132883. NULL,
  132884. 0
  132885. };
  132886. static long _vq_quantlist__44c6_s_p8_0[] = {
  132887. 7,
  132888. 6,
  132889. 8,
  132890. 5,
  132891. 9,
  132892. 4,
  132893. 10,
  132894. 3,
  132895. 11,
  132896. 2,
  132897. 12,
  132898. 1,
  132899. 13,
  132900. 0,
  132901. 14,
  132902. };
  132903. static long _vq_lengthlist__44c6_s_p8_0[] = {
  132904. 1, 4, 4, 7, 7, 8, 8, 7, 7, 8, 7, 9, 8,10, 9, 6,
  132905. 5, 5, 8, 8, 9, 9, 8, 8, 9, 9,11,10,11,10, 6, 5,
  132906. 5, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,11,18, 8, 8,
  132907. 9, 8,10,10, 9, 9,10,10,10,10,11,10,18, 8, 8, 9,
  132908. 9,10,10, 9, 9,10,10,11,11,12,12,18,12,13, 9,10,
  132909. 10,10, 9,10,10,10,11,11,12,11,18,13,13, 9, 9,10,
  132910. 10,10,10,10,10,11,11,12,12,18,18,18,10,10, 9, 9,
  132911. 11,11,11,11,11,12,12,12,18,18,18,10, 9,10, 9,11,
  132912. 10,11,11,11,11,13,12,18,18,18,14,13,10,10,11,11,
  132913. 12,12,12,12,12,12,18,18,18,14,13,10,10,11,10,12,
  132914. 12,12,12,12,12,18,18,18,18,18,12,12,11,11,12,12,
  132915. 13,13,13,14,18,18,18,18,18,12,12,11,11,12,11,13,
  132916. 13,14,13,18,18,18,18,18,16,16,11,12,12,13,13,13,
  132917. 14,13,18,18,18,18,18,16,15,12,11,12,11,13,11,15,
  132918. 14,
  132919. };
  132920. static float _vq_quantthresh__44c6_s_p8_0[] = {
  132921. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  132922. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  132923. };
  132924. static long _vq_quantmap__44c6_s_p8_0[] = {
  132925. 13, 11, 9, 7, 5, 3, 1, 0,
  132926. 2, 4, 6, 8, 10, 12, 14,
  132927. };
  132928. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_0 = {
  132929. _vq_quantthresh__44c6_s_p8_0,
  132930. _vq_quantmap__44c6_s_p8_0,
  132931. 15,
  132932. 15
  132933. };
  132934. static static_codebook _44c6_s_p8_0 = {
  132935. 2, 225,
  132936. _vq_lengthlist__44c6_s_p8_0,
  132937. 1, -520986624, 1620377600, 4, 0,
  132938. _vq_quantlist__44c6_s_p8_0,
  132939. NULL,
  132940. &_vq_auxt__44c6_s_p8_0,
  132941. NULL,
  132942. 0
  132943. };
  132944. static long _vq_quantlist__44c6_s_p8_1[] = {
  132945. 10,
  132946. 9,
  132947. 11,
  132948. 8,
  132949. 12,
  132950. 7,
  132951. 13,
  132952. 6,
  132953. 14,
  132954. 5,
  132955. 15,
  132956. 4,
  132957. 16,
  132958. 3,
  132959. 17,
  132960. 2,
  132961. 18,
  132962. 1,
  132963. 19,
  132964. 0,
  132965. 20,
  132966. };
  132967. static long _vq_lengthlist__44c6_s_p8_1[] = {
  132968. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  132969. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,
  132970. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  132971. 8, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10,
  132972. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132973. 9, 9, 9, 9,10,11,11, 8, 7, 8, 8, 8, 9, 9, 9, 9,
  132974. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8,
  132975. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,
  132976. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132977. 9, 9, 9,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132978. 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9, 9,
  132979. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,
  132980. 11,11, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9,10, 9, 9,
  132981. 10, 9,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,10,10,
  132982. 10,10, 9,10,10, 9,10,11,11,11,11,11, 9, 9, 9, 9,
  132983. 10,10,10, 9,10,10,10,10, 9,10,10, 9,11,11,11,11,
  132984. 11,11,11, 9, 9, 9, 9,10,10,10,10, 9,10,10,10,10,
  132985. 10,11,11,11,11,11,11,11,10, 9,10,10,10,10,10,10,
  132986. 10, 9,10, 9,10,10,11,11,11,11,11,11,11,10, 9,10,
  132987. 9,10,10, 9,10,10,10,10,10,10,10,11,11,11,11,11,
  132988. 11,11,10,10,10,10,10,10,10, 9,10,10,10,10,10, 9,
  132989. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  132990. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  132991. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  132992. 11,11,11,10,10,10,10,10,10,10,10,10, 9,10,10,11,
  132993. 11,11,11,11,11,11,11,11,10,10,10, 9,10,10,10,10,
  132994. 10,10,10,10,10,11,11,11,11,11,11,11,11,10,11, 9,
  132995. 10,10,10,10,10,10,10,10,10,
  132996. };
  132997. static float _vq_quantthresh__44c6_s_p8_1[] = {
  132998. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  132999. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  133000. 6.5, 7.5, 8.5, 9.5,
  133001. };
  133002. static long _vq_quantmap__44c6_s_p8_1[] = {
  133003. 19, 17, 15, 13, 11, 9, 7, 5,
  133004. 3, 1, 0, 2, 4, 6, 8, 10,
  133005. 12, 14, 16, 18, 20,
  133006. };
  133007. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_1 = {
  133008. _vq_quantthresh__44c6_s_p8_1,
  133009. _vq_quantmap__44c6_s_p8_1,
  133010. 21,
  133011. 21
  133012. };
  133013. static static_codebook _44c6_s_p8_1 = {
  133014. 2, 441,
  133015. _vq_lengthlist__44c6_s_p8_1,
  133016. 1, -529268736, 1611661312, 5, 0,
  133017. _vq_quantlist__44c6_s_p8_1,
  133018. NULL,
  133019. &_vq_auxt__44c6_s_p8_1,
  133020. NULL,
  133021. 0
  133022. };
  133023. static long _vq_quantlist__44c6_s_p9_0[] = {
  133024. 6,
  133025. 5,
  133026. 7,
  133027. 4,
  133028. 8,
  133029. 3,
  133030. 9,
  133031. 2,
  133032. 10,
  133033. 1,
  133034. 11,
  133035. 0,
  133036. 12,
  133037. };
  133038. static long _vq_lengthlist__44c6_s_p9_0[] = {
  133039. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 7, 7,
  133040. 11,11,11,11,11,11,11,11,11,11, 5, 8, 9,11,11,11,
  133041. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133042. 11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,10,
  133043. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133044. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133045. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133046. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133047. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133048. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133049. 10,10,10,10,10,10,10,10,10,
  133050. };
  133051. static float _vq_quantthresh__44c6_s_p9_0[] = {
  133052. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  133053. 1592.5, 2229.5, 2866.5, 3503.5,
  133054. };
  133055. static long _vq_quantmap__44c6_s_p9_0[] = {
  133056. 11, 9, 7, 5, 3, 1, 0, 2,
  133057. 4, 6, 8, 10, 12,
  133058. };
  133059. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_0 = {
  133060. _vq_quantthresh__44c6_s_p9_0,
  133061. _vq_quantmap__44c6_s_p9_0,
  133062. 13,
  133063. 13
  133064. };
  133065. static static_codebook _44c6_s_p9_0 = {
  133066. 2, 169,
  133067. _vq_lengthlist__44c6_s_p9_0,
  133068. 1, -511845376, 1630791680, 4, 0,
  133069. _vq_quantlist__44c6_s_p9_0,
  133070. NULL,
  133071. &_vq_auxt__44c6_s_p9_0,
  133072. NULL,
  133073. 0
  133074. };
  133075. static long _vq_quantlist__44c6_s_p9_1[] = {
  133076. 6,
  133077. 5,
  133078. 7,
  133079. 4,
  133080. 8,
  133081. 3,
  133082. 9,
  133083. 2,
  133084. 10,
  133085. 1,
  133086. 11,
  133087. 0,
  133088. 12,
  133089. };
  133090. static long _vq_lengthlist__44c6_s_p9_1[] = {
  133091. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  133092. 8, 8, 8, 8, 8, 7, 9, 8,10,10, 5, 6, 6, 8, 8, 9,
  133093. 9, 8, 8,10,10,10,10,16, 9, 9, 9, 9, 9, 9, 9, 8,
  133094. 10, 9,11,11,16, 8, 9, 9, 9, 9, 9, 9, 9,10,10,11,
  133095. 11,16,13,13, 9, 9,10, 9, 9,10,11,11,11,12,16,13,
  133096. 14, 9, 8,10, 8, 9, 9,10,10,12,11,16,14,16, 9, 9,
  133097. 9, 9,11,11,12,11,12,11,16,16,16, 9, 7, 9, 6,11,
  133098. 11,11,10,11,11,16,16,16,11,12, 9,10,11,11,12,11,
  133099. 13,13,16,16,16,12,11,10, 7,12,10,12,12,12,12,16,
  133100. 16,15,16,16,10,11,10,11,13,13,14,12,16,16,16,15,
  133101. 15,12,10,11,11,13,11,12,13,
  133102. };
  133103. static float _vq_quantthresh__44c6_s_p9_1[] = {
  133104. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  133105. 122.5, 171.5, 220.5, 269.5,
  133106. };
  133107. static long _vq_quantmap__44c6_s_p9_1[] = {
  133108. 11, 9, 7, 5, 3, 1, 0, 2,
  133109. 4, 6, 8, 10, 12,
  133110. };
  133111. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_1 = {
  133112. _vq_quantthresh__44c6_s_p9_1,
  133113. _vq_quantmap__44c6_s_p9_1,
  133114. 13,
  133115. 13
  133116. };
  133117. static static_codebook _44c6_s_p9_1 = {
  133118. 2, 169,
  133119. _vq_lengthlist__44c6_s_p9_1,
  133120. 1, -518889472, 1622704128, 4, 0,
  133121. _vq_quantlist__44c6_s_p9_1,
  133122. NULL,
  133123. &_vq_auxt__44c6_s_p9_1,
  133124. NULL,
  133125. 0
  133126. };
  133127. static long _vq_quantlist__44c6_s_p9_2[] = {
  133128. 24,
  133129. 23,
  133130. 25,
  133131. 22,
  133132. 26,
  133133. 21,
  133134. 27,
  133135. 20,
  133136. 28,
  133137. 19,
  133138. 29,
  133139. 18,
  133140. 30,
  133141. 17,
  133142. 31,
  133143. 16,
  133144. 32,
  133145. 15,
  133146. 33,
  133147. 14,
  133148. 34,
  133149. 13,
  133150. 35,
  133151. 12,
  133152. 36,
  133153. 11,
  133154. 37,
  133155. 10,
  133156. 38,
  133157. 9,
  133158. 39,
  133159. 8,
  133160. 40,
  133161. 7,
  133162. 41,
  133163. 6,
  133164. 42,
  133165. 5,
  133166. 43,
  133167. 4,
  133168. 44,
  133169. 3,
  133170. 45,
  133171. 2,
  133172. 46,
  133173. 1,
  133174. 47,
  133175. 0,
  133176. 48,
  133177. };
  133178. static long _vq_lengthlist__44c6_s_p9_2[] = {
  133179. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  133180. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133181. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133182. 7,
  133183. };
  133184. static float _vq_quantthresh__44c6_s_p9_2[] = {
  133185. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  133186. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  133187. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133188. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133189. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  133190. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  133191. };
  133192. static long _vq_quantmap__44c6_s_p9_2[] = {
  133193. 47, 45, 43, 41, 39, 37, 35, 33,
  133194. 31, 29, 27, 25, 23, 21, 19, 17,
  133195. 15, 13, 11, 9, 7, 5, 3, 1,
  133196. 0, 2, 4, 6, 8, 10, 12, 14,
  133197. 16, 18, 20, 22, 24, 26, 28, 30,
  133198. 32, 34, 36, 38, 40, 42, 44, 46,
  133199. 48,
  133200. };
  133201. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_2 = {
  133202. _vq_quantthresh__44c6_s_p9_2,
  133203. _vq_quantmap__44c6_s_p9_2,
  133204. 49,
  133205. 49
  133206. };
  133207. static static_codebook _44c6_s_p9_2 = {
  133208. 1, 49,
  133209. _vq_lengthlist__44c6_s_p9_2,
  133210. 1, -526909440, 1611661312, 6, 0,
  133211. _vq_quantlist__44c6_s_p9_2,
  133212. NULL,
  133213. &_vq_auxt__44c6_s_p9_2,
  133214. NULL,
  133215. 0
  133216. };
  133217. static long _huff_lengthlist__44c6_s_short[] = {
  133218. 3, 9,11,11,13,14,19,17,17,19, 5, 4, 5, 8,10,10,
  133219. 13,16,18,19, 7, 4, 4, 5, 8, 9,12,14,17,19, 8, 6,
  133220. 5, 5, 7, 7,10,13,16,18,10, 8, 7, 6, 5, 5, 8,11,
  133221. 17,19,11, 9, 7, 7, 5, 4, 5, 8,17,19,13,11, 8, 7,
  133222. 7, 5, 5, 7,16,18,14,13, 8, 6, 6, 5, 5, 7,16,18,
  133223. 18,16,10, 8, 8, 7, 7, 9,16,18,18,18,12,10,10, 9,
  133224. 9,10,17,18,
  133225. };
  133226. static static_codebook _huff_book__44c6_s_short = {
  133227. 2, 100,
  133228. _huff_lengthlist__44c6_s_short,
  133229. 0, 0, 0, 0, 0,
  133230. NULL,
  133231. NULL,
  133232. NULL,
  133233. NULL,
  133234. 0
  133235. };
  133236. static long _huff_lengthlist__44c7_s_long[] = {
  133237. 3, 8,11,13,15,14,14,13,15,14, 6, 4, 5, 7, 9,10,
  133238. 11,11,14,13,10, 4, 3, 5, 7, 8, 9,10,13,13,12, 7,
  133239. 4, 4, 5, 6, 8, 9,12,14,13, 9, 6, 5, 5, 6, 8, 9,
  133240. 12,14,12, 9, 7, 6, 5, 5, 6, 8,11,11,12,11, 9, 8,
  133241. 7, 6, 6, 7,10,11,13,11,10, 9, 8, 7, 6, 6, 9,11,
  133242. 13,13,12,12,12,10, 9, 8, 9,11,12,14,15,15,14,12,
  133243. 11,10,10,12,
  133244. };
  133245. static static_codebook _huff_book__44c7_s_long = {
  133246. 2, 100,
  133247. _huff_lengthlist__44c7_s_long,
  133248. 0, 0, 0, 0, 0,
  133249. NULL,
  133250. NULL,
  133251. NULL,
  133252. NULL,
  133253. 0
  133254. };
  133255. static long _vq_quantlist__44c7_s_p1_0[] = {
  133256. 1,
  133257. 0,
  133258. 2,
  133259. };
  133260. static long _vq_lengthlist__44c7_s_p1_0[] = {
  133261. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  133262. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  133263. 0, 0, 0, 0, 5, 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  133264. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  133265. 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  133266. 8,
  133267. };
  133268. static float _vq_quantthresh__44c7_s_p1_0[] = {
  133269. -0.5, 0.5,
  133270. };
  133271. static long _vq_quantmap__44c7_s_p1_0[] = {
  133272. 1, 0, 2,
  133273. };
  133274. static encode_aux_threshmatch _vq_auxt__44c7_s_p1_0 = {
  133275. _vq_quantthresh__44c7_s_p1_0,
  133276. _vq_quantmap__44c7_s_p1_0,
  133277. 3,
  133278. 3
  133279. };
  133280. static static_codebook _44c7_s_p1_0 = {
  133281. 4, 81,
  133282. _vq_lengthlist__44c7_s_p1_0,
  133283. 1, -535822336, 1611661312, 2, 0,
  133284. _vq_quantlist__44c7_s_p1_0,
  133285. NULL,
  133286. &_vq_auxt__44c7_s_p1_0,
  133287. NULL,
  133288. 0
  133289. };
  133290. static long _vq_quantlist__44c7_s_p2_0[] = {
  133291. 2,
  133292. 1,
  133293. 3,
  133294. 0,
  133295. 4,
  133296. };
  133297. static long _vq_lengthlist__44c7_s_p2_0[] = {
  133298. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  133299. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  133300. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  133301. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  133302. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  133303. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  133304. 0, 0,14,13, 8, 9, 9,10,11, 0,11,11,12,12, 0,10,
  133305. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  133306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133307. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  133308. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  133309. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  133310. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  133311. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  133312. 13, 8, 9,10,12,12, 0,10,10,12,12, 0,10,10,11,12,
  133313. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  133314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133315. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  133316. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,10,
  133317. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,10,
  133318. 0, 0, 0,10,11, 9,10,10,12,12, 0,10,10,12,12, 0,
  133319. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,13,12, 9,10,
  133320. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  133321. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133323. 7,10,10,14,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  133324. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  133325. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  133326. 12,12, 9,11,11,14,13, 0,11,10,13,12, 0,11,11,13,
  133327. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  133328. 0,10,11,12,13, 0,11,11,13,13, 0,12,12,13,13, 0,
  133329. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  133334. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,12,
  133335. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  133336. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  133337. 13,
  133338. };
  133339. static float _vq_quantthresh__44c7_s_p2_0[] = {
  133340. -1.5, -0.5, 0.5, 1.5,
  133341. };
  133342. static long _vq_quantmap__44c7_s_p2_0[] = {
  133343. 3, 1, 0, 2, 4,
  133344. };
  133345. static encode_aux_threshmatch _vq_auxt__44c7_s_p2_0 = {
  133346. _vq_quantthresh__44c7_s_p2_0,
  133347. _vq_quantmap__44c7_s_p2_0,
  133348. 5,
  133349. 5
  133350. };
  133351. static static_codebook _44c7_s_p2_0 = {
  133352. 4, 625,
  133353. _vq_lengthlist__44c7_s_p2_0,
  133354. 1, -533725184, 1611661312, 3, 0,
  133355. _vq_quantlist__44c7_s_p2_0,
  133356. NULL,
  133357. &_vq_auxt__44c7_s_p2_0,
  133358. NULL,
  133359. 0
  133360. };
  133361. static long _vq_quantlist__44c7_s_p3_0[] = {
  133362. 4,
  133363. 3,
  133364. 5,
  133365. 2,
  133366. 6,
  133367. 1,
  133368. 7,
  133369. 0,
  133370. 8,
  133371. };
  133372. static long _vq_lengthlist__44c7_s_p3_0[] = {
  133373. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  133374. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  133375. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  133376. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  133377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133378. 0,
  133379. };
  133380. static float _vq_quantthresh__44c7_s_p3_0[] = {
  133381. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  133382. };
  133383. static long _vq_quantmap__44c7_s_p3_0[] = {
  133384. 7, 5, 3, 1, 0, 2, 4, 6,
  133385. 8,
  133386. };
  133387. static encode_aux_threshmatch _vq_auxt__44c7_s_p3_0 = {
  133388. _vq_quantthresh__44c7_s_p3_0,
  133389. _vq_quantmap__44c7_s_p3_0,
  133390. 9,
  133391. 9
  133392. };
  133393. static static_codebook _44c7_s_p3_0 = {
  133394. 2, 81,
  133395. _vq_lengthlist__44c7_s_p3_0,
  133396. 1, -531628032, 1611661312, 4, 0,
  133397. _vq_quantlist__44c7_s_p3_0,
  133398. NULL,
  133399. &_vq_auxt__44c7_s_p3_0,
  133400. NULL,
  133401. 0
  133402. };
  133403. static long _vq_quantlist__44c7_s_p4_0[] = {
  133404. 8,
  133405. 7,
  133406. 9,
  133407. 6,
  133408. 10,
  133409. 5,
  133410. 11,
  133411. 4,
  133412. 12,
  133413. 3,
  133414. 13,
  133415. 2,
  133416. 14,
  133417. 1,
  133418. 15,
  133419. 0,
  133420. 16,
  133421. };
  133422. static long _vq_lengthlist__44c7_s_p4_0[] = {
  133423. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  133424. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  133425. 12,12, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  133426. 11,12,12, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,
  133427. 11,12,12,12, 0, 0, 0, 6, 6, 8, 7, 9, 9, 9, 9,10,
  133428. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  133429. 11,11,12,12,13,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  133430. 10,11,11,12,12,12,13, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  133431. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  133432. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  133433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133441. 0,
  133442. };
  133443. static float _vq_quantthresh__44c7_s_p4_0[] = {
  133444. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133445. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133446. };
  133447. static long _vq_quantmap__44c7_s_p4_0[] = {
  133448. 15, 13, 11, 9, 7, 5, 3, 1,
  133449. 0, 2, 4, 6, 8, 10, 12, 14,
  133450. 16,
  133451. };
  133452. static encode_aux_threshmatch _vq_auxt__44c7_s_p4_0 = {
  133453. _vq_quantthresh__44c7_s_p4_0,
  133454. _vq_quantmap__44c7_s_p4_0,
  133455. 17,
  133456. 17
  133457. };
  133458. static static_codebook _44c7_s_p4_0 = {
  133459. 2, 289,
  133460. _vq_lengthlist__44c7_s_p4_0,
  133461. 1, -529530880, 1611661312, 5, 0,
  133462. _vq_quantlist__44c7_s_p4_0,
  133463. NULL,
  133464. &_vq_auxt__44c7_s_p4_0,
  133465. NULL,
  133466. 0
  133467. };
  133468. static long _vq_quantlist__44c7_s_p5_0[] = {
  133469. 1,
  133470. 0,
  133471. 2,
  133472. };
  133473. static long _vq_lengthlist__44c7_s_p5_0[] = {
  133474. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 7,10,10,10,10,
  133475. 10, 9, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  133476. 12,10,11,12, 7,10,10,11,12,12,12,12,12, 7,10,10,
  133477. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  133478. 10,10,12,12,12,12,11,12, 7,10,10,11,12,12,12,12,
  133479. 12,
  133480. };
  133481. static float _vq_quantthresh__44c7_s_p5_0[] = {
  133482. -5.5, 5.5,
  133483. };
  133484. static long _vq_quantmap__44c7_s_p5_0[] = {
  133485. 1, 0, 2,
  133486. };
  133487. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_0 = {
  133488. _vq_quantthresh__44c7_s_p5_0,
  133489. _vq_quantmap__44c7_s_p5_0,
  133490. 3,
  133491. 3
  133492. };
  133493. static static_codebook _44c7_s_p5_0 = {
  133494. 4, 81,
  133495. _vq_lengthlist__44c7_s_p5_0,
  133496. 1, -529137664, 1618345984, 2, 0,
  133497. _vq_quantlist__44c7_s_p5_0,
  133498. NULL,
  133499. &_vq_auxt__44c7_s_p5_0,
  133500. NULL,
  133501. 0
  133502. };
  133503. static long _vq_quantlist__44c7_s_p5_1[] = {
  133504. 5,
  133505. 4,
  133506. 6,
  133507. 3,
  133508. 7,
  133509. 2,
  133510. 8,
  133511. 1,
  133512. 9,
  133513. 0,
  133514. 10,
  133515. };
  133516. static long _vq_lengthlist__44c7_s_p5_1[] = {
  133517. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  133518. 7, 7, 8, 8, 9, 9,11, 4, 4, 6, 6, 7, 7, 8, 8, 9,
  133519. 9,12, 5, 5, 6, 6, 7, 7, 9, 9, 9, 9,12,12,12, 6,
  133520. 6, 7, 7, 9, 9, 9, 9,11,11,11, 7, 7, 7, 7, 8, 8,
  133521. 9, 9,11,11,11, 7, 7, 7, 7, 8, 8, 9, 9,11,11,11,
  133522. 7, 7, 8, 8, 8, 8, 9, 9,11,11,11,11,11, 8, 8, 8,
  133523. 8, 8, 9,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  133524. 11,11,11, 7, 7, 8, 8, 8, 8,
  133525. };
  133526. static float _vq_quantthresh__44c7_s_p5_1[] = {
  133527. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133528. 3.5, 4.5,
  133529. };
  133530. static long _vq_quantmap__44c7_s_p5_1[] = {
  133531. 9, 7, 5, 3, 1, 0, 2, 4,
  133532. 6, 8, 10,
  133533. };
  133534. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_1 = {
  133535. _vq_quantthresh__44c7_s_p5_1,
  133536. _vq_quantmap__44c7_s_p5_1,
  133537. 11,
  133538. 11
  133539. };
  133540. static static_codebook _44c7_s_p5_1 = {
  133541. 2, 121,
  133542. _vq_lengthlist__44c7_s_p5_1,
  133543. 1, -531365888, 1611661312, 4, 0,
  133544. _vq_quantlist__44c7_s_p5_1,
  133545. NULL,
  133546. &_vq_auxt__44c7_s_p5_1,
  133547. NULL,
  133548. 0
  133549. };
  133550. static long _vq_quantlist__44c7_s_p6_0[] = {
  133551. 6,
  133552. 5,
  133553. 7,
  133554. 4,
  133555. 8,
  133556. 3,
  133557. 9,
  133558. 2,
  133559. 10,
  133560. 1,
  133561. 11,
  133562. 0,
  133563. 12,
  133564. };
  133565. static long _vq_lengthlist__44c7_s_p6_0[] = {
  133566. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 8,10,10, 6, 5, 5,
  133567. 7, 7, 8, 8, 9, 9, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  133568. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 8, 9, 9,
  133569. 10,10,11,11, 0, 8, 8, 7, 7, 8, 9, 9, 9,10,10,11,
  133570. 11, 0,11,11, 9, 9,10,10,11,10,11,11,12,12, 0,12,
  133571. 12, 9, 9,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0,
  133572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133576. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133577. };
  133578. static float _vq_quantthresh__44c7_s_p6_0[] = {
  133579. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  133580. 12.5, 17.5, 22.5, 27.5,
  133581. };
  133582. static long _vq_quantmap__44c7_s_p6_0[] = {
  133583. 11, 9, 7, 5, 3, 1, 0, 2,
  133584. 4, 6, 8, 10, 12,
  133585. };
  133586. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_0 = {
  133587. _vq_quantthresh__44c7_s_p6_0,
  133588. _vq_quantmap__44c7_s_p6_0,
  133589. 13,
  133590. 13
  133591. };
  133592. static static_codebook _44c7_s_p6_0 = {
  133593. 2, 169,
  133594. _vq_lengthlist__44c7_s_p6_0,
  133595. 1, -526516224, 1616117760, 4, 0,
  133596. _vq_quantlist__44c7_s_p6_0,
  133597. NULL,
  133598. &_vq_auxt__44c7_s_p6_0,
  133599. NULL,
  133600. 0
  133601. };
  133602. static long _vq_quantlist__44c7_s_p6_1[] = {
  133603. 2,
  133604. 1,
  133605. 3,
  133606. 0,
  133607. 4,
  133608. };
  133609. static long _vq_lengthlist__44c7_s_p6_1[] = {
  133610. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  133611. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  133612. };
  133613. static float _vq_quantthresh__44c7_s_p6_1[] = {
  133614. -1.5, -0.5, 0.5, 1.5,
  133615. };
  133616. static long _vq_quantmap__44c7_s_p6_1[] = {
  133617. 3, 1, 0, 2, 4,
  133618. };
  133619. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_1 = {
  133620. _vq_quantthresh__44c7_s_p6_1,
  133621. _vq_quantmap__44c7_s_p6_1,
  133622. 5,
  133623. 5
  133624. };
  133625. static static_codebook _44c7_s_p6_1 = {
  133626. 2, 25,
  133627. _vq_lengthlist__44c7_s_p6_1,
  133628. 1, -533725184, 1611661312, 3, 0,
  133629. _vq_quantlist__44c7_s_p6_1,
  133630. NULL,
  133631. &_vq_auxt__44c7_s_p6_1,
  133632. NULL,
  133633. 0
  133634. };
  133635. static long _vq_quantlist__44c7_s_p7_0[] = {
  133636. 6,
  133637. 5,
  133638. 7,
  133639. 4,
  133640. 8,
  133641. 3,
  133642. 9,
  133643. 2,
  133644. 10,
  133645. 1,
  133646. 11,
  133647. 0,
  133648. 12,
  133649. };
  133650. static long _vq_lengthlist__44c7_s_p7_0[] = {
  133651. 1, 4, 4, 6, 6, 7, 8, 9, 9,10,10,12,11, 6, 5, 5,
  133652. 7, 7, 8, 8, 9,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  133653. 8,10,10,11,11,12,12,20, 7, 7, 7, 7, 8, 9,10,10,
  133654. 11,11,12,13,20, 7, 7, 7, 7, 9, 9,10,10,11,12,13,
  133655. 13,20,11,11, 8, 8, 9, 9,11,11,12,12,13,13,20,11,
  133656. 11, 8, 8, 9, 9,11,11,12,12,13,13,20,20,20,10,10,
  133657. 10,10,12,12,13,13,13,13,20,20,20,10,10,10,10,12,
  133658. 12,13,13,13,14,20,20,20,14,14,11,11,12,12,13,13,
  133659. 14,14,20,20,20,14,14,11,11,12,12,13,13,14,14,20,
  133660. 20,20,20,19,13,13,13,13,14,14,15,14,19,19,19,19,
  133661. 19,13,13,13,13,14,14,15,15,
  133662. };
  133663. static float _vq_quantthresh__44c7_s_p7_0[] = {
  133664. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  133665. 27.5, 38.5, 49.5, 60.5,
  133666. };
  133667. static long _vq_quantmap__44c7_s_p7_0[] = {
  133668. 11, 9, 7, 5, 3, 1, 0, 2,
  133669. 4, 6, 8, 10, 12,
  133670. };
  133671. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_0 = {
  133672. _vq_quantthresh__44c7_s_p7_0,
  133673. _vq_quantmap__44c7_s_p7_0,
  133674. 13,
  133675. 13
  133676. };
  133677. static static_codebook _44c7_s_p7_0 = {
  133678. 2, 169,
  133679. _vq_lengthlist__44c7_s_p7_0,
  133680. 1, -523206656, 1618345984, 4, 0,
  133681. _vq_quantlist__44c7_s_p7_0,
  133682. NULL,
  133683. &_vq_auxt__44c7_s_p7_0,
  133684. NULL,
  133685. 0
  133686. };
  133687. static long _vq_quantlist__44c7_s_p7_1[] = {
  133688. 5,
  133689. 4,
  133690. 6,
  133691. 3,
  133692. 7,
  133693. 2,
  133694. 8,
  133695. 1,
  133696. 9,
  133697. 0,
  133698. 10,
  133699. };
  133700. static long _vq_lengthlist__44c7_s_p7_1[] = {
  133701. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 7, 7,
  133702. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  133703. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  133704. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133705. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  133706. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  133707. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  133708. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133709. };
  133710. static float _vq_quantthresh__44c7_s_p7_1[] = {
  133711. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133712. 3.5, 4.5,
  133713. };
  133714. static long _vq_quantmap__44c7_s_p7_1[] = {
  133715. 9, 7, 5, 3, 1, 0, 2, 4,
  133716. 6, 8, 10,
  133717. };
  133718. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_1 = {
  133719. _vq_quantthresh__44c7_s_p7_1,
  133720. _vq_quantmap__44c7_s_p7_1,
  133721. 11,
  133722. 11
  133723. };
  133724. static static_codebook _44c7_s_p7_1 = {
  133725. 2, 121,
  133726. _vq_lengthlist__44c7_s_p7_1,
  133727. 1, -531365888, 1611661312, 4, 0,
  133728. _vq_quantlist__44c7_s_p7_1,
  133729. NULL,
  133730. &_vq_auxt__44c7_s_p7_1,
  133731. NULL,
  133732. 0
  133733. };
  133734. static long _vq_quantlist__44c7_s_p8_0[] = {
  133735. 7,
  133736. 6,
  133737. 8,
  133738. 5,
  133739. 9,
  133740. 4,
  133741. 10,
  133742. 3,
  133743. 11,
  133744. 2,
  133745. 12,
  133746. 1,
  133747. 13,
  133748. 0,
  133749. 14,
  133750. };
  133751. static long _vq_lengthlist__44c7_s_p8_0[] = {
  133752. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8, 9, 9,10,10, 6,
  133753. 5, 5, 7, 7, 9, 9, 8, 8,10, 9,11,10,12,11, 6, 5,
  133754. 5, 8, 7, 9, 9, 8, 8,10,10,11,11,12,11,19, 8, 8,
  133755. 8, 8,10,10, 9, 9,10,10,11,11,12,11,19, 8, 8, 8,
  133756. 8,10,10, 9, 9,10,10,11,11,12,12,19,12,12, 9, 9,
  133757. 10,10, 9,10,10,10,11,11,12,12,19,12,12, 9, 9,10,
  133758. 10,10,10,10,10,12,12,12,12,19,19,19, 9, 9, 9, 9,
  133759. 11,10,11,11,12,11,13,13,19,19,19, 9, 9, 9, 9,11,
  133760. 10,11,11,11,12,13,13,19,19,19,13,13,10,10,11,11,
  133761. 12,12,12,12,13,12,19,19,19,14,13,10,10,11,11,12,
  133762. 12,12,13,13,13,19,19,19,19,19,12,12,12,11,12,13,
  133763. 14,13,13,13,19,19,19,19,19,12,12,12,11,12,12,13,
  133764. 14,13,14,19,19,19,19,19,16,16,12,13,12,13,13,14,
  133765. 15,14,19,18,18,18,18,16,15,12,11,12,11,14,12,14,
  133766. 14,
  133767. };
  133768. static float _vq_quantthresh__44c7_s_p8_0[] = {
  133769. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  133770. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  133771. };
  133772. static long _vq_quantmap__44c7_s_p8_0[] = {
  133773. 13, 11, 9, 7, 5, 3, 1, 0,
  133774. 2, 4, 6, 8, 10, 12, 14,
  133775. };
  133776. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_0 = {
  133777. _vq_quantthresh__44c7_s_p8_0,
  133778. _vq_quantmap__44c7_s_p8_0,
  133779. 15,
  133780. 15
  133781. };
  133782. static static_codebook _44c7_s_p8_0 = {
  133783. 2, 225,
  133784. _vq_lengthlist__44c7_s_p8_0,
  133785. 1, -520986624, 1620377600, 4, 0,
  133786. _vq_quantlist__44c7_s_p8_0,
  133787. NULL,
  133788. &_vq_auxt__44c7_s_p8_0,
  133789. NULL,
  133790. 0
  133791. };
  133792. static long _vq_quantlist__44c7_s_p8_1[] = {
  133793. 10,
  133794. 9,
  133795. 11,
  133796. 8,
  133797. 12,
  133798. 7,
  133799. 13,
  133800. 6,
  133801. 14,
  133802. 5,
  133803. 15,
  133804. 4,
  133805. 16,
  133806. 3,
  133807. 17,
  133808. 2,
  133809. 18,
  133810. 1,
  133811. 19,
  133812. 0,
  133813. 20,
  133814. };
  133815. static long _vq_lengthlist__44c7_s_p8_1[] = {
  133816. 3, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  133817. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  133818. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  133819. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  133820. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133821. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  133822. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  133823. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  133824. 10, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133825. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133826. 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,10,10, 9, 9, 9,
  133827. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9, 9,10,11,10,
  133828. 11,10, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9, 9,
  133829. 9, 9,11,10,11,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,
  133830. 10, 9, 9,10, 9, 9,10,11,10,10,11,10, 9, 9, 9, 9,
  133831. 9,10,10, 9,10,10,10,10, 9,10,10,10,10,10,10,11,
  133832. 11,11,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  133833. 10,10,10,11,11,10,10,10,10,10,10,10,10,10,10,10,
  133834. 10, 9,10,10, 9,10,11,11,10,11,10,11,10, 9,10,10,
  133835. 9,10,10,10,10,10,10,10,10,10,10,11,11,11,11,10,
  133836. 11,11,10,10,10,10,10,10, 9,10, 9,10,10, 9,10, 9,
  133837. 10,10,10,11,10,11,10,11,11,10,10,10,10,10,10, 9,
  133838. 10,10,10,10,10,10,10,11,10,10,10,10,10,10,10,10,
  133839. 10,10,10,10,10,10,10,10,10,10,10,10,10,11,10,11,
  133840. 11,10,10,10,10, 9, 9,10,10, 9, 9,10, 9,10,10,10,
  133841. 10,11,11,10,10,10,10,10,10,10, 9, 9,10,10,10, 9,
  133842. 9,10,10,10,10,10,11,10,11,10,10,10,10,10,10, 9,
  133843. 10,10,10,10,10,10,10,10,10,
  133844. };
  133845. static float _vq_quantthresh__44c7_s_p8_1[] = {
  133846. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  133847. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  133848. 6.5, 7.5, 8.5, 9.5,
  133849. };
  133850. static long _vq_quantmap__44c7_s_p8_1[] = {
  133851. 19, 17, 15, 13, 11, 9, 7, 5,
  133852. 3, 1, 0, 2, 4, 6, 8, 10,
  133853. 12, 14, 16, 18, 20,
  133854. };
  133855. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_1 = {
  133856. _vq_quantthresh__44c7_s_p8_1,
  133857. _vq_quantmap__44c7_s_p8_1,
  133858. 21,
  133859. 21
  133860. };
  133861. static static_codebook _44c7_s_p8_1 = {
  133862. 2, 441,
  133863. _vq_lengthlist__44c7_s_p8_1,
  133864. 1, -529268736, 1611661312, 5, 0,
  133865. _vq_quantlist__44c7_s_p8_1,
  133866. NULL,
  133867. &_vq_auxt__44c7_s_p8_1,
  133868. NULL,
  133869. 0
  133870. };
  133871. static long _vq_quantlist__44c7_s_p9_0[] = {
  133872. 6,
  133873. 5,
  133874. 7,
  133875. 4,
  133876. 8,
  133877. 3,
  133878. 9,
  133879. 2,
  133880. 10,
  133881. 1,
  133882. 11,
  133883. 0,
  133884. 12,
  133885. };
  133886. static long _vq_lengthlist__44c7_s_p9_0[] = {
  133887. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 6, 6,
  133888. 11,11,11,11,11,11,11,11,11,11, 4, 7, 7,11,11,11,
  133889. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133890. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133891. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133892. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133893. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133894. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133895. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133896. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133897. 11,11,11,11,11,11,11,11,11,
  133898. };
  133899. static float _vq_quantthresh__44c7_s_p9_0[] = {
  133900. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  133901. 1592.5, 2229.5, 2866.5, 3503.5,
  133902. };
  133903. static long _vq_quantmap__44c7_s_p9_0[] = {
  133904. 11, 9, 7, 5, 3, 1, 0, 2,
  133905. 4, 6, 8, 10, 12,
  133906. };
  133907. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_0 = {
  133908. _vq_quantthresh__44c7_s_p9_0,
  133909. _vq_quantmap__44c7_s_p9_0,
  133910. 13,
  133911. 13
  133912. };
  133913. static static_codebook _44c7_s_p9_0 = {
  133914. 2, 169,
  133915. _vq_lengthlist__44c7_s_p9_0,
  133916. 1, -511845376, 1630791680, 4, 0,
  133917. _vq_quantlist__44c7_s_p9_0,
  133918. NULL,
  133919. &_vq_auxt__44c7_s_p9_0,
  133920. NULL,
  133921. 0
  133922. };
  133923. static long _vq_quantlist__44c7_s_p9_1[] = {
  133924. 6,
  133925. 5,
  133926. 7,
  133927. 4,
  133928. 8,
  133929. 3,
  133930. 9,
  133931. 2,
  133932. 10,
  133933. 1,
  133934. 11,
  133935. 0,
  133936. 12,
  133937. };
  133938. static long _vq_lengthlist__44c7_s_p9_1[] = {
  133939. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  133940. 8, 8, 9, 8, 8, 7, 9, 8,11,10, 5, 6, 6, 8, 8, 9,
  133941. 8, 8, 8,10, 9,11,11,16, 8, 8, 9, 8, 9, 9, 9, 8,
  133942. 10, 9,11,10,16, 8, 8, 9, 9,10,10, 9, 9,10,10,11,
  133943. 11,16,13,13, 9, 9,10,10, 9,10,11,11,12,11,16,13,
  133944. 13, 9, 8,10, 9,10,10,10,10,11,11,16,14,16, 8, 9,
  133945. 9, 9,11,10,11,11,12,11,16,16,16, 9, 7,10, 7,11,
  133946. 10,11,11,12,11,16,16,16,12,12, 9,10,11,11,12,11,
  133947. 12,12,16,16,16,12,10,10, 7,11, 8,12,11,12,12,16,
  133948. 16,15,16,16,11,12,10,10,12,11,12,12,16,16,16,15,
  133949. 15,11,11,10,10,12,12,12,12,
  133950. };
  133951. static float _vq_quantthresh__44c7_s_p9_1[] = {
  133952. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  133953. 122.5, 171.5, 220.5, 269.5,
  133954. };
  133955. static long _vq_quantmap__44c7_s_p9_1[] = {
  133956. 11, 9, 7, 5, 3, 1, 0, 2,
  133957. 4, 6, 8, 10, 12,
  133958. };
  133959. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_1 = {
  133960. _vq_quantthresh__44c7_s_p9_1,
  133961. _vq_quantmap__44c7_s_p9_1,
  133962. 13,
  133963. 13
  133964. };
  133965. static static_codebook _44c7_s_p9_1 = {
  133966. 2, 169,
  133967. _vq_lengthlist__44c7_s_p9_1,
  133968. 1, -518889472, 1622704128, 4, 0,
  133969. _vq_quantlist__44c7_s_p9_1,
  133970. NULL,
  133971. &_vq_auxt__44c7_s_p9_1,
  133972. NULL,
  133973. 0
  133974. };
  133975. static long _vq_quantlist__44c7_s_p9_2[] = {
  133976. 24,
  133977. 23,
  133978. 25,
  133979. 22,
  133980. 26,
  133981. 21,
  133982. 27,
  133983. 20,
  133984. 28,
  133985. 19,
  133986. 29,
  133987. 18,
  133988. 30,
  133989. 17,
  133990. 31,
  133991. 16,
  133992. 32,
  133993. 15,
  133994. 33,
  133995. 14,
  133996. 34,
  133997. 13,
  133998. 35,
  133999. 12,
  134000. 36,
  134001. 11,
  134002. 37,
  134003. 10,
  134004. 38,
  134005. 9,
  134006. 39,
  134007. 8,
  134008. 40,
  134009. 7,
  134010. 41,
  134011. 6,
  134012. 42,
  134013. 5,
  134014. 43,
  134015. 4,
  134016. 44,
  134017. 3,
  134018. 45,
  134019. 2,
  134020. 46,
  134021. 1,
  134022. 47,
  134023. 0,
  134024. 48,
  134025. };
  134026. static long _vq_lengthlist__44c7_s_p9_2[] = {
  134027. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  134028. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134029. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134030. 7,
  134031. };
  134032. static float _vq_quantthresh__44c7_s_p9_2[] = {
  134033. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  134034. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  134035. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134036. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134037. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  134038. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  134039. };
  134040. static long _vq_quantmap__44c7_s_p9_2[] = {
  134041. 47, 45, 43, 41, 39, 37, 35, 33,
  134042. 31, 29, 27, 25, 23, 21, 19, 17,
  134043. 15, 13, 11, 9, 7, 5, 3, 1,
  134044. 0, 2, 4, 6, 8, 10, 12, 14,
  134045. 16, 18, 20, 22, 24, 26, 28, 30,
  134046. 32, 34, 36, 38, 40, 42, 44, 46,
  134047. 48,
  134048. };
  134049. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_2 = {
  134050. _vq_quantthresh__44c7_s_p9_2,
  134051. _vq_quantmap__44c7_s_p9_2,
  134052. 49,
  134053. 49
  134054. };
  134055. static static_codebook _44c7_s_p9_2 = {
  134056. 1, 49,
  134057. _vq_lengthlist__44c7_s_p9_2,
  134058. 1, -526909440, 1611661312, 6, 0,
  134059. _vq_quantlist__44c7_s_p9_2,
  134060. NULL,
  134061. &_vq_auxt__44c7_s_p9_2,
  134062. NULL,
  134063. 0
  134064. };
  134065. static long _huff_lengthlist__44c7_s_short[] = {
  134066. 4,11,12,14,15,15,17,17,18,18, 5, 6, 6, 8, 9,10,
  134067. 13,17,18,19, 7, 5, 4, 6, 8, 9,11,15,19,19, 8, 6,
  134068. 5, 5, 6, 7,11,14,16,17, 9, 7, 7, 6, 7, 7,10,13,
  134069. 15,19,10, 8, 7, 6, 7, 6, 7, 9,14,16,12,10, 9, 7,
  134070. 7, 6, 4, 5,10,15,14,13,11, 7, 6, 6, 4, 2, 7,13,
  134071. 16,16,15, 9, 8, 8, 8, 6, 9,13,19,19,17,12,11,10,
  134072. 10, 9,11,14,
  134073. };
  134074. static static_codebook _huff_book__44c7_s_short = {
  134075. 2, 100,
  134076. _huff_lengthlist__44c7_s_short,
  134077. 0, 0, 0, 0, 0,
  134078. NULL,
  134079. NULL,
  134080. NULL,
  134081. NULL,
  134082. 0
  134083. };
  134084. static long _huff_lengthlist__44c8_s_long[] = {
  134085. 3, 8,12,13,14,14,14,13,14,14, 6, 4, 5, 8,10,10,
  134086. 11,11,14,13, 9, 5, 4, 5, 7, 8, 9,10,13,13,12, 7,
  134087. 5, 4, 5, 6, 8, 9,12,13,13, 9, 6, 5, 5, 5, 7, 9,
  134088. 11,14,12,10, 7, 6, 5, 4, 6, 7,10,11,12,11, 9, 8,
  134089. 7, 5, 5, 6,10,10,13,12,10, 9, 8, 6, 6, 5, 8,10,
  134090. 14,13,12,12,11,10, 9, 7, 8,10,12,13,14,14,13,12,
  134091. 11, 9, 9,10,
  134092. };
  134093. static static_codebook _huff_book__44c8_s_long = {
  134094. 2, 100,
  134095. _huff_lengthlist__44c8_s_long,
  134096. 0, 0, 0, 0, 0,
  134097. NULL,
  134098. NULL,
  134099. NULL,
  134100. NULL,
  134101. 0
  134102. };
  134103. static long _vq_quantlist__44c8_s_p1_0[] = {
  134104. 1,
  134105. 0,
  134106. 2,
  134107. };
  134108. static long _vq_lengthlist__44c8_s_p1_0[] = {
  134109. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 7, 7, 0, 9, 8, 0,
  134110. 9, 8, 6, 7, 7, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  134111. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  134112. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  134113. 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  134114. 8,
  134115. };
  134116. static float _vq_quantthresh__44c8_s_p1_0[] = {
  134117. -0.5, 0.5,
  134118. };
  134119. static long _vq_quantmap__44c8_s_p1_0[] = {
  134120. 1, 0, 2,
  134121. };
  134122. static encode_aux_threshmatch _vq_auxt__44c8_s_p1_0 = {
  134123. _vq_quantthresh__44c8_s_p1_0,
  134124. _vq_quantmap__44c8_s_p1_0,
  134125. 3,
  134126. 3
  134127. };
  134128. static static_codebook _44c8_s_p1_0 = {
  134129. 4, 81,
  134130. _vq_lengthlist__44c8_s_p1_0,
  134131. 1, -535822336, 1611661312, 2, 0,
  134132. _vq_quantlist__44c8_s_p1_0,
  134133. NULL,
  134134. &_vq_auxt__44c8_s_p1_0,
  134135. NULL,
  134136. 0
  134137. };
  134138. static long _vq_quantlist__44c8_s_p2_0[] = {
  134139. 2,
  134140. 1,
  134141. 3,
  134142. 0,
  134143. 4,
  134144. };
  134145. static long _vq_lengthlist__44c8_s_p2_0[] = {
  134146. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  134147. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  134148. 7,10, 9, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  134149. 11,11, 5, 7, 7, 9, 9, 0, 7, 8, 9,10, 0, 7, 8, 9,
  134150. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  134151. 0,11,10,12,11, 0,11,10,12,12, 0,13,13,14,14, 0,
  134152. 0, 0,14,13, 8, 9, 9,10,11, 0,10,11,12,12, 0,10,
  134153. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  134154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134155. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  134156. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,11,10, 5,
  134157. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  134158. 9,10,10, 0, 0, 0,10,10, 8,10, 9,12,12, 0,10,10,
  134159. 12,11, 0,10,10,12,12, 0,12,12,13,12, 0, 0, 0,13,
  134160. 12, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,11,12,
  134161. 0,12,12,13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0,
  134162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134163. 0, 0, 0, 6, 8, 7,11,10, 0, 7, 7,10,10, 0, 7, 7,
  134164. 10,10, 0, 9, 9,10,11, 0, 0, 0,10,10, 6, 7, 8,10,
  134165. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,10,10,
  134166. 0, 0, 0,10,10, 9,10, 9,12,12, 0,10,10,12,12, 0,
  134167. 10,10,12,11, 0,12,12,13,13, 0, 0, 0,13,12, 8, 9,
  134168. 10,12,12, 0,10,10,12,12, 0,10,10,11,12, 0,12,12,
  134169. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134171. 7,10,10,13,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  134172. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,13, 0, 9,
  134173. 9,12,12, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  134174. 12,12, 9,11,11,14,13, 0,10,10,13,12, 0,11,10,13,
  134175. 12, 0,12,12,13,12, 0, 0, 0,13,13, 9,11,11,13,14,
  134176. 0,10,11,12,13, 0,10,11,13,13, 0,12,12,12,13, 0,
  134177. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  134182. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,11,
  134183. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  134184. 13,13, 0,10,11,13,13, 0,12,12,13,13, 0, 0, 0,12,
  134185. 13,
  134186. };
  134187. static float _vq_quantthresh__44c8_s_p2_0[] = {
  134188. -1.5, -0.5, 0.5, 1.5,
  134189. };
  134190. static long _vq_quantmap__44c8_s_p2_0[] = {
  134191. 3, 1, 0, 2, 4,
  134192. };
  134193. static encode_aux_threshmatch _vq_auxt__44c8_s_p2_0 = {
  134194. _vq_quantthresh__44c8_s_p2_0,
  134195. _vq_quantmap__44c8_s_p2_0,
  134196. 5,
  134197. 5
  134198. };
  134199. static static_codebook _44c8_s_p2_0 = {
  134200. 4, 625,
  134201. _vq_lengthlist__44c8_s_p2_0,
  134202. 1, -533725184, 1611661312, 3, 0,
  134203. _vq_quantlist__44c8_s_p2_0,
  134204. NULL,
  134205. &_vq_auxt__44c8_s_p2_0,
  134206. NULL,
  134207. 0
  134208. };
  134209. static long _vq_quantlist__44c8_s_p3_0[] = {
  134210. 4,
  134211. 3,
  134212. 5,
  134213. 2,
  134214. 6,
  134215. 1,
  134216. 7,
  134217. 0,
  134218. 8,
  134219. };
  134220. static long _vq_lengthlist__44c8_s_p3_0[] = {
  134221. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  134222. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  134223. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  134224. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  134225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134226. 0,
  134227. };
  134228. static float _vq_quantthresh__44c8_s_p3_0[] = {
  134229. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  134230. };
  134231. static long _vq_quantmap__44c8_s_p3_0[] = {
  134232. 7, 5, 3, 1, 0, 2, 4, 6,
  134233. 8,
  134234. };
  134235. static encode_aux_threshmatch _vq_auxt__44c8_s_p3_0 = {
  134236. _vq_quantthresh__44c8_s_p3_0,
  134237. _vq_quantmap__44c8_s_p3_0,
  134238. 9,
  134239. 9
  134240. };
  134241. static static_codebook _44c8_s_p3_0 = {
  134242. 2, 81,
  134243. _vq_lengthlist__44c8_s_p3_0,
  134244. 1, -531628032, 1611661312, 4, 0,
  134245. _vq_quantlist__44c8_s_p3_0,
  134246. NULL,
  134247. &_vq_auxt__44c8_s_p3_0,
  134248. NULL,
  134249. 0
  134250. };
  134251. static long _vq_quantlist__44c8_s_p4_0[] = {
  134252. 8,
  134253. 7,
  134254. 9,
  134255. 6,
  134256. 10,
  134257. 5,
  134258. 11,
  134259. 4,
  134260. 12,
  134261. 3,
  134262. 13,
  134263. 2,
  134264. 14,
  134265. 1,
  134266. 15,
  134267. 0,
  134268. 16,
  134269. };
  134270. static long _vq_lengthlist__44c8_s_p4_0[] = {
  134271. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  134272. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 8,10,10,11,11,
  134273. 11,11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  134274. 11,11,11, 0, 6, 5, 6, 6, 7, 7, 9, 9, 9, 9,10,10,
  134275. 11,11,12,12, 0, 0, 0, 6, 6, 7, 7, 9, 9, 9, 9,10,
  134276. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  134277. 11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  134278. 10,11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  134279. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  134280. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  134281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134289. 0,
  134290. };
  134291. static float _vq_quantthresh__44c8_s_p4_0[] = {
  134292. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134293. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134294. };
  134295. static long _vq_quantmap__44c8_s_p4_0[] = {
  134296. 15, 13, 11, 9, 7, 5, 3, 1,
  134297. 0, 2, 4, 6, 8, 10, 12, 14,
  134298. 16,
  134299. };
  134300. static encode_aux_threshmatch _vq_auxt__44c8_s_p4_0 = {
  134301. _vq_quantthresh__44c8_s_p4_0,
  134302. _vq_quantmap__44c8_s_p4_0,
  134303. 17,
  134304. 17
  134305. };
  134306. static static_codebook _44c8_s_p4_0 = {
  134307. 2, 289,
  134308. _vq_lengthlist__44c8_s_p4_0,
  134309. 1, -529530880, 1611661312, 5, 0,
  134310. _vq_quantlist__44c8_s_p4_0,
  134311. NULL,
  134312. &_vq_auxt__44c8_s_p4_0,
  134313. NULL,
  134314. 0
  134315. };
  134316. static long _vq_quantlist__44c8_s_p5_0[] = {
  134317. 1,
  134318. 0,
  134319. 2,
  134320. };
  134321. static long _vq_lengthlist__44c8_s_p5_0[] = {
  134322. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6,10,10,10,10,
  134323. 10,10, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  134324. 11,10,11,11, 7,10,10,11,12,12,12,12,12, 7,10,10,
  134325. 11,12,12,12,12,12, 6,10,10,10,12,12,10,12,12, 7,
  134326. 10,10,11,12,12,12,12,12, 7,10,10,11,12,12,12,12,
  134327. 12,
  134328. };
  134329. static float _vq_quantthresh__44c8_s_p5_0[] = {
  134330. -5.5, 5.5,
  134331. };
  134332. static long _vq_quantmap__44c8_s_p5_0[] = {
  134333. 1, 0, 2,
  134334. };
  134335. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_0 = {
  134336. _vq_quantthresh__44c8_s_p5_0,
  134337. _vq_quantmap__44c8_s_p5_0,
  134338. 3,
  134339. 3
  134340. };
  134341. static static_codebook _44c8_s_p5_0 = {
  134342. 4, 81,
  134343. _vq_lengthlist__44c8_s_p5_0,
  134344. 1, -529137664, 1618345984, 2, 0,
  134345. _vq_quantlist__44c8_s_p5_0,
  134346. NULL,
  134347. &_vq_auxt__44c8_s_p5_0,
  134348. NULL,
  134349. 0
  134350. };
  134351. static long _vq_quantlist__44c8_s_p5_1[] = {
  134352. 5,
  134353. 4,
  134354. 6,
  134355. 3,
  134356. 7,
  134357. 2,
  134358. 8,
  134359. 1,
  134360. 9,
  134361. 0,
  134362. 10,
  134363. };
  134364. static long _vq_lengthlist__44c8_s_p5_1[] = {
  134365. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 5, 6, 6,
  134366. 7, 7, 8, 8, 8, 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  134367. 9,12, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,12,12,12, 6,
  134368. 6, 7, 7, 8, 8, 9, 9,11,11,11, 6, 6, 7, 7, 8, 8,
  134369. 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11,
  134370. 7, 7, 7, 8, 8, 8, 8, 8,11,11,11,11,11, 7, 7, 8,
  134371. 8, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 8, 8,11,11,
  134372. 11,11,11, 7, 7, 7, 7, 8, 8,
  134373. };
  134374. static float _vq_quantthresh__44c8_s_p5_1[] = {
  134375. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134376. 3.5, 4.5,
  134377. };
  134378. static long _vq_quantmap__44c8_s_p5_1[] = {
  134379. 9, 7, 5, 3, 1, 0, 2, 4,
  134380. 6, 8, 10,
  134381. };
  134382. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_1 = {
  134383. _vq_quantthresh__44c8_s_p5_1,
  134384. _vq_quantmap__44c8_s_p5_1,
  134385. 11,
  134386. 11
  134387. };
  134388. static static_codebook _44c8_s_p5_1 = {
  134389. 2, 121,
  134390. _vq_lengthlist__44c8_s_p5_1,
  134391. 1, -531365888, 1611661312, 4, 0,
  134392. _vq_quantlist__44c8_s_p5_1,
  134393. NULL,
  134394. &_vq_auxt__44c8_s_p5_1,
  134395. NULL,
  134396. 0
  134397. };
  134398. static long _vq_quantlist__44c8_s_p6_0[] = {
  134399. 6,
  134400. 5,
  134401. 7,
  134402. 4,
  134403. 8,
  134404. 3,
  134405. 9,
  134406. 2,
  134407. 10,
  134408. 1,
  134409. 11,
  134410. 0,
  134411. 12,
  134412. };
  134413. static long _vq_lengthlist__44c8_s_p6_0[] = {
  134414. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  134415. 7, 7, 8, 8, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 8,
  134416. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,
  134417. 10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,10,10,11,
  134418. 11, 0,11,11, 9, 9,10,10,11,11,11,11,12,12, 0,12,
  134419. 12, 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  134420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134424. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134425. };
  134426. static float _vq_quantthresh__44c8_s_p6_0[] = {
  134427. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  134428. 12.5, 17.5, 22.5, 27.5,
  134429. };
  134430. static long _vq_quantmap__44c8_s_p6_0[] = {
  134431. 11, 9, 7, 5, 3, 1, 0, 2,
  134432. 4, 6, 8, 10, 12,
  134433. };
  134434. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_0 = {
  134435. _vq_quantthresh__44c8_s_p6_0,
  134436. _vq_quantmap__44c8_s_p6_0,
  134437. 13,
  134438. 13
  134439. };
  134440. static static_codebook _44c8_s_p6_0 = {
  134441. 2, 169,
  134442. _vq_lengthlist__44c8_s_p6_0,
  134443. 1, -526516224, 1616117760, 4, 0,
  134444. _vq_quantlist__44c8_s_p6_0,
  134445. NULL,
  134446. &_vq_auxt__44c8_s_p6_0,
  134447. NULL,
  134448. 0
  134449. };
  134450. static long _vq_quantlist__44c8_s_p6_1[] = {
  134451. 2,
  134452. 1,
  134453. 3,
  134454. 0,
  134455. 4,
  134456. };
  134457. static long _vq_lengthlist__44c8_s_p6_1[] = {
  134458. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  134459. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  134460. };
  134461. static float _vq_quantthresh__44c8_s_p6_1[] = {
  134462. -1.5, -0.5, 0.5, 1.5,
  134463. };
  134464. static long _vq_quantmap__44c8_s_p6_1[] = {
  134465. 3, 1, 0, 2, 4,
  134466. };
  134467. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_1 = {
  134468. _vq_quantthresh__44c8_s_p6_1,
  134469. _vq_quantmap__44c8_s_p6_1,
  134470. 5,
  134471. 5
  134472. };
  134473. static static_codebook _44c8_s_p6_1 = {
  134474. 2, 25,
  134475. _vq_lengthlist__44c8_s_p6_1,
  134476. 1, -533725184, 1611661312, 3, 0,
  134477. _vq_quantlist__44c8_s_p6_1,
  134478. NULL,
  134479. &_vq_auxt__44c8_s_p6_1,
  134480. NULL,
  134481. 0
  134482. };
  134483. static long _vq_quantlist__44c8_s_p7_0[] = {
  134484. 6,
  134485. 5,
  134486. 7,
  134487. 4,
  134488. 8,
  134489. 3,
  134490. 9,
  134491. 2,
  134492. 10,
  134493. 1,
  134494. 11,
  134495. 0,
  134496. 12,
  134497. };
  134498. static long _vq_lengthlist__44c8_s_p7_0[] = {
  134499. 1, 4, 4, 6, 6, 8, 7, 9, 9,10,10,12,12, 6, 5, 5,
  134500. 7, 7, 8, 8,10,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  134501. 8,10,10,11,11,12,12,21, 7, 7, 7, 7, 8, 9,10,10,
  134502. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,12,12,13,
  134503. 13,21,11,11, 8, 8, 9, 9,11,11,12,12,13,13,21,11,
  134504. 11, 8, 8, 9, 9,11,11,12,12,13,13,21,21,21,10,10,
  134505. 10,10,11,11,12,13,13,13,21,21,21,10,10,10,10,11,
  134506. 11,13,13,14,13,21,21,21,13,13,11,11,12,12,13,13,
  134507. 14,14,21,21,21,14,14,11,11,12,12,13,13,14,14,21,
  134508. 21,21,21,20,13,13,13,12,14,14,16,15,20,20,20,20,
  134509. 20,13,13,13,13,14,13,15,15,
  134510. };
  134511. static float _vq_quantthresh__44c8_s_p7_0[] = {
  134512. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  134513. 27.5, 38.5, 49.5, 60.5,
  134514. };
  134515. static long _vq_quantmap__44c8_s_p7_0[] = {
  134516. 11, 9, 7, 5, 3, 1, 0, 2,
  134517. 4, 6, 8, 10, 12,
  134518. };
  134519. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_0 = {
  134520. _vq_quantthresh__44c8_s_p7_0,
  134521. _vq_quantmap__44c8_s_p7_0,
  134522. 13,
  134523. 13
  134524. };
  134525. static static_codebook _44c8_s_p7_0 = {
  134526. 2, 169,
  134527. _vq_lengthlist__44c8_s_p7_0,
  134528. 1, -523206656, 1618345984, 4, 0,
  134529. _vq_quantlist__44c8_s_p7_0,
  134530. NULL,
  134531. &_vq_auxt__44c8_s_p7_0,
  134532. NULL,
  134533. 0
  134534. };
  134535. static long _vq_quantlist__44c8_s_p7_1[] = {
  134536. 5,
  134537. 4,
  134538. 6,
  134539. 3,
  134540. 7,
  134541. 2,
  134542. 8,
  134543. 1,
  134544. 9,
  134545. 0,
  134546. 10,
  134547. };
  134548. static long _vq_lengthlist__44c8_s_p7_1[] = {
  134549. 4, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7,
  134550. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  134551. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  134552. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134553. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  134554. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  134555. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  134556. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134557. };
  134558. static float _vq_quantthresh__44c8_s_p7_1[] = {
  134559. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134560. 3.5, 4.5,
  134561. };
  134562. static long _vq_quantmap__44c8_s_p7_1[] = {
  134563. 9, 7, 5, 3, 1, 0, 2, 4,
  134564. 6, 8, 10,
  134565. };
  134566. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_1 = {
  134567. _vq_quantthresh__44c8_s_p7_1,
  134568. _vq_quantmap__44c8_s_p7_1,
  134569. 11,
  134570. 11
  134571. };
  134572. static static_codebook _44c8_s_p7_1 = {
  134573. 2, 121,
  134574. _vq_lengthlist__44c8_s_p7_1,
  134575. 1, -531365888, 1611661312, 4, 0,
  134576. _vq_quantlist__44c8_s_p7_1,
  134577. NULL,
  134578. &_vq_auxt__44c8_s_p7_1,
  134579. NULL,
  134580. 0
  134581. };
  134582. static long _vq_quantlist__44c8_s_p8_0[] = {
  134583. 7,
  134584. 6,
  134585. 8,
  134586. 5,
  134587. 9,
  134588. 4,
  134589. 10,
  134590. 3,
  134591. 11,
  134592. 2,
  134593. 12,
  134594. 1,
  134595. 13,
  134596. 0,
  134597. 14,
  134598. };
  134599. static long _vq_lengthlist__44c8_s_p8_0[] = {
  134600. 1, 4, 4, 7, 6, 8, 8, 8, 7, 9, 8,10,10,11,10, 6,
  134601. 5, 5, 7, 7, 9, 9, 8, 8,10,10,11,11,12,11, 6, 5,
  134602. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8,
  134603. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8, 8,
  134604. 8,10, 9, 9, 9,10,10,11,11,12,12,20,12,12, 9, 9,
  134605. 10,10,10,10,10,11,12,12,12,12,20,12,12, 9, 9,10,
  134606. 10,10,10,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,
  134607. 11,10,11,11,12,12,12,13,20,19,19, 9, 9, 9, 9,11,
  134608. 11,11,12,12,12,13,13,19,19,19,13,13,10,10,11,11,
  134609. 12,12,13,13,13,13,19,19,19,14,13,11,10,11,11,12,
  134610. 12,12,13,13,13,19,19,19,19,19,12,12,12,12,13,13,
  134611. 13,13,14,13,19,19,19,19,19,12,12,12,11,12,12,13,
  134612. 14,14,14,19,19,19,19,19,16,15,13,12,13,13,13,14,
  134613. 14,14,19,19,19,19,19,17,17,13,12,13,11,14,13,15,
  134614. 15,
  134615. };
  134616. static float _vq_quantthresh__44c8_s_p8_0[] = {
  134617. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  134618. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  134619. };
  134620. static long _vq_quantmap__44c8_s_p8_0[] = {
  134621. 13, 11, 9, 7, 5, 3, 1, 0,
  134622. 2, 4, 6, 8, 10, 12, 14,
  134623. };
  134624. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_0 = {
  134625. _vq_quantthresh__44c8_s_p8_0,
  134626. _vq_quantmap__44c8_s_p8_0,
  134627. 15,
  134628. 15
  134629. };
  134630. static static_codebook _44c8_s_p8_0 = {
  134631. 2, 225,
  134632. _vq_lengthlist__44c8_s_p8_0,
  134633. 1, -520986624, 1620377600, 4, 0,
  134634. _vq_quantlist__44c8_s_p8_0,
  134635. NULL,
  134636. &_vq_auxt__44c8_s_p8_0,
  134637. NULL,
  134638. 0
  134639. };
  134640. static long _vq_quantlist__44c8_s_p8_1[] = {
  134641. 10,
  134642. 9,
  134643. 11,
  134644. 8,
  134645. 12,
  134646. 7,
  134647. 13,
  134648. 6,
  134649. 14,
  134650. 5,
  134651. 15,
  134652. 4,
  134653. 16,
  134654. 3,
  134655. 17,
  134656. 2,
  134657. 18,
  134658. 1,
  134659. 19,
  134660. 0,
  134661. 20,
  134662. };
  134663. static long _vq_lengthlist__44c8_s_p8_1[] = {
  134664. 4, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  134665. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  134666. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  134667. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  134668. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134669. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  134670. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  134671. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  134672. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134673. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134674. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  134675. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  134676. 10,10, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9,
  134677. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134678. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  134679. 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,10,10,10,10,
  134680. 10,10,10, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  134681. 9,10,10,10,10,10,10,10, 9,10,10, 9,10,10,10,10,
  134682. 9,10, 9,10,10, 9,10,10,10,10,10,10,10, 9,10,10,
  134683. 10,10,10,10, 9, 9,10,10, 9,10,10,10,10,10,10,10,
  134684. 10,10,10,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9, 9,
  134685. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  134686. 10, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  134687. 10,10,10,10, 9, 9,10, 9, 9, 9,10,10,10,10,10,10,
  134688. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,10,10,
  134689. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10, 9,
  134690. 9,10, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  134691. 10, 9, 9,10,10, 9,10, 9, 9,
  134692. };
  134693. static float _vq_quantthresh__44c8_s_p8_1[] = {
  134694. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  134695. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  134696. 6.5, 7.5, 8.5, 9.5,
  134697. };
  134698. static long _vq_quantmap__44c8_s_p8_1[] = {
  134699. 19, 17, 15, 13, 11, 9, 7, 5,
  134700. 3, 1, 0, 2, 4, 6, 8, 10,
  134701. 12, 14, 16, 18, 20,
  134702. };
  134703. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_1 = {
  134704. _vq_quantthresh__44c8_s_p8_1,
  134705. _vq_quantmap__44c8_s_p8_1,
  134706. 21,
  134707. 21
  134708. };
  134709. static static_codebook _44c8_s_p8_1 = {
  134710. 2, 441,
  134711. _vq_lengthlist__44c8_s_p8_1,
  134712. 1, -529268736, 1611661312, 5, 0,
  134713. _vq_quantlist__44c8_s_p8_1,
  134714. NULL,
  134715. &_vq_auxt__44c8_s_p8_1,
  134716. NULL,
  134717. 0
  134718. };
  134719. static long _vq_quantlist__44c8_s_p9_0[] = {
  134720. 8,
  134721. 7,
  134722. 9,
  134723. 6,
  134724. 10,
  134725. 5,
  134726. 11,
  134727. 4,
  134728. 12,
  134729. 3,
  134730. 13,
  134731. 2,
  134732. 14,
  134733. 1,
  134734. 15,
  134735. 0,
  134736. 16,
  134737. };
  134738. static long _vq_lengthlist__44c8_s_p9_0[] = {
  134739. 1, 4, 3,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134740. 11, 4, 7, 7,11,11,11,11,11,11,11,11,11,11,11,11,
  134741. 11,11, 4, 8,11,11,11,11,11,11,11,11,11,11,11,11,
  134742. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134743. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134744. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134745. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134746. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134747. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134748. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134749. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134750. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134751. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134752. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134753. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134754. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134755. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134756. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134757. 10,
  134758. };
  134759. static float _vq_quantthresh__44c8_s_p9_0[] = {
  134760. -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5,
  134761. 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5, 6982.5,
  134762. };
  134763. static long _vq_quantmap__44c8_s_p9_0[] = {
  134764. 15, 13, 11, 9, 7, 5, 3, 1,
  134765. 0, 2, 4, 6, 8, 10, 12, 14,
  134766. 16,
  134767. };
  134768. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_0 = {
  134769. _vq_quantthresh__44c8_s_p9_0,
  134770. _vq_quantmap__44c8_s_p9_0,
  134771. 17,
  134772. 17
  134773. };
  134774. static static_codebook _44c8_s_p9_0 = {
  134775. 2, 289,
  134776. _vq_lengthlist__44c8_s_p9_0,
  134777. 1, -509798400, 1631393792, 5, 0,
  134778. _vq_quantlist__44c8_s_p9_0,
  134779. NULL,
  134780. &_vq_auxt__44c8_s_p9_0,
  134781. NULL,
  134782. 0
  134783. };
  134784. static long _vq_quantlist__44c8_s_p9_1[] = {
  134785. 9,
  134786. 8,
  134787. 10,
  134788. 7,
  134789. 11,
  134790. 6,
  134791. 12,
  134792. 5,
  134793. 13,
  134794. 4,
  134795. 14,
  134796. 3,
  134797. 15,
  134798. 2,
  134799. 16,
  134800. 1,
  134801. 17,
  134802. 0,
  134803. 18,
  134804. };
  134805. static long _vq_lengthlist__44c8_s_p9_1[] = {
  134806. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,10,10,
  134807. 10,11,11, 6, 6, 6, 8, 8, 9, 8, 8, 7,10, 8,11,10,
  134808. 12,11,12,12,13,13, 5, 5, 6, 8, 8, 9, 9, 8, 8,10,
  134809. 9,11,11,12,12,13,13,13,13,17, 8, 8, 9, 9, 9, 9,
  134810. 9, 9,10, 9,12,10,12,12,13,12,13,13,17, 9, 8, 9,
  134811. 9, 9, 9, 9, 9,10,10,12,12,12,12,13,13,13,13,17,
  134812. 13,13, 9, 9,10,10,10,10,11,11,12,11,13,12,13,13,
  134813. 14,15,17,13,13, 9, 8,10, 9,10,10,11,11,12,12,14,
  134814. 13,15,13,14,15,17,17,17, 9,10, 9,10,11,11,12,12,
  134815. 12,12,13,13,14,14,15,15,17,17,17, 9, 8, 9, 8,11,
  134816. 11,12,12,12,12,14,13,14,14,14,15,17,17,17,12,14,
  134817. 9,10,11,11,12,12,14,13,13,14,15,13,15,15,17,17,
  134818. 17,13,11,10, 8,11, 9,13,12,13,13,13,13,13,14,14,
  134819. 14,17,17,17,17,17,11,12,11,11,13,13,14,13,15,14,
  134820. 13,15,16,15,17,17,17,17,17,11,11,12, 8,13,12,14,
  134821. 13,17,14,15,14,15,14,17,17,17,17,17,15,15,12,12,
  134822. 12,12,13,14,14,14,15,14,17,14,17,17,17,17,17,16,
  134823. 17,12,12,13,12,13,13,14,14,14,14,14,14,17,17,17,
  134824. 17,17,17,17,14,14,13,12,13,13,15,15,14,13,15,17,
  134825. 17,17,17,17,17,17,17,13,14,13,13,13,13,14,15,15,
  134826. 15,14,15,17,17,17,17,17,17,17,16,15,13,14,13,13,
  134827. 14,14,15,14,14,16,17,17,17,17,17,17,17,16,16,13,
  134828. 14,13,13,14,14,15,14,15,14,
  134829. };
  134830. static float _vq_quantthresh__44c8_s_p9_1[] = {
  134831. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  134832. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  134833. 367.5, 416.5,
  134834. };
  134835. static long _vq_quantmap__44c8_s_p9_1[] = {
  134836. 17, 15, 13, 11, 9, 7, 5, 3,
  134837. 1, 0, 2, 4, 6, 8, 10, 12,
  134838. 14, 16, 18,
  134839. };
  134840. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_1 = {
  134841. _vq_quantthresh__44c8_s_p9_1,
  134842. _vq_quantmap__44c8_s_p9_1,
  134843. 19,
  134844. 19
  134845. };
  134846. static static_codebook _44c8_s_p9_1 = {
  134847. 2, 361,
  134848. _vq_lengthlist__44c8_s_p9_1,
  134849. 1, -518287360, 1622704128, 5, 0,
  134850. _vq_quantlist__44c8_s_p9_1,
  134851. NULL,
  134852. &_vq_auxt__44c8_s_p9_1,
  134853. NULL,
  134854. 0
  134855. };
  134856. static long _vq_quantlist__44c8_s_p9_2[] = {
  134857. 24,
  134858. 23,
  134859. 25,
  134860. 22,
  134861. 26,
  134862. 21,
  134863. 27,
  134864. 20,
  134865. 28,
  134866. 19,
  134867. 29,
  134868. 18,
  134869. 30,
  134870. 17,
  134871. 31,
  134872. 16,
  134873. 32,
  134874. 15,
  134875. 33,
  134876. 14,
  134877. 34,
  134878. 13,
  134879. 35,
  134880. 12,
  134881. 36,
  134882. 11,
  134883. 37,
  134884. 10,
  134885. 38,
  134886. 9,
  134887. 39,
  134888. 8,
  134889. 40,
  134890. 7,
  134891. 41,
  134892. 6,
  134893. 42,
  134894. 5,
  134895. 43,
  134896. 4,
  134897. 44,
  134898. 3,
  134899. 45,
  134900. 2,
  134901. 46,
  134902. 1,
  134903. 47,
  134904. 0,
  134905. 48,
  134906. };
  134907. static long _vq_lengthlist__44c8_s_p9_2[] = {
  134908. 2, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  134909. 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134910. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134911. 7,
  134912. };
  134913. static float _vq_quantthresh__44c8_s_p9_2[] = {
  134914. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  134915. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  134916. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134917. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134918. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  134919. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  134920. };
  134921. static long _vq_quantmap__44c8_s_p9_2[] = {
  134922. 47, 45, 43, 41, 39, 37, 35, 33,
  134923. 31, 29, 27, 25, 23, 21, 19, 17,
  134924. 15, 13, 11, 9, 7, 5, 3, 1,
  134925. 0, 2, 4, 6, 8, 10, 12, 14,
  134926. 16, 18, 20, 22, 24, 26, 28, 30,
  134927. 32, 34, 36, 38, 40, 42, 44, 46,
  134928. 48,
  134929. };
  134930. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_2 = {
  134931. _vq_quantthresh__44c8_s_p9_2,
  134932. _vq_quantmap__44c8_s_p9_2,
  134933. 49,
  134934. 49
  134935. };
  134936. static static_codebook _44c8_s_p9_2 = {
  134937. 1, 49,
  134938. _vq_lengthlist__44c8_s_p9_2,
  134939. 1, -526909440, 1611661312, 6, 0,
  134940. _vq_quantlist__44c8_s_p9_2,
  134941. NULL,
  134942. &_vq_auxt__44c8_s_p9_2,
  134943. NULL,
  134944. 0
  134945. };
  134946. static long _huff_lengthlist__44c8_s_short[] = {
  134947. 4,11,13,14,15,15,18,17,19,17, 5, 6, 8, 9,10,10,
  134948. 12,15,19,19, 6, 6, 6, 6, 8, 8,11,14,18,19, 8, 6,
  134949. 5, 4, 6, 7,10,13,16,17, 9, 7, 6, 5, 6, 7, 9,12,
  134950. 15,19,10, 8, 7, 6, 6, 6, 7, 9,13,15,12,10, 9, 8,
  134951. 7, 6, 4, 5,10,15,13,13,11, 8, 6, 6, 4, 2, 7,12,
  134952. 17,15,16,10, 8, 8, 7, 6, 9,12,19,18,17,13,11,10,
  134953. 10, 9,11,14,
  134954. };
  134955. static static_codebook _huff_book__44c8_s_short = {
  134956. 2, 100,
  134957. _huff_lengthlist__44c8_s_short,
  134958. 0, 0, 0, 0, 0,
  134959. NULL,
  134960. NULL,
  134961. NULL,
  134962. NULL,
  134963. 0
  134964. };
  134965. static long _huff_lengthlist__44c9_s_long[] = {
  134966. 3, 8,12,14,15,15,15,13,15,15, 6, 5, 8,10,12,12,
  134967. 13,12,14,13,10, 6, 5, 6, 8, 9,11,11,13,13,13, 8,
  134968. 5, 4, 5, 6, 8,10,11,13,14,10, 7, 5, 4, 5, 7, 9,
  134969. 11,12,13,11, 8, 6, 5, 4, 5, 7, 9,11,12,11,10, 8,
  134970. 7, 5, 4, 5, 9,10,13,13,11,10, 8, 6, 5, 4, 7, 9,
  134971. 15,14,13,12,10, 9, 8, 7, 8, 9,12,12,14,13,12,11,
  134972. 10, 9, 8, 9,
  134973. };
  134974. static static_codebook _huff_book__44c9_s_long = {
  134975. 2, 100,
  134976. _huff_lengthlist__44c9_s_long,
  134977. 0, 0, 0, 0, 0,
  134978. NULL,
  134979. NULL,
  134980. NULL,
  134981. NULL,
  134982. 0
  134983. };
  134984. static long _vq_quantlist__44c9_s_p1_0[] = {
  134985. 1,
  134986. 0,
  134987. 2,
  134988. };
  134989. static long _vq_lengthlist__44c9_s_p1_0[] = {
  134990. 1, 5, 5, 0, 5, 5, 0, 5, 5, 6, 8, 8, 0, 9, 8, 0,
  134991. 9, 8, 6, 8, 8, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  134992. 0, 0, 0, 0, 5, 8, 8, 0, 7, 7, 0, 8, 8, 5, 8, 8,
  134993. 0, 7, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  134994. 9, 8, 0, 8, 8, 0, 7, 7, 5, 8, 9, 0, 8, 8, 0, 7,
  134995. 7,
  134996. };
  134997. static float _vq_quantthresh__44c9_s_p1_0[] = {
  134998. -0.5, 0.5,
  134999. };
  135000. static long _vq_quantmap__44c9_s_p1_0[] = {
  135001. 1, 0, 2,
  135002. };
  135003. static encode_aux_threshmatch _vq_auxt__44c9_s_p1_0 = {
  135004. _vq_quantthresh__44c9_s_p1_0,
  135005. _vq_quantmap__44c9_s_p1_0,
  135006. 3,
  135007. 3
  135008. };
  135009. static static_codebook _44c9_s_p1_0 = {
  135010. 4, 81,
  135011. _vq_lengthlist__44c9_s_p1_0,
  135012. 1, -535822336, 1611661312, 2, 0,
  135013. _vq_quantlist__44c9_s_p1_0,
  135014. NULL,
  135015. &_vq_auxt__44c9_s_p1_0,
  135016. NULL,
  135017. 0
  135018. };
  135019. static long _vq_quantlist__44c9_s_p2_0[] = {
  135020. 2,
  135021. 1,
  135022. 3,
  135023. 0,
  135024. 4,
  135025. };
  135026. static long _vq_lengthlist__44c9_s_p2_0[] = {
  135027. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  135028. 7, 7, 9, 9, 0, 0, 0, 9, 9, 6, 7, 7, 9, 8, 0, 8,
  135029. 8, 9, 9, 0, 8, 7, 9, 9, 0, 9,10,10,10, 0, 0, 0,
  135030. 11,10, 6, 7, 7, 8, 9, 0, 8, 8, 9, 9, 0, 7, 8, 9,
  135031. 9, 0,10, 9,11,10, 0, 0, 0,10,10, 8, 9, 8,10,10,
  135032. 0,10,10,12,11, 0,10,10,11,11, 0,12,13,13,13, 0,
  135033. 0, 0,13,12, 8, 8, 9,10,10, 0,10,10,11,12, 0,10,
  135034. 10,11,11, 0,13,12,13,13, 0, 0, 0,13,13, 0, 0, 0,
  135035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135036. 0, 0, 0, 0, 0, 0, 6, 8, 7,10,10, 0, 7, 7,10, 9,
  135037. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,10,10, 6,
  135038. 7, 8,10,10, 0, 7, 7, 9,10, 0, 7, 7,10,10, 0, 9,
  135039. 9,10,10, 0, 0, 0,10,10, 8, 9, 9,11,11, 0,10,10,
  135040. 11,11, 0,10,10,11,11, 0,12,12,12,12, 0, 0, 0,12,
  135041. 12, 8, 9,10,11,11, 0, 9,10,11,11, 0,10,10,11,11,
  135042. 0,12,12,12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0,
  135043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135044. 0, 0, 0, 5, 8, 7,10,10, 0, 7, 7,10,10, 0, 7, 7,
  135045. 10, 9, 0, 9, 9,10,10, 0, 0, 0,10,10, 6, 7, 8,10,
  135046. 10, 0, 7, 7,10,10, 0, 7, 7, 9,10, 0, 9, 9,10,10,
  135047. 0, 0, 0,10,10, 8,10, 9,12,11, 0,10,10,12,11, 0,
  135048. 10, 9,11,11, 0,11,12,12,12, 0, 0, 0,12,12, 8, 9,
  135049. 10,11,12, 0,10,10,11,11, 0, 9,10,11,11, 0,12,11,
  135050. 12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135052. 7,10, 9,12,12, 0, 9, 9,12,11, 0, 9, 9,11,11, 0,
  135053. 10,10,12,11, 0, 0, 0,11,12, 7, 9,10,12,12, 0, 9,
  135054. 9,11,12, 0, 9, 9,11,11, 0,10,10,11,12, 0, 0, 0,
  135055. 11,11, 9,11,10,13,12, 0,10,10,12,12, 0,10,10,12,
  135056. 12, 0,11,11,12,12, 0, 0, 0,13,12, 9,10,11,12,13,
  135057. 0,10,10,12,12, 0,10,10,12,12, 0,11,12,12,12, 0,
  135058. 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  135063. 11,10,13,13, 0,10,10,12,12, 0,10,10,12,12, 0,11,
  135064. 12,12,12, 0, 0, 0,12,12, 9,10,11,13,13, 0,10,10,
  135065. 12,12, 0,10,10,12,12, 0,12,11,13,12, 0, 0, 0,12,
  135066. 12,
  135067. };
  135068. static float _vq_quantthresh__44c9_s_p2_0[] = {
  135069. -1.5, -0.5, 0.5, 1.5,
  135070. };
  135071. static long _vq_quantmap__44c9_s_p2_0[] = {
  135072. 3, 1, 0, 2, 4,
  135073. };
  135074. static encode_aux_threshmatch _vq_auxt__44c9_s_p2_0 = {
  135075. _vq_quantthresh__44c9_s_p2_0,
  135076. _vq_quantmap__44c9_s_p2_0,
  135077. 5,
  135078. 5
  135079. };
  135080. static static_codebook _44c9_s_p2_0 = {
  135081. 4, 625,
  135082. _vq_lengthlist__44c9_s_p2_0,
  135083. 1, -533725184, 1611661312, 3, 0,
  135084. _vq_quantlist__44c9_s_p2_0,
  135085. NULL,
  135086. &_vq_auxt__44c9_s_p2_0,
  135087. NULL,
  135088. 0
  135089. };
  135090. static long _vq_quantlist__44c9_s_p3_0[] = {
  135091. 4,
  135092. 3,
  135093. 5,
  135094. 2,
  135095. 6,
  135096. 1,
  135097. 7,
  135098. 0,
  135099. 8,
  135100. };
  135101. static long _vq_lengthlist__44c9_s_p3_0[] = {
  135102. 3, 4, 4, 5, 5, 6, 6, 8, 8, 0, 4, 4, 5, 5, 6, 7,
  135103. 8, 8, 0, 4, 4, 5, 5, 7, 7, 8, 8, 0, 5, 5, 6, 6,
  135104. 7, 7, 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0,
  135105. 7, 7, 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0,
  135106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135107. 0,
  135108. };
  135109. static float _vq_quantthresh__44c9_s_p3_0[] = {
  135110. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  135111. };
  135112. static long _vq_quantmap__44c9_s_p3_0[] = {
  135113. 7, 5, 3, 1, 0, 2, 4, 6,
  135114. 8,
  135115. };
  135116. static encode_aux_threshmatch _vq_auxt__44c9_s_p3_0 = {
  135117. _vq_quantthresh__44c9_s_p3_0,
  135118. _vq_quantmap__44c9_s_p3_0,
  135119. 9,
  135120. 9
  135121. };
  135122. static static_codebook _44c9_s_p3_0 = {
  135123. 2, 81,
  135124. _vq_lengthlist__44c9_s_p3_0,
  135125. 1, -531628032, 1611661312, 4, 0,
  135126. _vq_quantlist__44c9_s_p3_0,
  135127. NULL,
  135128. &_vq_auxt__44c9_s_p3_0,
  135129. NULL,
  135130. 0
  135131. };
  135132. static long _vq_quantlist__44c9_s_p4_0[] = {
  135133. 8,
  135134. 7,
  135135. 9,
  135136. 6,
  135137. 10,
  135138. 5,
  135139. 11,
  135140. 4,
  135141. 12,
  135142. 3,
  135143. 13,
  135144. 2,
  135145. 14,
  135146. 1,
  135147. 15,
  135148. 0,
  135149. 16,
  135150. };
  135151. static long _vq_lengthlist__44c9_s_p4_0[] = {
  135152. 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,10,
  135153. 10, 0, 5, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  135154. 11,11, 0, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  135155. 10,11,11, 0, 6, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,
  135156. 11,11,11,12, 0, 0, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,
  135157. 10,11,11,12,12, 0, 0, 0, 7, 7, 7, 7, 9, 9, 9, 9,
  135158. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 7, 8, 9, 9, 9,
  135159. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  135160. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  135161. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  135162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135170. 0,
  135171. };
  135172. static float _vq_quantthresh__44c9_s_p4_0[] = {
  135173. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135174. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135175. };
  135176. static long _vq_quantmap__44c9_s_p4_0[] = {
  135177. 15, 13, 11, 9, 7, 5, 3, 1,
  135178. 0, 2, 4, 6, 8, 10, 12, 14,
  135179. 16,
  135180. };
  135181. static encode_aux_threshmatch _vq_auxt__44c9_s_p4_0 = {
  135182. _vq_quantthresh__44c9_s_p4_0,
  135183. _vq_quantmap__44c9_s_p4_0,
  135184. 17,
  135185. 17
  135186. };
  135187. static static_codebook _44c9_s_p4_0 = {
  135188. 2, 289,
  135189. _vq_lengthlist__44c9_s_p4_0,
  135190. 1, -529530880, 1611661312, 5, 0,
  135191. _vq_quantlist__44c9_s_p4_0,
  135192. NULL,
  135193. &_vq_auxt__44c9_s_p4_0,
  135194. NULL,
  135195. 0
  135196. };
  135197. static long _vq_quantlist__44c9_s_p5_0[] = {
  135198. 1,
  135199. 0,
  135200. 2,
  135201. };
  135202. static long _vq_lengthlist__44c9_s_p5_0[] = {
  135203. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6, 9,10,10,10,
  135204. 10, 9, 4, 6, 7, 9,10,10,10, 9,10, 5, 9, 9, 9,11,
  135205. 11,10,11,11, 7,10, 9,11,12,11,12,12,12, 7, 9,10,
  135206. 11,11,12,12,12,12, 6,10,10,10,12,12,10,12,11, 7,
  135207. 10,10,11,12,12,11,12,12, 7,10,10,11,12,12,12,12,
  135208. 12,
  135209. };
  135210. static float _vq_quantthresh__44c9_s_p5_0[] = {
  135211. -5.5, 5.5,
  135212. };
  135213. static long _vq_quantmap__44c9_s_p5_0[] = {
  135214. 1, 0, 2,
  135215. };
  135216. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_0 = {
  135217. _vq_quantthresh__44c9_s_p5_0,
  135218. _vq_quantmap__44c9_s_p5_0,
  135219. 3,
  135220. 3
  135221. };
  135222. static static_codebook _44c9_s_p5_0 = {
  135223. 4, 81,
  135224. _vq_lengthlist__44c9_s_p5_0,
  135225. 1, -529137664, 1618345984, 2, 0,
  135226. _vq_quantlist__44c9_s_p5_0,
  135227. NULL,
  135228. &_vq_auxt__44c9_s_p5_0,
  135229. NULL,
  135230. 0
  135231. };
  135232. static long _vq_quantlist__44c9_s_p5_1[] = {
  135233. 5,
  135234. 4,
  135235. 6,
  135236. 3,
  135237. 7,
  135238. 2,
  135239. 8,
  135240. 1,
  135241. 9,
  135242. 0,
  135243. 10,
  135244. };
  135245. static long _vq_lengthlist__44c9_s_p5_1[] = {
  135246. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7,11, 5, 5, 6, 6,
  135247. 7, 7, 7, 7, 8, 8,11, 5, 5, 6, 6, 7, 7, 7, 7, 8,
  135248. 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11, 6,
  135249. 6, 7, 7, 7, 8, 8, 8,11,11,11, 6, 6, 7, 7, 7, 8,
  135250. 8, 8,11,11,11, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11,
  135251. 7, 7, 7, 7, 7, 7, 8, 8,11,11,11,10,10, 7, 7, 7,
  135252. 7, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 7, 7,11,11,
  135253. 11,11,11, 7, 7, 7, 7, 7, 7,
  135254. };
  135255. static float _vq_quantthresh__44c9_s_p5_1[] = {
  135256. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135257. 3.5, 4.5,
  135258. };
  135259. static long _vq_quantmap__44c9_s_p5_1[] = {
  135260. 9, 7, 5, 3, 1, 0, 2, 4,
  135261. 6, 8, 10,
  135262. };
  135263. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_1 = {
  135264. _vq_quantthresh__44c9_s_p5_1,
  135265. _vq_quantmap__44c9_s_p5_1,
  135266. 11,
  135267. 11
  135268. };
  135269. static static_codebook _44c9_s_p5_1 = {
  135270. 2, 121,
  135271. _vq_lengthlist__44c9_s_p5_1,
  135272. 1, -531365888, 1611661312, 4, 0,
  135273. _vq_quantlist__44c9_s_p5_1,
  135274. NULL,
  135275. &_vq_auxt__44c9_s_p5_1,
  135276. NULL,
  135277. 0
  135278. };
  135279. static long _vq_quantlist__44c9_s_p6_0[] = {
  135280. 6,
  135281. 5,
  135282. 7,
  135283. 4,
  135284. 8,
  135285. 3,
  135286. 9,
  135287. 2,
  135288. 10,
  135289. 1,
  135290. 11,
  135291. 0,
  135292. 12,
  135293. };
  135294. static long _vq_lengthlist__44c9_s_p6_0[] = {
  135295. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 5, 4, 4,
  135296. 6, 6, 8, 8, 9, 9, 9, 9,10,10, 6, 4, 4, 6, 6, 8,
  135297. 8, 9, 9, 9, 9,10,10, 0, 6, 6, 7, 7, 8, 8, 9, 9,
  135298. 10,10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  135299. 11, 0,10,10, 8, 8, 9, 9,10,10,11,11,12,12, 0,11,
  135300. 11, 8, 8, 9, 9,10,10,11,11,12,12, 0, 0, 0, 0, 0,
  135301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135305. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135306. };
  135307. static float _vq_quantthresh__44c9_s_p6_0[] = {
  135308. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  135309. 12.5, 17.5, 22.5, 27.5,
  135310. };
  135311. static long _vq_quantmap__44c9_s_p6_0[] = {
  135312. 11, 9, 7, 5, 3, 1, 0, 2,
  135313. 4, 6, 8, 10, 12,
  135314. };
  135315. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_0 = {
  135316. _vq_quantthresh__44c9_s_p6_0,
  135317. _vq_quantmap__44c9_s_p6_0,
  135318. 13,
  135319. 13
  135320. };
  135321. static static_codebook _44c9_s_p6_0 = {
  135322. 2, 169,
  135323. _vq_lengthlist__44c9_s_p6_0,
  135324. 1, -526516224, 1616117760, 4, 0,
  135325. _vq_quantlist__44c9_s_p6_0,
  135326. NULL,
  135327. &_vq_auxt__44c9_s_p6_0,
  135328. NULL,
  135329. 0
  135330. };
  135331. static long _vq_quantlist__44c9_s_p6_1[] = {
  135332. 2,
  135333. 1,
  135334. 3,
  135335. 0,
  135336. 4,
  135337. };
  135338. static long _vq_lengthlist__44c9_s_p6_1[] = {
  135339. 4, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5,
  135340. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  135341. };
  135342. static float _vq_quantthresh__44c9_s_p6_1[] = {
  135343. -1.5, -0.5, 0.5, 1.5,
  135344. };
  135345. static long _vq_quantmap__44c9_s_p6_1[] = {
  135346. 3, 1, 0, 2, 4,
  135347. };
  135348. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_1 = {
  135349. _vq_quantthresh__44c9_s_p6_1,
  135350. _vq_quantmap__44c9_s_p6_1,
  135351. 5,
  135352. 5
  135353. };
  135354. static static_codebook _44c9_s_p6_1 = {
  135355. 2, 25,
  135356. _vq_lengthlist__44c9_s_p6_1,
  135357. 1, -533725184, 1611661312, 3, 0,
  135358. _vq_quantlist__44c9_s_p6_1,
  135359. NULL,
  135360. &_vq_auxt__44c9_s_p6_1,
  135361. NULL,
  135362. 0
  135363. };
  135364. static long _vq_quantlist__44c9_s_p7_0[] = {
  135365. 6,
  135366. 5,
  135367. 7,
  135368. 4,
  135369. 8,
  135370. 3,
  135371. 9,
  135372. 2,
  135373. 10,
  135374. 1,
  135375. 11,
  135376. 0,
  135377. 12,
  135378. };
  135379. static long _vq_lengthlist__44c9_s_p7_0[] = {
  135380. 2, 4, 4, 6, 6, 7, 7, 8, 8,10,10,11,11, 6, 4, 4,
  135381. 6, 6, 8, 8, 9, 9,10,10,12,12, 6, 4, 5, 6, 6, 8,
  135382. 8, 9, 9,10,10,12,12,20, 6, 6, 6, 6, 8, 8, 9,10,
  135383. 11,11,12,12,20, 6, 6, 6, 6, 8, 8,10,10,11,11,12,
  135384. 12,20,10,10, 7, 7, 9, 9,10,10,11,11,12,12,20,11,
  135385. 11, 7, 7, 9, 9,10,10,11,11,12,12,20,20,20, 9, 9,
  135386. 9, 9,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,11,
  135387. 11,12,12,13,13,20,20,20,13,13,10,10,11,11,12,13,
  135388. 13,13,20,20,20,13,13,10,10,11,11,12,13,13,13,20,
  135389. 20,20,20,19,12,12,12,12,13,13,14,15,19,19,19,19,
  135390. 19,12,12,12,12,13,13,14,14,
  135391. };
  135392. static float _vq_quantthresh__44c9_s_p7_0[] = {
  135393. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  135394. 27.5, 38.5, 49.5, 60.5,
  135395. };
  135396. static long _vq_quantmap__44c9_s_p7_0[] = {
  135397. 11, 9, 7, 5, 3, 1, 0, 2,
  135398. 4, 6, 8, 10, 12,
  135399. };
  135400. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_0 = {
  135401. _vq_quantthresh__44c9_s_p7_0,
  135402. _vq_quantmap__44c9_s_p7_0,
  135403. 13,
  135404. 13
  135405. };
  135406. static static_codebook _44c9_s_p7_0 = {
  135407. 2, 169,
  135408. _vq_lengthlist__44c9_s_p7_0,
  135409. 1, -523206656, 1618345984, 4, 0,
  135410. _vq_quantlist__44c9_s_p7_0,
  135411. NULL,
  135412. &_vq_auxt__44c9_s_p7_0,
  135413. NULL,
  135414. 0
  135415. };
  135416. static long _vq_quantlist__44c9_s_p7_1[] = {
  135417. 5,
  135418. 4,
  135419. 6,
  135420. 3,
  135421. 7,
  135422. 2,
  135423. 8,
  135424. 1,
  135425. 9,
  135426. 0,
  135427. 10,
  135428. };
  135429. static long _vq_lengthlist__44c9_s_p7_1[] = {
  135430. 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6,
  135431. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  135432. 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 6,
  135433. 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  135434. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  135435. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  135436. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  135437. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  135438. };
  135439. static float _vq_quantthresh__44c9_s_p7_1[] = {
  135440. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135441. 3.5, 4.5,
  135442. };
  135443. static long _vq_quantmap__44c9_s_p7_1[] = {
  135444. 9, 7, 5, 3, 1, 0, 2, 4,
  135445. 6, 8, 10,
  135446. };
  135447. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_1 = {
  135448. _vq_quantthresh__44c9_s_p7_1,
  135449. _vq_quantmap__44c9_s_p7_1,
  135450. 11,
  135451. 11
  135452. };
  135453. static static_codebook _44c9_s_p7_1 = {
  135454. 2, 121,
  135455. _vq_lengthlist__44c9_s_p7_1,
  135456. 1, -531365888, 1611661312, 4, 0,
  135457. _vq_quantlist__44c9_s_p7_1,
  135458. NULL,
  135459. &_vq_auxt__44c9_s_p7_1,
  135460. NULL,
  135461. 0
  135462. };
  135463. static long _vq_quantlist__44c9_s_p8_0[] = {
  135464. 7,
  135465. 6,
  135466. 8,
  135467. 5,
  135468. 9,
  135469. 4,
  135470. 10,
  135471. 3,
  135472. 11,
  135473. 2,
  135474. 12,
  135475. 1,
  135476. 13,
  135477. 0,
  135478. 14,
  135479. };
  135480. static long _vq_lengthlist__44c9_s_p8_0[] = {
  135481. 1, 4, 4, 7, 6, 8, 8, 8, 8, 9, 9,10,10,11,10, 6,
  135482. 5, 5, 7, 7, 9, 9, 8, 9,10,10,11,11,12,12, 6, 5,
  135483. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,21, 7, 8,
  135484. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,21, 8, 8, 8,
  135485. 8, 9, 9, 9, 9,10,10,11,11,12,12,21,11,12, 9, 9,
  135486. 10,10,10,10,10,11,11,12,12,12,21,12,12, 9, 8,10,
  135487. 10,10,10,11,11,12,12,13,13,21,21,21, 9, 9, 9, 9,
  135488. 11,11,11,11,12,12,12,13,21,20,20, 9, 9, 9, 9,10,
  135489. 11,11,11,12,12,13,13,20,20,20,13,13,10,10,11,11,
  135490. 12,12,13,13,13,13,20,20,20,13,13,10,10,11,11,12,
  135491. 12,13,13,13,13,20,20,20,20,20,12,12,12,12,12,12,
  135492. 13,13,14,14,20,20,20,20,20,12,12,12,11,13,12,13,
  135493. 13,14,14,20,20,20,20,20,15,16,13,12,13,13,14,13,
  135494. 14,14,20,20,20,20,20,16,15,12,12,13,12,14,13,14,
  135495. 14,
  135496. };
  135497. static float _vq_quantthresh__44c9_s_p8_0[] = {
  135498. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  135499. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  135500. };
  135501. static long _vq_quantmap__44c9_s_p8_0[] = {
  135502. 13, 11, 9, 7, 5, 3, 1, 0,
  135503. 2, 4, 6, 8, 10, 12, 14,
  135504. };
  135505. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_0 = {
  135506. _vq_quantthresh__44c9_s_p8_0,
  135507. _vq_quantmap__44c9_s_p8_0,
  135508. 15,
  135509. 15
  135510. };
  135511. static static_codebook _44c9_s_p8_0 = {
  135512. 2, 225,
  135513. _vq_lengthlist__44c9_s_p8_0,
  135514. 1, -520986624, 1620377600, 4, 0,
  135515. _vq_quantlist__44c9_s_p8_0,
  135516. NULL,
  135517. &_vq_auxt__44c9_s_p8_0,
  135518. NULL,
  135519. 0
  135520. };
  135521. static long _vq_quantlist__44c9_s_p8_1[] = {
  135522. 10,
  135523. 9,
  135524. 11,
  135525. 8,
  135526. 12,
  135527. 7,
  135528. 13,
  135529. 6,
  135530. 14,
  135531. 5,
  135532. 15,
  135533. 4,
  135534. 16,
  135535. 3,
  135536. 17,
  135537. 2,
  135538. 18,
  135539. 1,
  135540. 19,
  135541. 0,
  135542. 20,
  135543. };
  135544. static long _vq_lengthlist__44c9_s_p8_1[] = {
  135545. 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  135546. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  135547. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  135548. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  135549. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135550. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  135551. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8,
  135552. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  135553. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135554. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135555. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  135556. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  135557. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135558. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135559. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  135560. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,
  135561. 10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,
  135562. 9,10,10,10,10,10,10,10, 9, 9, 9,10,10,10,10,10,
  135563. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10, 9, 9,10,
  135564. 9,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  135565. 10,10,10,10, 9, 9,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  135566. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  135567. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  135568. 10,10, 9, 9,10, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  135569. 10,10,10,10,10, 9, 9,10,10, 9, 9,10, 9, 9, 9,10,
  135570. 10,10,10,10,10,10,10,10,10,10, 9, 9,10, 9, 9, 9,
  135571. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9,
  135572. 9, 9, 9,10, 9, 9, 9, 9, 9,
  135573. };
  135574. static float _vq_quantthresh__44c9_s_p8_1[] = {
  135575. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  135576. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  135577. 6.5, 7.5, 8.5, 9.5,
  135578. };
  135579. static long _vq_quantmap__44c9_s_p8_1[] = {
  135580. 19, 17, 15, 13, 11, 9, 7, 5,
  135581. 3, 1, 0, 2, 4, 6, 8, 10,
  135582. 12, 14, 16, 18, 20,
  135583. };
  135584. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_1 = {
  135585. _vq_quantthresh__44c9_s_p8_1,
  135586. _vq_quantmap__44c9_s_p8_1,
  135587. 21,
  135588. 21
  135589. };
  135590. static static_codebook _44c9_s_p8_1 = {
  135591. 2, 441,
  135592. _vq_lengthlist__44c9_s_p8_1,
  135593. 1, -529268736, 1611661312, 5, 0,
  135594. _vq_quantlist__44c9_s_p8_1,
  135595. NULL,
  135596. &_vq_auxt__44c9_s_p8_1,
  135597. NULL,
  135598. 0
  135599. };
  135600. static long _vq_quantlist__44c9_s_p9_0[] = {
  135601. 9,
  135602. 8,
  135603. 10,
  135604. 7,
  135605. 11,
  135606. 6,
  135607. 12,
  135608. 5,
  135609. 13,
  135610. 4,
  135611. 14,
  135612. 3,
  135613. 15,
  135614. 2,
  135615. 16,
  135616. 1,
  135617. 17,
  135618. 0,
  135619. 18,
  135620. };
  135621. static long _vq_lengthlist__44c9_s_p9_0[] = {
  135622. 1, 4, 3,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135623. 12,12,12, 4, 5, 6,12,12,12,12,12,12,12,12,12,12,
  135624. 12,12,12,12,12,12, 4, 6, 6,12,12,12,12,12,12,12,
  135625. 12,12,12,12,12,12,12,12,12,12,12,11,12,12,12,12,
  135626. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135627. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135628. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135629. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135630. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135631. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135632. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135633. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135634. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135635. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135636. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135637. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135638. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  135639. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135640. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135641. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135642. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135643. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135644. 11,11,11,11,11,11,11,11,11,
  135645. };
  135646. static float _vq_quantthresh__44c9_s_p9_0[] = {
  135647. -7913.5, -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5,
  135648. -465.5, 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  135649. 6982.5, 7913.5,
  135650. };
  135651. static long _vq_quantmap__44c9_s_p9_0[] = {
  135652. 17, 15, 13, 11, 9, 7, 5, 3,
  135653. 1, 0, 2, 4, 6, 8, 10, 12,
  135654. 14, 16, 18,
  135655. };
  135656. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_0 = {
  135657. _vq_quantthresh__44c9_s_p9_0,
  135658. _vq_quantmap__44c9_s_p9_0,
  135659. 19,
  135660. 19
  135661. };
  135662. static static_codebook _44c9_s_p9_0 = {
  135663. 2, 361,
  135664. _vq_lengthlist__44c9_s_p9_0,
  135665. 1, -508535424, 1631393792, 5, 0,
  135666. _vq_quantlist__44c9_s_p9_0,
  135667. NULL,
  135668. &_vq_auxt__44c9_s_p9_0,
  135669. NULL,
  135670. 0
  135671. };
  135672. static long _vq_quantlist__44c9_s_p9_1[] = {
  135673. 9,
  135674. 8,
  135675. 10,
  135676. 7,
  135677. 11,
  135678. 6,
  135679. 12,
  135680. 5,
  135681. 13,
  135682. 4,
  135683. 14,
  135684. 3,
  135685. 15,
  135686. 2,
  135687. 16,
  135688. 1,
  135689. 17,
  135690. 0,
  135691. 18,
  135692. };
  135693. static long _vq_lengthlist__44c9_s_p9_1[] = {
  135694. 1, 4, 4, 7, 7, 7, 7, 8, 7, 9, 8, 9, 9,10,10,11,
  135695. 11,11,11, 6, 5, 5, 8, 8, 9, 9, 9, 8,10, 9,11,10,
  135696. 12,12,13,12,13,13, 5, 5, 5, 8, 8, 9, 9, 9, 9,10,
  135697. 10,11,11,12,12,13,12,13,13,17, 8, 8, 9, 9, 9, 9,
  135698. 9, 9,10,10,12,11,13,12,13,13,13,13,18, 8, 8, 9,
  135699. 9, 9, 9, 9, 9,11,11,12,12,13,13,13,13,13,13,17,
  135700. 13,12, 9, 9,10,10,10,10,11,11,12,12,12,13,13,13,
  135701. 14,14,18,13,12, 9, 9,10,10,10,10,11,11,12,12,13,
  135702. 13,13,14,14,14,17,18,18,10,10,10,10,11,11,11,12,
  135703. 12,12,14,13,14,13,13,14,18,18,18,10, 9,10, 9,11,
  135704. 11,12,12,12,12,13,13,15,14,14,14,18,18,16,13,14,
  135705. 10,11,11,11,12,13,13,13,13,14,13,13,14,14,18,18,
  135706. 18,14,12,11, 9,11,10,13,12,13,13,13,14,14,14,13,
  135707. 14,18,18,17,18,18,11,12,12,12,13,13,14,13,14,14,
  135708. 13,14,14,14,18,18,18,18,17,12,10,12, 9,13,11,13,
  135709. 14,14,14,14,14,15,14,18,18,17,17,18,14,15,12,13,
  135710. 13,13,14,13,14,14,15,14,15,14,18,17,18,18,18,15,
  135711. 15,12,10,14,10,14,14,13,13,14,14,14,14,18,16,18,
  135712. 18,18,18,17,14,14,13,14,14,13,13,14,14,14,15,15,
  135713. 18,18,18,18,17,17,17,14,14,14,12,14,13,14,14,15,
  135714. 14,15,14,18,18,18,18,18,18,18,17,16,13,13,13,14,
  135715. 14,14,14,15,16,15,18,18,18,18,18,18,18,17,17,13,
  135716. 13,13,13,14,13,14,15,15,15,
  135717. };
  135718. static float _vq_quantthresh__44c9_s_p9_1[] = {
  135719. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  135720. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  135721. 367.5, 416.5,
  135722. };
  135723. static long _vq_quantmap__44c9_s_p9_1[] = {
  135724. 17, 15, 13, 11, 9, 7, 5, 3,
  135725. 1, 0, 2, 4, 6, 8, 10, 12,
  135726. 14, 16, 18,
  135727. };
  135728. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_1 = {
  135729. _vq_quantthresh__44c9_s_p9_1,
  135730. _vq_quantmap__44c9_s_p9_1,
  135731. 19,
  135732. 19
  135733. };
  135734. static static_codebook _44c9_s_p9_1 = {
  135735. 2, 361,
  135736. _vq_lengthlist__44c9_s_p9_1,
  135737. 1, -518287360, 1622704128, 5, 0,
  135738. _vq_quantlist__44c9_s_p9_1,
  135739. NULL,
  135740. &_vq_auxt__44c9_s_p9_1,
  135741. NULL,
  135742. 0
  135743. };
  135744. static long _vq_quantlist__44c9_s_p9_2[] = {
  135745. 24,
  135746. 23,
  135747. 25,
  135748. 22,
  135749. 26,
  135750. 21,
  135751. 27,
  135752. 20,
  135753. 28,
  135754. 19,
  135755. 29,
  135756. 18,
  135757. 30,
  135758. 17,
  135759. 31,
  135760. 16,
  135761. 32,
  135762. 15,
  135763. 33,
  135764. 14,
  135765. 34,
  135766. 13,
  135767. 35,
  135768. 12,
  135769. 36,
  135770. 11,
  135771. 37,
  135772. 10,
  135773. 38,
  135774. 9,
  135775. 39,
  135776. 8,
  135777. 40,
  135778. 7,
  135779. 41,
  135780. 6,
  135781. 42,
  135782. 5,
  135783. 43,
  135784. 4,
  135785. 44,
  135786. 3,
  135787. 45,
  135788. 2,
  135789. 46,
  135790. 1,
  135791. 47,
  135792. 0,
  135793. 48,
  135794. };
  135795. static long _vq_lengthlist__44c9_s_p9_2[] = {
  135796. 2, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  135797. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  135798. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  135799. 7,
  135800. };
  135801. static float _vq_quantthresh__44c9_s_p9_2[] = {
  135802. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  135803. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  135804. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135805. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135806. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  135807. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  135808. };
  135809. static long _vq_quantmap__44c9_s_p9_2[] = {
  135810. 47, 45, 43, 41, 39, 37, 35, 33,
  135811. 31, 29, 27, 25, 23, 21, 19, 17,
  135812. 15, 13, 11, 9, 7, 5, 3, 1,
  135813. 0, 2, 4, 6, 8, 10, 12, 14,
  135814. 16, 18, 20, 22, 24, 26, 28, 30,
  135815. 32, 34, 36, 38, 40, 42, 44, 46,
  135816. 48,
  135817. };
  135818. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_2 = {
  135819. _vq_quantthresh__44c9_s_p9_2,
  135820. _vq_quantmap__44c9_s_p9_2,
  135821. 49,
  135822. 49
  135823. };
  135824. static static_codebook _44c9_s_p9_2 = {
  135825. 1, 49,
  135826. _vq_lengthlist__44c9_s_p9_2,
  135827. 1, -526909440, 1611661312, 6, 0,
  135828. _vq_quantlist__44c9_s_p9_2,
  135829. NULL,
  135830. &_vq_auxt__44c9_s_p9_2,
  135831. NULL,
  135832. 0
  135833. };
  135834. static long _huff_lengthlist__44c9_s_short[] = {
  135835. 5,13,18,16,17,17,19,18,19,19, 5, 7,10,11,12,12,
  135836. 13,16,17,18, 6, 6, 7, 7, 9, 9,10,14,17,19, 8, 7,
  135837. 6, 5, 6, 7, 9,12,19,17, 8, 7, 7, 6, 5, 6, 8,11,
  135838. 15,19, 9, 8, 7, 6, 5, 5, 6, 8,13,15,11,10, 8, 8,
  135839. 7, 5, 4, 4,10,14,12,13,11, 9, 7, 6, 4, 2, 6,12,
  135840. 18,16,16,13, 8, 7, 7, 5, 8,13,16,17,18,15,11, 9,
  135841. 9, 8,10,13,
  135842. };
  135843. static static_codebook _huff_book__44c9_s_short = {
  135844. 2, 100,
  135845. _huff_lengthlist__44c9_s_short,
  135846. 0, 0, 0, 0, 0,
  135847. NULL,
  135848. NULL,
  135849. NULL,
  135850. NULL,
  135851. 0
  135852. };
  135853. static long _huff_lengthlist__44c0_s_long[] = {
  135854. 5, 4, 8, 9, 8, 9,10,12,15, 4, 1, 5, 5, 6, 8,11,
  135855. 12,12, 8, 5, 8, 9, 9,11,13,12,12, 9, 5, 8, 5, 7,
  135856. 9,12,13,13, 8, 6, 8, 7, 7, 9,11,11,11, 9, 7, 9,
  135857. 7, 7, 7, 7,10,12,10,10,11, 9, 8, 7, 7, 9,11,11,
  135858. 12,13,12,11, 9, 8, 9,11,13,16,16,15,15,12,10,11,
  135859. 12,
  135860. };
  135861. static static_codebook _huff_book__44c0_s_long = {
  135862. 2, 81,
  135863. _huff_lengthlist__44c0_s_long,
  135864. 0, 0, 0, 0, 0,
  135865. NULL,
  135866. NULL,
  135867. NULL,
  135868. NULL,
  135869. 0
  135870. };
  135871. static long _vq_quantlist__44c0_s_p1_0[] = {
  135872. 1,
  135873. 0,
  135874. 2,
  135875. };
  135876. static long _vq_lengthlist__44c0_s_p1_0[] = {
  135877. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  135878. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135882. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  135883. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135887. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135888. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 7, 0, 0, 0, 0,
  135923. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  135928. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  135929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135933. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  135934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135969. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  135974. 0, 0, 0, 0, 0, 9, 9,11, 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, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,11,
  135979. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  135980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136287. 0,
  136288. };
  136289. static float _vq_quantthresh__44c0_s_p1_0[] = {
  136290. -0.5, 0.5,
  136291. };
  136292. static long _vq_quantmap__44c0_s_p1_0[] = {
  136293. 1, 0, 2,
  136294. };
  136295. static encode_aux_threshmatch _vq_auxt__44c0_s_p1_0 = {
  136296. _vq_quantthresh__44c0_s_p1_0,
  136297. _vq_quantmap__44c0_s_p1_0,
  136298. 3,
  136299. 3
  136300. };
  136301. static static_codebook _44c0_s_p1_0 = {
  136302. 8, 6561,
  136303. _vq_lengthlist__44c0_s_p1_0,
  136304. 1, -535822336, 1611661312, 2, 0,
  136305. _vq_quantlist__44c0_s_p1_0,
  136306. NULL,
  136307. &_vq_auxt__44c0_s_p1_0,
  136308. NULL,
  136309. 0
  136310. };
  136311. static long _vq_quantlist__44c0_s_p2_0[] = {
  136312. 2,
  136313. 1,
  136314. 3,
  136315. 0,
  136316. 4,
  136317. };
  136318. static long _vq_lengthlist__44c0_s_p2_0[] = {
  136319. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 6, 0, 0,
  136321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136322. 0, 0, 4, 5, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  136324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136325. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  136326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136358. 0,
  136359. };
  136360. static float _vq_quantthresh__44c0_s_p2_0[] = {
  136361. -1.5, -0.5, 0.5, 1.5,
  136362. };
  136363. static long _vq_quantmap__44c0_s_p2_0[] = {
  136364. 3, 1, 0, 2, 4,
  136365. };
  136366. static encode_aux_threshmatch _vq_auxt__44c0_s_p2_0 = {
  136367. _vq_quantthresh__44c0_s_p2_0,
  136368. _vq_quantmap__44c0_s_p2_0,
  136369. 5,
  136370. 5
  136371. };
  136372. static static_codebook _44c0_s_p2_0 = {
  136373. 4, 625,
  136374. _vq_lengthlist__44c0_s_p2_0,
  136375. 1, -533725184, 1611661312, 3, 0,
  136376. _vq_quantlist__44c0_s_p2_0,
  136377. NULL,
  136378. &_vq_auxt__44c0_s_p2_0,
  136379. NULL,
  136380. 0
  136381. };
  136382. static long _vq_quantlist__44c0_s_p3_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_p3_0[] = {
  136394. 1, 3, 2, 8, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  136395. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  136396. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  136397. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  136398. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136399. 0,
  136400. };
  136401. static float _vq_quantthresh__44c0_s_p3_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_p3_0[] = {
  136405. 7, 5, 3, 1, 0, 2, 4, 6,
  136406. 8,
  136407. };
  136408. static encode_aux_threshmatch _vq_auxt__44c0_s_p3_0 = {
  136409. _vq_quantthresh__44c0_s_p3_0,
  136410. _vq_quantmap__44c0_s_p3_0,
  136411. 9,
  136412. 9
  136413. };
  136414. static static_codebook _44c0_s_p3_0 = {
  136415. 2, 81,
  136416. _vq_lengthlist__44c0_s_p3_0,
  136417. 1, -531628032, 1611661312, 4, 0,
  136418. _vq_quantlist__44c0_s_p3_0,
  136419. NULL,
  136420. &_vq_auxt__44c0_s_p3_0,
  136421. NULL,
  136422. 0
  136423. };
  136424. static long _vq_quantlist__44c0_s_p4_0[] = {
  136425. 4,
  136426. 3,
  136427. 5,
  136428. 2,
  136429. 6,
  136430. 1,
  136431. 7,
  136432. 0,
  136433. 8,
  136434. };
  136435. static long _vq_lengthlist__44c0_s_p4_0[] = {
  136436. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  136437. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  136438. 7, 8, 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0,
  136439. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 9, 8, 8,10,10, 0,
  136440. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  136441. 10,
  136442. };
  136443. static float _vq_quantthresh__44c0_s_p4_0[] = {
  136444. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136445. };
  136446. static long _vq_quantmap__44c0_s_p4_0[] = {
  136447. 7, 5, 3, 1, 0, 2, 4, 6,
  136448. 8,
  136449. };
  136450. static encode_aux_threshmatch _vq_auxt__44c0_s_p4_0 = {
  136451. _vq_quantthresh__44c0_s_p4_0,
  136452. _vq_quantmap__44c0_s_p4_0,
  136453. 9,
  136454. 9
  136455. };
  136456. static static_codebook _44c0_s_p4_0 = {
  136457. 2, 81,
  136458. _vq_lengthlist__44c0_s_p4_0,
  136459. 1, -531628032, 1611661312, 4, 0,
  136460. _vq_quantlist__44c0_s_p4_0,
  136461. NULL,
  136462. &_vq_auxt__44c0_s_p4_0,
  136463. NULL,
  136464. 0
  136465. };
  136466. static long _vq_quantlist__44c0_s_p5_0[] = {
  136467. 8,
  136468. 7,
  136469. 9,
  136470. 6,
  136471. 10,
  136472. 5,
  136473. 11,
  136474. 4,
  136475. 12,
  136476. 3,
  136477. 13,
  136478. 2,
  136479. 14,
  136480. 1,
  136481. 15,
  136482. 0,
  136483. 16,
  136484. };
  136485. static long _vq_lengthlist__44c0_s_p5_0[] = {
  136486. 1, 4, 3, 6, 6, 8, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  136487. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9, 9,10,10,10,
  136488. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  136489. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  136490. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  136491. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  136492. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  136493. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  136494. 10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  136495. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  136496. 10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  136497. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  136498. 10,10,11,11,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  136499. 0, 0, 0,11,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  136500. 0, 0, 0, 0,11,11,12,11,12,12,12,12,13,13, 0, 0,
  136501. 0, 0, 0, 0, 0,11,11,11,12,12,12,12,13,13,13, 0,
  136502. 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,13,14,14,
  136503. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  136504. 14,
  136505. };
  136506. static float _vq_quantthresh__44c0_s_p5_0[] = {
  136507. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136508. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136509. };
  136510. static long _vq_quantmap__44c0_s_p5_0[] = {
  136511. 15, 13, 11, 9, 7, 5, 3, 1,
  136512. 0, 2, 4, 6, 8, 10, 12, 14,
  136513. 16,
  136514. };
  136515. static encode_aux_threshmatch _vq_auxt__44c0_s_p5_0 = {
  136516. _vq_quantthresh__44c0_s_p5_0,
  136517. _vq_quantmap__44c0_s_p5_0,
  136518. 17,
  136519. 17
  136520. };
  136521. static static_codebook _44c0_s_p5_0 = {
  136522. 2, 289,
  136523. _vq_lengthlist__44c0_s_p5_0,
  136524. 1, -529530880, 1611661312, 5, 0,
  136525. _vq_quantlist__44c0_s_p5_0,
  136526. NULL,
  136527. &_vq_auxt__44c0_s_p5_0,
  136528. NULL,
  136529. 0
  136530. };
  136531. static long _vq_quantlist__44c0_s_p6_0[] = {
  136532. 1,
  136533. 0,
  136534. 2,
  136535. };
  136536. static long _vq_lengthlist__44c0_s_p6_0[] = {
  136537. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  136538. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  136539. 11,12,10,11, 6, 9, 9,11,10,11,11,10,10, 6, 9, 9,
  136540. 11,10,11,11,10,10, 7,11,10,12,11,11,11,11,11, 7,
  136541. 9, 9,10,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  136542. 10,
  136543. };
  136544. static float _vq_quantthresh__44c0_s_p6_0[] = {
  136545. -5.5, 5.5,
  136546. };
  136547. static long _vq_quantmap__44c0_s_p6_0[] = {
  136548. 1, 0, 2,
  136549. };
  136550. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_0 = {
  136551. _vq_quantthresh__44c0_s_p6_0,
  136552. _vq_quantmap__44c0_s_p6_0,
  136553. 3,
  136554. 3
  136555. };
  136556. static static_codebook _44c0_s_p6_0 = {
  136557. 4, 81,
  136558. _vq_lengthlist__44c0_s_p6_0,
  136559. 1, -529137664, 1618345984, 2, 0,
  136560. _vq_quantlist__44c0_s_p6_0,
  136561. NULL,
  136562. &_vq_auxt__44c0_s_p6_0,
  136563. NULL,
  136564. 0
  136565. };
  136566. static long _vq_quantlist__44c0_s_p6_1[] = {
  136567. 5,
  136568. 4,
  136569. 6,
  136570. 3,
  136571. 7,
  136572. 2,
  136573. 8,
  136574. 1,
  136575. 9,
  136576. 0,
  136577. 10,
  136578. };
  136579. static long _vq_lengthlist__44c0_s_p6_1[] = {
  136580. 2, 3, 3, 6, 6, 7, 7, 7, 7, 7, 8,10,10,10, 6, 6,
  136581. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  136582. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  136583. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  136584. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  136585. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  136586. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  136587. 10,10,10, 8, 8, 8, 8, 8, 8,
  136588. };
  136589. static float _vq_quantthresh__44c0_s_p6_1[] = {
  136590. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  136591. 3.5, 4.5,
  136592. };
  136593. static long _vq_quantmap__44c0_s_p6_1[] = {
  136594. 9, 7, 5, 3, 1, 0, 2, 4,
  136595. 6, 8, 10,
  136596. };
  136597. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_1 = {
  136598. _vq_quantthresh__44c0_s_p6_1,
  136599. _vq_quantmap__44c0_s_p6_1,
  136600. 11,
  136601. 11
  136602. };
  136603. static static_codebook _44c0_s_p6_1 = {
  136604. 2, 121,
  136605. _vq_lengthlist__44c0_s_p6_1,
  136606. 1, -531365888, 1611661312, 4, 0,
  136607. _vq_quantlist__44c0_s_p6_1,
  136608. NULL,
  136609. &_vq_auxt__44c0_s_p6_1,
  136610. NULL,
  136611. 0
  136612. };
  136613. static long _vq_quantlist__44c0_s_p7_0[] = {
  136614. 6,
  136615. 5,
  136616. 7,
  136617. 4,
  136618. 8,
  136619. 3,
  136620. 9,
  136621. 2,
  136622. 10,
  136623. 1,
  136624. 11,
  136625. 0,
  136626. 12,
  136627. };
  136628. static long _vq_lengthlist__44c0_s_p7_0[] = {
  136629. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  136630. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  136631. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  136632. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  136633. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  136634. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  136635. 10,10,11,11,11,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  136636. 11,11,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  136637. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  136638. 0, 0, 0, 0,11,11,11,11,13,12,13,13, 0, 0, 0, 0,
  136639. 0,12,12,11,11,12,12,13,13,
  136640. };
  136641. static float _vq_quantthresh__44c0_s_p7_0[] = {
  136642. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  136643. 12.5, 17.5, 22.5, 27.5,
  136644. };
  136645. static long _vq_quantmap__44c0_s_p7_0[] = {
  136646. 11, 9, 7, 5, 3, 1, 0, 2,
  136647. 4, 6, 8, 10, 12,
  136648. };
  136649. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_0 = {
  136650. _vq_quantthresh__44c0_s_p7_0,
  136651. _vq_quantmap__44c0_s_p7_0,
  136652. 13,
  136653. 13
  136654. };
  136655. static static_codebook _44c0_s_p7_0 = {
  136656. 2, 169,
  136657. _vq_lengthlist__44c0_s_p7_0,
  136658. 1, -526516224, 1616117760, 4, 0,
  136659. _vq_quantlist__44c0_s_p7_0,
  136660. NULL,
  136661. &_vq_auxt__44c0_s_p7_0,
  136662. NULL,
  136663. 0
  136664. };
  136665. static long _vq_quantlist__44c0_s_p7_1[] = {
  136666. 2,
  136667. 1,
  136668. 3,
  136669. 0,
  136670. 4,
  136671. };
  136672. static long _vq_lengthlist__44c0_s_p7_1[] = {
  136673. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  136674. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  136675. };
  136676. static float _vq_quantthresh__44c0_s_p7_1[] = {
  136677. -1.5, -0.5, 0.5, 1.5,
  136678. };
  136679. static long _vq_quantmap__44c0_s_p7_1[] = {
  136680. 3, 1, 0, 2, 4,
  136681. };
  136682. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_1 = {
  136683. _vq_quantthresh__44c0_s_p7_1,
  136684. _vq_quantmap__44c0_s_p7_1,
  136685. 5,
  136686. 5
  136687. };
  136688. static static_codebook _44c0_s_p7_1 = {
  136689. 2, 25,
  136690. _vq_lengthlist__44c0_s_p7_1,
  136691. 1, -533725184, 1611661312, 3, 0,
  136692. _vq_quantlist__44c0_s_p7_1,
  136693. NULL,
  136694. &_vq_auxt__44c0_s_p7_1,
  136695. NULL,
  136696. 0
  136697. };
  136698. static long _vq_quantlist__44c0_s_p8_0[] = {
  136699. 2,
  136700. 1,
  136701. 3,
  136702. 0,
  136703. 4,
  136704. };
  136705. static long _vq_lengthlist__44c0_s_p8_0[] = {
  136706. 1, 5, 5,10,10, 6, 9, 8,10,10, 6,10, 9,10,10,10,
  136707. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136708. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136709. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136710. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136711. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136712. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136713. 10,10,10,10,10,10,10,10,10,10,10,10,10, 8,10,10,
  136714. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136715. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136716. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136717. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136718. 10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,
  136719. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136720. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136721. 11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,
  136722. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136723. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136724. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136725. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136726. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136727. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136728. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136729. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136730. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136731. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136732. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136733. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136734. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136735. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136736. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136737. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136738. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136739. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136740. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136741. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136742. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136743. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136744. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136745. 11,
  136746. };
  136747. static float _vq_quantthresh__44c0_s_p8_0[] = {
  136748. -331.5, -110.5, 110.5, 331.5,
  136749. };
  136750. static long _vq_quantmap__44c0_s_p8_0[] = {
  136751. 3, 1, 0, 2, 4,
  136752. };
  136753. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_0 = {
  136754. _vq_quantthresh__44c0_s_p8_0,
  136755. _vq_quantmap__44c0_s_p8_0,
  136756. 5,
  136757. 5
  136758. };
  136759. static static_codebook _44c0_s_p8_0 = {
  136760. 4, 625,
  136761. _vq_lengthlist__44c0_s_p8_0,
  136762. 1, -518283264, 1627103232, 3, 0,
  136763. _vq_quantlist__44c0_s_p8_0,
  136764. NULL,
  136765. &_vq_auxt__44c0_s_p8_0,
  136766. NULL,
  136767. 0
  136768. };
  136769. static long _vq_quantlist__44c0_s_p8_1[] = {
  136770. 6,
  136771. 5,
  136772. 7,
  136773. 4,
  136774. 8,
  136775. 3,
  136776. 9,
  136777. 2,
  136778. 10,
  136779. 1,
  136780. 11,
  136781. 0,
  136782. 12,
  136783. };
  136784. static long _vq_lengthlist__44c0_s_p8_1[] = {
  136785. 1, 4, 4, 6, 6, 7, 7, 9, 9,11,12,13,12, 6, 5, 5,
  136786. 7, 7, 8, 8,10, 9,12,12,12,12, 6, 5, 5, 7, 7, 8,
  136787. 8,10, 9,12,11,11,13,16, 7, 7, 8, 8, 9, 9,10,10,
  136788. 12,12,13,12,16, 7, 7, 8, 7, 9, 9,10,10,11,12,12,
  136789. 13,16,10,10, 8, 8,10,10,11,12,12,12,13,13,16,11,
  136790. 10, 8, 7,11,10,11,11,12,11,13,13,16,16,16,10,10,
  136791. 10,10,11,11,13,12,13,13,16,16,16,11, 9,11, 9,15,
  136792. 13,12,13,13,13,16,16,16,15,13,11,11,12,13,12,12,
  136793. 14,13,16,16,16,14,13,11,11,13,12,14,13,13,13,16,
  136794. 16,16,16,16,13,13,13,12,14,13,14,14,16,16,16,16,
  136795. 16,13,13,12,12,14,14,15,13,
  136796. };
  136797. static float _vq_quantthresh__44c0_s_p8_1[] = {
  136798. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  136799. 42.5, 59.5, 76.5, 93.5,
  136800. };
  136801. static long _vq_quantmap__44c0_s_p8_1[] = {
  136802. 11, 9, 7, 5, 3, 1, 0, 2,
  136803. 4, 6, 8, 10, 12,
  136804. };
  136805. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_1 = {
  136806. _vq_quantthresh__44c0_s_p8_1,
  136807. _vq_quantmap__44c0_s_p8_1,
  136808. 13,
  136809. 13
  136810. };
  136811. static static_codebook _44c0_s_p8_1 = {
  136812. 2, 169,
  136813. _vq_lengthlist__44c0_s_p8_1,
  136814. 1, -522616832, 1620115456, 4, 0,
  136815. _vq_quantlist__44c0_s_p8_1,
  136816. NULL,
  136817. &_vq_auxt__44c0_s_p8_1,
  136818. NULL,
  136819. 0
  136820. };
  136821. static long _vq_quantlist__44c0_s_p8_2[] = {
  136822. 8,
  136823. 7,
  136824. 9,
  136825. 6,
  136826. 10,
  136827. 5,
  136828. 11,
  136829. 4,
  136830. 12,
  136831. 3,
  136832. 13,
  136833. 2,
  136834. 14,
  136835. 1,
  136836. 15,
  136837. 0,
  136838. 16,
  136839. };
  136840. static long _vq_lengthlist__44c0_s_p8_2[] = {
  136841. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  136842. 8,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  136843. 9, 9,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  136844. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  136845. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  136846. 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 8, 9, 9,
  136847. 9, 9, 9,10, 9,10,10,10,10, 7, 7, 8, 8, 9, 9, 9,
  136848. 9, 9, 9,10, 9,10,10,10,10,10, 8, 8, 8, 9, 9, 9,
  136849. 9, 9, 9, 9,10,10,10, 9,11,10,10,10,10, 8, 8, 9,
  136850. 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,11,11, 9, 9,
  136851. 9, 9, 9, 9, 9, 9,10, 9, 9,10,11,10,10,11,11, 9,
  136852. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  136853. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,10,11,
  136854. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  136855. 11,11,11,11, 9,10, 9,10, 9, 9, 9, 9,10, 9,10,11,
  136856. 10,11,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9,10,11,
  136857. 11,10,11,11,10,11,10,10,10, 9, 9, 9, 9,10, 9, 9,
  136858. 10,11,10,11,11,11,11,10,11,10,10, 9,10, 9, 9, 9,
  136859. 10,
  136860. };
  136861. static float _vq_quantthresh__44c0_s_p8_2[] = {
  136862. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136863. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136864. };
  136865. static long _vq_quantmap__44c0_s_p8_2[] = {
  136866. 15, 13, 11, 9, 7, 5, 3, 1,
  136867. 0, 2, 4, 6, 8, 10, 12, 14,
  136868. 16,
  136869. };
  136870. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_2 = {
  136871. _vq_quantthresh__44c0_s_p8_2,
  136872. _vq_quantmap__44c0_s_p8_2,
  136873. 17,
  136874. 17
  136875. };
  136876. static static_codebook _44c0_s_p8_2 = {
  136877. 2, 289,
  136878. _vq_lengthlist__44c0_s_p8_2,
  136879. 1, -529530880, 1611661312, 5, 0,
  136880. _vq_quantlist__44c0_s_p8_2,
  136881. NULL,
  136882. &_vq_auxt__44c0_s_p8_2,
  136883. NULL,
  136884. 0
  136885. };
  136886. static long _huff_lengthlist__44c0_s_short[] = {
  136887. 9, 8,12,11,12,13,14,14,16, 6, 1, 5, 6, 6, 9,12,
  136888. 14,17, 9, 4, 5, 9, 7, 9,13,15,16, 8, 5, 8, 6, 8,
  136889. 10,13,17,17, 9, 6, 7, 7, 8, 9,13,15,17,11, 8, 9,
  136890. 9, 9,10,12,16,16,13, 7, 8, 7, 7, 9,12,14,15,13,
  136891. 6, 7, 5, 5, 7,10,13,13,14, 7, 8, 5, 6, 7, 9,10,
  136892. 12,
  136893. };
  136894. static static_codebook _huff_book__44c0_s_short = {
  136895. 2, 81,
  136896. _huff_lengthlist__44c0_s_short,
  136897. 0, 0, 0, 0, 0,
  136898. NULL,
  136899. NULL,
  136900. NULL,
  136901. NULL,
  136902. 0
  136903. };
  136904. static long _huff_lengthlist__44c0_sm_long[] = {
  136905. 5, 4, 9,10, 9,10,11,12,13, 4, 1, 5, 7, 7, 9,11,
  136906. 12,14, 8, 5, 7, 9, 8,10,13,13,13,10, 7, 9, 4, 6,
  136907. 7,10,12,14, 9, 6, 7, 6, 6, 7,10,12,12, 9, 8, 9,
  136908. 7, 6, 7, 8,11,12,11,11,11, 9, 8, 7, 8,10,12,12,
  136909. 13,14,12,11, 9, 9, 9,12,12,17,17,15,16,12,10,11,
  136910. 13,
  136911. };
  136912. static static_codebook _huff_book__44c0_sm_long = {
  136913. 2, 81,
  136914. _huff_lengthlist__44c0_sm_long,
  136915. 0, 0, 0, 0, 0,
  136916. NULL,
  136917. NULL,
  136918. NULL,
  136919. NULL,
  136920. 0
  136921. };
  136922. static long _vq_quantlist__44c0_sm_p1_0[] = {
  136923. 1,
  136924. 0,
  136925. 2,
  136926. };
  136927. static long _vq_lengthlist__44c0_sm_p1_0[] = {
  136928. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  136929. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136933. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  136934. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136938. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  136939. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 7, 0, 0, 0, 0,
  136974. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  136975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  136979. 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  136980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  136984. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  136985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  137020. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  137025. 0, 0, 0, 0, 0, 9, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  137030. 0, 0, 0, 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 0,
  137031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137338. 0,
  137339. };
  137340. static float _vq_quantthresh__44c0_sm_p1_0[] = {
  137341. -0.5, 0.5,
  137342. };
  137343. static long _vq_quantmap__44c0_sm_p1_0[] = {
  137344. 1, 0, 2,
  137345. };
  137346. static encode_aux_threshmatch _vq_auxt__44c0_sm_p1_0 = {
  137347. _vq_quantthresh__44c0_sm_p1_0,
  137348. _vq_quantmap__44c0_sm_p1_0,
  137349. 3,
  137350. 3
  137351. };
  137352. static static_codebook _44c0_sm_p1_0 = {
  137353. 8, 6561,
  137354. _vq_lengthlist__44c0_sm_p1_0,
  137355. 1, -535822336, 1611661312, 2, 0,
  137356. _vq_quantlist__44c0_sm_p1_0,
  137357. NULL,
  137358. &_vq_auxt__44c0_sm_p1_0,
  137359. NULL,
  137360. 0
  137361. };
  137362. static long _vq_quantlist__44c0_sm_p2_0[] = {
  137363. 2,
  137364. 1,
  137365. 3,
  137366. 0,
  137367. 4,
  137368. };
  137369. static long _vq_lengthlist__44c0_sm_p2_0[] = {
  137370. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  137372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137373. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  137375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137376. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  137377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137409. 0,
  137410. };
  137411. static float _vq_quantthresh__44c0_sm_p2_0[] = {
  137412. -1.5, -0.5, 0.5, 1.5,
  137413. };
  137414. static long _vq_quantmap__44c0_sm_p2_0[] = {
  137415. 3, 1, 0, 2, 4,
  137416. };
  137417. static encode_aux_threshmatch _vq_auxt__44c0_sm_p2_0 = {
  137418. _vq_quantthresh__44c0_sm_p2_0,
  137419. _vq_quantmap__44c0_sm_p2_0,
  137420. 5,
  137421. 5
  137422. };
  137423. static static_codebook _44c0_sm_p2_0 = {
  137424. 4, 625,
  137425. _vq_lengthlist__44c0_sm_p2_0,
  137426. 1, -533725184, 1611661312, 3, 0,
  137427. _vq_quantlist__44c0_sm_p2_0,
  137428. NULL,
  137429. &_vq_auxt__44c0_sm_p2_0,
  137430. NULL,
  137431. 0
  137432. };
  137433. static long _vq_quantlist__44c0_sm_p3_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_p3_0[] = {
  137445. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 4, 7, 7, 0, 0,
  137446. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  137447. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  137448. 9,10, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  137449. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137450. 0,
  137451. };
  137452. static float _vq_quantthresh__44c0_sm_p3_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_p3_0[] = {
  137456. 7, 5, 3, 1, 0, 2, 4, 6,
  137457. 8,
  137458. };
  137459. static encode_aux_threshmatch _vq_auxt__44c0_sm_p3_0 = {
  137460. _vq_quantthresh__44c0_sm_p3_0,
  137461. _vq_quantmap__44c0_sm_p3_0,
  137462. 9,
  137463. 9
  137464. };
  137465. static static_codebook _44c0_sm_p3_0 = {
  137466. 2, 81,
  137467. _vq_lengthlist__44c0_sm_p3_0,
  137468. 1, -531628032, 1611661312, 4, 0,
  137469. _vq_quantlist__44c0_sm_p3_0,
  137470. NULL,
  137471. &_vq_auxt__44c0_sm_p3_0,
  137472. NULL,
  137473. 0
  137474. };
  137475. static long _vq_quantlist__44c0_sm_p4_0[] = {
  137476. 4,
  137477. 3,
  137478. 5,
  137479. 2,
  137480. 6,
  137481. 1,
  137482. 7,
  137483. 0,
  137484. 8,
  137485. };
  137486. static long _vq_lengthlist__44c0_sm_p4_0[] = {
  137487. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  137488. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  137489. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  137490. 9, 9, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  137491. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  137492. 11,
  137493. };
  137494. static float _vq_quantthresh__44c0_sm_p4_0[] = {
  137495. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137496. };
  137497. static long _vq_quantmap__44c0_sm_p4_0[] = {
  137498. 7, 5, 3, 1, 0, 2, 4, 6,
  137499. 8,
  137500. };
  137501. static encode_aux_threshmatch _vq_auxt__44c0_sm_p4_0 = {
  137502. _vq_quantthresh__44c0_sm_p4_0,
  137503. _vq_quantmap__44c0_sm_p4_0,
  137504. 9,
  137505. 9
  137506. };
  137507. static static_codebook _44c0_sm_p4_0 = {
  137508. 2, 81,
  137509. _vq_lengthlist__44c0_sm_p4_0,
  137510. 1, -531628032, 1611661312, 4, 0,
  137511. _vq_quantlist__44c0_sm_p4_0,
  137512. NULL,
  137513. &_vq_auxt__44c0_sm_p4_0,
  137514. NULL,
  137515. 0
  137516. };
  137517. static long _vq_quantlist__44c0_sm_p5_0[] = {
  137518. 8,
  137519. 7,
  137520. 9,
  137521. 6,
  137522. 10,
  137523. 5,
  137524. 11,
  137525. 4,
  137526. 12,
  137527. 3,
  137528. 13,
  137529. 2,
  137530. 14,
  137531. 1,
  137532. 15,
  137533. 0,
  137534. 16,
  137535. };
  137536. static long _vq_lengthlist__44c0_sm_p5_0[] = {
  137537. 1, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 9, 9,10,10,11,
  137538. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  137539. 11,11, 0, 5, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  137540. 11,11,11, 0, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  137541. 11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,
  137542. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  137543. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  137544. 10,11,11,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  137545. 10,10,11,11,12,12,12,13, 0, 0, 0, 0, 0, 9, 9,10,
  137546. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  137547. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  137548. 9,10,10,11,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  137549. 10,10,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0,
  137550. 0, 0, 0,10,10,11,11,12,12,12,13,13,13, 0, 0, 0,
  137551. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  137552. 0, 0, 0, 0, 0,11,11,12,11,12,12,13,13,13,13, 0,
  137553. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  137554. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  137555. 14,
  137556. };
  137557. static float _vq_quantthresh__44c0_sm_p5_0[] = {
  137558. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137559. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137560. };
  137561. static long _vq_quantmap__44c0_sm_p5_0[] = {
  137562. 15, 13, 11, 9, 7, 5, 3, 1,
  137563. 0, 2, 4, 6, 8, 10, 12, 14,
  137564. 16,
  137565. };
  137566. static encode_aux_threshmatch _vq_auxt__44c0_sm_p5_0 = {
  137567. _vq_quantthresh__44c0_sm_p5_0,
  137568. _vq_quantmap__44c0_sm_p5_0,
  137569. 17,
  137570. 17
  137571. };
  137572. static static_codebook _44c0_sm_p5_0 = {
  137573. 2, 289,
  137574. _vq_lengthlist__44c0_sm_p5_0,
  137575. 1, -529530880, 1611661312, 5, 0,
  137576. _vq_quantlist__44c0_sm_p5_0,
  137577. NULL,
  137578. &_vq_auxt__44c0_sm_p5_0,
  137579. NULL,
  137580. 0
  137581. };
  137582. static long _vq_quantlist__44c0_sm_p6_0[] = {
  137583. 1,
  137584. 0,
  137585. 2,
  137586. };
  137587. static long _vq_lengthlist__44c0_sm_p6_0[] = {
  137588. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  137589. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  137590. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  137591. 11,10,11,11,10,10, 7,11,10,11,11,11,11,11,11, 6,
  137592. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  137593. 11,
  137594. };
  137595. static float _vq_quantthresh__44c0_sm_p6_0[] = {
  137596. -5.5, 5.5,
  137597. };
  137598. static long _vq_quantmap__44c0_sm_p6_0[] = {
  137599. 1, 0, 2,
  137600. };
  137601. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_0 = {
  137602. _vq_quantthresh__44c0_sm_p6_0,
  137603. _vq_quantmap__44c0_sm_p6_0,
  137604. 3,
  137605. 3
  137606. };
  137607. static static_codebook _44c0_sm_p6_0 = {
  137608. 4, 81,
  137609. _vq_lengthlist__44c0_sm_p6_0,
  137610. 1, -529137664, 1618345984, 2, 0,
  137611. _vq_quantlist__44c0_sm_p6_0,
  137612. NULL,
  137613. &_vq_auxt__44c0_sm_p6_0,
  137614. NULL,
  137615. 0
  137616. };
  137617. static long _vq_quantlist__44c0_sm_p6_1[] = {
  137618. 5,
  137619. 4,
  137620. 6,
  137621. 3,
  137622. 7,
  137623. 2,
  137624. 8,
  137625. 1,
  137626. 9,
  137627. 0,
  137628. 10,
  137629. };
  137630. static long _vq_lengthlist__44c0_sm_p6_1[] = {
  137631. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 8, 9, 5, 5, 6, 6,
  137632. 7, 7, 8, 8, 8, 8, 9, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  137633. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  137634. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  137635. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  137636. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  137637. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  137638. 10,10,10, 8, 8, 8, 8, 8, 8,
  137639. };
  137640. static float _vq_quantthresh__44c0_sm_p6_1[] = {
  137641. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  137642. 3.5, 4.5,
  137643. };
  137644. static long _vq_quantmap__44c0_sm_p6_1[] = {
  137645. 9, 7, 5, 3, 1, 0, 2, 4,
  137646. 6, 8, 10,
  137647. };
  137648. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_1 = {
  137649. _vq_quantthresh__44c0_sm_p6_1,
  137650. _vq_quantmap__44c0_sm_p6_1,
  137651. 11,
  137652. 11
  137653. };
  137654. static static_codebook _44c0_sm_p6_1 = {
  137655. 2, 121,
  137656. _vq_lengthlist__44c0_sm_p6_1,
  137657. 1, -531365888, 1611661312, 4, 0,
  137658. _vq_quantlist__44c0_sm_p6_1,
  137659. NULL,
  137660. &_vq_auxt__44c0_sm_p6_1,
  137661. NULL,
  137662. 0
  137663. };
  137664. static long _vq_quantlist__44c0_sm_p7_0[] = {
  137665. 6,
  137666. 5,
  137667. 7,
  137668. 4,
  137669. 8,
  137670. 3,
  137671. 9,
  137672. 2,
  137673. 10,
  137674. 1,
  137675. 11,
  137676. 0,
  137677. 12,
  137678. };
  137679. static long _vq_lengthlist__44c0_sm_p7_0[] = {
  137680. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  137681. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  137682. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  137683. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  137684. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  137685. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0, 9,10,
  137686. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  137687. 11,12,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  137688. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  137689. 0, 0, 0, 0,11,12,11,11,13,12,13,13, 0, 0, 0, 0,
  137690. 0,12,12,11,11,13,12,14,14,
  137691. };
  137692. static float _vq_quantthresh__44c0_sm_p7_0[] = {
  137693. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  137694. 12.5, 17.5, 22.5, 27.5,
  137695. };
  137696. static long _vq_quantmap__44c0_sm_p7_0[] = {
  137697. 11, 9, 7, 5, 3, 1, 0, 2,
  137698. 4, 6, 8, 10, 12,
  137699. };
  137700. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_0 = {
  137701. _vq_quantthresh__44c0_sm_p7_0,
  137702. _vq_quantmap__44c0_sm_p7_0,
  137703. 13,
  137704. 13
  137705. };
  137706. static static_codebook _44c0_sm_p7_0 = {
  137707. 2, 169,
  137708. _vq_lengthlist__44c0_sm_p7_0,
  137709. 1, -526516224, 1616117760, 4, 0,
  137710. _vq_quantlist__44c0_sm_p7_0,
  137711. NULL,
  137712. &_vq_auxt__44c0_sm_p7_0,
  137713. NULL,
  137714. 0
  137715. };
  137716. static long _vq_quantlist__44c0_sm_p7_1[] = {
  137717. 2,
  137718. 1,
  137719. 3,
  137720. 0,
  137721. 4,
  137722. };
  137723. static long _vq_lengthlist__44c0_sm_p7_1[] = {
  137724. 2, 4, 4, 4, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  137725. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  137726. };
  137727. static float _vq_quantthresh__44c0_sm_p7_1[] = {
  137728. -1.5, -0.5, 0.5, 1.5,
  137729. };
  137730. static long _vq_quantmap__44c0_sm_p7_1[] = {
  137731. 3, 1, 0, 2, 4,
  137732. };
  137733. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_1 = {
  137734. _vq_quantthresh__44c0_sm_p7_1,
  137735. _vq_quantmap__44c0_sm_p7_1,
  137736. 5,
  137737. 5
  137738. };
  137739. static static_codebook _44c0_sm_p7_1 = {
  137740. 2, 25,
  137741. _vq_lengthlist__44c0_sm_p7_1,
  137742. 1, -533725184, 1611661312, 3, 0,
  137743. _vq_quantlist__44c0_sm_p7_1,
  137744. NULL,
  137745. &_vq_auxt__44c0_sm_p7_1,
  137746. NULL,
  137747. 0
  137748. };
  137749. static long _vq_quantlist__44c0_sm_p8_0[] = {
  137750. 4,
  137751. 3,
  137752. 5,
  137753. 2,
  137754. 6,
  137755. 1,
  137756. 7,
  137757. 0,
  137758. 8,
  137759. };
  137760. static long _vq_lengthlist__44c0_sm_p8_0[] = {
  137761. 1, 3, 3,11,11,11,11,11,11, 3, 7, 6,11,11,11,11,
  137762. 11,11, 4, 8, 7,11,11,11,11,11,11,11,11,11,11,11,
  137763. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137764. 11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137765. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137766. 12,
  137767. };
  137768. static float _vq_quantthresh__44c0_sm_p8_0[] = {
  137769. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  137770. };
  137771. static long _vq_quantmap__44c0_sm_p8_0[] = {
  137772. 7, 5, 3, 1, 0, 2, 4, 6,
  137773. 8,
  137774. };
  137775. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_0 = {
  137776. _vq_quantthresh__44c0_sm_p8_0,
  137777. _vq_quantmap__44c0_sm_p8_0,
  137778. 9,
  137779. 9
  137780. };
  137781. static static_codebook _44c0_sm_p8_0 = {
  137782. 2, 81,
  137783. _vq_lengthlist__44c0_sm_p8_0,
  137784. 1, -516186112, 1627103232, 4, 0,
  137785. _vq_quantlist__44c0_sm_p8_0,
  137786. NULL,
  137787. &_vq_auxt__44c0_sm_p8_0,
  137788. NULL,
  137789. 0
  137790. };
  137791. static long _vq_quantlist__44c0_sm_p8_1[] = {
  137792. 6,
  137793. 5,
  137794. 7,
  137795. 4,
  137796. 8,
  137797. 3,
  137798. 9,
  137799. 2,
  137800. 10,
  137801. 1,
  137802. 11,
  137803. 0,
  137804. 12,
  137805. };
  137806. static long _vq_lengthlist__44c0_sm_p8_1[] = {
  137807. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  137808. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  137809. 8,10,10,12,11,12,12,17, 7, 7, 8, 8, 9, 9,10,10,
  137810. 12,12,13,13,18, 7, 7, 8, 7, 9, 9,10,10,12,12,12,
  137811. 13,19,10,10, 8, 8,10,10,11,11,12,12,13,14,19,11,
  137812. 10, 8, 7,10,10,11,11,12,12,13,12,19,19,19,10,10,
  137813. 10,10,11,11,12,12,13,13,19,19,19,11, 9,11, 9,14,
  137814. 12,13,12,13,13,19,20,18,13,14,11,11,12,12,13,13,
  137815. 14,13,20,20,20,15,13,11,10,13,11,13,13,14,13,20,
  137816. 20,20,20,20,13,14,12,12,13,13,13,13,20,20,20,20,
  137817. 20,13,13,12,12,16,13,15,13,
  137818. };
  137819. static float _vq_quantthresh__44c0_sm_p8_1[] = {
  137820. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  137821. 42.5, 59.5, 76.5, 93.5,
  137822. };
  137823. static long _vq_quantmap__44c0_sm_p8_1[] = {
  137824. 11, 9, 7, 5, 3, 1, 0, 2,
  137825. 4, 6, 8, 10, 12,
  137826. };
  137827. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_1 = {
  137828. _vq_quantthresh__44c0_sm_p8_1,
  137829. _vq_quantmap__44c0_sm_p8_1,
  137830. 13,
  137831. 13
  137832. };
  137833. static static_codebook _44c0_sm_p8_1 = {
  137834. 2, 169,
  137835. _vq_lengthlist__44c0_sm_p8_1,
  137836. 1, -522616832, 1620115456, 4, 0,
  137837. _vq_quantlist__44c0_sm_p8_1,
  137838. NULL,
  137839. &_vq_auxt__44c0_sm_p8_1,
  137840. NULL,
  137841. 0
  137842. };
  137843. static long _vq_quantlist__44c0_sm_p8_2[] = {
  137844. 8,
  137845. 7,
  137846. 9,
  137847. 6,
  137848. 10,
  137849. 5,
  137850. 11,
  137851. 4,
  137852. 12,
  137853. 3,
  137854. 13,
  137855. 2,
  137856. 14,
  137857. 1,
  137858. 15,
  137859. 0,
  137860. 16,
  137861. };
  137862. static long _vq_lengthlist__44c0_sm_p8_2[] = {
  137863. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  137864. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  137865. 9, 9,10, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  137866. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  137867. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  137868. 9,10, 9, 9,10,10,10,11, 8, 8, 8, 8, 9, 9, 9, 9,
  137869. 9, 9, 9,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  137870. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  137871. 9, 9, 9, 9, 9, 9,10,10,10,10,10,11,11, 8, 8, 9,
  137872. 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,11,11,11, 9, 9,
  137873. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,10,11,11, 9,
  137874. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  137875. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,11,11,
  137876. 11,11,11, 9, 9,10, 9, 9, 9, 9, 9, 9, 9,10,11,10,
  137877. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  137878. 11,11,11,11,11, 9,10, 9, 9, 9, 9, 9, 9, 9, 9,11,
  137879. 11,10,11,11,11,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  137880. 10,11,10,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  137881. 9,
  137882. };
  137883. static float _vq_quantthresh__44c0_sm_p8_2[] = {
  137884. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137885. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137886. };
  137887. static long _vq_quantmap__44c0_sm_p8_2[] = {
  137888. 15, 13, 11, 9, 7, 5, 3, 1,
  137889. 0, 2, 4, 6, 8, 10, 12, 14,
  137890. 16,
  137891. };
  137892. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_2 = {
  137893. _vq_quantthresh__44c0_sm_p8_2,
  137894. _vq_quantmap__44c0_sm_p8_2,
  137895. 17,
  137896. 17
  137897. };
  137898. static static_codebook _44c0_sm_p8_2 = {
  137899. 2, 289,
  137900. _vq_lengthlist__44c0_sm_p8_2,
  137901. 1, -529530880, 1611661312, 5, 0,
  137902. _vq_quantlist__44c0_sm_p8_2,
  137903. NULL,
  137904. &_vq_auxt__44c0_sm_p8_2,
  137905. NULL,
  137906. 0
  137907. };
  137908. static long _huff_lengthlist__44c0_sm_short[] = {
  137909. 6, 6,12,13,13,14,16,17,17, 4, 2, 5, 8, 7, 9,12,
  137910. 15,15, 9, 4, 5, 9, 7, 9,12,16,18,11, 6, 7, 4, 6,
  137911. 8,11,14,18,10, 5, 6, 5, 5, 7,10,14,17,10, 5, 7,
  137912. 7, 6, 7,10,13,16,11, 5, 7, 7, 7, 8,10,12,15,13,
  137913. 6, 7, 5, 5, 7, 9,12,13,16, 8, 9, 6, 6, 7, 9,10,
  137914. 12,
  137915. };
  137916. static static_codebook _huff_book__44c0_sm_short = {
  137917. 2, 81,
  137918. _huff_lengthlist__44c0_sm_short,
  137919. 0, 0, 0, 0, 0,
  137920. NULL,
  137921. NULL,
  137922. NULL,
  137923. NULL,
  137924. 0
  137925. };
  137926. static long _huff_lengthlist__44c1_s_long[] = {
  137927. 5, 5, 9,10, 9, 9,10,11,12, 5, 1, 5, 6, 6, 7,10,
  137928. 12,14, 9, 5, 6, 8, 8,10,12,14,14,10, 5, 8, 5, 6,
  137929. 8,11,13,14, 9, 5, 7, 6, 6, 8,10,12,11, 9, 7, 9,
  137930. 7, 6, 6, 7,10,10,10, 9,12, 9, 8, 7, 7,10,12,11,
  137931. 11,13,12,10, 9, 8, 9,11,11,14,15,15,13,11, 9, 9,
  137932. 11,
  137933. };
  137934. static static_codebook _huff_book__44c1_s_long = {
  137935. 2, 81,
  137936. _huff_lengthlist__44c1_s_long,
  137937. 0, 0, 0, 0, 0,
  137938. NULL,
  137939. NULL,
  137940. NULL,
  137941. NULL,
  137942. 0
  137943. };
  137944. static long _vq_quantlist__44c1_s_p1_0[] = {
  137945. 1,
  137946. 0,
  137947. 2,
  137948. };
  137949. static long _vq_lengthlist__44c1_s_p1_0[] = {
  137950. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 6, 0, 0, 0, 0,
  137951. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137955. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  137956. 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137960. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  137961. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 4, 7, 7, 0, 0, 0, 0,
  137996. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  137997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  138001. 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  138002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  138006. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  138007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  138042. 0, 0, 0, 0, 7, 8, 9, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8,10, 9, 0,
  138047. 0, 0, 0, 0, 0, 8, 8, 9, 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, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  138052. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  138053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138360. 0,
  138361. };
  138362. static float _vq_quantthresh__44c1_s_p1_0[] = {
  138363. -0.5, 0.5,
  138364. };
  138365. static long _vq_quantmap__44c1_s_p1_0[] = {
  138366. 1, 0, 2,
  138367. };
  138368. static encode_aux_threshmatch _vq_auxt__44c1_s_p1_0 = {
  138369. _vq_quantthresh__44c1_s_p1_0,
  138370. _vq_quantmap__44c1_s_p1_0,
  138371. 3,
  138372. 3
  138373. };
  138374. static static_codebook _44c1_s_p1_0 = {
  138375. 8, 6561,
  138376. _vq_lengthlist__44c1_s_p1_0,
  138377. 1, -535822336, 1611661312, 2, 0,
  138378. _vq_quantlist__44c1_s_p1_0,
  138379. NULL,
  138380. &_vq_auxt__44c1_s_p1_0,
  138381. NULL,
  138382. 0
  138383. };
  138384. static long _vq_quantlist__44c1_s_p2_0[] = {
  138385. 2,
  138386. 1,
  138387. 3,
  138388. 0,
  138389. 4,
  138390. };
  138391. static long _vq_lengthlist__44c1_s_p2_0[] = {
  138392. 2, 3, 4, 6, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  138394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138395. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  138397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138398. 0, 0, 0, 0, 6, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  138399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138431. 0,
  138432. };
  138433. static float _vq_quantthresh__44c1_s_p2_0[] = {
  138434. -1.5, -0.5, 0.5, 1.5,
  138435. };
  138436. static long _vq_quantmap__44c1_s_p2_0[] = {
  138437. 3, 1, 0, 2, 4,
  138438. };
  138439. static encode_aux_threshmatch _vq_auxt__44c1_s_p2_0 = {
  138440. _vq_quantthresh__44c1_s_p2_0,
  138441. _vq_quantmap__44c1_s_p2_0,
  138442. 5,
  138443. 5
  138444. };
  138445. static static_codebook _44c1_s_p2_0 = {
  138446. 4, 625,
  138447. _vq_lengthlist__44c1_s_p2_0,
  138448. 1, -533725184, 1611661312, 3, 0,
  138449. _vq_quantlist__44c1_s_p2_0,
  138450. NULL,
  138451. &_vq_auxt__44c1_s_p2_0,
  138452. NULL,
  138453. 0
  138454. };
  138455. static long _vq_quantlist__44c1_s_p3_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_p3_0[] = {
  138467. 1, 3, 2, 7, 7, 0, 0, 0, 0, 0,13,13, 6, 6, 0, 0,
  138468. 0, 0, 0,12, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  138469. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  138470. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  138471. 0, 0,11,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138472. 0,
  138473. };
  138474. static float _vq_quantthresh__44c1_s_p3_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_p3_0[] = {
  138478. 7, 5, 3, 1, 0, 2, 4, 6,
  138479. 8,
  138480. };
  138481. static encode_aux_threshmatch _vq_auxt__44c1_s_p3_0 = {
  138482. _vq_quantthresh__44c1_s_p3_0,
  138483. _vq_quantmap__44c1_s_p3_0,
  138484. 9,
  138485. 9
  138486. };
  138487. static static_codebook _44c1_s_p3_0 = {
  138488. 2, 81,
  138489. _vq_lengthlist__44c1_s_p3_0,
  138490. 1, -531628032, 1611661312, 4, 0,
  138491. _vq_quantlist__44c1_s_p3_0,
  138492. NULL,
  138493. &_vq_auxt__44c1_s_p3_0,
  138494. NULL,
  138495. 0
  138496. };
  138497. static long _vq_quantlist__44c1_s_p4_0[] = {
  138498. 4,
  138499. 3,
  138500. 5,
  138501. 2,
  138502. 6,
  138503. 1,
  138504. 7,
  138505. 0,
  138506. 8,
  138507. };
  138508. static long _vq_lengthlist__44c1_s_p4_0[] = {
  138509. 1, 3, 3, 6, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  138510. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  138511. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  138512. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  138513. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  138514. 11,
  138515. };
  138516. static float _vq_quantthresh__44c1_s_p4_0[] = {
  138517. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138518. };
  138519. static long _vq_quantmap__44c1_s_p4_0[] = {
  138520. 7, 5, 3, 1, 0, 2, 4, 6,
  138521. 8,
  138522. };
  138523. static encode_aux_threshmatch _vq_auxt__44c1_s_p4_0 = {
  138524. _vq_quantthresh__44c1_s_p4_0,
  138525. _vq_quantmap__44c1_s_p4_0,
  138526. 9,
  138527. 9
  138528. };
  138529. static static_codebook _44c1_s_p4_0 = {
  138530. 2, 81,
  138531. _vq_lengthlist__44c1_s_p4_0,
  138532. 1, -531628032, 1611661312, 4, 0,
  138533. _vq_quantlist__44c1_s_p4_0,
  138534. NULL,
  138535. &_vq_auxt__44c1_s_p4_0,
  138536. NULL,
  138537. 0
  138538. };
  138539. static long _vq_quantlist__44c1_s_p5_0[] = {
  138540. 8,
  138541. 7,
  138542. 9,
  138543. 6,
  138544. 10,
  138545. 5,
  138546. 11,
  138547. 4,
  138548. 12,
  138549. 3,
  138550. 13,
  138551. 2,
  138552. 14,
  138553. 1,
  138554. 15,
  138555. 0,
  138556. 16,
  138557. };
  138558. static long _vq_lengthlist__44c1_s_p5_0[] = {
  138559. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  138560. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  138561. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  138562. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  138563. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  138564. 10,11,11,12,11, 0, 0, 0, 8, 8, 9, 9, 9,10,10,10,
  138565. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10, 9,10,
  138566. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  138567. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  138568. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  138569. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  138570. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  138571. 10,10,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  138572. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  138573. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13, 0, 0,
  138574. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  138575. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,14,14,
  138576. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  138577. 14,
  138578. };
  138579. static float _vq_quantthresh__44c1_s_p5_0[] = {
  138580. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138581. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138582. };
  138583. static long _vq_quantmap__44c1_s_p5_0[] = {
  138584. 15, 13, 11, 9, 7, 5, 3, 1,
  138585. 0, 2, 4, 6, 8, 10, 12, 14,
  138586. 16,
  138587. };
  138588. static encode_aux_threshmatch _vq_auxt__44c1_s_p5_0 = {
  138589. _vq_quantthresh__44c1_s_p5_0,
  138590. _vq_quantmap__44c1_s_p5_0,
  138591. 17,
  138592. 17
  138593. };
  138594. static static_codebook _44c1_s_p5_0 = {
  138595. 2, 289,
  138596. _vq_lengthlist__44c1_s_p5_0,
  138597. 1, -529530880, 1611661312, 5, 0,
  138598. _vq_quantlist__44c1_s_p5_0,
  138599. NULL,
  138600. &_vq_auxt__44c1_s_p5_0,
  138601. NULL,
  138602. 0
  138603. };
  138604. static long _vq_quantlist__44c1_s_p6_0[] = {
  138605. 1,
  138606. 0,
  138607. 2,
  138608. };
  138609. static long _vq_lengthlist__44c1_s_p6_0[] = {
  138610. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  138611. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 6,10,10,11,11,
  138612. 11,11,10,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  138613. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 7,
  138614. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,12,10,
  138615. 11,
  138616. };
  138617. static float _vq_quantthresh__44c1_s_p6_0[] = {
  138618. -5.5, 5.5,
  138619. };
  138620. static long _vq_quantmap__44c1_s_p6_0[] = {
  138621. 1, 0, 2,
  138622. };
  138623. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_0 = {
  138624. _vq_quantthresh__44c1_s_p6_0,
  138625. _vq_quantmap__44c1_s_p6_0,
  138626. 3,
  138627. 3
  138628. };
  138629. static static_codebook _44c1_s_p6_0 = {
  138630. 4, 81,
  138631. _vq_lengthlist__44c1_s_p6_0,
  138632. 1, -529137664, 1618345984, 2, 0,
  138633. _vq_quantlist__44c1_s_p6_0,
  138634. NULL,
  138635. &_vq_auxt__44c1_s_p6_0,
  138636. NULL,
  138637. 0
  138638. };
  138639. static long _vq_quantlist__44c1_s_p6_1[] = {
  138640. 5,
  138641. 4,
  138642. 6,
  138643. 3,
  138644. 7,
  138645. 2,
  138646. 8,
  138647. 1,
  138648. 9,
  138649. 0,
  138650. 10,
  138651. };
  138652. static long _vq_lengthlist__44c1_s_p6_1[] = {
  138653. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  138654. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  138655. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  138656. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  138657. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  138658. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  138659. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  138660. 10,10,10, 8, 8, 8, 8, 8, 8,
  138661. };
  138662. static float _vq_quantthresh__44c1_s_p6_1[] = {
  138663. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  138664. 3.5, 4.5,
  138665. };
  138666. static long _vq_quantmap__44c1_s_p6_1[] = {
  138667. 9, 7, 5, 3, 1, 0, 2, 4,
  138668. 6, 8, 10,
  138669. };
  138670. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_1 = {
  138671. _vq_quantthresh__44c1_s_p6_1,
  138672. _vq_quantmap__44c1_s_p6_1,
  138673. 11,
  138674. 11
  138675. };
  138676. static static_codebook _44c1_s_p6_1 = {
  138677. 2, 121,
  138678. _vq_lengthlist__44c1_s_p6_1,
  138679. 1, -531365888, 1611661312, 4, 0,
  138680. _vq_quantlist__44c1_s_p6_1,
  138681. NULL,
  138682. &_vq_auxt__44c1_s_p6_1,
  138683. NULL,
  138684. 0
  138685. };
  138686. static long _vq_quantlist__44c1_s_p7_0[] = {
  138687. 6,
  138688. 5,
  138689. 7,
  138690. 4,
  138691. 8,
  138692. 3,
  138693. 9,
  138694. 2,
  138695. 10,
  138696. 1,
  138697. 11,
  138698. 0,
  138699. 12,
  138700. };
  138701. static long _vq_lengthlist__44c1_s_p7_0[] = {
  138702. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 9, 7, 5, 6,
  138703. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  138704. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  138705. 10,10,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  138706. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,11, 0,13,
  138707. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  138708. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10,10, 9,11,
  138709. 11,12,11,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  138710. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  138711. 0, 0, 0, 0,11,12,11,11,12,12,14,13, 0, 0, 0, 0,
  138712. 0,12,11,11,11,13,10,14,13,
  138713. };
  138714. static float _vq_quantthresh__44c1_s_p7_0[] = {
  138715. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  138716. 12.5, 17.5, 22.5, 27.5,
  138717. };
  138718. static long _vq_quantmap__44c1_s_p7_0[] = {
  138719. 11, 9, 7, 5, 3, 1, 0, 2,
  138720. 4, 6, 8, 10, 12,
  138721. };
  138722. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_0 = {
  138723. _vq_quantthresh__44c1_s_p7_0,
  138724. _vq_quantmap__44c1_s_p7_0,
  138725. 13,
  138726. 13
  138727. };
  138728. static static_codebook _44c1_s_p7_0 = {
  138729. 2, 169,
  138730. _vq_lengthlist__44c1_s_p7_0,
  138731. 1, -526516224, 1616117760, 4, 0,
  138732. _vq_quantlist__44c1_s_p7_0,
  138733. NULL,
  138734. &_vq_auxt__44c1_s_p7_0,
  138735. NULL,
  138736. 0
  138737. };
  138738. static long _vq_quantlist__44c1_s_p7_1[] = {
  138739. 2,
  138740. 1,
  138741. 3,
  138742. 0,
  138743. 4,
  138744. };
  138745. static long _vq_lengthlist__44c1_s_p7_1[] = {
  138746. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  138747. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  138748. };
  138749. static float _vq_quantthresh__44c1_s_p7_1[] = {
  138750. -1.5, -0.5, 0.5, 1.5,
  138751. };
  138752. static long _vq_quantmap__44c1_s_p7_1[] = {
  138753. 3, 1, 0, 2, 4,
  138754. };
  138755. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_1 = {
  138756. _vq_quantthresh__44c1_s_p7_1,
  138757. _vq_quantmap__44c1_s_p7_1,
  138758. 5,
  138759. 5
  138760. };
  138761. static static_codebook _44c1_s_p7_1 = {
  138762. 2, 25,
  138763. _vq_lengthlist__44c1_s_p7_1,
  138764. 1, -533725184, 1611661312, 3, 0,
  138765. _vq_quantlist__44c1_s_p7_1,
  138766. NULL,
  138767. &_vq_auxt__44c1_s_p7_1,
  138768. NULL,
  138769. 0
  138770. };
  138771. static long _vq_quantlist__44c1_s_p8_0[] = {
  138772. 6,
  138773. 5,
  138774. 7,
  138775. 4,
  138776. 8,
  138777. 3,
  138778. 9,
  138779. 2,
  138780. 10,
  138781. 1,
  138782. 11,
  138783. 0,
  138784. 12,
  138785. };
  138786. static long _vq_lengthlist__44c1_s_p8_0[] = {
  138787. 1, 4, 3,10,10,10,10,10,10,10,10,10,10, 4, 8, 6,
  138788. 10,10,10,10,10,10,10,10,10,10, 4, 8, 7,10,10,10,
  138789. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138790. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138791. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138792. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138793. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138794. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138795. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138796. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138797. 10,10,10,10,10,10,10,10,10,
  138798. };
  138799. static float _vq_quantthresh__44c1_s_p8_0[] = {
  138800. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  138801. 552.5, 773.5, 994.5, 1215.5,
  138802. };
  138803. static long _vq_quantmap__44c1_s_p8_0[] = {
  138804. 11, 9, 7, 5, 3, 1, 0, 2,
  138805. 4, 6, 8, 10, 12,
  138806. };
  138807. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_0 = {
  138808. _vq_quantthresh__44c1_s_p8_0,
  138809. _vq_quantmap__44c1_s_p8_0,
  138810. 13,
  138811. 13
  138812. };
  138813. static static_codebook _44c1_s_p8_0 = {
  138814. 2, 169,
  138815. _vq_lengthlist__44c1_s_p8_0,
  138816. 1, -514541568, 1627103232, 4, 0,
  138817. _vq_quantlist__44c1_s_p8_0,
  138818. NULL,
  138819. &_vq_auxt__44c1_s_p8_0,
  138820. NULL,
  138821. 0
  138822. };
  138823. static long _vq_quantlist__44c1_s_p8_1[] = {
  138824. 6,
  138825. 5,
  138826. 7,
  138827. 4,
  138828. 8,
  138829. 3,
  138830. 9,
  138831. 2,
  138832. 10,
  138833. 1,
  138834. 11,
  138835. 0,
  138836. 12,
  138837. };
  138838. static long _vq_lengthlist__44c1_s_p8_1[] = {
  138839. 1, 4, 4, 6, 5, 7, 7, 9, 9,10,10,12,12, 6, 5, 5,
  138840. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  138841. 8,10,10,11,11,12,12,15, 7, 7, 8, 8, 9, 9,11,11,
  138842. 12,12,13,12,15, 8, 8, 8, 7, 9, 9,10,10,12,12,13,
  138843. 13,16,11,10, 8, 8,10,10,11,11,12,12,13,13,16,11,
  138844. 11, 9, 8,11,10,11,11,12,12,13,12,16,16,16,10,11,
  138845. 10,11,12,12,12,12,13,13,16,16,16,11, 9,11, 9,14,
  138846. 12,12,12,13,13,16,16,16,12,14,11,12,12,12,13,13,
  138847. 14,13,16,16,16,15,13,12,10,13,10,13,14,13,13,16,
  138848. 16,16,16,16,13,14,12,13,13,12,13,13,16,16,16,16,
  138849. 16,13,12,12,11,14,12,15,13,
  138850. };
  138851. static float _vq_quantthresh__44c1_s_p8_1[] = {
  138852. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  138853. 42.5, 59.5, 76.5, 93.5,
  138854. };
  138855. static long _vq_quantmap__44c1_s_p8_1[] = {
  138856. 11, 9, 7, 5, 3, 1, 0, 2,
  138857. 4, 6, 8, 10, 12,
  138858. };
  138859. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_1 = {
  138860. _vq_quantthresh__44c1_s_p8_1,
  138861. _vq_quantmap__44c1_s_p8_1,
  138862. 13,
  138863. 13
  138864. };
  138865. static static_codebook _44c1_s_p8_1 = {
  138866. 2, 169,
  138867. _vq_lengthlist__44c1_s_p8_1,
  138868. 1, -522616832, 1620115456, 4, 0,
  138869. _vq_quantlist__44c1_s_p8_1,
  138870. NULL,
  138871. &_vq_auxt__44c1_s_p8_1,
  138872. NULL,
  138873. 0
  138874. };
  138875. static long _vq_quantlist__44c1_s_p8_2[] = {
  138876. 8,
  138877. 7,
  138878. 9,
  138879. 6,
  138880. 10,
  138881. 5,
  138882. 11,
  138883. 4,
  138884. 12,
  138885. 3,
  138886. 13,
  138887. 2,
  138888. 14,
  138889. 1,
  138890. 15,
  138891. 0,
  138892. 16,
  138893. };
  138894. static long _vq_lengthlist__44c1_s_p8_2[] = {
  138895. 2, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  138896. 8,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  138897. 9, 9,10,10,10, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  138898. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  138899. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  138900. 9,10, 9, 9,10,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  138901. 9, 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  138902. 9, 9, 9, 9, 9,10,10,11,11,11, 8, 8, 9, 9, 9, 9,
  138903. 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11, 8, 8, 9,
  138904. 9, 9, 9,10, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  138905. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 9,
  138906. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  138907. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10,11,11,
  138908. 11,11,11, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,10,11,11,
  138909. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  138910. 11,11,11,11,11, 9,10, 9, 9, 9, 9,10, 9, 9, 9,11,
  138911. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  138912. 11,11,10,11,11,11,11,10,11, 9, 9, 9, 9, 9, 9, 9,
  138913. 9,
  138914. };
  138915. static float _vq_quantthresh__44c1_s_p8_2[] = {
  138916. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138917. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138918. };
  138919. static long _vq_quantmap__44c1_s_p8_2[] = {
  138920. 15, 13, 11, 9, 7, 5, 3, 1,
  138921. 0, 2, 4, 6, 8, 10, 12, 14,
  138922. 16,
  138923. };
  138924. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_2 = {
  138925. _vq_quantthresh__44c1_s_p8_2,
  138926. _vq_quantmap__44c1_s_p8_2,
  138927. 17,
  138928. 17
  138929. };
  138930. static static_codebook _44c1_s_p8_2 = {
  138931. 2, 289,
  138932. _vq_lengthlist__44c1_s_p8_2,
  138933. 1, -529530880, 1611661312, 5, 0,
  138934. _vq_quantlist__44c1_s_p8_2,
  138935. NULL,
  138936. &_vq_auxt__44c1_s_p8_2,
  138937. NULL,
  138938. 0
  138939. };
  138940. static long _huff_lengthlist__44c1_s_short[] = {
  138941. 6, 8,13,12,13,14,15,16,16, 4, 2, 4, 7, 6, 8,11,
  138942. 13,15,10, 4, 4, 8, 6, 8,11,14,17,11, 5, 6, 5, 6,
  138943. 8,12,14,17,11, 5, 5, 6, 5, 7,10,13,16,12, 6, 7,
  138944. 8, 7, 8,10,13,15,13, 8, 8, 7, 7, 8,10,12,15,15,
  138945. 7, 7, 5, 5, 7, 9,12,14,15, 8, 8, 6, 6, 7, 8,10,
  138946. 11,
  138947. };
  138948. static static_codebook _huff_book__44c1_s_short = {
  138949. 2, 81,
  138950. _huff_lengthlist__44c1_s_short,
  138951. 0, 0, 0, 0, 0,
  138952. NULL,
  138953. NULL,
  138954. NULL,
  138955. NULL,
  138956. 0
  138957. };
  138958. static long _huff_lengthlist__44c1_sm_long[] = {
  138959. 5, 4, 8,10, 9, 9,10,11,12, 4, 2, 5, 6, 6, 8,10,
  138960. 11,13, 8, 4, 6, 8, 7, 9,12,12,14,10, 6, 8, 4, 5,
  138961. 6, 9,11,12, 9, 5, 6, 5, 5, 6, 9,11,11, 9, 7, 9,
  138962. 6, 5, 5, 7,10,10,10, 9,11, 8, 7, 6, 7, 9,11,11,
  138963. 12,13,10,10, 9, 8, 9,11,11,15,15,12,13,11, 9,10,
  138964. 11,
  138965. };
  138966. static static_codebook _huff_book__44c1_sm_long = {
  138967. 2, 81,
  138968. _huff_lengthlist__44c1_sm_long,
  138969. 0, 0, 0, 0, 0,
  138970. NULL,
  138971. NULL,
  138972. NULL,
  138973. NULL,
  138974. 0
  138975. };
  138976. static long _vq_quantlist__44c1_sm_p1_0[] = {
  138977. 1,
  138978. 0,
  138979. 2,
  138980. };
  138981. static long _vq_lengthlist__44c1_sm_p1_0[] = {
  138982. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  138983. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138987. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  138988. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138992. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  138993. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 7, 0, 0, 0, 0,
  139028. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  139029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  139033. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  139034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  139038. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  139039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  139074. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  139079. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  139084. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  139085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139392. 0,
  139393. };
  139394. static float _vq_quantthresh__44c1_sm_p1_0[] = {
  139395. -0.5, 0.5,
  139396. };
  139397. static long _vq_quantmap__44c1_sm_p1_0[] = {
  139398. 1, 0, 2,
  139399. };
  139400. static encode_aux_threshmatch _vq_auxt__44c1_sm_p1_0 = {
  139401. _vq_quantthresh__44c1_sm_p1_0,
  139402. _vq_quantmap__44c1_sm_p1_0,
  139403. 3,
  139404. 3
  139405. };
  139406. static static_codebook _44c1_sm_p1_0 = {
  139407. 8, 6561,
  139408. _vq_lengthlist__44c1_sm_p1_0,
  139409. 1, -535822336, 1611661312, 2, 0,
  139410. _vq_quantlist__44c1_sm_p1_0,
  139411. NULL,
  139412. &_vq_auxt__44c1_sm_p1_0,
  139413. NULL,
  139414. 0
  139415. };
  139416. static long _vq_quantlist__44c1_sm_p2_0[] = {
  139417. 2,
  139418. 1,
  139419. 3,
  139420. 0,
  139421. 4,
  139422. };
  139423. static long _vq_lengthlist__44c1_sm_p2_0[] = {
  139424. 2, 3, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  139426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139427. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  139429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139430. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  139431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139463. 0,
  139464. };
  139465. static float _vq_quantthresh__44c1_sm_p2_0[] = {
  139466. -1.5, -0.5, 0.5, 1.5,
  139467. };
  139468. static long _vq_quantmap__44c1_sm_p2_0[] = {
  139469. 3, 1, 0, 2, 4,
  139470. };
  139471. static encode_aux_threshmatch _vq_auxt__44c1_sm_p2_0 = {
  139472. _vq_quantthresh__44c1_sm_p2_0,
  139473. _vq_quantmap__44c1_sm_p2_0,
  139474. 5,
  139475. 5
  139476. };
  139477. static static_codebook _44c1_sm_p2_0 = {
  139478. 4, 625,
  139479. _vq_lengthlist__44c1_sm_p2_0,
  139480. 1, -533725184, 1611661312, 3, 0,
  139481. _vq_quantlist__44c1_sm_p2_0,
  139482. NULL,
  139483. &_vq_auxt__44c1_sm_p2_0,
  139484. NULL,
  139485. 0
  139486. };
  139487. static long _vq_quantlist__44c1_sm_p3_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_p3_0[] = {
  139499. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 5, 6, 6, 0, 0,
  139500. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 7, 7, 7, 7,
  139501. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  139502. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  139503. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139504. 0,
  139505. };
  139506. static float _vq_quantthresh__44c1_sm_p3_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_p3_0[] = {
  139510. 7, 5, 3, 1, 0, 2, 4, 6,
  139511. 8,
  139512. };
  139513. static encode_aux_threshmatch _vq_auxt__44c1_sm_p3_0 = {
  139514. _vq_quantthresh__44c1_sm_p3_0,
  139515. _vq_quantmap__44c1_sm_p3_0,
  139516. 9,
  139517. 9
  139518. };
  139519. static static_codebook _44c1_sm_p3_0 = {
  139520. 2, 81,
  139521. _vq_lengthlist__44c1_sm_p3_0,
  139522. 1, -531628032, 1611661312, 4, 0,
  139523. _vq_quantlist__44c1_sm_p3_0,
  139524. NULL,
  139525. &_vq_auxt__44c1_sm_p3_0,
  139526. NULL,
  139527. 0
  139528. };
  139529. static long _vq_quantlist__44c1_sm_p4_0[] = {
  139530. 4,
  139531. 3,
  139532. 5,
  139533. 2,
  139534. 6,
  139535. 1,
  139536. 7,
  139537. 0,
  139538. 8,
  139539. };
  139540. static long _vq_lengthlist__44c1_sm_p4_0[] = {
  139541. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7, 8, 8,
  139542. 9, 9, 0, 6, 6, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  139543. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  139544. 8, 8, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  139545. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  139546. 11,
  139547. };
  139548. static float _vq_quantthresh__44c1_sm_p4_0[] = {
  139549. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139550. };
  139551. static long _vq_quantmap__44c1_sm_p4_0[] = {
  139552. 7, 5, 3, 1, 0, 2, 4, 6,
  139553. 8,
  139554. };
  139555. static encode_aux_threshmatch _vq_auxt__44c1_sm_p4_0 = {
  139556. _vq_quantthresh__44c1_sm_p4_0,
  139557. _vq_quantmap__44c1_sm_p4_0,
  139558. 9,
  139559. 9
  139560. };
  139561. static static_codebook _44c1_sm_p4_0 = {
  139562. 2, 81,
  139563. _vq_lengthlist__44c1_sm_p4_0,
  139564. 1, -531628032, 1611661312, 4, 0,
  139565. _vq_quantlist__44c1_sm_p4_0,
  139566. NULL,
  139567. &_vq_auxt__44c1_sm_p4_0,
  139568. NULL,
  139569. 0
  139570. };
  139571. static long _vq_quantlist__44c1_sm_p5_0[] = {
  139572. 8,
  139573. 7,
  139574. 9,
  139575. 6,
  139576. 10,
  139577. 5,
  139578. 11,
  139579. 4,
  139580. 12,
  139581. 3,
  139582. 13,
  139583. 2,
  139584. 14,
  139585. 1,
  139586. 15,
  139587. 0,
  139588. 16,
  139589. };
  139590. static long _vq_lengthlist__44c1_sm_p5_0[] = {
  139591. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  139592. 11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  139593. 11,11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  139594. 10,11,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  139595. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  139596. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,10,
  139597. 10,11,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,
  139598. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  139599. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  139600. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  139601. 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  139602. 9, 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  139603. 9, 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  139604. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  139605. 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0, 0,
  139606. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  139607. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14,
  139608. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  139609. 14,
  139610. };
  139611. static float _vq_quantthresh__44c1_sm_p5_0[] = {
  139612. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139613. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139614. };
  139615. static long _vq_quantmap__44c1_sm_p5_0[] = {
  139616. 15, 13, 11, 9, 7, 5, 3, 1,
  139617. 0, 2, 4, 6, 8, 10, 12, 14,
  139618. 16,
  139619. };
  139620. static encode_aux_threshmatch _vq_auxt__44c1_sm_p5_0 = {
  139621. _vq_quantthresh__44c1_sm_p5_0,
  139622. _vq_quantmap__44c1_sm_p5_0,
  139623. 17,
  139624. 17
  139625. };
  139626. static static_codebook _44c1_sm_p5_0 = {
  139627. 2, 289,
  139628. _vq_lengthlist__44c1_sm_p5_0,
  139629. 1, -529530880, 1611661312, 5, 0,
  139630. _vq_quantlist__44c1_sm_p5_0,
  139631. NULL,
  139632. &_vq_auxt__44c1_sm_p5_0,
  139633. NULL,
  139634. 0
  139635. };
  139636. static long _vq_quantlist__44c1_sm_p6_0[] = {
  139637. 1,
  139638. 0,
  139639. 2,
  139640. };
  139641. static long _vq_lengthlist__44c1_sm_p6_0[] = {
  139642. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  139643. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  139644. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  139645. 11,10,11,11,10,10, 7,11,11,11,11,11,11,11,11, 6,
  139646. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,11,10,
  139647. 11,
  139648. };
  139649. static float _vq_quantthresh__44c1_sm_p6_0[] = {
  139650. -5.5, 5.5,
  139651. };
  139652. static long _vq_quantmap__44c1_sm_p6_0[] = {
  139653. 1, 0, 2,
  139654. };
  139655. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_0 = {
  139656. _vq_quantthresh__44c1_sm_p6_0,
  139657. _vq_quantmap__44c1_sm_p6_0,
  139658. 3,
  139659. 3
  139660. };
  139661. static static_codebook _44c1_sm_p6_0 = {
  139662. 4, 81,
  139663. _vq_lengthlist__44c1_sm_p6_0,
  139664. 1, -529137664, 1618345984, 2, 0,
  139665. _vq_quantlist__44c1_sm_p6_0,
  139666. NULL,
  139667. &_vq_auxt__44c1_sm_p6_0,
  139668. NULL,
  139669. 0
  139670. };
  139671. static long _vq_quantlist__44c1_sm_p6_1[] = {
  139672. 5,
  139673. 4,
  139674. 6,
  139675. 3,
  139676. 7,
  139677. 2,
  139678. 8,
  139679. 1,
  139680. 9,
  139681. 0,
  139682. 10,
  139683. };
  139684. static long _vq_lengthlist__44c1_sm_p6_1[] = {
  139685. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  139686. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  139687. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  139688. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  139689. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  139690. 8, 8, 8, 8, 8, 8, 9, 8,10,10,10,10,10, 8, 8, 8,
  139691. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  139692. 10,10,10, 8, 8, 8, 8, 8, 8,
  139693. };
  139694. static float _vq_quantthresh__44c1_sm_p6_1[] = {
  139695. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  139696. 3.5, 4.5,
  139697. };
  139698. static long _vq_quantmap__44c1_sm_p6_1[] = {
  139699. 9, 7, 5, 3, 1, 0, 2, 4,
  139700. 6, 8, 10,
  139701. };
  139702. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_1 = {
  139703. _vq_quantthresh__44c1_sm_p6_1,
  139704. _vq_quantmap__44c1_sm_p6_1,
  139705. 11,
  139706. 11
  139707. };
  139708. static static_codebook _44c1_sm_p6_1 = {
  139709. 2, 121,
  139710. _vq_lengthlist__44c1_sm_p6_1,
  139711. 1, -531365888, 1611661312, 4, 0,
  139712. _vq_quantlist__44c1_sm_p6_1,
  139713. NULL,
  139714. &_vq_auxt__44c1_sm_p6_1,
  139715. NULL,
  139716. 0
  139717. };
  139718. static long _vq_quantlist__44c1_sm_p7_0[] = {
  139719. 6,
  139720. 5,
  139721. 7,
  139722. 4,
  139723. 8,
  139724. 3,
  139725. 9,
  139726. 2,
  139727. 10,
  139728. 1,
  139729. 11,
  139730. 0,
  139731. 12,
  139732. };
  139733. static long _vq_lengthlist__44c1_sm_p7_0[] = {
  139734. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  139735. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  139736. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  139737. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  139738. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  139739. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0, 9,10,
  139740. 9,10,11,11,12,11,13,12, 0, 0, 0,10,10, 9, 9,11,
  139741. 11,12,12,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  139742. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  139743. 0, 0, 0, 0,11,12,11,11,12,13,14,13, 0, 0, 0, 0,
  139744. 0,12,12,11,11,13,12,14,13,
  139745. };
  139746. static float _vq_quantthresh__44c1_sm_p7_0[] = {
  139747. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  139748. 12.5, 17.5, 22.5, 27.5,
  139749. };
  139750. static long _vq_quantmap__44c1_sm_p7_0[] = {
  139751. 11, 9, 7, 5, 3, 1, 0, 2,
  139752. 4, 6, 8, 10, 12,
  139753. };
  139754. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_0 = {
  139755. _vq_quantthresh__44c1_sm_p7_0,
  139756. _vq_quantmap__44c1_sm_p7_0,
  139757. 13,
  139758. 13
  139759. };
  139760. static static_codebook _44c1_sm_p7_0 = {
  139761. 2, 169,
  139762. _vq_lengthlist__44c1_sm_p7_0,
  139763. 1, -526516224, 1616117760, 4, 0,
  139764. _vq_quantlist__44c1_sm_p7_0,
  139765. NULL,
  139766. &_vq_auxt__44c1_sm_p7_0,
  139767. NULL,
  139768. 0
  139769. };
  139770. static long _vq_quantlist__44c1_sm_p7_1[] = {
  139771. 2,
  139772. 1,
  139773. 3,
  139774. 0,
  139775. 4,
  139776. };
  139777. static long _vq_lengthlist__44c1_sm_p7_1[] = {
  139778. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  139779. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  139780. };
  139781. static float _vq_quantthresh__44c1_sm_p7_1[] = {
  139782. -1.5, -0.5, 0.5, 1.5,
  139783. };
  139784. static long _vq_quantmap__44c1_sm_p7_1[] = {
  139785. 3, 1, 0, 2, 4,
  139786. };
  139787. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_1 = {
  139788. _vq_quantthresh__44c1_sm_p7_1,
  139789. _vq_quantmap__44c1_sm_p7_1,
  139790. 5,
  139791. 5
  139792. };
  139793. static static_codebook _44c1_sm_p7_1 = {
  139794. 2, 25,
  139795. _vq_lengthlist__44c1_sm_p7_1,
  139796. 1, -533725184, 1611661312, 3, 0,
  139797. _vq_quantlist__44c1_sm_p7_1,
  139798. NULL,
  139799. &_vq_auxt__44c1_sm_p7_1,
  139800. NULL,
  139801. 0
  139802. };
  139803. static long _vq_quantlist__44c1_sm_p8_0[] = {
  139804. 6,
  139805. 5,
  139806. 7,
  139807. 4,
  139808. 8,
  139809. 3,
  139810. 9,
  139811. 2,
  139812. 10,
  139813. 1,
  139814. 11,
  139815. 0,
  139816. 12,
  139817. };
  139818. static long _vq_lengthlist__44c1_sm_p8_0[] = {
  139819. 1, 3, 3,13,13,13,13,13,13,13,13,13,13, 3, 6, 6,
  139820. 13,13,13,13,13,13,13,13,13,13, 4, 8, 7,13,13,13,
  139821. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139822. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139823. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139824. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139825. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139826. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139827. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139828. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139829. 13,13,13,13,13,13,13,13,13,
  139830. };
  139831. static float _vq_quantthresh__44c1_sm_p8_0[] = {
  139832. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  139833. 552.5, 773.5, 994.5, 1215.5,
  139834. };
  139835. static long _vq_quantmap__44c1_sm_p8_0[] = {
  139836. 11, 9, 7, 5, 3, 1, 0, 2,
  139837. 4, 6, 8, 10, 12,
  139838. };
  139839. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_0 = {
  139840. _vq_quantthresh__44c1_sm_p8_0,
  139841. _vq_quantmap__44c1_sm_p8_0,
  139842. 13,
  139843. 13
  139844. };
  139845. static static_codebook _44c1_sm_p8_0 = {
  139846. 2, 169,
  139847. _vq_lengthlist__44c1_sm_p8_0,
  139848. 1, -514541568, 1627103232, 4, 0,
  139849. _vq_quantlist__44c1_sm_p8_0,
  139850. NULL,
  139851. &_vq_auxt__44c1_sm_p8_0,
  139852. NULL,
  139853. 0
  139854. };
  139855. static long _vq_quantlist__44c1_sm_p8_1[] = {
  139856. 6,
  139857. 5,
  139858. 7,
  139859. 4,
  139860. 8,
  139861. 3,
  139862. 9,
  139863. 2,
  139864. 10,
  139865. 1,
  139866. 11,
  139867. 0,
  139868. 12,
  139869. };
  139870. static long _vq_lengthlist__44c1_sm_p8_1[] = {
  139871. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  139872. 7, 7, 8, 7,10,10,11,11,12,12, 6, 5, 5, 7, 7, 8,
  139873. 8,10,10,11,11,12,12,16, 7, 7, 8, 8, 9, 9,11,11,
  139874. 12,12,13,13,17, 7, 7, 8, 7, 9, 9,11,10,12,12,13,
  139875. 13,19,11,10, 8, 8,10,10,11,11,12,12,13,13,19,11,
  139876. 11, 9, 7,11,10,11,11,12,12,13,12,19,19,19,10,10,
  139877. 10,10,11,12,12,12,13,14,18,19,19,11, 9,11, 9,13,
  139878. 12,12,12,13,13,19,20,19,13,15,11,11,12,12,13,13,
  139879. 14,13,18,19,20,15,13,12,10,13,10,13,13,13,14,20,
  139880. 20,20,20,20,13,14,12,12,13,12,13,13,20,20,20,20,
  139881. 20,13,12,12,12,14,12,14,13,
  139882. };
  139883. static float _vq_quantthresh__44c1_sm_p8_1[] = {
  139884. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  139885. 42.5, 59.5, 76.5, 93.5,
  139886. };
  139887. static long _vq_quantmap__44c1_sm_p8_1[] = {
  139888. 11, 9, 7, 5, 3, 1, 0, 2,
  139889. 4, 6, 8, 10, 12,
  139890. };
  139891. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_1 = {
  139892. _vq_quantthresh__44c1_sm_p8_1,
  139893. _vq_quantmap__44c1_sm_p8_1,
  139894. 13,
  139895. 13
  139896. };
  139897. static static_codebook _44c1_sm_p8_1 = {
  139898. 2, 169,
  139899. _vq_lengthlist__44c1_sm_p8_1,
  139900. 1, -522616832, 1620115456, 4, 0,
  139901. _vq_quantlist__44c1_sm_p8_1,
  139902. NULL,
  139903. &_vq_auxt__44c1_sm_p8_1,
  139904. NULL,
  139905. 0
  139906. };
  139907. static long _vq_quantlist__44c1_sm_p8_2[] = {
  139908. 8,
  139909. 7,
  139910. 9,
  139911. 6,
  139912. 10,
  139913. 5,
  139914. 11,
  139915. 4,
  139916. 12,
  139917. 3,
  139918. 13,
  139919. 2,
  139920. 14,
  139921. 1,
  139922. 15,
  139923. 0,
  139924. 16,
  139925. };
  139926. static long _vq_lengthlist__44c1_sm_p8_2[] = {
  139927. 2, 5, 5, 6, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  139928. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  139929. 9, 9,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  139930. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  139931. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  139932. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  139933. 9, 9,10,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  139934. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  139935. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 8, 8, 9,
  139936. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  139937. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,11,11,11, 9,
  139938. 8, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,10,11,11,
  139939. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,11,
  139940. 11,11,11, 9, 9,10, 9, 9, 9, 9,10, 9,10,10,11,10,
  139941. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  139942. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,
  139943. 11,10,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  139944. 10,11,10,11,11,11,11,11,11, 9, 9,10, 9, 9, 9, 9,
  139945. 9,
  139946. };
  139947. static float _vq_quantthresh__44c1_sm_p8_2[] = {
  139948. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139949. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139950. };
  139951. static long _vq_quantmap__44c1_sm_p8_2[] = {
  139952. 15, 13, 11, 9, 7, 5, 3, 1,
  139953. 0, 2, 4, 6, 8, 10, 12, 14,
  139954. 16,
  139955. };
  139956. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_2 = {
  139957. _vq_quantthresh__44c1_sm_p8_2,
  139958. _vq_quantmap__44c1_sm_p8_2,
  139959. 17,
  139960. 17
  139961. };
  139962. static static_codebook _44c1_sm_p8_2 = {
  139963. 2, 289,
  139964. _vq_lengthlist__44c1_sm_p8_2,
  139965. 1, -529530880, 1611661312, 5, 0,
  139966. _vq_quantlist__44c1_sm_p8_2,
  139967. NULL,
  139968. &_vq_auxt__44c1_sm_p8_2,
  139969. NULL,
  139970. 0
  139971. };
  139972. static long _huff_lengthlist__44c1_sm_short[] = {
  139973. 4, 7,13,14,14,15,16,18,18, 4, 2, 5, 8, 7, 9,12,
  139974. 15,15,10, 4, 5,10, 6, 8,11,15,17,12, 5, 7, 5, 6,
  139975. 8,11,14,17,11, 5, 6, 6, 5, 6, 9,13,17,12, 6, 7,
  139976. 6, 5, 6, 8,12,14,14, 7, 8, 6, 6, 7, 9,11,14,14,
  139977. 8, 9, 6, 5, 6, 9,11,13,16,10,10, 7, 6, 7, 8,10,
  139978. 11,
  139979. };
  139980. static static_codebook _huff_book__44c1_sm_short = {
  139981. 2, 81,
  139982. _huff_lengthlist__44c1_sm_short,
  139983. 0, 0, 0, 0, 0,
  139984. NULL,
  139985. NULL,
  139986. NULL,
  139987. NULL,
  139988. 0
  139989. };
  139990. static long _huff_lengthlist__44cn1_s_long[] = {
  139991. 4, 4, 7, 8, 7, 8,10,12,17, 3, 1, 6, 6, 7, 8,10,
  139992. 12,15, 7, 6, 9, 9, 9,11,12,14,17, 8, 6, 9, 6, 7,
  139993. 9,11,13,17, 7, 6, 9, 7, 7, 8, 9,12,15, 8, 8,10,
  139994. 8, 7, 7, 7,10,14, 9,10,12,10, 8, 8, 8,10,14,11,
  139995. 13,15,13,12,11,11,12,16,17,18,18,19,20,18,16,16,
  139996. 20,
  139997. };
  139998. static static_codebook _huff_book__44cn1_s_long = {
  139999. 2, 81,
  140000. _huff_lengthlist__44cn1_s_long,
  140001. 0, 0, 0, 0, 0,
  140002. NULL,
  140003. NULL,
  140004. NULL,
  140005. NULL,
  140006. 0
  140007. };
  140008. static long _vq_quantlist__44cn1_s_p1_0[] = {
  140009. 1,
  140010. 0,
  140011. 2,
  140012. };
  140013. static long _vq_lengthlist__44cn1_s_p1_0[] = {
  140014. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  140015. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140019. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  140020. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140024. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0,
  140025. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 8, 0, 0, 0, 0,
  140060. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0,
  140061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0, 0,
  140065. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  140066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0,
  140070. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0,10,11,11,
  140071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  140106. 0, 0, 0, 0, 8,10,10, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  140111. 0, 0, 0, 0, 0, 9, 9,11, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11,
  140116. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  140117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140424. 0,
  140425. };
  140426. static float _vq_quantthresh__44cn1_s_p1_0[] = {
  140427. -0.5, 0.5,
  140428. };
  140429. static long _vq_quantmap__44cn1_s_p1_0[] = {
  140430. 1, 0, 2,
  140431. };
  140432. static encode_aux_threshmatch _vq_auxt__44cn1_s_p1_0 = {
  140433. _vq_quantthresh__44cn1_s_p1_0,
  140434. _vq_quantmap__44cn1_s_p1_0,
  140435. 3,
  140436. 3
  140437. };
  140438. static static_codebook _44cn1_s_p1_0 = {
  140439. 8, 6561,
  140440. _vq_lengthlist__44cn1_s_p1_0,
  140441. 1, -535822336, 1611661312, 2, 0,
  140442. _vq_quantlist__44cn1_s_p1_0,
  140443. NULL,
  140444. &_vq_auxt__44cn1_s_p1_0,
  140445. NULL,
  140446. 0
  140447. };
  140448. static long _vq_quantlist__44cn1_s_p2_0[] = {
  140449. 2,
  140450. 1,
  140451. 3,
  140452. 0,
  140453. 4,
  140454. };
  140455. static long _vq_lengthlist__44cn1_s_p2_0[] = {
  140456. 1, 4, 4, 7, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  140458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140459. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  140461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140462. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  140463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140495. 0,
  140496. };
  140497. static float _vq_quantthresh__44cn1_s_p2_0[] = {
  140498. -1.5, -0.5, 0.5, 1.5,
  140499. };
  140500. static long _vq_quantmap__44cn1_s_p2_0[] = {
  140501. 3, 1, 0, 2, 4,
  140502. };
  140503. static encode_aux_threshmatch _vq_auxt__44cn1_s_p2_0 = {
  140504. _vq_quantthresh__44cn1_s_p2_0,
  140505. _vq_quantmap__44cn1_s_p2_0,
  140506. 5,
  140507. 5
  140508. };
  140509. static static_codebook _44cn1_s_p2_0 = {
  140510. 4, 625,
  140511. _vq_lengthlist__44cn1_s_p2_0,
  140512. 1, -533725184, 1611661312, 3, 0,
  140513. _vq_quantlist__44cn1_s_p2_0,
  140514. NULL,
  140515. &_vq_auxt__44cn1_s_p2_0,
  140516. NULL,
  140517. 0
  140518. };
  140519. static long _vq_quantlist__44cn1_s_p3_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_p3_0[] = {
  140531. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  140532. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  140533. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  140534. 9, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  140535. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140536. 0,
  140537. };
  140538. static float _vq_quantthresh__44cn1_s_p3_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_p3_0[] = {
  140542. 7, 5, 3, 1, 0, 2, 4, 6,
  140543. 8,
  140544. };
  140545. static encode_aux_threshmatch _vq_auxt__44cn1_s_p3_0 = {
  140546. _vq_quantthresh__44cn1_s_p3_0,
  140547. _vq_quantmap__44cn1_s_p3_0,
  140548. 9,
  140549. 9
  140550. };
  140551. static static_codebook _44cn1_s_p3_0 = {
  140552. 2, 81,
  140553. _vq_lengthlist__44cn1_s_p3_0,
  140554. 1, -531628032, 1611661312, 4, 0,
  140555. _vq_quantlist__44cn1_s_p3_0,
  140556. NULL,
  140557. &_vq_auxt__44cn1_s_p3_0,
  140558. NULL,
  140559. 0
  140560. };
  140561. static long _vq_quantlist__44cn1_s_p4_0[] = {
  140562. 4,
  140563. 3,
  140564. 5,
  140565. 2,
  140566. 6,
  140567. 1,
  140568. 7,
  140569. 0,
  140570. 8,
  140571. };
  140572. static long _vq_lengthlist__44cn1_s_p4_0[] = {
  140573. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  140574. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  140575. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  140576. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  140577. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  140578. 11,
  140579. };
  140580. static float _vq_quantthresh__44cn1_s_p4_0[] = {
  140581. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140582. };
  140583. static long _vq_quantmap__44cn1_s_p4_0[] = {
  140584. 7, 5, 3, 1, 0, 2, 4, 6,
  140585. 8,
  140586. };
  140587. static encode_aux_threshmatch _vq_auxt__44cn1_s_p4_0 = {
  140588. _vq_quantthresh__44cn1_s_p4_0,
  140589. _vq_quantmap__44cn1_s_p4_0,
  140590. 9,
  140591. 9
  140592. };
  140593. static static_codebook _44cn1_s_p4_0 = {
  140594. 2, 81,
  140595. _vq_lengthlist__44cn1_s_p4_0,
  140596. 1, -531628032, 1611661312, 4, 0,
  140597. _vq_quantlist__44cn1_s_p4_0,
  140598. NULL,
  140599. &_vq_auxt__44cn1_s_p4_0,
  140600. NULL,
  140601. 0
  140602. };
  140603. static long _vq_quantlist__44cn1_s_p5_0[] = {
  140604. 8,
  140605. 7,
  140606. 9,
  140607. 6,
  140608. 10,
  140609. 5,
  140610. 11,
  140611. 4,
  140612. 12,
  140613. 3,
  140614. 13,
  140615. 2,
  140616. 14,
  140617. 1,
  140618. 15,
  140619. 0,
  140620. 16,
  140621. };
  140622. static long _vq_lengthlist__44cn1_s_p5_0[] = {
  140623. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  140624. 10, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  140625. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  140626. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  140627. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  140628. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  140629. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  140630. 10,10,11,11,11,12,12, 0, 0, 0, 9, 9,10, 9,10,10,
  140631. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  140632. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  140633. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  140634. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  140635. 10,10,11,10,11,11,11,12,13,12,13,13, 0, 0, 0, 0,
  140636. 0, 0, 0,11,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  140637. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  140638. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  140639. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,13,13,14,14,
  140640. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,12,13,13,14,
  140641. 14,
  140642. };
  140643. static float _vq_quantthresh__44cn1_s_p5_0[] = {
  140644. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140645. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140646. };
  140647. static long _vq_quantmap__44cn1_s_p5_0[] = {
  140648. 15, 13, 11, 9, 7, 5, 3, 1,
  140649. 0, 2, 4, 6, 8, 10, 12, 14,
  140650. 16,
  140651. };
  140652. static encode_aux_threshmatch _vq_auxt__44cn1_s_p5_0 = {
  140653. _vq_quantthresh__44cn1_s_p5_0,
  140654. _vq_quantmap__44cn1_s_p5_0,
  140655. 17,
  140656. 17
  140657. };
  140658. static static_codebook _44cn1_s_p5_0 = {
  140659. 2, 289,
  140660. _vq_lengthlist__44cn1_s_p5_0,
  140661. 1, -529530880, 1611661312, 5, 0,
  140662. _vq_quantlist__44cn1_s_p5_0,
  140663. NULL,
  140664. &_vq_auxt__44cn1_s_p5_0,
  140665. NULL,
  140666. 0
  140667. };
  140668. static long _vq_quantlist__44cn1_s_p6_0[] = {
  140669. 1,
  140670. 0,
  140671. 2,
  140672. };
  140673. static long _vq_lengthlist__44cn1_s_p6_0[] = {
  140674. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 6, 6,10, 9, 9,11,
  140675. 9, 9, 4, 6, 6,10, 9, 9,10, 9, 9, 7,10,10,11,11,
  140676. 11,12,11,11, 7, 9, 9,11,11,10,11,10,10, 7, 9, 9,
  140677. 11,10,11,11,10,10, 7,10,10,11,11,11,12,11,11, 7,
  140678. 9, 9,11,10,10,11,10,10, 7, 9, 9,11,10,10,11,10,
  140679. 10,
  140680. };
  140681. static float _vq_quantthresh__44cn1_s_p6_0[] = {
  140682. -5.5, 5.5,
  140683. };
  140684. static long _vq_quantmap__44cn1_s_p6_0[] = {
  140685. 1, 0, 2,
  140686. };
  140687. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_0 = {
  140688. _vq_quantthresh__44cn1_s_p6_0,
  140689. _vq_quantmap__44cn1_s_p6_0,
  140690. 3,
  140691. 3
  140692. };
  140693. static static_codebook _44cn1_s_p6_0 = {
  140694. 4, 81,
  140695. _vq_lengthlist__44cn1_s_p6_0,
  140696. 1, -529137664, 1618345984, 2, 0,
  140697. _vq_quantlist__44cn1_s_p6_0,
  140698. NULL,
  140699. &_vq_auxt__44cn1_s_p6_0,
  140700. NULL,
  140701. 0
  140702. };
  140703. static long _vq_quantlist__44cn1_s_p6_1[] = {
  140704. 5,
  140705. 4,
  140706. 6,
  140707. 3,
  140708. 7,
  140709. 2,
  140710. 8,
  140711. 1,
  140712. 9,
  140713. 0,
  140714. 10,
  140715. };
  140716. static long _vq_lengthlist__44cn1_s_p6_1[] = {
  140717. 1, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 6,
  140718. 8, 8, 8, 8, 8, 8,10,10,10, 7, 6, 7, 7, 8, 8, 8,
  140719. 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  140720. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 9, 9,
  140721. 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,
  140722. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  140723. 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,
  140724. 10,10,10, 9, 9, 9, 9, 9, 9,
  140725. };
  140726. static float _vq_quantthresh__44cn1_s_p6_1[] = {
  140727. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  140728. 3.5, 4.5,
  140729. };
  140730. static long _vq_quantmap__44cn1_s_p6_1[] = {
  140731. 9, 7, 5, 3, 1, 0, 2, 4,
  140732. 6, 8, 10,
  140733. };
  140734. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_1 = {
  140735. _vq_quantthresh__44cn1_s_p6_1,
  140736. _vq_quantmap__44cn1_s_p6_1,
  140737. 11,
  140738. 11
  140739. };
  140740. static static_codebook _44cn1_s_p6_1 = {
  140741. 2, 121,
  140742. _vq_lengthlist__44cn1_s_p6_1,
  140743. 1, -531365888, 1611661312, 4, 0,
  140744. _vq_quantlist__44cn1_s_p6_1,
  140745. NULL,
  140746. &_vq_auxt__44cn1_s_p6_1,
  140747. NULL,
  140748. 0
  140749. };
  140750. static long _vq_quantlist__44cn1_s_p7_0[] = {
  140751. 6,
  140752. 5,
  140753. 7,
  140754. 4,
  140755. 8,
  140756. 3,
  140757. 9,
  140758. 2,
  140759. 10,
  140760. 1,
  140761. 11,
  140762. 0,
  140763. 12,
  140764. };
  140765. static long _vq_lengthlist__44cn1_s_p7_0[] = {
  140766. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  140767. 7, 7, 8, 8, 8, 8, 9, 9,11,11, 7, 5, 5, 7, 7, 8,
  140768. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  140769. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  140770. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,12, 0,13,
  140771. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  140772. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  140773. 11,12,12,13,12, 0, 0, 0,14,14,11,10,11,12,12,13,
  140774. 13,14, 0, 0, 0,15,15,11,11,12,11,12,12,14,13, 0,
  140775. 0, 0, 0, 0,12,12,12,12,13,13,14,14, 0, 0, 0, 0,
  140776. 0,13,13,12,12,13,13,13,14,
  140777. };
  140778. static float _vq_quantthresh__44cn1_s_p7_0[] = {
  140779. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  140780. 12.5, 17.5, 22.5, 27.5,
  140781. };
  140782. static long _vq_quantmap__44cn1_s_p7_0[] = {
  140783. 11, 9, 7, 5, 3, 1, 0, 2,
  140784. 4, 6, 8, 10, 12,
  140785. };
  140786. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_0 = {
  140787. _vq_quantthresh__44cn1_s_p7_0,
  140788. _vq_quantmap__44cn1_s_p7_0,
  140789. 13,
  140790. 13
  140791. };
  140792. static static_codebook _44cn1_s_p7_0 = {
  140793. 2, 169,
  140794. _vq_lengthlist__44cn1_s_p7_0,
  140795. 1, -526516224, 1616117760, 4, 0,
  140796. _vq_quantlist__44cn1_s_p7_0,
  140797. NULL,
  140798. &_vq_auxt__44cn1_s_p7_0,
  140799. NULL,
  140800. 0
  140801. };
  140802. static long _vq_quantlist__44cn1_s_p7_1[] = {
  140803. 2,
  140804. 1,
  140805. 3,
  140806. 0,
  140807. 4,
  140808. };
  140809. static long _vq_lengthlist__44cn1_s_p7_1[] = {
  140810. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  140811. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  140812. };
  140813. static float _vq_quantthresh__44cn1_s_p7_1[] = {
  140814. -1.5, -0.5, 0.5, 1.5,
  140815. };
  140816. static long _vq_quantmap__44cn1_s_p7_1[] = {
  140817. 3, 1, 0, 2, 4,
  140818. };
  140819. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_1 = {
  140820. _vq_quantthresh__44cn1_s_p7_1,
  140821. _vq_quantmap__44cn1_s_p7_1,
  140822. 5,
  140823. 5
  140824. };
  140825. static static_codebook _44cn1_s_p7_1 = {
  140826. 2, 25,
  140827. _vq_lengthlist__44cn1_s_p7_1,
  140828. 1, -533725184, 1611661312, 3, 0,
  140829. _vq_quantlist__44cn1_s_p7_1,
  140830. NULL,
  140831. &_vq_auxt__44cn1_s_p7_1,
  140832. NULL,
  140833. 0
  140834. };
  140835. static long _vq_quantlist__44cn1_s_p8_0[] = {
  140836. 2,
  140837. 1,
  140838. 3,
  140839. 0,
  140840. 4,
  140841. };
  140842. static long _vq_lengthlist__44cn1_s_p8_0[] = {
  140843. 1, 7, 7,11,11, 8,11,11,11,11, 4,11, 3,11,11,11,
  140844. 11,11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,
  140845. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140846. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  140847. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140848. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140849. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140850. 11,11,11,11,11,11,11,11,11,11,11,11,11, 7,11,11,
  140851. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140852. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  140853. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  140854. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140855. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140856. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140857. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140858. 11,11,11,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  140859. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140860. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140861. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140862. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140863. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140864. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140865. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140866. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140867. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140868. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140869. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140870. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140871. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140872. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140873. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140874. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140875. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140876. 11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,
  140877. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140878. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140879. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140880. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140881. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140882. 12,
  140883. };
  140884. static float _vq_quantthresh__44cn1_s_p8_0[] = {
  140885. -331.5, -110.5, 110.5, 331.5,
  140886. };
  140887. static long _vq_quantmap__44cn1_s_p8_0[] = {
  140888. 3, 1, 0, 2, 4,
  140889. };
  140890. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_0 = {
  140891. _vq_quantthresh__44cn1_s_p8_0,
  140892. _vq_quantmap__44cn1_s_p8_0,
  140893. 5,
  140894. 5
  140895. };
  140896. static static_codebook _44cn1_s_p8_0 = {
  140897. 4, 625,
  140898. _vq_lengthlist__44cn1_s_p8_0,
  140899. 1, -518283264, 1627103232, 3, 0,
  140900. _vq_quantlist__44cn1_s_p8_0,
  140901. NULL,
  140902. &_vq_auxt__44cn1_s_p8_0,
  140903. NULL,
  140904. 0
  140905. };
  140906. static long _vq_quantlist__44cn1_s_p8_1[] = {
  140907. 6,
  140908. 5,
  140909. 7,
  140910. 4,
  140911. 8,
  140912. 3,
  140913. 9,
  140914. 2,
  140915. 10,
  140916. 1,
  140917. 11,
  140918. 0,
  140919. 12,
  140920. };
  140921. static long _vq_lengthlist__44cn1_s_p8_1[] = {
  140922. 1, 4, 4, 6, 6, 8, 8, 9,10,10,11,11,11, 6, 5, 5,
  140923. 7, 7, 8, 8, 9,10, 9,11,11,12, 5, 5, 5, 7, 7, 8,
  140924. 9,10,10,12,12,14,13,15, 7, 7, 8, 8, 9,10,11,11,
  140925. 10,12,10,11,15, 7, 8, 8, 8, 9, 9,11,11,13,12,12,
  140926. 13,15,10,10, 8, 8,10,10,12,12,11,14,10,10,15,11,
  140927. 11, 8, 8,10,10,12,13,13,14,15,13,15,15,15,10,10,
  140928. 10,10,12,12,13,12,13,10,15,15,15,10,10,11,10,13,
  140929. 11,13,13,15,13,15,15,15,13,13,10,11,11,11,12,10,
  140930. 14,11,15,15,14,14,13,10,10,12,11,13,13,14,14,15,
  140931. 15,15,15,15,11,11,11,11,12,11,15,12,15,15,15,15,
  140932. 15,12,12,11,11,14,12,13,14,
  140933. };
  140934. static float _vq_quantthresh__44cn1_s_p8_1[] = {
  140935. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  140936. 42.5, 59.5, 76.5, 93.5,
  140937. };
  140938. static long _vq_quantmap__44cn1_s_p8_1[] = {
  140939. 11, 9, 7, 5, 3, 1, 0, 2,
  140940. 4, 6, 8, 10, 12,
  140941. };
  140942. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_1 = {
  140943. _vq_quantthresh__44cn1_s_p8_1,
  140944. _vq_quantmap__44cn1_s_p8_1,
  140945. 13,
  140946. 13
  140947. };
  140948. static static_codebook _44cn1_s_p8_1 = {
  140949. 2, 169,
  140950. _vq_lengthlist__44cn1_s_p8_1,
  140951. 1, -522616832, 1620115456, 4, 0,
  140952. _vq_quantlist__44cn1_s_p8_1,
  140953. NULL,
  140954. &_vq_auxt__44cn1_s_p8_1,
  140955. NULL,
  140956. 0
  140957. };
  140958. static long _vq_quantlist__44cn1_s_p8_2[] = {
  140959. 8,
  140960. 7,
  140961. 9,
  140962. 6,
  140963. 10,
  140964. 5,
  140965. 11,
  140966. 4,
  140967. 12,
  140968. 3,
  140969. 13,
  140970. 2,
  140971. 14,
  140972. 1,
  140973. 15,
  140974. 0,
  140975. 16,
  140976. };
  140977. static long _vq_lengthlist__44cn1_s_p8_2[] = {
  140978. 3, 4, 3, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  140979. 9,10,11,11, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  140980. 9, 9,10,10,10, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  140981. 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  140982. 9, 9,10, 9,10,11,10, 7, 6, 7, 7, 8, 8, 9, 9, 9,
  140983. 9, 9, 9, 9,10,10,10,11, 7, 7, 8, 8, 8, 8, 9, 9,
  140984. 9, 9, 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9,
  140985. 9, 9, 9, 9, 9, 9,10,11,11,11, 8, 8, 8, 8, 8, 8,
  140986. 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 8, 8, 8,
  140987. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,11, 9, 9,
  140988. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,10,11,11, 9,
  140989. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  140990. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,
  140991. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11,
  140992. 10,11,11,11, 9,10,10, 9, 9, 9, 9, 9, 9, 9,10,11,
  140993. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  140994. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  140995. 11,11,11,10,11,11,11,11,11, 9, 9, 9,10, 9, 9, 9,
  140996. 9,
  140997. };
  140998. static float _vq_quantthresh__44cn1_s_p8_2[] = {
  140999. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141000. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141001. };
  141002. static long _vq_quantmap__44cn1_s_p8_2[] = {
  141003. 15, 13, 11, 9, 7, 5, 3, 1,
  141004. 0, 2, 4, 6, 8, 10, 12, 14,
  141005. 16,
  141006. };
  141007. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_2 = {
  141008. _vq_quantthresh__44cn1_s_p8_2,
  141009. _vq_quantmap__44cn1_s_p8_2,
  141010. 17,
  141011. 17
  141012. };
  141013. static static_codebook _44cn1_s_p8_2 = {
  141014. 2, 289,
  141015. _vq_lengthlist__44cn1_s_p8_2,
  141016. 1, -529530880, 1611661312, 5, 0,
  141017. _vq_quantlist__44cn1_s_p8_2,
  141018. NULL,
  141019. &_vq_auxt__44cn1_s_p8_2,
  141020. NULL,
  141021. 0
  141022. };
  141023. static long _huff_lengthlist__44cn1_s_short[] = {
  141024. 10, 9,12,15,12,13,16,14,16, 7, 1, 5,14, 7,10,13,
  141025. 16,16, 9, 4, 6,16, 8,11,16,16,16,14, 4, 7,16, 9,
  141026. 12,14,16,16,10, 5, 7,14, 9,12,14,15,15,13, 8, 9,
  141027. 14,10,12,13,14,15,13, 9, 9, 7, 6, 8,11,12,12,14,
  141028. 8, 8, 5, 4, 5, 8,11,12,16,10,10, 6, 5, 6, 8, 9,
  141029. 10,
  141030. };
  141031. static static_codebook _huff_book__44cn1_s_short = {
  141032. 2, 81,
  141033. _huff_lengthlist__44cn1_s_short,
  141034. 0, 0, 0, 0, 0,
  141035. NULL,
  141036. NULL,
  141037. NULL,
  141038. NULL,
  141039. 0
  141040. };
  141041. static long _huff_lengthlist__44cn1_sm_long[] = {
  141042. 3, 3, 8, 8, 8, 8,10,12,14, 3, 2, 6, 7, 7, 8,10,
  141043. 12,16, 7, 6, 7, 9, 8,10,12,14,16, 8, 6, 8, 4, 5,
  141044. 7, 9,11,13, 7, 6, 8, 5, 6, 7, 9,11,14, 8, 8,10,
  141045. 7, 7, 6, 8,10,13, 9,11,12, 9, 9, 7, 8,10,12,10,
  141046. 13,15,11,11,10, 9,10,13,13,16,17,14,15,14,13,14,
  141047. 17,
  141048. };
  141049. static static_codebook _huff_book__44cn1_sm_long = {
  141050. 2, 81,
  141051. _huff_lengthlist__44cn1_sm_long,
  141052. 0, 0, 0, 0, 0,
  141053. NULL,
  141054. NULL,
  141055. NULL,
  141056. NULL,
  141057. 0
  141058. };
  141059. static long _vq_quantlist__44cn1_sm_p1_0[] = {
  141060. 1,
  141061. 0,
  141062. 2,
  141063. };
  141064. static long _vq_lengthlist__44cn1_sm_p1_0[] = {
  141065. 1, 4, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  141066. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141070. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  141071. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141075. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  141076. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 8, 0, 0, 0, 0,
  141111. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  141112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0, 0,
  141116. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  141117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  141121. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  141122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  141157. 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  141162. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10,
  141167. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  141168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141475. 0,
  141476. };
  141477. static float _vq_quantthresh__44cn1_sm_p1_0[] = {
  141478. -0.5, 0.5,
  141479. };
  141480. static long _vq_quantmap__44cn1_sm_p1_0[] = {
  141481. 1, 0, 2,
  141482. };
  141483. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p1_0 = {
  141484. _vq_quantthresh__44cn1_sm_p1_0,
  141485. _vq_quantmap__44cn1_sm_p1_0,
  141486. 3,
  141487. 3
  141488. };
  141489. static static_codebook _44cn1_sm_p1_0 = {
  141490. 8, 6561,
  141491. _vq_lengthlist__44cn1_sm_p1_0,
  141492. 1, -535822336, 1611661312, 2, 0,
  141493. _vq_quantlist__44cn1_sm_p1_0,
  141494. NULL,
  141495. &_vq_auxt__44cn1_sm_p1_0,
  141496. NULL,
  141497. 0
  141498. };
  141499. static long _vq_quantlist__44cn1_sm_p2_0[] = {
  141500. 2,
  141501. 1,
  141502. 3,
  141503. 0,
  141504. 4,
  141505. };
  141506. static long _vq_lengthlist__44cn1_sm_p2_0[] = {
  141507. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  141509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141510. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  141512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141513. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  141514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141546. 0,
  141547. };
  141548. static float _vq_quantthresh__44cn1_sm_p2_0[] = {
  141549. -1.5, -0.5, 0.5, 1.5,
  141550. };
  141551. static long _vq_quantmap__44cn1_sm_p2_0[] = {
  141552. 3, 1, 0, 2, 4,
  141553. };
  141554. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p2_0 = {
  141555. _vq_quantthresh__44cn1_sm_p2_0,
  141556. _vq_quantmap__44cn1_sm_p2_0,
  141557. 5,
  141558. 5
  141559. };
  141560. static static_codebook _44cn1_sm_p2_0 = {
  141561. 4, 625,
  141562. _vq_lengthlist__44cn1_sm_p2_0,
  141563. 1, -533725184, 1611661312, 3, 0,
  141564. _vq_quantlist__44cn1_sm_p2_0,
  141565. NULL,
  141566. &_vq_auxt__44cn1_sm_p2_0,
  141567. NULL,
  141568. 0
  141569. };
  141570. static long _vq_quantlist__44cn1_sm_p3_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_p3_0[] = {
  141582. 1, 3, 4, 7, 7, 0, 0, 0, 0, 0, 4, 4, 7, 7, 0, 0,
  141583. 0, 0, 0, 4, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  141584. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  141585. 9, 9, 0, 0, 0, 0, 0, 0, 0,10, 9, 0, 0, 0, 0, 0,
  141586. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141587. 0,
  141588. };
  141589. static float _vq_quantthresh__44cn1_sm_p3_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_p3_0[] = {
  141593. 7, 5, 3, 1, 0, 2, 4, 6,
  141594. 8,
  141595. };
  141596. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p3_0 = {
  141597. _vq_quantthresh__44cn1_sm_p3_0,
  141598. _vq_quantmap__44cn1_sm_p3_0,
  141599. 9,
  141600. 9
  141601. };
  141602. static static_codebook _44cn1_sm_p3_0 = {
  141603. 2, 81,
  141604. _vq_lengthlist__44cn1_sm_p3_0,
  141605. 1, -531628032, 1611661312, 4, 0,
  141606. _vq_quantlist__44cn1_sm_p3_0,
  141607. NULL,
  141608. &_vq_auxt__44cn1_sm_p3_0,
  141609. NULL,
  141610. 0
  141611. };
  141612. static long _vq_quantlist__44cn1_sm_p4_0[] = {
  141613. 4,
  141614. 3,
  141615. 5,
  141616. 2,
  141617. 6,
  141618. 1,
  141619. 7,
  141620. 0,
  141621. 8,
  141622. };
  141623. static long _vq_lengthlist__44cn1_sm_p4_0[] = {
  141624. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  141625. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  141626. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  141627. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  141628. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  141629. 11,
  141630. };
  141631. static float _vq_quantthresh__44cn1_sm_p4_0[] = {
  141632. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141633. };
  141634. static long _vq_quantmap__44cn1_sm_p4_0[] = {
  141635. 7, 5, 3, 1, 0, 2, 4, 6,
  141636. 8,
  141637. };
  141638. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p4_0 = {
  141639. _vq_quantthresh__44cn1_sm_p4_0,
  141640. _vq_quantmap__44cn1_sm_p4_0,
  141641. 9,
  141642. 9
  141643. };
  141644. static static_codebook _44cn1_sm_p4_0 = {
  141645. 2, 81,
  141646. _vq_lengthlist__44cn1_sm_p4_0,
  141647. 1, -531628032, 1611661312, 4, 0,
  141648. _vq_quantlist__44cn1_sm_p4_0,
  141649. NULL,
  141650. &_vq_auxt__44cn1_sm_p4_0,
  141651. NULL,
  141652. 0
  141653. };
  141654. static long _vq_quantlist__44cn1_sm_p5_0[] = {
  141655. 8,
  141656. 7,
  141657. 9,
  141658. 6,
  141659. 10,
  141660. 5,
  141661. 11,
  141662. 4,
  141663. 12,
  141664. 3,
  141665. 13,
  141666. 2,
  141667. 14,
  141668. 1,
  141669. 15,
  141670. 0,
  141671. 16,
  141672. };
  141673. static long _vq_lengthlist__44cn1_sm_p5_0[] = {
  141674. 1, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  141675. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  141676. 12,12, 0, 6, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  141677. 11,12,12, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  141678. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,11,
  141679. 11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  141680. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  141681. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  141682. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  141683. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  141684. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  141685. 9,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0, 0,
  141686. 10,10,11,11,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  141687. 0, 0, 0,11,11,11,11,12,12,13,13,14,14, 0, 0, 0,
  141688. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  141689. 0, 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0,
  141690. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,14,14,14,14,
  141691. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,14,14,
  141692. 14,
  141693. };
  141694. static float _vq_quantthresh__44cn1_sm_p5_0[] = {
  141695. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141696. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141697. };
  141698. static long _vq_quantmap__44cn1_sm_p5_0[] = {
  141699. 15, 13, 11, 9, 7, 5, 3, 1,
  141700. 0, 2, 4, 6, 8, 10, 12, 14,
  141701. 16,
  141702. };
  141703. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p5_0 = {
  141704. _vq_quantthresh__44cn1_sm_p5_0,
  141705. _vq_quantmap__44cn1_sm_p5_0,
  141706. 17,
  141707. 17
  141708. };
  141709. static static_codebook _44cn1_sm_p5_0 = {
  141710. 2, 289,
  141711. _vq_lengthlist__44cn1_sm_p5_0,
  141712. 1, -529530880, 1611661312, 5, 0,
  141713. _vq_quantlist__44cn1_sm_p5_0,
  141714. NULL,
  141715. &_vq_auxt__44cn1_sm_p5_0,
  141716. NULL,
  141717. 0
  141718. };
  141719. static long _vq_quantlist__44cn1_sm_p6_0[] = {
  141720. 1,
  141721. 0,
  141722. 2,
  141723. };
  141724. static long _vq_lengthlist__44cn1_sm_p6_0[] = {
  141725. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 6,10, 9, 9,11,
  141726. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  141727. 11,11,11,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  141728. 11,10,11,11,10,10, 7,11,11,11,11,11,12,11,11, 7,
  141729. 9, 9,11,10,10,12,10,10, 7, 9, 9,11,10,10,11,10,
  141730. 10,
  141731. };
  141732. static float _vq_quantthresh__44cn1_sm_p6_0[] = {
  141733. -5.5, 5.5,
  141734. };
  141735. static long _vq_quantmap__44cn1_sm_p6_0[] = {
  141736. 1, 0, 2,
  141737. };
  141738. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_0 = {
  141739. _vq_quantthresh__44cn1_sm_p6_0,
  141740. _vq_quantmap__44cn1_sm_p6_0,
  141741. 3,
  141742. 3
  141743. };
  141744. static static_codebook _44cn1_sm_p6_0 = {
  141745. 4, 81,
  141746. _vq_lengthlist__44cn1_sm_p6_0,
  141747. 1, -529137664, 1618345984, 2, 0,
  141748. _vq_quantlist__44cn1_sm_p6_0,
  141749. NULL,
  141750. &_vq_auxt__44cn1_sm_p6_0,
  141751. NULL,
  141752. 0
  141753. };
  141754. static long _vq_quantlist__44cn1_sm_p6_1[] = {
  141755. 5,
  141756. 4,
  141757. 6,
  141758. 3,
  141759. 7,
  141760. 2,
  141761. 8,
  141762. 1,
  141763. 9,
  141764. 0,
  141765. 10,
  141766. };
  141767. static long _vq_lengthlist__44cn1_sm_p6_1[] = {
  141768. 2, 4, 4, 5, 5, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  141769. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  141770. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  141771. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  141772. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  141773. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  141774. 8, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 8, 9,10,10,
  141775. 10,10,10, 8, 9, 8, 8, 9, 8,
  141776. };
  141777. static float _vq_quantthresh__44cn1_sm_p6_1[] = {
  141778. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  141779. 3.5, 4.5,
  141780. };
  141781. static long _vq_quantmap__44cn1_sm_p6_1[] = {
  141782. 9, 7, 5, 3, 1, 0, 2, 4,
  141783. 6, 8, 10,
  141784. };
  141785. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_1 = {
  141786. _vq_quantthresh__44cn1_sm_p6_1,
  141787. _vq_quantmap__44cn1_sm_p6_1,
  141788. 11,
  141789. 11
  141790. };
  141791. static static_codebook _44cn1_sm_p6_1 = {
  141792. 2, 121,
  141793. _vq_lengthlist__44cn1_sm_p6_1,
  141794. 1, -531365888, 1611661312, 4, 0,
  141795. _vq_quantlist__44cn1_sm_p6_1,
  141796. NULL,
  141797. &_vq_auxt__44cn1_sm_p6_1,
  141798. NULL,
  141799. 0
  141800. };
  141801. static long _vq_quantlist__44cn1_sm_p7_0[] = {
  141802. 6,
  141803. 5,
  141804. 7,
  141805. 4,
  141806. 8,
  141807. 3,
  141808. 9,
  141809. 2,
  141810. 10,
  141811. 1,
  141812. 11,
  141813. 0,
  141814. 12,
  141815. };
  141816. static long _vq_lengthlist__44cn1_sm_p7_0[] = {
  141817. 1, 4, 4, 6, 6, 7, 7, 7, 7, 9, 9,10,10, 7, 5, 5,
  141818. 7, 7, 8, 8, 8, 8,10, 9,11,10, 7, 5, 5, 7, 7, 8,
  141819. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  141820. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  141821. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,12,12, 0,13,
  141822. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10,
  141823. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  141824. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,13,
  141825. 13,13, 0, 0, 0,14,14,11,10,11,11,12,12,13,13, 0,
  141826. 0, 0, 0, 0,12,12,12,12,13,13,13,14, 0, 0, 0, 0,
  141827. 0,13,12,12,12,13,13,13,14,
  141828. };
  141829. static float _vq_quantthresh__44cn1_sm_p7_0[] = {
  141830. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  141831. 12.5, 17.5, 22.5, 27.5,
  141832. };
  141833. static long _vq_quantmap__44cn1_sm_p7_0[] = {
  141834. 11, 9, 7, 5, 3, 1, 0, 2,
  141835. 4, 6, 8, 10, 12,
  141836. };
  141837. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_0 = {
  141838. _vq_quantthresh__44cn1_sm_p7_0,
  141839. _vq_quantmap__44cn1_sm_p7_0,
  141840. 13,
  141841. 13
  141842. };
  141843. static static_codebook _44cn1_sm_p7_0 = {
  141844. 2, 169,
  141845. _vq_lengthlist__44cn1_sm_p7_0,
  141846. 1, -526516224, 1616117760, 4, 0,
  141847. _vq_quantlist__44cn1_sm_p7_0,
  141848. NULL,
  141849. &_vq_auxt__44cn1_sm_p7_0,
  141850. NULL,
  141851. 0
  141852. };
  141853. static long _vq_quantlist__44cn1_sm_p7_1[] = {
  141854. 2,
  141855. 1,
  141856. 3,
  141857. 0,
  141858. 4,
  141859. };
  141860. static long _vq_lengthlist__44cn1_sm_p7_1[] = {
  141861. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  141862. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  141863. };
  141864. static float _vq_quantthresh__44cn1_sm_p7_1[] = {
  141865. -1.5, -0.5, 0.5, 1.5,
  141866. };
  141867. static long _vq_quantmap__44cn1_sm_p7_1[] = {
  141868. 3, 1, 0, 2, 4,
  141869. };
  141870. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_1 = {
  141871. _vq_quantthresh__44cn1_sm_p7_1,
  141872. _vq_quantmap__44cn1_sm_p7_1,
  141873. 5,
  141874. 5
  141875. };
  141876. static static_codebook _44cn1_sm_p7_1 = {
  141877. 2, 25,
  141878. _vq_lengthlist__44cn1_sm_p7_1,
  141879. 1, -533725184, 1611661312, 3, 0,
  141880. _vq_quantlist__44cn1_sm_p7_1,
  141881. NULL,
  141882. &_vq_auxt__44cn1_sm_p7_1,
  141883. NULL,
  141884. 0
  141885. };
  141886. static long _vq_quantlist__44cn1_sm_p8_0[] = {
  141887. 4,
  141888. 3,
  141889. 5,
  141890. 2,
  141891. 6,
  141892. 1,
  141893. 7,
  141894. 0,
  141895. 8,
  141896. };
  141897. static long _vq_lengthlist__44cn1_sm_p8_0[] = {
  141898. 1, 4, 4,12,11,13,13,14,14, 4, 7, 7,11,13,14,14,
  141899. 14,14, 3, 8, 3,14,14,14,14,14,14,14,10,12,14,14,
  141900. 14,14,14,14,14,14, 5,14, 8,14,14,14,14,14,12,14,
  141901. 13,14,14,14,14,14,14,14,13,14,10,14,14,14,14,14,
  141902. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  141903. 14,
  141904. };
  141905. static float _vq_quantthresh__44cn1_sm_p8_0[] = {
  141906. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  141907. };
  141908. static long _vq_quantmap__44cn1_sm_p8_0[] = {
  141909. 7, 5, 3, 1, 0, 2, 4, 6,
  141910. 8,
  141911. };
  141912. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_0 = {
  141913. _vq_quantthresh__44cn1_sm_p8_0,
  141914. _vq_quantmap__44cn1_sm_p8_0,
  141915. 9,
  141916. 9
  141917. };
  141918. static static_codebook _44cn1_sm_p8_0 = {
  141919. 2, 81,
  141920. _vq_lengthlist__44cn1_sm_p8_0,
  141921. 1, -516186112, 1627103232, 4, 0,
  141922. _vq_quantlist__44cn1_sm_p8_0,
  141923. NULL,
  141924. &_vq_auxt__44cn1_sm_p8_0,
  141925. NULL,
  141926. 0
  141927. };
  141928. static long _vq_quantlist__44cn1_sm_p8_1[] = {
  141929. 6,
  141930. 5,
  141931. 7,
  141932. 4,
  141933. 8,
  141934. 3,
  141935. 9,
  141936. 2,
  141937. 10,
  141938. 1,
  141939. 11,
  141940. 0,
  141941. 12,
  141942. };
  141943. static long _vq_lengthlist__44cn1_sm_p8_1[] = {
  141944. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,11,11, 6, 5, 5,
  141945. 7, 7, 8, 8,10,10,10,11,11,11, 6, 5, 5, 7, 7, 8,
  141946. 8,10,10,11,12,12,12,14, 7, 7, 7, 8, 9, 9,11,11,
  141947. 11,12,11,12,17, 7, 7, 8, 7, 9, 9,11,11,12,12,12,
  141948. 12,14,11,11, 8, 8,10,10,11,12,12,13,11,12,14,11,
  141949. 11, 8, 8,10,10,11,12,12,13,13,12,14,15,14,10,10,
  141950. 10,10,11,12,12,12,12,11,14,13,16,10,10,10, 9,12,
  141951. 11,12,12,13,14,14,15,14,14,13,10,10,11,11,12,11,
  141952. 13,11,14,12,15,13,14,11,10,12,10,12,12,13,13,13,
  141953. 13,14,15,15,12,12,11,11,12,11,13,12,14,14,14,14,
  141954. 17,12,12,11,10,13,11,13,13,
  141955. };
  141956. static float _vq_quantthresh__44cn1_sm_p8_1[] = {
  141957. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  141958. 42.5, 59.5, 76.5, 93.5,
  141959. };
  141960. static long _vq_quantmap__44cn1_sm_p8_1[] = {
  141961. 11, 9, 7, 5, 3, 1, 0, 2,
  141962. 4, 6, 8, 10, 12,
  141963. };
  141964. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_1 = {
  141965. _vq_quantthresh__44cn1_sm_p8_1,
  141966. _vq_quantmap__44cn1_sm_p8_1,
  141967. 13,
  141968. 13
  141969. };
  141970. static static_codebook _44cn1_sm_p8_1 = {
  141971. 2, 169,
  141972. _vq_lengthlist__44cn1_sm_p8_1,
  141973. 1, -522616832, 1620115456, 4, 0,
  141974. _vq_quantlist__44cn1_sm_p8_1,
  141975. NULL,
  141976. &_vq_auxt__44cn1_sm_p8_1,
  141977. NULL,
  141978. 0
  141979. };
  141980. static long _vq_quantlist__44cn1_sm_p8_2[] = {
  141981. 8,
  141982. 7,
  141983. 9,
  141984. 6,
  141985. 10,
  141986. 5,
  141987. 11,
  141988. 4,
  141989. 12,
  141990. 3,
  141991. 13,
  141992. 2,
  141993. 14,
  141994. 1,
  141995. 15,
  141996. 0,
  141997. 16,
  141998. };
  141999. static long _vq_lengthlist__44cn1_sm_p8_2[] = {
  142000. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  142001. 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  142002. 9, 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  142003. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  142004. 9, 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,
  142005. 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9, 9,
  142006. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9,
  142007. 9, 9, 9, 9, 9, 9, 9,11,10,11, 8, 8, 8, 8, 8, 8,
  142008. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11, 8, 8, 8,
  142009. 8, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  142010. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,11,11, 9,
  142011. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,10,11,11,
  142012. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,
  142013. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,
  142014. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,11,10,
  142015. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  142016. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  142017. 10,11,11,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  142018. 9,
  142019. };
  142020. static float _vq_quantthresh__44cn1_sm_p8_2[] = {
  142021. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  142022. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  142023. };
  142024. static long _vq_quantmap__44cn1_sm_p8_2[] = {
  142025. 15, 13, 11, 9, 7, 5, 3, 1,
  142026. 0, 2, 4, 6, 8, 10, 12, 14,
  142027. 16,
  142028. };
  142029. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_2 = {
  142030. _vq_quantthresh__44cn1_sm_p8_2,
  142031. _vq_quantmap__44cn1_sm_p8_2,
  142032. 17,
  142033. 17
  142034. };
  142035. static static_codebook _44cn1_sm_p8_2 = {
  142036. 2, 289,
  142037. _vq_lengthlist__44cn1_sm_p8_2,
  142038. 1, -529530880, 1611661312, 5, 0,
  142039. _vq_quantlist__44cn1_sm_p8_2,
  142040. NULL,
  142041. &_vq_auxt__44cn1_sm_p8_2,
  142042. NULL,
  142043. 0
  142044. };
  142045. static long _huff_lengthlist__44cn1_sm_short[] = {
  142046. 5, 6,12,14,12,14,16,17,18, 4, 2, 5,11, 7,10,12,
  142047. 14,15, 9, 4, 5,11, 7,10,13,15,18,15, 6, 7, 5, 6,
  142048. 8,11,13,16,11, 5, 6, 5, 5, 6, 9,13,15,12, 5, 7,
  142049. 6, 5, 6, 9,12,14,12, 6, 7, 8, 6, 7, 9,12,13,14,
  142050. 8, 8, 7, 5, 5, 8,10,12,16, 9, 9, 8, 6, 6, 7, 9,
  142051. 9,
  142052. };
  142053. static static_codebook _huff_book__44cn1_sm_short = {
  142054. 2, 81,
  142055. _huff_lengthlist__44cn1_sm_short,
  142056. 0, 0, 0, 0, 0,
  142057. NULL,
  142058. NULL,
  142059. NULL,
  142060. NULL,
  142061. 0
  142062. };
  142063. /*** End of inlined file: res_books_stereo.h ***/
  142064. /***** residue backends *********************************************/
  142065. static vorbis_info_residue0 _residue_44_low={
  142066. 0,-1, -1, 9,-1,
  142067. /* 0 1 2 3 4 5 6 7 */
  142068. {0},
  142069. {-1},
  142070. { .5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  142071. { .5, .5, .5, 999., 4.5, 8.5, 16.5, 32.5},
  142072. };
  142073. static vorbis_info_residue0 _residue_44_mid={
  142074. 0,-1, -1, 10,-1,
  142075. /* 0 1 2 3 4 5 6 7 8 */
  142076. {0},
  142077. {-1},
  142078. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  142079. { .5, .5, 999., .5, 999., 4.5, 8.5, 16.5, 32.5},
  142080. };
  142081. static vorbis_info_residue0 _residue_44_high={
  142082. 0,-1, -1, 10,-1,
  142083. /* 0 1 2 3 4 5 6 7 8 */
  142084. {0},
  142085. {-1},
  142086. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  142087. { .5, 1.5, 2.5, 3.5, 4.5, 8.5, 16.5, 71.5,157.5},
  142088. };
  142089. static static_bookblock _resbook_44s_n1={
  142090. {
  142091. {0},{0,0,&_44cn1_s_p1_0},{0,0,&_44cn1_s_p2_0},
  142092. {0,0,&_44cn1_s_p3_0},{0,0,&_44cn1_s_p4_0},{0,0,&_44cn1_s_p5_0},
  142093. {&_44cn1_s_p6_0,&_44cn1_s_p6_1},{&_44cn1_s_p7_0,&_44cn1_s_p7_1},
  142094. {&_44cn1_s_p8_0,&_44cn1_s_p8_1,&_44cn1_s_p8_2}
  142095. }
  142096. };
  142097. static static_bookblock _resbook_44sm_n1={
  142098. {
  142099. {0},{0,0,&_44cn1_sm_p1_0},{0,0,&_44cn1_sm_p2_0},
  142100. {0,0,&_44cn1_sm_p3_0},{0,0,&_44cn1_sm_p4_0},{0,0,&_44cn1_sm_p5_0},
  142101. {&_44cn1_sm_p6_0,&_44cn1_sm_p6_1},{&_44cn1_sm_p7_0,&_44cn1_sm_p7_1},
  142102. {&_44cn1_sm_p8_0,&_44cn1_sm_p8_1,&_44cn1_sm_p8_2}
  142103. }
  142104. };
  142105. static static_bookblock _resbook_44s_0={
  142106. {
  142107. {0},{0,0,&_44c0_s_p1_0},{0,0,&_44c0_s_p2_0},
  142108. {0,0,&_44c0_s_p3_0},{0,0,&_44c0_s_p4_0},{0,0,&_44c0_s_p5_0},
  142109. {&_44c0_s_p6_0,&_44c0_s_p6_1},{&_44c0_s_p7_0,&_44c0_s_p7_1},
  142110. {&_44c0_s_p8_0,&_44c0_s_p8_1,&_44c0_s_p8_2}
  142111. }
  142112. };
  142113. static static_bookblock _resbook_44sm_0={
  142114. {
  142115. {0},{0,0,&_44c0_sm_p1_0},{0,0,&_44c0_sm_p2_0},
  142116. {0,0,&_44c0_sm_p3_0},{0,0,&_44c0_sm_p4_0},{0,0,&_44c0_sm_p5_0},
  142117. {&_44c0_sm_p6_0,&_44c0_sm_p6_1},{&_44c0_sm_p7_0,&_44c0_sm_p7_1},
  142118. {&_44c0_sm_p8_0,&_44c0_sm_p8_1,&_44c0_sm_p8_2}
  142119. }
  142120. };
  142121. static static_bookblock _resbook_44s_1={
  142122. {
  142123. {0},{0,0,&_44c1_s_p1_0},{0,0,&_44c1_s_p2_0},
  142124. {0,0,&_44c1_s_p3_0},{0,0,&_44c1_s_p4_0},{0,0,&_44c1_s_p5_0},
  142125. {&_44c1_s_p6_0,&_44c1_s_p6_1},{&_44c1_s_p7_0,&_44c1_s_p7_1},
  142126. {&_44c1_s_p8_0,&_44c1_s_p8_1,&_44c1_s_p8_2}
  142127. }
  142128. };
  142129. static static_bookblock _resbook_44sm_1={
  142130. {
  142131. {0},{0,0,&_44c1_sm_p1_0},{0,0,&_44c1_sm_p2_0},
  142132. {0,0,&_44c1_sm_p3_0},{0,0,&_44c1_sm_p4_0},{0,0,&_44c1_sm_p5_0},
  142133. {&_44c1_sm_p6_0,&_44c1_sm_p6_1},{&_44c1_sm_p7_0,&_44c1_sm_p7_1},
  142134. {&_44c1_sm_p8_0,&_44c1_sm_p8_1,&_44c1_sm_p8_2}
  142135. }
  142136. };
  142137. static static_bookblock _resbook_44s_2={
  142138. {
  142139. {0},{0,0,&_44c2_s_p1_0},{0,0,&_44c2_s_p2_0},{0,0,&_44c2_s_p3_0},
  142140. {0,0,&_44c2_s_p4_0},{0,0,&_44c2_s_p5_0},{0,0,&_44c2_s_p6_0},
  142141. {&_44c2_s_p7_0,&_44c2_s_p7_1},{&_44c2_s_p8_0,&_44c2_s_p8_1},
  142142. {&_44c2_s_p9_0,&_44c2_s_p9_1,&_44c2_s_p9_2}
  142143. }
  142144. };
  142145. static static_bookblock _resbook_44s_3={
  142146. {
  142147. {0},{0,0,&_44c3_s_p1_0},{0,0,&_44c3_s_p2_0},{0,0,&_44c3_s_p3_0},
  142148. {0,0,&_44c3_s_p4_0},{0,0,&_44c3_s_p5_0},{0,0,&_44c3_s_p6_0},
  142149. {&_44c3_s_p7_0,&_44c3_s_p7_1},{&_44c3_s_p8_0,&_44c3_s_p8_1},
  142150. {&_44c3_s_p9_0,&_44c3_s_p9_1,&_44c3_s_p9_2}
  142151. }
  142152. };
  142153. static static_bookblock _resbook_44s_4={
  142154. {
  142155. {0},{0,0,&_44c4_s_p1_0},{0,0,&_44c4_s_p2_0},{0,0,&_44c4_s_p3_0},
  142156. {0,0,&_44c4_s_p4_0},{0,0,&_44c4_s_p5_0},{0,0,&_44c4_s_p6_0},
  142157. {&_44c4_s_p7_0,&_44c4_s_p7_1},{&_44c4_s_p8_0,&_44c4_s_p8_1},
  142158. {&_44c4_s_p9_0,&_44c4_s_p9_1,&_44c4_s_p9_2}
  142159. }
  142160. };
  142161. static static_bookblock _resbook_44s_5={
  142162. {
  142163. {0},{0,0,&_44c5_s_p1_0},{0,0,&_44c5_s_p2_0},{0,0,&_44c5_s_p3_0},
  142164. {0,0,&_44c5_s_p4_0},{0,0,&_44c5_s_p5_0},{0,0,&_44c5_s_p6_0},
  142165. {&_44c5_s_p7_0,&_44c5_s_p7_1},{&_44c5_s_p8_0,&_44c5_s_p8_1},
  142166. {&_44c5_s_p9_0,&_44c5_s_p9_1,&_44c5_s_p9_2}
  142167. }
  142168. };
  142169. static static_bookblock _resbook_44s_6={
  142170. {
  142171. {0},{0,0,&_44c6_s_p1_0},{0,0,&_44c6_s_p2_0},{0,0,&_44c6_s_p3_0},
  142172. {0,0,&_44c6_s_p4_0},
  142173. {&_44c6_s_p5_0,&_44c6_s_p5_1},
  142174. {&_44c6_s_p6_0,&_44c6_s_p6_1},
  142175. {&_44c6_s_p7_0,&_44c6_s_p7_1},
  142176. {&_44c6_s_p8_0,&_44c6_s_p8_1},
  142177. {&_44c6_s_p9_0,&_44c6_s_p9_1,&_44c6_s_p9_2}
  142178. }
  142179. };
  142180. static static_bookblock _resbook_44s_7={
  142181. {
  142182. {0},{0,0,&_44c7_s_p1_0},{0,0,&_44c7_s_p2_0},{0,0,&_44c7_s_p3_0},
  142183. {0,0,&_44c7_s_p4_0},
  142184. {&_44c7_s_p5_0,&_44c7_s_p5_1},
  142185. {&_44c7_s_p6_0,&_44c7_s_p6_1},
  142186. {&_44c7_s_p7_0,&_44c7_s_p7_1},
  142187. {&_44c7_s_p8_0,&_44c7_s_p8_1},
  142188. {&_44c7_s_p9_0,&_44c7_s_p9_1,&_44c7_s_p9_2}
  142189. }
  142190. };
  142191. static static_bookblock _resbook_44s_8={
  142192. {
  142193. {0},{0,0,&_44c8_s_p1_0},{0,0,&_44c8_s_p2_0},{0,0,&_44c8_s_p3_0},
  142194. {0,0,&_44c8_s_p4_0},
  142195. {&_44c8_s_p5_0,&_44c8_s_p5_1},
  142196. {&_44c8_s_p6_0,&_44c8_s_p6_1},
  142197. {&_44c8_s_p7_0,&_44c8_s_p7_1},
  142198. {&_44c8_s_p8_0,&_44c8_s_p8_1},
  142199. {&_44c8_s_p9_0,&_44c8_s_p9_1,&_44c8_s_p9_2}
  142200. }
  142201. };
  142202. static static_bookblock _resbook_44s_9={
  142203. {
  142204. {0},{0,0,&_44c9_s_p1_0},{0,0,&_44c9_s_p2_0},{0,0,&_44c9_s_p3_0},
  142205. {0,0,&_44c9_s_p4_0},
  142206. {&_44c9_s_p5_0,&_44c9_s_p5_1},
  142207. {&_44c9_s_p6_0,&_44c9_s_p6_1},
  142208. {&_44c9_s_p7_0,&_44c9_s_p7_1},
  142209. {&_44c9_s_p8_0,&_44c9_s_p8_1},
  142210. {&_44c9_s_p9_0,&_44c9_s_p9_1,&_44c9_s_p9_2}
  142211. }
  142212. };
  142213. static vorbis_residue_template _res_44s_n1[]={
  142214. {2,0, &_residue_44_low,
  142215. &_huff_book__44cn1_s_short,&_huff_book__44cn1_sm_short,
  142216. &_resbook_44s_n1,&_resbook_44sm_n1},
  142217. {2,0, &_residue_44_low,
  142218. &_huff_book__44cn1_s_long,&_huff_book__44cn1_sm_long,
  142219. &_resbook_44s_n1,&_resbook_44sm_n1}
  142220. };
  142221. static vorbis_residue_template _res_44s_0[]={
  142222. {2,0, &_residue_44_low,
  142223. &_huff_book__44c0_s_short,&_huff_book__44c0_sm_short,
  142224. &_resbook_44s_0,&_resbook_44sm_0},
  142225. {2,0, &_residue_44_low,
  142226. &_huff_book__44c0_s_long,&_huff_book__44c0_sm_long,
  142227. &_resbook_44s_0,&_resbook_44sm_0}
  142228. };
  142229. static vorbis_residue_template _res_44s_1[]={
  142230. {2,0, &_residue_44_low,
  142231. &_huff_book__44c1_s_short,&_huff_book__44c1_sm_short,
  142232. &_resbook_44s_1,&_resbook_44sm_1},
  142233. {2,0, &_residue_44_low,
  142234. &_huff_book__44c1_s_long,&_huff_book__44c1_sm_long,
  142235. &_resbook_44s_1,&_resbook_44sm_1}
  142236. };
  142237. static vorbis_residue_template _res_44s_2[]={
  142238. {2,0, &_residue_44_mid,
  142239. &_huff_book__44c2_s_short,&_huff_book__44c2_s_short,
  142240. &_resbook_44s_2,&_resbook_44s_2},
  142241. {2,0, &_residue_44_mid,
  142242. &_huff_book__44c2_s_long,&_huff_book__44c2_s_long,
  142243. &_resbook_44s_2,&_resbook_44s_2}
  142244. };
  142245. static vorbis_residue_template _res_44s_3[]={
  142246. {2,0, &_residue_44_mid,
  142247. &_huff_book__44c3_s_short,&_huff_book__44c3_s_short,
  142248. &_resbook_44s_3,&_resbook_44s_3},
  142249. {2,0, &_residue_44_mid,
  142250. &_huff_book__44c3_s_long,&_huff_book__44c3_s_long,
  142251. &_resbook_44s_3,&_resbook_44s_3}
  142252. };
  142253. static vorbis_residue_template _res_44s_4[]={
  142254. {2,0, &_residue_44_mid,
  142255. &_huff_book__44c4_s_short,&_huff_book__44c4_s_short,
  142256. &_resbook_44s_4,&_resbook_44s_4},
  142257. {2,0, &_residue_44_mid,
  142258. &_huff_book__44c4_s_long,&_huff_book__44c4_s_long,
  142259. &_resbook_44s_4,&_resbook_44s_4}
  142260. };
  142261. static vorbis_residue_template _res_44s_5[]={
  142262. {2,0, &_residue_44_mid,
  142263. &_huff_book__44c5_s_short,&_huff_book__44c5_s_short,
  142264. &_resbook_44s_5,&_resbook_44s_5},
  142265. {2,0, &_residue_44_mid,
  142266. &_huff_book__44c5_s_long,&_huff_book__44c5_s_long,
  142267. &_resbook_44s_5,&_resbook_44s_5}
  142268. };
  142269. static vorbis_residue_template _res_44s_6[]={
  142270. {2,0, &_residue_44_high,
  142271. &_huff_book__44c6_s_short,&_huff_book__44c6_s_short,
  142272. &_resbook_44s_6,&_resbook_44s_6},
  142273. {2,0, &_residue_44_high,
  142274. &_huff_book__44c6_s_long,&_huff_book__44c6_s_long,
  142275. &_resbook_44s_6,&_resbook_44s_6}
  142276. };
  142277. static vorbis_residue_template _res_44s_7[]={
  142278. {2,0, &_residue_44_high,
  142279. &_huff_book__44c7_s_short,&_huff_book__44c7_s_short,
  142280. &_resbook_44s_7,&_resbook_44s_7},
  142281. {2,0, &_residue_44_high,
  142282. &_huff_book__44c7_s_long,&_huff_book__44c7_s_long,
  142283. &_resbook_44s_7,&_resbook_44s_7}
  142284. };
  142285. static vorbis_residue_template _res_44s_8[]={
  142286. {2,0, &_residue_44_high,
  142287. &_huff_book__44c8_s_short,&_huff_book__44c8_s_short,
  142288. &_resbook_44s_8,&_resbook_44s_8},
  142289. {2,0, &_residue_44_high,
  142290. &_huff_book__44c8_s_long,&_huff_book__44c8_s_long,
  142291. &_resbook_44s_8,&_resbook_44s_8}
  142292. };
  142293. static vorbis_residue_template _res_44s_9[]={
  142294. {2,0, &_residue_44_high,
  142295. &_huff_book__44c9_s_short,&_huff_book__44c9_s_short,
  142296. &_resbook_44s_9,&_resbook_44s_9},
  142297. {2,0, &_residue_44_high,
  142298. &_huff_book__44c9_s_long,&_huff_book__44c9_s_long,
  142299. &_resbook_44s_9,&_resbook_44s_9}
  142300. };
  142301. static vorbis_mapping_template _mapres_template_44_stereo[]={
  142302. { _map_nominal, _res_44s_n1 }, /* -1 */
  142303. { _map_nominal, _res_44s_0 }, /* 0 */
  142304. { _map_nominal, _res_44s_1 }, /* 1 */
  142305. { _map_nominal, _res_44s_2 }, /* 2 */
  142306. { _map_nominal, _res_44s_3 }, /* 3 */
  142307. { _map_nominal, _res_44s_4 }, /* 4 */
  142308. { _map_nominal, _res_44s_5 }, /* 5 */
  142309. { _map_nominal, _res_44s_6 }, /* 6 */
  142310. { _map_nominal, _res_44s_7 }, /* 7 */
  142311. { _map_nominal, _res_44s_8 }, /* 8 */
  142312. { _map_nominal, _res_44s_9 }, /* 9 */
  142313. };
  142314. /*** End of inlined file: residue_44.h ***/
  142315. /*** Start of inlined file: psych_44.h ***/
  142316. /* preecho trigger settings *****************************************/
  142317. static vorbis_info_psy_global _psy_global_44[5]={
  142318. {8, /* lines per eighth octave */
  142319. {20.f,14.f,12.f,12.f,12.f,12.f,12.f},
  142320. {-60.f,-30.f,-40.f,-40.f,-40.f,-40.f,-40.f}, 2,-75.f,
  142321. -6.f,
  142322. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142323. },
  142324. {8, /* lines per eighth octave */
  142325. {14.f,10.f,10.f,10.f,10.f,10.f,10.f},
  142326. {-40.f,-30.f,-25.f,-25.f,-25.f,-25.f,-25.f}, 2,-80.f,
  142327. -6.f,
  142328. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142329. },
  142330. {8, /* lines per eighth octave */
  142331. {12.f,10.f,10.f,10.f,10.f,10.f,10.f},
  142332. {-20.f,-20.f,-15.f,-15.f,-15.f,-15.f,-15.f}, 0,-80.f,
  142333. -6.f,
  142334. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142335. },
  142336. {8, /* lines per eighth octave */
  142337. {10.f,8.f,8.f,8.f,8.f,8.f,8.f},
  142338. {-20.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-80.f,
  142339. -6.f,
  142340. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142341. },
  142342. {8, /* lines per eighth octave */
  142343. {10.f,6.f,6.f,6.f,6.f,6.f,6.f},
  142344. {-15.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-85.f,
  142345. -6.f,
  142346. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142347. },
  142348. };
  142349. /* noise compander lookups * low, mid, high quality ****************/
  142350. static compandblock _psy_compand_44[6]={
  142351. /* sub-mode Z short */
  142352. {{
  142353. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142354. 8, 9,10,11,12,13,14, 15, /* 15dB */
  142355. 16,17,18,19,20,21,22, 23, /* 23dB */
  142356. 24,25,26,27,28,29,30, 31, /* 31dB */
  142357. 32,33,34,35,36,37,38, 39, /* 39dB */
  142358. }},
  142359. /* mode_Z nominal short */
  142360. {{
  142361. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  142362. 7, 7, 7, 7, 6, 6, 6, 7, /* 15dB */
  142363. 7, 8, 9,10,11,12,13, 14, /* 23dB */
  142364. 15,16,17,17,17,18,18, 19, /* 31dB */
  142365. 19,19,20,21,22,23,24, 25, /* 39dB */
  142366. }},
  142367. /* mode A short */
  142368. {{
  142369. 0, 1, 2, 3, 4, 5, 5, 5, /* 7dB */
  142370. 6, 6, 6, 5, 4, 4, 4, 4, /* 15dB */
  142371. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  142372. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  142373. 11,12,13,14,15,16,17, 18, /* 39dB */
  142374. }},
  142375. /* sub-mode Z long */
  142376. {{
  142377. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142378. 8, 9,10,11,12,13,14, 15, /* 15dB */
  142379. 16,17,18,19,20,21,22, 23, /* 23dB */
  142380. 24,25,26,27,28,29,30, 31, /* 31dB */
  142381. 32,33,34,35,36,37,38, 39, /* 39dB */
  142382. }},
  142383. /* mode_Z nominal long */
  142384. {{
  142385. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142386. 8, 9,10,11,12,12,13, 13, /* 15dB */
  142387. 13,14,14,14,15,15,15, 15, /* 23dB */
  142388. 16,16,17,17,17,18,18, 19, /* 31dB */
  142389. 19,19,20,21,22,23,24, 25, /* 39dB */
  142390. }},
  142391. /* mode A long */
  142392. {{
  142393. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142394. 8, 8, 7, 6, 5, 4, 4, 4, /* 15dB */
  142395. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  142396. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  142397. 11,12,13,14,15,16,17, 18, /* 39dB */
  142398. }}
  142399. };
  142400. /* tonal masking curve level adjustments *************************/
  142401. static vp_adjblock _vp_tonemask_adj_longblock[12]={
  142402. /* 63 125 250 500 1 2 4 8 16 */
  142403. {{ -3, -8,-13,-15,-10,-10,-10,-10,-10,-10,-10, 0, 0, 0, 0, 0, 0}}, /* -1 */
  142404. /* {{-15,-15,-15,-15,-10, -8, -4, -2, 0, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  142405. {{ -4,-10,-14,-16,-15,-14,-13,-12,-12,-12,-11, -1, -1, -1, -1, -1, 0}}, /* 0 */
  142406. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  142407. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, -1, -1, 0}}, /* 1 */
  142408. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  142409. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -6, -3, -1, -1, -1, 0}}, /* 2 */
  142410. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  142411. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, -1, -1, 0}}, /* 3 */
  142412. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, *//* 4 */
  142413. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  142414. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  142415. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  142416. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  142417. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  142418. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  142419. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  142420. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  142421. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  142422. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  142423. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  142424. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  142425. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  142426. };
  142427. static vp_adjblock _vp_tonemask_adj_otherblock[12]={
  142428. /* 63 125 250 500 1 2 4 8 16 */
  142429. {{ -3, -8,-13,-15,-10,-10, -9, -9, -9, -9, -9, 1, 1, 1, 1, 1, 1}}, /* -1 */
  142430. /* {{-20,-20,-20,-20,-14,-12,-10, -8, -4, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  142431. {{ -4,-10,-14,-16,-14,-13,-12,-12,-11,-11,-10, 0, 0, 0, 0, 0, 0}}, /* 0 */
  142432. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  142433. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, 0, 0, 0}}, /* 1 */
  142434. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  142435. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -5, -2, -1, 0, 0, 0}}, /* 2 */
  142436. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  142437. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, 0, 0, 0}}, /* 3 */
  142438. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 4 */
  142439. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  142440. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  142441. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  142442. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  142443. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  142444. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  142445. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  142446. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  142447. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  142448. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  142449. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  142450. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  142451. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  142452. };
  142453. /* noise bias (transition block) */
  142454. static noise3 _psy_noisebias_trans[12]={
  142455. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142456. /* -1 */
  142457. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142458. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142459. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142460. /* 0
  142461. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142462. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 4, 10},
  142463. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  142464. {{{-15,-15,-15,-15,-15,-12, -6, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142465. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 3, 6},
  142466. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142467. /* 1
  142468. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142469. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  142470. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  142471. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142472. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  142473. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  142474. /* 2
  142475. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142476. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  142477. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}}, */
  142478. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142479. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  142480. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -7, -4}}},
  142481. /* 3
  142482. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142483. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  142484. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142485. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142486. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  142487. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142488. /* 4
  142489. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142490. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  142491. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142492. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142493. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  142494. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142495. /* 5
  142496. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142497. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  142498. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}}, */
  142499. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142500. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  142501. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},
  142502. /* 6
  142503. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142504. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  142505. {-34,-34,-34,-34,-30,-26,-24,-18,-17,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  142506. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142507. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  142508. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},
  142509. /* 7
  142510. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142511. {-32,-32,-32,-32,-28,-24,-24,-18,-14,-12,-10, -8, -8, -8, -6, -4, 0},
  142512. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},*/
  142513. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142514. {-32,-32,-32,-32,-28,-24,-24,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  142515. {-34,-34,-34,-34,-30,-26,-26,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  142516. /* 8
  142517. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  142518. {-36,-36,-36,-36,-30,-30,-30,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  142519. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  142520. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  142521. {-36,-36,-36,-36,-30,-30,-30,-24,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  142522. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142523. /* 9
  142524. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142525. {-36,-36,-36,-36,-34,-32,-32,-28,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  142526. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  142527. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142528. {-38,-38,-38,-38,-36,-34,-34,-30,-24,-20,-20,-20,-20,-18,-16,-12,-10},
  142529. {-40,-40,-40,-40,-40,-40,-40,-38,-35,-35,-35,-35,-35,-35,-35,-35,-30}}},
  142530. /* 10 */
  142531. {{{-30,-30,-30,-30,-30,-30,-30,-28,-20,-14,-14,-14,-14,-14,-14,-12,-10},
  142532. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-20},
  142533. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142534. };
  142535. /* noise bias (long block) */
  142536. static noise3 _psy_noisebias_long[12]={
  142537. /*63 125 250 500 1k 2k 4k 8k 16k*/
  142538. /* -1 */
  142539. {{{-10,-10,-10,-10,-10, -4, 0, 0, 0, 6, 6, 6, 6, 10, 10, 12, 20},
  142540. {-20,-20,-20,-20,-20,-20,-10, -2, 0, 0, 0, 0, 0, 2, 4, 6, 15},
  142541. {-20,-20,-20,-20,-20,-20,-20,-10, -6, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142542. /* 0 */
  142543. /* {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  142544. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 4, 10},
  142545. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  142546. {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  142547. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 3, 6},
  142548. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142549. /* 1 */
  142550. /* {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142551. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  142552. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  142553. {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142554. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  142555. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  142556. /* 2 */
  142557. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142558. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  142559. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142560. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142561. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  142562. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142563. /* 3 */
  142564. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142565. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  142566. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142567. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142568. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  142569. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -5}}},
  142570. /* 4 */
  142571. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142572. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  142573. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142574. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142575. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  142576. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -7}}},
  142577. /* 5 */
  142578. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142579. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  142580. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},*/
  142581. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142582. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  142583. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -8}}},
  142584. /* 6 */
  142585. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142586. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  142587. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  142588. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142589. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  142590. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12,-10}}},
  142591. /* 7 */
  142592. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142593. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-10, -8, -8, -8, -8, -6, -4, 0},
  142594. {-26,-26,-26,-26,-26,-26,-26,-22,-20,-19,-19,-19,-19,-18,-17,-16,-12}}},
  142595. /* 8 */
  142596. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 0, 0, 0, 0, 1, 2, 3, 7},
  142597. {-26,-26,-26,-26,-26,-26,-26,-20,-16,-12,-10,-10,-10,-10, -8, -6, -2},
  142598. {-28,-28,-28,-28,-28,-28,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  142599. /* 9 */
  142600. {{{-22,-22,-22,-22,-22,-22,-22,-18,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142601. {-26,-26,-26,-26,-26,-26,-26,-22,-18,-16,-16,-16,-16,-14,-12,-10, -7},
  142602. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142603. /* 10 */
  142604. {{{-24,-24,-24,-24,-24,-24,-24,-24,-24,-18,-14,-14,-14,-14,-14,-12,-10},
  142605. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-20},
  142606. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142607. };
  142608. /* noise bias (impulse block) */
  142609. static noise3 _psy_noisebias_impulse[12]={
  142610. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142611. /* -1 */
  142612. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142613. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142614. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142615. /* 0 */
  142616. /* {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  142617. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 4, 10},
  142618. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},*/
  142619. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  142620. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 3, 6},
  142621. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142622. /* 1 */
  142623. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  142624. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -4, -4, -2, -2, -2, -2, 2},
  142625. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8,-10,-10, -8, -8, -8, -6, -4}}},
  142626. /* 2 */
  142627. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142628. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142629. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142630. /* 3 */
  142631. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  142632. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142633. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142634. /* 4 */
  142635. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  142636. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142637. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142638. /* 5 */
  142639. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142640. {-32,-32,-32,-32,-28,-24,-22,-16,-10, -6, -8, -8, -6, -6, -6, -4, -2},
  142641. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-12,-12,-12,-12,-12,-10, -9, -5}}},
  142642. /* 6
  142643. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142644. {-34,-34,-34,-34,-30,-30,-24,-20,-12,-12,-14,-14,-10, -9, -8, -6, -4},
  142645. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-15,-15,-15,-15,-15,-13,-12, -8}}},*/
  142646. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142647. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-16,-16,-16,-16,-16,-14,-14,-12},
  142648. {-36,-36,-36,-36,-36,-34,-28,-24,-20,-20,-20,-20,-20,-20,-20,-18,-16}}},
  142649. /* 7 */
  142650. /* {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  142651. {-34,-34,-34,-34,-30,-30,-24,-20,-14,-14,-16,-16,-14,-12,-10,-10,-10},
  142652. {-34,-34,-34,-34,-32,-32,-30,-24,-20,-19,-19,-19,-19,-19,-17,-16,-12}}},*/
  142653. {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  142654. {-34,-34,-34,-34,-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-24,-22},
  142655. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  142656. /* 8 */
  142657. /* {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  142658. {-34,-34,-34,-34,-30,-30,-30,-24,-20,-20,-20,-20,-20,-18,-16,-16,-14},
  142659. {-36,-36,-36,-36,-36,-34,-28,-24,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  142660. {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  142661. {-34,-34,-34,-34,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-24},
  142662. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  142663. /* 9 */
  142664. /* {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142665. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-22,-20,-20,-18},
  142666. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  142667. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142668. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26},
  142669. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142670. /* 10 */
  142671. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-16,-16,-16,-16,-16,-14,-12},
  142672. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-26},
  142673. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142674. };
  142675. /* noise bias (padding block) */
  142676. static noise3 _psy_noisebias_padding[12]={
  142677. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142678. /* -1 */
  142679. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142680. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142681. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142682. /* 0 */
  142683. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142684. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, 2, 3, 6, 6, 8, 10},
  142685. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -4, -4, -4, -4, -2, 0, 2}}},
  142686. /* 1 */
  142687. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  142688. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  142689. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -6, -4, -2, 0}}},
  142690. /* 2 */
  142691. /* {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142692. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  142693. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},*/
  142694. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142695. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  142696. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142697. /* 3 */
  142698. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  142699. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  142700. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142701. /* 4 */
  142702. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  142703. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, -1, 0, 2, 6},
  142704. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142705. /* 5 */
  142706. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142707. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -3, -3, -3, -3, -2, 0, 4},
  142708. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-10,-10,-10,-10,-10, -8, -5, -3}}},
  142709. /* 6 */
  142710. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142711. {-34,-34,-34,-34,-30,-30,-24,-20,-14, -8, -4, -4, -4, -4, -3, -1, 4},
  142712. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-13,-13,-13,-13,-13,-11, -8, -6}}},
  142713. /* 7 */
  142714. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142715. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-10, -8, -6, -6, -6, -5, -3, 1},
  142716. {-34,-34,-34,-34,-32,-32,-28,-22,-18,-16,-16,-16,-16,-16,-14,-12,-10}}},
  142717. /* 8 */
  142718. {{{-22,-22,-22,-22,-22,-20,-14,-10, -4, 0, 0, 0, 0, 3, 5, 5, 11},
  142719. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-12,-10, -8, -8, -8, -7, -5, -2},
  142720. {-36,-36,-36,-36,-36,-34,-28,-22,-20,-20,-20,-20,-20,-20,-20,-16,-14}}},
  142721. /* 9 */
  142722. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -2, -2, -2, -2, 0, 2, 6},
  142723. {-36,-36,-36,-36,-34,-32,-32,-24,-16,-12,-12,-12,-12,-12,-10, -8, -5},
  142724. {-40,-40,-40,-40,-40,-40,-40,-32,-26,-24,-24,-24,-24,-24,-24,-20,-18}}},
  142725. /* 10 */
  142726. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-12,-12,-12,-12,-12,-10, -8},
  142727. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-25,-25,-25,-25,-25,-25,-15},
  142728. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142729. };
  142730. static noiseguard _psy_noiseguards_44[4]={
  142731. {3,3,15},
  142732. {3,3,15},
  142733. {10,10,100},
  142734. {10,10,100},
  142735. };
  142736. static int _psy_tone_suppress[12]={
  142737. -20,-20,-20,-20,-20,-24,-30,-40,-40,-45,-45,-45,
  142738. };
  142739. static int _psy_tone_0dB[12]={
  142740. 90,90,95,95,95,95,105,105,105,105,105,105,
  142741. };
  142742. static int _psy_noise_suppress[12]={
  142743. -20,-20,-24,-24,-24,-24,-30,-40,-40,-45,-45,-45,
  142744. };
  142745. static vorbis_info_psy _psy_info_template={
  142746. /* blockflag */
  142747. -1,
  142748. /* ath_adjatt, ath_maxatt */
  142749. -140.,-140.,
  142750. /* tonemask att boost/decay,suppr,curves */
  142751. {0.f,0.f,0.f}, 0.,0., -40.f, {0.},
  142752. /*noisemaskp,supp, low/high window, low/hi guard, minimum */
  142753. 1, -0.f, .5f, .5f, 0,0,0,
  142754. /* noiseoffset*3, noisecompand, max_curve_dB */
  142755. {{-1},{-1},{-1}},{-1},105.f,
  142756. /* noise normalization - channel_p, point_p, start, partition, thresh. */
  142757. 0,0,-1,-1,0.,
  142758. };
  142759. /* ath ****************/
  142760. static int _psy_ath_floater[12]={
  142761. -100,-100,-100,-100,-100,-100,-105,-105,-105,-105,-110,-120,
  142762. };
  142763. static int _psy_ath_abs[12]={
  142764. -130,-130,-130,-130,-140,-140,-140,-140,-140,-140,-140,-150,
  142765. };
  142766. /* stereo setup. These don't map directly to quality level, there's
  142767. an additional indirection as several of the below may be used in a
  142768. single bitmanaged stream
  142769. ****************/
  142770. /* various stereo possibilities */
  142771. /* stereo mode by base quality level */
  142772. static adj_stereo _psy_stereo_modes_44[12]={
  142773. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 -1 */
  142774. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  142775. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  142776. { 1, 2, 3, 4, 4, 4, 4, 4, 4, 5, 6, 7, 8, 8, 8},
  142777. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  142778. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 0 */
  142779. /*{{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  142780. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  142781. { 1, 2, 3, 4, 5, 5, 6, 6, 6, 6, 6, 7, 8, 8, 8},
  142782. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142783. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 1, 0, 0, 0, 0, 0},
  142784. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  142785. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142786. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  142787. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 */
  142788. {{ 3, 3, 3, 3, 3, 3, 3, 3, 2, 1, 0, 0, 0, 0, 0},
  142789. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  142790. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142791. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142792. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 2 */
  142793. /* {{ 3, 3, 3, 3, 3, 3, 2, 2, 2, 1, 0, 0, 0, 0, 0},
  142794. { 8, 8, 8, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3, 2, 1},
  142795. { 3, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142796. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  142797. {{ 3, 3, 3, 3, 3, 3, 3, 2, 1, 1, 0, 0, 0, 0, 0},
  142798. { 8, 8, 6, 6, 5, 5, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  142799. { 3, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142800. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142801. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 3 */
  142802. {{ 2, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0},
  142803. { 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  142804. { 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 10, 10, 10, 10, 10},
  142805. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142806. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 4 */
  142807. {{ 2, 2, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142808. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 2, 1, 0},
  142809. { 6, 6, 6, 8, 8, 8, 8, 8, 8, 8, 10, 10, 10, 10, 10},
  142810. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142811. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 5 */
  142812. /* {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142813. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  142814. { 6, 6, 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142815. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142816. {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142817. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  142818. { 6, 7, 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12},
  142819. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142820. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 6 */
  142821. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142822. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142823. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142824. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  142825. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142826. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142827. { 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142828. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142829. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 7 */
  142830. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142831. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142832. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142833. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142834. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142835. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142836. { 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142837. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142838. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 8 */
  142839. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142840. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142841. { 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142842. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142843. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142844. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142845. { 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142846. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142847. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 9 */
  142848. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142849. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142850. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  142851. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142852. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 10 */
  142853. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142854. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142855. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  142856. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142857. };
  142858. /* tone master attenuation by base quality mode and bitrate tweak */
  142859. static att3 _psy_tone_masteratt_44[12]={
  142860. {{ 35, 21, 9}, 0, 0}, /* -1 */
  142861. {{ 30, 20, 8}, -2, 1.25}, /* 0 */
  142862. /* {{ 25, 14, 4}, 0, 0}, *//* 1 */
  142863. {{ 25, 12, 2}, 0, 0}, /* 1 */
  142864. /* {{ 20, 10, -2}, 0, 0}, *//* 2 */
  142865. {{ 20, 9, -3}, 0, 0}, /* 2 */
  142866. {{ 20, 9, -4}, 0, 0}, /* 3 */
  142867. {{ 20, 9, -4}, 0, 0}, /* 4 */
  142868. {{ 20, 6, -6}, 0, 0}, /* 5 */
  142869. {{ 20, 3, -10}, 0, 0}, /* 6 */
  142870. {{ 18, 1, -14}, 0, 0}, /* 7 */
  142871. {{ 18, 0, -16}, 0, 0}, /* 8 */
  142872. {{ 18, -2, -16}, 0, 0}, /* 9 */
  142873. {{ 12, -2, -20}, 0, 0}, /* 10 */
  142874. };
  142875. /* lowpass by mode **************/
  142876. static double _psy_lowpass_44[12]={
  142877. /* 15.1,15.8,16.5,17.9,20.5,48.,999.,999.,999.,999.,999. */
  142878. 13.9,15.1,15.8,16.5,17.2,18.9,20.1,48.,999.,999.,999.,999.
  142879. };
  142880. /* noise normalization **********/
  142881. static int _noise_start_short_44[11]={
  142882. /* 16,16,16,16,32,32,9999,9999,9999,9999 */
  142883. 32,16,16,16,32,9999,9999,9999,9999,9999,9999
  142884. };
  142885. static int _noise_start_long_44[11]={
  142886. /* 128,128,128,256,512,512,9999,9999,9999,9999 */
  142887. 256,128,128,256,512,9999,9999,9999,9999,9999,9999
  142888. };
  142889. static int _noise_part_short_44[11]={
  142890. 8,8,8,8,8,8,8,8,8,8,8
  142891. };
  142892. static int _noise_part_long_44[11]={
  142893. 32,32,32,32,32,32,32,32,32,32,32
  142894. };
  142895. static double _noise_thresh_44[11]={
  142896. /* .2,.2,.3,.4,.5,.5,9999.,9999.,9999.,9999., */
  142897. .2,.2,.2,.4,.6,9999.,9999.,9999.,9999.,9999.,9999.,
  142898. };
  142899. static double _noise_thresh_5only[2]={
  142900. .5,.5,
  142901. };
  142902. /*** End of inlined file: psych_44.h ***/
  142903. static double rate_mapping_44_stereo[12]={
  142904. 22500.,32000.,40000.,48000.,56000.,64000.,
  142905. 80000.,96000.,112000.,128000.,160000.,250001.
  142906. };
  142907. static double quality_mapping_44[12]={
  142908. -.1,.0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0
  142909. };
  142910. static int blocksize_short_44[11]={
  142911. 512,256,256,256,256,256,256,256,256,256,256
  142912. };
  142913. static int blocksize_long_44[11]={
  142914. 4096,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048
  142915. };
  142916. static double _psy_compand_short_mapping[12]={
  142917. 0.5, 1., 1., 1.3, 1.6, 2., 2., 2., 2., 2., 2., 2.
  142918. };
  142919. static double _psy_compand_long_mapping[12]={
  142920. 3.5, 4., 4., 4.3, 4.6, 5., 5., 5., 5., 5., 5., 5.
  142921. };
  142922. static double _global_mapping_44[12]={
  142923. /* 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.5, 4., 4. */
  142924. 0., 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.7, 4., 4.
  142925. };
  142926. static int _floor_short_mapping_44[11]={
  142927. 1,0,0,2,2,4,5,5,5,5,5
  142928. };
  142929. static int _floor_long_mapping_44[11]={
  142930. 8,7,7,7,7,7,7,7,7,7,7
  142931. };
  142932. ve_setup_data_template ve_setup_44_stereo={
  142933. 11,
  142934. rate_mapping_44_stereo,
  142935. quality_mapping_44,
  142936. 2,
  142937. 40000,
  142938. 50000,
  142939. blocksize_short_44,
  142940. blocksize_long_44,
  142941. _psy_tone_masteratt_44,
  142942. _psy_tone_0dB,
  142943. _psy_tone_suppress,
  142944. _vp_tonemask_adj_otherblock,
  142945. _vp_tonemask_adj_longblock,
  142946. _vp_tonemask_adj_otherblock,
  142947. _psy_noiseguards_44,
  142948. _psy_noisebias_impulse,
  142949. _psy_noisebias_padding,
  142950. _psy_noisebias_trans,
  142951. _psy_noisebias_long,
  142952. _psy_noise_suppress,
  142953. _psy_compand_44,
  142954. _psy_compand_short_mapping,
  142955. _psy_compand_long_mapping,
  142956. {_noise_start_short_44,_noise_start_long_44},
  142957. {_noise_part_short_44,_noise_part_long_44},
  142958. _noise_thresh_44,
  142959. _psy_ath_floater,
  142960. _psy_ath_abs,
  142961. _psy_lowpass_44,
  142962. _psy_global_44,
  142963. _global_mapping_44,
  142964. _psy_stereo_modes_44,
  142965. _floor_books,
  142966. _floor,
  142967. _floor_short_mapping_44,
  142968. _floor_long_mapping_44,
  142969. _mapres_template_44_stereo
  142970. };
  142971. /*** End of inlined file: setup_44.h ***/
  142972. /*** Start of inlined file: setup_44u.h ***/
  142973. /*** Start of inlined file: residue_44u.h ***/
  142974. /*** Start of inlined file: res_books_uncoupled.h ***/
  142975. static long _vq_quantlist__16u0__p1_0[] = {
  142976. 1,
  142977. 0,
  142978. 2,
  142979. };
  142980. static long _vq_lengthlist__16u0__p1_0[] = {
  142981. 1, 4, 4, 5, 7, 7, 5, 7, 8, 5, 8, 8, 8,10,10, 8,
  142982. 10,11, 5, 8, 8, 8,10,10, 8,10,10, 4, 9, 9, 9,12,
  142983. 11, 8,11,11, 8,12,11,10,12,14,10,13,13, 7,11,11,
  142984. 10,14,12,11,14,14, 4, 9, 9, 8,11,11, 9,11,12, 7,
  142985. 11,11,10,13,14,10,12,14, 8,11,12,10,14,14,10,13,
  142986. 12,
  142987. };
  142988. static float _vq_quantthresh__16u0__p1_0[] = {
  142989. -0.5, 0.5,
  142990. };
  142991. static long _vq_quantmap__16u0__p1_0[] = {
  142992. 1, 0, 2,
  142993. };
  142994. static encode_aux_threshmatch _vq_auxt__16u0__p1_0 = {
  142995. _vq_quantthresh__16u0__p1_0,
  142996. _vq_quantmap__16u0__p1_0,
  142997. 3,
  142998. 3
  142999. };
  143000. static static_codebook _16u0__p1_0 = {
  143001. 4, 81,
  143002. _vq_lengthlist__16u0__p1_0,
  143003. 1, -535822336, 1611661312, 2, 0,
  143004. _vq_quantlist__16u0__p1_0,
  143005. NULL,
  143006. &_vq_auxt__16u0__p1_0,
  143007. NULL,
  143008. 0
  143009. };
  143010. static long _vq_quantlist__16u0__p2_0[] = {
  143011. 1,
  143012. 0,
  143013. 2,
  143014. };
  143015. static long _vq_lengthlist__16u0__p2_0[] = {
  143016. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 9, 7,
  143017. 8, 9, 5, 7, 7, 7, 9, 8, 7, 9, 7, 4, 7, 7, 7, 9,
  143018. 9, 7, 8, 8, 6, 9, 8, 7, 8,11, 9,11,10, 6, 8, 9,
  143019. 8,11, 8, 9,10,11, 4, 7, 7, 7, 8, 8, 7, 9, 9, 6,
  143020. 9, 8, 9,11,10, 8, 8,11, 6, 8, 9, 9,10,11, 8,11,
  143021. 8,
  143022. };
  143023. static float _vq_quantthresh__16u0__p2_0[] = {
  143024. -0.5, 0.5,
  143025. };
  143026. static long _vq_quantmap__16u0__p2_0[] = {
  143027. 1, 0, 2,
  143028. };
  143029. static encode_aux_threshmatch _vq_auxt__16u0__p2_0 = {
  143030. _vq_quantthresh__16u0__p2_0,
  143031. _vq_quantmap__16u0__p2_0,
  143032. 3,
  143033. 3
  143034. };
  143035. static static_codebook _16u0__p2_0 = {
  143036. 4, 81,
  143037. _vq_lengthlist__16u0__p2_0,
  143038. 1, -535822336, 1611661312, 2, 0,
  143039. _vq_quantlist__16u0__p2_0,
  143040. NULL,
  143041. &_vq_auxt__16u0__p2_0,
  143042. NULL,
  143043. 0
  143044. };
  143045. static long _vq_quantlist__16u0__p3_0[] = {
  143046. 2,
  143047. 1,
  143048. 3,
  143049. 0,
  143050. 4,
  143051. };
  143052. static long _vq_lengthlist__16u0__p3_0[] = {
  143053. 1, 5, 5, 7, 7, 6, 7, 7, 8, 8, 6, 7, 8, 8, 8, 8,
  143054. 9, 9,11,11, 8, 9, 9,11,11, 6, 9, 8,10,10, 8,10,
  143055. 10,11,11, 8,10,10,11,11,10,11,10,13,12, 9,11,10,
  143056. 13,13, 6, 8, 9,10,10, 8,10,10,11,11, 8,10,10,11,
  143057. 11, 9,10,11,13,12,10,10,11,12,12, 8,11,11,14,13,
  143058. 10,12,11,15,13, 9,12,11,15,14,12,14,13,16,14,12,
  143059. 13,13,17,14, 8,11,11,13,14, 9,11,12,14,15,10,11,
  143060. 12,13,15,11,13,13,14,16,12,13,14,14,16, 5, 9, 9,
  143061. 11,11, 9,11,11,12,12, 8,11,11,12,12,11,12,12,15,
  143062. 14,10,12,12,15,15, 8,11,11,13,12,10,12,12,13,13,
  143063. 10,12,12,14,13,12,12,13,14,15,11,13,13,17,16, 7,
  143064. 11,11,13,13,10,12,12,14,13,10,12,12,13,14,12,13,
  143065. 12,15,14,11,13,13,15,14, 9,12,12,16,15,11,13,13,
  143066. 17,16,10,13,13,16,16,13,14,15,15,16,13,15,14,19,
  143067. 17, 9,12,12,14,16,11,13,13,15,16,10,13,13,17,16,
  143068. 13,14,13,17,15,12,15,15,16,17, 5, 9, 9,11,11, 8,
  143069. 11,11,13,12, 9,11,11,12,12,10,12,12,14,15,11,12,
  143070. 12,14,14, 7,11,10,13,12,10,12,12,14,13,10,11,12,
  143071. 13,13,11,13,13,15,16,12,12,13,15,15, 7,11,11,13,
  143072. 13,10,13,13,14,14,10,12,12,13,13,11,13,13,16,15,
  143073. 12,13,13,15,14, 9,12,12,15,15,10,13,13,17,16,11,
  143074. 12,13,15,15,12,15,14,18,18,13,14,14,16,17, 9,12,
  143075. 12,15,16,10,13,13,15,16,11,13,13,15,16,13,15,15,
  143076. 17,17,13,15,14,16,15, 7,11,11,15,16,10,13,12,16,
  143077. 17,10,12,13,15,17,15,16,16,18,17,13,15,15,17,18,
  143078. 8,12,12,16,16,11,13,14,17,18,11,13,13,18,16,15,
  143079. 17,16,17,19,14,15,15,17,16, 8,12,12,16,15,11,14,
  143080. 13,18,17,11,13,14,18,17,15,16,16,18,17,13,16,16,
  143081. 18,18,11,15,14,18,17,13,14,15,18, 0,12,15,15, 0,
  143082. 17,17,16,17,17,18,14,16,18,18, 0,11,14,14,17, 0,
  143083. 12,15,14,17,19,12,15,14,18, 0,15,18,16, 0,17,14,
  143084. 18,16,18, 0, 7,11,11,16,15,10,12,12,18,16,10,13,
  143085. 13,16,15,13,15,14,17,17,14,16,16,19,18, 8,12,12,
  143086. 16,16,11,13,13,18,16,11,13,14,17,16,14,15,15,19,
  143087. 18,15,16,16, 0,19, 8,12,12,16,17,11,13,13,17,17,
  143088. 11,14,13,17,17,13,15,15,17,19,15,17,17,19, 0,11,
  143089. 14,15,19,17,12,15,16,18,18,12,14,15,19,17,14,16,
  143090. 17, 0,18,16,16,19,17, 0,11,14,14,18,19,12,15,14,
  143091. 17,17,13,16,14,17,16,14,17,16,18,18,15,18,15, 0,
  143092. 18,
  143093. };
  143094. static float _vq_quantthresh__16u0__p3_0[] = {
  143095. -1.5, -0.5, 0.5, 1.5,
  143096. };
  143097. static long _vq_quantmap__16u0__p3_0[] = {
  143098. 3, 1, 0, 2, 4,
  143099. };
  143100. static encode_aux_threshmatch _vq_auxt__16u0__p3_0 = {
  143101. _vq_quantthresh__16u0__p3_0,
  143102. _vq_quantmap__16u0__p3_0,
  143103. 5,
  143104. 5
  143105. };
  143106. static static_codebook _16u0__p3_0 = {
  143107. 4, 625,
  143108. _vq_lengthlist__16u0__p3_0,
  143109. 1, -533725184, 1611661312, 3, 0,
  143110. _vq_quantlist__16u0__p3_0,
  143111. NULL,
  143112. &_vq_auxt__16u0__p3_0,
  143113. NULL,
  143114. 0
  143115. };
  143116. static long _vq_quantlist__16u0__p4_0[] = {
  143117. 2,
  143118. 1,
  143119. 3,
  143120. 0,
  143121. 4,
  143122. };
  143123. static long _vq_lengthlist__16u0__p4_0[] = {
  143124. 3, 5, 5, 8, 8, 6, 6, 6, 9, 9, 6, 6, 6, 9, 9, 9,
  143125. 10, 9,11,11, 9, 9, 9,11,11, 6, 7, 7,10,10, 7, 7,
  143126. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  143127. 11,12, 6, 7, 7,10,10, 7, 8, 7,10,10, 7, 8, 7,10,
  143128. 10,10,11,10,12,11,10,10,10,13,10, 9,10,10,12,12,
  143129. 10,11,10,14,12, 9,11,11,13,13,11,12,13,13,13,11,
  143130. 12,12,15,13, 9,10,10,12,13, 9,11,10,12,13,10,10,
  143131. 11,12,13,11,12,12,12,13,11,12,12,13,13, 5, 7, 7,
  143132. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  143133. 13,10,10,11,12,12, 6, 8, 8,11,10, 7, 8, 9,10,12,
  143134. 8, 9, 9,11,11,11,10,11,11,12,10,11,11,13,12, 7,
  143135. 8, 8,10,11, 8, 9, 8,11,10, 8, 9, 9,11,11,10,12,
  143136. 10,13,11,10,11,11,13,13,10,11,10,14,13,10,10,11,
  143137. 13,13,10,12,11,14,13,12,11,13,12,13,13,12,13,14,
  143138. 14,10,11,11,13,13,10,11,10,12,13,10,12,12,12,14,
  143139. 12,12,12,14,12,12,13,12,17,15, 5, 7, 7,10,10, 7,
  143140. 8, 8,10,10, 7, 8, 8,11,10,10,10,11,12,12,10,11,
  143141. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  143142. 10,11,11,11,11,12,12,10,10,11,12,13, 6, 8, 8,10,
  143143. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,12,12,13,13,
  143144. 11,11,10,13,11, 9,11,10,14,13,11,11,11,15,13,10,
  143145. 10,11,13,13,12,13,13,14,14,12,11,12,12,13,10,11,
  143146. 11,12,13,10,11,12,13,13,10,11,10,13,12,12,12,13,
  143147. 14, 0,12,13,11,13,11, 8,10,10,13,13,10,11,11,14,
  143148. 13,10,11,11,13,12,13,14,14,14,15,12,12,12,15,14,
  143149. 9,11,10,13,12,10,10,11,13,14,11,11,11,15,12,13,
  143150. 12,14,15,16,13,13,13,14,13, 9,11,11,12,12,10,12,
  143151. 11,13,13,10,11,11,13,14,13,13,13,15,15,13,13,14,
  143152. 17,15,11,12,12,14,14,10,11,12,13,15,12,13,13, 0,
  143153. 15,13,11,14,12,16,14,16,14, 0,15,11,12,12,14,16,
  143154. 11,13,12,16,15,12,13,13,14,15,12,14,12,15,13,15,
  143155. 14,14,16,16, 8,10,10,13,13,10,11,10,13,14,10,11,
  143156. 11,13,13,13,13,12,14,14,14,13,13,16,17, 9,10,10,
  143157. 12,14,10,12,11,14,13,10,11,12,13,14,12,12,12,15,
  143158. 15,13,13,13,14,14, 9,10,10,13,13,10,11,12,12,14,
  143159. 10,11,10,13,13,13,13,13,14,16,13,13,13,14,14,11,
  143160. 12,13,15,13,12,14,13,14,16,12,12,13,13,14,13,14,
  143161. 14,17,15,13,12,17,13,16,11,12,13,14,15,12,13,14,
  143162. 14,17,11,12,11,14,14,13,16,14,16, 0,14,15,11,15,
  143163. 11,
  143164. };
  143165. static float _vq_quantthresh__16u0__p4_0[] = {
  143166. -1.5, -0.5, 0.5, 1.5,
  143167. };
  143168. static long _vq_quantmap__16u0__p4_0[] = {
  143169. 3, 1, 0, 2, 4,
  143170. };
  143171. static encode_aux_threshmatch _vq_auxt__16u0__p4_0 = {
  143172. _vq_quantthresh__16u0__p4_0,
  143173. _vq_quantmap__16u0__p4_0,
  143174. 5,
  143175. 5
  143176. };
  143177. static static_codebook _16u0__p4_0 = {
  143178. 4, 625,
  143179. _vq_lengthlist__16u0__p4_0,
  143180. 1, -533725184, 1611661312, 3, 0,
  143181. _vq_quantlist__16u0__p4_0,
  143182. NULL,
  143183. &_vq_auxt__16u0__p4_0,
  143184. NULL,
  143185. 0
  143186. };
  143187. static long _vq_quantlist__16u0__p5_0[] = {
  143188. 4,
  143189. 3,
  143190. 5,
  143191. 2,
  143192. 6,
  143193. 1,
  143194. 7,
  143195. 0,
  143196. 8,
  143197. };
  143198. static long _vq_lengthlist__16u0__p5_0[] = {
  143199. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  143200. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  143201. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 7, 8, 8,
  143202. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  143203. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,10,11,11,12,
  143204. 12,
  143205. };
  143206. static float _vq_quantthresh__16u0__p5_0[] = {
  143207. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143208. };
  143209. static long _vq_quantmap__16u0__p5_0[] = {
  143210. 7, 5, 3, 1, 0, 2, 4, 6,
  143211. 8,
  143212. };
  143213. static encode_aux_threshmatch _vq_auxt__16u0__p5_0 = {
  143214. _vq_quantthresh__16u0__p5_0,
  143215. _vq_quantmap__16u0__p5_0,
  143216. 9,
  143217. 9
  143218. };
  143219. static static_codebook _16u0__p5_0 = {
  143220. 2, 81,
  143221. _vq_lengthlist__16u0__p5_0,
  143222. 1, -531628032, 1611661312, 4, 0,
  143223. _vq_quantlist__16u0__p5_0,
  143224. NULL,
  143225. &_vq_auxt__16u0__p5_0,
  143226. NULL,
  143227. 0
  143228. };
  143229. static long _vq_quantlist__16u0__p6_0[] = {
  143230. 6,
  143231. 5,
  143232. 7,
  143233. 4,
  143234. 8,
  143235. 3,
  143236. 9,
  143237. 2,
  143238. 10,
  143239. 1,
  143240. 11,
  143241. 0,
  143242. 12,
  143243. };
  143244. static long _vq_lengthlist__16u0__p6_0[] = {
  143245. 1, 4, 4, 7, 7,10,10,12,12,13,13,18,17, 3, 6, 6,
  143246. 9, 9,11,11,13,13,14,14,18,17, 3, 6, 6, 9, 9,11,
  143247. 11,13,13,14,14,17,18, 7, 9, 9,11,11,13,13,14,14,
  143248. 15,15, 0, 0, 7, 9, 9,11,11,13,13,14,14,15,16,19,
  143249. 18,10,11,11,13,13,14,14,16,15,17,18, 0, 0,10,11,
  143250. 11,13,13,14,14,15,15,16,18, 0, 0,11,13,13,14,14,
  143251. 15,15,17,17, 0,19, 0, 0,11,13,13,14,14,14,15,16,
  143252. 18, 0,19, 0, 0,13,14,14,15,15,18,17,18,18, 0,19,
  143253. 0, 0,13,14,14,15,16,16,16,18,18,19, 0, 0, 0,16,
  143254. 17,17, 0,17,19,19, 0,19, 0, 0, 0, 0,16,19,16,17,
  143255. 18, 0,19, 0, 0, 0, 0, 0, 0,
  143256. };
  143257. static float _vq_quantthresh__16u0__p6_0[] = {
  143258. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  143259. 12.5, 17.5, 22.5, 27.5,
  143260. };
  143261. static long _vq_quantmap__16u0__p6_0[] = {
  143262. 11, 9, 7, 5, 3, 1, 0, 2,
  143263. 4, 6, 8, 10, 12,
  143264. };
  143265. static encode_aux_threshmatch _vq_auxt__16u0__p6_0 = {
  143266. _vq_quantthresh__16u0__p6_0,
  143267. _vq_quantmap__16u0__p6_0,
  143268. 13,
  143269. 13
  143270. };
  143271. static static_codebook _16u0__p6_0 = {
  143272. 2, 169,
  143273. _vq_lengthlist__16u0__p6_0,
  143274. 1, -526516224, 1616117760, 4, 0,
  143275. _vq_quantlist__16u0__p6_0,
  143276. NULL,
  143277. &_vq_auxt__16u0__p6_0,
  143278. NULL,
  143279. 0
  143280. };
  143281. static long _vq_quantlist__16u0__p6_1[] = {
  143282. 2,
  143283. 1,
  143284. 3,
  143285. 0,
  143286. 4,
  143287. };
  143288. static long _vq_lengthlist__16u0__p6_1[] = {
  143289. 1, 4, 5, 6, 6, 4, 6, 6, 6, 6, 4, 6, 6, 6, 6, 6,
  143290. 6, 6, 7, 7, 6, 6, 6, 7, 7,
  143291. };
  143292. static float _vq_quantthresh__16u0__p6_1[] = {
  143293. -1.5, -0.5, 0.5, 1.5,
  143294. };
  143295. static long _vq_quantmap__16u0__p6_1[] = {
  143296. 3, 1, 0, 2, 4,
  143297. };
  143298. static encode_aux_threshmatch _vq_auxt__16u0__p6_1 = {
  143299. _vq_quantthresh__16u0__p6_1,
  143300. _vq_quantmap__16u0__p6_1,
  143301. 5,
  143302. 5
  143303. };
  143304. static static_codebook _16u0__p6_1 = {
  143305. 2, 25,
  143306. _vq_lengthlist__16u0__p6_1,
  143307. 1, -533725184, 1611661312, 3, 0,
  143308. _vq_quantlist__16u0__p6_1,
  143309. NULL,
  143310. &_vq_auxt__16u0__p6_1,
  143311. NULL,
  143312. 0
  143313. };
  143314. static long _vq_quantlist__16u0__p7_0[] = {
  143315. 1,
  143316. 0,
  143317. 2,
  143318. };
  143319. static long _vq_lengthlist__16u0__p7_0[] = {
  143320. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143321. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143322. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  143323. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  143324. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  143325. 7,
  143326. };
  143327. static float _vq_quantthresh__16u0__p7_0[] = {
  143328. -157.5, 157.5,
  143329. };
  143330. static long _vq_quantmap__16u0__p7_0[] = {
  143331. 1, 0, 2,
  143332. };
  143333. static encode_aux_threshmatch _vq_auxt__16u0__p7_0 = {
  143334. _vq_quantthresh__16u0__p7_0,
  143335. _vq_quantmap__16u0__p7_0,
  143336. 3,
  143337. 3
  143338. };
  143339. static static_codebook _16u0__p7_0 = {
  143340. 4, 81,
  143341. _vq_lengthlist__16u0__p7_0,
  143342. 1, -518803456, 1628680192, 2, 0,
  143343. _vq_quantlist__16u0__p7_0,
  143344. NULL,
  143345. &_vq_auxt__16u0__p7_0,
  143346. NULL,
  143347. 0
  143348. };
  143349. static long _vq_quantlist__16u0__p7_1[] = {
  143350. 7,
  143351. 6,
  143352. 8,
  143353. 5,
  143354. 9,
  143355. 4,
  143356. 10,
  143357. 3,
  143358. 11,
  143359. 2,
  143360. 12,
  143361. 1,
  143362. 13,
  143363. 0,
  143364. 14,
  143365. };
  143366. static long _vq_lengthlist__16u0__p7_1[] = {
  143367. 1, 5, 5, 6, 5, 9,10,11,11,10,10,10,10,10,10, 5,
  143368. 8, 8, 8,10,10,10,10,10,10,10,10,10,10,10, 5, 8,
  143369. 9, 9, 9,10,10,10,10,10,10,10,10,10,10, 5,10, 8,
  143370. 10,10,10,10,10,10,10,10,10,10,10,10, 4, 8, 9,10,
  143371. 10,10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,
  143372. 10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,
  143373. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143374. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143375. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143376. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143377. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143378. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143379. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143380. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143381. 10,
  143382. };
  143383. static float _vq_quantthresh__16u0__p7_1[] = {
  143384. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  143385. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  143386. };
  143387. static long _vq_quantmap__16u0__p7_1[] = {
  143388. 13, 11, 9, 7, 5, 3, 1, 0,
  143389. 2, 4, 6, 8, 10, 12, 14,
  143390. };
  143391. static encode_aux_threshmatch _vq_auxt__16u0__p7_1 = {
  143392. _vq_quantthresh__16u0__p7_1,
  143393. _vq_quantmap__16u0__p7_1,
  143394. 15,
  143395. 15
  143396. };
  143397. static static_codebook _16u0__p7_1 = {
  143398. 2, 225,
  143399. _vq_lengthlist__16u0__p7_1,
  143400. 1, -520986624, 1620377600, 4, 0,
  143401. _vq_quantlist__16u0__p7_1,
  143402. NULL,
  143403. &_vq_auxt__16u0__p7_1,
  143404. NULL,
  143405. 0
  143406. };
  143407. static long _vq_quantlist__16u0__p7_2[] = {
  143408. 10,
  143409. 9,
  143410. 11,
  143411. 8,
  143412. 12,
  143413. 7,
  143414. 13,
  143415. 6,
  143416. 14,
  143417. 5,
  143418. 15,
  143419. 4,
  143420. 16,
  143421. 3,
  143422. 17,
  143423. 2,
  143424. 18,
  143425. 1,
  143426. 19,
  143427. 0,
  143428. 20,
  143429. };
  143430. static long _vq_lengthlist__16u0__p7_2[] = {
  143431. 1, 6, 6, 7, 8, 7, 7,10, 9,10, 9,11,10, 9,11,10,
  143432. 9, 9, 9, 9,10, 6, 8, 7, 9, 9, 8, 8,10,10, 9,11,
  143433. 11,12,12,10, 9,11, 9,12,10, 9, 6, 9, 8, 9,12, 8,
  143434. 8,11, 9,11,11,12,11,12,12,10,11,11,10,10,11, 7,
  143435. 10, 9, 9, 9, 9, 9,10, 9,10, 9,10,10,12,10,10,10,
  143436. 11,12,10,10, 7, 9, 9, 9,10, 9, 9,10,10, 9, 9, 9,
  143437. 11,11,10,10,10,10, 9, 9,12, 7, 9,10, 9,11, 9,10,
  143438. 9,10,11,11,11,10,11,12, 9,12,11,10,10,10, 7, 9,
  143439. 9, 9, 9,10,12,10, 9,11,12,10,11,12,12,11, 9,10,
  143440. 11,10,11, 7, 9,10,10,11,10, 9,10,11,11,11,10,12,
  143441. 12,12,11,11,10,11,11,12, 8, 9,10,12,11,10,10,12,
  143442. 12,12,12,12,10,11,11, 9,11,10,12,11,11, 8, 9,10,
  143443. 10,11,12,11,11,10,10,10,12,12,12, 9,10,12,12,12,
  143444. 12,12, 8,10,11,10,10,12, 9,11,12,12,11,12,12,12,
  143445. 12,10,12,10,10,10,10, 8,12,11,11,11,10,10,11,12,
  143446. 12,12,12,11,12,12,12,11,11,11,12,10, 9,10,10,12,
  143447. 10,12,10,12,12,10,10,10,11,12,12,12,11,12,12,12,
  143448. 11,10,11,12,12,12,11,12,12,11,12,12,11,12,12,12,
  143449. 12,11,12,12,10,10,10,10,11,11,12,11,12,12,12,12,
  143450. 12,12,12,11,12,11,10,11,11,12,11,11, 9,10,10,10,
  143451. 12,10,10,11, 9,11,12,11,12,11,12,12,10,11,10,12,
  143452. 9, 9, 9,12,11,10,11,10,12,10,12,10,12,12,12,11,
  143453. 11,11,11,11,10, 9,10,10,11,10,11,11,12,11,10,11,
  143454. 12,12,12,11,11, 9,12,10,12, 9,10,12,10,10,11,10,
  143455. 11,11,12,11,10,11,10,11,11,11,11,12,11,11,10, 9,
  143456. 10,10,10, 9,11,11,10, 9,12,10,11,12,11,12,12,11,
  143457. 12,11,12,11,10,11,10,12,11,12,11,12,11,12,10,11,
  143458. 10,10,12,11,10,11,11,11,10,
  143459. };
  143460. static float _vq_quantthresh__16u0__p7_2[] = {
  143461. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  143462. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  143463. 6.5, 7.5, 8.5, 9.5,
  143464. };
  143465. static long _vq_quantmap__16u0__p7_2[] = {
  143466. 19, 17, 15, 13, 11, 9, 7, 5,
  143467. 3, 1, 0, 2, 4, 6, 8, 10,
  143468. 12, 14, 16, 18, 20,
  143469. };
  143470. static encode_aux_threshmatch _vq_auxt__16u0__p7_2 = {
  143471. _vq_quantthresh__16u0__p7_2,
  143472. _vq_quantmap__16u0__p7_2,
  143473. 21,
  143474. 21
  143475. };
  143476. static static_codebook _16u0__p7_2 = {
  143477. 2, 441,
  143478. _vq_lengthlist__16u0__p7_2,
  143479. 1, -529268736, 1611661312, 5, 0,
  143480. _vq_quantlist__16u0__p7_2,
  143481. NULL,
  143482. &_vq_auxt__16u0__p7_2,
  143483. NULL,
  143484. 0
  143485. };
  143486. static long _huff_lengthlist__16u0__single[] = {
  143487. 3, 5, 8, 7,14, 8, 9,19, 5, 2, 5, 5, 9, 6, 9,19,
  143488. 8, 4, 5, 7, 8, 9,13,19, 7, 4, 6, 5, 9, 6, 9,19,
  143489. 12, 8, 7, 9,10,11,13,19, 8, 5, 8, 6, 9, 6, 7,19,
  143490. 8, 8,10, 7, 7, 4, 5,19,12,17,19,15,18,13,11,18,
  143491. };
  143492. static static_codebook _huff_book__16u0__single = {
  143493. 2, 64,
  143494. _huff_lengthlist__16u0__single,
  143495. 0, 0, 0, 0, 0,
  143496. NULL,
  143497. NULL,
  143498. NULL,
  143499. NULL,
  143500. 0
  143501. };
  143502. static long _huff_lengthlist__16u1__long[] = {
  143503. 3, 6,10, 8,12, 8,14, 8,14,19, 5, 3, 5, 5, 7, 6,
  143504. 11, 7,16,19, 7, 5, 6, 7, 7, 9,11,12,19,19, 6, 4,
  143505. 7, 5, 7, 6,10, 7,18,18, 8, 6, 7, 7, 7, 7, 8, 9,
  143506. 18,18, 7, 5, 8, 5, 7, 5, 8, 6,18,18,12, 9,10, 9,
  143507. 9, 9, 8, 9,18,18, 8, 7,10, 6, 8, 5, 6, 4,11,18,
  143508. 11,15,16,12,11, 8, 8, 6, 9,18,14,18,18,18,16,16,
  143509. 16,13,16,18,
  143510. };
  143511. static static_codebook _huff_book__16u1__long = {
  143512. 2, 100,
  143513. _huff_lengthlist__16u1__long,
  143514. 0, 0, 0, 0, 0,
  143515. NULL,
  143516. NULL,
  143517. NULL,
  143518. NULL,
  143519. 0
  143520. };
  143521. static long _vq_quantlist__16u1__p1_0[] = {
  143522. 1,
  143523. 0,
  143524. 2,
  143525. };
  143526. static long _vq_lengthlist__16u1__p1_0[] = {
  143527. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 7, 7,10,10, 7,
  143528. 9,10, 5, 7, 8, 7,10, 9, 7,10,10, 5, 8, 8, 8,10,
  143529. 10, 8,10,10, 7,10,10,10,11,12,10,12,13, 7,10,10,
  143530. 9,13,11,10,12,13, 5, 8, 8, 8,10,10, 8,10,10, 7,
  143531. 10,10,10,12,12, 9,11,12, 7,10,11,10,12,12,10,13,
  143532. 11,
  143533. };
  143534. static float _vq_quantthresh__16u1__p1_0[] = {
  143535. -0.5, 0.5,
  143536. };
  143537. static long _vq_quantmap__16u1__p1_0[] = {
  143538. 1, 0, 2,
  143539. };
  143540. static encode_aux_threshmatch _vq_auxt__16u1__p1_0 = {
  143541. _vq_quantthresh__16u1__p1_0,
  143542. _vq_quantmap__16u1__p1_0,
  143543. 3,
  143544. 3
  143545. };
  143546. static static_codebook _16u1__p1_0 = {
  143547. 4, 81,
  143548. _vq_lengthlist__16u1__p1_0,
  143549. 1, -535822336, 1611661312, 2, 0,
  143550. _vq_quantlist__16u1__p1_0,
  143551. NULL,
  143552. &_vq_auxt__16u1__p1_0,
  143553. NULL,
  143554. 0
  143555. };
  143556. static long _vq_quantlist__16u1__p2_0[] = {
  143557. 1,
  143558. 0,
  143559. 2,
  143560. };
  143561. static long _vq_lengthlist__16u1__p2_0[] = {
  143562. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 7, 8, 6,
  143563. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 6, 8,
  143564. 8, 6, 8, 8, 6, 8, 8, 7, 7,10, 8, 9, 9, 6, 8, 8,
  143565. 7, 9, 8, 8, 9,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  143566. 8, 8, 8,10, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 7,10,
  143567. 8,
  143568. };
  143569. static float _vq_quantthresh__16u1__p2_0[] = {
  143570. -0.5, 0.5,
  143571. };
  143572. static long _vq_quantmap__16u1__p2_0[] = {
  143573. 1, 0, 2,
  143574. };
  143575. static encode_aux_threshmatch _vq_auxt__16u1__p2_0 = {
  143576. _vq_quantthresh__16u1__p2_0,
  143577. _vq_quantmap__16u1__p2_0,
  143578. 3,
  143579. 3
  143580. };
  143581. static static_codebook _16u1__p2_0 = {
  143582. 4, 81,
  143583. _vq_lengthlist__16u1__p2_0,
  143584. 1, -535822336, 1611661312, 2, 0,
  143585. _vq_quantlist__16u1__p2_0,
  143586. NULL,
  143587. &_vq_auxt__16u1__p2_0,
  143588. NULL,
  143589. 0
  143590. };
  143591. static long _vq_quantlist__16u1__p3_0[] = {
  143592. 2,
  143593. 1,
  143594. 3,
  143595. 0,
  143596. 4,
  143597. };
  143598. static long _vq_lengthlist__16u1__p3_0[] = {
  143599. 1, 5, 5, 8, 8, 6, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  143600. 10, 9,11,11, 9, 9,10,11,11, 6, 8, 8,10,10, 8, 9,
  143601. 10,11,11, 8, 9,10,11,11,10,11,11,12,13,10,11,11,
  143602. 13,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  143603. 11,10,11,11,13,13,10,11,11,13,12, 9,11,11,14,13,
  143604. 10,12,12,15,14,10,12,11,14,13,12,13,13,15,15,12,
  143605. 13,13,16,14, 9,11,11,13,14,10,11,12,14,14,10,12,
  143606. 12,14,15,12,13,13,14,15,12,13,14,15,16, 5, 8, 8,
  143607. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  143608. 14,11,12,12,14,14, 8,10,10,12,12, 9,11,12,12,13,
  143609. 10,12,12,13,13,12,12,13,14,15,11,13,13,15,15, 7,
  143610. 10,10,12,12, 9,12,11,13,12,10,11,12,13,13,12,13,
  143611. 12,15,14,11,12,13,15,15,10,12,12,15,14,11,13,13,
  143612. 16,15,11,13,13,16,15,14,13,14,15,16,13,15,15,17,
  143613. 17,10,12,12,14,15,11,12,12,15,15,11,13,13,15,16,
  143614. 13,15,13,16,15,13,15,15,16,17, 5, 8, 8,11,11, 8,
  143615. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  143616. 12,14,14, 7,10,10,12,12,10,12,12,14,13, 9,11,12,
  143617. 12,13,12,13,13,15,15,12,12,13,13,15, 7,10,10,12,
  143618. 13,10,11,12,13,13,10,12,11,13,13,11,13,13,15,15,
  143619. 12,13,12,15,14, 9,12,12,15,14,11,13,13,15,15,11,
  143620. 12,13,15,15,13,14,14,17,19,13,13,14,16,16,10,12,
  143621. 12,14,15,11,13,13,15,16,11,13,12,16,15,13,15,15,
  143622. 17,18,14,15,13,16,15, 8,11,11,15,14,10,12,12,16,
  143623. 15,10,12,12,16,16,14,15,15,18,17,13,14,15,16,18,
  143624. 9,12,12,15,15,11,12,14,16,17,11,13,13,16,15,15,
  143625. 15,15,17,18,14,15,16,17,17, 9,12,12,15,15,11,14,
  143626. 13,16,16,11,13,13,16,16,15,16,15,17,18,14,16,15,
  143627. 17,16,12,14,14,17,16,12,14,15,18,17,13,15,15,17,
  143628. 17,15,15,18,16,20,15,16,17,18,18,11,14,14,16,17,
  143629. 13,15,14,18,17,13,15,15,17,17,15,17,15,18,17,15,
  143630. 17,16,19,18, 8,11,11,14,15,10,12,12,15,15,10,12,
  143631. 12,16,16,13,14,14,17,16,14,15,15,17,17, 9,12,12,
  143632. 15,16,11,13,13,16,16,11,12,13,16,16,14,16,15,20,
  143633. 17,14,16,16,17,17, 9,12,12,15,16,11,13,13,16,17,
  143634. 11,13,13,17,16,14,15,15,17,18,15,15,15,18,18,11,
  143635. 14,14,17,16,13,15,15,17,17,13,14,14,18,17,15,16,
  143636. 16,18,19,15,15,17,17,19,11,14,14,16,17,13,15,14,
  143637. 17,19,13,15,14,18,17,15,17,16,18,18,15,17,15,18,
  143638. 16,
  143639. };
  143640. static float _vq_quantthresh__16u1__p3_0[] = {
  143641. -1.5, -0.5, 0.5, 1.5,
  143642. };
  143643. static long _vq_quantmap__16u1__p3_0[] = {
  143644. 3, 1, 0, 2, 4,
  143645. };
  143646. static encode_aux_threshmatch _vq_auxt__16u1__p3_0 = {
  143647. _vq_quantthresh__16u1__p3_0,
  143648. _vq_quantmap__16u1__p3_0,
  143649. 5,
  143650. 5
  143651. };
  143652. static static_codebook _16u1__p3_0 = {
  143653. 4, 625,
  143654. _vq_lengthlist__16u1__p3_0,
  143655. 1, -533725184, 1611661312, 3, 0,
  143656. _vq_quantlist__16u1__p3_0,
  143657. NULL,
  143658. &_vq_auxt__16u1__p3_0,
  143659. NULL,
  143660. 0
  143661. };
  143662. static long _vq_quantlist__16u1__p4_0[] = {
  143663. 2,
  143664. 1,
  143665. 3,
  143666. 0,
  143667. 4,
  143668. };
  143669. static long _vq_lengthlist__16u1__p4_0[] = {
  143670. 4, 5, 5, 8, 8, 6, 6, 7, 9, 9, 6, 6, 6, 9, 9, 9,
  143671. 10, 9,11,11, 9, 9,10,11,11, 6, 7, 7,10, 9, 7, 7,
  143672. 8, 9,10, 7, 7, 8,10,10,10,10,10,10,12, 9, 9,10,
  143673. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 7,10,
  143674. 10, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  143675. 10,10,10,12,12, 9,10,10,12,12,12,11,12,13,13,11,
  143676. 11,12,12,13, 9,10,10,11,12, 9,10,10,12,12,10,10,
  143677. 10,12,12,11,12,11,14,13,11,12,12,14,13, 5, 7, 7,
  143678. 10,10, 7, 8, 8,10,10, 7, 8, 7,10,10,10,10,10,12,
  143679. 12,10,10,10,12,12, 6, 8, 7,10,10, 7, 7, 9,10,11,
  143680. 8, 9, 9,11,10,10,10,11,11,13,10,10,11,12,13, 6,
  143681. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,10,11,10,11,
  143682. 10,13,11,10,11,10,12,12,10,11,10,12,11,10,10,10,
  143683. 12,13,10,11,11,13,12,11,11,13,11,14,12,12,13,14,
  143684. 14, 9,10,10,12,13,10,11,10,13,12,10,11,11,12,13,
  143685. 11,12,11,14,12,12,13,13,15,14, 5, 7, 7,10,10, 7,
  143686. 7, 8,10,10, 7, 8, 8,10,10,10,10,10,11,12,10,10,
  143687. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  143688. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 7, 8,10,
  143689. 10, 8, 8, 9,10,11, 7, 9, 7,11,10,10,11,11,13,12,
  143690. 11,11,10,13,11, 9,10,10,12,12,10,11,11,13,12,10,
  143691. 10,11,12,12,12,13,13,14,14,11,11,12,12,14,10,10,
  143692. 11,12,12,10,11,11,12,13,10,10,10,13,12,12,13,13,
  143693. 15,14,12,13,10,14,11, 8,10,10,12,12,10,11,10,13,
  143694. 13, 9,10,10,12,12,12,13,13,15,14,11,12,12,13,13,
  143695. 9,10,10,13,12,10,10,11,13,13,10,11,10,13,12,12,
  143696. 12,13,14,15,12,13,12,15,13, 9,10,10,12,13,10,11,
  143697. 10,13,12,10,10,11,12,13,12,14,12,15,13,12,12,13,
  143698. 14,15,11,12,11,14,13,11,11,12,14,15,12,13,12,15,
  143699. 14,13,11,15,11,16,13,14,14,16,15,11,12,12,14,14,
  143700. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,12,14,
  143701. 14,14,15,15, 8,10,10,12,12, 9,10,10,12,12,10,10,
  143702. 11,13,13,11,12,12,13,13,12,13,13,14,15, 9,10,10,
  143703. 13,12,10,11,11,13,12,10,10,11,13,13,12,13,12,15,
  143704. 14,12,12,13,13,16, 9, 9,10,12,13,10,10,11,12,13,
  143705. 10,11,10,13,13,12,12,13,13,15,13,13,12,15,13,11,
  143706. 12,12,14,14,12,13,12,15,14,11,11,12,13,14,14,14,
  143707. 14,16,15,13,12,15,12,16,11,11,12,13,14,12,13,13,
  143708. 14,15,10,12,11,14,13,14,15,14,16,16,13,14,11,15,
  143709. 11,
  143710. };
  143711. static float _vq_quantthresh__16u1__p4_0[] = {
  143712. -1.5, -0.5, 0.5, 1.5,
  143713. };
  143714. static long _vq_quantmap__16u1__p4_0[] = {
  143715. 3, 1, 0, 2, 4,
  143716. };
  143717. static encode_aux_threshmatch _vq_auxt__16u1__p4_0 = {
  143718. _vq_quantthresh__16u1__p4_0,
  143719. _vq_quantmap__16u1__p4_0,
  143720. 5,
  143721. 5
  143722. };
  143723. static static_codebook _16u1__p4_0 = {
  143724. 4, 625,
  143725. _vq_lengthlist__16u1__p4_0,
  143726. 1, -533725184, 1611661312, 3, 0,
  143727. _vq_quantlist__16u1__p4_0,
  143728. NULL,
  143729. &_vq_auxt__16u1__p4_0,
  143730. NULL,
  143731. 0
  143732. };
  143733. static long _vq_quantlist__16u1__p5_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__p5_0[] = {
  143745. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  143746. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  143747. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  143748. 10, 9,11,11,12,11, 7, 8, 8, 9, 9,11,11,12,12, 9,
  143749. 10,10,11,11,12,12,13,12, 9,10,10,11,11,12,12,12,
  143750. 13,
  143751. };
  143752. static float _vq_quantthresh__16u1__p5_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__p5_0[] = {
  143756. 7, 5, 3, 1, 0, 2, 4, 6,
  143757. 8,
  143758. };
  143759. static encode_aux_threshmatch _vq_auxt__16u1__p5_0 = {
  143760. _vq_quantthresh__16u1__p5_0,
  143761. _vq_quantmap__16u1__p5_0,
  143762. 9,
  143763. 9
  143764. };
  143765. static static_codebook _16u1__p5_0 = {
  143766. 2, 81,
  143767. _vq_lengthlist__16u1__p5_0,
  143768. 1, -531628032, 1611661312, 4, 0,
  143769. _vq_quantlist__16u1__p5_0,
  143770. NULL,
  143771. &_vq_auxt__16u1__p5_0,
  143772. NULL,
  143773. 0
  143774. };
  143775. static long _vq_quantlist__16u1__p6_0[] = {
  143776. 4,
  143777. 3,
  143778. 5,
  143779. 2,
  143780. 6,
  143781. 1,
  143782. 7,
  143783. 0,
  143784. 8,
  143785. };
  143786. static long _vq_lengthlist__16u1__p6_0[] = {
  143787. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 4, 6, 6, 8, 8,
  143788. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  143789. 8, 8,10, 9, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  143790. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  143791. 9, 9,10,10,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  143792. 11,
  143793. };
  143794. static float _vq_quantthresh__16u1__p6_0[] = {
  143795. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143796. };
  143797. static long _vq_quantmap__16u1__p6_0[] = {
  143798. 7, 5, 3, 1, 0, 2, 4, 6,
  143799. 8,
  143800. };
  143801. static encode_aux_threshmatch _vq_auxt__16u1__p6_0 = {
  143802. _vq_quantthresh__16u1__p6_0,
  143803. _vq_quantmap__16u1__p6_0,
  143804. 9,
  143805. 9
  143806. };
  143807. static static_codebook _16u1__p6_0 = {
  143808. 2, 81,
  143809. _vq_lengthlist__16u1__p6_0,
  143810. 1, -531628032, 1611661312, 4, 0,
  143811. _vq_quantlist__16u1__p6_0,
  143812. NULL,
  143813. &_vq_auxt__16u1__p6_0,
  143814. NULL,
  143815. 0
  143816. };
  143817. static long _vq_quantlist__16u1__p7_0[] = {
  143818. 1,
  143819. 0,
  143820. 2,
  143821. };
  143822. static long _vq_lengthlist__16u1__p7_0[] = {
  143823. 1, 4, 4, 4, 8, 8, 4, 8, 8, 5,11, 9, 8,12,11, 8,
  143824. 12,11, 5,10,11, 8,11,12, 8,11,12, 4,11,11,11,14,
  143825. 13,10,13,13, 8,14,13,12,14,16,12,16,15, 8,14,14,
  143826. 13,16,14,12,15,16, 4,11,11,10,14,13,11,14,14, 8,
  143827. 15,14,12,15,15,12,14,16, 8,14,14,11,16,15,12,15,
  143828. 13,
  143829. };
  143830. static float _vq_quantthresh__16u1__p7_0[] = {
  143831. -5.5, 5.5,
  143832. };
  143833. static long _vq_quantmap__16u1__p7_0[] = {
  143834. 1, 0, 2,
  143835. };
  143836. static encode_aux_threshmatch _vq_auxt__16u1__p7_0 = {
  143837. _vq_quantthresh__16u1__p7_0,
  143838. _vq_quantmap__16u1__p7_0,
  143839. 3,
  143840. 3
  143841. };
  143842. static static_codebook _16u1__p7_0 = {
  143843. 4, 81,
  143844. _vq_lengthlist__16u1__p7_0,
  143845. 1, -529137664, 1618345984, 2, 0,
  143846. _vq_quantlist__16u1__p7_0,
  143847. NULL,
  143848. &_vq_auxt__16u1__p7_0,
  143849. NULL,
  143850. 0
  143851. };
  143852. static long _vq_quantlist__16u1__p7_1[] = {
  143853. 5,
  143854. 4,
  143855. 6,
  143856. 3,
  143857. 7,
  143858. 2,
  143859. 8,
  143860. 1,
  143861. 9,
  143862. 0,
  143863. 10,
  143864. };
  143865. static long _vq_lengthlist__16u1__p7_1[] = {
  143866. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 5, 7, 7,
  143867. 8, 8, 8, 8, 8, 8, 4, 5, 6, 7, 7, 8, 8, 8, 8, 8,
  143868. 8, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  143869. 8, 8, 8, 9, 9, 9, 9, 7, 8, 8, 8, 8, 9, 9, 9,10,
  143870. 9,10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10, 9, 8, 8, 8,
  143871. 9, 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,10,
  143872. 10,10,10, 8, 8, 8, 9, 9, 9,10,10,10,10,10, 8, 8,
  143873. 8, 9, 9,10,10,10,10,10,10,
  143874. };
  143875. static float _vq_quantthresh__16u1__p7_1[] = {
  143876. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143877. 3.5, 4.5,
  143878. };
  143879. static long _vq_quantmap__16u1__p7_1[] = {
  143880. 9, 7, 5, 3, 1, 0, 2, 4,
  143881. 6, 8, 10,
  143882. };
  143883. static encode_aux_threshmatch _vq_auxt__16u1__p7_1 = {
  143884. _vq_quantthresh__16u1__p7_1,
  143885. _vq_quantmap__16u1__p7_1,
  143886. 11,
  143887. 11
  143888. };
  143889. static static_codebook _16u1__p7_1 = {
  143890. 2, 121,
  143891. _vq_lengthlist__16u1__p7_1,
  143892. 1, -531365888, 1611661312, 4, 0,
  143893. _vq_quantlist__16u1__p7_1,
  143894. NULL,
  143895. &_vq_auxt__16u1__p7_1,
  143896. NULL,
  143897. 0
  143898. };
  143899. static long _vq_quantlist__16u1__p8_0[] = {
  143900. 5,
  143901. 4,
  143902. 6,
  143903. 3,
  143904. 7,
  143905. 2,
  143906. 8,
  143907. 1,
  143908. 9,
  143909. 0,
  143910. 10,
  143911. };
  143912. static long _vq_lengthlist__16u1__p8_0[] = {
  143913. 1, 4, 4, 5, 5, 8, 8,10,10,12,12, 4, 7, 7, 8, 8,
  143914. 9, 9,12,11,14,13, 4, 7, 7, 7, 8, 9,10,11,11,13,
  143915. 12, 5, 8, 8, 9, 9,11,11,12,13,15,14, 5, 7, 8, 9,
  143916. 9,11,11,13,13,17,15, 8, 9,10,11,11,12,13,17,14,
  143917. 17,16, 8,10, 9,11,11,12,12,13,15,15,17,10,11,11,
  143918. 12,13,14,15,15,16,16,17, 9,11,11,12,12,14,15,17,
  143919. 15,15,16,11,14,12,14,15,16,15,16,16,16,15,11,13,
  143920. 13,14,14,15,15,16,16,15,16,
  143921. };
  143922. static float _vq_quantthresh__16u1__p8_0[] = {
  143923. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  143924. 38.5, 49.5,
  143925. };
  143926. static long _vq_quantmap__16u1__p8_0[] = {
  143927. 9, 7, 5, 3, 1, 0, 2, 4,
  143928. 6, 8, 10,
  143929. };
  143930. static encode_aux_threshmatch _vq_auxt__16u1__p8_0 = {
  143931. _vq_quantthresh__16u1__p8_0,
  143932. _vq_quantmap__16u1__p8_0,
  143933. 11,
  143934. 11
  143935. };
  143936. static static_codebook _16u1__p8_0 = {
  143937. 2, 121,
  143938. _vq_lengthlist__16u1__p8_0,
  143939. 1, -524582912, 1618345984, 4, 0,
  143940. _vq_quantlist__16u1__p8_0,
  143941. NULL,
  143942. &_vq_auxt__16u1__p8_0,
  143943. NULL,
  143944. 0
  143945. };
  143946. static long _vq_quantlist__16u1__p8_1[] = {
  143947. 5,
  143948. 4,
  143949. 6,
  143950. 3,
  143951. 7,
  143952. 2,
  143953. 8,
  143954. 1,
  143955. 9,
  143956. 0,
  143957. 10,
  143958. };
  143959. static long _vq_lengthlist__16u1__p8_1[] = {
  143960. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7,
  143961. 8, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  143962. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 6, 7, 7, 7,
  143963. 7, 8, 8, 8, 8, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  143964. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  143965. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  143966. 9, 9, 9, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  143967. 8, 9, 9, 9, 9, 9, 9, 9, 9,
  143968. };
  143969. static float _vq_quantthresh__16u1__p8_1[] = {
  143970. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143971. 3.5, 4.5,
  143972. };
  143973. static long _vq_quantmap__16u1__p8_1[] = {
  143974. 9, 7, 5, 3, 1, 0, 2, 4,
  143975. 6, 8, 10,
  143976. };
  143977. static encode_aux_threshmatch _vq_auxt__16u1__p8_1 = {
  143978. _vq_quantthresh__16u1__p8_1,
  143979. _vq_quantmap__16u1__p8_1,
  143980. 11,
  143981. 11
  143982. };
  143983. static static_codebook _16u1__p8_1 = {
  143984. 2, 121,
  143985. _vq_lengthlist__16u1__p8_1,
  143986. 1, -531365888, 1611661312, 4, 0,
  143987. _vq_quantlist__16u1__p8_1,
  143988. NULL,
  143989. &_vq_auxt__16u1__p8_1,
  143990. NULL,
  143991. 0
  143992. };
  143993. static long _vq_quantlist__16u1__p9_0[] = {
  143994. 7,
  143995. 6,
  143996. 8,
  143997. 5,
  143998. 9,
  143999. 4,
  144000. 10,
  144001. 3,
  144002. 11,
  144003. 2,
  144004. 12,
  144005. 1,
  144006. 13,
  144007. 0,
  144008. 14,
  144009. };
  144010. static long _vq_lengthlist__16u1__p9_0[] = {
  144011. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144012. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144013. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144014. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144015. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144016. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144017. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144018. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144019. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144020. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144021. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144022. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144023. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144024. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144025. 8,
  144026. };
  144027. static float _vq_quantthresh__16u1__p9_0[] = {
  144028. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  144029. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  144030. };
  144031. static long _vq_quantmap__16u1__p9_0[] = {
  144032. 13, 11, 9, 7, 5, 3, 1, 0,
  144033. 2, 4, 6, 8, 10, 12, 14,
  144034. };
  144035. static encode_aux_threshmatch _vq_auxt__16u1__p9_0 = {
  144036. _vq_quantthresh__16u1__p9_0,
  144037. _vq_quantmap__16u1__p9_0,
  144038. 15,
  144039. 15
  144040. };
  144041. static static_codebook _16u1__p9_0 = {
  144042. 2, 225,
  144043. _vq_lengthlist__16u1__p9_0,
  144044. 1, -514071552, 1627381760, 4, 0,
  144045. _vq_quantlist__16u1__p9_0,
  144046. NULL,
  144047. &_vq_auxt__16u1__p9_0,
  144048. NULL,
  144049. 0
  144050. };
  144051. static long _vq_quantlist__16u1__p9_1[] = {
  144052. 7,
  144053. 6,
  144054. 8,
  144055. 5,
  144056. 9,
  144057. 4,
  144058. 10,
  144059. 3,
  144060. 11,
  144061. 2,
  144062. 12,
  144063. 1,
  144064. 13,
  144065. 0,
  144066. 14,
  144067. };
  144068. static long _vq_lengthlist__16u1__p9_1[] = {
  144069. 1, 6, 5, 9, 9,10,10, 6, 7, 9, 9,10,10,10,10, 5,
  144070. 10, 8,10, 8,10,10, 8, 8,10, 9,10,10,10,10, 5, 8,
  144071. 9,10,10,10,10, 8,10,10,10,10,10,10,10, 9,10,10,
  144072. 10,10,10,10, 9, 9,10,10,10,10,10,10, 9, 9, 8, 9,
  144073. 10,10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  144074. 10,10,10,10,10,10,10,10,10,10,10, 8,10,10,10,10,
  144075. 10,10,10,10,10,10,10,10,10, 6, 8, 8,10,10,10, 8,
  144076. 10,10,10,10,10,10,10,10, 5, 8, 8,10,10,10, 9, 9,
  144077. 10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,10,
  144078. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144079. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  144080. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144081. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144082. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144083. 9,
  144084. };
  144085. static float _vq_quantthresh__16u1__p9_1[] = {
  144086. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  144087. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  144088. };
  144089. static long _vq_quantmap__16u1__p9_1[] = {
  144090. 13, 11, 9, 7, 5, 3, 1, 0,
  144091. 2, 4, 6, 8, 10, 12, 14,
  144092. };
  144093. static encode_aux_threshmatch _vq_auxt__16u1__p9_1 = {
  144094. _vq_quantthresh__16u1__p9_1,
  144095. _vq_quantmap__16u1__p9_1,
  144096. 15,
  144097. 15
  144098. };
  144099. static static_codebook _16u1__p9_1 = {
  144100. 2, 225,
  144101. _vq_lengthlist__16u1__p9_1,
  144102. 1, -522338304, 1620115456, 4, 0,
  144103. _vq_quantlist__16u1__p9_1,
  144104. NULL,
  144105. &_vq_auxt__16u1__p9_1,
  144106. NULL,
  144107. 0
  144108. };
  144109. static long _vq_quantlist__16u1__p9_2[] = {
  144110. 8,
  144111. 7,
  144112. 9,
  144113. 6,
  144114. 10,
  144115. 5,
  144116. 11,
  144117. 4,
  144118. 12,
  144119. 3,
  144120. 13,
  144121. 2,
  144122. 14,
  144123. 1,
  144124. 15,
  144125. 0,
  144126. 16,
  144127. };
  144128. static long _vq_lengthlist__16u1__p9_2[] = {
  144129. 1, 6, 6, 7, 8, 8,11,10, 9, 9,11, 9,10, 9,11,11,
  144130. 9, 6, 7, 6,11, 8,11, 9,10,10,11, 9,11,10,10,10,
  144131. 11, 9, 5, 7, 7, 8, 8,10,11, 8, 8,11, 9, 9,10,11,
  144132. 9,10,11, 8, 9, 6, 8, 8, 9, 9,10,10,11,11,11, 9,
  144133. 11,10, 9,11, 8, 8, 8, 9, 8, 9,10,11, 9, 9,11,11,
  144134. 10, 9, 9,11,10, 8,11, 8, 9, 8,11, 9,10, 9,10,11,
  144135. 11,10,10, 9,10,10, 8, 8, 9,10,10,10, 9,11, 9,10,
  144136. 11,11,11,11,10, 9,11, 9, 9,11,11,10, 8,11,11,11,
  144137. 9,10,10,11,10,11,11, 9,11,10, 9,11,10,10,10,10,
  144138. 9,11,10,11,10, 9, 9,10,11, 9, 8,10,11,11,10,10,
  144139. 11, 9,11,10,11,11,10,11, 9, 9, 8,10, 8, 9,11, 9,
  144140. 8,10,10, 9,11,10,11,10,11, 9,11, 8,10,11,11,11,
  144141. 11,10,10,11,11,11,11,10,11,11,10, 9, 8,10,10, 9,
  144142. 11,10,11,11,11, 9, 9, 9,11,11,11,10,10, 9, 9,10,
  144143. 9,11,11,11,11, 8,10,11,10,11,11,10,11,11, 9, 9,
  144144. 9,10, 9,11, 9,11,11,11,11,11,10,11,11,10,11,10,
  144145. 11,11, 9,11,10,11,10, 9,10, 9,10,10,11,11,11,11,
  144146. 9,10, 9,10,11,11,10,11,11,11,11,11,11,10,11,11,
  144147. 10,
  144148. };
  144149. static float _vq_quantthresh__16u1__p9_2[] = {
  144150. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144151. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144152. };
  144153. static long _vq_quantmap__16u1__p9_2[] = {
  144154. 15, 13, 11, 9, 7, 5, 3, 1,
  144155. 0, 2, 4, 6, 8, 10, 12, 14,
  144156. 16,
  144157. };
  144158. static encode_aux_threshmatch _vq_auxt__16u1__p9_2 = {
  144159. _vq_quantthresh__16u1__p9_2,
  144160. _vq_quantmap__16u1__p9_2,
  144161. 17,
  144162. 17
  144163. };
  144164. static static_codebook _16u1__p9_2 = {
  144165. 2, 289,
  144166. _vq_lengthlist__16u1__p9_2,
  144167. 1, -529530880, 1611661312, 5, 0,
  144168. _vq_quantlist__16u1__p9_2,
  144169. NULL,
  144170. &_vq_auxt__16u1__p9_2,
  144171. NULL,
  144172. 0
  144173. };
  144174. static long _huff_lengthlist__16u1__short[] = {
  144175. 5, 7,10, 9,11,10,15,11,13,16, 6, 4, 6, 6, 7, 7,
  144176. 10, 9,12,16,10, 6, 5, 6, 6, 7,10,11,16,16, 9, 6,
  144177. 7, 6, 7, 7,10, 8,14,16,11, 6, 5, 4, 5, 6, 8, 9,
  144178. 15,16, 9, 6, 6, 5, 6, 6, 9, 8,14,16,12, 7, 6, 6,
  144179. 5, 6, 6, 7,13,16, 8, 6, 7, 6, 5, 5, 4, 4,11,16,
  144180. 9, 8, 9, 9, 7, 7, 6, 5,13,16,14,14,16,15,16,15,
  144181. 16,16,16,16,
  144182. };
  144183. static static_codebook _huff_book__16u1__short = {
  144184. 2, 100,
  144185. _huff_lengthlist__16u1__short,
  144186. 0, 0, 0, 0, 0,
  144187. NULL,
  144188. NULL,
  144189. NULL,
  144190. NULL,
  144191. 0
  144192. };
  144193. static long _huff_lengthlist__16u2__long[] = {
  144194. 5, 7,10,10,10,11,11,13,18,19, 6, 5, 5, 6, 7, 8,
  144195. 9,12,19,19, 8, 5, 4, 4, 6, 7, 9,13,19,19, 8, 5,
  144196. 4, 4, 5, 6, 8,12,17,19, 7, 5, 5, 4, 4, 5, 7,12,
  144197. 18,18, 8, 7, 7, 6, 5, 5, 6,10,18,18, 9, 9, 9, 8,
  144198. 6, 5, 6, 9,18,18,11,13,13,13, 8, 7, 7, 9,16,18,
  144199. 13,17,18,16,11, 9, 9, 9,17,18,15,18,18,18,15,13,
  144200. 13,14,18,18,
  144201. };
  144202. static static_codebook _huff_book__16u2__long = {
  144203. 2, 100,
  144204. _huff_lengthlist__16u2__long,
  144205. 0, 0, 0, 0, 0,
  144206. NULL,
  144207. NULL,
  144208. NULL,
  144209. NULL,
  144210. 0
  144211. };
  144212. static long _huff_lengthlist__16u2__short[] = {
  144213. 8,11,12,12,14,15,16,16,16,16, 9, 7, 7, 8, 9,11,
  144214. 13,14,16,16,13, 7, 6, 6, 7, 9,12,13,15,16,15, 7,
  144215. 6, 5, 4, 6,10,11,14,16,12, 8, 7, 4, 2, 4, 7,10,
  144216. 14,16,11, 9, 7, 5, 3, 4, 6, 9,14,16,11,10, 9, 7,
  144217. 5, 5, 6, 9,16,16,10,10, 9, 8, 6, 6, 7,10,16,16,
  144218. 11,11,11,10,10,10,11,14,16,16,16,14,14,13,14,16,
  144219. 16,16,16,16,
  144220. };
  144221. static static_codebook _huff_book__16u2__short = {
  144222. 2, 100,
  144223. _huff_lengthlist__16u2__short,
  144224. 0, 0, 0, 0, 0,
  144225. NULL,
  144226. NULL,
  144227. NULL,
  144228. NULL,
  144229. 0
  144230. };
  144231. static long _vq_quantlist__16u2_p1_0[] = {
  144232. 1,
  144233. 0,
  144234. 2,
  144235. };
  144236. static long _vq_lengthlist__16u2_p1_0[] = {
  144237. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  144238. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 8, 9,
  144239. 9, 7, 9, 9, 7, 9, 9, 9,10,10, 9,10,10, 7, 9, 9,
  144240. 9,10,10, 9,10,11, 5, 7, 8, 8, 9, 9, 8, 9, 9, 7,
  144241. 9, 9, 9,10,10, 9, 9,10, 7, 9, 9, 9,10,10, 9,11,
  144242. 10,
  144243. };
  144244. static float _vq_quantthresh__16u2_p1_0[] = {
  144245. -0.5, 0.5,
  144246. };
  144247. static long _vq_quantmap__16u2_p1_0[] = {
  144248. 1, 0, 2,
  144249. };
  144250. static encode_aux_threshmatch _vq_auxt__16u2_p1_0 = {
  144251. _vq_quantthresh__16u2_p1_0,
  144252. _vq_quantmap__16u2_p1_0,
  144253. 3,
  144254. 3
  144255. };
  144256. static static_codebook _16u2_p1_0 = {
  144257. 4, 81,
  144258. _vq_lengthlist__16u2_p1_0,
  144259. 1, -535822336, 1611661312, 2, 0,
  144260. _vq_quantlist__16u2_p1_0,
  144261. NULL,
  144262. &_vq_auxt__16u2_p1_0,
  144263. NULL,
  144264. 0
  144265. };
  144266. static long _vq_quantlist__16u2_p2_0[] = {
  144267. 2,
  144268. 1,
  144269. 3,
  144270. 0,
  144271. 4,
  144272. };
  144273. static long _vq_lengthlist__16u2_p2_0[] = {
  144274. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  144275. 10, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  144276. 8,10,10, 7, 8, 8,10,10,10,10,10,12,12, 9,10,10,
  144277. 11,12, 5, 7, 7, 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,
  144278. 10, 9,10,10,12,11,10,10,10,12,12, 9,10,10,12,12,
  144279. 10,11,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  144280. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,12,10,10,
  144281. 10,12,12,11,12,12,14,13,12,13,12,14,14, 5, 7, 7,
  144282. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  144283. 12,10,10,11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  144284. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,12,13, 7,
  144285. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  144286. 10,13,12,10,11,11,13,13, 9,11,10,13,13,10,11,11,
  144287. 13,13,10,11,11,13,13,12,12,13,13,15,12,12,13,14,
  144288. 15, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  144289. 11,13,11,14,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  144290. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  144291. 11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  144292. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  144293. 11, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,12,
  144294. 11,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  144295. 10,11,12,13,12,13,13,15,14,11,11,13,12,14,10,10,
  144296. 11,13,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  144297. 14,14,12,13,12,14,13, 8,10, 9,12,12, 9,11,10,13,
  144298. 13, 9,10,10,12,13,12,13,13,14,14,12,12,13,14,14,
  144299. 9,11,10,13,13,10,11,11,13,13,10,11,11,13,13,12,
  144300. 13,13,15,15,13,13,13,14,15, 9,10,10,12,13,10,11,
  144301. 10,13,12,10,11,11,13,13,12,13,12,15,14,13,13,13,
  144302. 14,15,11,12,12,15,14,12,12,13,15,15,12,13,13,15,
  144303. 14,14,13,15,14,16,13,14,15,16,16,11,12,12,14,14,
  144304. 11,12,12,15,14,12,13,13,15,15,13,14,13,16,14,14,
  144305. 14,14,16,16, 8, 9, 9,12,12, 9,10,10,13,12, 9,10,
  144306. 10,13,13,12,12,12,14,14,12,12,13,15,15, 9,10,10,
  144307. 13,12,10,11,11,13,13,10,10,11,13,14,12,13,13,15,
  144308. 15,12,12,13,14,15, 9,10,10,13,13,10,11,11,13,13,
  144309. 10,11,11,13,13,12,13,13,14,14,13,14,13,15,14,11,
  144310. 12,12,14,14,12,13,13,15,14,11,12,12,14,15,14,14,
  144311. 14,16,15,13,12,14,14,16,11,12,13,14,15,12,13,13,
  144312. 14,16,12,13,12,15,14,13,15,14,16,16,14,15,13,16,
  144313. 13,
  144314. };
  144315. static float _vq_quantthresh__16u2_p2_0[] = {
  144316. -1.5, -0.5, 0.5, 1.5,
  144317. };
  144318. static long _vq_quantmap__16u2_p2_0[] = {
  144319. 3, 1, 0, 2, 4,
  144320. };
  144321. static encode_aux_threshmatch _vq_auxt__16u2_p2_0 = {
  144322. _vq_quantthresh__16u2_p2_0,
  144323. _vq_quantmap__16u2_p2_0,
  144324. 5,
  144325. 5
  144326. };
  144327. static static_codebook _16u2_p2_0 = {
  144328. 4, 625,
  144329. _vq_lengthlist__16u2_p2_0,
  144330. 1, -533725184, 1611661312, 3, 0,
  144331. _vq_quantlist__16u2_p2_0,
  144332. NULL,
  144333. &_vq_auxt__16u2_p2_0,
  144334. NULL,
  144335. 0
  144336. };
  144337. static long _vq_quantlist__16u2_p3_0[] = {
  144338. 4,
  144339. 3,
  144340. 5,
  144341. 2,
  144342. 6,
  144343. 1,
  144344. 7,
  144345. 0,
  144346. 8,
  144347. };
  144348. static long _vq_lengthlist__16u2_p3_0[] = {
  144349. 2, 4, 4, 6, 6, 7, 7, 9, 9, 4, 5, 5, 6, 6, 8, 7,
  144350. 9, 9, 4, 5, 5, 6, 6, 7, 8, 9, 9, 6, 6, 6, 7, 7,
  144351. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  144352. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  144353. 9, 9,10, 9,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  144354. 11,
  144355. };
  144356. static float _vq_quantthresh__16u2_p3_0[] = {
  144357. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144358. };
  144359. static long _vq_quantmap__16u2_p3_0[] = {
  144360. 7, 5, 3, 1, 0, 2, 4, 6,
  144361. 8,
  144362. };
  144363. static encode_aux_threshmatch _vq_auxt__16u2_p3_0 = {
  144364. _vq_quantthresh__16u2_p3_0,
  144365. _vq_quantmap__16u2_p3_0,
  144366. 9,
  144367. 9
  144368. };
  144369. static static_codebook _16u2_p3_0 = {
  144370. 2, 81,
  144371. _vq_lengthlist__16u2_p3_0,
  144372. 1, -531628032, 1611661312, 4, 0,
  144373. _vq_quantlist__16u2_p3_0,
  144374. NULL,
  144375. &_vq_auxt__16u2_p3_0,
  144376. NULL,
  144377. 0
  144378. };
  144379. static long _vq_quantlist__16u2_p4_0[] = {
  144380. 8,
  144381. 7,
  144382. 9,
  144383. 6,
  144384. 10,
  144385. 5,
  144386. 11,
  144387. 4,
  144388. 12,
  144389. 3,
  144390. 13,
  144391. 2,
  144392. 14,
  144393. 1,
  144394. 15,
  144395. 0,
  144396. 16,
  144397. };
  144398. static long _vq_lengthlist__16u2_p4_0[] = {
  144399. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,11,
  144400. 11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  144401. 12,11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  144402. 11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  144403. 11,11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,
  144404. 10,11,11,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  144405. 11,11,12,12,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  144406. 10,11,11,11,12,12,12, 9, 9, 9, 9, 9, 9,10,10,10,
  144407. 10,10,11,11,12,12,13,13, 8, 9, 9, 9, 9,10, 9,10,
  144408. 10,10,10,11,11,12,12,13,13, 9, 9, 9, 9, 9,10,10,
  144409. 10,10,11,11,11,12,12,12,13,13, 9, 9, 9, 9, 9,10,
  144410. 10,10,10,11,11,12,11,12,12,13,13,10,10,10,10,10,
  144411. 11,11,11,11,11,12,12,12,12,13,13,14,10,10,10,10,
  144412. 10,11,11,11,11,12,11,12,12,13,12,13,13,11,11,11,
  144413. 11,11,12,12,12,12,12,12,13,13,13,13,14,14,11,11,
  144414. 11,11,11,12,12,12,12,12,12,13,12,13,13,14,14,11,
  144415. 12,12,12,12,12,12,13,13,13,13,13,13,14,14,14,14,
  144416. 11,12,12,12,12,12,12,13,13,13,13,14,13,14,14,14,
  144417. 14,
  144418. };
  144419. static float _vq_quantthresh__16u2_p4_0[] = {
  144420. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144421. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144422. };
  144423. static long _vq_quantmap__16u2_p4_0[] = {
  144424. 15, 13, 11, 9, 7, 5, 3, 1,
  144425. 0, 2, 4, 6, 8, 10, 12, 14,
  144426. 16,
  144427. };
  144428. static encode_aux_threshmatch _vq_auxt__16u2_p4_0 = {
  144429. _vq_quantthresh__16u2_p4_0,
  144430. _vq_quantmap__16u2_p4_0,
  144431. 17,
  144432. 17
  144433. };
  144434. static static_codebook _16u2_p4_0 = {
  144435. 2, 289,
  144436. _vq_lengthlist__16u2_p4_0,
  144437. 1, -529530880, 1611661312, 5, 0,
  144438. _vq_quantlist__16u2_p4_0,
  144439. NULL,
  144440. &_vq_auxt__16u2_p4_0,
  144441. NULL,
  144442. 0
  144443. };
  144444. static long _vq_quantlist__16u2_p5_0[] = {
  144445. 1,
  144446. 0,
  144447. 2,
  144448. };
  144449. static long _vq_lengthlist__16u2_p5_0[] = {
  144450. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10, 9, 7,
  144451. 10, 9, 5, 8, 9, 7, 9,10, 7, 9,10, 4, 9, 9, 9,11,
  144452. 11, 8,11,11, 7,11,11,10,10,13,10,14,13, 7,11,11,
  144453. 10,13,11,10,13,14, 5, 9, 9, 8,11,11, 9,11,11, 7,
  144454. 11,11,10,14,13,10,12,14, 7,11,11,10,13,13,10,13,
  144455. 10,
  144456. };
  144457. static float _vq_quantthresh__16u2_p5_0[] = {
  144458. -5.5, 5.5,
  144459. };
  144460. static long _vq_quantmap__16u2_p5_0[] = {
  144461. 1, 0, 2,
  144462. };
  144463. static encode_aux_threshmatch _vq_auxt__16u2_p5_0 = {
  144464. _vq_quantthresh__16u2_p5_0,
  144465. _vq_quantmap__16u2_p5_0,
  144466. 3,
  144467. 3
  144468. };
  144469. static static_codebook _16u2_p5_0 = {
  144470. 4, 81,
  144471. _vq_lengthlist__16u2_p5_0,
  144472. 1, -529137664, 1618345984, 2, 0,
  144473. _vq_quantlist__16u2_p5_0,
  144474. NULL,
  144475. &_vq_auxt__16u2_p5_0,
  144476. NULL,
  144477. 0
  144478. };
  144479. static long _vq_quantlist__16u2_p5_1[] = {
  144480. 5,
  144481. 4,
  144482. 6,
  144483. 3,
  144484. 7,
  144485. 2,
  144486. 8,
  144487. 1,
  144488. 9,
  144489. 0,
  144490. 10,
  144491. };
  144492. static long _vq_lengthlist__16u2_p5_1[] = {
  144493. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 5, 5, 5, 7, 7,
  144494. 7, 7, 8, 8, 8, 8, 5, 5, 6, 7, 7, 7, 7, 8, 8, 8,
  144495. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  144496. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  144497. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  144498. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  144499. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  144500. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  144501. };
  144502. static float _vq_quantthresh__16u2_p5_1[] = {
  144503. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144504. 3.5, 4.5,
  144505. };
  144506. static long _vq_quantmap__16u2_p5_1[] = {
  144507. 9, 7, 5, 3, 1, 0, 2, 4,
  144508. 6, 8, 10,
  144509. };
  144510. static encode_aux_threshmatch _vq_auxt__16u2_p5_1 = {
  144511. _vq_quantthresh__16u2_p5_1,
  144512. _vq_quantmap__16u2_p5_1,
  144513. 11,
  144514. 11
  144515. };
  144516. static static_codebook _16u2_p5_1 = {
  144517. 2, 121,
  144518. _vq_lengthlist__16u2_p5_1,
  144519. 1, -531365888, 1611661312, 4, 0,
  144520. _vq_quantlist__16u2_p5_1,
  144521. NULL,
  144522. &_vq_auxt__16u2_p5_1,
  144523. NULL,
  144524. 0
  144525. };
  144526. static long _vq_quantlist__16u2_p6_0[] = {
  144527. 6,
  144528. 5,
  144529. 7,
  144530. 4,
  144531. 8,
  144532. 3,
  144533. 9,
  144534. 2,
  144535. 10,
  144536. 1,
  144537. 11,
  144538. 0,
  144539. 12,
  144540. };
  144541. static long _vq_lengthlist__16u2_p6_0[] = {
  144542. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6,
  144543. 8, 8, 9, 9, 9, 9,10,10,12,11, 4, 6, 6, 8, 8, 9,
  144544. 9, 9, 9,10,10,11,12, 7, 8, 8, 9, 9,10,10,10,10,
  144545. 12,12,13,12, 7, 8, 8, 9, 9,10,10,10,10,11,12,12,
  144546. 12, 8, 9, 9,10,10,11,11,11,11,12,12,13,13, 8, 9,
  144547. 9,10,10,11,11,11,11,12,13,13,13, 8, 9, 9,10,10,
  144548. 11,11,12,12,13,13,14,14, 8, 9, 9,10,10,11,11,12,
  144549. 12,13,13,14,14, 9,10,10,11,12,13,12,13,14,14,14,
  144550. 14,14, 9,10,10,11,12,12,13,13,13,14,14,14,14,10,
  144551. 11,11,12,12,13,13,14,14,15,15,15,15,10,11,11,12,
  144552. 12,13,13,14,14,14,14,15,15,
  144553. };
  144554. static float _vq_quantthresh__16u2_p6_0[] = {
  144555. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  144556. 12.5, 17.5, 22.5, 27.5,
  144557. };
  144558. static long _vq_quantmap__16u2_p6_0[] = {
  144559. 11, 9, 7, 5, 3, 1, 0, 2,
  144560. 4, 6, 8, 10, 12,
  144561. };
  144562. static encode_aux_threshmatch _vq_auxt__16u2_p6_0 = {
  144563. _vq_quantthresh__16u2_p6_0,
  144564. _vq_quantmap__16u2_p6_0,
  144565. 13,
  144566. 13
  144567. };
  144568. static static_codebook _16u2_p6_0 = {
  144569. 2, 169,
  144570. _vq_lengthlist__16u2_p6_0,
  144571. 1, -526516224, 1616117760, 4, 0,
  144572. _vq_quantlist__16u2_p6_0,
  144573. NULL,
  144574. &_vq_auxt__16u2_p6_0,
  144575. NULL,
  144576. 0
  144577. };
  144578. static long _vq_quantlist__16u2_p6_1[] = {
  144579. 2,
  144580. 1,
  144581. 3,
  144582. 0,
  144583. 4,
  144584. };
  144585. static long _vq_lengthlist__16u2_p6_1[] = {
  144586. 2, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  144587. 5, 5, 6, 6, 5, 5, 5, 6, 6,
  144588. };
  144589. static float _vq_quantthresh__16u2_p6_1[] = {
  144590. -1.5, -0.5, 0.5, 1.5,
  144591. };
  144592. static long _vq_quantmap__16u2_p6_1[] = {
  144593. 3, 1, 0, 2, 4,
  144594. };
  144595. static encode_aux_threshmatch _vq_auxt__16u2_p6_1 = {
  144596. _vq_quantthresh__16u2_p6_1,
  144597. _vq_quantmap__16u2_p6_1,
  144598. 5,
  144599. 5
  144600. };
  144601. static static_codebook _16u2_p6_1 = {
  144602. 2, 25,
  144603. _vq_lengthlist__16u2_p6_1,
  144604. 1, -533725184, 1611661312, 3, 0,
  144605. _vq_quantlist__16u2_p6_1,
  144606. NULL,
  144607. &_vq_auxt__16u2_p6_1,
  144608. NULL,
  144609. 0
  144610. };
  144611. static long _vq_quantlist__16u2_p7_0[] = {
  144612. 6,
  144613. 5,
  144614. 7,
  144615. 4,
  144616. 8,
  144617. 3,
  144618. 9,
  144619. 2,
  144620. 10,
  144621. 1,
  144622. 11,
  144623. 0,
  144624. 12,
  144625. };
  144626. static long _vq_lengthlist__16u2_p7_0[] = {
  144627. 1, 4, 4, 7, 7, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 6,
  144628. 9, 9, 9, 9, 9, 9,10,10,11,11, 4, 6, 6, 8, 9, 9,
  144629. 9, 9, 9,10,11,12,11, 7, 8, 9,10,10,10,10,11,10,
  144630. 11,12,12,13, 7, 9, 9,10,10,10,10,10,10,11,12,13,
  144631. 13, 7, 9, 8,10,10,11,11,11,12,12,13,13,14, 7, 9,
  144632. 9,10,10,11,11,11,12,13,13,13,13, 8, 9, 9,10,11,
  144633. 11,12,12,12,13,13,13,13, 8, 9, 9,10,11,11,11,12,
  144634. 12,13,13,14,14, 9,10,10,12,11,12,13,13,13,14,13,
  144635. 13,13, 9,10,10,11,11,12,12,13,14,13,13,14,13,10,
  144636. 11,11,12,13,14,14,14,15,14,14,14,14,10,11,11,12,
  144637. 12,13,13,13,14,14,14,15,14,
  144638. };
  144639. static float _vq_quantthresh__16u2_p7_0[] = {
  144640. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  144641. 27.5, 38.5, 49.5, 60.5,
  144642. };
  144643. static long _vq_quantmap__16u2_p7_0[] = {
  144644. 11, 9, 7, 5, 3, 1, 0, 2,
  144645. 4, 6, 8, 10, 12,
  144646. };
  144647. static encode_aux_threshmatch _vq_auxt__16u2_p7_0 = {
  144648. _vq_quantthresh__16u2_p7_0,
  144649. _vq_quantmap__16u2_p7_0,
  144650. 13,
  144651. 13
  144652. };
  144653. static static_codebook _16u2_p7_0 = {
  144654. 2, 169,
  144655. _vq_lengthlist__16u2_p7_0,
  144656. 1, -523206656, 1618345984, 4, 0,
  144657. _vq_quantlist__16u2_p7_0,
  144658. NULL,
  144659. &_vq_auxt__16u2_p7_0,
  144660. NULL,
  144661. 0
  144662. };
  144663. static long _vq_quantlist__16u2_p7_1[] = {
  144664. 5,
  144665. 4,
  144666. 6,
  144667. 3,
  144668. 7,
  144669. 2,
  144670. 8,
  144671. 1,
  144672. 9,
  144673. 0,
  144674. 10,
  144675. };
  144676. static long _vq_lengthlist__16u2_p7_1[] = {
  144677. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  144678. 7, 7, 7, 7, 8, 8, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8,
  144679. 8, 6, 6, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 7, 7, 7,
  144680. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  144681. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  144682. 8, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8,
  144683. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  144684. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144685. };
  144686. static float _vq_quantthresh__16u2_p7_1[] = {
  144687. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144688. 3.5, 4.5,
  144689. };
  144690. static long _vq_quantmap__16u2_p7_1[] = {
  144691. 9, 7, 5, 3, 1, 0, 2, 4,
  144692. 6, 8, 10,
  144693. };
  144694. static encode_aux_threshmatch _vq_auxt__16u2_p7_1 = {
  144695. _vq_quantthresh__16u2_p7_1,
  144696. _vq_quantmap__16u2_p7_1,
  144697. 11,
  144698. 11
  144699. };
  144700. static static_codebook _16u2_p7_1 = {
  144701. 2, 121,
  144702. _vq_lengthlist__16u2_p7_1,
  144703. 1, -531365888, 1611661312, 4, 0,
  144704. _vq_quantlist__16u2_p7_1,
  144705. NULL,
  144706. &_vq_auxt__16u2_p7_1,
  144707. NULL,
  144708. 0
  144709. };
  144710. static long _vq_quantlist__16u2_p8_0[] = {
  144711. 7,
  144712. 6,
  144713. 8,
  144714. 5,
  144715. 9,
  144716. 4,
  144717. 10,
  144718. 3,
  144719. 11,
  144720. 2,
  144721. 12,
  144722. 1,
  144723. 13,
  144724. 0,
  144725. 14,
  144726. };
  144727. static long _vq_lengthlist__16u2_p8_0[] = {
  144728. 1, 5, 5, 7, 7, 8, 8, 7, 7, 8, 8,10, 9,11,11, 4,
  144729. 6, 6, 8, 8,10, 9, 9, 8, 9, 9,10,10,12,14, 4, 6,
  144730. 7, 8, 9, 9,10, 9, 8, 9, 9,10,12,12,11, 7, 8, 8,
  144731. 10,10,10,10, 9, 9,10,10,11,13,13,12, 7, 8, 8, 9,
  144732. 11,11,10, 9, 9,11,10,12,11,11,14, 8, 9, 9,11,10,
  144733. 11,11,10,10,11,11,13,12,14,12, 8, 9, 9,11,12,11,
  144734. 11,10,10,12,11,12,12,12,14, 7, 8, 8, 9, 9,10,10,
  144735. 10,11,12,11,13,13,14,12, 7, 8, 9, 9, 9,10,10,11,
  144736. 11,11,12,12,14,14,14, 8,10, 9,10,11,11,11,11,14,
  144737. 12,12,13,14,14,13, 9, 9, 9,10,11,11,11,12,12,12,
  144738. 14,12,14,13,14,10,10,10,12,11,12,11,14,13,14,13,
  144739. 14,14,13,14, 9,10,10,11,12,11,13,12,13,13,14,14,
  144740. 14,13,14,10,13,13,12,12,11,12,14,13,14,13,14,12,
  144741. 14,13,10,11,11,12,11,12,12,14,14,14,13,14,14,14,
  144742. 14,
  144743. };
  144744. static float _vq_quantthresh__16u2_p8_0[] = {
  144745. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  144746. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  144747. };
  144748. static long _vq_quantmap__16u2_p8_0[] = {
  144749. 13, 11, 9, 7, 5, 3, 1, 0,
  144750. 2, 4, 6, 8, 10, 12, 14,
  144751. };
  144752. static encode_aux_threshmatch _vq_auxt__16u2_p8_0 = {
  144753. _vq_quantthresh__16u2_p8_0,
  144754. _vq_quantmap__16u2_p8_0,
  144755. 15,
  144756. 15
  144757. };
  144758. static static_codebook _16u2_p8_0 = {
  144759. 2, 225,
  144760. _vq_lengthlist__16u2_p8_0,
  144761. 1, -520986624, 1620377600, 4, 0,
  144762. _vq_quantlist__16u2_p8_0,
  144763. NULL,
  144764. &_vq_auxt__16u2_p8_0,
  144765. NULL,
  144766. 0
  144767. };
  144768. static long _vq_quantlist__16u2_p8_1[] = {
  144769. 10,
  144770. 9,
  144771. 11,
  144772. 8,
  144773. 12,
  144774. 7,
  144775. 13,
  144776. 6,
  144777. 14,
  144778. 5,
  144779. 15,
  144780. 4,
  144781. 16,
  144782. 3,
  144783. 17,
  144784. 2,
  144785. 18,
  144786. 1,
  144787. 19,
  144788. 0,
  144789. 20,
  144790. };
  144791. static long _vq_lengthlist__16u2_p8_1[] = {
  144792. 2, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,10, 9, 9,
  144793. 9,10,10,10,10, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,
  144794. 10, 9,10,10,10,10,10,10,11,10, 5, 6, 6, 7, 7, 8,
  144795. 8, 8, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 7,
  144796. 7, 7, 8, 8, 9, 8, 9, 9,10, 9,10,10,10,10,10,10,
  144797. 11,10,11,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,10, 9,10,
  144798. 10,10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,
  144799. 10, 9,10,10,10,10,10,10,10,11,10,10,11,10, 8, 8,
  144800. 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,
  144801. 11,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  144802. 11,10,11,10,11,10,11,10, 8, 9, 9, 9, 9, 9,10,10,
  144803. 10,10,10,10,10,10,10,10,11,11,10,10,10, 9,10, 9,
  144804. 9,10,10,10,11,10,10,10,10,10,10,10,10,11,11,11,
  144805. 11,11, 9, 9, 9,10, 9,10,10,10,10,10,10,11,10,11,
  144806. 10,11,11,11,11,10,10, 9,10, 9,10,10,10,10,11,10,
  144807. 10,10,10,10,11,10,11,10,11,10,10,11, 9,10,10,10,
  144808. 10,10,10,10,10,10,11,10,10,11,11,10,11,11,11,11,
  144809. 11, 9, 9,10,10,10,10,10,11,10,10,11,10,10,11,10,
  144810. 10,11,11,11,11,11, 9,10,10,10,10,10,10,10,11,10,
  144811. 11,10,11,10,11,11,11,11,11,10,11,10,10,10,10,10,
  144812. 10,10,10,10,11,11,11,11,11,11,11,11,11,10,11,11,
  144813. 10,10,10,10,10,11,10,10,10,11,10,11,11,11,11,10,
  144814. 12,11,11,11,10,10,10,10,10,10,11,10,10,10,11,11,
  144815. 12,11,11,11,11,11,11,11,11,11,10,10,10,11,10,11,
  144816. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  144817. 10,10,11,10,11,10,10,11,11,11,11,11,11,11,11,11,
  144818. 11,11,11,10,10,10,10,10,10,10,11,11,10,11,11,10,
  144819. 11,11,10,11,11,11,10,11,11,
  144820. };
  144821. static float _vq_quantthresh__16u2_p8_1[] = {
  144822. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  144823. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  144824. 6.5, 7.5, 8.5, 9.5,
  144825. };
  144826. static long _vq_quantmap__16u2_p8_1[] = {
  144827. 19, 17, 15, 13, 11, 9, 7, 5,
  144828. 3, 1, 0, 2, 4, 6, 8, 10,
  144829. 12, 14, 16, 18, 20,
  144830. };
  144831. static encode_aux_threshmatch _vq_auxt__16u2_p8_1 = {
  144832. _vq_quantthresh__16u2_p8_1,
  144833. _vq_quantmap__16u2_p8_1,
  144834. 21,
  144835. 21
  144836. };
  144837. static static_codebook _16u2_p8_1 = {
  144838. 2, 441,
  144839. _vq_lengthlist__16u2_p8_1,
  144840. 1, -529268736, 1611661312, 5, 0,
  144841. _vq_quantlist__16u2_p8_1,
  144842. NULL,
  144843. &_vq_auxt__16u2_p8_1,
  144844. NULL,
  144845. 0
  144846. };
  144847. static long _vq_quantlist__16u2_p9_0[] = {
  144848. 5586,
  144849. 4655,
  144850. 6517,
  144851. 3724,
  144852. 7448,
  144853. 2793,
  144854. 8379,
  144855. 1862,
  144856. 9310,
  144857. 931,
  144858. 10241,
  144859. 0,
  144860. 11172,
  144861. 5521,
  144862. 5651,
  144863. };
  144864. static long _vq_lengthlist__16u2_p9_0[] = {
  144865. 1,10,10,10,10,10,10,10,10,10,10,10,10, 5, 4,10,
  144866. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144867. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144868. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144869. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144870. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144871. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144872. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144873. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144874. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144875. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144876. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144877. 10,10,10, 4,10,10,10,10,10,10,10,10,10,10,10,10,
  144878. 6, 6, 5,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 5,
  144879. 5,
  144880. };
  144881. static float _vq_quantthresh__16u2_p9_0[] = {
  144882. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -498, -32.5, 32.5,
  144883. 498, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5,
  144884. };
  144885. static long _vq_quantmap__16u2_p9_0[] = {
  144886. 11, 9, 7, 5, 3, 1, 13, 0,
  144887. 14, 2, 4, 6, 8, 10, 12,
  144888. };
  144889. static encode_aux_threshmatch _vq_auxt__16u2_p9_0 = {
  144890. _vq_quantthresh__16u2_p9_0,
  144891. _vq_quantmap__16u2_p9_0,
  144892. 15,
  144893. 15
  144894. };
  144895. static static_codebook _16u2_p9_0 = {
  144896. 2, 225,
  144897. _vq_lengthlist__16u2_p9_0,
  144898. 1, -510275072, 1611661312, 14, 0,
  144899. _vq_quantlist__16u2_p9_0,
  144900. NULL,
  144901. &_vq_auxt__16u2_p9_0,
  144902. NULL,
  144903. 0
  144904. };
  144905. static long _vq_quantlist__16u2_p9_1[] = {
  144906. 392,
  144907. 343,
  144908. 441,
  144909. 294,
  144910. 490,
  144911. 245,
  144912. 539,
  144913. 196,
  144914. 588,
  144915. 147,
  144916. 637,
  144917. 98,
  144918. 686,
  144919. 49,
  144920. 735,
  144921. 0,
  144922. 784,
  144923. 388,
  144924. 396,
  144925. };
  144926. static long _vq_lengthlist__16u2_p9_1[] = {
  144927. 1,12,10,12,10,12,10,12,11,12,12,12,12,12,12,12,
  144928. 12, 5, 5, 9,10,12,11,11,12,12,12,12,12,12,12,12,
  144929. 12,12,12,12,10, 9, 9,11, 9,11,11,12,11,12,12,12,
  144930. 12,12,12,12,12,12,12, 8, 8,10,11, 9,12,11,12,12,
  144931. 12,12,12,12,12,12,12,12,12,12, 9, 8,10,11,12,11,
  144932. 12,11,12,12,12,12,12,12,12,12,12,12,12, 8, 9,11,
  144933. 11,10,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144934. 9,10,11,12,11,12,11,12,12,12,12,12,12,12,12,12,
  144935. 12,12,12, 9, 9,11,12,12,12,12,12,12,12,12,12,12,
  144936. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144937. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144938. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144939. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144940. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144941. 12,12,12,12,11,11,11,11,11,11,11,11,11,11,11,11,
  144942. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144943. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144944. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144945. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144946. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144947. 11,11,11, 5, 8, 9, 9, 8,11, 9,11,11,11,11,11,11,
  144948. 11,11,11,11, 5, 5, 4, 8, 8, 8, 8,10, 9,10,10,11,
  144949. 11,11,11,11,11,11,11, 5, 4,
  144950. };
  144951. static float _vq_quantthresh__16u2_p9_1[] = {
  144952. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -26.5,
  144953. -2, 2, 26.5, 73.5, 122.5, 171.5, 220.5, 269.5,
  144954. 318.5, 367.5,
  144955. };
  144956. static long _vq_quantmap__16u2_p9_1[] = {
  144957. 15, 13, 11, 9, 7, 5, 3, 1,
  144958. 17, 0, 18, 2, 4, 6, 8, 10,
  144959. 12, 14, 16,
  144960. };
  144961. static encode_aux_threshmatch _vq_auxt__16u2_p9_1 = {
  144962. _vq_quantthresh__16u2_p9_1,
  144963. _vq_quantmap__16u2_p9_1,
  144964. 19,
  144965. 19
  144966. };
  144967. static static_codebook _16u2_p9_1 = {
  144968. 2, 361,
  144969. _vq_lengthlist__16u2_p9_1,
  144970. 1, -518488064, 1611661312, 10, 0,
  144971. _vq_quantlist__16u2_p9_1,
  144972. NULL,
  144973. &_vq_auxt__16u2_p9_1,
  144974. NULL,
  144975. 0
  144976. };
  144977. static long _vq_quantlist__16u2_p9_2[] = {
  144978. 24,
  144979. 23,
  144980. 25,
  144981. 22,
  144982. 26,
  144983. 21,
  144984. 27,
  144985. 20,
  144986. 28,
  144987. 19,
  144988. 29,
  144989. 18,
  144990. 30,
  144991. 17,
  144992. 31,
  144993. 16,
  144994. 32,
  144995. 15,
  144996. 33,
  144997. 14,
  144998. 34,
  144999. 13,
  145000. 35,
  145001. 12,
  145002. 36,
  145003. 11,
  145004. 37,
  145005. 10,
  145006. 38,
  145007. 9,
  145008. 39,
  145009. 8,
  145010. 40,
  145011. 7,
  145012. 41,
  145013. 6,
  145014. 42,
  145015. 5,
  145016. 43,
  145017. 4,
  145018. 44,
  145019. 3,
  145020. 45,
  145021. 2,
  145022. 46,
  145023. 1,
  145024. 47,
  145025. 0,
  145026. 48,
  145027. };
  145028. static long _vq_lengthlist__16u2_p9_2[] = {
  145029. 1, 3, 3, 4, 7, 7, 7, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  145030. 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 9, 9, 8, 9, 9,
  145031. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,12,12,10,
  145032. 11,
  145033. };
  145034. static float _vq_quantthresh__16u2_p9_2[] = {
  145035. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  145036. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  145037. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  145038. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  145039. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  145040. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  145041. };
  145042. static long _vq_quantmap__16u2_p9_2[] = {
  145043. 47, 45, 43, 41, 39, 37, 35, 33,
  145044. 31, 29, 27, 25, 23, 21, 19, 17,
  145045. 15, 13, 11, 9, 7, 5, 3, 1,
  145046. 0, 2, 4, 6, 8, 10, 12, 14,
  145047. 16, 18, 20, 22, 24, 26, 28, 30,
  145048. 32, 34, 36, 38, 40, 42, 44, 46,
  145049. 48,
  145050. };
  145051. static encode_aux_threshmatch _vq_auxt__16u2_p9_2 = {
  145052. _vq_quantthresh__16u2_p9_2,
  145053. _vq_quantmap__16u2_p9_2,
  145054. 49,
  145055. 49
  145056. };
  145057. static static_codebook _16u2_p9_2 = {
  145058. 1, 49,
  145059. _vq_lengthlist__16u2_p9_2,
  145060. 1, -526909440, 1611661312, 6, 0,
  145061. _vq_quantlist__16u2_p9_2,
  145062. NULL,
  145063. &_vq_auxt__16u2_p9_2,
  145064. NULL,
  145065. 0
  145066. };
  145067. static long _vq_quantlist__8u0__p1_0[] = {
  145068. 1,
  145069. 0,
  145070. 2,
  145071. };
  145072. static long _vq_lengthlist__8u0__p1_0[] = {
  145073. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  145074. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 4, 9, 8, 8,11,
  145075. 11, 8,11,11, 7,11,11,10,11,13,10,13,13, 7,11,11,
  145076. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 8,11,11, 7,
  145077. 11,11, 9,13,13,10,12,13, 7,11,11,10,13,13,10,13,
  145078. 11,
  145079. };
  145080. static float _vq_quantthresh__8u0__p1_0[] = {
  145081. -0.5, 0.5,
  145082. };
  145083. static long _vq_quantmap__8u0__p1_0[] = {
  145084. 1, 0, 2,
  145085. };
  145086. static encode_aux_threshmatch _vq_auxt__8u0__p1_0 = {
  145087. _vq_quantthresh__8u0__p1_0,
  145088. _vq_quantmap__8u0__p1_0,
  145089. 3,
  145090. 3
  145091. };
  145092. static static_codebook _8u0__p1_0 = {
  145093. 4, 81,
  145094. _vq_lengthlist__8u0__p1_0,
  145095. 1, -535822336, 1611661312, 2, 0,
  145096. _vq_quantlist__8u0__p1_0,
  145097. NULL,
  145098. &_vq_auxt__8u0__p1_0,
  145099. NULL,
  145100. 0
  145101. };
  145102. static long _vq_quantlist__8u0__p2_0[] = {
  145103. 1,
  145104. 0,
  145105. 2,
  145106. };
  145107. static long _vq_lengthlist__8u0__p2_0[] = {
  145108. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 6, 7, 8, 6,
  145109. 7, 8, 5, 7, 7, 6, 8, 8, 7, 9, 7, 5, 7, 7, 7, 9,
  145110. 9, 7, 8, 8, 6, 9, 8, 7, 7,10, 8,10,10, 6, 8, 8,
  145111. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  145112. 8, 8, 8,10,10, 8, 8,10, 6, 8, 9, 8,10,10, 7,10,
  145113. 8,
  145114. };
  145115. static float _vq_quantthresh__8u0__p2_0[] = {
  145116. -0.5, 0.5,
  145117. };
  145118. static long _vq_quantmap__8u0__p2_0[] = {
  145119. 1, 0, 2,
  145120. };
  145121. static encode_aux_threshmatch _vq_auxt__8u0__p2_0 = {
  145122. _vq_quantthresh__8u0__p2_0,
  145123. _vq_quantmap__8u0__p2_0,
  145124. 3,
  145125. 3
  145126. };
  145127. static static_codebook _8u0__p2_0 = {
  145128. 4, 81,
  145129. _vq_lengthlist__8u0__p2_0,
  145130. 1, -535822336, 1611661312, 2, 0,
  145131. _vq_quantlist__8u0__p2_0,
  145132. NULL,
  145133. &_vq_auxt__8u0__p2_0,
  145134. NULL,
  145135. 0
  145136. };
  145137. static long _vq_quantlist__8u0__p3_0[] = {
  145138. 2,
  145139. 1,
  145140. 3,
  145141. 0,
  145142. 4,
  145143. };
  145144. static long _vq_lengthlist__8u0__p3_0[] = {
  145145. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  145146. 10, 9,11,11, 8, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  145147. 10,11,11, 8,10,10,11,11,10,11,11,12,12,10,11,11,
  145148. 12,13, 6, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  145149. 11, 9,10,11,12,12,10,11,11,12,12, 8,11,11,14,13,
  145150. 10,12,11,15,13,10,12,11,14,14,12,13,12,16,14,12,
  145151. 14,12,16,15, 8,11,11,13,14,10,11,12,13,15,10,11,
  145152. 12,13,15,11,12,13,14,15,12,12,14,14,16, 5, 8, 8,
  145153. 11,11, 9,11,11,12,12, 8,10,11,12,12,11,12,12,15,
  145154. 14,11,12,12,14,14, 7,11,10,13,12,10,11,12,13,14,
  145155. 10,12,12,14,13,12,13,13,14,15,12,13,13,15,15, 7,
  145156. 10,11,12,13,10,12,11,14,13,10,12,13,13,15,12,13,
  145157. 12,14,14,11,13,13,15,16, 9,12,12,15,14,11,13,13,
  145158. 15,16,11,13,13,16,16,13,14,15,15,15,12,14,15,17,
  145159. 16, 9,12,12,14,15,11,13,13,15,16,11,13,13,16,18,
  145160. 13,14,14,17,16,13,15,15,17,18, 5, 8, 9,11,11, 8,
  145161. 11,11,12,12, 8,10,11,12,12,11,12,12,14,14,11,12,
  145162. 12,14,15, 7,11,10,12,13,10,12,12,14,13,10,11,12,
  145163. 13,14,11,13,13,15,14,12,13,13,14,15, 7,10,11,13,
  145164. 13,10,12,12,13,14,10,12,12,13,13,11,13,13,16,16,
  145165. 12,13,13,15,14, 9,12,12,16,15,10,13,13,15,15,11,
  145166. 13,13,17,15,12,15,15,18,17,13,14,14,15,16, 9,12,
  145167. 12,15,15,11,13,13,15,16,11,13,13,15,15,12,15,15,
  145168. 16,16,13,15,14,17,15, 7,11,11,15,15,10,13,13,16,
  145169. 15,10,13,13,15,16,14,15,15,17,19,13,15,14,15,18,
  145170. 9,12,12,16,16,11,13,14,17,16,11,13,13,17,16,15,
  145171. 15,16,17,19,13,15,16, 0,18, 9,12,12,16,15,11,14,
  145172. 13,17,17,11,13,14,16,16,15,16,16,19,18,13,15,15,
  145173. 17,19,11,14,14,19,16,12,14,15, 0,18,12,16,15,18,
  145174. 17,15,15,18,16,19,14,15,17,19,19,11,14,14,18,19,
  145175. 13,15,14,19,19,12,16,15,18,17,15,17,15, 0,16,14,
  145176. 17,16,19, 0, 7,11,11,14,14,10,12,12,15,15,10,13,
  145177. 13,16,15,13,15,15,17, 0,14,15,15,16,19, 9,12,12,
  145178. 16,16,11,14,14,16,16,11,13,13,16,16,14,17,16,19,
  145179. 0,14,18,17,17,19, 9,12,12,15,16,11,13,13,15,17,
  145180. 12,14,13,19,16,13,15,15,17,19,15,17,16,17,19,11,
  145181. 14,14,19,16,12,15,15,19,17,13,14,15,17,19,14,16,
  145182. 17,19,19,16,15,16,17,19,11,15,14,16,16,12,15,15,
  145183. 19, 0,12,14,15,19,19,14,16,16, 0,18,15,19,14,18,
  145184. 16,
  145185. };
  145186. static float _vq_quantthresh__8u0__p3_0[] = {
  145187. -1.5, -0.5, 0.5, 1.5,
  145188. };
  145189. static long _vq_quantmap__8u0__p3_0[] = {
  145190. 3, 1, 0, 2, 4,
  145191. };
  145192. static encode_aux_threshmatch _vq_auxt__8u0__p3_0 = {
  145193. _vq_quantthresh__8u0__p3_0,
  145194. _vq_quantmap__8u0__p3_0,
  145195. 5,
  145196. 5
  145197. };
  145198. static static_codebook _8u0__p3_0 = {
  145199. 4, 625,
  145200. _vq_lengthlist__8u0__p3_0,
  145201. 1, -533725184, 1611661312, 3, 0,
  145202. _vq_quantlist__8u0__p3_0,
  145203. NULL,
  145204. &_vq_auxt__8u0__p3_0,
  145205. NULL,
  145206. 0
  145207. };
  145208. static long _vq_quantlist__8u0__p4_0[] = {
  145209. 2,
  145210. 1,
  145211. 3,
  145212. 0,
  145213. 4,
  145214. };
  145215. static long _vq_lengthlist__8u0__p4_0[] = {
  145216. 3, 5, 5, 8, 8, 5, 6, 7, 9, 9, 6, 7, 6, 9, 9, 9,
  145217. 9, 9,10,11, 9, 9, 9,11,10, 6, 7, 7,10,10, 7, 7,
  145218. 8,10,10, 7, 8, 8,10,10,10,10,10,10,11, 9,10,10,
  145219. 11,12, 6, 7, 7,10,10, 7, 8, 8,10,10, 7, 8, 7,10,
  145220. 10, 9,10,10,12,11,10,10,10,11,10, 9,10,10,12,11,
  145221. 10,10,10,13,11, 9,10,10,12,12,11,11,12,12,13,11,
  145222. 11,11,12,13, 9,10,10,12,12,10,10,11,12,12,10,10,
  145223. 11,12,12,11,11,11,13,13,11,12,12,13,13, 5, 7, 7,
  145224. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,11,12,
  145225. 12,10,11,10,12,12, 7, 8, 8,11,11, 7, 8, 9,10,11,
  145226. 8, 9, 9,11,11,11,10,11,10,12,10,11,11,12,13, 7,
  145227. 8, 8,10,11, 8, 9, 8,12,10, 8, 9, 9,11,12,10,11,
  145228. 10,13,11,10,11,11,13,12, 9,11,10,13,12,10,10,11,
  145229. 12,12,10,11,11,13,13,12,10,13,11,14,11,12,12,15,
  145230. 13, 9,11,11,13,13,10,11,11,13,12,10,11,11,12,14,
  145231. 12,13,11,14,12,12,12,12,14,14, 5, 7, 7,10,10, 7,
  145232. 8, 8,10,10, 7, 8, 8,11,10,10,11,11,12,12,10,11,
  145233. 10,12,12, 7, 8, 8,10,11, 8, 9, 9,12,11, 8, 8, 9,
  145234. 10,11,10,11,11,12,13,11,10,11,11,13, 6, 8, 8,10,
  145235. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,11,11,12,12,
  145236. 10,11,10,13,10, 9,11,10,13,12,10,12,11,13,13,10,
  145237. 10,11,12,13,11,12,13,15,14,11,11,13,12,13, 9,10,
  145238. 11,12,13,10,11,11,12,13,10,11,10,13,12,12,13,13,
  145239. 13,14,12,12,11,14,11, 8,10,10,12,13,10,11,11,13,
  145240. 13,10,11,10,13,13,12,13,14,15,14,12,12,12,14,13,
  145241. 9,10,10,13,12,10,10,12,13,13,10,11,11,15,12,12,
  145242. 12,13,15,14,12,13,13,15,13, 9,10,11,12,13,10,12,
  145243. 10,13,12,10,11,11,12,13,12,14,12,15,13,12,12,12,
  145244. 15,14,11,12,11,14,13,11,11,12,14,14,12,13,13,14,
  145245. 13,13,11,15,11,15,14,14,14,16,15,11,12,12,13,14,
  145246. 11,13,11,14,14,12,12,13,14,15,12,14,12,15,12,13,
  145247. 15,14,16,15, 8,10,10,12,12,10,10,10,12,13,10,11,
  145248. 11,13,13,12,12,12,13,14,13,13,13,15,15, 9,10,10,
  145249. 12,12,10,11,11,13,12,10,10,11,13,13,12,12,12,14,
  145250. 14,12,12,13,15,14, 9,10,10,13,12,10,10,12,12,13,
  145251. 10,11,10,13,13,12,13,13,14,14,12,13,12,14,13,11,
  145252. 12,12,14,13,12,13,12,14,14,10,12,12,14,14,14,14,
  145253. 14,16,14,13,12,14,12,15,10,12,12,14,15,12,13,13,
  145254. 14,16,11,12,11,15,14,13,14,14,14,15,13,14,11,14,
  145255. 12,
  145256. };
  145257. static float _vq_quantthresh__8u0__p4_0[] = {
  145258. -1.5, -0.5, 0.5, 1.5,
  145259. };
  145260. static long _vq_quantmap__8u0__p4_0[] = {
  145261. 3, 1, 0, 2, 4,
  145262. };
  145263. static encode_aux_threshmatch _vq_auxt__8u0__p4_0 = {
  145264. _vq_quantthresh__8u0__p4_0,
  145265. _vq_quantmap__8u0__p4_0,
  145266. 5,
  145267. 5
  145268. };
  145269. static static_codebook _8u0__p4_0 = {
  145270. 4, 625,
  145271. _vq_lengthlist__8u0__p4_0,
  145272. 1, -533725184, 1611661312, 3, 0,
  145273. _vq_quantlist__8u0__p4_0,
  145274. NULL,
  145275. &_vq_auxt__8u0__p4_0,
  145276. NULL,
  145277. 0
  145278. };
  145279. static long _vq_quantlist__8u0__p5_0[] = {
  145280. 4,
  145281. 3,
  145282. 5,
  145283. 2,
  145284. 6,
  145285. 1,
  145286. 7,
  145287. 0,
  145288. 8,
  145289. };
  145290. static long _vq_lengthlist__8u0__p5_0[] = {
  145291. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 7, 8, 8,
  145292. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 6, 8, 8, 9, 9,
  145293. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  145294. 9, 9,10,10,12,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  145295. 10,10,11,11,11,12,12,12, 9,10,10,11,11,12,12,12,
  145296. 12,
  145297. };
  145298. static float _vq_quantthresh__8u0__p5_0[] = {
  145299. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145300. };
  145301. static long _vq_quantmap__8u0__p5_0[] = {
  145302. 7, 5, 3, 1, 0, 2, 4, 6,
  145303. 8,
  145304. };
  145305. static encode_aux_threshmatch _vq_auxt__8u0__p5_0 = {
  145306. _vq_quantthresh__8u0__p5_0,
  145307. _vq_quantmap__8u0__p5_0,
  145308. 9,
  145309. 9
  145310. };
  145311. static static_codebook _8u0__p5_0 = {
  145312. 2, 81,
  145313. _vq_lengthlist__8u0__p5_0,
  145314. 1, -531628032, 1611661312, 4, 0,
  145315. _vq_quantlist__8u0__p5_0,
  145316. NULL,
  145317. &_vq_auxt__8u0__p5_0,
  145318. NULL,
  145319. 0
  145320. };
  145321. static long _vq_quantlist__8u0__p6_0[] = {
  145322. 6,
  145323. 5,
  145324. 7,
  145325. 4,
  145326. 8,
  145327. 3,
  145328. 9,
  145329. 2,
  145330. 10,
  145331. 1,
  145332. 11,
  145333. 0,
  145334. 12,
  145335. };
  145336. static long _vq_lengthlist__8u0__p6_0[] = {
  145337. 1, 4, 4, 7, 7, 9, 9,11,11,12,12,16,16, 3, 6, 6,
  145338. 9, 9,11,11,12,12,13,14,18,16, 3, 6, 7, 9, 9,11,
  145339. 11,13,12,14,14,17,16, 7, 9, 9,11,11,12,12,14,14,
  145340. 14,14,17,16, 7, 9, 9,11,11,13,12,13,13,14,14,17,
  145341. 0, 9,11,11,12,13,14,14,14,13,15,14,17,17, 9,11,
  145342. 11,12,12,14,14,13,14,14,15, 0, 0,11,12,12,15,14,
  145343. 15,14,15,14,15,16,17, 0,11,12,13,13,13,14,14,15,
  145344. 14,15,15, 0, 0,12,14,14,15,15,14,16,15,15,17,16,
  145345. 0,18,13,14,14,15,14,15,14,15,16,17,16, 0, 0,17,
  145346. 17,18, 0,16,18,16, 0, 0, 0,17, 0, 0,16, 0, 0,16,
  145347. 16, 0,15, 0,17, 0, 0, 0, 0,
  145348. };
  145349. static float _vq_quantthresh__8u0__p6_0[] = {
  145350. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  145351. 12.5, 17.5, 22.5, 27.5,
  145352. };
  145353. static long _vq_quantmap__8u0__p6_0[] = {
  145354. 11, 9, 7, 5, 3, 1, 0, 2,
  145355. 4, 6, 8, 10, 12,
  145356. };
  145357. static encode_aux_threshmatch _vq_auxt__8u0__p6_0 = {
  145358. _vq_quantthresh__8u0__p6_0,
  145359. _vq_quantmap__8u0__p6_0,
  145360. 13,
  145361. 13
  145362. };
  145363. static static_codebook _8u0__p6_0 = {
  145364. 2, 169,
  145365. _vq_lengthlist__8u0__p6_0,
  145366. 1, -526516224, 1616117760, 4, 0,
  145367. _vq_quantlist__8u0__p6_0,
  145368. NULL,
  145369. &_vq_auxt__8u0__p6_0,
  145370. NULL,
  145371. 0
  145372. };
  145373. static long _vq_quantlist__8u0__p6_1[] = {
  145374. 2,
  145375. 1,
  145376. 3,
  145377. 0,
  145378. 4,
  145379. };
  145380. static long _vq_lengthlist__8u0__p6_1[] = {
  145381. 1, 4, 4, 6, 6, 4, 6, 5, 7, 7, 4, 5, 6, 7, 7, 6,
  145382. 7, 7, 7, 7, 6, 7, 7, 7, 7,
  145383. };
  145384. static float _vq_quantthresh__8u0__p6_1[] = {
  145385. -1.5, -0.5, 0.5, 1.5,
  145386. };
  145387. static long _vq_quantmap__8u0__p6_1[] = {
  145388. 3, 1, 0, 2, 4,
  145389. };
  145390. static encode_aux_threshmatch _vq_auxt__8u0__p6_1 = {
  145391. _vq_quantthresh__8u0__p6_1,
  145392. _vq_quantmap__8u0__p6_1,
  145393. 5,
  145394. 5
  145395. };
  145396. static static_codebook _8u0__p6_1 = {
  145397. 2, 25,
  145398. _vq_lengthlist__8u0__p6_1,
  145399. 1, -533725184, 1611661312, 3, 0,
  145400. _vq_quantlist__8u0__p6_1,
  145401. NULL,
  145402. &_vq_auxt__8u0__p6_1,
  145403. NULL,
  145404. 0
  145405. };
  145406. static long _vq_quantlist__8u0__p7_0[] = {
  145407. 1,
  145408. 0,
  145409. 2,
  145410. };
  145411. static long _vq_lengthlist__8u0__p7_0[] = {
  145412. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145413. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145414. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145415. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145416. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145417. 7,
  145418. };
  145419. static float _vq_quantthresh__8u0__p7_0[] = {
  145420. -157.5, 157.5,
  145421. };
  145422. static long _vq_quantmap__8u0__p7_0[] = {
  145423. 1, 0, 2,
  145424. };
  145425. static encode_aux_threshmatch _vq_auxt__8u0__p7_0 = {
  145426. _vq_quantthresh__8u0__p7_0,
  145427. _vq_quantmap__8u0__p7_0,
  145428. 3,
  145429. 3
  145430. };
  145431. static static_codebook _8u0__p7_0 = {
  145432. 4, 81,
  145433. _vq_lengthlist__8u0__p7_0,
  145434. 1, -518803456, 1628680192, 2, 0,
  145435. _vq_quantlist__8u0__p7_0,
  145436. NULL,
  145437. &_vq_auxt__8u0__p7_0,
  145438. NULL,
  145439. 0
  145440. };
  145441. static long _vq_quantlist__8u0__p7_1[] = {
  145442. 7,
  145443. 6,
  145444. 8,
  145445. 5,
  145446. 9,
  145447. 4,
  145448. 10,
  145449. 3,
  145450. 11,
  145451. 2,
  145452. 12,
  145453. 1,
  145454. 13,
  145455. 0,
  145456. 14,
  145457. };
  145458. static long _vq_lengthlist__8u0__p7_1[] = {
  145459. 1, 5, 5, 5, 5,10,10,11,11,11,11,11,11,11,11, 5,
  145460. 7, 6, 8, 8, 9,10,11,11,11,11,11,11,11,11, 6, 6,
  145461. 7, 9, 7,11,10,11,11,11,11,11,11,11,11, 5, 6, 6,
  145462. 11, 8,11,11,11,11,11,11,11,11,11,11, 5, 6, 6, 9,
  145463. 10,11,10,11,11,11,11,11,11,11,11, 7,10,10,11,11,
  145464. 11,11,11,11,11,11,11,11,11,11, 7,11, 8,11,11,11,
  145465. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145466. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145467. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145468. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145469. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145470. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145471. 11,11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,
  145472. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145473. 10,
  145474. };
  145475. static float _vq_quantthresh__8u0__p7_1[] = {
  145476. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  145477. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  145478. };
  145479. static long _vq_quantmap__8u0__p7_1[] = {
  145480. 13, 11, 9, 7, 5, 3, 1, 0,
  145481. 2, 4, 6, 8, 10, 12, 14,
  145482. };
  145483. static encode_aux_threshmatch _vq_auxt__8u0__p7_1 = {
  145484. _vq_quantthresh__8u0__p7_1,
  145485. _vq_quantmap__8u0__p7_1,
  145486. 15,
  145487. 15
  145488. };
  145489. static static_codebook _8u0__p7_1 = {
  145490. 2, 225,
  145491. _vq_lengthlist__8u0__p7_1,
  145492. 1, -520986624, 1620377600, 4, 0,
  145493. _vq_quantlist__8u0__p7_1,
  145494. NULL,
  145495. &_vq_auxt__8u0__p7_1,
  145496. NULL,
  145497. 0
  145498. };
  145499. static long _vq_quantlist__8u0__p7_2[] = {
  145500. 10,
  145501. 9,
  145502. 11,
  145503. 8,
  145504. 12,
  145505. 7,
  145506. 13,
  145507. 6,
  145508. 14,
  145509. 5,
  145510. 15,
  145511. 4,
  145512. 16,
  145513. 3,
  145514. 17,
  145515. 2,
  145516. 18,
  145517. 1,
  145518. 19,
  145519. 0,
  145520. 20,
  145521. };
  145522. static long _vq_lengthlist__8u0__p7_2[] = {
  145523. 1, 6, 5, 7, 7, 9, 9, 9, 9,10,12,12,10,11,11,10,
  145524. 11,11,11,10,11, 6, 8, 8, 9, 9,10,10, 9,10,11,11,
  145525. 10,11,11,11,11,10,11,11,11,11, 6, 7, 8, 9, 9, 9,
  145526. 10,11,10,11,12,11,10,11,11,11,11,11,11,12,10, 8,
  145527. 9, 9,10, 9,10,10, 9,10,10,10,10,10, 9,10,10,10,
  145528. 10, 9,10,10, 9, 9, 9, 9,10,10, 9, 9,10,10,11,10,
  145529. 9,12,10,11,10, 9,10,10,10, 8, 9, 9,10, 9,10, 9,
  145530. 9,10,10, 9,10, 9,11,10,10,10,10,10, 9,10, 8, 8,
  145531. 9, 9,10, 9,11, 9, 8, 9, 9,10,11,10,10,10,11,12,
  145532. 9, 9,11, 8, 9, 8,11,10,11,10,10, 9,11,10,10,10,
  145533. 10,10,10,10,11,11,11,11, 8, 9, 9, 9,10,10,10,11,
  145534. 11,12,11,12,11,10,10,10,12,11,11,11,10, 8,10, 9,
  145535. 11,10,10,11,12,10,11,12,11,11,12,11,12,12,10,11,
  145536. 11,10, 9, 9,10,11,12,10,10,10,11,10,11,11,10,12,
  145537. 12,10,11,10,11,12,10, 9,10,10,11,10,11,11,11,11,
  145538. 11,12,11,11,11, 9,11,10,11,10,11,10, 9, 9,10,11,
  145539. 11,11,10,10,11,12,12,11,12,11,11,11,12,12,12,12,
  145540. 11, 9,11,11,12,10,11,11,11,11,11,11,12,11,11,12,
  145541. 11,11,11,10,11,11, 9,11,10,11,11,11,10,10,10,11,
  145542. 11,11,12,10,11,10,11,11,11,11,12, 9,11,10,11,11,
  145543. 10,10,11,11, 9,11,11,12,10,10,10,10,10,11,11,10,
  145544. 9,10,11,11,12,11,10,10,12,11,11,12,11,12,11,11,
  145545. 10,10,11,11,10,12,11,10,11,10,11,10,10,10,11,11,
  145546. 10,10,11,11,11,11,10,10,10,12,11,11,11,11,10, 9,
  145547. 10,11,11,11,12,11,11,11,12,10,11,11,11, 9,10,11,
  145548. 11,11,11,11,11,10,10,11,11,12,11,10,11,12,11,10,
  145549. 10,11, 9,10,11,11,11,11,11,10,11,11,10,12,11,11,
  145550. 11,12,11,11,11,10,10,11,11,
  145551. };
  145552. static float _vq_quantthresh__8u0__p7_2[] = {
  145553. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  145554. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  145555. 6.5, 7.5, 8.5, 9.5,
  145556. };
  145557. static long _vq_quantmap__8u0__p7_2[] = {
  145558. 19, 17, 15, 13, 11, 9, 7, 5,
  145559. 3, 1, 0, 2, 4, 6, 8, 10,
  145560. 12, 14, 16, 18, 20,
  145561. };
  145562. static encode_aux_threshmatch _vq_auxt__8u0__p7_2 = {
  145563. _vq_quantthresh__8u0__p7_2,
  145564. _vq_quantmap__8u0__p7_2,
  145565. 21,
  145566. 21
  145567. };
  145568. static static_codebook _8u0__p7_2 = {
  145569. 2, 441,
  145570. _vq_lengthlist__8u0__p7_2,
  145571. 1, -529268736, 1611661312, 5, 0,
  145572. _vq_quantlist__8u0__p7_2,
  145573. NULL,
  145574. &_vq_auxt__8u0__p7_2,
  145575. NULL,
  145576. 0
  145577. };
  145578. static long _huff_lengthlist__8u0__single[] = {
  145579. 4, 7,11, 9,12, 8, 7,10, 6, 4, 5, 5, 7, 5, 6,16,
  145580. 9, 5, 5, 6, 7, 7, 9,16, 7, 4, 6, 5, 7, 5, 7,17,
  145581. 10, 7, 7, 8, 7, 7, 8,18, 7, 5, 6, 4, 5, 4, 5,15,
  145582. 7, 6, 7, 5, 6, 4, 5,15,12,13,18,12,17,11, 9,17,
  145583. };
  145584. static static_codebook _huff_book__8u0__single = {
  145585. 2, 64,
  145586. _huff_lengthlist__8u0__single,
  145587. 0, 0, 0, 0, 0,
  145588. NULL,
  145589. NULL,
  145590. NULL,
  145591. NULL,
  145592. 0
  145593. };
  145594. static long _vq_quantlist__8u1__p1_0[] = {
  145595. 1,
  145596. 0,
  145597. 2,
  145598. };
  145599. static long _vq_lengthlist__8u1__p1_0[] = {
  145600. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 7, 9,10, 7,
  145601. 9, 9, 5, 8, 8, 7,10, 9, 7, 9, 9, 5, 8, 8, 8,10,
  145602. 10, 8,10,10, 7,10,10, 9,10,12,10,12,12, 7,10,10,
  145603. 9,12,11,10,12,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  145604. 10,10,10,12,12, 9,11,12, 7,10,10,10,12,12, 9,12,
  145605. 10,
  145606. };
  145607. static float _vq_quantthresh__8u1__p1_0[] = {
  145608. -0.5, 0.5,
  145609. };
  145610. static long _vq_quantmap__8u1__p1_0[] = {
  145611. 1, 0, 2,
  145612. };
  145613. static encode_aux_threshmatch _vq_auxt__8u1__p1_0 = {
  145614. _vq_quantthresh__8u1__p1_0,
  145615. _vq_quantmap__8u1__p1_0,
  145616. 3,
  145617. 3
  145618. };
  145619. static static_codebook _8u1__p1_0 = {
  145620. 4, 81,
  145621. _vq_lengthlist__8u1__p1_0,
  145622. 1, -535822336, 1611661312, 2, 0,
  145623. _vq_quantlist__8u1__p1_0,
  145624. NULL,
  145625. &_vq_auxt__8u1__p1_0,
  145626. NULL,
  145627. 0
  145628. };
  145629. static long _vq_quantlist__8u1__p2_0[] = {
  145630. 1,
  145631. 0,
  145632. 2,
  145633. };
  145634. static long _vq_lengthlist__8u1__p2_0[] = {
  145635. 3, 4, 5, 5, 6, 6, 5, 6, 6, 5, 7, 6, 6, 7, 8, 6,
  145636. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 7, 8,
  145637. 8, 6, 7, 7, 6, 8, 7, 7, 7, 9, 8, 9, 9, 6, 7, 8,
  145638. 7, 9, 7, 8, 9, 9, 5, 6, 6, 6, 7, 7, 7, 8, 8, 6,
  145639. 8, 7, 8, 9, 9, 7, 7, 9, 6, 7, 8, 8, 9, 9, 7, 9,
  145640. 7,
  145641. };
  145642. static float _vq_quantthresh__8u1__p2_0[] = {
  145643. -0.5, 0.5,
  145644. };
  145645. static long _vq_quantmap__8u1__p2_0[] = {
  145646. 1, 0, 2,
  145647. };
  145648. static encode_aux_threshmatch _vq_auxt__8u1__p2_0 = {
  145649. _vq_quantthresh__8u1__p2_0,
  145650. _vq_quantmap__8u1__p2_0,
  145651. 3,
  145652. 3
  145653. };
  145654. static static_codebook _8u1__p2_0 = {
  145655. 4, 81,
  145656. _vq_lengthlist__8u1__p2_0,
  145657. 1, -535822336, 1611661312, 2, 0,
  145658. _vq_quantlist__8u1__p2_0,
  145659. NULL,
  145660. &_vq_auxt__8u1__p2_0,
  145661. NULL,
  145662. 0
  145663. };
  145664. static long _vq_quantlist__8u1__p3_0[] = {
  145665. 2,
  145666. 1,
  145667. 3,
  145668. 0,
  145669. 4,
  145670. };
  145671. static long _vq_lengthlist__8u1__p3_0[] = {
  145672. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  145673. 10, 9,11,11, 9, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  145674. 10,11,11, 8, 9,10,11,11,10,11,11,12,12,10,11,11,
  145675. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  145676. 11,10,11,11,12,12,10,11,11,12,12, 9,11,11,14,13,
  145677. 10,12,11,14,14,10,12,11,14,13,12,13,13,15,14,12,
  145678. 13,13,15,14, 8,11,11,13,14,10,11,12,13,15,10,11,
  145679. 12,14,14,12,13,13,14,15,12,13,13,14,15, 5, 8, 8,
  145680. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  145681. 13,11,12,12,13,14, 8,10,10,12,12, 9,11,12,13,14,
  145682. 10,12,12,13,13,12,12,13,14,14,11,13,13,15,15, 7,
  145683. 10,10,12,12, 9,12,11,14,12,10,11,12,13,14,12,13,
  145684. 12,14,14,12,13,13,15,16,10,12,12,15,14,11,12,13,
  145685. 15,15,11,13,13,15,16,14,14,15,15,16,13,14,15,17,
  145686. 15, 9,12,12,14,15,11,13,12,15,15,11,13,13,15,15,
  145687. 13,14,13,15,14,13,14,14,17, 0, 5, 8, 8,11,11, 8,
  145688. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  145689. 12,14,14, 7,10,10,12,12,10,12,12,13,13, 9,11,12,
  145690. 12,13,11,12,13,15,15,11,12,13,14,15, 8,10,10,12,
  145691. 12,10,12,11,13,13,10,12,11,13,13,11,13,13,15,14,
  145692. 12,13,12,15,13, 9,12,12,14,14,11,13,13,16,15,11,
  145693. 12,13,16,15,13,14,15,16,16,13,13,15,15,16,10,12,
  145694. 12,15,14,11,13,13,14,16,11,13,13,15,16,13,15,15,
  145695. 16,17,13,15,14,16,15, 8,11,11,14,15,10,12,12,15,
  145696. 15,10,12,12,15,16,14,15,15,16,17,13,14,14,16,16,
  145697. 9,12,12,15,15,11,13,14,15,17,11,13,13,15,16,14,
  145698. 15,16,19,17,13,15,15, 0,17, 9,12,12,15,15,11,14,
  145699. 13,16,15,11,13,13,15,16,15,15,15,18,17,13,15,15,
  145700. 17,17,11,15,14,18,16,12,14,15,17,17,12,15,15,18,
  145701. 18,15,15,16,15,19,14,16,16, 0, 0,11,14,14,16,17,
  145702. 12,15,14,18,17,12,15,15,18,18,15,17,15,18,16,14,
  145703. 16,16,18,18, 7,11,11,14,14,10,12,12,15,15,10,12,
  145704. 13,15,15,13,14,15,16,16,14,15,15,18,18, 9,12,12,
  145705. 15,15,11,13,13,16,15,11,12,13,16,16,14,15,15,17,
  145706. 16,15,16,16,17,17, 9,12,12,15,15,11,13,13,15,17,
  145707. 11,14,13,16,15,13,15,15,17,17,15,15,15,18,17,11,
  145708. 14,14,17,15,12,14,15,17,18,13,13,15,17,17,14,16,
  145709. 16,19,18,16,15,17,17, 0,11,14,14,17,17,12,15,15,
  145710. 18, 0,12,15,14,18,16,14,17,17,19, 0,16,18,15, 0,
  145711. 16,
  145712. };
  145713. static float _vq_quantthresh__8u1__p3_0[] = {
  145714. -1.5, -0.5, 0.5, 1.5,
  145715. };
  145716. static long _vq_quantmap__8u1__p3_0[] = {
  145717. 3, 1, 0, 2, 4,
  145718. };
  145719. static encode_aux_threshmatch _vq_auxt__8u1__p3_0 = {
  145720. _vq_quantthresh__8u1__p3_0,
  145721. _vq_quantmap__8u1__p3_0,
  145722. 5,
  145723. 5
  145724. };
  145725. static static_codebook _8u1__p3_0 = {
  145726. 4, 625,
  145727. _vq_lengthlist__8u1__p3_0,
  145728. 1, -533725184, 1611661312, 3, 0,
  145729. _vq_quantlist__8u1__p3_0,
  145730. NULL,
  145731. &_vq_auxt__8u1__p3_0,
  145732. NULL,
  145733. 0
  145734. };
  145735. static long _vq_quantlist__8u1__p4_0[] = {
  145736. 2,
  145737. 1,
  145738. 3,
  145739. 0,
  145740. 4,
  145741. };
  145742. static long _vq_lengthlist__8u1__p4_0[] = {
  145743. 4, 5, 5, 9, 9, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 9,
  145744. 9, 9,11,11, 9, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 7,
  145745. 8, 9,10, 7, 7, 8, 9,10, 9, 9,10,10,11, 9, 9,10,
  145746. 10,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 7,10,
  145747. 9, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  145748. 9,10,10,12,11, 9,10,10,12,12,11,11,12,12,13,11,
  145749. 11,12,12,13, 9, 9,10,12,11, 9,10,10,12,12,10,10,
  145750. 10,12,12,11,12,11,13,12,11,12,11,13,12, 6, 7, 7,
  145751. 9, 9, 7, 8, 8,10,10, 7, 8, 7,10, 9,10,10,10,12,
  145752. 12,10,10,10,12,11, 7, 8, 7,10,10, 7, 7, 9,10,11,
  145753. 8, 9, 9,11,10,10,10,11,10,12,10,10,11,12,12, 7,
  145754. 8, 8,10,10, 7, 9, 8,11,10, 8, 8, 9,11,11,10,11,
  145755. 10,12,11,10,11,11,12,12, 9,10,10,12,12, 9,10,10,
  145756. 12,12,10,11,11,13,12,11,10,12,10,14,12,12,12,13,
  145757. 14, 9,10,10,12,12, 9,11,10,12,12,10,11,11,12,12,
  145758. 11,12,11,14,12,12,12,12,14,14, 5, 7, 7, 9, 9, 7,
  145759. 7, 7, 9,10, 7, 8, 8,10,10,10,10,10,11,11,10,10,
  145760. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  145761. 10,11,10,10,10,11,12,10,10,11,11,13, 6, 7, 8,10,
  145762. 10, 8, 9, 9,10,10, 7, 9, 7,11,10,10,11,10,12,12,
  145763. 10,11,10,12,10, 9,10,10,12,12,10,11,11,13,12, 9,
  145764. 10,10,12,12,12,12,12,14,13,11,11,12,11,14, 9,10,
  145765. 10,11,12,10,11,11,12,13, 9,10,10,12,12,12,12,12,
  145766. 14,13,11,12,10,14,11, 9, 9,10,11,12, 9,10,10,12,
  145767. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,13,12,
  145768. 9,10, 9,12,12, 9,10,11,12,13,10,11,10,13,11,12,
  145769. 12,13,13,14,12,12,12,13,13, 9,10,10,12,12,10,11,
  145770. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,12,
  145771. 13,14,11,12,11,14,13,10,10,11,13,13,12,12,12,14,
  145772. 13,12,10,14,10,15,13,14,14,14,14,11,11,12,13,14,
  145773. 10,12,11,13,13,12,12,12,13,15,12,13,11,15,12,13,
  145774. 13,14,14,14, 9,10, 9,12,12, 9,10,10,12,12,10,10,
  145775. 10,12,12,11,11,12,12,13,12,12,12,14,14, 9,10,10,
  145776. 12,12,10,11,10,13,12,10,10,11,12,13,12,12,12,14,
  145777. 13,12,12,13,13,14, 9,10,10,12,13,10,10,11,11,12,
  145778. 9,11,10,13,12,12,12,12,13,14,12,13,12,14,13,11,
  145779. 12,11,13,13,12,13,12,14,13,10,11,12,13,13,13,13,
  145780. 13,14,15,12,11,14,12,14,11,11,12,12,13,12,12,12,
  145781. 13,14,10,12,10,14,13,13,13,13,14,15,12,14,11,15,
  145782. 10,
  145783. };
  145784. static float _vq_quantthresh__8u1__p4_0[] = {
  145785. -1.5, -0.5, 0.5, 1.5,
  145786. };
  145787. static long _vq_quantmap__8u1__p4_0[] = {
  145788. 3, 1, 0, 2, 4,
  145789. };
  145790. static encode_aux_threshmatch _vq_auxt__8u1__p4_0 = {
  145791. _vq_quantthresh__8u1__p4_0,
  145792. _vq_quantmap__8u1__p4_0,
  145793. 5,
  145794. 5
  145795. };
  145796. static static_codebook _8u1__p4_0 = {
  145797. 4, 625,
  145798. _vq_lengthlist__8u1__p4_0,
  145799. 1, -533725184, 1611661312, 3, 0,
  145800. _vq_quantlist__8u1__p4_0,
  145801. NULL,
  145802. &_vq_auxt__8u1__p4_0,
  145803. NULL,
  145804. 0
  145805. };
  145806. static long _vq_quantlist__8u1__p5_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__p5_0[] = {
  145818. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  145819. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  145820. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  145821. 9, 9,10,10,12,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  145822. 10,10,11,11,11,11,13,12, 9,10,10,11,11,12,12,12,
  145823. 13,
  145824. };
  145825. static float _vq_quantthresh__8u1__p5_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__p5_0[] = {
  145829. 7, 5, 3, 1, 0, 2, 4, 6,
  145830. 8,
  145831. };
  145832. static encode_aux_threshmatch _vq_auxt__8u1__p5_0 = {
  145833. _vq_quantthresh__8u1__p5_0,
  145834. _vq_quantmap__8u1__p5_0,
  145835. 9,
  145836. 9
  145837. };
  145838. static static_codebook _8u1__p5_0 = {
  145839. 2, 81,
  145840. _vq_lengthlist__8u1__p5_0,
  145841. 1, -531628032, 1611661312, 4, 0,
  145842. _vq_quantlist__8u1__p5_0,
  145843. NULL,
  145844. &_vq_auxt__8u1__p5_0,
  145845. NULL,
  145846. 0
  145847. };
  145848. static long _vq_quantlist__8u1__p6_0[] = {
  145849. 4,
  145850. 3,
  145851. 5,
  145852. 2,
  145853. 6,
  145854. 1,
  145855. 7,
  145856. 0,
  145857. 8,
  145858. };
  145859. static long _vq_lengthlist__8u1__p6_0[] = {
  145860. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 5, 6, 6, 7, 7,
  145861. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  145862. 8, 8, 9, 9, 6, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  145863. 8, 8, 8, 9,10,10, 7, 7, 7, 8, 8, 9, 8,10,10, 9,
  145864. 9, 9, 9, 9,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  145865. 10,
  145866. };
  145867. static float _vq_quantthresh__8u1__p6_0[] = {
  145868. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145869. };
  145870. static long _vq_quantmap__8u1__p6_0[] = {
  145871. 7, 5, 3, 1, 0, 2, 4, 6,
  145872. 8,
  145873. };
  145874. static encode_aux_threshmatch _vq_auxt__8u1__p6_0 = {
  145875. _vq_quantthresh__8u1__p6_0,
  145876. _vq_quantmap__8u1__p6_0,
  145877. 9,
  145878. 9
  145879. };
  145880. static static_codebook _8u1__p6_0 = {
  145881. 2, 81,
  145882. _vq_lengthlist__8u1__p6_0,
  145883. 1, -531628032, 1611661312, 4, 0,
  145884. _vq_quantlist__8u1__p6_0,
  145885. NULL,
  145886. &_vq_auxt__8u1__p6_0,
  145887. NULL,
  145888. 0
  145889. };
  145890. static long _vq_quantlist__8u1__p7_0[] = {
  145891. 1,
  145892. 0,
  145893. 2,
  145894. };
  145895. static long _vq_lengthlist__8u1__p7_0[] = {
  145896. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,10,10, 8,
  145897. 10,10, 5, 9, 9, 7,10,10, 8,10,10, 4,10,10, 9,12,
  145898. 12, 9,11,11, 7,12,11,10,11,13,10,13,13, 7,12,12,
  145899. 10,13,12,10,13,13, 4,10,10, 9,12,12, 9,12,12, 7,
  145900. 12,12,10,13,13,10,12,13, 7,11,12,10,13,13,10,13,
  145901. 11,
  145902. };
  145903. static float _vq_quantthresh__8u1__p7_0[] = {
  145904. -5.5, 5.5,
  145905. };
  145906. static long _vq_quantmap__8u1__p7_0[] = {
  145907. 1, 0, 2,
  145908. };
  145909. static encode_aux_threshmatch _vq_auxt__8u1__p7_0 = {
  145910. _vq_quantthresh__8u1__p7_0,
  145911. _vq_quantmap__8u1__p7_0,
  145912. 3,
  145913. 3
  145914. };
  145915. static static_codebook _8u1__p7_0 = {
  145916. 4, 81,
  145917. _vq_lengthlist__8u1__p7_0,
  145918. 1, -529137664, 1618345984, 2, 0,
  145919. _vq_quantlist__8u1__p7_0,
  145920. NULL,
  145921. &_vq_auxt__8u1__p7_0,
  145922. NULL,
  145923. 0
  145924. };
  145925. static long _vq_quantlist__8u1__p7_1[] = {
  145926. 5,
  145927. 4,
  145928. 6,
  145929. 3,
  145930. 7,
  145931. 2,
  145932. 8,
  145933. 1,
  145934. 9,
  145935. 0,
  145936. 10,
  145937. };
  145938. static long _vq_lengthlist__8u1__p7_1[] = {
  145939. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  145940. 8, 8, 9, 9, 9, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 9,
  145941. 9, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  145942. 8, 8, 8, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  145943. 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  145944. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  145945. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  145946. 9, 9, 9, 9, 9,10,10,10,10,
  145947. };
  145948. static float _vq_quantthresh__8u1__p7_1[] = {
  145949. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145950. 3.5, 4.5,
  145951. };
  145952. static long _vq_quantmap__8u1__p7_1[] = {
  145953. 9, 7, 5, 3, 1, 0, 2, 4,
  145954. 6, 8, 10,
  145955. };
  145956. static encode_aux_threshmatch _vq_auxt__8u1__p7_1 = {
  145957. _vq_quantthresh__8u1__p7_1,
  145958. _vq_quantmap__8u1__p7_1,
  145959. 11,
  145960. 11
  145961. };
  145962. static static_codebook _8u1__p7_1 = {
  145963. 2, 121,
  145964. _vq_lengthlist__8u1__p7_1,
  145965. 1, -531365888, 1611661312, 4, 0,
  145966. _vq_quantlist__8u1__p7_1,
  145967. NULL,
  145968. &_vq_auxt__8u1__p7_1,
  145969. NULL,
  145970. 0
  145971. };
  145972. static long _vq_quantlist__8u1__p8_0[] = {
  145973. 5,
  145974. 4,
  145975. 6,
  145976. 3,
  145977. 7,
  145978. 2,
  145979. 8,
  145980. 1,
  145981. 9,
  145982. 0,
  145983. 10,
  145984. };
  145985. static long _vq_lengthlist__8u1__p8_0[] = {
  145986. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  145987. 9, 9,11,11,13,12, 4, 6, 6, 7, 7, 9, 9,11,11,12,
  145988. 12, 6, 7, 7, 9, 9,11,11,12,12,13,13, 6, 7, 7, 9,
  145989. 9,11,11,12,12,13,13, 8, 9, 9,11,11,12,12,13,13,
  145990. 14,14, 8, 9, 9,11,11,12,12,13,13,14,14, 9,11,11,
  145991. 12,12,13,13,14,14,15,15, 9,11,11,12,12,13,13,14,
  145992. 14,15,14,11,12,12,13,13,14,14,15,15,16,16,11,12,
  145993. 12,13,13,14,14,15,15,15,15,
  145994. };
  145995. static float _vq_quantthresh__8u1__p8_0[] = {
  145996. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  145997. 38.5, 49.5,
  145998. };
  145999. static long _vq_quantmap__8u1__p8_0[] = {
  146000. 9, 7, 5, 3, 1, 0, 2, 4,
  146001. 6, 8, 10,
  146002. };
  146003. static encode_aux_threshmatch _vq_auxt__8u1__p8_0 = {
  146004. _vq_quantthresh__8u1__p8_0,
  146005. _vq_quantmap__8u1__p8_0,
  146006. 11,
  146007. 11
  146008. };
  146009. static static_codebook _8u1__p8_0 = {
  146010. 2, 121,
  146011. _vq_lengthlist__8u1__p8_0,
  146012. 1, -524582912, 1618345984, 4, 0,
  146013. _vq_quantlist__8u1__p8_0,
  146014. NULL,
  146015. &_vq_auxt__8u1__p8_0,
  146016. NULL,
  146017. 0
  146018. };
  146019. static long _vq_quantlist__8u1__p8_1[] = {
  146020. 5,
  146021. 4,
  146022. 6,
  146023. 3,
  146024. 7,
  146025. 2,
  146026. 8,
  146027. 1,
  146028. 9,
  146029. 0,
  146030. 10,
  146031. };
  146032. static long _vq_lengthlist__8u1__p8_1[] = {
  146033. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 6, 6, 7, 7,
  146034. 7, 7, 8, 8, 8, 8, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  146035. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  146036. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  146037. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  146038. 8, 8, 8, 8, 9, 8, 9, 9, 7, 8, 8, 8, 8, 8, 8, 9,
  146039. 8, 9, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8,
  146040. 8, 8, 8, 8, 8, 9, 9, 9, 9,
  146041. };
  146042. static float _vq_quantthresh__8u1__p8_1[] = {
  146043. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  146044. 3.5, 4.5,
  146045. };
  146046. static long _vq_quantmap__8u1__p8_1[] = {
  146047. 9, 7, 5, 3, 1, 0, 2, 4,
  146048. 6, 8, 10,
  146049. };
  146050. static encode_aux_threshmatch _vq_auxt__8u1__p8_1 = {
  146051. _vq_quantthresh__8u1__p8_1,
  146052. _vq_quantmap__8u1__p8_1,
  146053. 11,
  146054. 11
  146055. };
  146056. static static_codebook _8u1__p8_1 = {
  146057. 2, 121,
  146058. _vq_lengthlist__8u1__p8_1,
  146059. 1, -531365888, 1611661312, 4, 0,
  146060. _vq_quantlist__8u1__p8_1,
  146061. NULL,
  146062. &_vq_auxt__8u1__p8_1,
  146063. NULL,
  146064. 0
  146065. };
  146066. static long _vq_quantlist__8u1__p9_0[] = {
  146067. 7,
  146068. 6,
  146069. 8,
  146070. 5,
  146071. 9,
  146072. 4,
  146073. 10,
  146074. 3,
  146075. 11,
  146076. 2,
  146077. 12,
  146078. 1,
  146079. 13,
  146080. 0,
  146081. 14,
  146082. };
  146083. static long _vq_lengthlist__8u1__p9_0[] = {
  146084. 1, 4, 4,11,11,11,11,11,11,11,11,11,11,11,11, 3,
  146085. 11, 8,11,11,11,11,11,11,11,11,11,11,11,11, 3, 9,
  146086. 9,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146087. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146088. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146089. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146090. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146091. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146092. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146093. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146094. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146095. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146096. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  146097. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146098. 10,
  146099. };
  146100. static float _vq_quantthresh__8u1__p9_0[] = {
  146101. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  146102. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  146103. };
  146104. static long _vq_quantmap__8u1__p9_0[] = {
  146105. 13, 11, 9, 7, 5, 3, 1, 0,
  146106. 2, 4, 6, 8, 10, 12, 14,
  146107. };
  146108. static encode_aux_threshmatch _vq_auxt__8u1__p9_0 = {
  146109. _vq_quantthresh__8u1__p9_0,
  146110. _vq_quantmap__8u1__p9_0,
  146111. 15,
  146112. 15
  146113. };
  146114. static static_codebook _8u1__p9_0 = {
  146115. 2, 225,
  146116. _vq_lengthlist__8u1__p9_0,
  146117. 1, -514071552, 1627381760, 4, 0,
  146118. _vq_quantlist__8u1__p9_0,
  146119. NULL,
  146120. &_vq_auxt__8u1__p9_0,
  146121. NULL,
  146122. 0
  146123. };
  146124. static long _vq_quantlist__8u1__p9_1[] = {
  146125. 7,
  146126. 6,
  146127. 8,
  146128. 5,
  146129. 9,
  146130. 4,
  146131. 10,
  146132. 3,
  146133. 11,
  146134. 2,
  146135. 12,
  146136. 1,
  146137. 13,
  146138. 0,
  146139. 14,
  146140. };
  146141. static long _vq_lengthlist__8u1__p9_1[] = {
  146142. 1, 4, 4, 7, 7, 9, 9, 7, 7, 8, 8,10,10,11,11, 4,
  146143. 7, 7, 9, 9,10,10, 8, 8,10,10,10,11,10,11, 4, 7,
  146144. 7, 9, 9,10,10, 8, 8,10, 9,11,11,11,11, 7, 9, 9,
  146145. 12,12,11,12,10,10,11,10,12,11,11,11, 7, 9, 9,11,
  146146. 11,13,12, 9, 9,11,10,11,11,12,11, 9,10,10,12,12,
  146147. 14,14,10,10,11,12,12,11,11,11, 9,10,11,11,13,14,
  146148. 13,10,11,11,11,12,11,12,12, 7, 8, 8,10, 9,11,10,
  146149. 11,12,12,11,12,14,12,13, 7, 8, 8, 9,10,10,11,12,
  146150. 12,12,11,12,12,12,13, 9, 9, 9,11,11,13,12,12,12,
  146151. 12,11,12,12,13,12, 8,10,10,11,10,11,12,12,12,12,
  146152. 12,12,14,12,12, 9,11,11,11,12,12,12,12,13,13,12,
  146153. 12,13,13,12,10,11,11,12,11,12,12,12,11,12,13,12,
  146154. 12,12,13,11,11,12,12,12,13,12,12,11,12,13,13,12,
  146155. 12,13,12,11,12,12,13,13,12,13,12,13,13,13,13,14,
  146156. 13,
  146157. };
  146158. static float _vq_quantthresh__8u1__p9_1[] = {
  146159. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  146160. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  146161. };
  146162. static long _vq_quantmap__8u1__p9_1[] = {
  146163. 13, 11, 9, 7, 5, 3, 1, 0,
  146164. 2, 4, 6, 8, 10, 12, 14,
  146165. };
  146166. static encode_aux_threshmatch _vq_auxt__8u1__p9_1 = {
  146167. _vq_quantthresh__8u1__p9_1,
  146168. _vq_quantmap__8u1__p9_1,
  146169. 15,
  146170. 15
  146171. };
  146172. static static_codebook _8u1__p9_1 = {
  146173. 2, 225,
  146174. _vq_lengthlist__8u1__p9_1,
  146175. 1, -522338304, 1620115456, 4, 0,
  146176. _vq_quantlist__8u1__p9_1,
  146177. NULL,
  146178. &_vq_auxt__8u1__p9_1,
  146179. NULL,
  146180. 0
  146181. };
  146182. static long _vq_quantlist__8u1__p9_2[] = {
  146183. 8,
  146184. 7,
  146185. 9,
  146186. 6,
  146187. 10,
  146188. 5,
  146189. 11,
  146190. 4,
  146191. 12,
  146192. 3,
  146193. 13,
  146194. 2,
  146195. 14,
  146196. 1,
  146197. 15,
  146198. 0,
  146199. 16,
  146200. };
  146201. static long _vq_lengthlist__8u1__p9_2[] = {
  146202. 2, 5, 4, 6, 6, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  146203. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  146204. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  146205. 9, 9, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  146206. 9,10,10, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  146207. 9, 9, 9,10,10, 8, 8, 8, 9, 9, 9, 9,10,10,10, 9,
  146208. 10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  146209. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,
  146210. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  146211. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  146212. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  146213. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  146214. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  146215. 9,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  146216. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10,
  146217. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  146218. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146219. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146220. 10,
  146221. };
  146222. static float _vq_quantthresh__8u1__p9_2[] = {
  146223. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  146224. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  146225. };
  146226. static long _vq_quantmap__8u1__p9_2[] = {
  146227. 15, 13, 11, 9, 7, 5, 3, 1,
  146228. 0, 2, 4, 6, 8, 10, 12, 14,
  146229. 16,
  146230. };
  146231. static encode_aux_threshmatch _vq_auxt__8u1__p9_2 = {
  146232. _vq_quantthresh__8u1__p9_2,
  146233. _vq_quantmap__8u1__p9_2,
  146234. 17,
  146235. 17
  146236. };
  146237. static static_codebook _8u1__p9_2 = {
  146238. 2, 289,
  146239. _vq_lengthlist__8u1__p9_2,
  146240. 1, -529530880, 1611661312, 5, 0,
  146241. _vq_quantlist__8u1__p9_2,
  146242. NULL,
  146243. &_vq_auxt__8u1__p9_2,
  146244. NULL,
  146245. 0
  146246. };
  146247. static long _huff_lengthlist__8u1__single[] = {
  146248. 4, 7,13, 9,15, 9,16, 8,10,13, 7, 5, 8, 6, 9, 7,
  146249. 10, 7,10,11,11, 6, 7, 8, 8, 9, 9, 9,12,16, 8, 5,
  146250. 8, 6, 8, 6, 9, 7,10,12,11, 7, 7, 7, 6, 7, 7, 7,
  146251. 11,15, 7, 5, 8, 6, 7, 5, 7, 6, 9,13,13, 9, 9, 8,
  146252. 6, 6, 5, 5, 9,14, 8, 6, 8, 6, 6, 4, 5, 3, 5,13,
  146253. 9, 9,11, 8,10, 7, 8, 4, 5,12,11,16,17,15,17,12,
  146254. 13, 8, 8,15,
  146255. };
  146256. static static_codebook _huff_book__8u1__single = {
  146257. 2, 100,
  146258. _huff_lengthlist__8u1__single,
  146259. 0, 0, 0, 0, 0,
  146260. NULL,
  146261. NULL,
  146262. NULL,
  146263. NULL,
  146264. 0
  146265. };
  146266. static long _huff_lengthlist__44u0__long[] = {
  146267. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  146268. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  146269. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  146270. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  146271. };
  146272. static static_codebook _huff_book__44u0__long = {
  146273. 2, 64,
  146274. _huff_lengthlist__44u0__long,
  146275. 0, 0, 0, 0, 0,
  146276. NULL,
  146277. NULL,
  146278. NULL,
  146279. NULL,
  146280. 0
  146281. };
  146282. static long _vq_quantlist__44u0__p1_0[] = {
  146283. 1,
  146284. 0,
  146285. 2,
  146286. };
  146287. static long _vq_lengthlist__44u0__p1_0[] = {
  146288. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  146289. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  146290. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  146291. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  146292. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  146293. 13,
  146294. };
  146295. static float _vq_quantthresh__44u0__p1_0[] = {
  146296. -0.5, 0.5,
  146297. };
  146298. static long _vq_quantmap__44u0__p1_0[] = {
  146299. 1, 0, 2,
  146300. };
  146301. static encode_aux_threshmatch _vq_auxt__44u0__p1_0 = {
  146302. _vq_quantthresh__44u0__p1_0,
  146303. _vq_quantmap__44u0__p1_0,
  146304. 3,
  146305. 3
  146306. };
  146307. static static_codebook _44u0__p1_0 = {
  146308. 4, 81,
  146309. _vq_lengthlist__44u0__p1_0,
  146310. 1, -535822336, 1611661312, 2, 0,
  146311. _vq_quantlist__44u0__p1_0,
  146312. NULL,
  146313. &_vq_auxt__44u0__p1_0,
  146314. NULL,
  146315. 0
  146316. };
  146317. static long _vq_quantlist__44u0__p2_0[] = {
  146318. 1,
  146319. 0,
  146320. 2,
  146321. };
  146322. static long _vq_lengthlist__44u0__p2_0[] = {
  146323. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  146324. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  146325. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  146326. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  146327. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  146328. 9,
  146329. };
  146330. static float _vq_quantthresh__44u0__p2_0[] = {
  146331. -0.5, 0.5,
  146332. };
  146333. static long _vq_quantmap__44u0__p2_0[] = {
  146334. 1, 0, 2,
  146335. };
  146336. static encode_aux_threshmatch _vq_auxt__44u0__p2_0 = {
  146337. _vq_quantthresh__44u0__p2_0,
  146338. _vq_quantmap__44u0__p2_0,
  146339. 3,
  146340. 3
  146341. };
  146342. static static_codebook _44u0__p2_0 = {
  146343. 4, 81,
  146344. _vq_lengthlist__44u0__p2_0,
  146345. 1, -535822336, 1611661312, 2, 0,
  146346. _vq_quantlist__44u0__p2_0,
  146347. NULL,
  146348. &_vq_auxt__44u0__p2_0,
  146349. NULL,
  146350. 0
  146351. };
  146352. static long _vq_quantlist__44u0__p3_0[] = {
  146353. 2,
  146354. 1,
  146355. 3,
  146356. 0,
  146357. 4,
  146358. };
  146359. static long _vq_lengthlist__44u0__p3_0[] = {
  146360. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  146361. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  146362. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  146363. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  146364. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  146365. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  146366. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  146367. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  146368. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  146369. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  146370. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  146371. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  146372. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  146373. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  146374. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  146375. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  146376. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  146377. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  146378. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  146379. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  146380. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  146381. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  146382. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  146383. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  146384. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  146385. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  146386. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  146387. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  146388. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  146389. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  146390. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  146391. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  146392. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  146393. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  146394. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  146395. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  146396. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  146397. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  146398. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  146399. 19,
  146400. };
  146401. static float _vq_quantthresh__44u0__p3_0[] = {
  146402. -1.5, -0.5, 0.5, 1.5,
  146403. };
  146404. static long _vq_quantmap__44u0__p3_0[] = {
  146405. 3, 1, 0, 2, 4,
  146406. };
  146407. static encode_aux_threshmatch _vq_auxt__44u0__p3_0 = {
  146408. _vq_quantthresh__44u0__p3_0,
  146409. _vq_quantmap__44u0__p3_0,
  146410. 5,
  146411. 5
  146412. };
  146413. static static_codebook _44u0__p3_0 = {
  146414. 4, 625,
  146415. _vq_lengthlist__44u0__p3_0,
  146416. 1, -533725184, 1611661312, 3, 0,
  146417. _vq_quantlist__44u0__p3_0,
  146418. NULL,
  146419. &_vq_auxt__44u0__p3_0,
  146420. NULL,
  146421. 0
  146422. };
  146423. static long _vq_quantlist__44u0__p4_0[] = {
  146424. 2,
  146425. 1,
  146426. 3,
  146427. 0,
  146428. 4,
  146429. };
  146430. static long _vq_lengthlist__44u0__p4_0[] = {
  146431. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  146432. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  146433. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  146434. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  146435. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  146436. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  146437. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  146438. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  146439. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  146440. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  146441. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  146442. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  146443. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  146444. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  146445. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  146446. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  146447. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  146448. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  146449. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  146450. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  146451. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  146452. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  146453. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  146454. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  146455. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  146456. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  146457. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  146458. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  146459. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  146460. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  146461. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  146462. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  146463. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  146464. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  146465. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  146466. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  146467. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  146468. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  146469. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  146470. 12,
  146471. };
  146472. static float _vq_quantthresh__44u0__p4_0[] = {
  146473. -1.5, -0.5, 0.5, 1.5,
  146474. };
  146475. static long _vq_quantmap__44u0__p4_0[] = {
  146476. 3, 1, 0, 2, 4,
  146477. };
  146478. static encode_aux_threshmatch _vq_auxt__44u0__p4_0 = {
  146479. _vq_quantthresh__44u0__p4_0,
  146480. _vq_quantmap__44u0__p4_0,
  146481. 5,
  146482. 5
  146483. };
  146484. static static_codebook _44u0__p4_0 = {
  146485. 4, 625,
  146486. _vq_lengthlist__44u0__p4_0,
  146487. 1, -533725184, 1611661312, 3, 0,
  146488. _vq_quantlist__44u0__p4_0,
  146489. NULL,
  146490. &_vq_auxt__44u0__p4_0,
  146491. NULL,
  146492. 0
  146493. };
  146494. static long _vq_quantlist__44u0__p5_0[] = {
  146495. 4,
  146496. 3,
  146497. 5,
  146498. 2,
  146499. 6,
  146500. 1,
  146501. 7,
  146502. 0,
  146503. 8,
  146504. };
  146505. static long _vq_lengthlist__44u0__p5_0[] = {
  146506. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  146507. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  146508. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  146509. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  146510. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  146511. 12,
  146512. };
  146513. static float _vq_quantthresh__44u0__p5_0[] = {
  146514. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146515. };
  146516. static long _vq_quantmap__44u0__p5_0[] = {
  146517. 7, 5, 3, 1, 0, 2, 4, 6,
  146518. 8,
  146519. };
  146520. static encode_aux_threshmatch _vq_auxt__44u0__p5_0 = {
  146521. _vq_quantthresh__44u0__p5_0,
  146522. _vq_quantmap__44u0__p5_0,
  146523. 9,
  146524. 9
  146525. };
  146526. static static_codebook _44u0__p5_0 = {
  146527. 2, 81,
  146528. _vq_lengthlist__44u0__p5_0,
  146529. 1, -531628032, 1611661312, 4, 0,
  146530. _vq_quantlist__44u0__p5_0,
  146531. NULL,
  146532. &_vq_auxt__44u0__p5_0,
  146533. NULL,
  146534. 0
  146535. };
  146536. static long _vq_quantlist__44u0__p6_0[] = {
  146537. 6,
  146538. 5,
  146539. 7,
  146540. 4,
  146541. 8,
  146542. 3,
  146543. 9,
  146544. 2,
  146545. 10,
  146546. 1,
  146547. 11,
  146548. 0,
  146549. 12,
  146550. };
  146551. static long _vq_lengthlist__44u0__p6_0[] = {
  146552. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  146553. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  146554. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  146555. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  146556. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  146557. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  146558. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  146559. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  146560. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  146561. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  146562. 15,17,16,17,18,17,17,18, 0,
  146563. };
  146564. static float _vq_quantthresh__44u0__p6_0[] = {
  146565. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  146566. 12.5, 17.5, 22.5, 27.5,
  146567. };
  146568. static long _vq_quantmap__44u0__p6_0[] = {
  146569. 11, 9, 7, 5, 3, 1, 0, 2,
  146570. 4, 6, 8, 10, 12,
  146571. };
  146572. static encode_aux_threshmatch _vq_auxt__44u0__p6_0 = {
  146573. _vq_quantthresh__44u0__p6_0,
  146574. _vq_quantmap__44u0__p6_0,
  146575. 13,
  146576. 13
  146577. };
  146578. static static_codebook _44u0__p6_0 = {
  146579. 2, 169,
  146580. _vq_lengthlist__44u0__p6_0,
  146581. 1, -526516224, 1616117760, 4, 0,
  146582. _vq_quantlist__44u0__p6_0,
  146583. NULL,
  146584. &_vq_auxt__44u0__p6_0,
  146585. NULL,
  146586. 0
  146587. };
  146588. static long _vq_quantlist__44u0__p6_1[] = {
  146589. 2,
  146590. 1,
  146591. 3,
  146592. 0,
  146593. 4,
  146594. };
  146595. static long _vq_lengthlist__44u0__p6_1[] = {
  146596. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  146597. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  146598. };
  146599. static float _vq_quantthresh__44u0__p6_1[] = {
  146600. -1.5, -0.5, 0.5, 1.5,
  146601. };
  146602. static long _vq_quantmap__44u0__p6_1[] = {
  146603. 3, 1, 0, 2, 4,
  146604. };
  146605. static encode_aux_threshmatch _vq_auxt__44u0__p6_1 = {
  146606. _vq_quantthresh__44u0__p6_1,
  146607. _vq_quantmap__44u0__p6_1,
  146608. 5,
  146609. 5
  146610. };
  146611. static static_codebook _44u0__p6_1 = {
  146612. 2, 25,
  146613. _vq_lengthlist__44u0__p6_1,
  146614. 1, -533725184, 1611661312, 3, 0,
  146615. _vq_quantlist__44u0__p6_1,
  146616. NULL,
  146617. &_vq_auxt__44u0__p6_1,
  146618. NULL,
  146619. 0
  146620. };
  146621. static long _vq_quantlist__44u0__p7_0[] = {
  146622. 2,
  146623. 1,
  146624. 3,
  146625. 0,
  146626. 4,
  146627. };
  146628. static long _vq_lengthlist__44u0__p7_0[] = {
  146629. 1, 4, 4,11,11, 9,11,11,11,11,11,11,11,11,11,11,
  146630. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146631. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146632. 11,11, 9,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146633. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146634. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146635. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146636. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  146637. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146638. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146639. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146640. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146641. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146642. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146643. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146644. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146645. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146646. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146647. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146648. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146649. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146650. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146651. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146652. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146653. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146654. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146655. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146656. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146657. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146658. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146659. 11,11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,
  146660. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146661. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146662. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146663. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146664. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146665. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146666. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146667. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146668. 10,
  146669. };
  146670. static float _vq_quantthresh__44u0__p7_0[] = {
  146671. -253.5, -84.5, 84.5, 253.5,
  146672. };
  146673. static long _vq_quantmap__44u0__p7_0[] = {
  146674. 3, 1, 0, 2, 4,
  146675. };
  146676. static encode_aux_threshmatch _vq_auxt__44u0__p7_0 = {
  146677. _vq_quantthresh__44u0__p7_0,
  146678. _vq_quantmap__44u0__p7_0,
  146679. 5,
  146680. 5
  146681. };
  146682. static static_codebook _44u0__p7_0 = {
  146683. 4, 625,
  146684. _vq_lengthlist__44u0__p7_0,
  146685. 1, -518709248, 1626677248, 3, 0,
  146686. _vq_quantlist__44u0__p7_0,
  146687. NULL,
  146688. &_vq_auxt__44u0__p7_0,
  146689. NULL,
  146690. 0
  146691. };
  146692. static long _vq_quantlist__44u0__p7_1[] = {
  146693. 6,
  146694. 5,
  146695. 7,
  146696. 4,
  146697. 8,
  146698. 3,
  146699. 9,
  146700. 2,
  146701. 10,
  146702. 1,
  146703. 11,
  146704. 0,
  146705. 12,
  146706. };
  146707. static long _vq_lengthlist__44u0__p7_1[] = {
  146708. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  146709. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  146710. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  146711. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  146712. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  146713. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  146714. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  146715. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  146716. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  146717. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  146718. 15,15,15,15,15,15,15,15,15,
  146719. };
  146720. static float _vq_quantthresh__44u0__p7_1[] = {
  146721. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  146722. 32.5, 45.5, 58.5, 71.5,
  146723. };
  146724. static long _vq_quantmap__44u0__p7_1[] = {
  146725. 11, 9, 7, 5, 3, 1, 0, 2,
  146726. 4, 6, 8, 10, 12,
  146727. };
  146728. static encode_aux_threshmatch _vq_auxt__44u0__p7_1 = {
  146729. _vq_quantthresh__44u0__p7_1,
  146730. _vq_quantmap__44u0__p7_1,
  146731. 13,
  146732. 13
  146733. };
  146734. static static_codebook _44u0__p7_1 = {
  146735. 2, 169,
  146736. _vq_lengthlist__44u0__p7_1,
  146737. 1, -523010048, 1618608128, 4, 0,
  146738. _vq_quantlist__44u0__p7_1,
  146739. NULL,
  146740. &_vq_auxt__44u0__p7_1,
  146741. NULL,
  146742. 0
  146743. };
  146744. static long _vq_quantlist__44u0__p7_2[] = {
  146745. 6,
  146746. 5,
  146747. 7,
  146748. 4,
  146749. 8,
  146750. 3,
  146751. 9,
  146752. 2,
  146753. 10,
  146754. 1,
  146755. 11,
  146756. 0,
  146757. 12,
  146758. };
  146759. static long _vq_lengthlist__44u0__p7_2[] = {
  146760. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  146761. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  146762. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  146763. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  146764. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  146765. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  146766. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  146767. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146768. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146769. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  146770. 9, 9, 9,10, 9, 9,10,10, 9,
  146771. };
  146772. static float _vq_quantthresh__44u0__p7_2[] = {
  146773. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  146774. 2.5, 3.5, 4.5, 5.5,
  146775. };
  146776. static long _vq_quantmap__44u0__p7_2[] = {
  146777. 11, 9, 7, 5, 3, 1, 0, 2,
  146778. 4, 6, 8, 10, 12,
  146779. };
  146780. static encode_aux_threshmatch _vq_auxt__44u0__p7_2 = {
  146781. _vq_quantthresh__44u0__p7_2,
  146782. _vq_quantmap__44u0__p7_2,
  146783. 13,
  146784. 13
  146785. };
  146786. static static_codebook _44u0__p7_2 = {
  146787. 2, 169,
  146788. _vq_lengthlist__44u0__p7_2,
  146789. 1, -531103744, 1611661312, 4, 0,
  146790. _vq_quantlist__44u0__p7_2,
  146791. NULL,
  146792. &_vq_auxt__44u0__p7_2,
  146793. NULL,
  146794. 0
  146795. };
  146796. static long _huff_lengthlist__44u0__short[] = {
  146797. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  146798. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  146799. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  146800. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  146801. };
  146802. static static_codebook _huff_book__44u0__short = {
  146803. 2, 64,
  146804. _huff_lengthlist__44u0__short,
  146805. 0, 0, 0, 0, 0,
  146806. NULL,
  146807. NULL,
  146808. NULL,
  146809. NULL,
  146810. 0
  146811. };
  146812. static long _huff_lengthlist__44u1__long[] = {
  146813. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  146814. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  146815. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  146816. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  146817. };
  146818. static static_codebook _huff_book__44u1__long = {
  146819. 2, 64,
  146820. _huff_lengthlist__44u1__long,
  146821. 0, 0, 0, 0, 0,
  146822. NULL,
  146823. NULL,
  146824. NULL,
  146825. NULL,
  146826. 0
  146827. };
  146828. static long _vq_quantlist__44u1__p1_0[] = {
  146829. 1,
  146830. 0,
  146831. 2,
  146832. };
  146833. static long _vq_lengthlist__44u1__p1_0[] = {
  146834. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  146835. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  146836. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  146837. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  146838. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  146839. 13,
  146840. };
  146841. static float _vq_quantthresh__44u1__p1_0[] = {
  146842. -0.5, 0.5,
  146843. };
  146844. static long _vq_quantmap__44u1__p1_0[] = {
  146845. 1, 0, 2,
  146846. };
  146847. static encode_aux_threshmatch _vq_auxt__44u1__p1_0 = {
  146848. _vq_quantthresh__44u1__p1_0,
  146849. _vq_quantmap__44u1__p1_0,
  146850. 3,
  146851. 3
  146852. };
  146853. static static_codebook _44u1__p1_0 = {
  146854. 4, 81,
  146855. _vq_lengthlist__44u1__p1_0,
  146856. 1, -535822336, 1611661312, 2, 0,
  146857. _vq_quantlist__44u1__p1_0,
  146858. NULL,
  146859. &_vq_auxt__44u1__p1_0,
  146860. NULL,
  146861. 0
  146862. };
  146863. static long _vq_quantlist__44u1__p2_0[] = {
  146864. 1,
  146865. 0,
  146866. 2,
  146867. };
  146868. static long _vq_lengthlist__44u1__p2_0[] = {
  146869. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  146870. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  146871. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  146872. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  146873. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  146874. 9,
  146875. };
  146876. static float _vq_quantthresh__44u1__p2_0[] = {
  146877. -0.5, 0.5,
  146878. };
  146879. static long _vq_quantmap__44u1__p2_0[] = {
  146880. 1, 0, 2,
  146881. };
  146882. static encode_aux_threshmatch _vq_auxt__44u1__p2_0 = {
  146883. _vq_quantthresh__44u1__p2_0,
  146884. _vq_quantmap__44u1__p2_0,
  146885. 3,
  146886. 3
  146887. };
  146888. static static_codebook _44u1__p2_0 = {
  146889. 4, 81,
  146890. _vq_lengthlist__44u1__p2_0,
  146891. 1, -535822336, 1611661312, 2, 0,
  146892. _vq_quantlist__44u1__p2_0,
  146893. NULL,
  146894. &_vq_auxt__44u1__p2_0,
  146895. NULL,
  146896. 0
  146897. };
  146898. static long _vq_quantlist__44u1__p3_0[] = {
  146899. 2,
  146900. 1,
  146901. 3,
  146902. 0,
  146903. 4,
  146904. };
  146905. static long _vq_lengthlist__44u1__p3_0[] = {
  146906. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  146907. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  146908. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  146909. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  146910. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  146911. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  146912. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  146913. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  146914. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  146915. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  146916. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  146917. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  146918. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  146919. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  146920. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  146921. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  146922. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  146923. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  146924. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  146925. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  146926. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  146927. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  146928. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  146929. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  146930. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  146931. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  146932. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  146933. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  146934. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  146935. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  146936. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  146937. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  146938. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  146939. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  146940. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  146941. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  146942. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  146943. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  146944. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  146945. 19,
  146946. };
  146947. static float _vq_quantthresh__44u1__p3_0[] = {
  146948. -1.5, -0.5, 0.5, 1.5,
  146949. };
  146950. static long _vq_quantmap__44u1__p3_0[] = {
  146951. 3, 1, 0, 2, 4,
  146952. };
  146953. static encode_aux_threshmatch _vq_auxt__44u1__p3_0 = {
  146954. _vq_quantthresh__44u1__p3_0,
  146955. _vq_quantmap__44u1__p3_0,
  146956. 5,
  146957. 5
  146958. };
  146959. static static_codebook _44u1__p3_0 = {
  146960. 4, 625,
  146961. _vq_lengthlist__44u1__p3_0,
  146962. 1, -533725184, 1611661312, 3, 0,
  146963. _vq_quantlist__44u1__p3_0,
  146964. NULL,
  146965. &_vq_auxt__44u1__p3_0,
  146966. NULL,
  146967. 0
  146968. };
  146969. static long _vq_quantlist__44u1__p4_0[] = {
  146970. 2,
  146971. 1,
  146972. 3,
  146973. 0,
  146974. 4,
  146975. };
  146976. static long _vq_lengthlist__44u1__p4_0[] = {
  146977. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  146978. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  146979. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  146980. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  146981. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  146982. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  146983. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  146984. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  146985. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  146986. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  146987. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  146988. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  146989. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  146990. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  146991. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  146992. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  146993. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  146994. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  146995. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  146996. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  146997. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  146998. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  146999. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  147000. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  147001. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  147002. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  147003. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  147004. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  147005. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  147006. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  147007. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  147008. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  147009. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  147010. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  147011. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  147012. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  147013. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  147014. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  147015. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  147016. 12,
  147017. };
  147018. static float _vq_quantthresh__44u1__p4_0[] = {
  147019. -1.5, -0.5, 0.5, 1.5,
  147020. };
  147021. static long _vq_quantmap__44u1__p4_0[] = {
  147022. 3, 1, 0, 2, 4,
  147023. };
  147024. static encode_aux_threshmatch _vq_auxt__44u1__p4_0 = {
  147025. _vq_quantthresh__44u1__p4_0,
  147026. _vq_quantmap__44u1__p4_0,
  147027. 5,
  147028. 5
  147029. };
  147030. static static_codebook _44u1__p4_0 = {
  147031. 4, 625,
  147032. _vq_lengthlist__44u1__p4_0,
  147033. 1, -533725184, 1611661312, 3, 0,
  147034. _vq_quantlist__44u1__p4_0,
  147035. NULL,
  147036. &_vq_auxt__44u1__p4_0,
  147037. NULL,
  147038. 0
  147039. };
  147040. static long _vq_quantlist__44u1__p5_0[] = {
  147041. 4,
  147042. 3,
  147043. 5,
  147044. 2,
  147045. 6,
  147046. 1,
  147047. 7,
  147048. 0,
  147049. 8,
  147050. };
  147051. static long _vq_lengthlist__44u1__p5_0[] = {
  147052. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  147053. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  147054. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  147055. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  147056. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  147057. 12,
  147058. };
  147059. static float _vq_quantthresh__44u1__p5_0[] = {
  147060. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147061. };
  147062. static long _vq_quantmap__44u1__p5_0[] = {
  147063. 7, 5, 3, 1, 0, 2, 4, 6,
  147064. 8,
  147065. };
  147066. static encode_aux_threshmatch _vq_auxt__44u1__p5_0 = {
  147067. _vq_quantthresh__44u1__p5_0,
  147068. _vq_quantmap__44u1__p5_0,
  147069. 9,
  147070. 9
  147071. };
  147072. static static_codebook _44u1__p5_0 = {
  147073. 2, 81,
  147074. _vq_lengthlist__44u1__p5_0,
  147075. 1, -531628032, 1611661312, 4, 0,
  147076. _vq_quantlist__44u1__p5_0,
  147077. NULL,
  147078. &_vq_auxt__44u1__p5_0,
  147079. NULL,
  147080. 0
  147081. };
  147082. static long _vq_quantlist__44u1__p6_0[] = {
  147083. 6,
  147084. 5,
  147085. 7,
  147086. 4,
  147087. 8,
  147088. 3,
  147089. 9,
  147090. 2,
  147091. 10,
  147092. 1,
  147093. 11,
  147094. 0,
  147095. 12,
  147096. };
  147097. static long _vq_lengthlist__44u1__p6_0[] = {
  147098. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  147099. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  147100. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  147101. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  147102. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  147103. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  147104. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  147105. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  147106. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  147107. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  147108. 15,17,16,17,18,17,17,18, 0,
  147109. };
  147110. static float _vq_quantthresh__44u1__p6_0[] = {
  147111. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147112. 12.5, 17.5, 22.5, 27.5,
  147113. };
  147114. static long _vq_quantmap__44u1__p6_0[] = {
  147115. 11, 9, 7, 5, 3, 1, 0, 2,
  147116. 4, 6, 8, 10, 12,
  147117. };
  147118. static encode_aux_threshmatch _vq_auxt__44u1__p6_0 = {
  147119. _vq_quantthresh__44u1__p6_0,
  147120. _vq_quantmap__44u1__p6_0,
  147121. 13,
  147122. 13
  147123. };
  147124. static static_codebook _44u1__p6_0 = {
  147125. 2, 169,
  147126. _vq_lengthlist__44u1__p6_0,
  147127. 1, -526516224, 1616117760, 4, 0,
  147128. _vq_quantlist__44u1__p6_0,
  147129. NULL,
  147130. &_vq_auxt__44u1__p6_0,
  147131. NULL,
  147132. 0
  147133. };
  147134. static long _vq_quantlist__44u1__p6_1[] = {
  147135. 2,
  147136. 1,
  147137. 3,
  147138. 0,
  147139. 4,
  147140. };
  147141. static long _vq_lengthlist__44u1__p6_1[] = {
  147142. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  147143. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  147144. };
  147145. static float _vq_quantthresh__44u1__p6_1[] = {
  147146. -1.5, -0.5, 0.5, 1.5,
  147147. };
  147148. static long _vq_quantmap__44u1__p6_1[] = {
  147149. 3, 1, 0, 2, 4,
  147150. };
  147151. static encode_aux_threshmatch _vq_auxt__44u1__p6_1 = {
  147152. _vq_quantthresh__44u1__p6_1,
  147153. _vq_quantmap__44u1__p6_1,
  147154. 5,
  147155. 5
  147156. };
  147157. static static_codebook _44u1__p6_1 = {
  147158. 2, 25,
  147159. _vq_lengthlist__44u1__p6_1,
  147160. 1, -533725184, 1611661312, 3, 0,
  147161. _vq_quantlist__44u1__p6_1,
  147162. NULL,
  147163. &_vq_auxt__44u1__p6_1,
  147164. NULL,
  147165. 0
  147166. };
  147167. static long _vq_quantlist__44u1__p7_0[] = {
  147168. 3,
  147169. 2,
  147170. 4,
  147171. 1,
  147172. 5,
  147173. 0,
  147174. 6,
  147175. };
  147176. static long _vq_lengthlist__44u1__p7_0[] = {
  147177. 1, 3, 2, 9, 9, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147178. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147179. 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  147180. 8,
  147181. };
  147182. static float _vq_quantthresh__44u1__p7_0[] = {
  147183. -422.5, -253.5, -84.5, 84.5, 253.5, 422.5,
  147184. };
  147185. static long _vq_quantmap__44u1__p7_0[] = {
  147186. 5, 3, 1, 0, 2, 4, 6,
  147187. };
  147188. static encode_aux_threshmatch _vq_auxt__44u1__p7_0 = {
  147189. _vq_quantthresh__44u1__p7_0,
  147190. _vq_quantmap__44u1__p7_0,
  147191. 7,
  147192. 7
  147193. };
  147194. static static_codebook _44u1__p7_0 = {
  147195. 2, 49,
  147196. _vq_lengthlist__44u1__p7_0,
  147197. 1, -518017024, 1626677248, 3, 0,
  147198. _vq_quantlist__44u1__p7_0,
  147199. NULL,
  147200. &_vq_auxt__44u1__p7_0,
  147201. NULL,
  147202. 0
  147203. };
  147204. static long _vq_quantlist__44u1__p7_1[] = {
  147205. 6,
  147206. 5,
  147207. 7,
  147208. 4,
  147209. 8,
  147210. 3,
  147211. 9,
  147212. 2,
  147213. 10,
  147214. 1,
  147215. 11,
  147216. 0,
  147217. 12,
  147218. };
  147219. static long _vq_lengthlist__44u1__p7_1[] = {
  147220. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  147221. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  147222. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  147223. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  147224. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  147225. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  147226. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  147227. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  147228. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  147229. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  147230. 15,15,15,15,15,15,15,15,15,
  147231. };
  147232. static float _vq_quantthresh__44u1__p7_1[] = {
  147233. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  147234. 32.5, 45.5, 58.5, 71.5,
  147235. };
  147236. static long _vq_quantmap__44u1__p7_1[] = {
  147237. 11, 9, 7, 5, 3, 1, 0, 2,
  147238. 4, 6, 8, 10, 12,
  147239. };
  147240. static encode_aux_threshmatch _vq_auxt__44u1__p7_1 = {
  147241. _vq_quantthresh__44u1__p7_1,
  147242. _vq_quantmap__44u1__p7_1,
  147243. 13,
  147244. 13
  147245. };
  147246. static static_codebook _44u1__p7_1 = {
  147247. 2, 169,
  147248. _vq_lengthlist__44u1__p7_1,
  147249. 1, -523010048, 1618608128, 4, 0,
  147250. _vq_quantlist__44u1__p7_1,
  147251. NULL,
  147252. &_vq_auxt__44u1__p7_1,
  147253. NULL,
  147254. 0
  147255. };
  147256. static long _vq_quantlist__44u1__p7_2[] = {
  147257. 6,
  147258. 5,
  147259. 7,
  147260. 4,
  147261. 8,
  147262. 3,
  147263. 9,
  147264. 2,
  147265. 10,
  147266. 1,
  147267. 11,
  147268. 0,
  147269. 12,
  147270. };
  147271. static long _vq_lengthlist__44u1__p7_2[] = {
  147272. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  147273. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  147274. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  147275. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  147276. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  147277. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  147278. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  147279. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147280. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147281. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  147282. 9, 9, 9,10, 9, 9,10,10, 9,
  147283. };
  147284. static float _vq_quantthresh__44u1__p7_2[] = {
  147285. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  147286. 2.5, 3.5, 4.5, 5.5,
  147287. };
  147288. static long _vq_quantmap__44u1__p7_2[] = {
  147289. 11, 9, 7, 5, 3, 1, 0, 2,
  147290. 4, 6, 8, 10, 12,
  147291. };
  147292. static encode_aux_threshmatch _vq_auxt__44u1__p7_2 = {
  147293. _vq_quantthresh__44u1__p7_2,
  147294. _vq_quantmap__44u1__p7_2,
  147295. 13,
  147296. 13
  147297. };
  147298. static static_codebook _44u1__p7_2 = {
  147299. 2, 169,
  147300. _vq_lengthlist__44u1__p7_2,
  147301. 1, -531103744, 1611661312, 4, 0,
  147302. _vq_quantlist__44u1__p7_2,
  147303. NULL,
  147304. &_vq_auxt__44u1__p7_2,
  147305. NULL,
  147306. 0
  147307. };
  147308. static long _huff_lengthlist__44u1__short[] = {
  147309. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  147310. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  147311. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  147312. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  147313. };
  147314. static static_codebook _huff_book__44u1__short = {
  147315. 2, 64,
  147316. _huff_lengthlist__44u1__short,
  147317. 0, 0, 0, 0, 0,
  147318. NULL,
  147319. NULL,
  147320. NULL,
  147321. NULL,
  147322. 0
  147323. };
  147324. static long _huff_lengthlist__44u2__long[] = {
  147325. 5, 9,14,12,15,13,10,13, 7, 4, 5, 6, 8, 7, 8,12,
  147326. 13, 4, 3, 5, 5, 6, 9,15,12, 6, 5, 6, 6, 6, 7,14,
  147327. 14, 7, 4, 6, 4, 6, 8,15,12, 6, 6, 5, 5, 5, 6,14,
  147328. 9, 7, 8, 6, 7, 5, 4,10,10,13,14,14,15,10, 6, 8,
  147329. };
  147330. static static_codebook _huff_book__44u2__long = {
  147331. 2, 64,
  147332. _huff_lengthlist__44u2__long,
  147333. 0, 0, 0, 0, 0,
  147334. NULL,
  147335. NULL,
  147336. NULL,
  147337. NULL,
  147338. 0
  147339. };
  147340. static long _vq_quantlist__44u2__p1_0[] = {
  147341. 1,
  147342. 0,
  147343. 2,
  147344. };
  147345. static long _vq_lengthlist__44u2__p1_0[] = {
  147346. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  147347. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  147348. 11, 8,11,11, 8,11,11,11,13,14,11,13,13, 7,11,11,
  147349. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 8,
  147350. 11,11,11,14,13,10,12,13, 8,11,11,11,13,13,11,13,
  147351. 13,
  147352. };
  147353. static float _vq_quantthresh__44u2__p1_0[] = {
  147354. -0.5, 0.5,
  147355. };
  147356. static long _vq_quantmap__44u2__p1_0[] = {
  147357. 1, 0, 2,
  147358. };
  147359. static encode_aux_threshmatch _vq_auxt__44u2__p1_0 = {
  147360. _vq_quantthresh__44u2__p1_0,
  147361. _vq_quantmap__44u2__p1_0,
  147362. 3,
  147363. 3
  147364. };
  147365. static static_codebook _44u2__p1_0 = {
  147366. 4, 81,
  147367. _vq_lengthlist__44u2__p1_0,
  147368. 1, -535822336, 1611661312, 2, 0,
  147369. _vq_quantlist__44u2__p1_0,
  147370. NULL,
  147371. &_vq_auxt__44u2__p1_0,
  147372. NULL,
  147373. 0
  147374. };
  147375. static long _vq_quantlist__44u2__p2_0[] = {
  147376. 1,
  147377. 0,
  147378. 2,
  147379. };
  147380. static long _vq_lengthlist__44u2__p2_0[] = {
  147381. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  147382. 8, 8, 5, 6, 6, 6, 8, 7, 7, 8, 8, 5, 6, 6, 7, 8,
  147383. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  147384. 7,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  147385. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  147386. 9,
  147387. };
  147388. static float _vq_quantthresh__44u2__p2_0[] = {
  147389. -0.5, 0.5,
  147390. };
  147391. static long _vq_quantmap__44u2__p2_0[] = {
  147392. 1, 0, 2,
  147393. };
  147394. static encode_aux_threshmatch _vq_auxt__44u2__p2_0 = {
  147395. _vq_quantthresh__44u2__p2_0,
  147396. _vq_quantmap__44u2__p2_0,
  147397. 3,
  147398. 3
  147399. };
  147400. static static_codebook _44u2__p2_0 = {
  147401. 4, 81,
  147402. _vq_lengthlist__44u2__p2_0,
  147403. 1, -535822336, 1611661312, 2, 0,
  147404. _vq_quantlist__44u2__p2_0,
  147405. NULL,
  147406. &_vq_auxt__44u2__p2_0,
  147407. NULL,
  147408. 0
  147409. };
  147410. static long _vq_quantlist__44u2__p3_0[] = {
  147411. 2,
  147412. 1,
  147413. 3,
  147414. 0,
  147415. 4,
  147416. };
  147417. static long _vq_lengthlist__44u2__p3_0[] = {
  147418. 2, 4, 4, 7, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  147419. 9, 9,12,11, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  147420. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  147421. 12,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  147422. 11, 9,11,10,13,13,10,11,11,13,13, 8,10,10,14,13,
  147423. 10,11,11,15,14, 9,11,11,15,14,13,14,13,16,14,12,
  147424. 13,13,15,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  147425. 11,14,15,12,13,13,15,15,12,13,14,15,16, 5, 7, 7,
  147426. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  147427. 13,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  147428. 9,11,11,13,13,12,13,12,14,14,11,12,13,15,15, 7,
  147429. 9, 9,12,12, 8,11,10,13,12, 9,11,11,13,13,11,13,
  147430. 12,15,13,11,13,13,15,16, 9,12,11,15,15,11,12,12,
  147431. 16,15,11,12,13,16,16,13,14,15,16,15,13,15,15,17,
  147432. 17, 9,11,11,14,15,10,12,12,15,15,11,13,12,15,16,
  147433. 13,15,14,16,16,13,15,15,17,19, 5, 7, 7,10,10, 7,
  147434. 9, 9,12,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  147435. 11,13,14, 7, 9, 9,12,12, 9,11,11,13,13, 9,10,11,
  147436. 12,13,11,13,12,16,15,11,12,12,14,15, 7, 9, 9,12,
  147437. 12, 9,11,11,13,13, 9,11,11,13,12,11,13,12,15,16,
  147438. 12,13,13,15,14, 9,11,11,15,14,11,13,12,16,15,10,
  147439. 11,12,15,15,13,14,14,18,17,13,14,14,15,17,10,11,
  147440. 11,14,15,11,13,12,15,17,11,13,12,15,16,13,15,14,
  147441. 18,17,14,15,15,16,18, 7,10,10,14,14,10,12,12,15,
  147442. 15,10,12,12,15,15,14,15,15,18,17,13,15,15,16,16,
  147443. 9,11,11,16,15,11,13,13,16,18,11,13,13,16,16,15,
  147444. 16,16, 0, 0,14,15,16,18,17, 9,11,11,15,15,10,13,
  147445. 12,17,16,11,12,13,16,17,14,15,16,19,19,14,15,15,
  147446. 0,20,12,14,14, 0, 0,13,14,16,19,18,13,15,16,20,
  147447. 17,16,18, 0, 0, 0,15,16,17,18,19,11,14,14, 0,19,
  147448. 12,15,14,17,17,13,15,15, 0, 0,16,17,15,20,19,15,
  147449. 17,16,19, 0, 8,10,10,14,15,10,12,11,15,15,10,11,
  147450. 12,16,15,13,14,14,19,17,14,15,15, 0, 0, 9,11,11,
  147451. 16,15,11,13,13,17,16,10,12,13,16,17,14,15,15,18,
  147452. 18,14,15,16,20,19, 9,12,12, 0,15,11,13,13,16,17,
  147453. 11,13,13,19,17,14,16,16,18,17,15,16,16,17,19,11,
  147454. 14,14,18,18,13,14,15, 0, 0,12,14,15,19,18,15,16,
  147455. 19, 0,19,15,16,19,19,17,12,14,14,16,19,13,15,15,
  147456. 0,17,13,15,14,18,18,15,16,15, 0,18,16,17,17, 0,
  147457. 0,
  147458. };
  147459. static float _vq_quantthresh__44u2__p3_0[] = {
  147460. -1.5, -0.5, 0.5, 1.5,
  147461. };
  147462. static long _vq_quantmap__44u2__p3_0[] = {
  147463. 3, 1, 0, 2, 4,
  147464. };
  147465. static encode_aux_threshmatch _vq_auxt__44u2__p3_0 = {
  147466. _vq_quantthresh__44u2__p3_0,
  147467. _vq_quantmap__44u2__p3_0,
  147468. 5,
  147469. 5
  147470. };
  147471. static static_codebook _44u2__p3_0 = {
  147472. 4, 625,
  147473. _vq_lengthlist__44u2__p3_0,
  147474. 1, -533725184, 1611661312, 3, 0,
  147475. _vq_quantlist__44u2__p3_0,
  147476. NULL,
  147477. &_vq_auxt__44u2__p3_0,
  147478. NULL,
  147479. 0
  147480. };
  147481. static long _vq_quantlist__44u2__p4_0[] = {
  147482. 2,
  147483. 1,
  147484. 3,
  147485. 0,
  147486. 4,
  147487. };
  147488. static long _vq_lengthlist__44u2__p4_0[] = {
  147489. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  147490. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  147491. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  147492. 11,12, 5, 7, 7, 9, 9, 6, 8, 7,10,10, 7, 8, 8,10,
  147493. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10,10,12,12,
  147494. 10,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  147495. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,13,10,10,
  147496. 10,12,13,11,12,12,14,13,12,12,12,14,13, 5, 7, 7,
  147497. 10, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  147498. 12,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  147499. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,13,13, 6,
  147500. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  147501. 10,13,11,10,11,11,13,13, 9,10,10,13,13,10,11,11,
  147502. 13,13,10,11,11,14,13,12,11,13,12,15,12,13,13,15,
  147503. 15, 9,10,10,12,13,10,11,10,13,13,10,11,11,13,13,
  147504. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9,10, 7,
  147505. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  147506. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  147507. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  147508. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  147509. 10,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  147510. 10,11,13,13,12,13,13,15,15,12,11,13,12,14, 9,10,
  147511. 10,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  147512. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  147513. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  147514. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,12,13,
  147515. 13,14,14,16,12,13,13,15,14, 9,10,10,13,13,10,11,
  147516. 10,14,13,10,11,11,13,14,12,14,13,16,14,13,13,13,
  147517. 14,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  147518. 15,14,12,15,12,16,14,15,15,17,16,11,12,12,14,15,
  147519. 11,13,11,15,14,12,13,13,15,16,13,15,12,17,13,14,
  147520. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,13,13, 9,10,
  147521. 10,13,13,12,13,12,14,14,12,13,13,15,15, 9,10,10,
  147522. 13,13,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  147523. 14,12,12,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  147524. 10,11,11,14,13,13,13,13,15,15,13,14,13,16,14,11,
  147525. 12,12,14,14,12,13,13,16,15,11,12,13,14,15,14,15,
  147526. 15,16,16,14,13,15,13,17,11,12,12,14,15,12,13,13,
  147527. 15,16,11,13,12,15,15,14,15,14,16,16,14,15,12,17,
  147528. 13,
  147529. };
  147530. static float _vq_quantthresh__44u2__p4_0[] = {
  147531. -1.5, -0.5, 0.5, 1.5,
  147532. };
  147533. static long _vq_quantmap__44u2__p4_0[] = {
  147534. 3, 1, 0, 2, 4,
  147535. };
  147536. static encode_aux_threshmatch _vq_auxt__44u2__p4_0 = {
  147537. _vq_quantthresh__44u2__p4_0,
  147538. _vq_quantmap__44u2__p4_0,
  147539. 5,
  147540. 5
  147541. };
  147542. static static_codebook _44u2__p4_0 = {
  147543. 4, 625,
  147544. _vq_lengthlist__44u2__p4_0,
  147545. 1, -533725184, 1611661312, 3, 0,
  147546. _vq_quantlist__44u2__p4_0,
  147547. NULL,
  147548. &_vq_auxt__44u2__p4_0,
  147549. NULL,
  147550. 0
  147551. };
  147552. static long _vq_quantlist__44u2__p5_0[] = {
  147553. 4,
  147554. 3,
  147555. 5,
  147556. 2,
  147557. 6,
  147558. 1,
  147559. 7,
  147560. 0,
  147561. 8,
  147562. };
  147563. static long _vq_lengthlist__44u2__p5_0[] = {
  147564. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 8, 8, 8,
  147565. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  147566. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  147567. 9, 9,10,11,12,12, 8, 8, 8, 9, 9,10,10,12,12,10,
  147568. 10,10,11,11,12,12,13,13,10,10,10,11,11,12,12,13,
  147569. 13,
  147570. };
  147571. static float _vq_quantthresh__44u2__p5_0[] = {
  147572. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147573. };
  147574. static long _vq_quantmap__44u2__p5_0[] = {
  147575. 7, 5, 3, 1, 0, 2, 4, 6,
  147576. 8,
  147577. };
  147578. static encode_aux_threshmatch _vq_auxt__44u2__p5_0 = {
  147579. _vq_quantthresh__44u2__p5_0,
  147580. _vq_quantmap__44u2__p5_0,
  147581. 9,
  147582. 9
  147583. };
  147584. static static_codebook _44u2__p5_0 = {
  147585. 2, 81,
  147586. _vq_lengthlist__44u2__p5_0,
  147587. 1, -531628032, 1611661312, 4, 0,
  147588. _vq_quantlist__44u2__p5_0,
  147589. NULL,
  147590. &_vq_auxt__44u2__p5_0,
  147591. NULL,
  147592. 0
  147593. };
  147594. static long _vq_quantlist__44u2__p6_0[] = {
  147595. 6,
  147596. 5,
  147597. 7,
  147598. 4,
  147599. 8,
  147600. 3,
  147601. 9,
  147602. 2,
  147603. 10,
  147604. 1,
  147605. 11,
  147606. 0,
  147607. 12,
  147608. };
  147609. static long _vq_lengthlist__44u2__p6_0[] = {
  147610. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,14,13, 4, 6, 5,
  147611. 8, 8, 9, 9,11,10,12,11,15,14, 4, 5, 6, 8, 8, 9,
  147612. 9,11,11,11,11,14,14, 6, 8, 8,10, 9,11,11,11,11,
  147613. 12,12,15,15, 6, 8, 8, 9, 9,11,11,11,12,12,12,15,
  147614. 15, 8,10,10,11,11,11,11,12,12,13,13,15,16, 8,10,
  147615. 10,11,11,11,11,12,12,13,13,16,16,10,11,11,12,12,
  147616. 12,12,13,13,13,13,17,16,10,11,11,12,12,12,12,13,
  147617. 13,13,14,16,17,11,12,12,13,13,13,13,14,14,15,14,
  147618. 18,17,11,12,12,13,13,13,13,14,14,14,15,19,18,14,
  147619. 15,15,15,15,16,16,18,19,18,18, 0, 0,14,15,15,16,
  147620. 15,17,17,16,18,17,18, 0, 0,
  147621. };
  147622. static float _vq_quantthresh__44u2__p6_0[] = {
  147623. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147624. 12.5, 17.5, 22.5, 27.5,
  147625. };
  147626. static long _vq_quantmap__44u2__p6_0[] = {
  147627. 11, 9, 7, 5, 3, 1, 0, 2,
  147628. 4, 6, 8, 10, 12,
  147629. };
  147630. static encode_aux_threshmatch _vq_auxt__44u2__p6_0 = {
  147631. _vq_quantthresh__44u2__p6_0,
  147632. _vq_quantmap__44u2__p6_0,
  147633. 13,
  147634. 13
  147635. };
  147636. static static_codebook _44u2__p6_0 = {
  147637. 2, 169,
  147638. _vq_lengthlist__44u2__p6_0,
  147639. 1, -526516224, 1616117760, 4, 0,
  147640. _vq_quantlist__44u2__p6_0,
  147641. NULL,
  147642. &_vq_auxt__44u2__p6_0,
  147643. NULL,
  147644. 0
  147645. };
  147646. static long _vq_quantlist__44u2__p6_1[] = {
  147647. 2,
  147648. 1,
  147649. 3,
  147650. 0,
  147651. 4,
  147652. };
  147653. static long _vq_lengthlist__44u2__p6_1[] = {
  147654. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  147655. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  147656. };
  147657. static float _vq_quantthresh__44u2__p6_1[] = {
  147658. -1.5, -0.5, 0.5, 1.5,
  147659. };
  147660. static long _vq_quantmap__44u2__p6_1[] = {
  147661. 3, 1, 0, 2, 4,
  147662. };
  147663. static encode_aux_threshmatch _vq_auxt__44u2__p6_1 = {
  147664. _vq_quantthresh__44u2__p6_1,
  147665. _vq_quantmap__44u2__p6_1,
  147666. 5,
  147667. 5
  147668. };
  147669. static static_codebook _44u2__p6_1 = {
  147670. 2, 25,
  147671. _vq_lengthlist__44u2__p6_1,
  147672. 1, -533725184, 1611661312, 3, 0,
  147673. _vq_quantlist__44u2__p6_1,
  147674. NULL,
  147675. &_vq_auxt__44u2__p6_1,
  147676. NULL,
  147677. 0
  147678. };
  147679. static long _vq_quantlist__44u2__p7_0[] = {
  147680. 4,
  147681. 3,
  147682. 5,
  147683. 2,
  147684. 6,
  147685. 1,
  147686. 7,
  147687. 0,
  147688. 8,
  147689. };
  147690. static long _vq_lengthlist__44u2__p7_0[] = {
  147691. 1, 3, 2,12,12,12,12,12,12, 4,12,12,12,12,12,12,
  147692. 12,12, 5,12,12,12,12,12,12,12,12,12,12,11,11,11,
  147693. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147694. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147695. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147696. 11,
  147697. };
  147698. static float _vq_quantthresh__44u2__p7_0[] = {
  147699. -591.5, -422.5, -253.5, -84.5, 84.5, 253.5, 422.5, 591.5,
  147700. };
  147701. static long _vq_quantmap__44u2__p7_0[] = {
  147702. 7, 5, 3, 1, 0, 2, 4, 6,
  147703. 8,
  147704. };
  147705. static encode_aux_threshmatch _vq_auxt__44u2__p7_0 = {
  147706. _vq_quantthresh__44u2__p7_0,
  147707. _vq_quantmap__44u2__p7_0,
  147708. 9,
  147709. 9
  147710. };
  147711. static static_codebook _44u2__p7_0 = {
  147712. 2, 81,
  147713. _vq_lengthlist__44u2__p7_0,
  147714. 1, -516612096, 1626677248, 4, 0,
  147715. _vq_quantlist__44u2__p7_0,
  147716. NULL,
  147717. &_vq_auxt__44u2__p7_0,
  147718. NULL,
  147719. 0
  147720. };
  147721. static long _vq_quantlist__44u2__p7_1[] = {
  147722. 6,
  147723. 5,
  147724. 7,
  147725. 4,
  147726. 8,
  147727. 3,
  147728. 9,
  147729. 2,
  147730. 10,
  147731. 1,
  147732. 11,
  147733. 0,
  147734. 12,
  147735. };
  147736. static long _vq_lengthlist__44u2__p7_1[] = {
  147737. 1, 4, 4, 7, 6, 7, 6, 8, 7, 9, 7, 9, 8, 4, 7, 6,
  147738. 8, 8, 9, 8,10, 9,10,10,11,11, 4, 7, 7, 8, 8, 8,
  147739. 8, 9,10,11,11,11,11, 6, 8, 8,10,10,10,10,11,11,
  147740. 12,12,12,12, 7, 8, 8,10,10,10,10,11,11,12,12,13,
  147741. 13, 7, 9, 9,11,10,12,12,13,13,14,13,14,14, 7, 9,
  147742. 9,10,11,11,12,13,13,13,13,16,14, 9,10,10,12,12,
  147743. 13,13,14,14,15,16,15,16, 9,10,10,12,12,12,13,14,
  147744. 14,14,15,16,15,10,12,12,13,13,15,13,16,16,15,17,
  147745. 17,17,10,11,11,12,14,14,14,15,15,17,17,15,17,11,
  147746. 12,12,14,14,14,15,15,15,17,16,17,17,10,12,12,13,
  147747. 14,14,14,17,15,17,17,17,17,
  147748. };
  147749. static float _vq_quantthresh__44u2__p7_1[] = {
  147750. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  147751. 32.5, 45.5, 58.5, 71.5,
  147752. };
  147753. static long _vq_quantmap__44u2__p7_1[] = {
  147754. 11, 9, 7, 5, 3, 1, 0, 2,
  147755. 4, 6, 8, 10, 12,
  147756. };
  147757. static encode_aux_threshmatch _vq_auxt__44u2__p7_1 = {
  147758. _vq_quantthresh__44u2__p7_1,
  147759. _vq_quantmap__44u2__p7_1,
  147760. 13,
  147761. 13
  147762. };
  147763. static static_codebook _44u2__p7_1 = {
  147764. 2, 169,
  147765. _vq_lengthlist__44u2__p7_1,
  147766. 1, -523010048, 1618608128, 4, 0,
  147767. _vq_quantlist__44u2__p7_1,
  147768. NULL,
  147769. &_vq_auxt__44u2__p7_1,
  147770. NULL,
  147771. 0
  147772. };
  147773. static long _vq_quantlist__44u2__p7_2[] = {
  147774. 6,
  147775. 5,
  147776. 7,
  147777. 4,
  147778. 8,
  147779. 3,
  147780. 9,
  147781. 2,
  147782. 10,
  147783. 1,
  147784. 11,
  147785. 0,
  147786. 12,
  147787. };
  147788. static long _vq_lengthlist__44u2__p7_2[] = {
  147789. 2, 5, 5, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 5, 6, 6,
  147790. 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 5, 6, 6, 7, 7, 8,
  147791. 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7, 8, 8, 8, 8, 8,
  147792. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  147793. 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 7, 8,
  147794. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 9,
  147795. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  147796. 9, 9, 9, 9, 9, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147797. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8,
  147798. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9,
  147799. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147800. };
  147801. static float _vq_quantthresh__44u2__p7_2[] = {
  147802. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  147803. 2.5, 3.5, 4.5, 5.5,
  147804. };
  147805. static long _vq_quantmap__44u2__p7_2[] = {
  147806. 11, 9, 7, 5, 3, 1, 0, 2,
  147807. 4, 6, 8, 10, 12,
  147808. };
  147809. static encode_aux_threshmatch _vq_auxt__44u2__p7_2 = {
  147810. _vq_quantthresh__44u2__p7_2,
  147811. _vq_quantmap__44u2__p7_2,
  147812. 13,
  147813. 13
  147814. };
  147815. static static_codebook _44u2__p7_2 = {
  147816. 2, 169,
  147817. _vq_lengthlist__44u2__p7_2,
  147818. 1, -531103744, 1611661312, 4, 0,
  147819. _vq_quantlist__44u2__p7_2,
  147820. NULL,
  147821. &_vq_auxt__44u2__p7_2,
  147822. NULL,
  147823. 0
  147824. };
  147825. static long _huff_lengthlist__44u2__short[] = {
  147826. 13,15,17,17,15,15,12,17,11, 9, 7,10,10, 9,12,17,
  147827. 10, 6, 3, 6, 5, 7,10,17,15,10, 6, 9, 8, 9,11,17,
  147828. 15, 8, 4, 7, 3, 5, 9,16,16,10, 5, 8, 4, 5, 8,16,
  147829. 13,11, 5, 8, 3, 3, 5,14,13,12, 7,10, 5, 5, 7,14,
  147830. };
  147831. static static_codebook _huff_book__44u2__short = {
  147832. 2, 64,
  147833. _huff_lengthlist__44u2__short,
  147834. 0, 0, 0, 0, 0,
  147835. NULL,
  147836. NULL,
  147837. NULL,
  147838. NULL,
  147839. 0
  147840. };
  147841. static long _huff_lengthlist__44u3__long[] = {
  147842. 6, 9,13,12,14,11,10,13, 8, 4, 5, 7, 8, 7, 8,12,
  147843. 11, 4, 3, 5, 5, 7, 9,14,11, 6, 5, 6, 6, 6, 7,13,
  147844. 13, 7, 5, 6, 4, 5, 7,14,11, 7, 6, 6, 5, 5, 6,13,
  147845. 9, 7, 8, 6, 7, 5, 3, 9, 9,12,13,12,14,10, 6, 7,
  147846. };
  147847. static static_codebook _huff_book__44u3__long = {
  147848. 2, 64,
  147849. _huff_lengthlist__44u3__long,
  147850. 0, 0, 0, 0, 0,
  147851. NULL,
  147852. NULL,
  147853. NULL,
  147854. NULL,
  147855. 0
  147856. };
  147857. static long _vq_quantlist__44u3__p1_0[] = {
  147858. 1,
  147859. 0,
  147860. 2,
  147861. };
  147862. static long _vq_lengthlist__44u3__p1_0[] = {
  147863. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  147864. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  147865. 11, 8,11,11, 8,11,11,11,13,14,11,14,14, 8,11,11,
  147866. 10,14,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  147867. 11,11,11,14,14,10,12,14, 8,11,11,11,14,14,11,14,
  147868. 13,
  147869. };
  147870. static float _vq_quantthresh__44u3__p1_0[] = {
  147871. -0.5, 0.5,
  147872. };
  147873. static long _vq_quantmap__44u3__p1_0[] = {
  147874. 1, 0, 2,
  147875. };
  147876. static encode_aux_threshmatch _vq_auxt__44u3__p1_0 = {
  147877. _vq_quantthresh__44u3__p1_0,
  147878. _vq_quantmap__44u3__p1_0,
  147879. 3,
  147880. 3
  147881. };
  147882. static static_codebook _44u3__p1_0 = {
  147883. 4, 81,
  147884. _vq_lengthlist__44u3__p1_0,
  147885. 1, -535822336, 1611661312, 2, 0,
  147886. _vq_quantlist__44u3__p1_0,
  147887. NULL,
  147888. &_vq_auxt__44u3__p1_0,
  147889. NULL,
  147890. 0
  147891. };
  147892. static long _vq_quantlist__44u3__p2_0[] = {
  147893. 1,
  147894. 0,
  147895. 2,
  147896. };
  147897. static long _vq_lengthlist__44u3__p2_0[] = {
  147898. 2, 5, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  147899. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 7, 8,
  147900. 8, 6, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  147901. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  147902. 8, 8, 8,10,10, 8, 8,10, 7, 8, 8, 8,10,10, 8,10,
  147903. 9,
  147904. };
  147905. static float _vq_quantthresh__44u3__p2_0[] = {
  147906. -0.5, 0.5,
  147907. };
  147908. static long _vq_quantmap__44u3__p2_0[] = {
  147909. 1, 0, 2,
  147910. };
  147911. static encode_aux_threshmatch _vq_auxt__44u3__p2_0 = {
  147912. _vq_quantthresh__44u3__p2_0,
  147913. _vq_quantmap__44u3__p2_0,
  147914. 3,
  147915. 3
  147916. };
  147917. static static_codebook _44u3__p2_0 = {
  147918. 4, 81,
  147919. _vq_lengthlist__44u3__p2_0,
  147920. 1, -535822336, 1611661312, 2, 0,
  147921. _vq_quantlist__44u3__p2_0,
  147922. NULL,
  147923. &_vq_auxt__44u3__p2_0,
  147924. NULL,
  147925. 0
  147926. };
  147927. static long _vq_quantlist__44u3__p3_0[] = {
  147928. 2,
  147929. 1,
  147930. 3,
  147931. 0,
  147932. 4,
  147933. };
  147934. static long _vq_lengthlist__44u3__p3_0[] = {
  147935. 2, 4, 4, 7, 7, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  147936. 9, 9,12,12, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  147937. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  147938. 13,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  147939. 11, 9,11,10,13,13,10,11,11,14,13, 8,10,10,14,13,
  147940. 10,11,11,15,14, 9,11,11,14,14,13,14,13,16,16,12,
  147941. 13,13,15,15, 8,10,10,13,14, 9,11,11,14,14,10,11,
  147942. 11,14,15,12,13,13,15,15,13,14,14,15,16, 5, 7, 7,
  147943. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  147944. 14,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  147945. 9,11,11,13,13,12,12,13,15,15,11,12,13,15,16, 7,
  147946. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  147947. 12,15,13,11,13,13,15,16, 9,12,11,15,14,11,12,13,
  147948. 16,15,11,13,13,15,16,14,14,15,17,16,13,15,16, 0,
  147949. 17, 9,11,11,15,15,10,13,12,15,15,11,13,13,15,16,
  147950. 13,15,13,16,15,14,16,15, 0,19, 5, 7, 7,10,10, 7,
  147951. 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,14,10,11,
  147952. 12,14,14, 7, 9, 9,12,12, 9,11,11,14,13, 9,10,11,
  147953. 12,13,11,13,13,16,16,11,12,13,13,16, 7, 9, 9,12,
  147954. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,15,
  147955. 12,13,12,15,14, 9,11,11,15,14,11,13,12,16,16,10,
  147956. 12,12,15,15,13,15,15,17,19,13,14,15,16,17,10,12,
  147957. 12,15,15,11,13,13,16,16,11,13,13,15,16,13,15,15,
  147958. 0, 0,14,15,15,16,16, 8,10,10,14,14,10,12,12,15,
  147959. 15,10,12,11,15,16,14,15,15,19,20,13,14,14,18,16,
  147960. 9,11,11,15,15,11,13,13,17,16,11,13,13,16,16,15,
  147961. 17,17,20,20,14,15,16,17,20, 9,11,11,15,15,10,13,
  147962. 12,16,15,11,13,13,15,17,14,16,15,18, 0,14,16,15,
  147963. 18,20,12,14,14, 0, 0,14,14,16, 0, 0,13,16,15, 0,
  147964. 0,17,17,18, 0, 0,16,17,19,19, 0,12,14,14,18, 0,
  147965. 12,16,14, 0,17,13,15,15,18, 0,16,18,17, 0,17,16,
  147966. 18,17, 0, 0, 7,10,10,14,14,10,12,11,15,15,10,12,
  147967. 12,16,15,13,15,15,18, 0,14,15,15,17, 0, 9,11,11,
  147968. 15,15,11,13,13,16,16,11,12,13,16,16,14,15,16,17,
  147969. 17,14,16,16,16,18, 9,11,12,16,16,11,13,13,17,17,
  147970. 11,14,13,20,17,15,16,16,19, 0,15,16,17, 0,19,11,
  147971. 13,14,17,16,14,15,15,20,18,13,14,15,17,19,16,18,
  147972. 18, 0,20,16,16,19,17, 0,12,15,14,17, 0,14,15,15,
  147973. 18,19,13,16,15,19,20,15,18,18, 0,20,17, 0,16, 0,
  147974. 0,
  147975. };
  147976. static float _vq_quantthresh__44u3__p3_0[] = {
  147977. -1.5, -0.5, 0.5, 1.5,
  147978. };
  147979. static long _vq_quantmap__44u3__p3_0[] = {
  147980. 3, 1, 0, 2, 4,
  147981. };
  147982. static encode_aux_threshmatch _vq_auxt__44u3__p3_0 = {
  147983. _vq_quantthresh__44u3__p3_0,
  147984. _vq_quantmap__44u3__p3_0,
  147985. 5,
  147986. 5
  147987. };
  147988. static static_codebook _44u3__p3_0 = {
  147989. 4, 625,
  147990. _vq_lengthlist__44u3__p3_0,
  147991. 1, -533725184, 1611661312, 3, 0,
  147992. _vq_quantlist__44u3__p3_0,
  147993. NULL,
  147994. &_vq_auxt__44u3__p3_0,
  147995. NULL,
  147996. 0
  147997. };
  147998. static long _vq_quantlist__44u3__p4_0[] = {
  147999. 2,
  148000. 1,
  148001. 3,
  148002. 0,
  148003. 4,
  148004. };
  148005. static long _vq_lengthlist__44u3__p4_0[] = {
  148006. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  148007. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  148008. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  148009. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  148010. 10, 9,10, 9,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  148011. 9,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  148012. 12,12,13,14, 9, 9,10,12,12, 9,10,10,12,12, 9,10,
  148013. 10,12,13,11,12,11,14,13,12,12,12,14,13, 5, 7, 7,
  148014. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  148015. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  148016. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  148017. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  148018. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  148019. 13,13,10,11,11,13,13,12,12,13,12,15,12,13,13,15,
  148020. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  148021. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  148022. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  148023. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  148024. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  148025. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  148026. 11,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  148027. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  148028. 11,12,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  148029. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  148030. 13, 9,10,10,13,13,12,13,13,15,14,12,12,12,14,13,
  148031. 9,10,10,13,12,10,11,11,13,13,10,11,11,14,12,13,
  148032. 13,14,14,16,12,13,13,15,15, 9,10,10,13,13,10,11,
  148033. 10,14,13,10,11,11,13,14,12,14,13,15,14,13,13,13,
  148034. 15,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  148035. 14,14,12,15,12,16,14,15,15,17,15,11,12,12,14,14,
  148036. 11,13,11,15,14,12,13,13,15,15,13,15,12,17,13,14,
  148037. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  148038. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  148039. 13,12,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  148040. 15,12,12,13,14,16, 9,10,10,13,13,10,11,11,13,14,
  148041. 10,11,11,14,13,12,13,13,14,15,13,14,13,16,14,11,
  148042. 12,12,14,14,12,13,13,15,14,11,12,13,14,15,14,15,
  148043. 15,16,16,13,13,15,13,16,11,12,12,14,15,12,13,13,
  148044. 14,15,11,13,12,15,14,14,15,15,16,16,14,15,12,16,
  148045. 13,
  148046. };
  148047. static float _vq_quantthresh__44u3__p4_0[] = {
  148048. -1.5, -0.5, 0.5, 1.5,
  148049. };
  148050. static long _vq_quantmap__44u3__p4_0[] = {
  148051. 3, 1, 0, 2, 4,
  148052. };
  148053. static encode_aux_threshmatch _vq_auxt__44u3__p4_0 = {
  148054. _vq_quantthresh__44u3__p4_0,
  148055. _vq_quantmap__44u3__p4_0,
  148056. 5,
  148057. 5
  148058. };
  148059. static static_codebook _44u3__p4_0 = {
  148060. 4, 625,
  148061. _vq_lengthlist__44u3__p4_0,
  148062. 1, -533725184, 1611661312, 3, 0,
  148063. _vq_quantlist__44u3__p4_0,
  148064. NULL,
  148065. &_vq_auxt__44u3__p4_0,
  148066. NULL,
  148067. 0
  148068. };
  148069. static long _vq_quantlist__44u3__p5_0[] = {
  148070. 4,
  148071. 3,
  148072. 5,
  148073. 2,
  148074. 6,
  148075. 1,
  148076. 7,
  148077. 0,
  148078. 8,
  148079. };
  148080. static long _vq_lengthlist__44u3__p5_0[] = {
  148081. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  148082. 10,10, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  148083. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,10, 7, 8, 8,
  148084. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  148085. 10,10,11,10,11,11,12,12, 9,10,10,10,10,11,11,12,
  148086. 12,
  148087. };
  148088. static float _vq_quantthresh__44u3__p5_0[] = {
  148089. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148090. };
  148091. static long _vq_quantmap__44u3__p5_0[] = {
  148092. 7, 5, 3, 1, 0, 2, 4, 6,
  148093. 8,
  148094. };
  148095. static encode_aux_threshmatch _vq_auxt__44u3__p5_0 = {
  148096. _vq_quantthresh__44u3__p5_0,
  148097. _vq_quantmap__44u3__p5_0,
  148098. 9,
  148099. 9
  148100. };
  148101. static static_codebook _44u3__p5_0 = {
  148102. 2, 81,
  148103. _vq_lengthlist__44u3__p5_0,
  148104. 1, -531628032, 1611661312, 4, 0,
  148105. _vq_quantlist__44u3__p5_0,
  148106. NULL,
  148107. &_vq_auxt__44u3__p5_0,
  148108. NULL,
  148109. 0
  148110. };
  148111. static long _vq_quantlist__44u3__p6_0[] = {
  148112. 6,
  148113. 5,
  148114. 7,
  148115. 4,
  148116. 8,
  148117. 3,
  148118. 9,
  148119. 2,
  148120. 10,
  148121. 1,
  148122. 11,
  148123. 0,
  148124. 12,
  148125. };
  148126. static long _vq_lengthlist__44u3__p6_0[] = {
  148127. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,13,14, 4, 6, 5,
  148128. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  148129. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  148130. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  148131. 15, 8, 9, 9,11,10,11,11,12,12,13,13,15,16, 8, 9,
  148132. 9,10,11,11,11,12,12,13,13,16,16,10,10,11,11,11,
  148133. 12,12,13,13,13,14,17,16, 9,10,11,12,11,12,12,13,
  148134. 13,13,13,16,18,11,12,11,12,12,13,13,13,14,15,14,
  148135. 17,17,11,11,12,12,12,13,13,13,14,14,15,18,17,14,
  148136. 15,15,15,15,16,16,17,17,19,18, 0,20,14,15,14,15,
  148137. 15,16,16,16,17,18,16,20,18,
  148138. };
  148139. static float _vq_quantthresh__44u3__p6_0[] = {
  148140. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  148141. 12.5, 17.5, 22.5, 27.5,
  148142. };
  148143. static long _vq_quantmap__44u3__p6_0[] = {
  148144. 11, 9, 7, 5, 3, 1, 0, 2,
  148145. 4, 6, 8, 10, 12,
  148146. };
  148147. static encode_aux_threshmatch _vq_auxt__44u3__p6_0 = {
  148148. _vq_quantthresh__44u3__p6_0,
  148149. _vq_quantmap__44u3__p6_0,
  148150. 13,
  148151. 13
  148152. };
  148153. static static_codebook _44u3__p6_0 = {
  148154. 2, 169,
  148155. _vq_lengthlist__44u3__p6_0,
  148156. 1, -526516224, 1616117760, 4, 0,
  148157. _vq_quantlist__44u3__p6_0,
  148158. NULL,
  148159. &_vq_auxt__44u3__p6_0,
  148160. NULL,
  148161. 0
  148162. };
  148163. static long _vq_quantlist__44u3__p6_1[] = {
  148164. 2,
  148165. 1,
  148166. 3,
  148167. 0,
  148168. 4,
  148169. };
  148170. static long _vq_lengthlist__44u3__p6_1[] = {
  148171. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  148172. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  148173. };
  148174. static float _vq_quantthresh__44u3__p6_1[] = {
  148175. -1.5, -0.5, 0.5, 1.5,
  148176. };
  148177. static long _vq_quantmap__44u3__p6_1[] = {
  148178. 3, 1, 0, 2, 4,
  148179. };
  148180. static encode_aux_threshmatch _vq_auxt__44u3__p6_1 = {
  148181. _vq_quantthresh__44u3__p6_1,
  148182. _vq_quantmap__44u3__p6_1,
  148183. 5,
  148184. 5
  148185. };
  148186. static static_codebook _44u3__p6_1 = {
  148187. 2, 25,
  148188. _vq_lengthlist__44u3__p6_1,
  148189. 1, -533725184, 1611661312, 3, 0,
  148190. _vq_quantlist__44u3__p6_1,
  148191. NULL,
  148192. &_vq_auxt__44u3__p6_1,
  148193. NULL,
  148194. 0
  148195. };
  148196. static long _vq_quantlist__44u3__p7_0[] = {
  148197. 4,
  148198. 3,
  148199. 5,
  148200. 2,
  148201. 6,
  148202. 1,
  148203. 7,
  148204. 0,
  148205. 8,
  148206. };
  148207. static long _vq_lengthlist__44u3__p7_0[] = {
  148208. 1, 3, 3,10,10,10,10,10,10, 4,10,10,10,10,10,10,
  148209. 10,10, 4,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  148210. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148211. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148212. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148213. 9,
  148214. };
  148215. static float _vq_quantthresh__44u3__p7_0[] = {
  148216. -892.5, -637.5, -382.5, -127.5, 127.5, 382.5, 637.5, 892.5,
  148217. };
  148218. static long _vq_quantmap__44u3__p7_0[] = {
  148219. 7, 5, 3, 1, 0, 2, 4, 6,
  148220. 8,
  148221. };
  148222. static encode_aux_threshmatch _vq_auxt__44u3__p7_0 = {
  148223. _vq_quantthresh__44u3__p7_0,
  148224. _vq_quantmap__44u3__p7_0,
  148225. 9,
  148226. 9
  148227. };
  148228. static static_codebook _44u3__p7_0 = {
  148229. 2, 81,
  148230. _vq_lengthlist__44u3__p7_0,
  148231. 1, -515907584, 1627381760, 4, 0,
  148232. _vq_quantlist__44u3__p7_0,
  148233. NULL,
  148234. &_vq_auxt__44u3__p7_0,
  148235. NULL,
  148236. 0
  148237. };
  148238. static long _vq_quantlist__44u3__p7_1[] = {
  148239. 7,
  148240. 6,
  148241. 8,
  148242. 5,
  148243. 9,
  148244. 4,
  148245. 10,
  148246. 3,
  148247. 11,
  148248. 2,
  148249. 12,
  148250. 1,
  148251. 13,
  148252. 0,
  148253. 14,
  148254. };
  148255. static long _vq_lengthlist__44u3__p7_1[] = {
  148256. 1, 4, 4, 6, 6, 7, 6, 8, 7, 9, 8,10, 9,11,11, 4,
  148257. 7, 7, 8, 7, 9, 9,10,10,11,11,11,11,12,12, 4, 7,
  148258. 7, 7, 7, 9, 9,10,10,11,11,12,12,12,11, 6, 8, 8,
  148259. 9, 9,10,10,11,11,12,12,13,12,13,13, 6, 8, 8, 9,
  148260. 9,10,11,11,11,12,12,13,14,13,13, 8, 9, 9,11,11,
  148261. 12,12,12,13,14,13,14,14,14,15, 8, 9, 9,11,11,11,
  148262. 12,13,14,13,14,15,17,14,15, 9,10,10,12,12,13,13,
  148263. 13,14,15,15,15,16,16,16, 9,11,11,12,12,13,13,14,
  148264. 14,14,15,16,16,16,16,10,12,12,13,13,14,14,15,15,
  148265. 15,16,17,17,17,17,10,12,11,13,13,15,14,15,14,16,
  148266. 17,16,16,16,16,11,13,12,14,14,14,14,15,16,17,16,
  148267. 17,17,17,17,11,13,12,14,14,14,15,17,16,17,17,17,
  148268. 17,17,17,12,13,13,15,16,15,16,17,17,16,16,17,17,
  148269. 17,17,12,13,13,15,15,15,16,17,17,17,16,17,16,17,
  148270. 17,
  148271. };
  148272. static float _vq_quantthresh__44u3__p7_1[] = {
  148273. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  148274. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  148275. };
  148276. static long _vq_quantmap__44u3__p7_1[] = {
  148277. 13, 11, 9, 7, 5, 3, 1, 0,
  148278. 2, 4, 6, 8, 10, 12, 14,
  148279. };
  148280. static encode_aux_threshmatch _vq_auxt__44u3__p7_1 = {
  148281. _vq_quantthresh__44u3__p7_1,
  148282. _vq_quantmap__44u3__p7_1,
  148283. 15,
  148284. 15
  148285. };
  148286. static static_codebook _44u3__p7_1 = {
  148287. 2, 225,
  148288. _vq_lengthlist__44u3__p7_1,
  148289. 1, -522338304, 1620115456, 4, 0,
  148290. _vq_quantlist__44u3__p7_1,
  148291. NULL,
  148292. &_vq_auxt__44u3__p7_1,
  148293. NULL,
  148294. 0
  148295. };
  148296. static long _vq_quantlist__44u3__p7_2[] = {
  148297. 8,
  148298. 7,
  148299. 9,
  148300. 6,
  148301. 10,
  148302. 5,
  148303. 11,
  148304. 4,
  148305. 12,
  148306. 3,
  148307. 13,
  148308. 2,
  148309. 14,
  148310. 1,
  148311. 15,
  148312. 0,
  148313. 16,
  148314. };
  148315. static long _vq_lengthlist__44u3__p7_2[] = {
  148316. 2, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148317. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148318. 10,10, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  148319. 9,10, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148320. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  148321. 9,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148322. 10,10,10,10,10,10, 7, 8, 8, 9, 8, 9, 9, 9, 9,10,
  148323. 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148324. 9,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9,10,
  148325. 9,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  148326. 9,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  148327. 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,
  148328. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10,
  148329. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  148330. 10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,10,
  148331. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,
  148332. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148333. 9,10,10,10,10,10,10,10,10,10,10,10,11,11,11,10,
  148334. 11,
  148335. };
  148336. static float _vq_quantthresh__44u3__p7_2[] = {
  148337. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  148338. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  148339. };
  148340. static long _vq_quantmap__44u3__p7_2[] = {
  148341. 15, 13, 11, 9, 7, 5, 3, 1,
  148342. 0, 2, 4, 6, 8, 10, 12, 14,
  148343. 16,
  148344. };
  148345. static encode_aux_threshmatch _vq_auxt__44u3__p7_2 = {
  148346. _vq_quantthresh__44u3__p7_2,
  148347. _vq_quantmap__44u3__p7_2,
  148348. 17,
  148349. 17
  148350. };
  148351. static static_codebook _44u3__p7_2 = {
  148352. 2, 289,
  148353. _vq_lengthlist__44u3__p7_2,
  148354. 1, -529530880, 1611661312, 5, 0,
  148355. _vq_quantlist__44u3__p7_2,
  148356. NULL,
  148357. &_vq_auxt__44u3__p7_2,
  148358. NULL,
  148359. 0
  148360. };
  148361. static long _huff_lengthlist__44u3__short[] = {
  148362. 14,14,14,15,13,15,12,16,10, 8, 7, 9, 9, 8,12,16,
  148363. 10, 5, 4, 6, 5, 6, 9,16,14, 8, 6, 8, 7, 8,10,16,
  148364. 14, 7, 4, 6, 3, 5, 8,16,15, 9, 5, 7, 4, 4, 7,16,
  148365. 13,10, 6, 7, 4, 3, 4,13,13,12, 7, 9, 5, 5, 6,12,
  148366. };
  148367. static static_codebook _huff_book__44u3__short = {
  148368. 2, 64,
  148369. _huff_lengthlist__44u3__short,
  148370. 0, 0, 0, 0, 0,
  148371. NULL,
  148372. NULL,
  148373. NULL,
  148374. NULL,
  148375. 0
  148376. };
  148377. static long _huff_lengthlist__44u4__long[] = {
  148378. 3, 8,12,12,13,12,11,13, 5, 4, 6, 7, 8, 8, 9,13,
  148379. 9, 5, 4, 5, 5, 7, 9,13, 9, 6, 5, 6, 6, 7, 8,12,
  148380. 12, 7, 5, 6, 4, 5, 8,13,11, 7, 6, 6, 5, 5, 6,12,
  148381. 10, 8, 8, 7, 7, 5, 3, 8,10,12,13,12,12, 9, 6, 7,
  148382. };
  148383. static static_codebook _huff_book__44u4__long = {
  148384. 2, 64,
  148385. _huff_lengthlist__44u4__long,
  148386. 0, 0, 0, 0, 0,
  148387. NULL,
  148388. NULL,
  148389. NULL,
  148390. NULL,
  148391. 0
  148392. };
  148393. static long _vq_quantlist__44u4__p1_0[] = {
  148394. 1,
  148395. 0,
  148396. 2,
  148397. };
  148398. static long _vq_lengthlist__44u4__p1_0[] = {
  148399. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  148400. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  148401. 11, 8,11,11, 8,11,11,11,13,14,11,15,14, 8,11,11,
  148402. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  148403. 11,11,11,15,14,10,12,14, 8,11,11,11,14,14,11,14,
  148404. 13,
  148405. };
  148406. static float _vq_quantthresh__44u4__p1_0[] = {
  148407. -0.5, 0.5,
  148408. };
  148409. static long _vq_quantmap__44u4__p1_0[] = {
  148410. 1, 0, 2,
  148411. };
  148412. static encode_aux_threshmatch _vq_auxt__44u4__p1_0 = {
  148413. _vq_quantthresh__44u4__p1_0,
  148414. _vq_quantmap__44u4__p1_0,
  148415. 3,
  148416. 3
  148417. };
  148418. static static_codebook _44u4__p1_0 = {
  148419. 4, 81,
  148420. _vq_lengthlist__44u4__p1_0,
  148421. 1, -535822336, 1611661312, 2, 0,
  148422. _vq_quantlist__44u4__p1_0,
  148423. NULL,
  148424. &_vq_auxt__44u4__p1_0,
  148425. NULL,
  148426. 0
  148427. };
  148428. static long _vq_quantlist__44u4__p2_0[] = {
  148429. 1,
  148430. 0,
  148431. 2,
  148432. };
  148433. static long _vq_lengthlist__44u4__p2_0[] = {
  148434. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  148435. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 6, 8,
  148436. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  148437. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 6, 8, 8, 6,
  148438. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  148439. 9,
  148440. };
  148441. static float _vq_quantthresh__44u4__p2_0[] = {
  148442. -0.5, 0.5,
  148443. };
  148444. static long _vq_quantmap__44u4__p2_0[] = {
  148445. 1, 0, 2,
  148446. };
  148447. static encode_aux_threshmatch _vq_auxt__44u4__p2_0 = {
  148448. _vq_quantthresh__44u4__p2_0,
  148449. _vq_quantmap__44u4__p2_0,
  148450. 3,
  148451. 3
  148452. };
  148453. static static_codebook _44u4__p2_0 = {
  148454. 4, 81,
  148455. _vq_lengthlist__44u4__p2_0,
  148456. 1, -535822336, 1611661312, 2, 0,
  148457. _vq_quantlist__44u4__p2_0,
  148458. NULL,
  148459. &_vq_auxt__44u4__p2_0,
  148460. NULL,
  148461. 0
  148462. };
  148463. static long _vq_quantlist__44u4__p3_0[] = {
  148464. 2,
  148465. 1,
  148466. 3,
  148467. 0,
  148468. 4,
  148469. };
  148470. static long _vq_lengthlist__44u4__p3_0[] = {
  148471. 2, 4, 4, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  148472. 10, 9,12,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  148473. 9,11,11, 7, 9, 9,11,11,10,12,11,14,14, 9,10,11,
  148474. 13,14, 5, 7, 7,10,10, 7, 9, 9,11,11, 7, 9, 9,11,
  148475. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  148476. 10,12,12,15,14, 9,11,11,15,14,13,14,14,17,17,12,
  148477. 14,14,16,16, 8,10,10,14,14, 9,11,11,14,15,10,12,
  148478. 12,14,15,12,14,13,16,16,13,14,15,15,18, 4, 7, 7,
  148479. 10,10, 7, 9, 9,12,11, 7, 9, 9,11,12,10,12,11,15,
  148480. 14,10,11,12,14,15, 7, 9, 9,12,12, 9,11,12,13,13,
  148481. 9,11,12,13,13,12,13,13,15,16,11,13,13,15,16, 7,
  148482. 9, 9,12,12, 9,11,10,13,12, 9,11,12,13,14,11,13,
  148483. 12,16,14,12,13,13,15,16,10,12,12,16,15,11,13,13,
  148484. 17,16,11,13,13,17,16,14,15,15,17,17,14,16,16,18,
  148485. 20, 9,11,11,15,16,11,13,12,16,16,11,13,13,16,17,
  148486. 14,15,14,18,16,14,16,16,17,20, 5, 7, 7,10,10, 7,
  148487. 9, 9,12,11, 7, 9,10,11,12,10,12,11,15,15,10,12,
  148488. 12,14,14, 7, 9, 9,12,12, 9,12,11,14,13, 9,10,11,
  148489. 12,13,12,13,14,16,16,11,12,13,14,16, 7, 9, 9,12,
  148490. 12, 9,12,11,13,13, 9,12,11,13,13,11,13,13,16,16,
  148491. 12,13,13,16,15, 9,11,11,16,14,11,13,13,16,16,11,
  148492. 12,13,16,16,14,16,16,17,17,13,14,15,16,17,10,12,
  148493. 12,15,15,11,13,13,16,17,11,13,13,16,16,14,16,15,
  148494. 19,19,14,15,15,17,18, 8,10,10,14,14,10,12,12,15,
  148495. 15,10,12,12,16,16,14,16,15,20,19,13,15,15,17,16,
  148496. 9,12,12,16,16,11,13,13,16,18,11,14,13,16,17,16,
  148497. 17,16,20, 0,15,16,18,18,20, 9,11,11,15,15,11,14,
  148498. 12,17,16,11,13,13,17,17,15,17,15,20,20,14,16,16,
  148499. 17, 0,13,15,14,18,16,14,15,16, 0,18,14,16,16, 0,
  148500. 0,18,16, 0, 0,20,16,18,18, 0, 0,12,14,14,17,18,
  148501. 13,15,14,20,18,14,16,15,19,19,16,20,16, 0,18,16,
  148502. 19,17,19, 0, 8,10,10,14,14,10,12,12,16,15,10,12,
  148503. 12,16,16,13,15,15,18,17,14,16,16,19, 0, 9,11,11,
  148504. 16,15,11,14,13,18,17,11,12,13,17,18,14,17,16,18,
  148505. 18,15,16,17,18,18, 9,12,12,16,16,11,13,13,16,18,
  148506. 11,14,13,17,17,15,16,16,18,20,16,17,17,20,20,12,
  148507. 14,14,18,17,14,16,16, 0,19,13,14,15,18, 0,16, 0,
  148508. 0, 0, 0,16,16, 0,19,20,13,15,14, 0, 0,14,16,16,
  148509. 18,19,14,16,15, 0,20,16,20,18, 0,20,17,20,17, 0,
  148510. 0,
  148511. };
  148512. static float _vq_quantthresh__44u4__p3_0[] = {
  148513. -1.5, -0.5, 0.5, 1.5,
  148514. };
  148515. static long _vq_quantmap__44u4__p3_0[] = {
  148516. 3, 1, 0, 2, 4,
  148517. };
  148518. static encode_aux_threshmatch _vq_auxt__44u4__p3_0 = {
  148519. _vq_quantthresh__44u4__p3_0,
  148520. _vq_quantmap__44u4__p3_0,
  148521. 5,
  148522. 5
  148523. };
  148524. static static_codebook _44u4__p3_0 = {
  148525. 4, 625,
  148526. _vq_lengthlist__44u4__p3_0,
  148527. 1, -533725184, 1611661312, 3, 0,
  148528. _vq_quantlist__44u4__p3_0,
  148529. NULL,
  148530. &_vq_auxt__44u4__p3_0,
  148531. NULL,
  148532. 0
  148533. };
  148534. static long _vq_quantlist__44u4__p4_0[] = {
  148535. 2,
  148536. 1,
  148537. 3,
  148538. 0,
  148539. 4,
  148540. };
  148541. static long _vq_lengthlist__44u4__p4_0[] = {
  148542. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  148543. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  148544. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  148545. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  148546. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  148547. 9,10,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  148548. 12,12,13,14, 9, 9,10,12,12, 9,10,10,13,13, 9,10,
  148549. 10,12,13,11,12,12,14,13,11,12,12,14,14, 5, 7, 7,
  148550. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  148551. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  148552. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  148553. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  148554. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  148555. 13,14,10,11,11,14,13,12,12,13,12,15,12,13,13,15,
  148556. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  148557. 12,13,11,15,13,13,13,13,15,15, 5, 7, 7, 9, 9, 7,
  148558. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  148559. 11,12,13, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  148560. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  148561. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  148562. 11,12,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  148563. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  148564. 11,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  148565. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  148566. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  148567. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,13,13,
  148568. 13,14,14,16,13,13,13,15,15, 9,10,10,13,13,10,11,
  148569. 10,14,13,10,11,11,13,14,12,14,13,16,14,12,13,13,
  148570. 14,15,11,12,12,15,14,11,12,13,14,15,12,13,13,16,
  148571. 15,14,12,15,12,16,14,15,15,16,16,11,12,12,14,14,
  148572. 11,13,12,15,14,12,13,13,15,16,13,15,13,17,13,14,
  148573. 15,15,16,17, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  148574. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  148575. 13,12,10,11,11,14,13,10,10,11,13,14,13,13,13,15,
  148576. 15,12,13,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  148577. 10,11,11,14,14,13,13,13,15,15,13,14,13,16,14,11,
  148578. 12,12,15,14,12,13,13,16,15,11,12,13,14,15,14,15,
  148579. 15,17,16,13,13,15,13,16,11,12,13,14,15,13,13,13,
  148580. 15,16,11,13,12,15,14,14,15,15,16,16,14,15,12,17,
  148581. 13,
  148582. };
  148583. static float _vq_quantthresh__44u4__p4_0[] = {
  148584. -1.5, -0.5, 0.5, 1.5,
  148585. };
  148586. static long _vq_quantmap__44u4__p4_0[] = {
  148587. 3, 1, 0, 2, 4,
  148588. };
  148589. static encode_aux_threshmatch _vq_auxt__44u4__p4_0 = {
  148590. _vq_quantthresh__44u4__p4_0,
  148591. _vq_quantmap__44u4__p4_0,
  148592. 5,
  148593. 5
  148594. };
  148595. static static_codebook _44u4__p4_0 = {
  148596. 4, 625,
  148597. _vq_lengthlist__44u4__p4_0,
  148598. 1, -533725184, 1611661312, 3, 0,
  148599. _vq_quantlist__44u4__p4_0,
  148600. NULL,
  148601. &_vq_auxt__44u4__p4_0,
  148602. NULL,
  148603. 0
  148604. };
  148605. static long _vq_quantlist__44u4__p5_0[] = {
  148606. 4,
  148607. 3,
  148608. 5,
  148609. 2,
  148610. 6,
  148611. 1,
  148612. 7,
  148613. 0,
  148614. 8,
  148615. };
  148616. static long _vq_lengthlist__44u4__p5_0[] = {
  148617. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  148618. 10, 9, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  148619. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,11, 7, 8, 8,
  148620. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  148621. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  148622. 12,
  148623. };
  148624. static float _vq_quantthresh__44u4__p5_0[] = {
  148625. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148626. };
  148627. static long _vq_quantmap__44u4__p5_0[] = {
  148628. 7, 5, 3, 1, 0, 2, 4, 6,
  148629. 8,
  148630. };
  148631. static encode_aux_threshmatch _vq_auxt__44u4__p5_0 = {
  148632. _vq_quantthresh__44u4__p5_0,
  148633. _vq_quantmap__44u4__p5_0,
  148634. 9,
  148635. 9
  148636. };
  148637. static static_codebook _44u4__p5_0 = {
  148638. 2, 81,
  148639. _vq_lengthlist__44u4__p5_0,
  148640. 1, -531628032, 1611661312, 4, 0,
  148641. _vq_quantlist__44u4__p5_0,
  148642. NULL,
  148643. &_vq_auxt__44u4__p5_0,
  148644. NULL,
  148645. 0
  148646. };
  148647. static long _vq_quantlist__44u4__p6_0[] = {
  148648. 6,
  148649. 5,
  148650. 7,
  148651. 4,
  148652. 8,
  148653. 3,
  148654. 9,
  148655. 2,
  148656. 10,
  148657. 1,
  148658. 11,
  148659. 0,
  148660. 12,
  148661. };
  148662. static long _vq_lengthlist__44u4__p6_0[] = {
  148663. 1, 4, 4, 6, 6, 8, 8, 9, 9,11,10,13,13, 4, 6, 5,
  148664. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  148665. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  148666. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  148667. 15, 8, 9, 9,11,10,11,11,12,12,13,13,16,16, 8, 9,
  148668. 9,10,10,11,11,12,12,13,13,16,16,10,10,10,12,11,
  148669. 12,12,13,13,14,14,16,16,10,10,10,11,12,12,12,13,
  148670. 13,13,14,16,17,11,12,11,12,12,13,13,14,14,15,14,
  148671. 18,17,11,11,12,12,12,13,13,14,14,14,15,19,18,14,
  148672. 15,14,15,15,17,16,17,17,17,17,21, 0,14,15,15,16,
  148673. 16,16,16,17,17,18,17,20,21,
  148674. };
  148675. static float _vq_quantthresh__44u4__p6_0[] = {
  148676. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  148677. 12.5, 17.5, 22.5, 27.5,
  148678. };
  148679. static long _vq_quantmap__44u4__p6_0[] = {
  148680. 11, 9, 7, 5, 3, 1, 0, 2,
  148681. 4, 6, 8, 10, 12,
  148682. };
  148683. static encode_aux_threshmatch _vq_auxt__44u4__p6_0 = {
  148684. _vq_quantthresh__44u4__p6_0,
  148685. _vq_quantmap__44u4__p6_0,
  148686. 13,
  148687. 13
  148688. };
  148689. static static_codebook _44u4__p6_0 = {
  148690. 2, 169,
  148691. _vq_lengthlist__44u4__p6_0,
  148692. 1, -526516224, 1616117760, 4, 0,
  148693. _vq_quantlist__44u4__p6_0,
  148694. NULL,
  148695. &_vq_auxt__44u4__p6_0,
  148696. NULL,
  148697. 0
  148698. };
  148699. static long _vq_quantlist__44u4__p6_1[] = {
  148700. 2,
  148701. 1,
  148702. 3,
  148703. 0,
  148704. 4,
  148705. };
  148706. static long _vq_lengthlist__44u4__p6_1[] = {
  148707. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  148708. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  148709. };
  148710. static float _vq_quantthresh__44u4__p6_1[] = {
  148711. -1.5, -0.5, 0.5, 1.5,
  148712. };
  148713. static long _vq_quantmap__44u4__p6_1[] = {
  148714. 3, 1, 0, 2, 4,
  148715. };
  148716. static encode_aux_threshmatch _vq_auxt__44u4__p6_1 = {
  148717. _vq_quantthresh__44u4__p6_1,
  148718. _vq_quantmap__44u4__p6_1,
  148719. 5,
  148720. 5
  148721. };
  148722. static static_codebook _44u4__p6_1 = {
  148723. 2, 25,
  148724. _vq_lengthlist__44u4__p6_1,
  148725. 1, -533725184, 1611661312, 3, 0,
  148726. _vq_quantlist__44u4__p6_1,
  148727. NULL,
  148728. &_vq_auxt__44u4__p6_1,
  148729. NULL,
  148730. 0
  148731. };
  148732. static long _vq_quantlist__44u4__p7_0[] = {
  148733. 6,
  148734. 5,
  148735. 7,
  148736. 4,
  148737. 8,
  148738. 3,
  148739. 9,
  148740. 2,
  148741. 10,
  148742. 1,
  148743. 11,
  148744. 0,
  148745. 12,
  148746. };
  148747. static long _vq_lengthlist__44u4__p7_0[] = {
  148748. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 3,12,11,
  148749. 12,12,12,12,12,12,12,12,12,12, 4,11,10,12,12,12,
  148750. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148751. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148752. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148753. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148754. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148755. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148756. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148757. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148758. 11,11,11,11,11,11,11,11,11,
  148759. };
  148760. static float _vq_quantthresh__44u4__p7_0[] = {
  148761. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  148762. 637.5, 892.5, 1147.5, 1402.5,
  148763. };
  148764. static long _vq_quantmap__44u4__p7_0[] = {
  148765. 11, 9, 7, 5, 3, 1, 0, 2,
  148766. 4, 6, 8, 10, 12,
  148767. };
  148768. static encode_aux_threshmatch _vq_auxt__44u4__p7_0 = {
  148769. _vq_quantthresh__44u4__p7_0,
  148770. _vq_quantmap__44u4__p7_0,
  148771. 13,
  148772. 13
  148773. };
  148774. static static_codebook _44u4__p7_0 = {
  148775. 2, 169,
  148776. _vq_lengthlist__44u4__p7_0,
  148777. 1, -514332672, 1627381760, 4, 0,
  148778. _vq_quantlist__44u4__p7_0,
  148779. NULL,
  148780. &_vq_auxt__44u4__p7_0,
  148781. NULL,
  148782. 0
  148783. };
  148784. static long _vq_quantlist__44u4__p7_1[] = {
  148785. 7,
  148786. 6,
  148787. 8,
  148788. 5,
  148789. 9,
  148790. 4,
  148791. 10,
  148792. 3,
  148793. 11,
  148794. 2,
  148795. 12,
  148796. 1,
  148797. 13,
  148798. 0,
  148799. 14,
  148800. };
  148801. static long _vq_lengthlist__44u4__p7_1[] = {
  148802. 1, 4, 4, 6, 6, 7, 7, 9, 8,10, 8,10, 9,11,11, 4,
  148803. 7, 6, 8, 7, 9, 9,10,10,11,10,11,10,12,10, 4, 6,
  148804. 7, 8, 8, 9, 9,10,10,11,11,11,11,12,12, 6, 8, 8,
  148805. 10, 9,11,10,12,11,12,12,12,12,13,13, 6, 8, 8,10,
  148806. 10,10,11,11,11,12,12,13,12,13,13, 8, 9, 9,11,11,
  148807. 12,11,12,12,13,13,13,13,13,13, 8, 9, 9,11,11,11,
  148808. 12,12,12,13,13,13,13,13,13, 9,10,10,12,11,13,13,
  148809. 13,13,14,13,13,14,14,14, 9,10,11,11,12,12,13,13,
  148810. 13,13,13,14,15,14,14,10,11,11,12,12,13,13,14,14,
  148811. 14,14,14,15,16,16,10,11,11,12,13,13,13,13,15,14,
  148812. 14,15,16,15,16,10,12,12,13,13,14,14,14,15,15,15,
  148813. 15,15,15,16,11,12,12,13,13,14,14,14,15,15,15,16,
  148814. 15,17,16,11,12,12,13,13,13,15,15,14,16,16,16,16,
  148815. 16,17,11,12,12,13,13,14,14,15,14,15,15,17,17,16,
  148816. 16,
  148817. };
  148818. static float _vq_quantthresh__44u4__p7_1[] = {
  148819. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  148820. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  148821. };
  148822. static long _vq_quantmap__44u4__p7_1[] = {
  148823. 13, 11, 9, 7, 5, 3, 1, 0,
  148824. 2, 4, 6, 8, 10, 12, 14,
  148825. };
  148826. static encode_aux_threshmatch _vq_auxt__44u4__p7_1 = {
  148827. _vq_quantthresh__44u4__p7_1,
  148828. _vq_quantmap__44u4__p7_1,
  148829. 15,
  148830. 15
  148831. };
  148832. static static_codebook _44u4__p7_1 = {
  148833. 2, 225,
  148834. _vq_lengthlist__44u4__p7_1,
  148835. 1, -522338304, 1620115456, 4, 0,
  148836. _vq_quantlist__44u4__p7_1,
  148837. NULL,
  148838. &_vq_auxt__44u4__p7_1,
  148839. NULL,
  148840. 0
  148841. };
  148842. static long _vq_quantlist__44u4__p7_2[] = {
  148843. 8,
  148844. 7,
  148845. 9,
  148846. 6,
  148847. 10,
  148848. 5,
  148849. 11,
  148850. 4,
  148851. 12,
  148852. 3,
  148853. 13,
  148854. 2,
  148855. 14,
  148856. 1,
  148857. 15,
  148858. 0,
  148859. 16,
  148860. };
  148861. static long _vq_lengthlist__44u4__p7_2[] = {
  148862. 2, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148863. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148864. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148865. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148866. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  148867. 9,10, 9,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148868. 10,10,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148869. 9,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  148870. 10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  148871. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,
  148872. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  148873. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  148874. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  148875. 10,10,10,10,10,10,10,10,10,11,10,10,10, 9, 9, 9,
  148876. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  148877. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  148878. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148879. 9,10, 9,10,10,10,10,10,10,10,10,10,10,11,10,10,
  148880. 10,
  148881. };
  148882. static float _vq_quantthresh__44u4__p7_2[] = {
  148883. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  148884. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  148885. };
  148886. static long _vq_quantmap__44u4__p7_2[] = {
  148887. 15, 13, 11, 9, 7, 5, 3, 1,
  148888. 0, 2, 4, 6, 8, 10, 12, 14,
  148889. 16,
  148890. };
  148891. static encode_aux_threshmatch _vq_auxt__44u4__p7_2 = {
  148892. _vq_quantthresh__44u4__p7_2,
  148893. _vq_quantmap__44u4__p7_2,
  148894. 17,
  148895. 17
  148896. };
  148897. static static_codebook _44u4__p7_2 = {
  148898. 2, 289,
  148899. _vq_lengthlist__44u4__p7_2,
  148900. 1, -529530880, 1611661312, 5, 0,
  148901. _vq_quantlist__44u4__p7_2,
  148902. NULL,
  148903. &_vq_auxt__44u4__p7_2,
  148904. NULL,
  148905. 0
  148906. };
  148907. static long _huff_lengthlist__44u4__short[] = {
  148908. 14,17,15,17,16,14,13,16,10, 7, 7,10,13,10,15,16,
  148909. 9, 4, 4, 6, 5, 7, 9,16,12, 8, 7, 8, 8, 8,11,16,
  148910. 14, 7, 4, 6, 3, 5, 8,15,13, 8, 5, 7, 4, 5, 7,16,
  148911. 12, 9, 6, 8, 3, 3, 5,16,14,13, 7,10, 5, 5, 7,15,
  148912. };
  148913. static static_codebook _huff_book__44u4__short = {
  148914. 2, 64,
  148915. _huff_lengthlist__44u4__short,
  148916. 0, 0, 0, 0, 0,
  148917. NULL,
  148918. NULL,
  148919. NULL,
  148920. NULL,
  148921. 0
  148922. };
  148923. static long _huff_lengthlist__44u5__long[] = {
  148924. 3, 8,13,12,14,12,16,11,13,14, 5, 4, 5, 6, 7, 8,
  148925. 10, 9,12,15,10, 5, 5, 5, 6, 8, 9, 9,13,15,10, 5,
  148926. 5, 6, 6, 7, 8, 8,11,13,12, 7, 5, 6, 4, 6, 7, 7,
  148927. 11,14,11, 7, 7, 6, 6, 6, 7, 6,10,14,14, 9, 8, 8,
  148928. 6, 7, 7, 7,11,16,11, 8, 8, 7, 6, 6, 7, 4, 7,12,
  148929. 10,10,12,10,10, 9,10, 5, 6, 9,10,12,15,13,14,14,
  148930. 14, 8, 7, 8,
  148931. };
  148932. static static_codebook _huff_book__44u5__long = {
  148933. 2, 100,
  148934. _huff_lengthlist__44u5__long,
  148935. 0, 0, 0, 0, 0,
  148936. NULL,
  148937. NULL,
  148938. NULL,
  148939. NULL,
  148940. 0
  148941. };
  148942. static long _vq_quantlist__44u5__p1_0[] = {
  148943. 1,
  148944. 0,
  148945. 2,
  148946. };
  148947. static long _vq_lengthlist__44u5__p1_0[] = {
  148948. 1, 4, 4, 5, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  148949. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  148950. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  148951. 10,13,11,10,13,13, 4, 8, 8, 8,11,10, 8,10,10, 7,
  148952. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  148953. 12,
  148954. };
  148955. static float _vq_quantthresh__44u5__p1_0[] = {
  148956. -0.5, 0.5,
  148957. };
  148958. static long _vq_quantmap__44u5__p1_0[] = {
  148959. 1, 0, 2,
  148960. };
  148961. static encode_aux_threshmatch _vq_auxt__44u5__p1_0 = {
  148962. _vq_quantthresh__44u5__p1_0,
  148963. _vq_quantmap__44u5__p1_0,
  148964. 3,
  148965. 3
  148966. };
  148967. static static_codebook _44u5__p1_0 = {
  148968. 4, 81,
  148969. _vq_lengthlist__44u5__p1_0,
  148970. 1, -535822336, 1611661312, 2, 0,
  148971. _vq_quantlist__44u5__p1_0,
  148972. NULL,
  148973. &_vq_auxt__44u5__p1_0,
  148974. NULL,
  148975. 0
  148976. };
  148977. static long _vq_quantlist__44u5__p2_0[] = {
  148978. 1,
  148979. 0,
  148980. 2,
  148981. };
  148982. static long _vq_lengthlist__44u5__p2_0[] = {
  148983. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  148984. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  148985. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  148986. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  148987. 8, 7, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  148988. 9,
  148989. };
  148990. static float _vq_quantthresh__44u5__p2_0[] = {
  148991. -0.5, 0.5,
  148992. };
  148993. static long _vq_quantmap__44u5__p2_0[] = {
  148994. 1, 0, 2,
  148995. };
  148996. static encode_aux_threshmatch _vq_auxt__44u5__p2_0 = {
  148997. _vq_quantthresh__44u5__p2_0,
  148998. _vq_quantmap__44u5__p2_0,
  148999. 3,
  149000. 3
  149001. };
  149002. static static_codebook _44u5__p2_0 = {
  149003. 4, 81,
  149004. _vq_lengthlist__44u5__p2_0,
  149005. 1, -535822336, 1611661312, 2, 0,
  149006. _vq_quantlist__44u5__p2_0,
  149007. NULL,
  149008. &_vq_auxt__44u5__p2_0,
  149009. NULL,
  149010. 0
  149011. };
  149012. static long _vq_quantlist__44u5__p3_0[] = {
  149013. 2,
  149014. 1,
  149015. 3,
  149016. 0,
  149017. 4,
  149018. };
  149019. static long _vq_lengthlist__44u5__p3_0[] = {
  149020. 2, 4, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  149021. 10, 9,13,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  149022. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  149023. 13,14, 5, 7, 7, 9,10, 7, 9, 8,11,11, 7, 9, 9,11,
  149024. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,13,13,
  149025. 10,11,11,15,14, 9,11,11,14,14,13,14,14,17,16,12,
  149026. 13,13,15,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  149027. 11,14,15,12,14,13,16,16,13,15,14,15,17, 5, 7, 7,
  149028. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,
  149029. 14,10,11,12,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  149030. 9,11,11,13,13,12,13,13,15,16,11,12,13,15,16, 6,
  149031. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,14,11,13,
  149032. 12,16,14,11,13,13,16,17,10,12,11,15,15,11,13,13,
  149033. 16,16,11,13,13,17,16,14,15,15,17,17,14,16,16,17,
  149034. 18, 9,11,11,14,15,10,12,12,15,15,11,13,13,16,17,
  149035. 13,15,13,17,15,14,15,16,18, 0, 5, 7, 7,10,10, 7,
  149036. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  149037. 12,14,15, 6, 9, 9,12,11, 9,11,11,13,13, 8,10,11,
  149038. 12,13,11,13,13,16,15,11,12,13,14,15, 7, 9, 9,11,
  149039. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,16,
  149040. 11,13,13,15,14, 9,11,11,15,14,11,13,13,17,15,10,
  149041. 12,12,15,15,14,16,16,17,17,13,13,15,15,17,10,11,
  149042. 12,15,15,11,13,13,16,16,11,13,13,15,15,14,15,15,
  149043. 18,18,14,15,15,17,17, 8,10,10,13,13,10,12,11,15,
  149044. 15,10,11,12,15,15,14,15,15,18,18,13,14,14,18,18,
  149045. 9,11,11,15,16,11,13,13,17,17,11,13,13,16,16,15,
  149046. 15,16,17, 0,14,15,17, 0, 0, 9,11,11,15,15,10,13,
  149047. 12,18,16,11,13,13,15,16,14,16,15,20,20,14,15,16,
  149048. 17, 0,13,14,14,20,16,14,15,16,19,18,14,15,15,19,
  149049. 0,18,16, 0,20,20,16,18,18, 0, 0,12,14,14,18,18,
  149050. 13,15,14,18,16,14,15,16,18,20,16,19,16, 0,17,17,
  149051. 18,18,19, 0, 8,10,10,14,14,10,11,11,14,15,10,11,
  149052. 12,15,15,13,15,14,19,17,13,15,15,17, 0, 9,11,11,
  149053. 16,15,11,13,13,16,16,10,12,13,15,17,14,16,16,18,
  149054. 18,14,15,15,18, 0, 9,11,11,15,15,11,13,13,16,17,
  149055. 11,13,13,18,17,14,18,16,18,18,15,17,17,18, 0,12,
  149056. 14,14,18,18,14,15,15,20, 0,13,14,15,17, 0,16,18,
  149057. 17, 0, 0,16,16, 0,17,20,12,14,14,18,18,14,16,15,
  149058. 0,18,14,16,15,18, 0,16,19,17, 0, 0,17,18,16, 0,
  149059. 0,
  149060. };
  149061. static float _vq_quantthresh__44u5__p3_0[] = {
  149062. -1.5, -0.5, 0.5, 1.5,
  149063. };
  149064. static long _vq_quantmap__44u5__p3_0[] = {
  149065. 3, 1, 0, 2, 4,
  149066. };
  149067. static encode_aux_threshmatch _vq_auxt__44u5__p3_0 = {
  149068. _vq_quantthresh__44u5__p3_0,
  149069. _vq_quantmap__44u5__p3_0,
  149070. 5,
  149071. 5
  149072. };
  149073. static static_codebook _44u5__p3_0 = {
  149074. 4, 625,
  149075. _vq_lengthlist__44u5__p3_0,
  149076. 1, -533725184, 1611661312, 3, 0,
  149077. _vq_quantlist__44u5__p3_0,
  149078. NULL,
  149079. &_vq_auxt__44u5__p3_0,
  149080. NULL,
  149081. 0
  149082. };
  149083. static long _vq_quantlist__44u5__p4_0[] = {
  149084. 2,
  149085. 1,
  149086. 3,
  149087. 0,
  149088. 4,
  149089. };
  149090. static long _vq_lengthlist__44u5__p4_0[] = {
  149091. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  149092. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  149093. 8,10,10, 6, 7, 8, 9,10, 9,10,10,11,12, 9, 9,10,
  149094. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  149095. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,12,11,
  149096. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  149097. 11,12,13,14, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  149098. 10,12,12,11,12,11,14,13,11,12,12,13,13, 5, 7, 7,
  149099. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  149100. 12, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,10,11,
  149101. 8, 9, 9,11,11,10,10,11,11,13,10,11,11,12,13, 6,
  149102. 7, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  149103. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  149104. 12,13,10,11,11,13,13,12,11,13,12,15,12,13,13,14,
  149105. 15, 9,10,10,12,12, 9,11,10,13,12,10,11,11,13,13,
  149106. 11,13,11,14,12,12,13,13,14,15, 5, 7, 7, 9, 9, 7,
  149107. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  149108. 10,12,12, 6, 8, 7,10,10, 8, 9, 9,11,11, 7, 8, 9,
  149109. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  149110. 10, 8, 9, 9,11,11, 8, 9, 8,11,10,10,11,11,13,12,
  149111. 10,11,10,13,11, 9,10,10,12,12,10,11,11,13,12, 9,
  149112. 10,10,12,13,12,13,13,14,15,11,11,13,12,14, 9,10,
  149113. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,13,13,
  149114. 14,14,12,13,11,14,12, 8, 9, 9,12,12, 9,10,10,12,
  149115. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,14,13,
  149116. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  149117. 12,13,14,15,12,13,13,15,14, 9,10,10,12,12,10,11,
  149118. 10,13,12,10,11,11,12,13,12,13,12,15,13,12,13,13,
  149119. 14,15,11,12,12,14,13,11,12,12,14,15,12,13,13,15,
  149120. 14,13,12,14,12,16,13,14,14,15,15,11,11,12,14,14,
  149121. 11,12,11,14,13,12,13,13,14,15,13,14,12,16,12,14,
  149122. 14,15,16,16, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  149123. 10,12,13,11,12,12,13,13,12,12,13,14,14, 9,10,10,
  149124. 12,12,10,11,10,13,12,10,10,11,12,13,12,13,13,15,
  149125. 14,12,12,13,13,15, 9,10,10,12,13,10,11,11,12,13,
  149126. 10,11,11,13,13,12,13,13,14,15,12,13,12,15,14,11,
  149127. 12,11,14,13,12,13,13,15,14,11,11,12,13,14,14,15,
  149128. 14,16,15,13,12,14,13,16,11,12,12,13,14,12,13,13,
  149129. 14,15,11,12,11,14,14,14,14,14,15,16,13,15,12,16,
  149130. 12,
  149131. };
  149132. static float _vq_quantthresh__44u5__p4_0[] = {
  149133. -1.5, -0.5, 0.5, 1.5,
  149134. };
  149135. static long _vq_quantmap__44u5__p4_0[] = {
  149136. 3, 1, 0, 2, 4,
  149137. };
  149138. static encode_aux_threshmatch _vq_auxt__44u5__p4_0 = {
  149139. _vq_quantthresh__44u5__p4_0,
  149140. _vq_quantmap__44u5__p4_0,
  149141. 5,
  149142. 5
  149143. };
  149144. static static_codebook _44u5__p4_0 = {
  149145. 4, 625,
  149146. _vq_lengthlist__44u5__p4_0,
  149147. 1, -533725184, 1611661312, 3, 0,
  149148. _vq_quantlist__44u5__p4_0,
  149149. NULL,
  149150. &_vq_auxt__44u5__p4_0,
  149151. NULL,
  149152. 0
  149153. };
  149154. static long _vq_quantlist__44u5__p5_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__p5_0[] = {
  149166. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  149167. 11,10, 3, 5, 5, 7, 8, 8, 8,10,11, 6, 8, 7,10, 9,
  149168. 10,10,11,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  149169. 10,10,11,11,13,12, 8, 8, 9, 9,10,11,11,12,13,10,
  149170. 11,10,12,11,13,12,14,14,10,10,11,11,12,12,13,14,
  149171. 14,
  149172. };
  149173. static float _vq_quantthresh__44u5__p5_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__p5_0[] = {
  149177. 7, 5, 3, 1, 0, 2, 4, 6,
  149178. 8,
  149179. };
  149180. static encode_aux_threshmatch _vq_auxt__44u5__p5_0 = {
  149181. _vq_quantthresh__44u5__p5_0,
  149182. _vq_quantmap__44u5__p5_0,
  149183. 9,
  149184. 9
  149185. };
  149186. static static_codebook _44u5__p5_0 = {
  149187. 2, 81,
  149188. _vq_lengthlist__44u5__p5_0,
  149189. 1, -531628032, 1611661312, 4, 0,
  149190. _vq_quantlist__44u5__p5_0,
  149191. NULL,
  149192. &_vq_auxt__44u5__p5_0,
  149193. NULL,
  149194. 0
  149195. };
  149196. static long _vq_quantlist__44u5__p6_0[] = {
  149197. 4,
  149198. 3,
  149199. 5,
  149200. 2,
  149201. 6,
  149202. 1,
  149203. 7,
  149204. 0,
  149205. 8,
  149206. };
  149207. static long _vq_lengthlist__44u5__p6_0[] = {
  149208. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  149209. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  149210. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  149211. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  149212. 9, 9,10,10,11,10,11,11, 9, 9, 9,10,10,11,10,11,
  149213. 11,
  149214. };
  149215. static float _vq_quantthresh__44u5__p6_0[] = {
  149216. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149217. };
  149218. static long _vq_quantmap__44u5__p6_0[] = {
  149219. 7, 5, 3, 1, 0, 2, 4, 6,
  149220. 8,
  149221. };
  149222. static encode_aux_threshmatch _vq_auxt__44u5__p6_0 = {
  149223. _vq_quantthresh__44u5__p6_0,
  149224. _vq_quantmap__44u5__p6_0,
  149225. 9,
  149226. 9
  149227. };
  149228. static static_codebook _44u5__p6_0 = {
  149229. 2, 81,
  149230. _vq_lengthlist__44u5__p6_0,
  149231. 1, -531628032, 1611661312, 4, 0,
  149232. _vq_quantlist__44u5__p6_0,
  149233. NULL,
  149234. &_vq_auxt__44u5__p6_0,
  149235. NULL,
  149236. 0
  149237. };
  149238. static long _vq_quantlist__44u5__p7_0[] = {
  149239. 1,
  149240. 0,
  149241. 2,
  149242. };
  149243. static long _vq_lengthlist__44u5__p7_0[] = {
  149244. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,11,10, 7,
  149245. 11,10, 5, 9, 9, 7,10,10, 8,10,11, 4, 9, 9, 9,12,
  149246. 12, 9,12,12, 8,12,12,11,12,12,10,12,13, 7,12,12,
  149247. 11,12,12,10,12,13, 4, 9, 9, 9,12,12, 9,12,12, 7,
  149248. 12,11,10,13,13,11,12,12, 7,12,12,10,13,13,11,12,
  149249. 12,
  149250. };
  149251. static float _vq_quantthresh__44u5__p7_0[] = {
  149252. -5.5, 5.5,
  149253. };
  149254. static long _vq_quantmap__44u5__p7_0[] = {
  149255. 1, 0, 2,
  149256. };
  149257. static encode_aux_threshmatch _vq_auxt__44u5__p7_0 = {
  149258. _vq_quantthresh__44u5__p7_0,
  149259. _vq_quantmap__44u5__p7_0,
  149260. 3,
  149261. 3
  149262. };
  149263. static static_codebook _44u5__p7_0 = {
  149264. 4, 81,
  149265. _vq_lengthlist__44u5__p7_0,
  149266. 1, -529137664, 1618345984, 2, 0,
  149267. _vq_quantlist__44u5__p7_0,
  149268. NULL,
  149269. &_vq_auxt__44u5__p7_0,
  149270. NULL,
  149271. 0
  149272. };
  149273. static long _vq_quantlist__44u5__p7_1[] = {
  149274. 5,
  149275. 4,
  149276. 6,
  149277. 3,
  149278. 7,
  149279. 2,
  149280. 8,
  149281. 1,
  149282. 9,
  149283. 0,
  149284. 10,
  149285. };
  149286. static long _vq_lengthlist__44u5__p7_1[] = {
  149287. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  149288. 8, 8, 9, 8, 8, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 8,
  149289. 9, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  149290. 8, 9, 9, 9, 9, 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  149291. 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  149292. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  149293. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  149294. 9, 9, 9, 9, 9,10,10,10,10,
  149295. };
  149296. static float _vq_quantthresh__44u5__p7_1[] = {
  149297. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149298. 3.5, 4.5,
  149299. };
  149300. static long _vq_quantmap__44u5__p7_1[] = {
  149301. 9, 7, 5, 3, 1, 0, 2, 4,
  149302. 6, 8, 10,
  149303. };
  149304. static encode_aux_threshmatch _vq_auxt__44u5__p7_1 = {
  149305. _vq_quantthresh__44u5__p7_1,
  149306. _vq_quantmap__44u5__p7_1,
  149307. 11,
  149308. 11
  149309. };
  149310. static static_codebook _44u5__p7_1 = {
  149311. 2, 121,
  149312. _vq_lengthlist__44u5__p7_1,
  149313. 1, -531365888, 1611661312, 4, 0,
  149314. _vq_quantlist__44u5__p7_1,
  149315. NULL,
  149316. &_vq_auxt__44u5__p7_1,
  149317. NULL,
  149318. 0
  149319. };
  149320. static long _vq_quantlist__44u5__p8_0[] = {
  149321. 5,
  149322. 4,
  149323. 6,
  149324. 3,
  149325. 7,
  149326. 2,
  149327. 8,
  149328. 1,
  149329. 9,
  149330. 0,
  149331. 10,
  149332. };
  149333. static long _vq_lengthlist__44u5__p8_0[] = {
  149334. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  149335. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  149336. 11, 6, 8, 7, 9, 9,10,10,11,11,13,12, 6, 8, 8, 9,
  149337. 9,10,10,11,11,12,13, 8, 9, 9,10,10,12,12,13,12,
  149338. 14,13, 8, 9, 9,10,10,12,12,13,13,14,14, 9,11,11,
  149339. 12,12,13,13,14,14,15,14, 9,11,11,12,12,13,13,14,
  149340. 14,15,14,11,12,12,13,13,14,14,15,14,15,14,11,11,
  149341. 12,13,13,14,14,14,14,15,15,
  149342. };
  149343. static float _vq_quantthresh__44u5__p8_0[] = {
  149344. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  149345. 38.5, 49.5,
  149346. };
  149347. static long _vq_quantmap__44u5__p8_0[] = {
  149348. 9, 7, 5, 3, 1, 0, 2, 4,
  149349. 6, 8, 10,
  149350. };
  149351. static encode_aux_threshmatch _vq_auxt__44u5__p8_0 = {
  149352. _vq_quantthresh__44u5__p8_0,
  149353. _vq_quantmap__44u5__p8_0,
  149354. 11,
  149355. 11
  149356. };
  149357. static static_codebook _44u5__p8_0 = {
  149358. 2, 121,
  149359. _vq_lengthlist__44u5__p8_0,
  149360. 1, -524582912, 1618345984, 4, 0,
  149361. _vq_quantlist__44u5__p8_0,
  149362. NULL,
  149363. &_vq_auxt__44u5__p8_0,
  149364. NULL,
  149365. 0
  149366. };
  149367. static long _vq_quantlist__44u5__p8_1[] = {
  149368. 5,
  149369. 4,
  149370. 6,
  149371. 3,
  149372. 7,
  149373. 2,
  149374. 8,
  149375. 1,
  149376. 9,
  149377. 0,
  149378. 10,
  149379. };
  149380. static long _vq_lengthlist__44u5__p8_1[] = {
  149381. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 6,
  149382. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  149383. 8, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 6, 6, 7, 7,
  149384. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  149385. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8,
  149386. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  149387. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  149388. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  149389. };
  149390. static float _vq_quantthresh__44u5__p8_1[] = {
  149391. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149392. 3.5, 4.5,
  149393. };
  149394. static long _vq_quantmap__44u5__p8_1[] = {
  149395. 9, 7, 5, 3, 1, 0, 2, 4,
  149396. 6, 8, 10,
  149397. };
  149398. static encode_aux_threshmatch _vq_auxt__44u5__p8_1 = {
  149399. _vq_quantthresh__44u5__p8_1,
  149400. _vq_quantmap__44u5__p8_1,
  149401. 11,
  149402. 11
  149403. };
  149404. static static_codebook _44u5__p8_1 = {
  149405. 2, 121,
  149406. _vq_lengthlist__44u5__p8_1,
  149407. 1, -531365888, 1611661312, 4, 0,
  149408. _vq_quantlist__44u5__p8_1,
  149409. NULL,
  149410. &_vq_auxt__44u5__p8_1,
  149411. NULL,
  149412. 0
  149413. };
  149414. static long _vq_quantlist__44u5__p9_0[] = {
  149415. 6,
  149416. 5,
  149417. 7,
  149418. 4,
  149419. 8,
  149420. 3,
  149421. 9,
  149422. 2,
  149423. 10,
  149424. 1,
  149425. 11,
  149426. 0,
  149427. 12,
  149428. };
  149429. static long _vq_lengthlist__44u5__p9_0[] = {
  149430. 1, 3, 2,12,10,13,13,13,13,13,13,13,13, 4, 9, 9,
  149431. 13,13,13,13,13,13,13,13,13,13, 5,10, 9,13,13,13,
  149432. 13,13,13,13,13,13,13,12,13,13,13,13,13,13,13,13,
  149433. 13,13,13,13,11,13,13,13,13,13,13,13,13,13,13,13,
  149434. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149435. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149436. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149437. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149438. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,12,12,
  149439. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  149440. 12,12,12,12,12,12,12,12,12,
  149441. };
  149442. static float _vq_quantthresh__44u5__p9_0[] = {
  149443. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  149444. 637.5, 892.5, 1147.5, 1402.5,
  149445. };
  149446. static long _vq_quantmap__44u5__p9_0[] = {
  149447. 11, 9, 7, 5, 3, 1, 0, 2,
  149448. 4, 6, 8, 10, 12,
  149449. };
  149450. static encode_aux_threshmatch _vq_auxt__44u5__p9_0 = {
  149451. _vq_quantthresh__44u5__p9_0,
  149452. _vq_quantmap__44u5__p9_0,
  149453. 13,
  149454. 13
  149455. };
  149456. static static_codebook _44u5__p9_0 = {
  149457. 2, 169,
  149458. _vq_lengthlist__44u5__p9_0,
  149459. 1, -514332672, 1627381760, 4, 0,
  149460. _vq_quantlist__44u5__p9_0,
  149461. NULL,
  149462. &_vq_auxt__44u5__p9_0,
  149463. NULL,
  149464. 0
  149465. };
  149466. static long _vq_quantlist__44u5__p9_1[] = {
  149467. 7,
  149468. 6,
  149469. 8,
  149470. 5,
  149471. 9,
  149472. 4,
  149473. 10,
  149474. 3,
  149475. 11,
  149476. 2,
  149477. 12,
  149478. 1,
  149479. 13,
  149480. 0,
  149481. 14,
  149482. };
  149483. static long _vq_lengthlist__44u5__p9_1[] = {
  149484. 1, 4, 4, 7, 7, 8, 8, 8, 7, 8, 7, 9, 8, 9, 9, 4,
  149485. 7, 6, 9, 8,10,10, 9, 8, 9, 9, 9, 9, 9, 8, 5, 6,
  149486. 6, 8, 9,10,10, 9, 9, 9,10,10,10,10,11, 7, 8, 8,
  149487. 10,10,11,11,10,10,11,11,11,12,11,11, 7, 8, 8,10,
  149488. 10,11,11,10,10,11,11,12,11,11,11, 8, 9, 9,11,11,
  149489. 12,12,11,11,12,11,12,12,12,12, 8, 9,10,11,11,12,
  149490. 12,11,11,12,12,12,12,12,12, 8, 9, 9,10,10,12,11,
  149491. 12,12,12,12,12,12,12,13, 8, 9, 9,11,11,11,11,12,
  149492. 12,12,12,13,12,13,13, 9,10,10,11,11,12,12,12,13,
  149493. 12,13,13,13,14,13, 9,10,10,11,11,12,12,12,13,13,
  149494. 12,13,13,14,13, 9,11,10,12,11,13,12,12,13,13,13,
  149495. 13,13,13,14, 9,10,10,12,12,12,12,12,13,13,13,13,
  149496. 13,14,14,10,11,11,12,12,12,13,13,13,14,14,13,14,
  149497. 14,14,10,11,11,12,12,12,12,13,12,13,14,13,14,14,
  149498. 14,
  149499. };
  149500. static float _vq_quantthresh__44u5__p9_1[] = {
  149501. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  149502. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  149503. };
  149504. static long _vq_quantmap__44u5__p9_1[] = {
  149505. 13, 11, 9, 7, 5, 3, 1, 0,
  149506. 2, 4, 6, 8, 10, 12, 14,
  149507. };
  149508. static encode_aux_threshmatch _vq_auxt__44u5__p9_1 = {
  149509. _vq_quantthresh__44u5__p9_1,
  149510. _vq_quantmap__44u5__p9_1,
  149511. 15,
  149512. 15
  149513. };
  149514. static static_codebook _44u5__p9_1 = {
  149515. 2, 225,
  149516. _vq_lengthlist__44u5__p9_1,
  149517. 1, -522338304, 1620115456, 4, 0,
  149518. _vq_quantlist__44u5__p9_1,
  149519. NULL,
  149520. &_vq_auxt__44u5__p9_1,
  149521. NULL,
  149522. 0
  149523. };
  149524. static long _vq_quantlist__44u5__p9_2[] = {
  149525. 8,
  149526. 7,
  149527. 9,
  149528. 6,
  149529. 10,
  149530. 5,
  149531. 11,
  149532. 4,
  149533. 12,
  149534. 3,
  149535. 13,
  149536. 2,
  149537. 14,
  149538. 1,
  149539. 15,
  149540. 0,
  149541. 16,
  149542. };
  149543. static long _vq_lengthlist__44u5__p9_2[] = {
  149544. 2, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149545. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  149546. 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149547. 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  149548. 9, 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149549. 9, 9, 9, 9, 9, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  149550. 9,10, 9,10,10,10, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149551. 9, 9,10, 9,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  149552. 9,10, 9,10,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  149553. 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,10, 9,
  149554. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,
  149555. 9,10, 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  149556. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  149557. 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  149558. 9,10,10, 9,10,10,10,10,10,10,10,10,10,10, 9, 9,
  149559. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  149560. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  149561. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,
  149562. 10,
  149563. };
  149564. static float _vq_quantthresh__44u5__p9_2[] = {
  149565. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  149566. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  149567. };
  149568. static long _vq_quantmap__44u5__p9_2[] = {
  149569. 15, 13, 11, 9, 7, 5, 3, 1,
  149570. 0, 2, 4, 6, 8, 10, 12, 14,
  149571. 16,
  149572. };
  149573. static encode_aux_threshmatch _vq_auxt__44u5__p9_2 = {
  149574. _vq_quantthresh__44u5__p9_2,
  149575. _vq_quantmap__44u5__p9_2,
  149576. 17,
  149577. 17
  149578. };
  149579. static static_codebook _44u5__p9_2 = {
  149580. 2, 289,
  149581. _vq_lengthlist__44u5__p9_2,
  149582. 1, -529530880, 1611661312, 5, 0,
  149583. _vq_quantlist__44u5__p9_2,
  149584. NULL,
  149585. &_vq_auxt__44u5__p9_2,
  149586. NULL,
  149587. 0
  149588. };
  149589. static long _huff_lengthlist__44u5__short[] = {
  149590. 4,10,17,13,17,13,17,17,17,17, 3, 6, 8, 9,11, 9,
  149591. 15,12,16,17, 6, 5, 5, 7, 7, 8,10,11,17,17, 7, 8,
  149592. 7, 9, 9,10,13,13,17,17, 8, 6, 5, 7, 4, 7, 5, 8,
  149593. 14,17, 9, 9, 8, 9, 7, 9, 8,10,16,17,12,10, 7, 8,
  149594. 4, 7, 4, 7,16,17,12,11, 9,10, 6, 9, 5, 7,14,17,
  149595. 14,13,10,15, 4, 8, 3, 5,14,17,17,14,11,15, 6,10,
  149596. 6, 8,15,17,
  149597. };
  149598. static static_codebook _huff_book__44u5__short = {
  149599. 2, 100,
  149600. _huff_lengthlist__44u5__short,
  149601. 0, 0, 0, 0, 0,
  149602. NULL,
  149603. NULL,
  149604. NULL,
  149605. NULL,
  149606. 0
  149607. };
  149608. static long _huff_lengthlist__44u6__long[] = {
  149609. 3, 9,14,13,14,13,16,12,13,14, 5, 4, 6, 6, 8, 9,
  149610. 11,10,12,15,10, 5, 5, 6, 6, 8,10,10,13,16,10, 6,
  149611. 6, 6, 6, 8, 9, 9,12,14,13, 7, 6, 6, 4, 6, 6, 7,
  149612. 11,14,10, 7, 7, 7, 6, 6, 6, 7,10,13,15,10, 9, 8,
  149613. 5, 6, 5, 6,10,14,10, 9, 8, 8, 6, 6, 5, 4, 6,11,
  149614. 11,11,12,11,10, 9, 9, 5, 5, 9,10,12,15,13,13,13,
  149615. 13, 8, 7, 7,
  149616. };
  149617. static static_codebook _huff_book__44u6__long = {
  149618. 2, 100,
  149619. _huff_lengthlist__44u6__long,
  149620. 0, 0, 0, 0, 0,
  149621. NULL,
  149622. NULL,
  149623. NULL,
  149624. NULL,
  149625. 0
  149626. };
  149627. static long _vq_quantlist__44u6__p1_0[] = {
  149628. 1,
  149629. 0,
  149630. 2,
  149631. };
  149632. static long _vq_lengthlist__44u6__p1_0[] = {
  149633. 1, 4, 4, 4, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  149634. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  149635. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  149636. 10,13,11,10,13,13, 5, 8, 8, 8,11,10, 8,10,10, 7,
  149637. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  149638. 12,
  149639. };
  149640. static float _vq_quantthresh__44u6__p1_0[] = {
  149641. -0.5, 0.5,
  149642. };
  149643. static long _vq_quantmap__44u6__p1_0[] = {
  149644. 1, 0, 2,
  149645. };
  149646. static encode_aux_threshmatch _vq_auxt__44u6__p1_0 = {
  149647. _vq_quantthresh__44u6__p1_0,
  149648. _vq_quantmap__44u6__p1_0,
  149649. 3,
  149650. 3
  149651. };
  149652. static static_codebook _44u6__p1_0 = {
  149653. 4, 81,
  149654. _vq_lengthlist__44u6__p1_0,
  149655. 1, -535822336, 1611661312, 2, 0,
  149656. _vq_quantlist__44u6__p1_0,
  149657. NULL,
  149658. &_vq_auxt__44u6__p1_0,
  149659. NULL,
  149660. 0
  149661. };
  149662. static long _vq_quantlist__44u6__p2_0[] = {
  149663. 1,
  149664. 0,
  149665. 2,
  149666. };
  149667. static long _vq_lengthlist__44u6__p2_0[] = {
  149668. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  149669. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  149670. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 7, 7,
  149671. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  149672. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  149673. 9,
  149674. };
  149675. static float _vq_quantthresh__44u6__p2_0[] = {
  149676. -0.5, 0.5,
  149677. };
  149678. static long _vq_quantmap__44u6__p2_0[] = {
  149679. 1, 0, 2,
  149680. };
  149681. static encode_aux_threshmatch _vq_auxt__44u6__p2_0 = {
  149682. _vq_quantthresh__44u6__p2_0,
  149683. _vq_quantmap__44u6__p2_0,
  149684. 3,
  149685. 3
  149686. };
  149687. static static_codebook _44u6__p2_0 = {
  149688. 4, 81,
  149689. _vq_lengthlist__44u6__p2_0,
  149690. 1, -535822336, 1611661312, 2, 0,
  149691. _vq_quantlist__44u6__p2_0,
  149692. NULL,
  149693. &_vq_auxt__44u6__p2_0,
  149694. NULL,
  149695. 0
  149696. };
  149697. static long _vq_quantlist__44u6__p3_0[] = {
  149698. 2,
  149699. 1,
  149700. 3,
  149701. 0,
  149702. 4,
  149703. };
  149704. static long _vq_lengthlist__44u6__p3_0[] = {
  149705. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  149706. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  149707. 9,11,11, 7, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  149708. 13,14, 5, 7, 7, 9,10, 6, 9, 8,11,11, 7, 9, 9,11,
  149709. 11, 9,11,10,14,13,10,11,11,14,13, 8,10,10,13,13,
  149710. 10,11,11,15,15, 9,11,11,14,14,13,14,14,17,16,12,
  149711. 13,14,16,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  149712. 12,14,15,12,14,13,16,15,13,14,14,15,17, 5, 7, 7,
  149713. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,
  149714. 14,10,11,11,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  149715. 9,11,11,13,13,11,13,13,14,15,11,12,13,15,16, 6,
  149716. 9, 9,11,12, 8,11,10,13,12, 9,11,11,13,14,11,13,
  149717. 12,16,14,11,13,13,15,16,10,12,11,14,15,11,13,13,
  149718. 15,17,11,13,13,17,16,15,15,16,17,16,14,15,16,18,
  149719. 0, 9,11,11,14,15,10,12,12,16,15,11,13,13,16,16,
  149720. 13,15,14,18,15,14,16,16, 0, 0, 5, 7, 7,10,10, 7,
  149721. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  149722. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  149723. 12,13,11,13,13,16,15,11,12,13,14,16, 7, 9, 9,11,
  149724. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,16,15,
  149725. 11,13,12,15,15, 9,11,11,15,14,11,13,13,17,16,10,
  149726. 12,13,15,16,14,16,16, 0,18,14,14,15,15,17,10,11,
  149727. 12,15,15,11,13,13,16,16,11,13,13,16,16,14,16,16,
  149728. 19,17,14,15,15,17,17, 8,10,10,14,14,10,12,11,15,
  149729. 15,10,11,12,16,15,14,15,15,18,20,13,14,16,17,18,
  149730. 9,11,11,15,16,11,13,13,17,17,11,13,13,17,16,15,
  149731. 16,16, 0, 0,15,16,16, 0, 0, 9,11,11,15,15,10,13,
  149732. 12,17,15,11,13,13,17,16,15,17,15,20,19,15,16,16,
  149733. 19, 0,13,15,14, 0,17,14,15,16, 0,20,15,16,16, 0,
  149734. 19,17,18, 0, 0, 0,16,17,18, 0, 0,12,14,14,19,18,
  149735. 13,15,14, 0,17,14,15,16,19,19,16,18,16, 0,19,19,
  149736. 20,17,20, 0, 8,10,10,13,14,10,11,11,15,15,10,12,
  149737. 12,15,16,14,15,14,19,16,14,15,15, 0,18, 9,11,11,
  149738. 16,15,11,13,13, 0,16,11,12,13,16,17,14,16,17, 0,
  149739. 19,15,16,16,18, 0, 9,11,11,15,16,11,13,13,16,16,
  149740. 11,14,13,18,17,15,16,16,18,20,15,17,19, 0, 0,12,
  149741. 14,14,17,17,14,16,15, 0, 0,13,14,15,19, 0,16,18,
  149742. 20, 0, 0,16,16,18,18, 0,12,14,14,17,20,14,16,16,
  149743. 19, 0,14,16,14, 0,20,16,20,17, 0, 0,17, 0,15, 0,
  149744. 19,
  149745. };
  149746. static float _vq_quantthresh__44u6__p3_0[] = {
  149747. -1.5, -0.5, 0.5, 1.5,
  149748. };
  149749. static long _vq_quantmap__44u6__p3_0[] = {
  149750. 3, 1, 0, 2, 4,
  149751. };
  149752. static encode_aux_threshmatch _vq_auxt__44u6__p3_0 = {
  149753. _vq_quantthresh__44u6__p3_0,
  149754. _vq_quantmap__44u6__p3_0,
  149755. 5,
  149756. 5
  149757. };
  149758. static static_codebook _44u6__p3_0 = {
  149759. 4, 625,
  149760. _vq_lengthlist__44u6__p3_0,
  149761. 1, -533725184, 1611661312, 3, 0,
  149762. _vq_quantlist__44u6__p3_0,
  149763. NULL,
  149764. &_vq_auxt__44u6__p3_0,
  149765. NULL,
  149766. 0
  149767. };
  149768. static long _vq_quantlist__44u6__p4_0[] = {
  149769. 2,
  149770. 1,
  149771. 3,
  149772. 0,
  149773. 4,
  149774. };
  149775. static long _vq_lengthlist__44u6__p4_0[] = {
  149776. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  149777. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  149778. 8,10,10, 7, 7, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  149779. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 8,10,
  149780. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  149781. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,13,11,
  149782. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  149783. 10,12,12,11,12,11,13,12,11,12,12,13,13, 5, 7, 7,
  149784. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  149785. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  149786. 8, 9, 9,11,11,10,10,11,12,13,10,10,11,12,12, 6,
  149787. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  149788. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  149789. 13,13,10,11,11,12,13,12,12,12,13,14,12,12,13,14,
  149790. 14, 9,10,10,12,12, 9,10,10,13,12,10,11,11,13,13,
  149791. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  149792. 8, 7,10,10, 7, 8, 8,10,10, 9,10,10,12,11, 9,10,
  149793. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  149794. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  149795. 10, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,10,13,12,
  149796. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,12, 9,
  149797. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  149798. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,12,12,
  149799. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  149800. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,14,
  149801. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  149802. 12,13,14,15,12,12,13,14,14, 9,10,10,12,12, 9,11,
  149803. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,13,
  149804. 14,15,11,12,12,14,13,11,12,12,14,14,12,13,13,14,
  149805. 14,13,13,14,14,16,13,14,14,15,15,11,12,11,13,13,
  149806. 11,12,11,14,13,12,12,13,14,15,12,14,12,15,12,13,
  149807. 14,15,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  149808. 10,12,12,11,12,12,14,13,11,12,12,13,13, 9,10,10,
  149809. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  149810. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  149811. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  149812. 11,11,13,13,12,13,12,14,14,11,11,12,13,14,14,14,
  149813. 14,16,15,12,12,14,12,15,11,12,12,13,14,12,13,13,
  149814. 14,15,11,12,12,14,14,13,14,14,16,16,13,14,13,16,
  149815. 13,
  149816. };
  149817. static float _vq_quantthresh__44u6__p4_0[] = {
  149818. -1.5, -0.5, 0.5, 1.5,
  149819. };
  149820. static long _vq_quantmap__44u6__p4_0[] = {
  149821. 3, 1, 0, 2, 4,
  149822. };
  149823. static encode_aux_threshmatch _vq_auxt__44u6__p4_0 = {
  149824. _vq_quantthresh__44u6__p4_0,
  149825. _vq_quantmap__44u6__p4_0,
  149826. 5,
  149827. 5
  149828. };
  149829. static static_codebook _44u6__p4_0 = {
  149830. 4, 625,
  149831. _vq_lengthlist__44u6__p4_0,
  149832. 1, -533725184, 1611661312, 3, 0,
  149833. _vq_quantlist__44u6__p4_0,
  149834. NULL,
  149835. &_vq_auxt__44u6__p4_0,
  149836. NULL,
  149837. 0
  149838. };
  149839. static long _vq_quantlist__44u6__p5_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__p5_0[] = {
  149851. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  149852. 11,11, 3, 5, 5, 7, 8, 8, 8,11,11, 6, 8, 7, 9, 9,
  149853. 10, 9,12,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  149854. 10, 9,12,11,13,13, 8, 8, 9, 9,10,11,12,13,13,10,
  149855. 11,11,12,12,13,13,14,14,10,10,11,11,12,13,13,14,
  149856. 14,
  149857. };
  149858. static float _vq_quantthresh__44u6__p5_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__p5_0[] = {
  149862. 7, 5, 3, 1, 0, 2, 4, 6,
  149863. 8,
  149864. };
  149865. static encode_aux_threshmatch _vq_auxt__44u6__p5_0 = {
  149866. _vq_quantthresh__44u6__p5_0,
  149867. _vq_quantmap__44u6__p5_0,
  149868. 9,
  149869. 9
  149870. };
  149871. static static_codebook _44u6__p5_0 = {
  149872. 2, 81,
  149873. _vq_lengthlist__44u6__p5_0,
  149874. 1, -531628032, 1611661312, 4, 0,
  149875. _vq_quantlist__44u6__p5_0,
  149876. NULL,
  149877. &_vq_auxt__44u6__p5_0,
  149878. NULL,
  149879. 0
  149880. };
  149881. static long _vq_quantlist__44u6__p6_0[] = {
  149882. 4,
  149883. 3,
  149884. 5,
  149885. 2,
  149886. 6,
  149887. 1,
  149888. 7,
  149889. 0,
  149890. 8,
  149891. };
  149892. static long _vq_lengthlist__44u6__p6_0[] = {
  149893. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  149894. 9, 9, 4, 4, 5, 6, 6, 7, 8, 9, 9, 5, 6, 6, 7, 7,
  149895. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  149896. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,10,11, 9,
  149897. 9, 9,10,10,11,11,12,11, 9, 9, 9,10,10,11,11,11,
  149898. 12,
  149899. };
  149900. static float _vq_quantthresh__44u6__p6_0[] = {
  149901. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149902. };
  149903. static long _vq_quantmap__44u6__p6_0[] = {
  149904. 7, 5, 3, 1, 0, 2, 4, 6,
  149905. 8,
  149906. };
  149907. static encode_aux_threshmatch _vq_auxt__44u6__p6_0 = {
  149908. _vq_quantthresh__44u6__p6_0,
  149909. _vq_quantmap__44u6__p6_0,
  149910. 9,
  149911. 9
  149912. };
  149913. static static_codebook _44u6__p6_0 = {
  149914. 2, 81,
  149915. _vq_lengthlist__44u6__p6_0,
  149916. 1, -531628032, 1611661312, 4, 0,
  149917. _vq_quantlist__44u6__p6_0,
  149918. NULL,
  149919. &_vq_auxt__44u6__p6_0,
  149920. NULL,
  149921. 0
  149922. };
  149923. static long _vq_quantlist__44u6__p7_0[] = {
  149924. 1,
  149925. 0,
  149926. 2,
  149927. };
  149928. static long _vq_lengthlist__44u6__p7_0[] = {
  149929. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10,10, 8,
  149930. 10,10, 5, 8, 9, 7,10,10, 7,10, 9, 4, 8, 8, 9,11,
  149931. 11, 8,11,11, 7,11,11,10,10,13,10,13,13, 7,11,11,
  149932. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 9,11,11, 7,
  149933. 11,11,10,13,13,10,12,13, 7,11,11,10,13,13, 9,13,
  149934. 10,
  149935. };
  149936. static float _vq_quantthresh__44u6__p7_0[] = {
  149937. -5.5, 5.5,
  149938. };
  149939. static long _vq_quantmap__44u6__p7_0[] = {
  149940. 1, 0, 2,
  149941. };
  149942. static encode_aux_threshmatch _vq_auxt__44u6__p7_0 = {
  149943. _vq_quantthresh__44u6__p7_0,
  149944. _vq_quantmap__44u6__p7_0,
  149945. 3,
  149946. 3
  149947. };
  149948. static static_codebook _44u6__p7_0 = {
  149949. 4, 81,
  149950. _vq_lengthlist__44u6__p7_0,
  149951. 1, -529137664, 1618345984, 2, 0,
  149952. _vq_quantlist__44u6__p7_0,
  149953. NULL,
  149954. &_vq_auxt__44u6__p7_0,
  149955. NULL,
  149956. 0
  149957. };
  149958. static long _vq_quantlist__44u6__p7_1[] = {
  149959. 5,
  149960. 4,
  149961. 6,
  149962. 3,
  149963. 7,
  149964. 2,
  149965. 8,
  149966. 1,
  149967. 9,
  149968. 0,
  149969. 10,
  149970. };
  149971. static long _vq_lengthlist__44u6__p7_1[] = {
  149972. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 6,
  149973. 8, 8, 8, 8, 8, 8, 4, 5, 5, 6, 7, 8, 8, 8, 8, 8,
  149974. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  149975. 7, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 9, 9,
  149976. 9, 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  149977. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  149978. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  149979. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149980. };
  149981. static float _vq_quantthresh__44u6__p7_1[] = {
  149982. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149983. 3.5, 4.5,
  149984. };
  149985. static long _vq_quantmap__44u6__p7_1[] = {
  149986. 9, 7, 5, 3, 1, 0, 2, 4,
  149987. 6, 8, 10,
  149988. };
  149989. static encode_aux_threshmatch _vq_auxt__44u6__p7_1 = {
  149990. _vq_quantthresh__44u6__p7_1,
  149991. _vq_quantmap__44u6__p7_1,
  149992. 11,
  149993. 11
  149994. };
  149995. static static_codebook _44u6__p7_1 = {
  149996. 2, 121,
  149997. _vq_lengthlist__44u6__p7_1,
  149998. 1, -531365888, 1611661312, 4, 0,
  149999. _vq_quantlist__44u6__p7_1,
  150000. NULL,
  150001. &_vq_auxt__44u6__p7_1,
  150002. NULL,
  150003. 0
  150004. };
  150005. static long _vq_quantlist__44u6__p8_0[] = {
  150006. 5,
  150007. 4,
  150008. 6,
  150009. 3,
  150010. 7,
  150011. 2,
  150012. 8,
  150013. 1,
  150014. 9,
  150015. 0,
  150016. 10,
  150017. };
  150018. static long _vq_lengthlist__44u6__p8_0[] = {
  150019. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  150020. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  150021. 11, 6, 8, 8, 9, 9,10,10,11,11,12,12, 6, 8, 8, 9,
  150022. 9,10,10,11,11,12,12, 8, 9, 9,10,10,11,11,12,12,
  150023. 13,13, 8, 9, 9,10,10,11,11,12,12,13,13,10,10,10,
  150024. 11,11,13,13,13,13,15,14, 9,10,10,12,11,12,13,13,
  150025. 13,14,15,11,12,12,13,13,13,13,15,14,15,15,11,11,
  150026. 12,13,13,14,14,14,15,15,15,
  150027. };
  150028. static float _vq_quantthresh__44u6__p8_0[] = {
  150029. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  150030. 38.5, 49.5,
  150031. };
  150032. static long _vq_quantmap__44u6__p8_0[] = {
  150033. 9, 7, 5, 3, 1, 0, 2, 4,
  150034. 6, 8, 10,
  150035. };
  150036. static encode_aux_threshmatch _vq_auxt__44u6__p8_0 = {
  150037. _vq_quantthresh__44u6__p8_0,
  150038. _vq_quantmap__44u6__p8_0,
  150039. 11,
  150040. 11
  150041. };
  150042. static static_codebook _44u6__p8_0 = {
  150043. 2, 121,
  150044. _vq_lengthlist__44u6__p8_0,
  150045. 1, -524582912, 1618345984, 4, 0,
  150046. _vq_quantlist__44u6__p8_0,
  150047. NULL,
  150048. &_vq_auxt__44u6__p8_0,
  150049. NULL,
  150050. 0
  150051. };
  150052. static long _vq_quantlist__44u6__p8_1[] = {
  150053. 5,
  150054. 4,
  150055. 6,
  150056. 3,
  150057. 7,
  150058. 2,
  150059. 8,
  150060. 1,
  150061. 9,
  150062. 0,
  150063. 10,
  150064. };
  150065. static long _vq_lengthlist__44u6__p8_1[] = {
  150066. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 7,
  150067. 7, 7, 8, 7, 8, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7, 8,
  150068. 8, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 6, 7, 7,
  150069. 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  150070. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  150071. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  150072. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  150073. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  150074. };
  150075. static float _vq_quantthresh__44u6__p8_1[] = {
  150076. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150077. 3.5, 4.5,
  150078. };
  150079. static long _vq_quantmap__44u6__p8_1[] = {
  150080. 9, 7, 5, 3, 1, 0, 2, 4,
  150081. 6, 8, 10,
  150082. };
  150083. static encode_aux_threshmatch _vq_auxt__44u6__p8_1 = {
  150084. _vq_quantthresh__44u6__p8_1,
  150085. _vq_quantmap__44u6__p8_1,
  150086. 11,
  150087. 11
  150088. };
  150089. static static_codebook _44u6__p8_1 = {
  150090. 2, 121,
  150091. _vq_lengthlist__44u6__p8_1,
  150092. 1, -531365888, 1611661312, 4, 0,
  150093. _vq_quantlist__44u6__p8_1,
  150094. NULL,
  150095. &_vq_auxt__44u6__p8_1,
  150096. NULL,
  150097. 0
  150098. };
  150099. static long _vq_quantlist__44u6__p9_0[] = {
  150100. 7,
  150101. 6,
  150102. 8,
  150103. 5,
  150104. 9,
  150105. 4,
  150106. 10,
  150107. 3,
  150108. 11,
  150109. 2,
  150110. 12,
  150111. 1,
  150112. 13,
  150113. 0,
  150114. 14,
  150115. };
  150116. static long _vq_lengthlist__44u6__p9_0[] = {
  150117. 1, 3, 2, 9, 8,15,15,15,15,15,15,15,15,15,15, 4,
  150118. 8, 9,13,14,14,14,14,14,14,14,14,14,14,14, 5, 8,
  150119. 9,14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,
  150120. 14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,14,
  150121. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150122. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150123. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150124. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150125. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150126. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150127. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150128. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150129. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150130. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150131. 14,
  150132. };
  150133. static float _vq_quantthresh__44u6__p9_0[] = {
  150134. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  150135. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  150136. };
  150137. static long _vq_quantmap__44u6__p9_0[] = {
  150138. 13, 11, 9, 7, 5, 3, 1, 0,
  150139. 2, 4, 6, 8, 10, 12, 14,
  150140. };
  150141. static encode_aux_threshmatch _vq_auxt__44u6__p9_0 = {
  150142. _vq_quantthresh__44u6__p9_0,
  150143. _vq_quantmap__44u6__p9_0,
  150144. 15,
  150145. 15
  150146. };
  150147. static static_codebook _44u6__p9_0 = {
  150148. 2, 225,
  150149. _vq_lengthlist__44u6__p9_0,
  150150. 1, -514071552, 1627381760, 4, 0,
  150151. _vq_quantlist__44u6__p9_0,
  150152. NULL,
  150153. &_vq_auxt__44u6__p9_0,
  150154. NULL,
  150155. 0
  150156. };
  150157. static long _vq_quantlist__44u6__p9_1[] = {
  150158. 7,
  150159. 6,
  150160. 8,
  150161. 5,
  150162. 9,
  150163. 4,
  150164. 10,
  150165. 3,
  150166. 11,
  150167. 2,
  150168. 12,
  150169. 1,
  150170. 13,
  150171. 0,
  150172. 14,
  150173. };
  150174. static long _vq_lengthlist__44u6__p9_1[] = {
  150175. 1, 4, 4, 7, 7, 8, 9, 8, 8, 9, 8, 9, 8, 9, 9, 4,
  150176. 7, 6, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 4, 7,
  150177. 6, 9, 9,10,10, 9, 9,10,10,10,10,11,11, 7, 9, 8,
  150178. 10,10,11,11,10,10,11,11,11,11,11,11, 7, 8, 9,10,
  150179. 10,11,11,10,10,11,11,11,11,11,12, 8,10,10,11,11,
  150180. 12,12,11,11,12,12,12,12,13,12, 8,10,10,11,11,12,
  150181. 11,11,11,11,12,12,12,12,13, 8, 9, 9,11,10,11,11,
  150182. 12,12,12,12,13,12,13,12, 8, 9, 9,11,11,11,11,12,
  150183. 12,12,12,12,13,13,13, 9,10,10,11,12,12,12,12,12,
  150184. 13,13,13,13,13,13, 9,10,10,11,11,12,12,12,12,13,
  150185. 13,13,13,14,13,10,10,10,12,11,12,12,13,13,13,13,
  150186. 13,13,13,13,10,10,11,11,11,12,12,13,13,13,13,13,
  150187. 13,13,13,10,11,11,12,12,13,12,12,13,13,13,13,13,
  150188. 13,14,10,11,11,12,12,13,12,13,13,13,14,13,13,14,
  150189. 13,
  150190. };
  150191. static float _vq_quantthresh__44u6__p9_1[] = {
  150192. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  150193. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  150194. };
  150195. static long _vq_quantmap__44u6__p9_1[] = {
  150196. 13, 11, 9, 7, 5, 3, 1, 0,
  150197. 2, 4, 6, 8, 10, 12, 14,
  150198. };
  150199. static encode_aux_threshmatch _vq_auxt__44u6__p9_1 = {
  150200. _vq_quantthresh__44u6__p9_1,
  150201. _vq_quantmap__44u6__p9_1,
  150202. 15,
  150203. 15
  150204. };
  150205. static static_codebook _44u6__p9_1 = {
  150206. 2, 225,
  150207. _vq_lengthlist__44u6__p9_1,
  150208. 1, -522338304, 1620115456, 4, 0,
  150209. _vq_quantlist__44u6__p9_1,
  150210. NULL,
  150211. &_vq_auxt__44u6__p9_1,
  150212. NULL,
  150213. 0
  150214. };
  150215. static long _vq_quantlist__44u6__p9_2[] = {
  150216. 8,
  150217. 7,
  150218. 9,
  150219. 6,
  150220. 10,
  150221. 5,
  150222. 11,
  150223. 4,
  150224. 12,
  150225. 3,
  150226. 13,
  150227. 2,
  150228. 14,
  150229. 1,
  150230. 15,
  150231. 0,
  150232. 16,
  150233. };
  150234. static long _vq_lengthlist__44u6__p9_2[] = {
  150235. 3, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 8, 8, 9, 9,
  150236. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  150237. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  150238. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150239. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  150240. 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150241. 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  150242. 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150243. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  150244. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9, 9, 9, 9,
  150245. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 8, 9, 9, 9, 9, 9,
  150246. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150247. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9, 9, 9, 9, 9,
  150248. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,
  150249. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9, 9,
  150250. 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9,10, 9,
  150251. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9,10,10,
  150252. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10, 9, 9,
  150253. 10,
  150254. };
  150255. static float _vq_quantthresh__44u6__p9_2[] = {
  150256. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  150257. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  150258. };
  150259. static long _vq_quantmap__44u6__p9_2[] = {
  150260. 15, 13, 11, 9, 7, 5, 3, 1,
  150261. 0, 2, 4, 6, 8, 10, 12, 14,
  150262. 16,
  150263. };
  150264. static encode_aux_threshmatch _vq_auxt__44u6__p9_2 = {
  150265. _vq_quantthresh__44u6__p9_2,
  150266. _vq_quantmap__44u6__p9_2,
  150267. 17,
  150268. 17
  150269. };
  150270. static static_codebook _44u6__p9_2 = {
  150271. 2, 289,
  150272. _vq_lengthlist__44u6__p9_2,
  150273. 1, -529530880, 1611661312, 5, 0,
  150274. _vq_quantlist__44u6__p9_2,
  150275. NULL,
  150276. &_vq_auxt__44u6__p9_2,
  150277. NULL,
  150278. 0
  150279. };
  150280. static long _huff_lengthlist__44u6__short[] = {
  150281. 4,11,16,13,17,13,17,16,17,17, 4, 7, 9, 9,13,10,
  150282. 16,12,16,17, 7, 6, 5, 7, 8, 9,12,12,16,17, 6, 9,
  150283. 7, 9,10,10,15,15,17,17, 6, 7, 5, 7, 5, 7, 7,10,
  150284. 16,17, 7, 9, 8, 9, 8,10,11,11,15,17, 7, 7, 7, 8,
  150285. 5, 8, 8, 9,15,17, 8, 7, 9, 9, 7, 8, 7, 2, 7,15,
  150286. 14,13,13,15, 5,10, 4, 3, 6,17,17,15,13,17, 7,11,
  150287. 7, 6, 9,16,
  150288. };
  150289. static static_codebook _huff_book__44u6__short = {
  150290. 2, 100,
  150291. _huff_lengthlist__44u6__short,
  150292. 0, 0, 0, 0, 0,
  150293. NULL,
  150294. NULL,
  150295. NULL,
  150296. NULL,
  150297. 0
  150298. };
  150299. static long _huff_lengthlist__44u7__long[] = {
  150300. 3, 9,14,13,15,14,16,13,13,14, 5, 5, 7, 7, 8, 9,
  150301. 11,10,12,15,10, 6, 5, 6, 6, 9,10,10,13,16,10, 6,
  150302. 6, 6, 6, 8, 9, 9,12,15,14, 7, 6, 6, 5, 6, 6, 8,
  150303. 12,15,10, 8, 7, 7, 6, 7, 7, 7,11,13,14,10, 9, 8,
  150304. 5, 6, 4, 5, 9,12,10, 9, 9, 8, 6, 6, 5, 3, 6,11,
  150305. 12,11,12,12,10, 9, 8, 5, 5, 8,10,11,15,13,13,13,
  150306. 12, 8, 6, 7,
  150307. };
  150308. static static_codebook _huff_book__44u7__long = {
  150309. 2, 100,
  150310. _huff_lengthlist__44u7__long,
  150311. 0, 0, 0, 0, 0,
  150312. NULL,
  150313. NULL,
  150314. NULL,
  150315. NULL,
  150316. 0
  150317. };
  150318. static long _vq_quantlist__44u7__p1_0[] = {
  150319. 1,
  150320. 0,
  150321. 2,
  150322. };
  150323. static long _vq_lengthlist__44u7__p1_0[] = {
  150324. 1, 4, 4, 4, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  150325. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 5, 8, 8, 8,11,
  150326. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  150327. 10,13,12,10,13,13, 5, 8, 8, 8,11,10, 8,10,11, 7,
  150328. 10,10,10,13,13,10,12,13, 8,11,11,10,13,13,10,13,
  150329. 12,
  150330. };
  150331. static float _vq_quantthresh__44u7__p1_0[] = {
  150332. -0.5, 0.5,
  150333. };
  150334. static long _vq_quantmap__44u7__p1_0[] = {
  150335. 1, 0, 2,
  150336. };
  150337. static encode_aux_threshmatch _vq_auxt__44u7__p1_0 = {
  150338. _vq_quantthresh__44u7__p1_0,
  150339. _vq_quantmap__44u7__p1_0,
  150340. 3,
  150341. 3
  150342. };
  150343. static static_codebook _44u7__p1_0 = {
  150344. 4, 81,
  150345. _vq_lengthlist__44u7__p1_0,
  150346. 1, -535822336, 1611661312, 2, 0,
  150347. _vq_quantlist__44u7__p1_0,
  150348. NULL,
  150349. &_vq_auxt__44u7__p1_0,
  150350. NULL,
  150351. 0
  150352. };
  150353. static long _vq_quantlist__44u7__p2_0[] = {
  150354. 1,
  150355. 0,
  150356. 2,
  150357. };
  150358. static long _vq_lengthlist__44u7__p2_0[] = {
  150359. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  150360. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  150361. 7, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  150362. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  150363. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  150364. 9,
  150365. };
  150366. static float _vq_quantthresh__44u7__p2_0[] = {
  150367. -0.5, 0.5,
  150368. };
  150369. static long _vq_quantmap__44u7__p2_0[] = {
  150370. 1, 0, 2,
  150371. };
  150372. static encode_aux_threshmatch _vq_auxt__44u7__p2_0 = {
  150373. _vq_quantthresh__44u7__p2_0,
  150374. _vq_quantmap__44u7__p2_0,
  150375. 3,
  150376. 3
  150377. };
  150378. static static_codebook _44u7__p2_0 = {
  150379. 4, 81,
  150380. _vq_lengthlist__44u7__p2_0,
  150381. 1, -535822336, 1611661312, 2, 0,
  150382. _vq_quantlist__44u7__p2_0,
  150383. NULL,
  150384. &_vq_auxt__44u7__p2_0,
  150385. NULL,
  150386. 0
  150387. };
  150388. static long _vq_quantlist__44u7__p3_0[] = {
  150389. 2,
  150390. 1,
  150391. 3,
  150392. 0,
  150393. 4,
  150394. };
  150395. static long _vq_lengthlist__44u7__p3_0[] = {
  150396. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  150397. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  150398. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  150399. 13,14, 5, 7, 7, 9, 9, 7, 9, 8,11,11, 7, 9, 9,11,
  150400. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  150401. 10,11,12,15,14, 9,11,11,15,14,13,14,14,16,16,12,
  150402. 13,14,17,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  150403. 12,14,15,12,14,13,16,16,13,14,15,15,17, 5, 7, 7,
  150404. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,15,
  150405. 14,10,11,12,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  150406. 9,11,11,13,13,11,13,13,14,17,11,13,13,15,16, 6,
  150407. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  150408. 12,16,14,11,13,13,16,16,10,12,12,15,15,11,13,13,
  150409. 16,16,11,13,13,16,15,14,16,17,17,19,14,16,16,18,
  150410. 0, 9,11,11,14,15,10,13,12,16,15,11,13,13,16,16,
  150411. 14,15,14, 0,16,14,16,16,18, 0, 5, 7, 7,10,10, 7,
  150412. 9, 9,12,11, 7, 9, 9,11,12,10,11,11,15,14,10,11,
  150413. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  150414. 12,13,11,13,13,17,15,11,12,13,14,15, 7, 9, 9,11,
  150415. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,12,16,16,
  150416. 11,13,13,15,14, 9,11,11,14,15,11,13,13,16,15,10,
  150417. 12,13,16,16,15,16,16, 0, 0,14,13,15,16,18,10,11,
  150418. 11,15,15,11,13,14,16,18,11,13,13,16,15,15,16,16,
  150419. 19, 0,14,15,15,16,16, 8,10,10,13,13,10,12,11,16,
  150420. 15,10,11,11,16,15,13,15,16,18, 0,13,14,15,17,17,
  150421. 9,11,11,15,15,11,13,13,16,18,11,13,13,16,17,15,
  150422. 16,16, 0, 0,15,18,16, 0,17, 9,11,11,15,15,11,13,
  150423. 12,17,15,11,13,14,16,17,15,18,15, 0,17,15,16,16,
  150424. 18,19,13,15,14, 0,18,14,16,16,19,18,14,16,15,19,
  150425. 19,16,18,19, 0, 0,16,17, 0, 0, 0,12,14,14,17,17,
  150426. 13,16,14, 0,18,14,16,15,18, 0,16,18,16,19,17,18,
  150427. 19,17, 0, 0, 8,10,10,14,14, 9,12,11,15,15,10,11,
  150428. 12,15,17,13,15,15,18,16,14,16,15,18,17, 9,11,11,
  150429. 16,15,11,13,13, 0,16,11,12,13,16,15,15,16,16, 0,
  150430. 17,15,15,16,18,17, 9,12,11,15,17,11,13,13,16,16,
  150431. 11,14,13,16,16,15,15,16,18,19,16,18,16, 0, 0,12,
  150432. 14,14, 0,16,14,16,16, 0,18,13,14,15,16, 0,17,16,
  150433. 18, 0, 0,16,16,17,19, 0,13,14,14,17, 0,14,17,16,
  150434. 0,19,14,15,15,18,19,17,16,18, 0, 0,15,19,16, 0,
  150435. 0,
  150436. };
  150437. static float _vq_quantthresh__44u7__p3_0[] = {
  150438. -1.5, -0.5, 0.5, 1.5,
  150439. };
  150440. static long _vq_quantmap__44u7__p3_0[] = {
  150441. 3, 1, 0, 2, 4,
  150442. };
  150443. static encode_aux_threshmatch _vq_auxt__44u7__p3_0 = {
  150444. _vq_quantthresh__44u7__p3_0,
  150445. _vq_quantmap__44u7__p3_0,
  150446. 5,
  150447. 5
  150448. };
  150449. static static_codebook _44u7__p3_0 = {
  150450. 4, 625,
  150451. _vq_lengthlist__44u7__p3_0,
  150452. 1, -533725184, 1611661312, 3, 0,
  150453. _vq_quantlist__44u7__p3_0,
  150454. NULL,
  150455. &_vq_auxt__44u7__p3_0,
  150456. NULL,
  150457. 0
  150458. };
  150459. static long _vq_quantlist__44u7__p4_0[] = {
  150460. 2,
  150461. 1,
  150462. 3,
  150463. 0,
  150464. 4,
  150465. };
  150466. static long _vq_lengthlist__44u7__p4_0[] = {
  150467. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  150468. 9, 9,11,11, 8, 9, 9,10,11, 6, 7, 7, 9, 9, 7, 8,
  150469. 8,10,10, 6, 7, 8, 9,10, 9,10,10,12,12, 9, 9,10,
  150470. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  150471. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  150472. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  150473. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,11, 9,10,
  150474. 10,12,12,11,12,11,13,13,11,12,12,13,13, 6, 7, 7,
  150475. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  150476. 11, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  150477. 8, 9, 9,11,11,10,11,11,12,12,10,10,11,12,13, 6,
  150478. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  150479. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  150480. 13,13,10,11,11,13,12,12,12,13,13,14,12,12,13,14,
  150481. 14, 9,10,10,12,12, 9,10,10,12,12,10,11,11,13,13,
  150482. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  150483. 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,11, 9,10,
  150484. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  150485. 10,11,10,11,11,13,12,10,10,11,11,13, 7, 8, 8,10,
  150486. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,10,13,12,
  150487. 10,11,11,12,12, 9,10,10,12,12,10,11,11,13,12, 9,
  150488. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  150489. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,12,
  150490. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  150491. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,13,
  150492. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  150493. 13,13,14,14,12,12,13,14,14, 9,10,10,12,12, 9,11,
  150494. 10,13,12,10,10,11,12,13,11,13,12,14,13,12,12,13,
  150495. 14,14,11,12,12,13,13,11,12,13,14,14,12,13,13,14,
  150496. 14,13,13,14,14,16,13,14,14,16,16,11,11,11,13,13,
  150497. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,13,14,
  150498. 14,14,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  150499. 10,12,12,11,12,12,14,13,11,12,12,13,14, 9,10,10,
  150500. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  150501. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,12,13,
  150502. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  150503. 12,12,13,13,12,13,12,14,14,11,11,12,13,14,13,15,
  150504. 14,16,15,13,12,14,13,16,11,12,12,13,13,12,13,13,
  150505. 14,14,12,12,12,14,14,13,14,14,15,15,13,14,13,16,
  150506. 14,
  150507. };
  150508. static float _vq_quantthresh__44u7__p4_0[] = {
  150509. -1.5, -0.5, 0.5, 1.5,
  150510. };
  150511. static long _vq_quantmap__44u7__p4_0[] = {
  150512. 3, 1, 0, 2, 4,
  150513. };
  150514. static encode_aux_threshmatch _vq_auxt__44u7__p4_0 = {
  150515. _vq_quantthresh__44u7__p4_0,
  150516. _vq_quantmap__44u7__p4_0,
  150517. 5,
  150518. 5
  150519. };
  150520. static static_codebook _44u7__p4_0 = {
  150521. 4, 625,
  150522. _vq_lengthlist__44u7__p4_0,
  150523. 1, -533725184, 1611661312, 3, 0,
  150524. _vq_quantlist__44u7__p4_0,
  150525. NULL,
  150526. &_vq_auxt__44u7__p4_0,
  150527. NULL,
  150528. 0
  150529. };
  150530. static long _vq_quantlist__44u7__p5_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__p5_0[] = {
  150542. 2, 3, 3, 6, 6, 7, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  150543. 11,11, 3, 5, 5, 7, 7, 8, 9,11,11, 6, 8, 7, 9, 9,
  150544. 10,10,12,12, 6, 7, 8, 9,10,10,10,12,12, 8, 8, 8,
  150545. 10,10,12,11,13,13, 8, 8, 9,10,10,11,11,13,13,10,
  150546. 11,11,12,12,13,13,14,14,10,11,11,12,12,13,13,14,
  150547. 14,
  150548. };
  150549. static float _vq_quantthresh__44u7__p5_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__p5_0[] = {
  150553. 7, 5, 3, 1, 0, 2, 4, 6,
  150554. 8,
  150555. };
  150556. static encode_aux_threshmatch _vq_auxt__44u7__p5_0 = {
  150557. _vq_quantthresh__44u7__p5_0,
  150558. _vq_quantmap__44u7__p5_0,
  150559. 9,
  150560. 9
  150561. };
  150562. static static_codebook _44u7__p5_0 = {
  150563. 2, 81,
  150564. _vq_lengthlist__44u7__p5_0,
  150565. 1, -531628032, 1611661312, 4, 0,
  150566. _vq_quantlist__44u7__p5_0,
  150567. NULL,
  150568. &_vq_auxt__44u7__p5_0,
  150569. NULL,
  150570. 0
  150571. };
  150572. static long _vq_quantlist__44u7__p6_0[] = {
  150573. 4,
  150574. 3,
  150575. 5,
  150576. 2,
  150577. 6,
  150578. 1,
  150579. 7,
  150580. 0,
  150581. 8,
  150582. };
  150583. static long _vq_lengthlist__44u7__p6_0[] = {
  150584. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 8, 7,
  150585. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  150586. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  150587. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,11,11, 9,
  150588. 9, 9,10,10,11,10,12,11, 9, 9, 9,10,10,11,11,11,
  150589. 12,
  150590. };
  150591. static float _vq_quantthresh__44u7__p6_0[] = {
  150592. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150593. };
  150594. static long _vq_quantmap__44u7__p6_0[] = {
  150595. 7, 5, 3, 1, 0, 2, 4, 6,
  150596. 8,
  150597. };
  150598. static encode_aux_threshmatch _vq_auxt__44u7__p6_0 = {
  150599. _vq_quantthresh__44u7__p6_0,
  150600. _vq_quantmap__44u7__p6_0,
  150601. 9,
  150602. 9
  150603. };
  150604. static static_codebook _44u7__p6_0 = {
  150605. 2, 81,
  150606. _vq_lengthlist__44u7__p6_0,
  150607. 1, -531628032, 1611661312, 4, 0,
  150608. _vq_quantlist__44u7__p6_0,
  150609. NULL,
  150610. &_vq_auxt__44u7__p6_0,
  150611. NULL,
  150612. 0
  150613. };
  150614. static long _vq_quantlist__44u7__p7_0[] = {
  150615. 1,
  150616. 0,
  150617. 2,
  150618. };
  150619. static long _vq_lengthlist__44u7__p7_0[] = {
  150620. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 8, 9, 9, 7,
  150621. 10,10, 5, 8, 9, 7, 9,10, 8, 9, 9, 4, 9, 9, 9,11,
  150622. 10, 8,10,10, 7,11,10,10,10,12,10,12,12, 7,10,10,
  150623. 10,12,11,10,12,12, 5, 9, 9, 8,10,10, 9,11,11, 7,
  150624. 11,10,10,12,12,10,11,12, 7,10,11,10,12,12,10,12,
  150625. 10,
  150626. };
  150627. static float _vq_quantthresh__44u7__p7_0[] = {
  150628. -5.5, 5.5,
  150629. };
  150630. static long _vq_quantmap__44u7__p7_0[] = {
  150631. 1, 0, 2,
  150632. };
  150633. static encode_aux_threshmatch _vq_auxt__44u7__p7_0 = {
  150634. _vq_quantthresh__44u7__p7_0,
  150635. _vq_quantmap__44u7__p7_0,
  150636. 3,
  150637. 3
  150638. };
  150639. static static_codebook _44u7__p7_0 = {
  150640. 4, 81,
  150641. _vq_lengthlist__44u7__p7_0,
  150642. 1, -529137664, 1618345984, 2, 0,
  150643. _vq_quantlist__44u7__p7_0,
  150644. NULL,
  150645. &_vq_auxt__44u7__p7_0,
  150646. NULL,
  150647. 0
  150648. };
  150649. static long _vq_quantlist__44u7__p7_1[] = {
  150650. 5,
  150651. 4,
  150652. 6,
  150653. 3,
  150654. 7,
  150655. 2,
  150656. 8,
  150657. 1,
  150658. 9,
  150659. 0,
  150660. 10,
  150661. };
  150662. static long _vq_lengthlist__44u7__p7_1[] = {
  150663. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6,
  150664. 8, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6, 7, 8, 8, 8, 8,
  150665. 8, 6, 7, 6, 7, 7, 8, 8, 9, 9, 9, 9, 6, 6, 7, 7,
  150666. 7, 8, 8, 9, 9, 9, 9, 7, 8, 7, 8, 8, 9, 9, 9, 9,
  150667. 9, 9, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  150668. 9, 9, 9, 9,10, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  150669. 9, 9,10, 8, 8, 8, 9, 9, 9, 9,10, 9,10,10, 8, 8,
  150670. 8, 9, 9, 9, 9, 9,10,10,10,
  150671. };
  150672. static float _vq_quantthresh__44u7__p7_1[] = {
  150673. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150674. 3.5, 4.5,
  150675. };
  150676. static long _vq_quantmap__44u7__p7_1[] = {
  150677. 9, 7, 5, 3, 1, 0, 2, 4,
  150678. 6, 8, 10,
  150679. };
  150680. static encode_aux_threshmatch _vq_auxt__44u7__p7_1 = {
  150681. _vq_quantthresh__44u7__p7_1,
  150682. _vq_quantmap__44u7__p7_1,
  150683. 11,
  150684. 11
  150685. };
  150686. static static_codebook _44u7__p7_1 = {
  150687. 2, 121,
  150688. _vq_lengthlist__44u7__p7_1,
  150689. 1, -531365888, 1611661312, 4, 0,
  150690. _vq_quantlist__44u7__p7_1,
  150691. NULL,
  150692. &_vq_auxt__44u7__p7_1,
  150693. NULL,
  150694. 0
  150695. };
  150696. static long _vq_quantlist__44u7__p8_0[] = {
  150697. 5,
  150698. 4,
  150699. 6,
  150700. 3,
  150701. 7,
  150702. 2,
  150703. 8,
  150704. 1,
  150705. 9,
  150706. 0,
  150707. 10,
  150708. };
  150709. static long _vq_lengthlist__44u7__p8_0[] = {
  150710. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  150711. 9, 9,11,10,12,12, 5, 6, 5, 7, 7, 9, 9,10,11,12,
  150712. 12, 6, 7, 7, 8, 8,10,10,11,11,13,13, 6, 7, 7, 8,
  150713. 8,10,10,11,12,13,13, 8, 9, 9,10,10,11,11,12,12,
  150714. 14,14, 8, 9, 9,10,10,11,11,12,12,14,14,10,10,10,
  150715. 11,11,13,12,14,14,15,15,10,10,10,12,12,13,13,14,
  150716. 14,15,15,11,12,12,13,13,14,14,15,14,16,15,11,12,
  150717. 12,13,13,14,14,15,15,15,16,
  150718. };
  150719. static float _vq_quantthresh__44u7__p8_0[] = {
  150720. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  150721. 38.5, 49.5,
  150722. };
  150723. static long _vq_quantmap__44u7__p8_0[] = {
  150724. 9, 7, 5, 3, 1, 0, 2, 4,
  150725. 6, 8, 10,
  150726. };
  150727. static encode_aux_threshmatch _vq_auxt__44u7__p8_0 = {
  150728. _vq_quantthresh__44u7__p8_0,
  150729. _vq_quantmap__44u7__p8_0,
  150730. 11,
  150731. 11
  150732. };
  150733. static static_codebook _44u7__p8_0 = {
  150734. 2, 121,
  150735. _vq_lengthlist__44u7__p8_0,
  150736. 1, -524582912, 1618345984, 4, 0,
  150737. _vq_quantlist__44u7__p8_0,
  150738. NULL,
  150739. &_vq_auxt__44u7__p8_0,
  150740. NULL,
  150741. 0
  150742. };
  150743. static long _vq_quantlist__44u7__p8_1[] = {
  150744. 5,
  150745. 4,
  150746. 6,
  150747. 3,
  150748. 7,
  150749. 2,
  150750. 8,
  150751. 1,
  150752. 9,
  150753. 0,
  150754. 10,
  150755. };
  150756. static long _vq_lengthlist__44u7__p8_1[] = {
  150757. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  150758. 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  150759. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  150760. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  150761. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  150762. 7, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  150763. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  150764. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  150765. };
  150766. static float _vq_quantthresh__44u7__p8_1[] = {
  150767. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150768. 3.5, 4.5,
  150769. };
  150770. static long _vq_quantmap__44u7__p8_1[] = {
  150771. 9, 7, 5, 3, 1, 0, 2, 4,
  150772. 6, 8, 10,
  150773. };
  150774. static encode_aux_threshmatch _vq_auxt__44u7__p8_1 = {
  150775. _vq_quantthresh__44u7__p8_1,
  150776. _vq_quantmap__44u7__p8_1,
  150777. 11,
  150778. 11
  150779. };
  150780. static static_codebook _44u7__p8_1 = {
  150781. 2, 121,
  150782. _vq_lengthlist__44u7__p8_1,
  150783. 1, -531365888, 1611661312, 4, 0,
  150784. _vq_quantlist__44u7__p8_1,
  150785. NULL,
  150786. &_vq_auxt__44u7__p8_1,
  150787. NULL,
  150788. 0
  150789. };
  150790. static long _vq_quantlist__44u7__p9_0[] = {
  150791. 5,
  150792. 4,
  150793. 6,
  150794. 3,
  150795. 7,
  150796. 2,
  150797. 8,
  150798. 1,
  150799. 9,
  150800. 0,
  150801. 10,
  150802. };
  150803. static long _vq_lengthlist__44u7__p9_0[] = {
  150804. 1, 3, 3,10,10,10,10,10,10,10,10, 4,10,10,10,10,
  150805. 10,10,10,10,10,10, 4,10,10,10,10,10,10,10,10,10,
  150806. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150807. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150808. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150809. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150810. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  150811. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150812. };
  150813. static float _vq_quantthresh__44u7__p9_0[] = {
  150814. -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5, 1592.5,
  150815. 2229.5, 2866.5,
  150816. };
  150817. static long _vq_quantmap__44u7__p9_0[] = {
  150818. 9, 7, 5, 3, 1, 0, 2, 4,
  150819. 6, 8, 10,
  150820. };
  150821. static encode_aux_threshmatch _vq_auxt__44u7__p9_0 = {
  150822. _vq_quantthresh__44u7__p9_0,
  150823. _vq_quantmap__44u7__p9_0,
  150824. 11,
  150825. 11
  150826. };
  150827. static static_codebook _44u7__p9_0 = {
  150828. 2, 121,
  150829. _vq_lengthlist__44u7__p9_0,
  150830. 1, -512171520, 1630791680, 4, 0,
  150831. _vq_quantlist__44u7__p9_0,
  150832. NULL,
  150833. &_vq_auxt__44u7__p9_0,
  150834. NULL,
  150835. 0
  150836. };
  150837. static long _vq_quantlist__44u7__p9_1[] = {
  150838. 6,
  150839. 5,
  150840. 7,
  150841. 4,
  150842. 8,
  150843. 3,
  150844. 9,
  150845. 2,
  150846. 10,
  150847. 1,
  150848. 11,
  150849. 0,
  150850. 12,
  150851. };
  150852. static long _vq_lengthlist__44u7__p9_1[] = {
  150853. 1, 4, 4, 6, 5, 8, 6, 9, 8,10, 9,11,10, 4, 6, 6,
  150854. 8, 8, 9, 9,11,10,11,11,11,11, 4, 6, 6, 8, 8,10,
  150855. 9,11,11,11,11,11,12, 6, 8, 8,10,10,11,11,12,12,
  150856. 13,12,13,13, 6, 8, 8,10,10,11,11,12,12,12,13,14,
  150857. 13, 8,10,10,11,11,12,13,14,14,14,14,15,15, 8,10,
  150858. 10,11,12,12,13,13,14,14,14,14,15, 9,11,11,13,13,
  150859. 14,14,15,14,16,15,17,15, 9,11,11,12,13,14,14,15,
  150860. 14,15,15,15,16,10,12,12,13,14,15,15,15,15,16,17,
  150861. 16,17,10,13,12,13,14,14,16,16,16,16,15,16,17,11,
  150862. 13,13,14,15,14,17,15,16,17,17,17,17,11,13,13,14,
  150863. 15,15,15,15,17,17,16,17,16,
  150864. };
  150865. static float _vq_quantthresh__44u7__p9_1[] = {
  150866. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  150867. 122.5, 171.5, 220.5, 269.5,
  150868. };
  150869. static long _vq_quantmap__44u7__p9_1[] = {
  150870. 11, 9, 7, 5, 3, 1, 0, 2,
  150871. 4, 6, 8, 10, 12,
  150872. };
  150873. static encode_aux_threshmatch _vq_auxt__44u7__p9_1 = {
  150874. _vq_quantthresh__44u7__p9_1,
  150875. _vq_quantmap__44u7__p9_1,
  150876. 13,
  150877. 13
  150878. };
  150879. static static_codebook _44u7__p9_1 = {
  150880. 2, 169,
  150881. _vq_lengthlist__44u7__p9_1,
  150882. 1, -518889472, 1622704128, 4, 0,
  150883. _vq_quantlist__44u7__p9_1,
  150884. NULL,
  150885. &_vq_auxt__44u7__p9_1,
  150886. NULL,
  150887. 0
  150888. };
  150889. static long _vq_quantlist__44u7__p9_2[] = {
  150890. 24,
  150891. 23,
  150892. 25,
  150893. 22,
  150894. 26,
  150895. 21,
  150896. 27,
  150897. 20,
  150898. 28,
  150899. 19,
  150900. 29,
  150901. 18,
  150902. 30,
  150903. 17,
  150904. 31,
  150905. 16,
  150906. 32,
  150907. 15,
  150908. 33,
  150909. 14,
  150910. 34,
  150911. 13,
  150912. 35,
  150913. 12,
  150914. 36,
  150915. 11,
  150916. 37,
  150917. 10,
  150918. 38,
  150919. 9,
  150920. 39,
  150921. 8,
  150922. 40,
  150923. 7,
  150924. 41,
  150925. 6,
  150926. 42,
  150927. 5,
  150928. 43,
  150929. 4,
  150930. 44,
  150931. 3,
  150932. 45,
  150933. 2,
  150934. 46,
  150935. 1,
  150936. 47,
  150937. 0,
  150938. 48,
  150939. };
  150940. static long _vq_lengthlist__44u7__p9_2[] = {
  150941. 2, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  150942. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  150943. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  150944. 8,
  150945. };
  150946. static float _vq_quantthresh__44u7__p9_2[] = {
  150947. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  150948. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  150949. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  150950. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  150951. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  150952. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  150953. };
  150954. static long _vq_quantmap__44u7__p9_2[] = {
  150955. 47, 45, 43, 41, 39, 37, 35, 33,
  150956. 31, 29, 27, 25, 23, 21, 19, 17,
  150957. 15, 13, 11, 9, 7, 5, 3, 1,
  150958. 0, 2, 4, 6, 8, 10, 12, 14,
  150959. 16, 18, 20, 22, 24, 26, 28, 30,
  150960. 32, 34, 36, 38, 40, 42, 44, 46,
  150961. 48,
  150962. };
  150963. static encode_aux_threshmatch _vq_auxt__44u7__p9_2 = {
  150964. _vq_quantthresh__44u7__p9_2,
  150965. _vq_quantmap__44u7__p9_2,
  150966. 49,
  150967. 49
  150968. };
  150969. static static_codebook _44u7__p9_2 = {
  150970. 1, 49,
  150971. _vq_lengthlist__44u7__p9_2,
  150972. 1, -526909440, 1611661312, 6, 0,
  150973. _vq_quantlist__44u7__p9_2,
  150974. NULL,
  150975. &_vq_auxt__44u7__p9_2,
  150976. NULL,
  150977. 0
  150978. };
  150979. static long _huff_lengthlist__44u7__short[] = {
  150980. 5,12,17,16,16,17,17,17,17,17, 4, 7,11,11,12, 9,
  150981. 17,10,17,17, 7, 7, 8, 9, 7, 9,11,10,15,17, 7, 9,
  150982. 10,11,10,12,14,12,16,17, 7, 8, 5, 7, 4, 7, 7, 8,
  150983. 16,16, 6,10, 9,10, 7,10,11,11,16,17, 6, 8, 8, 9,
  150984. 5, 7, 5, 8,16,17, 5, 5, 8, 7, 6, 7, 7, 6, 6,14,
  150985. 12,10,12,11, 7,11, 4, 4, 2, 7,17,15,15,15, 8,15,
  150986. 6, 8, 5, 9,
  150987. };
  150988. static static_codebook _huff_book__44u7__short = {
  150989. 2, 100,
  150990. _huff_lengthlist__44u7__short,
  150991. 0, 0, 0, 0, 0,
  150992. NULL,
  150993. NULL,
  150994. NULL,
  150995. NULL,
  150996. 0
  150997. };
  150998. static long _huff_lengthlist__44u8__long[] = {
  150999. 3, 9,13,14,14,15,14,14,15,15, 5, 4, 6, 8,10,12,
  151000. 12,14,15,15, 9, 5, 4, 5, 8,10,11,13,16,16,10, 7,
  151001. 4, 3, 5, 7, 9,11,13,13,10, 9, 7, 4, 4, 6, 8,10,
  151002. 12,14,13,11, 9, 6, 5, 5, 6, 8,12,14,13,11,10, 8,
  151003. 7, 6, 6, 7,10,14,13,11,12,10, 8, 7, 6, 6, 9,13,
  151004. 12,11,14,12,11, 9, 8, 7, 9,11,11,12,14,13,14,11,
  151005. 10, 8, 8, 9,
  151006. };
  151007. static static_codebook _huff_book__44u8__long = {
  151008. 2, 100,
  151009. _huff_lengthlist__44u8__long,
  151010. 0, 0, 0, 0, 0,
  151011. NULL,
  151012. NULL,
  151013. NULL,
  151014. NULL,
  151015. 0
  151016. };
  151017. static long _huff_lengthlist__44u8__short[] = {
  151018. 6,14,18,18,17,17,17,17,17,17, 4, 7, 9, 9,10,13,
  151019. 15,17,17,17, 6, 7, 5, 6, 8,11,16,17,16,17, 5, 7,
  151020. 5, 4, 6,10,14,17,17,17, 6, 6, 6, 5, 7,10,13,16,
  151021. 17,17, 7, 6, 7, 7, 7, 8, 7,10,15,16,12, 9, 9, 6,
  151022. 6, 5, 3, 5,11,15,14,14,13, 5, 5, 7, 3, 4, 8,15,
  151023. 17,17,13, 7, 7,10, 6, 6,10,15,17,17,16,10,11,14,
  151024. 10,10,15,17,
  151025. };
  151026. static static_codebook _huff_book__44u8__short = {
  151027. 2, 100,
  151028. _huff_lengthlist__44u8__short,
  151029. 0, 0, 0, 0, 0,
  151030. NULL,
  151031. NULL,
  151032. NULL,
  151033. NULL,
  151034. 0
  151035. };
  151036. static long _vq_quantlist__44u8_p1_0[] = {
  151037. 1,
  151038. 0,
  151039. 2,
  151040. };
  151041. static long _vq_lengthlist__44u8_p1_0[] = {
  151042. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 8, 9, 9, 7,
  151043. 9, 9, 5, 7, 7, 7, 9, 9, 8, 9, 9, 5, 7, 7, 7, 9,
  151044. 9, 7, 9, 9, 7, 9, 9, 9,10,11, 9,11,10, 7, 9, 9,
  151045. 9,11,10, 9,10,11, 5, 7, 7, 7, 9, 9, 7, 9, 9, 7,
  151046. 9, 9, 9,11,10, 9,10,10, 8, 9, 9, 9,11,11, 9,11,
  151047. 10,
  151048. };
  151049. static float _vq_quantthresh__44u8_p1_0[] = {
  151050. -0.5, 0.5,
  151051. };
  151052. static long _vq_quantmap__44u8_p1_0[] = {
  151053. 1, 0, 2,
  151054. };
  151055. static encode_aux_threshmatch _vq_auxt__44u8_p1_0 = {
  151056. _vq_quantthresh__44u8_p1_0,
  151057. _vq_quantmap__44u8_p1_0,
  151058. 3,
  151059. 3
  151060. };
  151061. static static_codebook _44u8_p1_0 = {
  151062. 4, 81,
  151063. _vq_lengthlist__44u8_p1_0,
  151064. 1, -535822336, 1611661312, 2, 0,
  151065. _vq_quantlist__44u8_p1_0,
  151066. NULL,
  151067. &_vq_auxt__44u8_p1_0,
  151068. NULL,
  151069. 0
  151070. };
  151071. static long _vq_quantlist__44u8_p2_0[] = {
  151072. 2,
  151073. 1,
  151074. 3,
  151075. 0,
  151076. 4,
  151077. };
  151078. static long _vq_lengthlist__44u8_p2_0[] = {
  151079. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  151080. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  151081. 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,10,
  151082. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  151083. 10, 9,10, 9,12,11, 9,10,10,12,12, 8, 9, 9,12,11,
  151084. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,14,11,
  151085. 11,12,13,14, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  151086. 10,12,12,11,12,11,13,13,11,12,12,14,14, 5, 7, 7,
  151087. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  151088. 12, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  151089. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,12,13, 6,
  151090. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  151091. 10,13,12,10,11,11,13,13, 9,10,10,12,12,10,11,11,
  151092. 13,13,10,11,11,13,13,12,12,13,13,14,12,13,13,14,
  151093. 14, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  151094. 11,13,12,14,13,12,13,13,14,14, 5, 7, 7, 9, 9, 7,
  151095. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  151096. 10,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  151097. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  151098. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  151099. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  151100. 10,11,12,13,12,13,13,14,14,12,12,13,13,14, 9,10,
  151101. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,13,
  151102. 15,14,12,13,13,14,13, 8, 9, 9,11,11, 9,10,10,12,
  151103. 12, 9,10,10,12,12,12,12,12,14,13,11,12,12,14,14,
  151104. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  151105. 13,13,14,15,12,13,13,14,15, 9,10,10,12,12,10,11,
  151106. 10,13,12,10,11,11,13,13,12,13,12,15,14,12,13,13,
  151107. 14,15,11,12,12,14,14,12,13,13,14,14,12,13,13,15,
  151108. 14,14,14,14,14,16,14,14,15,16,16,11,12,12,14,14,
  151109. 11,12,12,14,14,12,13,13,14,15,13,14,13,16,14,14,
  151110. 14,14,16,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  151111. 10,12,12,11,12,12,14,13,11,12,12,14,14, 9,10,10,
  151112. 12,12,10,11,11,13,13,10,10,11,12,13,12,13,13,15,
  151113. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  151114. 10,11,11,13,13,12,13,13,14,14,12,13,13,15,14,11,
  151115. 12,12,14,13,12,13,13,15,14,11,12,12,13,14,14,15,
  151116. 14,16,15,13,13,14,13,16,11,12,12,14,14,12,13,13,
  151117. 14,15,12,13,12,15,14,14,14,14,16,15,14,15,13,16,
  151118. 14,
  151119. };
  151120. static float _vq_quantthresh__44u8_p2_0[] = {
  151121. -1.5, -0.5, 0.5, 1.5,
  151122. };
  151123. static long _vq_quantmap__44u8_p2_0[] = {
  151124. 3, 1, 0, 2, 4,
  151125. };
  151126. static encode_aux_threshmatch _vq_auxt__44u8_p2_0 = {
  151127. _vq_quantthresh__44u8_p2_0,
  151128. _vq_quantmap__44u8_p2_0,
  151129. 5,
  151130. 5
  151131. };
  151132. static static_codebook _44u8_p2_0 = {
  151133. 4, 625,
  151134. _vq_lengthlist__44u8_p2_0,
  151135. 1, -533725184, 1611661312, 3, 0,
  151136. _vq_quantlist__44u8_p2_0,
  151137. NULL,
  151138. &_vq_auxt__44u8_p2_0,
  151139. NULL,
  151140. 0
  151141. };
  151142. static long _vq_quantlist__44u8_p3_0[] = {
  151143. 4,
  151144. 3,
  151145. 5,
  151146. 2,
  151147. 6,
  151148. 1,
  151149. 7,
  151150. 0,
  151151. 8,
  151152. };
  151153. static long _vq_lengthlist__44u8_p3_0[] = {
  151154. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  151155. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  151156. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  151157. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  151158. 9, 9,10,10,11,10,12,11, 9, 9, 9, 9,10,11,11,11,
  151159. 12,
  151160. };
  151161. static float _vq_quantthresh__44u8_p3_0[] = {
  151162. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  151163. };
  151164. static long _vq_quantmap__44u8_p3_0[] = {
  151165. 7, 5, 3, 1, 0, 2, 4, 6,
  151166. 8,
  151167. };
  151168. static encode_aux_threshmatch _vq_auxt__44u8_p3_0 = {
  151169. _vq_quantthresh__44u8_p3_0,
  151170. _vq_quantmap__44u8_p3_0,
  151171. 9,
  151172. 9
  151173. };
  151174. static static_codebook _44u8_p3_0 = {
  151175. 2, 81,
  151176. _vq_lengthlist__44u8_p3_0,
  151177. 1, -531628032, 1611661312, 4, 0,
  151178. _vq_quantlist__44u8_p3_0,
  151179. NULL,
  151180. &_vq_auxt__44u8_p3_0,
  151181. NULL,
  151182. 0
  151183. };
  151184. static long _vq_quantlist__44u8_p4_0[] = {
  151185. 8,
  151186. 7,
  151187. 9,
  151188. 6,
  151189. 10,
  151190. 5,
  151191. 11,
  151192. 4,
  151193. 12,
  151194. 3,
  151195. 13,
  151196. 2,
  151197. 14,
  151198. 1,
  151199. 15,
  151200. 0,
  151201. 16,
  151202. };
  151203. static long _vq_lengthlist__44u8_p4_0[] = {
  151204. 4, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,11,11,11,
  151205. 11, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  151206. 12,12, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  151207. 11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  151208. 11,11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,
  151209. 10,11,11,12,12, 7, 7, 7, 8, 8, 9, 8,10, 9,10, 9,
  151210. 11,10,12,11,13,12, 7, 7, 7, 8, 8, 8, 9, 9,10, 9,
  151211. 10,10,11,11,12,12,13, 8, 8, 8, 9, 9, 9, 9,10,10,
  151212. 11,10,11,11,12,12,13,13, 8, 8, 8, 9, 9, 9,10,10,
  151213. 10,10,11,11,11,12,12,12,13, 8, 9, 9, 9, 9,10, 9,
  151214. 11,10,11,11,12,11,13,12,13,13, 8, 9, 9, 9, 9, 9,
  151215. 10,10,11,11,11,11,12,12,13,13,13,10,10,10,10,10,
  151216. 11,10,11,11,12,11,13,12,13,13,14,13,10,10,10,10,
  151217. 10,10,11,11,11,11,12,12,13,13,13,13,14,11,11,11,
  151218. 11,11,12,11,12,12,13,12,13,13,14,13,14,14,11,11,
  151219. 11,11,11,11,12,12,12,12,13,13,13,13,14,14,14,11,
  151220. 12,12,12,12,13,12,13,12,13,13,14,13,14,14,14,14,
  151221. 11,12,12,12,12,12,12,13,13,13,13,13,14,14,14,14,
  151222. 14,
  151223. };
  151224. static float _vq_quantthresh__44u8_p4_0[] = {
  151225. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151226. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151227. };
  151228. static long _vq_quantmap__44u8_p4_0[] = {
  151229. 15, 13, 11, 9, 7, 5, 3, 1,
  151230. 0, 2, 4, 6, 8, 10, 12, 14,
  151231. 16,
  151232. };
  151233. static encode_aux_threshmatch _vq_auxt__44u8_p4_0 = {
  151234. _vq_quantthresh__44u8_p4_0,
  151235. _vq_quantmap__44u8_p4_0,
  151236. 17,
  151237. 17
  151238. };
  151239. static static_codebook _44u8_p4_0 = {
  151240. 2, 289,
  151241. _vq_lengthlist__44u8_p4_0,
  151242. 1, -529530880, 1611661312, 5, 0,
  151243. _vq_quantlist__44u8_p4_0,
  151244. NULL,
  151245. &_vq_auxt__44u8_p4_0,
  151246. NULL,
  151247. 0
  151248. };
  151249. static long _vq_quantlist__44u8_p5_0[] = {
  151250. 1,
  151251. 0,
  151252. 2,
  151253. };
  151254. static long _vq_lengthlist__44u8_p5_0[] = {
  151255. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  151256. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  151257. 10, 8,10,10, 7,10,10, 9,10,12, 9,12,11, 7,10,10,
  151258. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  151259. 10,10, 9,11,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  151260. 10,
  151261. };
  151262. static float _vq_quantthresh__44u8_p5_0[] = {
  151263. -5.5, 5.5,
  151264. };
  151265. static long _vq_quantmap__44u8_p5_0[] = {
  151266. 1, 0, 2,
  151267. };
  151268. static encode_aux_threshmatch _vq_auxt__44u8_p5_0 = {
  151269. _vq_quantthresh__44u8_p5_0,
  151270. _vq_quantmap__44u8_p5_0,
  151271. 3,
  151272. 3
  151273. };
  151274. static static_codebook _44u8_p5_0 = {
  151275. 4, 81,
  151276. _vq_lengthlist__44u8_p5_0,
  151277. 1, -529137664, 1618345984, 2, 0,
  151278. _vq_quantlist__44u8_p5_0,
  151279. NULL,
  151280. &_vq_auxt__44u8_p5_0,
  151281. NULL,
  151282. 0
  151283. };
  151284. static long _vq_quantlist__44u8_p5_1[] = {
  151285. 5,
  151286. 4,
  151287. 6,
  151288. 3,
  151289. 7,
  151290. 2,
  151291. 8,
  151292. 1,
  151293. 9,
  151294. 0,
  151295. 10,
  151296. };
  151297. static long _vq_lengthlist__44u8_p5_1[] = {
  151298. 4, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 5, 5, 6, 6,
  151299. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 7, 8, 8,
  151300. 8, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 6, 6, 6, 7,
  151301. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  151302. 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 7, 8, 7,
  151303. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  151304. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 8, 8,
  151305. 8, 8, 8, 8, 8, 8, 8, 9, 9,
  151306. };
  151307. static float _vq_quantthresh__44u8_p5_1[] = {
  151308. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151309. 3.5, 4.5,
  151310. };
  151311. static long _vq_quantmap__44u8_p5_1[] = {
  151312. 9, 7, 5, 3, 1, 0, 2, 4,
  151313. 6, 8, 10,
  151314. };
  151315. static encode_aux_threshmatch _vq_auxt__44u8_p5_1 = {
  151316. _vq_quantthresh__44u8_p5_1,
  151317. _vq_quantmap__44u8_p5_1,
  151318. 11,
  151319. 11
  151320. };
  151321. static static_codebook _44u8_p5_1 = {
  151322. 2, 121,
  151323. _vq_lengthlist__44u8_p5_1,
  151324. 1, -531365888, 1611661312, 4, 0,
  151325. _vq_quantlist__44u8_p5_1,
  151326. NULL,
  151327. &_vq_auxt__44u8_p5_1,
  151328. NULL,
  151329. 0
  151330. };
  151331. static long _vq_quantlist__44u8_p6_0[] = {
  151332. 6,
  151333. 5,
  151334. 7,
  151335. 4,
  151336. 8,
  151337. 3,
  151338. 9,
  151339. 2,
  151340. 10,
  151341. 1,
  151342. 11,
  151343. 0,
  151344. 12,
  151345. };
  151346. static long _vq_lengthlist__44u8_p6_0[] = {
  151347. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  151348. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7, 8,
  151349. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 7, 8, 8, 8, 8, 9,
  151350. 9,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 8,10, 9,11,
  151351. 10, 7, 8, 8, 8, 8, 8, 9, 9, 9,10,10,11,11, 7, 8,
  151352. 8, 8, 8, 9, 8, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  151353. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  151354. 9,10,10,11,11, 9, 9, 9, 9,10,10,10,10,10,10,11,
  151355. 11,12, 9, 9, 9,10, 9,10,10,10,10,11,10,12,11,10,
  151356. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  151357. 11,11,11,11,11,12,11,12,12,
  151358. };
  151359. static float _vq_quantthresh__44u8_p6_0[] = {
  151360. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  151361. 12.5, 17.5, 22.5, 27.5,
  151362. };
  151363. static long _vq_quantmap__44u8_p6_0[] = {
  151364. 11, 9, 7, 5, 3, 1, 0, 2,
  151365. 4, 6, 8, 10, 12,
  151366. };
  151367. static encode_aux_threshmatch _vq_auxt__44u8_p6_0 = {
  151368. _vq_quantthresh__44u8_p6_0,
  151369. _vq_quantmap__44u8_p6_0,
  151370. 13,
  151371. 13
  151372. };
  151373. static static_codebook _44u8_p6_0 = {
  151374. 2, 169,
  151375. _vq_lengthlist__44u8_p6_0,
  151376. 1, -526516224, 1616117760, 4, 0,
  151377. _vq_quantlist__44u8_p6_0,
  151378. NULL,
  151379. &_vq_auxt__44u8_p6_0,
  151380. NULL,
  151381. 0
  151382. };
  151383. static long _vq_quantlist__44u8_p6_1[] = {
  151384. 2,
  151385. 1,
  151386. 3,
  151387. 0,
  151388. 4,
  151389. };
  151390. static long _vq_lengthlist__44u8_p6_1[] = {
  151391. 3, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  151392. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  151393. };
  151394. static float _vq_quantthresh__44u8_p6_1[] = {
  151395. -1.5, -0.5, 0.5, 1.5,
  151396. };
  151397. static long _vq_quantmap__44u8_p6_1[] = {
  151398. 3, 1, 0, 2, 4,
  151399. };
  151400. static encode_aux_threshmatch _vq_auxt__44u8_p6_1 = {
  151401. _vq_quantthresh__44u8_p6_1,
  151402. _vq_quantmap__44u8_p6_1,
  151403. 5,
  151404. 5
  151405. };
  151406. static static_codebook _44u8_p6_1 = {
  151407. 2, 25,
  151408. _vq_lengthlist__44u8_p6_1,
  151409. 1, -533725184, 1611661312, 3, 0,
  151410. _vq_quantlist__44u8_p6_1,
  151411. NULL,
  151412. &_vq_auxt__44u8_p6_1,
  151413. NULL,
  151414. 0
  151415. };
  151416. static long _vq_quantlist__44u8_p7_0[] = {
  151417. 6,
  151418. 5,
  151419. 7,
  151420. 4,
  151421. 8,
  151422. 3,
  151423. 9,
  151424. 2,
  151425. 10,
  151426. 1,
  151427. 11,
  151428. 0,
  151429. 12,
  151430. };
  151431. static long _vq_lengthlist__44u8_p7_0[] = {
  151432. 1, 4, 5, 6, 6, 7, 7, 8, 8,10,10,11,11, 5, 6, 6,
  151433. 7, 7, 8, 8, 9, 9,11,10,12,11, 5, 6, 6, 7, 7, 8,
  151434. 8, 9, 9,10,11,11,12, 6, 7, 7, 8, 8, 9, 9,10,10,
  151435. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,12,13,
  151436. 12, 7, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  151437. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  151438. 11,11,12,12,13,13,14,14, 9, 9, 9,10,10,11,11,12,
  151439. 12,13,13,14,14,10,11,11,12,11,13,12,13,13,14,14,
  151440. 15,15,10,11,11,11,12,12,13,13,14,14,14,15,15,11,
  151441. 12,12,13,13,14,13,15,14,15,15,16,15,11,11,12,13,
  151442. 13,13,14,14,14,15,15,15,16,
  151443. };
  151444. static float _vq_quantthresh__44u8_p7_0[] = {
  151445. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  151446. 27.5, 38.5, 49.5, 60.5,
  151447. };
  151448. static long _vq_quantmap__44u8_p7_0[] = {
  151449. 11, 9, 7, 5, 3, 1, 0, 2,
  151450. 4, 6, 8, 10, 12,
  151451. };
  151452. static encode_aux_threshmatch _vq_auxt__44u8_p7_0 = {
  151453. _vq_quantthresh__44u8_p7_0,
  151454. _vq_quantmap__44u8_p7_0,
  151455. 13,
  151456. 13
  151457. };
  151458. static static_codebook _44u8_p7_0 = {
  151459. 2, 169,
  151460. _vq_lengthlist__44u8_p7_0,
  151461. 1, -523206656, 1618345984, 4, 0,
  151462. _vq_quantlist__44u8_p7_0,
  151463. NULL,
  151464. &_vq_auxt__44u8_p7_0,
  151465. NULL,
  151466. 0
  151467. };
  151468. static long _vq_quantlist__44u8_p7_1[] = {
  151469. 5,
  151470. 4,
  151471. 6,
  151472. 3,
  151473. 7,
  151474. 2,
  151475. 8,
  151476. 1,
  151477. 9,
  151478. 0,
  151479. 10,
  151480. };
  151481. static long _vq_lengthlist__44u8_p7_1[] = {
  151482. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  151483. 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  151484. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  151485. 7, 7, 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8,
  151486. 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 7, 7, 7,
  151487. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  151488. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  151489. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  151490. };
  151491. static float _vq_quantthresh__44u8_p7_1[] = {
  151492. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151493. 3.5, 4.5,
  151494. };
  151495. static long _vq_quantmap__44u8_p7_1[] = {
  151496. 9, 7, 5, 3, 1, 0, 2, 4,
  151497. 6, 8, 10,
  151498. };
  151499. static encode_aux_threshmatch _vq_auxt__44u8_p7_1 = {
  151500. _vq_quantthresh__44u8_p7_1,
  151501. _vq_quantmap__44u8_p7_1,
  151502. 11,
  151503. 11
  151504. };
  151505. static static_codebook _44u8_p7_1 = {
  151506. 2, 121,
  151507. _vq_lengthlist__44u8_p7_1,
  151508. 1, -531365888, 1611661312, 4, 0,
  151509. _vq_quantlist__44u8_p7_1,
  151510. NULL,
  151511. &_vq_auxt__44u8_p7_1,
  151512. NULL,
  151513. 0
  151514. };
  151515. static long _vq_quantlist__44u8_p8_0[] = {
  151516. 7,
  151517. 6,
  151518. 8,
  151519. 5,
  151520. 9,
  151521. 4,
  151522. 10,
  151523. 3,
  151524. 11,
  151525. 2,
  151526. 12,
  151527. 1,
  151528. 13,
  151529. 0,
  151530. 14,
  151531. };
  151532. static long _vq_lengthlist__44u8_p8_0[] = {
  151533. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8,10, 9,11,10, 4,
  151534. 6, 6, 8, 8,10, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  151535. 6, 8, 8,10,10, 9, 9,10,10,11,11,11,12, 7, 8, 8,
  151536. 10,10,11,11,11,10,12,11,12,12,13,11, 7, 8, 8,10,
  151537. 10,11,11,10,10,11,11,12,12,13,13, 8,10,10,11,11,
  151538. 12,11,12,11,13,12,13,12,14,13, 8,10, 9,11,11,12,
  151539. 12,12,12,12,12,13,13,14,13, 8, 9, 9,11,10,12,11,
  151540. 13,12,13,13,14,13,14,13, 8, 9, 9,10,11,12,12,12,
  151541. 12,13,13,14,15,14,14, 9,10,10,12,11,13,12,13,13,
  151542. 14,13,14,14,14,14, 9,10,10,12,12,12,12,13,13,14,
  151543. 14,14,15,14,14,10,11,11,13,12,13,12,14,14,14,14,
  151544. 14,14,15,15,10,11,11,12,12,13,13,14,14,14,15,15,
  151545. 14,16,15,11,12,12,13,12,14,14,14,13,15,14,15,15,
  151546. 15,17,11,12,12,13,13,14,14,14,15,15,14,15,15,14,
  151547. 17,
  151548. };
  151549. static float _vq_quantthresh__44u8_p8_0[] = {
  151550. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  151551. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  151552. };
  151553. static long _vq_quantmap__44u8_p8_0[] = {
  151554. 13, 11, 9, 7, 5, 3, 1, 0,
  151555. 2, 4, 6, 8, 10, 12, 14,
  151556. };
  151557. static encode_aux_threshmatch _vq_auxt__44u8_p8_0 = {
  151558. _vq_quantthresh__44u8_p8_0,
  151559. _vq_quantmap__44u8_p8_0,
  151560. 15,
  151561. 15
  151562. };
  151563. static static_codebook _44u8_p8_0 = {
  151564. 2, 225,
  151565. _vq_lengthlist__44u8_p8_0,
  151566. 1, -520986624, 1620377600, 4, 0,
  151567. _vq_quantlist__44u8_p8_0,
  151568. NULL,
  151569. &_vq_auxt__44u8_p8_0,
  151570. NULL,
  151571. 0
  151572. };
  151573. static long _vq_quantlist__44u8_p8_1[] = {
  151574. 10,
  151575. 9,
  151576. 11,
  151577. 8,
  151578. 12,
  151579. 7,
  151580. 13,
  151581. 6,
  151582. 14,
  151583. 5,
  151584. 15,
  151585. 4,
  151586. 16,
  151587. 3,
  151588. 17,
  151589. 2,
  151590. 18,
  151591. 1,
  151592. 19,
  151593. 0,
  151594. 20,
  151595. };
  151596. static long _vq_lengthlist__44u8_p8_1[] = {
  151597. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  151598. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  151599. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 5, 6, 6, 7, 7, 8,
  151600. 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  151601. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151602. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  151603. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  151604. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10, 8, 8,
  151605. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  151606. 10, 9,10, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,
  151607. 10,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9,
  151608. 9, 9, 9, 9, 9, 9,10,10,10,10, 9,10,10, 9, 9, 9,
  151609. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151610. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  151611. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,
  151612. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  151613. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  151614. 10, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  151615. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  151616. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  151617. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  151618. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  151619. 10,10,10,10,10, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151620. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  151621. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  151622. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  151623. 10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,10,
  151624. 10,10,10,10,10,10,10,10,10,
  151625. };
  151626. static float _vq_quantthresh__44u8_p8_1[] = {
  151627. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  151628. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  151629. 6.5, 7.5, 8.5, 9.5,
  151630. };
  151631. static long _vq_quantmap__44u8_p8_1[] = {
  151632. 19, 17, 15, 13, 11, 9, 7, 5,
  151633. 3, 1, 0, 2, 4, 6, 8, 10,
  151634. 12, 14, 16, 18, 20,
  151635. };
  151636. static encode_aux_threshmatch _vq_auxt__44u8_p8_1 = {
  151637. _vq_quantthresh__44u8_p8_1,
  151638. _vq_quantmap__44u8_p8_1,
  151639. 21,
  151640. 21
  151641. };
  151642. static static_codebook _44u8_p8_1 = {
  151643. 2, 441,
  151644. _vq_lengthlist__44u8_p8_1,
  151645. 1, -529268736, 1611661312, 5, 0,
  151646. _vq_quantlist__44u8_p8_1,
  151647. NULL,
  151648. &_vq_auxt__44u8_p8_1,
  151649. NULL,
  151650. 0
  151651. };
  151652. static long _vq_quantlist__44u8_p9_0[] = {
  151653. 4,
  151654. 3,
  151655. 5,
  151656. 2,
  151657. 6,
  151658. 1,
  151659. 7,
  151660. 0,
  151661. 8,
  151662. };
  151663. static long _vq_lengthlist__44u8_p9_0[] = {
  151664. 1, 3, 3, 9, 9, 9, 9, 9, 9, 4, 9, 9, 9, 9, 9, 9,
  151665. 9, 9, 5, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151666. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151667. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151668. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  151669. 8,
  151670. };
  151671. static float _vq_quantthresh__44u8_p9_0[] = {
  151672. -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5, 2327.5, 3258.5,
  151673. };
  151674. static long _vq_quantmap__44u8_p9_0[] = {
  151675. 7, 5, 3, 1, 0, 2, 4, 6,
  151676. 8,
  151677. };
  151678. static encode_aux_threshmatch _vq_auxt__44u8_p9_0 = {
  151679. _vq_quantthresh__44u8_p9_0,
  151680. _vq_quantmap__44u8_p9_0,
  151681. 9,
  151682. 9
  151683. };
  151684. static static_codebook _44u8_p9_0 = {
  151685. 2, 81,
  151686. _vq_lengthlist__44u8_p9_0,
  151687. 1, -511895552, 1631393792, 4, 0,
  151688. _vq_quantlist__44u8_p9_0,
  151689. NULL,
  151690. &_vq_auxt__44u8_p9_0,
  151691. NULL,
  151692. 0
  151693. };
  151694. static long _vq_quantlist__44u8_p9_1[] = {
  151695. 9,
  151696. 8,
  151697. 10,
  151698. 7,
  151699. 11,
  151700. 6,
  151701. 12,
  151702. 5,
  151703. 13,
  151704. 4,
  151705. 14,
  151706. 3,
  151707. 15,
  151708. 2,
  151709. 16,
  151710. 1,
  151711. 17,
  151712. 0,
  151713. 18,
  151714. };
  151715. static long _vq_lengthlist__44u8_p9_1[] = {
  151716. 1, 4, 4, 7, 7, 8, 7, 8, 6, 9, 7,10, 8,11,10,11,
  151717. 11,11,11, 4, 7, 6, 9, 9,10, 9, 9, 9,10,10,11,10,
  151718. 11,10,11,11,13,11, 4, 7, 7, 9, 9, 9, 9, 9, 9,10,
  151719. 10,11,10,11,11,11,12,11,12, 7, 9, 8,11,11,11,11,
  151720. 10,10,11,11,12,12,12,12,12,12,14,13, 7, 8, 9,10,
  151721. 11,11,11,10,10,11,11,11,11,12,12,14,12,13,14, 8,
  151722. 9, 9,11,11,11,11,11,11,12,12,14,12,15,14,14,14,
  151723. 15,14, 8, 9, 9,11,11,11,11,12,11,12,12,13,13,13,
  151724. 13,13,13,14,14, 8, 9, 9,11,10,12,11,12,12,13,13,
  151725. 13,13,15,14,14,14,16,16, 8, 9, 9,10,11,11,12,12,
  151726. 12,13,13,13,14,14,14,15,16,15,15, 9,10,10,11,12,
  151727. 12,13,13,13,14,14,16,14,14,16,16,16,16,15, 9,10,
  151728. 10,11,11,12,13,13,14,15,14,16,14,15,16,16,16,16,
  151729. 15,10,11,11,12,13,13,14,15,15,15,15,15,16,15,16,
  151730. 15,16,15,15,10,11,11,13,13,14,13,13,15,14,15,15,
  151731. 16,15,15,15,16,15,16,10,12,12,14,14,14,14,14,16,
  151732. 16,15,15,15,16,16,16,16,16,16,11,12,12,14,14,14,
  151733. 14,15,15,16,15,16,15,16,15,16,16,16,16,12,12,13,
  151734. 14,14,15,16,16,16,16,16,16,15,16,16,16,16,16,16,
  151735. 12,13,13,14,14,14,14,15,16,15,16,16,16,16,16,16,
  151736. 16,16,16,12,13,14,14,14,16,15,16,15,16,16,16,16,
  151737. 16,16,16,16,16,16,12,14,13,14,15,15,15,16,15,16,
  151738. 16,15,16,16,16,16,16,16,16,
  151739. };
  151740. static float _vq_quantthresh__44u8_p9_1[] = {
  151741. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  151742. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  151743. 367.5, 416.5,
  151744. };
  151745. static long _vq_quantmap__44u8_p9_1[] = {
  151746. 17, 15, 13, 11, 9, 7, 5, 3,
  151747. 1, 0, 2, 4, 6, 8, 10, 12,
  151748. 14, 16, 18,
  151749. };
  151750. static encode_aux_threshmatch _vq_auxt__44u8_p9_1 = {
  151751. _vq_quantthresh__44u8_p9_1,
  151752. _vq_quantmap__44u8_p9_1,
  151753. 19,
  151754. 19
  151755. };
  151756. static static_codebook _44u8_p9_1 = {
  151757. 2, 361,
  151758. _vq_lengthlist__44u8_p9_1,
  151759. 1, -518287360, 1622704128, 5, 0,
  151760. _vq_quantlist__44u8_p9_1,
  151761. NULL,
  151762. &_vq_auxt__44u8_p9_1,
  151763. NULL,
  151764. 0
  151765. };
  151766. static long _vq_quantlist__44u8_p9_2[] = {
  151767. 24,
  151768. 23,
  151769. 25,
  151770. 22,
  151771. 26,
  151772. 21,
  151773. 27,
  151774. 20,
  151775. 28,
  151776. 19,
  151777. 29,
  151778. 18,
  151779. 30,
  151780. 17,
  151781. 31,
  151782. 16,
  151783. 32,
  151784. 15,
  151785. 33,
  151786. 14,
  151787. 34,
  151788. 13,
  151789. 35,
  151790. 12,
  151791. 36,
  151792. 11,
  151793. 37,
  151794. 10,
  151795. 38,
  151796. 9,
  151797. 39,
  151798. 8,
  151799. 40,
  151800. 7,
  151801. 41,
  151802. 6,
  151803. 42,
  151804. 5,
  151805. 43,
  151806. 4,
  151807. 44,
  151808. 3,
  151809. 45,
  151810. 2,
  151811. 46,
  151812. 1,
  151813. 47,
  151814. 0,
  151815. 48,
  151816. };
  151817. static long _vq_lengthlist__44u8_p9_2[] = {
  151818. 2, 3, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  151819. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151820. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151821. 7,
  151822. };
  151823. static float _vq_quantthresh__44u8_p9_2[] = {
  151824. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  151825. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  151826. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151827. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151828. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  151829. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  151830. };
  151831. static long _vq_quantmap__44u8_p9_2[] = {
  151832. 47, 45, 43, 41, 39, 37, 35, 33,
  151833. 31, 29, 27, 25, 23, 21, 19, 17,
  151834. 15, 13, 11, 9, 7, 5, 3, 1,
  151835. 0, 2, 4, 6, 8, 10, 12, 14,
  151836. 16, 18, 20, 22, 24, 26, 28, 30,
  151837. 32, 34, 36, 38, 40, 42, 44, 46,
  151838. 48,
  151839. };
  151840. static encode_aux_threshmatch _vq_auxt__44u8_p9_2 = {
  151841. _vq_quantthresh__44u8_p9_2,
  151842. _vq_quantmap__44u8_p9_2,
  151843. 49,
  151844. 49
  151845. };
  151846. static static_codebook _44u8_p9_2 = {
  151847. 1, 49,
  151848. _vq_lengthlist__44u8_p9_2,
  151849. 1, -526909440, 1611661312, 6, 0,
  151850. _vq_quantlist__44u8_p9_2,
  151851. NULL,
  151852. &_vq_auxt__44u8_p9_2,
  151853. NULL,
  151854. 0
  151855. };
  151856. static long _huff_lengthlist__44u9__long[] = {
  151857. 3, 9,13,13,14,15,14,14,15,15, 5, 5, 9,10,12,12,
  151858. 13,14,16,15,10, 6, 6, 6, 8,11,12,13,16,15,11, 7,
  151859. 5, 3, 5, 8,10,12,15,15,10,10, 7, 4, 3, 5, 8,10,
  151860. 12,12,12,12, 9, 7, 5, 4, 6, 8,10,13,13,12,11, 9,
  151861. 7, 5, 5, 6, 9,12,14,12,12,10, 8, 6, 6, 6, 7,11,
  151862. 13,12,14,13,10, 8, 7, 7, 7,10,11,11,12,13,12,11,
  151863. 10, 8, 8, 9,
  151864. };
  151865. static static_codebook _huff_book__44u9__long = {
  151866. 2, 100,
  151867. _huff_lengthlist__44u9__long,
  151868. 0, 0, 0, 0, 0,
  151869. NULL,
  151870. NULL,
  151871. NULL,
  151872. NULL,
  151873. 0
  151874. };
  151875. static long _huff_lengthlist__44u9__short[] = {
  151876. 9,16,18,18,17,17,17,17,17,17, 5, 8,11,12,11,12,
  151877. 17,17,16,16, 6, 6, 8, 8, 9,10,14,15,16,16, 6, 7,
  151878. 7, 4, 6, 9,13,16,16,16, 6, 6, 7, 4, 5, 8,11,15,
  151879. 17,16, 7, 6, 7, 6, 6, 8, 9,10,14,16,11, 8, 8, 7,
  151880. 6, 6, 3, 4,10,15,14,12,12,10, 5, 6, 3, 3, 8,13,
  151881. 15,17,15,11, 6, 8, 6, 6, 9,14,17,15,15,12, 8,10,
  151882. 9, 9,12,15,
  151883. };
  151884. static static_codebook _huff_book__44u9__short = {
  151885. 2, 100,
  151886. _huff_lengthlist__44u9__short,
  151887. 0, 0, 0, 0, 0,
  151888. NULL,
  151889. NULL,
  151890. NULL,
  151891. NULL,
  151892. 0
  151893. };
  151894. static long _vq_quantlist__44u9_p1_0[] = {
  151895. 1,
  151896. 0,
  151897. 2,
  151898. };
  151899. static long _vq_lengthlist__44u9_p1_0[] = {
  151900. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  151901. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 7, 9,
  151902. 9, 7, 9, 9, 8, 9, 9, 9,10,11, 9,11,11, 7, 9, 9,
  151903. 9,11,10, 9,11,11, 5, 7, 7, 7, 9, 9, 8, 9,10, 7,
  151904. 9, 9, 9,11,11, 9,10,11, 7, 9,10, 9,11,11, 9,11,
  151905. 10,
  151906. };
  151907. static float _vq_quantthresh__44u9_p1_0[] = {
  151908. -0.5, 0.5,
  151909. };
  151910. static long _vq_quantmap__44u9_p1_0[] = {
  151911. 1, 0, 2,
  151912. };
  151913. static encode_aux_threshmatch _vq_auxt__44u9_p1_0 = {
  151914. _vq_quantthresh__44u9_p1_0,
  151915. _vq_quantmap__44u9_p1_0,
  151916. 3,
  151917. 3
  151918. };
  151919. static static_codebook _44u9_p1_0 = {
  151920. 4, 81,
  151921. _vq_lengthlist__44u9_p1_0,
  151922. 1, -535822336, 1611661312, 2, 0,
  151923. _vq_quantlist__44u9_p1_0,
  151924. NULL,
  151925. &_vq_auxt__44u9_p1_0,
  151926. NULL,
  151927. 0
  151928. };
  151929. static long _vq_quantlist__44u9_p2_0[] = {
  151930. 2,
  151931. 1,
  151932. 3,
  151933. 0,
  151934. 4,
  151935. };
  151936. static long _vq_lengthlist__44u9_p2_0[] = {
  151937. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  151938. 9, 9,11,10, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  151939. 8,10,10, 7, 8, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  151940. 11,11, 6, 7, 7, 9, 9, 7, 8, 8,10, 9, 7, 8, 8,10,
  151941. 10, 9,10, 9,11,11, 9,10,10,11,11, 8, 9, 9,11,11,
  151942. 9,10,10,12,11, 9,10,10,11,12,11,11,11,13,13,11,
  151943. 11,11,12,13, 8, 9, 9,11,11, 9,10,10,11,11, 9,10,
  151944. 10,12,11,11,12,11,13,12,11,11,12,13,13, 6, 7, 7,
  151945. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  151946. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  151947. 8, 9, 9,10,10,10,11,11,12,12,10,10,11,12,12, 7,
  151948. 8, 8,10,10, 8, 9, 8,10,10, 8, 9, 9,10,10,10,11,
  151949. 10,12,11,10,10,11,12,12, 9,10,10,11,12,10,11,11,
  151950. 12,12,10,11,10,12,12,12,12,12,13,13,11,12,12,13,
  151951. 13, 9,10,10,11,11, 9,10,10,12,12,10,11,11,12,13,
  151952. 11,12,11,13,12,12,12,12,13,14, 6, 7, 7, 9, 9, 7,
  151953. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,11,11, 9,10,
  151954. 10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,10, 8, 8, 9,
  151955. 10,10,10,11,10,12,12,10,10,11,11,12, 7, 8, 8,10,
  151956. 10, 8, 9, 9,10,10, 8, 9, 9,10,10,10,11,10,12,12,
  151957. 10,11,10,12,12, 9,10,10,12,11,10,11,11,12,12, 9,
  151958. 10,10,12,12,12,12,12,13,13,11,11,12,12,14, 9,10,
  151959. 10,11,12,10,11,11,12,12,10,11,11,12,12,11,12,12,
  151960. 14,14,12,12,12,13,13, 8, 9, 9,11,11, 9,10,10,12,
  151961. 11, 9,10,10,12,12,11,12,11,13,13,11,11,12,13,13,
  151962. 9,10,10,12,12,10,11,11,12,12,10,11,11,12,12,12,
  151963. 12,12,14,14,12,12,12,13,13, 9,10,10,12,11,10,11,
  151964. 10,12,12,10,11,11,12,12,11,12,12,14,13,12,12,12,
  151965. 13,14,11,12,11,13,13,11,12,12,13,13,12,12,12,14,
  151966. 14,13,13,13,13,15,13,13,14,15,15,11,11,11,13,13,
  151967. 11,12,11,13,13,11,12,12,13,13,12,13,12,15,13,13,
  151968. 13,14,14,15, 8, 9, 9,11,11, 9,10,10,11,12, 9,10,
  151969. 10,11,12,11,12,11,13,13,11,12,12,13,13, 9,10,10,
  151970. 11,12,10,11,10,12,12,10,10,11,12,13,12,12,12,14,
  151971. 13,11,12,12,13,14, 9,10,10,12,12,10,11,11,12,12,
  151972. 10,11,11,12,12,12,12,12,14,13,12,12,12,14,13,11,
  151973. 11,11,13,13,11,12,12,14,13,11,11,12,13,13,13,13,
  151974. 13,15,14,12,12,13,13,15,11,12,12,13,13,12,12,12,
  151975. 13,14,11,12,12,13,13,13,13,14,14,15,13,13,13,14,
  151976. 14,
  151977. };
  151978. static float _vq_quantthresh__44u9_p2_0[] = {
  151979. -1.5, -0.5, 0.5, 1.5,
  151980. };
  151981. static long _vq_quantmap__44u9_p2_0[] = {
  151982. 3, 1, 0, 2, 4,
  151983. };
  151984. static encode_aux_threshmatch _vq_auxt__44u9_p2_0 = {
  151985. _vq_quantthresh__44u9_p2_0,
  151986. _vq_quantmap__44u9_p2_0,
  151987. 5,
  151988. 5
  151989. };
  151990. static static_codebook _44u9_p2_0 = {
  151991. 4, 625,
  151992. _vq_lengthlist__44u9_p2_0,
  151993. 1, -533725184, 1611661312, 3, 0,
  151994. _vq_quantlist__44u9_p2_0,
  151995. NULL,
  151996. &_vq_auxt__44u9_p2_0,
  151997. NULL,
  151998. 0
  151999. };
  152000. static long _vq_quantlist__44u9_p3_0[] = {
  152001. 4,
  152002. 3,
  152003. 5,
  152004. 2,
  152005. 6,
  152006. 1,
  152007. 7,
  152008. 0,
  152009. 8,
  152010. };
  152011. static long _vq_lengthlist__44u9_p3_0[] = {
  152012. 3, 4, 4, 5, 5, 7, 7, 8, 8, 4, 5, 5, 6, 6, 7, 7,
  152013. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  152014. 8, 8, 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  152015. 8, 8, 9, 9,10,10, 7, 7, 7, 8, 8, 9, 9,10,10, 8,
  152016. 9, 9,10, 9,10,10,11,11, 8, 9, 9, 9,10,10,10,11,
  152017. 11,
  152018. };
  152019. static float _vq_quantthresh__44u9_p3_0[] = {
  152020. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  152021. };
  152022. static long _vq_quantmap__44u9_p3_0[] = {
  152023. 7, 5, 3, 1, 0, 2, 4, 6,
  152024. 8,
  152025. };
  152026. static encode_aux_threshmatch _vq_auxt__44u9_p3_0 = {
  152027. _vq_quantthresh__44u9_p3_0,
  152028. _vq_quantmap__44u9_p3_0,
  152029. 9,
  152030. 9
  152031. };
  152032. static static_codebook _44u9_p3_0 = {
  152033. 2, 81,
  152034. _vq_lengthlist__44u9_p3_0,
  152035. 1, -531628032, 1611661312, 4, 0,
  152036. _vq_quantlist__44u9_p3_0,
  152037. NULL,
  152038. &_vq_auxt__44u9_p3_0,
  152039. NULL,
  152040. 0
  152041. };
  152042. static long _vq_quantlist__44u9_p4_0[] = {
  152043. 8,
  152044. 7,
  152045. 9,
  152046. 6,
  152047. 10,
  152048. 5,
  152049. 11,
  152050. 4,
  152051. 12,
  152052. 3,
  152053. 13,
  152054. 2,
  152055. 14,
  152056. 1,
  152057. 15,
  152058. 0,
  152059. 16,
  152060. };
  152061. static long _vq_lengthlist__44u9_p4_0[] = {
  152062. 4, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  152063. 11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  152064. 11,11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  152065. 10,11,11, 6, 6, 6, 7, 6, 7, 7, 8, 8, 9, 9,10,10,
  152066. 11,11,12,11, 6, 6, 6, 6, 7, 7, 7, 8, 8, 9, 9,10,
  152067. 10,11,11,11,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,
  152068. 10,10,11,11,12,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  152069. 9,10,10,11,11,12,12, 8, 8, 8, 8, 8, 9, 8,10, 9,
  152070. 10,10,11,10,12,11,13,12, 8, 8, 8, 8, 8, 9, 9, 9,
  152071. 10,10,10,10,11,11,12,12,12, 8, 8, 8, 9, 9, 9, 9,
  152072. 10,10,11,10,12,11,12,12,13,12, 8, 8, 8, 9, 9, 9,
  152073. 9,10,10,10,11,11,11,12,12,12,13, 9, 9, 9,10,10,
  152074. 10,10,11,10,11,11,12,11,13,12,13,13, 9, 9,10,10,
  152075. 10,10,10,10,11,11,11,11,12,12,13,13,13,10,11,10,
  152076. 11,11,11,11,12,11,12,12,13,12,13,13,14,13,10,10,
  152077. 10,11,11,11,11,11,12,12,12,12,13,13,13,13,14,11,
  152078. 11,11,12,11,12,12,12,12,13,13,13,13,14,13,14,14,
  152079. 11,11,11,11,12,12,12,12,12,12,13,13,13,13,14,14,
  152080. 14,
  152081. };
  152082. static float _vq_quantthresh__44u9_p4_0[] = {
  152083. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  152084. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  152085. };
  152086. static long _vq_quantmap__44u9_p4_0[] = {
  152087. 15, 13, 11, 9, 7, 5, 3, 1,
  152088. 0, 2, 4, 6, 8, 10, 12, 14,
  152089. 16,
  152090. };
  152091. static encode_aux_threshmatch _vq_auxt__44u9_p4_0 = {
  152092. _vq_quantthresh__44u9_p4_0,
  152093. _vq_quantmap__44u9_p4_0,
  152094. 17,
  152095. 17
  152096. };
  152097. static static_codebook _44u9_p4_0 = {
  152098. 2, 289,
  152099. _vq_lengthlist__44u9_p4_0,
  152100. 1, -529530880, 1611661312, 5, 0,
  152101. _vq_quantlist__44u9_p4_0,
  152102. NULL,
  152103. &_vq_auxt__44u9_p4_0,
  152104. NULL,
  152105. 0
  152106. };
  152107. static long _vq_quantlist__44u9_p5_0[] = {
  152108. 1,
  152109. 0,
  152110. 2,
  152111. };
  152112. static long _vq_lengthlist__44u9_p5_0[] = {
  152113. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  152114. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  152115. 10, 8,10,10, 7,10,10, 9,10,12, 9,11,11, 7,10,10,
  152116. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  152117. 10,10, 9,12,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  152118. 10,
  152119. };
  152120. static float _vq_quantthresh__44u9_p5_0[] = {
  152121. -5.5, 5.5,
  152122. };
  152123. static long _vq_quantmap__44u9_p5_0[] = {
  152124. 1, 0, 2,
  152125. };
  152126. static encode_aux_threshmatch _vq_auxt__44u9_p5_0 = {
  152127. _vq_quantthresh__44u9_p5_0,
  152128. _vq_quantmap__44u9_p5_0,
  152129. 3,
  152130. 3
  152131. };
  152132. static static_codebook _44u9_p5_0 = {
  152133. 4, 81,
  152134. _vq_lengthlist__44u9_p5_0,
  152135. 1, -529137664, 1618345984, 2, 0,
  152136. _vq_quantlist__44u9_p5_0,
  152137. NULL,
  152138. &_vq_auxt__44u9_p5_0,
  152139. NULL,
  152140. 0
  152141. };
  152142. static long _vq_quantlist__44u9_p5_1[] = {
  152143. 5,
  152144. 4,
  152145. 6,
  152146. 3,
  152147. 7,
  152148. 2,
  152149. 8,
  152150. 1,
  152151. 9,
  152152. 0,
  152153. 10,
  152154. };
  152155. static long _vq_lengthlist__44u9_p5_1[] = {
  152156. 5, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 6,
  152157. 7, 7, 7, 7, 8, 7, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  152158. 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 6, 6, 6, 7,
  152159. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  152160. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  152161. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  152162. 8, 8, 8, 7, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  152163. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  152164. };
  152165. static float _vq_quantthresh__44u9_p5_1[] = {
  152166. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  152167. 3.5, 4.5,
  152168. };
  152169. static long _vq_quantmap__44u9_p5_1[] = {
  152170. 9, 7, 5, 3, 1, 0, 2, 4,
  152171. 6, 8, 10,
  152172. };
  152173. static encode_aux_threshmatch _vq_auxt__44u9_p5_1 = {
  152174. _vq_quantthresh__44u9_p5_1,
  152175. _vq_quantmap__44u9_p5_1,
  152176. 11,
  152177. 11
  152178. };
  152179. static static_codebook _44u9_p5_1 = {
  152180. 2, 121,
  152181. _vq_lengthlist__44u9_p5_1,
  152182. 1, -531365888, 1611661312, 4, 0,
  152183. _vq_quantlist__44u9_p5_1,
  152184. NULL,
  152185. &_vq_auxt__44u9_p5_1,
  152186. NULL,
  152187. 0
  152188. };
  152189. static long _vq_quantlist__44u9_p6_0[] = {
  152190. 6,
  152191. 5,
  152192. 7,
  152193. 4,
  152194. 8,
  152195. 3,
  152196. 9,
  152197. 2,
  152198. 10,
  152199. 1,
  152200. 11,
  152201. 0,
  152202. 12,
  152203. };
  152204. static long _vq_lengthlist__44u9_p6_0[] = {
  152205. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  152206. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 5, 6, 7, 7, 8,
  152207. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  152208. 10,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  152209. 10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 7, 8,
  152210. 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  152211. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  152212. 9,10,10,11,11, 9, 9, 9,10,10,10,10,10,11,11,11,
  152213. 11,12, 9, 9, 9,10,10,10,10,10,10,11,10,12,11,10,
  152214. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  152215. 10,11,11,11,11,12,11,12,12,
  152216. };
  152217. static float _vq_quantthresh__44u9_p6_0[] = {
  152218. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  152219. 12.5, 17.5, 22.5, 27.5,
  152220. };
  152221. static long _vq_quantmap__44u9_p6_0[] = {
  152222. 11, 9, 7, 5, 3, 1, 0, 2,
  152223. 4, 6, 8, 10, 12,
  152224. };
  152225. static encode_aux_threshmatch _vq_auxt__44u9_p6_0 = {
  152226. _vq_quantthresh__44u9_p6_0,
  152227. _vq_quantmap__44u9_p6_0,
  152228. 13,
  152229. 13
  152230. };
  152231. static static_codebook _44u9_p6_0 = {
  152232. 2, 169,
  152233. _vq_lengthlist__44u9_p6_0,
  152234. 1, -526516224, 1616117760, 4, 0,
  152235. _vq_quantlist__44u9_p6_0,
  152236. NULL,
  152237. &_vq_auxt__44u9_p6_0,
  152238. NULL,
  152239. 0
  152240. };
  152241. static long _vq_quantlist__44u9_p6_1[] = {
  152242. 2,
  152243. 1,
  152244. 3,
  152245. 0,
  152246. 4,
  152247. };
  152248. static long _vq_lengthlist__44u9_p6_1[] = {
  152249. 4, 4, 4, 5, 5, 4, 5, 4, 5, 5, 4, 4, 5, 5, 5, 5,
  152250. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  152251. };
  152252. static float _vq_quantthresh__44u9_p6_1[] = {
  152253. -1.5, -0.5, 0.5, 1.5,
  152254. };
  152255. static long _vq_quantmap__44u9_p6_1[] = {
  152256. 3, 1, 0, 2, 4,
  152257. };
  152258. static encode_aux_threshmatch _vq_auxt__44u9_p6_1 = {
  152259. _vq_quantthresh__44u9_p6_1,
  152260. _vq_quantmap__44u9_p6_1,
  152261. 5,
  152262. 5
  152263. };
  152264. static static_codebook _44u9_p6_1 = {
  152265. 2, 25,
  152266. _vq_lengthlist__44u9_p6_1,
  152267. 1, -533725184, 1611661312, 3, 0,
  152268. _vq_quantlist__44u9_p6_1,
  152269. NULL,
  152270. &_vq_auxt__44u9_p6_1,
  152271. NULL,
  152272. 0
  152273. };
  152274. static long _vq_quantlist__44u9_p7_0[] = {
  152275. 6,
  152276. 5,
  152277. 7,
  152278. 4,
  152279. 8,
  152280. 3,
  152281. 9,
  152282. 2,
  152283. 10,
  152284. 1,
  152285. 11,
  152286. 0,
  152287. 12,
  152288. };
  152289. static long _vq_lengthlist__44u9_p7_0[] = {
  152290. 1, 4, 5, 6, 6, 7, 7, 8, 9,10,10,11,11, 5, 6, 6,
  152291. 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 6, 6, 7, 7, 8,
  152292. 8, 9, 9,10,10,11,11, 6, 7, 7, 8, 8, 9, 9,10,10,
  152293. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,12,
  152294. 12, 8, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  152295. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  152296. 11,11,12,12,13,13,13,13, 9, 9, 9,10,10,11,11,12,
  152297. 12,13,13,14,14,10,10,10,11,11,12,12,13,13,14,13,
  152298. 15,14,10,10,10,11,11,12,12,13,13,14,14,14,14,11,
  152299. 11,12,12,12,13,13,14,14,14,14,15,15,11,11,12,12,
  152300. 12,13,13,14,14,14,15,15,15,
  152301. };
  152302. static float _vq_quantthresh__44u9_p7_0[] = {
  152303. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  152304. 27.5, 38.5, 49.5, 60.5,
  152305. };
  152306. static long _vq_quantmap__44u9_p7_0[] = {
  152307. 11, 9, 7, 5, 3, 1, 0, 2,
  152308. 4, 6, 8, 10, 12,
  152309. };
  152310. static encode_aux_threshmatch _vq_auxt__44u9_p7_0 = {
  152311. _vq_quantthresh__44u9_p7_0,
  152312. _vq_quantmap__44u9_p7_0,
  152313. 13,
  152314. 13
  152315. };
  152316. static static_codebook _44u9_p7_0 = {
  152317. 2, 169,
  152318. _vq_lengthlist__44u9_p7_0,
  152319. 1, -523206656, 1618345984, 4, 0,
  152320. _vq_quantlist__44u9_p7_0,
  152321. NULL,
  152322. &_vq_auxt__44u9_p7_0,
  152323. NULL,
  152324. 0
  152325. };
  152326. static long _vq_quantlist__44u9_p7_1[] = {
  152327. 5,
  152328. 4,
  152329. 6,
  152330. 3,
  152331. 7,
  152332. 2,
  152333. 8,
  152334. 1,
  152335. 9,
  152336. 0,
  152337. 10,
  152338. };
  152339. static long _vq_lengthlist__44u9_p7_1[] = {
  152340. 5, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7,
  152341. 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  152342. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 7, 7, 7,
  152343. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152344. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152345. 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152346. 7, 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 7, 8, 8, 7, 7,
  152347. 7, 7, 7, 7, 7, 8, 8, 8, 8,
  152348. };
  152349. static float _vq_quantthresh__44u9_p7_1[] = {
  152350. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  152351. 3.5, 4.5,
  152352. };
  152353. static long _vq_quantmap__44u9_p7_1[] = {
  152354. 9, 7, 5, 3, 1, 0, 2, 4,
  152355. 6, 8, 10,
  152356. };
  152357. static encode_aux_threshmatch _vq_auxt__44u9_p7_1 = {
  152358. _vq_quantthresh__44u9_p7_1,
  152359. _vq_quantmap__44u9_p7_1,
  152360. 11,
  152361. 11
  152362. };
  152363. static static_codebook _44u9_p7_1 = {
  152364. 2, 121,
  152365. _vq_lengthlist__44u9_p7_1,
  152366. 1, -531365888, 1611661312, 4, 0,
  152367. _vq_quantlist__44u9_p7_1,
  152368. NULL,
  152369. &_vq_auxt__44u9_p7_1,
  152370. NULL,
  152371. 0
  152372. };
  152373. static long _vq_quantlist__44u9_p8_0[] = {
  152374. 7,
  152375. 6,
  152376. 8,
  152377. 5,
  152378. 9,
  152379. 4,
  152380. 10,
  152381. 3,
  152382. 11,
  152383. 2,
  152384. 12,
  152385. 1,
  152386. 13,
  152387. 0,
  152388. 14,
  152389. };
  152390. static long _vq_lengthlist__44u9_p8_0[] = {
  152391. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,11,10, 4,
  152392. 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  152393. 6, 8, 8, 9,10, 9, 9,10,10,11,11,12,12, 7, 8, 8,
  152394. 10,10,11,11,10,10,11,11,12,12,13,12, 7, 8, 8,10,
  152395. 10,11,11,10,10,11,11,12,12,12,13, 8,10, 9,11,11,
  152396. 12,12,11,11,12,12,13,13,14,13, 8, 9, 9,11,11,12,
  152397. 12,11,12,12,12,13,13,14,13, 8, 9, 9,10,10,12,11,
  152398. 13,12,13,13,14,13,15,14, 8, 9, 9,10,10,11,12,12,
  152399. 12,13,13,13,14,14,14, 9,10,10,12,11,13,12,13,13,
  152400. 14,13,14,14,14,15, 9,10,10,11,12,12,12,13,13,14,
  152401. 14,14,15,15,15,10,11,11,12,12,13,13,14,14,14,14,
  152402. 15,14,16,15,10,11,11,12,12,13,13,13,14,14,14,14,
  152403. 14,15,16,11,12,12,13,13,14,13,14,14,15,14,15,16,
  152404. 16,16,11,12,12,13,13,14,13,14,14,15,15,15,16,15,
  152405. 15,
  152406. };
  152407. static float _vq_quantthresh__44u9_p8_0[] = {
  152408. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  152409. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  152410. };
  152411. static long _vq_quantmap__44u9_p8_0[] = {
  152412. 13, 11, 9, 7, 5, 3, 1, 0,
  152413. 2, 4, 6, 8, 10, 12, 14,
  152414. };
  152415. static encode_aux_threshmatch _vq_auxt__44u9_p8_0 = {
  152416. _vq_quantthresh__44u9_p8_0,
  152417. _vq_quantmap__44u9_p8_0,
  152418. 15,
  152419. 15
  152420. };
  152421. static static_codebook _44u9_p8_0 = {
  152422. 2, 225,
  152423. _vq_lengthlist__44u9_p8_0,
  152424. 1, -520986624, 1620377600, 4, 0,
  152425. _vq_quantlist__44u9_p8_0,
  152426. NULL,
  152427. &_vq_auxt__44u9_p8_0,
  152428. NULL,
  152429. 0
  152430. };
  152431. static long _vq_quantlist__44u9_p8_1[] = {
  152432. 10,
  152433. 9,
  152434. 11,
  152435. 8,
  152436. 12,
  152437. 7,
  152438. 13,
  152439. 6,
  152440. 14,
  152441. 5,
  152442. 15,
  152443. 4,
  152444. 16,
  152445. 3,
  152446. 17,
  152447. 2,
  152448. 18,
  152449. 1,
  152450. 19,
  152451. 0,
  152452. 20,
  152453. };
  152454. static long _vq_lengthlist__44u9_p8_1[] = {
  152455. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  152456. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  152457. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8,
  152458. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  152459. 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  152460. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  152461. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  152462. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10, 8, 8,
  152463. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152464. 9,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152465. 10, 9,10, 9,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  152466. 9, 9, 9, 9, 9,10,10, 9,10,10,10,10,10, 9, 9, 9,
  152467. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  152468. 10,10, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  152469. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152470. 9, 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  152471. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  152472. 10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  152473. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  152474. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  152475. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152476. 9, 9, 9, 9,10, 9, 9,10,10,10,10,10,10,10,10,10,
  152477. 10,10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,
  152478. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,10,
  152479. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  152480. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  152481. 10,10,10,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  152482. 10,10,10,10,10,10,10,10,10,
  152483. };
  152484. static float _vq_quantthresh__44u9_p8_1[] = {
  152485. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  152486. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  152487. 6.5, 7.5, 8.5, 9.5,
  152488. };
  152489. static long _vq_quantmap__44u9_p8_1[] = {
  152490. 19, 17, 15, 13, 11, 9, 7, 5,
  152491. 3, 1, 0, 2, 4, 6, 8, 10,
  152492. 12, 14, 16, 18, 20,
  152493. };
  152494. static encode_aux_threshmatch _vq_auxt__44u9_p8_1 = {
  152495. _vq_quantthresh__44u9_p8_1,
  152496. _vq_quantmap__44u9_p8_1,
  152497. 21,
  152498. 21
  152499. };
  152500. static static_codebook _44u9_p8_1 = {
  152501. 2, 441,
  152502. _vq_lengthlist__44u9_p8_1,
  152503. 1, -529268736, 1611661312, 5, 0,
  152504. _vq_quantlist__44u9_p8_1,
  152505. NULL,
  152506. &_vq_auxt__44u9_p8_1,
  152507. NULL,
  152508. 0
  152509. };
  152510. static long _vq_quantlist__44u9_p9_0[] = {
  152511. 7,
  152512. 6,
  152513. 8,
  152514. 5,
  152515. 9,
  152516. 4,
  152517. 10,
  152518. 3,
  152519. 11,
  152520. 2,
  152521. 12,
  152522. 1,
  152523. 13,
  152524. 0,
  152525. 14,
  152526. };
  152527. static long _vq_lengthlist__44u9_p9_0[] = {
  152528. 1, 3, 3,11,11,11,11,11,11,11,11,11,11,11,11, 4,
  152529. 10,11,11,11,11,11,11,11,11,11,11,11,11,11, 4,10,
  152530. 10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152531. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152532. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152533. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152534. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152535. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152536. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152537. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152538. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152539. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152540. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152541. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152542. 10,
  152543. };
  152544. static float _vq_quantthresh__44u9_p9_0[] = {
  152545. -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5,
  152546. 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  152547. };
  152548. static long _vq_quantmap__44u9_p9_0[] = {
  152549. 13, 11, 9, 7, 5, 3, 1, 0,
  152550. 2, 4, 6, 8, 10, 12, 14,
  152551. };
  152552. static encode_aux_threshmatch _vq_auxt__44u9_p9_0 = {
  152553. _vq_quantthresh__44u9_p9_0,
  152554. _vq_quantmap__44u9_p9_0,
  152555. 15,
  152556. 15
  152557. };
  152558. static static_codebook _44u9_p9_0 = {
  152559. 2, 225,
  152560. _vq_lengthlist__44u9_p9_0,
  152561. 1, -510036736, 1631393792, 4, 0,
  152562. _vq_quantlist__44u9_p9_0,
  152563. NULL,
  152564. &_vq_auxt__44u9_p9_0,
  152565. NULL,
  152566. 0
  152567. };
  152568. static long _vq_quantlist__44u9_p9_1[] = {
  152569. 9,
  152570. 8,
  152571. 10,
  152572. 7,
  152573. 11,
  152574. 6,
  152575. 12,
  152576. 5,
  152577. 13,
  152578. 4,
  152579. 14,
  152580. 3,
  152581. 15,
  152582. 2,
  152583. 16,
  152584. 1,
  152585. 17,
  152586. 0,
  152587. 18,
  152588. };
  152589. static long _vq_lengthlist__44u9_p9_1[] = {
  152590. 1, 4, 4, 7, 7, 8, 7, 8, 7, 9, 8,10, 9,10,10,11,
  152591. 11,12,12, 4, 7, 6, 9, 9,10, 9, 9, 8,10,10,11,10,
  152592. 12,10,13,12,13,12, 4, 6, 6, 9, 9, 9, 9, 9, 9,10,
  152593. 10,11,11,11,12,12,12,12,12, 7, 9, 8,11,10,10,10,
  152594. 11,10,11,11,12,12,13,12,13,13,13,13, 7, 8, 9,10,
  152595. 10,11,11,10,10,11,11,11,12,13,13,13,13,14,14, 8,
  152596. 9, 9,11,11,12,11,12,12,13,12,12,13,13,14,15,14,
  152597. 14,14, 8, 9, 9,10,11,11,11,12,12,13,12,13,13,14,
  152598. 14,14,15,14,16, 8, 9, 9,11,10,12,12,12,12,15,13,
  152599. 13,13,17,14,15,15,15,14, 8, 9, 9,10,11,11,12,13,
  152600. 12,13,13,13,14,15,14,14,14,16,15, 9,11,10,12,12,
  152601. 13,13,13,13,14,14,16,15,14,14,14,15,15,17, 9,10,
  152602. 10,11,11,13,13,13,14,14,13,15,14,15,14,15,16,15,
  152603. 16,10,11,11,12,12,13,14,15,14,15,14,14,15,17,16,
  152604. 15,15,17,17,10,12,11,13,12,14,14,13,14,15,15,15,
  152605. 15,16,17,17,15,17,16,11,12,12,14,13,15,14,15,16,
  152606. 17,15,17,15,17,15,15,16,17,15,11,11,12,14,14,14,
  152607. 14,14,15,15,16,15,17,17,17,16,17,16,15,12,12,13,
  152608. 14,14,14,15,14,15,15,16,16,17,16,17,15,17,17,16,
  152609. 12,14,12,14,14,15,15,15,14,14,16,16,16,15,16,16,
  152610. 15,17,15,12,13,13,14,15,14,15,17,15,17,16,17,17,
  152611. 17,16,17,16,17,17,12,13,13,14,16,15,15,15,16,15,
  152612. 17,17,15,17,15,17,16,16,17,
  152613. };
  152614. static float _vq_quantthresh__44u9_p9_1[] = {
  152615. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  152616. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  152617. 367.5, 416.5,
  152618. };
  152619. static long _vq_quantmap__44u9_p9_1[] = {
  152620. 17, 15, 13, 11, 9, 7, 5, 3,
  152621. 1, 0, 2, 4, 6, 8, 10, 12,
  152622. 14, 16, 18,
  152623. };
  152624. static encode_aux_threshmatch _vq_auxt__44u9_p9_1 = {
  152625. _vq_quantthresh__44u9_p9_1,
  152626. _vq_quantmap__44u9_p9_1,
  152627. 19,
  152628. 19
  152629. };
  152630. static static_codebook _44u9_p9_1 = {
  152631. 2, 361,
  152632. _vq_lengthlist__44u9_p9_1,
  152633. 1, -518287360, 1622704128, 5, 0,
  152634. _vq_quantlist__44u9_p9_1,
  152635. NULL,
  152636. &_vq_auxt__44u9_p9_1,
  152637. NULL,
  152638. 0
  152639. };
  152640. static long _vq_quantlist__44u9_p9_2[] = {
  152641. 24,
  152642. 23,
  152643. 25,
  152644. 22,
  152645. 26,
  152646. 21,
  152647. 27,
  152648. 20,
  152649. 28,
  152650. 19,
  152651. 29,
  152652. 18,
  152653. 30,
  152654. 17,
  152655. 31,
  152656. 16,
  152657. 32,
  152658. 15,
  152659. 33,
  152660. 14,
  152661. 34,
  152662. 13,
  152663. 35,
  152664. 12,
  152665. 36,
  152666. 11,
  152667. 37,
  152668. 10,
  152669. 38,
  152670. 9,
  152671. 39,
  152672. 8,
  152673. 40,
  152674. 7,
  152675. 41,
  152676. 6,
  152677. 42,
  152678. 5,
  152679. 43,
  152680. 4,
  152681. 44,
  152682. 3,
  152683. 45,
  152684. 2,
  152685. 46,
  152686. 1,
  152687. 47,
  152688. 0,
  152689. 48,
  152690. };
  152691. static long _vq_lengthlist__44u9_p9_2[] = {
  152692. 2, 4, 4, 5, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  152693. 6, 6, 6, 7, 6, 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152694. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152695. 7,
  152696. };
  152697. static float _vq_quantthresh__44u9_p9_2[] = {
  152698. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  152699. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  152700. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  152701. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  152702. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  152703. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  152704. };
  152705. static long _vq_quantmap__44u9_p9_2[] = {
  152706. 47, 45, 43, 41, 39, 37, 35, 33,
  152707. 31, 29, 27, 25, 23, 21, 19, 17,
  152708. 15, 13, 11, 9, 7, 5, 3, 1,
  152709. 0, 2, 4, 6, 8, 10, 12, 14,
  152710. 16, 18, 20, 22, 24, 26, 28, 30,
  152711. 32, 34, 36, 38, 40, 42, 44, 46,
  152712. 48,
  152713. };
  152714. static encode_aux_threshmatch _vq_auxt__44u9_p9_2 = {
  152715. _vq_quantthresh__44u9_p9_2,
  152716. _vq_quantmap__44u9_p9_2,
  152717. 49,
  152718. 49
  152719. };
  152720. static static_codebook _44u9_p9_2 = {
  152721. 1, 49,
  152722. _vq_lengthlist__44u9_p9_2,
  152723. 1, -526909440, 1611661312, 6, 0,
  152724. _vq_quantlist__44u9_p9_2,
  152725. NULL,
  152726. &_vq_auxt__44u9_p9_2,
  152727. NULL,
  152728. 0
  152729. };
  152730. static long _huff_lengthlist__44un1__long[] = {
  152731. 5, 6,12, 9,14, 9, 9,19, 6, 1, 5, 5, 8, 7, 9,19,
  152732. 12, 4, 4, 7, 7, 9,11,18, 9, 5, 6, 6, 8, 7, 8,17,
  152733. 14, 8, 7, 8, 8,10,12,18, 9, 6, 8, 6, 8, 6, 8,18,
  152734. 9, 8,11, 8,11, 7, 5,15,16,18,18,18,17,15,11,18,
  152735. };
  152736. static static_codebook _huff_book__44un1__long = {
  152737. 2, 64,
  152738. _huff_lengthlist__44un1__long,
  152739. 0, 0, 0, 0, 0,
  152740. NULL,
  152741. NULL,
  152742. NULL,
  152743. NULL,
  152744. 0
  152745. };
  152746. static long _vq_quantlist__44un1__p1_0[] = {
  152747. 1,
  152748. 0,
  152749. 2,
  152750. };
  152751. static long _vq_lengthlist__44un1__p1_0[] = {
  152752. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  152753. 10,11, 5, 8, 8, 8,11,10, 8,11,10, 4, 9, 9, 8,11,
  152754. 11, 8,11,11, 8,12,11,10,12,14,11,13,13, 7,11,11,
  152755. 10,13,11,11,13,14, 4, 8, 9, 8,11,11, 8,11,12, 7,
  152756. 11,11,11,14,13,10,11,13, 8,11,12,11,13,13,10,14,
  152757. 12,
  152758. };
  152759. static float _vq_quantthresh__44un1__p1_0[] = {
  152760. -0.5, 0.5,
  152761. };
  152762. static long _vq_quantmap__44un1__p1_0[] = {
  152763. 1, 0, 2,
  152764. };
  152765. static encode_aux_threshmatch _vq_auxt__44un1__p1_0 = {
  152766. _vq_quantthresh__44un1__p1_0,
  152767. _vq_quantmap__44un1__p1_0,
  152768. 3,
  152769. 3
  152770. };
  152771. static static_codebook _44un1__p1_0 = {
  152772. 4, 81,
  152773. _vq_lengthlist__44un1__p1_0,
  152774. 1, -535822336, 1611661312, 2, 0,
  152775. _vq_quantlist__44un1__p1_0,
  152776. NULL,
  152777. &_vq_auxt__44un1__p1_0,
  152778. NULL,
  152779. 0
  152780. };
  152781. static long _vq_quantlist__44un1__p2_0[] = {
  152782. 1,
  152783. 0,
  152784. 2,
  152785. };
  152786. static long _vq_lengthlist__44un1__p2_0[] = {
  152787. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  152788. 7, 9, 5, 7, 7, 6, 8, 7, 7, 9, 8, 4, 7, 7, 7, 9,
  152789. 8, 7, 8, 8, 7, 9, 8, 8, 8,10, 9,10,10, 6, 8, 8,
  152790. 7,10, 8, 9,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  152791. 8, 8, 9,10,10, 7, 8,10, 6, 8, 9, 9,10,10, 8,10,
  152792. 8,
  152793. };
  152794. static float _vq_quantthresh__44un1__p2_0[] = {
  152795. -0.5, 0.5,
  152796. };
  152797. static long _vq_quantmap__44un1__p2_0[] = {
  152798. 1, 0, 2,
  152799. };
  152800. static encode_aux_threshmatch _vq_auxt__44un1__p2_0 = {
  152801. _vq_quantthresh__44un1__p2_0,
  152802. _vq_quantmap__44un1__p2_0,
  152803. 3,
  152804. 3
  152805. };
  152806. static static_codebook _44un1__p2_0 = {
  152807. 4, 81,
  152808. _vq_lengthlist__44un1__p2_0,
  152809. 1, -535822336, 1611661312, 2, 0,
  152810. _vq_quantlist__44un1__p2_0,
  152811. NULL,
  152812. &_vq_auxt__44un1__p2_0,
  152813. NULL,
  152814. 0
  152815. };
  152816. static long _vq_quantlist__44un1__p3_0[] = {
  152817. 2,
  152818. 1,
  152819. 3,
  152820. 0,
  152821. 4,
  152822. };
  152823. static long _vq_lengthlist__44un1__p3_0[] = {
  152824. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  152825. 10, 9,12,12, 9, 9,10,11,12, 6, 8, 8,10,10, 8,10,
  152826. 10,11,11, 8, 9,10,11,11,10,11,11,13,13,10,11,11,
  152827. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10,10,11,
  152828. 11,10,11,11,13,12,10,11,11,13,12, 9,11,11,15,13,
  152829. 10,12,11,15,13,10,11,11,15,14,12,14,13,16,15,12,
  152830. 13,13,17,16, 9,11,11,13,15,10,11,12,14,15,10,11,
  152831. 12,14,15,12,13,13,15,16,12,13,13,16,16, 5, 8, 8,
  152832. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  152833. 14,11,12,12,14,14, 8,11,10,13,12,10,11,12,12,13,
  152834. 10,12,12,13,13,12,12,13,13,15,11,12,13,15,14, 7,
  152835. 10,10,12,12, 9,12,11,13,12,10,12,12,13,14,12,13,
  152836. 12,15,13,11,13,12,14,15,10,12,12,16,14,11,12,12,
  152837. 16,15,11,13,12,17,16,13,13,15,15,17,13,15,15,20,
  152838. 17,10,12,12,14,16,11,12,12,15,15,11,13,13,15,18,
  152839. 13,14,13,15,15,13,15,14,16,16, 5, 8, 8,11,11, 8,
  152840. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  152841. 12,14,15, 7,10,10,13,12,10,12,12,14,13, 9,10,12,
  152842. 12,13,11,13,13,15,15,11,12,13,13,15, 8,10,10,12,
  152843. 13,10,12,12,13,13,10,12,11,13,13,11,13,12,15,15,
  152844. 12,13,12,15,13,10,12,12,16,14,11,12,12,16,15,10,
  152845. 12,12,16,14,14,15,14,18,16,13,13,14,15,16,10,12,
  152846. 12,14,16,11,13,13,16,16,11,13,12,14,16,13,15,15,
  152847. 18,18,13,15,13,16,14, 8,11,11,16,16,10,13,13,17,
  152848. 16,10,12,12,16,15,14,16,15,20,17,13,14,14,17,17,
  152849. 9,12,12,16,16,11,13,14,16,17,11,13,13,16,16,15,
  152850. 15,19,18, 0,14,15,15,18,18, 9,12,12,17,16,11,13,
  152851. 12,17,16,11,12,13,15,17,15,16,15, 0,19,14,15,14,
  152852. 19,18,12,14,14, 0,16,13,14,14,19,18,13,15,16,17,
  152853. 16,15,15,17,18, 0,14,16,16,19, 0,12,14,14,16,18,
  152854. 13,15,13,17,18,13,15,14,17,18,15,18,14,18,18,16,
  152855. 17,16, 0,17, 8,11,11,15,15,10,12,12,16,16,10,13,
  152856. 13,16,16,13,15,14,17,17,14,15,17,17,18, 9,12,12,
  152857. 16,15,11,13,13,16,16,11,12,13,17,17,14,14,15,17,
  152858. 17,14,15,16, 0,18, 9,12,12,16,17,11,13,13,16,17,
  152859. 11,14,13,18,17,14,16,14,17,17,15,17,17,18,18,12,
  152860. 14,14, 0,16,13,15,15,19, 0,12,13,15, 0, 0,14,17,
  152861. 16,19, 0,16,15,18,18, 0,12,14,14,17, 0,13,14,14,
  152862. 17, 0,13,15,14, 0,18,15,16,16, 0,18,15,18,15, 0,
  152863. 17,
  152864. };
  152865. static float _vq_quantthresh__44un1__p3_0[] = {
  152866. -1.5, -0.5, 0.5, 1.5,
  152867. };
  152868. static long _vq_quantmap__44un1__p3_0[] = {
  152869. 3, 1, 0, 2, 4,
  152870. };
  152871. static encode_aux_threshmatch _vq_auxt__44un1__p3_0 = {
  152872. _vq_quantthresh__44un1__p3_0,
  152873. _vq_quantmap__44un1__p3_0,
  152874. 5,
  152875. 5
  152876. };
  152877. static static_codebook _44un1__p3_0 = {
  152878. 4, 625,
  152879. _vq_lengthlist__44un1__p3_0,
  152880. 1, -533725184, 1611661312, 3, 0,
  152881. _vq_quantlist__44un1__p3_0,
  152882. NULL,
  152883. &_vq_auxt__44un1__p3_0,
  152884. NULL,
  152885. 0
  152886. };
  152887. static long _vq_quantlist__44un1__p4_0[] = {
  152888. 2,
  152889. 1,
  152890. 3,
  152891. 0,
  152892. 4,
  152893. };
  152894. static long _vq_lengthlist__44un1__p4_0[] = {
  152895. 3, 5, 5, 9, 9, 5, 6, 6,10, 9, 5, 6, 6, 9,10,10,
  152896. 10,10,12,11, 9,10,10,12,12, 5, 7, 7,10,10, 7, 7,
  152897. 8,10,11, 7, 7, 8,10,11,10,10,11,11,13,10,10,11,
  152898. 11,13, 6, 7, 7,10,10, 7, 8, 7,11,10, 7, 8, 7,10,
  152899. 10,10,11, 9,13,11,10,11,10,13,11,10,10,10,14,13,
  152900. 10,11,11,14,13,10,10,11,13,14,12,12,13,15,15,12,
  152901. 12,13,13,14,10,10,10,12,13,10,11,10,13,13,10,11,
  152902. 11,13,13,12,13,12,14,13,12,13,13,14,13, 5, 7, 7,
  152903. 10,10, 7, 8, 8,11,10, 7, 8, 8,10,10,11,11,11,13,
  152904. 13,10,11,11,12,12, 7, 8, 8,11,11, 7, 8, 9,10,12,
  152905. 8, 9, 9,11,11,11,10,12,11,14,11,11,12,13,13, 6,
  152906. 8, 8,10,11, 7, 9, 7,12,10, 8, 9,10,11,12,10,12,
  152907. 10,14,11,11,12,11,13,13,10,11,11,14,14,10,10,11,
  152908. 13,14,11,12,12,15,13,12,11,14,12,16,12,13,14,15,
  152909. 16,10,10,11,13,14,10,11,10,14,12,11,12,12,13,14,
  152910. 12,13,11,15,12,14,14,14,15,15, 5, 7, 7,10,10, 7,
  152911. 8, 8,10,10, 7, 8, 8,10,11,10,11,10,12,12,10,11,
  152912. 11,12,13, 6, 8, 8,11,11, 8, 9, 9,12,11, 7, 7, 9,
  152913. 10,12,11,11,11,12,13,11,10,12,11,15, 7, 8, 8,11,
  152914. 11, 8, 9, 9,11,11, 7, 9, 8,12,10,11,12,11,13,12,
  152915. 11,12,10,15,11,10,11,10,14,12,11,12,11,14,13,10,
  152916. 10,11,13,14,13,13,13,17,15,12,11,14,12,15,10,10,
  152917. 11,13,14,11,12,12,14,14,10,11,10,14,13,13,14,13,
  152918. 16,17,12,14,11,16,12, 9,10,10,14,13,10,11,10,14,
  152919. 14,10,11,11,13,13,13,14,14,16,15,12,13,13,14,14,
  152920. 9,11,10,14,13,10,10,12,13,14,11,12,11,14,13,13,
  152921. 14,14,14,15,13,14,14,15,15, 9,10,11,13,14,10,11,
  152922. 10,15,13,11,11,12,12,15,13,14,12,15,14,13,13,14,
  152923. 14,15,12,13,12,16,14,11,11,12,15,14,13,15,13,16,
  152924. 14,13,12,15,12,17,15,16,15,16,16,12,12,13,13,15,
  152925. 11,13,11,15,14,13,13,14,15,17,13,14,12, 0,13,14,
  152926. 15,14,15, 0, 9,10,10,13,13,10,11,11,13,13,10,11,
  152927. 11,13,13,12,13,12,14,14,13,14,14,15,17, 9,10,10,
  152928. 13,13,11,12,11,15,12,10,10,11,13,16,13,14,13,15,
  152929. 14,13,13,14,15,16,10,10,11,13,14,11,11,12,13,14,
  152930. 10,12,11,14,14,13,13,13,14,15,13,15,13,16,15,12,
  152931. 13,12,15,13,12,15,13,15,15,11,11,13,14,15,15,15,
  152932. 15,15,17,13,12,14,13,17,12,12,14,14,15,13,13,14,
  152933. 14,16,11,13,11,16,15,14,16,16,17, 0,14,13,11,16,
  152934. 12,
  152935. };
  152936. static float _vq_quantthresh__44un1__p4_0[] = {
  152937. -1.5, -0.5, 0.5, 1.5,
  152938. };
  152939. static long _vq_quantmap__44un1__p4_0[] = {
  152940. 3, 1, 0, 2, 4,
  152941. };
  152942. static encode_aux_threshmatch _vq_auxt__44un1__p4_0 = {
  152943. _vq_quantthresh__44un1__p4_0,
  152944. _vq_quantmap__44un1__p4_0,
  152945. 5,
  152946. 5
  152947. };
  152948. static static_codebook _44un1__p4_0 = {
  152949. 4, 625,
  152950. _vq_lengthlist__44un1__p4_0,
  152951. 1, -533725184, 1611661312, 3, 0,
  152952. _vq_quantlist__44un1__p4_0,
  152953. NULL,
  152954. &_vq_auxt__44un1__p4_0,
  152955. NULL,
  152956. 0
  152957. };
  152958. static long _vq_quantlist__44un1__p5_0[] = {
  152959. 4,
  152960. 3,
  152961. 5,
  152962. 2,
  152963. 6,
  152964. 1,
  152965. 7,
  152966. 0,
  152967. 8,
  152968. };
  152969. static long _vq_lengthlist__44un1__p5_0[] = {
  152970. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  152971. 10, 9, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 7, 9, 9,
  152972. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 8, 8, 8,
  152973. 9, 9,10,10,11,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  152974. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  152975. 12,
  152976. };
  152977. static float _vq_quantthresh__44un1__p5_0[] = {
  152978. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  152979. };
  152980. static long _vq_quantmap__44un1__p5_0[] = {
  152981. 7, 5, 3, 1, 0, 2, 4, 6,
  152982. 8,
  152983. };
  152984. static encode_aux_threshmatch _vq_auxt__44un1__p5_0 = {
  152985. _vq_quantthresh__44un1__p5_0,
  152986. _vq_quantmap__44un1__p5_0,
  152987. 9,
  152988. 9
  152989. };
  152990. static static_codebook _44un1__p5_0 = {
  152991. 2, 81,
  152992. _vq_lengthlist__44un1__p5_0,
  152993. 1, -531628032, 1611661312, 4, 0,
  152994. _vq_quantlist__44un1__p5_0,
  152995. NULL,
  152996. &_vq_auxt__44un1__p5_0,
  152997. NULL,
  152998. 0
  152999. };
  153000. static long _vq_quantlist__44un1__p6_0[] = {
  153001. 6,
  153002. 5,
  153003. 7,
  153004. 4,
  153005. 8,
  153006. 3,
  153007. 9,
  153008. 2,
  153009. 10,
  153010. 1,
  153011. 11,
  153012. 0,
  153013. 12,
  153014. };
  153015. static long _vq_lengthlist__44un1__p6_0[] = {
  153016. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,15,15, 4, 5, 5,
  153017. 8, 8, 9, 9,11,11,12,12,16,16, 4, 5, 6, 8, 8, 9,
  153018. 9,11,11,12,12,14,14, 7, 8, 8, 9, 9,10,10,11,12,
  153019. 13,13,16,17, 7, 8, 8, 9, 9,10,10,12,12,12,13,15,
  153020. 15, 9,10,10,10,10,11,11,12,12,13,13,15,16, 9, 9,
  153021. 9,10,10,11,11,13,12,13,13,17,17,10,11,11,11,12,
  153022. 12,12,13,13,14,15, 0,18,10,11,11,12,12,12,13,14,
  153023. 13,14,14,17,16,11,12,12,13,13,14,14,14,14,15,16,
  153024. 17,16,11,12,12,13,13,14,14,14,14,15,15,17,17,14,
  153025. 15,15,16,16,16,17,17,16, 0,17, 0,18,14,15,15,16,
  153026. 16, 0,15,18,18, 0,16, 0, 0,
  153027. };
  153028. static float _vq_quantthresh__44un1__p6_0[] = {
  153029. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  153030. 12.5, 17.5, 22.5, 27.5,
  153031. };
  153032. static long _vq_quantmap__44un1__p6_0[] = {
  153033. 11, 9, 7, 5, 3, 1, 0, 2,
  153034. 4, 6, 8, 10, 12,
  153035. };
  153036. static encode_aux_threshmatch _vq_auxt__44un1__p6_0 = {
  153037. _vq_quantthresh__44un1__p6_0,
  153038. _vq_quantmap__44un1__p6_0,
  153039. 13,
  153040. 13
  153041. };
  153042. static static_codebook _44un1__p6_0 = {
  153043. 2, 169,
  153044. _vq_lengthlist__44un1__p6_0,
  153045. 1, -526516224, 1616117760, 4, 0,
  153046. _vq_quantlist__44un1__p6_0,
  153047. NULL,
  153048. &_vq_auxt__44un1__p6_0,
  153049. NULL,
  153050. 0
  153051. };
  153052. static long _vq_quantlist__44un1__p6_1[] = {
  153053. 2,
  153054. 1,
  153055. 3,
  153056. 0,
  153057. 4,
  153058. };
  153059. static long _vq_lengthlist__44un1__p6_1[] = {
  153060. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 6, 5, 5,
  153061. 6, 5, 6, 6, 5, 6, 6, 6, 6,
  153062. };
  153063. static float _vq_quantthresh__44un1__p6_1[] = {
  153064. -1.5, -0.5, 0.5, 1.5,
  153065. };
  153066. static long _vq_quantmap__44un1__p6_1[] = {
  153067. 3, 1, 0, 2, 4,
  153068. };
  153069. static encode_aux_threshmatch _vq_auxt__44un1__p6_1 = {
  153070. _vq_quantthresh__44un1__p6_1,
  153071. _vq_quantmap__44un1__p6_1,
  153072. 5,
  153073. 5
  153074. };
  153075. static static_codebook _44un1__p6_1 = {
  153076. 2, 25,
  153077. _vq_lengthlist__44un1__p6_1,
  153078. 1, -533725184, 1611661312, 3, 0,
  153079. _vq_quantlist__44un1__p6_1,
  153080. NULL,
  153081. &_vq_auxt__44un1__p6_1,
  153082. NULL,
  153083. 0
  153084. };
  153085. static long _vq_quantlist__44un1__p7_0[] = {
  153086. 2,
  153087. 1,
  153088. 3,
  153089. 0,
  153090. 4,
  153091. };
  153092. static long _vq_lengthlist__44un1__p7_0[] = {
  153093. 1, 5, 3,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  153094. 11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,11,
  153095. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153096. 11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153097. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153098. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153099. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153100. 11,11,11,11,11,11,11,11,11,11,11,11,11, 8,11,11,
  153101. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153102. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153103. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  153104. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153105. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153106. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153107. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153108. 11,11,11,11,11,11,11,11,11,11, 7,11,11,11,11,11,
  153109. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153110. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  153111. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153112. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153113. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153114. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153115. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153116. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153117. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153118. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153119. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153120. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153121. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153122. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153123. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153124. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153125. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153126. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153127. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153128. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153129. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  153130. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  153131. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  153132. 10,
  153133. };
  153134. static float _vq_quantthresh__44un1__p7_0[] = {
  153135. -253.5, -84.5, 84.5, 253.5,
  153136. };
  153137. static long _vq_quantmap__44un1__p7_0[] = {
  153138. 3, 1, 0, 2, 4,
  153139. };
  153140. static encode_aux_threshmatch _vq_auxt__44un1__p7_0 = {
  153141. _vq_quantthresh__44un1__p7_0,
  153142. _vq_quantmap__44un1__p7_0,
  153143. 5,
  153144. 5
  153145. };
  153146. static static_codebook _44un1__p7_0 = {
  153147. 4, 625,
  153148. _vq_lengthlist__44un1__p7_0,
  153149. 1, -518709248, 1626677248, 3, 0,
  153150. _vq_quantlist__44un1__p7_0,
  153151. NULL,
  153152. &_vq_auxt__44un1__p7_0,
  153153. NULL,
  153154. 0
  153155. };
  153156. static long _vq_quantlist__44un1__p7_1[] = {
  153157. 6,
  153158. 5,
  153159. 7,
  153160. 4,
  153161. 8,
  153162. 3,
  153163. 9,
  153164. 2,
  153165. 10,
  153166. 1,
  153167. 11,
  153168. 0,
  153169. 12,
  153170. };
  153171. static long _vq_lengthlist__44un1__p7_1[] = {
  153172. 1, 4, 4, 6, 6, 6, 6, 9, 8, 9, 8, 8, 8, 5, 7, 7,
  153173. 7, 7, 8, 8, 8,10, 8,10, 8, 9, 5, 7, 7, 8, 7, 7,
  153174. 8,10,10,11,10,12,11, 7, 8, 8, 9, 9, 9,10,11,11,
  153175. 11,11,11,11, 7, 8, 8, 8, 9, 9, 9,10,10,10,11,11,
  153176. 12, 7, 8, 8, 9, 9,10,11,11,12,11,12,11,11, 7, 8,
  153177. 8, 9, 9,10,10,11,11,11,12,12,11, 8,10,10,10,10,
  153178. 11,11,14,11,12,12,12,13, 9,10,10,10,10,12,11,14,
  153179. 11,14,11,12,13,10,11,11,11,11,13,11,14,14,13,13,
  153180. 13,14,11,11,11,12,11,12,12,12,13,14,14,13,14,12,
  153181. 11,12,12,12,12,13,13,13,14,13,14,14,11,12,12,14,
  153182. 12,13,13,12,13,13,14,14,14,
  153183. };
  153184. static float _vq_quantthresh__44un1__p7_1[] = {
  153185. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  153186. 32.5, 45.5, 58.5, 71.5,
  153187. };
  153188. static long _vq_quantmap__44un1__p7_1[] = {
  153189. 11, 9, 7, 5, 3, 1, 0, 2,
  153190. 4, 6, 8, 10, 12,
  153191. };
  153192. static encode_aux_threshmatch _vq_auxt__44un1__p7_1 = {
  153193. _vq_quantthresh__44un1__p7_1,
  153194. _vq_quantmap__44un1__p7_1,
  153195. 13,
  153196. 13
  153197. };
  153198. static static_codebook _44un1__p7_1 = {
  153199. 2, 169,
  153200. _vq_lengthlist__44un1__p7_1,
  153201. 1, -523010048, 1618608128, 4, 0,
  153202. _vq_quantlist__44un1__p7_1,
  153203. NULL,
  153204. &_vq_auxt__44un1__p7_1,
  153205. NULL,
  153206. 0
  153207. };
  153208. static long _vq_quantlist__44un1__p7_2[] = {
  153209. 6,
  153210. 5,
  153211. 7,
  153212. 4,
  153213. 8,
  153214. 3,
  153215. 9,
  153216. 2,
  153217. 10,
  153218. 1,
  153219. 11,
  153220. 0,
  153221. 12,
  153222. };
  153223. static long _vq_lengthlist__44un1__p7_2[] = {
  153224. 3, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9, 9, 8, 4, 5, 5,
  153225. 6, 6, 8, 8, 9, 8, 9, 9, 9, 9, 4, 5, 5, 7, 6, 8,
  153226. 8, 8, 8, 9, 8, 9, 8, 6, 7, 7, 7, 8, 8, 8, 9, 9,
  153227. 9, 9, 9, 9, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  153228. 9, 7, 8, 8, 8, 8, 9, 8, 9, 9,10, 9, 9,10, 7, 8,
  153229. 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 8, 9, 9, 9, 9,
  153230. 9, 9, 9, 9,10,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9,
  153231. 9, 9, 9,10,10, 9, 9, 9,10, 9, 9,10, 9, 9,10,10,
  153232. 10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10, 9,
  153233. 9, 9,10, 9, 9,10,10, 9,10,10,10,10, 9, 9, 9,10,
  153234. 9, 9, 9,10,10,10,10,10,10,
  153235. };
  153236. static float _vq_quantthresh__44un1__p7_2[] = {
  153237. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  153238. 2.5, 3.5, 4.5, 5.5,
  153239. };
  153240. static long _vq_quantmap__44un1__p7_2[] = {
  153241. 11, 9, 7, 5, 3, 1, 0, 2,
  153242. 4, 6, 8, 10, 12,
  153243. };
  153244. static encode_aux_threshmatch _vq_auxt__44un1__p7_2 = {
  153245. _vq_quantthresh__44un1__p7_2,
  153246. _vq_quantmap__44un1__p7_2,
  153247. 13,
  153248. 13
  153249. };
  153250. static static_codebook _44un1__p7_2 = {
  153251. 2, 169,
  153252. _vq_lengthlist__44un1__p7_2,
  153253. 1, -531103744, 1611661312, 4, 0,
  153254. _vq_quantlist__44un1__p7_2,
  153255. NULL,
  153256. &_vq_auxt__44un1__p7_2,
  153257. NULL,
  153258. 0
  153259. };
  153260. static long _huff_lengthlist__44un1__short[] = {
  153261. 12,12,14,12,14,14,14,14,12, 6, 6, 8, 9, 9,11,14,
  153262. 12, 4, 2, 6, 6, 7,11,14,13, 6, 5, 7, 8, 9,11,14,
  153263. 13, 8, 5, 8, 6, 8,12,14,12, 7, 7, 8, 8, 8,10,14,
  153264. 12, 6, 3, 4, 4, 4, 7,14,11, 7, 4, 6, 6, 6, 8,14,
  153265. };
  153266. static static_codebook _huff_book__44un1__short = {
  153267. 2, 64,
  153268. _huff_lengthlist__44un1__short,
  153269. 0, 0, 0, 0, 0,
  153270. NULL,
  153271. NULL,
  153272. NULL,
  153273. NULL,
  153274. 0
  153275. };
  153276. /*** End of inlined file: res_books_uncoupled.h ***/
  153277. /***** residue backends *********************************************/
  153278. static vorbis_info_residue0 _residue_44_low_un={
  153279. 0,-1, -1, 8,-1,
  153280. {0},
  153281. {-1},
  153282. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 28.5},
  153283. { -1, 25, -1, 45, -1, -1, -1}
  153284. };
  153285. static vorbis_info_residue0 _residue_44_mid_un={
  153286. 0,-1, -1, 10,-1,
  153287. /* 0 1 2 3 4 5 6 7 8 9 */
  153288. {0},
  153289. {-1},
  153290. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 4.5, 16.5, 60.5},
  153291. { -1, 30, -1, 50, -1, 80, -1, -1, -1}
  153292. };
  153293. static vorbis_info_residue0 _residue_44_hi_un={
  153294. 0,-1, -1, 10,-1,
  153295. /* 0 1 2 3 4 5 6 7 8 9 */
  153296. {0},
  153297. {-1},
  153298. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  153299. { -1, -1, -1, -1, -1, -1, -1, -1, -1}
  153300. };
  153301. /* mapping conventions:
  153302. only one submap (this would change for efficient 5.1 support for example)*/
  153303. /* Four psychoacoustic profiles are used, one for each blocktype */
  153304. static vorbis_info_mapping0 _map_nominal_u[2]={
  153305. {1, {0,0}, {0}, {0}, 0,{0},{0}},
  153306. {1, {0,0}, {1}, {1}, 0,{0},{0}}
  153307. };
  153308. static static_bookblock _resbook_44u_n1={
  153309. {
  153310. {0},
  153311. {0,0,&_44un1__p1_0},
  153312. {0,0,&_44un1__p2_0},
  153313. {0,0,&_44un1__p3_0},
  153314. {0,0,&_44un1__p4_0},
  153315. {0,0,&_44un1__p5_0},
  153316. {&_44un1__p6_0,&_44un1__p6_1},
  153317. {&_44un1__p7_0,&_44un1__p7_1,&_44un1__p7_2}
  153318. }
  153319. };
  153320. static static_bookblock _resbook_44u_0={
  153321. {
  153322. {0},
  153323. {0,0,&_44u0__p1_0},
  153324. {0,0,&_44u0__p2_0},
  153325. {0,0,&_44u0__p3_0},
  153326. {0,0,&_44u0__p4_0},
  153327. {0,0,&_44u0__p5_0},
  153328. {&_44u0__p6_0,&_44u0__p6_1},
  153329. {&_44u0__p7_0,&_44u0__p7_1,&_44u0__p7_2}
  153330. }
  153331. };
  153332. static static_bookblock _resbook_44u_1={
  153333. {
  153334. {0},
  153335. {0,0,&_44u1__p1_0},
  153336. {0,0,&_44u1__p2_0},
  153337. {0,0,&_44u1__p3_0},
  153338. {0,0,&_44u1__p4_0},
  153339. {0,0,&_44u1__p5_0},
  153340. {&_44u1__p6_0,&_44u1__p6_1},
  153341. {&_44u1__p7_0,&_44u1__p7_1,&_44u1__p7_2}
  153342. }
  153343. };
  153344. static static_bookblock _resbook_44u_2={
  153345. {
  153346. {0},
  153347. {0,0,&_44u2__p1_0},
  153348. {0,0,&_44u2__p2_0},
  153349. {0,0,&_44u2__p3_0},
  153350. {0,0,&_44u2__p4_0},
  153351. {0,0,&_44u2__p5_0},
  153352. {&_44u2__p6_0,&_44u2__p6_1},
  153353. {&_44u2__p7_0,&_44u2__p7_1,&_44u2__p7_2}
  153354. }
  153355. };
  153356. static static_bookblock _resbook_44u_3={
  153357. {
  153358. {0},
  153359. {0,0,&_44u3__p1_0},
  153360. {0,0,&_44u3__p2_0},
  153361. {0,0,&_44u3__p3_0},
  153362. {0,0,&_44u3__p4_0},
  153363. {0,0,&_44u3__p5_0},
  153364. {&_44u3__p6_0,&_44u3__p6_1},
  153365. {&_44u3__p7_0,&_44u3__p7_1,&_44u3__p7_2}
  153366. }
  153367. };
  153368. static static_bookblock _resbook_44u_4={
  153369. {
  153370. {0},
  153371. {0,0,&_44u4__p1_0},
  153372. {0,0,&_44u4__p2_0},
  153373. {0,0,&_44u4__p3_0},
  153374. {0,0,&_44u4__p4_0},
  153375. {0,0,&_44u4__p5_0},
  153376. {&_44u4__p6_0,&_44u4__p6_1},
  153377. {&_44u4__p7_0,&_44u4__p7_1,&_44u4__p7_2}
  153378. }
  153379. };
  153380. static static_bookblock _resbook_44u_5={
  153381. {
  153382. {0},
  153383. {0,0,&_44u5__p1_0},
  153384. {0,0,&_44u5__p2_0},
  153385. {0,0,&_44u5__p3_0},
  153386. {0,0,&_44u5__p4_0},
  153387. {0,0,&_44u5__p5_0},
  153388. {0,0,&_44u5__p6_0},
  153389. {&_44u5__p7_0,&_44u5__p7_1},
  153390. {&_44u5__p8_0,&_44u5__p8_1},
  153391. {&_44u5__p9_0,&_44u5__p9_1,&_44u5__p9_2}
  153392. }
  153393. };
  153394. static static_bookblock _resbook_44u_6={
  153395. {
  153396. {0},
  153397. {0,0,&_44u6__p1_0},
  153398. {0,0,&_44u6__p2_0},
  153399. {0,0,&_44u6__p3_0},
  153400. {0,0,&_44u6__p4_0},
  153401. {0,0,&_44u6__p5_0},
  153402. {0,0,&_44u6__p6_0},
  153403. {&_44u6__p7_0,&_44u6__p7_1},
  153404. {&_44u6__p8_0,&_44u6__p8_1},
  153405. {&_44u6__p9_0,&_44u6__p9_1,&_44u6__p9_2}
  153406. }
  153407. };
  153408. static static_bookblock _resbook_44u_7={
  153409. {
  153410. {0},
  153411. {0,0,&_44u7__p1_0},
  153412. {0,0,&_44u7__p2_0},
  153413. {0,0,&_44u7__p3_0},
  153414. {0,0,&_44u7__p4_0},
  153415. {0,0,&_44u7__p5_0},
  153416. {0,0,&_44u7__p6_0},
  153417. {&_44u7__p7_0,&_44u7__p7_1},
  153418. {&_44u7__p8_0,&_44u7__p8_1},
  153419. {&_44u7__p9_0,&_44u7__p9_1,&_44u7__p9_2}
  153420. }
  153421. };
  153422. static static_bookblock _resbook_44u_8={
  153423. {
  153424. {0},
  153425. {0,0,&_44u8_p1_0},
  153426. {0,0,&_44u8_p2_0},
  153427. {0,0,&_44u8_p3_0},
  153428. {0,0,&_44u8_p4_0},
  153429. {&_44u8_p5_0,&_44u8_p5_1},
  153430. {&_44u8_p6_0,&_44u8_p6_1},
  153431. {&_44u8_p7_0,&_44u8_p7_1},
  153432. {&_44u8_p8_0,&_44u8_p8_1},
  153433. {&_44u8_p9_0,&_44u8_p9_1,&_44u8_p9_2}
  153434. }
  153435. };
  153436. static static_bookblock _resbook_44u_9={
  153437. {
  153438. {0},
  153439. {0,0,&_44u9_p1_0},
  153440. {0,0,&_44u9_p2_0},
  153441. {0,0,&_44u9_p3_0},
  153442. {0,0,&_44u9_p4_0},
  153443. {&_44u9_p5_0,&_44u9_p5_1},
  153444. {&_44u9_p6_0,&_44u9_p6_1},
  153445. {&_44u9_p7_0,&_44u9_p7_1},
  153446. {&_44u9_p8_0,&_44u9_p8_1},
  153447. {&_44u9_p9_0,&_44u9_p9_1,&_44u9_p9_2}
  153448. }
  153449. };
  153450. static vorbis_residue_template _res_44u_n1[]={
  153451. {1,0, &_residue_44_low_un,
  153452. &_huff_book__44un1__short,&_huff_book__44un1__short,
  153453. &_resbook_44u_n1,&_resbook_44u_n1},
  153454. {1,0, &_residue_44_low_un,
  153455. &_huff_book__44un1__long,&_huff_book__44un1__long,
  153456. &_resbook_44u_n1,&_resbook_44u_n1}
  153457. };
  153458. static vorbis_residue_template _res_44u_0[]={
  153459. {1,0, &_residue_44_low_un,
  153460. &_huff_book__44u0__short,&_huff_book__44u0__short,
  153461. &_resbook_44u_0,&_resbook_44u_0},
  153462. {1,0, &_residue_44_low_un,
  153463. &_huff_book__44u0__long,&_huff_book__44u0__long,
  153464. &_resbook_44u_0,&_resbook_44u_0}
  153465. };
  153466. static vorbis_residue_template _res_44u_1[]={
  153467. {1,0, &_residue_44_low_un,
  153468. &_huff_book__44u1__short,&_huff_book__44u1__short,
  153469. &_resbook_44u_1,&_resbook_44u_1},
  153470. {1,0, &_residue_44_low_un,
  153471. &_huff_book__44u1__long,&_huff_book__44u1__long,
  153472. &_resbook_44u_1,&_resbook_44u_1}
  153473. };
  153474. static vorbis_residue_template _res_44u_2[]={
  153475. {1,0, &_residue_44_low_un,
  153476. &_huff_book__44u2__short,&_huff_book__44u2__short,
  153477. &_resbook_44u_2,&_resbook_44u_2},
  153478. {1,0, &_residue_44_low_un,
  153479. &_huff_book__44u2__long,&_huff_book__44u2__long,
  153480. &_resbook_44u_2,&_resbook_44u_2}
  153481. };
  153482. static vorbis_residue_template _res_44u_3[]={
  153483. {1,0, &_residue_44_low_un,
  153484. &_huff_book__44u3__short,&_huff_book__44u3__short,
  153485. &_resbook_44u_3,&_resbook_44u_3},
  153486. {1,0, &_residue_44_low_un,
  153487. &_huff_book__44u3__long,&_huff_book__44u3__long,
  153488. &_resbook_44u_3,&_resbook_44u_3}
  153489. };
  153490. static vorbis_residue_template _res_44u_4[]={
  153491. {1,0, &_residue_44_low_un,
  153492. &_huff_book__44u4__short,&_huff_book__44u4__short,
  153493. &_resbook_44u_4,&_resbook_44u_4},
  153494. {1,0, &_residue_44_low_un,
  153495. &_huff_book__44u4__long,&_huff_book__44u4__long,
  153496. &_resbook_44u_4,&_resbook_44u_4}
  153497. };
  153498. static vorbis_residue_template _res_44u_5[]={
  153499. {1,0, &_residue_44_mid_un,
  153500. &_huff_book__44u5__short,&_huff_book__44u5__short,
  153501. &_resbook_44u_5,&_resbook_44u_5},
  153502. {1,0, &_residue_44_mid_un,
  153503. &_huff_book__44u5__long,&_huff_book__44u5__long,
  153504. &_resbook_44u_5,&_resbook_44u_5}
  153505. };
  153506. static vorbis_residue_template _res_44u_6[]={
  153507. {1,0, &_residue_44_mid_un,
  153508. &_huff_book__44u6__short,&_huff_book__44u6__short,
  153509. &_resbook_44u_6,&_resbook_44u_6},
  153510. {1,0, &_residue_44_mid_un,
  153511. &_huff_book__44u6__long,&_huff_book__44u6__long,
  153512. &_resbook_44u_6,&_resbook_44u_6}
  153513. };
  153514. static vorbis_residue_template _res_44u_7[]={
  153515. {1,0, &_residue_44_mid_un,
  153516. &_huff_book__44u7__short,&_huff_book__44u7__short,
  153517. &_resbook_44u_7,&_resbook_44u_7},
  153518. {1,0, &_residue_44_mid_un,
  153519. &_huff_book__44u7__long,&_huff_book__44u7__long,
  153520. &_resbook_44u_7,&_resbook_44u_7}
  153521. };
  153522. static vorbis_residue_template _res_44u_8[]={
  153523. {1,0, &_residue_44_hi_un,
  153524. &_huff_book__44u8__short,&_huff_book__44u8__short,
  153525. &_resbook_44u_8,&_resbook_44u_8},
  153526. {1,0, &_residue_44_hi_un,
  153527. &_huff_book__44u8__long,&_huff_book__44u8__long,
  153528. &_resbook_44u_8,&_resbook_44u_8}
  153529. };
  153530. static vorbis_residue_template _res_44u_9[]={
  153531. {1,0, &_residue_44_hi_un,
  153532. &_huff_book__44u9__short,&_huff_book__44u9__short,
  153533. &_resbook_44u_9,&_resbook_44u_9},
  153534. {1,0, &_residue_44_hi_un,
  153535. &_huff_book__44u9__long,&_huff_book__44u9__long,
  153536. &_resbook_44u_9,&_resbook_44u_9}
  153537. };
  153538. static vorbis_mapping_template _mapres_template_44_uncoupled[]={
  153539. { _map_nominal_u, _res_44u_n1 }, /* -1 */
  153540. { _map_nominal_u, _res_44u_0 }, /* 0 */
  153541. { _map_nominal_u, _res_44u_1 }, /* 1 */
  153542. { _map_nominal_u, _res_44u_2 }, /* 2 */
  153543. { _map_nominal_u, _res_44u_3 }, /* 3 */
  153544. { _map_nominal_u, _res_44u_4 }, /* 4 */
  153545. { _map_nominal_u, _res_44u_5 }, /* 5 */
  153546. { _map_nominal_u, _res_44u_6 }, /* 6 */
  153547. { _map_nominal_u, _res_44u_7 }, /* 7 */
  153548. { _map_nominal_u, _res_44u_8 }, /* 8 */
  153549. { _map_nominal_u, _res_44u_9 }, /* 9 */
  153550. };
  153551. /*** End of inlined file: residue_44u.h ***/
  153552. static double rate_mapping_44_un[12]={
  153553. 32000.,48000.,60000.,70000.,80000.,86000.,
  153554. 96000.,110000.,120000.,140000.,160000.,240001.
  153555. };
  153556. ve_setup_data_template ve_setup_44_uncoupled={
  153557. 11,
  153558. rate_mapping_44_un,
  153559. quality_mapping_44,
  153560. -1,
  153561. 40000,
  153562. 50000,
  153563. blocksize_short_44,
  153564. blocksize_long_44,
  153565. _psy_tone_masteratt_44,
  153566. _psy_tone_0dB,
  153567. _psy_tone_suppress,
  153568. _vp_tonemask_adj_otherblock,
  153569. _vp_tonemask_adj_longblock,
  153570. _vp_tonemask_adj_otherblock,
  153571. _psy_noiseguards_44,
  153572. _psy_noisebias_impulse,
  153573. _psy_noisebias_padding,
  153574. _psy_noisebias_trans,
  153575. _psy_noisebias_long,
  153576. _psy_noise_suppress,
  153577. _psy_compand_44,
  153578. _psy_compand_short_mapping,
  153579. _psy_compand_long_mapping,
  153580. {_noise_start_short_44,_noise_start_long_44},
  153581. {_noise_part_short_44,_noise_part_long_44},
  153582. _noise_thresh_44,
  153583. _psy_ath_floater,
  153584. _psy_ath_abs,
  153585. _psy_lowpass_44,
  153586. _psy_global_44,
  153587. _global_mapping_44,
  153588. NULL,
  153589. _floor_books,
  153590. _floor,
  153591. _floor_short_mapping_44,
  153592. _floor_long_mapping_44,
  153593. _mapres_template_44_uncoupled
  153594. };
  153595. /*** End of inlined file: setup_44u.h ***/
  153596. /*** Start of inlined file: setup_32.h ***/
  153597. static double rate_mapping_32[12]={
  153598. 18000.,28000.,35000.,45000.,56000.,60000.,
  153599. 75000.,90000.,100000.,115000.,150000.,190000.,
  153600. };
  153601. static double rate_mapping_32_un[12]={
  153602. 30000.,42000.,52000.,64000.,72000.,78000.,
  153603. 86000.,92000.,110000.,120000.,140000.,190000.,
  153604. };
  153605. static double _psy_lowpass_32[12]={
  153606. 12.3,13.,13.,14.,15.,99.,99.,99.,99.,99.,99.,99.
  153607. };
  153608. ve_setup_data_template ve_setup_32_stereo={
  153609. 11,
  153610. rate_mapping_32,
  153611. quality_mapping_44,
  153612. 2,
  153613. 26000,
  153614. 40000,
  153615. blocksize_short_44,
  153616. blocksize_long_44,
  153617. _psy_tone_masteratt_44,
  153618. _psy_tone_0dB,
  153619. _psy_tone_suppress,
  153620. _vp_tonemask_adj_otherblock,
  153621. _vp_tonemask_adj_longblock,
  153622. _vp_tonemask_adj_otherblock,
  153623. _psy_noiseguards_44,
  153624. _psy_noisebias_impulse,
  153625. _psy_noisebias_padding,
  153626. _psy_noisebias_trans,
  153627. _psy_noisebias_long,
  153628. _psy_noise_suppress,
  153629. _psy_compand_44,
  153630. _psy_compand_short_mapping,
  153631. _psy_compand_long_mapping,
  153632. {_noise_start_short_44,_noise_start_long_44},
  153633. {_noise_part_short_44,_noise_part_long_44},
  153634. _noise_thresh_44,
  153635. _psy_ath_floater,
  153636. _psy_ath_abs,
  153637. _psy_lowpass_32,
  153638. _psy_global_44,
  153639. _global_mapping_44,
  153640. _psy_stereo_modes_44,
  153641. _floor_books,
  153642. _floor,
  153643. _floor_short_mapping_44,
  153644. _floor_long_mapping_44,
  153645. _mapres_template_44_stereo
  153646. };
  153647. ve_setup_data_template ve_setup_32_uncoupled={
  153648. 11,
  153649. rate_mapping_32_un,
  153650. quality_mapping_44,
  153651. -1,
  153652. 26000,
  153653. 40000,
  153654. blocksize_short_44,
  153655. blocksize_long_44,
  153656. _psy_tone_masteratt_44,
  153657. _psy_tone_0dB,
  153658. _psy_tone_suppress,
  153659. _vp_tonemask_adj_otherblock,
  153660. _vp_tonemask_adj_longblock,
  153661. _vp_tonemask_adj_otherblock,
  153662. _psy_noiseguards_44,
  153663. _psy_noisebias_impulse,
  153664. _psy_noisebias_padding,
  153665. _psy_noisebias_trans,
  153666. _psy_noisebias_long,
  153667. _psy_noise_suppress,
  153668. _psy_compand_44,
  153669. _psy_compand_short_mapping,
  153670. _psy_compand_long_mapping,
  153671. {_noise_start_short_44,_noise_start_long_44},
  153672. {_noise_part_short_44,_noise_part_long_44},
  153673. _noise_thresh_44,
  153674. _psy_ath_floater,
  153675. _psy_ath_abs,
  153676. _psy_lowpass_32,
  153677. _psy_global_44,
  153678. _global_mapping_44,
  153679. NULL,
  153680. _floor_books,
  153681. _floor,
  153682. _floor_short_mapping_44,
  153683. _floor_long_mapping_44,
  153684. _mapres_template_44_uncoupled
  153685. };
  153686. /*** End of inlined file: setup_32.h ***/
  153687. /*** Start of inlined file: setup_8.h ***/
  153688. /*** Start of inlined file: psych_8.h ***/
  153689. static att3 _psy_tone_masteratt_8[3]={
  153690. {{ 32, 25, 12}, 0, 0}, /* 0 */
  153691. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153692. {{ 20, 0, -14}, 0, 0}, /* 0 */
  153693. };
  153694. static vp_adjblock _vp_tonemask_adj_8[3]={
  153695. /* adjust for mode zero */
  153696. /* 63 125 250 500 1 2 4 8 16 */
  153697. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  153698. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  153699. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 1 */
  153700. };
  153701. static noise3 _psy_noisebias_8[3]={
  153702. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153703. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  153704. {-10,-10,-10,-10, -5, -5, -5, 0, 0, 4, 4, 4, 4, 4, 99, 99, 99},
  153705. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153706. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  153707. {-10,-10,-10,-10,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  153708. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153709. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  153710. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  153711. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  153712. };
  153713. /* stereo mode by base quality level */
  153714. static adj_stereo _psy_stereo_modes_8[3]={
  153715. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  153716. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153717. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153718. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153719. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153720. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153721. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153722. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153723. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153724. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153725. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153726. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153727. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153728. };
  153729. static noiseguard _psy_noiseguards_8[2]={
  153730. {10,10,-1},
  153731. {10,10,-1},
  153732. };
  153733. static compandblock _psy_compand_8[2]={
  153734. {{
  153735. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  153736. 8, 8, 9, 9,10,10,11, 11, /* 15dB */
  153737. 12,12,13,13,14,14,15, 15, /* 23dB */
  153738. 16,16,17,17,17,18,18, 19, /* 31dB */
  153739. 19,19,20,21,22,23,24, 25, /* 39dB */
  153740. }},
  153741. {{
  153742. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  153743. 7, 7, 6, 6, 5, 5, 4, 4, /* 15dB */
  153744. 3, 3, 3, 4, 5, 6, 7, 8, /* 23dB */
  153745. 9,10,11,12,13,14,15, 16, /* 31dB */
  153746. 17,18,19,20,21,22,23, 24, /* 39dB */
  153747. }},
  153748. };
  153749. static double _psy_lowpass_8[3]={3.,4.,4.};
  153750. static int _noise_start_8[2]={
  153751. 64,64,
  153752. };
  153753. static int _noise_part_8[2]={
  153754. 8,8,
  153755. };
  153756. static int _psy_ath_floater_8[3]={
  153757. -100,-100,-105,
  153758. };
  153759. static int _psy_ath_abs_8[3]={
  153760. -130,-130,-140,
  153761. };
  153762. /*** End of inlined file: psych_8.h ***/
  153763. /*** Start of inlined file: residue_8.h ***/
  153764. /***** residue backends *********************************************/
  153765. static static_bookblock _resbook_8s_0={
  153766. {
  153767. {0},{0,0,&_8c0_s_p1_0},{0,0,&_8c0_s_p2_0},{0,0,&_8c0_s_p3_0},
  153768. {0,0,&_8c0_s_p4_0},{0,0,&_8c0_s_p5_0},{0,0,&_8c0_s_p6_0},
  153769. {&_8c0_s_p7_0,&_8c0_s_p7_1},{&_8c0_s_p8_0,&_8c0_s_p8_1},
  153770. {&_8c0_s_p9_0,&_8c0_s_p9_1,&_8c0_s_p9_2}
  153771. }
  153772. };
  153773. static static_bookblock _resbook_8s_1={
  153774. {
  153775. {0},{0,0,&_8c1_s_p1_0},{0,0,&_8c1_s_p2_0},{0,0,&_8c1_s_p3_0},
  153776. {0,0,&_8c1_s_p4_0},{0,0,&_8c1_s_p5_0},{0,0,&_8c1_s_p6_0},
  153777. {&_8c1_s_p7_0,&_8c1_s_p7_1},{&_8c1_s_p8_0,&_8c1_s_p8_1},
  153778. {&_8c1_s_p9_0,&_8c1_s_p9_1,&_8c1_s_p9_2}
  153779. }
  153780. };
  153781. static vorbis_residue_template _res_8s_0[]={
  153782. {2,0, &_residue_44_mid,
  153783. &_huff_book__8c0_s_single,&_huff_book__8c0_s_single,
  153784. &_resbook_8s_0,&_resbook_8s_0},
  153785. };
  153786. static vorbis_residue_template _res_8s_1[]={
  153787. {2,0, &_residue_44_mid,
  153788. &_huff_book__8c1_s_single,&_huff_book__8c1_s_single,
  153789. &_resbook_8s_1,&_resbook_8s_1},
  153790. };
  153791. static vorbis_mapping_template _mapres_template_8_stereo[2]={
  153792. { _map_nominal, _res_8s_0 }, /* 0 */
  153793. { _map_nominal, _res_8s_1 }, /* 1 */
  153794. };
  153795. static static_bookblock _resbook_8u_0={
  153796. {
  153797. {0},
  153798. {0,0,&_8u0__p1_0},
  153799. {0,0,&_8u0__p2_0},
  153800. {0,0,&_8u0__p3_0},
  153801. {0,0,&_8u0__p4_0},
  153802. {0,0,&_8u0__p5_0},
  153803. {&_8u0__p6_0,&_8u0__p6_1},
  153804. {&_8u0__p7_0,&_8u0__p7_1,&_8u0__p7_2}
  153805. }
  153806. };
  153807. static static_bookblock _resbook_8u_1={
  153808. {
  153809. {0},
  153810. {0,0,&_8u1__p1_0},
  153811. {0,0,&_8u1__p2_0},
  153812. {0,0,&_8u1__p3_0},
  153813. {0,0,&_8u1__p4_0},
  153814. {0,0,&_8u1__p5_0},
  153815. {0,0,&_8u1__p6_0},
  153816. {&_8u1__p7_0,&_8u1__p7_1},
  153817. {&_8u1__p8_0,&_8u1__p8_1},
  153818. {&_8u1__p9_0,&_8u1__p9_1,&_8u1__p9_2}
  153819. }
  153820. };
  153821. static vorbis_residue_template _res_8u_0[]={
  153822. {1,0, &_residue_44_low_un,
  153823. &_huff_book__8u0__single,&_huff_book__8u0__single,
  153824. &_resbook_8u_0,&_resbook_8u_0},
  153825. };
  153826. static vorbis_residue_template _res_8u_1[]={
  153827. {1,0, &_residue_44_mid_un,
  153828. &_huff_book__8u1__single,&_huff_book__8u1__single,
  153829. &_resbook_8u_1,&_resbook_8u_1},
  153830. };
  153831. static vorbis_mapping_template _mapres_template_8_uncoupled[2]={
  153832. { _map_nominal_u, _res_8u_0 }, /* 0 */
  153833. { _map_nominal_u, _res_8u_1 }, /* 1 */
  153834. };
  153835. /*** End of inlined file: residue_8.h ***/
  153836. static int blocksize_8[2]={
  153837. 512,512
  153838. };
  153839. static int _floor_mapping_8[2]={
  153840. 6,6,
  153841. };
  153842. static double rate_mapping_8[3]={
  153843. 6000.,9000.,32000.,
  153844. };
  153845. static double rate_mapping_8_uncoupled[3]={
  153846. 8000.,14000.,42000.,
  153847. };
  153848. static double quality_mapping_8[3]={
  153849. -.1,.0,1.
  153850. };
  153851. static double _psy_compand_8_mapping[3]={ 0., 1., 1.};
  153852. static double _global_mapping_8[3]={ 1., 2., 3. };
  153853. ve_setup_data_template ve_setup_8_stereo={
  153854. 2,
  153855. rate_mapping_8,
  153856. quality_mapping_8,
  153857. 2,
  153858. 8000,
  153859. 9000,
  153860. blocksize_8,
  153861. blocksize_8,
  153862. _psy_tone_masteratt_8,
  153863. _psy_tone_0dB,
  153864. _psy_tone_suppress,
  153865. _vp_tonemask_adj_8,
  153866. NULL,
  153867. _vp_tonemask_adj_8,
  153868. _psy_noiseguards_8,
  153869. _psy_noisebias_8,
  153870. _psy_noisebias_8,
  153871. NULL,
  153872. NULL,
  153873. _psy_noise_suppress,
  153874. _psy_compand_8,
  153875. _psy_compand_8_mapping,
  153876. NULL,
  153877. {_noise_start_8,_noise_start_8},
  153878. {_noise_part_8,_noise_part_8},
  153879. _noise_thresh_5only,
  153880. _psy_ath_floater_8,
  153881. _psy_ath_abs_8,
  153882. _psy_lowpass_8,
  153883. _psy_global_44,
  153884. _global_mapping_8,
  153885. _psy_stereo_modes_8,
  153886. _floor_books,
  153887. _floor,
  153888. _floor_mapping_8,
  153889. NULL,
  153890. _mapres_template_8_stereo
  153891. };
  153892. ve_setup_data_template ve_setup_8_uncoupled={
  153893. 2,
  153894. rate_mapping_8_uncoupled,
  153895. quality_mapping_8,
  153896. -1,
  153897. 8000,
  153898. 9000,
  153899. blocksize_8,
  153900. blocksize_8,
  153901. _psy_tone_masteratt_8,
  153902. _psy_tone_0dB,
  153903. _psy_tone_suppress,
  153904. _vp_tonemask_adj_8,
  153905. NULL,
  153906. _vp_tonemask_adj_8,
  153907. _psy_noiseguards_8,
  153908. _psy_noisebias_8,
  153909. _psy_noisebias_8,
  153910. NULL,
  153911. NULL,
  153912. _psy_noise_suppress,
  153913. _psy_compand_8,
  153914. _psy_compand_8_mapping,
  153915. NULL,
  153916. {_noise_start_8,_noise_start_8},
  153917. {_noise_part_8,_noise_part_8},
  153918. _noise_thresh_5only,
  153919. _psy_ath_floater_8,
  153920. _psy_ath_abs_8,
  153921. _psy_lowpass_8,
  153922. _psy_global_44,
  153923. _global_mapping_8,
  153924. _psy_stereo_modes_8,
  153925. _floor_books,
  153926. _floor,
  153927. _floor_mapping_8,
  153928. NULL,
  153929. _mapres_template_8_uncoupled
  153930. };
  153931. /*** End of inlined file: setup_8.h ***/
  153932. /*** Start of inlined file: setup_11.h ***/
  153933. /*** Start of inlined file: psych_11.h ***/
  153934. static double _psy_lowpass_11[3]={4.5,5.5,30.,};
  153935. static att3 _psy_tone_masteratt_11[3]={
  153936. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153937. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153938. {{ 20, 0, -14}, 0, 0}, /* 0 */
  153939. };
  153940. static vp_adjblock _vp_tonemask_adj_11[3]={
  153941. /* adjust for mode zero */
  153942. /* 63 125 250 500 1 2 4 8 16 */
  153943. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 2, 0,99,99,99}}, /* 0 */
  153944. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 5, 0, 0,99,99,99}}, /* 1 */
  153945. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 2 */
  153946. };
  153947. static noise3 _psy_noisebias_11[3]={
  153948. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153949. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  153950. {-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 4, 5, 5, 10, 99, 99, 99},
  153951. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153952. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  153953. {-15,-15,-15,-15,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  153954. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153955. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  153956. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  153957. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  153958. };
  153959. static double _noise_thresh_11[3]={ .3,.5,.5 };
  153960. /*** End of inlined file: psych_11.h ***/
  153961. static int blocksize_11[2]={
  153962. 512,512
  153963. };
  153964. static int _floor_mapping_11[2]={
  153965. 6,6,
  153966. };
  153967. static double rate_mapping_11[3]={
  153968. 8000.,13000.,44000.,
  153969. };
  153970. static double rate_mapping_11_uncoupled[3]={
  153971. 12000.,20000.,50000.,
  153972. };
  153973. static double quality_mapping_11[3]={
  153974. -.1,.0,1.
  153975. };
  153976. ve_setup_data_template ve_setup_11_stereo={
  153977. 2,
  153978. rate_mapping_11,
  153979. quality_mapping_11,
  153980. 2,
  153981. 9000,
  153982. 15000,
  153983. blocksize_11,
  153984. blocksize_11,
  153985. _psy_tone_masteratt_11,
  153986. _psy_tone_0dB,
  153987. _psy_tone_suppress,
  153988. _vp_tonemask_adj_11,
  153989. NULL,
  153990. _vp_tonemask_adj_11,
  153991. _psy_noiseguards_8,
  153992. _psy_noisebias_11,
  153993. _psy_noisebias_11,
  153994. NULL,
  153995. NULL,
  153996. _psy_noise_suppress,
  153997. _psy_compand_8,
  153998. _psy_compand_8_mapping,
  153999. NULL,
  154000. {_noise_start_8,_noise_start_8},
  154001. {_noise_part_8,_noise_part_8},
  154002. _noise_thresh_11,
  154003. _psy_ath_floater_8,
  154004. _psy_ath_abs_8,
  154005. _psy_lowpass_11,
  154006. _psy_global_44,
  154007. _global_mapping_8,
  154008. _psy_stereo_modes_8,
  154009. _floor_books,
  154010. _floor,
  154011. _floor_mapping_11,
  154012. NULL,
  154013. _mapres_template_8_stereo
  154014. };
  154015. ve_setup_data_template ve_setup_11_uncoupled={
  154016. 2,
  154017. rate_mapping_11_uncoupled,
  154018. quality_mapping_11,
  154019. -1,
  154020. 9000,
  154021. 15000,
  154022. blocksize_11,
  154023. blocksize_11,
  154024. _psy_tone_masteratt_11,
  154025. _psy_tone_0dB,
  154026. _psy_tone_suppress,
  154027. _vp_tonemask_adj_11,
  154028. NULL,
  154029. _vp_tonemask_adj_11,
  154030. _psy_noiseguards_8,
  154031. _psy_noisebias_11,
  154032. _psy_noisebias_11,
  154033. NULL,
  154034. NULL,
  154035. _psy_noise_suppress,
  154036. _psy_compand_8,
  154037. _psy_compand_8_mapping,
  154038. NULL,
  154039. {_noise_start_8,_noise_start_8},
  154040. {_noise_part_8,_noise_part_8},
  154041. _noise_thresh_11,
  154042. _psy_ath_floater_8,
  154043. _psy_ath_abs_8,
  154044. _psy_lowpass_11,
  154045. _psy_global_44,
  154046. _global_mapping_8,
  154047. _psy_stereo_modes_8,
  154048. _floor_books,
  154049. _floor,
  154050. _floor_mapping_11,
  154051. NULL,
  154052. _mapres_template_8_uncoupled
  154053. };
  154054. /*** End of inlined file: setup_11.h ***/
  154055. /*** Start of inlined file: setup_16.h ***/
  154056. /*** Start of inlined file: psych_16.h ***/
  154057. /* stereo mode by base quality level */
  154058. static adj_stereo _psy_stereo_modes_16[4]={
  154059. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  154060. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  154061. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  154062. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 4},
  154063. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  154064. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  154065. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  154066. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 4, 4, 4, 4, 4},
  154067. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  154068. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  154069. { 5, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  154070. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  154071. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  154072. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  154073. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  154074. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8},
  154075. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  154076. };
  154077. static double _psy_lowpass_16[4]={6.5,8,30.,99.};
  154078. static att3 _psy_tone_masteratt_16[4]={
  154079. {{ 30, 25, 12}, 0, 0}, /* 0 */
  154080. {{ 25, 22, 12}, 0, 0}, /* 0 */
  154081. {{ 20, 12, 0}, 0, 0}, /* 0 */
  154082. {{ 15, 0, -14}, 0, 0}, /* 0 */
  154083. };
  154084. static vp_adjblock _vp_tonemask_adj_16[4]={
  154085. /* adjust for mode zero */
  154086. /* 63 125 250 500 1 2 4 8 16 */
  154087. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 0 */
  154088. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 1 */
  154089. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  154090. {{-30,-30,-30,-30,-30,-26,-20,-10, -5, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  154091. };
  154092. static noise3 _psy_noisebias_16_short[4]={
  154093. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  154094. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  154095. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  154096. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  154097. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  154098. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 4, 5, 6, 8, 8, 15},
  154099. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  154100. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  154101. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10, -8, 0, 0, 0, 0, 2, 5},
  154102. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154103. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  154104. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  154105. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154106. };
  154107. static noise3 _psy_noisebias_16_impulse[4]={
  154108. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  154109. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  154110. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  154111. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  154112. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 4, 4, 4, 5, 5, 6, 8, 15},
  154113. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 0, 0, 0, 0, 4, 10},
  154114. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  154115. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 4, 10},
  154116. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10,-10,-10,-10,-10,-10, -7, -5},
  154117. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154118. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  154119. {-30,-30,-30,-30,-26,-22,-20,-18,-18,-18,-20,-20,-20,-20,-20,-20,-16},
  154120. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154121. };
  154122. static noise3 _psy_noisebias_16[4]={
  154123. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  154124. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 8, 8, 10, 10, 10, 14, 20},
  154125. {-10,-10,-10,-10,-10, -5, -2, -2, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  154126. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  154127. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  154128. {-15,-15,-15,-15,-15,-10, -5, -5, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  154129. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  154130. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  154131. {-20,-20,-20,-20,-16,-12,-20,-10, -5, -5, 0, 0, 0, 0, 0, 2, 5},
  154132. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154133. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  154134. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  154135. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154136. };
  154137. static double _noise_thresh_16[4]={ .3,.5,.5,.5 };
  154138. static int _noise_start_16[3]={ 256,256,9999 };
  154139. static int _noise_part_16[4]={ 8,8,8,8 };
  154140. static int _psy_ath_floater_16[4]={
  154141. -100,-100,-100,-105,
  154142. };
  154143. static int _psy_ath_abs_16[4]={
  154144. -130,-130,-130,-140,
  154145. };
  154146. /*** End of inlined file: psych_16.h ***/
  154147. /*** Start of inlined file: residue_16.h ***/
  154148. /***** residue backends *********************************************/
  154149. static static_bookblock _resbook_16s_0={
  154150. {
  154151. {0},
  154152. {0,0,&_16c0_s_p1_0},
  154153. {0,0,&_16c0_s_p2_0},
  154154. {0,0,&_16c0_s_p3_0},
  154155. {0,0,&_16c0_s_p4_0},
  154156. {0,0,&_16c0_s_p5_0},
  154157. {0,0,&_16c0_s_p6_0},
  154158. {&_16c0_s_p7_0,&_16c0_s_p7_1},
  154159. {&_16c0_s_p8_0,&_16c0_s_p8_1},
  154160. {&_16c0_s_p9_0,&_16c0_s_p9_1,&_16c0_s_p9_2}
  154161. }
  154162. };
  154163. static static_bookblock _resbook_16s_1={
  154164. {
  154165. {0},
  154166. {0,0,&_16c1_s_p1_0},
  154167. {0,0,&_16c1_s_p2_0},
  154168. {0,0,&_16c1_s_p3_0},
  154169. {0,0,&_16c1_s_p4_0},
  154170. {0,0,&_16c1_s_p5_0},
  154171. {0,0,&_16c1_s_p6_0},
  154172. {&_16c1_s_p7_0,&_16c1_s_p7_1},
  154173. {&_16c1_s_p8_0,&_16c1_s_p8_1},
  154174. {&_16c1_s_p9_0,&_16c1_s_p9_1,&_16c1_s_p9_2}
  154175. }
  154176. };
  154177. static static_bookblock _resbook_16s_2={
  154178. {
  154179. {0},
  154180. {0,0,&_16c2_s_p1_0},
  154181. {0,0,&_16c2_s_p2_0},
  154182. {0,0,&_16c2_s_p3_0},
  154183. {0,0,&_16c2_s_p4_0},
  154184. {&_16c2_s_p5_0,&_16c2_s_p5_1},
  154185. {&_16c2_s_p6_0,&_16c2_s_p6_1},
  154186. {&_16c2_s_p7_0,&_16c2_s_p7_1},
  154187. {&_16c2_s_p8_0,&_16c2_s_p8_1},
  154188. {&_16c2_s_p9_0,&_16c2_s_p9_1,&_16c2_s_p9_2}
  154189. }
  154190. };
  154191. static vorbis_residue_template _res_16s_0[]={
  154192. {2,0, &_residue_44_mid,
  154193. &_huff_book__16c0_s_single,&_huff_book__16c0_s_single,
  154194. &_resbook_16s_0,&_resbook_16s_0},
  154195. };
  154196. static vorbis_residue_template _res_16s_1[]={
  154197. {2,0, &_residue_44_mid,
  154198. &_huff_book__16c1_s_short,&_huff_book__16c1_s_short,
  154199. &_resbook_16s_1,&_resbook_16s_1},
  154200. {2,0, &_residue_44_mid,
  154201. &_huff_book__16c1_s_long,&_huff_book__16c1_s_long,
  154202. &_resbook_16s_1,&_resbook_16s_1}
  154203. };
  154204. static vorbis_residue_template _res_16s_2[]={
  154205. {2,0, &_residue_44_high,
  154206. &_huff_book__16c2_s_short,&_huff_book__16c2_s_short,
  154207. &_resbook_16s_2,&_resbook_16s_2},
  154208. {2,0, &_residue_44_high,
  154209. &_huff_book__16c2_s_long,&_huff_book__16c2_s_long,
  154210. &_resbook_16s_2,&_resbook_16s_2}
  154211. };
  154212. static vorbis_mapping_template _mapres_template_16_stereo[3]={
  154213. { _map_nominal, _res_16s_0 }, /* 0 */
  154214. { _map_nominal, _res_16s_1 }, /* 1 */
  154215. { _map_nominal, _res_16s_2 }, /* 2 */
  154216. };
  154217. static static_bookblock _resbook_16u_0={
  154218. {
  154219. {0},
  154220. {0,0,&_16u0__p1_0},
  154221. {0,0,&_16u0__p2_0},
  154222. {0,0,&_16u0__p3_0},
  154223. {0,0,&_16u0__p4_0},
  154224. {0,0,&_16u0__p5_0},
  154225. {&_16u0__p6_0,&_16u0__p6_1},
  154226. {&_16u0__p7_0,&_16u0__p7_1,&_16u0__p7_2}
  154227. }
  154228. };
  154229. static static_bookblock _resbook_16u_1={
  154230. {
  154231. {0},
  154232. {0,0,&_16u1__p1_0},
  154233. {0,0,&_16u1__p2_0},
  154234. {0,0,&_16u1__p3_0},
  154235. {0,0,&_16u1__p4_0},
  154236. {0,0,&_16u1__p5_0},
  154237. {0,0,&_16u1__p6_0},
  154238. {&_16u1__p7_0,&_16u1__p7_1},
  154239. {&_16u1__p8_0,&_16u1__p8_1},
  154240. {&_16u1__p9_0,&_16u1__p9_1,&_16u1__p9_2}
  154241. }
  154242. };
  154243. static static_bookblock _resbook_16u_2={
  154244. {
  154245. {0},
  154246. {0,0,&_16u2_p1_0},
  154247. {0,0,&_16u2_p2_0},
  154248. {0,0,&_16u2_p3_0},
  154249. {0,0,&_16u2_p4_0},
  154250. {&_16u2_p5_0,&_16u2_p5_1},
  154251. {&_16u2_p6_0,&_16u2_p6_1},
  154252. {&_16u2_p7_0,&_16u2_p7_1},
  154253. {&_16u2_p8_0,&_16u2_p8_1},
  154254. {&_16u2_p9_0,&_16u2_p9_1,&_16u2_p9_2}
  154255. }
  154256. };
  154257. static vorbis_residue_template _res_16u_0[]={
  154258. {1,0, &_residue_44_low_un,
  154259. &_huff_book__16u0__single,&_huff_book__16u0__single,
  154260. &_resbook_16u_0,&_resbook_16u_0},
  154261. };
  154262. static vorbis_residue_template _res_16u_1[]={
  154263. {1,0, &_residue_44_mid_un,
  154264. &_huff_book__16u1__short,&_huff_book__16u1__short,
  154265. &_resbook_16u_1,&_resbook_16u_1},
  154266. {1,0, &_residue_44_mid_un,
  154267. &_huff_book__16u1__long,&_huff_book__16u1__long,
  154268. &_resbook_16u_1,&_resbook_16u_1}
  154269. };
  154270. static vorbis_residue_template _res_16u_2[]={
  154271. {1,0, &_residue_44_hi_un,
  154272. &_huff_book__16u2__short,&_huff_book__16u2__short,
  154273. &_resbook_16u_2,&_resbook_16u_2},
  154274. {1,0, &_residue_44_hi_un,
  154275. &_huff_book__16u2__long,&_huff_book__16u2__long,
  154276. &_resbook_16u_2,&_resbook_16u_2}
  154277. };
  154278. static vorbis_mapping_template _mapres_template_16_uncoupled[3]={
  154279. { _map_nominal_u, _res_16u_0 }, /* 0 */
  154280. { _map_nominal_u, _res_16u_1 }, /* 1 */
  154281. { _map_nominal_u, _res_16u_2 }, /* 2 */
  154282. };
  154283. /*** End of inlined file: residue_16.h ***/
  154284. static int blocksize_16_short[3]={
  154285. 1024,512,512
  154286. };
  154287. static int blocksize_16_long[3]={
  154288. 1024,1024,1024
  154289. };
  154290. static int _floor_mapping_16_short[3]={
  154291. 9,3,3
  154292. };
  154293. static int _floor_mapping_16[3]={
  154294. 9,9,9
  154295. };
  154296. static double rate_mapping_16[4]={
  154297. 12000.,20000.,44000.,86000.
  154298. };
  154299. static double rate_mapping_16_uncoupled[4]={
  154300. 16000.,28000.,64000.,100000.
  154301. };
  154302. static double _global_mapping_16[4]={ 1., 2., 3., 4. };
  154303. static double quality_mapping_16[4]={ -.1,.05,.5,1. };
  154304. static double _psy_compand_16_mapping[4]={ 0., .8, 1., 1.};
  154305. ve_setup_data_template ve_setup_16_stereo={
  154306. 3,
  154307. rate_mapping_16,
  154308. quality_mapping_16,
  154309. 2,
  154310. 15000,
  154311. 19000,
  154312. blocksize_16_short,
  154313. blocksize_16_long,
  154314. _psy_tone_masteratt_16,
  154315. _psy_tone_0dB,
  154316. _psy_tone_suppress,
  154317. _vp_tonemask_adj_16,
  154318. _vp_tonemask_adj_16,
  154319. _vp_tonemask_adj_16,
  154320. _psy_noiseguards_8,
  154321. _psy_noisebias_16_impulse,
  154322. _psy_noisebias_16_short,
  154323. _psy_noisebias_16_short,
  154324. _psy_noisebias_16,
  154325. _psy_noise_suppress,
  154326. _psy_compand_8,
  154327. _psy_compand_16_mapping,
  154328. _psy_compand_16_mapping,
  154329. {_noise_start_16,_noise_start_16},
  154330. { _noise_part_16, _noise_part_16},
  154331. _noise_thresh_16,
  154332. _psy_ath_floater_16,
  154333. _psy_ath_abs_16,
  154334. _psy_lowpass_16,
  154335. _psy_global_44,
  154336. _global_mapping_16,
  154337. _psy_stereo_modes_16,
  154338. _floor_books,
  154339. _floor,
  154340. _floor_mapping_16_short,
  154341. _floor_mapping_16,
  154342. _mapres_template_16_stereo
  154343. };
  154344. ve_setup_data_template ve_setup_16_uncoupled={
  154345. 3,
  154346. rate_mapping_16_uncoupled,
  154347. quality_mapping_16,
  154348. -1,
  154349. 15000,
  154350. 19000,
  154351. blocksize_16_short,
  154352. blocksize_16_long,
  154353. _psy_tone_masteratt_16,
  154354. _psy_tone_0dB,
  154355. _psy_tone_suppress,
  154356. _vp_tonemask_adj_16,
  154357. _vp_tonemask_adj_16,
  154358. _vp_tonemask_adj_16,
  154359. _psy_noiseguards_8,
  154360. _psy_noisebias_16_impulse,
  154361. _psy_noisebias_16_short,
  154362. _psy_noisebias_16_short,
  154363. _psy_noisebias_16,
  154364. _psy_noise_suppress,
  154365. _psy_compand_8,
  154366. _psy_compand_16_mapping,
  154367. _psy_compand_16_mapping,
  154368. {_noise_start_16,_noise_start_16},
  154369. { _noise_part_16, _noise_part_16},
  154370. _noise_thresh_16,
  154371. _psy_ath_floater_16,
  154372. _psy_ath_abs_16,
  154373. _psy_lowpass_16,
  154374. _psy_global_44,
  154375. _global_mapping_16,
  154376. _psy_stereo_modes_16,
  154377. _floor_books,
  154378. _floor,
  154379. _floor_mapping_16_short,
  154380. _floor_mapping_16,
  154381. _mapres_template_16_uncoupled
  154382. };
  154383. /*** End of inlined file: setup_16.h ***/
  154384. /*** Start of inlined file: setup_22.h ***/
  154385. static double rate_mapping_22[4]={
  154386. 15000.,20000.,44000.,86000.
  154387. };
  154388. static double rate_mapping_22_uncoupled[4]={
  154389. 16000.,28000.,50000.,90000.
  154390. };
  154391. static double _psy_lowpass_22[4]={9.5,11.,30.,99.};
  154392. ve_setup_data_template ve_setup_22_stereo={
  154393. 3,
  154394. rate_mapping_22,
  154395. quality_mapping_16,
  154396. 2,
  154397. 19000,
  154398. 26000,
  154399. blocksize_16_short,
  154400. blocksize_16_long,
  154401. _psy_tone_masteratt_16,
  154402. _psy_tone_0dB,
  154403. _psy_tone_suppress,
  154404. _vp_tonemask_adj_16,
  154405. _vp_tonemask_adj_16,
  154406. _vp_tonemask_adj_16,
  154407. _psy_noiseguards_8,
  154408. _psy_noisebias_16_impulse,
  154409. _psy_noisebias_16_short,
  154410. _psy_noisebias_16_short,
  154411. _psy_noisebias_16,
  154412. _psy_noise_suppress,
  154413. _psy_compand_8,
  154414. _psy_compand_8_mapping,
  154415. _psy_compand_8_mapping,
  154416. {_noise_start_16,_noise_start_16},
  154417. { _noise_part_16, _noise_part_16},
  154418. _noise_thresh_16,
  154419. _psy_ath_floater_16,
  154420. _psy_ath_abs_16,
  154421. _psy_lowpass_22,
  154422. _psy_global_44,
  154423. _global_mapping_16,
  154424. _psy_stereo_modes_16,
  154425. _floor_books,
  154426. _floor,
  154427. _floor_mapping_16_short,
  154428. _floor_mapping_16,
  154429. _mapres_template_16_stereo
  154430. };
  154431. ve_setup_data_template ve_setup_22_uncoupled={
  154432. 3,
  154433. rate_mapping_22_uncoupled,
  154434. quality_mapping_16,
  154435. -1,
  154436. 19000,
  154437. 26000,
  154438. blocksize_16_short,
  154439. blocksize_16_long,
  154440. _psy_tone_masteratt_16,
  154441. _psy_tone_0dB,
  154442. _psy_tone_suppress,
  154443. _vp_tonemask_adj_16,
  154444. _vp_tonemask_adj_16,
  154445. _vp_tonemask_adj_16,
  154446. _psy_noiseguards_8,
  154447. _psy_noisebias_16_impulse,
  154448. _psy_noisebias_16_short,
  154449. _psy_noisebias_16_short,
  154450. _psy_noisebias_16,
  154451. _psy_noise_suppress,
  154452. _psy_compand_8,
  154453. _psy_compand_8_mapping,
  154454. _psy_compand_8_mapping,
  154455. {_noise_start_16,_noise_start_16},
  154456. { _noise_part_16, _noise_part_16},
  154457. _noise_thresh_16,
  154458. _psy_ath_floater_16,
  154459. _psy_ath_abs_16,
  154460. _psy_lowpass_22,
  154461. _psy_global_44,
  154462. _global_mapping_16,
  154463. _psy_stereo_modes_16,
  154464. _floor_books,
  154465. _floor,
  154466. _floor_mapping_16_short,
  154467. _floor_mapping_16,
  154468. _mapres_template_16_uncoupled
  154469. };
  154470. /*** End of inlined file: setup_22.h ***/
  154471. /*** Start of inlined file: setup_X.h ***/
  154472. static double rate_mapping_X[12]={
  154473. -1.,-1.,-1.,-1.,-1.,-1.,
  154474. -1.,-1.,-1.,-1.,-1.,-1.
  154475. };
  154476. ve_setup_data_template ve_setup_X_stereo={
  154477. 11,
  154478. rate_mapping_X,
  154479. quality_mapping_44,
  154480. 2,
  154481. 50000,
  154482. 200000,
  154483. blocksize_short_44,
  154484. blocksize_long_44,
  154485. _psy_tone_masteratt_44,
  154486. _psy_tone_0dB,
  154487. _psy_tone_suppress,
  154488. _vp_tonemask_adj_otherblock,
  154489. _vp_tonemask_adj_longblock,
  154490. _vp_tonemask_adj_otherblock,
  154491. _psy_noiseguards_44,
  154492. _psy_noisebias_impulse,
  154493. _psy_noisebias_padding,
  154494. _psy_noisebias_trans,
  154495. _psy_noisebias_long,
  154496. _psy_noise_suppress,
  154497. _psy_compand_44,
  154498. _psy_compand_short_mapping,
  154499. _psy_compand_long_mapping,
  154500. {_noise_start_short_44,_noise_start_long_44},
  154501. {_noise_part_short_44,_noise_part_long_44},
  154502. _noise_thresh_44,
  154503. _psy_ath_floater,
  154504. _psy_ath_abs,
  154505. _psy_lowpass_44,
  154506. _psy_global_44,
  154507. _global_mapping_44,
  154508. _psy_stereo_modes_44,
  154509. _floor_books,
  154510. _floor,
  154511. _floor_short_mapping_44,
  154512. _floor_long_mapping_44,
  154513. _mapres_template_44_stereo
  154514. };
  154515. ve_setup_data_template ve_setup_X_uncoupled={
  154516. 11,
  154517. rate_mapping_X,
  154518. quality_mapping_44,
  154519. -1,
  154520. 50000,
  154521. 200000,
  154522. blocksize_short_44,
  154523. blocksize_long_44,
  154524. _psy_tone_masteratt_44,
  154525. _psy_tone_0dB,
  154526. _psy_tone_suppress,
  154527. _vp_tonemask_adj_otherblock,
  154528. _vp_tonemask_adj_longblock,
  154529. _vp_tonemask_adj_otherblock,
  154530. _psy_noiseguards_44,
  154531. _psy_noisebias_impulse,
  154532. _psy_noisebias_padding,
  154533. _psy_noisebias_trans,
  154534. _psy_noisebias_long,
  154535. _psy_noise_suppress,
  154536. _psy_compand_44,
  154537. _psy_compand_short_mapping,
  154538. _psy_compand_long_mapping,
  154539. {_noise_start_short_44,_noise_start_long_44},
  154540. {_noise_part_short_44,_noise_part_long_44},
  154541. _noise_thresh_44,
  154542. _psy_ath_floater,
  154543. _psy_ath_abs,
  154544. _psy_lowpass_44,
  154545. _psy_global_44,
  154546. _global_mapping_44,
  154547. NULL,
  154548. _floor_books,
  154549. _floor,
  154550. _floor_short_mapping_44,
  154551. _floor_long_mapping_44,
  154552. _mapres_template_44_uncoupled
  154553. };
  154554. ve_setup_data_template ve_setup_XX_stereo={
  154555. 2,
  154556. rate_mapping_X,
  154557. quality_mapping_8,
  154558. 2,
  154559. 0,
  154560. 8000,
  154561. blocksize_8,
  154562. blocksize_8,
  154563. _psy_tone_masteratt_8,
  154564. _psy_tone_0dB,
  154565. _psy_tone_suppress,
  154566. _vp_tonemask_adj_8,
  154567. NULL,
  154568. _vp_tonemask_adj_8,
  154569. _psy_noiseguards_8,
  154570. _psy_noisebias_8,
  154571. _psy_noisebias_8,
  154572. NULL,
  154573. NULL,
  154574. _psy_noise_suppress,
  154575. _psy_compand_8,
  154576. _psy_compand_8_mapping,
  154577. NULL,
  154578. {_noise_start_8,_noise_start_8},
  154579. {_noise_part_8,_noise_part_8},
  154580. _noise_thresh_5only,
  154581. _psy_ath_floater_8,
  154582. _psy_ath_abs_8,
  154583. _psy_lowpass_8,
  154584. _psy_global_44,
  154585. _global_mapping_8,
  154586. _psy_stereo_modes_8,
  154587. _floor_books,
  154588. _floor,
  154589. _floor_mapping_8,
  154590. NULL,
  154591. _mapres_template_8_stereo
  154592. };
  154593. ve_setup_data_template ve_setup_XX_uncoupled={
  154594. 2,
  154595. rate_mapping_X,
  154596. quality_mapping_8,
  154597. -1,
  154598. 0,
  154599. 8000,
  154600. blocksize_8,
  154601. blocksize_8,
  154602. _psy_tone_masteratt_8,
  154603. _psy_tone_0dB,
  154604. _psy_tone_suppress,
  154605. _vp_tonemask_adj_8,
  154606. NULL,
  154607. _vp_tonemask_adj_8,
  154608. _psy_noiseguards_8,
  154609. _psy_noisebias_8,
  154610. _psy_noisebias_8,
  154611. NULL,
  154612. NULL,
  154613. _psy_noise_suppress,
  154614. _psy_compand_8,
  154615. _psy_compand_8_mapping,
  154616. NULL,
  154617. {_noise_start_8,_noise_start_8},
  154618. {_noise_part_8,_noise_part_8},
  154619. _noise_thresh_5only,
  154620. _psy_ath_floater_8,
  154621. _psy_ath_abs_8,
  154622. _psy_lowpass_8,
  154623. _psy_global_44,
  154624. _global_mapping_8,
  154625. _psy_stereo_modes_8,
  154626. _floor_books,
  154627. _floor,
  154628. _floor_mapping_8,
  154629. NULL,
  154630. _mapres_template_8_uncoupled
  154631. };
  154632. /*** End of inlined file: setup_X.h ***/
  154633. static ve_setup_data_template *setup_list[]={
  154634. &ve_setup_44_stereo,
  154635. &ve_setup_44_uncoupled,
  154636. &ve_setup_32_stereo,
  154637. &ve_setup_32_uncoupled,
  154638. &ve_setup_22_stereo,
  154639. &ve_setup_22_uncoupled,
  154640. &ve_setup_16_stereo,
  154641. &ve_setup_16_uncoupled,
  154642. &ve_setup_11_stereo,
  154643. &ve_setup_11_uncoupled,
  154644. &ve_setup_8_stereo,
  154645. &ve_setup_8_uncoupled,
  154646. &ve_setup_X_stereo,
  154647. &ve_setup_X_uncoupled,
  154648. &ve_setup_XX_stereo,
  154649. &ve_setup_XX_uncoupled,
  154650. 0
  154651. };
  154652. static int vorbis_encode_toplevel_setup(vorbis_info *vi,int ch,long rate){
  154653. if(vi && vi->codec_setup){
  154654. vi->version=0;
  154655. vi->channels=ch;
  154656. vi->rate=rate;
  154657. return(0);
  154658. }
  154659. return(OV_EINVAL);
  154660. }
  154661. static void vorbis_encode_floor_setup(vorbis_info *vi,double s,int block,
  154662. static_codebook ***books,
  154663. vorbis_info_floor1 *in,
  154664. int *x){
  154665. int i,k,is=s;
  154666. vorbis_info_floor1 *f=(vorbis_info_floor1*) _ogg_calloc(1,sizeof(*f));
  154667. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154668. memcpy(f,in+x[is],sizeof(*f));
  154669. /* fill in the lowpass field, even if it's temporary */
  154670. f->n=ci->blocksizes[block]>>1;
  154671. /* books */
  154672. {
  154673. int partitions=f->partitions;
  154674. int maxclass=-1;
  154675. int maxbook=-1;
  154676. for(i=0;i<partitions;i++)
  154677. if(f->partitionclass[i]>maxclass)maxclass=f->partitionclass[i];
  154678. for(i=0;i<=maxclass;i++){
  154679. if(f->class_book[i]>maxbook)maxbook=f->class_book[i];
  154680. f->class_book[i]+=ci->books;
  154681. for(k=0;k<(1<<f->class_subs[i]);k++){
  154682. if(f->class_subbook[i][k]>maxbook)maxbook=f->class_subbook[i][k];
  154683. if(f->class_subbook[i][k]>=0)f->class_subbook[i][k]+=ci->books;
  154684. }
  154685. }
  154686. for(i=0;i<=maxbook;i++)
  154687. ci->book_param[ci->books++]=books[x[is]][i];
  154688. }
  154689. /* for now, we're only using floor 1 */
  154690. ci->floor_type[ci->floors]=1;
  154691. ci->floor_param[ci->floors]=f;
  154692. ci->floors++;
  154693. return;
  154694. }
  154695. static void vorbis_encode_global_psych_setup(vorbis_info *vi,double s,
  154696. vorbis_info_psy_global *in,
  154697. double *x){
  154698. int i,is=s;
  154699. double ds=s-is;
  154700. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154701. vorbis_info_psy_global *g=&ci->psy_g_param;
  154702. memcpy(g,in+(int)x[is],sizeof(*g));
  154703. ds=x[is]*(1.-ds)+x[is+1]*ds;
  154704. is=(int)ds;
  154705. ds-=is;
  154706. if(ds==0 && is>0){
  154707. is--;
  154708. ds=1.;
  154709. }
  154710. /* interpolate the trigger threshholds */
  154711. for(i=0;i<4;i++){
  154712. g->preecho_thresh[i]=in[is].preecho_thresh[i]*(1.-ds)+in[is+1].preecho_thresh[i]*ds;
  154713. g->postecho_thresh[i]=in[is].postecho_thresh[i]*(1.-ds)+in[is+1].postecho_thresh[i]*ds;
  154714. }
  154715. g->ampmax_att_per_sec=ci->hi.amplitude_track_dBpersec;
  154716. return;
  154717. }
  154718. static void vorbis_encode_global_stereo(vorbis_info *vi,
  154719. highlevel_encode_setup *hi,
  154720. adj_stereo *p){
  154721. float s=hi->stereo_point_setting;
  154722. int i,is=s;
  154723. double ds=s-is;
  154724. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154725. vorbis_info_psy_global *g=&ci->psy_g_param;
  154726. if(p){
  154727. memcpy(g->coupling_prepointamp,p[is].pre,sizeof(*p[is].pre)*PACKETBLOBS);
  154728. memcpy(g->coupling_postpointamp,p[is].post,sizeof(*p[is].post)*PACKETBLOBS);
  154729. if(hi->managed){
  154730. /* interpolate the kHz threshholds */
  154731. for(i=0;i<PACKETBLOBS;i++){
  154732. float kHz=p[is].kHz[i]*(1.-ds)+p[is+1].kHz[i]*ds;
  154733. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154734. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154735. g->coupling_pkHz[i]=kHz;
  154736. kHz=p[is].lowpasskHz[i]*(1.-ds)+p[is+1].lowpasskHz[i]*ds;
  154737. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154738. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154739. }
  154740. }else{
  154741. float kHz=p[is].kHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].kHz[PACKETBLOBS/2]*ds;
  154742. for(i=0;i<PACKETBLOBS;i++){
  154743. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154744. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154745. g->coupling_pkHz[i]=kHz;
  154746. }
  154747. kHz=p[is].lowpasskHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].lowpasskHz[PACKETBLOBS/2]*ds;
  154748. for(i=0;i<PACKETBLOBS;i++){
  154749. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154750. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154751. }
  154752. }
  154753. }else{
  154754. for(i=0;i<PACKETBLOBS;i++){
  154755. g->sliding_lowpass[0][i]=ci->blocksizes[0];
  154756. g->sliding_lowpass[1][i]=ci->blocksizes[1];
  154757. }
  154758. }
  154759. return;
  154760. }
  154761. static void vorbis_encode_psyset_setup(vorbis_info *vi,double s,
  154762. int *nn_start,
  154763. int *nn_partition,
  154764. double *nn_thresh,
  154765. int block){
  154766. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154767. vorbis_info_psy *p=ci->psy_param[block];
  154768. highlevel_encode_setup *hi=&ci->hi;
  154769. int is=s;
  154770. if(block>=ci->psys)
  154771. ci->psys=block+1;
  154772. if(!p){
  154773. p=(vorbis_info_psy*)_ogg_calloc(1,sizeof(*p));
  154774. ci->psy_param[block]=p;
  154775. }
  154776. memcpy(p,&_psy_info_template,sizeof(*p));
  154777. p->blockflag=block>>1;
  154778. if(hi->noise_normalize_p){
  154779. p->normal_channel_p=1;
  154780. p->normal_point_p=1;
  154781. p->normal_start=nn_start[is];
  154782. p->normal_partition=nn_partition[is];
  154783. p->normal_thresh=nn_thresh[is];
  154784. }
  154785. return;
  154786. }
  154787. static void vorbis_encode_tonemask_setup(vorbis_info *vi,double s,int block,
  154788. att3 *att,
  154789. int *max,
  154790. vp_adjblock *in){
  154791. int i,is=s;
  154792. double ds=s-is;
  154793. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154794. vorbis_info_psy *p=ci->psy_param[block];
  154795. /* 0 and 2 are only used by bitmanagement, but there's no harm to always
  154796. filling the values in here */
  154797. p->tone_masteratt[0]=att[is].att[0]*(1.-ds)+att[is+1].att[0]*ds;
  154798. p->tone_masteratt[1]=att[is].att[1]*(1.-ds)+att[is+1].att[1]*ds;
  154799. p->tone_masteratt[2]=att[is].att[2]*(1.-ds)+att[is+1].att[2]*ds;
  154800. p->tone_centerboost=att[is].boost*(1.-ds)+att[is+1].boost*ds;
  154801. p->tone_decay=att[is].decay*(1.-ds)+att[is+1].decay*ds;
  154802. p->max_curve_dB=max[is]*(1.-ds)+max[is+1]*ds;
  154803. for(i=0;i<P_BANDS;i++)
  154804. p->toneatt[i]=in[is].block[i]*(1.-ds)+in[is+1].block[i]*ds;
  154805. return;
  154806. }
  154807. static void vorbis_encode_compand_setup(vorbis_info *vi,double s,int block,
  154808. compandblock *in, double *x){
  154809. int i,is=s;
  154810. double ds=s-is;
  154811. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154812. vorbis_info_psy *p=ci->psy_param[block];
  154813. ds=x[is]*(1.-ds)+x[is+1]*ds;
  154814. is=(int)ds;
  154815. ds-=is;
  154816. if(ds==0 && is>0){
  154817. is--;
  154818. ds=1.;
  154819. }
  154820. /* interpolate the compander settings */
  154821. for(i=0;i<NOISE_COMPAND_LEVELS;i++)
  154822. p->noisecompand[i]=in[is].data[i]*(1.-ds)+in[is+1].data[i]*ds;
  154823. return;
  154824. }
  154825. static void vorbis_encode_peak_setup(vorbis_info *vi,double s,int block,
  154826. int *suppress){
  154827. int is=s;
  154828. double ds=s-is;
  154829. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154830. vorbis_info_psy *p=ci->psy_param[block];
  154831. p->tone_abs_limit=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  154832. return;
  154833. }
  154834. static void vorbis_encode_noisebias_setup(vorbis_info *vi,double s,int block,
  154835. int *suppress,
  154836. noise3 *in,
  154837. noiseguard *guard,
  154838. double userbias){
  154839. int i,is=s,j;
  154840. double ds=s-is;
  154841. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154842. vorbis_info_psy *p=ci->psy_param[block];
  154843. p->noisemaxsupp=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  154844. p->noisewindowlomin=guard[block].lo;
  154845. p->noisewindowhimin=guard[block].hi;
  154846. p->noisewindowfixed=guard[block].fixed;
  154847. for(j=0;j<P_NOISECURVES;j++)
  154848. for(i=0;i<P_BANDS;i++)
  154849. p->noiseoff[j][i]=in[is].data[j][i]*(1.-ds)+in[is+1].data[j][i]*ds;
  154850. /* impulse blocks may take a user specified bias to boost the
  154851. nominal/high noise encoding depth */
  154852. for(j=0;j<P_NOISECURVES;j++){
  154853. float min=p->noiseoff[j][0]+6; /* the lowest it can go */
  154854. for(i=0;i<P_BANDS;i++){
  154855. p->noiseoff[j][i]+=userbias;
  154856. if(p->noiseoff[j][i]<min)p->noiseoff[j][i]=min;
  154857. }
  154858. }
  154859. return;
  154860. }
  154861. static void vorbis_encode_ath_setup(vorbis_info *vi,int block){
  154862. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154863. vorbis_info_psy *p=ci->psy_param[block];
  154864. p->ath_adjatt=ci->hi.ath_floating_dB;
  154865. p->ath_maxatt=ci->hi.ath_absolute_dB;
  154866. return;
  154867. }
  154868. static int book_dup_or_new(codec_setup_info *ci,static_codebook *book){
  154869. int i;
  154870. for(i=0;i<ci->books;i++)
  154871. if(ci->book_param[i]==book)return(i);
  154872. return(ci->books++);
  154873. }
  154874. static void vorbis_encode_blocksize_setup(vorbis_info *vi,double s,
  154875. int *shortb,int *longb){
  154876. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154877. int is=s;
  154878. int blockshort=shortb[is];
  154879. int blocklong=longb[is];
  154880. ci->blocksizes[0]=blockshort;
  154881. ci->blocksizes[1]=blocklong;
  154882. }
  154883. static void vorbis_encode_residue_setup(vorbis_info *vi,
  154884. int number, int block,
  154885. vorbis_residue_template *res){
  154886. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154887. int i,n;
  154888. vorbis_info_residue0 *r=(vorbis_info_residue0*)(ci->residue_param[number]=
  154889. (vorbis_info_residue0*)_ogg_malloc(sizeof(*r)));
  154890. memcpy(r,res->res,sizeof(*r));
  154891. if(ci->residues<=number)ci->residues=number+1;
  154892. switch(ci->blocksizes[block]){
  154893. case 64:case 128:case 256:
  154894. r->grouping=16;
  154895. break;
  154896. default:
  154897. r->grouping=32;
  154898. break;
  154899. }
  154900. ci->residue_type[number]=res->res_type;
  154901. /* to be adjusted by lowpass/pointlimit later */
  154902. n=r->end=ci->blocksizes[block]>>1;
  154903. if(res->res_type==2)
  154904. n=r->end*=vi->channels;
  154905. /* fill in all the books */
  154906. {
  154907. int booklist=0,k;
  154908. if(ci->hi.managed){
  154909. for(i=0;i<r->partitions;i++)
  154910. for(k=0;k<3;k++)
  154911. if(res->books_base_managed->books[i][k])
  154912. r->secondstages[i]|=(1<<k);
  154913. r->groupbook=book_dup_or_new(ci,res->book_aux_managed);
  154914. ci->book_param[r->groupbook]=res->book_aux_managed;
  154915. for(i=0;i<r->partitions;i++){
  154916. for(k=0;k<3;k++){
  154917. if(res->books_base_managed->books[i][k]){
  154918. int bookid=book_dup_or_new(ci,res->books_base_managed->books[i][k]);
  154919. r->booklist[booklist++]=bookid;
  154920. ci->book_param[bookid]=res->books_base_managed->books[i][k];
  154921. }
  154922. }
  154923. }
  154924. }else{
  154925. for(i=0;i<r->partitions;i++)
  154926. for(k=0;k<3;k++)
  154927. if(res->books_base->books[i][k])
  154928. r->secondstages[i]|=(1<<k);
  154929. r->groupbook=book_dup_or_new(ci,res->book_aux);
  154930. ci->book_param[r->groupbook]=res->book_aux;
  154931. for(i=0;i<r->partitions;i++){
  154932. for(k=0;k<3;k++){
  154933. if(res->books_base->books[i][k]){
  154934. int bookid=book_dup_or_new(ci,res->books_base->books[i][k]);
  154935. r->booklist[booklist++]=bookid;
  154936. ci->book_param[bookid]=res->books_base->books[i][k];
  154937. }
  154938. }
  154939. }
  154940. }
  154941. }
  154942. /* lowpass setup/pointlimit */
  154943. {
  154944. double freq=ci->hi.lowpass_kHz*1000.;
  154945. vorbis_info_floor1 *f=(vorbis_info_floor1*)ci->floor_param[block]; /* by convention */
  154946. double nyq=vi->rate/2.;
  154947. long blocksize=ci->blocksizes[block]>>1;
  154948. /* lowpass needs to be set in the floor and the residue. */
  154949. if(freq>nyq)freq=nyq;
  154950. /* in the floor, the granularity can be very fine; it doesn't alter
  154951. the encoding structure, only the samples used to fit the floor
  154952. approximation */
  154953. f->n=freq/nyq*blocksize;
  154954. /* this res may by limited by the maximum pointlimit of the mode,
  154955. not the lowpass. the floor is always lowpass limited. */
  154956. if(res->limit_type){
  154957. if(ci->hi.managed)
  154958. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS-1]*1000.;
  154959. else
  154960. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS/2]*1000.;
  154961. if(freq>nyq)freq=nyq;
  154962. }
  154963. /* in the residue, we're constrained, physically, by partition
  154964. boundaries. We still lowpass 'wherever', but we have to round up
  154965. here to next boundary, or the vorbis spec will round it *down* to
  154966. previous boundary in encode/decode */
  154967. if(ci->residue_type[block]==2)
  154968. r->end=(int)((freq/nyq*blocksize*2)/r->grouping+.9)* /* round up only if we're well past */
  154969. r->grouping;
  154970. else
  154971. r->end=(int)((freq/nyq*blocksize)/r->grouping+.9)* /* round up only if we're well past */
  154972. r->grouping;
  154973. }
  154974. }
  154975. /* we assume two maps in this encoder */
  154976. static void vorbis_encode_map_n_res_setup(vorbis_info *vi,double s,
  154977. vorbis_mapping_template *maps){
  154978. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154979. int i,j,is=s,modes=2;
  154980. vorbis_info_mapping0 *map=maps[is].map;
  154981. vorbis_info_mode *mode=_mode_template;
  154982. vorbis_residue_template *res=maps[is].res;
  154983. if(ci->blocksizes[0]==ci->blocksizes[1])modes=1;
  154984. for(i=0;i<modes;i++){
  154985. ci->map_param[i]=_ogg_calloc(1,sizeof(*map));
  154986. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*mode));
  154987. memcpy(ci->mode_param[i],mode+i,sizeof(*_mode_template));
  154988. if(i>=ci->modes)ci->modes=i+1;
  154989. ci->map_type[i]=0;
  154990. memcpy(ci->map_param[i],map+i,sizeof(*map));
  154991. if(i>=ci->maps)ci->maps=i+1;
  154992. for(j=0;j<map[i].submaps;j++)
  154993. vorbis_encode_residue_setup(vi,map[i].residuesubmap[j],i
  154994. ,res+map[i].residuesubmap[j]);
  154995. }
  154996. }
  154997. static double setting_to_approx_bitrate(vorbis_info *vi){
  154998. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154999. highlevel_encode_setup *hi=&ci->hi;
  155000. ve_setup_data_template *setup=(ve_setup_data_template *)hi->setup;
  155001. int is=hi->base_setting;
  155002. double ds=hi->base_setting-is;
  155003. int ch=vi->channels;
  155004. double *r=setup->rate_mapping;
  155005. if(r==NULL)
  155006. return(-1);
  155007. return((r[is]*(1.-ds)+r[is+1]*ds)*ch);
  155008. }
  155009. static void get_setup_template(vorbis_info *vi,
  155010. long ch,long srate,
  155011. double req,int q_or_bitrate){
  155012. int i=0,j;
  155013. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  155014. highlevel_encode_setup *hi=&ci->hi;
  155015. if(q_or_bitrate)req/=ch;
  155016. while(setup_list[i]){
  155017. if(setup_list[i]->coupling_restriction==-1 ||
  155018. setup_list[i]->coupling_restriction==ch){
  155019. if(srate>=setup_list[i]->samplerate_min_restriction &&
  155020. srate<=setup_list[i]->samplerate_max_restriction){
  155021. int mappings=setup_list[i]->mappings;
  155022. double *map=(q_or_bitrate?
  155023. setup_list[i]->rate_mapping:
  155024. setup_list[i]->quality_mapping);
  155025. /* the template matches. Does the requested quality mode
  155026. fall within this template's modes? */
  155027. if(req<map[0]){++i;continue;}
  155028. if(req>map[setup_list[i]->mappings]){++i;continue;}
  155029. for(j=0;j<mappings;j++)
  155030. if(req>=map[j] && req<map[j+1])break;
  155031. /* an all-points match */
  155032. hi->setup=setup_list[i];
  155033. if(j==mappings)
  155034. hi->base_setting=j-.001;
  155035. else{
  155036. float low=map[j];
  155037. float high=map[j+1];
  155038. float del=(req-low)/(high-low);
  155039. hi->base_setting=j+del;
  155040. }
  155041. return;
  155042. }
  155043. }
  155044. i++;
  155045. }
  155046. hi->setup=NULL;
  155047. }
  155048. /* encoders will need to use vorbis_info_init beforehand and call
  155049. vorbis_info clear when all done */
  155050. /* two interfaces; this, more detailed one, and later a convenience
  155051. layer on top */
  155052. /* the final setup call */
  155053. int vorbis_encode_setup_init(vorbis_info *vi){
  155054. int i0=0,singleblock=0;
  155055. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  155056. ve_setup_data_template *setup=NULL;
  155057. highlevel_encode_setup *hi=&ci->hi;
  155058. if(ci==NULL)return(OV_EINVAL);
  155059. if(!hi->impulse_block_p)i0=1;
  155060. /* too low/high an ATH floater is nonsensical, but doesn't break anything */
  155061. if(hi->ath_floating_dB>-80)hi->ath_floating_dB=-80;
  155062. if(hi->ath_floating_dB<-200)hi->ath_floating_dB=-200;
  155063. /* again, bound this to avoid the app shooting itself int he foot
  155064. too badly */
  155065. if(hi->amplitude_track_dBpersec>0.)hi->amplitude_track_dBpersec=0.;
  155066. if(hi->amplitude_track_dBpersec<-99999.)hi->amplitude_track_dBpersec=-99999.;
  155067. /* get the appropriate setup template; matches the fetch in previous
  155068. stages */
  155069. setup=(ve_setup_data_template *)hi->setup;
  155070. if(setup==NULL)return(OV_EINVAL);
  155071. hi->set_in_stone=1;
  155072. /* choose block sizes from configured sizes as well as paying
  155073. attention to long_block_p and short_block_p. If the configured
  155074. short and long blocks are the same length, we set long_block_p
  155075. and unset short_block_p */
  155076. vorbis_encode_blocksize_setup(vi,hi->base_setting,
  155077. setup->blocksize_short,
  155078. setup->blocksize_long);
  155079. if(ci->blocksizes[0]==ci->blocksizes[1])singleblock=1;
  155080. /* floor setup; choose proper floor params. Allocated on the floor
  155081. stack in order; if we alloc only long floor, it's 0 */
  155082. vorbis_encode_floor_setup(vi,hi->short_setting,0,
  155083. setup->floor_books,
  155084. setup->floor_params,
  155085. setup->floor_short_mapping);
  155086. if(!singleblock)
  155087. vorbis_encode_floor_setup(vi,hi->long_setting,1,
  155088. setup->floor_books,
  155089. setup->floor_params,
  155090. setup->floor_long_mapping);
  155091. /* setup of [mostly] short block detection and stereo*/
  155092. vorbis_encode_global_psych_setup(vi,hi->trigger_setting,
  155093. setup->global_params,
  155094. setup->global_mapping);
  155095. vorbis_encode_global_stereo(vi,hi,setup->stereo_modes);
  155096. /* basic psych setup and noise normalization */
  155097. vorbis_encode_psyset_setup(vi,hi->short_setting,
  155098. setup->psy_noise_normal_start[0],
  155099. setup->psy_noise_normal_partition[0],
  155100. setup->psy_noise_normal_thresh,
  155101. 0);
  155102. vorbis_encode_psyset_setup(vi,hi->short_setting,
  155103. setup->psy_noise_normal_start[0],
  155104. setup->psy_noise_normal_partition[0],
  155105. setup->psy_noise_normal_thresh,
  155106. 1);
  155107. if(!singleblock){
  155108. vorbis_encode_psyset_setup(vi,hi->long_setting,
  155109. setup->psy_noise_normal_start[1],
  155110. setup->psy_noise_normal_partition[1],
  155111. setup->psy_noise_normal_thresh,
  155112. 2);
  155113. vorbis_encode_psyset_setup(vi,hi->long_setting,
  155114. setup->psy_noise_normal_start[1],
  155115. setup->psy_noise_normal_partition[1],
  155116. setup->psy_noise_normal_thresh,
  155117. 3);
  155118. }
  155119. /* tone masking setup */
  155120. vorbis_encode_tonemask_setup(vi,hi->block[i0].tone_mask_setting,0,
  155121. setup->psy_tone_masteratt,
  155122. setup->psy_tone_0dB,
  155123. setup->psy_tone_adj_impulse);
  155124. vorbis_encode_tonemask_setup(vi,hi->block[1].tone_mask_setting,1,
  155125. setup->psy_tone_masteratt,
  155126. setup->psy_tone_0dB,
  155127. setup->psy_tone_adj_other);
  155128. if(!singleblock){
  155129. vorbis_encode_tonemask_setup(vi,hi->block[2].tone_mask_setting,2,
  155130. setup->psy_tone_masteratt,
  155131. setup->psy_tone_0dB,
  155132. setup->psy_tone_adj_other);
  155133. vorbis_encode_tonemask_setup(vi,hi->block[3].tone_mask_setting,3,
  155134. setup->psy_tone_masteratt,
  155135. setup->psy_tone_0dB,
  155136. setup->psy_tone_adj_long);
  155137. }
  155138. /* noise companding setup */
  155139. vorbis_encode_compand_setup(vi,hi->block[i0].noise_compand_setting,0,
  155140. setup->psy_noise_compand,
  155141. setup->psy_noise_compand_short_mapping);
  155142. vorbis_encode_compand_setup(vi,hi->block[1].noise_compand_setting,1,
  155143. setup->psy_noise_compand,
  155144. setup->psy_noise_compand_short_mapping);
  155145. if(!singleblock){
  155146. vorbis_encode_compand_setup(vi,hi->block[2].noise_compand_setting,2,
  155147. setup->psy_noise_compand,
  155148. setup->psy_noise_compand_long_mapping);
  155149. vorbis_encode_compand_setup(vi,hi->block[3].noise_compand_setting,3,
  155150. setup->psy_noise_compand,
  155151. setup->psy_noise_compand_long_mapping);
  155152. }
  155153. /* peak guarding setup */
  155154. vorbis_encode_peak_setup(vi,hi->block[i0].tone_peaklimit_setting,0,
  155155. setup->psy_tone_dBsuppress);
  155156. vorbis_encode_peak_setup(vi,hi->block[1].tone_peaklimit_setting,1,
  155157. setup->psy_tone_dBsuppress);
  155158. if(!singleblock){
  155159. vorbis_encode_peak_setup(vi,hi->block[2].tone_peaklimit_setting,2,
  155160. setup->psy_tone_dBsuppress);
  155161. vorbis_encode_peak_setup(vi,hi->block[3].tone_peaklimit_setting,3,
  155162. setup->psy_tone_dBsuppress);
  155163. }
  155164. /* noise bias setup */
  155165. vorbis_encode_noisebias_setup(vi,hi->block[i0].noise_bias_setting,0,
  155166. setup->psy_noise_dBsuppress,
  155167. setup->psy_noise_bias_impulse,
  155168. setup->psy_noiseguards,
  155169. (i0==0?hi->impulse_noisetune:0.));
  155170. vorbis_encode_noisebias_setup(vi,hi->block[1].noise_bias_setting,1,
  155171. setup->psy_noise_dBsuppress,
  155172. setup->psy_noise_bias_padding,
  155173. setup->psy_noiseguards,0.);
  155174. if(!singleblock){
  155175. vorbis_encode_noisebias_setup(vi,hi->block[2].noise_bias_setting,2,
  155176. setup->psy_noise_dBsuppress,
  155177. setup->psy_noise_bias_trans,
  155178. setup->psy_noiseguards,0.);
  155179. vorbis_encode_noisebias_setup(vi,hi->block[3].noise_bias_setting,3,
  155180. setup->psy_noise_dBsuppress,
  155181. setup->psy_noise_bias_long,
  155182. setup->psy_noiseguards,0.);
  155183. }
  155184. vorbis_encode_ath_setup(vi,0);
  155185. vorbis_encode_ath_setup(vi,1);
  155186. if(!singleblock){
  155187. vorbis_encode_ath_setup(vi,2);
  155188. vorbis_encode_ath_setup(vi,3);
  155189. }
  155190. vorbis_encode_map_n_res_setup(vi,hi->base_setting,setup->maps);
  155191. /* set bitrate readonlies and management */
  155192. if(hi->bitrate_av>0)
  155193. vi->bitrate_nominal=hi->bitrate_av;
  155194. else{
  155195. vi->bitrate_nominal=setting_to_approx_bitrate(vi);
  155196. }
  155197. vi->bitrate_lower=hi->bitrate_min;
  155198. vi->bitrate_upper=hi->bitrate_max;
  155199. if(hi->bitrate_av)
  155200. vi->bitrate_window=(double)hi->bitrate_reservoir/hi->bitrate_av;
  155201. else
  155202. vi->bitrate_window=0.;
  155203. if(hi->managed){
  155204. ci->bi.avg_rate=hi->bitrate_av;
  155205. ci->bi.min_rate=hi->bitrate_min;
  155206. ci->bi.max_rate=hi->bitrate_max;
  155207. ci->bi.reservoir_bits=hi->bitrate_reservoir;
  155208. ci->bi.reservoir_bias=
  155209. hi->bitrate_reservoir_bias;
  155210. ci->bi.slew_damp=hi->bitrate_av_damp;
  155211. }
  155212. return(0);
  155213. }
  155214. static int vorbis_encode_setup_setting(vorbis_info *vi,
  155215. long channels,
  155216. long rate){
  155217. int ret=0,i,is;
  155218. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155219. highlevel_encode_setup *hi=&ci->hi;
  155220. ve_setup_data_template *setup=(ve_setup_data_template*) hi->setup;
  155221. double ds;
  155222. ret=vorbis_encode_toplevel_setup(vi,channels,rate);
  155223. if(ret)return(ret);
  155224. is=hi->base_setting;
  155225. ds=hi->base_setting-is;
  155226. hi->short_setting=hi->base_setting;
  155227. hi->long_setting=hi->base_setting;
  155228. hi->managed=0;
  155229. hi->impulse_block_p=1;
  155230. hi->noise_normalize_p=1;
  155231. hi->stereo_point_setting=hi->base_setting;
  155232. hi->lowpass_kHz=
  155233. setup->psy_lowpass[is]*(1.-ds)+setup->psy_lowpass[is+1]*ds;
  155234. hi->ath_floating_dB=setup->psy_ath_float[is]*(1.-ds)+
  155235. setup->psy_ath_float[is+1]*ds;
  155236. hi->ath_absolute_dB=setup->psy_ath_abs[is]*(1.-ds)+
  155237. setup->psy_ath_abs[is+1]*ds;
  155238. hi->amplitude_track_dBpersec=-6.;
  155239. hi->trigger_setting=hi->base_setting;
  155240. for(i=0;i<4;i++){
  155241. hi->block[i].tone_mask_setting=hi->base_setting;
  155242. hi->block[i].tone_peaklimit_setting=hi->base_setting;
  155243. hi->block[i].noise_bias_setting=hi->base_setting;
  155244. hi->block[i].noise_compand_setting=hi->base_setting;
  155245. }
  155246. return(ret);
  155247. }
  155248. int vorbis_encode_setup_vbr(vorbis_info *vi,
  155249. long channels,
  155250. long rate,
  155251. float quality){
  155252. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  155253. highlevel_encode_setup *hi=&ci->hi;
  155254. quality+=.0000001;
  155255. if(quality>=1.)quality=.9999;
  155256. get_setup_template(vi,channels,rate,quality,0);
  155257. if(!hi->setup)return OV_EIMPL;
  155258. return vorbis_encode_setup_setting(vi,channels,rate);
  155259. }
  155260. int vorbis_encode_init_vbr(vorbis_info *vi,
  155261. long channels,
  155262. long rate,
  155263. float base_quality /* 0. to 1. */
  155264. ){
  155265. int ret=0;
  155266. ret=vorbis_encode_setup_vbr(vi,channels,rate,base_quality);
  155267. if(ret){
  155268. vorbis_info_clear(vi);
  155269. return ret;
  155270. }
  155271. ret=vorbis_encode_setup_init(vi);
  155272. if(ret)
  155273. vorbis_info_clear(vi);
  155274. return(ret);
  155275. }
  155276. int vorbis_encode_setup_managed(vorbis_info *vi,
  155277. long channels,
  155278. long rate,
  155279. long max_bitrate,
  155280. long nominal_bitrate,
  155281. long min_bitrate){
  155282. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155283. highlevel_encode_setup *hi=&ci->hi;
  155284. double tnominal=nominal_bitrate;
  155285. int ret=0;
  155286. if(nominal_bitrate<=0.){
  155287. if(max_bitrate>0.){
  155288. if(min_bitrate>0.)
  155289. nominal_bitrate=(max_bitrate+min_bitrate)*.5;
  155290. else
  155291. nominal_bitrate=max_bitrate*.875;
  155292. }else{
  155293. if(min_bitrate>0.){
  155294. nominal_bitrate=min_bitrate;
  155295. }else{
  155296. return(OV_EINVAL);
  155297. }
  155298. }
  155299. }
  155300. get_setup_template(vi,channels,rate,nominal_bitrate,1);
  155301. if(!hi->setup)return OV_EIMPL;
  155302. ret=vorbis_encode_setup_setting(vi,channels,rate);
  155303. if(ret){
  155304. vorbis_info_clear(vi);
  155305. return ret;
  155306. }
  155307. /* initialize management with sane defaults */
  155308. hi->managed=1;
  155309. hi->bitrate_min=min_bitrate;
  155310. hi->bitrate_max=max_bitrate;
  155311. hi->bitrate_av=tnominal;
  155312. hi->bitrate_av_damp=1.5f; /* full range in no less than 1.5 second */
  155313. hi->bitrate_reservoir=nominal_bitrate*2;
  155314. hi->bitrate_reservoir_bias=.1; /* bias toward hoarding bits */
  155315. return(ret);
  155316. }
  155317. int vorbis_encode_init(vorbis_info *vi,
  155318. long channels,
  155319. long rate,
  155320. long max_bitrate,
  155321. long nominal_bitrate,
  155322. long min_bitrate){
  155323. int ret=vorbis_encode_setup_managed(vi,channels,rate,
  155324. max_bitrate,
  155325. nominal_bitrate,
  155326. min_bitrate);
  155327. if(ret){
  155328. vorbis_info_clear(vi);
  155329. return(ret);
  155330. }
  155331. ret=vorbis_encode_setup_init(vi);
  155332. if(ret)
  155333. vorbis_info_clear(vi);
  155334. return(ret);
  155335. }
  155336. int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg){
  155337. if(vi){
  155338. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155339. highlevel_encode_setup *hi=&ci->hi;
  155340. int setp=(number&0xf); /* a read request has a low nibble of 0 */
  155341. if(setp && hi->set_in_stone)return(OV_EINVAL);
  155342. switch(number){
  155343. /* now deprecated *****************/
  155344. case OV_ECTL_RATEMANAGE_GET:
  155345. {
  155346. struct ovectl_ratemanage_arg *ai=
  155347. (struct ovectl_ratemanage_arg *)arg;
  155348. ai->management_active=hi->managed;
  155349. ai->bitrate_hard_window=ai->bitrate_av_window=
  155350. (double)hi->bitrate_reservoir/vi->rate;
  155351. ai->bitrate_av_window_center=1.;
  155352. ai->bitrate_hard_min=hi->bitrate_min;
  155353. ai->bitrate_hard_max=hi->bitrate_max;
  155354. ai->bitrate_av_lo=hi->bitrate_av;
  155355. ai->bitrate_av_hi=hi->bitrate_av;
  155356. }
  155357. return(0);
  155358. /* now deprecated *****************/
  155359. case OV_ECTL_RATEMANAGE_SET:
  155360. {
  155361. struct ovectl_ratemanage_arg *ai=
  155362. (struct ovectl_ratemanage_arg *)arg;
  155363. if(ai==NULL){
  155364. hi->managed=0;
  155365. }else{
  155366. hi->managed=ai->management_active;
  155367. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_AVG,arg);
  155368. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_HARD,arg);
  155369. }
  155370. }
  155371. return 0;
  155372. /* now deprecated *****************/
  155373. case OV_ECTL_RATEMANAGE_AVG:
  155374. {
  155375. struct ovectl_ratemanage_arg *ai=
  155376. (struct ovectl_ratemanage_arg *)arg;
  155377. if(ai==NULL){
  155378. hi->bitrate_av=0;
  155379. }else{
  155380. hi->bitrate_av=(ai->bitrate_av_lo+ai->bitrate_av_hi)*.5;
  155381. }
  155382. }
  155383. return(0);
  155384. /* now deprecated *****************/
  155385. case OV_ECTL_RATEMANAGE_HARD:
  155386. {
  155387. struct ovectl_ratemanage_arg *ai=
  155388. (struct ovectl_ratemanage_arg *)arg;
  155389. if(ai==NULL){
  155390. hi->bitrate_min=0;
  155391. hi->bitrate_max=0;
  155392. }else{
  155393. hi->bitrate_min=ai->bitrate_hard_min;
  155394. hi->bitrate_max=ai->bitrate_hard_max;
  155395. hi->bitrate_reservoir=ai->bitrate_hard_window*
  155396. (hi->bitrate_max+hi->bitrate_min)*.5;
  155397. }
  155398. if(hi->bitrate_reservoir<128.)
  155399. hi->bitrate_reservoir=128.;
  155400. }
  155401. return(0);
  155402. /* replacement ratemanage interface */
  155403. case OV_ECTL_RATEMANAGE2_GET:
  155404. {
  155405. struct ovectl_ratemanage2_arg *ai=
  155406. (struct ovectl_ratemanage2_arg *)arg;
  155407. if(ai==NULL)return OV_EINVAL;
  155408. ai->management_active=hi->managed;
  155409. ai->bitrate_limit_min_kbps=hi->bitrate_min/1000;
  155410. ai->bitrate_limit_max_kbps=hi->bitrate_max/1000;
  155411. ai->bitrate_average_kbps=hi->bitrate_av/1000;
  155412. ai->bitrate_average_damping=hi->bitrate_av_damp;
  155413. ai->bitrate_limit_reservoir_bits=hi->bitrate_reservoir;
  155414. ai->bitrate_limit_reservoir_bias=hi->bitrate_reservoir_bias;
  155415. }
  155416. return (0);
  155417. case OV_ECTL_RATEMANAGE2_SET:
  155418. {
  155419. struct ovectl_ratemanage2_arg *ai=
  155420. (struct ovectl_ratemanage2_arg *)arg;
  155421. if(ai==NULL){
  155422. hi->managed=0;
  155423. }else{
  155424. /* sanity check; only catch invariant violations */
  155425. if(ai->bitrate_limit_min_kbps>0 &&
  155426. ai->bitrate_average_kbps>0 &&
  155427. ai->bitrate_limit_min_kbps>ai->bitrate_average_kbps)
  155428. return OV_EINVAL;
  155429. if(ai->bitrate_limit_max_kbps>0 &&
  155430. ai->bitrate_average_kbps>0 &&
  155431. ai->bitrate_limit_max_kbps<ai->bitrate_average_kbps)
  155432. return OV_EINVAL;
  155433. if(ai->bitrate_limit_min_kbps>0 &&
  155434. ai->bitrate_limit_max_kbps>0 &&
  155435. ai->bitrate_limit_min_kbps>ai->bitrate_limit_max_kbps)
  155436. return OV_EINVAL;
  155437. if(ai->bitrate_average_damping <= 0.)
  155438. return OV_EINVAL;
  155439. if(ai->bitrate_limit_reservoir_bits < 0)
  155440. return OV_EINVAL;
  155441. if(ai->bitrate_limit_reservoir_bias < 0.)
  155442. return OV_EINVAL;
  155443. if(ai->bitrate_limit_reservoir_bias > 1.)
  155444. return OV_EINVAL;
  155445. hi->managed=ai->management_active;
  155446. hi->bitrate_min=ai->bitrate_limit_min_kbps * 1000;
  155447. hi->bitrate_max=ai->bitrate_limit_max_kbps * 1000;
  155448. hi->bitrate_av=ai->bitrate_average_kbps * 1000;
  155449. hi->bitrate_av_damp=ai->bitrate_average_damping;
  155450. hi->bitrate_reservoir=ai->bitrate_limit_reservoir_bits;
  155451. hi->bitrate_reservoir_bias=ai->bitrate_limit_reservoir_bias;
  155452. }
  155453. }
  155454. return 0;
  155455. case OV_ECTL_LOWPASS_GET:
  155456. {
  155457. double *farg=(double *)arg;
  155458. *farg=hi->lowpass_kHz;
  155459. }
  155460. return(0);
  155461. case OV_ECTL_LOWPASS_SET:
  155462. {
  155463. double *farg=(double *)arg;
  155464. hi->lowpass_kHz=*farg;
  155465. if(hi->lowpass_kHz<2.)hi->lowpass_kHz=2.;
  155466. if(hi->lowpass_kHz>99.)hi->lowpass_kHz=99.;
  155467. }
  155468. return(0);
  155469. case OV_ECTL_IBLOCK_GET:
  155470. {
  155471. double *farg=(double *)arg;
  155472. *farg=hi->impulse_noisetune;
  155473. }
  155474. return(0);
  155475. case OV_ECTL_IBLOCK_SET:
  155476. {
  155477. double *farg=(double *)arg;
  155478. hi->impulse_noisetune=*farg;
  155479. if(hi->impulse_noisetune>0.)hi->impulse_noisetune=0.;
  155480. if(hi->impulse_noisetune<-15.)hi->impulse_noisetune=-15.;
  155481. }
  155482. return(0);
  155483. }
  155484. return(OV_EIMPL);
  155485. }
  155486. return(OV_EINVAL);
  155487. }
  155488. #endif
  155489. /*** End of inlined file: vorbisenc.c ***/
  155490. /*** Start of inlined file: vorbisfile.c ***/
  155491. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  155492. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  155493. // tasks..
  155494. #if JUCE_MSVC
  155495. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  155496. #endif
  155497. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  155498. #if JUCE_USE_OGGVORBIS
  155499. #include <stdlib.h>
  155500. #include <stdio.h>
  155501. #include <errno.h>
  155502. #include <string.h>
  155503. #include <math.h>
  155504. /* A 'chained bitstream' is a Vorbis bitstream that contains more than
  155505. one logical bitstream arranged end to end (the only form of Ogg
  155506. multiplexing allowed in a Vorbis bitstream; grouping [parallel
  155507. multiplexing] is not allowed in Vorbis) */
  155508. /* A Vorbis file can be played beginning to end (streamed) without
  155509. worrying ahead of time about chaining (see decoder_example.c). If
  155510. we have the whole file, however, and want random access
  155511. (seeking/scrubbing) or desire to know the total length/time of a
  155512. file, we need to account for the possibility of chaining. */
  155513. /* We can handle things a number of ways; we can determine the entire
  155514. bitstream structure right off the bat, or find pieces on demand.
  155515. This example determines and caches structure for the entire
  155516. bitstream, but builds a virtual decoder on the fly when moving
  155517. between links in the chain. */
  155518. /* There are also different ways to implement seeking. Enough
  155519. information exists in an Ogg bitstream to seek to
  155520. sample-granularity positions in the output. Or, one can seek by
  155521. picking some portion of the stream roughly in the desired area if
  155522. we only want coarse navigation through the stream. */
  155523. /*************************************************************************
  155524. * Many, many internal helpers. The intention is not to be confusing;
  155525. * rampant duplication and monolithic function implementation would be
  155526. * harder to understand anyway. The high level functions are last. Begin
  155527. * grokking near the end of the file */
  155528. /* read a little more data from the file/pipe into the ogg_sync framer
  155529. */
  155530. #define CHUNKSIZE 8500 /* a shade over 8k; anyone using pages well
  155531. over 8k gets what they deserve */
  155532. static long _get_data(OggVorbis_File *vf){
  155533. errno=0;
  155534. if(vf->datasource){
  155535. char *buffer=ogg_sync_buffer(&vf->oy,CHUNKSIZE);
  155536. long bytes=(vf->callbacks.read_func)(buffer,1,CHUNKSIZE,vf->datasource);
  155537. if(bytes>0)ogg_sync_wrote(&vf->oy,bytes);
  155538. if(bytes==0 && errno)return(-1);
  155539. return(bytes);
  155540. }else
  155541. return(0);
  155542. }
  155543. /* save a tiny smidge of verbosity to make the code more readable */
  155544. static void _seek_helper(OggVorbis_File *vf,ogg_int64_t offset){
  155545. if(vf->datasource){
  155546. (vf->callbacks.seek_func)(vf->datasource, offset, SEEK_SET);
  155547. vf->offset=offset;
  155548. ogg_sync_reset(&vf->oy);
  155549. }else{
  155550. /* shouldn't happen unless someone writes a broken callback */
  155551. return;
  155552. }
  155553. }
  155554. /* The read/seek functions track absolute position within the stream */
  155555. /* from the head of the stream, get the next page. boundary specifies
  155556. if the function is allowed to fetch more data from the stream (and
  155557. how much) or only use internally buffered data.
  155558. boundary: -1) unbounded search
  155559. 0) read no additional data; use cached only
  155560. n) search for a new page beginning for n bytes
  155561. return: <0) did not find a page (OV_FALSE, OV_EOF, OV_EREAD)
  155562. n) found a page at absolute offset n */
  155563. static ogg_int64_t _get_next_page(OggVorbis_File *vf,ogg_page *og,
  155564. ogg_int64_t boundary){
  155565. if(boundary>0)boundary+=vf->offset;
  155566. while(1){
  155567. long more;
  155568. if(boundary>0 && vf->offset>=boundary)return(OV_FALSE);
  155569. more=ogg_sync_pageseek(&vf->oy,og);
  155570. if(more<0){
  155571. /* skipped n bytes */
  155572. vf->offset-=more;
  155573. }else{
  155574. if(more==0){
  155575. /* send more paramedics */
  155576. if(!boundary)return(OV_FALSE);
  155577. {
  155578. long ret=_get_data(vf);
  155579. if(ret==0)return(OV_EOF);
  155580. if(ret<0)return(OV_EREAD);
  155581. }
  155582. }else{
  155583. /* got a page. Return the offset at the page beginning,
  155584. advance the internal offset past the page end */
  155585. ogg_int64_t ret=vf->offset;
  155586. vf->offset+=more;
  155587. return(ret);
  155588. }
  155589. }
  155590. }
  155591. }
  155592. /* find the latest page beginning before the current stream cursor
  155593. position. Much dirtier than the above as Ogg doesn't have any
  155594. backward search linkage. no 'readp' as it will certainly have to
  155595. read. */
  155596. /* returns offset or OV_EREAD, OV_FAULT */
  155597. static ogg_int64_t _get_prev_page(OggVorbis_File *vf,ogg_page *og){
  155598. ogg_int64_t begin=vf->offset;
  155599. ogg_int64_t end=begin;
  155600. ogg_int64_t ret;
  155601. ogg_int64_t offset=-1;
  155602. while(offset==-1){
  155603. begin-=CHUNKSIZE;
  155604. if(begin<0)
  155605. begin=0;
  155606. _seek_helper(vf,begin);
  155607. while(vf->offset<end){
  155608. ret=_get_next_page(vf,og,end-vf->offset);
  155609. if(ret==OV_EREAD)return(OV_EREAD);
  155610. if(ret<0){
  155611. break;
  155612. }else{
  155613. offset=ret;
  155614. }
  155615. }
  155616. }
  155617. /* we have the offset. Actually snork and hold the page now */
  155618. _seek_helper(vf,offset);
  155619. ret=_get_next_page(vf,og,CHUNKSIZE);
  155620. if(ret<0)
  155621. /* this shouldn't be possible */
  155622. return(OV_EFAULT);
  155623. return(offset);
  155624. }
  155625. /* finds each bitstream link one at a time using a bisection search
  155626. (has to begin by knowing the offset of the lb's initial page).
  155627. Recurses for each link so it can alloc the link storage after
  155628. finding them all, then unroll and fill the cache at the same time */
  155629. static int _bisect_forward_serialno(OggVorbis_File *vf,
  155630. ogg_int64_t begin,
  155631. ogg_int64_t searched,
  155632. ogg_int64_t end,
  155633. long currentno,
  155634. long m){
  155635. ogg_int64_t endsearched=end;
  155636. ogg_int64_t next=end;
  155637. ogg_page og;
  155638. ogg_int64_t ret;
  155639. /* the below guards against garbage seperating the last and
  155640. first pages of two links. */
  155641. while(searched<endsearched){
  155642. ogg_int64_t bisect;
  155643. if(endsearched-searched<CHUNKSIZE){
  155644. bisect=searched;
  155645. }else{
  155646. bisect=(searched+endsearched)/2;
  155647. }
  155648. _seek_helper(vf,bisect);
  155649. ret=_get_next_page(vf,&og,-1);
  155650. if(ret==OV_EREAD)return(OV_EREAD);
  155651. if(ret<0 || ogg_page_serialno(&og)!=currentno){
  155652. endsearched=bisect;
  155653. if(ret>=0)next=ret;
  155654. }else{
  155655. searched=ret+og.header_len+og.body_len;
  155656. }
  155657. }
  155658. _seek_helper(vf,next);
  155659. ret=_get_next_page(vf,&og,-1);
  155660. if(ret==OV_EREAD)return(OV_EREAD);
  155661. if(searched>=end || ret<0){
  155662. vf->links=m+1;
  155663. vf->offsets=(ogg_int64_t*)_ogg_malloc((vf->links+1)*sizeof(*vf->offsets));
  155664. vf->serialnos=(long*)_ogg_malloc(vf->links*sizeof(*vf->serialnos));
  155665. vf->offsets[m+1]=searched;
  155666. }else{
  155667. ret=_bisect_forward_serialno(vf,next,vf->offset,
  155668. end,ogg_page_serialno(&og),m+1);
  155669. if(ret==OV_EREAD)return(OV_EREAD);
  155670. }
  155671. vf->offsets[m]=begin;
  155672. vf->serialnos[m]=currentno;
  155673. return(0);
  155674. }
  155675. /* uses the local ogg_stream storage in vf; this is important for
  155676. non-streaming input sources */
  155677. static int _fetch_headers(OggVorbis_File *vf,vorbis_info *vi,vorbis_comment *vc,
  155678. long *serialno,ogg_page *og_ptr){
  155679. ogg_page og;
  155680. ogg_packet op;
  155681. int i,ret;
  155682. if(!og_ptr){
  155683. ogg_int64_t llret=_get_next_page(vf,&og,CHUNKSIZE);
  155684. if(llret==OV_EREAD)return(OV_EREAD);
  155685. if(llret<0)return OV_ENOTVORBIS;
  155686. og_ptr=&og;
  155687. }
  155688. ogg_stream_reset_serialno(&vf->os,ogg_page_serialno(og_ptr));
  155689. if(serialno)*serialno=vf->os.serialno;
  155690. vf->ready_state=STREAMSET;
  155691. /* extract the initial header from the first page and verify that the
  155692. Ogg bitstream is in fact Vorbis data */
  155693. vorbis_info_init(vi);
  155694. vorbis_comment_init(vc);
  155695. i=0;
  155696. while(i<3){
  155697. ogg_stream_pagein(&vf->os,og_ptr);
  155698. while(i<3){
  155699. int result=ogg_stream_packetout(&vf->os,&op);
  155700. if(result==0)break;
  155701. if(result==-1){
  155702. ret=OV_EBADHEADER;
  155703. goto bail_header;
  155704. }
  155705. if((ret=vorbis_synthesis_headerin(vi,vc,&op))){
  155706. goto bail_header;
  155707. }
  155708. i++;
  155709. }
  155710. if(i<3)
  155711. if(_get_next_page(vf,og_ptr,CHUNKSIZE)<0){
  155712. ret=OV_EBADHEADER;
  155713. goto bail_header;
  155714. }
  155715. }
  155716. return 0;
  155717. bail_header:
  155718. vorbis_info_clear(vi);
  155719. vorbis_comment_clear(vc);
  155720. vf->ready_state=OPENED;
  155721. return ret;
  155722. }
  155723. /* last step of the OggVorbis_File initialization; get all the
  155724. vorbis_info structs and PCM positions. Only called by the seekable
  155725. initialization (local stream storage is hacked slightly; pay
  155726. attention to how that's done) */
  155727. /* this is void and does not propogate errors up because we want to be
  155728. able to open and use damaged bitstreams as well as we can. Just
  155729. watch out for missing information for links in the OggVorbis_File
  155730. struct */
  155731. static void _prefetch_all_headers(OggVorbis_File *vf, ogg_int64_t dataoffset){
  155732. ogg_page og;
  155733. int i;
  155734. ogg_int64_t ret;
  155735. vf->vi=(vorbis_info*) _ogg_realloc(vf->vi,vf->links*sizeof(*vf->vi));
  155736. vf->vc=(vorbis_comment*) _ogg_realloc(vf->vc,vf->links*sizeof(*vf->vc));
  155737. vf->dataoffsets=(ogg_int64_t*) _ogg_malloc(vf->links*sizeof(*vf->dataoffsets));
  155738. vf->pcmlengths=(ogg_int64_t*) _ogg_malloc(vf->links*2*sizeof(*vf->pcmlengths));
  155739. for(i=0;i<vf->links;i++){
  155740. if(i==0){
  155741. /* we already grabbed the initial header earlier. Just set the offset */
  155742. vf->dataoffsets[i]=dataoffset;
  155743. _seek_helper(vf,dataoffset);
  155744. }else{
  155745. /* seek to the location of the initial header */
  155746. _seek_helper(vf,vf->offsets[i]);
  155747. if(_fetch_headers(vf,vf->vi+i,vf->vc+i,NULL,NULL)<0){
  155748. vf->dataoffsets[i]=-1;
  155749. }else{
  155750. vf->dataoffsets[i]=vf->offset;
  155751. }
  155752. }
  155753. /* fetch beginning PCM offset */
  155754. if(vf->dataoffsets[i]!=-1){
  155755. ogg_int64_t accumulated=0;
  155756. long lastblock=-1;
  155757. int result;
  155758. ogg_stream_reset_serialno(&vf->os,vf->serialnos[i]);
  155759. while(1){
  155760. ogg_packet op;
  155761. ret=_get_next_page(vf,&og,-1);
  155762. if(ret<0)
  155763. /* this should not be possible unless the file is
  155764. truncated/mangled */
  155765. break;
  155766. if(ogg_page_serialno(&og)!=vf->serialnos[i])
  155767. break;
  155768. /* count blocksizes of all frames in the page */
  155769. ogg_stream_pagein(&vf->os,&og);
  155770. while((result=ogg_stream_packetout(&vf->os,&op))){
  155771. if(result>0){ /* ignore holes */
  155772. long thisblock=vorbis_packet_blocksize(vf->vi+i,&op);
  155773. if(lastblock!=-1)
  155774. accumulated+=(lastblock+thisblock)>>2;
  155775. lastblock=thisblock;
  155776. }
  155777. }
  155778. if(ogg_page_granulepos(&og)!=-1){
  155779. /* pcm offset of last packet on the first audio page */
  155780. accumulated= ogg_page_granulepos(&og)-accumulated;
  155781. break;
  155782. }
  155783. }
  155784. /* less than zero? This is a stream with samples trimmed off
  155785. the beginning, a normal occurrence; set the offset to zero */
  155786. if(accumulated<0)accumulated=0;
  155787. vf->pcmlengths[i*2]=accumulated;
  155788. }
  155789. /* get the PCM length of this link. To do this,
  155790. get the last page of the stream */
  155791. {
  155792. ogg_int64_t end=vf->offsets[i+1];
  155793. _seek_helper(vf,end);
  155794. while(1){
  155795. ret=_get_prev_page(vf,&og);
  155796. if(ret<0){
  155797. /* this should not be possible */
  155798. vorbis_info_clear(vf->vi+i);
  155799. vorbis_comment_clear(vf->vc+i);
  155800. break;
  155801. }
  155802. if(ogg_page_granulepos(&og)!=-1){
  155803. vf->pcmlengths[i*2+1]=ogg_page_granulepos(&og)-vf->pcmlengths[i*2];
  155804. break;
  155805. }
  155806. vf->offset=ret;
  155807. }
  155808. }
  155809. }
  155810. }
  155811. static int _make_decode_ready(OggVorbis_File *vf){
  155812. if(vf->ready_state>STREAMSET)return 0;
  155813. if(vf->ready_state<STREAMSET)return OV_EFAULT;
  155814. if(vf->seekable){
  155815. if(vorbis_synthesis_init(&vf->vd,vf->vi+vf->current_link))
  155816. return OV_EBADLINK;
  155817. }else{
  155818. if(vorbis_synthesis_init(&vf->vd,vf->vi))
  155819. return OV_EBADLINK;
  155820. }
  155821. vorbis_block_init(&vf->vd,&vf->vb);
  155822. vf->ready_state=INITSET;
  155823. vf->bittrack=0.f;
  155824. vf->samptrack=0.f;
  155825. return 0;
  155826. }
  155827. static int _open_seekable2(OggVorbis_File *vf){
  155828. long serialno=vf->current_serialno;
  155829. ogg_int64_t dataoffset=vf->offset, end;
  155830. ogg_page og;
  155831. /* we're partially open and have a first link header state in
  155832. storage in vf */
  155833. /* we can seek, so set out learning all about this file */
  155834. (vf->callbacks.seek_func)(vf->datasource,0,SEEK_END);
  155835. vf->offset=vf->end=(vf->callbacks.tell_func)(vf->datasource);
  155836. /* We get the offset for the last page of the physical bitstream.
  155837. Most OggVorbis files will contain a single logical bitstream */
  155838. end=_get_prev_page(vf,&og);
  155839. if(end<0)return(end);
  155840. /* more than one logical bitstream? */
  155841. if(ogg_page_serialno(&og)!=serialno){
  155842. /* Chained bitstream. Bisect-search each logical bitstream
  155843. section. Do so based on serial number only */
  155844. if(_bisect_forward_serialno(vf,0,0,end+1,serialno,0)<0)return(OV_EREAD);
  155845. }else{
  155846. /* Only one logical bitstream */
  155847. if(_bisect_forward_serialno(vf,0,end,end+1,serialno,0))return(OV_EREAD);
  155848. }
  155849. /* the initial header memory is referenced by vf after; don't free it */
  155850. _prefetch_all_headers(vf,dataoffset);
  155851. return(ov_raw_seek(vf,0));
  155852. }
  155853. /* clear out the current logical bitstream decoder */
  155854. static void _decode_clear(OggVorbis_File *vf){
  155855. vorbis_dsp_clear(&vf->vd);
  155856. vorbis_block_clear(&vf->vb);
  155857. vf->ready_state=OPENED;
  155858. }
  155859. /* fetch and process a packet. Handles the case where we're at a
  155860. bitstream boundary and dumps the decoding machine. If the decoding
  155861. machine is unloaded, it loads it. It also keeps pcm_offset up to
  155862. date (seek and read both use this. seek uses a special hack with
  155863. readp).
  155864. return: <0) error, OV_HOLE (lost packet) or OV_EOF
  155865. 0) need more data (only if readp==0)
  155866. 1) got a packet
  155867. */
  155868. static int _fetch_and_process_packet(OggVorbis_File *vf,
  155869. ogg_packet *op_in,
  155870. int readp,
  155871. int spanp){
  155872. ogg_page og;
  155873. /* handle one packet. Try to fetch it from current stream state */
  155874. /* extract packets from page */
  155875. while(1){
  155876. /* process a packet if we can. If the machine isn't loaded,
  155877. neither is a page */
  155878. if(vf->ready_state==INITSET){
  155879. while(1) {
  155880. ogg_packet op;
  155881. ogg_packet *op_ptr=(op_in?op_in:&op);
  155882. int result=ogg_stream_packetout(&vf->os,op_ptr);
  155883. ogg_int64_t granulepos;
  155884. op_in=NULL;
  155885. if(result==-1)return(OV_HOLE); /* hole in the data. */
  155886. if(result>0){
  155887. /* got a packet. process it */
  155888. granulepos=op_ptr->granulepos;
  155889. if(!vorbis_synthesis(&vf->vb,op_ptr)){ /* lazy check for lazy
  155890. header handling. The
  155891. header packets aren't
  155892. audio, so if/when we
  155893. submit them,
  155894. vorbis_synthesis will
  155895. reject them */
  155896. /* suck in the synthesis data and track bitrate */
  155897. {
  155898. int oldsamples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  155899. /* for proper use of libvorbis within libvorbisfile,
  155900. oldsamples will always be zero. */
  155901. if(oldsamples)return(OV_EFAULT);
  155902. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  155903. vf->samptrack+=vorbis_synthesis_pcmout(&vf->vd,NULL)-oldsamples;
  155904. vf->bittrack+=op_ptr->bytes*8;
  155905. }
  155906. /* update the pcm offset. */
  155907. if(granulepos!=-1 && !op_ptr->e_o_s){
  155908. int link=(vf->seekable?vf->current_link:0);
  155909. int i,samples;
  155910. /* this packet has a pcm_offset on it (the last packet
  155911. completed on a page carries the offset) After processing
  155912. (above), we know the pcm position of the *last* sample
  155913. ready to be returned. Find the offset of the *first*
  155914. As an aside, this trick is inaccurate if we begin
  155915. reading anew right at the last page; the end-of-stream
  155916. granulepos declares the last frame in the stream, and the
  155917. last packet of the last page may be a partial frame.
  155918. So, we need a previous granulepos from an in-sequence page
  155919. to have a reference point. Thus the !op_ptr->e_o_s clause
  155920. above */
  155921. if(vf->seekable && link>0)
  155922. granulepos-=vf->pcmlengths[link*2];
  155923. if(granulepos<0)granulepos=0; /* actually, this
  155924. shouldn't be possible
  155925. here unless the stream
  155926. is very broken */
  155927. samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  155928. granulepos-=samples;
  155929. for(i=0;i<link;i++)
  155930. granulepos+=vf->pcmlengths[i*2+1];
  155931. vf->pcm_offset=granulepos;
  155932. }
  155933. return(1);
  155934. }
  155935. }
  155936. else
  155937. break;
  155938. }
  155939. }
  155940. if(vf->ready_state>=OPENED){
  155941. ogg_int64_t ret;
  155942. if(!readp)return(0);
  155943. if((ret=_get_next_page(vf,&og,-1))<0){
  155944. return(OV_EOF); /* eof.
  155945. leave unitialized */
  155946. }
  155947. /* bitrate tracking; add the header's bytes here, the body bytes
  155948. are done by packet above */
  155949. vf->bittrack+=og.header_len*8;
  155950. /* has our decoding just traversed a bitstream boundary? */
  155951. if(vf->ready_state==INITSET){
  155952. if(vf->current_serialno!=ogg_page_serialno(&og)){
  155953. if(!spanp)
  155954. return(OV_EOF);
  155955. _decode_clear(vf);
  155956. if(!vf->seekable){
  155957. vorbis_info_clear(vf->vi);
  155958. vorbis_comment_clear(vf->vc);
  155959. }
  155960. }
  155961. }
  155962. }
  155963. /* Do we need to load a new machine before submitting the page? */
  155964. /* This is different in the seekable and non-seekable cases.
  155965. In the seekable case, we already have all the header
  155966. information loaded and cached; we just initialize the machine
  155967. with it and continue on our merry way.
  155968. In the non-seekable (streaming) case, we'll only be at a
  155969. boundary if we just left the previous logical bitstream and
  155970. we're now nominally at the header of the next bitstream
  155971. */
  155972. if(vf->ready_state!=INITSET){
  155973. int link;
  155974. if(vf->ready_state<STREAMSET){
  155975. if(vf->seekable){
  155976. vf->current_serialno=ogg_page_serialno(&og);
  155977. /* match the serialno to bitstream section. We use this rather than
  155978. offset positions to avoid problems near logical bitstream
  155979. boundaries */
  155980. for(link=0;link<vf->links;link++)
  155981. if(vf->serialnos[link]==vf->current_serialno)break;
  155982. if(link==vf->links)return(OV_EBADLINK); /* sign of a bogus
  155983. stream. error out,
  155984. leave machine
  155985. uninitialized */
  155986. vf->current_link=link;
  155987. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  155988. vf->ready_state=STREAMSET;
  155989. }else{
  155990. /* we're streaming */
  155991. /* fetch the three header packets, build the info struct */
  155992. int ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,&og);
  155993. if(ret)return(ret);
  155994. vf->current_link++;
  155995. link=0;
  155996. }
  155997. }
  155998. {
  155999. int ret=_make_decode_ready(vf);
  156000. if(ret<0)return ret;
  156001. }
  156002. }
  156003. ogg_stream_pagein(&vf->os,&og);
  156004. }
  156005. }
  156006. /* if, eg, 64 bit stdio is configured by default, this will build with
  156007. fseek64 */
  156008. static int _fseek64_wrap(FILE *f,ogg_int64_t off,int whence){
  156009. if(f==NULL)return(-1);
  156010. return fseek(f,off,whence);
  156011. }
  156012. static int _ov_open1(void *f,OggVorbis_File *vf,char *initial,
  156013. long ibytes, ov_callbacks callbacks){
  156014. int offsettest=(f?callbacks.seek_func(f,0,SEEK_CUR):-1);
  156015. int ret;
  156016. memset(vf,0,sizeof(*vf));
  156017. vf->datasource=f;
  156018. vf->callbacks = callbacks;
  156019. /* init the framing state */
  156020. ogg_sync_init(&vf->oy);
  156021. /* perhaps some data was previously read into a buffer for testing
  156022. against other stream types. Allow initialization from this
  156023. previously read data (as we may be reading from a non-seekable
  156024. stream) */
  156025. if(initial){
  156026. char *buffer=ogg_sync_buffer(&vf->oy,ibytes);
  156027. memcpy(buffer,initial,ibytes);
  156028. ogg_sync_wrote(&vf->oy,ibytes);
  156029. }
  156030. /* can we seek? Stevens suggests the seek test was portable */
  156031. if(offsettest!=-1)vf->seekable=1;
  156032. /* No seeking yet; Set up a 'single' (current) logical bitstream
  156033. entry for partial open */
  156034. vf->links=1;
  156035. vf->vi=(vorbis_info*) _ogg_calloc(vf->links,sizeof(*vf->vi));
  156036. vf->vc=(vorbis_comment*) _ogg_calloc(vf->links,sizeof(*vf->vc));
  156037. ogg_stream_init(&vf->os,-1); /* fill in the serialno later */
  156038. /* Try to fetch the headers, maintaining all the storage */
  156039. if((ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,NULL))<0){
  156040. vf->datasource=NULL;
  156041. ov_clear(vf);
  156042. }else
  156043. vf->ready_state=PARTOPEN;
  156044. return(ret);
  156045. }
  156046. static int _ov_open2(OggVorbis_File *vf){
  156047. if(vf->ready_state != PARTOPEN) return OV_EINVAL;
  156048. vf->ready_state=OPENED;
  156049. if(vf->seekable){
  156050. int ret=_open_seekable2(vf);
  156051. if(ret){
  156052. vf->datasource=NULL;
  156053. ov_clear(vf);
  156054. }
  156055. return(ret);
  156056. }else
  156057. vf->ready_state=STREAMSET;
  156058. return 0;
  156059. }
  156060. /* clear out the OggVorbis_File struct */
  156061. int ov_clear(OggVorbis_File *vf){
  156062. if(vf){
  156063. vorbis_block_clear(&vf->vb);
  156064. vorbis_dsp_clear(&vf->vd);
  156065. ogg_stream_clear(&vf->os);
  156066. if(vf->vi && vf->links){
  156067. int i;
  156068. for(i=0;i<vf->links;i++){
  156069. vorbis_info_clear(vf->vi+i);
  156070. vorbis_comment_clear(vf->vc+i);
  156071. }
  156072. _ogg_free(vf->vi);
  156073. _ogg_free(vf->vc);
  156074. }
  156075. if(vf->dataoffsets)_ogg_free(vf->dataoffsets);
  156076. if(vf->pcmlengths)_ogg_free(vf->pcmlengths);
  156077. if(vf->serialnos)_ogg_free(vf->serialnos);
  156078. if(vf->offsets)_ogg_free(vf->offsets);
  156079. ogg_sync_clear(&vf->oy);
  156080. if(vf->datasource)(vf->callbacks.close_func)(vf->datasource);
  156081. memset(vf,0,sizeof(*vf));
  156082. }
  156083. #ifdef DEBUG_LEAKS
  156084. _VDBG_dump();
  156085. #endif
  156086. return(0);
  156087. }
  156088. /* inspects the OggVorbis file and finds/documents all the logical
  156089. bitstreams contained in it. Tries to be tolerant of logical
  156090. bitstream sections that are truncated/woogie.
  156091. return: -1) error
  156092. 0) OK
  156093. */
  156094. int ov_open_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  156095. ov_callbacks callbacks){
  156096. int ret=_ov_open1(f,vf,initial,ibytes,callbacks);
  156097. if(ret)return ret;
  156098. return _ov_open2(vf);
  156099. }
  156100. int ov_open(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_open_callbacks((void *)f, vf, initial, ibytes, callbacks);
  156108. }
  156109. /* cheap hack for game usage where downsampling is desirable; there's
  156110. no need for SRC as we can just do it cheaply in libvorbis. */
  156111. int ov_halfrate(OggVorbis_File *vf,int flag){
  156112. int i;
  156113. if(vf->vi==NULL)return OV_EINVAL;
  156114. if(!vf->seekable)return OV_EINVAL;
  156115. if(vf->ready_state>=STREAMSET)
  156116. _decode_clear(vf); /* clear out stream state; later on libvorbis
  156117. will be able to swap this on the fly, but
  156118. for now dumping the decode machine is needed
  156119. to reinit the MDCT lookups. 1.1 libvorbis
  156120. is planned to be able to switch on the fly */
  156121. for(i=0;i<vf->links;i++){
  156122. if(vorbis_synthesis_halfrate(vf->vi+i,flag)){
  156123. ov_halfrate(vf,0);
  156124. return OV_EINVAL;
  156125. }
  156126. }
  156127. return 0;
  156128. }
  156129. int ov_halfrate_p(OggVorbis_File *vf){
  156130. if(vf->vi==NULL)return OV_EINVAL;
  156131. return vorbis_synthesis_halfrate_p(vf->vi);
  156132. }
  156133. /* Only partially open the vorbis file; test for Vorbisness, and load
  156134. the headers for the first chain. Do not seek (although test for
  156135. seekability). Use ov_test_open to finish opening the file, else
  156136. ov_clear to close/free it. Same return codes as open. */
  156137. int ov_test_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  156138. ov_callbacks callbacks)
  156139. {
  156140. return _ov_open1(f,vf,initial,ibytes,callbacks);
  156141. }
  156142. int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  156143. ov_callbacks callbacks = {
  156144. (size_t (*)(void *, size_t, size_t, void *)) fread,
  156145. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  156146. (int (*)(void *)) fclose,
  156147. (long (*)(void *)) ftell
  156148. };
  156149. return ov_test_callbacks((void *)f, vf, initial, ibytes, callbacks);
  156150. }
  156151. int ov_test_open(OggVorbis_File *vf){
  156152. if(vf->ready_state!=PARTOPEN)return(OV_EINVAL);
  156153. return _ov_open2(vf);
  156154. }
  156155. /* How many logical bitstreams in this physical bitstream? */
  156156. long ov_streams(OggVorbis_File *vf){
  156157. return vf->links;
  156158. }
  156159. /* Is the FILE * associated with vf seekable? */
  156160. long ov_seekable(OggVorbis_File *vf){
  156161. return vf->seekable;
  156162. }
  156163. /* returns the bitrate for a given logical bitstream or the entire
  156164. physical bitstream. If the file is open for random access, it will
  156165. find the *actual* average bitrate. If the file is streaming, it
  156166. returns the nominal bitrate (if set) else the average of the
  156167. upper/lower bounds (if set) else -1 (unset).
  156168. If you want the actual bitrate field settings, get them from the
  156169. vorbis_info structs */
  156170. long ov_bitrate(OggVorbis_File *vf,int i){
  156171. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156172. if(i>=vf->links)return(OV_EINVAL);
  156173. if(!vf->seekable && i!=0)return(ov_bitrate(vf,0));
  156174. if(i<0){
  156175. ogg_int64_t bits=0;
  156176. int i;
  156177. float br;
  156178. for(i=0;i<vf->links;i++)
  156179. bits+=(vf->offsets[i+1]-vf->dataoffsets[i])*8;
  156180. /* This once read: return(rint(bits/ov_time_total(vf,-1)));
  156181. * gcc 3.x on x86 miscompiled this at optimisation level 2 and above,
  156182. * so this is slightly transformed to make it work.
  156183. */
  156184. br = bits/ov_time_total(vf,-1);
  156185. return(rint(br));
  156186. }else{
  156187. if(vf->seekable){
  156188. /* return the actual bitrate */
  156189. return(rint((vf->offsets[i+1]-vf->dataoffsets[i])*8/ov_time_total(vf,i)));
  156190. }else{
  156191. /* return nominal if set */
  156192. if(vf->vi[i].bitrate_nominal>0){
  156193. return vf->vi[i].bitrate_nominal;
  156194. }else{
  156195. if(vf->vi[i].bitrate_upper>0){
  156196. if(vf->vi[i].bitrate_lower>0){
  156197. return (vf->vi[i].bitrate_upper+vf->vi[i].bitrate_lower)/2;
  156198. }else{
  156199. return vf->vi[i].bitrate_upper;
  156200. }
  156201. }
  156202. return(OV_FALSE);
  156203. }
  156204. }
  156205. }
  156206. }
  156207. /* returns the actual bitrate since last call. returns -1 if no
  156208. additional data to offer since last call (or at beginning of stream),
  156209. EINVAL if stream is only partially open
  156210. */
  156211. long ov_bitrate_instant(OggVorbis_File *vf){
  156212. int link=(vf->seekable?vf->current_link:0);
  156213. long ret;
  156214. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156215. if(vf->samptrack==0)return(OV_FALSE);
  156216. ret=vf->bittrack/vf->samptrack*vf->vi[link].rate+.5;
  156217. vf->bittrack=0.f;
  156218. vf->samptrack=0.f;
  156219. return(ret);
  156220. }
  156221. /* Guess */
  156222. long ov_serialnumber(OggVorbis_File *vf,int i){
  156223. if(i>=vf->links)return(ov_serialnumber(vf,vf->links-1));
  156224. if(!vf->seekable && i>=0)return(ov_serialnumber(vf,-1));
  156225. if(i<0){
  156226. return(vf->current_serialno);
  156227. }else{
  156228. return(vf->serialnos[i]);
  156229. }
  156230. }
  156231. /* returns: total raw (compressed) length of content if i==-1
  156232. raw (compressed) length of that logical bitstream for i==0 to n
  156233. OV_EINVAL if the stream is not seekable (we can't know the length)
  156234. or if stream is only partially open
  156235. */
  156236. ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i){
  156237. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156238. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  156239. if(i<0){
  156240. ogg_int64_t acc=0;
  156241. int i;
  156242. for(i=0;i<vf->links;i++)
  156243. acc+=ov_raw_total(vf,i);
  156244. return(acc);
  156245. }else{
  156246. return(vf->offsets[i+1]-vf->offsets[i]);
  156247. }
  156248. }
  156249. /* returns: total PCM length (samples) of content if i==-1 PCM length
  156250. (samples) of that logical bitstream for i==0 to n
  156251. OV_EINVAL if the stream is not seekable (we can't know the
  156252. length) or only partially open
  156253. */
  156254. ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i){
  156255. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156256. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  156257. if(i<0){
  156258. ogg_int64_t acc=0;
  156259. int i;
  156260. for(i=0;i<vf->links;i++)
  156261. acc+=ov_pcm_total(vf,i);
  156262. return(acc);
  156263. }else{
  156264. return(vf->pcmlengths[i*2+1]);
  156265. }
  156266. }
  156267. /* returns: total seconds of content if i==-1
  156268. seconds in that logical bitstream for i==0 to n
  156269. OV_EINVAL if the stream is not seekable (we can't know the
  156270. length) or only partially open
  156271. */
  156272. double ov_time_total(OggVorbis_File *vf,int i){
  156273. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156274. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  156275. if(i<0){
  156276. double acc=0;
  156277. int i;
  156278. for(i=0;i<vf->links;i++)
  156279. acc+=ov_time_total(vf,i);
  156280. return(acc);
  156281. }else{
  156282. return((double)(vf->pcmlengths[i*2+1])/vf->vi[i].rate);
  156283. }
  156284. }
  156285. /* seek to an offset relative to the *compressed* data. This also
  156286. scans packets to update the PCM cursor. It will cross a logical
  156287. bitstream boundary, but only if it can't get any packets out of the
  156288. tail of the bitstream we seek to (so no surprises).
  156289. returns zero on success, nonzero on failure */
  156290. int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos){
  156291. ogg_stream_state work_os;
  156292. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156293. if(!vf->seekable)
  156294. return(OV_ENOSEEK); /* don't dump machine if we can't seek */
  156295. if(pos<0 || pos>vf->end)return(OV_EINVAL);
  156296. /* don't yet clear out decoding machine (if it's initialized), in
  156297. the case we're in the same link. Restart the decode lapping, and
  156298. let _fetch_and_process_packet deal with a potential bitstream
  156299. boundary */
  156300. vf->pcm_offset=-1;
  156301. ogg_stream_reset_serialno(&vf->os,
  156302. vf->current_serialno); /* must set serialno */
  156303. vorbis_synthesis_restart(&vf->vd);
  156304. _seek_helper(vf,pos);
  156305. /* we need to make sure the pcm_offset is set, but we don't want to
  156306. advance the raw cursor past good packets just to get to the first
  156307. with a granulepos. That's not equivalent behavior to beginning
  156308. decoding as immediately after the seek position as possible.
  156309. So, a hack. We use two stream states; a local scratch state and
  156310. the shared vf->os stream state. We use the local state to
  156311. scan, and the shared state as a buffer for later decode.
  156312. Unfortuantely, on the last page we still advance to last packet
  156313. because the granulepos on the last page is not necessarily on a
  156314. packet boundary, and we need to make sure the granpos is
  156315. correct.
  156316. */
  156317. {
  156318. ogg_page og;
  156319. ogg_packet op;
  156320. int lastblock=0;
  156321. int accblock=0;
  156322. int thisblock;
  156323. int eosflag;
  156324. ogg_stream_init(&work_os,vf->current_serialno); /* get the memory ready */
  156325. ogg_stream_reset(&work_os); /* eliminate the spurious OV_HOLE
  156326. return from not necessarily
  156327. starting from the beginning */
  156328. while(1){
  156329. if(vf->ready_state>=STREAMSET){
  156330. /* snarf/scan a packet if we can */
  156331. int result=ogg_stream_packetout(&work_os,&op);
  156332. if(result>0){
  156333. if(vf->vi[vf->current_link].codec_setup){
  156334. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  156335. if(thisblock<0){
  156336. ogg_stream_packetout(&vf->os,NULL);
  156337. thisblock=0;
  156338. }else{
  156339. if(eosflag)
  156340. ogg_stream_packetout(&vf->os,NULL);
  156341. else
  156342. if(lastblock)accblock+=(lastblock+thisblock)>>2;
  156343. }
  156344. if(op.granulepos!=-1){
  156345. int i,link=vf->current_link;
  156346. ogg_int64_t granulepos=op.granulepos-vf->pcmlengths[link*2];
  156347. if(granulepos<0)granulepos=0;
  156348. for(i=0;i<link;i++)
  156349. granulepos+=vf->pcmlengths[i*2+1];
  156350. vf->pcm_offset=granulepos-accblock;
  156351. break;
  156352. }
  156353. lastblock=thisblock;
  156354. continue;
  156355. }else
  156356. ogg_stream_packetout(&vf->os,NULL);
  156357. }
  156358. }
  156359. if(!lastblock){
  156360. if(_get_next_page(vf,&og,-1)<0){
  156361. vf->pcm_offset=ov_pcm_total(vf,-1);
  156362. break;
  156363. }
  156364. }else{
  156365. /* huh? Bogus stream with packets but no granulepos */
  156366. vf->pcm_offset=-1;
  156367. break;
  156368. }
  156369. /* has our decoding just traversed a bitstream boundary? */
  156370. if(vf->ready_state>=STREAMSET)
  156371. if(vf->current_serialno!=ogg_page_serialno(&og)){
  156372. _decode_clear(vf); /* clear out stream state */
  156373. ogg_stream_clear(&work_os);
  156374. }
  156375. if(vf->ready_state<STREAMSET){
  156376. int link;
  156377. vf->current_serialno=ogg_page_serialno(&og);
  156378. for(link=0;link<vf->links;link++)
  156379. if(vf->serialnos[link]==vf->current_serialno)break;
  156380. if(link==vf->links)goto seek_error; /* sign of a bogus stream.
  156381. error out, leave
  156382. machine uninitialized */
  156383. vf->current_link=link;
  156384. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156385. ogg_stream_reset_serialno(&work_os,vf->current_serialno);
  156386. vf->ready_state=STREAMSET;
  156387. }
  156388. ogg_stream_pagein(&vf->os,&og);
  156389. ogg_stream_pagein(&work_os,&og);
  156390. eosflag=ogg_page_eos(&og);
  156391. }
  156392. }
  156393. ogg_stream_clear(&work_os);
  156394. vf->bittrack=0.f;
  156395. vf->samptrack=0.f;
  156396. return(0);
  156397. seek_error:
  156398. /* dump the machine so we're in a known state */
  156399. vf->pcm_offset=-1;
  156400. ogg_stream_clear(&work_os);
  156401. _decode_clear(vf);
  156402. return OV_EBADLINK;
  156403. }
  156404. /* Page granularity seek (faster than sample granularity because we
  156405. don't do the last bit of decode to find a specific sample).
  156406. Seek to the last [granule marked] page preceeding the specified pos
  156407. location, such that decoding past the returned point will quickly
  156408. arrive at the requested position. */
  156409. int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos){
  156410. int link=-1;
  156411. ogg_int64_t result=0;
  156412. ogg_int64_t total=ov_pcm_total(vf,-1);
  156413. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156414. if(!vf->seekable)return(OV_ENOSEEK);
  156415. if(pos<0 || pos>total)return(OV_EINVAL);
  156416. /* which bitstream section does this pcm offset occur in? */
  156417. for(link=vf->links-1;link>=0;link--){
  156418. total-=vf->pcmlengths[link*2+1];
  156419. if(pos>=total)break;
  156420. }
  156421. /* search within the logical bitstream for the page with the highest
  156422. pcm_pos preceeding (or equal to) pos. There is a danger here;
  156423. missing pages or incorrect frame number information in the
  156424. bitstream could make our task impossible. Account for that (it
  156425. would be an error condition) */
  156426. /* new search algorithm by HB (Nicholas Vinen) */
  156427. {
  156428. ogg_int64_t end=vf->offsets[link+1];
  156429. ogg_int64_t begin=vf->offsets[link];
  156430. ogg_int64_t begintime = vf->pcmlengths[link*2];
  156431. ogg_int64_t endtime = vf->pcmlengths[link*2+1]+begintime;
  156432. ogg_int64_t target=pos-total+begintime;
  156433. ogg_int64_t best=begin;
  156434. ogg_page og;
  156435. while(begin<end){
  156436. ogg_int64_t bisect;
  156437. if(end-begin<CHUNKSIZE){
  156438. bisect=begin;
  156439. }else{
  156440. /* take a (pretty decent) guess. */
  156441. bisect=begin +
  156442. (target-begintime)*(end-begin)/(endtime-begintime) - CHUNKSIZE;
  156443. if(bisect<=begin)
  156444. bisect=begin+1;
  156445. }
  156446. _seek_helper(vf,bisect);
  156447. while(begin<end){
  156448. result=_get_next_page(vf,&og,end-vf->offset);
  156449. if(result==OV_EREAD) goto seek_error;
  156450. if(result<0){
  156451. if(bisect<=begin+1)
  156452. end=begin; /* found it */
  156453. else{
  156454. if(bisect==0) goto seek_error;
  156455. bisect-=CHUNKSIZE;
  156456. if(bisect<=begin)bisect=begin+1;
  156457. _seek_helper(vf,bisect);
  156458. }
  156459. }else{
  156460. ogg_int64_t granulepos=ogg_page_granulepos(&og);
  156461. if(granulepos==-1)continue;
  156462. if(granulepos<target){
  156463. best=result; /* raw offset of packet with granulepos */
  156464. begin=vf->offset; /* raw offset of next page */
  156465. begintime=granulepos;
  156466. if(target-begintime>44100)break;
  156467. bisect=begin; /* *not* begin + 1 */
  156468. }else{
  156469. if(bisect<=begin+1)
  156470. end=begin; /* found it */
  156471. else{
  156472. if(end==vf->offset){ /* we're pretty close - we'd be stuck in */
  156473. end=result;
  156474. bisect-=CHUNKSIZE; /* an endless loop otherwise. */
  156475. if(bisect<=begin)bisect=begin+1;
  156476. _seek_helper(vf,bisect);
  156477. }else{
  156478. end=result;
  156479. endtime=granulepos;
  156480. break;
  156481. }
  156482. }
  156483. }
  156484. }
  156485. }
  156486. }
  156487. /* found our page. seek to it, update pcm offset. Easier case than
  156488. raw_seek, don't keep packets preceeding granulepos. */
  156489. {
  156490. ogg_page og;
  156491. ogg_packet op;
  156492. /* seek */
  156493. _seek_helper(vf,best);
  156494. vf->pcm_offset=-1;
  156495. if(_get_next_page(vf,&og,-1)<0)return(OV_EOF); /* shouldn't happen */
  156496. if(link!=vf->current_link){
  156497. /* Different link; dump entire decode machine */
  156498. _decode_clear(vf);
  156499. vf->current_link=link;
  156500. vf->current_serialno=ogg_page_serialno(&og);
  156501. vf->ready_state=STREAMSET;
  156502. }else{
  156503. vorbis_synthesis_restart(&vf->vd);
  156504. }
  156505. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156506. ogg_stream_pagein(&vf->os,&og);
  156507. /* pull out all but last packet; the one with granulepos */
  156508. while(1){
  156509. result=ogg_stream_packetpeek(&vf->os,&op);
  156510. if(result==0){
  156511. /* !!! the packet finishing this page originated on a
  156512. preceeding page. Keep fetching previous pages until we
  156513. get one with a granulepos or without the 'continued' flag
  156514. set. Then just use raw_seek for simplicity. */
  156515. _seek_helper(vf,best);
  156516. while(1){
  156517. result=_get_prev_page(vf,&og);
  156518. if(result<0) goto seek_error;
  156519. if(ogg_page_granulepos(&og)>-1 ||
  156520. !ogg_page_continued(&og)){
  156521. return ov_raw_seek(vf,result);
  156522. }
  156523. vf->offset=result;
  156524. }
  156525. }
  156526. if(result<0){
  156527. result = OV_EBADPACKET;
  156528. goto seek_error;
  156529. }
  156530. if(op.granulepos!=-1){
  156531. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  156532. if(vf->pcm_offset<0)vf->pcm_offset=0;
  156533. vf->pcm_offset+=total;
  156534. break;
  156535. }else
  156536. result=ogg_stream_packetout(&vf->os,NULL);
  156537. }
  156538. }
  156539. }
  156540. /* verify result */
  156541. if(vf->pcm_offset>pos || pos>ov_pcm_total(vf,-1)){
  156542. result=OV_EFAULT;
  156543. goto seek_error;
  156544. }
  156545. vf->bittrack=0.f;
  156546. vf->samptrack=0.f;
  156547. return(0);
  156548. seek_error:
  156549. /* dump machine so we're in a known state */
  156550. vf->pcm_offset=-1;
  156551. _decode_clear(vf);
  156552. return (int)result;
  156553. }
  156554. /* seek to a sample offset relative to the decompressed pcm stream
  156555. returns zero on success, nonzero on failure */
  156556. int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos){
  156557. int thisblock,lastblock=0;
  156558. int ret=ov_pcm_seek_page(vf,pos);
  156559. if(ret<0)return(ret);
  156560. if((ret=_make_decode_ready(vf)))return ret;
  156561. /* discard leading packets we don't need for the lapping of the
  156562. position we want; don't decode them */
  156563. while(1){
  156564. ogg_packet op;
  156565. ogg_page og;
  156566. int ret=ogg_stream_packetpeek(&vf->os,&op);
  156567. if(ret>0){
  156568. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  156569. if(thisblock<0){
  156570. ogg_stream_packetout(&vf->os,NULL);
  156571. continue; /* non audio packet */
  156572. }
  156573. if(lastblock)vf->pcm_offset+=(lastblock+thisblock)>>2;
  156574. if(vf->pcm_offset+((thisblock+
  156575. vorbis_info_blocksize(vf->vi,1))>>2)>=pos)break;
  156576. /* remove the packet from packet queue and track its granulepos */
  156577. ogg_stream_packetout(&vf->os,NULL);
  156578. vorbis_synthesis_trackonly(&vf->vb,&op); /* set up a vb with
  156579. only tracking, no
  156580. pcm_decode */
  156581. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  156582. /* end of logical stream case is hard, especially with exact
  156583. length positioning. */
  156584. if(op.granulepos>-1){
  156585. int i;
  156586. /* always believe the stream markers */
  156587. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  156588. if(vf->pcm_offset<0)vf->pcm_offset=0;
  156589. for(i=0;i<vf->current_link;i++)
  156590. vf->pcm_offset+=vf->pcmlengths[i*2+1];
  156591. }
  156592. lastblock=thisblock;
  156593. }else{
  156594. if(ret<0 && ret!=OV_HOLE)break;
  156595. /* suck in a new page */
  156596. if(_get_next_page(vf,&og,-1)<0)break;
  156597. if(vf->current_serialno!=ogg_page_serialno(&og))_decode_clear(vf);
  156598. if(vf->ready_state<STREAMSET){
  156599. int link;
  156600. vf->current_serialno=ogg_page_serialno(&og);
  156601. for(link=0;link<vf->links;link++)
  156602. if(vf->serialnos[link]==vf->current_serialno)break;
  156603. if(link==vf->links)return(OV_EBADLINK);
  156604. vf->current_link=link;
  156605. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156606. vf->ready_state=STREAMSET;
  156607. ret=_make_decode_ready(vf);
  156608. if(ret)return ret;
  156609. lastblock=0;
  156610. }
  156611. ogg_stream_pagein(&vf->os,&og);
  156612. }
  156613. }
  156614. vf->bittrack=0.f;
  156615. vf->samptrack=0.f;
  156616. /* discard samples until we reach the desired position. Crossing a
  156617. logical bitstream boundary with abandon is OK. */
  156618. while(vf->pcm_offset<pos){
  156619. ogg_int64_t target=pos-vf->pcm_offset;
  156620. long samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  156621. if(samples>target)samples=target;
  156622. vorbis_synthesis_read(&vf->vd,samples);
  156623. vf->pcm_offset+=samples;
  156624. if(samples<target)
  156625. if(_fetch_and_process_packet(vf,NULL,1,1)<=0)
  156626. vf->pcm_offset=ov_pcm_total(vf,-1); /* eof */
  156627. }
  156628. return 0;
  156629. }
  156630. /* seek to a playback time relative to the decompressed pcm stream
  156631. returns zero on success, nonzero on failure */
  156632. int ov_time_seek(OggVorbis_File *vf,double seconds){
  156633. /* translate time to PCM position and call ov_pcm_seek */
  156634. int link=-1;
  156635. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  156636. double time_total=ov_time_total(vf,-1);
  156637. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156638. if(!vf->seekable)return(OV_ENOSEEK);
  156639. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  156640. /* which bitstream section does this time offset occur in? */
  156641. for(link=vf->links-1;link>=0;link--){
  156642. pcm_total-=vf->pcmlengths[link*2+1];
  156643. time_total-=ov_time_total(vf,link);
  156644. if(seconds>=time_total)break;
  156645. }
  156646. /* enough information to convert time offset to pcm offset */
  156647. {
  156648. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  156649. return(ov_pcm_seek(vf,target));
  156650. }
  156651. }
  156652. /* page-granularity version of ov_time_seek
  156653. returns zero on success, nonzero on failure */
  156654. int ov_time_seek_page(OggVorbis_File *vf,double seconds){
  156655. /* translate time to PCM position and call ov_pcm_seek */
  156656. int link=-1;
  156657. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  156658. double time_total=ov_time_total(vf,-1);
  156659. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156660. if(!vf->seekable)return(OV_ENOSEEK);
  156661. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  156662. /* which bitstream section does this time offset occur in? */
  156663. for(link=vf->links-1;link>=0;link--){
  156664. pcm_total-=vf->pcmlengths[link*2+1];
  156665. time_total-=ov_time_total(vf,link);
  156666. if(seconds>=time_total)break;
  156667. }
  156668. /* enough information to convert time offset to pcm offset */
  156669. {
  156670. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  156671. return(ov_pcm_seek_page(vf,target));
  156672. }
  156673. }
  156674. /* tell the current stream offset cursor. Note that seek followed by
  156675. tell will likely not give the set offset due to caching */
  156676. ogg_int64_t ov_raw_tell(OggVorbis_File *vf){
  156677. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156678. return(vf->offset);
  156679. }
  156680. /* return PCM offset (sample) of next PCM sample to be read */
  156681. ogg_int64_t ov_pcm_tell(OggVorbis_File *vf){
  156682. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156683. return(vf->pcm_offset);
  156684. }
  156685. /* return time offset (seconds) of next PCM sample to be read */
  156686. double ov_time_tell(OggVorbis_File *vf){
  156687. int link=0;
  156688. ogg_int64_t pcm_total=0;
  156689. double time_total=0.f;
  156690. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156691. if(vf->seekable){
  156692. pcm_total=ov_pcm_total(vf,-1);
  156693. time_total=ov_time_total(vf,-1);
  156694. /* which bitstream section does this time offset occur in? */
  156695. for(link=vf->links-1;link>=0;link--){
  156696. pcm_total-=vf->pcmlengths[link*2+1];
  156697. time_total-=ov_time_total(vf,link);
  156698. if(vf->pcm_offset>=pcm_total)break;
  156699. }
  156700. }
  156701. return((double)time_total+(double)(vf->pcm_offset-pcm_total)/vf->vi[link].rate);
  156702. }
  156703. /* link: -1) return the vorbis_info struct for the bitstream section
  156704. currently being decoded
  156705. 0-n) to request information for a specific bitstream section
  156706. In the case of a non-seekable bitstream, any call returns the
  156707. current bitstream. NULL in the case that the machine is not
  156708. initialized */
  156709. vorbis_info *ov_info(OggVorbis_File *vf,int link){
  156710. if(vf->seekable){
  156711. if(link<0)
  156712. if(vf->ready_state>=STREAMSET)
  156713. return vf->vi+vf->current_link;
  156714. else
  156715. return vf->vi;
  156716. else
  156717. if(link>=vf->links)
  156718. return NULL;
  156719. else
  156720. return vf->vi+link;
  156721. }else{
  156722. return vf->vi;
  156723. }
  156724. }
  156725. /* grr, strong typing, grr, no templates/inheritence, grr */
  156726. vorbis_comment *ov_comment(OggVorbis_File *vf,int link){
  156727. if(vf->seekable){
  156728. if(link<0)
  156729. if(vf->ready_state>=STREAMSET)
  156730. return vf->vc+vf->current_link;
  156731. else
  156732. return vf->vc;
  156733. else
  156734. if(link>=vf->links)
  156735. return NULL;
  156736. else
  156737. return vf->vc+link;
  156738. }else{
  156739. return vf->vc;
  156740. }
  156741. }
  156742. static int host_is_big_endian() {
  156743. ogg_int32_t pattern = 0xfeedface; /* deadbeef */
  156744. unsigned char *bytewise = (unsigned char *)&pattern;
  156745. if (bytewise[0] == 0xfe) return 1;
  156746. return 0;
  156747. }
  156748. /* up to this point, everything could more or less hide the multiple
  156749. logical bitstream nature of chaining from the toplevel application
  156750. if the toplevel application didn't particularly care. However, at
  156751. the point that we actually read audio back, the multiple-section
  156752. nature must surface: Multiple bitstream sections do not necessarily
  156753. have to have the same number of channels or sampling rate.
  156754. ov_read returns the sequential logical bitstream number currently
  156755. being decoded along with the PCM data in order that the toplevel
  156756. application can take action on channel/sample rate changes. This
  156757. number will be incremented even for streamed (non-seekable) streams
  156758. (for seekable streams, it represents the actual logical bitstream
  156759. index within the physical bitstream. Note that the accessor
  156760. functions above are aware of this dichotomy).
  156761. input values: buffer) a buffer to hold packed PCM data for return
  156762. length) the byte length requested to be placed into buffer
  156763. bigendianp) should the data be packed LSB first (0) or
  156764. MSB first (1)
  156765. word) word size for output. currently 1 (byte) or
  156766. 2 (16 bit short)
  156767. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  156768. 0) EOF
  156769. n) number of bytes of PCM actually returned. The
  156770. below works on a packet-by-packet basis, so the
  156771. return length is not related to the 'length' passed
  156772. in, just guaranteed to fit.
  156773. *section) set to the logical bitstream number */
  156774. long ov_read(OggVorbis_File *vf,char *buffer,int length,
  156775. int bigendianp,int word,int sgned,int *bitstream){
  156776. int i,j;
  156777. int host_endian = host_is_big_endian();
  156778. float **pcm;
  156779. long samples;
  156780. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156781. while(1){
  156782. if(vf->ready_state==INITSET){
  156783. samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  156784. if(samples)break;
  156785. }
  156786. /* suck in another packet */
  156787. {
  156788. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  156789. if(ret==OV_EOF)
  156790. return(0);
  156791. if(ret<=0)
  156792. return(ret);
  156793. }
  156794. }
  156795. if(samples>0){
  156796. /* yay! proceed to pack data into the byte buffer */
  156797. long channels=ov_info(vf,-1)->channels;
  156798. long bytespersample=word * channels;
  156799. vorbis_fpu_control fpu;
  156800. (void) fpu; // (to avoid a warning about it being unused)
  156801. if(samples>length/bytespersample)samples=length/bytespersample;
  156802. if(samples <= 0)
  156803. return OV_EINVAL;
  156804. /* a tight loop to pack each size */
  156805. {
  156806. int val;
  156807. if(word==1){
  156808. int off=(sgned?0:128);
  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]*128.f);
  156813. if(val>127)val=127;
  156814. else if(val<-128)val=-128;
  156815. *buffer++=val+off;
  156816. }
  156817. vorbis_fpu_restore(fpu);
  156818. }else{
  156819. int off=(sgned?0:32768);
  156820. if(host_endian==bigendianp){
  156821. if(sgned){
  156822. vorbis_fpu_setround(&fpu);
  156823. for(i=0;i<channels;i++) { /* It's faster in this order */
  156824. float *src=pcm[i];
  156825. short *dest=((short *)buffer)+i;
  156826. for(j=0;j<samples;j++) {
  156827. val=vorbis_ftoi(src[j]*32768.f);
  156828. if(val>32767)val=32767;
  156829. else if(val<-32768)val=-32768;
  156830. *dest=val;
  156831. dest+=channels;
  156832. }
  156833. }
  156834. vorbis_fpu_restore(fpu);
  156835. }else{
  156836. vorbis_fpu_setround(&fpu);
  156837. for(i=0;i<channels;i++) {
  156838. float *src=pcm[i];
  156839. short *dest=((short *)buffer)+i;
  156840. for(j=0;j<samples;j++) {
  156841. val=vorbis_ftoi(src[j]*32768.f);
  156842. if(val>32767)val=32767;
  156843. else if(val<-32768)val=-32768;
  156844. *dest=val+off;
  156845. dest+=channels;
  156846. }
  156847. }
  156848. vorbis_fpu_restore(fpu);
  156849. }
  156850. }else if(bigendianp){
  156851. vorbis_fpu_setround(&fpu);
  156852. for(j=0;j<samples;j++)
  156853. for(i=0;i<channels;i++){
  156854. val=vorbis_ftoi(pcm[i][j]*32768.f);
  156855. if(val>32767)val=32767;
  156856. else if(val<-32768)val=-32768;
  156857. val+=off;
  156858. *buffer++=(val>>8);
  156859. *buffer++=(val&0xff);
  156860. }
  156861. vorbis_fpu_restore(fpu);
  156862. }else{
  156863. int val;
  156864. vorbis_fpu_setround(&fpu);
  156865. for(j=0;j<samples;j++)
  156866. for(i=0;i<channels;i++){
  156867. val=vorbis_ftoi(pcm[i][j]*32768.f);
  156868. if(val>32767)val=32767;
  156869. else if(val<-32768)val=-32768;
  156870. val+=off;
  156871. *buffer++=(val&0xff);
  156872. *buffer++=(val>>8);
  156873. }
  156874. vorbis_fpu_restore(fpu);
  156875. }
  156876. }
  156877. }
  156878. vorbis_synthesis_read(&vf->vd,samples);
  156879. vf->pcm_offset+=samples;
  156880. if(bitstream)*bitstream=vf->current_link;
  156881. return(samples*bytespersample);
  156882. }else{
  156883. return(samples);
  156884. }
  156885. }
  156886. /* input values: pcm_channels) a float vector per channel of output
  156887. length) the sample length being read by the app
  156888. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  156889. 0) EOF
  156890. n) number of samples of PCM actually returned. The
  156891. below works on a packet-by-packet basis, so the
  156892. return length is not related to the 'length' passed
  156893. in, just guaranteed to fit.
  156894. *section) set to the logical bitstream number */
  156895. long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int length,
  156896. int *bitstream){
  156897. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156898. while(1){
  156899. if(vf->ready_state==INITSET){
  156900. float **pcm;
  156901. long samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  156902. if(samples){
  156903. if(pcm_channels)*pcm_channels=pcm;
  156904. if(samples>length)samples=length;
  156905. vorbis_synthesis_read(&vf->vd,samples);
  156906. vf->pcm_offset+=samples;
  156907. if(bitstream)*bitstream=vf->current_link;
  156908. return samples;
  156909. }
  156910. }
  156911. /* suck in another packet */
  156912. {
  156913. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  156914. if(ret==OV_EOF)return(0);
  156915. if(ret<=0)return(ret);
  156916. }
  156917. }
  156918. }
  156919. extern float *vorbis_window(vorbis_dsp_state *v,int W);
  156920. extern void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,
  156921. ogg_int64_t off);
  156922. static void _ov_splice(float **pcm,float **lappcm,
  156923. int n1, int n2,
  156924. int ch1, int ch2,
  156925. float *w1, float *w2){
  156926. int i,j;
  156927. float *w=w1;
  156928. int n=n1;
  156929. if(n1>n2){
  156930. n=n2;
  156931. w=w2;
  156932. }
  156933. /* splice */
  156934. for(j=0;j<ch1 && j<ch2;j++){
  156935. float *s=lappcm[j];
  156936. float *d=pcm[j];
  156937. for(i=0;i<n;i++){
  156938. float wd=w[i]*w[i];
  156939. float ws=1.-wd;
  156940. d[i]=d[i]*wd + s[i]*ws;
  156941. }
  156942. }
  156943. /* window from zero */
  156944. for(;j<ch2;j++){
  156945. float *d=pcm[j];
  156946. for(i=0;i<n;i++){
  156947. float wd=w[i]*w[i];
  156948. d[i]=d[i]*wd;
  156949. }
  156950. }
  156951. }
  156952. /* make sure vf is INITSET */
  156953. static int _ov_initset(OggVorbis_File *vf){
  156954. while(1){
  156955. if(vf->ready_state==INITSET)break;
  156956. /* suck in another packet */
  156957. {
  156958. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  156959. if(ret<0 && ret!=OV_HOLE)return(ret);
  156960. }
  156961. }
  156962. return 0;
  156963. }
  156964. /* make sure vf is INITSET and that we have a primed buffer; if
  156965. we're crosslapping at a stream section boundary, this also makes
  156966. sure we're sanity checking against the right stream information */
  156967. static int _ov_initprime(OggVorbis_File *vf){
  156968. vorbis_dsp_state *vd=&vf->vd;
  156969. while(1){
  156970. if(vf->ready_state==INITSET)
  156971. if(vorbis_synthesis_pcmout(vd,NULL))break;
  156972. /* suck in another packet */
  156973. {
  156974. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  156975. if(ret<0 && ret!=OV_HOLE)return(ret);
  156976. }
  156977. }
  156978. return 0;
  156979. }
  156980. /* grab enough data for lapping from vf; this may be in the form of
  156981. unreturned, already-decoded pcm, remaining PCM we will need to
  156982. decode, or synthetic postextrapolation from last packets. */
  156983. static void _ov_getlap(OggVorbis_File *vf,vorbis_info *vi,vorbis_dsp_state *vd,
  156984. float **lappcm,int lapsize){
  156985. int lapcount=0,i;
  156986. float **pcm;
  156987. /* try first to decode the lapping data */
  156988. while(lapcount<lapsize){
  156989. int samples=vorbis_synthesis_pcmout(vd,&pcm);
  156990. if(samples){
  156991. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  156992. for(i=0;i<vi->channels;i++)
  156993. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  156994. lapcount+=samples;
  156995. vorbis_synthesis_read(vd,samples);
  156996. }else{
  156997. /* suck in another packet */
  156998. int ret=_fetch_and_process_packet(vf,NULL,1,0); /* do *not* span */
  156999. if(ret==OV_EOF)break;
  157000. }
  157001. }
  157002. if(lapcount<lapsize){
  157003. /* failed to get lapping data from normal decode; pry it from the
  157004. postextrapolation buffering, or the second half of the MDCT
  157005. from the last packet */
  157006. int samples=vorbis_synthesis_lapout(&vf->vd,&pcm);
  157007. if(samples==0){
  157008. for(i=0;i<vi->channels;i++)
  157009. memset(lappcm[i]+lapcount,0,sizeof(**pcm)*lapsize-lapcount);
  157010. lapcount=lapsize;
  157011. }else{
  157012. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  157013. for(i=0;i<vi->channels;i++)
  157014. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  157015. lapcount+=samples;
  157016. }
  157017. }
  157018. }
  157019. /* this sets up crosslapping of a sample by using trailing data from
  157020. sample 1 and lapping it into the windowing buffer of sample 2 */
  157021. int ov_crosslap(OggVorbis_File *vf1, OggVorbis_File *vf2){
  157022. vorbis_info *vi1,*vi2;
  157023. float **lappcm;
  157024. float **pcm;
  157025. float *w1,*w2;
  157026. int n1,n2,i,ret,hs1,hs2;
  157027. if(vf1==vf2)return(0); /* degenerate case */
  157028. if(vf1->ready_state<OPENED)return(OV_EINVAL);
  157029. if(vf2->ready_state<OPENED)return(OV_EINVAL);
  157030. /* the relevant overlap buffers must be pre-checked and pre-primed
  157031. before looking at settings in the event that priming would cross
  157032. a bitstream boundary. So, do it now */
  157033. ret=_ov_initset(vf1);
  157034. if(ret)return(ret);
  157035. ret=_ov_initprime(vf2);
  157036. if(ret)return(ret);
  157037. vi1=ov_info(vf1,-1);
  157038. vi2=ov_info(vf2,-1);
  157039. hs1=ov_halfrate_p(vf1);
  157040. hs2=ov_halfrate_p(vf2);
  157041. lappcm=(float**) alloca(sizeof(*lappcm)*vi1->channels);
  157042. n1=vorbis_info_blocksize(vi1,0)>>(1+hs1);
  157043. n2=vorbis_info_blocksize(vi2,0)>>(1+hs2);
  157044. w1=vorbis_window(&vf1->vd,0);
  157045. w2=vorbis_window(&vf2->vd,0);
  157046. for(i=0;i<vi1->channels;i++)
  157047. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  157048. _ov_getlap(vf1,vi1,&vf1->vd,lappcm,n1);
  157049. /* have a lapping buffer from vf1; now to splice it into the lapping
  157050. buffer of vf2 */
  157051. /* consolidate and expose the buffer. */
  157052. vorbis_synthesis_lapout(&vf2->vd,&pcm);
  157053. _analysis_output_always("pcmL",0,pcm[0],n1*2,0,0,0);
  157054. _analysis_output_always("pcmR",0,pcm[1],n1*2,0,0,0);
  157055. /* splice */
  157056. _ov_splice(pcm,lappcm,n1,n2,vi1->channels,vi2->channels,w1,w2);
  157057. /* done */
  157058. return(0);
  157059. }
  157060. static int _ov_64_seek_lap(OggVorbis_File *vf,ogg_int64_t pos,
  157061. int (*localseek)(OggVorbis_File *,ogg_int64_t)){
  157062. vorbis_info *vi;
  157063. float **lappcm;
  157064. float **pcm;
  157065. float *w1,*w2;
  157066. int n1,n2,ch1,ch2,hs;
  157067. int i,ret;
  157068. if(vf->ready_state<OPENED)return(OV_EINVAL);
  157069. ret=_ov_initset(vf);
  157070. if(ret)return(ret);
  157071. vi=ov_info(vf,-1);
  157072. hs=ov_halfrate_p(vf);
  157073. ch1=vi->channels;
  157074. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  157075. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  157076. persistent; even if the decode state
  157077. from this link gets dumped, this
  157078. window array continues to exist */
  157079. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  157080. for(i=0;i<ch1;i++)
  157081. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  157082. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  157083. /* have lapping data; seek and prime the buffer */
  157084. ret=localseek(vf,pos);
  157085. if(ret)return ret;
  157086. ret=_ov_initprime(vf);
  157087. if(ret)return(ret);
  157088. /* Guard against cross-link changes; they're perfectly legal */
  157089. vi=ov_info(vf,-1);
  157090. ch2=vi->channels;
  157091. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  157092. w2=vorbis_window(&vf->vd,0);
  157093. /* consolidate and expose the buffer. */
  157094. vorbis_synthesis_lapout(&vf->vd,&pcm);
  157095. /* splice */
  157096. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  157097. /* done */
  157098. return(0);
  157099. }
  157100. int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  157101. return _ov_64_seek_lap(vf,pos,ov_raw_seek);
  157102. }
  157103. int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  157104. return _ov_64_seek_lap(vf,pos,ov_pcm_seek);
  157105. }
  157106. int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos){
  157107. return _ov_64_seek_lap(vf,pos,ov_pcm_seek_page);
  157108. }
  157109. static int _ov_d_seek_lap(OggVorbis_File *vf,double pos,
  157110. int (*localseek)(OggVorbis_File *,double)){
  157111. vorbis_info *vi;
  157112. float **lappcm;
  157113. float **pcm;
  157114. float *w1,*w2;
  157115. int n1,n2,ch1,ch2,hs;
  157116. int i,ret;
  157117. if(vf->ready_state<OPENED)return(OV_EINVAL);
  157118. ret=_ov_initset(vf);
  157119. if(ret)return(ret);
  157120. vi=ov_info(vf,-1);
  157121. hs=ov_halfrate_p(vf);
  157122. ch1=vi->channels;
  157123. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  157124. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  157125. persistent; even if the decode state
  157126. from this link gets dumped, this
  157127. window array continues to exist */
  157128. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  157129. for(i=0;i<ch1;i++)
  157130. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  157131. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  157132. /* have lapping data; seek and prime the buffer */
  157133. ret=localseek(vf,pos);
  157134. if(ret)return ret;
  157135. ret=_ov_initprime(vf);
  157136. if(ret)return(ret);
  157137. /* Guard against cross-link changes; they're perfectly legal */
  157138. vi=ov_info(vf,-1);
  157139. ch2=vi->channels;
  157140. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  157141. w2=vorbis_window(&vf->vd,0);
  157142. /* consolidate and expose the buffer. */
  157143. vorbis_synthesis_lapout(&vf->vd,&pcm);
  157144. /* splice */
  157145. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  157146. /* done */
  157147. return(0);
  157148. }
  157149. int ov_time_seek_lap(OggVorbis_File *vf,double pos){
  157150. return _ov_d_seek_lap(vf,pos,ov_time_seek);
  157151. }
  157152. int ov_time_seek_page_lap(OggVorbis_File *vf,double pos){
  157153. return _ov_d_seek_lap(vf,pos,ov_time_seek_page);
  157154. }
  157155. #endif
  157156. /*** End of inlined file: vorbisfile.c ***/
  157157. /*** Start of inlined file: window.c ***/
  157158. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  157159. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  157160. // tasks..
  157161. #if JUCE_MSVC
  157162. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  157163. #endif
  157164. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  157165. #if JUCE_USE_OGGVORBIS
  157166. #include <stdlib.h>
  157167. #include <math.h>
  157168. static float vwin64[32] = {
  157169. 0.0009460463F, 0.0085006468F, 0.0235352254F, 0.0458950567F,
  157170. 0.0753351908F, 0.1115073077F, 0.1539457973F, 0.2020557475F,
  157171. 0.2551056759F, 0.3122276645F, 0.3724270287F, 0.4346027792F,
  157172. 0.4975789974F, 0.5601459521F, 0.6211085051F, 0.6793382689F,
  157173. 0.7338252629F, 0.7837245849F, 0.8283939355F, 0.8674186656F,
  157174. 0.9006222429F, 0.9280614787F, 0.9500073081F, 0.9669131782F,
  157175. 0.9793740220F, 0.9880792941F, 0.9937636139F, 0.9971582668F,
  157176. 0.9989462667F, 0.9997230082F, 0.9999638688F, 0.9999995525F,
  157177. };
  157178. static float vwin128[64] = {
  157179. 0.0002365472F, 0.0021280687F, 0.0059065254F, 0.0115626550F,
  157180. 0.0190823442F, 0.0284463735F, 0.0396300935F, 0.0526030430F,
  157181. 0.0673285281F, 0.0837631763F, 0.1018564887F, 0.1215504095F,
  157182. 0.1427789367F, 0.1654677960F, 0.1895342001F, 0.2148867160F,
  157183. 0.2414252576F, 0.2690412240F, 0.2976177952F, 0.3270303960F,
  157184. 0.3571473350F, 0.3878306189F, 0.4189369387F, 0.4503188188F,
  157185. 0.4818259135F, 0.5133064334F, 0.5446086751F, 0.5755826278F,
  157186. 0.6060816248F, 0.6359640047F, 0.6650947483F, 0.6933470543F,
  157187. 0.7206038179F, 0.7467589810F, 0.7717187213F, 0.7954024542F,
  157188. 0.8177436264F, 0.8386902831F, 0.8582053981F, 0.8762669622F,
  157189. 0.8928678298F, 0.9080153310F, 0.9217306608F, 0.9340480615F,
  157190. 0.9450138200F, 0.9546851041F, 0.9631286621F, 0.9704194171F,
  157191. 0.9766389810F, 0.9818741197F, 0.9862151938F, 0.9897546035F,
  157192. 0.9925852598F, 0.9947991032F, 0.9964856900F, 0.9977308602F,
  157193. 0.9986155015F, 0.9992144193F, 0.9995953200F, 0.9998179155F,
  157194. 0.9999331503F, 0.9999825563F, 0.9999977357F, 0.9999999720F,
  157195. };
  157196. static float vwin256[128] = {
  157197. 0.0000591390F, 0.0005321979F, 0.0014780301F, 0.0028960636F,
  157198. 0.0047854363F, 0.0071449926F, 0.0099732775F, 0.0132685298F,
  157199. 0.0170286741F, 0.0212513119F, 0.0259337111F, 0.0310727950F,
  157200. 0.0366651302F, 0.0427069140F, 0.0491939614F, 0.0561216907F,
  157201. 0.0634851102F, 0.0712788035F, 0.0794969160F, 0.0881331402F,
  157202. 0.0971807028F, 0.1066323515F, 0.1164803426F, 0.1267164297F,
  157203. 0.1373318534F, 0.1483173323F, 0.1596630553F, 0.1713586755F,
  157204. 0.1833933062F, 0.1957555184F, 0.2084333404F, 0.2214142599F,
  157205. 0.2346852280F, 0.2482326664F, 0.2620424757F, 0.2761000481F,
  157206. 0.2903902813F, 0.3048975959F, 0.3196059553F, 0.3344988887F,
  157207. 0.3495595160F, 0.3647705766F, 0.3801144597F, 0.3955732382F,
  157208. 0.4111287047F, 0.4267624093F, 0.4424557009F, 0.4581897696F,
  157209. 0.4739456913F, 0.4897044744F, 0.5054471075F, 0.5211546088F,
  157210. 0.5368080763F, 0.5523887395F, 0.5678780103F, 0.5832575361F,
  157211. 0.5985092508F, 0.6136154277F, 0.6285587300F, 0.6433222619F,
  157212. 0.6578896175F, 0.6722449294F, 0.6863729144F, 0.7002589187F,
  157213. 0.7138889597F, 0.7272497662F, 0.7403288154F, 0.7531143679F,
  157214. 0.7655954985F, 0.7777621249F, 0.7896050322F, 0.8011158947F,
  157215. 0.8122872932F, 0.8231127294F, 0.8335866365F, 0.8437043850F,
  157216. 0.8534622861F, 0.8628575905F, 0.8718884835F, 0.8805540765F,
  157217. 0.8888543947F, 0.8967903616F, 0.9043637797F, 0.9115773078F,
  157218. 0.9184344360F, 0.9249394562F, 0.9310974312F, 0.9369141608F,
  157219. 0.9423961446F, 0.9475505439F, 0.9523851406F, 0.9569082947F,
  157220. 0.9611289005F, 0.9650563408F, 0.9687004405F, 0.9720714191F,
  157221. 0.9751798427F, 0.9780365753F, 0.9806527301F, 0.9830396204F,
  157222. 0.9852087111F, 0.9871715701F, 0.9889398207F, 0.9905250941F,
  157223. 0.9919389832F, 0.9931929973F, 0.9942985174F, 0.9952667537F,
  157224. 0.9961087037F, 0.9968351119F, 0.9974564312F, 0.9979827858F,
  157225. 0.9984239359F, 0.9987892441F, 0.9990876435F, 0.9993276081F,
  157226. 0.9995171241F, 0.9996636648F, 0.9997741654F, 0.9998550016F,
  157227. 0.9999119692F, 0.9999502656F, 0.9999744742F, 0.9999885497F,
  157228. 0.9999958064F, 0.9999989077F, 0.9999998584F, 0.9999999983F,
  157229. };
  157230. static float vwin512[256] = {
  157231. 0.0000147849F, 0.0001330607F, 0.0003695946F, 0.0007243509F,
  157232. 0.0011972759F, 0.0017882983F, 0.0024973285F, 0.0033242588F,
  157233. 0.0042689632F, 0.0053312973F, 0.0065110982F, 0.0078081841F,
  157234. 0.0092223540F, 0.0107533880F, 0.0124010466F, 0.0141650703F,
  157235. 0.0160451800F, 0.0180410758F, 0.0201524373F, 0.0223789233F,
  157236. 0.0247201710F, 0.0271757958F, 0.0297453914F, 0.0324285286F,
  157237. 0.0352247556F, 0.0381335972F, 0.0411545545F, 0.0442871045F,
  157238. 0.0475306997F, 0.0508847676F, 0.0543487103F, 0.0579219038F,
  157239. 0.0616036982F, 0.0653934164F, 0.0692903546F, 0.0732937809F,
  157240. 0.0774029356F, 0.0816170305F, 0.0859352485F, 0.0903567428F,
  157241. 0.0948806375F, 0.0995060259F, 0.1042319712F, 0.1090575056F,
  157242. 0.1139816300F, 0.1190033137F, 0.1241214941F, 0.1293350764F,
  157243. 0.1346429333F, 0.1400439046F, 0.1455367974F, 0.1511203852F,
  157244. 0.1567934083F, 0.1625545735F, 0.1684025537F, 0.1743359881F,
  157245. 0.1803534820F, 0.1864536069F, 0.1926349000F, 0.1988958650F,
  157246. 0.2052349715F, 0.2116506555F, 0.2181413191F, 0.2247053313F,
  157247. 0.2313410275F, 0.2380467105F, 0.2448206500F, 0.2516610835F,
  157248. 0.2585662164F, 0.2655342226F, 0.2725632448F, 0.2796513950F,
  157249. 0.2867967551F, 0.2939973773F, 0.3012512852F, 0.3085564739F,
  157250. 0.3159109111F, 0.3233125375F, 0.3307592680F, 0.3382489922F,
  157251. 0.3457795756F, 0.3533488602F, 0.3609546657F, 0.3685947904F,
  157252. 0.3762670121F, 0.3839690896F, 0.3916987634F, 0.3994537572F,
  157253. 0.4072317788F, 0.4150305215F, 0.4228476653F, 0.4306808783F,
  157254. 0.4385278181F, 0.4463861329F, 0.4542534630F, 0.4621274424F,
  157255. 0.4700057001F, 0.4778858615F, 0.4857655502F, 0.4936423891F,
  157256. 0.5015140023F, 0.5093780165F, 0.5172320626F, 0.5250737772F,
  157257. 0.5329008043F, 0.5407107971F, 0.5485014192F, 0.5562703465F,
  157258. 0.5640152688F, 0.5717338914F, 0.5794239366F, 0.5870831457F,
  157259. 0.5947092801F, 0.6023001235F, 0.6098534829F, 0.6173671907F,
  157260. 0.6248391059F, 0.6322671161F, 0.6396491384F, 0.6469831217F,
  157261. 0.6542670475F, 0.6614989319F, 0.6686768267F, 0.6757988210F,
  157262. 0.6828630426F, 0.6898676592F, 0.6968108799F, 0.7036909564F,
  157263. 0.7105061843F, 0.7172549043F, 0.7239355032F, 0.7305464154F,
  157264. 0.7370861235F, 0.7435531598F, 0.7499461068F, 0.7562635986F,
  157265. 0.7625043214F, 0.7686670148F, 0.7747504721F, 0.7807535410F,
  157266. 0.7866751247F, 0.7925141825F, 0.7982697296F, 0.8039408387F,
  157267. 0.8095266395F, 0.8150263196F, 0.8204391248F, 0.8257643590F,
  157268. 0.8310013848F, 0.8361496236F, 0.8412085555F, 0.8461777194F,
  157269. 0.8510567129F, 0.8558451924F, 0.8605428730F, 0.8651495278F,
  157270. 0.8696649882F, 0.8740891432F, 0.8784219392F, 0.8826633797F,
  157271. 0.8868135244F, 0.8908724888F, 0.8948404441F, 0.8987176157F,
  157272. 0.9025042831F, 0.9062007791F, 0.9098074886F, 0.9133248482F,
  157273. 0.9167533451F, 0.9200935163F, 0.9233459472F, 0.9265112712F,
  157274. 0.9295901680F, 0.9325833632F, 0.9354916263F, 0.9383157705F,
  157275. 0.9410566504F, 0.9437151618F, 0.9462922398F, 0.9487888576F,
  157276. 0.9512060252F, 0.9535447882F, 0.9558062262F, 0.9579914516F,
  157277. 0.9601016078F, 0.9621378683F, 0.9641014348F, 0.9659935361F,
  157278. 0.9678154261F, 0.9695683830F, 0.9712537071F, 0.9728727198F,
  157279. 0.9744267618F, 0.9759171916F, 0.9773453842F, 0.9787127293F,
  157280. 0.9800206298F, 0.9812705006F, 0.9824637665F, 0.9836018613F,
  157281. 0.9846862258F, 0.9857183066F, 0.9866995544F, 0.9876314227F,
  157282. 0.9885153662F, 0.9893528393F, 0.9901452948F, 0.9908941823F,
  157283. 0.9916009470F, 0.9922670279F, 0.9928938570F, 0.9934828574F,
  157284. 0.9940354423F, 0.9945530133F, 0.9950369595F, 0.9954886562F,
  157285. 0.9959094633F, 0.9963007242F, 0.9966637649F, 0.9969998925F,
  157286. 0.9973103939F, 0.9975965351F, 0.9978595598F, 0.9981006885F,
  157287. 0.9983211172F, 0.9985220166F, 0.9987045311F, 0.9988697776F,
  157288. 0.9990188449F, 0.9991527924F, 0.9992726499F, 0.9993794157F,
  157289. 0.9994740570F, 0.9995575079F, 0.9996306699F, 0.9996944099F,
  157290. 0.9997495605F, 0.9997969190F, 0.9998372465F, 0.9998712678F,
  157291. 0.9998996704F, 0.9999231041F, 0.9999421807F, 0.9999574732F,
  157292. 0.9999695157F, 0.9999788026F, 0.9999857885F, 0.9999908879F,
  157293. 0.9999944746F, 0.9999968817F, 0.9999984010F, 0.9999992833F,
  157294. 0.9999997377F, 0.9999999317F, 0.9999999911F, 0.9999999999F,
  157295. };
  157296. static float vwin1024[512] = {
  157297. 0.0000036962F, 0.0000332659F, 0.0000924041F, 0.0001811086F,
  157298. 0.0002993761F, 0.0004472021F, 0.0006245811F, 0.0008315063F,
  157299. 0.0010679699F, 0.0013339631F, 0.0016294757F, 0.0019544965F,
  157300. 0.0023090133F, 0.0026930125F, 0.0031064797F, 0.0035493989F,
  157301. 0.0040217533F, 0.0045235250F, 0.0050546946F, 0.0056152418F,
  157302. 0.0062051451F, 0.0068243817F, 0.0074729278F, 0.0081507582F,
  157303. 0.0088578466F, 0.0095941655F, 0.0103596863F, 0.0111543789F,
  157304. 0.0119782122F, 0.0128311538F, 0.0137131701F, 0.0146242260F,
  157305. 0.0155642855F, 0.0165333111F, 0.0175312640F, 0.0185581042F,
  157306. 0.0196137903F, 0.0206982797F, 0.0218115284F, 0.0229534910F,
  157307. 0.0241241208F, 0.0253233698F, 0.0265511886F, 0.0278075263F,
  157308. 0.0290923308F, 0.0304055484F, 0.0317471241F, 0.0331170013F,
  157309. 0.0345151222F, 0.0359414274F, 0.0373958560F, 0.0388783456F,
  157310. 0.0403888325F, 0.0419272511F, 0.0434935347F, 0.0450876148F,
  157311. 0.0467094213F, 0.0483588828F, 0.0500359261F, 0.0517404765F,
  157312. 0.0534724575F, 0.0552317913F, 0.0570183983F, 0.0588321971F,
  157313. 0.0606731048F, 0.0625410369F, 0.0644359070F, 0.0663576272F,
  157314. 0.0683061077F, 0.0702812571F, 0.0722829821F, 0.0743111878F,
  157315. 0.0763657775F, 0.0784466526F, 0.0805537129F, 0.0826868561F,
  157316. 0.0848459782F, 0.0870309736F, 0.0892417345F, 0.0914781514F,
  157317. 0.0937401128F, 0.0960275056F, 0.0983402145F, 0.1006781223F,
  157318. 0.1030411101F, 0.1054290568F, 0.1078418397F, 0.1102793336F,
  157319. 0.1127414119F, 0.1152279457F, 0.1177388042F, 0.1202738544F,
  157320. 0.1228329618F, 0.1254159892F, 0.1280227980F, 0.1306532471F,
  157321. 0.1333071937F, 0.1359844927F, 0.1386849970F, 0.1414085575F,
  157322. 0.1441550230F, 0.1469242403F, 0.1497160539F, 0.1525303063F,
  157323. 0.1553668381F, 0.1582254875F, 0.1611060909F, 0.1640084822F,
  157324. 0.1669324936F, 0.1698779549F, 0.1728446939F, 0.1758325362F,
  157325. 0.1788413055F, 0.1818708232F, 0.1849209084F, 0.1879913785F,
  157326. 0.1910820485F, 0.1941927312F, 0.1973232376F, 0.2004733764F,
  157327. 0.2036429541F, 0.2068317752F, 0.2100396421F, 0.2132663552F,
  157328. 0.2165117125F, 0.2197755102F, 0.2230575422F, 0.2263576007F,
  157329. 0.2296754753F, 0.2330109540F, 0.2363638225F, 0.2397338646F,
  157330. 0.2431208619F, 0.2465245941F, 0.2499448389F, 0.2533813719F,
  157331. 0.2568339669F, 0.2603023956F, 0.2637864277F, 0.2672858312F,
  157332. 0.2708003718F, 0.2743298135F, 0.2778739186F, 0.2814324472F,
  157333. 0.2850051576F, 0.2885918065F, 0.2921921485F, 0.2958059366F,
  157334. 0.2994329219F, 0.3030728538F, 0.3067254799F, 0.3103905462F,
  157335. 0.3140677969F, 0.3177569747F, 0.3214578205F, 0.3251700736F,
  157336. 0.3288934718F, 0.3326277513F, 0.3363726468F, 0.3401278914F,
  157337. 0.3438932168F, 0.3476683533F, 0.3514530297F, 0.3552469734F,
  157338. 0.3590499106F, 0.3628615659F, 0.3666816630F, 0.3705099239F,
  157339. 0.3743460698F, 0.3781898204F, 0.3820408945F, 0.3858990095F,
  157340. 0.3897638820F, 0.3936352274F, 0.3975127601F, 0.4013961936F,
  157341. 0.4052852405F, 0.4091796123F, 0.4130790198F, 0.4169831732F,
  157342. 0.4208917815F, 0.4248045534F, 0.4287211965F, 0.4326414181F,
  157343. 0.4365649248F, 0.4404914225F, 0.4444206167F, 0.4483522125F,
  157344. 0.4522859146F, 0.4562214270F, 0.4601584538F, 0.4640966984F,
  157345. 0.4680358644F, 0.4719756548F, 0.4759157726F, 0.4798559209F,
  157346. 0.4837958024F, 0.4877351199F, 0.4916735765F, 0.4956108751F,
  157347. 0.4995467188F, 0.5034808109F, 0.5074128550F, 0.5113425550F,
  157348. 0.5152696149F, 0.5191937395F, 0.5231146336F, 0.5270320028F,
  157349. 0.5309455530F, 0.5348549910F, 0.5387600239F, 0.5426603597F,
  157350. 0.5465557070F, 0.5504457754F, 0.5543302752F, 0.5582089175F,
  157351. 0.5620814145F, 0.5659474793F, 0.5698068262F, 0.5736591704F,
  157352. 0.5775042283F, 0.5813417176F, 0.5851713571F, 0.5889928670F,
  157353. 0.5928059689F, 0.5966103856F, 0.6004058415F, 0.6041920626F,
  157354. 0.6079687761F, 0.6117357113F, 0.6154925986F, 0.6192391705F,
  157355. 0.6229751612F, 0.6267003064F, 0.6304143441F, 0.6341170137F,
  157356. 0.6378080569F, 0.6414872173F, 0.6451542405F, 0.6488088741F,
  157357. 0.6524508681F, 0.6560799742F, 0.6596959469F, 0.6632985424F,
  157358. 0.6668875197F, 0.6704626398F, 0.6740236662F, 0.6775703649F,
  157359. 0.6811025043F, 0.6846198554F, 0.6881221916F, 0.6916092892F,
  157360. 0.6950809269F, 0.6985368861F, 0.7019769510F, 0.7054009085F,
  157361. 0.7088085484F, 0.7121996632F, 0.7155740484F, 0.7189315023F,
  157362. 0.7222718263F, 0.7255948245F, 0.7289003043F, 0.7321880760F,
  157363. 0.7354579530F, 0.7387097518F, 0.7419432921F, 0.7451583966F,
  157364. 0.7483548915F, 0.7515326059F, 0.7546913723F, 0.7578310265F,
  157365. 0.7609514077F, 0.7640523581F, 0.7671337237F, 0.7701953535F,
  157366. 0.7732371001F, 0.7762588195F, 0.7792603711F, 0.7822416178F,
  157367. 0.7852024259F, 0.7881426654F, 0.7910622097F, 0.7939609356F,
  157368. 0.7968387237F, 0.7996954579F, 0.8025310261F, 0.8053453193F,
  157369. 0.8081382324F, 0.8109096638F, 0.8136595156F, 0.8163876936F,
  157370. 0.8190941071F, 0.8217786690F, 0.8244412960F, 0.8270819086F,
  157371. 0.8297004305F, 0.8322967896F, 0.8348709171F, 0.8374227481F,
  157372. 0.8399522213F, 0.8424592789F, 0.8449438672F, 0.8474059356F,
  157373. 0.8498454378F, 0.8522623306F, 0.8546565748F, 0.8570281348F,
  157374. 0.8593769787F, 0.8617030779F, 0.8640064080F, 0.8662869477F,
  157375. 0.8685446796F, 0.8707795899F, 0.8729916682F, 0.8751809079F,
  157376. 0.8773473059F, 0.8794908626F, 0.8816115819F, 0.8837094713F,
  157377. 0.8857845418F, 0.8878368079F, 0.8898662874F, 0.8918730019F,
  157378. 0.8938569760F, 0.8958182380F, 0.8977568194F, 0.8996727552F,
  157379. 0.9015660837F, 0.9034368465F, 0.9052850885F, 0.9071108577F,
  157380. 0.9089142057F, 0.9106951869F, 0.9124538591F, 0.9141902832F,
  157381. 0.9159045233F, 0.9175966464F, 0.9192667228F, 0.9209148257F,
  157382. 0.9225410313F, 0.9241454187F, 0.9257280701F, 0.9272890704F,
  157383. 0.9288285075F, 0.9303464720F, 0.9318430576F, 0.9333183603F,
  157384. 0.9347724792F, 0.9362055158F, 0.9376175745F, 0.9390087622F,
  157385. 0.9403791881F, 0.9417289644F, 0.9430582055F, 0.9443670283F,
  157386. 0.9456555521F, 0.9469238986F, 0.9481721917F, 0.9494005577F,
  157387. 0.9506091252F, 0.9517980248F, 0.9529673894F, 0.9541173540F,
  157388. 0.9552480557F, 0.9563596334F, 0.9574522282F, 0.9585259830F,
  157389. 0.9595810428F, 0.9606175542F, 0.9616356656F, 0.9626355274F,
  157390. 0.9636172915F, 0.9645811114F, 0.9655271425F, 0.9664555414F,
  157391. 0.9673664664F, 0.9682600774F, 0.9691365355F, 0.9699960034F,
  157392. 0.9708386448F, 0.9716646250F, 0.9724741103F, 0.9732672685F,
  157393. 0.9740442683F, 0.9748052795F, 0.9755504729F, 0.9762800205F,
  157394. 0.9769940950F, 0.9776928703F, 0.9783765210F, 0.9790452223F,
  157395. 0.9796991504F, 0.9803384823F, 0.9809633954F, 0.9815740679F,
  157396. 0.9821706784F, 0.9827534063F, 0.9833224312F, 0.9838779332F,
  157397. 0.9844200928F, 0.9849490910F, 0.9854651087F, 0.9859683274F,
  157398. 0.9864589286F, 0.9869370940F, 0.9874030054F, 0.9878568447F,
  157399. 0.9882987937F, 0.9887290343F, 0.9891477481F, 0.9895551169F,
  157400. 0.9899513220F, 0.9903365446F, 0.9907109658F, 0.9910747662F,
  157401. 0.9914281260F, 0.9917712252F, 0.9921042433F, 0.9924273593F,
  157402. 0.9927407516F, 0.9930445982F, 0.9933390763F, 0.9936243626F,
  157403. 0.9939006331F, 0.9941680631F, 0.9944268269F, 0.9946770982F,
  157404. 0.9949190498F, 0.9951528537F, 0.9953786808F, 0.9955967011F,
  157405. 0.9958070836F, 0.9960099963F, 0.9962056061F, 0.9963940787F,
  157406. 0.9965755786F, 0.9967502693F, 0.9969183129F, 0.9970798704F,
  157407. 0.9972351013F, 0.9973841640F, 0.9975272151F, 0.9976644103F,
  157408. 0.9977959036F, 0.9979218476F, 0.9980423932F, 0.9981576901F,
  157409. 0.9982678862F, 0.9983731278F, 0.9984735596F, 0.9985693247F,
  157410. 0.9986605645F, 0.9987474186F, 0.9988300248F, 0.9989085193F,
  157411. 0.9989830364F, 0.9990537085F, 0.9991206662F, 0.9991840382F,
  157412. 0.9992439513F, 0.9993005303F, 0.9993538982F, 0.9994041757F,
  157413. 0.9994514817F, 0.9994959330F, 0.9995376444F, 0.9995767286F,
  157414. 0.9996132960F, 0.9996474550F, 0.9996793121F, 0.9997089710F,
  157415. 0.9997365339F, 0.9997621003F, 0.9997857677F, 0.9998076311F,
  157416. 0.9998277836F, 0.9998463156F, 0.9998633155F, 0.9998788692F,
  157417. 0.9998930603F, 0.9999059701F, 0.9999176774F, 0.9999282586F,
  157418. 0.9999377880F, 0.9999463370F, 0.9999539749F, 0.9999607685F,
  157419. 0.9999667820F, 0.9999720773F, 0.9999767136F, 0.9999807479F,
  157420. 0.9999842344F, 0.9999872249F, 0.9999897688F, 0.9999919127F,
  157421. 0.9999937009F, 0.9999951749F, 0.9999963738F, 0.9999973342F,
  157422. 0.9999980900F, 0.9999986724F, 0.9999991103F, 0.9999994297F,
  157423. 0.9999996543F, 0.9999998049F, 0.9999999000F, 0.9999999552F,
  157424. 0.9999999836F, 0.9999999957F, 0.9999999994F, 1.0000000000F,
  157425. };
  157426. static float vwin2048[1024] = {
  157427. 0.0000009241F, 0.0000083165F, 0.0000231014F, 0.0000452785F,
  157428. 0.0000748476F, 0.0001118085F, 0.0001561608F, 0.0002079041F,
  157429. 0.0002670379F, 0.0003335617F, 0.0004074748F, 0.0004887765F,
  157430. 0.0005774661F, 0.0006735427F, 0.0007770054F, 0.0008878533F,
  157431. 0.0010060853F, 0.0011317002F, 0.0012646969F, 0.0014050742F,
  157432. 0.0015528307F, 0.0017079650F, 0.0018704756F, 0.0020403610F,
  157433. 0.0022176196F, 0.0024022497F, 0.0025942495F, 0.0027936173F,
  157434. 0.0030003511F, 0.0032144490F, 0.0034359088F, 0.0036647286F,
  157435. 0.0039009061F, 0.0041444391F, 0.0043953253F, 0.0046535621F,
  157436. 0.0049191472F, 0.0051920781F, 0.0054723520F, 0.0057599664F,
  157437. 0.0060549184F, 0.0063572052F, 0.0066668239F, 0.0069837715F,
  157438. 0.0073080449F, 0.0076396410F, 0.0079785566F, 0.0083247884F,
  157439. 0.0086783330F, 0.0090391871F, 0.0094073470F, 0.0097828092F,
  157440. 0.0101655700F, 0.0105556258F, 0.0109529726F, 0.0113576065F,
  157441. 0.0117695237F, 0.0121887200F, 0.0126151913F, 0.0130489335F,
  157442. 0.0134899422F, 0.0139382130F, 0.0143937415F, 0.0148565233F,
  157443. 0.0153265536F, 0.0158038279F, 0.0162883413F, 0.0167800889F,
  157444. 0.0172790660F, 0.0177852675F, 0.0182986882F, 0.0188193231F,
  157445. 0.0193471668F, 0.0198822141F, 0.0204244594F, 0.0209738974F,
  157446. 0.0215305225F, 0.0220943289F, 0.0226653109F, 0.0232434627F,
  157447. 0.0238287784F, 0.0244212519F, 0.0250208772F, 0.0256276481F,
  157448. 0.0262415582F, 0.0268626014F, 0.0274907711F, 0.0281260608F,
  157449. 0.0287684638F, 0.0294179736F, 0.0300745833F, 0.0307382859F,
  157450. 0.0314090747F, 0.0320869424F, 0.0327718819F, 0.0334638860F,
  157451. 0.0341629474F, 0.0348690586F, 0.0355822122F, 0.0363024004F,
  157452. 0.0370296157F, 0.0377638502F, 0.0385050960F, 0.0392533451F,
  157453. 0.0400085896F, 0.0407708211F, 0.0415400315F, 0.0423162123F,
  157454. 0.0430993552F, 0.0438894515F, 0.0446864926F, 0.0454904698F,
  157455. 0.0463013742F, 0.0471191969F, 0.0479439288F, 0.0487755607F,
  157456. 0.0496140836F, 0.0504594879F, 0.0513117642F, 0.0521709031F,
  157457. 0.0530368949F, 0.0539097297F, 0.0547893979F, 0.0556758894F,
  157458. 0.0565691941F, 0.0574693019F, 0.0583762026F, 0.0592898858F,
  157459. 0.0602103410F, 0.0611375576F, 0.0620715250F, 0.0630122324F,
  157460. 0.0639596688F, 0.0649138234F, 0.0658746848F, 0.0668422421F,
  157461. 0.0678164838F, 0.0687973985F, 0.0697849746F, 0.0707792005F,
  157462. 0.0717800645F, 0.0727875547F, 0.0738016591F, 0.0748223656F,
  157463. 0.0758496620F, 0.0768835359F, 0.0779239751F, 0.0789709668F,
  157464. 0.0800244985F, 0.0810845574F, 0.0821511306F, 0.0832242052F,
  157465. 0.0843037679F, 0.0853898056F, 0.0864823050F, 0.0875812525F,
  157466. 0.0886866347F, 0.0897984378F, 0.0909166480F, 0.0920412513F,
  157467. 0.0931722338F, 0.0943095813F, 0.0954532795F, 0.0966033140F,
  157468. 0.0977596702F, 0.0989223336F, 0.1000912894F, 0.1012665227F,
  157469. 0.1024480185F, 0.1036357616F, 0.1048297369F, 0.1060299290F,
  157470. 0.1072363224F, 0.1084489014F, 0.1096676504F, 0.1108925534F,
  157471. 0.1121235946F, 0.1133607577F, 0.1146040267F, 0.1158533850F,
  157472. 0.1171088163F, 0.1183703040F, 0.1196378312F, 0.1209113812F,
  157473. 0.1221909370F, 0.1234764815F, 0.1247679974F, 0.1260654674F,
  157474. 0.1273688740F, 0.1286781995F, 0.1299934263F, 0.1313145365F,
  157475. 0.1326415121F, 0.1339743349F, 0.1353129866F, 0.1366574490F,
  157476. 0.1380077035F, 0.1393637315F, 0.1407255141F, 0.1420930325F,
  157477. 0.1434662677F, 0.1448452004F, 0.1462298115F, 0.1476200814F,
  157478. 0.1490159906F, 0.1504175195F, 0.1518246482F, 0.1532373569F,
  157479. 0.1546556253F, 0.1560794333F, 0.1575087606F, 0.1589435866F,
  157480. 0.1603838909F, 0.1618296526F, 0.1632808509F, 0.1647374648F,
  157481. 0.1661994731F, 0.1676668546F, 0.1691395880F, 0.1706176516F,
  157482. 0.1721010238F, 0.1735896829F, 0.1750836068F, 0.1765827736F,
  157483. 0.1780871610F, 0.1795967468F, 0.1811115084F, 0.1826314234F,
  157484. 0.1841564689F, 0.1856866221F, 0.1872218600F, 0.1887621595F,
  157485. 0.1903074974F, 0.1918578503F, 0.1934131947F, 0.1949735068F,
  157486. 0.1965387630F, 0.1981089393F, 0.1996840117F, 0.2012639560F,
  157487. 0.2028487479F, 0.2044383630F, 0.2060327766F, 0.2076319642F,
  157488. 0.2092359007F, 0.2108445614F, 0.2124579211F, 0.2140759545F,
  157489. 0.2156986364F, 0.2173259411F, 0.2189578432F, 0.2205943168F,
  157490. 0.2222353361F, 0.2238808751F, 0.2255309076F, 0.2271854073F,
  157491. 0.2288443480F, 0.2305077030F, 0.2321754457F, 0.2338475493F,
  157492. 0.2355239869F, 0.2372047315F, 0.2388897560F, 0.2405790329F,
  157493. 0.2422725350F, 0.2439702347F, 0.2456721043F, 0.2473781159F,
  157494. 0.2490882418F, 0.2508024539F, 0.2525207240F, 0.2542430237F,
  157495. 0.2559693248F, 0.2576995986F, 0.2594338166F, 0.2611719498F,
  157496. 0.2629139695F, 0.2646598466F, 0.2664095520F, 0.2681630564F,
  157497. 0.2699203304F, 0.2716813445F, 0.2734460691F, 0.2752144744F,
  157498. 0.2769865307F, 0.2787622079F, 0.2805414760F, 0.2823243047F,
  157499. 0.2841106637F, 0.2859005227F, 0.2876938509F, 0.2894906179F,
  157500. 0.2912907928F, 0.2930943447F, 0.2949012426F, 0.2967114554F,
  157501. 0.2985249520F, 0.3003417009F, 0.3021616708F, 0.3039848301F,
  157502. 0.3058111471F, 0.3076405901F, 0.3094731273F, 0.3113087266F,
  157503. 0.3131473560F, 0.3149889833F, 0.3168335762F, 0.3186811024F,
  157504. 0.3205315294F, 0.3223848245F, 0.3242409552F, 0.3260998886F,
  157505. 0.3279615918F, 0.3298260319F, 0.3316931758F, 0.3335629903F,
  157506. 0.3354354423F, 0.3373104982F, 0.3391881247F, 0.3410682882F,
  157507. 0.3429509551F, 0.3448360917F, 0.3467236642F, 0.3486136387F,
  157508. 0.3505059811F, 0.3524006575F, 0.3542976336F, 0.3561968753F,
  157509. 0.3580983482F, 0.3600020179F, 0.3619078499F, 0.3638158096F,
  157510. 0.3657258625F, 0.3676379737F, 0.3695521086F, 0.3714682321F,
  157511. 0.3733863094F, 0.3753063055F, 0.3772281852F, 0.3791519134F,
  157512. 0.3810774548F, 0.3830047742F, 0.3849338362F, 0.3868646053F,
  157513. 0.3887970459F, 0.3907311227F, 0.3926667998F, 0.3946040417F,
  157514. 0.3965428125F, 0.3984830765F, 0.4004247978F, 0.4023679403F,
  157515. 0.4043124683F, 0.4062583455F, 0.4082055359F, 0.4101540034F,
  157516. 0.4121037117F, 0.4140546246F, 0.4160067058F, 0.4179599190F,
  157517. 0.4199142277F, 0.4218695956F, 0.4238259861F, 0.4257833627F,
  157518. 0.4277416888F, 0.4297009279F, 0.4316610433F, 0.4336219983F,
  157519. 0.4355837562F, 0.4375462803F, 0.4395095337F, 0.4414734797F,
  157520. 0.4434380815F, 0.4454033021F, 0.4473691046F, 0.4493354521F,
  157521. 0.4513023078F, 0.4532696345F, 0.4552373954F, 0.4572055533F,
  157522. 0.4591740713F, 0.4611429123F, 0.4631120393F, 0.4650814151F,
  157523. 0.4670510028F, 0.4690207650F, 0.4709906649F, 0.4729606651F,
  157524. 0.4749307287F, 0.4769008185F, 0.4788708972F, 0.4808409279F,
  157525. 0.4828108732F, 0.4847806962F, 0.4867503597F, 0.4887198264F,
  157526. 0.4906890593F, 0.4926580213F, 0.4946266753F, 0.4965949840F,
  157527. 0.4985629105F, 0.5005304176F, 0.5024974683F, 0.5044640255F,
  157528. 0.5064300522F, 0.5083955114F, 0.5103603659F, 0.5123245790F,
  157529. 0.5142881136F, 0.5162509328F, 0.5182129997F, 0.5201742774F,
  157530. 0.5221347290F, 0.5240943178F, 0.5260530070F, 0.5280107598F,
  157531. 0.5299675395F, 0.5319233095F, 0.5338780330F, 0.5358316736F,
  157532. 0.5377841946F, 0.5397355596F, 0.5416857320F, 0.5436346755F,
  157533. 0.5455823538F, 0.5475287304F, 0.5494737691F, 0.5514174337F,
  157534. 0.5533596881F, 0.5553004962F, 0.5572398218F, 0.5591776291F,
  157535. 0.5611138821F, 0.5630485449F, 0.5649815818F, 0.5669129570F,
  157536. 0.5688426349F, 0.5707705799F, 0.5726967564F, 0.5746211290F,
  157537. 0.5765436624F, 0.5784643212F, 0.5803830702F, 0.5822998743F,
  157538. 0.5842146984F, 0.5861275076F, 0.5880382669F, 0.5899469416F,
  157539. 0.5918534968F, 0.5937578981F, 0.5956601107F, 0.5975601004F,
  157540. 0.5994578326F, 0.6013532732F, 0.6032463880F, 0.6051371429F,
  157541. 0.6070255039F, 0.6089114372F, 0.6107949090F, 0.6126758856F,
  157542. 0.6145543334F, 0.6164302191F, 0.6183035092F, 0.6201741706F,
  157543. 0.6220421700F, 0.6239074745F, 0.6257700513F, 0.6276298674F,
  157544. 0.6294868903F, 0.6313410873F, 0.6331924262F, 0.6350408745F,
  157545. 0.6368864001F, 0.6387289710F, 0.6405685552F, 0.6424051209F,
  157546. 0.6442386364F, 0.6460690702F, 0.6478963910F, 0.6497205673F,
  157547. 0.6515415682F, 0.6533593625F, 0.6551739194F, 0.6569852082F,
  157548. 0.6587931984F, 0.6605978593F, 0.6623991609F, 0.6641970728F,
  157549. 0.6659915652F, 0.6677826081F, 0.6695701718F, 0.6713542268F,
  157550. 0.6731347437F, 0.6749116932F, 0.6766850461F, 0.6784547736F,
  157551. 0.6802208469F, 0.6819832374F, 0.6837419164F, 0.6854968559F,
  157552. 0.6872480275F, 0.6889954034F, 0.6907389556F, 0.6924786566F,
  157553. 0.6942144788F, 0.6959463950F, 0.6976743780F, 0.6993984008F,
  157554. 0.7011184365F, 0.7028344587F, 0.7045464407F, 0.7062543564F,
  157555. 0.7079581796F, 0.7096578844F, 0.7113534450F, 0.7130448359F,
  157556. 0.7147320316F, 0.7164150070F, 0.7180937371F, 0.7197681970F,
  157557. 0.7214383620F, 0.7231042077F, 0.7247657098F, 0.7264228443F,
  157558. 0.7280755871F, 0.7297239147F, 0.7313678035F, 0.7330072301F,
  157559. 0.7346421715F, 0.7362726046F, 0.7378985069F, 0.7395198556F,
  157560. 0.7411366285F, 0.7427488034F, 0.7443563584F, 0.7459592717F,
  157561. 0.7475575218F, 0.7491510873F, 0.7507399471F, 0.7523240803F,
  157562. 0.7539034661F, 0.7554780839F, 0.7570479136F, 0.7586129349F,
  157563. 0.7601731279F, 0.7617284730F, 0.7632789506F, 0.7648245416F,
  157564. 0.7663652267F, 0.7679009872F, 0.7694318044F, 0.7709576599F,
  157565. 0.7724785354F, 0.7739944130F, 0.7755052749F, 0.7770111035F,
  157566. 0.7785118815F, 0.7800075916F, 0.7814982170F, 0.7829837410F,
  157567. 0.7844641472F, 0.7859394191F, 0.7874095408F, 0.7888744965F,
  157568. 0.7903342706F, 0.7917888476F, 0.7932382124F, 0.7946823501F,
  157569. 0.7961212460F, 0.7975548855F, 0.7989832544F, 0.8004063386F,
  157570. 0.8018241244F, 0.8032365981F, 0.8046437463F, 0.8060455560F,
  157571. 0.8074420141F, 0.8088331080F, 0.8102188253F, 0.8115991536F,
  157572. 0.8129740810F, 0.8143435957F, 0.8157076861F, 0.8170663409F,
  157573. 0.8184195489F, 0.8197672994F, 0.8211095817F, 0.8224463853F,
  157574. 0.8237777001F, 0.8251035161F, 0.8264238235F, 0.8277386129F,
  157575. 0.8290478750F, 0.8303516008F, 0.8316497814F, 0.8329424083F,
  157576. 0.8342294731F, 0.8355109677F, 0.8367868841F, 0.8380572148F,
  157577. 0.8393219523F, 0.8405810893F, 0.8418346190F, 0.8430825345F,
  157578. 0.8443248294F, 0.8455614974F, 0.8467925323F, 0.8480179285F,
  157579. 0.8492376802F, 0.8504517822F, 0.8516602292F, 0.8528630164F,
  157580. 0.8540601391F, 0.8552515928F, 0.8564373733F, 0.8576174766F,
  157581. 0.8587918990F, 0.8599606368F, 0.8611236868F, 0.8622810460F,
  157582. 0.8634327113F, 0.8645786802F, 0.8657189504F, 0.8668535195F,
  157583. 0.8679823857F, 0.8691055472F, 0.8702230025F, 0.8713347503F,
  157584. 0.8724407896F, 0.8735411194F, 0.8746357394F, 0.8757246489F,
  157585. 0.8768078479F, 0.8778853364F, 0.8789571146F, 0.8800231832F,
  157586. 0.8810835427F, 0.8821381942F, 0.8831871387F, 0.8842303777F,
  157587. 0.8852679127F, 0.8862997456F, 0.8873258784F, 0.8883463132F,
  157588. 0.8893610527F, 0.8903700994F, 0.8913734562F, 0.8923711263F,
  157589. 0.8933631129F, 0.8943494196F, 0.8953300500F, 0.8963050083F,
  157590. 0.8972742985F, 0.8982379249F, 0.8991958922F, 0.9001482052F,
  157591. 0.9010948688F, 0.9020358883F, 0.9029712690F, 0.9039010165F,
  157592. 0.9048251367F, 0.9057436357F, 0.9066565195F, 0.9075637946F,
  157593. 0.9084654678F, 0.9093615456F, 0.9102520353F, 0.9111369440F,
  157594. 0.9120162792F, 0.9128900484F, 0.9137582595F, 0.9146209204F,
  157595. 0.9154780394F, 0.9163296248F, 0.9171756853F, 0.9180162296F,
  157596. 0.9188512667F, 0.9196808057F, 0.9205048559F, 0.9213234270F,
  157597. 0.9221365285F, 0.9229441704F, 0.9237463629F, 0.9245431160F,
  157598. 0.9253344404F, 0.9261203465F, 0.9269008453F, 0.9276759477F,
  157599. 0.9284456648F, 0.9292100080F, 0.9299689889F, 0.9307226190F,
  157600. 0.9314709103F, 0.9322138747F, 0.9329515245F, 0.9336838721F,
  157601. 0.9344109300F, 0.9351327108F, 0.9358492275F, 0.9365604931F,
  157602. 0.9372665208F, 0.9379673239F, 0.9386629160F, 0.9393533107F,
  157603. 0.9400385220F, 0.9407185637F, 0.9413934501F, 0.9420631954F,
  157604. 0.9427278141F, 0.9433873208F, 0.9440417304F, 0.9446910576F,
  157605. 0.9453353176F, 0.9459745255F, 0.9466086968F, 0.9472378469F,
  157606. 0.9478619915F, 0.9484811463F, 0.9490953274F, 0.9497045506F,
  157607. 0.9503088323F, 0.9509081888F, 0.9515026365F, 0.9520921921F,
  157608. 0.9526768723F, 0.9532566940F, 0.9538316742F, 0.9544018300F,
  157609. 0.9549671786F, 0.9555277375F, 0.9560835241F, 0.9566345562F,
  157610. 0.9571808513F, 0.9577224275F, 0.9582593027F, 0.9587914949F,
  157611. 0.9593190225F, 0.9598419038F, 0.9603601571F, 0.9608738012F,
  157612. 0.9613828546F, 0.9618873361F, 0.9623872646F, 0.9628826591F,
  157613. 0.9633735388F, 0.9638599227F, 0.9643418303F, 0.9648192808F,
  157614. 0.9652922939F, 0.9657608890F, 0.9662250860F, 0.9666849046F,
  157615. 0.9671403646F, 0.9675914861F, 0.9680382891F, 0.9684807937F,
  157616. 0.9689190202F, 0.9693529890F, 0.9697827203F, 0.9702082347F,
  157617. 0.9706295529F, 0.9710466953F, 0.9714596828F, 0.9718685362F,
  157618. 0.9722732762F, 0.9726739240F, 0.9730705005F, 0.9734630267F,
  157619. 0.9738515239F, 0.9742360134F, 0.9746165163F, 0.9749930540F,
  157620. 0.9753656481F, 0.9757343198F, 0.9760990909F, 0.9764599829F,
  157621. 0.9768170175F, 0.9771702164F, 0.9775196013F, 0.9778651941F,
  157622. 0.9782070167F, 0.9785450909F, 0.9788794388F, 0.9792100824F,
  157623. 0.9795370437F, 0.9798603449F, 0.9801800080F, 0.9804960554F,
  157624. 0.9808085092F, 0.9811173916F, 0.9814227251F, 0.9817245318F,
  157625. 0.9820228343F, 0.9823176549F, 0.9826090160F, 0.9828969402F,
  157626. 0.9831814498F, 0.9834625674F, 0.9837403156F, 0.9840147169F,
  157627. 0.9842857939F, 0.9845535692F, 0.9848180654F, 0.9850793052F,
  157628. 0.9853373113F, 0.9855921062F, 0.9858437127F, 0.9860921535F,
  157629. 0.9863374512F, 0.9865796287F, 0.9868187085F, 0.9870547136F,
  157630. 0.9872876664F, 0.9875175899F, 0.9877445067F, 0.9879684396F,
  157631. 0.9881894112F, 0.9884074444F, 0.9886225619F, 0.9888347863F,
  157632. 0.9890441404F, 0.9892506468F, 0.9894543284F, 0.9896552077F,
  157633. 0.9898533074F, 0.9900486502F, 0.9902412587F, 0.9904311555F,
  157634. 0.9906183633F, 0.9908029045F, 0.9909848019F, 0.9911640779F,
  157635. 0.9913407550F, 0.9915148557F, 0.9916864025F, 0.9918554179F,
  157636. 0.9920219241F, 0.9921859437F, 0.9923474989F, 0.9925066120F,
  157637. 0.9926633054F, 0.9928176012F, 0.9929695218F, 0.9931190891F,
  157638. 0.9932663254F, 0.9934112527F, 0.9935538932F, 0.9936942686F,
  157639. 0.9938324012F, 0.9939683126F, 0.9941020248F, 0.9942335597F,
  157640. 0.9943629388F, 0.9944901841F, 0.9946153170F, 0.9947383593F,
  157641. 0.9948593325F, 0.9949782579F, 0.9950951572F, 0.9952100516F,
  157642. 0.9953229625F, 0.9954339111F, 0.9955429186F, 0.9956500062F,
  157643. 0.9957551948F, 0.9958585056F, 0.9959599593F, 0.9960595769F,
  157644. 0.9961573792F, 0.9962533869F, 0.9963476206F, 0.9964401009F,
  157645. 0.9965308483F, 0.9966198833F, 0.9967072261F, 0.9967928971F,
  157646. 0.9968769164F, 0.9969593041F, 0.9970400804F, 0.9971192651F,
  157647. 0.9971968781F, 0.9972729391F, 0.9973474680F, 0.9974204842F,
  157648. 0.9974920074F, 0.9975620569F, 0.9976306521F, 0.9976978122F,
  157649. 0.9977635565F, 0.9978279039F, 0.9978908736F, 0.9979524842F,
  157650. 0.9980127547F, 0.9980717037F, 0.9981293499F, 0.9981857116F,
  157651. 0.9982408073F, 0.9982946554F, 0.9983472739F, 0.9983986810F,
  157652. 0.9984488947F, 0.9984979328F, 0.9985458132F, 0.9985925534F,
  157653. 0.9986381711F, 0.9986826838F, 0.9987261086F, 0.9987684630F,
  157654. 0.9988097640F, 0.9988500286F, 0.9988892738F, 0.9989275163F,
  157655. 0.9989647727F, 0.9990010597F, 0.9990363938F, 0.9990707911F,
  157656. 0.9991042679F, 0.9991368404F, 0.9991685244F, 0.9991993358F,
  157657. 0.9992292905F, 0.9992584038F, 0.9992866914F, 0.9993141686F,
  157658. 0.9993408506F, 0.9993667526F, 0.9993918895F, 0.9994162761F,
  157659. 0.9994399273F, 0.9994628576F, 0.9994850815F, 0.9995066133F,
  157660. 0.9995274672F, 0.9995476574F, 0.9995671978F, 0.9995861021F,
  157661. 0.9996043841F, 0.9996220573F, 0.9996391352F, 0.9996556310F,
  157662. 0.9996715579F, 0.9996869288F, 0.9997017568F, 0.9997160543F,
  157663. 0.9997298342F, 0.9997431088F, 0.9997558905F, 0.9997681914F,
  157664. 0.9997800236F, 0.9997913990F, 0.9998023292F, 0.9998128261F,
  157665. 0.9998229009F, 0.9998325650F, 0.9998418296F, 0.9998507058F,
  157666. 0.9998592044F, 0.9998673362F, 0.9998751117F, 0.9998825415F,
  157667. 0.9998896358F, 0.9998964047F, 0.9999028584F, 0.9999090066F,
  157668. 0.9999148590F, 0.9999204253F, 0.9999257148F, 0.9999307368F,
  157669. 0.9999355003F, 0.9999400144F, 0.9999442878F, 0.9999483293F,
  157670. 0.9999521472F, 0.9999557499F, 0.9999591457F, 0.9999623426F,
  157671. 0.9999653483F, 0.9999681708F, 0.9999708175F, 0.9999732959F,
  157672. 0.9999756132F, 0.9999777765F, 0.9999797928F, 0.9999816688F,
  157673. 0.9999834113F, 0.9999850266F, 0.9999865211F, 0.9999879009F,
  157674. 0.9999891721F, 0.9999903405F, 0.9999914118F, 0.9999923914F,
  157675. 0.9999932849F, 0.9999940972F, 0.9999948336F, 0.9999954989F,
  157676. 0.9999960978F, 0.9999966349F, 0.9999971146F, 0.9999975411F,
  157677. 0.9999979185F, 0.9999982507F, 0.9999985414F, 0.9999987944F,
  157678. 0.9999990129F, 0.9999992003F, 0.9999993596F, 0.9999994939F,
  157679. 0.9999996059F, 0.9999996981F, 0.9999997732F, 0.9999998333F,
  157680. 0.9999998805F, 0.9999999170F, 0.9999999444F, 0.9999999643F,
  157681. 0.9999999784F, 0.9999999878F, 0.9999999937F, 0.9999999972F,
  157682. 0.9999999990F, 0.9999999997F, 1.0000000000F, 1.0000000000F,
  157683. };
  157684. static float vwin4096[2048] = {
  157685. 0.0000002310F, 0.0000020791F, 0.0000057754F, 0.0000113197F,
  157686. 0.0000187121F, 0.0000279526F, 0.0000390412F, 0.0000519777F,
  157687. 0.0000667623F, 0.0000833949F, 0.0001018753F, 0.0001222036F,
  157688. 0.0001443798F, 0.0001684037F, 0.0001942754F, 0.0002219947F,
  157689. 0.0002515616F, 0.0002829761F, 0.0003162380F, 0.0003513472F,
  157690. 0.0003883038F, 0.0004271076F, 0.0004677584F, 0.0005102563F,
  157691. 0.0005546011F, 0.0006007928F, 0.0006488311F, 0.0006987160F,
  157692. 0.0007504474F, 0.0008040251F, 0.0008594490F, 0.0009167191F,
  157693. 0.0009758351F, 0.0010367969F, 0.0010996044F, 0.0011642574F,
  157694. 0.0012307558F, 0.0012990994F, 0.0013692880F, 0.0014413216F,
  157695. 0.0015151998F, 0.0015909226F, 0.0016684898F, 0.0017479011F,
  157696. 0.0018291565F, 0.0019122556F, 0.0019971983F, 0.0020839845F,
  157697. 0.0021726138F, 0.0022630861F, 0.0023554012F, 0.0024495588F,
  157698. 0.0025455588F, 0.0026434008F, 0.0027430847F, 0.0028446103F,
  157699. 0.0029479772F, 0.0030531853F, 0.0031602342F, 0.0032691238F,
  157700. 0.0033798538F, 0.0034924239F, 0.0036068338F, 0.0037230833F,
  157701. 0.0038411721F, 0.0039610999F, 0.0040828664F, 0.0042064714F,
  157702. 0.0043319145F, 0.0044591954F, 0.0045883139F, 0.0047192696F,
  157703. 0.0048520622F, 0.0049866914F, 0.0051231569F, 0.0052614583F,
  157704. 0.0054015953F, 0.0055435676F, 0.0056873748F, 0.0058330166F,
  157705. 0.0059804926F, 0.0061298026F, 0.0062809460F, 0.0064339226F,
  157706. 0.0065887320F, 0.0067453738F, 0.0069038476F, 0.0070641531F,
  157707. 0.0072262899F, 0.0073902575F, 0.0075560556F, 0.0077236838F,
  157708. 0.0078931417F, 0.0080644288F, 0.0082375447F, 0.0084124891F,
  157709. 0.0085892615F, 0.0087678614F, 0.0089482885F, 0.0091305422F,
  157710. 0.0093146223F, 0.0095005281F, 0.0096882592F, 0.0098778153F,
  157711. 0.0100691958F, 0.0102624002F, 0.0104574281F, 0.0106542791F,
  157712. 0.0108529525F, 0.0110534480F, 0.0112557651F, 0.0114599032F,
  157713. 0.0116658618F, 0.0118736405F, 0.0120832387F, 0.0122946560F,
  157714. 0.0125078917F, 0.0127229454F, 0.0129398166F, 0.0131585046F,
  157715. 0.0133790090F, 0.0136013292F, 0.0138254647F, 0.0140514149F,
  157716. 0.0142791792F, 0.0145087572F, 0.0147401481F, 0.0149733515F,
  157717. 0.0152083667F, 0.0154451932F, 0.0156838304F, 0.0159242777F,
  157718. 0.0161665345F, 0.0164106001F, 0.0166564741F, 0.0169041557F,
  157719. 0.0171536443F, 0.0174049393F, 0.0176580401F, 0.0179129461F,
  157720. 0.0181696565F, 0.0184281708F, 0.0186884883F, 0.0189506084F,
  157721. 0.0192145303F, 0.0194802535F, 0.0197477772F, 0.0200171008F,
  157722. 0.0202882236F, 0.0205611449F, 0.0208358639F, 0.0211123801F,
  157723. 0.0213906927F, 0.0216708011F, 0.0219527043F, 0.0222364019F,
  157724. 0.0225218930F, 0.0228091769F, 0.0230982529F, 0.0233891203F,
  157725. 0.0236817782F, 0.0239762259F, 0.0242724628F, 0.0245704880F,
  157726. 0.0248703007F, 0.0251719002F, 0.0254752858F, 0.0257804565F,
  157727. 0.0260874117F, 0.0263961506F, 0.0267066722F, 0.0270189760F,
  157728. 0.0273330609F, 0.0276489263F, 0.0279665712F, 0.0282859949F,
  157729. 0.0286071966F, 0.0289301753F, 0.0292549303F, 0.0295814607F,
  157730. 0.0299097656F, 0.0302398442F, 0.0305716957F, 0.0309053191F,
  157731. 0.0312407135F, 0.0315778782F, 0.0319168122F, 0.0322575145F,
  157732. 0.0325999844F, 0.0329442209F, 0.0332902231F, 0.0336379900F,
  157733. 0.0339875208F, 0.0343388146F, 0.0346918703F, 0.0350466871F,
  157734. 0.0354032640F, 0.0357616000F, 0.0361216943F, 0.0364835458F,
  157735. 0.0368471535F, 0.0372125166F, 0.0375796339F, 0.0379485046F,
  157736. 0.0383191276F, 0.0386915020F, 0.0390656267F, 0.0394415008F,
  157737. 0.0398191231F, 0.0401984927F, 0.0405796086F, 0.0409624698F,
  157738. 0.0413470751F, 0.0417334235F, 0.0421215141F, 0.0425113457F,
  157739. 0.0429029172F, 0.0432962277F, 0.0436912760F, 0.0440880610F,
  157740. 0.0444865817F, 0.0448868370F, 0.0452888257F, 0.0456925468F,
  157741. 0.0460979992F, 0.0465051816F, 0.0469140931F, 0.0473247325F,
  157742. 0.0477370986F, 0.0481511902F, 0.0485670064F, 0.0489845458F,
  157743. 0.0494038074F, 0.0498247899F, 0.0502474922F, 0.0506719131F,
  157744. 0.0510980514F, 0.0515259060F, 0.0519554756F, 0.0523867590F,
  157745. 0.0528197550F, 0.0532544624F, 0.0536908800F, 0.0541290066F,
  157746. 0.0545688408F, 0.0550103815F, 0.0554536274F, 0.0558985772F,
  157747. 0.0563452297F, 0.0567935837F, 0.0572436377F, 0.0576953907F,
  157748. 0.0581488412F, 0.0586039880F, 0.0590608297F, 0.0595193651F,
  157749. 0.0599795929F, 0.0604415117F, 0.0609051202F, 0.0613704170F,
  157750. 0.0618374009F, 0.0623060704F, 0.0627764243F, 0.0632484611F,
  157751. 0.0637221795F, 0.0641975781F, 0.0646746555F, 0.0651534104F,
  157752. 0.0656338413F, 0.0661159469F, 0.0665997257F, 0.0670851763F,
  157753. 0.0675722973F, 0.0680610873F, 0.0685515448F, 0.0690436684F,
  157754. 0.0695374567F, 0.0700329081F, 0.0705300213F, 0.0710287947F,
  157755. 0.0715292269F, 0.0720313163F, 0.0725350616F, 0.0730404612F,
  157756. 0.0735475136F, 0.0740562172F, 0.0745665707F, 0.0750785723F,
  157757. 0.0755922207F, 0.0761075143F, 0.0766244515F, 0.0771430307F,
  157758. 0.0776632505F, 0.0781851092F, 0.0787086052F, 0.0792337371F,
  157759. 0.0797605032F, 0.0802889018F, 0.0808189315F, 0.0813505905F,
  157760. 0.0818838773F, 0.0824187903F, 0.0829553277F, 0.0834934881F,
  157761. 0.0840332697F, 0.0845746708F, 0.0851176899F, 0.0856623252F,
  157762. 0.0862085751F, 0.0867564379F, 0.0873059119F, 0.0878569954F,
  157763. 0.0884096867F, 0.0889639840F, 0.0895198858F, 0.0900773902F,
  157764. 0.0906364955F, 0.0911972000F, 0.0917595019F, 0.0923233995F,
  157765. 0.0928888909F, 0.0934559745F, 0.0940246485F, 0.0945949110F,
  157766. 0.0951667604F, 0.0957401946F, 0.0963152121F, 0.0968918109F,
  157767. 0.0974699893F, 0.0980497454F, 0.0986310773F, 0.0992139832F,
  157768. 0.0997984614F, 0.1003845098F, 0.1009721267F, 0.1015613101F,
  157769. 0.1021520582F, 0.1027443692F, 0.1033382410F, 0.1039336718F,
  157770. 0.1045306597F, 0.1051292027F, 0.1057292990F, 0.1063309466F,
  157771. 0.1069341435F, 0.1075388878F, 0.1081451776F, 0.1087530108F,
  157772. 0.1093623856F, 0.1099732998F, 0.1105857516F, 0.1111997389F,
  157773. 0.1118152597F, 0.1124323121F, 0.1130508939F, 0.1136710032F,
  157774. 0.1142926379F, 0.1149157960F, 0.1155404755F, 0.1161666742F,
  157775. 0.1167943901F, 0.1174236211F, 0.1180543652F, 0.1186866202F,
  157776. 0.1193203841F, 0.1199556548F, 0.1205924300F, 0.1212307078F,
  157777. 0.1218704860F, 0.1225117624F, 0.1231545349F, 0.1237988013F,
  157778. 0.1244445596F, 0.1250918074F, 0.1257405427F, 0.1263907632F,
  157779. 0.1270424667F, 0.1276956512F, 0.1283503142F, 0.1290064537F,
  157780. 0.1296640674F, 0.1303231530F, 0.1309837084F, 0.1316457312F,
  157781. 0.1323092193F, 0.1329741703F, 0.1336405820F, 0.1343084520F,
  157782. 0.1349777782F, 0.1356485582F, 0.1363207897F, 0.1369944704F,
  157783. 0.1376695979F, 0.1383461700F, 0.1390241842F, 0.1397036384F,
  157784. 0.1403845300F, 0.1410668567F, 0.1417506162F, 0.1424358061F,
  157785. 0.1431224240F, 0.1438104674F, 0.1444999341F, 0.1451908216F,
  157786. 0.1458831274F, 0.1465768492F, 0.1472719844F, 0.1479685308F,
  157787. 0.1486664857F, 0.1493658468F, 0.1500666115F, 0.1507687775F,
  157788. 0.1514723422F, 0.1521773031F, 0.1528836577F, 0.1535914035F,
  157789. 0.1543005380F, 0.1550110587F, 0.1557229631F, 0.1564362485F,
  157790. 0.1571509124F, 0.1578669524F, 0.1585843657F, 0.1593031499F,
  157791. 0.1600233024F, 0.1607448205F, 0.1614677017F, 0.1621919433F,
  157792. 0.1629175428F, 0.1636444975F, 0.1643728047F, 0.1651024619F,
  157793. 0.1658334665F, 0.1665658156F, 0.1672995067F, 0.1680345371F,
  157794. 0.1687709041F, 0.1695086050F, 0.1702476372F, 0.1709879978F,
  157795. 0.1717296843F, 0.1724726938F, 0.1732170237F, 0.1739626711F,
  157796. 0.1747096335F, 0.1754579079F, 0.1762074916F, 0.1769583819F,
  157797. 0.1777105760F, 0.1784640710F, 0.1792188642F, 0.1799749529F,
  157798. 0.1807323340F, 0.1814910049F, 0.1822509628F, 0.1830122046F,
  157799. 0.1837747277F, 0.1845385292F, 0.1853036062F, 0.1860699558F,
  157800. 0.1868375751F, 0.1876064613F, 0.1883766114F, 0.1891480226F,
  157801. 0.1899206919F, 0.1906946164F, 0.1914697932F, 0.1922462194F,
  157802. 0.1930238919F, 0.1938028079F, 0.1945829643F, 0.1953643583F,
  157803. 0.1961469868F, 0.1969308468F, 0.1977159353F, 0.1985022494F,
  157804. 0.1992897859F, 0.2000785420F, 0.2008685145F, 0.2016597005F,
  157805. 0.2024520968F, 0.2032457005F, 0.2040405084F, 0.2048365175F,
  157806. 0.2056337247F, 0.2064321269F, 0.2072317211F, 0.2080325041F,
  157807. 0.2088344727F, 0.2096376240F, 0.2104419547F, 0.2112474618F,
  157808. 0.2120541420F, 0.2128619923F, 0.2136710094F, 0.2144811902F,
  157809. 0.2152925315F, 0.2161050301F, 0.2169186829F, 0.2177334866F,
  157810. 0.2185494381F, 0.2193665340F, 0.2201847712F, 0.2210041465F,
  157811. 0.2218246565F, 0.2226462981F, 0.2234690680F, 0.2242929629F,
  157812. 0.2251179796F, 0.2259441147F, 0.2267713650F, 0.2275997272F,
  157813. 0.2284291979F, 0.2292597739F, 0.2300914518F, 0.2309242283F,
  157814. 0.2317581001F, 0.2325930638F, 0.2334291160F, 0.2342662534F,
  157815. 0.2351044727F, 0.2359437703F, 0.2367841431F, 0.2376255875F,
  157816. 0.2384681001F, 0.2393116776F, 0.2401563165F, 0.2410020134F,
  157817. 0.2418487649F, 0.2426965675F, 0.2435454178F, 0.2443953122F,
  157818. 0.2452462474F, 0.2460982199F, 0.2469512262F, 0.2478052628F,
  157819. 0.2486603262F, 0.2495164129F, 0.2503735194F, 0.2512316421F,
  157820. 0.2520907776F, 0.2529509222F, 0.2538120726F, 0.2546742250F,
  157821. 0.2555373760F, 0.2564015219F, 0.2572666593F, 0.2581327845F,
  157822. 0.2589998939F, 0.2598679840F, 0.2607370510F, 0.2616070916F,
  157823. 0.2624781019F, 0.2633500783F, 0.2642230173F, 0.2650969152F,
  157824. 0.2659717684F, 0.2668475731F, 0.2677243257F, 0.2686020226F,
  157825. 0.2694806601F, 0.2703602344F, 0.2712407419F, 0.2721221789F,
  157826. 0.2730045417F, 0.2738878265F, 0.2747720297F, 0.2756571474F,
  157827. 0.2765431760F, 0.2774301117F, 0.2783179508F, 0.2792066895F,
  157828. 0.2800963240F, 0.2809868505F, 0.2818782654F, 0.2827705647F,
  157829. 0.2836637447F, 0.2845578016F, 0.2854527315F, 0.2863485307F,
  157830. 0.2872451953F, 0.2881427215F, 0.2890411055F, 0.2899403433F,
  157831. 0.2908404312F, 0.2917413654F, 0.2926431418F, 0.2935457567F,
  157832. 0.2944492061F, 0.2953534863F, 0.2962585932F, 0.2971645230F,
  157833. 0.2980712717F, 0.2989788356F, 0.2998872105F, 0.3007963927F,
  157834. 0.3017063781F, 0.3026171629F, 0.3035287430F, 0.3044411145F,
  157835. 0.3053542736F, 0.3062682161F, 0.3071829381F, 0.3080984356F,
  157836. 0.3090147047F, 0.3099317413F, 0.3108495414F, 0.3117681011F,
  157837. 0.3126874163F, 0.3136074830F, 0.3145282972F, 0.3154498548F,
  157838. 0.3163721517F, 0.3172951841F, 0.3182189477F, 0.3191434385F,
  157839. 0.3200686525F, 0.3209945856F, 0.3219212336F, 0.3228485927F,
  157840. 0.3237766585F, 0.3247054271F, 0.3256348943F, 0.3265650560F,
  157841. 0.3274959081F, 0.3284274465F, 0.3293596671F, 0.3302925657F,
  157842. 0.3312261382F, 0.3321603804F, 0.3330952882F, 0.3340308574F,
  157843. 0.3349670838F, 0.3359039634F, 0.3368414919F, 0.3377796651F,
  157844. 0.3387184789F, 0.3396579290F, 0.3405980113F, 0.3415387216F,
  157845. 0.3424800556F, 0.3434220091F, 0.3443645779F, 0.3453077578F,
  157846. 0.3462515446F, 0.3471959340F, 0.3481409217F, 0.3490865036F,
  157847. 0.3500326754F, 0.3509794328F, 0.3519267715F, 0.3528746873F,
  157848. 0.3538231759F, 0.3547722330F, 0.3557218544F, 0.3566720357F,
  157849. 0.3576227727F, 0.3585740610F, 0.3595258964F, 0.3604782745F,
  157850. 0.3614311910F, 0.3623846417F, 0.3633386221F, 0.3642931280F,
  157851. 0.3652481549F, 0.3662036987F, 0.3671597548F, 0.3681163191F,
  157852. 0.3690733870F, 0.3700309544F, 0.3709890167F, 0.3719475696F,
  157853. 0.3729066089F, 0.3738661299F, 0.3748261285F, 0.3757866002F,
  157854. 0.3767475406F, 0.3777089453F, 0.3786708100F, 0.3796331302F,
  157855. 0.3805959014F, 0.3815591194F, 0.3825227796F, 0.3834868777F,
  157856. 0.3844514093F, 0.3854163698F, 0.3863817549F, 0.3873475601F,
  157857. 0.3883137810F, 0.3892804131F, 0.3902474521F, 0.3912148933F,
  157858. 0.3921827325F, 0.3931509650F, 0.3941195865F, 0.3950885925F,
  157859. 0.3960579785F, 0.3970277400F, 0.3979978725F, 0.3989683716F,
  157860. 0.3999392328F, 0.4009104516F, 0.4018820234F, 0.4028539438F,
  157861. 0.4038262084F, 0.4047988125F, 0.4057717516F, 0.4067450214F,
  157862. 0.4077186172F, 0.4086925345F, 0.4096667688F, 0.4106413155F,
  157863. 0.4116161703F, 0.4125913284F, 0.4135667854F, 0.4145425368F,
  157864. 0.4155185780F, 0.4164949044F, 0.4174715116F, 0.4184483949F,
  157865. 0.4194255498F, 0.4204029718F, 0.4213806563F, 0.4223585987F,
  157866. 0.4233367946F, 0.4243152392F, 0.4252939281F, 0.4262728566F,
  157867. 0.4272520202F, 0.4282314144F, 0.4292110345F, 0.4301908760F,
  157868. 0.4311709343F, 0.4321512047F, 0.4331316828F, 0.4341123639F,
  157869. 0.4350932435F, 0.4360743168F, 0.4370555794F, 0.4380370267F,
  157870. 0.4390186540F, 0.4400004567F, 0.4409824303F, 0.4419645701F,
  157871. 0.4429468716F, 0.4439293300F, 0.4449119409F, 0.4458946996F,
  157872. 0.4468776014F, 0.4478606418F, 0.4488438162F, 0.4498271199F,
  157873. 0.4508105483F, 0.4517940967F, 0.4527777607F, 0.4537615355F,
  157874. 0.4547454165F, 0.4557293991F, 0.4567134786F, 0.4576976505F,
  157875. 0.4586819101F, 0.4596662527F, 0.4606506738F, 0.4616351687F,
  157876. 0.4626197328F, 0.4636043614F, 0.4645890499F, 0.4655737936F,
  157877. 0.4665585880F, 0.4675434284F, 0.4685283101F, 0.4695132286F,
  157878. 0.4704981791F, 0.4714831570F, 0.4724681577F, 0.4734531766F,
  157879. 0.4744382089F, 0.4754232501F, 0.4764082956F, 0.4773933406F,
  157880. 0.4783783806F, 0.4793634108F, 0.4803484267F, 0.4813334237F,
  157881. 0.4823183969F, 0.4833033419F, 0.4842882540F, 0.4852731285F,
  157882. 0.4862579608F, 0.4872427462F, 0.4882274802F, 0.4892121580F,
  157883. 0.4901967751F, 0.4911813267F, 0.4921658083F, 0.4931502151F,
  157884. 0.4941345427F, 0.4951187863F, 0.4961029412F, 0.4970870029F,
  157885. 0.4980709667F, 0.4990548280F, 0.5000385822F, 0.5010222245F,
  157886. 0.5020057505F, 0.5029891553F, 0.5039724345F, 0.5049555834F,
  157887. 0.5059385973F, 0.5069214716F, 0.5079042018F, 0.5088867831F,
  157888. 0.5098692110F, 0.5108514808F, 0.5118335879F, 0.5128155277F,
  157889. 0.5137972956F, 0.5147788869F, 0.5157602971F, 0.5167415215F,
  157890. 0.5177225555F, 0.5187033945F, 0.5196840339F, 0.5206644692F,
  157891. 0.5216446956F, 0.5226247086F, 0.5236045035F, 0.5245840759F,
  157892. 0.5255634211F, 0.5265425344F, 0.5275214114F, 0.5285000474F,
  157893. 0.5294784378F, 0.5304565781F, 0.5314344637F, 0.5324120899F,
  157894. 0.5333894522F, 0.5343665461F, 0.5353433670F, 0.5363199102F,
  157895. 0.5372961713F, 0.5382721457F, 0.5392478287F, 0.5402232159F,
  157896. 0.5411983027F, 0.5421730845F, 0.5431475569F, 0.5441217151F,
  157897. 0.5450955548F, 0.5460690714F, 0.5470422602F, 0.5480151169F,
  157898. 0.5489876368F, 0.5499598155F, 0.5509316484F, 0.5519031310F,
  157899. 0.5528742587F, 0.5538450271F, 0.5548154317F, 0.5557854680F,
  157900. 0.5567551314F, 0.5577244174F, 0.5586933216F, 0.5596618395F,
  157901. 0.5606299665F, 0.5615976983F, 0.5625650302F, 0.5635319580F,
  157902. 0.5644984770F, 0.5654645828F, 0.5664302709F, 0.5673955370F,
  157903. 0.5683603765F, 0.5693247850F, 0.5702887580F, 0.5712522912F,
  157904. 0.5722153800F, 0.5731780200F, 0.5741402069F, 0.5751019362F,
  157905. 0.5760632034F, 0.5770240042F, 0.5779843341F, 0.5789441889F,
  157906. 0.5799035639F, 0.5808624549F, 0.5818208575F, 0.5827787673F,
  157907. 0.5837361800F, 0.5846930910F, 0.5856494961F, 0.5866053910F,
  157908. 0.5875607712F, 0.5885156324F, 0.5894699703F, 0.5904237804F,
  157909. 0.5913770586F, 0.5923298004F, 0.5932820016F, 0.5942336578F,
  157910. 0.5951847646F, 0.5961353179F, 0.5970853132F, 0.5980347464F,
  157911. 0.5989836131F, 0.5999319090F, 0.6008796298F, 0.6018267713F,
  157912. 0.6027733292F, 0.6037192993F, 0.6046646773F, 0.6056094589F,
  157913. 0.6065536400F, 0.6074972162F, 0.6084401833F, 0.6093825372F,
  157914. 0.6103242736F, 0.6112653884F, 0.6122058772F, 0.6131457359F,
  157915. 0.6140849604F, 0.6150235464F, 0.6159614897F, 0.6168987862F,
  157916. 0.6178354318F, 0.6187714223F, 0.6197067535F, 0.6206414213F,
  157917. 0.6215754215F, 0.6225087501F, 0.6234414028F, 0.6243733757F,
  157918. 0.6253046646F, 0.6262352654F, 0.6271651739F, 0.6280943862F,
  157919. 0.6290228982F, 0.6299507057F, 0.6308778048F, 0.6318041913F,
  157920. 0.6327298612F, 0.6336548105F, 0.6345790352F, 0.6355025312F,
  157921. 0.6364252945F, 0.6373473211F, 0.6382686070F, 0.6391891483F,
  157922. 0.6401089409F, 0.6410279808F, 0.6419462642F, 0.6428637869F,
  157923. 0.6437805452F, 0.6446965350F, 0.6456117524F, 0.6465261935F,
  157924. 0.6474398544F, 0.6483527311F, 0.6492648197F, 0.6501761165F,
  157925. 0.6510866174F, 0.6519963186F, 0.6529052162F, 0.6538133064F,
  157926. 0.6547205854F, 0.6556270492F, 0.6565326941F, 0.6574375162F,
  157927. 0.6583415117F, 0.6592446769F, 0.6601470079F, 0.6610485009F,
  157928. 0.6619491521F, 0.6628489578F, 0.6637479143F, 0.6646460177F,
  157929. 0.6655432643F, 0.6664396505F, 0.6673351724F, 0.6682298264F,
  157930. 0.6691236087F, 0.6700165157F, 0.6709085436F, 0.6717996889F,
  157931. 0.6726899478F, 0.6735793167F, 0.6744677918F, 0.6753553697F,
  157932. 0.6762420466F, 0.6771278190F, 0.6780126832F, 0.6788966357F,
  157933. 0.6797796728F, 0.6806617909F, 0.6815429866F, 0.6824232562F,
  157934. 0.6833025961F, 0.6841810030F, 0.6850584731F, 0.6859350031F,
  157935. 0.6868105894F, 0.6876852284F, 0.6885589168F, 0.6894316510F,
  157936. 0.6903034275F, 0.6911742430F, 0.6920440939F, 0.6929129769F,
  157937. 0.6937808884F, 0.6946478251F, 0.6955137837F, 0.6963787606F,
  157938. 0.6972427525F, 0.6981057560F, 0.6989677678F, 0.6998287845F,
  157939. 0.7006888028F, 0.7015478194F, 0.7024058309F, 0.7032628340F,
  157940. 0.7041188254F, 0.7049738019F, 0.7058277601F, 0.7066806969F,
  157941. 0.7075326089F, 0.7083834929F, 0.7092333457F, 0.7100821640F,
  157942. 0.7109299447F, 0.7117766846F, 0.7126223804F, 0.7134670291F,
  157943. 0.7143106273F, 0.7151531721F, 0.7159946602F, 0.7168350885F,
  157944. 0.7176744539F, 0.7185127534F, 0.7193499837F, 0.7201861418F,
  157945. 0.7210212247F, 0.7218552293F, 0.7226881526F, 0.7235199914F,
  157946. 0.7243507428F, 0.7251804039F, 0.7260089715F, 0.7268364426F,
  157947. 0.7276628144F, 0.7284880839F, 0.7293122481F, 0.7301353040F,
  157948. 0.7309572487F, 0.7317780794F, 0.7325977930F, 0.7334163868F,
  157949. 0.7342338579F, 0.7350502033F, 0.7358654202F, 0.7366795059F,
  157950. 0.7374924573F, 0.7383042718F, 0.7391149465F, 0.7399244787F,
  157951. 0.7407328655F, 0.7415401041F, 0.7423461920F, 0.7431511261F,
  157952. 0.7439549040F, 0.7447575227F, 0.7455589797F, 0.7463592723F,
  157953. 0.7471583976F, 0.7479563532F, 0.7487531363F, 0.7495487443F,
  157954. 0.7503431745F, 0.7511364244F, 0.7519284913F, 0.7527193726F,
  157955. 0.7535090658F, 0.7542975683F, 0.7550848776F, 0.7558709910F,
  157956. 0.7566559062F, 0.7574396205F, 0.7582221314F, 0.7590034366F,
  157957. 0.7597835334F, 0.7605624194F, 0.7613400923F, 0.7621165495F,
  157958. 0.7628917886F, 0.7636658072F, 0.7644386030F, 0.7652101735F,
  157959. 0.7659805164F, 0.7667496292F, 0.7675175098F, 0.7682841556F,
  157960. 0.7690495645F, 0.7698137341F, 0.7705766622F, 0.7713383463F,
  157961. 0.7720987844F, 0.7728579741F, 0.7736159132F, 0.7743725994F,
  157962. 0.7751280306F, 0.7758822046F, 0.7766351192F, 0.7773867722F,
  157963. 0.7781371614F, 0.7788862848F, 0.7796341401F, 0.7803807253F,
  157964. 0.7811260383F, 0.7818700769F, 0.7826128392F, 0.7833543230F,
  157965. 0.7840945263F, 0.7848334471F, 0.7855710833F, 0.7863074330F,
  157966. 0.7870424941F, 0.7877762647F, 0.7885087428F, 0.7892399264F,
  157967. 0.7899698137F, 0.7906984026F, 0.7914256914F, 0.7921516780F,
  157968. 0.7928763607F, 0.7935997375F, 0.7943218065F, 0.7950425661F,
  157969. 0.7957620142F, 0.7964801492F, 0.7971969692F, 0.7979124724F,
  157970. 0.7986266570F, 0.7993395214F, 0.8000510638F, 0.8007612823F,
  157971. 0.8014701754F, 0.8021777413F, 0.8028839784F, 0.8035888849F,
  157972. 0.8042924592F, 0.8049946997F, 0.8056956048F, 0.8063951727F,
  157973. 0.8070934020F, 0.8077902910F, 0.8084858381F, 0.8091800419F,
  157974. 0.8098729007F, 0.8105644130F, 0.8112545774F, 0.8119433922F,
  157975. 0.8126308561F, 0.8133169676F, 0.8140017251F, 0.8146851272F,
  157976. 0.8153671726F, 0.8160478598F, 0.8167271874F, 0.8174051539F,
  157977. 0.8180817582F, 0.8187569986F, 0.8194308741F, 0.8201033831F,
  157978. 0.8207745244F, 0.8214442966F, 0.8221126986F, 0.8227797290F,
  157979. 0.8234453865F, 0.8241096700F, 0.8247725781F, 0.8254341097F,
  157980. 0.8260942636F, 0.8267530385F, 0.8274104334F, 0.8280664470F,
  157981. 0.8287210782F, 0.8293743259F, 0.8300261889F, 0.8306766662F,
  157982. 0.8313257566F, 0.8319734591F, 0.8326197727F, 0.8332646963F,
  157983. 0.8339082288F, 0.8345503692F, 0.8351911167F, 0.8358304700F,
  157984. 0.8364684284F, 0.8371049907F, 0.8377401562F, 0.8383739238F,
  157985. 0.8390062927F, 0.8396372618F, 0.8402668305F, 0.8408949977F,
  157986. 0.8415217626F, 0.8421471245F, 0.8427710823F, 0.8433936354F,
  157987. 0.8440147830F, 0.8446345242F, 0.8452528582F, 0.8458697844F,
  157988. 0.8464853020F, 0.8470994102F, 0.8477121084F, 0.8483233958F,
  157989. 0.8489332718F, 0.8495417356F, 0.8501487866F, 0.8507544243F,
  157990. 0.8513586479F, 0.8519614568F, 0.8525628505F, 0.8531628283F,
  157991. 0.8537613897F, 0.8543585341F, 0.8549542611F, 0.8555485699F,
  157992. 0.8561414603F, 0.8567329315F, 0.8573229832F, 0.8579116149F,
  157993. 0.8584988262F, 0.8590846165F, 0.8596689855F, 0.8602519327F,
  157994. 0.8608334577F, 0.8614135603F, 0.8619922399F, 0.8625694962F,
  157995. 0.8631453289F, 0.8637197377F, 0.8642927222F, 0.8648642821F,
  157996. 0.8654344172F, 0.8660031272F, 0.8665704118F, 0.8671362708F,
  157997. 0.8677007039F, 0.8682637109F, 0.8688252917F, 0.8693854460F,
  157998. 0.8699441737F, 0.8705014745F, 0.8710573485F, 0.8716117953F,
  157999. 0.8721648150F, 0.8727164073F, 0.8732665723F, 0.8738153098F,
  158000. 0.8743626197F, 0.8749085021F, 0.8754529569F, 0.8759959840F,
  158001. 0.8765375835F, 0.8770777553F, 0.8776164996F, 0.8781538162F,
  158002. 0.8786897054F, 0.8792241670F, 0.8797572013F, 0.8802888082F,
  158003. 0.8808189880F, 0.8813477407F, 0.8818750664F, 0.8824009653F,
  158004. 0.8829254375F, 0.8834484833F, 0.8839701028F, 0.8844902961F,
  158005. 0.8850090636F, 0.8855264054F, 0.8860423218F, 0.8865568131F,
  158006. 0.8870698794F, 0.8875815212F, 0.8880917386F, 0.8886005319F,
  158007. 0.8891079016F, 0.8896138479F, 0.8901183712F, 0.8906214719F,
  158008. 0.8911231503F, 0.8916234067F, 0.8921222417F, 0.8926196556F,
  158009. 0.8931156489F, 0.8936102219F, 0.8941033752F, 0.8945951092F,
  158010. 0.8950854244F, 0.8955743212F, 0.8960618003F, 0.8965478621F,
  158011. 0.8970325071F, 0.8975157359F, 0.8979975490F, 0.8984779471F,
  158012. 0.8989569307F, 0.8994345004F, 0.8999106568F, 0.9003854005F,
  158013. 0.9008587323F, 0.9013306526F, 0.9018011623F, 0.9022702619F,
  158014. 0.9027379521F, 0.9032042337F, 0.9036691074F, 0.9041325739F,
  158015. 0.9045946339F, 0.9050552882F, 0.9055145376F, 0.9059723828F,
  158016. 0.9064288246F, 0.9068838638F, 0.9073375013F, 0.9077897379F,
  158017. 0.9082405743F, 0.9086900115F, 0.9091380503F, 0.9095846917F,
  158018. 0.9100299364F, 0.9104737854F, 0.9109162397F, 0.9113573001F,
  158019. 0.9117969675F, 0.9122352430F, 0.9126721275F, 0.9131076219F,
  158020. 0.9135417273F, 0.9139744447F, 0.9144057750F, 0.9148357194F,
  158021. 0.9152642787F, 0.9156914542F, 0.9161172468F, 0.9165416576F,
  158022. 0.9169646877F, 0.9173863382F, 0.9178066102F, 0.9182255048F,
  158023. 0.9186430232F, 0.9190591665F, 0.9194739359F, 0.9198873324F,
  158024. 0.9202993574F, 0.9207100120F, 0.9211192973F, 0.9215272147F,
  158025. 0.9219337653F, 0.9223389504F, 0.9227427713F, 0.9231452290F,
  158026. 0.9235463251F, 0.9239460607F, 0.9243444371F, 0.9247414557F,
  158027. 0.9251371177F, 0.9255314245F, 0.9259243774F, 0.9263159778F,
  158028. 0.9267062270F, 0.9270951264F, 0.9274826774F, 0.9278688814F,
  158029. 0.9282537398F, 0.9286372540F, 0.9290194254F, 0.9294002555F,
  158030. 0.9297797458F, 0.9301578976F, 0.9305347125F, 0.9309101919F,
  158031. 0.9312843373F, 0.9316571503F, 0.9320286323F, 0.9323987849F,
  158032. 0.9327676097F, 0.9331351080F, 0.9335012816F, 0.9338661320F,
  158033. 0.9342296607F, 0.9345918694F, 0.9349527596F, 0.9353123330F,
  158034. 0.9356705911F, 0.9360275357F, 0.9363831683F, 0.9367374905F,
  158035. 0.9370905042F, 0.9374422108F, 0.9377926122F, 0.9381417099F,
  158036. 0.9384895057F, 0.9388360014F, 0.9391811985F, 0.9395250989F,
  158037. 0.9398677043F, 0.9402090165F, 0.9405490371F, 0.9408877680F,
  158038. 0.9412252110F, 0.9415613678F, 0.9418962402F, 0.9422298301F,
  158039. 0.9425621392F, 0.9428931695F, 0.9432229226F, 0.9435514005F,
  158040. 0.9438786050F, 0.9442045381F, 0.9445292014F, 0.9448525971F,
  158041. 0.9451747268F, 0.9454955926F, 0.9458151963F, 0.9461335399F,
  158042. 0.9464506253F, 0.9467664545F, 0.9470810293F, 0.9473943517F,
  158043. 0.9477064238F, 0.9480172474F, 0.9483268246F, 0.9486351573F,
  158044. 0.9489422475F, 0.9492480973F, 0.9495527087F, 0.9498560837F,
  158045. 0.9501582243F, 0.9504591325F, 0.9507588105F, 0.9510572603F,
  158046. 0.9513544839F, 0.9516504834F, 0.9519452609F, 0.9522388186F,
  158047. 0.9525311584F, 0.9528222826F, 0.9531121932F, 0.9534008923F,
  158048. 0.9536883821F, 0.9539746647F, 0.9542597424F, 0.9545436171F,
  158049. 0.9548262912F, 0.9551077667F, 0.9553880459F, 0.9556671309F,
  158050. 0.9559450239F, 0.9562217272F, 0.9564972429F, 0.9567715733F,
  158051. 0.9570447206F, 0.9573166871F, 0.9575874749F, 0.9578570863F,
  158052. 0.9581255236F, 0.9583927890F, 0.9586588849F, 0.9589238134F,
  158053. 0.9591875769F, 0.9594501777F, 0.9597116180F, 0.9599719003F,
  158054. 0.9602310267F, 0.9604889995F, 0.9607458213F, 0.9610014942F,
  158055. 0.9612560206F, 0.9615094028F, 0.9617616433F, 0.9620127443F,
  158056. 0.9622627083F, 0.9625115376F, 0.9627592345F, 0.9630058016F,
  158057. 0.9632512411F, 0.9634955555F, 0.9637387471F, 0.9639808185F,
  158058. 0.9642217720F, 0.9644616100F, 0.9647003349F, 0.9649379493F,
  158059. 0.9651744556F, 0.9654098561F, 0.9656441534F, 0.9658773499F,
  158060. 0.9661094480F, 0.9663404504F, 0.9665703593F, 0.9667991774F,
  158061. 0.9670269071F, 0.9672535509F, 0.9674791114F, 0.9677035909F,
  158062. 0.9679269921F, 0.9681493174F, 0.9683705694F, 0.9685907506F,
  158063. 0.9688098636F, 0.9690279108F, 0.9692448948F, 0.9694608182F,
  158064. 0.9696756836F, 0.9698894934F, 0.9701022503F, 0.9703139569F,
  158065. 0.9705246156F, 0.9707342291F, 0.9709428000F, 0.9711503309F,
  158066. 0.9713568243F, 0.9715622829F, 0.9717667093F, 0.9719701060F,
  158067. 0.9721724757F, 0.9723738210F, 0.9725741446F, 0.9727734490F,
  158068. 0.9729717369F, 0.9731690109F, 0.9733652737F, 0.9735605279F,
  158069. 0.9737547762F, 0.9739480212F, 0.9741402656F, 0.9743315120F,
  158070. 0.9745217631F, 0.9747110216F, 0.9748992901F, 0.9750865714F,
  158071. 0.9752728681F, 0.9754581829F, 0.9756425184F, 0.9758258775F,
  158072. 0.9760082627F, 0.9761896768F, 0.9763701224F, 0.9765496024F,
  158073. 0.9767281193F, 0.9769056760F, 0.9770822751F, 0.9772579193F,
  158074. 0.9774326114F, 0.9776063542F, 0.9777791502F, 0.9779510023F,
  158075. 0.9781219133F, 0.9782918858F, 0.9784609226F, 0.9786290264F,
  158076. 0.9787962000F, 0.9789624461F, 0.9791277676F, 0.9792921671F,
  158077. 0.9794556474F, 0.9796182113F, 0.9797798615F, 0.9799406009F,
  158078. 0.9801004321F, 0.9802593580F, 0.9804173813F, 0.9805745049F,
  158079. 0.9807307314F, 0.9808860637F, 0.9810405046F, 0.9811940568F,
  158080. 0.9813467232F, 0.9814985065F, 0.9816494095F, 0.9817994351F,
  158081. 0.9819485860F, 0.9820968650F, 0.9822442750F, 0.9823908186F,
  158082. 0.9825364988F, 0.9826813184F, 0.9828252801F, 0.9829683868F,
  158083. 0.9831106413F, 0.9832520463F, 0.9833926048F, 0.9835323195F,
  158084. 0.9836711932F, 0.9838092288F, 0.9839464291F, 0.9840827969F,
  158085. 0.9842183351F, 0.9843530464F, 0.9844869337F, 0.9846199998F,
  158086. 0.9847522475F, 0.9848836798F, 0.9850142993F, 0.9851441090F,
  158087. 0.9852731117F, 0.9854013101F, 0.9855287073F, 0.9856553058F,
  158088. 0.9857811087F, 0.9859061188F, 0.9860303388F, 0.9861537717F,
  158089. 0.9862764202F, 0.9863982872F, 0.9865193756F, 0.9866396882F,
  158090. 0.9867592277F, 0.9868779972F, 0.9869959993F, 0.9871132370F,
  158091. 0.9872297131F, 0.9873454304F, 0.9874603918F, 0.9875746001F,
  158092. 0.9876880581F, 0.9878007688F, 0.9879127348F, 0.9880239592F,
  158093. 0.9881344447F, 0.9882441941F, 0.9883532104F, 0.9884614962F,
  158094. 0.9885690546F, 0.9886758883F, 0.9887820001F, 0.9888873930F,
  158095. 0.9889920697F, 0.9890960331F, 0.9891992859F, 0.9893018312F,
  158096. 0.9894036716F, 0.9895048100F, 0.9896052493F, 0.9897049923F,
  158097. 0.9898040418F, 0.9899024006F, 0.9900000717F, 0.9900970577F,
  158098. 0.9901933616F, 0.9902889862F, 0.9903839343F, 0.9904782087F,
  158099. 0.9905718122F, 0.9906647477F, 0.9907570180F, 0.9908486259F,
  158100. 0.9909395742F, 0.9910298658F, 0.9911195034F, 0.9912084899F,
  158101. 0.9912968281F, 0.9913845208F, 0.9914715708F, 0.9915579810F,
  158102. 0.9916437540F, 0.9917288928F, 0.9918134001F, 0.9918972788F,
  158103. 0.9919805316F, 0.9920631613F, 0.9921451707F, 0.9922265626F,
  158104. 0.9923073399F, 0.9923875052F, 0.9924670615F, 0.9925460114F,
  158105. 0.9926243577F, 0.9927021033F, 0.9927792508F, 0.9928558032F,
  158106. 0.9929317631F, 0.9930071333F, 0.9930819167F, 0.9931561158F,
  158107. 0.9932297337F, 0.9933027728F, 0.9933752362F, 0.9934471264F,
  158108. 0.9935184462F, 0.9935891985F, 0.9936593859F, 0.9937290112F,
  158109. 0.9937980771F, 0.9938665864F, 0.9939345418F, 0.9940019460F,
  158110. 0.9940688018F, 0.9941351118F, 0.9942008789F, 0.9942661057F,
  158111. 0.9943307950F, 0.9943949494F, 0.9944585717F, 0.9945216645F,
  158112. 0.9945842307F, 0.9946462728F, 0.9947077936F, 0.9947687957F,
  158113. 0.9948292820F, 0.9948892550F, 0.9949487174F, 0.9950076719F,
  158114. 0.9950661212F, 0.9951240679F, 0.9951815148F, 0.9952384645F,
  158115. 0.9952949196F, 0.9953508828F, 0.9954063568F, 0.9954613442F,
  158116. 0.9955158476F, 0.9955698697F, 0.9956234132F, 0.9956764806F,
  158117. 0.9957290746F, 0.9957811978F, 0.9958328528F, 0.9958840423F,
  158118. 0.9959347688F, 0.9959850351F, 0.9960348435F, 0.9960841969F,
  158119. 0.9961330977F, 0.9961815486F, 0.9962295521F, 0.9962771108F,
  158120. 0.9963242274F, 0.9963709043F, 0.9964171441F, 0.9964629494F,
  158121. 0.9965083228F, 0.9965532668F, 0.9965977840F, 0.9966418768F,
  158122. 0.9966855479F, 0.9967287998F, 0.9967716350F, 0.9968140559F,
  158123. 0.9968560653F, 0.9968976655F, 0.9969388591F, 0.9969796485F,
  158124. 0.9970200363F, 0.9970600250F, 0.9970996170F, 0.9971388149F,
  158125. 0.9971776211F, 0.9972160380F, 0.9972540683F, 0.9972917142F,
  158126. 0.9973289783F, 0.9973658631F, 0.9974023709F, 0.9974385042F,
  158127. 0.9974742655F, 0.9975096571F, 0.9975446816F, 0.9975793413F,
  158128. 0.9976136386F, 0.9976475759F, 0.9976811557F, 0.9977143803F,
  158129. 0.9977472521F, 0.9977797736F, 0.9978119470F, 0.9978437748F,
  158130. 0.9978752593F, 0.9979064029F, 0.9979372079F, 0.9979676768F,
  158131. 0.9979978117F, 0.9980276151F, 0.9980570893F, 0.9980862367F,
  158132. 0.9981150595F, 0.9981435600F, 0.9981717406F, 0.9981996035F,
  158133. 0.9982271511F, 0.9982543856F, 0.9982813093F, 0.9983079246F,
  158134. 0.9983342336F, 0.9983602386F, 0.9983859418F, 0.9984113456F,
  158135. 0.9984364522F, 0.9984612638F, 0.9984857825F, 0.9985100108F,
  158136. 0.9985339507F, 0.9985576044F, 0.9985809743F, 0.9986040624F,
  158137. 0.9986268710F, 0.9986494022F, 0.9986716583F, 0.9986936413F,
  158138. 0.9987153535F, 0.9987367969F, 0.9987579738F, 0.9987788864F,
  158139. 0.9987995366F, 0.9988199267F, 0.9988400587F, 0.9988599348F,
  158140. 0.9988795572F, 0.9988989278F, 0.9989180487F, 0.9989369222F,
  158141. 0.9989555501F, 0.9989739347F, 0.9989920780F, 0.9990099820F,
  158142. 0.9990276487F, 0.9990450803F, 0.9990622787F, 0.9990792460F,
  158143. 0.9990959841F, 0.9991124952F, 0.9991287812F, 0.9991448440F,
  158144. 0.9991606858F, 0.9991763084F, 0.9991917139F, 0.9992069042F,
  158145. 0.9992218813F, 0.9992366471F, 0.9992512035F, 0.9992655525F,
  158146. 0.9992796961F, 0.9992936361F, 0.9993073744F, 0.9993209131F,
  158147. 0.9993342538F, 0.9993473987F, 0.9993603494F, 0.9993731080F,
  158148. 0.9993856762F, 0.9993980559F, 0.9994102490F, 0.9994222573F,
  158149. 0.9994340827F, 0.9994457269F, 0.9994571918F, 0.9994684793F,
  158150. 0.9994795910F, 0.9994905288F, 0.9995012945F, 0.9995118898F,
  158151. 0.9995223165F, 0.9995325765F, 0.9995426713F, 0.9995526029F,
  158152. 0.9995623728F, 0.9995719829F, 0.9995814349F, 0.9995907304F,
  158153. 0.9995998712F, 0.9996088590F, 0.9996176954F, 0.9996263821F,
  158154. 0.9996349208F, 0.9996433132F, 0.9996515609F, 0.9996596656F,
  158155. 0.9996676288F, 0.9996754522F, 0.9996831375F, 0.9996906862F,
  158156. 0.9996981000F, 0.9997053804F, 0.9997125290F, 0.9997195474F,
  158157. 0.9997264371F, 0.9997331998F, 0.9997398369F, 0.9997463500F,
  158158. 0.9997527406F, 0.9997590103F, 0.9997651606F, 0.9997711930F,
  158159. 0.9997771089F, 0.9997829098F, 0.9997885973F, 0.9997941728F,
  158160. 0.9997996378F, 0.9998049936F, 0.9998102419F, 0.9998153839F,
  158161. 0.9998204211F, 0.9998253550F, 0.9998301868F, 0.9998349182F,
  158162. 0.9998395503F, 0.9998440847F, 0.9998485226F, 0.9998528654F,
  158163. 0.9998571146F, 0.9998612713F, 0.9998653370F, 0.9998693130F,
  158164. 0.9998732007F, 0.9998770012F, 0.9998807159F, 0.9998843461F,
  158165. 0.9998878931F, 0.9998913581F, 0.9998947424F, 0.9998980473F,
  158166. 0.9999012740F, 0.9999044237F, 0.9999074976F, 0.9999104971F,
  158167. 0.9999134231F, 0.9999162771F, 0.9999190601F, 0.9999217733F,
  158168. 0.9999244179F, 0.9999269950F, 0.9999295058F, 0.9999319515F,
  158169. 0.9999343332F, 0.9999366519F, 0.9999389088F, 0.9999411050F,
  158170. 0.9999432416F, 0.9999453196F, 0.9999473402F, 0.9999493044F,
  158171. 0.9999512132F, 0.9999530677F, 0.9999548690F, 0.9999566180F,
  158172. 0.9999583157F, 0.9999599633F, 0.9999615616F, 0.9999631116F,
  158173. 0.9999646144F, 0.9999660709F, 0.9999674820F, 0.9999688487F,
  158174. 0.9999701719F, 0.9999714526F, 0.9999726917F, 0.9999738900F,
  158175. 0.9999750486F, 0.9999761682F, 0.9999772497F, 0.9999782941F,
  158176. 0.9999793021F, 0.9999802747F, 0.9999812126F, 0.9999821167F,
  158177. 0.9999829878F, 0.9999838268F, 0.9999846343F, 0.9999854113F,
  158178. 0.9999861584F, 0.9999868765F, 0.9999875664F, 0.9999882287F,
  158179. 0.9999888642F, 0.9999894736F, 0.9999900577F, 0.9999906172F,
  158180. 0.9999911528F, 0.9999916651F, 0.9999921548F, 0.9999926227F,
  158181. 0.9999930693F, 0.9999934954F, 0.9999939015F, 0.9999942883F,
  158182. 0.9999946564F, 0.9999950064F, 0.9999953390F, 0.9999956547F,
  158183. 0.9999959541F, 0.9999962377F, 0.9999965062F, 0.9999967601F,
  158184. 0.9999969998F, 0.9999972260F, 0.9999974392F, 0.9999976399F,
  158185. 0.9999978285F, 0.9999980056F, 0.9999981716F, 0.9999983271F,
  158186. 0.9999984724F, 0.9999986081F, 0.9999987345F, 0.9999988521F,
  158187. 0.9999989613F, 0.9999990625F, 0.9999991562F, 0.9999992426F,
  158188. 0.9999993223F, 0.9999993954F, 0.9999994625F, 0.9999995239F,
  158189. 0.9999995798F, 0.9999996307F, 0.9999996768F, 0.9999997184F,
  158190. 0.9999997559F, 0.9999997895F, 0.9999998195F, 0.9999998462F,
  158191. 0.9999998698F, 0.9999998906F, 0.9999999088F, 0.9999999246F,
  158192. 0.9999999383F, 0.9999999500F, 0.9999999600F, 0.9999999684F,
  158193. 0.9999999754F, 0.9999999811F, 0.9999999858F, 0.9999999896F,
  158194. 0.9999999925F, 0.9999999948F, 0.9999999965F, 0.9999999978F,
  158195. 0.9999999986F, 0.9999999992F, 0.9999999996F, 0.9999999998F,
  158196. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  158197. };
  158198. static float vwin8192[4096] = {
  158199. 0.0000000578F, 0.0000005198F, 0.0000014438F, 0.0000028299F,
  158200. 0.0000046780F, 0.0000069882F, 0.0000097604F, 0.0000129945F,
  158201. 0.0000166908F, 0.0000208490F, 0.0000254692F, 0.0000305515F,
  158202. 0.0000360958F, 0.0000421021F, 0.0000485704F, 0.0000555006F,
  158203. 0.0000628929F, 0.0000707472F, 0.0000790635F, 0.0000878417F,
  158204. 0.0000970820F, 0.0001067842F, 0.0001169483F, 0.0001275744F,
  158205. 0.0001386625F, 0.0001502126F, 0.0001622245F, 0.0001746984F,
  158206. 0.0001876343F, 0.0002010320F, 0.0002148917F, 0.0002292132F,
  158207. 0.0002439967F, 0.0002592421F, 0.0002749493F, 0.0002911184F,
  158208. 0.0003077493F, 0.0003248421F, 0.0003423967F, 0.0003604132F,
  158209. 0.0003788915F, 0.0003978316F, 0.0004172335F, 0.0004370971F,
  158210. 0.0004574226F, 0.0004782098F, 0.0004994587F, 0.0005211694F,
  158211. 0.0005433418F, 0.0005659759F, 0.0005890717F, 0.0006126292F,
  158212. 0.0006366484F, 0.0006611292F, 0.0006860716F, 0.0007114757F,
  158213. 0.0007373414F, 0.0007636687F, 0.0007904576F, 0.0008177080F,
  158214. 0.0008454200F, 0.0008735935F, 0.0009022285F, 0.0009313250F,
  158215. 0.0009608830F, 0.0009909025F, 0.0010213834F, 0.0010523257F,
  158216. 0.0010837295F, 0.0011155946F, 0.0011479211F, 0.0011807090F,
  158217. 0.0012139582F, 0.0012476687F, 0.0012818405F, 0.0013164736F,
  158218. 0.0013515679F, 0.0013871235F, 0.0014231402F, 0.0014596182F,
  158219. 0.0014965573F, 0.0015339576F, 0.0015718190F, 0.0016101415F,
  158220. 0.0016489251F, 0.0016881698F, 0.0017278754F, 0.0017680421F,
  158221. 0.0018086698F, 0.0018497584F, 0.0018913080F, 0.0019333185F,
  158222. 0.0019757898F, 0.0020187221F, 0.0020621151F, 0.0021059690F,
  158223. 0.0021502837F, 0.0021950591F, 0.0022402953F, 0.0022859921F,
  158224. 0.0023321497F, 0.0023787679F, 0.0024258467F, 0.0024733861F,
  158225. 0.0025213861F, 0.0025698466F, 0.0026187676F, 0.0026681491F,
  158226. 0.0027179911F, 0.0027682935F, 0.0028190562F, 0.0028702794F,
  158227. 0.0029219628F, 0.0029741066F, 0.0030267107F, 0.0030797749F,
  158228. 0.0031332994F, 0.0031872841F, 0.0032417289F, 0.0032966338F,
  158229. 0.0033519988F, 0.0034078238F, 0.0034641089F, 0.0035208539F,
  158230. 0.0035780589F, 0.0036357237F, 0.0036938485F, 0.0037524331F,
  158231. 0.0038114775F, 0.0038709817F, 0.0039309456F, 0.0039913692F,
  158232. 0.0040522524F, 0.0041135953F, 0.0041753978F, 0.0042376599F,
  158233. 0.0043003814F, 0.0043635624F, 0.0044272029F, 0.0044913028F,
  158234. 0.0045558620F, 0.0046208806F, 0.0046863585F, 0.0047522955F,
  158235. 0.0048186919F, 0.0048855473F, 0.0049528619F, 0.0050206356F,
  158236. 0.0050888684F, 0.0051575601F, 0.0052267108F, 0.0052963204F,
  158237. 0.0053663890F, 0.0054369163F, 0.0055079025F, 0.0055793474F,
  158238. 0.0056512510F, 0.0057236133F, 0.0057964342F, 0.0058697137F,
  158239. 0.0059434517F, 0.0060176482F, 0.0060923032F, 0.0061674166F,
  158240. 0.0062429883F, 0.0063190183F, 0.0063955066F, 0.0064724532F,
  158241. 0.0065498579F, 0.0066277207F, 0.0067060416F, 0.0067848205F,
  158242. 0.0068640575F, 0.0069437523F, 0.0070239051F, 0.0071045157F,
  158243. 0.0071855840F, 0.0072671102F, 0.0073490940F, 0.0074315355F,
  158244. 0.0075144345F, 0.0075977911F, 0.0076816052F, 0.0077658768F,
  158245. 0.0078506057F, 0.0079357920F, 0.0080214355F, 0.0081075363F,
  158246. 0.0081940943F, 0.0082811094F, 0.0083685816F, 0.0084565108F,
  158247. 0.0085448970F, 0.0086337401F, 0.0087230401F, 0.0088127969F,
  158248. 0.0089030104F, 0.0089936807F, 0.0090848076F, 0.0091763911F,
  158249. 0.0092684311F, 0.0093609276F, 0.0094538805F, 0.0095472898F,
  158250. 0.0096411554F, 0.0097354772F, 0.0098302552F, 0.0099254894F,
  158251. 0.0100211796F, 0.0101173259F, 0.0102139281F, 0.0103109863F,
  158252. 0.0104085002F, 0.0105064700F, 0.0106048955F, 0.0107037766F,
  158253. 0.0108031133F, 0.0109029056F, 0.0110031534F, 0.0111038565F,
  158254. 0.0112050151F, 0.0113066289F, 0.0114086980F, 0.0115112222F,
  158255. 0.0116142015F, 0.0117176359F, 0.0118215252F, 0.0119258695F,
  158256. 0.0120306686F, 0.0121359225F, 0.0122416312F, 0.0123477944F,
  158257. 0.0124544123F, 0.0125614847F, 0.0126690116F, 0.0127769928F,
  158258. 0.0128854284F, 0.0129943182F, 0.0131036623F, 0.0132134604F,
  158259. 0.0133237126F, 0.0134344188F, 0.0135455790F, 0.0136571929F,
  158260. 0.0137692607F, 0.0138817821F, 0.0139947572F, 0.0141081859F,
  158261. 0.0142220681F, 0.0143364037F, 0.0144511927F, 0.0145664350F,
  158262. 0.0146821304F, 0.0147982791F, 0.0149148808F, 0.0150319355F,
  158263. 0.0151494431F, 0.0152674036F, 0.0153858168F, 0.0155046828F,
  158264. 0.0156240014F, 0.0157437726F, 0.0158639962F, 0.0159846723F,
  158265. 0.0161058007F, 0.0162273814F, 0.0163494142F, 0.0164718991F,
  158266. 0.0165948361F, 0.0167182250F, 0.0168420658F, 0.0169663584F,
  158267. 0.0170911027F, 0.0172162987F, 0.0173419462F, 0.0174680452F,
  158268. 0.0175945956F, 0.0177215974F, 0.0178490504F, 0.0179769545F,
  158269. 0.0181053098F, 0.0182341160F, 0.0183633732F, 0.0184930812F,
  158270. 0.0186232399F, 0.0187538494F, 0.0188849094F, 0.0190164200F,
  158271. 0.0191483809F, 0.0192807923F, 0.0194136539F, 0.0195469656F,
  158272. 0.0196807275F, 0.0198149394F, 0.0199496012F, 0.0200847128F,
  158273. 0.0202202742F, 0.0203562853F, 0.0204927460F, 0.0206296561F,
  158274. 0.0207670157F, 0.0209048245F, 0.0210430826F, 0.0211817899F,
  158275. 0.0213209462F, 0.0214605515F, 0.0216006057F, 0.0217411086F,
  158276. 0.0218820603F, 0.0220234605F, 0.0221653093F, 0.0223076066F,
  158277. 0.0224503521F, 0.0225935459F, 0.0227371879F, 0.0228812779F,
  158278. 0.0230258160F, 0.0231708018F, 0.0233162355F, 0.0234621169F,
  158279. 0.0236084459F, 0.0237552224F, 0.0239024462F, 0.0240501175F,
  158280. 0.0241982359F, 0.0243468015F, 0.0244958141F, 0.0246452736F,
  158281. 0.0247951800F, 0.0249455331F, 0.0250963329F, 0.0252475792F,
  158282. 0.0253992720F, 0.0255514111F, 0.0257039965F, 0.0258570281F,
  158283. 0.0260105057F, 0.0261644293F, 0.0263187987F, 0.0264736139F,
  158284. 0.0266288747F, 0.0267845811F, 0.0269407330F, 0.0270973302F,
  158285. 0.0272543727F, 0.0274118604F, 0.0275697930F, 0.0277281707F,
  158286. 0.0278869932F, 0.0280462604F, 0.0282059723F, 0.0283661287F,
  158287. 0.0285267295F, 0.0286877747F, 0.0288492641F, 0.0290111976F,
  158288. 0.0291735751F, 0.0293363965F, 0.0294996617F, 0.0296633706F,
  158289. 0.0298275231F, 0.0299921190F, 0.0301571583F, 0.0303226409F,
  158290. 0.0304885667F, 0.0306549354F, 0.0308217472F, 0.0309890017F,
  158291. 0.0311566989F, 0.0313248388F, 0.0314934211F, 0.0316624459F,
  158292. 0.0318319128F, 0.0320018220F, 0.0321721732F, 0.0323429663F,
  158293. 0.0325142013F, 0.0326858779F, 0.0328579962F, 0.0330305559F,
  158294. 0.0332035570F, 0.0333769994F, 0.0335508829F, 0.0337252074F,
  158295. 0.0338999728F, 0.0340751790F, 0.0342508259F, 0.0344269134F,
  158296. 0.0346034412F, 0.0347804094F, 0.0349578178F, 0.0351356663F,
  158297. 0.0353139548F, 0.0354926831F, 0.0356718511F, 0.0358514588F,
  158298. 0.0360315059F, 0.0362119924F, 0.0363929182F, 0.0365742831F,
  158299. 0.0367560870F, 0.0369383297F, 0.0371210113F, 0.0373041315F,
  158300. 0.0374876902F, 0.0376716873F, 0.0378561226F, 0.0380409961F,
  158301. 0.0382263077F, 0.0384120571F, 0.0385982443F, 0.0387848691F,
  158302. 0.0389719315F, 0.0391594313F, 0.0393473683F, 0.0395357425F,
  158303. 0.0397245537F, 0.0399138017F, 0.0401034866F, 0.0402936080F,
  158304. 0.0404841660F, 0.0406751603F, 0.0408665909F, 0.0410584576F,
  158305. 0.0412507603F, 0.0414434988F, 0.0416366731F, 0.0418302829F,
  158306. 0.0420243282F, 0.0422188088F, 0.0424137246F, 0.0426090755F,
  158307. 0.0428048613F, 0.0430010819F, 0.0431977371F, 0.0433948269F,
  158308. 0.0435923511F, 0.0437903095F, 0.0439887020F, 0.0441875285F,
  158309. 0.0443867889F, 0.0445864830F, 0.0447866106F, 0.0449871717F,
  158310. 0.0451881661F, 0.0453895936F, 0.0455914542F, 0.0457937477F,
  158311. 0.0459964738F, 0.0461996326F, 0.0464032239F, 0.0466072475F,
  158312. 0.0468117032F, 0.0470165910F, 0.0472219107F, 0.0474276622F,
  158313. 0.0476338452F, 0.0478404597F, 0.0480475056F, 0.0482549827F,
  158314. 0.0484628907F, 0.0486712297F, 0.0488799994F, 0.0490891998F,
  158315. 0.0492988306F, 0.0495088917F, 0.0497193830F, 0.0499303043F,
  158316. 0.0501416554F, 0.0503534363F, 0.0505656468F, 0.0507782867F,
  158317. 0.0509913559F, 0.0512048542F, 0.0514187815F, 0.0516331376F,
  158318. 0.0518479225F, 0.0520631358F, 0.0522787775F, 0.0524948475F,
  158319. 0.0527113455F, 0.0529282715F, 0.0531456252F, 0.0533634066F,
  158320. 0.0535816154F, 0.0538002515F, 0.0540193148F, 0.0542388051F,
  158321. 0.0544587222F, 0.0546790660F, 0.0548998364F, 0.0551210331F,
  158322. 0.0553426561F, 0.0555647051F, 0.0557871801F, 0.0560100807F,
  158323. 0.0562334070F, 0.0564571587F, 0.0566813357F, 0.0569059378F,
  158324. 0.0571309649F, 0.0573564168F, 0.0575822933F, 0.0578085942F,
  158325. 0.0580353195F, 0.0582624689F, 0.0584900423F, 0.0587180396F,
  158326. 0.0589464605F, 0.0591753049F, 0.0594045726F, 0.0596342635F,
  158327. 0.0598643774F, 0.0600949141F, 0.0603258735F, 0.0605572555F,
  158328. 0.0607890597F, 0.0610212862F, 0.0612539346F, 0.0614870049F,
  158329. 0.0617204968F, 0.0619544103F, 0.0621887451F, 0.0624235010F,
  158330. 0.0626586780F, 0.0628942758F, 0.0631302942F, 0.0633667331F,
  158331. 0.0636035923F, 0.0638408717F, 0.0640785710F, 0.0643166901F,
  158332. 0.0645552288F, 0.0647941870F, 0.0650335645F, 0.0652733610F,
  158333. 0.0655135765F, 0.0657542108F, 0.0659952636F, 0.0662367348F,
  158334. 0.0664786242F, 0.0667209316F, 0.0669636570F, 0.0672068000F,
  158335. 0.0674503605F, 0.0676943384F, 0.0679387334F, 0.0681835454F,
  158336. 0.0684287742F, 0.0686744196F, 0.0689204814F, 0.0691669595F,
  158337. 0.0694138536F, 0.0696611637F, 0.0699088894F, 0.0701570307F,
  158338. 0.0704055873F, 0.0706545590F, 0.0709039458F, 0.0711537473F,
  158339. 0.0714039634F, 0.0716545939F, 0.0719056387F, 0.0721570975F,
  158340. 0.0724089702F, 0.0726612565F, 0.0729139563F, 0.0731670694F,
  158341. 0.0734205956F, 0.0736745347F, 0.0739288866F, 0.0741836510F,
  158342. 0.0744388277F, 0.0746944166F, 0.0749504175F, 0.0752068301F,
  158343. 0.0754636543F, 0.0757208899F, 0.0759785367F, 0.0762365946F,
  158344. 0.0764950632F, 0.0767539424F, 0.0770132320F, 0.0772729319F,
  158345. 0.0775330418F, 0.0777935616F, 0.0780544909F, 0.0783158298F,
  158346. 0.0785775778F, 0.0788397349F, 0.0791023009F, 0.0793652755F,
  158347. 0.0796286585F, 0.0798924498F, 0.0801566492F, 0.0804212564F,
  158348. 0.0806862712F, 0.0809516935F, 0.0812175231F, 0.0814837597F,
  158349. 0.0817504031F, 0.0820174532F, 0.0822849097F, 0.0825527724F,
  158350. 0.0828210412F, 0.0830897158F, 0.0833587960F, 0.0836282816F,
  158351. 0.0838981724F, 0.0841684682F, 0.0844391688F, 0.0847102740F,
  158352. 0.0849817835F, 0.0852536973F, 0.0855260150F, 0.0857987364F,
  158353. 0.0860718614F, 0.0863453897F, 0.0866193211F, 0.0868936554F,
  158354. 0.0871683924F, 0.0874435319F, 0.0877190737F, 0.0879950175F,
  158355. 0.0882713632F, 0.0885481105F, 0.0888252592F, 0.0891028091F,
  158356. 0.0893807600F, 0.0896591117F, 0.0899378639F, 0.0902170165F,
  158357. 0.0904965692F, 0.0907765218F, 0.0910568740F, 0.0913376258F,
  158358. 0.0916187767F, 0.0919003268F, 0.0921822756F, 0.0924646230F,
  158359. 0.0927473687F, 0.0930305126F, 0.0933140545F, 0.0935979940F,
  158360. 0.0938823310F, 0.0941670653F, 0.0944521966F, 0.0947377247F,
  158361. 0.0950236494F, 0.0953099704F, 0.0955966876F, 0.0958838007F,
  158362. 0.0961713094F, 0.0964592136F, 0.0967475131F, 0.0970362075F,
  158363. 0.0973252967F, 0.0976147805F, 0.0979046585F, 0.0981949307F,
  158364. 0.0984855967F, 0.0987766563F, 0.0990681093F, 0.0993599555F,
  158365. 0.0996521945F, 0.0999448263F, 0.1002378506F, 0.1005312671F,
  158366. 0.1008250755F, 0.1011192757F, 0.1014138675F, 0.1017088505F,
  158367. 0.1020042246F, 0.1022999895F, 0.1025961450F, 0.1028926909F,
  158368. 0.1031896268F, 0.1034869526F, 0.1037846680F, 0.1040827729F,
  158369. 0.1043812668F, 0.1046801497F, 0.1049794213F, 0.1052790813F,
  158370. 0.1055791294F, 0.1058795656F, 0.1061803894F, 0.1064816006F,
  158371. 0.1067831991F, 0.1070851846F, 0.1073875568F, 0.1076903155F,
  158372. 0.1079934604F, 0.1082969913F, 0.1086009079F, 0.1089052101F,
  158373. 0.1092098975F, 0.1095149699F, 0.1098204270F, 0.1101262687F,
  158374. 0.1104324946F, 0.1107391045F, 0.1110460982F, 0.1113534754F,
  158375. 0.1116612359F, 0.1119693793F, 0.1122779055F, 0.1125868142F,
  158376. 0.1128961052F, 0.1132057781F, 0.1135158328F, 0.1138262690F,
  158377. 0.1141370863F, 0.1144482847F, 0.1147598638F, 0.1150718233F,
  158378. 0.1153841631F, 0.1156968828F, 0.1160099822F, 0.1163234610F,
  158379. 0.1166373190F, 0.1169515559F, 0.1172661714F, 0.1175811654F,
  158380. 0.1178965374F, 0.1182122874F, 0.1185284149F, 0.1188449198F,
  158381. 0.1191618018F, 0.1194790606F, 0.1197966960F, 0.1201147076F,
  158382. 0.1204330953F, 0.1207518587F, 0.1210709976F, 0.1213905118F,
  158383. 0.1217104009F, 0.1220306647F, 0.1223513029F, 0.1226723153F,
  158384. 0.1229937016F, 0.1233154615F, 0.1236375948F, 0.1239601011F,
  158385. 0.1242829803F, 0.1246062319F, 0.1249298559F, 0.1252538518F,
  158386. 0.1255782195F, 0.1259029586F, 0.1262280689F, 0.1265535501F,
  158387. 0.1268794019F, 0.1272056241F, 0.1275322163F, 0.1278591784F,
  158388. 0.1281865099F, 0.1285142108F, 0.1288422805F, 0.1291707190F,
  158389. 0.1294995259F, 0.1298287009F, 0.1301582437F, 0.1304881542F,
  158390. 0.1308184319F, 0.1311490766F, 0.1314800881F, 0.1318114660F,
  158391. 0.1321432100F, 0.1324753200F, 0.1328077955F, 0.1331406364F,
  158392. 0.1334738422F, 0.1338074129F, 0.1341413479F, 0.1344756472F,
  158393. 0.1348103103F, 0.1351453370F, 0.1354807270F, 0.1358164801F,
  158394. 0.1361525959F, 0.1364890741F, 0.1368259145F, 0.1371631167F,
  158395. 0.1375006805F, 0.1378386056F, 0.1381768917F, 0.1385155384F,
  158396. 0.1388545456F, 0.1391939129F, 0.1395336400F, 0.1398737266F,
  158397. 0.1402141724F, 0.1405549772F, 0.1408961406F, 0.1412376623F,
  158398. 0.1415795421F, 0.1419217797F, 0.1422643746F, 0.1426073268F,
  158399. 0.1429506358F, 0.1432943013F, 0.1436383231F, 0.1439827008F,
  158400. 0.1443274342F, 0.1446725229F, 0.1450179667F, 0.1453637652F,
  158401. 0.1457099181F, 0.1460564252F, 0.1464032861F, 0.1467505006F,
  158402. 0.1470980682F, 0.1474459888F, 0.1477942620F, 0.1481428875F,
  158403. 0.1484918651F, 0.1488411942F, 0.1491908748F, 0.1495409065F,
  158404. 0.1498912889F, 0.1502420218F, 0.1505931048F, 0.1509445376F,
  158405. 0.1512963200F, 0.1516484516F, 0.1520009321F, 0.1523537612F,
  158406. 0.1527069385F, 0.1530604638F, 0.1534143368F, 0.1537685571F,
  158407. 0.1541231244F, 0.1544780384F, 0.1548332987F, 0.1551889052F,
  158408. 0.1555448574F, 0.1559011550F, 0.1562577978F, 0.1566147853F,
  158409. 0.1569721173F, 0.1573297935F, 0.1576878135F, 0.1580461771F,
  158410. 0.1584048838F, 0.1587639334F, 0.1591233255F, 0.1594830599F,
  158411. 0.1598431361F, 0.1602035540F, 0.1605643131F, 0.1609254131F,
  158412. 0.1612868537F, 0.1616486346F, 0.1620107555F, 0.1623732160F,
  158413. 0.1627360158F, 0.1630991545F, 0.1634626319F, 0.1638264476F,
  158414. 0.1641906013F, 0.1645550926F, 0.1649199212F, 0.1652850869F,
  158415. 0.1656505892F, 0.1660164278F, 0.1663826024F, 0.1667491127F,
  158416. 0.1671159583F, 0.1674831388F, 0.1678506541F, 0.1682185036F,
  158417. 0.1685866872F, 0.1689552044F, 0.1693240549F, 0.1696932384F,
  158418. 0.1700627545F, 0.1704326029F, 0.1708027833F, 0.1711732952F,
  158419. 0.1715441385F, 0.1719153127F, 0.1722868175F, 0.1726586526F,
  158420. 0.1730308176F, 0.1734033121F, 0.1737761359F, 0.1741492886F,
  158421. 0.1745227698F, 0.1748965792F, 0.1752707164F, 0.1756451812F,
  158422. 0.1760199731F, 0.1763950918F, 0.1767705370F, 0.1771463083F,
  158423. 0.1775224054F, 0.1778988279F, 0.1782755754F, 0.1786526477F,
  158424. 0.1790300444F, 0.1794077651F, 0.1797858094F, 0.1801641771F,
  158425. 0.1805428677F, 0.1809218810F, 0.1813012165F, 0.1816808739F,
  158426. 0.1820608528F, 0.1824411530F, 0.1828217739F, 0.1832027154F,
  158427. 0.1835839770F, 0.1839655584F, 0.1843474592F, 0.1847296790F,
  158428. 0.1851122175F, 0.1854950744F, 0.1858782492F, 0.1862617417F,
  158429. 0.1866455514F, 0.1870296780F, 0.1874141211F, 0.1877988804F,
  158430. 0.1881839555F, 0.1885693461F, 0.1889550517F, 0.1893410721F,
  158431. 0.1897274068F, 0.1901140555F, 0.1905010178F, 0.1908882933F,
  158432. 0.1912758818F, 0.1916637828F, 0.1920519959F, 0.1924405208F,
  158433. 0.1928293571F, 0.1932185044F, 0.1936079625F, 0.1939977308F,
  158434. 0.1943878091F, 0.1947781969F, 0.1951688939F, 0.1955598998F,
  158435. 0.1959512141F, 0.1963428364F, 0.1967347665F, 0.1971270038F,
  158436. 0.1975195482F, 0.1979123990F, 0.1983055561F, 0.1986990190F,
  158437. 0.1990927873F, 0.1994868607F, 0.1998812388F, 0.2002759212F,
  158438. 0.2006709075F, 0.2010661974F, 0.2014617904F, 0.2018576862F,
  158439. 0.2022538844F, 0.2026503847F, 0.2030471865F, 0.2034442897F,
  158440. 0.2038416937F, 0.2042393982F, 0.2046374028F, 0.2050357071F,
  158441. 0.2054343107F, 0.2058332133F, 0.2062324145F, 0.2066319138F,
  158442. 0.2070317110F, 0.2074318055F, 0.2078321970F, 0.2082328852F,
  158443. 0.2086338696F, 0.2090351498F, 0.2094367255F, 0.2098385962F,
  158444. 0.2102407617F, 0.2106432213F, 0.2110459749F, 0.2114490220F,
  158445. 0.2118523621F, 0.2122559950F, 0.2126599202F, 0.2130641373F,
  158446. 0.2134686459F, 0.2138734456F, 0.2142785361F, 0.2146839168F,
  158447. 0.2150895875F, 0.2154955478F, 0.2159017972F, 0.2163083353F,
  158448. 0.2167151617F, 0.2171222761F, 0.2175296780F, 0.2179373670F,
  158449. 0.2183453428F, 0.2187536049F, 0.2191621529F, 0.2195709864F,
  158450. 0.2199801051F, 0.2203895085F, 0.2207991961F, 0.2212091677F,
  158451. 0.2216194228F, 0.2220299610F, 0.2224407818F, 0.2228518850F,
  158452. 0.2232632699F, 0.2236749364F, 0.2240868839F, 0.2244991121F,
  158453. 0.2249116204F, 0.2253244086F, 0.2257374763F, 0.2261508229F,
  158454. 0.2265644481F, 0.2269783514F, 0.2273925326F, 0.2278069911F,
  158455. 0.2282217265F, 0.2286367384F, 0.2290520265F, 0.2294675902F,
  158456. 0.2298834292F, 0.2302995431F, 0.2307159314F, 0.2311325937F,
  158457. 0.2315495297F, 0.2319667388F, 0.2323842207F, 0.2328019749F,
  158458. 0.2332200011F, 0.2336382988F, 0.2340568675F, 0.2344757070F,
  158459. 0.2348948166F, 0.2353141961F, 0.2357338450F, 0.2361537629F,
  158460. 0.2365739493F, 0.2369944038F, 0.2374151261F, 0.2378361156F,
  158461. 0.2382573720F, 0.2386788948F, 0.2391006836F, 0.2395227380F,
  158462. 0.2399450575F, 0.2403676417F, 0.2407904902F, 0.2412136026F,
  158463. 0.2416369783F, 0.2420606171F, 0.2424845185F, 0.2429086820F,
  158464. 0.2433331072F, 0.2437577936F, 0.2441827409F, 0.2446079486F,
  158465. 0.2450334163F, 0.2454591435F, 0.2458851298F, 0.2463113747F,
  158466. 0.2467378779F, 0.2471646389F, 0.2475916573F, 0.2480189325F,
  158467. 0.2484464643F, 0.2488742521F, 0.2493022955F, 0.2497305940F,
  158468. 0.2501591473F, 0.2505879549F, 0.2510170163F, 0.2514463311F,
  158469. 0.2518758989F, 0.2523057193F, 0.2527357916F, 0.2531661157F,
  158470. 0.2535966909F, 0.2540275169F, 0.2544585931F, 0.2548899193F,
  158471. 0.2553214948F, 0.2557533193F, 0.2561853924F, 0.2566177135F,
  158472. 0.2570502822F, 0.2574830981F, 0.2579161608F, 0.2583494697F,
  158473. 0.2587830245F, 0.2592168246F, 0.2596508697F, 0.2600851593F,
  158474. 0.2605196929F, 0.2609544701F, 0.2613894904F, 0.2618247534F,
  158475. 0.2622602586F, 0.2626960055F, 0.2631319938F, 0.2635682230F,
  158476. 0.2640046925F, 0.2644414021F, 0.2648783511F, 0.2653155391F,
  158477. 0.2657529657F, 0.2661906305F, 0.2666285329F, 0.2670666725F,
  158478. 0.2675050489F, 0.2679436616F, 0.2683825101F, 0.2688215940F,
  158479. 0.2692609127F, 0.2697004660F, 0.2701402532F, 0.2705802739F,
  158480. 0.2710205278F, 0.2714610142F, 0.2719017327F, 0.2723426830F,
  158481. 0.2727838644F, 0.2732252766F, 0.2736669191F, 0.2741087914F,
  158482. 0.2745508930F, 0.2749932235F, 0.2754357824F, 0.2758785693F,
  158483. 0.2763215837F, 0.2767648251F, 0.2772082930F, 0.2776519870F,
  158484. 0.2780959066F, 0.2785400513F, 0.2789844207F, 0.2794290143F,
  158485. 0.2798738316F, 0.2803188722F, 0.2807641355F, 0.2812096211F,
  158486. 0.2816553286F, 0.2821012574F, 0.2825474071F, 0.2829937773F,
  158487. 0.2834403673F, 0.2838871768F, 0.2843342053F, 0.2847814523F,
  158488. 0.2852289174F, 0.2856765999F, 0.2861244996F, 0.2865726159F,
  158489. 0.2870209482F, 0.2874694962F, 0.2879182594F, 0.2883672372F,
  158490. 0.2888164293F, 0.2892658350F, 0.2897154540F, 0.2901652858F,
  158491. 0.2906153298F, 0.2910655856F, 0.2915160527F, 0.2919667306F,
  158492. 0.2924176189F, 0.2928687171F, 0.2933200246F, 0.2937715409F,
  158493. 0.2942232657F, 0.2946751984F, 0.2951273386F, 0.2955796856F,
  158494. 0.2960322391F, 0.2964849986F, 0.2969379636F, 0.2973911335F,
  158495. 0.2978445080F, 0.2982980864F, 0.2987518684F, 0.2992058534F,
  158496. 0.2996600409F, 0.3001144305F, 0.3005690217F, 0.3010238139F,
  158497. 0.3014788067F, 0.3019339995F, 0.3023893920F, 0.3028449835F,
  158498. 0.3033007736F, 0.3037567618F, 0.3042129477F, 0.3046693306F,
  158499. 0.3051259102F, 0.3055826859F, 0.3060396572F, 0.3064968236F,
  158500. 0.3069541847F, 0.3074117399F, 0.3078694887F, 0.3083274307F,
  158501. 0.3087855653F, 0.3092438920F, 0.3097024104F, 0.3101611199F,
  158502. 0.3106200200F, 0.3110791103F, 0.3115383902F, 0.3119978592F,
  158503. 0.3124575169F, 0.3129173627F, 0.3133773961F, 0.3138376166F,
  158504. 0.3142980238F, 0.3147586170F, 0.3152193959F, 0.3156803598F,
  158505. 0.3161415084F, 0.3166028410F, 0.3170643573F, 0.3175260566F,
  158506. 0.3179879384F, 0.3184500023F, 0.3189122478F, 0.3193746743F,
  158507. 0.3198372814F, 0.3203000685F, 0.3207630351F, 0.3212261807F,
  158508. 0.3216895048F, 0.3221530069F, 0.3226166865F, 0.3230805430F,
  158509. 0.3235445760F, 0.3240087849F, 0.3244731693F, 0.3249377285F,
  158510. 0.3254024622F, 0.3258673698F, 0.3263324507F, 0.3267977045F,
  158511. 0.3272631306F, 0.3277287286F, 0.3281944978F, 0.3286604379F,
  158512. 0.3291265482F, 0.3295928284F, 0.3300592777F, 0.3305258958F,
  158513. 0.3309926821F, 0.3314596361F, 0.3319267573F, 0.3323940451F,
  158514. 0.3328614990F, 0.3333291186F, 0.3337969033F, 0.3342648525F,
  158515. 0.3347329658F, 0.3352012427F, 0.3356696825F, 0.3361382849F,
  158516. 0.3366070492F, 0.3370759749F, 0.3375450616F, 0.3380143087F,
  158517. 0.3384837156F, 0.3389532819F, 0.3394230071F, 0.3398928905F,
  158518. 0.3403629317F, 0.3408331302F, 0.3413034854F, 0.3417739967F,
  158519. 0.3422446638F, 0.3427154860F, 0.3431864628F, 0.3436575938F,
  158520. 0.3441288782F, 0.3446003158F, 0.3450719058F, 0.3455436478F,
  158521. 0.3460155412F, 0.3464875856F, 0.3469597804F, 0.3474321250F,
  158522. 0.3479046189F, 0.3483772617F, 0.3488500527F, 0.3493229914F,
  158523. 0.3497960774F, 0.3502693100F, 0.3507426887F, 0.3512162131F,
  158524. 0.3516898825F, 0.3521636965F, 0.3526376545F, 0.3531117559F,
  158525. 0.3535860003F, 0.3540603870F, 0.3545349157F, 0.3550095856F,
  158526. 0.3554843964F, 0.3559593474F, 0.3564344381F, 0.3569096680F,
  158527. 0.3573850366F, 0.3578605432F, 0.3583361875F, 0.3588119687F,
  158528. 0.3592878865F, 0.3597639402F, 0.3602401293F, 0.3607164533F,
  158529. 0.3611929117F, 0.3616695038F, 0.3621462292F, 0.3626230873F,
  158530. 0.3631000776F, 0.3635771995F, 0.3640544525F, 0.3645318360F,
  158531. 0.3650093496F, 0.3654869926F, 0.3659647645F, 0.3664426648F,
  158532. 0.3669206930F, 0.3673988484F, 0.3678771306F, 0.3683555390F,
  158533. 0.3688340731F, 0.3693127322F, 0.3697915160F, 0.3702704237F,
  158534. 0.3707494549F, 0.3712286091F, 0.3717078857F, 0.3721872840F,
  158535. 0.3726668037F, 0.3731464441F, 0.3736262047F, 0.3741060850F,
  158536. 0.3745860843F, 0.3750662023F, 0.3755464382F, 0.3760267915F,
  158537. 0.3765072618F, 0.3769878484F, 0.3774685509F, 0.3779493686F,
  158538. 0.3784303010F, 0.3789113475F, 0.3793925076F, 0.3798737809F,
  158539. 0.3803551666F, 0.3808366642F, 0.3813182733F, 0.3817999932F,
  158540. 0.3822818234F, 0.3827637633F, 0.3832458124F, 0.3837279702F,
  158541. 0.3842102360F, 0.3846926093F, 0.3851750897F, 0.3856576764F,
  158542. 0.3861403690F, 0.3866231670F, 0.3871060696F, 0.3875890765F,
  158543. 0.3880721870F, 0.3885554007F, 0.3890387168F, 0.3895221349F,
  158544. 0.3900056544F, 0.3904892748F, 0.3909729955F, 0.3914568160F,
  158545. 0.3919407356F, 0.3924247539F, 0.3929088702F, 0.3933930841F,
  158546. 0.3938773949F, 0.3943618021F, 0.3948463052F, 0.3953309035F,
  158547. 0.3958155966F, 0.3963003838F, 0.3967852646F, 0.3972702385F,
  158548. 0.3977553048F, 0.3982404631F, 0.3987257127F, 0.3992110531F,
  158549. 0.3996964838F, 0.4001820041F, 0.4006676136F, 0.4011533116F,
  158550. 0.4016390976F, 0.4021249710F, 0.4026109313F, 0.4030969779F,
  158551. 0.4035831102F, 0.4040693277F, 0.4045556299F, 0.4050420160F,
  158552. 0.4055284857F, 0.4060150383F, 0.4065016732F, 0.4069883899F,
  158553. 0.4074751879F, 0.4079620665F, 0.4084490252F, 0.4089360635F,
  158554. 0.4094231807F, 0.4099103763F, 0.4103976498F, 0.4108850005F,
  158555. 0.4113724280F, 0.4118599315F, 0.4123475107F, 0.4128351648F,
  158556. 0.4133228934F, 0.4138106959F, 0.4142985716F, 0.4147865201F,
  158557. 0.4152745408F, 0.4157626330F, 0.4162507963F, 0.4167390301F,
  158558. 0.4172273337F, 0.4177157067F, 0.4182041484F, 0.4186926583F,
  158559. 0.4191812359F, 0.4196698805F, 0.4201585915F, 0.4206473685F,
  158560. 0.4211362108F, 0.4216251179F, 0.4221140892F, 0.4226031241F,
  158561. 0.4230922221F, 0.4235813826F, 0.4240706050F, 0.4245598887F,
  158562. 0.4250492332F, 0.4255386379F, 0.4260281022F, 0.4265176256F,
  158563. 0.4270072075F, 0.4274968473F, 0.4279865445F, 0.4284762984F,
  158564. 0.4289661086F, 0.4294559743F, 0.4299458951F, 0.4304358704F,
  158565. 0.4309258996F, 0.4314159822F, 0.4319061175F, 0.4323963050F,
  158566. 0.4328865441F, 0.4333768342F, 0.4338671749F, 0.4343575654F,
  158567. 0.4348480052F, 0.4353384938F, 0.4358290306F, 0.4363196149F,
  158568. 0.4368102463F, 0.4373009241F, 0.4377916478F, 0.4382824168F,
  158569. 0.4387732305F, 0.4392640884F, 0.4397549899F, 0.4402459343F,
  158570. 0.4407369212F, 0.4412279499F, 0.4417190198F, 0.4422101305F,
  158571. 0.4427012813F, 0.4431924717F, 0.4436837010F, 0.4441749686F,
  158572. 0.4446662742F, 0.4451576169F, 0.4456489963F, 0.4461404118F,
  158573. 0.4466318628F, 0.4471233487F, 0.4476148690F, 0.4481064230F,
  158574. 0.4485980103F, 0.4490896302F, 0.4495812821F, 0.4500729654F,
  158575. 0.4505646797F, 0.4510564243F, 0.4515481986F, 0.4520400021F,
  158576. 0.4525318341F, 0.4530236942F, 0.4535155816F, 0.4540074959F,
  158577. 0.4544994365F, 0.4549914028F, 0.4554833941F, 0.4559754100F,
  158578. 0.4564674499F, 0.4569595131F, 0.4574515991F, 0.4579437074F,
  158579. 0.4584358372F, 0.4589279881F, 0.4594201595F, 0.4599123508F,
  158580. 0.4604045615F, 0.4608967908F, 0.4613890383F, 0.4618813034F,
  158581. 0.4623735855F, 0.4628658841F, 0.4633581984F, 0.4638505281F,
  158582. 0.4643428724F, 0.4648352308F, 0.4653276028F, 0.4658199877F,
  158583. 0.4663123849F, 0.4668047940F, 0.4672972143F, 0.4677896451F,
  158584. 0.4682820861F, 0.4687745365F, 0.4692669958F, 0.4697594634F,
  158585. 0.4702519387F, 0.4707444211F, 0.4712369102F, 0.4717294052F,
  158586. 0.4722219056F, 0.4727144109F, 0.4732069204F, 0.4736994336F,
  158587. 0.4741919498F, 0.4746844686F, 0.4751769893F, 0.4756695113F,
  158588. 0.4761620341F, 0.4766545571F, 0.4771470797F, 0.4776396013F,
  158589. 0.4781321213F, 0.4786246392F, 0.4791171544F, 0.4796096663F,
  158590. 0.4801021744F, 0.4805946779F, 0.4810871765F, 0.4815796694F,
  158591. 0.4820721561F, 0.4825646360F, 0.4830571086F, 0.4835495732F,
  158592. 0.4840420293F, 0.4845344763F, 0.4850269136F, 0.4855193407F,
  158593. 0.4860117569F, 0.4865041617F, 0.4869965545F, 0.4874889347F,
  158594. 0.4879813018F, 0.4884736551F, 0.4889659941F, 0.4894583182F,
  158595. 0.4899506268F, 0.4904429193F, 0.4909351952F, 0.4914274538F,
  158596. 0.4919196947F, 0.4924119172F, 0.4929041207F, 0.4933963046F,
  158597. 0.4938884685F, 0.4943806116F, 0.4948727335F, 0.4953648335F,
  158598. 0.4958569110F, 0.4963489656F, 0.4968409965F, 0.4973330032F,
  158599. 0.4978249852F, 0.4983169419F, 0.4988088726F, 0.4993007768F,
  158600. 0.4997926539F, 0.5002845034F, 0.5007763247F, 0.5012681171F,
  158601. 0.5017598801F, 0.5022516132F, 0.5027433157F, 0.5032349871F,
  158602. 0.5037266268F, 0.5042182341F, 0.5047098086F, 0.5052013497F,
  158603. 0.5056928567F, 0.5061843292F, 0.5066757664F, 0.5071671679F,
  158604. 0.5076585330F, 0.5081498613F, 0.5086411520F, 0.5091324047F,
  158605. 0.5096236187F, 0.5101147934F, 0.5106059284F, 0.5110970230F,
  158606. 0.5115880766F, 0.5120790887F, 0.5125700587F, 0.5130609860F,
  158607. 0.5135518700F, 0.5140427102F, 0.5145335059F, 0.5150242566F,
  158608. 0.5155149618F, 0.5160056208F, 0.5164962331F, 0.5169867980F,
  158609. 0.5174773151F, 0.5179677837F, 0.5184582033F, 0.5189485733F,
  158610. 0.5194388931F, 0.5199291621F, 0.5204193798F, 0.5209095455F,
  158611. 0.5213996588F, 0.5218897190F, 0.5223797256F, 0.5228696779F,
  158612. 0.5233595755F, 0.5238494177F, 0.5243392039F, 0.5248289337F,
  158613. 0.5253186063F, 0.5258082213F, 0.5262977781F, 0.5267872760F,
  158614. 0.5272767146F, 0.5277660932F, 0.5282554112F, 0.5287446682F,
  158615. 0.5292338635F, 0.5297229965F, 0.5302120667F, 0.5307010736F,
  158616. 0.5311900164F, 0.5316788947F, 0.5321677079F, 0.5326564554F,
  158617. 0.5331451366F, 0.5336337511F, 0.5341222981F, 0.5346107771F,
  158618. 0.5350991876F, 0.5355875290F, 0.5360758007F, 0.5365640021F,
  158619. 0.5370521327F, 0.5375401920F, 0.5380281792F, 0.5385160939F,
  158620. 0.5390039355F, 0.5394917034F, 0.5399793971F, 0.5404670159F,
  158621. 0.5409545594F, 0.5414420269F, 0.5419294179F, 0.5424167318F,
  158622. 0.5429039680F, 0.5433911261F, 0.5438782053F, 0.5443652051F,
  158623. 0.5448521250F, 0.5453389644F, 0.5458257228F, 0.5463123995F,
  158624. 0.5467989940F, 0.5472855057F, 0.5477719341F, 0.5482582786F,
  158625. 0.5487445387F, 0.5492307137F, 0.5497168031F, 0.5502028063F,
  158626. 0.5506887228F, 0.5511745520F, 0.5516602934F, 0.5521459463F,
  158627. 0.5526315103F, 0.5531169847F, 0.5536023690F, 0.5540876626F,
  158628. 0.5545728649F, 0.5550579755F, 0.5555429937F, 0.5560279189F,
  158629. 0.5565127507F, 0.5569974884F, 0.5574821315F, 0.5579666794F,
  158630. 0.5584511316F, 0.5589354875F, 0.5594197465F, 0.5599039080F,
  158631. 0.5603879716F, 0.5608719367F, 0.5613558026F, 0.5618395689F,
  158632. 0.5623232350F, 0.5628068002F, 0.5632902642F, 0.5637736262F,
  158633. 0.5642568858F, 0.5647400423F, 0.5652230953F, 0.5657060442F,
  158634. 0.5661888883F, 0.5666716272F, 0.5671542603F, 0.5676367870F,
  158635. 0.5681192069F, 0.5686015192F, 0.5690837235F, 0.5695658192F,
  158636. 0.5700478058F, 0.5705296827F, 0.5710114494F, 0.5714931052F,
  158637. 0.5719746497F, 0.5724560822F, 0.5729374023F, 0.5734186094F,
  158638. 0.5738997029F, 0.5743806823F, 0.5748615470F, 0.5753422965F,
  158639. 0.5758229301F, 0.5763034475F, 0.5767838480F, 0.5772641310F,
  158640. 0.5777442960F, 0.5782243426F, 0.5787042700F, 0.5791840778F,
  158641. 0.5796637654F, 0.5801433322F, 0.5806227778F, 0.5811021016F,
  158642. 0.5815813029F, 0.5820603814F, 0.5825393363F, 0.5830181673F,
  158643. 0.5834968737F, 0.5839754549F, 0.5844539105F, 0.5849322399F,
  158644. 0.5854104425F, 0.5858885179F, 0.5863664653F, 0.5868442844F,
  158645. 0.5873219746F, 0.5877995353F, 0.5882769660F, 0.5887542661F,
  158646. 0.5892314351F, 0.5897084724F, 0.5901853776F, 0.5906621500F,
  158647. 0.5911387892F, 0.5916152945F, 0.5920916655F, 0.5925679016F,
  158648. 0.5930440022F, 0.5935199669F, 0.5939957950F, 0.5944714861F,
  158649. 0.5949470396F, 0.5954224550F, 0.5958977317F, 0.5963728692F,
  158650. 0.5968478669F, 0.5973227244F, 0.5977974411F, 0.5982720163F,
  158651. 0.5987464497F, 0.5992207407F, 0.5996948887F, 0.6001688932F,
  158652. 0.6006427537F, 0.6011164696F, 0.6015900405F, 0.6020634657F,
  158653. 0.6025367447F, 0.6030098770F, 0.6034828621F, 0.6039556995F,
  158654. 0.6044283885F, 0.6049009288F, 0.6053733196F, 0.6058455606F,
  158655. 0.6063176512F, 0.6067895909F, 0.6072613790F, 0.6077330152F,
  158656. 0.6082044989F, 0.6086758295F, 0.6091470065F, 0.6096180294F,
  158657. 0.6100888977F, 0.6105596108F, 0.6110301682F, 0.6115005694F,
  158658. 0.6119708139F, 0.6124409011F, 0.6129108305F, 0.6133806017F,
  158659. 0.6138502139F, 0.6143196669F, 0.6147889599F, 0.6152580926F,
  158660. 0.6157270643F, 0.6161958746F, 0.6166645230F, 0.6171330088F,
  158661. 0.6176013317F, 0.6180694910F, 0.6185374863F, 0.6190053171F,
  158662. 0.6194729827F, 0.6199404828F, 0.6204078167F, 0.6208749841F,
  158663. 0.6213419842F, 0.6218088168F, 0.6222754811F, 0.6227419768F,
  158664. 0.6232083032F, 0.6236744600F, 0.6241404465F, 0.6246062622F,
  158665. 0.6250719067F, 0.6255373795F, 0.6260026799F, 0.6264678076F,
  158666. 0.6269327619F, 0.6273975425F, 0.6278621487F, 0.6283265800F,
  158667. 0.6287908361F, 0.6292549163F, 0.6297188201F, 0.6301825471F,
  158668. 0.6306460966F, 0.6311094683F, 0.6315726617F, 0.6320356761F,
  158669. 0.6324985111F, 0.6329611662F, 0.6334236410F, 0.6338859348F,
  158670. 0.6343480472F, 0.6348099777F, 0.6352717257F, 0.6357332909F,
  158671. 0.6361946726F, 0.6366558704F, 0.6371168837F, 0.6375777122F,
  158672. 0.6380383552F, 0.6384988123F, 0.6389590830F, 0.6394191668F,
  158673. 0.6398790631F, 0.6403387716F, 0.6407982916F, 0.6412576228F,
  158674. 0.6417167645F, 0.6421757163F, 0.6426344778F, 0.6430930483F,
  158675. 0.6435514275F, 0.6440096149F, 0.6444676098F, 0.6449254119F,
  158676. 0.6453830207F, 0.6458404356F, 0.6462976562F, 0.6467546820F,
  158677. 0.6472115125F, 0.6476681472F, 0.6481245856F, 0.6485808273F,
  158678. 0.6490368717F, 0.6494927183F, 0.6499483667F, 0.6504038164F,
  158679. 0.6508590670F, 0.6513141178F, 0.6517689684F, 0.6522236185F,
  158680. 0.6526780673F, 0.6531323146F, 0.6535863598F, 0.6540402024F,
  158681. 0.6544938419F, 0.6549472779F, 0.6554005099F, 0.6558535373F,
  158682. 0.6563063598F, 0.6567589769F, 0.6572113880F, 0.6576635927F,
  158683. 0.6581155906F, 0.6585673810F, 0.6590189637F, 0.6594703380F,
  158684. 0.6599215035F, 0.6603724598F, 0.6608232064F, 0.6612737427F,
  158685. 0.6617240684F, 0.6621741829F, 0.6626240859F, 0.6630737767F,
  158686. 0.6635232550F, 0.6639725202F, 0.6644215720F, 0.6648704098F,
  158687. 0.6653190332F, 0.6657674417F, 0.6662156348F, 0.6666636121F,
  158688. 0.6671113731F, 0.6675589174F, 0.6680062445F, 0.6684533538F,
  158689. 0.6689002450F, 0.6693469177F, 0.6697933712F, 0.6702396052F,
  158690. 0.6706856193F, 0.6711314129F, 0.6715769855F, 0.6720223369F,
  158691. 0.6724674664F, 0.6729123736F, 0.6733570581F, 0.6738015194F,
  158692. 0.6742457570F, 0.6746897706F, 0.6751335596F, 0.6755771236F,
  158693. 0.6760204621F, 0.6764635747F, 0.6769064609F, 0.6773491204F,
  158694. 0.6777915525F, 0.6782337570F, 0.6786757332F, 0.6791174809F,
  158695. 0.6795589995F, 0.6800002886F, 0.6804413477F, 0.6808821765F,
  158696. 0.6813227743F, 0.6817631409F, 0.6822032758F, 0.6826431785F,
  158697. 0.6830828485F, 0.6835222855F, 0.6839614890F, 0.6844004585F,
  158698. 0.6848391936F, 0.6852776939F, 0.6857159589F, 0.6861539883F,
  158699. 0.6865917815F, 0.6870293381F, 0.6874666576F, 0.6879037398F,
  158700. 0.6883405840F, 0.6887771899F, 0.6892135571F, 0.6896496850F,
  158701. 0.6900855733F, 0.6905212216F, 0.6909566294F, 0.6913917963F,
  158702. 0.6918267218F, 0.6922614055F, 0.6926958471F, 0.6931300459F,
  158703. 0.6935640018F, 0.6939977141F, 0.6944311825F, 0.6948644066F,
  158704. 0.6952973859F, 0.6957301200F, 0.6961626085F, 0.6965948510F,
  158705. 0.6970268470F, 0.6974585961F, 0.6978900980F, 0.6983213521F,
  158706. 0.6987523580F, 0.6991831154F, 0.6996136238F, 0.7000438828F,
  158707. 0.7004738921F, 0.7009036510F, 0.7013331594F, 0.7017624166F,
  158708. 0.7021914224F, 0.7026201763F, 0.7030486779F, 0.7034769268F,
  158709. 0.7039049226F, 0.7043326648F, 0.7047601531F, 0.7051873870F,
  158710. 0.7056143662F, 0.7060410902F, 0.7064675586F, 0.7068937711F,
  158711. 0.7073197271F, 0.7077454264F, 0.7081708684F, 0.7085960529F,
  158712. 0.7090209793F, 0.7094456474F, 0.7098700566F, 0.7102942066F,
  158713. 0.7107180970F, 0.7111417274F, 0.7115650974F, 0.7119882066F,
  158714. 0.7124110545F, 0.7128336409F, 0.7132559653F, 0.7136780272F,
  158715. 0.7140998264F, 0.7145213624F, 0.7149426348F, 0.7153636433F,
  158716. 0.7157843874F, 0.7162048668F, 0.7166250810F, 0.7170450296F,
  158717. 0.7174647124F, 0.7178841289F, 0.7183032786F, 0.7187221613F,
  158718. 0.7191407765F, 0.7195591239F, 0.7199772030F, 0.7203950135F,
  158719. 0.7208125550F, 0.7212298271F, 0.7216468294F, 0.7220635616F,
  158720. 0.7224800233F, 0.7228962140F, 0.7233121335F, 0.7237277813F,
  158721. 0.7241431571F, 0.7245582604F, 0.7249730910F, 0.7253876484F,
  158722. 0.7258019322F, 0.7262159422F, 0.7266296778F, 0.7270431388F,
  158723. 0.7274563247F, 0.7278692353F, 0.7282818700F, 0.7286942287F,
  158724. 0.7291063108F, 0.7295181160F, 0.7299296440F, 0.7303408944F,
  158725. 0.7307518669F, 0.7311625609F, 0.7315729763F, 0.7319831126F,
  158726. 0.7323929695F, 0.7328025466F, 0.7332118435F, 0.7336208600F,
  158727. 0.7340295955F, 0.7344380499F, 0.7348462226F, 0.7352541134F,
  158728. 0.7356617220F, 0.7360690478F, 0.7364760907F, 0.7368828502F,
  158729. 0.7372893259F, 0.7376955176F, 0.7381014249F, 0.7385070475F,
  158730. 0.7389123849F, 0.7393174368F, 0.7397222029F, 0.7401266829F,
  158731. 0.7405308763F, 0.7409347829F, 0.7413384023F, 0.7417417341F,
  158732. 0.7421447780F, 0.7425475338F, 0.7429500009F, 0.7433521791F,
  158733. 0.7437540681F, 0.7441556674F, 0.7445569769F, 0.7449579960F,
  158734. 0.7453587245F, 0.7457591621F, 0.7461593084F, 0.7465591631F,
  158735. 0.7469587259F, 0.7473579963F, 0.7477569741F, 0.7481556590F,
  158736. 0.7485540506F, 0.7489521486F, 0.7493499526F, 0.7497474623F,
  158737. 0.7501446775F, 0.7505415977F, 0.7509382227F, 0.7513345521F,
  158738. 0.7517305856F, 0.7521263229F, 0.7525217636F, 0.7529169074F,
  158739. 0.7533117541F, 0.7537063032F, 0.7541005545F, 0.7544945076F,
  158740. 0.7548881623F, 0.7552815182F, 0.7556745749F, 0.7560673323F,
  158741. 0.7564597899F, 0.7568519474F, 0.7572438046F, 0.7576353611F,
  158742. 0.7580266166F, 0.7584175708F, 0.7588082235F, 0.7591985741F,
  158743. 0.7595886226F, 0.7599783685F, 0.7603678116F, 0.7607569515F,
  158744. 0.7611457879F, 0.7615343206F, 0.7619225493F, 0.7623104735F,
  158745. 0.7626980931F, 0.7630854078F, 0.7634724171F, 0.7638591209F,
  158746. 0.7642455188F, 0.7646316106F, 0.7650173959F, 0.7654028744F,
  158747. 0.7657880459F, 0.7661729100F, 0.7665574664F, 0.7669417150F,
  158748. 0.7673256553F, 0.7677092871F, 0.7680926100F, 0.7684756239F,
  158749. 0.7688583284F, 0.7692407232F, 0.7696228080F, 0.7700045826F,
  158750. 0.7703860467F, 0.7707671999F, 0.7711480420F, 0.7715285728F,
  158751. 0.7719087918F, 0.7722886989F, 0.7726682938F, 0.7730475762F,
  158752. 0.7734265458F, 0.7738052023F, 0.7741835454F, 0.7745615750F,
  158753. 0.7749392906F, 0.7753166921F, 0.7756937791F, 0.7760705514F,
  158754. 0.7764470087F, 0.7768231508F, 0.7771989773F, 0.7775744880F,
  158755. 0.7779496827F, 0.7783245610F, 0.7786991227F, 0.7790733676F,
  158756. 0.7794472953F, 0.7798209056F, 0.7801941982F, 0.7805671729F,
  158757. 0.7809398294F, 0.7813121675F, 0.7816841869F, 0.7820558873F,
  158758. 0.7824272684F, 0.7827983301F, 0.7831690720F, 0.7835394940F,
  158759. 0.7839095957F, 0.7842793768F, 0.7846488373F, 0.7850179767F,
  158760. 0.7853867948F, 0.7857552914F, 0.7861234663F, 0.7864913191F,
  158761. 0.7868588497F, 0.7872260578F, 0.7875929431F, 0.7879595055F,
  158762. 0.7883257445F, 0.7886916601F, 0.7890572520F, 0.7894225198F,
  158763. 0.7897874635F, 0.7901520827F, 0.7905163772F, 0.7908803468F,
  158764. 0.7912439912F, 0.7916073102F, 0.7919703035F, 0.7923329710F,
  158765. 0.7926953124F, 0.7930573274F, 0.7934190158F, 0.7937803774F,
  158766. 0.7941414120F, 0.7945021193F, 0.7948624991F, 0.7952225511F,
  158767. 0.7955822752F, 0.7959416711F, 0.7963007387F, 0.7966594775F,
  158768. 0.7970178875F, 0.7973759685F, 0.7977337201F, 0.7980911422F,
  158769. 0.7984482346F, 0.7988049970F, 0.7991614292F, 0.7995175310F,
  158770. 0.7998733022F, 0.8002287426F, 0.8005838519F, 0.8009386299F,
  158771. 0.8012930765F, 0.8016471914F, 0.8020009744F, 0.8023544253F,
  158772. 0.8027075438F, 0.8030603298F, 0.8034127831F, 0.8037649035F,
  158773. 0.8041166906F, 0.8044681445F, 0.8048192647F, 0.8051700512F,
  158774. 0.8055205038F, 0.8058706222F, 0.8062204062F, 0.8065698556F,
  158775. 0.8069189702F, 0.8072677499F, 0.8076161944F, 0.8079643036F,
  158776. 0.8083120772F, 0.8086595151F, 0.8090066170F, 0.8093533827F,
  158777. 0.8096998122F, 0.8100459051F, 0.8103916613F, 0.8107370806F,
  158778. 0.8110821628F, 0.8114269077F, 0.8117713151F, 0.8121153849F,
  158779. 0.8124591169F, 0.8128025108F, 0.8131455666F, 0.8134882839F,
  158780. 0.8138306627F, 0.8141727027F, 0.8145144038F, 0.8148557658F,
  158781. 0.8151967886F, 0.8155374718F, 0.8158778154F, 0.8162178192F,
  158782. 0.8165574830F, 0.8168968067F, 0.8172357900F, 0.8175744328F,
  158783. 0.8179127349F, 0.8182506962F, 0.8185883164F, 0.8189255955F,
  158784. 0.8192625332F, 0.8195991295F, 0.8199353840F, 0.8202712967F,
  158785. 0.8206068673F, 0.8209420958F, 0.8212769820F, 0.8216115256F,
  158786. 0.8219457266F, 0.8222795848F, 0.8226131000F, 0.8229462721F,
  158787. 0.8232791009F, 0.8236115863F, 0.8239437280F, 0.8242755260F,
  158788. 0.8246069801F, 0.8249380901F, 0.8252688559F, 0.8255992774F,
  158789. 0.8259293544F, 0.8262590867F, 0.8265884741F, 0.8269175167F,
  158790. 0.8272462141F, 0.8275745663F, 0.8279025732F, 0.8282302344F,
  158791. 0.8285575501F, 0.8288845199F, 0.8292111437F, 0.8295374215F,
  158792. 0.8298633530F, 0.8301889382F, 0.8305141768F, 0.8308390688F,
  158793. 0.8311636141F, 0.8314878124F, 0.8318116637F, 0.8321351678F,
  158794. 0.8324583246F, 0.8327811340F, 0.8331035957F, 0.8334257098F,
  158795. 0.8337474761F, 0.8340688944F, 0.8343899647F, 0.8347106867F,
  158796. 0.8350310605F, 0.8353510857F, 0.8356707624F, 0.8359900904F,
  158797. 0.8363090696F, 0.8366276999F, 0.8369459811F, 0.8372639131F,
  158798. 0.8375814958F, 0.8378987292F, 0.8382156130F, 0.8385321472F,
  158799. 0.8388483316F, 0.8391641662F, 0.8394796508F, 0.8397947853F,
  158800. 0.8401095697F, 0.8404240037F, 0.8407380873F, 0.8410518204F,
  158801. 0.8413652029F, 0.8416782347F, 0.8419909156F, 0.8423032456F,
  158802. 0.8426152245F, 0.8429268523F, 0.8432381289F, 0.8435490541F,
  158803. 0.8438596279F, 0.8441698502F, 0.8444797208F, 0.8447892396F,
  158804. 0.8450984067F, 0.8454072218F, 0.8457156849F, 0.8460237959F,
  158805. 0.8463315547F, 0.8466389612F, 0.8469460154F, 0.8472527170F,
  158806. 0.8475590661F, 0.8478650625F, 0.8481707063F, 0.8484759971F,
  158807. 0.8487809351F, 0.8490855201F, 0.8493897521F, 0.8496936308F,
  158808. 0.8499971564F, 0.8503003286F, 0.8506031474F, 0.8509056128F,
  158809. 0.8512077246F, 0.8515094828F, 0.8518108872F, 0.8521119379F,
  158810. 0.8524126348F, 0.8527129777F, 0.8530129666F, 0.8533126015F,
  158811. 0.8536118822F, 0.8539108087F, 0.8542093809F, 0.8545075988F,
  158812. 0.8548054623F, 0.8551029712F, 0.8554001257F, 0.8556969255F,
  158813. 0.8559933707F, 0.8562894611F, 0.8565851968F, 0.8568805775F,
  158814. 0.8571756034F, 0.8574702743F, 0.8577645902F, 0.8580585509F,
  158815. 0.8583521566F, 0.8586454070F, 0.8589383021F, 0.8592308420F,
  158816. 0.8595230265F, 0.8598148556F, 0.8601063292F, 0.8603974473F,
  158817. 0.8606882098F, 0.8609786167F, 0.8612686680F, 0.8615583636F,
  158818. 0.8618477034F, 0.8621366874F, 0.8624253156F, 0.8627135878F,
  158819. 0.8630015042F, 0.8632890646F, 0.8635762690F, 0.8638631173F,
  158820. 0.8641496096F, 0.8644357457F, 0.8647215257F, 0.8650069495F,
  158821. 0.8652920171F, 0.8655767283F, 0.8658610833F, 0.8661450820F,
  158822. 0.8664287243F, 0.8667120102F, 0.8669949397F, 0.8672775127F,
  158823. 0.8675597293F, 0.8678415894F, 0.8681230929F, 0.8684042398F,
  158824. 0.8686850302F, 0.8689654640F, 0.8692455412F, 0.8695252617F,
  158825. 0.8698046255F, 0.8700836327F, 0.8703622831F, 0.8706405768F,
  158826. 0.8709185138F, 0.8711960940F, 0.8714733174F, 0.8717501840F,
  158827. 0.8720266939F, 0.8723028469F, 0.8725786430F, 0.8728540824F,
  158828. 0.8731291648F, 0.8734038905F, 0.8736782592F, 0.8739522711F,
  158829. 0.8742259261F, 0.8744992242F, 0.8747721653F, 0.8750447496F,
  158830. 0.8753169770F, 0.8755888475F, 0.8758603611F, 0.8761315177F,
  158831. 0.8764023175F, 0.8766727603F, 0.8769428462F, 0.8772125752F,
  158832. 0.8774819474F, 0.8777509626F, 0.8780196209F, 0.8782879224F,
  158833. 0.8785558669F, 0.8788234546F, 0.8790906854F, 0.8793575594F,
  158834. 0.8796240765F, 0.8798902368F, 0.8801560403F, 0.8804214870F,
  158835. 0.8806865768F, 0.8809513099F, 0.8812156863F, 0.8814797059F,
  158836. 0.8817433687F, 0.8820066749F, 0.8822696243F, 0.8825322171F,
  158837. 0.8827944532F, 0.8830563327F, 0.8833178556F, 0.8835790219F,
  158838. 0.8838398316F, 0.8841002848F, 0.8843603815F, 0.8846201217F,
  158839. 0.8848795054F, 0.8851385327F, 0.8853972036F, 0.8856555182F,
  158840. 0.8859134764F, 0.8861710783F, 0.8864283239F, 0.8866852133F,
  158841. 0.8869417464F, 0.8871979234F, 0.8874537443F, 0.8877092090F,
  158842. 0.8879643177F, 0.8882190704F, 0.8884734671F, 0.8887275078F,
  158843. 0.8889811927F, 0.8892345216F, 0.8894874948F, 0.8897401122F,
  158844. 0.8899923738F, 0.8902442798F, 0.8904958301F, 0.8907470248F,
  158845. 0.8909978640F, 0.8912483477F, 0.8914984759F, 0.8917482487F,
  158846. 0.8919976662F, 0.8922467284F, 0.8924954353F, 0.8927437871F,
  158847. 0.8929917837F, 0.8932394252F, 0.8934867118F, 0.8937336433F,
  158848. 0.8939802199F, 0.8942264417F, 0.8944723087F, 0.8947178210F,
  158849. 0.8949629785F, 0.8952077815F, 0.8954522299F, 0.8956963239F,
  158850. 0.8959400634F, 0.8961834486F, 0.8964264795F, 0.8966691561F,
  158851. 0.8969114786F, 0.8971534470F, 0.8973950614F, 0.8976363219F,
  158852. 0.8978772284F, 0.8981177812F, 0.8983579802F, 0.8985978256F,
  158853. 0.8988373174F, 0.8990764556F, 0.8993152405F, 0.8995536720F,
  158854. 0.8997917502F, 0.9000294751F, 0.9002668470F, 0.9005038658F,
  158855. 0.9007405317F, 0.9009768446F, 0.9012128048F, 0.9014484123F,
  158856. 0.9016836671F, 0.9019185693F, 0.9021531191F, 0.9023873165F,
  158857. 0.9026211616F, 0.9028546546F, 0.9030877954F, 0.9033205841F,
  158858. 0.9035530210F, 0.9037851059F, 0.9040168392F, 0.9042482207F,
  158859. 0.9044792507F, 0.9047099293F, 0.9049402564F, 0.9051702323F,
  158860. 0.9053998569F, 0.9056291305F, 0.9058580531F, 0.9060866248F,
  158861. 0.9063148457F, 0.9065427159F, 0.9067702355F, 0.9069974046F,
  158862. 0.9072242233F, 0.9074506917F, 0.9076768100F, 0.9079025782F,
  158863. 0.9081279964F, 0.9083530647F, 0.9085777833F, 0.9088021523F,
  158864. 0.9090261717F, 0.9092498417F, 0.9094731623F, 0.9096961338F,
  158865. 0.9099187561F, 0.9101410295F, 0.9103629540F, 0.9105845297F,
  158866. 0.9108057568F, 0.9110266354F, 0.9112471656F, 0.9114673475F,
  158867. 0.9116871812F, 0.9119066668F, 0.9121258046F, 0.9123445945F,
  158868. 0.9125630367F, 0.9127811314F, 0.9129988786F, 0.9132162785F,
  158869. 0.9134333312F, 0.9136500368F, 0.9138663954F, 0.9140824073F,
  158870. 0.9142980724F, 0.9145133910F, 0.9147283632F, 0.9149429890F,
  158871. 0.9151572687F, 0.9153712023F, 0.9155847900F, 0.9157980319F,
  158872. 0.9160109282F, 0.9162234790F, 0.9164356844F, 0.9166475445F,
  158873. 0.9168590595F, 0.9170702296F, 0.9172810548F, 0.9174915354F,
  158874. 0.9177016714F, 0.9179114629F, 0.9181209102F, 0.9183300134F,
  158875. 0.9185387726F, 0.9187471879F, 0.9189552595F, 0.9191629876F,
  158876. 0.9193703723F, 0.9195774136F, 0.9197841119F, 0.9199904672F,
  158877. 0.9201964797F, 0.9204021495F, 0.9206074767F, 0.9208124616F,
  158878. 0.9210171043F, 0.9212214049F, 0.9214253636F, 0.9216289805F,
  158879. 0.9218322558F, 0.9220351896F, 0.9222377821F, 0.9224400335F,
  158880. 0.9226419439F, 0.9228435134F, 0.9230447423F, 0.9232456307F,
  158881. 0.9234461787F, 0.9236463865F, 0.9238462543F, 0.9240457822F,
  158882. 0.9242449704F, 0.9244438190F, 0.9246423282F, 0.9248404983F,
  158883. 0.9250383293F, 0.9252358214F, 0.9254329747F, 0.9256297896F,
  158884. 0.9258262660F, 0.9260224042F, 0.9262182044F, 0.9264136667F,
  158885. 0.9266087913F, 0.9268035783F, 0.9269980280F, 0.9271921405F,
  158886. 0.9273859160F, 0.9275793546F, 0.9277724566F, 0.9279652221F,
  158887. 0.9281576513F, 0.9283497443F, 0.9285415014F, 0.9287329227F,
  158888. 0.9289240084F, 0.9291147586F, 0.9293051737F, 0.9294952536F,
  158889. 0.9296849987F, 0.9298744091F, 0.9300634850F, 0.9302522266F,
  158890. 0.9304406340F, 0.9306287074F, 0.9308164471F, 0.9310038532F,
  158891. 0.9311909259F, 0.9313776654F, 0.9315640719F, 0.9317501455F,
  158892. 0.9319358865F, 0.9321212951F, 0.9323063713F, 0.9324911155F,
  158893. 0.9326755279F, 0.9328596085F, 0.9330433577F, 0.9332267756F,
  158894. 0.9334098623F, 0.9335926182F, 0.9337750434F, 0.9339571380F,
  158895. 0.9341389023F, 0.9343203366F, 0.9345014409F, 0.9346822155F,
  158896. 0.9348626606F, 0.9350427763F, 0.9352225630F, 0.9354020207F,
  158897. 0.9355811498F, 0.9357599503F, 0.9359384226F, 0.9361165667F,
  158898. 0.9362943830F, 0.9364718716F, 0.9366490327F, 0.9368258666F,
  158899. 0.9370023733F, 0.9371785533F, 0.9373544066F, 0.9375299335F,
  158900. 0.9377051341F, 0.9378800087F, 0.9380545576F, 0.9382287809F,
  158901. 0.9384026787F, 0.9385762515F, 0.9387494993F, 0.9389224223F,
  158902. 0.9390950209F, 0.9392672951F, 0.9394392453F, 0.9396108716F,
  158903. 0.9397821743F, 0.9399531536F, 0.9401238096F, 0.9402941427F,
  158904. 0.9404641530F, 0.9406338407F, 0.9408032061F, 0.9409722495F,
  158905. 0.9411409709F, 0.9413093707F, 0.9414774491F, 0.9416452062F,
  158906. 0.9418126424F, 0.9419797579F, 0.9421465528F, 0.9423130274F,
  158907. 0.9424791819F, 0.9426450166F, 0.9428105317F, 0.9429757274F,
  158908. 0.9431406039F, 0.9433051616F, 0.9434694005F, 0.9436333209F,
  158909. 0.9437969232F, 0.9439602074F, 0.9441231739F, 0.9442858229F,
  158910. 0.9444481545F, 0.9446101691F, 0.9447718669F, 0.9449332481F,
  158911. 0.9450943129F, 0.9452550617F, 0.9454154945F, 0.9455756118F,
  158912. 0.9457354136F, 0.9458949003F, 0.9460540721F, 0.9462129292F,
  158913. 0.9463714719F, 0.9465297003F, 0.9466876149F, 0.9468452157F,
  158914. 0.9470025031F, 0.9471594772F, 0.9473161384F, 0.9474724869F,
  158915. 0.9476285229F, 0.9477842466F, 0.9479396584F, 0.9480947585F,
  158916. 0.9482495470F, 0.9484040243F, 0.9485581906F, 0.9487120462F,
  158917. 0.9488655913F, 0.9490188262F, 0.9491717511F, 0.9493243662F,
  158918. 0.9494766718F, 0.9496286683F, 0.9497803557F, 0.9499317345F,
  158919. 0.9500828047F, 0.9502335668F, 0.9503840209F, 0.9505341673F,
  158920. 0.9506840062F, 0.9508335380F, 0.9509827629F, 0.9511316810F,
  158921. 0.9512802928F, 0.9514285984F, 0.9515765982F, 0.9517242923F,
  158922. 0.9518716810F, 0.9520187646F, 0.9521655434F, 0.9523120176F,
  158923. 0.9524581875F, 0.9526040534F, 0.9527496154F, 0.9528948739F,
  158924. 0.9530398292F, 0.9531844814F, 0.9533288310F, 0.9534728780F,
  158925. 0.9536166229F, 0.9537600659F, 0.9539032071F, 0.9540460470F,
  158926. 0.9541885858F, 0.9543308237F, 0.9544727611F, 0.9546143981F,
  158927. 0.9547557351F, 0.9548967723F, 0.9550375100F, 0.9551779485F,
  158928. 0.9553180881F, 0.9554579290F, 0.9555974714F, 0.9557367158F,
  158929. 0.9558756623F, 0.9560143112F, 0.9561526628F, 0.9562907174F,
  158930. 0.9564284752F, 0.9565659366F, 0.9567031017F, 0.9568399710F,
  158931. 0.9569765446F, 0.9571128229F, 0.9572488061F, 0.9573844944F,
  158932. 0.9575198883F, 0.9576549879F, 0.9577897936F, 0.9579243056F,
  158933. 0.9580585242F, 0.9581924497F, 0.9583260824F, 0.9584594226F,
  158934. 0.9585924705F, 0.9587252264F, 0.9588576906F, 0.9589898634F,
  158935. 0.9591217452F, 0.9592533360F, 0.9593846364F, 0.9595156465F,
  158936. 0.9596463666F, 0.9597767971F, 0.9599069382F, 0.9600367901F,
  158937. 0.9601663533F, 0.9602956279F, 0.9604246143F, 0.9605533128F,
  158938. 0.9606817236F, 0.9608098471F, 0.9609376835F, 0.9610652332F,
  158939. 0.9611924963F, 0.9613194733F, 0.9614461644F, 0.9615725699F,
  158940. 0.9616986901F, 0.9618245253F, 0.9619500757F, 0.9620753418F,
  158941. 0.9622003238F, 0.9623250219F, 0.9624494365F, 0.9625735679F,
  158942. 0.9626974163F, 0.9628209821F, 0.9629442656F, 0.9630672671F,
  158943. 0.9631899868F, 0.9633124251F, 0.9634345822F, 0.9635564585F,
  158944. 0.9636780543F, 0.9637993699F, 0.9639204056F, 0.9640411616F,
  158945. 0.9641616383F, 0.9642818359F, 0.9644017549F, 0.9645213955F,
  158946. 0.9646407579F, 0.9647598426F, 0.9648786497F, 0.9649971797F,
  158947. 0.9651154328F, 0.9652334092F, 0.9653511095F, 0.9654685337F,
  158948. 0.9655856823F, 0.9657025556F, 0.9658191538F, 0.9659354773F,
  158949. 0.9660515263F, 0.9661673013F, 0.9662828024F, 0.9663980300F,
  158950. 0.9665129845F, 0.9666276660F, 0.9667420750F, 0.9668562118F,
  158951. 0.9669700766F, 0.9670836698F, 0.9671969917F, 0.9673100425F,
  158952. 0.9674228227F, 0.9675353325F, 0.9676475722F, 0.9677595422F,
  158953. 0.9678712428F, 0.9679826742F, 0.9680938368F, 0.9682047309F,
  158954. 0.9683153569F, 0.9684257150F, 0.9685358056F, 0.9686456289F,
  158955. 0.9687551853F, 0.9688644752F, 0.9689734987F, 0.9690822564F,
  158956. 0.9691907483F, 0.9692989750F, 0.9694069367F, 0.9695146337F,
  158957. 0.9696220663F, 0.9697292349F, 0.9698361398F, 0.9699427813F,
  158958. 0.9700491597F, 0.9701552754F, 0.9702611286F, 0.9703667197F,
  158959. 0.9704720490F, 0.9705771169F, 0.9706819236F, 0.9707864695F,
  158960. 0.9708907549F, 0.9709947802F, 0.9710985456F, 0.9712020514F,
  158961. 0.9713052981F, 0.9714082859F, 0.9715110151F, 0.9716134862F,
  158962. 0.9717156993F, 0.9718176549F, 0.9719193532F, 0.9720207946F,
  158963. 0.9721219794F, 0.9722229080F, 0.9723235806F, 0.9724239976F,
  158964. 0.9725241593F, 0.9726240661F, 0.9727237183F, 0.9728231161F,
  158965. 0.9729222601F, 0.9730211503F, 0.9731197873F, 0.9732181713F,
  158966. 0.9733163027F, 0.9734141817F, 0.9735118088F, 0.9736091842F,
  158967. 0.9737063083F, 0.9738031814F, 0.9738998039F, 0.9739961760F,
  158968. 0.9740922981F, 0.9741881706F, 0.9742837938F, 0.9743791680F,
  158969. 0.9744742935F, 0.9745691707F, 0.9746637999F, 0.9747581814F,
  158970. 0.9748523157F, 0.9749462029F, 0.9750398435F, 0.9751332378F,
  158971. 0.9752263861F, 0.9753192887F, 0.9754119461F, 0.9755043585F,
  158972. 0.9755965262F, 0.9756884496F, 0.9757801291F, 0.9758715650F,
  158973. 0.9759627575F, 0.9760537071F, 0.9761444141F, 0.9762348789F,
  158974. 0.9763251016F, 0.9764150828F, 0.9765048228F, 0.9765943218F,
  158975. 0.9766835802F, 0.9767725984F, 0.9768613767F, 0.9769499154F,
  158976. 0.9770382149F, 0.9771262755F, 0.9772140976F, 0.9773016815F,
  158977. 0.9773890275F, 0.9774761360F, 0.9775630073F, 0.9776496418F,
  158978. 0.9777360398F, 0.9778222016F, 0.9779081277F, 0.9779938182F,
  158979. 0.9780792736F, 0.9781644943F, 0.9782494805F, 0.9783342326F,
  158980. 0.9784187509F, 0.9785030359F, 0.9785870877F, 0.9786709069F,
  158981. 0.9787544936F, 0.9788378484F, 0.9789209714F, 0.9790038631F,
  158982. 0.9790865238F, 0.9791689538F, 0.9792511535F, 0.9793331232F,
  158983. 0.9794148633F, 0.9794963742F, 0.9795776561F, 0.9796587094F,
  158984. 0.9797395345F, 0.9798201316F, 0.9799005013F, 0.9799806437F,
  158985. 0.9800605593F, 0.9801402483F, 0.9802197112F, 0.9802989483F,
  158986. 0.9803779600F, 0.9804567465F, 0.9805353082F, 0.9806136455F,
  158987. 0.9806917587F, 0.9807696482F, 0.9808473143F, 0.9809247574F,
  158988. 0.9810019778F, 0.9810789759F, 0.9811557519F, 0.9812323064F,
  158989. 0.9813086395F, 0.9813847517F, 0.9814606433F, 0.9815363147F,
  158990. 0.9816117662F, 0.9816869981F, 0.9817620108F, 0.9818368047F,
  158991. 0.9819113801F, 0.9819857374F, 0.9820598769F, 0.9821337989F,
  158992. 0.9822075038F, 0.9822809920F, 0.9823542638F, 0.9824273195F,
  158993. 0.9825001596F, 0.9825727843F, 0.9826451940F, 0.9827173891F,
  158994. 0.9827893700F, 0.9828611368F, 0.9829326901F, 0.9830040302F,
  158995. 0.9830751574F, 0.9831460720F, 0.9832167745F, 0.9832872652F,
  158996. 0.9833575444F, 0.9834276124F, 0.9834974697F, 0.9835671166F,
  158997. 0.9836365535F, 0.9837057806F, 0.9837747983F, 0.9838436071F,
  158998. 0.9839122072F, 0.9839805990F, 0.9840487829F, 0.9841167591F,
  158999. 0.9841845282F, 0.9842520903F, 0.9843194459F, 0.9843865953F,
  159000. 0.9844535389F, 0.9845202771F, 0.9845868101F, 0.9846531383F,
  159001. 0.9847192622F, 0.9847851820F, 0.9848508980F, 0.9849164108F,
  159002. 0.9849817205F, 0.9850468276F, 0.9851117324F, 0.9851764352F,
  159003. 0.9852409365F, 0.9853052366F, 0.9853693358F, 0.9854332344F,
  159004. 0.9854969330F, 0.9855604317F, 0.9856237309F, 0.9856868310F,
  159005. 0.9857497325F, 0.9858124355F, 0.9858749404F, 0.9859372477F,
  159006. 0.9859993577F, 0.9860612707F, 0.9861229871F, 0.9861845072F,
  159007. 0.9862458315F, 0.9863069601F, 0.9863678936F, 0.9864286322F,
  159008. 0.9864891764F, 0.9865495264F, 0.9866096826F, 0.9866696454F,
  159009. 0.9867294152F, 0.9867889922F, 0.9868483769F, 0.9869075695F,
  159010. 0.9869665706F, 0.9870253803F, 0.9870839991F, 0.9871424273F,
  159011. 0.9872006653F, 0.9872587135F, 0.9873165721F, 0.9873742415F,
  159012. 0.9874317222F, 0.9874890144F, 0.9875461185F, 0.9876030348F,
  159013. 0.9876597638F, 0.9877163057F, 0.9877726610F, 0.9878288300F,
  159014. 0.9878848130F, 0.9879406104F, 0.9879962225F, 0.9880516497F,
  159015. 0.9881068924F, 0.9881619509F, 0.9882168256F, 0.9882715168F,
  159016. 0.9883260249F, 0.9883803502F, 0.9884344931F, 0.9884884539F,
  159017. 0.9885422331F, 0.9885958309F, 0.9886492477F, 0.9887024838F,
  159018. 0.9887555397F, 0.9888084157F, 0.9888611120F, 0.9889136292F,
  159019. 0.9889659675F, 0.9890181273F, 0.9890701089F, 0.9891219128F,
  159020. 0.9891735392F, 0.9892249885F, 0.9892762610F, 0.9893273572F,
  159021. 0.9893782774F, 0.9894290219F, 0.9894795911F, 0.9895299853F,
  159022. 0.9895802049F, 0.9896302502F, 0.9896801217F, 0.9897298196F,
  159023. 0.9897793443F, 0.9898286961F, 0.9898778755F, 0.9899268828F,
  159024. 0.9899757183F, 0.9900243823F, 0.9900728753F, 0.9901211976F,
  159025. 0.9901693495F, 0.9902173314F, 0.9902651436F, 0.9903127865F,
  159026. 0.9903602605F, 0.9904075659F, 0.9904547031F, 0.9905016723F,
  159027. 0.9905484740F, 0.9905951086F, 0.9906415763F, 0.9906878775F,
  159028. 0.9907340126F, 0.9907799819F, 0.9908257858F, 0.9908714247F,
  159029. 0.9909168988F, 0.9909622086F, 0.9910073543F, 0.9910523364F,
  159030. 0.9910971552F, 0.9911418110F, 0.9911863042F, 0.9912306351F,
  159031. 0.9912748042F, 0.9913188117F, 0.9913626580F, 0.9914063435F,
  159032. 0.9914498684F, 0.9914932333F, 0.9915364383F, 0.9915794839F,
  159033. 0.9916223703F, 0.9916650981F, 0.9917076674F, 0.9917500787F,
  159034. 0.9917923323F, 0.9918344286F, 0.9918763679F, 0.9919181505F,
  159035. 0.9919597769F, 0.9920012473F, 0.9920425621F, 0.9920837217F,
  159036. 0.9921247263F, 0.9921655765F, 0.9922062724F, 0.9922468145F,
  159037. 0.9922872030F, 0.9923274385F, 0.9923675211F, 0.9924074513F,
  159038. 0.9924472294F, 0.9924868557F, 0.9925263306F, 0.9925656544F,
  159039. 0.9926048275F, 0.9926438503F, 0.9926827230F, 0.9927214461F,
  159040. 0.9927600199F, 0.9927984446F, 0.9928367208F, 0.9928748486F,
  159041. 0.9929128285F, 0.9929506608F, 0.9929883459F, 0.9930258841F,
  159042. 0.9930632757F, 0.9931005211F, 0.9931376207F, 0.9931745747F,
  159043. 0.9932113836F, 0.9932480476F, 0.9932845671F, 0.9933209425F,
  159044. 0.9933571742F, 0.9933932623F, 0.9934292074F, 0.9934650097F,
  159045. 0.9935006696F, 0.9935361874F, 0.9935715635F, 0.9936067982F,
  159046. 0.9936418919F, 0.9936768448F, 0.9937116574F, 0.9937463300F,
  159047. 0.9937808629F, 0.9938152565F, 0.9938495111F, 0.9938836271F,
  159048. 0.9939176047F, 0.9939514444F, 0.9939851465F, 0.9940187112F,
  159049. 0.9940521391F, 0.9940854303F, 0.9941185853F, 0.9941516044F,
  159050. 0.9941844879F, 0.9942172361F, 0.9942498495F, 0.9942823283F,
  159051. 0.9943146729F, 0.9943468836F, 0.9943789608F, 0.9944109047F,
  159052. 0.9944427158F, 0.9944743944F, 0.9945059408F, 0.9945373553F,
  159053. 0.9945686384F, 0.9945997902F, 0.9946308112F, 0.9946617017F,
  159054. 0.9946924621F, 0.9947230926F, 0.9947535937F, 0.9947839656F,
  159055. 0.9948142086F, 0.9948443232F, 0.9948743097F, 0.9949041683F,
  159056. 0.9949338995F, 0.9949635035F, 0.9949929807F, 0.9950223315F,
  159057. 0.9950515561F, 0.9950806549F, 0.9951096282F, 0.9951384764F,
  159058. 0.9951671998F, 0.9951957987F, 0.9952242735F, 0.9952526245F,
  159059. 0.9952808520F, 0.9953089564F, 0.9953369380F, 0.9953647971F,
  159060. 0.9953925340F, 0.9954201491F, 0.9954476428F, 0.9954750153F,
  159061. 0.9955022670F, 0.9955293981F, 0.9955564092F, 0.9955833003F,
  159062. 0.9956100720F, 0.9956367245F, 0.9956632582F, 0.9956896733F,
  159063. 0.9957159703F, 0.9957421494F, 0.9957682110F, 0.9957941553F,
  159064. 0.9958199828F, 0.9958456937F, 0.9958712884F, 0.9958967672F,
  159065. 0.9959221305F, 0.9959473784F, 0.9959725115F, 0.9959975300F,
  159066. 0.9960224342F, 0.9960472244F, 0.9960719011F, 0.9960964644F,
  159067. 0.9961209148F, 0.9961452525F, 0.9961694779F, 0.9961935913F,
  159068. 0.9962175930F, 0.9962414834F, 0.9962652627F, 0.9962889313F,
  159069. 0.9963124895F, 0.9963359377F, 0.9963592761F, 0.9963825051F,
  159070. 0.9964056250F, 0.9964286361F, 0.9964515387F, 0.9964743332F,
  159071. 0.9964970198F, 0.9965195990F, 0.9965420709F, 0.9965644360F,
  159072. 0.9965866946F, 0.9966088469F, 0.9966308932F, 0.9966528340F,
  159073. 0.9966746695F, 0.9966964001F, 0.9967180260F, 0.9967395475F,
  159074. 0.9967609651F, 0.9967822789F, 0.9968034894F, 0.9968245968F,
  159075. 0.9968456014F, 0.9968665036F, 0.9968873037F, 0.9969080019F,
  159076. 0.9969285987F, 0.9969490942F, 0.9969694889F, 0.9969897830F,
  159077. 0.9970099769F, 0.9970300708F, 0.9970500651F, 0.9970699601F,
  159078. 0.9970897561F, 0.9971094533F, 0.9971290522F, 0.9971485531F,
  159079. 0.9971679561F, 0.9971872617F, 0.9972064702F, 0.9972255818F,
  159080. 0.9972445968F, 0.9972635157F, 0.9972823386F, 0.9973010659F,
  159081. 0.9973196980F, 0.9973382350F, 0.9973566773F, 0.9973750253F,
  159082. 0.9973932791F, 0.9974114392F, 0.9974295059F, 0.9974474793F,
  159083. 0.9974653599F, 0.9974831480F, 0.9975008438F, 0.9975184476F,
  159084. 0.9975359598F, 0.9975533806F, 0.9975707104F, 0.9975879495F,
  159085. 0.9976050981F, 0.9976221566F, 0.9976391252F, 0.9976560043F,
  159086. 0.9976727941F, 0.9976894950F, 0.9977061073F, 0.9977226312F,
  159087. 0.9977390671F, 0.9977554152F, 0.9977716759F, 0.9977878495F,
  159088. 0.9978039361F, 0.9978199363F, 0.9978358501F, 0.9978516780F,
  159089. 0.9978674202F, 0.9978830771F, 0.9978986488F, 0.9979141358F,
  159090. 0.9979295383F, 0.9979448566F, 0.9979600909F, 0.9979752417F,
  159091. 0.9979903091F, 0.9980052936F, 0.9980201952F, 0.9980350145F,
  159092. 0.9980497515F, 0.9980644067F, 0.9980789804F, 0.9980934727F,
  159093. 0.9981078841F, 0.9981222147F, 0.9981364649F, 0.9981506350F,
  159094. 0.9981647253F, 0.9981787360F, 0.9981926674F, 0.9982065199F,
  159095. 0.9982202936F, 0.9982339890F, 0.9982476062F, 0.9982611456F,
  159096. 0.9982746074F, 0.9982879920F, 0.9983012996F, 0.9983145304F,
  159097. 0.9983276849F, 0.9983407632F, 0.9983537657F, 0.9983666926F,
  159098. 0.9983795442F, 0.9983923208F, 0.9984050226F, 0.9984176501F,
  159099. 0.9984302033F, 0.9984426827F, 0.9984550884F, 0.9984674208F,
  159100. 0.9984796802F, 0.9984918667F, 0.9985039808F, 0.9985160227F,
  159101. 0.9985279926F, 0.9985398909F, 0.9985517177F, 0.9985634734F,
  159102. 0.9985751583F, 0.9985867727F, 0.9985983167F, 0.9986097907F,
  159103. 0.9986211949F, 0.9986325297F, 0.9986437953F, 0.9986549919F,
  159104. 0.9986661199F, 0.9986771795F, 0.9986881710F, 0.9986990946F,
  159105. 0.9987099507F, 0.9987207394F, 0.9987314611F, 0.9987421161F,
  159106. 0.9987527045F, 0.9987632267F, 0.9987736829F, 0.9987840734F,
  159107. 0.9987943985F, 0.9988046584F, 0.9988148534F, 0.9988249838F,
  159108. 0.9988350498F, 0.9988450516F, 0.9988549897F, 0.9988648641F,
  159109. 0.9988746753F, 0.9988844233F, 0.9988941086F, 0.9989037313F,
  159110. 0.9989132918F, 0.9989227902F, 0.9989322269F, 0.9989416021F,
  159111. 0.9989509160F, 0.9989601690F, 0.9989693613F, 0.9989784931F,
  159112. 0.9989875647F, 0.9989965763F, 0.9990055283F, 0.9990144208F,
  159113. 0.9990232541F, 0.9990320286F, 0.9990407443F, 0.9990494016F,
  159114. 0.9990580008F, 0.9990665421F, 0.9990750257F, 0.9990834519F,
  159115. 0.9990918209F, 0.9991001331F, 0.9991083886F, 0.9991165877F,
  159116. 0.9991247307F, 0.9991328177F, 0.9991408491F, 0.9991488251F,
  159117. 0.9991567460F, 0.9991646119F, 0.9991724232F, 0.9991801801F,
  159118. 0.9991878828F, 0.9991955316F, 0.9992031267F, 0.9992106684F,
  159119. 0.9992181569F, 0.9992255925F, 0.9992329753F, 0.9992403057F,
  159120. 0.9992475839F, 0.9992548101F, 0.9992619846F, 0.9992691076F,
  159121. 0.9992761793F, 0.9992832001F, 0.9992901701F, 0.9992970895F,
  159122. 0.9993039587F, 0.9993107777F, 0.9993175470F, 0.9993242667F,
  159123. 0.9993309371F, 0.9993375583F, 0.9993441307F, 0.9993506545F,
  159124. 0.9993571298F, 0.9993635570F, 0.9993699362F, 0.9993762678F,
  159125. 0.9993825519F, 0.9993887887F, 0.9993949785F, 0.9994011216F,
  159126. 0.9994072181F, 0.9994132683F, 0.9994192725F, 0.9994252307F,
  159127. 0.9994311434F, 0.9994370107F, 0.9994428327F, 0.9994486099F,
  159128. 0.9994543423F, 0.9994600303F, 0.9994656739F, 0.9994712736F,
  159129. 0.9994768294F, 0.9994823417F, 0.9994878105F, 0.9994932363F,
  159130. 0.9994986191F, 0.9995039592F, 0.9995092568F, 0.9995145122F,
  159131. 0.9995197256F, 0.9995248971F, 0.9995300270F, 0.9995351156F,
  159132. 0.9995401630F, 0.9995451695F, 0.9995501352F, 0.9995550604F,
  159133. 0.9995599454F, 0.9995647903F, 0.9995695953F, 0.9995743607F,
  159134. 0.9995790866F, 0.9995837734F, 0.9995884211F, 0.9995930300F,
  159135. 0.9995976004F, 0.9996021324F, 0.9996066263F, 0.9996110822F,
  159136. 0.9996155004F, 0.9996198810F, 0.9996242244F, 0.9996285306F,
  159137. 0.9996327999F, 0.9996370326F, 0.9996412287F, 0.9996453886F,
  159138. 0.9996495125F, 0.9996536004F, 0.9996576527F, 0.9996616696F,
  159139. 0.9996656512F, 0.9996695977F, 0.9996735094F, 0.9996773865F,
  159140. 0.9996812291F, 0.9996850374F, 0.9996888118F, 0.9996925523F,
  159141. 0.9996962591F, 0.9996999325F, 0.9997035727F, 0.9997071798F,
  159142. 0.9997107541F, 0.9997142957F, 0.9997178049F, 0.9997212818F,
  159143. 0.9997247266F, 0.9997281396F, 0.9997315209F, 0.9997348708F,
  159144. 0.9997381893F, 0.9997414767F, 0.9997447333F, 0.9997479591F,
  159145. 0.9997511544F, 0.9997543194F, 0.9997574542F, 0.9997605591F,
  159146. 0.9997636342F, 0.9997666797F, 0.9997696958F, 0.9997726828F,
  159147. 0.9997756407F, 0.9997785698F, 0.9997814703F, 0.9997843423F,
  159148. 0.9997871860F, 0.9997900016F, 0.9997927894F, 0.9997955494F,
  159149. 0.9997982818F, 0.9998009869F, 0.9998036648F, 0.9998063157F,
  159150. 0.9998089398F, 0.9998115373F, 0.9998141082F, 0.9998166529F,
  159151. 0.9998191715F, 0.9998216642F, 0.9998241311F, 0.9998265724F,
  159152. 0.9998289884F, 0.9998313790F, 0.9998337447F, 0.9998360854F,
  159153. 0.9998384015F, 0.9998406930F, 0.9998429602F, 0.9998452031F,
  159154. 0.9998474221F, 0.9998496171F, 0.9998517885F, 0.9998539364F,
  159155. 0.9998560610F, 0.9998581624F, 0.9998602407F, 0.9998622962F,
  159156. 0.9998643291F, 0.9998663394F, 0.9998683274F, 0.9998702932F,
  159157. 0.9998722370F, 0.9998741589F, 0.9998760591F, 0.9998779378F,
  159158. 0.9998797952F, 0.9998816313F, 0.9998834464F, 0.9998852406F,
  159159. 0.9998870141F, 0.9998887670F, 0.9998904995F, 0.9998922117F,
  159160. 0.9998939039F, 0.9998955761F, 0.9998972285F, 0.9998988613F,
  159161. 0.9999004746F, 0.9999020686F, 0.9999036434F, 0.9999051992F,
  159162. 0.9999067362F, 0.9999082544F, 0.9999097541F, 0.9999112354F,
  159163. 0.9999126984F, 0.9999141433F, 0.9999155703F, 0.9999169794F,
  159164. 0.9999183709F, 0.9999197449F, 0.9999211014F, 0.9999224408F,
  159165. 0.9999237631F, 0.9999250684F, 0.9999263570F, 0.9999276289F,
  159166. 0.9999288843F, 0.9999301233F, 0.9999313461F, 0.9999325529F,
  159167. 0.9999337437F, 0.9999349187F, 0.9999360780F, 0.9999372218F,
  159168. 0.9999383503F, 0.9999394635F, 0.9999405616F, 0.9999416447F,
  159169. 0.9999427129F, 0.9999437665F, 0.9999448055F, 0.9999458301F,
  159170. 0.9999468404F, 0.9999478365F, 0.9999488185F, 0.9999497867F,
  159171. 0.9999507411F, 0.9999516819F, 0.9999526091F, 0.9999535230F,
  159172. 0.9999544236F, 0.9999553111F, 0.9999561856F, 0.9999570472F,
  159173. 0.9999578960F, 0.9999587323F, 0.9999595560F, 0.9999603674F,
  159174. 0.9999611666F, 0.9999619536F, 0.9999627286F, 0.9999634917F,
  159175. 0.9999642431F, 0.9999649828F, 0.9999657110F, 0.9999664278F,
  159176. 0.9999671334F, 0.9999678278F, 0.9999685111F, 0.9999691835F,
  159177. 0.9999698451F, 0.9999704960F, 0.9999711364F, 0.9999717662F,
  159178. 0.9999723858F, 0.9999729950F, 0.9999735942F, 0.9999741834F,
  159179. 0.9999747626F, 0.9999753321F, 0.9999758919F, 0.9999764421F,
  159180. 0.9999769828F, 0.9999775143F, 0.9999780364F, 0.9999785495F,
  159181. 0.9999790535F, 0.9999795485F, 0.9999800348F, 0.9999805124F,
  159182. 0.9999809813F, 0.9999814417F, 0.9999818938F, 0.9999823375F,
  159183. 0.9999827731F, 0.9999832005F, 0.9999836200F, 0.9999840316F,
  159184. 0.9999844353F, 0.9999848314F, 0.9999852199F, 0.9999856008F,
  159185. 0.9999859744F, 0.9999863407F, 0.9999866997F, 0.9999870516F,
  159186. 0.9999873965F, 0.9999877345F, 0.9999880656F, 0.9999883900F,
  159187. 0.9999887078F, 0.9999890190F, 0.9999893237F, 0.9999896220F,
  159188. 0.9999899140F, 0.9999901999F, 0.9999904796F, 0.9999907533F,
  159189. 0.9999910211F, 0.9999912830F, 0.9999915391F, 0.9999917896F,
  159190. 0.9999920345F, 0.9999922738F, 0.9999925077F, 0.9999927363F,
  159191. 0.9999929596F, 0.9999931777F, 0.9999933907F, 0.9999935987F,
  159192. 0.9999938018F, 0.9999940000F, 0.9999941934F, 0.9999943820F,
  159193. 0.9999945661F, 0.9999947456F, 0.9999949206F, 0.9999950912F,
  159194. 0.9999952575F, 0.9999954195F, 0.9999955773F, 0.9999957311F,
  159195. 0.9999958807F, 0.9999960265F, 0.9999961683F, 0.9999963063F,
  159196. 0.9999964405F, 0.9999965710F, 0.9999966979F, 0.9999968213F,
  159197. 0.9999969412F, 0.9999970576F, 0.9999971707F, 0.9999972805F,
  159198. 0.9999973871F, 0.9999974905F, 0.9999975909F, 0.9999976881F,
  159199. 0.9999977824F, 0.9999978738F, 0.9999979624F, 0.9999980481F,
  159200. 0.9999981311F, 0.9999982115F, 0.9999982892F, 0.9999983644F,
  159201. 0.9999984370F, 0.9999985072F, 0.9999985750F, 0.9999986405F,
  159202. 0.9999987037F, 0.9999987647F, 0.9999988235F, 0.9999988802F,
  159203. 0.9999989348F, 0.9999989873F, 0.9999990379F, 0.9999990866F,
  159204. 0.9999991334F, 0.9999991784F, 0.9999992217F, 0.9999992632F,
  159205. 0.9999993030F, 0.9999993411F, 0.9999993777F, 0.9999994128F,
  159206. 0.9999994463F, 0.9999994784F, 0.9999995091F, 0.9999995384F,
  159207. 0.9999995663F, 0.9999995930F, 0.9999996184F, 0.9999996426F,
  159208. 0.9999996657F, 0.9999996876F, 0.9999997084F, 0.9999997282F,
  159209. 0.9999997469F, 0.9999997647F, 0.9999997815F, 0.9999997973F,
  159210. 0.9999998123F, 0.9999998265F, 0.9999998398F, 0.9999998524F,
  159211. 0.9999998642F, 0.9999998753F, 0.9999998857F, 0.9999998954F,
  159212. 0.9999999045F, 0.9999999130F, 0.9999999209F, 0.9999999282F,
  159213. 0.9999999351F, 0.9999999414F, 0.9999999472F, 0.9999999526F,
  159214. 0.9999999576F, 0.9999999622F, 0.9999999664F, 0.9999999702F,
  159215. 0.9999999737F, 0.9999999769F, 0.9999999798F, 0.9999999824F,
  159216. 0.9999999847F, 0.9999999868F, 0.9999999887F, 0.9999999904F,
  159217. 0.9999999919F, 0.9999999932F, 0.9999999943F, 0.9999999953F,
  159218. 0.9999999961F, 0.9999999969F, 0.9999999975F, 0.9999999980F,
  159219. 0.9999999985F, 0.9999999988F, 0.9999999991F, 0.9999999993F,
  159220. 0.9999999995F, 0.9999999997F, 0.9999999998F, 0.9999999999F,
  159221. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  159222. 1.0000000000F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  159223. };
  159224. static float *vwin[8] = {
  159225. vwin64,
  159226. vwin128,
  159227. vwin256,
  159228. vwin512,
  159229. vwin1024,
  159230. vwin2048,
  159231. vwin4096,
  159232. vwin8192,
  159233. };
  159234. float *_vorbis_window_get(int n){
  159235. return vwin[n];
  159236. }
  159237. void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  159238. int lW,int W,int nW){
  159239. lW=(W?lW:0);
  159240. nW=(W?nW:0);
  159241. {
  159242. float *windowLW=vwin[winno[lW]];
  159243. float *windowNW=vwin[winno[nW]];
  159244. long n=blocksizes[W];
  159245. long ln=blocksizes[lW];
  159246. long rn=blocksizes[nW];
  159247. long leftbegin=n/4-ln/4;
  159248. long leftend=leftbegin+ln/2;
  159249. long rightbegin=n/2+n/4-rn/4;
  159250. long rightend=rightbegin+rn/2;
  159251. int i,p;
  159252. for(i=0;i<leftbegin;i++)
  159253. d[i]=0.f;
  159254. for(p=0;i<leftend;i++,p++)
  159255. d[i]*=windowLW[p];
  159256. for(i=rightbegin,p=rn/2-1;i<rightend;i++,p--)
  159257. d[i]*=windowNW[p];
  159258. for(;i<n;i++)
  159259. d[i]=0.f;
  159260. }
  159261. }
  159262. #endif
  159263. /*** End of inlined file: window.c ***/
  159264. #else
  159265. #include <vorbis/vorbisenc.h>
  159266. #include <vorbis/codec.h>
  159267. #include <vorbis/vorbisfile.h>
  159268. #endif
  159269. }
  159270. #undef max
  159271. #undef min
  159272. BEGIN_JUCE_NAMESPACE
  159273. static const char* const oggFormatName = "Ogg-Vorbis file";
  159274. static const char* const oggExtensions[] = { ".ogg", 0 };
  159275. class OggReader : public AudioFormatReader
  159276. {
  159277. OggVorbisNamespace::OggVorbis_File ovFile;
  159278. OggVorbisNamespace::ov_callbacks callbacks;
  159279. AudioSampleBuffer reservoir;
  159280. int reservoirStart, samplesInReservoir;
  159281. public:
  159282. OggReader (InputStream* const inp)
  159283. : AudioFormatReader (inp, TRANS (oggFormatName)),
  159284. reservoir (2, 4096),
  159285. reservoirStart (0),
  159286. samplesInReservoir (0)
  159287. {
  159288. using namespace OggVorbisNamespace;
  159289. sampleRate = 0;
  159290. usesFloatingPointData = true;
  159291. callbacks.read_func = &oggReadCallback;
  159292. callbacks.seek_func = &oggSeekCallback;
  159293. callbacks.close_func = &oggCloseCallback;
  159294. callbacks.tell_func = &oggTellCallback;
  159295. const int err = ov_open_callbacks (input, &ovFile, 0, 0, callbacks);
  159296. if (err == 0)
  159297. {
  159298. vorbis_info* info = ov_info (&ovFile, -1);
  159299. lengthInSamples = (uint32) ov_pcm_total (&ovFile, -1);
  159300. numChannels = info->channels;
  159301. bitsPerSample = 16;
  159302. sampleRate = info->rate;
  159303. reservoir.setSize (numChannels,
  159304. (int) jmin (lengthInSamples, (int64) reservoir.getNumSamples()));
  159305. }
  159306. }
  159307. ~OggReader()
  159308. {
  159309. OggVorbisNamespace::ov_clear (&ovFile);
  159310. }
  159311. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  159312. int64 startSampleInFile, int numSamples)
  159313. {
  159314. while (numSamples > 0)
  159315. {
  159316. const int numAvailable = reservoirStart + samplesInReservoir - startSampleInFile;
  159317. if (startSampleInFile >= reservoirStart && numAvailable > 0)
  159318. {
  159319. // got a few samples overlapping, so use them before seeking..
  159320. const int numToUse = jmin (numSamples, numAvailable);
  159321. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  159322. if (destSamples[i] != 0)
  159323. memcpy (destSamples[i] + startOffsetInDestBuffer,
  159324. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  159325. sizeof (float) * numToUse);
  159326. startSampleInFile += numToUse;
  159327. numSamples -= numToUse;
  159328. startOffsetInDestBuffer += numToUse;
  159329. if (numSamples == 0)
  159330. break;
  159331. }
  159332. if (startSampleInFile < reservoirStart
  159333. || startSampleInFile + numSamples > reservoirStart + samplesInReservoir)
  159334. {
  159335. // buffer miss, so refill the reservoir
  159336. int bitStream = 0;
  159337. reservoirStart = jmax (0, (int) startSampleInFile);
  159338. samplesInReservoir = reservoir.getNumSamples();
  159339. if (reservoirStart != (int) OggVorbisNamespace::ov_pcm_tell (&ovFile))
  159340. OggVorbisNamespace::ov_pcm_seek (&ovFile, reservoirStart);
  159341. int offset = 0;
  159342. int numToRead = samplesInReservoir;
  159343. while (numToRead > 0)
  159344. {
  159345. float** dataIn = 0;
  159346. const int samps = OggVorbisNamespace::ov_read_float (&ovFile, &dataIn, numToRead, &bitStream);
  159347. if (samps <= 0)
  159348. break;
  159349. jassert (samps <= numToRead);
  159350. for (int i = jmin ((int) numChannels, reservoir.getNumChannels()); --i >= 0;)
  159351. {
  159352. memcpy (reservoir.getSampleData (i, offset),
  159353. dataIn[i],
  159354. sizeof (float) * samps);
  159355. }
  159356. numToRead -= samps;
  159357. offset += samps;
  159358. }
  159359. if (numToRead > 0)
  159360. reservoir.clear (offset, numToRead);
  159361. }
  159362. }
  159363. if (numSamples > 0)
  159364. {
  159365. for (int i = numDestChannels; --i >= 0;)
  159366. if (destSamples[i] != 0)
  159367. zeromem (destSamples[i] + startOffsetInDestBuffer,
  159368. sizeof (int) * numSamples);
  159369. }
  159370. return true;
  159371. }
  159372. static size_t oggReadCallback (void* ptr, size_t size, size_t nmemb, void* datasource)
  159373. {
  159374. return (size_t) (static_cast <InputStream*> (datasource)->read (ptr, (int) (size * nmemb)) / size);
  159375. }
  159376. static int oggSeekCallback (void* datasource, OggVorbisNamespace::ogg_int64_t offset, int whence)
  159377. {
  159378. InputStream* const in = static_cast <InputStream*> (datasource);
  159379. if (whence == SEEK_CUR)
  159380. offset += in->getPosition();
  159381. else if (whence == SEEK_END)
  159382. offset += in->getTotalLength();
  159383. in->setPosition (offset);
  159384. return 0;
  159385. }
  159386. static int oggCloseCallback (void*)
  159387. {
  159388. return 0;
  159389. }
  159390. static long oggTellCallback (void* datasource)
  159391. {
  159392. return (long) static_cast <InputStream*> (datasource)->getPosition();
  159393. }
  159394. juce_UseDebuggingNewOperator
  159395. };
  159396. class OggWriter : public AudioFormatWriter
  159397. {
  159398. OggVorbisNamespace::ogg_stream_state os;
  159399. OggVorbisNamespace::ogg_page og;
  159400. OggVorbisNamespace::ogg_packet op;
  159401. OggVorbisNamespace::vorbis_info vi;
  159402. OggVorbisNamespace::vorbis_comment vc;
  159403. OggVorbisNamespace::vorbis_dsp_state vd;
  159404. OggVorbisNamespace::vorbis_block vb;
  159405. public:
  159406. bool ok;
  159407. OggWriter (OutputStream* const out,
  159408. const double sampleRate,
  159409. const int numChannels,
  159410. const int bitsPerSample,
  159411. const int qualityIndex)
  159412. : AudioFormatWriter (out, TRANS (oggFormatName),
  159413. sampleRate,
  159414. numChannels,
  159415. bitsPerSample)
  159416. {
  159417. using namespace OggVorbisNamespace;
  159418. ok = false;
  159419. vorbis_info_init (&vi);
  159420. if (vorbis_encode_init_vbr (&vi,
  159421. numChannels,
  159422. (int) sampleRate,
  159423. jlimit (0.0f, 1.0f, qualityIndex * 0.5f)) == 0)
  159424. {
  159425. vorbis_comment_init (&vc);
  159426. if (JUCEApplication::getInstance() != 0)
  159427. vorbis_comment_add_tag (&vc, "ENCODER", const_cast <char*> (JUCEApplication::getInstance()->getApplicationName().toUTF8()));
  159428. vorbis_analysis_init (&vd, &vi);
  159429. vorbis_block_init (&vd, &vb);
  159430. ogg_stream_init (&os, Random::getSystemRandom().nextInt());
  159431. ogg_packet header;
  159432. ogg_packet header_comm;
  159433. ogg_packet header_code;
  159434. vorbis_analysis_headerout (&vd, &vc, &header, &header_comm, &header_code);
  159435. ogg_stream_packetin (&os, &header);
  159436. ogg_stream_packetin (&os, &header_comm);
  159437. ogg_stream_packetin (&os, &header_code);
  159438. for (;;)
  159439. {
  159440. if (ogg_stream_flush (&os, &og) == 0)
  159441. break;
  159442. output->write (og.header, og.header_len);
  159443. output->write (og.body, og.body_len);
  159444. }
  159445. ok = true;
  159446. }
  159447. }
  159448. ~OggWriter()
  159449. {
  159450. using namespace OggVorbisNamespace;
  159451. if (ok)
  159452. {
  159453. // write a zero-length packet to show ogg that we're finished..
  159454. write (0, 0);
  159455. ogg_stream_clear (&os);
  159456. vorbis_block_clear (&vb);
  159457. vorbis_dsp_clear (&vd);
  159458. vorbis_comment_clear (&vc);
  159459. vorbis_info_clear (&vi);
  159460. output->flush();
  159461. }
  159462. else
  159463. {
  159464. vorbis_info_clear (&vi);
  159465. output = 0; // to stop the base class deleting this, as it needs to be returned
  159466. // to the caller of createWriter()
  159467. }
  159468. }
  159469. bool write (const int** samplesToWrite, int numSamples)
  159470. {
  159471. using namespace OggVorbisNamespace;
  159472. if (! ok)
  159473. return false;
  159474. if (numSamples > 0)
  159475. {
  159476. const double gain = 1.0 / 0x80000000u;
  159477. float** const vorbisBuffer = vorbis_analysis_buffer (&vd, numSamples);
  159478. for (int i = numChannels; --i >= 0;)
  159479. {
  159480. float* const dst = vorbisBuffer[i];
  159481. const int* const src = samplesToWrite [i];
  159482. if (src != 0 && dst != 0)
  159483. {
  159484. for (int j = 0; j < numSamples; ++j)
  159485. dst[j] = (float) (src[j] * gain);
  159486. }
  159487. }
  159488. }
  159489. vorbis_analysis_wrote (&vd, numSamples);
  159490. while (vorbis_analysis_blockout (&vd, &vb) == 1)
  159491. {
  159492. vorbis_analysis (&vb, 0);
  159493. vorbis_bitrate_addblock (&vb);
  159494. while (vorbis_bitrate_flushpacket (&vd, &op))
  159495. {
  159496. ogg_stream_packetin (&os, &op);
  159497. for (;;)
  159498. {
  159499. if (ogg_stream_pageout (&os, &og) == 0)
  159500. break;
  159501. output->write (og.header, og.header_len);
  159502. output->write (og.body, og.body_len);
  159503. if (ogg_page_eos (&og))
  159504. break;
  159505. }
  159506. }
  159507. }
  159508. return true;
  159509. }
  159510. juce_UseDebuggingNewOperator
  159511. };
  159512. OggVorbisAudioFormat::OggVorbisAudioFormat()
  159513. : AudioFormat (TRANS (oggFormatName), StringArray (oggExtensions))
  159514. {
  159515. }
  159516. OggVorbisAudioFormat::~OggVorbisAudioFormat()
  159517. {
  159518. }
  159519. const Array <int> OggVorbisAudioFormat::getPossibleSampleRates()
  159520. {
  159521. const int rates[] = { 22050, 32000, 44100, 48000, 0 };
  159522. return Array <int> (rates);
  159523. }
  159524. const Array <int> OggVorbisAudioFormat::getPossibleBitDepths()
  159525. {
  159526. const int depths[] = { 32, 0 };
  159527. return Array <int> (depths);
  159528. }
  159529. bool OggVorbisAudioFormat::canDoStereo() { return true; }
  159530. bool OggVorbisAudioFormat::canDoMono() { return true; }
  159531. bool OggVorbisAudioFormat::isCompressed() { return true; }
  159532. AudioFormatReader* OggVorbisAudioFormat::createReaderFor (InputStream* in,
  159533. const bool deleteStreamIfOpeningFails)
  159534. {
  159535. ScopedPointer <OggReader> r (new OggReader (in));
  159536. if (r->sampleRate != 0)
  159537. return r.release();
  159538. if (! deleteStreamIfOpeningFails)
  159539. r->input = 0;
  159540. return 0;
  159541. }
  159542. AudioFormatWriter* OggVorbisAudioFormat::createWriterFor (OutputStream* out,
  159543. double sampleRate,
  159544. unsigned int numChannels,
  159545. int bitsPerSample,
  159546. const StringPairArray& /*metadataValues*/,
  159547. int qualityOptionIndex)
  159548. {
  159549. ScopedPointer <OggWriter> w (new OggWriter (out,
  159550. sampleRate,
  159551. numChannels,
  159552. bitsPerSample,
  159553. qualityOptionIndex));
  159554. return w->ok ? w.release() : 0;
  159555. }
  159556. const StringArray OggVorbisAudioFormat::getQualityOptions()
  159557. {
  159558. StringArray s;
  159559. s.add ("Low Quality");
  159560. s.add ("Medium Quality");
  159561. s.add ("High Quality");
  159562. return s;
  159563. }
  159564. int OggVorbisAudioFormat::estimateOggFileQuality (const File& source)
  159565. {
  159566. FileInputStream* const in = source.createInputStream();
  159567. if (in != 0)
  159568. {
  159569. ScopedPointer <AudioFormatReader> r (createReaderFor (in, true));
  159570. if (r != 0)
  159571. {
  159572. const int64 numSamps = r->lengthInSamples;
  159573. r = 0;
  159574. const int64 fileNumSamps = source.getSize() / 4;
  159575. const double ratio = numSamps / (double) fileNumSamps;
  159576. if (ratio > 12.0)
  159577. return 0;
  159578. else if (ratio > 6.0)
  159579. return 1;
  159580. else
  159581. return 2;
  159582. }
  159583. }
  159584. return 1;
  159585. }
  159586. END_JUCE_NAMESPACE
  159587. #endif
  159588. /*** End of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  159589. #endif
  159590. #if JUCE_BUILD_CORE && ! JUCE_ONLY_BUILD_CORE_LIBRARY // do these in the core section to help balance the sizes
  159591. /*** Start of inlined file: juce_JPEGLoader.cpp ***/
  159592. #if JUCE_MSVC
  159593. #pragma warning (push)
  159594. #endif
  159595. namespace jpeglibNamespace
  159596. {
  159597. #if JUCE_INCLUDE_JPEGLIB_CODE
  159598. #if JUCE_MINGW
  159599. typedef unsigned char boolean;
  159600. #endif
  159601. #define JPEG_INTERNALS
  159602. #undef FAR
  159603. /*** Start of inlined file: jpeglib.h ***/
  159604. #ifndef JPEGLIB_H
  159605. #define JPEGLIB_H
  159606. /*
  159607. * First we include the configuration files that record how this
  159608. * installation of the JPEG library is set up. jconfig.h can be
  159609. * generated automatically for many systems. jmorecfg.h contains
  159610. * manual configuration options that most people need not worry about.
  159611. */
  159612. #ifndef JCONFIG_INCLUDED /* in case jinclude.h already did */
  159613. /*** Start of inlined file: jconfig.h ***/
  159614. /* see jconfig.doc for explanations */
  159615. // disable all the warnings under MSVC
  159616. #ifdef _MSC_VER
  159617. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  159618. #endif
  159619. #ifdef __BORLANDC__
  159620. #pragma warn -8057
  159621. #pragma warn -8019
  159622. #pragma warn -8004
  159623. #pragma warn -8008
  159624. #endif
  159625. #define HAVE_PROTOTYPES
  159626. #define HAVE_UNSIGNED_CHAR
  159627. #define HAVE_UNSIGNED_SHORT
  159628. /* #define void char */
  159629. /* #define const */
  159630. #undef CHAR_IS_UNSIGNED
  159631. #define HAVE_STDDEF_H
  159632. #define HAVE_STDLIB_H
  159633. #undef NEED_BSD_STRINGS
  159634. #undef NEED_SYS_TYPES_H
  159635. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  159636. #undef NEED_SHORT_EXTERNAL_NAMES
  159637. #undef INCOMPLETE_TYPES_BROKEN
  159638. /* Define "boolean" as unsigned char, not int, per Windows custom */
  159639. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  159640. typedef unsigned char boolean;
  159641. #endif
  159642. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  159643. #ifdef JPEG_INTERNALS
  159644. #undef RIGHT_SHIFT_IS_UNSIGNED
  159645. #endif /* JPEG_INTERNALS */
  159646. #ifdef JPEG_CJPEG_DJPEG
  159647. #define BMP_SUPPORTED /* BMP image file format */
  159648. #define GIF_SUPPORTED /* GIF image file format */
  159649. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  159650. #undef RLE_SUPPORTED /* Utah RLE image file format */
  159651. #define TARGA_SUPPORTED /* Targa image file format */
  159652. #define TWO_FILE_COMMANDLINE /* optional */
  159653. #define USE_SETMODE /* Microsoft has setmode() */
  159654. #undef NEED_SIGNAL_CATCHER
  159655. #undef DONT_USE_B_MODE
  159656. #undef PROGRESS_REPORT /* optional */
  159657. #endif /* JPEG_CJPEG_DJPEG */
  159658. /*** End of inlined file: jconfig.h ***/
  159659. /* widely used configuration options */
  159660. #endif
  159661. /*** Start of inlined file: jmorecfg.h ***/
  159662. /*
  159663. * Define BITS_IN_JSAMPLE as either
  159664. * 8 for 8-bit sample values (the usual setting)
  159665. * 12 for 12-bit sample values
  159666. * Only 8 and 12 are legal data precisions for lossy JPEG according to the
  159667. * JPEG standard, and the IJG code does not support anything else!
  159668. * We do not support run-time selection of data precision, sorry.
  159669. */
  159670. #define BITS_IN_JSAMPLE 8 /* use 8 or 12 */
  159671. /*
  159672. * Maximum number of components (color channels) allowed in JPEG image.
  159673. * To meet the letter of the JPEG spec, set this to 255. However, darn
  159674. * few applications need more than 4 channels (maybe 5 for CMYK + alpha
  159675. * mask). We recommend 10 as a reasonable compromise; use 4 if you are
  159676. * really short on memory. (Each allowed component costs a hundred or so
  159677. * bytes of storage, whether actually used in an image or not.)
  159678. */
  159679. #define MAX_COMPONENTS 10 /* maximum number of image components */
  159680. /*
  159681. * Basic data types.
  159682. * You may need to change these if you have a machine with unusual data
  159683. * type sizes; for example, "char" not 8 bits, "short" not 16 bits,
  159684. * or "long" not 32 bits. We don't care whether "int" is 16 or 32 bits,
  159685. * but it had better be at least 16.
  159686. */
  159687. /* Representation of a single sample (pixel element value).
  159688. * We frequently allocate large arrays of these, so it's important to keep
  159689. * them small. But if you have memory to burn and access to char or short
  159690. * arrays is very slow on your hardware, you might want to change these.
  159691. */
  159692. #if BITS_IN_JSAMPLE == 8
  159693. /* JSAMPLE should be the smallest type that will hold the values 0..255.
  159694. * You can use a signed char by having GETJSAMPLE mask it with 0xFF.
  159695. */
  159696. #ifdef HAVE_UNSIGNED_CHAR
  159697. typedef unsigned char JSAMPLE;
  159698. #define GETJSAMPLE(value) ((int) (value))
  159699. #else /* not HAVE_UNSIGNED_CHAR */
  159700. typedef char JSAMPLE;
  159701. #ifdef CHAR_IS_UNSIGNED
  159702. #define GETJSAMPLE(value) ((int) (value))
  159703. #else
  159704. #define GETJSAMPLE(value) ((int) (value) & 0xFF)
  159705. #endif /* CHAR_IS_UNSIGNED */
  159706. #endif /* HAVE_UNSIGNED_CHAR */
  159707. #define MAXJSAMPLE 255
  159708. #define CENTERJSAMPLE 128
  159709. #endif /* BITS_IN_JSAMPLE == 8 */
  159710. #if BITS_IN_JSAMPLE == 12
  159711. /* JSAMPLE should be the smallest type that will hold the values 0..4095.
  159712. * On nearly all machines "short" will do nicely.
  159713. */
  159714. typedef short JSAMPLE;
  159715. #define GETJSAMPLE(value) ((int) (value))
  159716. #define MAXJSAMPLE 4095
  159717. #define CENTERJSAMPLE 2048
  159718. #endif /* BITS_IN_JSAMPLE == 12 */
  159719. /* Representation of a DCT frequency coefficient.
  159720. * This should be a signed value of at least 16 bits; "short" is usually OK.
  159721. * Again, we allocate large arrays of these, but you can change to int
  159722. * if you have memory to burn and "short" is really slow.
  159723. */
  159724. typedef short JCOEF;
  159725. /* Compressed datastreams are represented as arrays of JOCTET.
  159726. * These must be EXACTLY 8 bits wide, at least once they are written to
  159727. * external storage. Note that when using the stdio data source/destination
  159728. * managers, this is also the data type passed to fread/fwrite.
  159729. */
  159730. #ifdef HAVE_UNSIGNED_CHAR
  159731. typedef unsigned char JOCTET;
  159732. #define GETJOCTET(value) (value)
  159733. #else /* not HAVE_UNSIGNED_CHAR */
  159734. typedef char JOCTET;
  159735. #ifdef CHAR_IS_UNSIGNED
  159736. #define GETJOCTET(value) (value)
  159737. #else
  159738. #define GETJOCTET(value) ((value) & 0xFF)
  159739. #endif /* CHAR_IS_UNSIGNED */
  159740. #endif /* HAVE_UNSIGNED_CHAR */
  159741. /* These typedefs are used for various table entries and so forth.
  159742. * They must be at least as wide as specified; but making them too big
  159743. * won't cost a huge amount of memory, so we don't provide special
  159744. * extraction code like we did for JSAMPLE. (In other words, these
  159745. * typedefs live at a different point on the speed/space tradeoff curve.)
  159746. */
  159747. /* UINT8 must hold at least the values 0..255. */
  159748. #ifdef HAVE_UNSIGNED_CHAR
  159749. typedef unsigned char UINT8;
  159750. #else /* not HAVE_UNSIGNED_CHAR */
  159751. #ifdef CHAR_IS_UNSIGNED
  159752. typedef char UINT8;
  159753. #else /* not CHAR_IS_UNSIGNED */
  159754. typedef short UINT8;
  159755. #endif /* CHAR_IS_UNSIGNED */
  159756. #endif /* HAVE_UNSIGNED_CHAR */
  159757. /* UINT16 must hold at least the values 0..65535. */
  159758. #ifdef HAVE_UNSIGNED_SHORT
  159759. typedef unsigned short UINT16;
  159760. #else /* not HAVE_UNSIGNED_SHORT */
  159761. typedef unsigned int UINT16;
  159762. #endif /* HAVE_UNSIGNED_SHORT */
  159763. /* INT16 must hold at least the values -32768..32767. */
  159764. #ifndef XMD_H /* X11/xmd.h correctly defines INT16 */
  159765. typedef short INT16;
  159766. #endif
  159767. /* INT32 must hold at least signed 32-bit values. */
  159768. #ifndef XMD_H /* X11/xmd.h correctly defines INT32 */
  159769. typedef long INT32;
  159770. #endif
  159771. /* Datatype used for image dimensions. The JPEG standard only supports
  159772. * images up to 64K*64K due to 16-bit fields in SOF markers. Therefore
  159773. * "unsigned int" is sufficient on all machines. However, if you need to
  159774. * handle larger images and you don't mind deviating from the spec, you
  159775. * can change this datatype.
  159776. */
  159777. typedef unsigned int JDIMENSION;
  159778. #define JPEG_MAX_DIMENSION 65500L /* a tad under 64K to prevent overflows */
  159779. /* These macros are used in all function definitions and extern declarations.
  159780. * You could modify them if you need to change function linkage conventions;
  159781. * in particular, you'll need to do that to make the library a Windows DLL.
  159782. * Another application is to make all functions global for use with debuggers
  159783. * or code profilers that require it.
  159784. */
  159785. /* a function called through method pointers: */
  159786. #define METHODDEF(type) static type
  159787. /* a function used only in its module: */
  159788. #define LOCAL(type) static type
  159789. /* a function referenced thru EXTERNs: */
  159790. #define GLOBAL(type) type
  159791. /* a reference to a GLOBAL function: */
  159792. #define EXTERN(type) extern type
  159793. /* This macro is used to declare a "method", that is, a function pointer.
  159794. * We want to supply prototype parameters if the compiler can cope.
  159795. * Note that the arglist parameter must be parenthesized!
  159796. * Again, you can customize this if you need special linkage keywords.
  159797. */
  159798. #ifdef HAVE_PROTOTYPES
  159799. #define JMETHOD(type,methodname,arglist) type (*methodname) arglist
  159800. #else
  159801. #define JMETHOD(type,methodname,arglist) type (*methodname) ()
  159802. #endif
  159803. /* Here is the pseudo-keyword for declaring pointers that must be "far"
  159804. * on 80x86 machines. Most of the specialized coding for 80x86 is handled
  159805. * by just saying "FAR *" where such a pointer is needed. In a few places
  159806. * explicit coding is needed; see uses of the NEED_FAR_POINTERS symbol.
  159807. */
  159808. #ifdef NEED_FAR_POINTERS
  159809. #define FAR far
  159810. #else
  159811. #define FAR
  159812. #endif
  159813. /*
  159814. * On a few systems, type boolean and/or its values FALSE, TRUE may appear
  159815. * in standard header files. Or you may have conflicts with application-
  159816. * specific header files that you want to include together with these files.
  159817. * Defining HAVE_BOOLEAN before including jpeglib.h should make it work.
  159818. */
  159819. #ifndef HAVE_BOOLEAN
  159820. typedef int boolean;
  159821. #endif
  159822. #ifndef FALSE /* in case these macros already exist */
  159823. #define FALSE 0 /* values of boolean */
  159824. #endif
  159825. #ifndef TRUE
  159826. #define TRUE 1
  159827. #endif
  159828. /*
  159829. * The remaining options affect code selection within the JPEG library,
  159830. * but they don't need to be visible to most applications using the library.
  159831. * To minimize application namespace pollution, the symbols won't be
  159832. * defined unless JPEG_INTERNALS or JPEG_INTERNAL_OPTIONS has been defined.
  159833. */
  159834. #ifdef JPEG_INTERNALS
  159835. #define JPEG_INTERNAL_OPTIONS
  159836. #endif
  159837. #ifdef JPEG_INTERNAL_OPTIONS
  159838. /*
  159839. * These defines indicate whether to include various optional functions.
  159840. * Undefining some of these symbols will produce a smaller but less capable
  159841. * library. Note that you can leave certain source files out of the
  159842. * compilation/linking process if you've #undef'd the corresponding symbols.
  159843. * (You may HAVE to do that if your compiler doesn't like null source files.)
  159844. */
  159845. /* Arithmetic coding is unsupported for legal reasons. Complaints to IBM. */
  159846. /* Capability options common to encoder and decoder: */
  159847. #define DCT_ISLOW_SUPPORTED /* slow but accurate integer algorithm */
  159848. #define DCT_IFAST_SUPPORTED /* faster, less accurate integer method */
  159849. #define DCT_FLOAT_SUPPORTED /* floating-point: accurate, fast on fast HW */
  159850. /* Encoder capability options: */
  159851. #undef C_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  159852. #define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  159853. #define C_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  159854. #define ENTROPY_OPT_SUPPORTED /* Optimization of entropy coding parms? */
  159855. /* Note: if you selected 12-bit data precision, it is dangerous to turn off
  159856. * ENTROPY_OPT_SUPPORTED. The standard Huffman tables are only good for 8-bit
  159857. * precision, so jchuff.c normally uses entropy optimization to compute
  159858. * usable tables for higher precision. If you don't want to do optimization,
  159859. * you'll have to supply different default Huffman tables.
  159860. * The exact same statements apply for progressive JPEG: the default tables
  159861. * don't work for progressive mode. (This may get fixed, however.)
  159862. */
  159863. #define INPUT_SMOOTHING_SUPPORTED /* Input image smoothing option? */
  159864. /* Decoder capability options: */
  159865. #undef D_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  159866. #define D_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  159867. #define D_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  159868. #define SAVE_MARKERS_SUPPORTED /* jpeg_save_markers() needed? */
  159869. #define BLOCK_SMOOTHING_SUPPORTED /* Block smoothing? (Progressive only) */
  159870. #define IDCT_SCALING_SUPPORTED /* Output rescaling via IDCT? */
  159871. #undef UPSAMPLE_SCALING_SUPPORTED /* Output rescaling at upsample stage? */
  159872. #define UPSAMPLE_MERGING_SUPPORTED /* Fast path for sloppy upsampling? */
  159873. #define QUANT_1PASS_SUPPORTED /* 1-pass color quantization? */
  159874. #define QUANT_2PASS_SUPPORTED /* 2-pass color quantization? */
  159875. /* more capability options later, no doubt */
  159876. /*
  159877. * Ordering of RGB data in scanlines passed to or from the application.
  159878. * If your application wants to deal with data in the order B,G,R, just
  159879. * change these macros. You can also deal with formats such as R,G,B,X
  159880. * (one extra byte per pixel) by changing RGB_PIXELSIZE. Note that changing
  159881. * the offsets will also change the order in which colormap data is organized.
  159882. * RESTRICTIONS:
  159883. * 1. The sample applications cjpeg,djpeg do NOT support modified RGB formats.
  159884. * 2. These macros only affect RGB<=>YCbCr color conversion, so they are not
  159885. * useful if you are using JPEG color spaces other than YCbCr or grayscale.
  159886. * 3. The color quantizer modules will not behave desirably if RGB_PIXELSIZE
  159887. * is not 3 (they don't understand about dummy color components!). So you
  159888. * can't use color quantization if you change that value.
  159889. */
  159890. #define RGB_RED 0 /* Offset of Red in an RGB scanline element */
  159891. #define RGB_GREEN 1 /* Offset of Green */
  159892. #define RGB_BLUE 2 /* Offset of Blue */
  159893. #define RGB_PIXELSIZE 3 /* JSAMPLEs per RGB scanline element */
  159894. /* Definitions for speed-related optimizations. */
  159895. /* If your compiler supports inline functions, define INLINE
  159896. * as the inline keyword; otherwise define it as empty.
  159897. */
  159898. #ifndef INLINE
  159899. #ifdef __GNUC__ /* for instance, GNU C knows about inline */
  159900. #define INLINE __inline__
  159901. #endif
  159902. #ifndef INLINE
  159903. #define INLINE /* default is to define it as empty */
  159904. #endif
  159905. #endif
  159906. /* On some machines (notably 68000 series) "int" is 32 bits, but multiplying
  159907. * two 16-bit shorts is faster than multiplying two ints. Define MULTIPLIER
  159908. * as short on such a machine. MULTIPLIER must be at least 16 bits wide.
  159909. */
  159910. #ifndef MULTIPLIER
  159911. #define MULTIPLIER int /* type for fastest integer multiply */
  159912. #endif
  159913. /* FAST_FLOAT should be either float or double, whichever is done faster
  159914. * by your compiler. (Note that this type is only used in the floating point
  159915. * DCT routines, so it only matters if you've defined DCT_FLOAT_SUPPORTED.)
  159916. * Typically, float is faster in ANSI C compilers, while double is faster in
  159917. * pre-ANSI compilers (because they insist on converting to double anyway).
  159918. * The code below therefore chooses float if we have ANSI-style prototypes.
  159919. */
  159920. #ifndef FAST_FLOAT
  159921. #ifdef HAVE_PROTOTYPES
  159922. #define FAST_FLOAT float
  159923. #else
  159924. #define FAST_FLOAT double
  159925. #endif
  159926. #endif
  159927. #endif /* JPEG_INTERNAL_OPTIONS */
  159928. /*** End of inlined file: jmorecfg.h ***/
  159929. /* seldom changed options */
  159930. /* Version ID for the JPEG library.
  159931. * Might be useful for tests like "#if JPEG_LIB_VERSION >= 60".
  159932. */
  159933. #define JPEG_LIB_VERSION 62 /* Version 6b */
  159934. /* Various constants determining the sizes of things.
  159935. * All of these are specified by the JPEG standard, so don't change them
  159936. * if you want to be compatible.
  159937. */
  159938. #define DCTSIZE 8 /* The basic DCT block is 8x8 samples */
  159939. #define DCTSIZE2 64 /* DCTSIZE squared; # of elements in a block */
  159940. #define NUM_QUANT_TBLS 4 /* Quantization tables are numbered 0..3 */
  159941. #define NUM_HUFF_TBLS 4 /* Huffman tables are numbered 0..3 */
  159942. #define NUM_ARITH_TBLS 16 /* Arith-coding tables are numbered 0..15 */
  159943. #define MAX_COMPS_IN_SCAN 4 /* JPEG limit on # of components in one scan */
  159944. #define MAX_SAMP_FACTOR 4 /* JPEG limit on sampling factors */
  159945. /* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard;
  159946. * the PostScript DCT filter can emit files with many more than 10 blocks/MCU.
  159947. * If you happen to run across such a file, you can up D_MAX_BLOCKS_IN_MCU
  159948. * to handle it. We even let you do this from the jconfig.h file. However,
  159949. * we strongly discourage changing C_MAX_BLOCKS_IN_MCU; just because Adobe
  159950. * sometimes emits noncompliant files doesn't mean you should too.
  159951. */
  159952. #define C_MAX_BLOCKS_IN_MCU 10 /* compressor's limit on blocks per MCU */
  159953. #ifndef D_MAX_BLOCKS_IN_MCU
  159954. #define D_MAX_BLOCKS_IN_MCU 10 /* decompressor's limit on blocks per MCU */
  159955. #endif
  159956. /* Data structures for images (arrays of samples and of DCT coefficients).
  159957. * On 80x86 machines, the image arrays are too big for near pointers,
  159958. * but the pointer arrays can fit in near memory.
  159959. */
  159960. typedef JSAMPLE FAR *JSAMPROW; /* ptr to one image row of pixel samples. */
  159961. typedef JSAMPROW *JSAMPARRAY; /* ptr to some rows (a 2-D sample array) */
  159962. typedef JSAMPARRAY *JSAMPIMAGE; /* a 3-D sample array: top index is color */
  159963. typedef JCOEF JBLOCK[DCTSIZE2]; /* one block of coefficients */
  159964. typedef JBLOCK FAR *JBLOCKROW; /* pointer to one row of coefficient blocks */
  159965. typedef JBLOCKROW *JBLOCKARRAY; /* a 2-D array of coefficient blocks */
  159966. typedef JBLOCKARRAY *JBLOCKIMAGE; /* a 3-D array of coefficient blocks */
  159967. typedef JCOEF FAR *JCOEFPTR; /* useful in a couple of places */
  159968. /* Types for JPEG compression parameters and working tables. */
  159969. /* DCT coefficient quantization tables. */
  159970. typedef struct {
  159971. /* This array gives the coefficient quantizers in natural array order
  159972. * (not the zigzag order in which they are stored in a JPEG DQT marker).
  159973. * CAUTION: IJG versions prior to v6a kept this array in zigzag order.
  159974. */
  159975. UINT16 quantval[DCTSIZE2]; /* quantization step for each coefficient */
  159976. /* This field is used only during compression. It's initialized FALSE when
  159977. * the table is created, and set TRUE when it's been output to the file.
  159978. * You could suppress output of a table by setting this to TRUE.
  159979. * (See jpeg_suppress_tables for an example.)
  159980. */
  159981. boolean sent_table; /* TRUE when table has been output */
  159982. } JQUANT_TBL;
  159983. /* Huffman coding tables. */
  159984. typedef struct {
  159985. /* These two fields directly represent the contents of a JPEG DHT marker */
  159986. UINT8 bits[17]; /* bits[k] = # of symbols with codes of */
  159987. /* length k bits; bits[0] is unused */
  159988. UINT8 huffval[256]; /* The symbols, in order of incr code length */
  159989. /* This field is used only during compression. It's initialized FALSE when
  159990. * the table is created, and set TRUE when it's been output to the file.
  159991. * You could suppress output of a table by setting this to TRUE.
  159992. * (See jpeg_suppress_tables for an example.)
  159993. */
  159994. boolean sent_table; /* TRUE when table has been output */
  159995. } JHUFF_TBL;
  159996. /* Basic info about one component (color channel). */
  159997. typedef struct {
  159998. /* These values are fixed over the whole image. */
  159999. /* For compression, they must be supplied by parameter setup; */
  160000. /* for decompression, they are read from the SOF marker. */
  160001. int component_id; /* identifier for this component (0..255) */
  160002. int component_index; /* its index in SOF or cinfo->comp_info[] */
  160003. int h_samp_factor; /* horizontal sampling factor (1..4) */
  160004. int v_samp_factor; /* vertical sampling factor (1..4) */
  160005. int quant_tbl_no; /* quantization table selector (0..3) */
  160006. /* These values may vary between scans. */
  160007. /* For compression, they must be supplied by parameter setup; */
  160008. /* for decompression, they are read from the SOS marker. */
  160009. /* The decompressor output side may not use these variables. */
  160010. int dc_tbl_no; /* DC entropy table selector (0..3) */
  160011. int ac_tbl_no; /* AC entropy table selector (0..3) */
  160012. /* Remaining fields should be treated as private by applications. */
  160013. /* These values are computed during compression or decompression startup: */
  160014. /* Component's size in DCT blocks.
  160015. * Any dummy blocks added to complete an MCU are not counted; therefore
  160016. * these values do not depend on whether a scan is interleaved or not.
  160017. */
  160018. JDIMENSION width_in_blocks;
  160019. JDIMENSION height_in_blocks;
  160020. /* Size of a DCT block in samples. Always DCTSIZE for compression.
  160021. * For decompression this is the size of the output from one DCT block,
  160022. * reflecting any scaling we choose to apply during the IDCT step.
  160023. * Values of 1,2,4,8 are likely to be supported. Note that different
  160024. * components may receive different IDCT scalings.
  160025. */
  160026. int DCT_scaled_size;
  160027. /* The downsampled dimensions are the component's actual, unpadded number
  160028. * of samples at the main buffer (preprocessing/compression interface), thus
  160029. * downsampled_width = ceil(image_width * Hi/Hmax)
  160030. * and similarly for height. For decompression, IDCT scaling is included, so
  160031. * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE)
  160032. */
  160033. JDIMENSION downsampled_width; /* actual width in samples */
  160034. JDIMENSION downsampled_height; /* actual height in samples */
  160035. /* This flag is used only for decompression. In cases where some of the
  160036. * components will be ignored (eg grayscale output from YCbCr image),
  160037. * we can skip most computations for the unused components.
  160038. */
  160039. boolean component_needed; /* do we need the value of this component? */
  160040. /* These values are computed before starting a scan of the component. */
  160041. /* The decompressor output side may not use these variables. */
  160042. int MCU_width; /* number of blocks per MCU, horizontally */
  160043. int MCU_height; /* number of blocks per MCU, vertically */
  160044. int MCU_blocks; /* MCU_width * MCU_height */
  160045. int MCU_sample_width; /* MCU width in samples, MCU_width*DCT_scaled_size */
  160046. int last_col_width; /* # of non-dummy blocks across in last MCU */
  160047. int last_row_height; /* # of non-dummy blocks down in last MCU */
  160048. /* Saved quantization table for component; NULL if none yet saved.
  160049. * See jdinput.c comments about the need for this information.
  160050. * This field is currently used only for decompression.
  160051. */
  160052. JQUANT_TBL * quant_table;
  160053. /* Private per-component storage for DCT or IDCT subsystem. */
  160054. void * dct_table;
  160055. } jpeg_component_info;
  160056. /* The script for encoding a multiple-scan file is an array of these: */
  160057. typedef struct {
  160058. int comps_in_scan; /* number of components encoded in this scan */
  160059. int component_index[MAX_COMPS_IN_SCAN]; /* their SOF/comp_info[] indexes */
  160060. int Ss, Se; /* progressive JPEG spectral selection parms */
  160061. int Ah, Al; /* progressive JPEG successive approx. parms */
  160062. } jpeg_scan_info;
  160063. /* The decompressor can save APPn and COM markers in a list of these: */
  160064. typedef struct jpeg_marker_struct FAR * jpeg_saved_marker_ptr;
  160065. struct jpeg_marker_struct {
  160066. jpeg_saved_marker_ptr next; /* next in list, or NULL */
  160067. UINT8 marker; /* marker code: JPEG_COM, or JPEG_APP0+n */
  160068. unsigned int original_length; /* # bytes of data in the file */
  160069. unsigned int data_length; /* # bytes of data saved at data[] */
  160070. JOCTET FAR * data; /* the data contained in the marker */
  160071. /* the marker length word is not counted in data_length or original_length */
  160072. };
  160073. /* Known color spaces. */
  160074. typedef enum {
  160075. JCS_UNKNOWN, /* error/unspecified */
  160076. JCS_GRAYSCALE, /* monochrome */
  160077. JCS_RGB, /* red/green/blue */
  160078. JCS_YCbCr, /* Y/Cb/Cr (also known as YUV) */
  160079. JCS_CMYK, /* C/M/Y/K */
  160080. JCS_YCCK /* Y/Cb/Cr/K */
  160081. } J_COLOR_SPACE;
  160082. /* DCT/IDCT algorithm options. */
  160083. typedef enum {
  160084. JDCT_ISLOW, /* slow but accurate integer algorithm */
  160085. JDCT_IFAST, /* faster, less accurate integer method */
  160086. JDCT_FLOAT /* floating-point: accurate, fast on fast HW */
  160087. } J_DCT_METHOD;
  160088. #ifndef JDCT_DEFAULT /* may be overridden in jconfig.h */
  160089. #define JDCT_DEFAULT JDCT_ISLOW
  160090. #endif
  160091. #ifndef JDCT_FASTEST /* may be overridden in jconfig.h */
  160092. #define JDCT_FASTEST JDCT_IFAST
  160093. #endif
  160094. /* Dithering options for decompression. */
  160095. typedef enum {
  160096. JDITHER_NONE, /* no dithering */
  160097. JDITHER_ORDERED, /* simple ordered dither */
  160098. JDITHER_FS /* Floyd-Steinberg error diffusion dither */
  160099. } J_DITHER_MODE;
  160100. /* Common fields between JPEG compression and decompression master structs. */
  160101. #define jpeg_common_fields \
  160102. struct jpeg_error_mgr * err; /* Error handler module */\
  160103. struct jpeg_memory_mgr * mem; /* Memory manager module */\
  160104. struct jpeg_progress_mgr * progress; /* Progress monitor, or NULL if none */\
  160105. void * client_data; /* Available for use by application */\
  160106. boolean is_decompressor; /* So common code can tell which is which */\
  160107. int global_state /* For checking call sequence validity */
  160108. /* Routines that are to be used by both halves of the library are declared
  160109. * to receive a pointer to this structure. There are no actual instances of
  160110. * jpeg_common_struct, only of jpeg_compress_struct and jpeg_decompress_struct.
  160111. */
  160112. struct jpeg_common_struct {
  160113. jpeg_common_fields; /* Fields common to both master struct types */
  160114. /* Additional fields follow in an actual jpeg_compress_struct or
  160115. * jpeg_decompress_struct. All three structs must agree on these
  160116. * initial fields! (This would be a lot cleaner in C++.)
  160117. */
  160118. };
  160119. typedef struct jpeg_common_struct * j_common_ptr;
  160120. typedef struct jpeg_compress_struct * j_compress_ptr;
  160121. typedef struct jpeg_decompress_struct * j_decompress_ptr;
  160122. /* Master record for a compression instance */
  160123. struct jpeg_compress_struct {
  160124. jpeg_common_fields; /* Fields shared with jpeg_decompress_struct */
  160125. /* Destination for compressed data */
  160126. struct jpeg_destination_mgr * dest;
  160127. /* Description of source image --- these fields must be filled in by
  160128. * outer application before starting compression. in_color_space must
  160129. * be correct before you can even call jpeg_set_defaults().
  160130. */
  160131. JDIMENSION image_width; /* input image width */
  160132. JDIMENSION image_height; /* input image height */
  160133. int input_components; /* # of color components in input image */
  160134. J_COLOR_SPACE in_color_space; /* colorspace of input image */
  160135. double input_gamma; /* image gamma of input image */
  160136. /* Compression parameters --- these fields must be set before calling
  160137. * jpeg_start_compress(). We recommend calling jpeg_set_defaults() to
  160138. * initialize everything to reasonable defaults, then changing anything
  160139. * the application specifically wants to change. That way you won't get
  160140. * burnt when new parameters are added. Also note that there are several
  160141. * helper routines to simplify changing parameters.
  160142. */
  160143. int data_precision; /* bits of precision in image data */
  160144. int num_components; /* # of color components in JPEG image */
  160145. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  160146. jpeg_component_info * comp_info;
  160147. /* comp_info[i] describes component that appears i'th in SOF */
  160148. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  160149. /* ptrs to coefficient quantization tables, or NULL if not defined */
  160150. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160151. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160152. /* ptrs to Huffman coding tables, or NULL if not defined */
  160153. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  160154. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  160155. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  160156. int num_scans; /* # of entries in scan_info array */
  160157. const jpeg_scan_info * scan_info; /* script for multi-scan file, or NULL */
  160158. /* The default value of scan_info is NULL, which causes a single-scan
  160159. * sequential JPEG file to be emitted. To create a multi-scan file,
  160160. * set num_scans and scan_info to point to an array of scan definitions.
  160161. */
  160162. boolean raw_data_in; /* TRUE=caller supplies downsampled data */
  160163. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  160164. boolean optimize_coding; /* TRUE=optimize entropy encoding parms */
  160165. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  160166. int smoothing_factor; /* 1..100, or 0 for no input smoothing */
  160167. J_DCT_METHOD dct_method; /* DCT algorithm selector */
  160168. /* The restart interval can be specified in absolute MCUs by setting
  160169. * restart_interval, or in MCU rows by setting restart_in_rows
  160170. * (in which case the correct restart_interval will be figured
  160171. * for each scan).
  160172. */
  160173. unsigned int restart_interval; /* MCUs per restart, or 0 for no restart */
  160174. int restart_in_rows; /* if > 0, MCU rows per restart interval */
  160175. /* Parameters controlling emission of special markers. */
  160176. boolean write_JFIF_header; /* should a JFIF marker be written? */
  160177. UINT8 JFIF_major_version; /* What to write for the JFIF version number */
  160178. UINT8 JFIF_minor_version;
  160179. /* These three values are not used by the JPEG code, merely copied */
  160180. /* into the JFIF APP0 marker. density_unit can be 0 for unknown, */
  160181. /* 1 for dots/inch, or 2 for dots/cm. Note that the pixel aspect */
  160182. /* ratio is defined by X_density/Y_density even when density_unit=0. */
  160183. UINT8 density_unit; /* JFIF code for pixel size units */
  160184. UINT16 X_density; /* Horizontal pixel density */
  160185. UINT16 Y_density; /* Vertical pixel density */
  160186. boolean write_Adobe_marker; /* should an Adobe marker be written? */
  160187. /* State variable: index of next scanline to be written to
  160188. * jpeg_write_scanlines(). Application may use this to control its
  160189. * processing loop, e.g., "while (next_scanline < image_height)".
  160190. */
  160191. JDIMENSION next_scanline; /* 0 .. image_height-1 */
  160192. /* Remaining fields are known throughout compressor, but generally
  160193. * should not be touched by a surrounding application.
  160194. */
  160195. /*
  160196. * These fields are computed during compression startup
  160197. */
  160198. boolean progressive_mode; /* TRUE if scan script uses progressive mode */
  160199. int max_h_samp_factor; /* largest h_samp_factor */
  160200. int max_v_samp_factor; /* largest v_samp_factor */
  160201. JDIMENSION total_iMCU_rows; /* # of iMCU rows to be input to coef ctlr */
  160202. /* The coefficient controller receives data in units of MCU rows as defined
  160203. * for fully interleaved scans (whether the JPEG file is interleaved or not).
  160204. * There are v_samp_factor * DCTSIZE sample rows of each component in an
  160205. * "iMCU" (interleaved MCU) row.
  160206. */
  160207. /*
  160208. * These fields are valid during any one scan.
  160209. * They describe the components and MCUs actually appearing in the scan.
  160210. */
  160211. int comps_in_scan; /* # of JPEG components in this scan */
  160212. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  160213. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  160214. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  160215. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  160216. int blocks_in_MCU; /* # of DCT blocks per MCU */
  160217. int MCU_membership[C_MAX_BLOCKS_IN_MCU];
  160218. /* MCU_membership[i] is index in cur_comp_info of component owning */
  160219. /* i'th block in an MCU */
  160220. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  160221. /*
  160222. * Links to compression subobjects (methods and private variables of modules)
  160223. */
  160224. struct jpeg_comp_master * master;
  160225. struct jpeg_c_main_controller * main;
  160226. struct jpeg_c_prep_controller * prep;
  160227. struct jpeg_c_coef_controller * coef;
  160228. struct jpeg_marker_writer * marker;
  160229. struct jpeg_color_converter * cconvert;
  160230. struct jpeg_downsampler * downsample;
  160231. struct jpeg_forward_dct * fdct;
  160232. struct jpeg_entropy_encoder * entropy;
  160233. jpeg_scan_info * script_space; /* workspace for jpeg_simple_progression */
  160234. int script_space_size;
  160235. };
  160236. /* Master record for a decompression instance */
  160237. struct jpeg_decompress_struct {
  160238. jpeg_common_fields; /* Fields shared with jpeg_compress_struct */
  160239. /* Source of compressed data */
  160240. struct jpeg_source_mgr * src;
  160241. /* Basic description of image --- filled in by jpeg_read_header(). */
  160242. /* Application may inspect these values to decide how to process image. */
  160243. JDIMENSION image_width; /* nominal image width (from SOF marker) */
  160244. JDIMENSION image_height; /* nominal image height */
  160245. int num_components; /* # of color components in JPEG image */
  160246. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  160247. /* Decompression processing parameters --- these fields must be set before
  160248. * calling jpeg_start_decompress(). Note that jpeg_read_header() initializes
  160249. * them to default values.
  160250. */
  160251. J_COLOR_SPACE out_color_space; /* colorspace for output */
  160252. unsigned int scale_num, scale_denom; /* fraction by which to scale image */
  160253. double output_gamma; /* image gamma wanted in output */
  160254. boolean buffered_image; /* TRUE=multiple output passes */
  160255. boolean raw_data_out; /* TRUE=downsampled data wanted */
  160256. J_DCT_METHOD dct_method; /* IDCT algorithm selector */
  160257. boolean do_fancy_upsampling; /* TRUE=apply fancy upsampling */
  160258. boolean do_block_smoothing; /* TRUE=apply interblock smoothing */
  160259. boolean quantize_colors; /* TRUE=colormapped output wanted */
  160260. /* the following are ignored if not quantize_colors: */
  160261. J_DITHER_MODE dither_mode; /* type of color dithering to use */
  160262. boolean two_pass_quantize; /* TRUE=use two-pass color quantization */
  160263. int desired_number_of_colors; /* max # colors to use in created colormap */
  160264. /* these are significant only in buffered-image mode: */
  160265. boolean enable_1pass_quant; /* enable future use of 1-pass quantizer */
  160266. boolean enable_external_quant;/* enable future use of external colormap */
  160267. boolean enable_2pass_quant; /* enable future use of 2-pass quantizer */
  160268. /* Description of actual output image that will be returned to application.
  160269. * These fields are computed by jpeg_start_decompress().
  160270. * You can also use jpeg_calc_output_dimensions() to determine these values
  160271. * in advance of calling jpeg_start_decompress().
  160272. */
  160273. JDIMENSION output_width; /* scaled image width */
  160274. JDIMENSION output_height; /* scaled image height */
  160275. int out_color_components; /* # of color components in out_color_space */
  160276. int output_components; /* # of color components returned */
  160277. /* output_components is 1 (a colormap index) when quantizing colors;
  160278. * otherwise it equals out_color_components.
  160279. */
  160280. int rec_outbuf_height; /* min recommended height of scanline buffer */
  160281. /* If the buffer passed to jpeg_read_scanlines() is less than this many rows
  160282. * high, space and time will be wasted due to unnecessary data copying.
  160283. * Usually rec_outbuf_height will be 1 or 2, at most 4.
  160284. */
  160285. /* When quantizing colors, the output colormap is described by these fields.
  160286. * The application can supply a colormap by setting colormap non-NULL before
  160287. * calling jpeg_start_decompress; otherwise a colormap is created during
  160288. * jpeg_start_decompress or jpeg_start_output.
  160289. * The map has out_color_components rows and actual_number_of_colors columns.
  160290. */
  160291. int actual_number_of_colors; /* number of entries in use */
  160292. JSAMPARRAY colormap; /* The color map as a 2-D pixel array */
  160293. /* State variables: these variables indicate the progress of decompression.
  160294. * The application may examine these but must not modify them.
  160295. */
  160296. /* Row index of next scanline to be read from jpeg_read_scanlines().
  160297. * Application may use this to control its processing loop, e.g.,
  160298. * "while (output_scanline < output_height)".
  160299. */
  160300. JDIMENSION output_scanline; /* 0 .. output_height-1 */
  160301. /* Current input scan number and number of iMCU rows completed in scan.
  160302. * These indicate the progress of the decompressor input side.
  160303. */
  160304. int input_scan_number; /* Number of SOS markers seen so far */
  160305. JDIMENSION input_iMCU_row; /* Number of iMCU rows completed */
  160306. /* The "output scan number" is the notional scan being displayed by the
  160307. * output side. The decompressor will not allow output scan/row number
  160308. * to get ahead of input scan/row, but it can fall arbitrarily far behind.
  160309. */
  160310. int output_scan_number; /* Nominal scan number being displayed */
  160311. JDIMENSION output_iMCU_row; /* Number of iMCU rows read */
  160312. /* Current progression status. coef_bits[c][i] indicates the precision
  160313. * with which component c's DCT coefficient i (in zigzag order) is known.
  160314. * It is -1 when no data has yet been received, otherwise it is the point
  160315. * transform (shift) value for the most recent scan of the coefficient
  160316. * (thus, 0 at completion of the progression).
  160317. * This pointer is NULL when reading a non-progressive file.
  160318. */
  160319. int (*coef_bits)[DCTSIZE2]; /* -1 or current Al value for each coef */
  160320. /* Internal JPEG parameters --- the application usually need not look at
  160321. * these fields. Note that the decompressor output side may not use
  160322. * any parameters that can change between scans.
  160323. */
  160324. /* Quantization and Huffman tables are carried forward across input
  160325. * datastreams when processing abbreviated JPEG datastreams.
  160326. */
  160327. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  160328. /* ptrs to coefficient quantization tables, or NULL if not defined */
  160329. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160330. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160331. /* ptrs to Huffman coding tables, or NULL if not defined */
  160332. /* These parameters are never carried across datastreams, since they
  160333. * are given in SOF/SOS markers or defined to be reset by SOI.
  160334. */
  160335. int data_precision; /* bits of precision in image data */
  160336. jpeg_component_info * comp_info;
  160337. /* comp_info[i] describes component that appears i'th in SOF */
  160338. boolean progressive_mode; /* TRUE if SOFn specifies progressive mode */
  160339. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  160340. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  160341. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  160342. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  160343. unsigned int restart_interval; /* MCUs per restart interval, or 0 for no restart */
  160344. /* These fields record data obtained from optional markers recognized by
  160345. * the JPEG library.
  160346. */
  160347. boolean saw_JFIF_marker; /* TRUE iff a JFIF APP0 marker was found */
  160348. /* Data copied from JFIF marker; only valid if saw_JFIF_marker is TRUE: */
  160349. UINT8 JFIF_major_version; /* JFIF version number */
  160350. UINT8 JFIF_minor_version;
  160351. UINT8 density_unit; /* JFIF code for pixel size units */
  160352. UINT16 X_density; /* Horizontal pixel density */
  160353. UINT16 Y_density; /* Vertical pixel density */
  160354. boolean saw_Adobe_marker; /* TRUE iff an Adobe APP14 marker was found */
  160355. UINT8 Adobe_transform; /* Color transform code from Adobe marker */
  160356. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  160357. /* Aside from the specific data retained from APPn markers known to the
  160358. * library, the uninterpreted contents of any or all APPn and COM markers
  160359. * can be saved in a list for examination by the application.
  160360. */
  160361. jpeg_saved_marker_ptr marker_list; /* Head of list of saved markers */
  160362. /* Remaining fields are known throughout decompressor, but generally
  160363. * should not be touched by a surrounding application.
  160364. */
  160365. /*
  160366. * These fields are computed during decompression startup
  160367. */
  160368. int max_h_samp_factor; /* largest h_samp_factor */
  160369. int max_v_samp_factor; /* largest v_samp_factor */
  160370. int min_DCT_scaled_size; /* smallest DCT_scaled_size of any component */
  160371. JDIMENSION total_iMCU_rows; /* # of iMCU rows in image */
  160372. /* The coefficient controller's input and output progress is measured in
  160373. * units of "iMCU" (interleaved MCU) rows. These are the same as MCU rows
  160374. * in fully interleaved JPEG scans, but are used whether the scan is
  160375. * interleaved or not. We define an iMCU row as v_samp_factor DCT block
  160376. * rows of each component. Therefore, the IDCT output contains
  160377. * v_samp_factor*DCT_scaled_size sample rows of a component per iMCU row.
  160378. */
  160379. JSAMPLE * sample_range_limit; /* table for fast range-limiting */
  160380. /*
  160381. * These fields are valid during any one scan.
  160382. * They describe the components and MCUs actually appearing in the scan.
  160383. * Note that the decompressor output side must not use these fields.
  160384. */
  160385. int comps_in_scan; /* # of JPEG components in this scan */
  160386. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  160387. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  160388. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  160389. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  160390. int blocks_in_MCU; /* # of DCT blocks per MCU */
  160391. int MCU_membership[D_MAX_BLOCKS_IN_MCU];
  160392. /* MCU_membership[i] is index in cur_comp_info of component owning */
  160393. /* i'th block in an MCU */
  160394. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  160395. /* This field is shared between entropy decoder and marker parser.
  160396. * It is either zero or the code of a JPEG marker that has been
  160397. * read from the data source, but has not yet been processed.
  160398. */
  160399. int unread_marker;
  160400. /*
  160401. * Links to decompression subobjects (methods, private variables of modules)
  160402. */
  160403. struct jpeg_decomp_master * master;
  160404. struct jpeg_d_main_controller * main;
  160405. struct jpeg_d_coef_controller * coef;
  160406. struct jpeg_d_post_controller * post;
  160407. struct jpeg_input_controller * inputctl;
  160408. struct jpeg_marker_reader * marker;
  160409. struct jpeg_entropy_decoder * entropy;
  160410. struct jpeg_inverse_dct * idct;
  160411. struct jpeg_upsampler * upsample;
  160412. struct jpeg_color_deconverter * cconvert;
  160413. struct jpeg_color_quantizer * cquantize;
  160414. };
  160415. /* "Object" declarations for JPEG modules that may be supplied or called
  160416. * directly by the surrounding application.
  160417. * As with all objects in the JPEG library, these structs only define the
  160418. * publicly visible methods and state variables of a module. Additional
  160419. * private fields may exist after the public ones.
  160420. */
  160421. /* Error handler object */
  160422. struct jpeg_error_mgr {
  160423. /* Error exit handler: does not return to caller */
  160424. JMETHOD(void, error_exit, (j_common_ptr cinfo));
  160425. /* Conditionally emit a trace or warning message */
  160426. JMETHOD(void, emit_message, (j_common_ptr cinfo, int msg_level));
  160427. /* Routine that actually outputs a trace or error message */
  160428. JMETHOD(void, output_message, (j_common_ptr cinfo));
  160429. /* Format a message string for the most recent JPEG error or message */
  160430. JMETHOD(void, format_message, (j_common_ptr cinfo, char * buffer));
  160431. #define JMSG_LENGTH_MAX 200 /* recommended size of format_message buffer */
  160432. /* Reset error state variables at start of a new image */
  160433. JMETHOD(void, reset_error_mgr, (j_common_ptr cinfo));
  160434. /* The message ID code and any parameters are saved here.
  160435. * A message can have one string parameter or up to 8 int parameters.
  160436. */
  160437. int msg_code;
  160438. #define JMSG_STR_PARM_MAX 80
  160439. union {
  160440. int i[8];
  160441. char s[JMSG_STR_PARM_MAX];
  160442. } msg_parm;
  160443. /* Standard state variables for error facility */
  160444. int trace_level; /* max msg_level that will be displayed */
  160445. /* For recoverable corrupt-data errors, we emit a warning message,
  160446. * but keep going unless emit_message chooses to abort. emit_message
  160447. * should count warnings in num_warnings. The surrounding application
  160448. * can check for bad data by seeing if num_warnings is nonzero at the
  160449. * end of processing.
  160450. */
  160451. long num_warnings; /* number of corrupt-data warnings */
  160452. /* These fields point to the table(s) of error message strings.
  160453. * An application can change the table pointer to switch to a different
  160454. * message list (typically, to change the language in which errors are
  160455. * reported). Some applications may wish to add additional error codes
  160456. * that will be handled by the JPEG library error mechanism; the second
  160457. * table pointer is used for this purpose.
  160458. *
  160459. * First table includes all errors generated by JPEG library itself.
  160460. * Error code 0 is reserved for a "no such error string" message.
  160461. */
  160462. const char * const * jpeg_message_table; /* Library errors */
  160463. int last_jpeg_message; /* Table contains strings 0..last_jpeg_message */
  160464. /* Second table can be added by application (see cjpeg/djpeg for example).
  160465. * It contains strings numbered first_addon_message..last_addon_message.
  160466. */
  160467. const char * const * addon_message_table; /* Non-library errors */
  160468. int first_addon_message; /* code for first string in addon table */
  160469. int last_addon_message; /* code for last string in addon table */
  160470. };
  160471. /* Progress monitor object */
  160472. struct jpeg_progress_mgr {
  160473. JMETHOD(void, progress_monitor, (j_common_ptr cinfo));
  160474. long pass_counter; /* work units completed in this pass */
  160475. long pass_limit; /* total number of work units in this pass */
  160476. int completed_passes; /* passes completed so far */
  160477. int total_passes; /* total number of passes expected */
  160478. };
  160479. /* Data destination object for compression */
  160480. struct jpeg_destination_mgr {
  160481. JOCTET * next_output_byte; /* => next byte to write in buffer */
  160482. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  160483. JMETHOD(void, init_destination, (j_compress_ptr cinfo));
  160484. JMETHOD(boolean, empty_output_buffer, (j_compress_ptr cinfo));
  160485. JMETHOD(void, term_destination, (j_compress_ptr cinfo));
  160486. };
  160487. /* Data source object for decompression */
  160488. struct jpeg_source_mgr {
  160489. const JOCTET * next_input_byte; /* => next byte to read from buffer */
  160490. size_t bytes_in_buffer; /* # of bytes remaining in buffer */
  160491. JMETHOD(void, init_source, (j_decompress_ptr cinfo));
  160492. JMETHOD(boolean, fill_input_buffer, (j_decompress_ptr cinfo));
  160493. JMETHOD(void, skip_input_data, (j_decompress_ptr cinfo, long num_bytes));
  160494. JMETHOD(boolean, resync_to_restart, (j_decompress_ptr cinfo, int desired));
  160495. JMETHOD(void, term_source, (j_decompress_ptr cinfo));
  160496. };
  160497. /* Memory manager object.
  160498. * Allocates "small" objects (a few K total), "large" objects (tens of K),
  160499. * and "really big" objects (virtual arrays with backing store if needed).
  160500. * The memory manager does not allow individual objects to be freed; rather,
  160501. * each created object is assigned to a pool, and whole pools can be freed
  160502. * at once. This is faster and more convenient than remembering exactly what
  160503. * to free, especially where malloc()/free() are not too speedy.
  160504. * NB: alloc routines never return NULL. They exit to error_exit if not
  160505. * successful.
  160506. */
  160507. #define JPOOL_PERMANENT 0 /* lasts until master record is destroyed */
  160508. #define JPOOL_IMAGE 1 /* lasts until done with image/datastream */
  160509. #define JPOOL_NUMPOOLS 2
  160510. typedef struct jvirt_sarray_control * jvirt_sarray_ptr;
  160511. typedef struct jvirt_barray_control * jvirt_barray_ptr;
  160512. struct jpeg_memory_mgr {
  160513. /* Method pointers */
  160514. JMETHOD(void *, alloc_small, (j_common_ptr cinfo, int pool_id,
  160515. size_t sizeofobject));
  160516. JMETHOD(void FAR *, alloc_large, (j_common_ptr cinfo, int pool_id,
  160517. size_t sizeofobject));
  160518. JMETHOD(JSAMPARRAY, alloc_sarray, (j_common_ptr cinfo, int pool_id,
  160519. JDIMENSION samplesperrow,
  160520. JDIMENSION numrows));
  160521. JMETHOD(JBLOCKARRAY, alloc_barray, (j_common_ptr cinfo, int pool_id,
  160522. JDIMENSION blocksperrow,
  160523. JDIMENSION numrows));
  160524. JMETHOD(jvirt_sarray_ptr, request_virt_sarray, (j_common_ptr cinfo,
  160525. int pool_id,
  160526. boolean pre_zero,
  160527. JDIMENSION samplesperrow,
  160528. JDIMENSION numrows,
  160529. JDIMENSION maxaccess));
  160530. JMETHOD(jvirt_barray_ptr, request_virt_barray, (j_common_ptr cinfo,
  160531. int pool_id,
  160532. boolean pre_zero,
  160533. JDIMENSION blocksperrow,
  160534. JDIMENSION numrows,
  160535. JDIMENSION maxaccess));
  160536. JMETHOD(void, realize_virt_arrays, (j_common_ptr cinfo));
  160537. JMETHOD(JSAMPARRAY, access_virt_sarray, (j_common_ptr cinfo,
  160538. jvirt_sarray_ptr ptr,
  160539. JDIMENSION start_row,
  160540. JDIMENSION num_rows,
  160541. boolean writable));
  160542. JMETHOD(JBLOCKARRAY, access_virt_barray, (j_common_ptr cinfo,
  160543. jvirt_barray_ptr ptr,
  160544. JDIMENSION start_row,
  160545. JDIMENSION num_rows,
  160546. boolean writable));
  160547. JMETHOD(void, free_pool, (j_common_ptr cinfo, int pool_id));
  160548. JMETHOD(void, self_destruct, (j_common_ptr cinfo));
  160549. /* Limit on memory allocation for this JPEG object. (Note that this is
  160550. * merely advisory, not a guaranteed maximum; it only affects the space
  160551. * used for virtual-array buffers.) May be changed by outer application
  160552. * after creating the JPEG object.
  160553. */
  160554. long max_memory_to_use;
  160555. /* Maximum allocation request accepted by alloc_large. */
  160556. long max_alloc_chunk;
  160557. };
  160558. /* Routine signature for application-supplied marker processing methods.
  160559. * Need not pass marker code since it is stored in cinfo->unread_marker.
  160560. */
  160561. typedef JMETHOD(boolean, jpeg_marker_parser_method, (j_decompress_ptr cinfo));
  160562. /* Declarations for routines called by application.
  160563. * The JPP macro hides prototype parameters from compilers that can't cope.
  160564. * Note JPP requires double parentheses.
  160565. */
  160566. #ifdef HAVE_PROTOTYPES
  160567. #define JPP(arglist) arglist
  160568. #else
  160569. #define JPP(arglist) ()
  160570. #endif
  160571. /* Short forms of external names for systems with brain-damaged linkers.
  160572. * We shorten external names to be unique in the first six letters, which
  160573. * is good enough for all known systems.
  160574. * (If your compiler itself needs names to be unique in less than 15
  160575. * characters, you are out of luck. Get a better compiler.)
  160576. */
  160577. #ifdef NEED_SHORT_EXTERNAL_NAMES
  160578. #define jpeg_std_error jStdError
  160579. #define jpeg_CreateCompress jCreaCompress
  160580. #define jpeg_CreateDecompress jCreaDecompress
  160581. #define jpeg_destroy_compress jDestCompress
  160582. #define jpeg_destroy_decompress jDestDecompress
  160583. #define jpeg_stdio_dest jStdDest
  160584. #define jpeg_stdio_src jStdSrc
  160585. #define jpeg_set_defaults jSetDefaults
  160586. #define jpeg_set_colorspace jSetColorspace
  160587. #define jpeg_default_colorspace jDefColorspace
  160588. #define jpeg_set_quality jSetQuality
  160589. #define jpeg_set_linear_quality jSetLQuality
  160590. #define jpeg_add_quant_table jAddQuantTable
  160591. #define jpeg_quality_scaling jQualityScaling
  160592. #define jpeg_simple_progression jSimProgress
  160593. #define jpeg_suppress_tables jSuppressTables
  160594. #define jpeg_alloc_quant_table jAlcQTable
  160595. #define jpeg_alloc_huff_table jAlcHTable
  160596. #define jpeg_start_compress jStrtCompress
  160597. #define jpeg_write_scanlines jWrtScanlines
  160598. #define jpeg_finish_compress jFinCompress
  160599. #define jpeg_write_raw_data jWrtRawData
  160600. #define jpeg_write_marker jWrtMarker
  160601. #define jpeg_write_m_header jWrtMHeader
  160602. #define jpeg_write_m_byte jWrtMByte
  160603. #define jpeg_write_tables jWrtTables
  160604. #define jpeg_read_header jReadHeader
  160605. #define jpeg_start_decompress jStrtDecompress
  160606. #define jpeg_read_scanlines jReadScanlines
  160607. #define jpeg_finish_decompress jFinDecompress
  160608. #define jpeg_read_raw_data jReadRawData
  160609. #define jpeg_has_multiple_scans jHasMultScn
  160610. #define jpeg_start_output jStrtOutput
  160611. #define jpeg_finish_output jFinOutput
  160612. #define jpeg_input_complete jInComplete
  160613. #define jpeg_new_colormap jNewCMap
  160614. #define jpeg_consume_input jConsumeInput
  160615. #define jpeg_calc_output_dimensions jCalcDimensions
  160616. #define jpeg_save_markers jSaveMarkers
  160617. #define jpeg_set_marker_processor jSetMarker
  160618. #define jpeg_read_coefficients jReadCoefs
  160619. #define jpeg_write_coefficients jWrtCoefs
  160620. #define jpeg_copy_critical_parameters jCopyCrit
  160621. #define jpeg_abort_compress jAbrtCompress
  160622. #define jpeg_abort_decompress jAbrtDecompress
  160623. #define jpeg_abort jAbort
  160624. #define jpeg_destroy jDestroy
  160625. #define jpeg_resync_to_restart jResyncRestart
  160626. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  160627. /* Default error-management setup */
  160628. EXTERN(struct jpeg_error_mgr *) jpeg_std_error
  160629. JPP((struct jpeg_error_mgr * err));
  160630. /* Initialization of JPEG compression objects.
  160631. * jpeg_create_compress() and jpeg_create_decompress() are the exported
  160632. * names that applications should call. These expand to calls on
  160633. * jpeg_CreateCompress and jpeg_CreateDecompress with additional information
  160634. * passed for version mismatch checking.
  160635. * NB: you must set up the error-manager BEFORE calling jpeg_create_xxx.
  160636. */
  160637. #define jpeg_create_compress(cinfo) \
  160638. jpeg_CreateCompress((cinfo), JPEG_LIB_VERSION, \
  160639. (size_t) sizeof(struct jpeg_compress_struct))
  160640. #define jpeg_create_decompress(cinfo) \
  160641. jpeg_CreateDecompress((cinfo), JPEG_LIB_VERSION, \
  160642. (size_t) sizeof(struct jpeg_decompress_struct))
  160643. EXTERN(void) jpeg_CreateCompress JPP((j_compress_ptr cinfo,
  160644. int version, size_t structsize));
  160645. EXTERN(void) jpeg_CreateDecompress JPP((j_decompress_ptr cinfo,
  160646. int version, size_t structsize));
  160647. /* Destruction of JPEG compression objects */
  160648. EXTERN(void) jpeg_destroy_compress JPP((j_compress_ptr cinfo));
  160649. EXTERN(void) jpeg_destroy_decompress JPP((j_decompress_ptr cinfo));
  160650. /* Standard data source and destination managers: stdio streams. */
  160651. /* Caller is responsible for opening the file before and closing after. */
  160652. EXTERN(void) jpeg_stdio_dest JPP((j_compress_ptr cinfo, FILE * outfile));
  160653. EXTERN(void) jpeg_stdio_src JPP((j_decompress_ptr cinfo, FILE * infile));
  160654. /* Default parameter setup for compression */
  160655. EXTERN(void) jpeg_set_defaults JPP((j_compress_ptr cinfo));
  160656. /* Compression parameter setup aids */
  160657. EXTERN(void) jpeg_set_colorspace JPP((j_compress_ptr cinfo,
  160658. J_COLOR_SPACE colorspace));
  160659. EXTERN(void) jpeg_default_colorspace JPP((j_compress_ptr cinfo));
  160660. EXTERN(void) jpeg_set_quality JPP((j_compress_ptr cinfo, int quality,
  160661. boolean force_baseline));
  160662. EXTERN(void) jpeg_set_linear_quality JPP((j_compress_ptr cinfo,
  160663. int scale_factor,
  160664. boolean force_baseline));
  160665. EXTERN(void) jpeg_add_quant_table JPP((j_compress_ptr cinfo, int which_tbl,
  160666. const unsigned int *basic_table,
  160667. int scale_factor,
  160668. boolean force_baseline));
  160669. EXTERN(int) jpeg_quality_scaling JPP((int quality));
  160670. EXTERN(void) jpeg_simple_progression JPP((j_compress_ptr cinfo));
  160671. EXTERN(void) jpeg_suppress_tables JPP((j_compress_ptr cinfo,
  160672. boolean suppress));
  160673. EXTERN(JQUANT_TBL *) jpeg_alloc_quant_table JPP((j_common_ptr cinfo));
  160674. EXTERN(JHUFF_TBL *) jpeg_alloc_huff_table JPP((j_common_ptr cinfo));
  160675. /* Main entry points for compression */
  160676. EXTERN(void) jpeg_start_compress JPP((j_compress_ptr cinfo,
  160677. boolean write_all_tables));
  160678. EXTERN(JDIMENSION) jpeg_write_scanlines JPP((j_compress_ptr cinfo,
  160679. JSAMPARRAY scanlines,
  160680. JDIMENSION num_lines));
  160681. EXTERN(void) jpeg_finish_compress JPP((j_compress_ptr cinfo));
  160682. /* Replaces jpeg_write_scanlines when writing raw downsampled data. */
  160683. EXTERN(JDIMENSION) jpeg_write_raw_data JPP((j_compress_ptr cinfo,
  160684. JSAMPIMAGE data,
  160685. JDIMENSION num_lines));
  160686. /* Write a special marker. See libjpeg.doc concerning safe usage. */
  160687. EXTERN(void) jpeg_write_marker
  160688. JPP((j_compress_ptr cinfo, int marker,
  160689. const JOCTET * dataptr, unsigned int datalen));
  160690. /* Same, but piecemeal. */
  160691. EXTERN(void) jpeg_write_m_header
  160692. JPP((j_compress_ptr cinfo, int marker, unsigned int datalen));
  160693. EXTERN(void) jpeg_write_m_byte
  160694. JPP((j_compress_ptr cinfo, int val));
  160695. /* Alternate compression function: just write an abbreviated table file */
  160696. EXTERN(void) jpeg_write_tables JPP((j_compress_ptr cinfo));
  160697. /* Decompression startup: read start of JPEG datastream to see what's there */
  160698. EXTERN(int) jpeg_read_header JPP((j_decompress_ptr cinfo,
  160699. boolean require_image));
  160700. /* Return value is one of: */
  160701. #define JPEG_SUSPENDED 0 /* Suspended due to lack of input data */
  160702. #define JPEG_HEADER_OK 1 /* Found valid image datastream */
  160703. #define JPEG_HEADER_TABLES_ONLY 2 /* Found valid table-specs-only datastream */
  160704. /* If you pass require_image = TRUE (normal case), you need not check for
  160705. * a TABLES_ONLY return code; an abbreviated file will cause an error exit.
  160706. * JPEG_SUSPENDED is only possible if you use a data source module that can
  160707. * give a suspension return (the stdio source module doesn't).
  160708. */
  160709. /* Main entry points for decompression */
  160710. EXTERN(boolean) jpeg_start_decompress JPP((j_decompress_ptr cinfo));
  160711. EXTERN(JDIMENSION) jpeg_read_scanlines JPP((j_decompress_ptr cinfo,
  160712. JSAMPARRAY scanlines,
  160713. JDIMENSION max_lines));
  160714. EXTERN(boolean) jpeg_finish_decompress JPP((j_decompress_ptr cinfo));
  160715. /* Replaces jpeg_read_scanlines when reading raw downsampled data. */
  160716. EXTERN(JDIMENSION) jpeg_read_raw_data JPP((j_decompress_ptr cinfo,
  160717. JSAMPIMAGE data,
  160718. JDIMENSION max_lines));
  160719. /* Additional entry points for buffered-image mode. */
  160720. EXTERN(boolean) jpeg_has_multiple_scans JPP((j_decompress_ptr cinfo));
  160721. EXTERN(boolean) jpeg_start_output JPP((j_decompress_ptr cinfo,
  160722. int scan_number));
  160723. EXTERN(boolean) jpeg_finish_output JPP((j_decompress_ptr cinfo));
  160724. EXTERN(boolean) jpeg_input_complete JPP((j_decompress_ptr cinfo));
  160725. EXTERN(void) jpeg_new_colormap JPP((j_decompress_ptr cinfo));
  160726. EXTERN(int) jpeg_consume_input JPP((j_decompress_ptr cinfo));
  160727. /* Return value is one of: */
  160728. /* #define JPEG_SUSPENDED 0 Suspended due to lack of input data */
  160729. #define JPEG_REACHED_SOS 1 /* Reached start of new scan */
  160730. #define JPEG_REACHED_EOI 2 /* Reached end of image */
  160731. #define JPEG_ROW_COMPLETED 3 /* Completed one iMCU row */
  160732. #define JPEG_SCAN_COMPLETED 4 /* Completed last iMCU row of a scan */
  160733. /* Precalculate output dimensions for current decompression parameters. */
  160734. EXTERN(void) jpeg_calc_output_dimensions JPP((j_decompress_ptr cinfo));
  160735. /* Control saving of COM and APPn markers into marker_list. */
  160736. EXTERN(void) jpeg_save_markers
  160737. JPP((j_decompress_ptr cinfo, int marker_code,
  160738. unsigned int length_limit));
  160739. /* Install a special processing method for COM or APPn markers. */
  160740. EXTERN(void) jpeg_set_marker_processor
  160741. JPP((j_decompress_ptr cinfo, int marker_code,
  160742. jpeg_marker_parser_method routine));
  160743. /* Read or write raw DCT coefficients --- useful for lossless transcoding. */
  160744. EXTERN(jvirt_barray_ptr *) jpeg_read_coefficients JPP((j_decompress_ptr cinfo));
  160745. EXTERN(void) jpeg_write_coefficients JPP((j_compress_ptr cinfo,
  160746. jvirt_barray_ptr * coef_arrays));
  160747. EXTERN(void) jpeg_copy_critical_parameters JPP((j_decompress_ptr srcinfo,
  160748. j_compress_ptr dstinfo));
  160749. /* If you choose to abort compression or decompression before completing
  160750. * jpeg_finish_(de)compress, then you need to clean up to release memory,
  160751. * temporary files, etc. You can just call jpeg_destroy_(de)compress
  160752. * if you're done with the JPEG object, but if you want to clean it up and
  160753. * reuse it, call this:
  160754. */
  160755. EXTERN(void) jpeg_abort_compress JPP((j_compress_ptr cinfo));
  160756. EXTERN(void) jpeg_abort_decompress JPP((j_decompress_ptr cinfo));
  160757. /* Generic versions of jpeg_abort and jpeg_destroy that work on either
  160758. * flavor of JPEG object. These may be more convenient in some places.
  160759. */
  160760. EXTERN(void) jpeg_abort JPP((j_common_ptr cinfo));
  160761. EXTERN(void) jpeg_destroy JPP((j_common_ptr cinfo));
  160762. /* Default restart-marker-resync procedure for use by data source modules */
  160763. EXTERN(boolean) jpeg_resync_to_restart JPP((j_decompress_ptr cinfo,
  160764. int desired));
  160765. /* These marker codes are exported since applications and data source modules
  160766. * are likely to want to use them.
  160767. */
  160768. #define JPEG_RST0 0xD0 /* RST0 marker code */
  160769. #define JPEG_EOI 0xD9 /* EOI marker code */
  160770. #define JPEG_APP0 0xE0 /* APP0 marker code */
  160771. #define JPEG_COM 0xFE /* COM marker code */
  160772. /* If we have a brain-damaged compiler that emits warnings (or worse, errors)
  160773. * for structure definitions that are never filled in, keep it quiet by
  160774. * supplying dummy definitions for the various substructures.
  160775. */
  160776. #ifdef INCOMPLETE_TYPES_BROKEN
  160777. #ifndef JPEG_INTERNALS /* will be defined in jpegint.h */
  160778. struct jvirt_sarray_control { long dummy; };
  160779. struct jvirt_barray_control { long dummy; };
  160780. struct jpeg_comp_master { long dummy; };
  160781. struct jpeg_c_main_controller { long dummy; };
  160782. struct jpeg_c_prep_controller { long dummy; };
  160783. struct jpeg_c_coef_controller { long dummy; };
  160784. struct jpeg_marker_writer { long dummy; };
  160785. struct jpeg_color_converter { long dummy; };
  160786. struct jpeg_downsampler { long dummy; };
  160787. struct jpeg_forward_dct { long dummy; };
  160788. struct jpeg_entropy_encoder { long dummy; };
  160789. struct jpeg_decomp_master { long dummy; };
  160790. struct jpeg_d_main_controller { long dummy; };
  160791. struct jpeg_d_coef_controller { long dummy; };
  160792. struct jpeg_d_post_controller { long dummy; };
  160793. struct jpeg_input_controller { long dummy; };
  160794. struct jpeg_marker_reader { long dummy; };
  160795. struct jpeg_entropy_decoder { long dummy; };
  160796. struct jpeg_inverse_dct { long dummy; };
  160797. struct jpeg_upsampler { long dummy; };
  160798. struct jpeg_color_deconverter { long dummy; };
  160799. struct jpeg_color_quantizer { long dummy; };
  160800. #endif /* JPEG_INTERNALS */
  160801. #endif /* INCOMPLETE_TYPES_BROKEN */
  160802. /*
  160803. * The JPEG library modules define JPEG_INTERNALS before including this file.
  160804. * The internal structure declarations are read only when that is true.
  160805. * Applications using the library should not include jpegint.h, but may wish
  160806. * to include jerror.h.
  160807. */
  160808. #ifdef JPEG_INTERNALS
  160809. /*** Start of inlined file: jpegint.h ***/
  160810. /* Declarations for both compression & decompression */
  160811. typedef enum { /* Operating modes for buffer controllers */
  160812. JBUF_PASS_THRU, /* Plain stripwise operation */
  160813. /* Remaining modes require a full-image buffer to have been created */
  160814. JBUF_SAVE_SOURCE, /* Run source subobject only, save output */
  160815. JBUF_CRANK_DEST, /* Run dest subobject only, using saved data */
  160816. JBUF_SAVE_AND_PASS /* Run both subobjects, save output */
  160817. } J_BUF_MODE;
  160818. /* Values of global_state field (jdapi.c has some dependencies on ordering!) */
  160819. #define CSTATE_START 100 /* after create_compress */
  160820. #define CSTATE_SCANNING 101 /* start_compress done, write_scanlines OK */
  160821. #define CSTATE_RAW_OK 102 /* start_compress done, write_raw_data OK */
  160822. #define CSTATE_WRCOEFS 103 /* jpeg_write_coefficients done */
  160823. #define DSTATE_START 200 /* after create_decompress */
  160824. #define DSTATE_INHEADER 201 /* reading header markers, no SOS yet */
  160825. #define DSTATE_READY 202 /* found SOS, ready for start_decompress */
  160826. #define DSTATE_PRELOAD 203 /* reading multiscan file in start_decompress*/
  160827. #define DSTATE_PRESCAN 204 /* performing dummy pass for 2-pass quant */
  160828. #define DSTATE_SCANNING 205 /* start_decompress done, read_scanlines OK */
  160829. #define DSTATE_RAW_OK 206 /* start_decompress done, read_raw_data OK */
  160830. #define DSTATE_BUFIMAGE 207 /* expecting jpeg_start_output */
  160831. #define DSTATE_BUFPOST 208 /* looking for SOS/EOI in jpeg_finish_output */
  160832. #define DSTATE_RDCOEFS 209 /* reading file in jpeg_read_coefficients */
  160833. #define DSTATE_STOPPING 210 /* looking for EOI in jpeg_finish_decompress */
  160834. /* Declarations for compression modules */
  160835. /* Master control module */
  160836. struct jpeg_comp_master {
  160837. JMETHOD(void, prepare_for_pass, (j_compress_ptr cinfo));
  160838. JMETHOD(void, pass_startup, (j_compress_ptr cinfo));
  160839. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  160840. /* State variables made visible to other modules */
  160841. boolean call_pass_startup; /* True if pass_startup must be called */
  160842. boolean is_last_pass; /* True during last pass */
  160843. };
  160844. /* Main buffer control (downsampled-data buffer) */
  160845. struct jpeg_c_main_controller {
  160846. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160847. JMETHOD(void, process_data, (j_compress_ptr cinfo,
  160848. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  160849. JDIMENSION in_rows_avail));
  160850. };
  160851. /* Compression preprocessing (downsampling input buffer control) */
  160852. struct jpeg_c_prep_controller {
  160853. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160854. JMETHOD(void, pre_process_data, (j_compress_ptr cinfo,
  160855. JSAMPARRAY input_buf,
  160856. JDIMENSION *in_row_ctr,
  160857. JDIMENSION in_rows_avail,
  160858. JSAMPIMAGE output_buf,
  160859. JDIMENSION *out_row_group_ctr,
  160860. JDIMENSION out_row_groups_avail));
  160861. };
  160862. /* Coefficient buffer control */
  160863. struct jpeg_c_coef_controller {
  160864. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160865. JMETHOD(boolean, compress_data, (j_compress_ptr cinfo,
  160866. JSAMPIMAGE input_buf));
  160867. };
  160868. /* Colorspace conversion */
  160869. struct jpeg_color_converter {
  160870. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  160871. JMETHOD(void, color_convert, (j_compress_ptr cinfo,
  160872. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  160873. JDIMENSION output_row, int num_rows));
  160874. };
  160875. /* Downsampling */
  160876. struct jpeg_downsampler {
  160877. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  160878. JMETHOD(void, downsample, (j_compress_ptr cinfo,
  160879. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  160880. JSAMPIMAGE output_buf,
  160881. JDIMENSION out_row_group_index));
  160882. boolean need_context_rows; /* TRUE if need rows above & below */
  160883. };
  160884. /* Forward DCT (also controls coefficient quantization) */
  160885. struct jpeg_forward_dct {
  160886. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  160887. /* perhaps this should be an array??? */
  160888. JMETHOD(void, forward_DCT, (j_compress_ptr cinfo,
  160889. jpeg_component_info * compptr,
  160890. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  160891. JDIMENSION start_row, JDIMENSION start_col,
  160892. JDIMENSION num_blocks));
  160893. };
  160894. /* Entropy encoding */
  160895. struct jpeg_entropy_encoder {
  160896. JMETHOD(void, start_pass, (j_compress_ptr cinfo, boolean gather_statistics));
  160897. JMETHOD(boolean, encode_mcu, (j_compress_ptr cinfo, JBLOCKROW *MCU_data));
  160898. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  160899. };
  160900. /* Marker writing */
  160901. struct jpeg_marker_writer {
  160902. JMETHOD(void, write_file_header, (j_compress_ptr cinfo));
  160903. JMETHOD(void, write_frame_header, (j_compress_ptr cinfo));
  160904. JMETHOD(void, write_scan_header, (j_compress_ptr cinfo));
  160905. JMETHOD(void, write_file_trailer, (j_compress_ptr cinfo));
  160906. JMETHOD(void, write_tables_only, (j_compress_ptr cinfo));
  160907. /* These routines are exported to allow insertion of extra markers */
  160908. /* Probably only COM and APPn markers should be written this way */
  160909. JMETHOD(void, write_marker_header, (j_compress_ptr cinfo, int marker,
  160910. unsigned int datalen));
  160911. JMETHOD(void, write_marker_byte, (j_compress_ptr cinfo, int val));
  160912. };
  160913. /* Declarations for decompression modules */
  160914. /* Master control module */
  160915. struct jpeg_decomp_master {
  160916. JMETHOD(void, prepare_for_output_pass, (j_decompress_ptr cinfo));
  160917. JMETHOD(void, finish_output_pass, (j_decompress_ptr cinfo));
  160918. /* State variables made visible to other modules */
  160919. boolean is_dummy_pass; /* True during 1st pass for 2-pass quant */
  160920. };
  160921. /* Input control module */
  160922. struct jpeg_input_controller {
  160923. JMETHOD(int, consume_input, (j_decompress_ptr cinfo));
  160924. JMETHOD(void, reset_input_controller, (j_decompress_ptr cinfo));
  160925. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  160926. JMETHOD(void, finish_input_pass, (j_decompress_ptr cinfo));
  160927. /* State variables made visible to other modules */
  160928. boolean has_multiple_scans; /* True if file has multiple scans */
  160929. boolean eoi_reached; /* True when EOI has been consumed */
  160930. };
  160931. /* Main buffer control (downsampled-data buffer) */
  160932. struct jpeg_d_main_controller {
  160933. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  160934. JMETHOD(void, process_data, (j_decompress_ptr cinfo,
  160935. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  160936. JDIMENSION out_rows_avail));
  160937. };
  160938. /* Coefficient buffer control */
  160939. struct jpeg_d_coef_controller {
  160940. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  160941. JMETHOD(int, consume_data, (j_decompress_ptr cinfo));
  160942. JMETHOD(void, start_output_pass, (j_decompress_ptr cinfo));
  160943. JMETHOD(int, decompress_data, (j_decompress_ptr cinfo,
  160944. JSAMPIMAGE output_buf));
  160945. /* Pointer to array of coefficient virtual arrays, or NULL if none */
  160946. jvirt_barray_ptr *coef_arrays;
  160947. };
  160948. /* Decompression postprocessing (color quantization buffer control) */
  160949. struct jpeg_d_post_controller {
  160950. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  160951. JMETHOD(void, post_process_data, (j_decompress_ptr cinfo,
  160952. JSAMPIMAGE input_buf,
  160953. JDIMENSION *in_row_group_ctr,
  160954. JDIMENSION in_row_groups_avail,
  160955. JSAMPARRAY output_buf,
  160956. JDIMENSION *out_row_ctr,
  160957. JDIMENSION out_rows_avail));
  160958. };
  160959. /* Marker reading & parsing */
  160960. struct jpeg_marker_reader {
  160961. JMETHOD(void, reset_marker_reader, (j_decompress_ptr cinfo));
  160962. /* Read markers until SOS or EOI.
  160963. * Returns same codes as are defined for jpeg_consume_input:
  160964. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  160965. */
  160966. JMETHOD(int, read_markers, (j_decompress_ptr cinfo));
  160967. /* Read a restart marker --- exported for use by entropy decoder only */
  160968. jpeg_marker_parser_method read_restart_marker;
  160969. /* State of marker reader --- nominally internal, but applications
  160970. * supplying COM or APPn handlers might like to know the state.
  160971. */
  160972. boolean saw_SOI; /* found SOI? */
  160973. boolean saw_SOF; /* found SOF? */
  160974. int next_restart_num; /* next restart number expected (0-7) */
  160975. unsigned int discarded_bytes; /* # of bytes skipped looking for a marker */
  160976. };
  160977. /* Entropy decoding */
  160978. struct jpeg_entropy_decoder {
  160979. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160980. JMETHOD(boolean, decode_mcu, (j_decompress_ptr cinfo,
  160981. JBLOCKROW *MCU_data));
  160982. /* This is here to share code between baseline and progressive decoders; */
  160983. /* other modules probably should not use it */
  160984. boolean insufficient_data; /* set TRUE after emitting warning */
  160985. };
  160986. /* Inverse DCT (also performs dequantization) */
  160987. typedef JMETHOD(void, inverse_DCT_method_ptr,
  160988. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  160989. JCOEFPTR coef_block,
  160990. JSAMPARRAY output_buf, JDIMENSION output_col));
  160991. struct jpeg_inverse_dct {
  160992. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160993. /* It is useful to allow each component to have a separate IDCT method. */
  160994. inverse_DCT_method_ptr inverse_DCT[MAX_COMPONENTS];
  160995. };
  160996. /* Upsampling (note that upsampler must also call color converter) */
  160997. struct jpeg_upsampler {
  160998. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160999. JMETHOD(void, upsample, (j_decompress_ptr cinfo,
  161000. JSAMPIMAGE input_buf,
  161001. JDIMENSION *in_row_group_ctr,
  161002. JDIMENSION in_row_groups_avail,
  161003. JSAMPARRAY output_buf,
  161004. JDIMENSION *out_row_ctr,
  161005. JDIMENSION out_rows_avail));
  161006. boolean need_context_rows; /* TRUE if need rows above & below */
  161007. };
  161008. /* Colorspace conversion */
  161009. struct jpeg_color_deconverter {
  161010. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  161011. JMETHOD(void, color_convert, (j_decompress_ptr cinfo,
  161012. JSAMPIMAGE input_buf, JDIMENSION input_row,
  161013. JSAMPARRAY output_buf, int num_rows));
  161014. };
  161015. /* Color quantization or color precision reduction */
  161016. struct jpeg_color_quantizer {
  161017. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, boolean is_pre_scan));
  161018. JMETHOD(void, color_quantize, (j_decompress_ptr cinfo,
  161019. JSAMPARRAY input_buf, JSAMPARRAY output_buf,
  161020. int num_rows));
  161021. JMETHOD(void, finish_pass, (j_decompress_ptr cinfo));
  161022. JMETHOD(void, new_color_map, (j_decompress_ptr cinfo));
  161023. };
  161024. /* Miscellaneous useful macros */
  161025. #undef MAX
  161026. #define MAX(a,b) ((a) > (b) ? (a) : (b))
  161027. #undef MIN
  161028. #define MIN(a,b) ((a) < (b) ? (a) : (b))
  161029. /* We assume that right shift corresponds to signed division by 2 with
  161030. * rounding towards minus infinity. This is correct for typical "arithmetic
  161031. * shift" instructions that shift in copies of the sign bit. But some
  161032. * C compilers implement >> with an unsigned shift. For these machines you
  161033. * must define RIGHT_SHIFT_IS_UNSIGNED.
  161034. * RIGHT_SHIFT provides a proper signed right shift of an INT32 quantity.
  161035. * It is only applied with constant shift counts. SHIFT_TEMPS must be
  161036. * included in the variables of any routine using RIGHT_SHIFT.
  161037. */
  161038. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  161039. #define SHIFT_TEMPS INT32 shift_temp;
  161040. #define RIGHT_SHIFT(x,shft) \
  161041. ((shift_temp = (x)) < 0 ? \
  161042. (shift_temp >> (shft)) | ((~((INT32) 0)) << (32-(shft))) : \
  161043. (shift_temp >> (shft)))
  161044. #else
  161045. #define SHIFT_TEMPS
  161046. #define RIGHT_SHIFT(x,shft) ((x) >> (shft))
  161047. #endif
  161048. /* Short forms of external names for systems with brain-damaged linkers. */
  161049. #ifdef NEED_SHORT_EXTERNAL_NAMES
  161050. #define jinit_compress_master jICompress
  161051. #define jinit_c_master_control jICMaster
  161052. #define jinit_c_main_controller jICMainC
  161053. #define jinit_c_prep_controller jICPrepC
  161054. #define jinit_c_coef_controller jICCoefC
  161055. #define jinit_color_converter jICColor
  161056. #define jinit_downsampler jIDownsampler
  161057. #define jinit_forward_dct jIFDCT
  161058. #define jinit_huff_encoder jIHEncoder
  161059. #define jinit_phuff_encoder jIPHEncoder
  161060. #define jinit_marker_writer jIMWriter
  161061. #define jinit_master_decompress jIDMaster
  161062. #define jinit_d_main_controller jIDMainC
  161063. #define jinit_d_coef_controller jIDCoefC
  161064. #define jinit_d_post_controller jIDPostC
  161065. #define jinit_input_controller jIInCtlr
  161066. #define jinit_marker_reader jIMReader
  161067. #define jinit_huff_decoder jIHDecoder
  161068. #define jinit_phuff_decoder jIPHDecoder
  161069. #define jinit_inverse_dct jIIDCT
  161070. #define jinit_upsampler jIUpsampler
  161071. #define jinit_color_deconverter jIDColor
  161072. #define jinit_1pass_quantizer jI1Quant
  161073. #define jinit_2pass_quantizer jI2Quant
  161074. #define jinit_merged_upsampler jIMUpsampler
  161075. #define jinit_memory_mgr jIMemMgr
  161076. #define jdiv_round_up jDivRound
  161077. #define jround_up jRound
  161078. #define jcopy_sample_rows jCopySamples
  161079. #define jcopy_block_row jCopyBlocks
  161080. #define jzero_far jZeroFar
  161081. #define jpeg_zigzag_order jZIGTable
  161082. #define jpeg_natural_order jZAGTable
  161083. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  161084. /* Compression module initialization routines */
  161085. EXTERN(void) jinit_compress_master JPP((j_compress_ptr cinfo));
  161086. EXTERN(void) jinit_c_master_control JPP((j_compress_ptr cinfo,
  161087. boolean transcode_only));
  161088. EXTERN(void) jinit_c_main_controller JPP((j_compress_ptr cinfo,
  161089. boolean need_full_buffer));
  161090. EXTERN(void) jinit_c_prep_controller JPP((j_compress_ptr cinfo,
  161091. boolean need_full_buffer));
  161092. EXTERN(void) jinit_c_coef_controller JPP((j_compress_ptr cinfo,
  161093. boolean need_full_buffer));
  161094. EXTERN(void) jinit_color_converter JPP((j_compress_ptr cinfo));
  161095. EXTERN(void) jinit_downsampler JPP((j_compress_ptr cinfo));
  161096. EXTERN(void) jinit_forward_dct JPP((j_compress_ptr cinfo));
  161097. EXTERN(void) jinit_huff_encoder JPP((j_compress_ptr cinfo));
  161098. EXTERN(void) jinit_phuff_encoder JPP((j_compress_ptr cinfo));
  161099. EXTERN(void) jinit_marker_writer JPP((j_compress_ptr cinfo));
  161100. /* Decompression module initialization routines */
  161101. EXTERN(void) jinit_master_decompress JPP((j_decompress_ptr cinfo));
  161102. EXTERN(void) jinit_d_main_controller JPP((j_decompress_ptr cinfo,
  161103. boolean need_full_buffer));
  161104. EXTERN(void) jinit_d_coef_controller JPP((j_decompress_ptr cinfo,
  161105. boolean need_full_buffer));
  161106. EXTERN(void) jinit_d_post_controller JPP((j_decompress_ptr cinfo,
  161107. boolean need_full_buffer));
  161108. EXTERN(void) jinit_input_controller JPP((j_decompress_ptr cinfo));
  161109. EXTERN(void) jinit_marker_reader JPP((j_decompress_ptr cinfo));
  161110. EXTERN(void) jinit_huff_decoder JPP((j_decompress_ptr cinfo));
  161111. EXTERN(void) jinit_phuff_decoder JPP((j_decompress_ptr cinfo));
  161112. EXTERN(void) jinit_inverse_dct JPP((j_decompress_ptr cinfo));
  161113. EXTERN(void) jinit_upsampler JPP((j_decompress_ptr cinfo));
  161114. EXTERN(void) jinit_color_deconverter JPP((j_decompress_ptr cinfo));
  161115. EXTERN(void) jinit_1pass_quantizer JPP((j_decompress_ptr cinfo));
  161116. EXTERN(void) jinit_2pass_quantizer JPP((j_decompress_ptr cinfo));
  161117. EXTERN(void) jinit_merged_upsampler JPP((j_decompress_ptr cinfo));
  161118. /* Memory manager initialization */
  161119. EXTERN(void) jinit_memory_mgr JPP((j_common_ptr cinfo));
  161120. /* Utility routines in jutils.c */
  161121. EXTERN(long) jdiv_round_up JPP((long a, long b));
  161122. EXTERN(long) jround_up JPP((long a, long b));
  161123. EXTERN(void) jcopy_sample_rows JPP((JSAMPARRAY input_array, int source_row,
  161124. JSAMPARRAY output_array, int dest_row,
  161125. int num_rows, JDIMENSION num_cols));
  161126. EXTERN(void) jcopy_block_row JPP((JBLOCKROW input_row, JBLOCKROW output_row,
  161127. JDIMENSION num_blocks));
  161128. EXTERN(void) jzero_far JPP((void FAR * target, size_t bytestozero));
  161129. /* Constant tables in jutils.c */
  161130. #if 0 /* This table is not actually needed in v6a */
  161131. extern const int jpeg_zigzag_order[]; /* natural coef order to zigzag order */
  161132. #endif
  161133. extern const int jpeg_natural_order[]; /* zigzag coef order to natural order */
  161134. /* Suppress undefined-structure complaints if necessary. */
  161135. #ifdef INCOMPLETE_TYPES_BROKEN
  161136. #ifndef AM_MEMORY_MANAGER /* only jmemmgr.c defines these */
  161137. struct jvirt_sarray_control { long dummy; };
  161138. struct jvirt_barray_control { long dummy; };
  161139. #endif
  161140. #endif /* INCOMPLETE_TYPES_BROKEN */
  161141. /*** End of inlined file: jpegint.h ***/
  161142. /* fetch private declarations */
  161143. /*** Start of inlined file: jerror.h ***/
  161144. /*
  161145. * To define the enum list of message codes, include this file without
  161146. * defining macro JMESSAGE. To create a message string table, include it
  161147. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  161148. */
  161149. #ifndef JMESSAGE
  161150. #ifndef JERROR_H
  161151. /* First time through, define the enum list */
  161152. #define JMAKE_ENUM_LIST
  161153. #else
  161154. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  161155. #define JMESSAGE(code,string)
  161156. #endif /* JERROR_H */
  161157. #endif /* JMESSAGE */
  161158. #ifdef JMAKE_ENUM_LIST
  161159. typedef enum {
  161160. #define JMESSAGE(code,string) code ,
  161161. #endif /* JMAKE_ENUM_LIST */
  161162. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  161163. /* For maintenance convenience, list is alphabetical by message code name */
  161164. JMESSAGE(JERR_ARITH_NOTIMPL,
  161165. "Sorry, there are legal restrictions on arithmetic coding")
  161166. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  161167. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  161168. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  161169. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  161170. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  161171. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  161172. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  161173. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  161174. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  161175. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  161176. JMESSAGE(JERR_BAD_LIB_VERSION,
  161177. "Wrong JPEG library version: library is %d, caller expects %d")
  161178. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  161179. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  161180. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  161181. JMESSAGE(JERR_BAD_PROGRESSION,
  161182. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  161183. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  161184. "Invalid progressive parameters at scan script entry %d")
  161185. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  161186. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  161187. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  161188. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  161189. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  161190. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  161191. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  161192. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  161193. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  161194. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  161195. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  161196. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  161197. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  161198. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  161199. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  161200. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  161201. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  161202. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  161203. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  161204. JMESSAGE(JERR_FILE_READ, "Input file read error")
  161205. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  161206. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  161207. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  161208. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  161209. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  161210. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  161211. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  161212. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  161213. "Cannot transcode due to multiple use of quantization table %d")
  161214. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  161215. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  161216. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  161217. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  161218. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  161219. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  161220. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  161221. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  161222. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  161223. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  161224. JMESSAGE(JERR_QUANT_COMPONENTS,
  161225. "Cannot quantize more than %d color components")
  161226. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  161227. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  161228. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  161229. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  161230. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  161231. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  161232. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  161233. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  161234. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  161235. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  161236. JMESSAGE(JERR_TFILE_WRITE,
  161237. "Write failed on temporary file --- out of disk space?")
  161238. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  161239. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  161240. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  161241. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  161242. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  161243. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  161244. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  161245. JMESSAGE(JMSG_VERSION, JVERSION)
  161246. JMESSAGE(JTRC_16BIT_TABLES,
  161247. "Caution: quantization tables are too coarse for baseline JPEG")
  161248. JMESSAGE(JTRC_ADOBE,
  161249. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  161250. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  161251. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  161252. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  161253. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  161254. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  161255. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  161256. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  161257. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  161258. JMESSAGE(JTRC_EOI, "End Of Image")
  161259. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  161260. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  161261. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  161262. "Warning: thumbnail image size does not match data length %u")
  161263. JMESSAGE(JTRC_JFIF_EXTENSION,
  161264. "JFIF extension marker: type 0x%02x, length %u")
  161265. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  161266. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  161267. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  161268. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  161269. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  161270. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  161271. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  161272. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  161273. JMESSAGE(JTRC_RST, "RST%d")
  161274. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  161275. "Smoothing not supported with nonstandard sampling ratios")
  161276. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  161277. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  161278. JMESSAGE(JTRC_SOI, "Start of Image")
  161279. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  161280. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  161281. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  161282. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  161283. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  161284. JMESSAGE(JTRC_THUMB_JPEG,
  161285. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  161286. JMESSAGE(JTRC_THUMB_PALETTE,
  161287. "JFIF extension marker: palette thumbnail image, length %u")
  161288. JMESSAGE(JTRC_THUMB_RGB,
  161289. "JFIF extension marker: RGB thumbnail image, length %u")
  161290. JMESSAGE(JTRC_UNKNOWN_IDS,
  161291. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  161292. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  161293. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  161294. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  161295. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  161296. "Inconsistent progression sequence for component %d coefficient %d")
  161297. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  161298. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  161299. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  161300. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  161301. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  161302. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  161303. JMESSAGE(JWRN_MUST_RESYNC,
  161304. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  161305. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  161306. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  161307. #ifdef JMAKE_ENUM_LIST
  161308. JMSG_LASTMSGCODE
  161309. } J_MESSAGE_CODE;
  161310. #undef JMAKE_ENUM_LIST
  161311. #endif /* JMAKE_ENUM_LIST */
  161312. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  161313. #undef JMESSAGE
  161314. #ifndef JERROR_H
  161315. #define JERROR_H
  161316. /* Macros to simplify using the error and trace message stuff */
  161317. /* The first parameter is either type of cinfo pointer */
  161318. /* Fatal errors (print message and exit) */
  161319. #define ERREXIT(cinfo,code) \
  161320. ((cinfo)->err->msg_code = (code), \
  161321. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161322. #define ERREXIT1(cinfo,code,p1) \
  161323. ((cinfo)->err->msg_code = (code), \
  161324. (cinfo)->err->msg_parm.i[0] = (p1), \
  161325. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161326. #define ERREXIT2(cinfo,code,p1,p2) \
  161327. ((cinfo)->err->msg_code = (code), \
  161328. (cinfo)->err->msg_parm.i[0] = (p1), \
  161329. (cinfo)->err->msg_parm.i[1] = (p2), \
  161330. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161331. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  161332. ((cinfo)->err->msg_code = (code), \
  161333. (cinfo)->err->msg_parm.i[0] = (p1), \
  161334. (cinfo)->err->msg_parm.i[1] = (p2), \
  161335. (cinfo)->err->msg_parm.i[2] = (p3), \
  161336. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161337. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  161338. ((cinfo)->err->msg_code = (code), \
  161339. (cinfo)->err->msg_parm.i[0] = (p1), \
  161340. (cinfo)->err->msg_parm.i[1] = (p2), \
  161341. (cinfo)->err->msg_parm.i[2] = (p3), \
  161342. (cinfo)->err->msg_parm.i[3] = (p4), \
  161343. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161344. #define ERREXITS(cinfo,code,str) \
  161345. ((cinfo)->err->msg_code = (code), \
  161346. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  161347. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161348. #define MAKESTMT(stuff) do { stuff } while (0)
  161349. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  161350. #define WARNMS(cinfo,code) \
  161351. ((cinfo)->err->msg_code = (code), \
  161352. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161353. #define WARNMS1(cinfo,code,p1) \
  161354. ((cinfo)->err->msg_code = (code), \
  161355. (cinfo)->err->msg_parm.i[0] = (p1), \
  161356. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161357. #define WARNMS2(cinfo,code,p1,p2) \
  161358. ((cinfo)->err->msg_code = (code), \
  161359. (cinfo)->err->msg_parm.i[0] = (p1), \
  161360. (cinfo)->err->msg_parm.i[1] = (p2), \
  161361. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161362. /* Informational/debugging messages */
  161363. #define TRACEMS(cinfo,lvl,code) \
  161364. ((cinfo)->err->msg_code = (code), \
  161365. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161366. #define TRACEMS1(cinfo,lvl,code,p1) \
  161367. ((cinfo)->err->msg_code = (code), \
  161368. (cinfo)->err->msg_parm.i[0] = (p1), \
  161369. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161370. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  161371. ((cinfo)->err->msg_code = (code), \
  161372. (cinfo)->err->msg_parm.i[0] = (p1), \
  161373. (cinfo)->err->msg_parm.i[1] = (p2), \
  161374. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161375. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  161376. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161377. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  161378. (cinfo)->err->msg_code = (code); \
  161379. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161380. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  161381. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161382. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161383. (cinfo)->err->msg_code = (code); \
  161384. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161385. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  161386. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161387. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161388. _mp[4] = (p5); \
  161389. (cinfo)->err->msg_code = (code); \
  161390. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161391. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  161392. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161393. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161394. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  161395. (cinfo)->err->msg_code = (code); \
  161396. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161397. #define TRACEMSS(cinfo,lvl,code,str) \
  161398. ((cinfo)->err->msg_code = (code), \
  161399. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  161400. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161401. #endif /* JERROR_H */
  161402. /*** End of inlined file: jerror.h ***/
  161403. /* fetch error codes too */
  161404. #endif
  161405. #endif /* JPEGLIB_H */
  161406. /*** End of inlined file: jpeglib.h ***/
  161407. /*** Start of inlined file: jcapimin.c ***/
  161408. #define JPEG_INTERNALS
  161409. /*** Start of inlined file: jinclude.h ***/
  161410. /* Include auto-config file to find out which system include files we need. */
  161411. #ifndef __jinclude_h__
  161412. #define __jinclude_h__
  161413. /*** Start of inlined file: jconfig.h ***/
  161414. /* see jconfig.doc for explanations */
  161415. // disable all the warnings under MSVC
  161416. #ifdef _MSC_VER
  161417. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  161418. #endif
  161419. #ifdef __BORLANDC__
  161420. #pragma warn -8057
  161421. #pragma warn -8019
  161422. #pragma warn -8004
  161423. #pragma warn -8008
  161424. #endif
  161425. #define HAVE_PROTOTYPES
  161426. #define HAVE_UNSIGNED_CHAR
  161427. #define HAVE_UNSIGNED_SHORT
  161428. /* #define void char */
  161429. /* #define const */
  161430. #undef CHAR_IS_UNSIGNED
  161431. #define HAVE_STDDEF_H
  161432. #define HAVE_STDLIB_H
  161433. #undef NEED_BSD_STRINGS
  161434. #undef NEED_SYS_TYPES_H
  161435. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  161436. #undef NEED_SHORT_EXTERNAL_NAMES
  161437. #undef INCOMPLETE_TYPES_BROKEN
  161438. /* Define "boolean" as unsigned char, not int, per Windows custom */
  161439. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  161440. typedef unsigned char boolean;
  161441. #endif
  161442. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  161443. #ifdef JPEG_INTERNALS
  161444. #undef RIGHT_SHIFT_IS_UNSIGNED
  161445. #endif /* JPEG_INTERNALS */
  161446. #ifdef JPEG_CJPEG_DJPEG
  161447. #define BMP_SUPPORTED /* BMP image file format */
  161448. #define GIF_SUPPORTED /* GIF image file format */
  161449. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  161450. #undef RLE_SUPPORTED /* Utah RLE image file format */
  161451. #define TARGA_SUPPORTED /* Targa image file format */
  161452. #define TWO_FILE_COMMANDLINE /* optional */
  161453. #define USE_SETMODE /* Microsoft has setmode() */
  161454. #undef NEED_SIGNAL_CATCHER
  161455. #undef DONT_USE_B_MODE
  161456. #undef PROGRESS_REPORT /* optional */
  161457. #endif /* JPEG_CJPEG_DJPEG */
  161458. /*** End of inlined file: jconfig.h ***/
  161459. /* auto configuration options */
  161460. #define JCONFIG_INCLUDED /* so that jpeglib.h doesn't do it again */
  161461. /*
  161462. * We need the NULL macro and size_t typedef.
  161463. * On an ANSI-conforming system it is sufficient to include <stddef.h>.
  161464. * Otherwise, we get them from <stdlib.h> or <stdio.h>; we may have to
  161465. * pull in <sys/types.h> as well.
  161466. * Note that the core JPEG library does not require <stdio.h>;
  161467. * only the default error handler and data source/destination modules do.
  161468. * But we must pull it in because of the references to FILE in jpeglib.h.
  161469. * You can remove those references if you want to compile without <stdio.h>.
  161470. */
  161471. #ifdef HAVE_STDDEF_H
  161472. #include <stddef.h>
  161473. #endif
  161474. #ifdef HAVE_STDLIB_H
  161475. #include <stdlib.h>
  161476. #endif
  161477. #ifdef NEED_SYS_TYPES_H
  161478. #include <sys/types.h>
  161479. #endif
  161480. #include <stdio.h>
  161481. /*
  161482. * We need memory copying and zeroing functions, plus strncpy().
  161483. * ANSI and System V implementations declare these in <string.h>.
  161484. * BSD doesn't have the mem() functions, but it does have bcopy()/bzero().
  161485. * Some systems may declare memset and memcpy in <memory.h>.
  161486. *
  161487. * NOTE: we assume the size parameters to these functions are of type size_t.
  161488. * Change the casts in these macros if not!
  161489. */
  161490. #ifdef NEED_BSD_STRINGS
  161491. #include <strings.h>
  161492. #define MEMZERO(target,size) bzero((void *)(target), (size_t)(size))
  161493. #define MEMCOPY(dest,src,size) bcopy((const void *)(src), (void *)(dest), (size_t)(size))
  161494. #else /* not BSD, assume ANSI/SysV string lib */
  161495. #include <string.h>
  161496. #define MEMZERO(target,size) memset((void *)(target), 0, (size_t)(size))
  161497. #define MEMCOPY(dest,src,size) memcpy((void *)(dest), (const void *)(src), (size_t)(size))
  161498. #endif
  161499. /*
  161500. * In ANSI C, and indeed any rational implementation, size_t is also the
  161501. * type returned by sizeof(). However, it seems there are some irrational
  161502. * implementations out there, in which sizeof() returns an int even though
  161503. * size_t is defined as long or unsigned long. To ensure consistent results
  161504. * we always use this SIZEOF() macro in place of using sizeof() directly.
  161505. */
  161506. #define SIZEOF(object) ((size_t) sizeof(object))
  161507. /*
  161508. * The modules that use fread() and fwrite() always invoke them through
  161509. * these macros. On some systems you may need to twiddle the argument casts.
  161510. * CAUTION: argument order is different from underlying functions!
  161511. */
  161512. #define JFREAD(file,buf,sizeofbuf) \
  161513. ((size_t) fread((void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  161514. #define JFWRITE(file,buf,sizeofbuf) \
  161515. ((size_t) fwrite((const void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  161516. typedef enum { /* JPEG marker codes */
  161517. M_SOF0 = 0xc0,
  161518. M_SOF1 = 0xc1,
  161519. M_SOF2 = 0xc2,
  161520. M_SOF3 = 0xc3,
  161521. M_SOF5 = 0xc5,
  161522. M_SOF6 = 0xc6,
  161523. M_SOF7 = 0xc7,
  161524. M_JPG = 0xc8,
  161525. M_SOF9 = 0xc9,
  161526. M_SOF10 = 0xca,
  161527. M_SOF11 = 0xcb,
  161528. M_SOF13 = 0xcd,
  161529. M_SOF14 = 0xce,
  161530. M_SOF15 = 0xcf,
  161531. M_DHT = 0xc4,
  161532. M_DAC = 0xcc,
  161533. M_RST0 = 0xd0,
  161534. M_RST1 = 0xd1,
  161535. M_RST2 = 0xd2,
  161536. M_RST3 = 0xd3,
  161537. M_RST4 = 0xd4,
  161538. M_RST5 = 0xd5,
  161539. M_RST6 = 0xd6,
  161540. M_RST7 = 0xd7,
  161541. M_SOI = 0xd8,
  161542. M_EOI = 0xd9,
  161543. M_SOS = 0xda,
  161544. M_DQT = 0xdb,
  161545. M_DNL = 0xdc,
  161546. M_DRI = 0xdd,
  161547. M_DHP = 0xde,
  161548. M_EXP = 0xdf,
  161549. M_APP0 = 0xe0,
  161550. M_APP1 = 0xe1,
  161551. M_APP2 = 0xe2,
  161552. M_APP3 = 0xe3,
  161553. M_APP4 = 0xe4,
  161554. M_APP5 = 0xe5,
  161555. M_APP6 = 0xe6,
  161556. M_APP7 = 0xe7,
  161557. M_APP8 = 0xe8,
  161558. M_APP9 = 0xe9,
  161559. M_APP10 = 0xea,
  161560. M_APP11 = 0xeb,
  161561. M_APP12 = 0xec,
  161562. M_APP13 = 0xed,
  161563. M_APP14 = 0xee,
  161564. M_APP15 = 0xef,
  161565. M_JPG0 = 0xf0,
  161566. M_JPG13 = 0xfd,
  161567. M_COM = 0xfe,
  161568. M_TEM = 0x01,
  161569. M_ERROR = 0x100
  161570. } JPEG_MARKER;
  161571. /*
  161572. * Figure F.12: extend sign bit.
  161573. * On some machines, a shift and add will be faster than a table lookup.
  161574. */
  161575. #ifdef AVOID_TABLES
  161576. #define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
  161577. #else
  161578. #define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
  161579. static const int extend_test[16] = /* entry n is 2**(n-1) */
  161580. { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
  161581. 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
  161582. static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
  161583. { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
  161584. ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
  161585. ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
  161586. ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
  161587. #endif /* AVOID_TABLES */
  161588. #endif
  161589. /*** End of inlined file: jinclude.h ***/
  161590. /*
  161591. * Initialization of a JPEG compression object.
  161592. * The error manager must already be set up (in case memory manager fails).
  161593. */
  161594. GLOBAL(void)
  161595. jpeg_CreateCompress (j_compress_ptr cinfo, int version, size_t structsize)
  161596. {
  161597. int i;
  161598. /* Guard against version mismatches between library and caller. */
  161599. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  161600. if (version != JPEG_LIB_VERSION)
  161601. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  161602. if (structsize != SIZEOF(struct jpeg_compress_struct))
  161603. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  161604. (int) SIZEOF(struct jpeg_compress_struct), (int) structsize);
  161605. /* For debugging purposes, we zero the whole master structure.
  161606. * But the application has already set the err pointer, and may have set
  161607. * client_data, so we have to save and restore those fields.
  161608. * Note: if application hasn't set client_data, tools like Purify may
  161609. * complain here.
  161610. */
  161611. {
  161612. struct jpeg_error_mgr * err = cinfo->err;
  161613. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  161614. MEMZERO(cinfo, SIZEOF(struct jpeg_compress_struct));
  161615. cinfo->err = err;
  161616. cinfo->client_data = client_data;
  161617. }
  161618. cinfo->is_decompressor = FALSE;
  161619. /* Initialize a memory manager instance for this object */
  161620. jinit_memory_mgr((j_common_ptr) cinfo);
  161621. /* Zero out pointers to permanent structures. */
  161622. cinfo->progress = NULL;
  161623. cinfo->dest = NULL;
  161624. cinfo->comp_info = NULL;
  161625. for (i = 0; i < NUM_QUANT_TBLS; i++)
  161626. cinfo->quant_tbl_ptrs[i] = NULL;
  161627. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161628. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  161629. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  161630. }
  161631. cinfo->script_space = NULL;
  161632. cinfo->input_gamma = 1.0; /* in case application forgets */
  161633. /* OK, I'm ready */
  161634. cinfo->global_state = CSTATE_START;
  161635. }
  161636. /*
  161637. * Destruction of a JPEG compression object
  161638. */
  161639. GLOBAL(void)
  161640. jpeg_destroy_compress (j_compress_ptr cinfo)
  161641. {
  161642. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  161643. }
  161644. /*
  161645. * Abort processing of a JPEG compression operation,
  161646. * but don't destroy the object itself.
  161647. */
  161648. GLOBAL(void)
  161649. jpeg_abort_compress (j_compress_ptr cinfo)
  161650. {
  161651. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  161652. }
  161653. /*
  161654. * Forcibly suppress or un-suppress all quantization and Huffman tables.
  161655. * Marks all currently defined tables as already written (if suppress)
  161656. * or not written (if !suppress). This will control whether they get emitted
  161657. * by a subsequent jpeg_start_compress call.
  161658. *
  161659. * This routine is exported for use by applications that want to produce
  161660. * abbreviated JPEG datastreams. It logically belongs in jcparam.c, but
  161661. * since it is called by jpeg_start_compress, we put it here --- otherwise
  161662. * jcparam.o would be linked whether the application used it or not.
  161663. */
  161664. GLOBAL(void)
  161665. jpeg_suppress_tables (j_compress_ptr cinfo, boolean suppress)
  161666. {
  161667. int i;
  161668. JQUANT_TBL * qtbl;
  161669. JHUFF_TBL * htbl;
  161670. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  161671. if ((qtbl = cinfo->quant_tbl_ptrs[i]) != NULL)
  161672. qtbl->sent_table = suppress;
  161673. }
  161674. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161675. if ((htbl = cinfo->dc_huff_tbl_ptrs[i]) != NULL)
  161676. htbl->sent_table = suppress;
  161677. if ((htbl = cinfo->ac_huff_tbl_ptrs[i]) != NULL)
  161678. htbl->sent_table = suppress;
  161679. }
  161680. }
  161681. /*
  161682. * Finish JPEG compression.
  161683. *
  161684. * If a multipass operating mode was selected, this may do a great deal of
  161685. * work including most of the actual output.
  161686. */
  161687. GLOBAL(void)
  161688. jpeg_finish_compress (j_compress_ptr cinfo)
  161689. {
  161690. JDIMENSION iMCU_row;
  161691. if (cinfo->global_state == CSTATE_SCANNING ||
  161692. cinfo->global_state == CSTATE_RAW_OK) {
  161693. /* Terminate first pass */
  161694. if (cinfo->next_scanline < cinfo->image_height)
  161695. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  161696. (*cinfo->master->finish_pass) (cinfo);
  161697. } else if (cinfo->global_state != CSTATE_WRCOEFS)
  161698. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161699. /* Perform any remaining passes */
  161700. while (! cinfo->master->is_last_pass) {
  161701. (*cinfo->master->prepare_for_pass) (cinfo);
  161702. for (iMCU_row = 0; iMCU_row < cinfo->total_iMCU_rows; iMCU_row++) {
  161703. if (cinfo->progress != NULL) {
  161704. cinfo->progress->pass_counter = (long) iMCU_row;
  161705. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows;
  161706. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161707. }
  161708. /* We bypass the main controller and invoke coef controller directly;
  161709. * all work is being done from the coefficient buffer.
  161710. */
  161711. if (! (*cinfo->coef->compress_data) (cinfo, (JSAMPIMAGE) NULL))
  161712. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  161713. }
  161714. (*cinfo->master->finish_pass) (cinfo);
  161715. }
  161716. /* Write EOI, do final cleanup */
  161717. (*cinfo->marker->write_file_trailer) (cinfo);
  161718. (*cinfo->dest->term_destination) (cinfo);
  161719. /* We can use jpeg_abort to release memory and reset global_state */
  161720. jpeg_abort((j_common_ptr) cinfo);
  161721. }
  161722. /*
  161723. * Write a special marker.
  161724. * This is only recommended for writing COM or APPn markers.
  161725. * Must be called after jpeg_start_compress() and before
  161726. * first call to jpeg_write_scanlines() or jpeg_write_raw_data().
  161727. */
  161728. GLOBAL(void)
  161729. jpeg_write_marker (j_compress_ptr cinfo, int marker,
  161730. const JOCTET *dataptr, unsigned int datalen)
  161731. {
  161732. JMETHOD(void, write_marker_byte, (j_compress_ptr info, int val));
  161733. if (cinfo->next_scanline != 0 ||
  161734. (cinfo->global_state != CSTATE_SCANNING &&
  161735. cinfo->global_state != CSTATE_RAW_OK &&
  161736. cinfo->global_state != CSTATE_WRCOEFS))
  161737. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161738. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  161739. write_marker_byte = cinfo->marker->write_marker_byte; /* copy for speed */
  161740. while (datalen--) {
  161741. (*write_marker_byte) (cinfo, *dataptr);
  161742. dataptr++;
  161743. }
  161744. }
  161745. /* Same, but piecemeal. */
  161746. GLOBAL(void)
  161747. jpeg_write_m_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  161748. {
  161749. if (cinfo->next_scanline != 0 ||
  161750. (cinfo->global_state != CSTATE_SCANNING &&
  161751. cinfo->global_state != CSTATE_RAW_OK &&
  161752. cinfo->global_state != CSTATE_WRCOEFS))
  161753. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161754. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  161755. }
  161756. GLOBAL(void)
  161757. jpeg_write_m_byte (j_compress_ptr cinfo, int val)
  161758. {
  161759. (*cinfo->marker->write_marker_byte) (cinfo, val);
  161760. }
  161761. /*
  161762. * Alternate compression function: just write an abbreviated table file.
  161763. * Before calling this, all parameters and a data destination must be set up.
  161764. *
  161765. * To produce a pair of files containing abbreviated tables and abbreviated
  161766. * image data, one would proceed as follows:
  161767. *
  161768. * initialize JPEG object
  161769. * set JPEG parameters
  161770. * set destination to table file
  161771. * jpeg_write_tables(cinfo);
  161772. * set destination to image file
  161773. * jpeg_start_compress(cinfo, FALSE);
  161774. * write data...
  161775. * jpeg_finish_compress(cinfo);
  161776. *
  161777. * jpeg_write_tables has the side effect of marking all tables written
  161778. * (same as jpeg_suppress_tables(..., TRUE)). Thus a subsequent start_compress
  161779. * will not re-emit the tables unless it is passed write_all_tables=TRUE.
  161780. */
  161781. GLOBAL(void)
  161782. jpeg_write_tables (j_compress_ptr cinfo)
  161783. {
  161784. if (cinfo->global_state != CSTATE_START)
  161785. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161786. /* (Re)initialize error mgr and destination modules */
  161787. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  161788. (*cinfo->dest->init_destination) (cinfo);
  161789. /* Initialize the marker writer ... bit of a crock to do it here. */
  161790. jinit_marker_writer(cinfo);
  161791. /* Write them tables! */
  161792. (*cinfo->marker->write_tables_only) (cinfo);
  161793. /* And clean up. */
  161794. (*cinfo->dest->term_destination) (cinfo);
  161795. /*
  161796. * In library releases up through v6a, we called jpeg_abort() here to free
  161797. * any working memory allocated by the destination manager and marker
  161798. * writer. Some applications had a problem with that: they allocated space
  161799. * of their own from the library memory manager, and didn't want it to go
  161800. * away during write_tables. So now we do nothing. This will cause a
  161801. * memory leak if an app calls write_tables repeatedly without doing a full
  161802. * compression cycle or otherwise resetting the JPEG object. However, that
  161803. * seems less bad than unexpectedly freeing memory in the normal case.
  161804. * An app that prefers the old behavior can call jpeg_abort for itself after
  161805. * each call to jpeg_write_tables().
  161806. */
  161807. }
  161808. /*** End of inlined file: jcapimin.c ***/
  161809. /*** Start of inlined file: jcapistd.c ***/
  161810. #define JPEG_INTERNALS
  161811. /*
  161812. * Compression initialization.
  161813. * Before calling this, all parameters and a data destination must be set up.
  161814. *
  161815. * We require a write_all_tables parameter as a failsafe check when writing
  161816. * multiple datastreams from the same compression object. Since prior runs
  161817. * will have left all the tables marked sent_table=TRUE, a subsequent run
  161818. * would emit an abbreviated stream (no tables) by default. This may be what
  161819. * is wanted, but for safety's sake it should not be the default behavior:
  161820. * programmers should have to make a deliberate choice to emit abbreviated
  161821. * images. Therefore the documentation and examples should encourage people
  161822. * to pass write_all_tables=TRUE; then it will take active thought to do the
  161823. * wrong thing.
  161824. */
  161825. GLOBAL(void)
  161826. jpeg_start_compress (j_compress_ptr cinfo, boolean write_all_tables)
  161827. {
  161828. if (cinfo->global_state != CSTATE_START)
  161829. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161830. if (write_all_tables)
  161831. jpeg_suppress_tables(cinfo, FALSE); /* mark all tables to be written */
  161832. /* (Re)initialize error mgr and destination modules */
  161833. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  161834. (*cinfo->dest->init_destination) (cinfo);
  161835. /* Perform master selection of active modules */
  161836. jinit_compress_master(cinfo);
  161837. /* Set up for the first pass */
  161838. (*cinfo->master->prepare_for_pass) (cinfo);
  161839. /* Ready for application to drive first pass through jpeg_write_scanlines
  161840. * or jpeg_write_raw_data.
  161841. */
  161842. cinfo->next_scanline = 0;
  161843. cinfo->global_state = (cinfo->raw_data_in ? CSTATE_RAW_OK : CSTATE_SCANNING);
  161844. }
  161845. /*
  161846. * Write some scanlines of data to the JPEG compressor.
  161847. *
  161848. * The return value will be the number of lines actually written.
  161849. * This should be less than the supplied num_lines only in case that
  161850. * the data destination module has requested suspension of the compressor,
  161851. * or if more than image_height scanlines are passed in.
  161852. *
  161853. * Note: we warn about excess calls to jpeg_write_scanlines() since
  161854. * this likely signals an application programmer error. However,
  161855. * excess scanlines passed in the last valid call are *silently* ignored,
  161856. * so that the application need not adjust num_lines for end-of-image
  161857. * when using a multiple-scanline buffer.
  161858. */
  161859. GLOBAL(JDIMENSION)
  161860. jpeg_write_scanlines (j_compress_ptr cinfo, JSAMPARRAY scanlines,
  161861. JDIMENSION num_lines)
  161862. {
  161863. JDIMENSION row_ctr, rows_left;
  161864. if (cinfo->global_state != CSTATE_SCANNING)
  161865. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161866. if (cinfo->next_scanline >= cinfo->image_height)
  161867. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  161868. /* Call progress monitor hook if present */
  161869. if (cinfo->progress != NULL) {
  161870. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  161871. cinfo->progress->pass_limit = (long) cinfo->image_height;
  161872. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161873. }
  161874. /* Give master control module another chance if this is first call to
  161875. * jpeg_write_scanlines. This lets output of the frame/scan headers be
  161876. * delayed so that application can write COM, etc, markers between
  161877. * jpeg_start_compress and jpeg_write_scanlines.
  161878. */
  161879. if (cinfo->master->call_pass_startup)
  161880. (*cinfo->master->pass_startup) (cinfo);
  161881. /* Ignore any extra scanlines at bottom of image. */
  161882. rows_left = cinfo->image_height - cinfo->next_scanline;
  161883. if (num_lines > rows_left)
  161884. num_lines = rows_left;
  161885. row_ctr = 0;
  161886. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, num_lines);
  161887. cinfo->next_scanline += row_ctr;
  161888. return row_ctr;
  161889. }
  161890. /*
  161891. * Alternate entry point to write raw data.
  161892. * Processes exactly one iMCU row per call, unless suspended.
  161893. */
  161894. GLOBAL(JDIMENSION)
  161895. jpeg_write_raw_data (j_compress_ptr cinfo, JSAMPIMAGE data,
  161896. JDIMENSION num_lines)
  161897. {
  161898. JDIMENSION lines_per_iMCU_row;
  161899. if (cinfo->global_state != CSTATE_RAW_OK)
  161900. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161901. if (cinfo->next_scanline >= cinfo->image_height) {
  161902. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  161903. return 0;
  161904. }
  161905. /* Call progress monitor hook if present */
  161906. if (cinfo->progress != NULL) {
  161907. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  161908. cinfo->progress->pass_limit = (long) cinfo->image_height;
  161909. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161910. }
  161911. /* Give master control module another chance if this is first call to
  161912. * jpeg_write_raw_data. This lets output of the frame/scan headers be
  161913. * delayed so that application can write COM, etc, markers between
  161914. * jpeg_start_compress and jpeg_write_raw_data.
  161915. */
  161916. if (cinfo->master->call_pass_startup)
  161917. (*cinfo->master->pass_startup) (cinfo);
  161918. /* Verify that at least one iMCU row has been passed. */
  161919. lines_per_iMCU_row = cinfo->max_v_samp_factor * DCTSIZE;
  161920. if (num_lines < lines_per_iMCU_row)
  161921. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  161922. /* Directly compress the row. */
  161923. if (! (*cinfo->coef->compress_data) (cinfo, data)) {
  161924. /* If compressor did not consume the whole row, suspend processing. */
  161925. return 0;
  161926. }
  161927. /* OK, we processed one iMCU row. */
  161928. cinfo->next_scanline += lines_per_iMCU_row;
  161929. return lines_per_iMCU_row;
  161930. }
  161931. /*** End of inlined file: jcapistd.c ***/
  161932. /*** Start of inlined file: jccoefct.c ***/
  161933. #define JPEG_INTERNALS
  161934. /* We use a full-image coefficient buffer when doing Huffman optimization,
  161935. * and also for writing multiple-scan JPEG files. In all cases, the DCT
  161936. * step is run during the first pass, and subsequent passes need only read
  161937. * the buffered coefficients.
  161938. */
  161939. #ifdef ENTROPY_OPT_SUPPORTED
  161940. #define FULL_COEF_BUFFER_SUPPORTED
  161941. #else
  161942. #ifdef C_MULTISCAN_FILES_SUPPORTED
  161943. #define FULL_COEF_BUFFER_SUPPORTED
  161944. #endif
  161945. #endif
  161946. /* Private buffer controller object */
  161947. typedef struct {
  161948. struct jpeg_c_coef_controller pub; /* public fields */
  161949. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  161950. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  161951. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  161952. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  161953. /* For single-pass compression, it's sufficient to buffer just one MCU
  161954. * (although this may prove a bit slow in practice). We allocate a
  161955. * workspace of C_MAX_BLOCKS_IN_MCU coefficient blocks, and reuse it for each
  161956. * MCU constructed and sent. (On 80x86, the workspace is FAR even though
  161957. * it's not really very big; this is to keep the module interfaces unchanged
  161958. * when a large coefficient buffer is necessary.)
  161959. * In multi-pass modes, this array points to the current MCU's blocks
  161960. * within the virtual arrays.
  161961. */
  161962. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  161963. /* In multi-pass modes, we need a virtual block array for each component. */
  161964. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  161965. } my_coef_controller;
  161966. typedef my_coef_controller * my_coef_ptr;
  161967. /* Forward declarations */
  161968. METHODDEF(boolean) compress_data
  161969. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  161970. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161971. METHODDEF(boolean) compress_first_pass
  161972. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  161973. METHODDEF(boolean) compress_output
  161974. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  161975. #endif
  161976. LOCAL(void)
  161977. start_iMCU_row (j_compress_ptr cinfo)
  161978. /* Reset within-iMCU-row counters for a new row */
  161979. {
  161980. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161981. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  161982. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  161983. * But at the bottom of the image, process only what's left.
  161984. */
  161985. if (cinfo->comps_in_scan > 1) {
  161986. coef->MCU_rows_per_iMCU_row = 1;
  161987. } else {
  161988. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  161989. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  161990. else
  161991. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  161992. }
  161993. coef->mcu_ctr = 0;
  161994. coef->MCU_vert_offset = 0;
  161995. }
  161996. /*
  161997. * Initialize for a processing pass.
  161998. */
  161999. METHODDEF(void)
  162000. start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  162001. {
  162002. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162003. coef->iMCU_row_num = 0;
  162004. start_iMCU_row(cinfo);
  162005. switch (pass_mode) {
  162006. case JBUF_PASS_THRU:
  162007. if (coef->whole_image[0] != NULL)
  162008. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162009. coef->pub.compress_data = compress_data;
  162010. break;
  162011. #ifdef FULL_COEF_BUFFER_SUPPORTED
  162012. case JBUF_SAVE_AND_PASS:
  162013. if (coef->whole_image[0] == NULL)
  162014. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162015. coef->pub.compress_data = compress_first_pass;
  162016. break;
  162017. case JBUF_CRANK_DEST:
  162018. if (coef->whole_image[0] == NULL)
  162019. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162020. coef->pub.compress_data = compress_output;
  162021. break;
  162022. #endif
  162023. default:
  162024. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162025. break;
  162026. }
  162027. }
  162028. /*
  162029. * Process some data in the single-pass case.
  162030. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  162031. * per call, ie, v_samp_factor block rows for each component in the image.
  162032. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  162033. *
  162034. * NB: input_buf contains a plane for each component in image,
  162035. * which we index according to the component's SOF position.
  162036. */
  162037. METHODDEF(boolean)
  162038. compress_data (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  162039. {
  162040. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162041. JDIMENSION MCU_col_num; /* index of current MCU within row */
  162042. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  162043. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  162044. int blkn, bi, ci, yindex, yoffset, blockcnt;
  162045. JDIMENSION ypos, xpos;
  162046. jpeg_component_info *compptr;
  162047. /* Loop to write as much as one whole iMCU row */
  162048. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  162049. yoffset++) {
  162050. for (MCU_col_num = coef->mcu_ctr; MCU_col_num <= last_MCU_col;
  162051. MCU_col_num++) {
  162052. /* Determine where data comes from in input_buf and do the DCT thing.
  162053. * Each call on forward_DCT processes a horizontal row of DCT blocks
  162054. * as wide as an MCU; we rely on having allocated the MCU_buffer[] blocks
  162055. * sequentially. Dummy blocks at the right or bottom edge are filled in
  162056. * specially. The data in them does not matter for image reconstruction,
  162057. * so we fill them with values that will encode to the smallest amount of
  162058. * data, viz: all zeroes in the AC entries, DC entries equal to previous
  162059. * block's DC value. (Thanks to Thomas Kinsman for this idea.)
  162060. */
  162061. blkn = 0;
  162062. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162063. compptr = cinfo->cur_comp_info[ci];
  162064. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  162065. : compptr->last_col_width;
  162066. xpos = MCU_col_num * compptr->MCU_sample_width;
  162067. ypos = yoffset * DCTSIZE; /* ypos == (yoffset+yindex) * DCTSIZE */
  162068. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  162069. if (coef->iMCU_row_num < last_iMCU_row ||
  162070. yoffset+yindex < compptr->last_row_height) {
  162071. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  162072. input_buf[compptr->component_index],
  162073. coef->MCU_buffer[blkn],
  162074. ypos, xpos, (JDIMENSION) blockcnt);
  162075. if (blockcnt < compptr->MCU_width) {
  162076. /* Create some dummy blocks at the right edge of the image. */
  162077. jzero_far((void FAR *) coef->MCU_buffer[blkn + blockcnt],
  162078. (compptr->MCU_width - blockcnt) * SIZEOF(JBLOCK));
  162079. for (bi = blockcnt; bi < compptr->MCU_width; bi++) {
  162080. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn+bi-1][0][0];
  162081. }
  162082. }
  162083. } else {
  162084. /* Create a row of dummy blocks at the bottom of the image. */
  162085. jzero_far((void FAR *) coef->MCU_buffer[blkn],
  162086. compptr->MCU_width * SIZEOF(JBLOCK));
  162087. for (bi = 0; bi < compptr->MCU_width; bi++) {
  162088. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn-1][0][0];
  162089. }
  162090. }
  162091. blkn += compptr->MCU_width;
  162092. ypos += DCTSIZE;
  162093. }
  162094. }
  162095. /* Try to write the MCU. In event of a suspension failure, we will
  162096. * re-DCT the MCU on restart (a bit inefficient, could be fixed...)
  162097. */
  162098. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  162099. /* Suspension forced; update state counters and exit */
  162100. coef->MCU_vert_offset = yoffset;
  162101. coef->mcu_ctr = MCU_col_num;
  162102. return FALSE;
  162103. }
  162104. }
  162105. /* Completed an MCU row, but perhaps not an iMCU row */
  162106. coef->mcu_ctr = 0;
  162107. }
  162108. /* Completed the iMCU row, advance counters for next one */
  162109. coef->iMCU_row_num++;
  162110. start_iMCU_row(cinfo);
  162111. return TRUE;
  162112. }
  162113. #ifdef FULL_COEF_BUFFER_SUPPORTED
  162114. /*
  162115. * Process some data in the first pass of a multi-pass case.
  162116. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  162117. * per call, ie, v_samp_factor block rows for each component in the image.
  162118. * This amount of data is read from the source buffer, DCT'd and quantized,
  162119. * and saved into the virtual arrays. We also generate suitable dummy blocks
  162120. * as needed at the right and lower edges. (The dummy blocks are constructed
  162121. * in the virtual arrays, which have been padded appropriately.) This makes
  162122. * it possible for subsequent passes not to worry about real vs. dummy blocks.
  162123. *
  162124. * We must also emit the data to the entropy encoder. This is conveniently
  162125. * done by calling compress_output() after we've loaded the current strip
  162126. * of the virtual arrays.
  162127. *
  162128. * NB: input_buf contains a plane for each component in image. All
  162129. * components are DCT'd and loaded into the virtual arrays in this pass.
  162130. * However, it may be that only a subset of the components are emitted to
  162131. * the entropy encoder during this first pass; be careful about looking
  162132. * at the scan-dependent variables (MCU dimensions, etc).
  162133. */
  162134. METHODDEF(boolean)
  162135. compress_first_pass (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  162136. {
  162137. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162138. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  162139. JDIMENSION blocks_across, MCUs_across, MCUindex;
  162140. int bi, ci, h_samp_factor, block_row, block_rows, ndummy;
  162141. JCOEF lastDC;
  162142. jpeg_component_info *compptr;
  162143. JBLOCKARRAY buffer;
  162144. JBLOCKROW thisblockrow, lastblockrow;
  162145. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162146. ci++, compptr++) {
  162147. /* Align the virtual buffer for this component. */
  162148. buffer = (*cinfo->mem->access_virt_barray)
  162149. ((j_common_ptr) cinfo, coef->whole_image[ci],
  162150. coef->iMCU_row_num * compptr->v_samp_factor,
  162151. (JDIMENSION) compptr->v_samp_factor, TRUE);
  162152. /* Count non-dummy DCT block rows in this iMCU row. */
  162153. if (coef->iMCU_row_num < last_iMCU_row)
  162154. block_rows = compptr->v_samp_factor;
  162155. else {
  162156. /* NB: can't use last_row_height here, since may not be set! */
  162157. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  162158. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  162159. }
  162160. blocks_across = compptr->width_in_blocks;
  162161. h_samp_factor = compptr->h_samp_factor;
  162162. /* Count number of dummy blocks to be added at the right margin. */
  162163. ndummy = (int) (blocks_across % h_samp_factor);
  162164. if (ndummy > 0)
  162165. ndummy = h_samp_factor - ndummy;
  162166. /* Perform DCT for all non-dummy blocks in this iMCU row. Each call
  162167. * on forward_DCT processes a complete horizontal row of DCT blocks.
  162168. */
  162169. for (block_row = 0; block_row < block_rows; block_row++) {
  162170. thisblockrow = buffer[block_row];
  162171. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  162172. input_buf[ci], thisblockrow,
  162173. (JDIMENSION) (block_row * DCTSIZE),
  162174. (JDIMENSION) 0, blocks_across);
  162175. if (ndummy > 0) {
  162176. /* Create dummy blocks at the right edge of the image. */
  162177. thisblockrow += blocks_across; /* => first dummy block */
  162178. jzero_far((void FAR *) thisblockrow, ndummy * SIZEOF(JBLOCK));
  162179. lastDC = thisblockrow[-1][0];
  162180. for (bi = 0; bi < ndummy; bi++) {
  162181. thisblockrow[bi][0] = lastDC;
  162182. }
  162183. }
  162184. }
  162185. /* If at end of image, create dummy block rows as needed.
  162186. * The tricky part here is that within each MCU, we want the DC values
  162187. * of the dummy blocks to match the last real block's DC value.
  162188. * This squeezes a few more bytes out of the resulting file...
  162189. */
  162190. if (coef->iMCU_row_num == last_iMCU_row) {
  162191. blocks_across += ndummy; /* include lower right corner */
  162192. MCUs_across = blocks_across / h_samp_factor;
  162193. for (block_row = block_rows; block_row < compptr->v_samp_factor;
  162194. block_row++) {
  162195. thisblockrow = buffer[block_row];
  162196. lastblockrow = buffer[block_row-1];
  162197. jzero_far((void FAR *) thisblockrow,
  162198. (size_t) (blocks_across * SIZEOF(JBLOCK)));
  162199. for (MCUindex = 0; MCUindex < MCUs_across; MCUindex++) {
  162200. lastDC = lastblockrow[h_samp_factor-1][0];
  162201. for (bi = 0; bi < h_samp_factor; bi++) {
  162202. thisblockrow[bi][0] = lastDC;
  162203. }
  162204. thisblockrow += h_samp_factor; /* advance to next MCU in row */
  162205. lastblockrow += h_samp_factor;
  162206. }
  162207. }
  162208. }
  162209. }
  162210. /* NB: compress_output will increment iMCU_row_num if successful.
  162211. * A suspension return will result in redoing all the work above next time.
  162212. */
  162213. /* Emit data to the entropy encoder, sharing code with subsequent passes */
  162214. return compress_output(cinfo, input_buf);
  162215. }
  162216. /*
  162217. * Process some data in subsequent passes of a multi-pass case.
  162218. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  162219. * per call, ie, v_samp_factor block rows for each component in the scan.
  162220. * The data is obtained from the virtual arrays and fed to the entropy coder.
  162221. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  162222. *
  162223. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  162224. */
  162225. METHODDEF(boolean)
  162226. compress_output (j_compress_ptr cinfo, JSAMPIMAGE)
  162227. {
  162228. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162229. JDIMENSION MCU_col_num; /* index of current MCU within row */
  162230. int blkn, ci, xindex, yindex, yoffset;
  162231. JDIMENSION start_col;
  162232. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  162233. JBLOCKROW buffer_ptr;
  162234. jpeg_component_info *compptr;
  162235. /* Align the virtual buffers for the components used in this scan.
  162236. * NB: during first pass, this is safe only because the buffers will
  162237. * already be aligned properly, so jmemmgr.c won't need to do any I/O.
  162238. */
  162239. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162240. compptr = cinfo->cur_comp_info[ci];
  162241. buffer[ci] = (*cinfo->mem->access_virt_barray)
  162242. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  162243. coef->iMCU_row_num * compptr->v_samp_factor,
  162244. (JDIMENSION) compptr->v_samp_factor, FALSE);
  162245. }
  162246. /* Loop to process one whole iMCU row */
  162247. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  162248. yoffset++) {
  162249. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  162250. MCU_col_num++) {
  162251. /* Construct list of pointers to DCT blocks belonging to this MCU */
  162252. blkn = 0; /* index of current DCT block within MCU */
  162253. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162254. compptr = cinfo->cur_comp_info[ci];
  162255. start_col = MCU_col_num * compptr->MCU_width;
  162256. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  162257. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  162258. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  162259. coef->MCU_buffer[blkn++] = buffer_ptr++;
  162260. }
  162261. }
  162262. }
  162263. /* Try to write the MCU. */
  162264. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  162265. /* Suspension forced; update state counters and exit */
  162266. coef->MCU_vert_offset = yoffset;
  162267. coef->mcu_ctr = MCU_col_num;
  162268. return FALSE;
  162269. }
  162270. }
  162271. /* Completed an MCU row, but perhaps not an iMCU row */
  162272. coef->mcu_ctr = 0;
  162273. }
  162274. /* Completed the iMCU row, advance counters for next one */
  162275. coef->iMCU_row_num++;
  162276. start_iMCU_row(cinfo);
  162277. return TRUE;
  162278. }
  162279. #endif /* FULL_COEF_BUFFER_SUPPORTED */
  162280. /*
  162281. * Initialize coefficient buffer controller.
  162282. */
  162283. GLOBAL(void)
  162284. jinit_c_coef_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  162285. {
  162286. my_coef_ptr coef;
  162287. coef = (my_coef_ptr)
  162288. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162289. SIZEOF(my_coef_controller));
  162290. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  162291. coef->pub.start_pass = start_pass_coef;
  162292. /* Create the coefficient buffer. */
  162293. if (need_full_buffer) {
  162294. #ifdef FULL_COEF_BUFFER_SUPPORTED
  162295. /* Allocate a full-image virtual array for each component, */
  162296. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  162297. int ci;
  162298. jpeg_component_info *compptr;
  162299. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162300. ci++, compptr++) {
  162301. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  162302. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  162303. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  162304. (long) compptr->h_samp_factor),
  162305. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  162306. (long) compptr->v_samp_factor),
  162307. (JDIMENSION) compptr->v_samp_factor);
  162308. }
  162309. #else
  162310. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162311. #endif
  162312. } else {
  162313. /* We only need a single-MCU buffer. */
  162314. JBLOCKROW buffer;
  162315. int i;
  162316. buffer = (JBLOCKROW)
  162317. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162318. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  162319. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  162320. coef->MCU_buffer[i] = buffer + i;
  162321. }
  162322. coef->whole_image[0] = NULL; /* flag for no virtual arrays */
  162323. }
  162324. }
  162325. /*** End of inlined file: jccoefct.c ***/
  162326. /*** Start of inlined file: jccolor.c ***/
  162327. #define JPEG_INTERNALS
  162328. /* Private subobject */
  162329. typedef struct {
  162330. struct jpeg_color_converter pub; /* public fields */
  162331. /* Private state for RGB->YCC conversion */
  162332. INT32 * rgb_ycc_tab; /* => table for RGB to YCbCr conversion */
  162333. } my_color_converter;
  162334. typedef my_color_converter * my_cconvert_ptr;
  162335. /**************** RGB -> YCbCr conversion: most common case **************/
  162336. /*
  162337. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  162338. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  162339. * The conversion equations to be implemented are therefore
  162340. * Y = 0.29900 * R + 0.58700 * G + 0.11400 * B
  162341. * Cb = -0.16874 * R - 0.33126 * G + 0.50000 * B + CENTERJSAMPLE
  162342. * Cr = 0.50000 * R - 0.41869 * G - 0.08131 * B + CENTERJSAMPLE
  162343. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  162344. * Note: older versions of the IJG code used a zero offset of MAXJSAMPLE/2,
  162345. * rather than CENTERJSAMPLE, for Cb and Cr. This gave equal positive and
  162346. * negative swings for Cb/Cr, but meant that grayscale values (Cb=Cr=0)
  162347. * were not represented exactly. Now we sacrifice exact representation of
  162348. * maximum red and maximum blue in order to get exact grayscales.
  162349. *
  162350. * To avoid floating-point arithmetic, we represent the fractional constants
  162351. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  162352. * the products by 2^16, with appropriate rounding, to get the correct answer.
  162353. *
  162354. * For even more speed, we avoid doing any multiplications in the inner loop
  162355. * by precalculating the constants times R,G,B for all possible values.
  162356. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  162357. * for 12-bit samples it is still acceptable. It's not very reasonable for
  162358. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  162359. * colorspace anyway.
  162360. * The CENTERJSAMPLE offsets and the rounding fudge-factor of 0.5 are included
  162361. * in the tables to save adding them separately in the inner loop.
  162362. */
  162363. #define SCALEBITS 16 /* speediest right-shift on some machines */
  162364. #define CBCR_OFFSET ((INT32) CENTERJSAMPLE << SCALEBITS)
  162365. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  162366. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  162367. /* We allocate one big table and divide it up into eight parts, instead of
  162368. * doing eight alloc_small requests. This lets us use a single table base
  162369. * address, which can be held in a register in the inner loops on many
  162370. * machines (more than can hold all eight addresses, anyway).
  162371. */
  162372. #define R_Y_OFF 0 /* offset to R => Y section */
  162373. #define G_Y_OFF (1*(MAXJSAMPLE+1)) /* offset to G => Y section */
  162374. #define B_Y_OFF (2*(MAXJSAMPLE+1)) /* etc. */
  162375. #define R_CB_OFF (3*(MAXJSAMPLE+1))
  162376. #define G_CB_OFF (4*(MAXJSAMPLE+1))
  162377. #define B_CB_OFF (5*(MAXJSAMPLE+1))
  162378. #define R_CR_OFF B_CB_OFF /* B=>Cb, R=>Cr are the same */
  162379. #define G_CR_OFF (6*(MAXJSAMPLE+1))
  162380. #define B_CR_OFF (7*(MAXJSAMPLE+1))
  162381. #define TABLE_SIZE (8*(MAXJSAMPLE+1))
  162382. /*
  162383. * Initialize for RGB->YCC colorspace conversion.
  162384. */
  162385. METHODDEF(void)
  162386. rgb_ycc_start (j_compress_ptr cinfo)
  162387. {
  162388. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162389. INT32 * rgb_ycc_tab;
  162390. INT32 i;
  162391. /* Allocate and fill in the conversion tables. */
  162392. cconvert->rgb_ycc_tab = rgb_ycc_tab = (INT32 *)
  162393. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162394. (TABLE_SIZE * SIZEOF(INT32)));
  162395. for (i = 0; i <= MAXJSAMPLE; i++) {
  162396. rgb_ycc_tab[i+R_Y_OFF] = FIX(0.29900) * i;
  162397. rgb_ycc_tab[i+G_Y_OFF] = FIX(0.58700) * i;
  162398. rgb_ycc_tab[i+B_Y_OFF] = FIX(0.11400) * i + ONE_HALF;
  162399. rgb_ycc_tab[i+R_CB_OFF] = (-FIX(0.16874)) * i;
  162400. rgb_ycc_tab[i+G_CB_OFF] = (-FIX(0.33126)) * i;
  162401. /* We use a rounding fudge-factor of 0.5-epsilon for Cb and Cr.
  162402. * This ensures that the maximum output will round to MAXJSAMPLE
  162403. * not MAXJSAMPLE+1, and thus that we don't have to range-limit.
  162404. */
  162405. rgb_ycc_tab[i+B_CB_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  162406. /* B=>Cb and R=>Cr tables are the same
  162407. rgb_ycc_tab[i+R_CR_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  162408. */
  162409. rgb_ycc_tab[i+G_CR_OFF] = (-FIX(0.41869)) * i;
  162410. rgb_ycc_tab[i+B_CR_OFF] = (-FIX(0.08131)) * i;
  162411. }
  162412. }
  162413. /*
  162414. * Convert some rows of samples to the JPEG colorspace.
  162415. *
  162416. * Note that we change from the application's interleaved-pixel format
  162417. * to our internal noninterleaved, one-plane-per-component format.
  162418. * The input buffer is therefore three times as wide as the output buffer.
  162419. *
  162420. * A starting row offset is provided only for the output buffer. The caller
  162421. * can easily adjust the passed input_buf value to accommodate any row
  162422. * offset required on that side.
  162423. */
  162424. METHODDEF(void)
  162425. rgb_ycc_convert (j_compress_ptr cinfo,
  162426. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162427. JDIMENSION output_row, int num_rows)
  162428. {
  162429. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162430. register int r, g, b;
  162431. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162432. register JSAMPROW inptr;
  162433. register JSAMPROW outptr0, outptr1, outptr2;
  162434. register JDIMENSION col;
  162435. JDIMENSION num_cols = cinfo->image_width;
  162436. while (--num_rows >= 0) {
  162437. inptr = *input_buf++;
  162438. outptr0 = output_buf[0][output_row];
  162439. outptr1 = output_buf[1][output_row];
  162440. outptr2 = output_buf[2][output_row];
  162441. output_row++;
  162442. for (col = 0; col < num_cols; col++) {
  162443. r = GETJSAMPLE(inptr[RGB_RED]);
  162444. g = GETJSAMPLE(inptr[RGB_GREEN]);
  162445. b = GETJSAMPLE(inptr[RGB_BLUE]);
  162446. inptr += RGB_PIXELSIZE;
  162447. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  162448. * must be too; we do not need an explicit range-limiting operation.
  162449. * Hence the value being shifted is never negative, and we don't
  162450. * need the general RIGHT_SHIFT macro.
  162451. */
  162452. /* Y */
  162453. outptr0[col] = (JSAMPLE)
  162454. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162455. >> SCALEBITS);
  162456. /* Cb */
  162457. outptr1[col] = (JSAMPLE)
  162458. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  162459. >> SCALEBITS);
  162460. /* Cr */
  162461. outptr2[col] = (JSAMPLE)
  162462. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  162463. >> SCALEBITS);
  162464. }
  162465. }
  162466. }
  162467. /**************** Cases other than RGB -> YCbCr **************/
  162468. /*
  162469. * Convert some rows of samples to the JPEG colorspace.
  162470. * This version handles RGB->grayscale conversion, which is the same
  162471. * as the RGB->Y portion of RGB->YCbCr.
  162472. * We assume rgb_ycc_start has been called (we only use the Y tables).
  162473. */
  162474. METHODDEF(void)
  162475. rgb_gray_convert (j_compress_ptr cinfo,
  162476. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162477. JDIMENSION output_row, int num_rows)
  162478. {
  162479. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162480. register int r, g, b;
  162481. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162482. register JSAMPROW inptr;
  162483. register JSAMPROW outptr;
  162484. register JDIMENSION col;
  162485. JDIMENSION num_cols = cinfo->image_width;
  162486. while (--num_rows >= 0) {
  162487. inptr = *input_buf++;
  162488. outptr = output_buf[0][output_row];
  162489. output_row++;
  162490. for (col = 0; col < num_cols; col++) {
  162491. r = GETJSAMPLE(inptr[RGB_RED]);
  162492. g = GETJSAMPLE(inptr[RGB_GREEN]);
  162493. b = GETJSAMPLE(inptr[RGB_BLUE]);
  162494. inptr += RGB_PIXELSIZE;
  162495. /* Y */
  162496. outptr[col] = (JSAMPLE)
  162497. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162498. >> SCALEBITS);
  162499. }
  162500. }
  162501. }
  162502. /*
  162503. * Convert some rows of samples to the JPEG colorspace.
  162504. * This version handles Adobe-style CMYK->YCCK conversion,
  162505. * where we convert R=1-C, G=1-M, and B=1-Y to YCbCr using the same
  162506. * conversion as above, while passing K (black) unchanged.
  162507. * We assume rgb_ycc_start has been called.
  162508. */
  162509. METHODDEF(void)
  162510. cmyk_ycck_convert (j_compress_ptr cinfo,
  162511. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162512. JDIMENSION output_row, int num_rows)
  162513. {
  162514. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162515. register int r, g, b;
  162516. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162517. register JSAMPROW inptr;
  162518. register JSAMPROW outptr0, outptr1, outptr2, outptr3;
  162519. register JDIMENSION col;
  162520. JDIMENSION num_cols = cinfo->image_width;
  162521. while (--num_rows >= 0) {
  162522. inptr = *input_buf++;
  162523. outptr0 = output_buf[0][output_row];
  162524. outptr1 = output_buf[1][output_row];
  162525. outptr2 = output_buf[2][output_row];
  162526. outptr3 = output_buf[3][output_row];
  162527. output_row++;
  162528. for (col = 0; col < num_cols; col++) {
  162529. r = MAXJSAMPLE - GETJSAMPLE(inptr[0]);
  162530. g = MAXJSAMPLE - GETJSAMPLE(inptr[1]);
  162531. b = MAXJSAMPLE - GETJSAMPLE(inptr[2]);
  162532. /* K passes through as-is */
  162533. outptr3[col] = inptr[3]; /* don't need GETJSAMPLE here */
  162534. inptr += 4;
  162535. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  162536. * must be too; we do not need an explicit range-limiting operation.
  162537. * Hence the value being shifted is never negative, and we don't
  162538. * need the general RIGHT_SHIFT macro.
  162539. */
  162540. /* Y */
  162541. outptr0[col] = (JSAMPLE)
  162542. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162543. >> SCALEBITS);
  162544. /* Cb */
  162545. outptr1[col] = (JSAMPLE)
  162546. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  162547. >> SCALEBITS);
  162548. /* Cr */
  162549. outptr2[col] = (JSAMPLE)
  162550. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  162551. >> SCALEBITS);
  162552. }
  162553. }
  162554. }
  162555. /*
  162556. * Convert some rows of samples to the JPEG colorspace.
  162557. * This version handles grayscale output with no conversion.
  162558. * The source can be either plain grayscale or YCbCr (since Y == gray).
  162559. */
  162560. METHODDEF(void)
  162561. grayscale_convert (j_compress_ptr cinfo,
  162562. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162563. JDIMENSION output_row, int num_rows)
  162564. {
  162565. register JSAMPROW inptr;
  162566. register JSAMPROW outptr;
  162567. register JDIMENSION col;
  162568. JDIMENSION num_cols = cinfo->image_width;
  162569. int instride = cinfo->input_components;
  162570. while (--num_rows >= 0) {
  162571. inptr = *input_buf++;
  162572. outptr = output_buf[0][output_row];
  162573. output_row++;
  162574. for (col = 0; col < num_cols; col++) {
  162575. outptr[col] = inptr[0]; /* don't need GETJSAMPLE() here */
  162576. inptr += instride;
  162577. }
  162578. }
  162579. }
  162580. /*
  162581. * Convert some rows of samples to the JPEG colorspace.
  162582. * This version handles multi-component colorspaces without conversion.
  162583. * We assume input_components == num_components.
  162584. */
  162585. METHODDEF(void)
  162586. null_convert (j_compress_ptr cinfo,
  162587. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162588. JDIMENSION output_row, int num_rows)
  162589. {
  162590. register JSAMPROW inptr;
  162591. register JSAMPROW outptr;
  162592. register JDIMENSION col;
  162593. register int ci;
  162594. int nc = cinfo->num_components;
  162595. JDIMENSION num_cols = cinfo->image_width;
  162596. while (--num_rows >= 0) {
  162597. /* It seems fastest to make a separate pass for each component. */
  162598. for (ci = 0; ci < nc; ci++) {
  162599. inptr = *input_buf;
  162600. outptr = output_buf[ci][output_row];
  162601. for (col = 0; col < num_cols; col++) {
  162602. outptr[col] = inptr[ci]; /* don't need GETJSAMPLE() here */
  162603. inptr += nc;
  162604. }
  162605. }
  162606. input_buf++;
  162607. output_row++;
  162608. }
  162609. }
  162610. /*
  162611. * Empty method for start_pass.
  162612. */
  162613. METHODDEF(void)
  162614. null_method (j_compress_ptr)
  162615. {
  162616. /* no work needed */
  162617. }
  162618. /*
  162619. * Module initialization routine for input colorspace conversion.
  162620. */
  162621. GLOBAL(void)
  162622. jinit_color_converter (j_compress_ptr cinfo)
  162623. {
  162624. my_cconvert_ptr cconvert;
  162625. cconvert = (my_cconvert_ptr)
  162626. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162627. SIZEOF(my_color_converter));
  162628. cinfo->cconvert = (struct jpeg_color_converter *) cconvert;
  162629. /* set start_pass to null method until we find out differently */
  162630. cconvert->pub.start_pass = null_method;
  162631. /* Make sure input_components agrees with in_color_space */
  162632. switch (cinfo->in_color_space) {
  162633. case JCS_GRAYSCALE:
  162634. if (cinfo->input_components != 1)
  162635. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162636. break;
  162637. case JCS_RGB:
  162638. #if RGB_PIXELSIZE != 3
  162639. if (cinfo->input_components != RGB_PIXELSIZE)
  162640. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162641. break;
  162642. #endif /* else share code with YCbCr */
  162643. case JCS_YCbCr:
  162644. if (cinfo->input_components != 3)
  162645. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162646. break;
  162647. case JCS_CMYK:
  162648. case JCS_YCCK:
  162649. if (cinfo->input_components != 4)
  162650. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162651. break;
  162652. default: /* JCS_UNKNOWN can be anything */
  162653. if (cinfo->input_components < 1)
  162654. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162655. break;
  162656. }
  162657. /* Check num_components, set conversion method based on requested space */
  162658. switch (cinfo->jpeg_color_space) {
  162659. case JCS_GRAYSCALE:
  162660. if (cinfo->num_components != 1)
  162661. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162662. if (cinfo->in_color_space == JCS_GRAYSCALE)
  162663. cconvert->pub.color_convert = grayscale_convert;
  162664. else if (cinfo->in_color_space == JCS_RGB) {
  162665. cconvert->pub.start_pass = rgb_ycc_start;
  162666. cconvert->pub.color_convert = rgb_gray_convert;
  162667. } else if (cinfo->in_color_space == JCS_YCbCr)
  162668. cconvert->pub.color_convert = grayscale_convert;
  162669. else
  162670. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162671. break;
  162672. case JCS_RGB:
  162673. if (cinfo->num_components != 3)
  162674. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162675. if (cinfo->in_color_space == JCS_RGB && RGB_PIXELSIZE == 3)
  162676. cconvert->pub.color_convert = null_convert;
  162677. else
  162678. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162679. break;
  162680. case JCS_YCbCr:
  162681. if (cinfo->num_components != 3)
  162682. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162683. if (cinfo->in_color_space == JCS_RGB) {
  162684. cconvert->pub.start_pass = rgb_ycc_start;
  162685. cconvert->pub.color_convert = rgb_ycc_convert;
  162686. } else if (cinfo->in_color_space == JCS_YCbCr)
  162687. cconvert->pub.color_convert = null_convert;
  162688. else
  162689. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162690. break;
  162691. case JCS_CMYK:
  162692. if (cinfo->num_components != 4)
  162693. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162694. if (cinfo->in_color_space == JCS_CMYK)
  162695. cconvert->pub.color_convert = null_convert;
  162696. else
  162697. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162698. break;
  162699. case JCS_YCCK:
  162700. if (cinfo->num_components != 4)
  162701. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162702. if (cinfo->in_color_space == JCS_CMYK) {
  162703. cconvert->pub.start_pass = rgb_ycc_start;
  162704. cconvert->pub.color_convert = cmyk_ycck_convert;
  162705. } else if (cinfo->in_color_space == JCS_YCCK)
  162706. cconvert->pub.color_convert = null_convert;
  162707. else
  162708. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162709. break;
  162710. default: /* allow null conversion of JCS_UNKNOWN */
  162711. if (cinfo->jpeg_color_space != cinfo->in_color_space ||
  162712. cinfo->num_components != cinfo->input_components)
  162713. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162714. cconvert->pub.color_convert = null_convert;
  162715. break;
  162716. }
  162717. }
  162718. /*** End of inlined file: jccolor.c ***/
  162719. #undef FIX
  162720. /*** Start of inlined file: jcdctmgr.c ***/
  162721. #define JPEG_INTERNALS
  162722. /*** Start of inlined file: jdct.h ***/
  162723. /*
  162724. * A forward DCT routine is given a pointer to a work area of type DCTELEM[];
  162725. * the DCT is to be performed in-place in that buffer. Type DCTELEM is int
  162726. * for 8-bit samples, INT32 for 12-bit samples. (NOTE: Floating-point DCT
  162727. * implementations use an array of type FAST_FLOAT, instead.)
  162728. * The DCT inputs are expected to be signed (range +-CENTERJSAMPLE).
  162729. * The DCT outputs are returned scaled up by a factor of 8; they therefore
  162730. * have a range of +-8K for 8-bit data, +-128K for 12-bit data. This
  162731. * convention improves accuracy in integer implementations and saves some
  162732. * work in floating-point ones.
  162733. * Quantization of the output coefficients is done by jcdctmgr.c.
  162734. */
  162735. #ifndef __jdct_h__
  162736. #define __jdct_h__
  162737. #if BITS_IN_JSAMPLE == 8
  162738. typedef int DCTELEM; /* 16 or 32 bits is fine */
  162739. #else
  162740. typedef INT32 DCTELEM; /* must have 32 bits */
  162741. #endif
  162742. typedef JMETHOD(void, forward_DCT_method_ptr, (DCTELEM * data));
  162743. typedef JMETHOD(void, float_DCT_method_ptr, (FAST_FLOAT * data));
  162744. /*
  162745. * An inverse DCT routine is given a pointer to the input JBLOCK and a pointer
  162746. * to an output sample array. The routine must dequantize the input data as
  162747. * well as perform the IDCT; for dequantization, it uses the multiplier table
  162748. * pointed to by compptr->dct_table. The output data is to be placed into the
  162749. * sample array starting at a specified column. (Any row offset needed will
  162750. * be applied to the array pointer before it is passed to the IDCT code.)
  162751. * Note that the number of samples emitted by the IDCT routine is
  162752. * DCT_scaled_size * DCT_scaled_size.
  162753. */
  162754. /* typedef inverse_DCT_method_ptr is declared in jpegint.h */
  162755. /*
  162756. * Each IDCT routine has its own ideas about the best dct_table element type.
  162757. */
  162758. typedef MULTIPLIER ISLOW_MULT_TYPE; /* short or int, whichever is faster */
  162759. #if BITS_IN_JSAMPLE == 8
  162760. typedef MULTIPLIER IFAST_MULT_TYPE; /* 16 bits is OK, use short if faster */
  162761. #define IFAST_SCALE_BITS 2 /* fractional bits in scale factors */
  162762. #else
  162763. typedef INT32 IFAST_MULT_TYPE; /* need 32 bits for scaled quantizers */
  162764. #define IFAST_SCALE_BITS 13 /* fractional bits in scale factors */
  162765. #endif
  162766. typedef FAST_FLOAT FLOAT_MULT_TYPE; /* preferred floating type */
  162767. /*
  162768. * Each IDCT routine is responsible for range-limiting its results and
  162769. * converting them to unsigned form (0..MAXJSAMPLE). The raw outputs could
  162770. * be quite far out of range if the input data is corrupt, so a bulletproof
  162771. * range-limiting step is required. We use a mask-and-table-lookup method
  162772. * to do the combined operations quickly. See the comments with
  162773. * prepare_range_limit_table (in jdmaster.c) for more info.
  162774. */
  162775. #define IDCT_range_limit(cinfo) ((cinfo)->sample_range_limit + CENTERJSAMPLE)
  162776. #define RANGE_MASK (MAXJSAMPLE * 4 + 3) /* 2 bits wider than legal samples */
  162777. /* Short forms of external names for systems with brain-damaged linkers. */
  162778. #ifdef NEED_SHORT_EXTERNAL_NAMES
  162779. #define jpeg_fdct_islow jFDislow
  162780. #define jpeg_fdct_ifast jFDifast
  162781. #define jpeg_fdct_float jFDfloat
  162782. #define jpeg_idct_islow jRDislow
  162783. #define jpeg_idct_ifast jRDifast
  162784. #define jpeg_idct_float jRDfloat
  162785. #define jpeg_idct_4x4 jRD4x4
  162786. #define jpeg_idct_2x2 jRD2x2
  162787. #define jpeg_idct_1x1 jRD1x1
  162788. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  162789. /* Extern declarations for the forward and inverse DCT routines. */
  162790. EXTERN(void) jpeg_fdct_islow JPP((DCTELEM * data));
  162791. EXTERN(void) jpeg_fdct_ifast JPP((DCTELEM * data));
  162792. EXTERN(void) jpeg_fdct_float JPP((FAST_FLOAT * data));
  162793. EXTERN(void) jpeg_idct_islow
  162794. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162795. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162796. EXTERN(void) jpeg_idct_ifast
  162797. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162798. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162799. EXTERN(void) jpeg_idct_float
  162800. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162801. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162802. EXTERN(void) jpeg_idct_4x4
  162803. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162804. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162805. EXTERN(void) jpeg_idct_2x2
  162806. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162807. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162808. EXTERN(void) jpeg_idct_1x1
  162809. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162810. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162811. /*
  162812. * Macros for handling fixed-point arithmetic; these are used by many
  162813. * but not all of the DCT/IDCT modules.
  162814. *
  162815. * All values are expected to be of type INT32.
  162816. * Fractional constants are scaled left by CONST_BITS bits.
  162817. * CONST_BITS is defined within each module using these macros,
  162818. * and may differ from one module to the next.
  162819. */
  162820. #define ONE ((INT32) 1)
  162821. #define CONST_SCALE (ONE << CONST_BITS)
  162822. /* Convert a positive real constant to an integer scaled by CONST_SCALE.
  162823. * Caution: some C compilers fail to reduce "FIX(constant)" at compile time,
  162824. * thus causing a lot of useless floating-point operations at run time.
  162825. */
  162826. #define FIX(x) ((INT32) ((x) * CONST_SCALE + 0.5))
  162827. /* Descale and correctly round an INT32 value that's scaled by N bits.
  162828. * We assume RIGHT_SHIFT rounds towards minus infinity, so adding
  162829. * the fudge factor is correct for either sign of X.
  162830. */
  162831. #define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n)
  162832. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  162833. * This macro is used only when the two inputs will actually be no more than
  162834. * 16 bits wide, so that a 16x16->32 bit multiply can be used instead of a
  162835. * full 32x32 multiply. This provides a useful speedup on many machines.
  162836. * Unfortunately there is no way to specify a 16x16->32 multiply portably
  162837. * in C, but some C compilers will do the right thing if you provide the
  162838. * correct combination of casts.
  162839. */
  162840. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  162841. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT16) (const)))
  162842. #endif
  162843. #ifdef SHORTxLCONST_32 /* known to work with Microsoft C 6.0 */
  162844. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT32) (const)))
  162845. #endif
  162846. #ifndef MULTIPLY16C16 /* default definition */
  162847. #define MULTIPLY16C16(var,const) ((var) * (const))
  162848. #endif
  162849. /* Same except both inputs are variables. */
  162850. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  162851. #define MULTIPLY16V16(var1,var2) (((INT16) (var1)) * ((INT16) (var2)))
  162852. #endif
  162853. #ifndef MULTIPLY16V16 /* default definition */
  162854. #define MULTIPLY16V16(var1,var2) ((var1) * (var2))
  162855. #endif
  162856. #endif
  162857. /*** End of inlined file: jdct.h ***/
  162858. /* Private declarations for DCT subsystem */
  162859. /* Private subobject for this module */
  162860. typedef struct {
  162861. struct jpeg_forward_dct pub; /* public fields */
  162862. /* Pointer to the DCT routine actually in use */
  162863. forward_DCT_method_ptr do_dct;
  162864. /* The actual post-DCT divisors --- not identical to the quant table
  162865. * entries, because of scaling (especially for an unnormalized DCT).
  162866. * Each table is given in normal array order.
  162867. */
  162868. DCTELEM * divisors[NUM_QUANT_TBLS];
  162869. #ifdef DCT_FLOAT_SUPPORTED
  162870. /* Same as above for the floating-point case. */
  162871. float_DCT_method_ptr do_float_dct;
  162872. FAST_FLOAT * float_divisors[NUM_QUANT_TBLS];
  162873. #endif
  162874. } my_fdct_controller;
  162875. typedef my_fdct_controller * my_fdct_ptr;
  162876. /*
  162877. * Initialize for a processing pass.
  162878. * Verify that all referenced Q-tables are present, and set up
  162879. * the divisor table for each one.
  162880. * In the current implementation, DCT of all components is done during
  162881. * the first pass, even if only some components will be output in the
  162882. * first scan. Hence all components should be examined here.
  162883. */
  162884. METHODDEF(void)
  162885. start_pass_fdctmgr (j_compress_ptr cinfo)
  162886. {
  162887. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  162888. int ci, qtblno, i;
  162889. jpeg_component_info *compptr;
  162890. JQUANT_TBL * qtbl;
  162891. DCTELEM * dtbl;
  162892. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162893. ci++, compptr++) {
  162894. qtblno = compptr->quant_tbl_no;
  162895. /* Make sure specified quantization table is present */
  162896. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  162897. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  162898. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  162899. qtbl = cinfo->quant_tbl_ptrs[qtblno];
  162900. /* Compute divisors for this quant table */
  162901. /* We may do this more than once for same table, but it's not a big deal */
  162902. switch (cinfo->dct_method) {
  162903. #ifdef DCT_ISLOW_SUPPORTED
  162904. case JDCT_ISLOW:
  162905. /* For LL&M IDCT method, divisors are equal to raw quantization
  162906. * coefficients multiplied by 8 (to counteract scaling).
  162907. */
  162908. if (fdct->divisors[qtblno] == NULL) {
  162909. fdct->divisors[qtblno] = (DCTELEM *)
  162910. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162911. DCTSIZE2 * SIZEOF(DCTELEM));
  162912. }
  162913. dtbl = fdct->divisors[qtblno];
  162914. for (i = 0; i < DCTSIZE2; i++) {
  162915. dtbl[i] = ((DCTELEM) qtbl->quantval[i]) << 3;
  162916. }
  162917. break;
  162918. #endif
  162919. #ifdef DCT_IFAST_SUPPORTED
  162920. case JDCT_IFAST:
  162921. {
  162922. /* For AA&N IDCT method, divisors are equal to quantization
  162923. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  162924. * scalefactor[0] = 1
  162925. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  162926. * We apply a further scale factor of 8.
  162927. */
  162928. #define CONST_BITS 14
  162929. static const INT16 aanscales[DCTSIZE2] = {
  162930. /* precomputed values scaled up by 14 bits */
  162931. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  162932. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  162933. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  162934. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  162935. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  162936. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  162937. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  162938. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  162939. };
  162940. SHIFT_TEMPS
  162941. if (fdct->divisors[qtblno] == NULL) {
  162942. fdct->divisors[qtblno] = (DCTELEM *)
  162943. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162944. DCTSIZE2 * SIZEOF(DCTELEM));
  162945. }
  162946. dtbl = fdct->divisors[qtblno];
  162947. for (i = 0; i < DCTSIZE2; i++) {
  162948. dtbl[i] = (DCTELEM)
  162949. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  162950. (INT32) aanscales[i]),
  162951. CONST_BITS-3);
  162952. }
  162953. }
  162954. break;
  162955. #endif
  162956. #ifdef DCT_FLOAT_SUPPORTED
  162957. case JDCT_FLOAT:
  162958. {
  162959. /* For float AA&N IDCT method, divisors are equal to quantization
  162960. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  162961. * scalefactor[0] = 1
  162962. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  162963. * We apply a further scale factor of 8.
  162964. * What's actually stored is 1/divisor so that the inner loop can
  162965. * use a multiplication rather than a division.
  162966. */
  162967. FAST_FLOAT * fdtbl;
  162968. int row, col;
  162969. static const double aanscalefactor[DCTSIZE] = {
  162970. 1.0, 1.387039845, 1.306562965, 1.175875602,
  162971. 1.0, 0.785694958, 0.541196100, 0.275899379
  162972. };
  162973. if (fdct->float_divisors[qtblno] == NULL) {
  162974. fdct->float_divisors[qtblno] = (FAST_FLOAT *)
  162975. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162976. DCTSIZE2 * SIZEOF(FAST_FLOAT));
  162977. }
  162978. fdtbl = fdct->float_divisors[qtblno];
  162979. i = 0;
  162980. for (row = 0; row < DCTSIZE; row++) {
  162981. for (col = 0; col < DCTSIZE; col++) {
  162982. fdtbl[i] = (FAST_FLOAT)
  162983. (1.0 / (((double) qtbl->quantval[i] *
  162984. aanscalefactor[row] * aanscalefactor[col] * 8.0)));
  162985. i++;
  162986. }
  162987. }
  162988. }
  162989. break;
  162990. #endif
  162991. default:
  162992. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162993. break;
  162994. }
  162995. }
  162996. }
  162997. /*
  162998. * Perform forward DCT on one or more blocks of a component.
  162999. *
  163000. * The input samples are taken from the sample_data[] array starting at
  163001. * position start_row/start_col, and moving to the right for any additional
  163002. * blocks. The quantized coefficients are returned in coef_blocks[].
  163003. */
  163004. METHODDEF(void)
  163005. forward_DCT (j_compress_ptr cinfo, jpeg_component_info * compptr,
  163006. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  163007. JDIMENSION start_row, JDIMENSION start_col,
  163008. JDIMENSION num_blocks)
  163009. /* This version is used for integer DCT implementations. */
  163010. {
  163011. /* This routine is heavily used, so it's worth coding it tightly. */
  163012. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  163013. forward_DCT_method_ptr do_dct = fdct->do_dct;
  163014. DCTELEM * divisors = fdct->divisors[compptr->quant_tbl_no];
  163015. DCTELEM workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  163016. JDIMENSION bi;
  163017. sample_data += start_row; /* fold in the vertical offset once */
  163018. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  163019. /* Load data into workspace, applying unsigned->signed conversion */
  163020. { register DCTELEM *workspaceptr;
  163021. register JSAMPROW elemptr;
  163022. register int elemr;
  163023. workspaceptr = workspace;
  163024. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  163025. elemptr = sample_data[elemr] + start_col;
  163026. #if DCTSIZE == 8 /* unroll the inner loop */
  163027. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163028. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163029. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163030. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163031. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163032. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163033. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163034. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163035. #else
  163036. { register int elemc;
  163037. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  163038. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163039. }
  163040. }
  163041. #endif
  163042. }
  163043. }
  163044. /* Perform the DCT */
  163045. (*do_dct) (workspace);
  163046. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  163047. { register DCTELEM temp, qval;
  163048. register int i;
  163049. register JCOEFPTR output_ptr = coef_blocks[bi];
  163050. for (i = 0; i < DCTSIZE2; i++) {
  163051. qval = divisors[i];
  163052. temp = workspace[i];
  163053. /* Divide the coefficient value by qval, ensuring proper rounding.
  163054. * Since C does not specify the direction of rounding for negative
  163055. * quotients, we have to force the dividend positive for portability.
  163056. *
  163057. * In most files, at least half of the output values will be zero
  163058. * (at default quantization settings, more like three-quarters...)
  163059. * so we should ensure that this case is fast. On many machines,
  163060. * a comparison is enough cheaper than a divide to make a special test
  163061. * a win. Since both inputs will be nonnegative, we need only test
  163062. * for a < b to discover whether a/b is 0.
  163063. * If your machine's division is fast enough, define FAST_DIVIDE.
  163064. */
  163065. #ifdef FAST_DIVIDE
  163066. #define DIVIDE_BY(a,b) a /= b
  163067. #else
  163068. #define DIVIDE_BY(a,b) if (a >= b) a /= b; else a = 0
  163069. #endif
  163070. if (temp < 0) {
  163071. temp = -temp;
  163072. temp += qval>>1; /* for rounding */
  163073. DIVIDE_BY(temp, qval);
  163074. temp = -temp;
  163075. } else {
  163076. temp += qval>>1; /* for rounding */
  163077. DIVIDE_BY(temp, qval);
  163078. }
  163079. output_ptr[i] = (JCOEF) temp;
  163080. }
  163081. }
  163082. }
  163083. }
  163084. #ifdef DCT_FLOAT_SUPPORTED
  163085. METHODDEF(void)
  163086. forward_DCT_float (j_compress_ptr cinfo, jpeg_component_info * compptr,
  163087. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  163088. JDIMENSION start_row, JDIMENSION start_col,
  163089. JDIMENSION num_blocks)
  163090. /* This version is used for floating-point DCT implementations. */
  163091. {
  163092. /* This routine is heavily used, so it's worth coding it tightly. */
  163093. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  163094. float_DCT_method_ptr do_dct = fdct->do_float_dct;
  163095. FAST_FLOAT * divisors = fdct->float_divisors[compptr->quant_tbl_no];
  163096. FAST_FLOAT workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  163097. JDIMENSION bi;
  163098. sample_data += start_row; /* fold in the vertical offset once */
  163099. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  163100. /* Load data into workspace, applying unsigned->signed conversion */
  163101. { register FAST_FLOAT *workspaceptr;
  163102. register JSAMPROW elemptr;
  163103. register int elemr;
  163104. workspaceptr = workspace;
  163105. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  163106. elemptr = sample_data[elemr] + start_col;
  163107. #if DCTSIZE == 8 /* unroll the inner loop */
  163108. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163109. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163110. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163111. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163112. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163113. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163114. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163115. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163116. #else
  163117. { register int elemc;
  163118. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  163119. *workspaceptr++ = (FAST_FLOAT)
  163120. (GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163121. }
  163122. }
  163123. #endif
  163124. }
  163125. }
  163126. /* Perform the DCT */
  163127. (*do_dct) (workspace);
  163128. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  163129. { register FAST_FLOAT temp;
  163130. register int i;
  163131. register JCOEFPTR output_ptr = coef_blocks[bi];
  163132. for (i = 0; i < DCTSIZE2; i++) {
  163133. /* Apply the quantization and scaling factor */
  163134. temp = workspace[i] * divisors[i];
  163135. /* Round to nearest integer.
  163136. * Since C does not specify the direction of rounding for negative
  163137. * quotients, we have to force the dividend positive for portability.
  163138. * The maximum coefficient size is +-16K (for 12-bit data), so this
  163139. * code should work for either 16-bit or 32-bit ints.
  163140. */
  163141. output_ptr[i] = (JCOEF) ((int) (temp + (FAST_FLOAT) 16384.5) - 16384);
  163142. }
  163143. }
  163144. }
  163145. }
  163146. #endif /* DCT_FLOAT_SUPPORTED */
  163147. /*
  163148. * Initialize FDCT manager.
  163149. */
  163150. GLOBAL(void)
  163151. jinit_forward_dct (j_compress_ptr cinfo)
  163152. {
  163153. my_fdct_ptr fdct;
  163154. int i;
  163155. fdct = (my_fdct_ptr)
  163156. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163157. SIZEOF(my_fdct_controller));
  163158. cinfo->fdct = (struct jpeg_forward_dct *) fdct;
  163159. fdct->pub.start_pass = start_pass_fdctmgr;
  163160. switch (cinfo->dct_method) {
  163161. #ifdef DCT_ISLOW_SUPPORTED
  163162. case JDCT_ISLOW:
  163163. fdct->pub.forward_DCT = forward_DCT;
  163164. fdct->do_dct = jpeg_fdct_islow;
  163165. break;
  163166. #endif
  163167. #ifdef DCT_IFAST_SUPPORTED
  163168. case JDCT_IFAST:
  163169. fdct->pub.forward_DCT = forward_DCT;
  163170. fdct->do_dct = jpeg_fdct_ifast;
  163171. break;
  163172. #endif
  163173. #ifdef DCT_FLOAT_SUPPORTED
  163174. case JDCT_FLOAT:
  163175. fdct->pub.forward_DCT = forward_DCT_float;
  163176. fdct->do_float_dct = jpeg_fdct_float;
  163177. break;
  163178. #endif
  163179. default:
  163180. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163181. break;
  163182. }
  163183. /* Mark divisor tables unallocated */
  163184. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  163185. fdct->divisors[i] = NULL;
  163186. #ifdef DCT_FLOAT_SUPPORTED
  163187. fdct->float_divisors[i] = NULL;
  163188. #endif
  163189. }
  163190. }
  163191. /*** End of inlined file: jcdctmgr.c ***/
  163192. #undef CONST_BITS
  163193. /*** Start of inlined file: jchuff.c ***/
  163194. #define JPEG_INTERNALS
  163195. /*** Start of inlined file: jchuff.h ***/
  163196. /* The legal range of a DCT coefficient is
  163197. * -1024 .. +1023 for 8-bit data;
  163198. * -16384 .. +16383 for 12-bit data.
  163199. * Hence the magnitude should always fit in 10 or 14 bits respectively.
  163200. */
  163201. #ifndef _jchuff_h_
  163202. #define _jchuff_h_
  163203. #if BITS_IN_JSAMPLE == 8
  163204. #define MAX_COEF_BITS 10
  163205. #else
  163206. #define MAX_COEF_BITS 14
  163207. #endif
  163208. /* Derived data constructed for each Huffman table */
  163209. typedef struct {
  163210. unsigned int ehufco[256]; /* code for each symbol */
  163211. char ehufsi[256]; /* length of code for each symbol */
  163212. /* If no code has been allocated for a symbol S, ehufsi[S] contains 0 */
  163213. } c_derived_tbl;
  163214. /* Short forms of external names for systems with brain-damaged linkers. */
  163215. #ifdef NEED_SHORT_EXTERNAL_NAMES
  163216. #define jpeg_make_c_derived_tbl jMkCDerived
  163217. #define jpeg_gen_optimal_table jGenOptTbl
  163218. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  163219. /* Expand a Huffman table definition into the derived format */
  163220. EXTERN(void) jpeg_make_c_derived_tbl
  163221. JPP((j_compress_ptr cinfo, boolean isDC, int tblno,
  163222. c_derived_tbl ** pdtbl));
  163223. /* Generate an optimal table definition given the specified counts */
  163224. EXTERN(void) jpeg_gen_optimal_table
  163225. JPP((j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[]));
  163226. #endif
  163227. /*** End of inlined file: jchuff.h ***/
  163228. /* Declarations shared with jcphuff.c */
  163229. /* Expanded entropy encoder object for Huffman encoding.
  163230. *
  163231. * The savable_state subrecord contains fields that change within an MCU,
  163232. * but must not be updated permanently until we complete the MCU.
  163233. */
  163234. typedef struct {
  163235. INT32 put_buffer; /* current bit-accumulation buffer */
  163236. int put_bits; /* # of bits now in it */
  163237. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  163238. } savable_state;
  163239. /* This macro is to work around compilers with missing or broken
  163240. * structure assignment. You'll need to fix this code if you have
  163241. * such a compiler and you change MAX_COMPS_IN_SCAN.
  163242. */
  163243. #ifndef NO_STRUCT_ASSIGN
  163244. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  163245. #else
  163246. #if MAX_COMPS_IN_SCAN == 4
  163247. #define ASSIGN_STATE(dest,src) \
  163248. ((dest).put_buffer = (src).put_buffer, \
  163249. (dest).put_bits = (src).put_bits, \
  163250. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  163251. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  163252. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  163253. (dest).last_dc_val[3] = (src).last_dc_val[3])
  163254. #endif
  163255. #endif
  163256. typedef struct {
  163257. struct jpeg_entropy_encoder pub; /* public fields */
  163258. savable_state saved; /* Bit buffer & DC state at start of MCU */
  163259. /* These fields are NOT loaded into local working state. */
  163260. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  163261. int next_restart_num; /* next restart number to write (0-7) */
  163262. /* Pointers to derived tables (these workspaces have image lifespan) */
  163263. c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  163264. c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  163265. #ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
  163266. long * dc_count_ptrs[NUM_HUFF_TBLS];
  163267. long * ac_count_ptrs[NUM_HUFF_TBLS];
  163268. #endif
  163269. } huff_entropy_encoder;
  163270. typedef huff_entropy_encoder * huff_entropy_ptr;
  163271. /* Working state while writing an MCU.
  163272. * This struct contains all the fields that are needed by subroutines.
  163273. */
  163274. typedef struct {
  163275. JOCTET * next_output_byte; /* => next byte to write in buffer */
  163276. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  163277. savable_state cur; /* Current bit buffer & DC state */
  163278. j_compress_ptr cinfo; /* dump_buffer needs access to this */
  163279. } working_state;
  163280. /* Forward declarations */
  163281. METHODDEF(boolean) encode_mcu_huff JPP((j_compress_ptr cinfo,
  163282. JBLOCKROW *MCU_data));
  163283. METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo));
  163284. #ifdef ENTROPY_OPT_SUPPORTED
  163285. METHODDEF(boolean) encode_mcu_gather JPP((j_compress_ptr cinfo,
  163286. JBLOCKROW *MCU_data));
  163287. METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo));
  163288. #endif
  163289. /*
  163290. * Initialize for a Huffman-compressed scan.
  163291. * If gather_statistics is TRUE, we do not output anything during the scan,
  163292. * just count the Huffman symbols used and generate Huffman code tables.
  163293. */
  163294. METHODDEF(void)
  163295. start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
  163296. {
  163297. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163298. int ci, dctbl, actbl;
  163299. jpeg_component_info * compptr;
  163300. if (gather_statistics) {
  163301. #ifdef ENTROPY_OPT_SUPPORTED
  163302. entropy->pub.encode_mcu = encode_mcu_gather;
  163303. entropy->pub.finish_pass = finish_pass_gather;
  163304. #else
  163305. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163306. #endif
  163307. } else {
  163308. entropy->pub.encode_mcu = encode_mcu_huff;
  163309. entropy->pub.finish_pass = finish_pass_huff;
  163310. }
  163311. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163312. compptr = cinfo->cur_comp_info[ci];
  163313. dctbl = compptr->dc_tbl_no;
  163314. actbl = compptr->ac_tbl_no;
  163315. if (gather_statistics) {
  163316. #ifdef ENTROPY_OPT_SUPPORTED
  163317. /* Check for invalid table indexes */
  163318. /* (make_c_derived_tbl does this in the other path) */
  163319. if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
  163320. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
  163321. if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
  163322. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
  163323. /* Allocate and zero the statistics tables */
  163324. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  163325. if (entropy->dc_count_ptrs[dctbl] == NULL)
  163326. entropy->dc_count_ptrs[dctbl] = (long *)
  163327. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163328. 257 * SIZEOF(long));
  163329. MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
  163330. if (entropy->ac_count_ptrs[actbl] == NULL)
  163331. entropy->ac_count_ptrs[actbl] = (long *)
  163332. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163333. 257 * SIZEOF(long));
  163334. MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
  163335. #endif
  163336. } else {
  163337. /* Compute derived values for Huffman tables */
  163338. /* We may do this more than once for a table, but it's not expensive */
  163339. jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
  163340. & entropy->dc_derived_tbls[dctbl]);
  163341. jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
  163342. & entropy->ac_derived_tbls[actbl]);
  163343. }
  163344. /* Initialize DC predictions to 0 */
  163345. entropy->saved.last_dc_val[ci] = 0;
  163346. }
  163347. /* Initialize bit buffer to empty */
  163348. entropy->saved.put_buffer = 0;
  163349. entropy->saved.put_bits = 0;
  163350. /* Initialize restart stuff */
  163351. entropy->restarts_to_go = cinfo->restart_interval;
  163352. entropy->next_restart_num = 0;
  163353. }
  163354. /*
  163355. * Compute the derived values for a Huffman table.
  163356. * This routine also performs some validation checks on the table.
  163357. *
  163358. * Note this is also used by jcphuff.c.
  163359. */
  163360. GLOBAL(void)
  163361. jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
  163362. c_derived_tbl ** pdtbl)
  163363. {
  163364. JHUFF_TBL *htbl;
  163365. c_derived_tbl *dtbl;
  163366. int p, i, l, lastp, si, maxsymbol;
  163367. char huffsize[257];
  163368. unsigned int huffcode[257];
  163369. unsigned int code;
  163370. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  163371. * paralleling the order of the symbols themselves in htbl->huffval[].
  163372. */
  163373. /* Find the input Huffman table */
  163374. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  163375. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  163376. htbl =
  163377. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  163378. if (htbl == NULL)
  163379. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  163380. /* Allocate a workspace if we haven't already done so. */
  163381. if (*pdtbl == NULL)
  163382. *pdtbl = (c_derived_tbl *)
  163383. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163384. SIZEOF(c_derived_tbl));
  163385. dtbl = *pdtbl;
  163386. /* Figure C.1: make table of Huffman code length for each symbol */
  163387. p = 0;
  163388. for (l = 1; l <= 16; l++) {
  163389. i = (int) htbl->bits[l];
  163390. if (i < 0 || p + i > 256) /* protect against table overrun */
  163391. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163392. while (i--)
  163393. huffsize[p++] = (char) l;
  163394. }
  163395. huffsize[p] = 0;
  163396. lastp = p;
  163397. /* Figure C.2: generate the codes themselves */
  163398. /* We also validate that the counts represent a legal Huffman code tree. */
  163399. code = 0;
  163400. si = huffsize[0];
  163401. p = 0;
  163402. while (huffsize[p]) {
  163403. while (((int) huffsize[p]) == si) {
  163404. huffcode[p++] = code;
  163405. code++;
  163406. }
  163407. /* code is now 1 more than the last code used for codelength si; but
  163408. * it must still fit in si bits, since no code is allowed to be all ones.
  163409. */
  163410. if (((INT32) code) >= (((INT32) 1) << si))
  163411. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163412. code <<= 1;
  163413. si++;
  163414. }
  163415. /* Figure C.3: generate encoding tables */
  163416. /* These are code and size indexed by symbol value */
  163417. /* Set all codeless symbols to have code length 0;
  163418. * this lets us detect duplicate VAL entries here, and later
  163419. * allows emit_bits to detect any attempt to emit such symbols.
  163420. */
  163421. MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));
  163422. /* This is also a convenient place to check for out-of-range
  163423. * and duplicated VAL entries. We allow 0..255 for AC symbols
  163424. * but only 0..15 for DC. (We could constrain them further
  163425. * based on data depth and mode, but this seems enough.)
  163426. */
  163427. maxsymbol = isDC ? 15 : 255;
  163428. for (p = 0; p < lastp; p++) {
  163429. i = htbl->huffval[p];
  163430. if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
  163431. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163432. dtbl->ehufco[i] = huffcode[p];
  163433. dtbl->ehufsi[i] = huffsize[p];
  163434. }
  163435. }
  163436. /* Outputting bytes to the file */
  163437. /* Emit a byte, taking 'action' if must suspend. */
  163438. #define emit_byte(state,val,action) \
  163439. { *(state)->next_output_byte++ = (JOCTET) (val); \
  163440. if (--(state)->free_in_buffer == 0) \
  163441. if (! dump_buffer(state)) \
  163442. { action; } }
  163443. LOCAL(boolean)
  163444. dump_buffer (working_state * state)
  163445. /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
  163446. {
  163447. struct jpeg_destination_mgr * dest = state->cinfo->dest;
  163448. if (! (*dest->empty_output_buffer) (state->cinfo))
  163449. return FALSE;
  163450. /* After a successful buffer dump, must reset buffer pointers */
  163451. state->next_output_byte = dest->next_output_byte;
  163452. state->free_in_buffer = dest->free_in_buffer;
  163453. return TRUE;
  163454. }
  163455. /* Outputting bits to the file */
  163456. /* Only the right 24 bits of put_buffer are used; the valid bits are
  163457. * left-justified in this part. At most 16 bits can be passed to emit_bits
  163458. * in one call, and we never retain more than 7 bits in put_buffer
  163459. * between calls, so 24 bits are sufficient.
  163460. */
  163461. INLINE
  163462. LOCAL(boolean)
  163463. emit_bits (working_state * state, unsigned int code, int size)
  163464. /* Emit some bits; return TRUE if successful, FALSE if must suspend */
  163465. {
  163466. /* This routine is heavily used, so it's worth coding tightly. */
  163467. register INT32 put_buffer = (INT32) code;
  163468. register int put_bits = state->cur.put_bits;
  163469. /* if size is 0, caller used an invalid Huffman table entry */
  163470. if (size == 0)
  163471. ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
  163472. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  163473. put_bits += size; /* new number of bits in buffer */
  163474. put_buffer <<= 24 - put_bits; /* align incoming bits */
  163475. put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
  163476. while (put_bits >= 8) {
  163477. int c = (int) ((put_buffer >> 16) & 0xFF);
  163478. emit_byte(state, c, return FALSE);
  163479. if (c == 0xFF) { /* need to stuff a zero byte? */
  163480. emit_byte(state, 0, return FALSE);
  163481. }
  163482. put_buffer <<= 8;
  163483. put_bits -= 8;
  163484. }
  163485. state->cur.put_buffer = put_buffer; /* update state variables */
  163486. state->cur.put_bits = put_bits;
  163487. return TRUE;
  163488. }
  163489. LOCAL(boolean)
  163490. flush_bits (working_state * state)
  163491. {
  163492. if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */
  163493. return FALSE;
  163494. state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
  163495. state->cur.put_bits = 0;
  163496. return TRUE;
  163497. }
  163498. /* Encode a single block's worth of coefficients */
  163499. LOCAL(boolean)
  163500. encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
  163501. c_derived_tbl *dctbl, c_derived_tbl *actbl)
  163502. {
  163503. register int temp, temp2;
  163504. register int nbits;
  163505. register int k, r, i;
  163506. /* Encode the DC coefficient difference per section F.1.2.1 */
  163507. temp = temp2 = block[0] - last_dc_val;
  163508. if (temp < 0) {
  163509. temp = -temp; /* temp is abs value of input */
  163510. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  163511. /* This code assumes we are on a two's complement machine */
  163512. temp2--;
  163513. }
  163514. /* Find the number of bits needed for the magnitude of the coefficient */
  163515. nbits = 0;
  163516. while (temp) {
  163517. nbits++;
  163518. temp >>= 1;
  163519. }
  163520. /* Check for out-of-range coefficient values.
  163521. * Since we're encoding a difference, the range limit is twice as much.
  163522. */
  163523. if (nbits > MAX_COEF_BITS+1)
  163524. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  163525. /* Emit the Huffman-coded symbol for the number of bits */
  163526. if (! emit_bits(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
  163527. return FALSE;
  163528. /* Emit that number of bits of the value, if positive, */
  163529. /* or the complement of its magnitude, if negative. */
  163530. if (nbits) /* emit_bits rejects calls with size 0 */
  163531. if (! emit_bits(state, (unsigned int) temp2, nbits))
  163532. return FALSE;
  163533. /* Encode the AC coefficients per section F.1.2.2 */
  163534. r = 0; /* r = run length of zeros */
  163535. for (k = 1; k < DCTSIZE2; k++) {
  163536. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  163537. r++;
  163538. } else {
  163539. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  163540. while (r > 15) {
  163541. if (! emit_bits(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
  163542. return FALSE;
  163543. r -= 16;
  163544. }
  163545. temp2 = temp;
  163546. if (temp < 0) {
  163547. temp = -temp; /* temp is abs value of input */
  163548. /* This code assumes we are on a two's complement machine */
  163549. temp2--;
  163550. }
  163551. /* Find the number of bits needed for the magnitude of the coefficient */
  163552. nbits = 1; /* there must be at least one 1 bit */
  163553. while ((temp >>= 1))
  163554. nbits++;
  163555. /* Check for out-of-range coefficient values */
  163556. if (nbits > MAX_COEF_BITS)
  163557. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  163558. /* Emit Huffman symbol for run length / number of bits */
  163559. i = (r << 4) + nbits;
  163560. if (! emit_bits(state, actbl->ehufco[i], actbl->ehufsi[i]))
  163561. return FALSE;
  163562. /* Emit that number of bits of the value, if positive, */
  163563. /* or the complement of its magnitude, if negative. */
  163564. if (! emit_bits(state, (unsigned int) temp2, nbits))
  163565. return FALSE;
  163566. r = 0;
  163567. }
  163568. }
  163569. /* If the last coef(s) were zero, emit an end-of-block code */
  163570. if (r > 0)
  163571. if (! emit_bits(state, actbl->ehufco[0], actbl->ehufsi[0]))
  163572. return FALSE;
  163573. return TRUE;
  163574. }
  163575. /*
  163576. * Emit a restart marker & resynchronize predictions.
  163577. */
  163578. LOCAL(boolean)
  163579. emit_restart (working_state * state, int restart_num)
  163580. {
  163581. int ci;
  163582. if (! flush_bits(state))
  163583. return FALSE;
  163584. emit_byte(state, 0xFF, return FALSE);
  163585. emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
  163586. /* Re-initialize DC predictions to 0 */
  163587. for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
  163588. state->cur.last_dc_val[ci] = 0;
  163589. /* The restart counter is not updated until we successfully write the MCU. */
  163590. return TRUE;
  163591. }
  163592. /*
  163593. * Encode and output one MCU's worth of Huffman-compressed coefficients.
  163594. */
  163595. METHODDEF(boolean)
  163596. encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  163597. {
  163598. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163599. working_state state;
  163600. int blkn, ci;
  163601. jpeg_component_info * compptr;
  163602. /* Load up working state */
  163603. state.next_output_byte = cinfo->dest->next_output_byte;
  163604. state.free_in_buffer = cinfo->dest->free_in_buffer;
  163605. ASSIGN_STATE(state.cur, entropy->saved);
  163606. state.cinfo = cinfo;
  163607. /* Emit restart marker if needed */
  163608. if (cinfo->restart_interval) {
  163609. if (entropy->restarts_to_go == 0)
  163610. if (! emit_restart(&state, entropy->next_restart_num))
  163611. return FALSE;
  163612. }
  163613. /* Encode the MCU data blocks */
  163614. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  163615. ci = cinfo->MCU_membership[blkn];
  163616. compptr = cinfo->cur_comp_info[ci];
  163617. if (! encode_one_block(&state,
  163618. MCU_data[blkn][0], state.cur.last_dc_val[ci],
  163619. entropy->dc_derived_tbls[compptr->dc_tbl_no],
  163620. entropy->ac_derived_tbls[compptr->ac_tbl_no]))
  163621. return FALSE;
  163622. /* Update last_dc_val */
  163623. state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
  163624. }
  163625. /* Completed MCU, so update state */
  163626. cinfo->dest->next_output_byte = state.next_output_byte;
  163627. cinfo->dest->free_in_buffer = state.free_in_buffer;
  163628. ASSIGN_STATE(entropy->saved, state.cur);
  163629. /* Update restart-interval state too */
  163630. if (cinfo->restart_interval) {
  163631. if (entropy->restarts_to_go == 0) {
  163632. entropy->restarts_to_go = cinfo->restart_interval;
  163633. entropy->next_restart_num++;
  163634. entropy->next_restart_num &= 7;
  163635. }
  163636. entropy->restarts_to_go--;
  163637. }
  163638. return TRUE;
  163639. }
  163640. /*
  163641. * Finish up at the end of a Huffman-compressed scan.
  163642. */
  163643. METHODDEF(void)
  163644. finish_pass_huff (j_compress_ptr cinfo)
  163645. {
  163646. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163647. working_state state;
  163648. /* Load up working state ... flush_bits needs it */
  163649. state.next_output_byte = cinfo->dest->next_output_byte;
  163650. state.free_in_buffer = cinfo->dest->free_in_buffer;
  163651. ASSIGN_STATE(state.cur, entropy->saved);
  163652. state.cinfo = cinfo;
  163653. /* Flush out the last data */
  163654. if (! flush_bits(&state))
  163655. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  163656. /* Update state */
  163657. cinfo->dest->next_output_byte = state.next_output_byte;
  163658. cinfo->dest->free_in_buffer = state.free_in_buffer;
  163659. ASSIGN_STATE(entropy->saved, state.cur);
  163660. }
  163661. /*
  163662. * Huffman coding optimization.
  163663. *
  163664. * We first scan the supplied data and count the number of uses of each symbol
  163665. * that is to be Huffman-coded. (This process MUST agree with the code above.)
  163666. * Then we build a Huffman coding tree for the observed counts.
  163667. * Symbols which are not needed at all for the particular image are not
  163668. * assigned any code, which saves space in the DHT marker as well as in
  163669. * the compressed data.
  163670. */
  163671. #ifdef ENTROPY_OPT_SUPPORTED
  163672. /* Process a single block's worth of coefficients */
  163673. LOCAL(void)
  163674. htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
  163675. long dc_counts[], long ac_counts[])
  163676. {
  163677. register int temp;
  163678. register int nbits;
  163679. register int k, r;
  163680. /* Encode the DC coefficient difference per section F.1.2.1 */
  163681. temp = block[0] - last_dc_val;
  163682. if (temp < 0)
  163683. temp = -temp;
  163684. /* Find the number of bits needed for the magnitude of the coefficient */
  163685. nbits = 0;
  163686. while (temp) {
  163687. nbits++;
  163688. temp >>= 1;
  163689. }
  163690. /* Check for out-of-range coefficient values.
  163691. * Since we're encoding a difference, the range limit is twice as much.
  163692. */
  163693. if (nbits > MAX_COEF_BITS+1)
  163694. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  163695. /* Count the Huffman symbol for the number of bits */
  163696. dc_counts[nbits]++;
  163697. /* Encode the AC coefficients per section F.1.2.2 */
  163698. r = 0; /* r = run length of zeros */
  163699. for (k = 1; k < DCTSIZE2; k++) {
  163700. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  163701. r++;
  163702. } else {
  163703. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  163704. while (r > 15) {
  163705. ac_counts[0xF0]++;
  163706. r -= 16;
  163707. }
  163708. /* Find the number of bits needed for the magnitude of the coefficient */
  163709. if (temp < 0)
  163710. temp = -temp;
  163711. /* Find the number of bits needed for the magnitude of the coefficient */
  163712. nbits = 1; /* there must be at least one 1 bit */
  163713. while ((temp >>= 1))
  163714. nbits++;
  163715. /* Check for out-of-range coefficient values */
  163716. if (nbits > MAX_COEF_BITS)
  163717. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  163718. /* Count Huffman symbol for run length / number of bits */
  163719. ac_counts[(r << 4) + nbits]++;
  163720. r = 0;
  163721. }
  163722. }
  163723. /* If the last coef(s) were zero, emit an end-of-block code */
  163724. if (r > 0)
  163725. ac_counts[0]++;
  163726. }
  163727. /*
  163728. * Trial-encode one MCU's worth of Huffman-compressed coefficients.
  163729. * No data is actually output, so no suspension return is possible.
  163730. */
  163731. METHODDEF(boolean)
  163732. encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  163733. {
  163734. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163735. int blkn, ci;
  163736. jpeg_component_info * compptr;
  163737. /* Take care of restart intervals if needed */
  163738. if (cinfo->restart_interval) {
  163739. if (entropy->restarts_to_go == 0) {
  163740. /* Re-initialize DC predictions to 0 */
  163741. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  163742. entropy->saved.last_dc_val[ci] = 0;
  163743. /* Update restart state */
  163744. entropy->restarts_to_go = cinfo->restart_interval;
  163745. }
  163746. entropy->restarts_to_go--;
  163747. }
  163748. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  163749. ci = cinfo->MCU_membership[blkn];
  163750. compptr = cinfo->cur_comp_info[ci];
  163751. htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
  163752. entropy->dc_count_ptrs[compptr->dc_tbl_no],
  163753. entropy->ac_count_ptrs[compptr->ac_tbl_no]);
  163754. entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
  163755. }
  163756. return TRUE;
  163757. }
  163758. /*
  163759. * Generate the best Huffman code table for the given counts, fill htbl.
  163760. * Note this is also used by jcphuff.c.
  163761. *
  163762. * The JPEG standard requires that no symbol be assigned a codeword of all
  163763. * one bits (so that padding bits added at the end of a compressed segment
  163764. * can't look like a valid code). Because of the canonical ordering of
  163765. * codewords, this just means that there must be an unused slot in the
  163766. * longest codeword length category. Section K.2 of the JPEG spec suggests
  163767. * reserving such a slot by pretending that symbol 256 is a valid symbol
  163768. * with count 1. In theory that's not optimal; giving it count zero but
  163769. * including it in the symbol set anyway should give a better Huffman code.
  163770. * But the theoretically better code actually seems to come out worse in
  163771. * practice, because it produces more all-ones bytes (which incur stuffed
  163772. * zero bytes in the final file). In any case the difference is tiny.
  163773. *
  163774. * The JPEG standard requires Huffman codes to be no more than 16 bits long.
  163775. * If some symbols have a very small but nonzero probability, the Huffman tree
  163776. * must be adjusted to meet the code length restriction. We currently use
  163777. * the adjustment method suggested in JPEG section K.2. This method is *not*
  163778. * optimal; it may not choose the best possible limited-length code. But
  163779. * typically only very-low-frequency symbols will be given less-than-optimal
  163780. * lengths, so the code is almost optimal. Experimental comparisons against
  163781. * an optimal limited-length-code algorithm indicate that the difference is
  163782. * microscopic --- usually less than a hundredth of a percent of total size.
  163783. * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
  163784. */
  163785. GLOBAL(void)
  163786. jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
  163787. {
  163788. #define MAX_CLEN 32 /* assumed maximum initial code length */
  163789. UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */
  163790. int codesize[257]; /* codesize[k] = code length of symbol k */
  163791. int others[257]; /* next symbol in current branch of tree */
  163792. int c1, c2;
  163793. int p, i, j;
  163794. long v;
  163795. /* This algorithm is explained in section K.2 of the JPEG standard */
  163796. MEMZERO(bits, SIZEOF(bits));
  163797. MEMZERO(codesize, SIZEOF(codesize));
  163798. for (i = 0; i < 257; i++)
  163799. others[i] = -1; /* init links to empty */
  163800. freq[256] = 1; /* make sure 256 has a nonzero count */
  163801. /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
  163802. * that no real symbol is given code-value of all ones, because 256
  163803. * will be placed last in the largest codeword category.
  163804. */
  163805. /* Huffman's basic algorithm to assign optimal code lengths to symbols */
  163806. for (;;) {
  163807. /* Find the smallest nonzero frequency, set c1 = its symbol */
  163808. /* In case of ties, take the larger symbol number */
  163809. c1 = -1;
  163810. v = 1000000000L;
  163811. for (i = 0; i <= 256; i++) {
  163812. if (freq[i] && freq[i] <= v) {
  163813. v = freq[i];
  163814. c1 = i;
  163815. }
  163816. }
  163817. /* Find the next smallest nonzero frequency, set c2 = its symbol */
  163818. /* In case of ties, take the larger symbol number */
  163819. c2 = -1;
  163820. v = 1000000000L;
  163821. for (i = 0; i <= 256; i++) {
  163822. if (freq[i] && freq[i] <= v && i != c1) {
  163823. v = freq[i];
  163824. c2 = i;
  163825. }
  163826. }
  163827. /* Done if we've merged everything into one frequency */
  163828. if (c2 < 0)
  163829. break;
  163830. /* Else merge the two counts/trees */
  163831. freq[c1] += freq[c2];
  163832. freq[c2] = 0;
  163833. /* Increment the codesize of everything in c1's tree branch */
  163834. codesize[c1]++;
  163835. while (others[c1] >= 0) {
  163836. c1 = others[c1];
  163837. codesize[c1]++;
  163838. }
  163839. others[c1] = c2; /* chain c2 onto c1's tree branch */
  163840. /* Increment the codesize of everything in c2's tree branch */
  163841. codesize[c2]++;
  163842. while (others[c2] >= 0) {
  163843. c2 = others[c2];
  163844. codesize[c2]++;
  163845. }
  163846. }
  163847. /* Now count the number of symbols of each code length */
  163848. for (i = 0; i <= 256; i++) {
  163849. if (codesize[i]) {
  163850. /* The JPEG standard seems to think that this can't happen, */
  163851. /* but I'm paranoid... */
  163852. if (codesize[i] > MAX_CLEN)
  163853. ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
  163854. bits[codesize[i]]++;
  163855. }
  163856. }
  163857. /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
  163858. * Huffman procedure assigned any such lengths, we must adjust the coding.
  163859. * Here is what the JPEG spec says about how this next bit works:
  163860. * Since symbols are paired for the longest Huffman code, the symbols are
  163861. * removed from this length category two at a time. The prefix for the pair
  163862. * (which is one bit shorter) is allocated to one of the pair; then,
  163863. * skipping the BITS entry for that prefix length, a code word from the next
  163864. * shortest nonzero BITS entry is converted into a prefix for two code words
  163865. * one bit longer.
  163866. */
  163867. for (i = MAX_CLEN; i > 16; i--) {
  163868. while (bits[i] > 0) {
  163869. j = i - 2; /* find length of new prefix to be used */
  163870. while (bits[j] == 0)
  163871. j--;
  163872. bits[i] -= 2; /* remove two symbols */
  163873. bits[i-1]++; /* one goes in this length */
  163874. bits[j+1] += 2; /* two new symbols in this length */
  163875. bits[j]--; /* symbol of this length is now a prefix */
  163876. }
  163877. }
  163878. /* Remove the count for the pseudo-symbol 256 from the largest codelength */
  163879. while (bits[i] == 0) /* find largest codelength still in use */
  163880. i--;
  163881. bits[i]--;
  163882. /* Return final symbol counts (only for lengths 0..16) */
  163883. MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
  163884. /* Return a list of the symbols sorted by code length */
  163885. /* It's not real clear to me why we don't need to consider the codelength
  163886. * changes made above, but the JPEG spec seems to think this works.
  163887. */
  163888. p = 0;
  163889. for (i = 1; i <= MAX_CLEN; i++) {
  163890. for (j = 0; j <= 255; j++) {
  163891. if (codesize[j] == i) {
  163892. htbl->huffval[p] = (UINT8) j;
  163893. p++;
  163894. }
  163895. }
  163896. }
  163897. /* Set sent_table FALSE so updated table will be written to JPEG file. */
  163898. htbl->sent_table = FALSE;
  163899. }
  163900. /*
  163901. * Finish up a statistics-gathering pass and create the new Huffman tables.
  163902. */
  163903. METHODDEF(void)
  163904. finish_pass_gather (j_compress_ptr cinfo)
  163905. {
  163906. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163907. int ci, dctbl, actbl;
  163908. jpeg_component_info * compptr;
  163909. JHUFF_TBL **htblptr;
  163910. boolean did_dc[NUM_HUFF_TBLS];
  163911. boolean did_ac[NUM_HUFF_TBLS];
  163912. /* It's important not to apply jpeg_gen_optimal_table more than once
  163913. * per table, because it clobbers the input frequency counts!
  163914. */
  163915. MEMZERO(did_dc, SIZEOF(did_dc));
  163916. MEMZERO(did_ac, SIZEOF(did_ac));
  163917. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163918. compptr = cinfo->cur_comp_info[ci];
  163919. dctbl = compptr->dc_tbl_no;
  163920. actbl = compptr->ac_tbl_no;
  163921. if (! did_dc[dctbl]) {
  163922. htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
  163923. if (*htblptr == NULL)
  163924. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  163925. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
  163926. did_dc[dctbl] = TRUE;
  163927. }
  163928. if (! did_ac[actbl]) {
  163929. htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
  163930. if (*htblptr == NULL)
  163931. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  163932. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
  163933. did_ac[actbl] = TRUE;
  163934. }
  163935. }
  163936. }
  163937. #endif /* ENTROPY_OPT_SUPPORTED */
  163938. /*
  163939. * Module initialization routine for Huffman entropy encoding.
  163940. */
  163941. GLOBAL(void)
  163942. jinit_huff_encoder (j_compress_ptr cinfo)
  163943. {
  163944. huff_entropy_ptr entropy;
  163945. int i;
  163946. entropy = (huff_entropy_ptr)
  163947. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163948. SIZEOF(huff_entropy_encoder));
  163949. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  163950. entropy->pub.start_pass = start_pass_huff;
  163951. /* Mark tables unallocated */
  163952. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  163953. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  163954. #ifdef ENTROPY_OPT_SUPPORTED
  163955. entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
  163956. #endif
  163957. }
  163958. }
  163959. /*** End of inlined file: jchuff.c ***/
  163960. #undef emit_byte
  163961. /*** Start of inlined file: jcinit.c ***/
  163962. #define JPEG_INTERNALS
  163963. /*
  163964. * Master selection of compression modules.
  163965. * This is done once at the start of processing an image. We determine
  163966. * which modules will be used and give them appropriate initialization calls.
  163967. */
  163968. GLOBAL(void)
  163969. jinit_compress_master (j_compress_ptr cinfo)
  163970. {
  163971. /* Initialize master control (includes parameter checking/processing) */
  163972. jinit_c_master_control(cinfo, FALSE /* full compression */);
  163973. /* Preprocessing */
  163974. if (! cinfo->raw_data_in) {
  163975. jinit_color_converter(cinfo);
  163976. jinit_downsampler(cinfo);
  163977. jinit_c_prep_controller(cinfo, FALSE /* never need full buffer here */);
  163978. }
  163979. /* Forward DCT */
  163980. jinit_forward_dct(cinfo);
  163981. /* Entropy encoding: either Huffman or arithmetic coding. */
  163982. if (cinfo->arith_code) {
  163983. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  163984. } else {
  163985. if (cinfo->progressive_mode) {
  163986. #ifdef C_PROGRESSIVE_SUPPORTED
  163987. jinit_phuff_encoder(cinfo);
  163988. #else
  163989. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163990. #endif
  163991. } else
  163992. jinit_huff_encoder(cinfo);
  163993. }
  163994. /* Need a full-image coefficient buffer in any multi-pass mode. */
  163995. jinit_c_coef_controller(cinfo,
  163996. (boolean) (cinfo->num_scans > 1 || cinfo->optimize_coding));
  163997. jinit_c_main_controller(cinfo, FALSE /* never need full buffer here */);
  163998. jinit_marker_writer(cinfo);
  163999. /* We can now tell the memory manager to allocate virtual arrays. */
  164000. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  164001. /* Write the datastream header (SOI) immediately.
  164002. * Frame and scan headers are postponed till later.
  164003. * This lets application insert special markers after the SOI.
  164004. */
  164005. (*cinfo->marker->write_file_header) (cinfo);
  164006. }
  164007. /*** End of inlined file: jcinit.c ***/
  164008. /*** Start of inlined file: jcmainct.c ***/
  164009. #define JPEG_INTERNALS
  164010. /* Note: currently, there is no operating mode in which a full-image buffer
  164011. * is needed at this step. If there were, that mode could not be used with
  164012. * "raw data" input, since this module is bypassed in that case. However,
  164013. * we've left the code here for possible use in special applications.
  164014. */
  164015. #undef FULL_MAIN_BUFFER_SUPPORTED
  164016. /* Private buffer controller object */
  164017. typedef struct {
  164018. struct jpeg_c_main_controller pub; /* public fields */
  164019. JDIMENSION cur_iMCU_row; /* number of current iMCU row */
  164020. JDIMENSION rowgroup_ctr; /* counts row groups received in iMCU row */
  164021. boolean suspended; /* remember if we suspended output */
  164022. J_BUF_MODE pass_mode; /* current operating mode */
  164023. /* If using just a strip buffer, this points to the entire set of buffers
  164024. * (we allocate one for each component). In the full-image case, this
  164025. * points to the currently accessible strips of the virtual arrays.
  164026. */
  164027. JSAMPARRAY buffer[MAX_COMPONENTS];
  164028. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164029. /* If using full-image storage, this array holds pointers to virtual-array
  164030. * control blocks for each component. Unused if not full-image storage.
  164031. */
  164032. jvirt_sarray_ptr whole_image[MAX_COMPONENTS];
  164033. #endif
  164034. } my_main_controller;
  164035. typedef my_main_controller * my_main_ptr;
  164036. /* Forward declarations */
  164037. METHODDEF(void) process_data_simple_main
  164038. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  164039. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  164040. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164041. METHODDEF(void) process_data_buffer_main
  164042. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  164043. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  164044. #endif
  164045. /*
  164046. * Initialize for a processing pass.
  164047. */
  164048. METHODDEF(void)
  164049. start_pass_main (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  164050. {
  164051. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  164052. /* Do nothing in raw-data mode. */
  164053. if (cinfo->raw_data_in)
  164054. return;
  164055. main_->cur_iMCU_row = 0; /* initialize counters */
  164056. main_->rowgroup_ctr = 0;
  164057. main_->suspended = FALSE;
  164058. main_->pass_mode = pass_mode; /* save mode for use by process_data */
  164059. switch (pass_mode) {
  164060. case JBUF_PASS_THRU:
  164061. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164062. if (main_->whole_image[0] != NULL)
  164063. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164064. #endif
  164065. main_->pub.process_data = process_data_simple_main;
  164066. break;
  164067. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164068. case JBUF_SAVE_SOURCE:
  164069. case JBUF_CRANK_DEST:
  164070. case JBUF_SAVE_AND_PASS:
  164071. if (main_->whole_image[0] == NULL)
  164072. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164073. main_->pub.process_data = process_data_buffer_main;
  164074. break;
  164075. #endif
  164076. default:
  164077. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164078. break;
  164079. }
  164080. }
  164081. /*
  164082. * Process some data.
  164083. * This routine handles the simple pass-through mode,
  164084. * where we have only a strip buffer.
  164085. */
  164086. METHODDEF(void)
  164087. process_data_simple_main (j_compress_ptr cinfo,
  164088. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  164089. JDIMENSION in_rows_avail)
  164090. {
  164091. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  164092. while (main_->cur_iMCU_row < cinfo->total_iMCU_rows) {
  164093. /* Read input data if we haven't filled the main buffer yet */
  164094. if (main_->rowgroup_ctr < DCTSIZE)
  164095. (*cinfo->prep->pre_process_data) (cinfo,
  164096. input_buf, in_row_ctr, in_rows_avail,
  164097. main_->buffer, &main_->rowgroup_ctr,
  164098. (JDIMENSION) DCTSIZE);
  164099. /* If we don't have a full iMCU row buffered, return to application for
  164100. * more data. Note that preprocessor will always pad to fill the iMCU row
  164101. * at the bottom of the image.
  164102. */
  164103. if (main_->rowgroup_ctr != DCTSIZE)
  164104. return;
  164105. /* Send the completed row to the compressor */
  164106. if (! (*cinfo->coef->compress_data) (cinfo, main_->buffer)) {
  164107. /* If compressor did not consume the whole row, then we must need to
  164108. * suspend processing and return to the application. In this situation
  164109. * we pretend we didn't yet consume the last input row; otherwise, if
  164110. * it happened to be the last row of the image, the application would
  164111. * think we were done.
  164112. */
  164113. if (! main_->suspended) {
  164114. (*in_row_ctr)--;
  164115. main_->suspended = TRUE;
  164116. }
  164117. return;
  164118. }
  164119. /* We did finish the row. Undo our little suspension hack if a previous
  164120. * call suspended; then mark the main buffer empty.
  164121. */
  164122. if (main_->suspended) {
  164123. (*in_row_ctr)++;
  164124. main_->suspended = FALSE;
  164125. }
  164126. main_->rowgroup_ctr = 0;
  164127. main_->cur_iMCU_row++;
  164128. }
  164129. }
  164130. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164131. /*
  164132. * Process some data.
  164133. * This routine handles all of the modes that use a full-size buffer.
  164134. */
  164135. METHODDEF(void)
  164136. process_data_buffer_main (j_compress_ptr cinfo,
  164137. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  164138. JDIMENSION in_rows_avail)
  164139. {
  164140. my_main_ptr main = (my_main_ptr) cinfo->main;
  164141. int ci;
  164142. jpeg_component_info *compptr;
  164143. boolean writing = (main->pass_mode != JBUF_CRANK_DEST);
  164144. while (main->cur_iMCU_row < cinfo->total_iMCU_rows) {
  164145. /* Realign the virtual buffers if at the start of an iMCU row. */
  164146. if (main->rowgroup_ctr == 0) {
  164147. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164148. ci++, compptr++) {
  164149. main->buffer[ci] = (*cinfo->mem->access_virt_sarray)
  164150. ((j_common_ptr) cinfo, main->whole_image[ci],
  164151. main->cur_iMCU_row * (compptr->v_samp_factor * DCTSIZE),
  164152. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE), writing);
  164153. }
  164154. /* In a read pass, pretend we just read some source data. */
  164155. if (! writing) {
  164156. *in_row_ctr += cinfo->max_v_samp_factor * DCTSIZE;
  164157. main->rowgroup_ctr = DCTSIZE;
  164158. }
  164159. }
  164160. /* If a write pass, read input data until the current iMCU row is full. */
  164161. /* Note: preprocessor will pad if necessary to fill the last iMCU row. */
  164162. if (writing) {
  164163. (*cinfo->prep->pre_process_data) (cinfo,
  164164. input_buf, in_row_ctr, in_rows_avail,
  164165. main->buffer, &main->rowgroup_ctr,
  164166. (JDIMENSION) DCTSIZE);
  164167. /* Return to application if we need more data to fill the iMCU row. */
  164168. if (main->rowgroup_ctr < DCTSIZE)
  164169. return;
  164170. }
  164171. /* Emit data, unless this is a sink-only pass. */
  164172. if (main->pass_mode != JBUF_SAVE_SOURCE) {
  164173. if (! (*cinfo->coef->compress_data) (cinfo, main->buffer)) {
  164174. /* If compressor did not consume the whole row, then we must need to
  164175. * suspend processing and return to the application. In this situation
  164176. * we pretend we didn't yet consume the last input row; otherwise, if
  164177. * it happened to be the last row of the image, the application would
  164178. * think we were done.
  164179. */
  164180. if (! main->suspended) {
  164181. (*in_row_ctr)--;
  164182. main->suspended = TRUE;
  164183. }
  164184. return;
  164185. }
  164186. /* We did finish the row. Undo our little suspension hack if a previous
  164187. * call suspended; then mark the main buffer empty.
  164188. */
  164189. if (main->suspended) {
  164190. (*in_row_ctr)++;
  164191. main->suspended = FALSE;
  164192. }
  164193. }
  164194. /* If get here, we are done with this iMCU row. Mark buffer empty. */
  164195. main->rowgroup_ctr = 0;
  164196. main->cur_iMCU_row++;
  164197. }
  164198. }
  164199. #endif /* FULL_MAIN_BUFFER_SUPPORTED */
  164200. /*
  164201. * Initialize main buffer controller.
  164202. */
  164203. GLOBAL(void)
  164204. jinit_c_main_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  164205. {
  164206. my_main_ptr main_;
  164207. int ci;
  164208. jpeg_component_info *compptr;
  164209. main_ = (my_main_ptr)
  164210. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164211. SIZEOF(my_main_controller));
  164212. cinfo->main = (struct jpeg_c_main_controller *) main_;
  164213. main_->pub.start_pass = start_pass_main;
  164214. /* We don't need to create a buffer in raw-data mode. */
  164215. if (cinfo->raw_data_in)
  164216. return;
  164217. /* Create the buffer. It holds downsampled data, so each component
  164218. * may be of a different size.
  164219. */
  164220. if (need_full_buffer) {
  164221. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164222. /* Allocate a full-image virtual array for each component */
  164223. /* Note we pad the bottom to a multiple of the iMCU height */
  164224. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164225. ci++, compptr++) {
  164226. main->whole_image[ci] = (*cinfo->mem->request_virt_sarray)
  164227. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  164228. compptr->width_in_blocks * DCTSIZE,
  164229. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  164230. (long) compptr->v_samp_factor) * DCTSIZE,
  164231. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  164232. }
  164233. #else
  164234. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164235. #endif
  164236. } else {
  164237. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164238. main_->whole_image[0] = NULL; /* flag for no virtual arrays */
  164239. #endif
  164240. /* Allocate a strip buffer for each component */
  164241. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164242. ci++, compptr++) {
  164243. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  164244. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164245. compptr->width_in_blocks * DCTSIZE,
  164246. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  164247. }
  164248. }
  164249. }
  164250. /*** End of inlined file: jcmainct.c ***/
  164251. /*** Start of inlined file: jcmarker.c ***/
  164252. #define JPEG_INTERNALS
  164253. /* Private state */
  164254. typedef struct {
  164255. struct jpeg_marker_writer pub; /* public fields */
  164256. unsigned int last_restart_interval; /* last DRI value emitted; 0 after SOI */
  164257. } my_marker_writer;
  164258. typedef my_marker_writer * my_marker_ptr;
  164259. /*
  164260. * Basic output routines.
  164261. *
  164262. * Note that we do not support suspension while writing a marker.
  164263. * Therefore, an application using suspension must ensure that there is
  164264. * enough buffer space for the initial markers (typ. 600-700 bytes) before
  164265. * calling jpeg_start_compress, and enough space to write the trailing EOI
  164266. * (a few bytes) before calling jpeg_finish_compress. Multipass compression
  164267. * modes are not supported at all with suspension, so those two are the only
  164268. * points where markers will be written.
  164269. */
  164270. LOCAL(void)
  164271. emit_byte (j_compress_ptr cinfo, int val)
  164272. /* Emit a byte */
  164273. {
  164274. struct jpeg_destination_mgr * dest = cinfo->dest;
  164275. *(dest->next_output_byte)++ = (JOCTET) val;
  164276. if (--dest->free_in_buffer == 0) {
  164277. if (! (*dest->empty_output_buffer) (cinfo))
  164278. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  164279. }
  164280. }
  164281. LOCAL(void)
  164282. emit_marker (j_compress_ptr cinfo, JPEG_MARKER mark)
  164283. /* Emit a marker code */
  164284. {
  164285. emit_byte(cinfo, 0xFF);
  164286. emit_byte(cinfo, (int) mark);
  164287. }
  164288. LOCAL(void)
  164289. emit_2bytes (j_compress_ptr cinfo, int value)
  164290. /* Emit a 2-byte integer; these are always MSB first in JPEG files */
  164291. {
  164292. emit_byte(cinfo, (value >> 8) & 0xFF);
  164293. emit_byte(cinfo, value & 0xFF);
  164294. }
  164295. /*
  164296. * Routines to write specific marker types.
  164297. */
  164298. LOCAL(int)
  164299. emit_dqt (j_compress_ptr cinfo, int index)
  164300. /* Emit a DQT marker */
  164301. /* Returns the precision used (0 = 8bits, 1 = 16bits) for baseline checking */
  164302. {
  164303. JQUANT_TBL * qtbl = cinfo->quant_tbl_ptrs[index];
  164304. int prec;
  164305. int i;
  164306. if (qtbl == NULL)
  164307. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, index);
  164308. prec = 0;
  164309. for (i = 0; i < DCTSIZE2; i++) {
  164310. if (qtbl->quantval[i] > 255)
  164311. prec = 1;
  164312. }
  164313. if (! qtbl->sent_table) {
  164314. emit_marker(cinfo, M_DQT);
  164315. emit_2bytes(cinfo, prec ? DCTSIZE2*2 + 1 + 2 : DCTSIZE2 + 1 + 2);
  164316. emit_byte(cinfo, index + (prec<<4));
  164317. for (i = 0; i < DCTSIZE2; i++) {
  164318. /* The table entries must be emitted in zigzag order. */
  164319. unsigned int qval = qtbl->quantval[jpeg_natural_order[i]];
  164320. if (prec)
  164321. emit_byte(cinfo, (int) (qval >> 8));
  164322. emit_byte(cinfo, (int) (qval & 0xFF));
  164323. }
  164324. qtbl->sent_table = TRUE;
  164325. }
  164326. return prec;
  164327. }
  164328. LOCAL(void)
  164329. emit_dht (j_compress_ptr cinfo, int index, boolean is_ac)
  164330. /* Emit a DHT marker */
  164331. {
  164332. JHUFF_TBL * htbl;
  164333. int length, i;
  164334. if (is_ac) {
  164335. htbl = cinfo->ac_huff_tbl_ptrs[index];
  164336. index += 0x10; /* output index has AC bit set */
  164337. } else {
  164338. htbl = cinfo->dc_huff_tbl_ptrs[index];
  164339. }
  164340. if (htbl == NULL)
  164341. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, index);
  164342. if (! htbl->sent_table) {
  164343. emit_marker(cinfo, M_DHT);
  164344. length = 0;
  164345. for (i = 1; i <= 16; i++)
  164346. length += htbl->bits[i];
  164347. emit_2bytes(cinfo, length + 2 + 1 + 16);
  164348. emit_byte(cinfo, index);
  164349. for (i = 1; i <= 16; i++)
  164350. emit_byte(cinfo, htbl->bits[i]);
  164351. for (i = 0; i < length; i++)
  164352. emit_byte(cinfo, htbl->huffval[i]);
  164353. htbl->sent_table = TRUE;
  164354. }
  164355. }
  164356. LOCAL(void)
  164357. emit_dac (j_compress_ptr)
  164358. /* Emit a DAC marker */
  164359. /* Since the useful info is so small, we want to emit all the tables in */
  164360. /* one DAC marker. Therefore this routine does its own scan of the table. */
  164361. {
  164362. #ifdef C_ARITH_CODING_SUPPORTED
  164363. char dc_in_use[NUM_ARITH_TBLS];
  164364. char ac_in_use[NUM_ARITH_TBLS];
  164365. int length, i;
  164366. jpeg_component_info *compptr;
  164367. for (i = 0; i < NUM_ARITH_TBLS; i++)
  164368. dc_in_use[i] = ac_in_use[i] = 0;
  164369. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164370. compptr = cinfo->cur_comp_info[i];
  164371. dc_in_use[compptr->dc_tbl_no] = 1;
  164372. ac_in_use[compptr->ac_tbl_no] = 1;
  164373. }
  164374. length = 0;
  164375. for (i = 0; i < NUM_ARITH_TBLS; i++)
  164376. length += dc_in_use[i] + ac_in_use[i];
  164377. emit_marker(cinfo, M_DAC);
  164378. emit_2bytes(cinfo, length*2 + 2);
  164379. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  164380. if (dc_in_use[i]) {
  164381. emit_byte(cinfo, i);
  164382. emit_byte(cinfo, cinfo->arith_dc_L[i] + (cinfo->arith_dc_U[i]<<4));
  164383. }
  164384. if (ac_in_use[i]) {
  164385. emit_byte(cinfo, i + 0x10);
  164386. emit_byte(cinfo, cinfo->arith_ac_K[i]);
  164387. }
  164388. }
  164389. #endif /* C_ARITH_CODING_SUPPORTED */
  164390. }
  164391. LOCAL(void)
  164392. emit_dri (j_compress_ptr cinfo)
  164393. /* Emit a DRI marker */
  164394. {
  164395. emit_marker(cinfo, M_DRI);
  164396. emit_2bytes(cinfo, 4); /* fixed length */
  164397. emit_2bytes(cinfo, (int) cinfo->restart_interval);
  164398. }
  164399. LOCAL(void)
  164400. emit_sof (j_compress_ptr cinfo, JPEG_MARKER code)
  164401. /* Emit a SOF marker */
  164402. {
  164403. int ci;
  164404. jpeg_component_info *compptr;
  164405. emit_marker(cinfo, code);
  164406. emit_2bytes(cinfo, 3 * cinfo->num_components + 2 + 5 + 1); /* length */
  164407. /* Make sure image isn't bigger than SOF field can handle */
  164408. if ((long) cinfo->image_height > 65535L ||
  164409. (long) cinfo->image_width > 65535L)
  164410. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) 65535);
  164411. emit_byte(cinfo, cinfo->data_precision);
  164412. emit_2bytes(cinfo, (int) cinfo->image_height);
  164413. emit_2bytes(cinfo, (int) cinfo->image_width);
  164414. emit_byte(cinfo, cinfo->num_components);
  164415. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164416. ci++, compptr++) {
  164417. emit_byte(cinfo, compptr->component_id);
  164418. emit_byte(cinfo, (compptr->h_samp_factor << 4) + compptr->v_samp_factor);
  164419. emit_byte(cinfo, compptr->quant_tbl_no);
  164420. }
  164421. }
  164422. LOCAL(void)
  164423. emit_sos (j_compress_ptr cinfo)
  164424. /* Emit a SOS marker */
  164425. {
  164426. int i, td, ta;
  164427. jpeg_component_info *compptr;
  164428. emit_marker(cinfo, M_SOS);
  164429. emit_2bytes(cinfo, 2 * cinfo->comps_in_scan + 2 + 1 + 3); /* length */
  164430. emit_byte(cinfo, cinfo->comps_in_scan);
  164431. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164432. compptr = cinfo->cur_comp_info[i];
  164433. emit_byte(cinfo, compptr->component_id);
  164434. td = compptr->dc_tbl_no;
  164435. ta = compptr->ac_tbl_no;
  164436. if (cinfo->progressive_mode) {
  164437. /* Progressive mode: only DC or only AC tables are used in one scan;
  164438. * furthermore, Huffman coding of DC refinement uses no table at all.
  164439. * We emit 0 for unused field(s); this is recommended by the P&M text
  164440. * but does not seem to be specified in the standard.
  164441. */
  164442. if (cinfo->Ss == 0) {
  164443. ta = 0; /* DC scan */
  164444. if (cinfo->Ah != 0 && !cinfo->arith_code)
  164445. td = 0; /* no DC table either */
  164446. } else {
  164447. td = 0; /* AC scan */
  164448. }
  164449. }
  164450. emit_byte(cinfo, (td << 4) + ta);
  164451. }
  164452. emit_byte(cinfo, cinfo->Ss);
  164453. emit_byte(cinfo, cinfo->Se);
  164454. emit_byte(cinfo, (cinfo->Ah << 4) + cinfo->Al);
  164455. }
  164456. LOCAL(void)
  164457. emit_jfif_app0 (j_compress_ptr cinfo)
  164458. /* Emit a JFIF-compliant APP0 marker */
  164459. {
  164460. /*
  164461. * Length of APP0 block (2 bytes)
  164462. * Block ID (4 bytes - ASCII "JFIF")
  164463. * Zero byte (1 byte to terminate the ID string)
  164464. * Version Major, Minor (2 bytes - major first)
  164465. * Units (1 byte - 0x00 = none, 0x01 = inch, 0x02 = cm)
  164466. * Xdpu (2 bytes - dots per unit horizontal)
  164467. * Ydpu (2 bytes - dots per unit vertical)
  164468. * Thumbnail X size (1 byte)
  164469. * Thumbnail Y size (1 byte)
  164470. */
  164471. emit_marker(cinfo, M_APP0);
  164472. emit_2bytes(cinfo, 2 + 4 + 1 + 2 + 1 + 2 + 2 + 1 + 1); /* length */
  164473. emit_byte(cinfo, 0x4A); /* Identifier: ASCII "JFIF" */
  164474. emit_byte(cinfo, 0x46);
  164475. emit_byte(cinfo, 0x49);
  164476. emit_byte(cinfo, 0x46);
  164477. emit_byte(cinfo, 0);
  164478. emit_byte(cinfo, cinfo->JFIF_major_version); /* Version fields */
  164479. emit_byte(cinfo, cinfo->JFIF_minor_version);
  164480. emit_byte(cinfo, cinfo->density_unit); /* Pixel size information */
  164481. emit_2bytes(cinfo, (int) cinfo->X_density);
  164482. emit_2bytes(cinfo, (int) cinfo->Y_density);
  164483. emit_byte(cinfo, 0); /* No thumbnail image */
  164484. emit_byte(cinfo, 0);
  164485. }
  164486. LOCAL(void)
  164487. emit_adobe_app14 (j_compress_ptr cinfo)
  164488. /* Emit an Adobe APP14 marker */
  164489. {
  164490. /*
  164491. * Length of APP14 block (2 bytes)
  164492. * Block ID (5 bytes - ASCII "Adobe")
  164493. * Version Number (2 bytes - currently 100)
  164494. * Flags0 (2 bytes - currently 0)
  164495. * Flags1 (2 bytes - currently 0)
  164496. * Color transform (1 byte)
  164497. *
  164498. * Although Adobe TN 5116 mentions Version = 101, all the Adobe files
  164499. * now in circulation seem to use Version = 100, so that's what we write.
  164500. *
  164501. * We write the color transform byte as 1 if the JPEG color space is
  164502. * YCbCr, 2 if it's YCCK, 0 otherwise. Adobe's definition has to do with
  164503. * whether the encoder performed a transformation, which is pretty useless.
  164504. */
  164505. emit_marker(cinfo, M_APP14);
  164506. emit_2bytes(cinfo, 2 + 5 + 2 + 2 + 2 + 1); /* length */
  164507. emit_byte(cinfo, 0x41); /* Identifier: ASCII "Adobe" */
  164508. emit_byte(cinfo, 0x64);
  164509. emit_byte(cinfo, 0x6F);
  164510. emit_byte(cinfo, 0x62);
  164511. emit_byte(cinfo, 0x65);
  164512. emit_2bytes(cinfo, 100); /* Version */
  164513. emit_2bytes(cinfo, 0); /* Flags0 */
  164514. emit_2bytes(cinfo, 0); /* Flags1 */
  164515. switch (cinfo->jpeg_color_space) {
  164516. case JCS_YCbCr:
  164517. emit_byte(cinfo, 1); /* Color transform = 1 */
  164518. break;
  164519. case JCS_YCCK:
  164520. emit_byte(cinfo, 2); /* Color transform = 2 */
  164521. break;
  164522. default:
  164523. emit_byte(cinfo, 0); /* Color transform = 0 */
  164524. break;
  164525. }
  164526. }
  164527. /*
  164528. * These routines allow writing an arbitrary marker with parameters.
  164529. * The only intended use is to emit COM or APPn markers after calling
  164530. * write_file_header and before calling write_frame_header.
  164531. * Other uses are not guaranteed to produce desirable results.
  164532. * Counting the parameter bytes properly is the caller's responsibility.
  164533. */
  164534. METHODDEF(void)
  164535. write_marker_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  164536. /* Emit an arbitrary marker header */
  164537. {
  164538. if (datalen > (unsigned int) 65533) /* safety check */
  164539. ERREXIT(cinfo, JERR_BAD_LENGTH);
  164540. emit_marker(cinfo, (JPEG_MARKER) marker);
  164541. emit_2bytes(cinfo, (int) (datalen + 2)); /* total length */
  164542. }
  164543. METHODDEF(void)
  164544. write_marker_byte (j_compress_ptr cinfo, int val)
  164545. /* Emit one byte of marker parameters following write_marker_header */
  164546. {
  164547. emit_byte(cinfo, val);
  164548. }
  164549. /*
  164550. * Write datastream header.
  164551. * This consists of an SOI and optional APPn markers.
  164552. * We recommend use of the JFIF marker, but not the Adobe marker,
  164553. * when using YCbCr or grayscale data. The JFIF marker should NOT
  164554. * be used for any other JPEG colorspace. The Adobe marker is helpful
  164555. * to distinguish RGB, CMYK, and YCCK colorspaces.
  164556. * Note that an application can write additional header markers after
  164557. * jpeg_start_compress returns.
  164558. */
  164559. METHODDEF(void)
  164560. write_file_header (j_compress_ptr cinfo)
  164561. {
  164562. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  164563. emit_marker(cinfo, M_SOI); /* first the SOI */
  164564. /* SOI is defined to reset restart interval to 0 */
  164565. marker->last_restart_interval = 0;
  164566. if (cinfo->write_JFIF_header) /* next an optional JFIF APP0 */
  164567. emit_jfif_app0(cinfo);
  164568. if (cinfo->write_Adobe_marker) /* next an optional Adobe APP14 */
  164569. emit_adobe_app14(cinfo);
  164570. }
  164571. /*
  164572. * Write frame header.
  164573. * This consists of DQT and SOFn markers.
  164574. * Note that we do not emit the SOF until we have emitted the DQT(s).
  164575. * This avoids compatibility problems with incorrect implementations that
  164576. * try to error-check the quant table numbers as soon as they see the SOF.
  164577. */
  164578. METHODDEF(void)
  164579. write_frame_header (j_compress_ptr cinfo)
  164580. {
  164581. int ci, prec;
  164582. boolean is_baseline;
  164583. jpeg_component_info *compptr;
  164584. /* Emit DQT for each quantization table.
  164585. * Note that emit_dqt() suppresses any duplicate tables.
  164586. */
  164587. prec = 0;
  164588. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164589. ci++, compptr++) {
  164590. prec += emit_dqt(cinfo, compptr->quant_tbl_no);
  164591. }
  164592. /* now prec is nonzero iff there are any 16-bit quant tables. */
  164593. /* Check for a non-baseline specification.
  164594. * Note we assume that Huffman table numbers won't be changed later.
  164595. */
  164596. if (cinfo->arith_code || cinfo->progressive_mode ||
  164597. cinfo->data_precision != 8) {
  164598. is_baseline = FALSE;
  164599. } else {
  164600. is_baseline = TRUE;
  164601. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164602. ci++, compptr++) {
  164603. if (compptr->dc_tbl_no > 1 || compptr->ac_tbl_no > 1)
  164604. is_baseline = FALSE;
  164605. }
  164606. if (prec && is_baseline) {
  164607. is_baseline = FALSE;
  164608. /* If it's baseline except for quantizer size, warn the user */
  164609. TRACEMS(cinfo, 0, JTRC_16BIT_TABLES);
  164610. }
  164611. }
  164612. /* Emit the proper SOF marker */
  164613. if (cinfo->arith_code) {
  164614. emit_sof(cinfo, M_SOF9); /* SOF code for arithmetic coding */
  164615. } else {
  164616. if (cinfo->progressive_mode)
  164617. emit_sof(cinfo, M_SOF2); /* SOF code for progressive Huffman */
  164618. else if (is_baseline)
  164619. emit_sof(cinfo, M_SOF0); /* SOF code for baseline implementation */
  164620. else
  164621. emit_sof(cinfo, M_SOF1); /* SOF code for non-baseline Huffman file */
  164622. }
  164623. }
  164624. /*
  164625. * Write scan header.
  164626. * This consists of DHT or DAC markers, optional DRI, and SOS.
  164627. * Compressed data will be written following the SOS.
  164628. */
  164629. METHODDEF(void)
  164630. write_scan_header (j_compress_ptr cinfo)
  164631. {
  164632. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  164633. int i;
  164634. jpeg_component_info *compptr;
  164635. if (cinfo->arith_code) {
  164636. /* Emit arith conditioning info. We may have some duplication
  164637. * if the file has multiple scans, but it's so small it's hardly
  164638. * worth worrying about.
  164639. */
  164640. emit_dac(cinfo);
  164641. } else {
  164642. /* Emit Huffman tables.
  164643. * Note that emit_dht() suppresses any duplicate tables.
  164644. */
  164645. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164646. compptr = cinfo->cur_comp_info[i];
  164647. if (cinfo->progressive_mode) {
  164648. /* Progressive mode: only DC or only AC tables are used in one scan */
  164649. if (cinfo->Ss == 0) {
  164650. if (cinfo->Ah == 0) /* DC needs no table for refinement scan */
  164651. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  164652. } else {
  164653. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  164654. }
  164655. } else {
  164656. /* Sequential mode: need both DC and AC tables */
  164657. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  164658. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  164659. }
  164660. }
  164661. }
  164662. /* Emit DRI if required --- note that DRI value could change for each scan.
  164663. * We avoid wasting space with unnecessary DRIs, however.
  164664. */
  164665. if (cinfo->restart_interval != marker->last_restart_interval) {
  164666. emit_dri(cinfo);
  164667. marker->last_restart_interval = cinfo->restart_interval;
  164668. }
  164669. emit_sos(cinfo);
  164670. }
  164671. /*
  164672. * Write datastream trailer.
  164673. */
  164674. METHODDEF(void)
  164675. write_file_trailer (j_compress_ptr cinfo)
  164676. {
  164677. emit_marker(cinfo, M_EOI);
  164678. }
  164679. /*
  164680. * Write an abbreviated table-specification datastream.
  164681. * This consists of SOI, DQT and DHT tables, and EOI.
  164682. * Any table that is defined and not marked sent_table = TRUE will be
  164683. * emitted. Note that all tables will be marked sent_table = TRUE at exit.
  164684. */
  164685. METHODDEF(void)
  164686. write_tables_only (j_compress_ptr cinfo)
  164687. {
  164688. int i;
  164689. emit_marker(cinfo, M_SOI);
  164690. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  164691. if (cinfo->quant_tbl_ptrs[i] != NULL)
  164692. (void) emit_dqt(cinfo, i);
  164693. }
  164694. if (! cinfo->arith_code) {
  164695. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  164696. if (cinfo->dc_huff_tbl_ptrs[i] != NULL)
  164697. emit_dht(cinfo, i, FALSE);
  164698. if (cinfo->ac_huff_tbl_ptrs[i] != NULL)
  164699. emit_dht(cinfo, i, TRUE);
  164700. }
  164701. }
  164702. emit_marker(cinfo, M_EOI);
  164703. }
  164704. /*
  164705. * Initialize the marker writer module.
  164706. */
  164707. GLOBAL(void)
  164708. jinit_marker_writer (j_compress_ptr cinfo)
  164709. {
  164710. my_marker_ptr marker;
  164711. /* Create the subobject */
  164712. marker = (my_marker_ptr)
  164713. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164714. SIZEOF(my_marker_writer));
  164715. cinfo->marker = (struct jpeg_marker_writer *) marker;
  164716. /* Initialize method pointers */
  164717. marker->pub.write_file_header = write_file_header;
  164718. marker->pub.write_frame_header = write_frame_header;
  164719. marker->pub.write_scan_header = write_scan_header;
  164720. marker->pub.write_file_trailer = write_file_trailer;
  164721. marker->pub.write_tables_only = write_tables_only;
  164722. marker->pub.write_marker_header = write_marker_header;
  164723. marker->pub.write_marker_byte = write_marker_byte;
  164724. /* Initialize private state */
  164725. marker->last_restart_interval = 0;
  164726. }
  164727. /*** End of inlined file: jcmarker.c ***/
  164728. /*** Start of inlined file: jcmaster.c ***/
  164729. #define JPEG_INTERNALS
  164730. /* Private state */
  164731. typedef enum {
  164732. main_pass, /* input data, also do first output step */
  164733. huff_opt_pass, /* Huffman code optimization pass */
  164734. output_pass /* data output pass */
  164735. } c_pass_type;
  164736. typedef struct {
  164737. struct jpeg_comp_master pub; /* public fields */
  164738. c_pass_type pass_type; /* the type of the current pass */
  164739. int pass_number; /* # of passes completed */
  164740. int total_passes; /* total # of passes needed */
  164741. int scan_number; /* current index in scan_info[] */
  164742. } my_comp_master;
  164743. typedef my_comp_master * my_master_ptr;
  164744. /*
  164745. * Support routines that do various essential calculations.
  164746. */
  164747. LOCAL(void)
  164748. initial_setup (j_compress_ptr cinfo)
  164749. /* Do computations that are needed before master selection phase */
  164750. {
  164751. int ci;
  164752. jpeg_component_info *compptr;
  164753. long samplesperrow;
  164754. JDIMENSION jd_samplesperrow;
  164755. /* Sanity check on image dimensions */
  164756. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  164757. || cinfo->num_components <= 0 || cinfo->input_components <= 0)
  164758. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  164759. /* Make sure image isn't bigger than I can handle */
  164760. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  164761. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  164762. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  164763. /* Width of an input scanline must be representable as JDIMENSION. */
  164764. samplesperrow = (long) cinfo->image_width * (long) cinfo->input_components;
  164765. jd_samplesperrow = (JDIMENSION) samplesperrow;
  164766. if ((long) jd_samplesperrow != samplesperrow)
  164767. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  164768. /* For now, precision must match compiled-in value... */
  164769. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  164770. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  164771. /* Check that number of components won't exceed internal array sizes */
  164772. if (cinfo->num_components > MAX_COMPONENTS)
  164773. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  164774. MAX_COMPONENTS);
  164775. /* Compute maximum sampling factors; check factor validity */
  164776. cinfo->max_h_samp_factor = 1;
  164777. cinfo->max_v_samp_factor = 1;
  164778. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164779. ci++, compptr++) {
  164780. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  164781. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  164782. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  164783. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  164784. compptr->h_samp_factor);
  164785. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  164786. compptr->v_samp_factor);
  164787. }
  164788. /* Compute dimensions of components */
  164789. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164790. ci++, compptr++) {
  164791. /* Fill in the correct component_index value; don't rely on application */
  164792. compptr->component_index = ci;
  164793. /* For compression, we never do DCT scaling. */
  164794. compptr->DCT_scaled_size = DCTSIZE;
  164795. /* Size in DCT blocks */
  164796. compptr->width_in_blocks = (JDIMENSION)
  164797. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  164798. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  164799. compptr->height_in_blocks = (JDIMENSION)
  164800. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  164801. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  164802. /* Size in samples */
  164803. compptr->downsampled_width = (JDIMENSION)
  164804. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  164805. (long) cinfo->max_h_samp_factor);
  164806. compptr->downsampled_height = (JDIMENSION)
  164807. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  164808. (long) cinfo->max_v_samp_factor);
  164809. /* Mark component needed (this flag isn't actually used for compression) */
  164810. compptr->component_needed = TRUE;
  164811. }
  164812. /* Compute number of fully interleaved MCU rows (number of times that
  164813. * main controller will call coefficient controller).
  164814. */
  164815. cinfo->total_iMCU_rows = (JDIMENSION)
  164816. jdiv_round_up((long) cinfo->image_height,
  164817. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  164818. }
  164819. #ifdef C_MULTISCAN_FILES_SUPPORTED
  164820. LOCAL(void)
  164821. validate_script (j_compress_ptr cinfo)
  164822. /* Verify that the scan script in cinfo->scan_info[] is valid; also
  164823. * determine whether it uses progressive JPEG, and set cinfo->progressive_mode.
  164824. */
  164825. {
  164826. const jpeg_scan_info * scanptr;
  164827. int scanno, ncomps, ci, coefi, thisi;
  164828. int Ss, Se, Ah, Al;
  164829. boolean component_sent[MAX_COMPONENTS];
  164830. #ifdef C_PROGRESSIVE_SUPPORTED
  164831. int * last_bitpos_ptr;
  164832. int last_bitpos[MAX_COMPONENTS][DCTSIZE2];
  164833. /* -1 until that coefficient has been seen; then last Al for it */
  164834. #endif
  164835. if (cinfo->num_scans <= 0)
  164836. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, 0);
  164837. /* For sequential JPEG, all scans must have Ss=0, Se=DCTSIZE2-1;
  164838. * for progressive JPEG, no scan can have this.
  164839. */
  164840. scanptr = cinfo->scan_info;
  164841. if (scanptr->Ss != 0 || scanptr->Se != DCTSIZE2-1) {
  164842. #ifdef C_PROGRESSIVE_SUPPORTED
  164843. cinfo->progressive_mode = TRUE;
  164844. last_bitpos_ptr = & last_bitpos[0][0];
  164845. for (ci = 0; ci < cinfo->num_components; ci++)
  164846. for (coefi = 0; coefi < DCTSIZE2; coefi++)
  164847. *last_bitpos_ptr++ = -1;
  164848. #else
  164849. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164850. #endif
  164851. } else {
  164852. cinfo->progressive_mode = FALSE;
  164853. for (ci = 0; ci < cinfo->num_components; ci++)
  164854. component_sent[ci] = FALSE;
  164855. }
  164856. for (scanno = 1; scanno <= cinfo->num_scans; scanptr++, scanno++) {
  164857. /* Validate component indexes */
  164858. ncomps = scanptr->comps_in_scan;
  164859. if (ncomps <= 0 || ncomps > MAX_COMPS_IN_SCAN)
  164860. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, ncomps, MAX_COMPS_IN_SCAN);
  164861. for (ci = 0; ci < ncomps; ci++) {
  164862. thisi = scanptr->component_index[ci];
  164863. if (thisi < 0 || thisi >= cinfo->num_components)
  164864. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  164865. /* Components must appear in SOF order within each scan */
  164866. if (ci > 0 && thisi <= scanptr->component_index[ci-1])
  164867. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  164868. }
  164869. /* Validate progression parameters */
  164870. Ss = scanptr->Ss;
  164871. Se = scanptr->Se;
  164872. Ah = scanptr->Ah;
  164873. Al = scanptr->Al;
  164874. if (cinfo->progressive_mode) {
  164875. #ifdef C_PROGRESSIVE_SUPPORTED
  164876. /* The JPEG spec simply gives the ranges 0..13 for Ah and Al, but that
  164877. * seems wrong: the upper bound ought to depend on data precision.
  164878. * Perhaps they really meant 0..N+1 for N-bit precision.
  164879. * Here we allow 0..10 for 8-bit data; Al larger than 10 results in
  164880. * out-of-range reconstructed DC values during the first DC scan,
  164881. * which might cause problems for some decoders.
  164882. */
  164883. #if BITS_IN_JSAMPLE == 8
  164884. #define MAX_AH_AL 10
  164885. #else
  164886. #define MAX_AH_AL 13
  164887. #endif
  164888. if (Ss < 0 || Ss >= DCTSIZE2 || Se < Ss || Se >= DCTSIZE2 ||
  164889. Ah < 0 || Ah > MAX_AH_AL || Al < 0 || Al > MAX_AH_AL)
  164890. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164891. if (Ss == 0) {
  164892. if (Se != 0) /* DC and AC together not OK */
  164893. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164894. } else {
  164895. if (ncomps != 1) /* AC scans must be for only one component */
  164896. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164897. }
  164898. for (ci = 0; ci < ncomps; ci++) {
  164899. last_bitpos_ptr = & last_bitpos[scanptr->component_index[ci]][0];
  164900. if (Ss != 0 && last_bitpos_ptr[0] < 0) /* AC without prior DC scan */
  164901. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164902. for (coefi = Ss; coefi <= Se; coefi++) {
  164903. if (last_bitpos_ptr[coefi] < 0) {
  164904. /* first scan of this coefficient */
  164905. if (Ah != 0)
  164906. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164907. } else {
  164908. /* not first scan */
  164909. if (Ah != last_bitpos_ptr[coefi] || Al != Ah-1)
  164910. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164911. }
  164912. last_bitpos_ptr[coefi] = Al;
  164913. }
  164914. }
  164915. #endif
  164916. } else {
  164917. /* For sequential JPEG, all progression parameters must be these: */
  164918. if (Ss != 0 || Se != DCTSIZE2-1 || Ah != 0 || Al != 0)
  164919. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164920. /* Make sure components are not sent twice */
  164921. for (ci = 0; ci < ncomps; ci++) {
  164922. thisi = scanptr->component_index[ci];
  164923. if (component_sent[thisi])
  164924. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  164925. component_sent[thisi] = TRUE;
  164926. }
  164927. }
  164928. }
  164929. /* Now verify that everything got sent. */
  164930. if (cinfo->progressive_mode) {
  164931. #ifdef C_PROGRESSIVE_SUPPORTED
  164932. /* For progressive mode, we only check that at least some DC data
  164933. * got sent for each component; the spec does not require that all bits
  164934. * of all coefficients be transmitted. Would it be wiser to enforce
  164935. * transmission of all coefficient bits??
  164936. */
  164937. for (ci = 0; ci < cinfo->num_components; ci++) {
  164938. if (last_bitpos[ci][0] < 0)
  164939. ERREXIT(cinfo, JERR_MISSING_DATA);
  164940. }
  164941. #endif
  164942. } else {
  164943. for (ci = 0; ci < cinfo->num_components; ci++) {
  164944. if (! component_sent[ci])
  164945. ERREXIT(cinfo, JERR_MISSING_DATA);
  164946. }
  164947. }
  164948. }
  164949. #endif /* C_MULTISCAN_FILES_SUPPORTED */
  164950. LOCAL(void)
  164951. select_scan_parameters (j_compress_ptr cinfo)
  164952. /* Set up the scan parameters for the current scan */
  164953. {
  164954. int ci;
  164955. #ifdef C_MULTISCAN_FILES_SUPPORTED
  164956. if (cinfo->scan_info != NULL) {
  164957. /* Prepare for current scan --- the script is already validated */
  164958. my_master_ptr master = (my_master_ptr) cinfo->master;
  164959. const jpeg_scan_info * scanptr = cinfo->scan_info + master->scan_number;
  164960. cinfo->comps_in_scan = scanptr->comps_in_scan;
  164961. for (ci = 0; ci < scanptr->comps_in_scan; ci++) {
  164962. cinfo->cur_comp_info[ci] =
  164963. &cinfo->comp_info[scanptr->component_index[ci]];
  164964. }
  164965. cinfo->Ss = scanptr->Ss;
  164966. cinfo->Se = scanptr->Se;
  164967. cinfo->Ah = scanptr->Ah;
  164968. cinfo->Al = scanptr->Al;
  164969. }
  164970. else
  164971. #endif
  164972. {
  164973. /* Prepare for single sequential-JPEG scan containing all components */
  164974. if (cinfo->num_components > MAX_COMPS_IN_SCAN)
  164975. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  164976. MAX_COMPS_IN_SCAN);
  164977. cinfo->comps_in_scan = cinfo->num_components;
  164978. for (ci = 0; ci < cinfo->num_components; ci++) {
  164979. cinfo->cur_comp_info[ci] = &cinfo->comp_info[ci];
  164980. }
  164981. cinfo->Ss = 0;
  164982. cinfo->Se = DCTSIZE2-1;
  164983. cinfo->Ah = 0;
  164984. cinfo->Al = 0;
  164985. }
  164986. }
  164987. LOCAL(void)
  164988. per_scan_setup (j_compress_ptr cinfo)
  164989. /* Do computations that are needed before processing a JPEG scan */
  164990. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] are already set */
  164991. {
  164992. int ci, mcublks, tmp;
  164993. jpeg_component_info *compptr;
  164994. if (cinfo->comps_in_scan == 1) {
  164995. /* Noninterleaved (single-component) scan */
  164996. compptr = cinfo->cur_comp_info[0];
  164997. /* Overall image size in MCUs */
  164998. cinfo->MCUs_per_row = compptr->width_in_blocks;
  164999. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  165000. /* For noninterleaved scan, always one block per MCU */
  165001. compptr->MCU_width = 1;
  165002. compptr->MCU_height = 1;
  165003. compptr->MCU_blocks = 1;
  165004. compptr->MCU_sample_width = DCTSIZE;
  165005. compptr->last_col_width = 1;
  165006. /* For noninterleaved scans, it is convenient to define last_row_height
  165007. * as the number of block rows present in the last iMCU row.
  165008. */
  165009. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  165010. if (tmp == 0) tmp = compptr->v_samp_factor;
  165011. compptr->last_row_height = tmp;
  165012. /* Prepare array describing MCU composition */
  165013. cinfo->blocks_in_MCU = 1;
  165014. cinfo->MCU_membership[0] = 0;
  165015. } else {
  165016. /* Interleaved (multi-component) scan */
  165017. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  165018. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  165019. MAX_COMPS_IN_SCAN);
  165020. /* Overall image size in MCUs */
  165021. cinfo->MCUs_per_row = (JDIMENSION)
  165022. jdiv_round_up((long) cinfo->image_width,
  165023. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  165024. cinfo->MCU_rows_in_scan = (JDIMENSION)
  165025. jdiv_round_up((long) cinfo->image_height,
  165026. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  165027. cinfo->blocks_in_MCU = 0;
  165028. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  165029. compptr = cinfo->cur_comp_info[ci];
  165030. /* Sampling factors give # of blocks of component in each MCU */
  165031. compptr->MCU_width = compptr->h_samp_factor;
  165032. compptr->MCU_height = compptr->v_samp_factor;
  165033. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  165034. compptr->MCU_sample_width = compptr->MCU_width * DCTSIZE;
  165035. /* Figure number of non-dummy blocks in last MCU column & row */
  165036. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  165037. if (tmp == 0) tmp = compptr->MCU_width;
  165038. compptr->last_col_width = tmp;
  165039. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  165040. if (tmp == 0) tmp = compptr->MCU_height;
  165041. compptr->last_row_height = tmp;
  165042. /* Prepare array describing MCU composition */
  165043. mcublks = compptr->MCU_blocks;
  165044. if (cinfo->blocks_in_MCU + mcublks > C_MAX_BLOCKS_IN_MCU)
  165045. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  165046. while (mcublks-- > 0) {
  165047. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  165048. }
  165049. }
  165050. }
  165051. /* Convert restart specified in rows to actual MCU count. */
  165052. /* Note that count must fit in 16 bits, so we provide limiting. */
  165053. if (cinfo->restart_in_rows > 0) {
  165054. long nominal = (long) cinfo->restart_in_rows * (long) cinfo->MCUs_per_row;
  165055. cinfo->restart_interval = (unsigned int) MIN(nominal, 65535L);
  165056. }
  165057. }
  165058. /*
  165059. * Per-pass setup.
  165060. * This is called at the beginning of each pass. We determine which modules
  165061. * will be active during this pass and give them appropriate start_pass calls.
  165062. * We also set is_last_pass to indicate whether any more passes will be
  165063. * required.
  165064. */
  165065. METHODDEF(void)
  165066. prepare_for_pass (j_compress_ptr cinfo)
  165067. {
  165068. my_master_ptr master = (my_master_ptr) cinfo->master;
  165069. switch (master->pass_type) {
  165070. case main_pass:
  165071. /* Initial pass: will collect input data, and do either Huffman
  165072. * optimization or data output for the first scan.
  165073. */
  165074. select_scan_parameters(cinfo);
  165075. per_scan_setup(cinfo);
  165076. if (! cinfo->raw_data_in) {
  165077. (*cinfo->cconvert->start_pass) (cinfo);
  165078. (*cinfo->downsample->start_pass) (cinfo);
  165079. (*cinfo->prep->start_pass) (cinfo, JBUF_PASS_THRU);
  165080. }
  165081. (*cinfo->fdct->start_pass) (cinfo);
  165082. (*cinfo->entropy->start_pass) (cinfo, cinfo->optimize_coding);
  165083. (*cinfo->coef->start_pass) (cinfo,
  165084. (master->total_passes > 1 ?
  165085. JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  165086. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  165087. if (cinfo->optimize_coding) {
  165088. /* No immediate data output; postpone writing frame/scan headers */
  165089. master->pub.call_pass_startup = FALSE;
  165090. } else {
  165091. /* Will write frame/scan headers at first jpeg_write_scanlines call */
  165092. master->pub.call_pass_startup = TRUE;
  165093. }
  165094. break;
  165095. #ifdef ENTROPY_OPT_SUPPORTED
  165096. case huff_opt_pass:
  165097. /* Do Huffman optimization for a scan after the first one. */
  165098. select_scan_parameters(cinfo);
  165099. per_scan_setup(cinfo);
  165100. if (cinfo->Ss != 0 || cinfo->Ah == 0 || cinfo->arith_code) {
  165101. (*cinfo->entropy->start_pass) (cinfo, TRUE);
  165102. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  165103. master->pub.call_pass_startup = FALSE;
  165104. break;
  165105. }
  165106. /* Special case: Huffman DC refinement scans need no Huffman table
  165107. * and therefore we can skip the optimization pass for them.
  165108. */
  165109. master->pass_type = output_pass;
  165110. master->pass_number++;
  165111. /*FALLTHROUGH*/
  165112. #endif
  165113. case output_pass:
  165114. /* Do a data-output pass. */
  165115. /* We need not repeat per-scan setup if prior optimization pass did it. */
  165116. if (! cinfo->optimize_coding) {
  165117. select_scan_parameters(cinfo);
  165118. per_scan_setup(cinfo);
  165119. }
  165120. (*cinfo->entropy->start_pass) (cinfo, FALSE);
  165121. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  165122. /* We emit frame/scan headers now */
  165123. if (master->scan_number == 0)
  165124. (*cinfo->marker->write_frame_header) (cinfo);
  165125. (*cinfo->marker->write_scan_header) (cinfo);
  165126. master->pub.call_pass_startup = FALSE;
  165127. break;
  165128. default:
  165129. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165130. }
  165131. master->pub.is_last_pass = (master->pass_number == master->total_passes-1);
  165132. /* Set up progress monitor's pass info if present */
  165133. if (cinfo->progress != NULL) {
  165134. cinfo->progress->completed_passes = master->pass_number;
  165135. cinfo->progress->total_passes = master->total_passes;
  165136. }
  165137. }
  165138. /*
  165139. * Special start-of-pass hook.
  165140. * This is called by jpeg_write_scanlines if call_pass_startup is TRUE.
  165141. * In single-pass processing, we need this hook because we don't want to
  165142. * write frame/scan headers during jpeg_start_compress; we want to let the
  165143. * application write COM markers etc. between jpeg_start_compress and the
  165144. * jpeg_write_scanlines loop.
  165145. * In multi-pass processing, this routine is not used.
  165146. */
  165147. METHODDEF(void)
  165148. pass_startup (j_compress_ptr cinfo)
  165149. {
  165150. cinfo->master->call_pass_startup = FALSE; /* reset flag so call only once */
  165151. (*cinfo->marker->write_frame_header) (cinfo);
  165152. (*cinfo->marker->write_scan_header) (cinfo);
  165153. }
  165154. /*
  165155. * Finish up at end of pass.
  165156. */
  165157. METHODDEF(void)
  165158. finish_pass_master (j_compress_ptr cinfo)
  165159. {
  165160. my_master_ptr master = (my_master_ptr) cinfo->master;
  165161. /* The entropy coder always needs an end-of-pass call,
  165162. * either to analyze statistics or to flush its output buffer.
  165163. */
  165164. (*cinfo->entropy->finish_pass) (cinfo);
  165165. /* Update state for next pass */
  165166. switch (master->pass_type) {
  165167. case main_pass:
  165168. /* next pass is either output of scan 0 (after optimization)
  165169. * or output of scan 1 (if no optimization).
  165170. */
  165171. master->pass_type = output_pass;
  165172. if (! cinfo->optimize_coding)
  165173. master->scan_number++;
  165174. break;
  165175. case huff_opt_pass:
  165176. /* next pass is always output of current scan */
  165177. master->pass_type = output_pass;
  165178. break;
  165179. case output_pass:
  165180. /* next pass is either optimization or output of next scan */
  165181. if (cinfo->optimize_coding)
  165182. master->pass_type = huff_opt_pass;
  165183. master->scan_number++;
  165184. break;
  165185. }
  165186. master->pass_number++;
  165187. }
  165188. /*
  165189. * Initialize master compression control.
  165190. */
  165191. GLOBAL(void)
  165192. jinit_c_master_control (j_compress_ptr cinfo, boolean transcode_only)
  165193. {
  165194. my_master_ptr master;
  165195. master = (my_master_ptr)
  165196. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165197. SIZEOF(my_comp_master));
  165198. cinfo->master = (struct jpeg_comp_master *) master;
  165199. master->pub.prepare_for_pass = prepare_for_pass;
  165200. master->pub.pass_startup = pass_startup;
  165201. master->pub.finish_pass = finish_pass_master;
  165202. master->pub.is_last_pass = FALSE;
  165203. /* Validate parameters, determine derived values */
  165204. initial_setup(cinfo);
  165205. if (cinfo->scan_info != NULL) {
  165206. #ifdef C_MULTISCAN_FILES_SUPPORTED
  165207. validate_script(cinfo);
  165208. #else
  165209. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165210. #endif
  165211. } else {
  165212. cinfo->progressive_mode = FALSE;
  165213. cinfo->num_scans = 1;
  165214. }
  165215. if (cinfo->progressive_mode) /* TEMPORARY HACK ??? */
  165216. cinfo->optimize_coding = TRUE; /* assume default tables no good for progressive mode */
  165217. /* Initialize my private state */
  165218. if (transcode_only) {
  165219. /* no main pass in transcoding */
  165220. if (cinfo->optimize_coding)
  165221. master->pass_type = huff_opt_pass;
  165222. else
  165223. master->pass_type = output_pass;
  165224. } else {
  165225. /* for normal compression, first pass is always this type: */
  165226. master->pass_type = main_pass;
  165227. }
  165228. master->scan_number = 0;
  165229. master->pass_number = 0;
  165230. if (cinfo->optimize_coding)
  165231. master->total_passes = cinfo->num_scans * 2;
  165232. else
  165233. master->total_passes = cinfo->num_scans;
  165234. }
  165235. /*** End of inlined file: jcmaster.c ***/
  165236. /*** Start of inlined file: jcomapi.c ***/
  165237. #define JPEG_INTERNALS
  165238. /*
  165239. * Abort processing of a JPEG compression or decompression operation,
  165240. * but don't destroy the object itself.
  165241. *
  165242. * For this, we merely clean up all the nonpermanent memory pools.
  165243. * Note that temp files (virtual arrays) are not allowed to belong to
  165244. * the permanent pool, so we will be able to close all temp files here.
  165245. * Closing a data source or destination, if necessary, is the application's
  165246. * responsibility.
  165247. */
  165248. GLOBAL(void)
  165249. jpeg_abort (j_common_ptr cinfo)
  165250. {
  165251. int pool;
  165252. /* Do nothing if called on a not-initialized or destroyed JPEG object. */
  165253. if (cinfo->mem == NULL)
  165254. return;
  165255. /* Releasing pools in reverse order might help avoid fragmentation
  165256. * with some (brain-damaged) malloc libraries.
  165257. */
  165258. for (pool = JPOOL_NUMPOOLS-1; pool > JPOOL_PERMANENT; pool--) {
  165259. (*cinfo->mem->free_pool) (cinfo, pool);
  165260. }
  165261. /* Reset overall state for possible reuse of object */
  165262. if (cinfo->is_decompressor) {
  165263. cinfo->global_state = DSTATE_START;
  165264. /* Try to keep application from accessing now-deleted marker list.
  165265. * A bit kludgy to do it here, but this is the most central place.
  165266. */
  165267. ((j_decompress_ptr) cinfo)->marker_list = NULL;
  165268. } else {
  165269. cinfo->global_state = CSTATE_START;
  165270. }
  165271. }
  165272. /*
  165273. * Destruction of a JPEG object.
  165274. *
  165275. * Everything gets deallocated except the master jpeg_compress_struct itself
  165276. * and the error manager struct. Both of these are supplied by the application
  165277. * and must be freed, if necessary, by the application. (Often they are on
  165278. * the stack and so don't need to be freed anyway.)
  165279. * Closing a data source or destination, if necessary, is the application's
  165280. * responsibility.
  165281. */
  165282. GLOBAL(void)
  165283. jpeg_destroy (j_common_ptr cinfo)
  165284. {
  165285. /* We need only tell the memory manager to release everything. */
  165286. /* NB: mem pointer is NULL if memory mgr failed to initialize. */
  165287. if (cinfo->mem != NULL)
  165288. (*cinfo->mem->self_destruct) (cinfo);
  165289. cinfo->mem = NULL; /* be safe if jpeg_destroy is called twice */
  165290. cinfo->global_state = 0; /* mark it destroyed */
  165291. }
  165292. /*
  165293. * Convenience routines for allocating quantization and Huffman tables.
  165294. * (Would jutils.c be a more reasonable place to put these?)
  165295. */
  165296. GLOBAL(JQUANT_TBL *)
  165297. jpeg_alloc_quant_table (j_common_ptr cinfo)
  165298. {
  165299. JQUANT_TBL *tbl;
  165300. tbl = (JQUANT_TBL *)
  165301. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JQUANT_TBL));
  165302. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  165303. return tbl;
  165304. }
  165305. GLOBAL(JHUFF_TBL *)
  165306. jpeg_alloc_huff_table (j_common_ptr cinfo)
  165307. {
  165308. JHUFF_TBL *tbl;
  165309. tbl = (JHUFF_TBL *)
  165310. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JHUFF_TBL));
  165311. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  165312. return tbl;
  165313. }
  165314. /*** End of inlined file: jcomapi.c ***/
  165315. /*** Start of inlined file: jcparam.c ***/
  165316. #define JPEG_INTERNALS
  165317. /*
  165318. * Quantization table setup routines
  165319. */
  165320. GLOBAL(void)
  165321. jpeg_add_quant_table (j_compress_ptr cinfo, int which_tbl,
  165322. const unsigned int *basic_table,
  165323. int scale_factor, boolean force_baseline)
  165324. /* Define a quantization table equal to the basic_table times
  165325. * a scale factor (given as a percentage).
  165326. * If force_baseline is TRUE, the computed quantization table entries
  165327. * are limited to 1..255 for JPEG baseline compatibility.
  165328. */
  165329. {
  165330. JQUANT_TBL ** qtblptr;
  165331. int i;
  165332. long temp;
  165333. /* Safety check to ensure start_compress not called yet. */
  165334. if (cinfo->global_state != CSTATE_START)
  165335. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165336. if (which_tbl < 0 || which_tbl >= NUM_QUANT_TBLS)
  165337. ERREXIT1(cinfo, JERR_DQT_INDEX, which_tbl);
  165338. qtblptr = & cinfo->quant_tbl_ptrs[which_tbl];
  165339. if (*qtblptr == NULL)
  165340. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  165341. for (i = 0; i < DCTSIZE2; i++) {
  165342. temp = ((long) basic_table[i] * scale_factor + 50L) / 100L;
  165343. /* limit the values to the valid range */
  165344. if (temp <= 0L) temp = 1L;
  165345. if (temp > 32767L) temp = 32767L; /* max quantizer needed for 12 bits */
  165346. if (force_baseline && temp > 255L)
  165347. temp = 255L; /* limit to baseline range if requested */
  165348. (*qtblptr)->quantval[i] = (UINT16) temp;
  165349. }
  165350. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  165351. (*qtblptr)->sent_table = FALSE;
  165352. }
  165353. GLOBAL(void)
  165354. jpeg_set_linear_quality (j_compress_ptr cinfo, int scale_factor,
  165355. boolean force_baseline)
  165356. /* Set or change the 'quality' (quantization) setting, using default tables
  165357. * and a straight percentage-scaling quality scale. In most cases it's better
  165358. * to use jpeg_set_quality (below); this entry point is provided for
  165359. * applications that insist on a linear percentage scaling.
  165360. */
  165361. {
  165362. /* These are the sample quantization tables given in JPEG spec section K.1.
  165363. * The spec says that the values given produce "good" quality, and
  165364. * when divided by 2, "very good" quality.
  165365. */
  165366. static const unsigned int std_luminance_quant_tbl[DCTSIZE2] = {
  165367. 16, 11, 10, 16, 24, 40, 51, 61,
  165368. 12, 12, 14, 19, 26, 58, 60, 55,
  165369. 14, 13, 16, 24, 40, 57, 69, 56,
  165370. 14, 17, 22, 29, 51, 87, 80, 62,
  165371. 18, 22, 37, 56, 68, 109, 103, 77,
  165372. 24, 35, 55, 64, 81, 104, 113, 92,
  165373. 49, 64, 78, 87, 103, 121, 120, 101,
  165374. 72, 92, 95, 98, 112, 100, 103, 99
  165375. };
  165376. static const unsigned int std_chrominance_quant_tbl[DCTSIZE2] = {
  165377. 17, 18, 24, 47, 99, 99, 99, 99,
  165378. 18, 21, 26, 66, 99, 99, 99, 99,
  165379. 24, 26, 56, 99, 99, 99, 99, 99,
  165380. 47, 66, 99, 99, 99, 99, 99, 99,
  165381. 99, 99, 99, 99, 99, 99, 99, 99,
  165382. 99, 99, 99, 99, 99, 99, 99, 99,
  165383. 99, 99, 99, 99, 99, 99, 99, 99,
  165384. 99, 99, 99, 99, 99, 99, 99, 99
  165385. };
  165386. /* Set up two quantization tables using the specified scaling */
  165387. jpeg_add_quant_table(cinfo, 0, std_luminance_quant_tbl,
  165388. scale_factor, force_baseline);
  165389. jpeg_add_quant_table(cinfo, 1, std_chrominance_quant_tbl,
  165390. scale_factor, force_baseline);
  165391. }
  165392. GLOBAL(int)
  165393. jpeg_quality_scaling (int quality)
  165394. /* Convert a user-specified quality rating to a percentage scaling factor
  165395. * for an underlying quantization table, using our recommended scaling curve.
  165396. * The input 'quality' factor should be 0 (terrible) to 100 (very good).
  165397. */
  165398. {
  165399. /* Safety limit on quality factor. Convert 0 to 1 to avoid zero divide. */
  165400. if (quality <= 0) quality = 1;
  165401. if (quality > 100) quality = 100;
  165402. /* The basic table is used as-is (scaling 100) for a quality of 50.
  165403. * Qualities 50..100 are converted to scaling percentage 200 - 2*Q;
  165404. * note that at Q=100 the scaling is 0, which will cause jpeg_add_quant_table
  165405. * to make all the table entries 1 (hence, minimum quantization loss).
  165406. * Qualities 1..50 are converted to scaling percentage 5000/Q.
  165407. */
  165408. if (quality < 50)
  165409. quality = 5000 / quality;
  165410. else
  165411. quality = 200 - quality*2;
  165412. return quality;
  165413. }
  165414. GLOBAL(void)
  165415. jpeg_set_quality (j_compress_ptr cinfo, int quality, boolean force_baseline)
  165416. /* Set or change the 'quality' (quantization) setting, using default tables.
  165417. * This is the standard quality-adjusting entry point for typical user
  165418. * interfaces; only those who want detailed control over quantization tables
  165419. * would use the preceding three routines directly.
  165420. */
  165421. {
  165422. /* Convert user 0-100 rating to percentage scaling */
  165423. quality = jpeg_quality_scaling(quality);
  165424. /* Set up standard quality tables */
  165425. jpeg_set_linear_quality(cinfo, quality, force_baseline);
  165426. }
  165427. /*
  165428. * Huffman table setup routines
  165429. */
  165430. LOCAL(void)
  165431. add_huff_table (j_compress_ptr cinfo,
  165432. JHUFF_TBL **htblptr, const UINT8 *bits, const UINT8 *val)
  165433. /* Define a Huffman table */
  165434. {
  165435. int nsymbols, len;
  165436. if (*htblptr == NULL)
  165437. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  165438. /* Copy the number-of-symbols-of-each-code-length counts */
  165439. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  165440. /* Validate the counts. We do this here mainly so we can copy the right
  165441. * number of symbols from the val[] array, without risking marching off
  165442. * the end of memory. jchuff.c will do a more thorough test later.
  165443. */
  165444. nsymbols = 0;
  165445. for (len = 1; len <= 16; len++)
  165446. nsymbols += bits[len];
  165447. if (nsymbols < 1 || nsymbols > 256)
  165448. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  165449. MEMCOPY((*htblptr)->huffval, val, nsymbols * SIZEOF(UINT8));
  165450. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  165451. (*htblptr)->sent_table = FALSE;
  165452. }
  165453. LOCAL(void)
  165454. std_huff_tables (j_compress_ptr cinfo)
  165455. /* Set up the standard Huffman tables (cf. JPEG standard section K.3) */
  165456. /* IMPORTANT: these are only valid for 8-bit data precision! */
  165457. {
  165458. static const UINT8 bits_dc_luminance[17] =
  165459. { /* 0-base */ 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 };
  165460. static const UINT8 val_dc_luminance[] =
  165461. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  165462. static const UINT8 bits_dc_chrominance[17] =
  165463. { /* 0-base */ 0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
  165464. static const UINT8 val_dc_chrominance[] =
  165465. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  165466. static const UINT8 bits_ac_luminance[17] =
  165467. { /* 0-base */ 0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d };
  165468. static const UINT8 val_ac_luminance[] =
  165469. { 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
  165470. 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
  165471. 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
  165472. 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
  165473. 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
  165474. 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
  165475. 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
  165476. 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
  165477. 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
  165478. 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
  165479. 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
  165480. 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
  165481. 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
  165482. 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
  165483. 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
  165484. 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
  165485. 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
  165486. 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
  165487. 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
  165488. 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  165489. 0xf9, 0xfa };
  165490. static const UINT8 bits_ac_chrominance[17] =
  165491. { /* 0-base */ 0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 };
  165492. static const UINT8 val_ac_chrominance[] =
  165493. { 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
  165494. 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
  165495. 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
  165496. 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
  165497. 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
  165498. 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
  165499. 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
  165500. 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
  165501. 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
  165502. 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
  165503. 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
  165504. 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
  165505. 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
  165506. 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
  165507. 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
  165508. 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
  165509. 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
  165510. 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
  165511. 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
  165512. 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  165513. 0xf9, 0xfa };
  165514. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[0],
  165515. bits_dc_luminance, val_dc_luminance);
  165516. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[0],
  165517. bits_ac_luminance, val_ac_luminance);
  165518. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[1],
  165519. bits_dc_chrominance, val_dc_chrominance);
  165520. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[1],
  165521. bits_ac_chrominance, val_ac_chrominance);
  165522. }
  165523. /*
  165524. * Default parameter setup for compression.
  165525. *
  165526. * Applications that don't choose to use this routine must do their
  165527. * own setup of all these parameters. Alternately, you can call this
  165528. * to establish defaults and then alter parameters selectively. This
  165529. * is the recommended approach since, if we add any new parameters,
  165530. * your code will still work (they'll be set to reasonable defaults).
  165531. */
  165532. GLOBAL(void)
  165533. jpeg_set_defaults (j_compress_ptr cinfo)
  165534. {
  165535. int i;
  165536. /* Safety check to ensure start_compress not called yet. */
  165537. if (cinfo->global_state != CSTATE_START)
  165538. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165539. /* Allocate comp_info array large enough for maximum component count.
  165540. * Array is made permanent in case application wants to compress
  165541. * multiple images at same param settings.
  165542. */
  165543. if (cinfo->comp_info == NULL)
  165544. cinfo->comp_info = (jpeg_component_info *)
  165545. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  165546. MAX_COMPONENTS * SIZEOF(jpeg_component_info));
  165547. /* Initialize everything not dependent on the color space */
  165548. cinfo->data_precision = BITS_IN_JSAMPLE;
  165549. /* Set up two quantization tables using default quality of 75 */
  165550. jpeg_set_quality(cinfo, 75, TRUE);
  165551. /* Set up two Huffman tables */
  165552. std_huff_tables(cinfo);
  165553. /* Initialize default arithmetic coding conditioning */
  165554. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  165555. cinfo->arith_dc_L[i] = 0;
  165556. cinfo->arith_dc_U[i] = 1;
  165557. cinfo->arith_ac_K[i] = 5;
  165558. }
  165559. /* Default is no multiple-scan output */
  165560. cinfo->scan_info = NULL;
  165561. cinfo->num_scans = 0;
  165562. /* Expect normal source image, not raw downsampled data */
  165563. cinfo->raw_data_in = FALSE;
  165564. /* Use Huffman coding, not arithmetic coding, by default */
  165565. cinfo->arith_code = FALSE;
  165566. /* By default, don't do extra passes to optimize entropy coding */
  165567. cinfo->optimize_coding = FALSE;
  165568. /* The standard Huffman tables are only valid for 8-bit data precision.
  165569. * If the precision is higher, force optimization on so that usable
  165570. * tables will be computed. This test can be removed if default tables
  165571. * are supplied that are valid for the desired precision.
  165572. */
  165573. if (cinfo->data_precision > 8)
  165574. cinfo->optimize_coding = TRUE;
  165575. /* By default, use the simpler non-cosited sampling alignment */
  165576. cinfo->CCIR601_sampling = FALSE;
  165577. /* No input smoothing */
  165578. cinfo->smoothing_factor = 0;
  165579. /* DCT algorithm preference */
  165580. cinfo->dct_method = JDCT_DEFAULT;
  165581. /* No restart markers */
  165582. cinfo->restart_interval = 0;
  165583. cinfo->restart_in_rows = 0;
  165584. /* Fill in default JFIF marker parameters. Note that whether the marker
  165585. * will actually be written is determined by jpeg_set_colorspace.
  165586. *
  165587. * By default, the library emits JFIF version code 1.01.
  165588. * An application that wants to emit JFIF 1.02 extension markers should set
  165589. * JFIF_minor_version to 2. We could probably get away with just defaulting
  165590. * to 1.02, but there may still be some decoders in use that will complain
  165591. * about that; saying 1.01 should minimize compatibility problems.
  165592. */
  165593. cinfo->JFIF_major_version = 1; /* Default JFIF version = 1.01 */
  165594. cinfo->JFIF_minor_version = 1;
  165595. cinfo->density_unit = 0; /* Pixel size is unknown by default */
  165596. cinfo->X_density = 1; /* Pixel aspect ratio is square by default */
  165597. cinfo->Y_density = 1;
  165598. /* Choose JPEG colorspace based on input space, set defaults accordingly */
  165599. jpeg_default_colorspace(cinfo);
  165600. }
  165601. /*
  165602. * Select an appropriate JPEG colorspace for in_color_space.
  165603. */
  165604. GLOBAL(void)
  165605. jpeg_default_colorspace (j_compress_ptr cinfo)
  165606. {
  165607. switch (cinfo->in_color_space) {
  165608. case JCS_GRAYSCALE:
  165609. jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
  165610. break;
  165611. case JCS_RGB:
  165612. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  165613. break;
  165614. case JCS_YCbCr:
  165615. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  165616. break;
  165617. case JCS_CMYK:
  165618. jpeg_set_colorspace(cinfo, JCS_CMYK); /* By default, no translation */
  165619. break;
  165620. case JCS_YCCK:
  165621. jpeg_set_colorspace(cinfo, JCS_YCCK);
  165622. break;
  165623. case JCS_UNKNOWN:
  165624. jpeg_set_colorspace(cinfo, JCS_UNKNOWN);
  165625. break;
  165626. default:
  165627. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  165628. }
  165629. }
  165630. /*
  165631. * Set the JPEG colorspace, and choose colorspace-dependent default values.
  165632. */
  165633. GLOBAL(void)
  165634. jpeg_set_colorspace (j_compress_ptr cinfo, J_COLOR_SPACE colorspace)
  165635. {
  165636. jpeg_component_info * compptr;
  165637. int ci;
  165638. #define SET_COMP(index,id,hsamp,vsamp,quant,dctbl,actbl) \
  165639. (compptr = &cinfo->comp_info[index], \
  165640. compptr->component_id = (id), \
  165641. compptr->h_samp_factor = (hsamp), \
  165642. compptr->v_samp_factor = (vsamp), \
  165643. compptr->quant_tbl_no = (quant), \
  165644. compptr->dc_tbl_no = (dctbl), \
  165645. compptr->ac_tbl_no = (actbl) )
  165646. /* Safety check to ensure start_compress not called yet. */
  165647. if (cinfo->global_state != CSTATE_START)
  165648. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165649. /* For all colorspaces, we use Q and Huff tables 0 for luminance components,
  165650. * tables 1 for chrominance components.
  165651. */
  165652. cinfo->jpeg_color_space = colorspace;
  165653. cinfo->write_JFIF_header = FALSE; /* No marker for non-JFIF colorspaces */
  165654. cinfo->write_Adobe_marker = FALSE; /* write no Adobe marker by default */
  165655. switch (colorspace) {
  165656. case JCS_GRAYSCALE:
  165657. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  165658. cinfo->num_components = 1;
  165659. /* JFIF specifies component ID 1 */
  165660. SET_COMP(0, 1, 1,1, 0, 0,0);
  165661. break;
  165662. case JCS_RGB:
  165663. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag RGB */
  165664. cinfo->num_components = 3;
  165665. SET_COMP(0, 0x52 /* 'R' */, 1,1, 0, 0,0);
  165666. SET_COMP(1, 0x47 /* 'G' */, 1,1, 0, 0,0);
  165667. SET_COMP(2, 0x42 /* 'B' */, 1,1, 0, 0,0);
  165668. break;
  165669. case JCS_YCbCr:
  165670. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  165671. cinfo->num_components = 3;
  165672. /* JFIF specifies component IDs 1,2,3 */
  165673. /* We default to 2x2 subsamples of chrominance */
  165674. SET_COMP(0, 1, 2,2, 0, 0,0);
  165675. SET_COMP(1, 2, 1,1, 1, 1,1);
  165676. SET_COMP(2, 3, 1,1, 1, 1,1);
  165677. break;
  165678. case JCS_CMYK:
  165679. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag CMYK */
  165680. cinfo->num_components = 4;
  165681. SET_COMP(0, 0x43 /* 'C' */, 1,1, 0, 0,0);
  165682. SET_COMP(1, 0x4D /* 'M' */, 1,1, 0, 0,0);
  165683. SET_COMP(2, 0x59 /* 'Y' */, 1,1, 0, 0,0);
  165684. SET_COMP(3, 0x4B /* 'K' */, 1,1, 0, 0,0);
  165685. break;
  165686. case JCS_YCCK:
  165687. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag YCCK */
  165688. cinfo->num_components = 4;
  165689. SET_COMP(0, 1, 2,2, 0, 0,0);
  165690. SET_COMP(1, 2, 1,1, 1, 1,1);
  165691. SET_COMP(2, 3, 1,1, 1, 1,1);
  165692. SET_COMP(3, 4, 2,2, 0, 0,0);
  165693. break;
  165694. case JCS_UNKNOWN:
  165695. cinfo->num_components = cinfo->input_components;
  165696. if (cinfo->num_components < 1 || cinfo->num_components > MAX_COMPONENTS)
  165697. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  165698. MAX_COMPONENTS);
  165699. for (ci = 0; ci < cinfo->num_components; ci++) {
  165700. SET_COMP(ci, ci, 1,1, 0, 0,0);
  165701. }
  165702. break;
  165703. default:
  165704. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  165705. }
  165706. }
  165707. #ifdef C_PROGRESSIVE_SUPPORTED
  165708. LOCAL(jpeg_scan_info *)
  165709. fill_a_scan (jpeg_scan_info * scanptr, int ci,
  165710. int Ss, int Se, int Ah, int Al)
  165711. /* Support routine: generate one scan for specified component */
  165712. {
  165713. scanptr->comps_in_scan = 1;
  165714. scanptr->component_index[0] = ci;
  165715. scanptr->Ss = Ss;
  165716. scanptr->Se = Se;
  165717. scanptr->Ah = Ah;
  165718. scanptr->Al = Al;
  165719. scanptr++;
  165720. return scanptr;
  165721. }
  165722. LOCAL(jpeg_scan_info *)
  165723. fill_scans (jpeg_scan_info * scanptr, int ncomps,
  165724. int Ss, int Se, int Ah, int Al)
  165725. /* Support routine: generate one scan for each component */
  165726. {
  165727. int ci;
  165728. for (ci = 0; ci < ncomps; ci++) {
  165729. scanptr->comps_in_scan = 1;
  165730. scanptr->component_index[0] = ci;
  165731. scanptr->Ss = Ss;
  165732. scanptr->Se = Se;
  165733. scanptr->Ah = Ah;
  165734. scanptr->Al = Al;
  165735. scanptr++;
  165736. }
  165737. return scanptr;
  165738. }
  165739. LOCAL(jpeg_scan_info *)
  165740. fill_dc_scans (jpeg_scan_info * scanptr, int ncomps, int Ah, int Al)
  165741. /* Support routine: generate interleaved DC scan if possible, else N scans */
  165742. {
  165743. int ci;
  165744. if (ncomps <= MAX_COMPS_IN_SCAN) {
  165745. /* Single interleaved DC scan */
  165746. scanptr->comps_in_scan = ncomps;
  165747. for (ci = 0; ci < ncomps; ci++)
  165748. scanptr->component_index[ci] = ci;
  165749. scanptr->Ss = scanptr->Se = 0;
  165750. scanptr->Ah = Ah;
  165751. scanptr->Al = Al;
  165752. scanptr++;
  165753. } else {
  165754. /* Noninterleaved DC scan for each component */
  165755. scanptr = fill_scans(scanptr, ncomps, 0, 0, Ah, Al);
  165756. }
  165757. return scanptr;
  165758. }
  165759. /*
  165760. * Create a recommended progressive-JPEG script.
  165761. * cinfo->num_components and cinfo->jpeg_color_space must be correct.
  165762. */
  165763. GLOBAL(void)
  165764. jpeg_simple_progression (j_compress_ptr cinfo)
  165765. {
  165766. int ncomps = cinfo->num_components;
  165767. int nscans;
  165768. jpeg_scan_info * scanptr;
  165769. /* Safety check to ensure start_compress not called yet. */
  165770. if (cinfo->global_state != CSTATE_START)
  165771. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165772. /* Figure space needed for script. Calculation must match code below! */
  165773. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  165774. /* Custom script for YCbCr color images. */
  165775. nscans = 10;
  165776. } else {
  165777. /* All-purpose script for other color spaces. */
  165778. if (ncomps > MAX_COMPS_IN_SCAN)
  165779. nscans = 6 * ncomps; /* 2 DC + 4 AC scans per component */
  165780. else
  165781. nscans = 2 + 4 * ncomps; /* 2 DC scans; 4 AC scans per component */
  165782. }
  165783. /* Allocate space for script.
  165784. * We need to put it in the permanent pool in case the application performs
  165785. * multiple compressions without changing the settings. To avoid a memory
  165786. * leak if jpeg_simple_progression is called repeatedly for the same JPEG
  165787. * object, we try to re-use previously allocated space, and we allocate
  165788. * enough space to handle YCbCr even if initially asked for grayscale.
  165789. */
  165790. if (cinfo->script_space == NULL || cinfo->script_space_size < nscans) {
  165791. cinfo->script_space_size = MAX(nscans, 10);
  165792. cinfo->script_space = (jpeg_scan_info *)
  165793. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  165794. cinfo->script_space_size * SIZEOF(jpeg_scan_info));
  165795. }
  165796. scanptr = cinfo->script_space;
  165797. cinfo->scan_info = scanptr;
  165798. cinfo->num_scans = nscans;
  165799. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  165800. /* Custom script for YCbCr color images. */
  165801. /* Initial DC scan */
  165802. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  165803. /* Initial AC scan: get some luma data out in a hurry */
  165804. scanptr = fill_a_scan(scanptr, 0, 1, 5, 0, 2);
  165805. /* Chroma data is too small to be worth expending many scans on */
  165806. scanptr = fill_a_scan(scanptr, 2, 1, 63, 0, 1);
  165807. scanptr = fill_a_scan(scanptr, 1, 1, 63, 0, 1);
  165808. /* Complete spectral selection for luma AC */
  165809. scanptr = fill_a_scan(scanptr, 0, 6, 63, 0, 2);
  165810. /* Refine next bit of luma AC */
  165811. scanptr = fill_a_scan(scanptr, 0, 1, 63, 2, 1);
  165812. /* Finish DC successive approximation */
  165813. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  165814. /* Finish AC successive approximation */
  165815. scanptr = fill_a_scan(scanptr, 2, 1, 63, 1, 0);
  165816. scanptr = fill_a_scan(scanptr, 1, 1, 63, 1, 0);
  165817. /* Luma bottom bit comes last since it's usually largest scan */
  165818. scanptr = fill_a_scan(scanptr, 0, 1, 63, 1, 0);
  165819. } else {
  165820. /* All-purpose script for other color spaces. */
  165821. /* Successive approximation first pass */
  165822. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  165823. scanptr = fill_scans(scanptr, ncomps, 1, 5, 0, 2);
  165824. scanptr = fill_scans(scanptr, ncomps, 6, 63, 0, 2);
  165825. /* Successive approximation second pass */
  165826. scanptr = fill_scans(scanptr, ncomps, 1, 63, 2, 1);
  165827. /* Successive approximation final pass */
  165828. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  165829. scanptr = fill_scans(scanptr, ncomps, 1, 63, 1, 0);
  165830. }
  165831. }
  165832. #endif /* C_PROGRESSIVE_SUPPORTED */
  165833. /*** End of inlined file: jcparam.c ***/
  165834. /*** Start of inlined file: jcphuff.c ***/
  165835. #define JPEG_INTERNALS
  165836. #ifdef C_PROGRESSIVE_SUPPORTED
  165837. /* Expanded entropy encoder object for progressive Huffman encoding. */
  165838. typedef struct {
  165839. struct jpeg_entropy_encoder pub; /* public fields */
  165840. /* Mode flag: TRUE for optimization, FALSE for actual data output */
  165841. boolean gather_statistics;
  165842. /* Bit-level coding status.
  165843. * next_output_byte/free_in_buffer are local copies of cinfo->dest fields.
  165844. */
  165845. JOCTET * next_output_byte; /* => next byte to write in buffer */
  165846. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  165847. INT32 put_buffer; /* current bit-accumulation buffer */
  165848. int put_bits; /* # of bits now in it */
  165849. j_compress_ptr cinfo; /* link to cinfo (needed for dump_buffer) */
  165850. /* Coding status for DC components */
  165851. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  165852. /* Coding status for AC components */
  165853. int ac_tbl_no; /* the table number of the single component */
  165854. unsigned int EOBRUN; /* run length of EOBs */
  165855. unsigned int BE; /* # of buffered correction bits before MCU */
  165856. char * bit_buffer; /* buffer for correction bits (1 per char) */
  165857. /* packing correction bits tightly would save some space but cost time... */
  165858. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  165859. int next_restart_num; /* next restart number to write (0-7) */
  165860. /* Pointers to derived tables (these workspaces have image lifespan).
  165861. * Since any one scan codes only DC or only AC, we only need one set
  165862. * of tables, not one for DC and one for AC.
  165863. */
  165864. c_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  165865. /* Statistics tables for optimization; again, one set is enough */
  165866. long * count_ptrs[NUM_HUFF_TBLS];
  165867. } phuff_entropy_encoder;
  165868. typedef phuff_entropy_encoder * phuff_entropy_ptr;
  165869. /* MAX_CORR_BITS is the number of bits the AC refinement correction-bit
  165870. * buffer can hold. Larger sizes may slightly improve compression, but
  165871. * 1000 is already well into the realm of overkill.
  165872. * The minimum safe size is 64 bits.
  165873. */
  165874. #define MAX_CORR_BITS 1000 /* Max # of correction bits I can buffer */
  165875. /* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32.
  165876. * We assume that int right shift is unsigned if INT32 right shift is,
  165877. * which should be safe.
  165878. */
  165879. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  165880. #define ISHIFT_TEMPS int ishift_temp;
  165881. #define IRIGHT_SHIFT(x,shft) \
  165882. ((ishift_temp = (x)) < 0 ? \
  165883. (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \
  165884. (ishift_temp >> (shft)))
  165885. #else
  165886. #define ISHIFT_TEMPS
  165887. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  165888. #endif
  165889. /* Forward declarations */
  165890. METHODDEF(boolean) encode_mcu_DC_first JPP((j_compress_ptr cinfo,
  165891. JBLOCKROW *MCU_data));
  165892. METHODDEF(boolean) encode_mcu_AC_first JPP((j_compress_ptr cinfo,
  165893. JBLOCKROW *MCU_data));
  165894. METHODDEF(boolean) encode_mcu_DC_refine JPP((j_compress_ptr cinfo,
  165895. JBLOCKROW *MCU_data));
  165896. METHODDEF(boolean) encode_mcu_AC_refine JPP((j_compress_ptr cinfo,
  165897. JBLOCKROW *MCU_data));
  165898. METHODDEF(void) finish_pass_phuff JPP((j_compress_ptr cinfo));
  165899. METHODDEF(void) finish_pass_gather_phuff JPP((j_compress_ptr cinfo));
  165900. /*
  165901. * Initialize for a Huffman-compressed scan using progressive JPEG.
  165902. */
  165903. METHODDEF(void)
  165904. start_pass_phuff (j_compress_ptr cinfo, boolean gather_statistics)
  165905. {
  165906. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165907. boolean is_DC_band;
  165908. int ci, tbl;
  165909. jpeg_component_info * compptr;
  165910. entropy->cinfo = cinfo;
  165911. entropy->gather_statistics = gather_statistics;
  165912. is_DC_band = (cinfo->Ss == 0);
  165913. /* We assume jcmaster.c already validated the scan parameters. */
  165914. /* Select execution routines */
  165915. if (cinfo->Ah == 0) {
  165916. if (is_DC_band)
  165917. entropy->pub.encode_mcu = encode_mcu_DC_first;
  165918. else
  165919. entropy->pub.encode_mcu = encode_mcu_AC_first;
  165920. } else {
  165921. if (is_DC_band)
  165922. entropy->pub.encode_mcu = encode_mcu_DC_refine;
  165923. else {
  165924. entropy->pub.encode_mcu = encode_mcu_AC_refine;
  165925. /* AC refinement needs a correction bit buffer */
  165926. if (entropy->bit_buffer == NULL)
  165927. entropy->bit_buffer = (char *)
  165928. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165929. MAX_CORR_BITS * SIZEOF(char));
  165930. }
  165931. }
  165932. if (gather_statistics)
  165933. entropy->pub.finish_pass = finish_pass_gather_phuff;
  165934. else
  165935. entropy->pub.finish_pass = finish_pass_phuff;
  165936. /* Only DC coefficients may be interleaved, so cinfo->comps_in_scan = 1
  165937. * for AC coefficients.
  165938. */
  165939. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  165940. compptr = cinfo->cur_comp_info[ci];
  165941. /* Initialize DC predictions to 0 */
  165942. entropy->last_dc_val[ci] = 0;
  165943. /* Get table index */
  165944. if (is_DC_band) {
  165945. if (cinfo->Ah != 0) /* DC refinement needs no table */
  165946. continue;
  165947. tbl = compptr->dc_tbl_no;
  165948. } else {
  165949. entropy->ac_tbl_no = tbl = compptr->ac_tbl_no;
  165950. }
  165951. if (gather_statistics) {
  165952. /* Check for invalid table index */
  165953. /* (make_c_derived_tbl does this in the other path) */
  165954. if (tbl < 0 || tbl >= NUM_HUFF_TBLS)
  165955. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
  165956. /* Allocate and zero the statistics tables */
  165957. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  165958. if (entropy->count_ptrs[tbl] == NULL)
  165959. entropy->count_ptrs[tbl] = (long *)
  165960. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165961. 257 * SIZEOF(long));
  165962. MEMZERO(entropy->count_ptrs[tbl], 257 * SIZEOF(long));
  165963. } else {
  165964. /* Compute derived values for Huffman table */
  165965. /* We may do this more than once for a table, but it's not expensive */
  165966. jpeg_make_c_derived_tbl(cinfo, is_DC_band, tbl,
  165967. & entropy->derived_tbls[tbl]);
  165968. }
  165969. }
  165970. /* Initialize AC stuff */
  165971. entropy->EOBRUN = 0;
  165972. entropy->BE = 0;
  165973. /* Initialize bit buffer to empty */
  165974. entropy->put_buffer = 0;
  165975. entropy->put_bits = 0;
  165976. /* Initialize restart stuff */
  165977. entropy->restarts_to_go = cinfo->restart_interval;
  165978. entropy->next_restart_num = 0;
  165979. }
  165980. /* Outputting bytes to the file.
  165981. * NB: these must be called only when actually outputting,
  165982. * that is, entropy->gather_statistics == FALSE.
  165983. */
  165984. /* Emit a byte */
  165985. #define emit_byte(entropy,val) \
  165986. { *(entropy)->next_output_byte++ = (JOCTET) (val); \
  165987. if (--(entropy)->free_in_buffer == 0) \
  165988. dump_buffer_p(entropy); }
  165989. LOCAL(void)
  165990. dump_buffer_p (phuff_entropy_ptr entropy)
  165991. /* Empty the output buffer; we do not support suspension in this module. */
  165992. {
  165993. struct jpeg_destination_mgr * dest = entropy->cinfo->dest;
  165994. if (! (*dest->empty_output_buffer) (entropy->cinfo))
  165995. ERREXIT(entropy->cinfo, JERR_CANT_SUSPEND);
  165996. /* After a successful buffer dump, must reset buffer pointers */
  165997. entropy->next_output_byte = dest->next_output_byte;
  165998. entropy->free_in_buffer = dest->free_in_buffer;
  165999. }
  166000. /* Outputting bits to the file */
  166001. /* Only the right 24 bits of put_buffer are used; the valid bits are
  166002. * left-justified in this part. At most 16 bits can be passed to emit_bits
  166003. * in one call, and we never retain more than 7 bits in put_buffer
  166004. * between calls, so 24 bits are sufficient.
  166005. */
  166006. INLINE
  166007. LOCAL(void)
  166008. emit_bits_p (phuff_entropy_ptr entropy, unsigned int code, int size)
  166009. /* Emit some bits, unless we are in gather mode */
  166010. {
  166011. /* This routine is heavily used, so it's worth coding tightly. */
  166012. register INT32 put_buffer = (INT32) code;
  166013. register int put_bits = entropy->put_bits;
  166014. /* if size is 0, caller used an invalid Huffman table entry */
  166015. if (size == 0)
  166016. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  166017. if (entropy->gather_statistics)
  166018. return; /* do nothing if we're only getting stats */
  166019. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  166020. put_bits += size; /* new number of bits in buffer */
  166021. put_buffer <<= 24 - put_bits; /* align incoming bits */
  166022. put_buffer |= entropy->put_buffer; /* and merge with old buffer contents */
  166023. while (put_bits >= 8) {
  166024. int c = (int) ((put_buffer >> 16) & 0xFF);
  166025. emit_byte(entropy, c);
  166026. if (c == 0xFF) { /* need to stuff a zero byte? */
  166027. emit_byte(entropy, 0);
  166028. }
  166029. put_buffer <<= 8;
  166030. put_bits -= 8;
  166031. }
  166032. entropy->put_buffer = put_buffer; /* update variables */
  166033. entropy->put_bits = put_bits;
  166034. }
  166035. LOCAL(void)
  166036. flush_bits_p (phuff_entropy_ptr entropy)
  166037. {
  166038. emit_bits_p(entropy, 0x7F, 7); /* fill any partial byte with ones */
  166039. entropy->put_buffer = 0; /* and reset bit-buffer to empty */
  166040. entropy->put_bits = 0;
  166041. }
  166042. /*
  166043. * Emit (or just count) a Huffman symbol.
  166044. */
  166045. INLINE
  166046. LOCAL(void)
  166047. emit_symbol (phuff_entropy_ptr entropy, int tbl_no, int symbol)
  166048. {
  166049. if (entropy->gather_statistics)
  166050. entropy->count_ptrs[tbl_no][symbol]++;
  166051. else {
  166052. c_derived_tbl * tbl = entropy->derived_tbls[tbl_no];
  166053. emit_bits_p(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
  166054. }
  166055. }
  166056. /*
  166057. * Emit bits from a correction bit buffer.
  166058. */
  166059. LOCAL(void)
  166060. emit_buffered_bits (phuff_entropy_ptr entropy, char * bufstart,
  166061. unsigned int nbits)
  166062. {
  166063. if (entropy->gather_statistics)
  166064. return; /* no real work */
  166065. while (nbits > 0) {
  166066. emit_bits_p(entropy, (unsigned int) (*bufstart), 1);
  166067. bufstart++;
  166068. nbits--;
  166069. }
  166070. }
  166071. /*
  166072. * Emit any pending EOBRUN symbol.
  166073. */
  166074. LOCAL(void)
  166075. emit_eobrun (phuff_entropy_ptr entropy)
  166076. {
  166077. register int temp, nbits;
  166078. if (entropy->EOBRUN > 0) { /* if there is any pending EOBRUN */
  166079. temp = entropy->EOBRUN;
  166080. nbits = 0;
  166081. while ((temp >>= 1))
  166082. nbits++;
  166083. /* safety check: shouldn't happen given limited correction-bit buffer */
  166084. if (nbits > 14)
  166085. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  166086. emit_symbol(entropy, entropy->ac_tbl_no, nbits << 4);
  166087. if (nbits)
  166088. emit_bits_p(entropy, entropy->EOBRUN, nbits);
  166089. entropy->EOBRUN = 0;
  166090. /* Emit any buffered correction bits */
  166091. emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE);
  166092. entropy->BE = 0;
  166093. }
  166094. }
  166095. /*
  166096. * Emit a restart marker & resynchronize predictions.
  166097. */
  166098. LOCAL(void)
  166099. emit_restart_p (phuff_entropy_ptr entropy, int restart_num)
  166100. {
  166101. int ci;
  166102. emit_eobrun(entropy);
  166103. if (! entropy->gather_statistics) {
  166104. flush_bits_p(entropy);
  166105. emit_byte(entropy, 0xFF);
  166106. emit_byte(entropy, JPEG_RST0 + restart_num);
  166107. }
  166108. if (entropy->cinfo->Ss == 0) {
  166109. /* Re-initialize DC predictions to 0 */
  166110. for (ci = 0; ci < entropy->cinfo->comps_in_scan; ci++)
  166111. entropy->last_dc_val[ci] = 0;
  166112. } else {
  166113. /* Re-initialize all AC-related fields to 0 */
  166114. entropy->EOBRUN = 0;
  166115. entropy->BE = 0;
  166116. }
  166117. }
  166118. /*
  166119. * MCU encoding for DC initial scan (either spectral selection,
  166120. * or first pass of successive approximation).
  166121. */
  166122. METHODDEF(boolean)
  166123. encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166124. {
  166125. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166126. register int temp, temp2;
  166127. register int nbits;
  166128. int blkn, ci;
  166129. int Al = cinfo->Al;
  166130. JBLOCKROW block;
  166131. jpeg_component_info * compptr;
  166132. ISHIFT_TEMPS
  166133. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166134. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166135. /* Emit restart marker if needed */
  166136. if (cinfo->restart_interval)
  166137. if (entropy->restarts_to_go == 0)
  166138. emit_restart_p(entropy, entropy->next_restart_num);
  166139. /* Encode the MCU data blocks */
  166140. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  166141. block = MCU_data[blkn];
  166142. ci = cinfo->MCU_membership[blkn];
  166143. compptr = cinfo->cur_comp_info[ci];
  166144. /* Compute the DC value after the required point transform by Al.
  166145. * This is simply an arithmetic right shift.
  166146. */
  166147. temp2 = IRIGHT_SHIFT((int) ((*block)[0]), Al);
  166148. /* DC differences are figured on the point-transformed values. */
  166149. temp = temp2 - entropy->last_dc_val[ci];
  166150. entropy->last_dc_val[ci] = temp2;
  166151. /* Encode the DC coefficient difference per section G.1.2.1 */
  166152. temp2 = temp;
  166153. if (temp < 0) {
  166154. temp = -temp; /* temp is abs value of input */
  166155. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  166156. /* This code assumes we are on a two's complement machine */
  166157. temp2--;
  166158. }
  166159. /* Find the number of bits needed for the magnitude of the coefficient */
  166160. nbits = 0;
  166161. while (temp) {
  166162. nbits++;
  166163. temp >>= 1;
  166164. }
  166165. /* Check for out-of-range coefficient values.
  166166. * Since we're encoding a difference, the range limit is twice as much.
  166167. */
  166168. if (nbits > MAX_COEF_BITS+1)
  166169. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  166170. /* Count/emit the Huffman-coded symbol for the number of bits */
  166171. emit_symbol(entropy, compptr->dc_tbl_no, nbits);
  166172. /* Emit that number of bits of the value, if positive, */
  166173. /* or the complement of its magnitude, if negative. */
  166174. if (nbits) /* emit_bits rejects calls with size 0 */
  166175. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  166176. }
  166177. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166178. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166179. /* Update restart-interval state too */
  166180. if (cinfo->restart_interval) {
  166181. if (entropy->restarts_to_go == 0) {
  166182. entropy->restarts_to_go = cinfo->restart_interval;
  166183. entropy->next_restart_num++;
  166184. entropy->next_restart_num &= 7;
  166185. }
  166186. entropy->restarts_to_go--;
  166187. }
  166188. return TRUE;
  166189. }
  166190. /*
  166191. * MCU encoding for AC initial scan (either spectral selection,
  166192. * or first pass of successive approximation).
  166193. */
  166194. METHODDEF(boolean)
  166195. encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166196. {
  166197. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166198. register int temp, temp2;
  166199. register int nbits;
  166200. register int r, k;
  166201. int Se = cinfo->Se;
  166202. int Al = cinfo->Al;
  166203. JBLOCKROW block;
  166204. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166205. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166206. /* Emit restart marker if needed */
  166207. if (cinfo->restart_interval)
  166208. if (entropy->restarts_to_go == 0)
  166209. emit_restart_p(entropy, entropy->next_restart_num);
  166210. /* Encode the MCU data block */
  166211. block = MCU_data[0];
  166212. /* Encode the AC coefficients per section G.1.2.2, fig. G.3 */
  166213. r = 0; /* r = run length of zeros */
  166214. for (k = cinfo->Ss; k <= Se; k++) {
  166215. if ((temp = (*block)[jpeg_natural_order[k]]) == 0) {
  166216. r++;
  166217. continue;
  166218. }
  166219. /* We must apply the point transform by Al. For AC coefficients this
  166220. * is an integer division with rounding towards 0. To do this portably
  166221. * in C, we shift after obtaining the absolute value; so the code is
  166222. * interwoven with finding the abs value (temp) and output bits (temp2).
  166223. */
  166224. if (temp < 0) {
  166225. temp = -temp; /* temp is abs value of input */
  166226. temp >>= Al; /* apply the point transform */
  166227. /* For a negative coef, want temp2 = bitwise complement of abs(coef) */
  166228. temp2 = ~temp;
  166229. } else {
  166230. temp >>= Al; /* apply the point transform */
  166231. temp2 = temp;
  166232. }
  166233. /* Watch out for case that nonzero coef is zero after point transform */
  166234. if (temp == 0) {
  166235. r++;
  166236. continue;
  166237. }
  166238. /* Emit any pending EOBRUN */
  166239. if (entropy->EOBRUN > 0)
  166240. emit_eobrun(entropy);
  166241. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  166242. while (r > 15) {
  166243. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  166244. r -= 16;
  166245. }
  166246. /* Find the number of bits needed for the magnitude of the coefficient */
  166247. nbits = 1; /* there must be at least one 1 bit */
  166248. while ((temp >>= 1))
  166249. nbits++;
  166250. /* Check for out-of-range coefficient values */
  166251. if (nbits > MAX_COEF_BITS)
  166252. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  166253. /* Count/emit Huffman symbol for run length / number of bits */
  166254. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + nbits);
  166255. /* Emit that number of bits of the value, if positive, */
  166256. /* or the complement of its magnitude, if negative. */
  166257. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  166258. r = 0; /* reset zero run length */
  166259. }
  166260. if (r > 0) { /* If there are trailing zeroes, */
  166261. entropy->EOBRUN++; /* count an EOB */
  166262. if (entropy->EOBRUN == 0x7FFF)
  166263. emit_eobrun(entropy); /* force it out to avoid overflow */
  166264. }
  166265. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166266. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166267. /* Update restart-interval state too */
  166268. if (cinfo->restart_interval) {
  166269. if (entropy->restarts_to_go == 0) {
  166270. entropy->restarts_to_go = cinfo->restart_interval;
  166271. entropy->next_restart_num++;
  166272. entropy->next_restart_num &= 7;
  166273. }
  166274. entropy->restarts_to_go--;
  166275. }
  166276. return TRUE;
  166277. }
  166278. /*
  166279. * MCU encoding for DC successive approximation refinement scan.
  166280. * Note: we assume such scans can be multi-component, although the spec
  166281. * is not very clear on the point.
  166282. */
  166283. METHODDEF(boolean)
  166284. encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166285. {
  166286. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166287. register int temp;
  166288. int blkn;
  166289. int Al = cinfo->Al;
  166290. JBLOCKROW block;
  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 blocks */
  166298. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  166299. block = MCU_data[blkn];
  166300. /* We simply emit the Al'th bit of the DC coefficient value. */
  166301. temp = (*block)[0];
  166302. emit_bits_p(entropy, (unsigned int) (temp >> Al), 1);
  166303. }
  166304. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166305. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166306. /* Update restart-interval state too */
  166307. if (cinfo->restart_interval) {
  166308. if (entropy->restarts_to_go == 0) {
  166309. entropy->restarts_to_go = cinfo->restart_interval;
  166310. entropy->next_restart_num++;
  166311. entropy->next_restart_num &= 7;
  166312. }
  166313. entropy->restarts_to_go--;
  166314. }
  166315. return TRUE;
  166316. }
  166317. /*
  166318. * MCU encoding for AC successive approximation refinement scan.
  166319. */
  166320. METHODDEF(boolean)
  166321. encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166322. {
  166323. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166324. register int temp;
  166325. register int r, k;
  166326. int EOB;
  166327. char *BR_buffer;
  166328. unsigned int BR;
  166329. int Se = cinfo->Se;
  166330. int Al = cinfo->Al;
  166331. JBLOCKROW block;
  166332. int absvalues[DCTSIZE2];
  166333. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166334. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166335. /* Emit restart marker if needed */
  166336. if (cinfo->restart_interval)
  166337. if (entropy->restarts_to_go == 0)
  166338. emit_restart_p(entropy, entropy->next_restart_num);
  166339. /* Encode the MCU data block */
  166340. block = MCU_data[0];
  166341. /* It is convenient to make a pre-pass to determine the transformed
  166342. * coefficients' absolute values and the EOB position.
  166343. */
  166344. EOB = 0;
  166345. for (k = cinfo->Ss; k <= Se; k++) {
  166346. temp = (*block)[jpeg_natural_order[k]];
  166347. /* We must apply the point transform by Al. For AC coefficients this
  166348. * is an integer division with rounding towards 0. To do this portably
  166349. * in C, we shift after obtaining the absolute value.
  166350. */
  166351. if (temp < 0)
  166352. temp = -temp; /* temp is abs value of input */
  166353. temp >>= Al; /* apply the point transform */
  166354. absvalues[k] = temp; /* save abs value for main pass */
  166355. if (temp == 1)
  166356. EOB = k; /* EOB = index of last newly-nonzero coef */
  166357. }
  166358. /* Encode the AC coefficients per section G.1.2.3, fig. G.7 */
  166359. r = 0; /* r = run length of zeros */
  166360. BR = 0; /* BR = count of buffered bits added now */
  166361. BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */
  166362. for (k = cinfo->Ss; k <= Se; k++) {
  166363. if ((temp = absvalues[k]) == 0) {
  166364. r++;
  166365. continue;
  166366. }
  166367. /* Emit any required ZRLs, but not if they can be folded into EOB */
  166368. while (r > 15 && k <= EOB) {
  166369. /* emit any pending EOBRUN and the BE correction bits */
  166370. emit_eobrun(entropy);
  166371. /* Emit ZRL */
  166372. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  166373. r -= 16;
  166374. /* Emit buffered correction bits that must be associated with ZRL */
  166375. emit_buffered_bits(entropy, BR_buffer, BR);
  166376. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  166377. BR = 0;
  166378. }
  166379. /* If the coef was previously nonzero, it only needs a correction bit.
  166380. * NOTE: a straight translation of the spec's figure G.7 would suggest
  166381. * that we also need to test r > 15. But if r > 15, we can only get here
  166382. * if k > EOB, which implies that this coefficient is not 1.
  166383. */
  166384. if (temp > 1) {
  166385. /* The correction bit is the next bit of the absolute value. */
  166386. BR_buffer[BR++] = (char) (temp & 1);
  166387. continue;
  166388. }
  166389. /* Emit any pending EOBRUN and the BE correction bits */
  166390. emit_eobrun(entropy);
  166391. /* Count/emit Huffman symbol for run length / number of bits */
  166392. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + 1);
  166393. /* Emit output bit for newly-nonzero coef */
  166394. temp = ((*block)[jpeg_natural_order[k]] < 0) ? 0 : 1;
  166395. emit_bits_p(entropy, (unsigned int) temp, 1);
  166396. /* Emit buffered correction bits that must be associated with this code */
  166397. emit_buffered_bits(entropy, BR_buffer, BR);
  166398. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  166399. BR = 0;
  166400. r = 0; /* reset zero run length */
  166401. }
  166402. if (r > 0 || BR > 0) { /* If there are trailing zeroes, */
  166403. entropy->EOBRUN++; /* count an EOB */
  166404. entropy->BE += BR; /* concat my correction bits to older ones */
  166405. /* We force out the EOB if we risk either:
  166406. * 1. overflow of the EOB counter;
  166407. * 2. overflow of the correction bit buffer during the next MCU.
  166408. */
  166409. if (entropy->EOBRUN == 0x7FFF || entropy->BE > (MAX_CORR_BITS-DCTSIZE2+1))
  166410. emit_eobrun(entropy);
  166411. }
  166412. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166413. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166414. /* Update restart-interval state too */
  166415. if (cinfo->restart_interval) {
  166416. if (entropy->restarts_to_go == 0) {
  166417. entropy->restarts_to_go = cinfo->restart_interval;
  166418. entropy->next_restart_num++;
  166419. entropy->next_restart_num &= 7;
  166420. }
  166421. entropy->restarts_to_go--;
  166422. }
  166423. return TRUE;
  166424. }
  166425. /*
  166426. * Finish up at the end of a Huffman-compressed progressive scan.
  166427. */
  166428. METHODDEF(void)
  166429. finish_pass_phuff (j_compress_ptr cinfo)
  166430. {
  166431. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166432. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166433. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166434. /* Flush out any buffered data */
  166435. emit_eobrun(entropy);
  166436. flush_bits_p(entropy);
  166437. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166438. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166439. }
  166440. /*
  166441. * Finish up a statistics-gathering pass and create the new Huffman tables.
  166442. */
  166443. METHODDEF(void)
  166444. finish_pass_gather_phuff (j_compress_ptr cinfo)
  166445. {
  166446. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166447. boolean is_DC_band;
  166448. int ci, tbl;
  166449. jpeg_component_info * compptr;
  166450. JHUFF_TBL **htblptr;
  166451. boolean did[NUM_HUFF_TBLS];
  166452. /* Flush out buffered data (all we care about is counting the EOB symbol) */
  166453. emit_eobrun(entropy);
  166454. is_DC_band = (cinfo->Ss == 0);
  166455. /* It's important not to apply jpeg_gen_optimal_table more than once
  166456. * per table, because it clobbers the input frequency counts!
  166457. */
  166458. MEMZERO(did, SIZEOF(did));
  166459. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166460. compptr = cinfo->cur_comp_info[ci];
  166461. if (is_DC_band) {
  166462. if (cinfo->Ah != 0) /* DC refinement needs no table */
  166463. continue;
  166464. tbl = compptr->dc_tbl_no;
  166465. } else {
  166466. tbl = compptr->ac_tbl_no;
  166467. }
  166468. if (! did[tbl]) {
  166469. if (is_DC_band)
  166470. htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];
  166471. else
  166472. htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];
  166473. if (*htblptr == NULL)
  166474. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  166475. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->count_ptrs[tbl]);
  166476. did[tbl] = TRUE;
  166477. }
  166478. }
  166479. }
  166480. /*
  166481. * Module initialization routine for progressive Huffman entropy encoding.
  166482. */
  166483. GLOBAL(void)
  166484. jinit_phuff_encoder (j_compress_ptr cinfo)
  166485. {
  166486. phuff_entropy_ptr entropy;
  166487. int i;
  166488. entropy = (phuff_entropy_ptr)
  166489. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166490. SIZEOF(phuff_entropy_encoder));
  166491. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  166492. entropy->pub.start_pass = start_pass_phuff;
  166493. /* Mark tables unallocated */
  166494. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  166495. entropy->derived_tbls[i] = NULL;
  166496. entropy->count_ptrs[i] = NULL;
  166497. }
  166498. entropy->bit_buffer = NULL; /* needed only in AC refinement scan */
  166499. }
  166500. #endif /* C_PROGRESSIVE_SUPPORTED */
  166501. /*** End of inlined file: jcphuff.c ***/
  166502. /*** Start of inlined file: jcprepct.c ***/
  166503. #define JPEG_INTERNALS
  166504. /* At present, jcsample.c can request context rows only for smoothing.
  166505. * In the future, we might also need context rows for CCIR601 sampling
  166506. * or other more-complex downsampling procedures. The code to support
  166507. * context rows should be compiled only if needed.
  166508. */
  166509. #ifdef INPUT_SMOOTHING_SUPPORTED
  166510. #define CONTEXT_ROWS_SUPPORTED
  166511. #endif
  166512. /*
  166513. * For the simple (no-context-row) case, we just need to buffer one
  166514. * row group's worth of pixels for the downsampling step. At the bottom of
  166515. * the image, we pad to a full row group by replicating the last pixel row.
  166516. * The downsampler's last output row is then replicated if needed to pad
  166517. * out to a full iMCU row.
  166518. *
  166519. * When providing context rows, we must buffer three row groups' worth of
  166520. * pixels. Three row groups are physically allocated, but the row pointer
  166521. * arrays are made five row groups high, with the extra pointers above and
  166522. * below "wrapping around" to point to the last and first real row groups.
  166523. * This allows the downsampler to access the proper context rows.
  166524. * At the top and bottom of the image, we create dummy context rows by
  166525. * copying the first or last real pixel row. This copying could be avoided
  166526. * by pointer hacking as is done in jdmainct.c, but it doesn't seem worth the
  166527. * trouble on the compression side.
  166528. */
  166529. /* Private buffer controller object */
  166530. typedef struct {
  166531. struct jpeg_c_prep_controller pub; /* public fields */
  166532. /* Downsampling input buffer. This buffer holds color-converted data
  166533. * until we have enough to do a downsample step.
  166534. */
  166535. JSAMPARRAY color_buf[MAX_COMPONENTS];
  166536. JDIMENSION rows_to_go; /* counts rows remaining in source image */
  166537. int next_buf_row; /* index of next row to store in color_buf */
  166538. #ifdef CONTEXT_ROWS_SUPPORTED /* only needed for context case */
  166539. int this_row_group; /* starting row index of group to process */
  166540. int next_buf_stop; /* downsample when we reach this index */
  166541. #endif
  166542. } my_prep_controller;
  166543. typedef my_prep_controller * my_prep_ptr;
  166544. /*
  166545. * Initialize for a processing pass.
  166546. */
  166547. METHODDEF(void)
  166548. start_pass_prep (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  166549. {
  166550. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166551. if (pass_mode != JBUF_PASS_THRU)
  166552. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166553. /* Initialize total-height counter for detecting bottom of image */
  166554. prep->rows_to_go = cinfo->image_height;
  166555. /* Mark the conversion buffer empty */
  166556. prep->next_buf_row = 0;
  166557. #ifdef CONTEXT_ROWS_SUPPORTED
  166558. /* Preset additional state variables for context mode.
  166559. * These aren't used in non-context mode, so we needn't test which mode.
  166560. */
  166561. prep->this_row_group = 0;
  166562. /* Set next_buf_stop to stop after two row groups have been read in. */
  166563. prep->next_buf_stop = 2 * cinfo->max_v_samp_factor;
  166564. #endif
  166565. }
  166566. /*
  166567. * Expand an image vertically from height input_rows to height output_rows,
  166568. * by duplicating the bottom row.
  166569. */
  166570. LOCAL(void)
  166571. expand_bottom_edge (JSAMPARRAY image_data, JDIMENSION num_cols,
  166572. int input_rows, int output_rows)
  166573. {
  166574. register int row;
  166575. for (row = input_rows; row < output_rows; row++) {
  166576. jcopy_sample_rows(image_data, input_rows-1, image_data, row,
  166577. 1, num_cols);
  166578. }
  166579. }
  166580. /*
  166581. * Process some data in the simple no-context case.
  166582. *
  166583. * Preprocessor output data is counted in "row groups". A row group
  166584. * is defined to be v_samp_factor sample rows of each component.
  166585. * Downsampling will produce this much data from each max_v_samp_factor
  166586. * input rows.
  166587. */
  166588. METHODDEF(void)
  166589. pre_process_data (j_compress_ptr cinfo,
  166590. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  166591. JDIMENSION in_rows_avail,
  166592. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  166593. JDIMENSION out_row_groups_avail)
  166594. {
  166595. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166596. int numrows, ci;
  166597. JDIMENSION inrows;
  166598. jpeg_component_info * compptr;
  166599. while (*in_row_ctr < in_rows_avail &&
  166600. *out_row_group_ctr < out_row_groups_avail) {
  166601. /* Do color conversion to fill the conversion buffer. */
  166602. inrows = in_rows_avail - *in_row_ctr;
  166603. numrows = cinfo->max_v_samp_factor - prep->next_buf_row;
  166604. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  166605. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  166606. prep->color_buf,
  166607. (JDIMENSION) prep->next_buf_row,
  166608. numrows);
  166609. *in_row_ctr += numrows;
  166610. prep->next_buf_row += numrows;
  166611. prep->rows_to_go -= numrows;
  166612. /* If at bottom of image, pad to fill the conversion buffer. */
  166613. if (prep->rows_to_go == 0 &&
  166614. prep->next_buf_row < cinfo->max_v_samp_factor) {
  166615. for (ci = 0; ci < cinfo->num_components; ci++) {
  166616. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  166617. prep->next_buf_row, cinfo->max_v_samp_factor);
  166618. }
  166619. prep->next_buf_row = cinfo->max_v_samp_factor;
  166620. }
  166621. /* If we've filled the conversion buffer, empty it. */
  166622. if (prep->next_buf_row == cinfo->max_v_samp_factor) {
  166623. (*cinfo->downsample->downsample) (cinfo,
  166624. prep->color_buf, (JDIMENSION) 0,
  166625. output_buf, *out_row_group_ctr);
  166626. prep->next_buf_row = 0;
  166627. (*out_row_group_ctr)++;
  166628. }
  166629. /* If at bottom of image, pad the output to a full iMCU height.
  166630. * Note we assume the caller is providing a one-iMCU-height output buffer!
  166631. */
  166632. if (prep->rows_to_go == 0 &&
  166633. *out_row_group_ctr < out_row_groups_avail) {
  166634. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166635. ci++, compptr++) {
  166636. expand_bottom_edge(output_buf[ci],
  166637. compptr->width_in_blocks * DCTSIZE,
  166638. (int) (*out_row_group_ctr * compptr->v_samp_factor),
  166639. (int) (out_row_groups_avail * compptr->v_samp_factor));
  166640. }
  166641. *out_row_group_ctr = out_row_groups_avail;
  166642. break; /* can exit outer loop without test */
  166643. }
  166644. }
  166645. }
  166646. #ifdef CONTEXT_ROWS_SUPPORTED
  166647. /*
  166648. * Process some data in the context case.
  166649. */
  166650. METHODDEF(void)
  166651. pre_process_context (j_compress_ptr cinfo,
  166652. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  166653. JDIMENSION in_rows_avail,
  166654. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  166655. JDIMENSION out_row_groups_avail)
  166656. {
  166657. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166658. int numrows, ci;
  166659. int buf_height = cinfo->max_v_samp_factor * 3;
  166660. JDIMENSION inrows;
  166661. while (*out_row_group_ctr < out_row_groups_avail) {
  166662. if (*in_row_ctr < in_rows_avail) {
  166663. /* Do color conversion to fill the conversion buffer. */
  166664. inrows = in_rows_avail - *in_row_ctr;
  166665. numrows = prep->next_buf_stop - prep->next_buf_row;
  166666. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  166667. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  166668. prep->color_buf,
  166669. (JDIMENSION) prep->next_buf_row,
  166670. numrows);
  166671. /* Pad at top of image, if first time through */
  166672. if (prep->rows_to_go == cinfo->image_height) {
  166673. for (ci = 0; ci < cinfo->num_components; ci++) {
  166674. int row;
  166675. for (row = 1; row <= cinfo->max_v_samp_factor; row++) {
  166676. jcopy_sample_rows(prep->color_buf[ci], 0,
  166677. prep->color_buf[ci], -row,
  166678. 1, cinfo->image_width);
  166679. }
  166680. }
  166681. }
  166682. *in_row_ctr += numrows;
  166683. prep->next_buf_row += numrows;
  166684. prep->rows_to_go -= numrows;
  166685. } else {
  166686. /* Return for more data, unless we are at the bottom of the image. */
  166687. if (prep->rows_to_go != 0)
  166688. break;
  166689. /* When at bottom of image, pad to fill the conversion buffer. */
  166690. if (prep->next_buf_row < prep->next_buf_stop) {
  166691. for (ci = 0; ci < cinfo->num_components; ci++) {
  166692. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  166693. prep->next_buf_row, prep->next_buf_stop);
  166694. }
  166695. prep->next_buf_row = prep->next_buf_stop;
  166696. }
  166697. }
  166698. /* If we've gotten enough data, downsample a row group. */
  166699. if (prep->next_buf_row == prep->next_buf_stop) {
  166700. (*cinfo->downsample->downsample) (cinfo,
  166701. prep->color_buf,
  166702. (JDIMENSION) prep->this_row_group,
  166703. output_buf, *out_row_group_ctr);
  166704. (*out_row_group_ctr)++;
  166705. /* Advance pointers with wraparound as necessary. */
  166706. prep->this_row_group += cinfo->max_v_samp_factor;
  166707. if (prep->this_row_group >= buf_height)
  166708. prep->this_row_group = 0;
  166709. if (prep->next_buf_row >= buf_height)
  166710. prep->next_buf_row = 0;
  166711. prep->next_buf_stop = prep->next_buf_row + cinfo->max_v_samp_factor;
  166712. }
  166713. }
  166714. }
  166715. /*
  166716. * Create the wrapped-around downsampling input buffer needed for context mode.
  166717. */
  166718. LOCAL(void)
  166719. create_context_buffer (j_compress_ptr cinfo)
  166720. {
  166721. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166722. int rgroup_height = cinfo->max_v_samp_factor;
  166723. int ci, i;
  166724. jpeg_component_info * compptr;
  166725. JSAMPARRAY true_buffer, fake_buffer;
  166726. /* Grab enough space for fake row pointers for all the components;
  166727. * we need five row groups' worth of pointers for each component.
  166728. */
  166729. fake_buffer = (JSAMPARRAY)
  166730. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166731. (cinfo->num_components * 5 * rgroup_height) *
  166732. SIZEOF(JSAMPROW));
  166733. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166734. ci++, compptr++) {
  166735. /* Allocate the actual buffer space (3 row groups) for this component.
  166736. * We make the buffer wide enough to allow the downsampler to edge-expand
  166737. * horizontally within the buffer, if it so chooses.
  166738. */
  166739. true_buffer = (*cinfo->mem->alloc_sarray)
  166740. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166741. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  166742. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  166743. (JDIMENSION) (3 * rgroup_height));
  166744. /* Copy true buffer row pointers into the middle of the fake row array */
  166745. MEMCOPY(fake_buffer + rgroup_height, true_buffer,
  166746. 3 * rgroup_height * SIZEOF(JSAMPROW));
  166747. /* Fill in the above and below wraparound pointers */
  166748. for (i = 0; i < rgroup_height; i++) {
  166749. fake_buffer[i] = true_buffer[2 * rgroup_height + i];
  166750. fake_buffer[4 * rgroup_height + i] = true_buffer[i];
  166751. }
  166752. prep->color_buf[ci] = fake_buffer + rgroup_height;
  166753. fake_buffer += 5 * rgroup_height; /* point to space for next component */
  166754. }
  166755. }
  166756. #endif /* CONTEXT_ROWS_SUPPORTED */
  166757. /*
  166758. * Initialize preprocessing controller.
  166759. */
  166760. GLOBAL(void)
  166761. jinit_c_prep_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  166762. {
  166763. my_prep_ptr prep;
  166764. int ci;
  166765. jpeg_component_info * compptr;
  166766. if (need_full_buffer) /* safety check */
  166767. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166768. prep = (my_prep_ptr)
  166769. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166770. SIZEOF(my_prep_controller));
  166771. cinfo->prep = (struct jpeg_c_prep_controller *) prep;
  166772. prep->pub.start_pass = start_pass_prep;
  166773. /* Allocate the color conversion buffer.
  166774. * We make the buffer wide enough to allow the downsampler to edge-expand
  166775. * horizontally within the buffer, if it so chooses.
  166776. */
  166777. if (cinfo->downsample->need_context_rows) {
  166778. /* Set up to provide context rows */
  166779. #ifdef CONTEXT_ROWS_SUPPORTED
  166780. prep->pub.pre_process_data = pre_process_context;
  166781. create_context_buffer(cinfo);
  166782. #else
  166783. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166784. #endif
  166785. } else {
  166786. /* No context, just make it tall enough for one row group */
  166787. prep->pub.pre_process_data = pre_process_data;
  166788. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166789. ci++, compptr++) {
  166790. prep->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  166791. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166792. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  166793. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  166794. (JDIMENSION) cinfo->max_v_samp_factor);
  166795. }
  166796. }
  166797. }
  166798. /*** End of inlined file: jcprepct.c ***/
  166799. /*** Start of inlined file: jcsample.c ***/
  166800. #define JPEG_INTERNALS
  166801. /* Pointer to routine to downsample a single component */
  166802. typedef JMETHOD(void, downsample1_ptr,
  166803. (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166804. JSAMPARRAY input_data, JSAMPARRAY output_data));
  166805. /* Private subobject */
  166806. typedef struct {
  166807. struct jpeg_downsampler pub; /* public fields */
  166808. /* Downsampling method pointers, one per component */
  166809. downsample1_ptr methods[MAX_COMPONENTS];
  166810. } my_downsampler;
  166811. typedef my_downsampler * my_downsample_ptr;
  166812. /*
  166813. * Initialize for a downsampling pass.
  166814. */
  166815. METHODDEF(void)
  166816. start_pass_downsample (j_compress_ptr)
  166817. {
  166818. /* no work for now */
  166819. }
  166820. /*
  166821. * Expand a component horizontally from width input_cols to width output_cols,
  166822. * by duplicating the rightmost samples.
  166823. */
  166824. LOCAL(void)
  166825. expand_right_edge (JSAMPARRAY image_data, int num_rows,
  166826. JDIMENSION input_cols, JDIMENSION output_cols)
  166827. {
  166828. register JSAMPROW ptr;
  166829. register JSAMPLE pixval;
  166830. register int count;
  166831. int row;
  166832. int numcols = (int) (output_cols - input_cols);
  166833. if (numcols > 0) {
  166834. for (row = 0; row < num_rows; row++) {
  166835. ptr = image_data[row] + input_cols;
  166836. pixval = ptr[-1]; /* don't need GETJSAMPLE() here */
  166837. for (count = numcols; count > 0; count--)
  166838. *ptr++ = pixval;
  166839. }
  166840. }
  166841. }
  166842. /*
  166843. * Do downsampling for a whole row group (all components).
  166844. *
  166845. * In this version we simply downsample each component independently.
  166846. */
  166847. METHODDEF(void)
  166848. sep_downsample (j_compress_ptr cinfo,
  166849. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  166850. JSAMPIMAGE output_buf, JDIMENSION out_row_group_index)
  166851. {
  166852. my_downsample_ptr downsample = (my_downsample_ptr) cinfo->downsample;
  166853. int ci;
  166854. jpeg_component_info * compptr;
  166855. JSAMPARRAY in_ptr, out_ptr;
  166856. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166857. ci++, compptr++) {
  166858. in_ptr = input_buf[ci] + in_row_index;
  166859. out_ptr = output_buf[ci] + (out_row_group_index * compptr->v_samp_factor);
  166860. (*downsample->methods[ci]) (cinfo, compptr, in_ptr, out_ptr);
  166861. }
  166862. }
  166863. /*
  166864. * Downsample pixel values of a single component.
  166865. * One row group is processed per call.
  166866. * This version handles arbitrary integral sampling ratios, without smoothing.
  166867. * Note that this version is not actually used for customary sampling ratios.
  166868. */
  166869. METHODDEF(void)
  166870. int_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166871. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166872. {
  166873. int inrow, outrow, h_expand, v_expand, numpix, numpix2, h, v;
  166874. JDIMENSION outcol, outcol_h; /* outcol_h == outcol*h_expand */
  166875. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166876. JSAMPROW inptr, outptr;
  166877. INT32 outvalue;
  166878. h_expand = cinfo->max_h_samp_factor / compptr->h_samp_factor;
  166879. v_expand = cinfo->max_v_samp_factor / compptr->v_samp_factor;
  166880. numpix = h_expand * v_expand;
  166881. numpix2 = numpix/2;
  166882. /* Expand input data enough to let all the output samples be generated
  166883. * by the standard loop. Special-casing padded output would be more
  166884. * efficient.
  166885. */
  166886. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  166887. cinfo->image_width, output_cols * h_expand);
  166888. inrow = 0;
  166889. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166890. outptr = output_data[outrow];
  166891. for (outcol = 0, outcol_h = 0; outcol < output_cols;
  166892. outcol++, outcol_h += h_expand) {
  166893. outvalue = 0;
  166894. for (v = 0; v < v_expand; v++) {
  166895. inptr = input_data[inrow+v] + outcol_h;
  166896. for (h = 0; h < h_expand; h++) {
  166897. outvalue += (INT32) GETJSAMPLE(*inptr++);
  166898. }
  166899. }
  166900. *outptr++ = (JSAMPLE) ((outvalue + numpix2) / numpix);
  166901. }
  166902. inrow += v_expand;
  166903. }
  166904. }
  166905. /*
  166906. * Downsample pixel values of a single component.
  166907. * This version handles the special case of a full-size component,
  166908. * without smoothing.
  166909. */
  166910. METHODDEF(void)
  166911. fullsize_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166912. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166913. {
  166914. /* Copy the data */
  166915. jcopy_sample_rows(input_data, 0, output_data, 0,
  166916. cinfo->max_v_samp_factor, cinfo->image_width);
  166917. /* Edge-expand */
  166918. expand_right_edge(output_data, cinfo->max_v_samp_factor,
  166919. cinfo->image_width, compptr->width_in_blocks * DCTSIZE);
  166920. }
  166921. /*
  166922. * Downsample pixel values of a single component.
  166923. * This version handles the common case of 2:1 horizontal and 1:1 vertical,
  166924. * without smoothing.
  166925. *
  166926. * A note about the "bias" calculations: when rounding fractional values to
  166927. * integer, we do not want to always round 0.5 up to the next integer.
  166928. * If we did that, we'd introduce a noticeable bias towards larger values.
  166929. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  166930. * alternate pixel locations (a simple ordered dither pattern).
  166931. */
  166932. METHODDEF(void)
  166933. h2v1_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166934. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166935. {
  166936. int outrow;
  166937. JDIMENSION outcol;
  166938. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166939. register JSAMPROW inptr, outptr;
  166940. register int bias;
  166941. /* Expand input data enough to let all the output samples be generated
  166942. * by the standard loop. Special-casing padded output would be more
  166943. * efficient.
  166944. */
  166945. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  166946. cinfo->image_width, output_cols * 2);
  166947. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166948. outptr = output_data[outrow];
  166949. inptr = input_data[outrow];
  166950. bias = 0; /* bias = 0,1,0,1,... for successive samples */
  166951. for (outcol = 0; outcol < output_cols; outcol++) {
  166952. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr) + GETJSAMPLE(inptr[1])
  166953. + bias) >> 1);
  166954. bias ^= 1; /* 0=>1, 1=>0 */
  166955. inptr += 2;
  166956. }
  166957. }
  166958. }
  166959. /*
  166960. * Downsample pixel values of a single component.
  166961. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  166962. * without smoothing.
  166963. */
  166964. METHODDEF(void)
  166965. h2v2_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166966. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166967. {
  166968. int inrow, outrow;
  166969. JDIMENSION outcol;
  166970. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166971. register JSAMPROW inptr0, inptr1, outptr;
  166972. register int bias;
  166973. /* Expand input data enough to let all the output samples be generated
  166974. * by the standard loop. Special-casing padded output would be more
  166975. * efficient.
  166976. */
  166977. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  166978. cinfo->image_width, output_cols * 2);
  166979. inrow = 0;
  166980. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166981. outptr = output_data[outrow];
  166982. inptr0 = input_data[inrow];
  166983. inptr1 = input_data[inrow+1];
  166984. bias = 1; /* bias = 1,2,1,2,... for successive samples */
  166985. for (outcol = 0; outcol < output_cols; outcol++) {
  166986. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166987. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1])
  166988. + bias) >> 2);
  166989. bias ^= 3; /* 1=>2, 2=>1 */
  166990. inptr0 += 2; inptr1 += 2;
  166991. }
  166992. inrow += 2;
  166993. }
  166994. }
  166995. #ifdef INPUT_SMOOTHING_SUPPORTED
  166996. /*
  166997. * Downsample pixel values of a single component.
  166998. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  166999. * with smoothing. One row of context is required.
  167000. */
  167001. METHODDEF(void)
  167002. h2v2_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  167003. JSAMPARRAY input_data, JSAMPARRAY output_data)
  167004. {
  167005. int inrow, outrow;
  167006. JDIMENSION colctr;
  167007. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  167008. register JSAMPROW inptr0, inptr1, above_ptr, below_ptr, outptr;
  167009. INT32 membersum, neighsum, memberscale, neighscale;
  167010. /* Expand input data enough to let all the output samples be generated
  167011. * by the standard loop. Special-casing padded output would be more
  167012. * efficient.
  167013. */
  167014. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  167015. cinfo->image_width, output_cols * 2);
  167016. /* We don't bother to form the individual "smoothed" input pixel values;
  167017. * we can directly compute the output which is the average of the four
  167018. * smoothed values. Each of the four member pixels contributes a fraction
  167019. * (1-8*SF) to its own smoothed image and a fraction SF to each of the three
  167020. * other smoothed pixels, therefore a total fraction (1-5*SF)/4 to the final
  167021. * output. The four corner-adjacent neighbor pixels contribute a fraction
  167022. * SF to just one smoothed pixel, or SF/4 to the final output; while the
  167023. * eight edge-adjacent neighbors contribute SF to each of two smoothed
  167024. * pixels, or SF/2 overall. In order to use integer arithmetic, these
  167025. * factors are scaled by 2^16 = 65536.
  167026. * Also recall that SF = smoothing_factor / 1024.
  167027. */
  167028. memberscale = 16384 - cinfo->smoothing_factor * 80; /* scaled (1-5*SF)/4 */
  167029. neighscale = cinfo->smoothing_factor * 16; /* scaled SF/4 */
  167030. inrow = 0;
  167031. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  167032. outptr = output_data[outrow];
  167033. inptr0 = input_data[inrow];
  167034. inptr1 = input_data[inrow+1];
  167035. above_ptr = input_data[inrow-1];
  167036. below_ptr = input_data[inrow+2];
  167037. /* Special case for first column: pretend column -1 is same as column 0 */
  167038. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  167039. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  167040. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  167041. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  167042. GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[2]) +
  167043. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[2]);
  167044. neighsum += neighsum;
  167045. neighsum += GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[2]) +
  167046. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[2]);
  167047. membersum = membersum * memberscale + neighsum * neighscale;
  167048. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  167049. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  167050. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  167051. /* sum of pixels directly mapped to this output element */
  167052. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  167053. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  167054. /* sum of edge-neighbor pixels */
  167055. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  167056. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  167057. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[2]) +
  167058. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[2]);
  167059. /* The edge-neighbors count twice as much as corner-neighbors */
  167060. neighsum += neighsum;
  167061. /* Add in the corner-neighbors */
  167062. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[2]) +
  167063. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[2]);
  167064. /* form final output scaled up by 2^16 */
  167065. membersum = membersum * memberscale + neighsum * neighscale;
  167066. /* round, descale and output it */
  167067. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  167068. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  167069. }
  167070. /* Special case for last column */
  167071. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  167072. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  167073. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  167074. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  167075. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[1]) +
  167076. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[1]);
  167077. neighsum += neighsum;
  167078. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[1]) +
  167079. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[1]);
  167080. membersum = membersum * memberscale + neighsum * neighscale;
  167081. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  167082. inrow += 2;
  167083. }
  167084. }
  167085. /*
  167086. * Downsample pixel values of a single component.
  167087. * This version handles the special case of a full-size component,
  167088. * with smoothing. One row of context is required.
  167089. */
  167090. METHODDEF(void)
  167091. fullsize_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info *compptr,
  167092. JSAMPARRAY input_data, JSAMPARRAY output_data)
  167093. {
  167094. int outrow;
  167095. JDIMENSION colctr;
  167096. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  167097. register JSAMPROW inptr, above_ptr, below_ptr, outptr;
  167098. INT32 membersum, neighsum, memberscale, neighscale;
  167099. int colsum, lastcolsum, nextcolsum;
  167100. /* Expand input data enough to let all the output samples be generated
  167101. * by the standard loop. Special-casing padded output would be more
  167102. * efficient.
  167103. */
  167104. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  167105. cinfo->image_width, output_cols);
  167106. /* Each of the eight neighbor pixels contributes a fraction SF to the
  167107. * smoothed pixel, while the main pixel contributes (1-8*SF). In order
  167108. * to use integer arithmetic, these factors are multiplied by 2^16 = 65536.
  167109. * Also recall that SF = smoothing_factor / 1024.
  167110. */
  167111. memberscale = 65536L - cinfo->smoothing_factor * 512L; /* scaled 1-8*SF */
  167112. neighscale = cinfo->smoothing_factor * 64; /* scaled SF */
  167113. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  167114. outptr = output_data[outrow];
  167115. inptr = input_data[outrow];
  167116. above_ptr = input_data[outrow-1];
  167117. below_ptr = input_data[outrow+1];
  167118. /* Special case for first column */
  167119. colsum = GETJSAMPLE(*above_ptr++) + GETJSAMPLE(*below_ptr++) +
  167120. GETJSAMPLE(*inptr);
  167121. membersum = GETJSAMPLE(*inptr++);
  167122. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  167123. GETJSAMPLE(*inptr);
  167124. neighsum = colsum + (colsum - membersum) + nextcolsum;
  167125. membersum = membersum * memberscale + neighsum * neighscale;
  167126. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  167127. lastcolsum = colsum; colsum = nextcolsum;
  167128. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  167129. membersum = GETJSAMPLE(*inptr++);
  167130. above_ptr++; below_ptr++;
  167131. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  167132. GETJSAMPLE(*inptr);
  167133. neighsum = lastcolsum + (colsum - membersum) + nextcolsum;
  167134. membersum = membersum * memberscale + neighsum * neighscale;
  167135. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  167136. lastcolsum = colsum; colsum = nextcolsum;
  167137. }
  167138. /* Special case for last column */
  167139. membersum = GETJSAMPLE(*inptr);
  167140. neighsum = lastcolsum + (colsum - membersum) + colsum;
  167141. membersum = membersum * memberscale + neighsum * neighscale;
  167142. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  167143. }
  167144. }
  167145. #endif /* INPUT_SMOOTHING_SUPPORTED */
  167146. /*
  167147. * Module initialization routine for downsampling.
  167148. * Note that we must select a routine for each component.
  167149. */
  167150. GLOBAL(void)
  167151. jinit_downsampler (j_compress_ptr cinfo)
  167152. {
  167153. my_downsample_ptr downsample;
  167154. int ci;
  167155. jpeg_component_info * compptr;
  167156. boolean smoothok = TRUE;
  167157. downsample = (my_downsample_ptr)
  167158. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167159. SIZEOF(my_downsampler));
  167160. cinfo->downsample = (struct jpeg_downsampler *) downsample;
  167161. downsample->pub.start_pass = start_pass_downsample;
  167162. downsample->pub.downsample = sep_downsample;
  167163. downsample->pub.need_context_rows = FALSE;
  167164. if (cinfo->CCIR601_sampling)
  167165. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  167166. /* Verify we can handle the sampling factors, and set up method pointers */
  167167. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167168. ci++, compptr++) {
  167169. if (compptr->h_samp_factor == cinfo->max_h_samp_factor &&
  167170. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  167171. #ifdef INPUT_SMOOTHING_SUPPORTED
  167172. if (cinfo->smoothing_factor) {
  167173. downsample->methods[ci] = fullsize_smooth_downsample;
  167174. downsample->pub.need_context_rows = TRUE;
  167175. } else
  167176. #endif
  167177. downsample->methods[ci] = fullsize_downsample;
  167178. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  167179. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  167180. smoothok = FALSE;
  167181. downsample->methods[ci] = h2v1_downsample;
  167182. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  167183. compptr->v_samp_factor * 2 == cinfo->max_v_samp_factor) {
  167184. #ifdef INPUT_SMOOTHING_SUPPORTED
  167185. if (cinfo->smoothing_factor) {
  167186. downsample->methods[ci] = h2v2_smooth_downsample;
  167187. downsample->pub.need_context_rows = TRUE;
  167188. } else
  167189. #endif
  167190. downsample->methods[ci] = h2v2_downsample;
  167191. } else if ((cinfo->max_h_samp_factor % compptr->h_samp_factor) == 0 &&
  167192. (cinfo->max_v_samp_factor % compptr->v_samp_factor) == 0) {
  167193. smoothok = FALSE;
  167194. downsample->methods[ci] = int_downsample;
  167195. } else
  167196. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  167197. }
  167198. #ifdef INPUT_SMOOTHING_SUPPORTED
  167199. if (cinfo->smoothing_factor && !smoothok)
  167200. TRACEMS(cinfo, 0, JTRC_SMOOTH_NOTIMPL);
  167201. #endif
  167202. }
  167203. /*** End of inlined file: jcsample.c ***/
  167204. /*** Start of inlined file: jctrans.c ***/
  167205. #define JPEG_INTERNALS
  167206. /* Forward declarations */
  167207. LOCAL(void) transencode_master_selection
  167208. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  167209. LOCAL(void) transencode_coef_controller
  167210. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  167211. /*
  167212. * Compression initialization for writing raw-coefficient data.
  167213. * Before calling this, all parameters and a data destination must be set up.
  167214. * Call jpeg_finish_compress() to actually write the data.
  167215. *
  167216. * The number of passed virtual arrays must match cinfo->num_components.
  167217. * Note that the virtual arrays need not be filled or even realized at
  167218. * the time write_coefficients is called; indeed, if the virtual arrays
  167219. * were requested from this compression object's memory manager, they
  167220. * typically will be realized during this routine and filled afterwards.
  167221. */
  167222. GLOBAL(void)
  167223. jpeg_write_coefficients (j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays)
  167224. {
  167225. if (cinfo->global_state != CSTATE_START)
  167226. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167227. /* Mark all tables to be written */
  167228. jpeg_suppress_tables(cinfo, FALSE);
  167229. /* (Re)initialize error mgr and destination modules */
  167230. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  167231. (*cinfo->dest->init_destination) (cinfo);
  167232. /* Perform master selection of active modules */
  167233. transencode_master_selection(cinfo, coef_arrays);
  167234. /* Wait for jpeg_finish_compress() call */
  167235. cinfo->next_scanline = 0; /* so jpeg_write_marker works */
  167236. cinfo->global_state = CSTATE_WRCOEFS;
  167237. }
  167238. /*
  167239. * Initialize the compression object with default parameters,
  167240. * then copy from the source object all parameters needed for lossless
  167241. * transcoding. Parameters that can be varied without loss (such as
  167242. * scan script and Huffman optimization) are left in their default states.
  167243. */
  167244. GLOBAL(void)
  167245. jpeg_copy_critical_parameters (j_decompress_ptr srcinfo,
  167246. j_compress_ptr dstinfo)
  167247. {
  167248. JQUANT_TBL ** qtblptr;
  167249. jpeg_component_info *incomp, *outcomp;
  167250. JQUANT_TBL *c_quant, *slot_quant;
  167251. int tblno, ci, coefi;
  167252. /* Safety check to ensure start_compress not called yet. */
  167253. if (dstinfo->global_state != CSTATE_START)
  167254. ERREXIT1(dstinfo, JERR_BAD_STATE, dstinfo->global_state);
  167255. /* Copy fundamental image dimensions */
  167256. dstinfo->image_width = srcinfo->image_width;
  167257. dstinfo->image_height = srcinfo->image_height;
  167258. dstinfo->input_components = srcinfo->num_components;
  167259. dstinfo->in_color_space = srcinfo->jpeg_color_space;
  167260. /* Initialize all parameters to default values */
  167261. jpeg_set_defaults(dstinfo);
  167262. /* jpeg_set_defaults may choose wrong colorspace, eg YCbCr if input is RGB.
  167263. * Fix it to get the right header markers for the image colorspace.
  167264. */
  167265. jpeg_set_colorspace(dstinfo, srcinfo->jpeg_color_space);
  167266. dstinfo->data_precision = srcinfo->data_precision;
  167267. dstinfo->CCIR601_sampling = srcinfo->CCIR601_sampling;
  167268. /* Copy the source's quantization tables. */
  167269. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  167270. if (srcinfo->quant_tbl_ptrs[tblno] != NULL) {
  167271. qtblptr = & dstinfo->quant_tbl_ptrs[tblno];
  167272. if (*qtblptr == NULL)
  167273. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) dstinfo);
  167274. MEMCOPY((*qtblptr)->quantval,
  167275. srcinfo->quant_tbl_ptrs[tblno]->quantval,
  167276. SIZEOF((*qtblptr)->quantval));
  167277. (*qtblptr)->sent_table = FALSE;
  167278. }
  167279. }
  167280. /* Copy the source's per-component info.
  167281. * Note we assume jpeg_set_defaults has allocated the dest comp_info array.
  167282. */
  167283. dstinfo->num_components = srcinfo->num_components;
  167284. if (dstinfo->num_components < 1 || dstinfo->num_components > MAX_COMPONENTS)
  167285. ERREXIT2(dstinfo, JERR_COMPONENT_COUNT, dstinfo->num_components,
  167286. MAX_COMPONENTS);
  167287. for (ci = 0, incomp = srcinfo->comp_info, outcomp = dstinfo->comp_info;
  167288. ci < dstinfo->num_components; ci++, incomp++, outcomp++) {
  167289. outcomp->component_id = incomp->component_id;
  167290. outcomp->h_samp_factor = incomp->h_samp_factor;
  167291. outcomp->v_samp_factor = incomp->v_samp_factor;
  167292. outcomp->quant_tbl_no = incomp->quant_tbl_no;
  167293. /* Make sure saved quantization table for component matches the qtable
  167294. * slot. If not, the input file re-used this qtable slot.
  167295. * IJG encoder currently cannot duplicate this.
  167296. */
  167297. tblno = outcomp->quant_tbl_no;
  167298. if (tblno < 0 || tblno >= NUM_QUANT_TBLS ||
  167299. srcinfo->quant_tbl_ptrs[tblno] == NULL)
  167300. ERREXIT1(dstinfo, JERR_NO_QUANT_TABLE, tblno);
  167301. slot_quant = srcinfo->quant_tbl_ptrs[tblno];
  167302. c_quant = incomp->quant_table;
  167303. if (c_quant != NULL) {
  167304. for (coefi = 0; coefi < DCTSIZE2; coefi++) {
  167305. if (c_quant->quantval[coefi] != slot_quant->quantval[coefi])
  167306. ERREXIT1(dstinfo, JERR_MISMATCHED_QUANT_TABLE, tblno);
  167307. }
  167308. }
  167309. /* Note: we do not copy the source's Huffman table assignments;
  167310. * instead we rely on jpeg_set_colorspace to have made a suitable choice.
  167311. */
  167312. }
  167313. /* Also copy JFIF version and resolution information, if available.
  167314. * Strictly speaking this isn't "critical" info, but it's nearly
  167315. * always appropriate to copy it if available. In particular,
  167316. * if the application chooses to copy JFIF 1.02 extension markers from
  167317. * the source file, we need to copy the version to make sure we don't
  167318. * emit a file that has 1.02 extensions but a claimed version of 1.01.
  167319. * We will *not*, however, copy version info from mislabeled "2.01" files.
  167320. */
  167321. if (srcinfo->saw_JFIF_marker) {
  167322. if (srcinfo->JFIF_major_version == 1) {
  167323. dstinfo->JFIF_major_version = srcinfo->JFIF_major_version;
  167324. dstinfo->JFIF_minor_version = srcinfo->JFIF_minor_version;
  167325. }
  167326. dstinfo->density_unit = srcinfo->density_unit;
  167327. dstinfo->X_density = srcinfo->X_density;
  167328. dstinfo->Y_density = srcinfo->Y_density;
  167329. }
  167330. }
  167331. /*
  167332. * Master selection of compression modules for transcoding.
  167333. * This substitutes for jcinit.c's initialization of the full compressor.
  167334. */
  167335. LOCAL(void)
  167336. transencode_master_selection (j_compress_ptr cinfo,
  167337. jvirt_barray_ptr * coef_arrays)
  167338. {
  167339. /* Although we don't actually use input_components for transcoding,
  167340. * jcmaster.c's initial_setup will complain if input_components is 0.
  167341. */
  167342. cinfo->input_components = 1;
  167343. /* Initialize master control (includes parameter checking/processing) */
  167344. jinit_c_master_control(cinfo, TRUE /* transcode only */);
  167345. /* Entropy encoding: either Huffman or arithmetic coding. */
  167346. if (cinfo->arith_code) {
  167347. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  167348. } else {
  167349. if (cinfo->progressive_mode) {
  167350. #ifdef C_PROGRESSIVE_SUPPORTED
  167351. jinit_phuff_encoder(cinfo);
  167352. #else
  167353. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167354. #endif
  167355. } else
  167356. jinit_huff_encoder(cinfo);
  167357. }
  167358. /* We need a special coefficient buffer controller. */
  167359. transencode_coef_controller(cinfo, coef_arrays);
  167360. jinit_marker_writer(cinfo);
  167361. /* We can now tell the memory manager to allocate virtual arrays. */
  167362. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  167363. /* Write the datastream header (SOI, JFIF) immediately.
  167364. * Frame and scan headers are postponed till later.
  167365. * This lets application insert special markers after the SOI.
  167366. */
  167367. (*cinfo->marker->write_file_header) (cinfo);
  167368. }
  167369. /*
  167370. * The rest of this file is a special implementation of the coefficient
  167371. * buffer controller. This is similar to jccoefct.c, but it handles only
  167372. * output from presupplied virtual arrays. Furthermore, we generate any
  167373. * dummy padding blocks on-the-fly rather than expecting them to be present
  167374. * in the arrays.
  167375. */
  167376. /* Private buffer controller object */
  167377. typedef struct {
  167378. struct jpeg_c_coef_controller pub; /* public fields */
  167379. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  167380. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  167381. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  167382. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  167383. /* Virtual block array for each component. */
  167384. jvirt_barray_ptr * whole_image;
  167385. /* Workspace for constructing dummy blocks at right/bottom edges. */
  167386. JBLOCKROW dummy_buffer[C_MAX_BLOCKS_IN_MCU];
  167387. } my_coef_controller2;
  167388. typedef my_coef_controller2 * my_coef_ptr2;
  167389. LOCAL(void)
  167390. start_iMCU_row2 (j_compress_ptr cinfo)
  167391. /* Reset within-iMCU-row counters for a new row */
  167392. {
  167393. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167394. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  167395. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  167396. * But at the bottom of the image, process only what's left.
  167397. */
  167398. if (cinfo->comps_in_scan > 1) {
  167399. coef->MCU_rows_per_iMCU_row = 1;
  167400. } else {
  167401. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  167402. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  167403. else
  167404. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  167405. }
  167406. coef->mcu_ctr = 0;
  167407. coef->MCU_vert_offset = 0;
  167408. }
  167409. /*
  167410. * Initialize for a processing pass.
  167411. */
  167412. METHODDEF(void)
  167413. start_pass_coef2 (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  167414. {
  167415. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167416. if (pass_mode != JBUF_CRANK_DEST)
  167417. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  167418. coef->iMCU_row_num = 0;
  167419. start_iMCU_row2(cinfo);
  167420. }
  167421. /*
  167422. * Process some data.
  167423. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  167424. * per call, ie, v_samp_factor block rows for each component in the scan.
  167425. * The data is obtained from the virtual arrays and fed to the entropy coder.
  167426. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  167427. *
  167428. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  167429. */
  167430. METHODDEF(boolean)
  167431. compress_output2 (j_compress_ptr cinfo, JSAMPIMAGE)
  167432. {
  167433. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167434. JDIMENSION MCU_col_num; /* index of current MCU within row */
  167435. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  167436. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  167437. int blkn, ci, xindex, yindex, yoffset, blockcnt;
  167438. JDIMENSION start_col;
  167439. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  167440. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  167441. JBLOCKROW buffer_ptr;
  167442. jpeg_component_info *compptr;
  167443. /* Align the virtual buffers for the components used in this scan. */
  167444. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167445. compptr = cinfo->cur_comp_info[ci];
  167446. buffer[ci] = (*cinfo->mem->access_virt_barray)
  167447. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  167448. coef->iMCU_row_num * compptr->v_samp_factor,
  167449. (JDIMENSION) compptr->v_samp_factor, FALSE);
  167450. }
  167451. /* Loop to process one whole iMCU row */
  167452. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  167453. yoffset++) {
  167454. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  167455. MCU_col_num++) {
  167456. /* Construct list of pointers to DCT blocks belonging to this MCU */
  167457. blkn = 0; /* index of current DCT block within MCU */
  167458. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167459. compptr = cinfo->cur_comp_info[ci];
  167460. start_col = MCU_col_num * compptr->MCU_width;
  167461. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  167462. : compptr->last_col_width;
  167463. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  167464. if (coef->iMCU_row_num < last_iMCU_row ||
  167465. yindex+yoffset < compptr->last_row_height) {
  167466. /* Fill in pointers to real blocks in this row */
  167467. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  167468. for (xindex = 0; xindex < blockcnt; xindex++)
  167469. MCU_buffer[blkn++] = buffer_ptr++;
  167470. } else {
  167471. /* At bottom of image, need a whole row of dummy blocks */
  167472. xindex = 0;
  167473. }
  167474. /* Fill in any dummy blocks needed in this row.
  167475. * Dummy blocks are filled in the same way as in jccoefct.c:
  167476. * all zeroes in the AC entries, DC entries equal to previous
  167477. * block's DC value. The init routine has already zeroed the
  167478. * AC entries, so we need only set the DC entries correctly.
  167479. */
  167480. for (; xindex < compptr->MCU_width; xindex++) {
  167481. MCU_buffer[blkn] = coef->dummy_buffer[blkn];
  167482. MCU_buffer[blkn][0][0] = MCU_buffer[blkn-1][0][0];
  167483. blkn++;
  167484. }
  167485. }
  167486. }
  167487. /* Try to write the MCU. */
  167488. if (! (*cinfo->entropy->encode_mcu) (cinfo, MCU_buffer)) {
  167489. /* Suspension forced; update state counters and exit */
  167490. coef->MCU_vert_offset = yoffset;
  167491. coef->mcu_ctr = MCU_col_num;
  167492. return FALSE;
  167493. }
  167494. }
  167495. /* Completed an MCU row, but perhaps not an iMCU row */
  167496. coef->mcu_ctr = 0;
  167497. }
  167498. /* Completed the iMCU row, advance counters for next one */
  167499. coef->iMCU_row_num++;
  167500. start_iMCU_row2(cinfo);
  167501. return TRUE;
  167502. }
  167503. /*
  167504. * Initialize coefficient buffer controller.
  167505. *
  167506. * Each passed coefficient array must be the right size for that
  167507. * coefficient: width_in_blocks wide and height_in_blocks high,
  167508. * with unitheight at least v_samp_factor.
  167509. */
  167510. LOCAL(void)
  167511. transencode_coef_controller (j_compress_ptr cinfo,
  167512. jvirt_barray_ptr * coef_arrays)
  167513. {
  167514. my_coef_ptr2 coef;
  167515. JBLOCKROW buffer;
  167516. int i;
  167517. coef = (my_coef_ptr2)
  167518. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167519. SIZEOF(my_coef_controller2));
  167520. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  167521. coef->pub.start_pass = start_pass_coef2;
  167522. coef->pub.compress_data = compress_output2;
  167523. /* Save pointer to virtual arrays */
  167524. coef->whole_image = coef_arrays;
  167525. /* Allocate and pre-zero space for dummy DCT blocks. */
  167526. buffer = (JBLOCKROW)
  167527. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167528. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  167529. jzero_far((void FAR *) buffer, C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  167530. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  167531. coef->dummy_buffer[i] = buffer + i;
  167532. }
  167533. }
  167534. /*** End of inlined file: jctrans.c ***/
  167535. /*** Start of inlined file: jdapistd.c ***/
  167536. #define JPEG_INTERNALS
  167537. /* Forward declarations */
  167538. LOCAL(boolean) output_pass_setup JPP((j_decompress_ptr cinfo));
  167539. /*
  167540. * Decompression initialization.
  167541. * jpeg_read_header must be completed before calling this.
  167542. *
  167543. * If a multipass operating mode was selected, this will do all but the
  167544. * last pass, and thus may take a great deal of time.
  167545. *
  167546. * Returns FALSE if suspended. The return value need be inspected only if
  167547. * a suspending data source is used.
  167548. */
  167549. GLOBAL(boolean)
  167550. jpeg_start_decompress (j_decompress_ptr cinfo)
  167551. {
  167552. if (cinfo->global_state == DSTATE_READY) {
  167553. /* First call: initialize master control, select active modules */
  167554. jinit_master_decompress(cinfo);
  167555. if (cinfo->buffered_image) {
  167556. /* No more work here; expecting jpeg_start_output next */
  167557. cinfo->global_state = DSTATE_BUFIMAGE;
  167558. return TRUE;
  167559. }
  167560. cinfo->global_state = DSTATE_PRELOAD;
  167561. }
  167562. if (cinfo->global_state == DSTATE_PRELOAD) {
  167563. /* If file has multiple scans, absorb them all into the coef buffer */
  167564. if (cinfo->inputctl->has_multiple_scans) {
  167565. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167566. for (;;) {
  167567. int retcode;
  167568. /* Call progress monitor hook if present */
  167569. if (cinfo->progress != NULL)
  167570. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167571. /* Absorb some more input */
  167572. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  167573. if (retcode == JPEG_SUSPENDED)
  167574. return FALSE;
  167575. if (retcode == JPEG_REACHED_EOI)
  167576. break;
  167577. /* Advance progress counter if appropriate */
  167578. if (cinfo->progress != NULL &&
  167579. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  167580. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  167581. /* jdmaster underestimated number of scans; ratchet up one scan */
  167582. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  167583. }
  167584. }
  167585. }
  167586. #else
  167587. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167588. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  167589. }
  167590. cinfo->output_scan_number = cinfo->input_scan_number;
  167591. } else if (cinfo->global_state != DSTATE_PRESCAN)
  167592. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167593. /* Perform any dummy output passes, and set up for the final pass */
  167594. return output_pass_setup(cinfo);
  167595. }
  167596. /*
  167597. * Set up for an output pass, and perform any dummy pass(es) needed.
  167598. * Common subroutine for jpeg_start_decompress and jpeg_start_output.
  167599. * Entry: global_state = DSTATE_PRESCAN only if previously suspended.
  167600. * Exit: If done, returns TRUE and sets global_state for proper output mode.
  167601. * If suspended, returns FALSE and sets global_state = DSTATE_PRESCAN.
  167602. */
  167603. LOCAL(boolean)
  167604. output_pass_setup (j_decompress_ptr cinfo)
  167605. {
  167606. if (cinfo->global_state != DSTATE_PRESCAN) {
  167607. /* First call: do pass setup */
  167608. (*cinfo->master->prepare_for_output_pass) (cinfo);
  167609. cinfo->output_scanline = 0;
  167610. cinfo->global_state = DSTATE_PRESCAN;
  167611. }
  167612. /* Loop over any required dummy passes */
  167613. while (cinfo->master->is_dummy_pass) {
  167614. #ifdef QUANT_2PASS_SUPPORTED
  167615. /* Crank through the dummy pass */
  167616. while (cinfo->output_scanline < cinfo->output_height) {
  167617. JDIMENSION last_scanline;
  167618. /* Call progress monitor hook if present */
  167619. if (cinfo->progress != NULL) {
  167620. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167621. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167622. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167623. }
  167624. /* Process some data */
  167625. last_scanline = cinfo->output_scanline;
  167626. (*cinfo->main->process_data) (cinfo, (JSAMPARRAY) NULL,
  167627. &cinfo->output_scanline, (JDIMENSION) 0);
  167628. if (cinfo->output_scanline == last_scanline)
  167629. return FALSE; /* No progress made, must suspend */
  167630. }
  167631. /* Finish up dummy pass, and set up for another one */
  167632. (*cinfo->master->finish_output_pass) (cinfo);
  167633. (*cinfo->master->prepare_for_output_pass) (cinfo);
  167634. cinfo->output_scanline = 0;
  167635. #else
  167636. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167637. #endif /* QUANT_2PASS_SUPPORTED */
  167638. }
  167639. /* Ready for application to drive output pass through
  167640. * jpeg_read_scanlines or jpeg_read_raw_data.
  167641. */
  167642. cinfo->global_state = cinfo->raw_data_out ? DSTATE_RAW_OK : DSTATE_SCANNING;
  167643. return TRUE;
  167644. }
  167645. /*
  167646. * Read some scanlines of data from the JPEG decompressor.
  167647. *
  167648. * The return value will be the number of lines actually read.
  167649. * This may be less than the number requested in several cases,
  167650. * including bottom of image, data source suspension, and operating
  167651. * modes that emit multiple scanlines at a time.
  167652. *
  167653. * Note: we warn about excess calls to jpeg_read_scanlines() since
  167654. * this likely signals an application programmer error. However,
  167655. * an oversize buffer (max_lines > scanlines remaining) is not an error.
  167656. */
  167657. GLOBAL(JDIMENSION)
  167658. jpeg_read_scanlines (j_decompress_ptr cinfo, JSAMPARRAY scanlines,
  167659. JDIMENSION max_lines)
  167660. {
  167661. JDIMENSION row_ctr;
  167662. if (cinfo->global_state != DSTATE_SCANNING)
  167663. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167664. if (cinfo->output_scanline >= cinfo->output_height) {
  167665. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  167666. return 0;
  167667. }
  167668. /* Call progress monitor hook if present */
  167669. if (cinfo->progress != NULL) {
  167670. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167671. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167672. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167673. }
  167674. /* Process some data */
  167675. row_ctr = 0;
  167676. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, max_lines);
  167677. cinfo->output_scanline += row_ctr;
  167678. return row_ctr;
  167679. }
  167680. /*
  167681. * Alternate entry point to read raw data.
  167682. * Processes exactly one iMCU row per call, unless suspended.
  167683. */
  167684. GLOBAL(JDIMENSION)
  167685. jpeg_read_raw_data (j_decompress_ptr cinfo, JSAMPIMAGE data,
  167686. JDIMENSION max_lines)
  167687. {
  167688. JDIMENSION lines_per_iMCU_row;
  167689. if (cinfo->global_state != DSTATE_RAW_OK)
  167690. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167691. if (cinfo->output_scanline >= cinfo->output_height) {
  167692. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  167693. return 0;
  167694. }
  167695. /* Call progress monitor hook if present */
  167696. if (cinfo->progress != NULL) {
  167697. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167698. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167699. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167700. }
  167701. /* Verify that at least one iMCU row can be returned. */
  167702. lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size;
  167703. if (max_lines < lines_per_iMCU_row)
  167704. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  167705. /* Decompress directly into user's buffer. */
  167706. if (! (*cinfo->coef->decompress_data) (cinfo, data))
  167707. return 0; /* suspension forced, can do nothing more */
  167708. /* OK, we processed one iMCU row. */
  167709. cinfo->output_scanline += lines_per_iMCU_row;
  167710. return lines_per_iMCU_row;
  167711. }
  167712. /* Additional entry points for buffered-image mode. */
  167713. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167714. /*
  167715. * Initialize for an output pass in buffered-image mode.
  167716. */
  167717. GLOBAL(boolean)
  167718. jpeg_start_output (j_decompress_ptr cinfo, int scan_number)
  167719. {
  167720. if (cinfo->global_state != DSTATE_BUFIMAGE &&
  167721. cinfo->global_state != DSTATE_PRESCAN)
  167722. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167723. /* Limit scan number to valid range */
  167724. if (scan_number <= 0)
  167725. scan_number = 1;
  167726. if (cinfo->inputctl->eoi_reached &&
  167727. scan_number > cinfo->input_scan_number)
  167728. scan_number = cinfo->input_scan_number;
  167729. cinfo->output_scan_number = scan_number;
  167730. /* Perform any dummy output passes, and set up for the real pass */
  167731. return output_pass_setup(cinfo);
  167732. }
  167733. /*
  167734. * Finish up after an output pass in buffered-image mode.
  167735. *
  167736. * Returns FALSE if suspended. The return value need be inspected only if
  167737. * a suspending data source is used.
  167738. */
  167739. GLOBAL(boolean)
  167740. jpeg_finish_output (j_decompress_ptr cinfo)
  167741. {
  167742. if ((cinfo->global_state == DSTATE_SCANNING ||
  167743. cinfo->global_state == DSTATE_RAW_OK) && cinfo->buffered_image) {
  167744. /* Terminate this pass. */
  167745. /* We do not require the whole pass to have been completed. */
  167746. (*cinfo->master->finish_output_pass) (cinfo);
  167747. cinfo->global_state = DSTATE_BUFPOST;
  167748. } else if (cinfo->global_state != DSTATE_BUFPOST) {
  167749. /* BUFPOST = repeat call after a suspension, anything else is error */
  167750. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167751. }
  167752. /* Read markers looking for SOS or EOI */
  167753. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  167754. ! cinfo->inputctl->eoi_reached) {
  167755. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  167756. return FALSE; /* Suspend, come back later */
  167757. }
  167758. cinfo->global_state = DSTATE_BUFIMAGE;
  167759. return TRUE;
  167760. }
  167761. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  167762. /*** End of inlined file: jdapistd.c ***/
  167763. /*** Start of inlined file: jdapimin.c ***/
  167764. #define JPEG_INTERNALS
  167765. /*
  167766. * Initialization of a JPEG decompression object.
  167767. * The error manager must already be set up (in case memory manager fails).
  167768. */
  167769. GLOBAL(void)
  167770. jpeg_CreateDecompress (j_decompress_ptr cinfo, int version, size_t structsize)
  167771. {
  167772. int i;
  167773. /* Guard against version mismatches between library and caller. */
  167774. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  167775. if (version != JPEG_LIB_VERSION)
  167776. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  167777. if (structsize != SIZEOF(struct jpeg_decompress_struct))
  167778. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  167779. (int) SIZEOF(struct jpeg_decompress_struct), (int) structsize);
  167780. /* For debugging purposes, we zero the whole master structure.
  167781. * But the application has already set the err pointer, and may have set
  167782. * client_data, so we have to save and restore those fields.
  167783. * Note: if application hasn't set client_data, tools like Purify may
  167784. * complain here.
  167785. */
  167786. {
  167787. struct jpeg_error_mgr * err = cinfo->err;
  167788. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  167789. MEMZERO(cinfo, SIZEOF(struct jpeg_decompress_struct));
  167790. cinfo->err = err;
  167791. cinfo->client_data = client_data;
  167792. }
  167793. cinfo->is_decompressor = TRUE;
  167794. /* Initialize a memory manager instance for this object */
  167795. jinit_memory_mgr((j_common_ptr) cinfo);
  167796. /* Zero out pointers to permanent structures. */
  167797. cinfo->progress = NULL;
  167798. cinfo->src = NULL;
  167799. for (i = 0; i < NUM_QUANT_TBLS; i++)
  167800. cinfo->quant_tbl_ptrs[i] = NULL;
  167801. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  167802. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  167803. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  167804. }
  167805. /* Initialize marker processor so application can override methods
  167806. * for COM, APPn markers before calling jpeg_read_header.
  167807. */
  167808. cinfo->marker_list = NULL;
  167809. jinit_marker_reader(cinfo);
  167810. /* And initialize the overall input controller. */
  167811. jinit_input_controller(cinfo);
  167812. /* OK, I'm ready */
  167813. cinfo->global_state = DSTATE_START;
  167814. }
  167815. /*
  167816. * Destruction of a JPEG decompression object
  167817. */
  167818. GLOBAL(void)
  167819. jpeg_destroy_decompress (j_decompress_ptr cinfo)
  167820. {
  167821. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  167822. }
  167823. /*
  167824. * Abort processing of a JPEG decompression operation,
  167825. * but don't destroy the object itself.
  167826. */
  167827. GLOBAL(void)
  167828. jpeg_abort_decompress (j_decompress_ptr cinfo)
  167829. {
  167830. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  167831. }
  167832. /*
  167833. * Set default decompression parameters.
  167834. */
  167835. LOCAL(void)
  167836. default_decompress_parms (j_decompress_ptr cinfo)
  167837. {
  167838. /* Guess the input colorspace, and set output colorspace accordingly. */
  167839. /* (Wish JPEG committee had provided a real way to specify this...) */
  167840. /* Note application may override our guesses. */
  167841. switch (cinfo->num_components) {
  167842. case 1:
  167843. cinfo->jpeg_color_space = JCS_GRAYSCALE;
  167844. cinfo->out_color_space = JCS_GRAYSCALE;
  167845. break;
  167846. case 3:
  167847. if (cinfo->saw_JFIF_marker) {
  167848. cinfo->jpeg_color_space = JCS_YCbCr; /* JFIF implies YCbCr */
  167849. } else if (cinfo->saw_Adobe_marker) {
  167850. switch (cinfo->Adobe_transform) {
  167851. case 0:
  167852. cinfo->jpeg_color_space = JCS_RGB;
  167853. break;
  167854. case 1:
  167855. cinfo->jpeg_color_space = JCS_YCbCr;
  167856. break;
  167857. default:
  167858. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  167859. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  167860. break;
  167861. }
  167862. } else {
  167863. /* Saw no special markers, try to guess from the component IDs */
  167864. int cid0 = cinfo->comp_info[0].component_id;
  167865. int cid1 = cinfo->comp_info[1].component_id;
  167866. int cid2 = cinfo->comp_info[2].component_id;
  167867. if (cid0 == 1 && cid1 == 2 && cid2 == 3)
  167868. cinfo->jpeg_color_space = JCS_YCbCr; /* assume JFIF w/out marker */
  167869. else if (cid0 == 82 && cid1 == 71 && cid2 == 66)
  167870. cinfo->jpeg_color_space = JCS_RGB; /* ASCII 'R', 'G', 'B' */
  167871. else {
  167872. TRACEMS3(cinfo, 1, JTRC_UNKNOWN_IDS, cid0, cid1, cid2);
  167873. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  167874. }
  167875. }
  167876. /* Always guess RGB is proper output colorspace. */
  167877. cinfo->out_color_space = JCS_RGB;
  167878. break;
  167879. case 4:
  167880. if (cinfo->saw_Adobe_marker) {
  167881. switch (cinfo->Adobe_transform) {
  167882. case 0:
  167883. cinfo->jpeg_color_space = JCS_CMYK;
  167884. break;
  167885. case 2:
  167886. cinfo->jpeg_color_space = JCS_YCCK;
  167887. break;
  167888. default:
  167889. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  167890. cinfo->jpeg_color_space = JCS_YCCK; /* assume it's YCCK */
  167891. break;
  167892. }
  167893. } else {
  167894. /* No special markers, assume straight CMYK. */
  167895. cinfo->jpeg_color_space = JCS_CMYK;
  167896. }
  167897. cinfo->out_color_space = JCS_CMYK;
  167898. break;
  167899. default:
  167900. cinfo->jpeg_color_space = JCS_UNKNOWN;
  167901. cinfo->out_color_space = JCS_UNKNOWN;
  167902. break;
  167903. }
  167904. /* Set defaults for other decompression parameters. */
  167905. cinfo->scale_num = 1; /* 1:1 scaling */
  167906. cinfo->scale_denom = 1;
  167907. cinfo->output_gamma = 1.0;
  167908. cinfo->buffered_image = FALSE;
  167909. cinfo->raw_data_out = FALSE;
  167910. cinfo->dct_method = JDCT_DEFAULT;
  167911. cinfo->do_fancy_upsampling = TRUE;
  167912. cinfo->do_block_smoothing = TRUE;
  167913. cinfo->quantize_colors = FALSE;
  167914. /* We set these in case application only sets quantize_colors. */
  167915. cinfo->dither_mode = JDITHER_FS;
  167916. #ifdef QUANT_2PASS_SUPPORTED
  167917. cinfo->two_pass_quantize = TRUE;
  167918. #else
  167919. cinfo->two_pass_quantize = FALSE;
  167920. #endif
  167921. cinfo->desired_number_of_colors = 256;
  167922. cinfo->colormap = NULL;
  167923. /* Initialize for no mode change in buffered-image mode. */
  167924. cinfo->enable_1pass_quant = FALSE;
  167925. cinfo->enable_external_quant = FALSE;
  167926. cinfo->enable_2pass_quant = FALSE;
  167927. }
  167928. /*
  167929. * Decompression startup: read start of JPEG datastream to see what's there.
  167930. * Need only initialize JPEG object and supply a data source before calling.
  167931. *
  167932. * This routine will read as far as the first SOS marker (ie, actual start of
  167933. * compressed data), and will save all tables and parameters in the JPEG
  167934. * object. It will also initialize the decompression parameters to default
  167935. * values, and finally return JPEG_HEADER_OK. On return, the application may
  167936. * adjust the decompression parameters and then call jpeg_start_decompress.
  167937. * (Or, if the application only wanted to determine the image parameters,
  167938. * the data need not be decompressed. In that case, call jpeg_abort or
  167939. * jpeg_destroy to release any temporary space.)
  167940. * If an abbreviated (tables only) datastream is presented, the routine will
  167941. * return JPEG_HEADER_TABLES_ONLY upon reaching EOI. The application may then
  167942. * re-use the JPEG object to read the abbreviated image datastream(s).
  167943. * It is unnecessary (but OK) to call jpeg_abort in this case.
  167944. * The JPEG_SUSPENDED return code only occurs if the data source module
  167945. * requests suspension of the decompressor. In this case the application
  167946. * should load more source data and then re-call jpeg_read_header to resume
  167947. * processing.
  167948. * If a non-suspending data source is used and require_image is TRUE, then the
  167949. * return code need not be inspected since only JPEG_HEADER_OK is possible.
  167950. *
  167951. * This routine is now just a front end to jpeg_consume_input, with some
  167952. * extra error checking.
  167953. */
  167954. GLOBAL(int)
  167955. jpeg_read_header (j_decompress_ptr cinfo, boolean require_image)
  167956. {
  167957. int retcode;
  167958. if (cinfo->global_state != DSTATE_START &&
  167959. cinfo->global_state != DSTATE_INHEADER)
  167960. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167961. retcode = jpeg_consume_input(cinfo);
  167962. switch (retcode) {
  167963. case JPEG_REACHED_SOS:
  167964. retcode = JPEG_HEADER_OK;
  167965. break;
  167966. case JPEG_REACHED_EOI:
  167967. if (require_image) /* Complain if application wanted an image */
  167968. ERREXIT(cinfo, JERR_NO_IMAGE);
  167969. /* Reset to start state; it would be safer to require the application to
  167970. * call jpeg_abort, but we can't change it now for compatibility reasons.
  167971. * A side effect is to free any temporary memory (there shouldn't be any).
  167972. */
  167973. jpeg_abort((j_common_ptr) cinfo); /* sets state = DSTATE_START */
  167974. retcode = JPEG_HEADER_TABLES_ONLY;
  167975. break;
  167976. case JPEG_SUSPENDED:
  167977. /* no work */
  167978. break;
  167979. }
  167980. return retcode;
  167981. }
  167982. /*
  167983. * Consume data in advance of what the decompressor requires.
  167984. * This can be called at any time once the decompressor object has
  167985. * been created and a data source has been set up.
  167986. *
  167987. * This routine is essentially a state machine that handles a couple
  167988. * of critical state-transition actions, namely initial setup and
  167989. * transition from header scanning to ready-for-start_decompress.
  167990. * All the actual input is done via the input controller's consume_input
  167991. * method.
  167992. */
  167993. GLOBAL(int)
  167994. jpeg_consume_input (j_decompress_ptr cinfo)
  167995. {
  167996. int retcode = JPEG_SUSPENDED;
  167997. /* NB: every possible DSTATE value should be listed in this switch */
  167998. switch (cinfo->global_state) {
  167999. case DSTATE_START:
  168000. /* Start-of-datastream actions: reset appropriate modules */
  168001. (*cinfo->inputctl->reset_input_controller) (cinfo);
  168002. /* Initialize application's data source module */
  168003. (*cinfo->src->init_source) (cinfo);
  168004. cinfo->global_state = DSTATE_INHEADER;
  168005. /*FALLTHROUGH*/
  168006. case DSTATE_INHEADER:
  168007. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  168008. if (retcode == JPEG_REACHED_SOS) { /* Found SOS, prepare to decompress */
  168009. /* Set up default parameters based on header data */
  168010. default_decompress_parms(cinfo);
  168011. /* Set global state: ready for start_decompress */
  168012. cinfo->global_state = DSTATE_READY;
  168013. }
  168014. break;
  168015. case DSTATE_READY:
  168016. /* Can't advance past first SOS until start_decompress is called */
  168017. retcode = JPEG_REACHED_SOS;
  168018. break;
  168019. case DSTATE_PRELOAD:
  168020. case DSTATE_PRESCAN:
  168021. case DSTATE_SCANNING:
  168022. case DSTATE_RAW_OK:
  168023. case DSTATE_BUFIMAGE:
  168024. case DSTATE_BUFPOST:
  168025. case DSTATE_STOPPING:
  168026. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  168027. break;
  168028. default:
  168029. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168030. }
  168031. return retcode;
  168032. }
  168033. /*
  168034. * Have we finished reading the input file?
  168035. */
  168036. GLOBAL(boolean)
  168037. jpeg_input_complete (j_decompress_ptr cinfo)
  168038. {
  168039. /* Check for valid jpeg object */
  168040. if (cinfo->global_state < DSTATE_START ||
  168041. cinfo->global_state > DSTATE_STOPPING)
  168042. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168043. return cinfo->inputctl->eoi_reached;
  168044. }
  168045. /*
  168046. * Is there more than one scan?
  168047. */
  168048. GLOBAL(boolean)
  168049. jpeg_has_multiple_scans (j_decompress_ptr cinfo)
  168050. {
  168051. /* Only valid after jpeg_read_header completes */
  168052. if (cinfo->global_state < DSTATE_READY ||
  168053. cinfo->global_state > DSTATE_STOPPING)
  168054. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168055. return cinfo->inputctl->has_multiple_scans;
  168056. }
  168057. /*
  168058. * Finish JPEG decompression.
  168059. *
  168060. * This will normally just verify the file trailer and release temp storage.
  168061. *
  168062. * Returns FALSE if suspended. The return value need be inspected only if
  168063. * a suspending data source is used.
  168064. */
  168065. GLOBAL(boolean)
  168066. jpeg_finish_decompress (j_decompress_ptr cinfo)
  168067. {
  168068. if ((cinfo->global_state == DSTATE_SCANNING ||
  168069. cinfo->global_state == DSTATE_RAW_OK) && ! cinfo->buffered_image) {
  168070. /* Terminate final pass of non-buffered mode */
  168071. if (cinfo->output_scanline < cinfo->output_height)
  168072. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  168073. (*cinfo->master->finish_output_pass) (cinfo);
  168074. cinfo->global_state = DSTATE_STOPPING;
  168075. } else if (cinfo->global_state == DSTATE_BUFIMAGE) {
  168076. /* Finishing after a buffered-image operation */
  168077. cinfo->global_state = DSTATE_STOPPING;
  168078. } else if (cinfo->global_state != DSTATE_STOPPING) {
  168079. /* STOPPING = repeat call after a suspension, anything else is error */
  168080. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168081. }
  168082. /* Read until EOI */
  168083. while (! cinfo->inputctl->eoi_reached) {
  168084. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  168085. return FALSE; /* Suspend, come back later */
  168086. }
  168087. /* Do final cleanup */
  168088. (*cinfo->src->term_source) (cinfo);
  168089. /* We can use jpeg_abort to release memory and reset global_state */
  168090. jpeg_abort((j_common_ptr) cinfo);
  168091. return TRUE;
  168092. }
  168093. /*** End of inlined file: jdapimin.c ***/
  168094. /*** Start of inlined file: jdatasrc.c ***/
  168095. /* this is not a core library module, so it doesn't define JPEG_INTERNALS */
  168096. /*** Start of inlined file: jerror.h ***/
  168097. /*
  168098. * To define the enum list of message codes, include this file without
  168099. * defining macro JMESSAGE. To create a message string table, include it
  168100. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  168101. */
  168102. #ifndef JMESSAGE
  168103. #ifndef JERROR_H
  168104. /* First time through, define the enum list */
  168105. #define JMAKE_ENUM_LIST
  168106. #else
  168107. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  168108. #define JMESSAGE(code,string)
  168109. #endif /* JERROR_H */
  168110. #endif /* JMESSAGE */
  168111. #ifdef JMAKE_ENUM_LIST
  168112. typedef enum {
  168113. #define JMESSAGE(code,string) code ,
  168114. #endif /* JMAKE_ENUM_LIST */
  168115. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  168116. /* For maintenance convenience, list is alphabetical by message code name */
  168117. JMESSAGE(JERR_ARITH_NOTIMPL,
  168118. "Sorry, there are legal restrictions on arithmetic coding")
  168119. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  168120. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  168121. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  168122. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  168123. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  168124. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  168125. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  168126. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  168127. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  168128. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  168129. JMESSAGE(JERR_BAD_LIB_VERSION,
  168130. "Wrong JPEG library version: library is %d, caller expects %d")
  168131. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  168132. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  168133. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  168134. JMESSAGE(JERR_BAD_PROGRESSION,
  168135. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  168136. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  168137. "Invalid progressive parameters at scan script entry %d")
  168138. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  168139. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  168140. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  168141. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  168142. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  168143. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  168144. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  168145. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  168146. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  168147. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  168148. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  168149. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  168150. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  168151. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  168152. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  168153. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  168154. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  168155. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  168156. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  168157. JMESSAGE(JERR_FILE_READ, "Input file read error")
  168158. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  168159. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  168160. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  168161. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  168162. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  168163. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  168164. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  168165. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  168166. "Cannot transcode due to multiple use of quantization table %d")
  168167. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  168168. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  168169. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  168170. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  168171. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  168172. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  168173. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  168174. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  168175. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  168176. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  168177. JMESSAGE(JERR_QUANT_COMPONENTS,
  168178. "Cannot quantize more than %d color components")
  168179. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  168180. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  168181. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  168182. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  168183. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  168184. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  168185. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  168186. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  168187. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  168188. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  168189. JMESSAGE(JERR_TFILE_WRITE,
  168190. "Write failed on temporary file --- out of disk space?")
  168191. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  168192. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  168193. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  168194. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  168195. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  168196. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  168197. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  168198. JMESSAGE(JMSG_VERSION, JVERSION)
  168199. JMESSAGE(JTRC_16BIT_TABLES,
  168200. "Caution: quantization tables are too coarse for baseline JPEG")
  168201. JMESSAGE(JTRC_ADOBE,
  168202. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  168203. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  168204. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  168205. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  168206. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  168207. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  168208. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  168209. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  168210. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  168211. JMESSAGE(JTRC_EOI, "End Of Image")
  168212. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  168213. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  168214. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  168215. "Warning: thumbnail image size does not match data length %u")
  168216. JMESSAGE(JTRC_JFIF_EXTENSION,
  168217. "JFIF extension marker: type 0x%02x, length %u")
  168218. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  168219. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  168220. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  168221. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  168222. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  168223. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  168224. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  168225. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  168226. JMESSAGE(JTRC_RST, "RST%d")
  168227. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  168228. "Smoothing not supported with nonstandard sampling ratios")
  168229. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  168230. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  168231. JMESSAGE(JTRC_SOI, "Start of Image")
  168232. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  168233. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  168234. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  168235. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  168236. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  168237. JMESSAGE(JTRC_THUMB_JPEG,
  168238. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  168239. JMESSAGE(JTRC_THUMB_PALETTE,
  168240. "JFIF extension marker: palette thumbnail image, length %u")
  168241. JMESSAGE(JTRC_THUMB_RGB,
  168242. "JFIF extension marker: RGB thumbnail image, length %u")
  168243. JMESSAGE(JTRC_UNKNOWN_IDS,
  168244. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  168245. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  168246. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  168247. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  168248. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  168249. "Inconsistent progression sequence for component %d coefficient %d")
  168250. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  168251. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  168252. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  168253. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  168254. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  168255. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  168256. JMESSAGE(JWRN_MUST_RESYNC,
  168257. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  168258. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  168259. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  168260. #ifdef JMAKE_ENUM_LIST
  168261. JMSG_LASTMSGCODE
  168262. } J_MESSAGE_CODE;
  168263. #undef JMAKE_ENUM_LIST
  168264. #endif /* JMAKE_ENUM_LIST */
  168265. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  168266. #undef JMESSAGE
  168267. #ifndef JERROR_H
  168268. #define JERROR_H
  168269. /* Macros to simplify using the error and trace message stuff */
  168270. /* The first parameter is either type of cinfo pointer */
  168271. /* Fatal errors (print message and exit) */
  168272. #define ERREXIT(cinfo,code) \
  168273. ((cinfo)->err->msg_code = (code), \
  168274. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168275. #define ERREXIT1(cinfo,code,p1) \
  168276. ((cinfo)->err->msg_code = (code), \
  168277. (cinfo)->err->msg_parm.i[0] = (p1), \
  168278. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168279. #define ERREXIT2(cinfo,code,p1,p2) \
  168280. ((cinfo)->err->msg_code = (code), \
  168281. (cinfo)->err->msg_parm.i[0] = (p1), \
  168282. (cinfo)->err->msg_parm.i[1] = (p2), \
  168283. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168284. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  168285. ((cinfo)->err->msg_code = (code), \
  168286. (cinfo)->err->msg_parm.i[0] = (p1), \
  168287. (cinfo)->err->msg_parm.i[1] = (p2), \
  168288. (cinfo)->err->msg_parm.i[2] = (p3), \
  168289. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168290. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  168291. ((cinfo)->err->msg_code = (code), \
  168292. (cinfo)->err->msg_parm.i[0] = (p1), \
  168293. (cinfo)->err->msg_parm.i[1] = (p2), \
  168294. (cinfo)->err->msg_parm.i[2] = (p3), \
  168295. (cinfo)->err->msg_parm.i[3] = (p4), \
  168296. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168297. #define ERREXITS(cinfo,code,str) \
  168298. ((cinfo)->err->msg_code = (code), \
  168299. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  168300. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168301. #define MAKESTMT(stuff) do { stuff } while (0)
  168302. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  168303. #define WARNMS(cinfo,code) \
  168304. ((cinfo)->err->msg_code = (code), \
  168305. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  168306. #define WARNMS1(cinfo,code,p1) \
  168307. ((cinfo)->err->msg_code = (code), \
  168308. (cinfo)->err->msg_parm.i[0] = (p1), \
  168309. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  168310. #define WARNMS2(cinfo,code,p1,p2) \
  168311. ((cinfo)->err->msg_code = (code), \
  168312. (cinfo)->err->msg_parm.i[0] = (p1), \
  168313. (cinfo)->err->msg_parm.i[1] = (p2), \
  168314. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  168315. /* Informational/debugging messages */
  168316. #define TRACEMS(cinfo,lvl,code) \
  168317. ((cinfo)->err->msg_code = (code), \
  168318. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168319. #define TRACEMS1(cinfo,lvl,code,p1) \
  168320. ((cinfo)->err->msg_code = (code), \
  168321. (cinfo)->err->msg_parm.i[0] = (p1), \
  168322. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168323. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  168324. ((cinfo)->err->msg_code = (code), \
  168325. (cinfo)->err->msg_parm.i[0] = (p1), \
  168326. (cinfo)->err->msg_parm.i[1] = (p2), \
  168327. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168328. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  168329. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168330. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  168331. (cinfo)->err->msg_code = (code); \
  168332. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168333. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  168334. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168335. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  168336. (cinfo)->err->msg_code = (code); \
  168337. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168338. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  168339. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168340. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  168341. _mp[4] = (p5); \
  168342. (cinfo)->err->msg_code = (code); \
  168343. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168344. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  168345. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168346. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  168347. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  168348. (cinfo)->err->msg_code = (code); \
  168349. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168350. #define TRACEMSS(cinfo,lvl,code,str) \
  168351. ((cinfo)->err->msg_code = (code), \
  168352. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  168353. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168354. #endif /* JERROR_H */
  168355. /*** End of inlined file: jerror.h ***/
  168356. /* Expanded data source object for stdio input */
  168357. typedef struct {
  168358. struct jpeg_source_mgr pub; /* public fields */
  168359. FILE * infile; /* source stream */
  168360. JOCTET * buffer; /* start of buffer */
  168361. boolean start_of_file; /* have we gotten any data yet? */
  168362. } my_source_mgr;
  168363. typedef my_source_mgr * my_src_ptr;
  168364. #define INPUT_BUF_SIZE 4096 /* choose an efficiently fread'able size */
  168365. /*
  168366. * Initialize source --- called by jpeg_read_header
  168367. * before any data is actually read.
  168368. */
  168369. METHODDEF(void)
  168370. init_source (j_decompress_ptr cinfo)
  168371. {
  168372. my_src_ptr src = (my_src_ptr) cinfo->src;
  168373. /* We reset the empty-input-file flag for each image,
  168374. * but we don't clear the input buffer.
  168375. * This is correct behavior for reading a series of images from one source.
  168376. */
  168377. src->start_of_file = TRUE;
  168378. }
  168379. /*
  168380. * Fill the input buffer --- called whenever buffer is emptied.
  168381. *
  168382. * In typical applications, this should read fresh data into the buffer
  168383. * (ignoring the current state of next_input_byte & bytes_in_buffer),
  168384. * reset the pointer & count to the start of the buffer, and return TRUE
  168385. * indicating that the buffer has been reloaded. It is not necessary to
  168386. * fill the buffer entirely, only to obtain at least one more byte.
  168387. *
  168388. * There is no such thing as an EOF return. If the end of the file has been
  168389. * reached, the routine has a choice of ERREXIT() or inserting fake data into
  168390. * the buffer. In most cases, generating a warning message and inserting a
  168391. * fake EOI marker is the best course of action --- this will allow the
  168392. * decompressor to output however much of the image is there. However,
  168393. * the resulting error message is misleading if the real problem is an empty
  168394. * input file, so we handle that case specially.
  168395. *
  168396. * In applications that need to be able to suspend compression due to input
  168397. * not being available yet, a FALSE return indicates that no more data can be
  168398. * obtained right now, but more may be forthcoming later. In this situation,
  168399. * the decompressor will return to its caller (with an indication of the
  168400. * number of scanlines it has read, if any). The application should resume
  168401. * decompression after it has loaded more data into the input buffer. Note
  168402. * that there are substantial restrictions on the use of suspension --- see
  168403. * the documentation.
  168404. *
  168405. * When suspending, the decompressor will back up to a convenient restart point
  168406. * (typically the start of the current MCU). next_input_byte & bytes_in_buffer
  168407. * indicate where the restart point will be if the current call returns FALSE.
  168408. * Data beyond this point must be rescanned after resumption, so move it to
  168409. * the front of the buffer rather than discarding it.
  168410. */
  168411. METHODDEF(boolean)
  168412. fill_input_buffer (j_decompress_ptr cinfo)
  168413. {
  168414. my_src_ptr src = (my_src_ptr) cinfo->src;
  168415. size_t nbytes;
  168416. nbytes = JFREAD(src->infile, src->buffer, INPUT_BUF_SIZE);
  168417. if (nbytes <= 0) {
  168418. if (src->start_of_file) /* Treat empty input file as fatal error */
  168419. ERREXIT(cinfo, JERR_INPUT_EMPTY);
  168420. WARNMS(cinfo, JWRN_JPEG_EOF);
  168421. /* Insert a fake EOI marker */
  168422. src->buffer[0] = (JOCTET) 0xFF;
  168423. src->buffer[1] = (JOCTET) JPEG_EOI;
  168424. nbytes = 2;
  168425. }
  168426. src->pub.next_input_byte = src->buffer;
  168427. src->pub.bytes_in_buffer = nbytes;
  168428. src->start_of_file = FALSE;
  168429. return TRUE;
  168430. }
  168431. /*
  168432. * Skip data --- used to skip over a potentially large amount of
  168433. * uninteresting data (such as an APPn marker).
  168434. *
  168435. * Writers of suspendable-input applications must note that skip_input_data
  168436. * is not granted the right to give a suspension return. If the skip extends
  168437. * beyond the data currently in the buffer, the buffer can be marked empty so
  168438. * that the next read will cause a fill_input_buffer call that can suspend.
  168439. * Arranging for additional bytes to be discarded before reloading the input
  168440. * buffer is the application writer's problem.
  168441. */
  168442. METHODDEF(void)
  168443. skip_input_data (j_decompress_ptr cinfo, long num_bytes)
  168444. {
  168445. my_src_ptr src = (my_src_ptr) cinfo->src;
  168446. /* Just a dumb implementation for now. Could use fseek() except
  168447. * it doesn't work on pipes. Not clear that being smart is worth
  168448. * any trouble anyway --- large skips are infrequent.
  168449. */
  168450. if (num_bytes > 0) {
  168451. while (num_bytes > (long) src->pub.bytes_in_buffer) {
  168452. num_bytes -= (long) src->pub.bytes_in_buffer;
  168453. (void) fill_input_buffer(cinfo);
  168454. /* note we assume that fill_input_buffer will never return FALSE,
  168455. * so suspension need not be handled.
  168456. */
  168457. }
  168458. src->pub.next_input_byte += (size_t) num_bytes;
  168459. src->pub.bytes_in_buffer -= (size_t) num_bytes;
  168460. }
  168461. }
  168462. /*
  168463. * An additional method that can be provided by data source modules is the
  168464. * resync_to_restart method for error recovery in the presence of RST markers.
  168465. * For the moment, this source module just uses the default resync method
  168466. * provided by the JPEG library. That method assumes that no backtracking
  168467. * is possible.
  168468. */
  168469. /*
  168470. * Terminate source --- called by jpeg_finish_decompress
  168471. * after all data has been read. Often a no-op.
  168472. *
  168473. * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
  168474. * application must deal with any cleanup that should happen even
  168475. * for error exit.
  168476. */
  168477. METHODDEF(void)
  168478. term_source (j_decompress_ptr)
  168479. {
  168480. /* no work necessary here */
  168481. }
  168482. /*
  168483. * Prepare for input from a stdio stream.
  168484. * The caller must have already opened the stream, and is responsible
  168485. * for closing it after finishing decompression.
  168486. */
  168487. GLOBAL(void)
  168488. jpeg_stdio_src (j_decompress_ptr cinfo, FILE * infile)
  168489. {
  168490. my_src_ptr src;
  168491. /* The source object and input buffer are made permanent so that a series
  168492. * of JPEG images can be read from the same file by calling jpeg_stdio_src
  168493. * only before the first one. (If we discarded the buffer at the end of
  168494. * one image, we'd likely lose the start of the next one.)
  168495. * This makes it unsafe to use this manager and a different source
  168496. * manager serially with the same JPEG object. Caveat programmer.
  168497. */
  168498. if (cinfo->src == NULL) { /* first time for this JPEG object? */
  168499. cinfo->src = (struct jpeg_source_mgr *)
  168500. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  168501. SIZEOF(my_source_mgr));
  168502. src = (my_src_ptr) cinfo->src;
  168503. src->buffer = (JOCTET *)
  168504. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  168505. INPUT_BUF_SIZE * SIZEOF(JOCTET));
  168506. }
  168507. src = (my_src_ptr) cinfo->src;
  168508. src->pub.init_source = init_source;
  168509. src->pub.fill_input_buffer = fill_input_buffer;
  168510. src->pub.skip_input_data = skip_input_data;
  168511. src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
  168512. src->pub.term_source = term_source;
  168513. src->infile = infile;
  168514. src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
  168515. src->pub.next_input_byte = NULL; /* until buffer loaded */
  168516. }
  168517. /*** End of inlined file: jdatasrc.c ***/
  168518. /*** Start of inlined file: jdcoefct.c ***/
  168519. #define JPEG_INTERNALS
  168520. /* Block smoothing is only applicable for progressive JPEG, so: */
  168521. #ifndef D_PROGRESSIVE_SUPPORTED
  168522. #undef BLOCK_SMOOTHING_SUPPORTED
  168523. #endif
  168524. /* Private buffer controller object */
  168525. typedef struct {
  168526. struct jpeg_d_coef_controller pub; /* public fields */
  168527. /* These variables keep track of the current location of the input side. */
  168528. /* cinfo->input_iMCU_row is also used for this. */
  168529. JDIMENSION MCU_ctr; /* counts MCUs processed in current row */
  168530. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  168531. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  168532. /* The output side's location is represented by cinfo->output_iMCU_row. */
  168533. /* In single-pass modes, it's sufficient to buffer just one MCU.
  168534. * We allocate a workspace of D_MAX_BLOCKS_IN_MCU coefficient blocks,
  168535. * and let the entropy decoder write into that workspace each time.
  168536. * (On 80x86, the workspace is FAR even though it's not really very big;
  168537. * this is to keep the module interfaces unchanged when a large coefficient
  168538. * buffer is necessary.)
  168539. * In multi-pass modes, this array points to the current MCU's blocks
  168540. * within the virtual arrays; it is used only by the input side.
  168541. */
  168542. JBLOCKROW MCU_buffer[D_MAX_BLOCKS_IN_MCU];
  168543. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168544. /* In multi-pass modes, we need a virtual block array for each component. */
  168545. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  168546. #endif
  168547. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168548. /* When doing block smoothing, we latch coefficient Al values here */
  168549. int * coef_bits_latch;
  168550. #define SAVED_COEFS 6 /* we save coef_bits[0..5] */
  168551. #endif
  168552. } my_coef_controller3;
  168553. typedef my_coef_controller3 * my_coef_ptr3;
  168554. /* Forward declarations */
  168555. METHODDEF(int) decompress_onepass
  168556. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168557. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168558. METHODDEF(int) decompress_data
  168559. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168560. #endif
  168561. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168562. LOCAL(boolean) smoothing_ok JPP((j_decompress_ptr cinfo));
  168563. METHODDEF(int) decompress_smooth_data
  168564. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168565. #endif
  168566. LOCAL(void)
  168567. start_iMCU_row3 (j_decompress_ptr cinfo)
  168568. /* Reset within-iMCU-row counters for a new row (input side) */
  168569. {
  168570. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168571. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  168572. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  168573. * But at the bottom of the image, process only what's left.
  168574. */
  168575. if (cinfo->comps_in_scan > 1) {
  168576. coef->MCU_rows_per_iMCU_row = 1;
  168577. } else {
  168578. if (cinfo->input_iMCU_row < (cinfo->total_iMCU_rows-1))
  168579. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  168580. else
  168581. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  168582. }
  168583. coef->MCU_ctr = 0;
  168584. coef->MCU_vert_offset = 0;
  168585. }
  168586. /*
  168587. * Initialize for an input processing pass.
  168588. */
  168589. METHODDEF(void)
  168590. start_input_pass (j_decompress_ptr cinfo)
  168591. {
  168592. cinfo->input_iMCU_row = 0;
  168593. start_iMCU_row3(cinfo);
  168594. }
  168595. /*
  168596. * Initialize for an output processing pass.
  168597. */
  168598. METHODDEF(void)
  168599. start_output_pass (j_decompress_ptr cinfo)
  168600. {
  168601. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168602. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168603. /* If multipass, check to see whether to use block smoothing on this pass */
  168604. if (coef->pub.coef_arrays != NULL) {
  168605. if (cinfo->do_block_smoothing && smoothing_ok(cinfo))
  168606. coef->pub.decompress_data = decompress_smooth_data;
  168607. else
  168608. coef->pub.decompress_data = decompress_data;
  168609. }
  168610. #endif
  168611. cinfo->output_iMCU_row = 0;
  168612. }
  168613. /*
  168614. * Decompress and return some data in the single-pass case.
  168615. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  168616. * Input and output must run in lockstep since we have only a one-MCU buffer.
  168617. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168618. *
  168619. * NB: output_buf contains a plane for each component in image,
  168620. * which we index according to the component's SOF position.
  168621. */
  168622. METHODDEF(int)
  168623. decompress_onepass (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168624. {
  168625. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168626. JDIMENSION MCU_col_num; /* index of current MCU within row */
  168627. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  168628. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168629. int blkn, ci, xindex, yindex, yoffset, useful_width;
  168630. JSAMPARRAY output_ptr;
  168631. JDIMENSION start_col, output_col;
  168632. jpeg_component_info *compptr;
  168633. inverse_DCT_method_ptr inverse_DCT;
  168634. /* Loop to process as much as one whole iMCU row */
  168635. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  168636. yoffset++) {
  168637. for (MCU_col_num = coef->MCU_ctr; MCU_col_num <= last_MCU_col;
  168638. MCU_col_num++) {
  168639. /* Try to fetch an MCU. Entropy decoder expects buffer to be zeroed. */
  168640. jzero_far((void FAR *) coef->MCU_buffer[0],
  168641. (size_t) (cinfo->blocks_in_MCU * SIZEOF(JBLOCK)));
  168642. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  168643. /* Suspension forced; update state counters and exit */
  168644. coef->MCU_vert_offset = yoffset;
  168645. coef->MCU_ctr = MCU_col_num;
  168646. return JPEG_SUSPENDED;
  168647. }
  168648. /* Determine where data should go in output_buf and do the IDCT thing.
  168649. * We skip dummy blocks at the right and bottom edges (but blkn gets
  168650. * incremented past them!). Note the inner loop relies on having
  168651. * allocated the MCU_buffer[] blocks sequentially.
  168652. */
  168653. blkn = 0; /* index of current DCT block within MCU */
  168654. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168655. compptr = cinfo->cur_comp_info[ci];
  168656. /* Don't bother to IDCT an uninteresting component. */
  168657. if (! compptr->component_needed) {
  168658. blkn += compptr->MCU_blocks;
  168659. continue;
  168660. }
  168661. inverse_DCT = cinfo->idct->inverse_DCT[compptr->component_index];
  168662. useful_width = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  168663. : compptr->last_col_width;
  168664. output_ptr = output_buf[compptr->component_index] +
  168665. yoffset * compptr->DCT_scaled_size;
  168666. start_col = MCU_col_num * compptr->MCU_sample_width;
  168667. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  168668. if (cinfo->input_iMCU_row < last_iMCU_row ||
  168669. yoffset+yindex < compptr->last_row_height) {
  168670. output_col = start_col;
  168671. for (xindex = 0; xindex < useful_width; xindex++) {
  168672. (*inverse_DCT) (cinfo, compptr,
  168673. (JCOEFPTR) coef->MCU_buffer[blkn+xindex],
  168674. output_ptr, output_col);
  168675. output_col += compptr->DCT_scaled_size;
  168676. }
  168677. }
  168678. blkn += compptr->MCU_width;
  168679. output_ptr += compptr->DCT_scaled_size;
  168680. }
  168681. }
  168682. }
  168683. /* Completed an MCU row, but perhaps not an iMCU row */
  168684. coef->MCU_ctr = 0;
  168685. }
  168686. /* Completed the iMCU row, advance counters for next one */
  168687. cinfo->output_iMCU_row++;
  168688. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  168689. start_iMCU_row3(cinfo);
  168690. return JPEG_ROW_COMPLETED;
  168691. }
  168692. /* Completed the scan */
  168693. (*cinfo->inputctl->finish_input_pass) (cinfo);
  168694. return JPEG_SCAN_COMPLETED;
  168695. }
  168696. /*
  168697. * Dummy consume-input routine for single-pass operation.
  168698. */
  168699. METHODDEF(int)
  168700. dummy_consume_data (j_decompress_ptr)
  168701. {
  168702. return JPEG_SUSPENDED; /* Always indicate nothing was done */
  168703. }
  168704. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168705. /*
  168706. * Consume input data and store it in the full-image coefficient buffer.
  168707. * We read as much as one fully interleaved MCU row ("iMCU" row) per call,
  168708. * ie, v_samp_factor block rows for each component in the scan.
  168709. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168710. */
  168711. METHODDEF(int)
  168712. consume_data (j_decompress_ptr cinfo)
  168713. {
  168714. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168715. JDIMENSION MCU_col_num; /* index of current MCU within row */
  168716. int blkn, ci, xindex, yindex, yoffset;
  168717. JDIMENSION start_col;
  168718. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  168719. JBLOCKROW buffer_ptr;
  168720. jpeg_component_info *compptr;
  168721. /* Align the virtual buffers for the components used in this scan. */
  168722. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168723. compptr = cinfo->cur_comp_info[ci];
  168724. buffer[ci] = (*cinfo->mem->access_virt_barray)
  168725. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  168726. cinfo->input_iMCU_row * compptr->v_samp_factor,
  168727. (JDIMENSION) compptr->v_samp_factor, TRUE);
  168728. /* Note: entropy decoder expects buffer to be zeroed,
  168729. * but this is handled automatically by the memory manager
  168730. * because we requested a pre-zeroed array.
  168731. */
  168732. }
  168733. /* Loop to process one whole iMCU row */
  168734. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  168735. yoffset++) {
  168736. for (MCU_col_num = coef->MCU_ctr; MCU_col_num < cinfo->MCUs_per_row;
  168737. MCU_col_num++) {
  168738. /* Construct list of pointers to DCT blocks belonging to this MCU */
  168739. blkn = 0; /* index of current DCT block within MCU */
  168740. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168741. compptr = cinfo->cur_comp_info[ci];
  168742. start_col = MCU_col_num * compptr->MCU_width;
  168743. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  168744. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  168745. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  168746. coef->MCU_buffer[blkn++] = buffer_ptr++;
  168747. }
  168748. }
  168749. }
  168750. /* Try to fetch the MCU. */
  168751. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  168752. /* Suspension forced; update state counters and exit */
  168753. coef->MCU_vert_offset = yoffset;
  168754. coef->MCU_ctr = MCU_col_num;
  168755. return JPEG_SUSPENDED;
  168756. }
  168757. }
  168758. /* Completed an MCU row, but perhaps not an iMCU row */
  168759. coef->MCU_ctr = 0;
  168760. }
  168761. /* Completed the iMCU row, advance counters for next one */
  168762. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  168763. start_iMCU_row3(cinfo);
  168764. return JPEG_ROW_COMPLETED;
  168765. }
  168766. /* Completed the scan */
  168767. (*cinfo->inputctl->finish_input_pass) (cinfo);
  168768. return JPEG_SCAN_COMPLETED;
  168769. }
  168770. /*
  168771. * Decompress and return some data in the multi-pass case.
  168772. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  168773. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168774. *
  168775. * NB: output_buf contains a plane for each component in image.
  168776. */
  168777. METHODDEF(int)
  168778. decompress_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168779. {
  168780. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168781. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168782. JDIMENSION block_num;
  168783. int ci, block_row, block_rows;
  168784. JBLOCKARRAY buffer;
  168785. JBLOCKROW buffer_ptr;
  168786. JSAMPARRAY output_ptr;
  168787. JDIMENSION output_col;
  168788. jpeg_component_info *compptr;
  168789. inverse_DCT_method_ptr inverse_DCT;
  168790. /* Force some input to be done if we are getting ahead of the input. */
  168791. while (cinfo->input_scan_number < cinfo->output_scan_number ||
  168792. (cinfo->input_scan_number == cinfo->output_scan_number &&
  168793. cinfo->input_iMCU_row <= cinfo->output_iMCU_row)) {
  168794. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  168795. return JPEG_SUSPENDED;
  168796. }
  168797. /* OK, output from the virtual arrays. */
  168798. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168799. ci++, compptr++) {
  168800. /* Don't bother to IDCT an uninteresting component. */
  168801. if (! compptr->component_needed)
  168802. continue;
  168803. /* Align the virtual buffer for this component. */
  168804. buffer = (*cinfo->mem->access_virt_barray)
  168805. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168806. cinfo->output_iMCU_row * compptr->v_samp_factor,
  168807. (JDIMENSION) compptr->v_samp_factor, FALSE);
  168808. /* Count non-dummy DCT block rows in this iMCU row. */
  168809. if (cinfo->output_iMCU_row < last_iMCU_row)
  168810. block_rows = compptr->v_samp_factor;
  168811. else {
  168812. /* NB: can't use last_row_height here; it is input-side-dependent! */
  168813. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  168814. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  168815. }
  168816. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  168817. output_ptr = output_buf[ci];
  168818. /* Loop over all DCT blocks to be processed. */
  168819. for (block_row = 0; block_row < block_rows; block_row++) {
  168820. buffer_ptr = buffer[block_row];
  168821. output_col = 0;
  168822. for (block_num = 0; block_num < compptr->width_in_blocks; block_num++) {
  168823. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) buffer_ptr,
  168824. output_ptr, output_col);
  168825. buffer_ptr++;
  168826. output_col += compptr->DCT_scaled_size;
  168827. }
  168828. output_ptr += compptr->DCT_scaled_size;
  168829. }
  168830. }
  168831. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  168832. return JPEG_ROW_COMPLETED;
  168833. return JPEG_SCAN_COMPLETED;
  168834. }
  168835. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  168836. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168837. /*
  168838. * This code applies interblock smoothing as described by section K.8
  168839. * of the JPEG standard: the first 5 AC coefficients are estimated from
  168840. * the DC values of a DCT block and its 8 neighboring blocks.
  168841. * We apply smoothing only for progressive JPEG decoding, and only if
  168842. * the coefficients it can estimate are not yet known to full precision.
  168843. */
  168844. /* Natural-order array positions of the first 5 zigzag-order coefficients */
  168845. #define Q01_POS 1
  168846. #define Q10_POS 8
  168847. #define Q20_POS 16
  168848. #define Q11_POS 9
  168849. #define Q02_POS 2
  168850. /*
  168851. * Determine whether block smoothing is applicable and safe.
  168852. * We also latch the current states of the coef_bits[] entries for the
  168853. * AC coefficients; otherwise, if the input side of the decompressor
  168854. * advances into a new scan, we might think the coefficients are known
  168855. * more accurately than they really are.
  168856. */
  168857. LOCAL(boolean)
  168858. smoothing_ok (j_decompress_ptr cinfo)
  168859. {
  168860. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168861. boolean smoothing_useful = FALSE;
  168862. int ci, coefi;
  168863. jpeg_component_info *compptr;
  168864. JQUANT_TBL * qtable;
  168865. int * coef_bits;
  168866. int * coef_bits_latch;
  168867. if (! cinfo->progressive_mode || cinfo->coef_bits == NULL)
  168868. return FALSE;
  168869. /* Allocate latch area if not already done */
  168870. if (coef->coef_bits_latch == NULL)
  168871. coef->coef_bits_latch = (int *)
  168872. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168873. cinfo->num_components *
  168874. (SAVED_COEFS * SIZEOF(int)));
  168875. coef_bits_latch = coef->coef_bits_latch;
  168876. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168877. ci++, compptr++) {
  168878. /* All components' quantization values must already be latched. */
  168879. if ((qtable = compptr->quant_table) == NULL)
  168880. return FALSE;
  168881. /* Verify DC & first 5 AC quantizers are nonzero to avoid zero-divide. */
  168882. if (qtable->quantval[0] == 0 ||
  168883. qtable->quantval[Q01_POS] == 0 ||
  168884. qtable->quantval[Q10_POS] == 0 ||
  168885. qtable->quantval[Q20_POS] == 0 ||
  168886. qtable->quantval[Q11_POS] == 0 ||
  168887. qtable->quantval[Q02_POS] == 0)
  168888. return FALSE;
  168889. /* DC values must be at least partly known for all components. */
  168890. coef_bits = cinfo->coef_bits[ci];
  168891. if (coef_bits[0] < 0)
  168892. return FALSE;
  168893. /* Block smoothing is helpful if some AC coefficients remain inaccurate. */
  168894. for (coefi = 1; coefi <= 5; coefi++) {
  168895. coef_bits_latch[coefi] = coef_bits[coefi];
  168896. if (coef_bits[coefi] != 0)
  168897. smoothing_useful = TRUE;
  168898. }
  168899. coef_bits_latch += SAVED_COEFS;
  168900. }
  168901. return smoothing_useful;
  168902. }
  168903. /*
  168904. * Variant of decompress_data for use when doing block smoothing.
  168905. */
  168906. METHODDEF(int)
  168907. decompress_smooth_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168908. {
  168909. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168910. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168911. JDIMENSION block_num, last_block_column;
  168912. int ci, block_row, block_rows, access_rows;
  168913. JBLOCKARRAY buffer;
  168914. JBLOCKROW buffer_ptr, prev_block_row, next_block_row;
  168915. JSAMPARRAY output_ptr;
  168916. JDIMENSION output_col;
  168917. jpeg_component_info *compptr;
  168918. inverse_DCT_method_ptr inverse_DCT;
  168919. boolean first_row, last_row;
  168920. JBLOCK workspace;
  168921. int *coef_bits;
  168922. JQUANT_TBL *quanttbl;
  168923. INT32 Q00,Q01,Q02,Q10,Q11,Q20, num;
  168924. int DC1,DC2,DC3,DC4,DC5,DC6,DC7,DC8,DC9;
  168925. int Al, pred;
  168926. /* Force some input to be done if we are getting ahead of the input. */
  168927. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  168928. ! cinfo->inputctl->eoi_reached) {
  168929. if (cinfo->input_scan_number == cinfo->output_scan_number) {
  168930. /* If input is working on current scan, we ordinarily want it to
  168931. * have completed the current row. But if input scan is DC,
  168932. * we want it to keep one row ahead so that next block row's DC
  168933. * values are up to date.
  168934. */
  168935. JDIMENSION delta = (cinfo->Ss == 0) ? 1 : 0;
  168936. if (cinfo->input_iMCU_row > cinfo->output_iMCU_row+delta)
  168937. break;
  168938. }
  168939. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  168940. return JPEG_SUSPENDED;
  168941. }
  168942. /* OK, output from the virtual arrays. */
  168943. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168944. ci++, compptr++) {
  168945. /* Don't bother to IDCT an uninteresting component. */
  168946. if (! compptr->component_needed)
  168947. continue;
  168948. /* Count non-dummy DCT block rows in this iMCU row. */
  168949. if (cinfo->output_iMCU_row < last_iMCU_row) {
  168950. block_rows = compptr->v_samp_factor;
  168951. access_rows = block_rows * 2; /* this and next iMCU row */
  168952. last_row = FALSE;
  168953. } else {
  168954. /* NB: can't use last_row_height here; it is input-side-dependent! */
  168955. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  168956. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  168957. access_rows = block_rows; /* this iMCU row only */
  168958. last_row = TRUE;
  168959. }
  168960. /* Align the virtual buffer for this component. */
  168961. if (cinfo->output_iMCU_row > 0) {
  168962. access_rows += compptr->v_samp_factor; /* prior iMCU row too */
  168963. buffer = (*cinfo->mem->access_virt_barray)
  168964. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168965. (cinfo->output_iMCU_row - 1) * compptr->v_samp_factor,
  168966. (JDIMENSION) access_rows, FALSE);
  168967. buffer += compptr->v_samp_factor; /* point to current iMCU row */
  168968. first_row = FALSE;
  168969. } else {
  168970. buffer = (*cinfo->mem->access_virt_barray)
  168971. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168972. (JDIMENSION) 0, (JDIMENSION) access_rows, FALSE);
  168973. first_row = TRUE;
  168974. }
  168975. /* Fetch component-dependent info */
  168976. coef_bits = coef->coef_bits_latch + (ci * SAVED_COEFS);
  168977. quanttbl = compptr->quant_table;
  168978. Q00 = quanttbl->quantval[0];
  168979. Q01 = quanttbl->quantval[Q01_POS];
  168980. Q10 = quanttbl->quantval[Q10_POS];
  168981. Q20 = quanttbl->quantval[Q20_POS];
  168982. Q11 = quanttbl->quantval[Q11_POS];
  168983. Q02 = quanttbl->quantval[Q02_POS];
  168984. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  168985. output_ptr = output_buf[ci];
  168986. /* Loop over all DCT blocks to be processed. */
  168987. for (block_row = 0; block_row < block_rows; block_row++) {
  168988. buffer_ptr = buffer[block_row];
  168989. if (first_row && block_row == 0)
  168990. prev_block_row = buffer_ptr;
  168991. else
  168992. prev_block_row = buffer[block_row-1];
  168993. if (last_row && block_row == block_rows-1)
  168994. next_block_row = buffer_ptr;
  168995. else
  168996. next_block_row = buffer[block_row+1];
  168997. /* We fetch the surrounding DC values using a sliding-register approach.
  168998. * Initialize all nine here so as to do the right thing on narrow pics.
  168999. */
  169000. DC1 = DC2 = DC3 = (int) prev_block_row[0][0];
  169001. DC4 = DC5 = DC6 = (int) buffer_ptr[0][0];
  169002. DC7 = DC8 = DC9 = (int) next_block_row[0][0];
  169003. output_col = 0;
  169004. last_block_column = compptr->width_in_blocks - 1;
  169005. for (block_num = 0; block_num <= last_block_column; block_num++) {
  169006. /* Fetch current DCT block into workspace so we can modify it. */
  169007. jcopy_block_row(buffer_ptr, (JBLOCKROW) workspace, (JDIMENSION) 1);
  169008. /* Update DC values */
  169009. if (block_num < last_block_column) {
  169010. DC3 = (int) prev_block_row[1][0];
  169011. DC6 = (int) buffer_ptr[1][0];
  169012. DC9 = (int) next_block_row[1][0];
  169013. }
  169014. /* Compute coefficient estimates per K.8.
  169015. * An estimate is applied only if coefficient is still zero,
  169016. * and is not known to be fully accurate.
  169017. */
  169018. /* AC01 */
  169019. if ((Al=coef_bits[1]) != 0 && workspace[1] == 0) {
  169020. num = 36 * Q00 * (DC4 - DC6);
  169021. if (num >= 0) {
  169022. pred = (int) (((Q01<<7) + num) / (Q01<<8));
  169023. if (Al > 0 && pred >= (1<<Al))
  169024. pred = (1<<Al)-1;
  169025. } else {
  169026. pred = (int) (((Q01<<7) - num) / (Q01<<8));
  169027. if (Al > 0 && pred >= (1<<Al))
  169028. pred = (1<<Al)-1;
  169029. pred = -pred;
  169030. }
  169031. workspace[1] = (JCOEF) pred;
  169032. }
  169033. /* AC10 */
  169034. if ((Al=coef_bits[2]) != 0 && workspace[8] == 0) {
  169035. num = 36 * Q00 * (DC2 - DC8);
  169036. if (num >= 0) {
  169037. pred = (int) (((Q10<<7) + num) / (Q10<<8));
  169038. if (Al > 0 && pred >= (1<<Al))
  169039. pred = (1<<Al)-1;
  169040. } else {
  169041. pred = (int) (((Q10<<7) - num) / (Q10<<8));
  169042. if (Al > 0 && pred >= (1<<Al))
  169043. pred = (1<<Al)-1;
  169044. pred = -pred;
  169045. }
  169046. workspace[8] = (JCOEF) pred;
  169047. }
  169048. /* AC20 */
  169049. if ((Al=coef_bits[3]) != 0 && workspace[16] == 0) {
  169050. num = 9 * Q00 * (DC2 + DC8 - 2*DC5);
  169051. if (num >= 0) {
  169052. pred = (int) (((Q20<<7) + num) / (Q20<<8));
  169053. if (Al > 0 && pred >= (1<<Al))
  169054. pred = (1<<Al)-1;
  169055. } else {
  169056. pred = (int) (((Q20<<7) - num) / (Q20<<8));
  169057. if (Al > 0 && pred >= (1<<Al))
  169058. pred = (1<<Al)-1;
  169059. pred = -pred;
  169060. }
  169061. workspace[16] = (JCOEF) pred;
  169062. }
  169063. /* AC11 */
  169064. if ((Al=coef_bits[4]) != 0 && workspace[9] == 0) {
  169065. num = 5 * Q00 * (DC1 - DC3 - DC7 + DC9);
  169066. if (num >= 0) {
  169067. pred = (int) (((Q11<<7) + num) / (Q11<<8));
  169068. if (Al > 0 && pred >= (1<<Al))
  169069. pred = (1<<Al)-1;
  169070. } else {
  169071. pred = (int) (((Q11<<7) - num) / (Q11<<8));
  169072. if (Al > 0 && pred >= (1<<Al))
  169073. pred = (1<<Al)-1;
  169074. pred = -pred;
  169075. }
  169076. workspace[9] = (JCOEF) pred;
  169077. }
  169078. /* AC02 */
  169079. if ((Al=coef_bits[5]) != 0 && workspace[2] == 0) {
  169080. num = 9 * Q00 * (DC4 + DC6 - 2*DC5);
  169081. if (num >= 0) {
  169082. pred = (int) (((Q02<<7) + num) / (Q02<<8));
  169083. if (Al > 0 && pred >= (1<<Al))
  169084. pred = (1<<Al)-1;
  169085. } else {
  169086. pred = (int) (((Q02<<7) - num) / (Q02<<8));
  169087. if (Al > 0 && pred >= (1<<Al))
  169088. pred = (1<<Al)-1;
  169089. pred = -pred;
  169090. }
  169091. workspace[2] = (JCOEF) pred;
  169092. }
  169093. /* OK, do the IDCT */
  169094. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) workspace,
  169095. output_ptr, output_col);
  169096. /* Advance for next column */
  169097. DC1 = DC2; DC2 = DC3;
  169098. DC4 = DC5; DC5 = DC6;
  169099. DC7 = DC8; DC8 = DC9;
  169100. buffer_ptr++, prev_block_row++, next_block_row++;
  169101. output_col += compptr->DCT_scaled_size;
  169102. }
  169103. output_ptr += compptr->DCT_scaled_size;
  169104. }
  169105. }
  169106. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  169107. return JPEG_ROW_COMPLETED;
  169108. return JPEG_SCAN_COMPLETED;
  169109. }
  169110. #endif /* BLOCK_SMOOTHING_SUPPORTED */
  169111. /*
  169112. * Initialize coefficient buffer controller.
  169113. */
  169114. GLOBAL(void)
  169115. jinit_d_coef_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  169116. {
  169117. my_coef_ptr3 coef;
  169118. coef = (my_coef_ptr3)
  169119. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169120. SIZEOF(my_coef_controller3));
  169121. cinfo->coef = (struct jpeg_d_coef_controller *) coef;
  169122. coef->pub.start_input_pass = start_input_pass;
  169123. coef->pub.start_output_pass = start_output_pass;
  169124. #ifdef BLOCK_SMOOTHING_SUPPORTED
  169125. coef->coef_bits_latch = NULL;
  169126. #endif
  169127. /* Create the coefficient buffer. */
  169128. if (need_full_buffer) {
  169129. #ifdef D_MULTISCAN_FILES_SUPPORTED
  169130. /* Allocate a full-image virtual array for each component, */
  169131. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  169132. /* Note we ask for a pre-zeroed array. */
  169133. int ci, access_rows;
  169134. jpeg_component_info *compptr;
  169135. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169136. ci++, compptr++) {
  169137. access_rows = compptr->v_samp_factor;
  169138. #ifdef BLOCK_SMOOTHING_SUPPORTED
  169139. /* If block smoothing could be used, need a bigger window */
  169140. if (cinfo->progressive_mode)
  169141. access_rows *= 3;
  169142. #endif
  169143. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  169144. ((j_common_ptr) cinfo, JPOOL_IMAGE, TRUE,
  169145. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  169146. (long) compptr->h_samp_factor),
  169147. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  169148. (long) compptr->v_samp_factor),
  169149. (JDIMENSION) access_rows);
  169150. }
  169151. coef->pub.consume_data = consume_data;
  169152. coef->pub.decompress_data = decompress_data;
  169153. coef->pub.coef_arrays = coef->whole_image; /* link to virtual arrays */
  169154. #else
  169155. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169156. #endif
  169157. } else {
  169158. /* We only need a single-MCU buffer. */
  169159. JBLOCKROW buffer;
  169160. int i;
  169161. buffer = (JBLOCKROW)
  169162. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169163. D_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  169164. for (i = 0; i < D_MAX_BLOCKS_IN_MCU; i++) {
  169165. coef->MCU_buffer[i] = buffer + i;
  169166. }
  169167. coef->pub.consume_data = dummy_consume_data;
  169168. coef->pub.decompress_data = decompress_onepass;
  169169. coef->pub.coef_arrays = NULL; /* flag for no virtual arrays */
  169170. }
  169171. }
  169172. /*** End of inlined file: jdcoefct.c ***/
  169173. #undef FIX
  169174. /*** Start of inlined file: jdcolor.c ***/
  169175. #define JPEG_INTERNALS
  169176. /* Private subobject */
  169177. typedef struct {
  169178. struct jpeg_color_deconverter pub; /* public fields */
  169179. /* Private state for YCC->RGB conversion */
  169180. int * Cr_r_tab; /* => table for Cr to R conversion */
  169181. int * Cb_b_tab; /* => table for Cb to B conversion */
  169182. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  169183. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  169184. } my_color_deconverter2;
  169185. typedef my_color_deconverter2 * my_cconvert_ptr2;
  169186. /**************** YCbCr -> RGB conversion: most common case **************/
  169187. /*
  169188. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  169189. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  169190. * The conversion equations to be implemented are therefore
  169191. * R = Y + 1.40200 * Cr
  169192. * G = Y - 0.34414 * Cb - 0.71414 * Cr
  169193. * B = Y + 1.77200 * Cb
  169194. * where Cb and Cr represent the incoming values less CENTERJSAMPLE.
  169195. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  169196. *
  169197. * To avoid floating-point arithmetic, we represent the fractional constants
  169198. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  169199. * the products by 2^16, with appropriate rounding, to get the correct answer.
  169200. * Notice that Y, being an integral input, does not contribute any fraction
  169201. * so it need not participate in the rounding.
  169202. *
  169203. * For even more speed, we avoid doing any multiplications in the inner loop
  169204. * by precalculating the constants times Cb and Cr for all possible values.
  169205. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  169206. * for 12-bit samples it is still acceptable. It's not very reasonable for
  169207. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  169208. * colorspace anyway.
  169209. * The Cr=>R and Cb=>B values can be rounded to integers in advance; the
  169210. * values for the G calculation are left scaled up, since we must add them
  169211. * together before rounding.
  169212. */
  169213. #define SCALEBITS 16 /* speediest right-shift on some machines */
  169214. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  169215. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  169216. /*
  169217. * Initialize tables for YCC->RGB colorspace conversion.
  169218. */
  169219. LOCAL(void)
  169220. build_ycc_rgb_table (j_decompress_ptr cinfo)
  169221. {
  169222. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  169223. int i;
  169224. INT32 x;
  169225. SHIFT_TEMPS
  169226. cconvert->Cr_r_tab = (int *)
  169227. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169228. (MAXJSAMPLE+1) * SIZEOF(int));
  169229. cconvert->Cb_b_tab = (int *)
  169230. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169231. (MAXJSAMPLE+1) * SIZEOF(int));
  169232. cconvert->Cr_g_tab = (INT32 *)
  169233. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169234. (MAXJSAMPLE+1) * SIZEOF(INT32));
  169235. cconvert->Cb_g_tab = (INT32 *)
  169236. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169237. (MAXJSAMPLE+1) * SIZEOF(INT32));
  169238. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  169239. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  169240. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  169241. /* Cr=>R value is nearest int to 1.40200 * x */
  169242. cconvert->Cr_r_tab[i] = (int)
  169243. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  169244. /* Cb=>B value is nearest int to 1.77200 * x */
  169245. cconvert->Cb_b_tab[i] = (int)
  169246. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  169247. /* Cr=>G value is scaled-up -0.71414 * x */
  169248. cconvert->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  169249. /* Cb=>G value is scaled-up -0.34414 * x */
  169250. /* We also add in ONE_HALF so that need not do it in inner loop */
  169251. cconvert->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  169252. }
  169253. }
  169254. /*
  169255. * Convert some rows of samples to the output colorspace.
  169256. *
  169257. * Note that we change from noninterleaved, one-plane-per-component format
  169258. * to interleaved-pixel format. The output buffer is therefore three times
  169259. * as wide as the input buffer.
  169260. * A starting row offset is provided only for the input buffer. The caller
  169261. * can easily adjust the passed output_buf value to accommodate any row
  169262. * offset required on that side.
  169263. */
  169264. METHODDEF(void)
  169265. ycc_rgb_convert (j_decompress_ptr cinfo,
  169266. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169267. JSAMPARRAY output_buf, int num_rows)
  169268. {
  169269. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  169270. register int y, cb, cr;
  169271. register JSAMPROW outptr;
  169272. register JSAMPROW inptr0, inptr1, inptr2;
  169273. register JDIMENSION col;
  169274. JDIMENSION num_cols = cinfo->output_width;
  169275. /* copy these pointers into registers if possible */
  169276. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  169277. register int * Crrtab = cconvert->Cr_r_tab;
  169278. register int * Cbbtab = cconvert->Cb_b_tab;
  169279. register INT32 * Crgtab = cconvert->Cr_g_tab;
  169280. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  169281. SHIFT_TEMPS
  169282. while (--num_rows >= 0) {
  169283. inptr0 = input_buf[0][input_row];
  169284. inptr1 = input_buf[1][input_row];
  169285. inptr2 = input_buf[2][input_row];
  169286. input_row++;
  169287. outptr = *output_buf++;
  169288. for (col = 0; col < num_cols; col++) {
  169289. y = GETJSAMPLE(inptr0[col]);
  169290. cb = GETJSAMPLE(inptr1[col]);
  169291. cr = GETJSAMPLE(inptr2[col]);
  169292. /* Range-limiting is essential due to noise introduced by DCT losses. */
  169293. outptr[RGB_RED] = range_limit[y + Crrtab[cr]];
  169294. outptr[RGB_GREEN] = range_limit[y +
  169295. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  169296. SCALEBITS))];
  169297. outptr[RGB_BLUE] = range_limit[y + Cbbtab[cb]];
  169298. outptr += RGB_PIXELSIZE;
  169299. }
  169300. }
  169301. }
  169302. /**************** Cases other than YCbCr -> RGB **************/
  169303. /*
  169304. * Color conversion for no colorspace change: just copy the data,
  169305. * converting from separate-planes to interleaved representation.
  169306. */
  169307. METHODDEF(void)
  169308. null_convert2 (j_decompress_ptr cinfo,
  169309. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169310. JSAMPARRAY output_buf, int num_rows)
  169311. {
  169312. register JSAMPROW inptr, outptr;
  169313. register JDIMENSION count;
  169314. register int num_components = cinfo->num_components;
  169315. JDIMENSION num_cols = cinfo->output_width;
  169316. int ci;
  169317. while (--num_rows >= 0) {
  169318. for (ci = 0; ci < num_components; ci++) {
  169319. inptr = input_buf[ci][input_row];
  169320. outptr = output_buf[0] + ci;
  169321. for (count = num_cols; count > 0; count--) {
  169322. *outptr = *inptr++; /* needn't bother with GETJSAMPLE() here */
  169323. outptr += num_components;
  169324. }
  169325. }
  169326. input_row++;
  169327. output_buf++;
  169328. }
  169329. }
  169330. /*
  169331. * Color conversion for grayscale: just copy the data.
  169332. * This also works for YCbCr -> grayscale conversion, in which
  169333. * we just copy the Y (luminance) component and ignore chrominance.
  169334. */
  169335. METHODDEF(void)
  169336. grayscale_convert2 (j_decompress_ptr cinfo,
  169337. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169338. JSAMPARRAY output_buf, int num_rows)
  169339. {
  169340. jcopy_sample_rows(input_buf[0], (int) input_row, output_buf, 0,
  169341. num_rows, cinfo->output_width);
  169342. }
  169343. /*
  169344. * Convert grayscale to RGB: just duplicate the graylevel three times.
  169345. * This is provided to support applications that don't want to cope
  169346. * with grayscale as a separate case.
  169347. */
  169348. METHODDEF(void)
  169349. gray_rgb_convert (j_decompress_ptr cinfo,
  169350. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169351. JSAMPARRAY output_buf, int num_rows)
  169352. {
  169353. register JSAMPROW inptr, outptr;
  169354. register JDIMENSION col;
  169355. JDIMENSION num_cols = cinfo->output_width;
  169356. while (--num_rows >= 0) {
  169357. inptr = input_buf[0][input_row++];
  169358. outptr = *output_buf++;
  169359. for (col = 0; col < num_cols; col++) {
  169360. /* We can dispense with GETJSAMPLE() here */
  169361. outptr[RGB_RED] = outptr[RGB_GREEN] = outptr[RGB_BLUE] = inptr[col];
  169362. outptr += RGB_PIXELSIZE;
  169363. }
  169364. }
  169365. }
  169366. /*
  169367. * Adobe-style YCCK->CMYK conversion.
  169368. * We convert YCbCr to R=1-C, G=1-M, and B=1-Y using the same
  169369. * conversion as above, while passing K (black) unchanged.
  169370. * We assume build_ycc_rgb_table has been called.
  169371. */
  169372. METHODDEF(void)
  169373. ycck_cmyk_convert (j_decompress_ptr cinfo,
  169374. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169375. JSAMPARRAY output_buf, int num_rows)
  169376. {
  169377. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  169378. register int y, cb, cr;
  169379. register JSAMPROW outptr;
  169380. register JSAMPROW inptr0, inptr1, inptr2, inptr3;
  169381. register JDIMENSION col;
  169382. JDIMENSION num_cols = cinfo->output_width;
  169383. /* copy these pointers into registers if possible */
  169384. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  169385. register int * Crrtab = cconvert->Cr_r_tab;
  169386. register int * Cbbtab = cconvert->Cb_b_tab;
  169387. register INT32 * Crgtab = cconvert->Cr_g_tab;
  169388. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  169389. SHIFT_TEMPS
  169390. while (--num_rows >= 0) {
  169391. inptr0 = input_buf[0][input_row];
  169392. inptr1 = input_buf[1][input_row];
  169393. inptr2 = input_buf[2][input_row];
  169394. inptr3 = input_buf[3][input_row];
  169395. input_row++;
  169396. outptr = *output_buf++;
  169397. for (col = 0; col < num_cols; col++) {
  169398. y = GETJSAMPLE(inptr0[col]);
  169399. cb = GETJSAMPLE(inptr1[col]);
  169400. cr = GETJSAMPLE(inptr2[col]);
  169401. /* Range-limiting is essential due to noise introduced by DCT losses. */
  169402. outptr[0] = range_limit[MAXJSAMPLE - (y + Crrtab[cr])]; /* red */
  169403. outptr[1] = range_limit[MAXJSAMPLE - (y + /* green */
  169404. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  169405. SCALEBITS)))];
  169406. outptr[2] = range_limit[MAXJSAMPLE - (y + Cbbtab[cb])]; /* blue */
  169407. /* K passes through unchanged */
  169408. outptr[3] = inptr3[col]; /* don't need GETJSAMPLE here */
  169409. outptr += 4;
  169410. }
  169411. }
  169412. }
  169413. /*
  169414. * Empty method for start_pass.
  169415. */
  169416. METHODDEF(void)
  169417. start_pass_dcolor (j_decompress_ptr)
  169418. {
  169419. /* no work needed */
  169420. }
  169421. /*
  169422. * Module initialization routine for output colorspace conversion.
  169423. */
  169424. GLOBAL(void)
  169425. jinit_color_deconverter (j_decompress_ptr cinfo)
  169426. {
  169427. my_cconvert_ptr2 cconvert;
  169428. int ci;
  169429. cconvert = (my_cconvert_ptr2)
  169430. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169431. SIZEOF(my_color_deconverter2));
  169432. cinfo->cconvert = (struct jpeg_color_deconverter *) cconvert;
  169433. cconvert->pub.start_pass = start_pass_dcolor;
  169434. /* Make sure num_components agrees with jpeg_color_space */
  169435. switch (cinfo->jpeg_color_space) {
  169436. case JCS_GRAYSCALE:
  169437. if (cinfo->num_components != 1)
  169438. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169439. break;
  169440. case JCS_RGB:
  169441. case JCS_YCbCr:
  169442. if (cinfo->num_components != 3)
  169443. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169444. break;
  169445. case JCS_CMYK:
  169446. case JCS_YCCK:
  169447. if (cinfo->num_components != 4)
  169448. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169449. break;
  169450. default: /* JCS_UNKNOWN can be anything */
  169451. if (cinfo->num_components < 1)
  169452. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169453. break;
  169454. }
  169455. /* Set out_color_components and conversion method based on requested space.
  169456. * Also clear the component_needed flags for any unused components,
  169457. * so that earlier pipeline stages can avoid useless computation.
  169458. */
  169459. switch (cinfo->out_color_space) {
  169460. case JCS_GRAYSCALE:
  169461. cinfo->out_color_components = 1;
  169462. if (cinfo->jpeg_color_space == JCS_GRAYSCALE ||
  169463. cinfo->jpeg_color_space == JCS_YCbCr) {
  169464. cconvert->pub.color_convert = grayscale_convert2;
  169465. /* For color->grayscale conversion, only the Y (0) component is needed */
  169466. for (ci = 1; ci < cinfo->num_components; ci++)
  169467. cinfo->comp_info[ci].component_needed = FALSE;
  169468. } else
  169469. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169470. break;
  169471. case JCS_RGB:
  169472. cinfo->out_color_components = RGB_PIXELSIZE;
  169473. if (cinfo->jpeg_color_space == JCS_YCbCr) {
  169474. cconvert->pub.color_convert = ycc_rgb_convert;
  169475. build_ycc_rgb_table(cinfo);
  169476. } else if (cinfo->jpeg_color_space == JCS_GRAYSCALE) {
  169477. cconvert->pub.color_convert = gray_rgb_convert;
  169478. } else if (cinfo->jpeg_color_space == JCS_RGB && RGB_PIXELSIZE == 3) {
  169479. cconvert->pub.color_convert = null_convert2;
  169480. } else
  169481. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169482. break;
  169483. case JCS_CMYK:
  169484. cinfo->out_color_components = 4;
  169485. if (cinfo->jpeg_color_space == JCS_YCCK) {
  169486. cconvert->pub.color_convert = ycck_cmyk_convert;
  169487. build_ycc_rgb_table(cinfo);
  169488. } else if (cinfo->jpeg_color_space == JCS_CMYK) {
  169489. cconvert->pub.color_convert = null_convert2;
  169490. } else
  169491. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169492. break;
  169493. default:
  169494. /* Permit null conversion to same output space */
  169495. if (cinfo->out_color_space == cinfo->jpeg_color_space) {
  169496. cinfo->out_color_components = cinfo->num_components;
  169497. cconvert->pub.color_convert = null_convert2;
  169498. } else /* unsupported non-null conversion */
  169499. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169500. break;
  169501. }
  169502. if (cinfo->quantize_colors)
  169503. cinfo->output_components = 1; /* single colormapped output component */
  169504. else
  169505. cinfo->output_components = cinfo->out_color_components;
  169506. }
  169507. /*** End of inlined file: jdcolor.c ***/
  169508. #undef FIX
  169509. /*** Start of inlined file: jddctmgr.c ***/
  169510. #define JPEG_INTERNALS
  169511. /*
  169512. * The decompressor input side (jdinput.c) saves away the appropriate
  169513. * quantization table for each component at the start of the first scan
  169514. * involving that component. (This is necessary in order to correctly
  169515. * decode files that reuse Q-table slots.)
  169516. * When we are ready to make an output pass, the saved Q-table is converted
  169517. * to a multiplier table that will actually be used by the IDCT routine.
  169518. * The multiplier table contents are IDCT-method-dependent. To support
  169519. * application changes in IDCT method between scans, we can remake the
  169520. * multiplier tables if necessary.
  169521. * In buffered-image mode, the first output pass may occur before any data
  169522. * has been seen for some components, and thus before their Q-tables have
  169523. * been saved away. To handle this case, multiplier tables are preset
  169524. * to zeroes; the result of the IDCT will be a neutral gray level.
  169525. */
  169526. /* Private subobject for this module */
  169527. typedef struct {
  169528. struct jpeg_inverse_dct pub; /* public fields */
  169529. /* This array contains the IDCT method code that each multiplier table
  169530. * is currently set up for, or -1 if it's not yet set up.
  169531. * The actual multiplier tables are pointed to by dct_table in the
  169532. * per-component comp_info structures.
  169533. */
  169534. int cur_method[MAX_COMPONENTS];
  169535. } my_idct_controller;
  169536. typedef my_idct_controller * my_idct_ptr;
  169537. /* Allocated multiplier tables: big enough for any supported variant */
  169538. typedef union {
  169539. ISLOW_MULT_TYPE islow_array[DCTSIZE2];
  169540. #ifdef DCT_IFAST_SUPPORTED
  169541. IFAST_MULT_TYPE ifast_array[DCTSIZE2];
  169542. #endif
  169543. #ifdef DCT_FLOAT_SUPPORTED
  169544. FLOAT_MULT_TYPE float_array[DCTSIZE2];
  169545. #endif
  169546. } multiplier_table;
  169547. /* The current scaled-IDCT routines require ISLOW-style multiplier tables,
  169548. * so be sure to compile that code if either ISLOW or SCALING is requested.
  169549. */
  169550. #ifdef DCT_ISLOW_SUPPORTED
  169551. #define PROVIDE_ISLOW_TABLES
  169552. #else
  169553. #ifdef IDCT_SCALING_SUPPORTED
  169554. #define PROVIDE_ISLOW_TABLES
  169555. #endif
  169556. #endif
  169557. /*
  169558. * Prepare for an output pass.
  169559. * Here we select the proper IDCT routine for each component and build
  169560. * a matching multiplier table.
  169561. */
  169562. METHODDEF(void)
  169563. start_pass (j_decompress_ptr cinfo)
  169564. {
  169565. my_idct_ptr idct = (my_idct_ptr) cinfo->idct;
  169566. int ci, i;
  169567. jpeg_component_info *compptr;
  169568. int method = 0;
  169569. inverse_DCT_method_ptr method_ptr = NULL;
  169570. JQUANT_TBL * qtbl;
  169571. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169572. ci++, compptr++) {
  169573. /* Select the proper IDCT routine for this component's scaling */
  169574. switch (compptr->DCT_scaled_size) {
  169575. #ifdef IDCT_SCALING_SUPPORTED
  169576. case 1:
  169577. method_ptr = jpeg_idct_1x1;
  169578. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169579. break;
  169580. case 2:
  169581. method_ptr = jpeg_idct_2x2;
  169582. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169583. break;
  169584. case 4:
  169585. method_ptr = jpeg_idct_4x4;
  169586. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169587. break;
  169588. #endif
  169589. case DCTSIZE:
  169590. switch (cinfo->dct_method) {
  169591. #ifdef DCT_ISLOW_SUPPORTED
  169592. case JDCT_ISLOW:
  169593. method_ptr = jpeg_idct_islow;
  169594. method = JDCT_ISLOW;
  169595. break;
  169596. #endif
  169597. #ifdef DCT_IFAST_SUPPORTED
  169598. case JDCT_IFAST:
  169599. method_ptr = jpeg_idct_ifast;
  169600. method = JDCT_IFAST;
  169601. break;
  169602. #endif
  169603. #ifdef DCT_FLOAT_SUPPORTED
  169604. case JDCT_FLOAT:
  169605. method_ptr = jpeg_idct_float;
  169606. method = JDCT_FLOAT;
  169607. break;
  169608. #endif
  169609. default:
  169610. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169611. break;
  169612. }
  169613. break;
  169614. default:
  169615. ERREXIT1(cinfo, JERR_BAD_DCTSIZE, compptr->DCT_scaled_size);
  169616. break;
  169617. }
  169618. idct->pub.inverse_DCT[ci] = method_ptr;
  169619. /* Create multiplier table from quant table.
  169620. * However, we can skip this if the component is uninteresting
  169621. * or if we already built the table. Also, if no quant table
  169622. * has yet been saved for the component, we leave the
  169623. * multiplier table all-zero; we'll be reading zeroes from the
  169624. * coefficient controller's buffer anyway.
  169625. */
  169626. if (! compptr->component_needed || idct->cur_method[ci] == method)
  169627. continue;
  169628. qtbl = compptr->quant_table;
  169629. if (qtbl == NULL) /* happens if no data yet for component */
  169630. continue;
  169631. idct->cur_method[ci] = method;
  169632. switch (method) {
  169633. #ifdef PROVIDE_ISLOW_TABLES
  169634. case JDCT_ISLOW:
  169635. {
  169636. /* For LL&M IDCT method, multipliers are equal to raw quantization
  169637. * coefficients, but are stored as ints to ensure access efficiency.
  169638. */
  169639. ISLOW_MULT_TYPE * ismtbl = (ISLOW_MULT_TYPE *) compptr->dct_table;
  169640. for (i = 0; i < DCTSIZE2; i++) {
  169641. ismtbl[i] = (ISLOW_MULT_TYPE) qtbl->quantval[i];
  169642. }
  169643. }
  169644. break;
  169645. #endif
  169646. #ifdef DCT_IFAST_SUPPORTED
  169647. case JDCT_IFAST:
  169648. {
  169649. /* For AA&N IDCT method, multipliers are equal to quantization
  169650. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  169651. * scalefactor[0] = 1
  169652. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  169653. * For integer operation, the multiplier table is to be scaled by
  169654. * IFAST_SCALE_BITS.
  169655. */
  169656. IFAST_MULT_TYPE * ifmtbl = (IFAST_MULT_TYPE *) compptr->dct_table;
  169657. #define CONST_BITS 14
  169658. static const INT16 aanscales[DCTSIZE2] = {
  169659. /* precomputed values scaled up by 14 bits */
  169660. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  169661. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  169662. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  169663. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  169664. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  169665. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  169666. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  169667. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  169668. };
  169669. SHIFT_TEMPS
  169670. for (i = 0; i < DCTSIZE2; i++) {
  169671. ifmtbl[i] = (IFAST_MULT_TYPE)
  169672. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  169673. (INT32) aanscales[i]),
  169674. CONST_BITS-IFAST_SCALE_BITS);
  169675. }
  169676. }
  169677. break;
  169678. #endif
  169679. #ifdef DCT_FLOAT_SUPPORTED
  169680. case JDCT_FLOAT:
  169681. {
  169682. /* For float AA&N IDCT method, multipliers are equal to quantization
  169683. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  169684. * scalefactor[0] = 1
  169685. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  169686. */
  169687. FLOAT_MULT_TYPE * fmtbl = (FLOAT_MULT_TYPE *) compptr->dct_table;
  169688. int row, col;
  169689. static const double aanscalefactor[DCTSIZE] = {
  169690. 1.0, 1.387039845, 1.306562965, 1.175875602,
  169691. 1.0, 0.785694958, 0.541196100, 0.275899379
  169692. };
  169693. i = 0;
  169694. for (row = 0; row < DCTSIZE; row++) {
  169695. for (col = 0; col < DCTSIZE; col++) {
  169696. fmtbl[i] = (FLOAT_MULT_TYPE)
  169697. ((double) qtbl->quantval[i] *
  169698. aanscalefactor[row] * aanscalefactor[col]);
  169699. i++;
  169700. }
  169701. }
  169702. }
  169703. break;
  169704. #endif
  169705. default:
  169706. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169707. break;
  169708. }
  169709. }
  169710. }
  169711. /*
  169712. * Initialize IDCT manager.
  169713. */
  169714. GLOBAL(void)
  169715. jinit_inverse_dct (j_decompress_ptr cinfo)
  169716. {
  169717. my_idct_ptr idct;
  169718. int ci;
  169719. jpeg_component_info *compptr;
  169720. idct = (my_idct_ptr)
  169721. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169722. SIZEOF(my_idct_controller));
  169723. cinfo->idct = (struct jpeg_inverse_dct *) idct;
  169724. idct->pub.start_pass = start_pass;
  169725. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169726. ci++, compptr++) {
  169727. /* Allocate and pre-zero a multiplier table for each component */
  169728. compptr->dct_table =
  169729. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169730. SIZEOF(multiplier_table));
  169731. MEMZERO(compptr->dct_table, SIZEOF(multiplier_table));
  169732. /* Mark multiplier table not yet set up for any method */
  169733. idct->cur_method[ci] = -1;
  169734. }
  169735. }
  169736. /*** End of inlined file: jddctmgr.c ***/
  169737. #undef CONST_BITS
  169738. #undef ASSIGN_STATE
  169739. /*** Start of inlined file: jdhuff.c ***/
  169740. #define JPEG_INTERNALS
  169741. /*** Start of inlined file: jdhuff.h ***/
  169742. /* Short forms of external names for systems with brain-damaged linkers. */
  169743. #ifndef __jdhuff_h__
  169744. #define __jdhuff_h__
  169745. #ifdef NEED_SHORT_EXTERNAL_NAMES
  169746. #define jpeg_make_d_derived_tbl jMkDDerived
  169747. #define jpeg_fill_bit_buffer jFilBitBuf
  169748. #define jpeg_huff_decode jHufDecode
  169749. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  169750. /* Derived data constructed for each Huffman table */
  169751. #define HUFF_LOOKAHEAD 8 /* # of bits of lookahead */
  169752. typedef struct {
  169753. /* Basic tables: (element [0] of each array is unused) */
  169754. INT32 maxcode[18]; /* largest code of length k (-1 if none) */
  169755. /* (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) */
  169756. INT32 valoffset[17]; /* huffval[] offset for codes of length k */
  169757. /* valoffset[k] = huffval[] index of 1st symbol of code length k, less
  169758. * the smallest code of length k; so given a code of length k, the
  169759. * corresponding symbol is huffval[code + valoffset[k]]
  169760. */
  169761. /* Link to public Huffman table (needed only in jpeg_huff_decode) */
  169762. JHUFF_TBL *pub;
  169763. /* Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of
  169764. * the input data stream. If the next Huffman code is no more
  169765. * than HUFF_LOOKAHEAD bits long, we can obtain its length and
  169766. * the corresponding symbol directly from these tables.
  169767. */
  169768. int look_nbits[1<<HUFF_LOOKAHEAD]; /* # bits, or 0 if too long */
  169769. UINT8 look_sym[1<<HUFF_LOOKAHEAD]; /* symbol, or unused */
  169770. } d_derived_tbl;
  169771. /* Expand a Huffman table definition into the derived format */
  169772. EXTERN(void) jpeg_make_d_derived_tbl
  169773. JPP((j_decompress_ptr cinfo, boolean isDC, int tblno,
  169774. d_derived_tbl ** pdtbl));
  169775. /*
  169776. * Fetching the next N bits from the input stream is a time-critical operation
  169777. * for the Huffman decoders. We implement it with a combination of inline
  169778. * macros and out-of-line subroutines. Note that N (the number of bits
  169779. * demanded at one time) never exceeds 15 for JPEG use.
  169780. *
  169781. * We read source bytes into get_buffer and dole out bits as needed.
  169782. * If get_buffer already contains enough bits, they are fetched in-line
  169783. * by the macros CHECK_BIT_BUFFER and GET_BITS. When there aren't enough
  169784. * bits, jpeg_fill_bit_buffer is called; it will attempt to fill get_buffer
  169785. * as full as possible (not just to the number of bits needed; this
  169786. * prefetching reduces the overhead cost of calling jpeg_fill_bit_buffer).
  169787. * Note that jpeg_fill_bit_buffer may return FALSE to indicate suspension.
  169788. * On TRUE return, jpeg_fill_bit_buffer guarantees that get_buffer contains
  169789. * at least the requested number of bits --- dummy zeroes are inserted if
  169790. * necessary.
  169791. */
  169792. typedef INT32 bit_buf_type; /* type of bit-extraction buffer */
  169793. #define BIT_BUF_SIZE 32 /* size of buffer in bits */
  169794. /* If long is > 32 bits on your machine, and shifting/masking longs is
  169795. * reasonably fast, making bit_buf_type be long and setting BIT_BUF_SIZE
  169796. * appropriately should be a win. Unfortunately we can't define the size
  169797. * with something like #define BIT_BUF_SIZE (sizeof(bit_buf_type)*8)
  169798. * because not all machines measure sizeof in 8-bit bytes.
  169799. */
  169800. typedef struct { /* Bitreading state saved across MCUs */
  169801. bit_buf_type get_buffer; /* current bit-extraction buffer */
  169802. int bits_left; /* # of unused bits in it */
  169803. } bitread_perm_state;
  169804. typedef struct { /* Bitreading working state within an MCU */
  169805. /* Current data source location */
  169806. /* We need a copy, rather than munging the original, in case of suspension */
  169807. const JOCTET * next_input_byte; /* => next byte to read from source */
  169808. size_t bytes_in_buffer; /* # of bytes remaining in source buffer */
  169809. /* Bit input buffer --- note these values are kept in register variables,
  169810. * not in this struct, inside the inner loops.
  169811. */
  169812. bit_buf_type get_buffer; /* current bit-extraction buffer */
  169813. int bits_left; /* # of unused bits in it */
  169814. /* Pointer needed by jpeg_fill_bit_buffer. */
  169815. j_decompress_ptr cinfo; /* back link to decompress master record */
  169816. } bitread_working_state;
  169817. /* Macros to declare and load/save bitread local variables. */
  169818. #define BITREAD_STATE_VARS \
  169819. register bit_buf_type get_buffer; \
  169820. register int bits_left; \
  169821. bitread_working_state br_state
  169822. #define BITREAD_LOAD_STATE(cinfop,permstate) \
  169823. br_state.cinfo = cinfop; \
  169824. br_state.next_input_byte = cinfop->src->next_input_byte; \
  169825. br_state.bytes_in_buffer = cinfop->src->bytes_in_buffer; \
  169826. get_buffer = permstate.get_buffer; \
  169827. bits_left = permstate.bits_left;
  169828. #define BITREAD_SAVE_STATE(cinfop,permstate) \
  169829. cinfop->src->next_input_byte = br_state.next_input_byte; \
  169830. cinfop->src->bytes_in_buffer = br_state.bytes_in_buffer; \
  169831. permstate.get_buffer = get_buffer; \
  169832. permstate.bits_left = bits_left
  169833. /*
  169834. * These macros provide the in-line portion of bit fetching.
  169835. * Use CHECK_BIT_BUFFER to ensure there are N bits in get_buffer
  169836. * before using GET_BITS, PEEK_BITS, or DROP_BITS.
  169837. * The variables get_buffer and bits_left are assumed to be locals,
  169838. * but the state struct might not be (jpeg_huff_decode needs this).
  169839. * CHECK_BIT_BUFFER(state,n,action);
  169840. * Ensure there are N bits in get_buffer; if suspend, take action.
  169841. * val = GET_BITS(n);
  169842. * Fetch next N bits.
  169843. * val = PEEK_BITS(n);
  169844. * Fetch next N bits without removing them from the buffer.
  169845. * DROP_BITS(n);
  169846. * Discard next N bits.
  169847. * The value N should be a simple variable, not an expression, because it
  169848. * is evaluated multiple times.
  169849. */
  169850. #define CHECK_BIT_BUFFER(state,nbits,action) \
  169851. { if (bits_left < (nbits)) { \
  169852. if (! jpeg_fill_bit_buffer(&(state),get_buffer,bits_left,nbits)) \
  169853. { action; } \
  169854. get_buffer = (state).get_buffer; bits_left = (state).bits_left; } }
  169855. #define GET_BITS(nbits) \
  169856. (((int) (get_buffer >> (bits_left -= (nbits)))) & ((1<<(nbits))-1))
  169857. #define PEEK_BITS(nbits) \
  169858. (((int) (get_buffer >> (bits_left - (nbits)))) & ((1<<(nbits))-1))
  169859. #define DROP_BITS(nbits) \
  169860. (bits_left -= (nbits))
  169861. /* Load up the bit buffer to a depth of at least nbits */
  169862. EXTERN(boolean) jpeg_fill_bit_buffer
  169863. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  169864. register int bits_left, int nbits));
  169865. /*
  169866. * Code for extracting next Huffman-coded symbol from input bit stream.
  169867. * Again, this is time-critical and we make the main paths be macros.
  169868. *
  169869. * We use a lookahead table to process codes of up to HUFF_LOOKAHEAD bits
  169870. * without looping. Usually, more than 95% of the Huffman codes will be 8
  169871. * or fewer bits long. The few overlength codes are handled with a loop,
  169872. * which need not be inline code.
  169873. *
  169874. * Notes about the HUFF_DECODE macro:
  169875. * 1. Near the end of the data segment, we may fail to get enough bits
  169876. * for a lookahead. In that case, we do it the hard way.
  169877. * 2. If the lookahead table contains no entry, the next code must be
  169878. * more than HUFF_LOOKAHEAD bits long.
  169879. * 3. jpeg_huff_decode returns -1 if forced to suspend.
  169880. */
  169881. #define HUFF_DECODE(result,state,htbl,failaction,slowlabel) \
  169882. { register int nb, look; \
  169883. if (bits_left < HUFF_LOOKAHEAD) { \
  169884. if (! jpeg_fill_bit_buffer(&state,get_buffer,bits_left, 0)) {failaction;} \
  169885. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  169886. if (bits_left < HUFF_LOOKAHEAD) { \
  169887. nb = 1; goto slowlabel; \
  169888. } \
  169889. } \
  169890. look = PEEK_BITS(HUFF_LOOKAHEAD); \
  169891. if ((nb = htbl->look_nbits[look]) != 0) { \
  169892. DROP_BITS(nb); \
  169893. result = htbl->look_sym[look]; \
  169894. } else { \
  169895. nb = HUFF_LOOKAHEAD+1; \
  169896. slowlabel: \
  169897. if ((result=jpeg_huff_decode(&state,get_buffer,bits_left,htbl,nb)) < 0) \
  169898. { failaction; } \
  169899. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  169900. } \
  169901. }
  169902. /* Out-of-line case for Huffman code fetching */
  169903. EXTERN(int) jpeg_huff_decode
  169904. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  169905. register int bits_left, d_derived_tbl * htbl, int min_bits));
  169906. #endif
  169907. /*** End of inlined file: jdhuff.h ***/
  169908. /* Declarations shared with jdphuff.c */
  169909. /*
  169910. * Expanded entropy decoder object for Huffman decoding.
  169911. *
  169912. * The savable_state subrecord contains fields that change within an MCU,
  169913. * but must not be updated permanently until we complete the MCU.
  169914. */
  169915. typedef struct {
  169916. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  169917. } savable_state2;
  169918. /* This macro is to work around compilers with missing or broken
  169919. * structure assignment. You'll need to fix this code if you have
  169920. * such a compiler and you change MAX_COMPS_IN_SCAN.
  169921. */
  169922. #ifndef NO_STRUCT_ASSIGN
  169923. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  169924. #else
  169925. #if MAX_COMPS_IN_SCAN == 4
  169926. #define ASSIGN_STATE(dest,src) \
  169927. ((dest).last_dc_val[0] = (src).last_dc_val[0], \
  169928. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  169929. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  169930. (dest).last_dc_val[3] = (src).last_dc_val[3])
  169931. #endif
  169932. #endif
  169933. typedef struct {
  169934. struct jpeg_entropy_decoder pub; /* public fields */
  169935. /* These fields are loaded into local variables at start of each MCU.
  169936. * In case of suspension, we exit WITHOUT updating them.
  169937. */
  169938. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  169939. savable_state2 saved; /* Other state at start of MCU */
  169940. /* These fields are NOT loaded into local working state. */
  169941. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  169942. /* Pointers to derived tables (these workspaces have image lifespan) */
  169943. d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  169944. d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  169945. /* Precalculated info set up by start_pass for use in decode_mcu: */
  169946. /* Pointers to derived tables to be used for each block within an MCU */
  169947. d_derived_tbl * dc_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  169948. d_derived_tbl * ac_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  169949. /* Whether we care about the DC and AC coefficient values for each block */
  169950. boolean dc_needed[D_MAX_BLOCKS_IN_MCU];
  169951. boolean ac_needed[D_MAX_BLOCKS_IN_MCU];
  169952. } huff_entropy_decoder2;
  169953. typedef huff_entropy_decoder2 * huff_entropy_ptr2;
  169954. /*
  169955. * Initialize for a Huffman-compressed scan.
  169956. */
  169957. METHODDEF(void)
  169958. start_pass_huff_decoder (j_decompress_ptr cinfo)
  169959. {
  169960. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  169961. int ci, blkn, dctbl, actbl;
  169962. jpeg_component_info * compptr;
  169963. /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
  169964. * This ought to be an error condition, but we make it a warning because
  169965. * there are some baseline files out there with all zeroes in these bytes.
  169966. */
  169967. if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 ||
  169968. cinfo->Ah != 0 || cinfo->Al != 0)
  169969. WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
  169970. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  169971. compptr = cinfo->cur_comp_info[ci];
  169972. dctbl = compptr->dc_tbl_no;
  169973. actbl = compptr->ac_tbl_no;
  169974. /* Compute derived values for Huffman tables */
  169975. /* We may do this more than once for a table, but it's not expensive */
  169976. jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl,
  169977. & entropy->dc_derived_tbls[dctbl]);
  169978. jpeg_make_d_derived_tbl(cinfo, FALSE, actbl,
  169979. & entropy->ac_derived_tbls[actbl]);
  169980. /* Initialize DC predictions to 0 */
  169981. entropy->saved.last_dc_val[ci] = 0;
  169982. }
  169983. /* Precalculate decoding info for each block in an MCU of this scan */
  169984. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  169985. ci = cinfo->MCU_membership[blkn];
  169986. compptr = cinfo->cur_comp_info[ci];
  169987. /* Precalculate which table to use for each block */
  169988. entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
  169989. entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];
  169990. /* Decide whether we really care about the coefficient values */
  169991. if (compptr->component_needed) {
  169992. entropy->dc_needed[blkn] = TRUE;
  169993. /* we don't need the ACs if producing a 1/8th-size image */
  169994. entropy->ac_needed[blkn] = (compptr->DCT_scaled_size > 1);
  169995. } else {
  169996. entropy->dc_needed[blkn] = entropy->ac_needed[blkn] = FALSE;
  169997. }
  169998. }
  169999. /* Initialize bitread state variables */
  170000. entropy->bitstate.bits_left = 0;
  170001. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  170002. entropy->pub.insufficient_data = FALSE;
  170003. /* Initialize restart counter */
  170004. entropy->restarts_to_go = cinfo->restart_interval;
  170005. }
  170006. /*
  170007. * Compute the derived values for a Huffman table.
  170008. * This routine also performs some validation checks on the table.
  170009. *
  170010. * Note this is also used by jdphuff.c.
  170011. */
  170012. GLOBAL(void)
  170013. jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, boolean isDC, int tblno,
  170014. d_derived_tbl ** pdtbl)
  170015. {
  170016. JHUFF_TBL *htbl;
  170017. d_derived_tbl *dtbl;
  170018. int p, i, l, si, numsymbols;
  170019. int lookbits, ctr;
  170020. char huffsize[257];
  170021. unsigned int huffcode[257];
  170022. unsigned int code;
  170023. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  170024. * paralleling the order of the symbols themselves in htbl->huffval[].
  170025. */
  170026. /* Find the input Huffman table */
  170027. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  170028. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  170029. htbl =
  170030. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  170031. if (htbl == NULL)
  170032. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  170033. /* Allocate a workspace if we haven't already done so. */
  170034. if (*pdtbl == NULL)
  170035. *pdtbl = (d_derived_tbl *)
  170036. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170037. SIZEOF(d_derived_tbl));
  170038. dtbl = *pdtbl;
  170039. dtbl->pub = htbl; /* fill in back link */
  170040. /* Figure C.1: make table of Huffman code length for each symbol */
  170041. p = 0;
  170042. for (l = 1; l <= 16; l++) {
  170043. i = (int) htbl->bits[l];
  170044. if (i < 0 || p + i > 256) /* protect against table overrun */
  170045. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  170046. while (i--)
  170047. huffsize[p++] = (char) l;
  170048. }
  170049. huffsize[p] = 0;
  170050. numsymbols = p;
  170051. /* Figure C.2: generate the codes themselves */
  170052. /* We also validate that the counts represent a legal Huffman code tree. */
  170053. code = 0;
  170054. si = huffsize[0];
  170055. p = 0;
  170056. while (huffsize[p]) {
  170057. while (((int) huffsize[p]) == si) {
  170058. huffcode[p++] = code;
  170059. code++;
  170060. }
  170061. /* code is now 1 more than the last code used for codelength si; but
  170062. * it must still fit in si bits, since no code is allowed to be all ones.
  170063. */
  170064. if (((INT32) code) >= (((INT32) 1) << si))
  170065. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  170066. code <<= 1;
  170067. si++;
  170068. }
  170069. /* Figure F.15: generate decoding tables for bit-sequential decoding */
  170070. p = 0;
  170071. for (l = 1; l <= 16; l++) {
  170072. if (htbl->bits[l]) {
  170073. /* valoffset[l] = huffval[] index of 1st symbol of code length l,
  170074. * minus the minimum code of length l
  170075. */
  170076. dtbl->valoffset[l] = (INT32) p - (INT32) huffcode[p];
  170077. p += htbl->bits[l];
  170078. dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */
  170079. } else {
  170080. dtbl->maxcode[l] = -1; /* -1 if no codes of this length */
  170081. }
  170082. }
  170083. dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */
  170084. /* Compute lookahead tables to speed up decoding.
  170085. * First we set all the table entries to 0, indicating "too long";
  170086. * then we iterate through the Huffman codes that are short enough and
  170087. * fill in all the entries that correspond to bit sequences starting
  170088. * with that code.
  170089. */
  170090. MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));
  170091. p = 0;
  170092. for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
  170093. for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {
  170094. /* l = current code's length, p = its index in huffcode[] & huffval[]. */
  170095. /* Generate left-justified code followed by all possible bit sequences */
  170096. lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
  170097. for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
  170098. dtbl->look_nbits[lookbits] = l;
  170099. dtbl->look_sym[lookbits] = htbl->huffval[p];
  170100. lookbits++;
  170101. }
  170102. }
  170103. }
  170104. /* Validate symbols as being reasonable.
  170105. * For AC tables, we make no check, but accept all byte values 0..255.
  170106. * For DC tables, we require the symbols to be in range 0..15.
  170107. * (Tighter bounds could be applied depending on the data depth and mode,
  170108. * but this is sufficient to ensure safe decoding.)
  170109. */
  170110. if (isDC) {
  170111. for (i = 0; i < numsymbols; i++) {
  170112. int sym = htbl->huffval[i];
  170113. if (sym < 0 || sym > 15)
  170114. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  170115. }
  170116. }
  170117. }
  170118. /*
  170119. * Out-of-line code for bit fetching (shared with jdphuff.c).
  170120. * See jdhuff.h for info about usage.
  170121. * Note: current values of get_buffer and bits_left are passed as parameters,
  170122. * but are returned in the corresponding fields of the state struct.
  170123. *
  170124. * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
  170125. * of get_buffer to be used. (On machines with wider words, an even larger
  170126. * buffer could be used.) However, on some machines 32-bit shifts are
  170127. * quite slow and take time proportional to the number of places shifted.
  170128. * (This is true with most PC compilers, for instance.) In this case it may
  170129. * be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the
  170130. * average shift distance at the cost of more calls to jpeg_fill_bit_buffer.
  170131. */
  170132. #ifdef SLOW_SHIFT_32
  170133. #define MIN_GET_BITS 15 /* minimum allowable value */
  170134. #else
  170135. #define MIN_GET_BITS (BIT_BUF_SIZE-7)
  170136. #endif
  170137. GLOBAL(boolean)
  170138. jpeg_fill_bit_buffer (bitread_working_state * state,
  170139. register bit_buf_type get_buffer, register int bits_left,
  170140. int nbits)
  170141. /* Load up the bit buffer to a depth of at least nbits */
  170142. {
  170143. /* Copy heavily used state fields into locals (hopefully registers) */
  170144. register const JOCTET * next_input_byte = state->next_input_byte;
  170145. register size_t bytes_in_buffer = state->bytes_in_buffer;
  170146. j_decompress_ptr cinfo = state->cinfo;
  170147. /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
  170148. /* (It is assumed that no request will be for more than that many bits.) */
  170149. /* We fail to do so only if we hit a marker or are forced to suspend. */
  170150. if (cinfo->unread_marker == 0) { /* cannot advance past a marker */
  170151. while (bits_left < MIN_GET_BITS) {
  170152. register int c;
  170153. /* Attempt to read a byte */
  170154. if (bytes_in_buffer == 0) {
  170155. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  170156. return FALSE;
  170157. next_input_byte = cinfo->src->next_input_byte;
  170158. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  170159. }
  170160. bytes_in_buffer--;
  170161. c = GETJOCTET(*next_input_byte++);
  170162. /* If it's 0xFF, check and discard stuffed zero byte */
  170163. if (c == 0xFF) {
  170164. /* Loop here to discard any padding FF's on terminating marker,
  170165. * so that we can save a valid unread_marker value. NOTE: we will
  170166. * accept multiple FF's followed by a 0 as meaning a single FF data
  170167. * byte. This data pattern is not valid according to the standard.
  170168. */
  170169. do {
  170170. if (bytes_in_buffer == 0) {
  170171. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  170172. return FALSE;
  170173. next_input_byte = cinfo->src->next_input_byte;
  170174. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  170175. }
  170176. bytes_in_buffer--;
  170177. c = GETJOCTET(*next_input_byte++);
  170178. } while (c == 0xFF);
  170179. if (c == 0) {
  170180. /* Found FF/00, which represents an FF data byte */
  170181. c = 0xFF;
  170182. } else {
  170183. /* Oops, it's actually a marker indicating end of compressed data.
  170184. * Save the marker code for later use.
  170185. * Fine point: it might appear that we should save the marker into
  170186. * bitread working state, not straight into permanent state. But
  170187. * once we have hit a marker, we cannot need to suspend within the
  170188. * current MCU, because we will read no more bytes from the data
  170189. * source. So it is OK to update permanent state right away.
  170190. */
  170191. cinfo->unread_marker = c;
  170192. /* See if we need to insert some fake zero bits. */
  170193. goto no_more_bytes;
  170194. }
  170195. }
  170196. /* OK, load c into get_buffer */
  170197. get_buffer = (get_buffer << 8) | c;
  170198. bits_left += 8;
  170199. } /* end while */
  170200. } else {
  170201. no_more_bytes:
  170202. /* We get here if we've read the marker that terminates the compressed
  170203. * data segment. There should be enough bits in the buffer register
  170204. * to satisfy the request; if so, no problem.
  170205. */
  170206. if (nbits > bits_left) {
  170207. /* Uh-oh. Report corrupted data to user and stuff zeroes into
  170208. * the data stream, so that we can produce some kind of image.
  170209. * We use a nonvolatile flag to ensure that only one warning message
  170210. * appears per data segment.
  170211. */
  170212. if (! cinfo->entropy->insufficient_data) {
  170213. WARNMS(cinfo, JWRN_HIT_MARKER);
  170214. cinfo->entropy->insufficient_data = TRUE;
  170215. }
  170216. /* Fill the buffer with zero bits */
  170217. get_buffer <<= MIN_GET_BITS - bits_left;
  170218. bits_left = MIN_GET_BITS;
  170219. }
  170220. }
  170221. /* Unload the local registers */
  170222. state->next_input_byte = next_input_byte;
  170223. state->bytes_in_buffer = bytes_in_buffer;
  170224. state->get_buffer = get_buffer;
  170225. state->bits_left = bits_left;
  170226. return TRUE;
  170227. }
  170228. /*
  170229. * Out-of-line code for Huffman code decoding.
  170230. * See jdhuff.h for info about usage.
  170231. */
  170232. GLOBAL(int)
  170233. jpeg_huff_decode (bitread_working_state * state,
  170234. register bit_buf_type get_buffer, register int bits_left,
  170235. d_derived_tbl * htbl, int min_bits)
  170236. {
  170237. register int l = min_bits;
  170238. register INT32 code;
  170239. /* HUFF_DECODE has determined that the code is at least min_bits */
  170240. /* bits long, so fetch that many bits in one swoop. */
  170241. CHECK_BIT_BUFFER(*state, l, return -1);
  170242. code = GET_BITS(l);
  170243. /* Collect the rest of the Huffman code one bit at a time. */
  170244. /* This is per Figure F.16 in the JPEG spec. */
  170245. while (code > htbl->maxcode[l]) {
  170246. code <<= 1;
  170247. CHECK_BIT_BUFFER(*state, 1, return -1);
  170248. code |= GET_BITS(1);
  170249. l++;
  170250. }
  170251. /* Unload the local registers */
  170252. state->get_buffer = get_buffer;
  170253. state->bits_left = bits_left;
  170254. /* With garbage input we may reach the sentinel value l = 17. */
  170255. if (l > 16) {
  170256. WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
  170257. return 0; /* fake a zero as the safest result */
  170258. }
  170259. return htbl->pub->huffval[ (int) (code + htbl->valoffset[l]) ];
  170260. }
  170261. /*
  170262. * Check for a restart marker & resynchronize decoder.
  170263. * Returns FALSE if must suspend.
  170264. */
  170265. LOCAL(boolean)
  170266. process_restart (j_decompress_ptr cinfo)
  170267. {
  170268. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  170269. int ci;
  170270. /* Throw away any unused bits remaining in bit buffer; */
  170271. /* include any full bytes in next_marker's count of discarded bytes */
  170272. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  170273. entropy->bitstate.bits_left = 0;
  170274. /* Advance past the RSTn marker */
  170275. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  170276. return FALSE;
  170277. /* Re-initialize DC predictions to 0 */
  170278. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  170279. entropy->saved.last_dc_val[ci] = 0;
  170280. /* Reset restart counter */
  170281. entropy->restarts_to_go = cinfo->restart_interval;
  170282. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  170283. * against a marker. In that case we will end up treating the next data
  170284. * segment as empty, and we can avoid producing bogus output pixels by
  170285. * leaving the flag set.
  170286. */
  170287. if (cinfo->unread_marker == 0)
  170288. entropy->pub.insufficient_data = FALSE;
  170289. return TRUE;
  170290. }
  170291. /*
  170292. * Decode and return one MCU's worth of Huffman-compressed coefficients.
  170293. * The coefficients are reordered from zigzag order into natural array order,
  170294. * but are not dequantized.
  170295. *
  170296. * The i'th block of the MCU is stored into the block pointed to by
  170297. * MCU_data[i]. WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.
  170298. * (Wholesale zeroing is usually a little faster than retail...)
  170299. *
  170300. * Returns FALSE if data source requested suspension. In that case no
  170301. * changes have been made to permanent state. (Exception: some output
  170302. * coefficients may already have been assigned. This is harmless for
  170303. * this module, since we'll just re-assign them on the next call.)
  170304. */
  170305. METHODDEF(boolean)
  170306. decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  170307. {
  170308. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  170309. int blkn;
  170310. BITREAD_STATE_VARS;
  170311. savable_state2 state;
  170312. /* Process restart marker if needed; may have to suspend */
  170313. if (cinfo->restart_interval) {
  170314. if (entropy->restarts_to_go == 0)
  170315. if (! process_restart(cinfo))
  170316. return FALSE;
  170317. }
  170318. /* If we've run out of data, just leave the MCU set to zeroes.
  170319. * This way, we return uniform gray for the remainder of the segment.
  170320. */
  170321. if (! entropy->pub.insufficient_data) {
  170322. /* Load up working state */
  170323. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  170324. ASSIGN_STATE(state, entropy->saved);
  170325. /* Outer loop handles each block in the MCU */
  170326. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  170327. JBLOCKROW block = MCU_data[blkn];
  170328. d_derived_tbl * dctbl = entropy->dc_cur_tbls[blkn];
  170329. d_derived_tbl * actbl = entropy->ac_cur_tbls[blkn];
  170330. register int s, k, r;
  170331. /* Decode a single block's worth of coefficients */
  170332. /* Section F.2.2.1: decode the DC coefficient difference */
  170333. HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);
  170334. if (s) {
  170335. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170336. r = GET_BITS(s);
  170337. s = HUFF_EXTEND(r, s);
  170338. }
  170339. if (entropy->dc_needed[blkn]) {
  170340. /* Convert DC difference to actual value, update last_dc_val */
  170341. int ci = cinfo->MCU_membership[blkn];
  170342. s += state.last_dc_val[ci];
  170343. state.last_dc_val[ci] = s;
  170344. /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */
  170345. (*block)[0] = (JCOEF) s;
  170346. }
  170347. if (entropy->ac_needed[blkn]) {
  170348. /* Section F.2.2.2: decode the AC coefficients */
  170349. /* Since zeroes are skipped, output area must be cleared beforehand */
  170350. for (k = 1; k < DCTSIZE2; k++) {
  170351. HUFF_DECODE(s, br_state, actbl, return FALSE, label2);
  170352. r = s >> 4;
  170353. s &= 15;
  170354. if (s) {
  170355. k += r;
  170356. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170357. r = GET_BITS(s);
  170358. s = HUFF_EXTEND(r, s);
  170359. /* Output coefficient in natural (dezigzagged) order.
  170360. * Note: the extra entries in jpeg_natural_order[] will save us
  170361. * if k >= DCTSIZE2, which could happen if the data is corrupted.
  170362. */
  170363. (*block)[jpeg_natural_order[k]] = (JCOEF) s;
  170364. } else {
  170365. if (r != 15)
  170366. break;
  170367. k += 15;
  170368. }
  170369. }
  170370. } else {
  170371. /* Section F.2.2.2: decode the AC coefficients */
  170372. /* In this path we just discard the values */
  170373. for (k = 1; k < DCTSIZE2; k++) {
  170374. HUFF_DECODE(s, br_state, actbl, return FALSE, label3);
  170375. r = s >> 4;
  170376. s &= 15;
  170377. if (s) {
  170378. k += r;
  170379. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170380. DROP_BITS(s);
  170381. } else {
  170382. if (r != 15)
  170383. break;
  170384. k += 15;
  170385. }
  170386. }
  170387. }
  170388. }
  170389. /* Completed MCU, so update state */
  170390. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  170391. ASSIGN_STATE(entropy->saved, state);
  170392. }
  170393. /* Account for restart interval (no-op if not using restarts) */
  170394. entropy->restarts_to_go--;
  170395. return TRUE;
  170396. }
  170397. /*
  170398. * Module initialization routine for Huffman entropy decoding.
  170399. */
  170400. GLOBAL(void)
  170401. jinit_huff_decoder (j_decompress_ptr cinfo)
  170402. {
  170403. huff_entropy_ptr2 entropy;
  170404. int i;
  170405. entropy = (huff_entropy_ptr2)
  170406. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170407. SIZEOF(huff_entropy_decoder2));
  170408. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  170409. entropy->pub.start_pass = start_pass_huff_decoder;
  170410. entropy->pub.decode_mcu = decode_mcu;
  170411. /* Mark tables unallocated */
  170412. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  170413. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  170414. }
  170415. }
  170416. /*** End of inlined file: jdhuff.c ***/
  170417. /*** Start of inlined file: jdinput.c ***/
  170418. #define JPEG_INTERNALS
  170419. /* Private state */
  170420. typedef struct {
  170421. struct jpeg_input_controller pub; /* public fields */
  170422. boolean inheaders; /* TRUE until first SOS is reached */
  170423. } my_input_controller;
  170424. typedef my_input_controller * my_inputctl_ptr;
  170425. /* Forward declarations */
  170426. METHODDEF(int) consume_markers JPP((j_decompress_ptr cinfo));
  170427. /*
  170428. * Routines to calculate various quantities related to the size of the image.
  170429. */
  170430. LOCAL(void)
  170431. initial_setup2 (j_decompress_ptr cinfo)
  170432. /* Called once, when first SOS marker is reached */
  170433. {
  170434. int ci;
  170435. jpeg_component_info *compptr;
  170436. /* Make sure image isn't bigger than I can handle */
  170437. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  170438. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  170439. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  170440. /* For now, precision must match compiled-in value... */
  170441. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  170442. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  170443. /* Check that number of components won't exceed internal array sizes */
  170444. if (cinfo->num_components > MAX_COMPONENTS)
  170445. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  170446. MAX_COMPONENTS);
  170447. /* Compute maximum sampling factors; check factor validity */
  170448. cinfo->max_h_samp_factor = 1;
  170449. cinfo->max_v_samp_factor = 1;
  170450. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170451. ci++, compptr++) {
  170452. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  170453. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  170454. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  170455. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  170456. compptr->h_samp_factor);
  170457. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  170458. compptr->v_samp_factor);
  170459. }
  170460. /* We initialize DCT_scaled_size and min_DCT_scaled_size to DCTSIZE.
  170461. * In the full decompressor, this will be overridden by jdmaster.c;
  170462. * but in the transcoder, jdmaster.c is not used, so we must do it here.
  170463. */
  170464. cinfo->min_DCT_scaled_size = DCTSIZE;
  170465. /* Compute dimensions of components */
  170466. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170467. ci++, compptr++) {
  170468. compptr->DCT_scaled_size = DCTSIZE;
  170469. /* Size in DCT blocks */
  170470. compptr->width_in_blocks = (JDIMENSION)
  170471. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  170472. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  170473. compptr->height_in_blocks = (JDIMENSION)
  170474. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  170475. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  170476. /* downsampled_width and downsampled_height will also be overridden by
  170477. * jdmaster.c if we are doing full decompression. The transcoder library
  170478. * doesn't use these values, but the calling application might.
  170479. */
  170480. /* Size in samples */
  170481. compptr->downsampled_width = (JDIMENSION)
  170482. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  170483. (long) cinfo->max_h_samp_factor);
  170484. compptr->downsampled_height = (JDIMENSION)
  170485. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  170486. (long) cinfo->max_v_samp_factor);
  170487. /* Mark component needed, until color conversion says otherwise */
  170488. compptr->component_needed = TRUE;
  170489. /* Mark no quantization table yet saved for component */
  170490. compptr->quant_table = NULL;
  170491. }
  170492. /* Compute number of fully interleaved MCU rows. */
  170493. cinfo->total_iMCU_rows = (JDIMENSION)
  170494. jdiv_round_up((long) cinfo->image_height,
  170495. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  170496. /* Decide whether file contains multiple scans */
  170497. if (cinfo->comps_in_scan < cinfo->num_components || cinfo->progressive_mode)
  170498. cinfo->inputctl->has_multiple_scans = TRUE;
  170499. else
  170500. cinfo->inputctl->has_multiple_scans = FALSE;
  170501. }
  170502. LOCAL(void)
  170503. per_scan_setup2 (j_decompress_ptr cinfo)
  170504. /* Do computations that are needed before processing a JPEG scan */
  170505. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] were set from SOS marker */
  170506. {
  170507. int ci, mcublks, tmp;
  170508. jpeg_component_info *compptr;
  170509. if (cinfo->comps_in_scan == 1) {
  170510. /* Noninterleaved (single-component) scan */
  170511. compptr = cinfo->cur_comp_info[0];
  170512. /* Overall image size in MCUs */
  170513. cinfo->MCUs_per_row = compptr->width_in_blocks;
  170514. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  170515. /* For noninterleaved scan, always one block per MCU */
  170516. compptr->MCU_width = 1;
  170517. compptr->MCU_height = 1;
  170518. compptr->MCU_blocks = 1;
  170519. compptr->MCU_sample_width = compptr->DCT_scaled_size;
  170520. compptr->last_col_width = 1;
  170521. /* For noninterleaved scans, it is convenient to define last_row_height
  170522. * as the number of block rows present in the last iMCU row.
  170523. */
  170524. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  170525. if (tmp == 0) tmp = compptr->v_samp_factor;
  170526. compptr->last_row_height = tmp;
  170527. /* Prepare array describing MCU composition */
  170528. cinfo->blocks_in_MCU = 1;
  170529. cinfo->MCU_membership[0] = 0;
  170530. } else {
  170531. /* Interleaved (multi-component) scan */
  170532. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  170533. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  170534. MAX_COMPS_IN_SCAN);
  170535. /* Overall image size in MCUs */
  170536. cinfo->MCUs_per_row = (JDIMENSION)
  170537. jdiv_round_up((long) cinfo->image_width,
  170538. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  170539. cinfo->MCU_rows_in_scan = (JDIMENSION)
  170540. jdiv_round_up((long) cinfo->image_height,
  170541. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  170542. cinfo->blocks_in_MCU = 0;
  170543. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  170544. compptr = cinfo->cur_comp_info[ci];
  170545. /* Sampling factors give # of blocks of component in each MCU */
  170546. compptr->MCU_width = compptr->h_samp_factor;
  170547. compptr->MCU_height = compptr->v_samp_factor;
  170548. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  170549. compptr->MCU_sample_width = compptr->MCU_width * compptr->DCT_scaled_size;
  170550. /* Figure number of non-dummy blocks in last MCU column & row */
  170551. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  170552. if (tmp == 0) tmp = compptr->MCU_width;
  170553. compptr->last_col_width = tmp;
  170554. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  170555. if (tmp == 0) tmp = compptr->MCU_height;
  170556. compptr->last_row_height = tmp;
  170557. /* Prepare array describing MCU composition */
  170558. mcublks = compptr->MCU_blocks;
  170559. if (cinfo->blocks_in_MCU + mcublks > D_MAX_BLOCKS_IN_MCU)
  170560. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  170561. while (mcublks-- > 0) {
  170562. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  170563. }
  170564. }
  170565. }
  170566. }
  170567. /*
  170568. * Save away a copy of the Q-table referenced by each component present
  170569. * in the current scan, unless already saved during a prior scan.
  170570. *
  170571. * In a multiple-scan JPEG file, the encoder could assign different components
  170572. * the same Q-table slot number, but change table definitions between scans
  170573. * so that each component uses a different Q-table. (The IJG encoder is not
  170574. * currently capable of doing this, but other encoders might.) Since we want
  170575. * to be able to dequantize all the components at the end of the file, this
  170576. * means that we have to save away the table actually used for each component.
  170577. * We do this by copying the table at the start of the first scan containing
  170578. * the component.
  170579. * The JPEG spec prohibits the encoder from changing the contents of a Q-table
  170580. * slot between scans of a component using that slot. If the encoder does so
  170581. * anyway, this decoder will simply use the Q-table values that were current
  170582. * at the start of the first scan for the component.
  170583. *
  170584. * The decompressor output side looks only at the saved quant tables,
  170585. * not at the current Q-table slots.
  170586. */
  170587. LOCAL(void)
  170588. latch_quant_tables (j_decompress_ptr cinfo)
  170589. {
  170590. int ci, qtblno;
  170591. jpeg_component_info *compptr;
  170592. JQUANT_TBL * qtbl;
  170593. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  170594. compptr = cinfo->cur_comp_info[ci];
  170595. /* No work if we already saved Q-table for this component */
  170596. if (compptr->quant_table != NULL)
  170597. continue;
  170598. /* Make sure specified quantization table is present */
  170599. qtblno = compptr->quant_tbl_no;
  170600. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  170601. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  170602. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  170603. /* OK, save away the quantization table */
  170604. qtbl = (JQUANT_TBL *)
  170605. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170606. SIZEOF(JQUANT_TBL));
  170607. MEMCOPY(qtbl, cinfo->quant_tbl_ptrs[qtblno], SIZEOF(JQUANT_TBL));
  170608. compptr->quant_table = qtbl;
  170609. }
  170610. }
  170611. /*
  170612. * Initialize the input modules to read a scan of compressed data.
  170613. * The first call to this is done by jdmaster.c after initializing
  170614. * the entire decompressor (during jpeg_start_decompress).
  170615. * Subsequent calls come from consume_markers, below.
  170616. */
  170617. METHODDEF(void)
  170618. start_input_pass2 (j_decompress_ptr cinfo)
  170619. {
  170620. per_scan_setup2(cinfo);
  170621. latch_quant_tables(cinfo);
  170622. (*cinfo->entropy->start_pass) (cinfo);
  170623. (*cinfo->coef->start_input_pass) (cinfo);
  170624. cinfo->inputctl->consume_input = cinfo->coef->consume_data;
  170625. }
  170626. /*
  170627. * Finish up after inputting a compressed-data scan.
  170628. * This is called by the coefficient controller after it's read all
  170629. * the expected data of the scan.
  170630. */
  170631. METHODDEF(void)
  170632. finish_input_pass (j_decompress_ptr cinfo)
  170633. {
  170634. cinfo->inputctl->consume_input = consume_markers;
  170635. }
  170636. /*
  170637. * Read JPEG markers before, between, or after compressed-data scans.
  170638. * Change state as necessary when a new scan is reached.
  170639. * Return value is JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  170640. *
  170641. * The consume_input method pointer points either here or to the
  170642. * coefficient controller's consume_data routine, depending on whether
  170643. * we are reading a compressed data segment or inter-segment markers.
  170644. */
  170645. METHODDEF(int)
  170646. consume_markers (j_decompress_ptr cinfo)
  170647. {
  170648. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  170649. int val;
  170650. if (inputctl->pub.eoi_reached) /* After hitting EOI, read no further */
  170651. return JPEG_REACHED_EOI;
  170652. val = (*cinfo->marker->read_markers) (cinfo);
  170653. switch (val) {
  170654. case JPEG_REACHED_SOS: /* Found SOS */
  170655. if (inputctl->inheaders) { /* 1st SOS */
  170656. initial_setup2(cinfo);
  170657. inputctl->inheaders = FALSE;
  170658. /* Note: start_input_pass must be called by jdmaster.c
  170659. * before any more input can be consumed. jdapimin.c is
  170660. * responsible for enforcing this sequencing.
  170661. */
  170662. } else { /* 2nd or later SOS marker */
  170663. if (! inputctl->pub.has_multiple_scans)
  170664. ERREXIT(cinfo, JERR_EOI_EXPECTED); /* Oops, I wasn't expecting this! */
  170665. start_input_pass2(cinfo);
  170666. }
  170667. break;
  170668. case JPEG_REACHED_EOI: /* Found EOI */
  170669. inputctl->pub.eoi_reached = TRUE;
  170670. if (inputctl->inheaders) { /* Tables-only datastream, apparently */
  170671. if (cinfo->marker->saw_SOF)
  170672. ERREXIT(cinfo, JERR_SOF_NO_SOS);
  170673. } else {
  170674. /* Prevent infinite loop in coef ctlr's decompress_data routine
  170675. * if user set output_scan_number larger than number of scans.
  170676. */
  170677. if (cinfo->output_scan_number > cinfo->input_scan_number)
  170678. cinfo->output_scan_number = cinfo->input_scan_number;
  170679. }
  170680. break;
  170681. case JPEG_SUSPENDED:
  170682. break;
  170683. }
  170684. return val;
  170685. }
  170686. /*
  170687. * Reset state to begin a fresh datastream.
  170688. */
  170689. METHODDEF(void)
  170690. reset_input_controller (j_decompress_ptr cinfo)
  170691. {
  170692. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  170693. inputctl->pub.consume_input = consume_markers;
  170694. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  170695. inputctl->pub.eoi_reached = FALSE;
  170696. inputctl->inheaders = TRUE;
  170697. /* Reset other modules */
  170698. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  170699. (*cinfo->marker->reset_marker_reader) (cinfo);
  170700. /* Reset progression state -- would be cleaner if entropy decoder did this */
  170701. cinfo->coef_bits = NULL;
  170702. }
  170703. /*
  170704. * Initialize the input controller module.
  170705. * This is called only once, when the decompression object is created.
  170706. */
  170707. GLOBAL(void)
  170708. jinit_input_controller (j_decompress_ptr cinfo)
  170709. {
  170710. my_inputctl_ptr inputctl;
  170711. /* Create subobject in permanent pool */
  170712. inputctl = (my_inputctl_ptr)
  170713. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  170714. SIZEOF(my_input_controller));
  170715. cinfo->inputctl = (struct jpeg_input_controller *) inputctl;
  170716. /* Initialize method pointers */
  170717. inputctl->pub.consume_input = consume_markers;
  170718. inputctl->pub.reset_input_controller = reset_input_controller;
  170719. inputctl->pub.start_input_pass = start_input_pass2;
  170720. inputctl->pub.finish_input_pass = finish_input_pass;
  170721. /* Initialize state: can't use reset_input_controller since we don't
  170722. * want to try to reset other modules yet.
  170723. */
  170724. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  170725. inputctl->pub.eoi_reached = FALSE;
  170726. inputctl->inheaders = TRUE;
  170727. }
  170728. /*** End of inlined file: jdinput.c ***/
  170729. /*** Start of inlined file: jdmainct.c ***/
  170730. #define JPEG_INTERNALS
  170731. /*
  170732. * In the current system design, the main buffer need never be a full-image
  170733. * buffer; any full-height buffers will be found inside the coefficient or
  170734. * postprocessing controllers. Nonetheless, the main controller is not
  170735. * trivial. Its responsibility is to provide context rows for upsampling/
  170736. * rescaling, and doing this in an efficient fashion is a bit tricky.
  170737. *
  170738. * Postprocessor input data is counted in "row groups". A row group
  170739. * is defined to be (v_samp_factor * DCT_scaled_size / min_DCT_scaled_size)
  170740. * sample rows of each component. (We require DCT_scaled_size values to be
  170741. * chosen such that these numbers are integers. In practice DCT_scaled_size
  170742. * values will likely be powers of two, so we actually have the stronger
  170743. * condition that DCT_scaled_size / min_DCT_scaled_size is an integer.)
  170744. * Upsampling will typically produce max_v_samp_factor pixel rows from each
  170745. * row group (times any additional scale factor that the upsampler is
  170746. * applying).
  170747. *
  170748. * The coefficient controller will deliver data to us one iMCU row at a time;
  170749. * each iMCU row contains v_samp_factor * DCT_scaled_size sample rows, or
  170750. * exactly min_DCT_scaled_size row groups. (This amount of data corresponds
  170751. * to one row of MCUs when the image is fully interleaved.) Note that the
  170752. * number of sample rows varies across components, but the number of row
  170753. * groups does not. Some garbage sample rows may be included in the last iMCU
  170754. * row at the bottom of the image.
  170755. *
  170756. * Depending on the vertical scaling algorithm used, the upsampler may need
  170757. * access to the sample row(s) above and below its current input row group.
  170758. * The upsampler is required to set need_context_rows TRUE at global selection
  170759. * time if so. When need_context_rows is FALSE, this controller can simply
  170760. * obtain one iMCU row at a time from the coefficient controller and dole it
  170761. * out as row groups to the postprocessor.
  170762. *
  170763. * When need_context_rows is TRUE, this controller guarantees that the buffer
  170764. * passed to postprocessing contains at least one row group's worth of samples
  170765. * above and below the row group(s) being processed. Note that the context
  170766. * rows "above" the first passed row group appear at negative row offsets in
  170767. * the passed buffer. At the top and bottom of the image, the required
  170768. * context rows are manufactured by duplicating the first or last real sample
  170769. * row; this avoids having special cases in the upsampling inner loops.
  170770. *
  170771. * The amount of context is fixed at one row group just because that's a
  170772. * convenient number for this controller to work with. The existing
  170773. * upsamplers really only need one sample row of context. An upsampler
  170774. * supporting arbitrary output rescaling might wish for more than one row
  170775. * group of context when shrinking the image; tough, we don't handle that.
  170776. * (This is justified by the assumption that downsizing will be handled mostly
  170777. * by adjusting the DCT_scaled_size values, so that the actual scale factor at
  170778. * the upsample step needn't be much less than one.)
  170779. *
  170780. * To provide the desired context, we have to retain the last two row groups
  170781. * of one iMCU row while reading in the next iMCU row. (The last row group
  170782. * can't be processed until we have another row group for its below-context,
  170783. * and so we have to save the next-to-last group too for its above-context.)
  170784. * We could do this most simply by copying data around in our buffer, but
  170785. * that'd be very slow. We can avoid copying any data by creating a rather
  170786. * strange pointer structure. Here's how it works. We allocate a workspace
  170787. * consisting of M+2 row groups (where M = min_DCT_scaled_size is the number
  170788. * of row groups per iMCU row). We create two sets of redundant pointers to
  170789. * the workspace. Labeling the physical row groups 0 to M+1, the synthesized
  170790. * pointer lists look like this:
  170791. * M+1 M-1
  170792. * master pointer --> 0 master pointer --> 0
  170793. * 1 1
  170794. * ... ...
  170795. * M-3 M-3
  170796. * M-2 M
  170797. * M-1 M+1
  170798. * M M-2
  170799. * M+1 M-1
  170800. * 0 0
  170801. * We read alternate iMCU rows using each master pointer; thus the last two
  170802. * row groups of the previous iMCU row remain un-overwritten in the workspace.
  170803. * The pointer lists are set up so that the required context rows appear to
  170804. * be adjacent to the proper places when we pass the pointer lists to the
  170805. * upsampler.
  170806. *
  170807. * The above pictures describe the normal state of the pointer lists.
  170808. * At top and bottom of the image, we diddle the pointer lists to duplicate
  170809. * the first or last sample row as necessary (this is cheaper than copying
  170810. * sample rows around).
  170811. *
  170812. * This scheme breaks down if M < 2, ie, min_DCT_scaled_size is 1. In that
  170813. * situation each iMCU row provides only one row group so the buffering logic
  170814. * must be different (eg, we must read two iMCU rows before we can emit the
  170815. * first row group). For now, we simply do not support providing context
  170816. * rows when min_DCT_scaled_size is 1. That combination seems unlikely to
  170817. * be worth providing --- if someone wants a 1/8th-size preview, they probably
  170818. * want it quick and dirty, so a context-free upsampler is sufficient.
  170819. */
  170820. /* Private buffer controller object */
  170821. typedef struct {
  170822. struct jpeg_d_main_controller pub; /* public fields */
  170823. /* Pointer to allocated workspace (M or M+2 row groups). */
  170824. JSAMPARRAY buffer[MAX_COMPONENTS];
  170825. boolean buffer_full; /* Have we gotten an iMCU row from decoder? */
  170826. JDIMENSION rowgroup_ctr; /* counts row groups output to postprocessor */
  170827. /* Remaining fields are only used in the context case. */
  170828. /* These are the master pointers to the funny-order pointer lists. */
  170829. JSAMPIMAGE xbuffer[2]; /* pointers to weird pointer lists */
  170830. int whichptr; /* indicates which pointer set is now in use */
  170831. int context_state; /* process_data state machine status */
  170832. JDIMENSION rowgroups_avail; /* row groups available to postprocessor */
  170833. JDIMENSION iMCU_row_ctr; /* counts iMCU rows to detect image top/bot */
  170834. } my_main_controller4;
  170835. typedef my_main_controller4 * my_main_ptr4;
  170836. /* context_state values: */
  170837. #define CTX_PREPARE_FOR_IMCU 0 /* need to prepare for MCU row */
  170838. #define CTX_PROCESS_IMCU 1 /* feeding iMCU to postprocessor */
  170839. #define CTX_POSTPONED_ROW 2 /* feeding postponed row group */
  170840. /* Forward declarations */
  170841. METHODDEF(void) process_data_simple_main2
  170842. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170843. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170844. METHODDEF(void) process_data_context_main
  170845. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170846. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170847. #ifdef QUANT_2PASS_SUPPORTED
  170848. METHODDEF(void) process_data_crank_post
  170849. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170850. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170851. #endif
  170852. LOCAL(void)
  170853. alloc_funny_pointers (j_decompress_ptr cinfo)
  170854. /* Allocate space for the funny pointer lists.
  170855. * This is done only once, not once per pass.
  170856. */
  170857. {
  170858. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170859. int ci, rgroup;
  170860. int M = cinfo->min_DCT_scaled_size;
  170861. jpeg_component_info *compptr;
  170862. JSAMPARRAY xbuf;
  170863. /* Get top-level space for component array pointers.
  170864. * We alloc both arrays with one call to save a few cycles.
  170865. */
  170866. main_->xbuffer[0] = (JSAMPIMAGE)
  170867. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170868. cinfo->num_components * 2 * SIZEOF(JSAMPARRAY));
  170869. main_->xbuffer[1] = main_->xbuffer[0] + cinfo->num_components;
  170870. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170871. ci++, compptr++) {
  170872. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170873. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170874. /* Get space for pointer lists --- M+4 row groups in each list.
  170875. * We alloc both pointer lists with one call to save a few cycles.
  170876. */
  170877. xbuf = (JSAMPARRAY)
  170878. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170879. 2 * (rgroup * (M + 4)) * SIZEOF(JSAMPROW));
  170880. xbuf += rgroup; /* want one row group at negative offsets */
  170881. main_->xbuffer[0][ci] = xbuf;
  170882. xbuf += rgroup * (M + 4);
  170883. main_->xbuffer[1][ci] = xbuf;
  170884. }
  170885. }
  170886. LOCAL(void)
  170887. make_funny_pointers (j_decompress_ptr cinfo)
  170888. /* Create the funny pointer lists discussed in the comments above.
  170889. * The actual workspace is already allocated (in main->buffer),
  170890. * and the space for the pointer lists is allocated too.
  170891. * This routine just fills in the curiously ordered lists.
  170892. * This will be repeated at the beginning of each pass.
  170893. */
  170894. {
  170895. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170896. int ci, i, rgroup;
  170897. int M = cinfo->min_DCT_scaled_size;
  170898. jpeg_component_info *compptr;
  170899. JSAMPARRAY buf, xbuf0, xbuf1;
  170900. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170901. ci++, compptr++) {
  170902. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170903. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170904. xbuf0 = main_->xbuffer[0][ci];
  170905. xbuf1 = main_->xbuffer[1][ci];
  170906. /* First copy the workspace pointers as-is */
  170907. buf = main_->buffer[ci];
  170908. for (i = 0; i < rgroup * (M + 2); i++) {
  170909. xbuf0[i] = xbuf1[i] = buf[i];
  170910. }
  170911. /* In the second list, put the last four row groups in swapped order */
  170912. for (i = 0; i < rgroup * 2; i++) {
  170913. xbuf1[rgroup*(M-2) + i] = buf[rgroup*M + i];
  170914. xbuf1[rgroup*M + i] = buf[rgroup*(M-2) + i];
  170915. }
  170916. /* The wraparound pointers at top and bottom will be filled later
  170917. * (see set_wraparound_pointers, below). Initially we want the "above"
  170918. * pointers to duplicate the first actual data line. This only needs
  170919. * to happen in xbuffer[0].
  170920. */
  170921. for (i = 0; i < rgroup; i++) {
  170922. xbuf0[i - rgroup] = xbuf0[0];
  170923. }
  170924. }
  170925. }
  170926. LOCAL(void)
  170927. set_wraparound_pointers (j_decompress_ptr cinfo)
  170928. /* Set up the "wraparound" pointers at top and bottom of the pointer lists.
  170929. * This changes the pointer list state from top-of-image to the normal state.
  170930. */
  170931. {
  170932. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170933. int ci, i, rgroup;
  170934. int M = cinfo->min_DCT_scaled_size;
  170935. jpeg_component_info *compptr;
  170936. JSAMPARRAY xbuf0, xbuf1;
  170937. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170938. ci++, compptr++) {
  170939. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170940. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170941. xbuf0 = main_->xbuffer[0][ci];
  170942. xbuf1 = main_->xbuffer[1][ci];
  170943. for (i = 0; i < rgroup; i++) {
  170944. xbuf0[i - rgroup] = xbuf0[rgroup*(M+1) + i];
  170945. xbuf1[i - rgroup] = xbuf1[rgroup*(M+1) + i];
  170946. xbuf0[rgroup*(M+2) + i] = xbuf0[i];
  170947. xbuf1[rgroup*(M+2) + i] = xbuf1[i];
  170948. }
  170949. }
  170950. }
  170951. LOCAL(void)
  170952. set_bottom_pointers (j_decompress_ptr cinfo)
  170953. /* Change the pointer lists to duplicate the last sample row at the bottom
  170954. * of the image. whichptr indicates which xbuffer holds the final iMCU row.
  170955. * Also sets rowgroups_avail to indicate number of nondummy row groups in row.
  170956. */
  170957. {
  170958. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170959. int ci, i, rgroup, iMCUheight, rows_left;
  170960. jpeg_component_info *compptr;
  170961. JSAMPARRAY xbuf;
  170962. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170963. ci++, compptr++) {
  170964. /* Count sample rows in one iMCU row and in one row group */
  170965. iMCUheight = compptr->v_samp_factor * compptr->DCT_scaled_size;
  170966. rgroup = iMCUheight / cinfo->min_DCT_scaled_size;
  170967. /* Count nondummy sample rows remaining for this component */
  170968. rows_left = (int) (compptr->downsampled_height % (JDIMENSION) iMCUheight);
  170969. if (rows_left == 0) rows_left = iMCUheight;
  170970. /* Count nondummy row groups. Should get same answer for each component,
  170971. * so we need only do it once.
  170972. */
  170973. if (ci == 0) {
  170974. main_->rowgroups_avail = (JDIMENSION) ((rows_left-1) / rgroup + 1);
  170975. }
  170976. /* Duplicate the last real sample row rgroup*2 times; this pads out the
  170977. * last partial rowgroup and ensures at least one full rowgroup of context.
  170978. */
  170979. xbuf = main_->xbuffer[main_->whichptr][ci];
  170980. for (i = 0; i < rgroup * 2; i++) {
  170981. xbuf[rows_left + i] = xbuf[rows_left-1];
  170982. }
  170983. }
  170984. }
  170985. /*
  170986. * Initialize for a processing pass.
  170987. */
  170988. METHODDEF(void)
  170989. start_pass_main2 (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  170990. {
  170991. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170992. switch (pass_mode) {
  170993. case JBUF_PASS_THRU:
  170994. if (cinfo->upsample->need_context_rows) {
  170995. main_->pub.process_data = process_data_context_main;
  170996. make_funny_pointers(cinfo); /* Create the xbuffer[] lists */
  170997. main_->whichptr = 0; /* Read first iMCU row into xbuffer[0] */
  170998. main_->context_state = CTX_PREPARE_FOR_IMCU;
  170999. main_->iMCU_row_ctr = 0;
  171000. } else {
  171001. /* Simple case with no context needed */
  171002. main_->pub.process_data = process_data_simple_main2;
  171003. }
  171004. main_->buffer_full = FALSE; /* Mark buffer empty */
  171005. main_->rowgroup_ctr = 0;
  171006. break;
  171007. #ifdef QUANT_2PASS_SUPPORTED
  171008. case JBUF_CRANK_DEST:
  171009. /* For last pass of 2-pass quantization, just crank the postprocessor */
  171010. main_->pub.process_data = process_data_crank_post;
  171011. break;
  171012. #endif
  171013. default:
  171014. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  171015. break;
  171016. }
  171017. }
  171018. /*
  171019. * Process some data.
  171020. * This handles the simple case where no context is required.
  171021. */
  171022. METHODDEF(void)
  171023. process_data_simple_main2 (j_decompress_ptr cinfo,
  171024. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  171025. JDIMENSION out_rows_avail)
  171026. {
  171027. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171028. JDIMENSION rowgroups_avail;
  171029. /* Read input data if we haven't filled the main buffer yet */
  171030. if (! main_->buffer_full) {
  171031. if (! (*cinfo->coef->decompress_data) (cinfo, main_->buffer))
  171032. return; /* suspension forced, can do nothing more */
  171033. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  171034. }
  171035. /* There are always min_DCT_scaled_size row groups in an iMCU row. */
  171036. rowgroups_avail = (JDIMENSION) cinfo->min_DCT_scaled_size;
  171037. /* Note: at the bottom of the image, we may pass extra garbage row groups
  171038. * to the postprocessor. The postprocessor has to check for bottom
  171039. * of image anyway (at row resolution), so no point in us doing it too.
  171040. */
  171041. /* Feed the postprocessor */
  171042. (*cinfo->post->post_process_data) (cinfo, main_->buffer,
  171043. &main_->rowgroup_ctr, rowgroups_avail,
  171044. output_buf, out_row_ctr, out_rows_avail);
  171045. /* Has postprocessor consumed all the data yet? If so, mark buffer empty */
  171046. if (main_->rowgroup_ctr >= rowgroups_avail) {
  171047. main_->buffer_full = FALSE;
  171048. main_->rowgroup_ctr = 0;
  171049. }
  171050. }
  171051. /*
  171052. * Process some data.
  171053. * This handles the case where context rows must be provided.
  171054. */
  171055. METHODDEF(void)
  171056. process_data_context_main (j_decompress_ptr cinfo,
  171057. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  171058. JDIMENSION out_rows_avail)
  171059. {
  171060. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171061. /* Read input data if we haven't filled the main buffer yet */
  171062. if (! main_->buffer_full) {
  171063. if (! (*cinfo->coef->decompress_data) (cinfo,
  171064. main_->xbuffer[main_->whichptr]))
  171065. return; /* suspension forced, can do nothing more */
  171066. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  171067. main_->iMCU_row_ctr++; /* count rows received */
  171068. }
  171069. /* Postprocessor typically will not swallow all the input data it is handed
  171070. * in one call (due to filling the output buffer first). Must be prepared
  171071. * to exit and restart. This switch lets us keep track of how far we got.
  171072. * Note that each case falls through to the next on successful completion.
  171073. */
  171074. switch (main_->context_state) {
  171075. case CTX_POSTPONED_ROW:
  171076. /* Call postprocessor using previously set pointers for postponed row */
  171077. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  171078. &main_->rowgroup_ctr, main_->rowgroups_avail,
  171079. output_buf, out_row_ctr, out_rows_avail);
  171080. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  171081. return; /* Need to suspend */
  171082. main_->context_state = CTX_PREPARE_FOR_IMCU;
  171083. if (*out_row_ctr >= out_rows_avail)
  171084. return; /* Postprocessor exactly filled output buf */
  171085. /*FALLTHROUGH*/
  171086. case CTX_PREPARE_FOR_IMCU:
  171087. /* Prepare to process first M-1 row groups of this iMCU row */
  171088. main_->rowgroup_ctr = 0;
  171089. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size - 1);
  171090. /* Check for bottom of image: if so, tweak pointers to "duplicate"
  171091. * the last sample row, and adjust rowgroups_avail to ignore padding rows.
  171092. */
  171093. if (main_->iMCU_row_ctr == cinfo->total_iMCU_rows)
  171094. set_bottom_pointers(cinfo);
  171095. main_->context_state = CTX_PROCESS_IMCU;
  171096. /*FALLTHROUGH*/
  171097. case CTX_PROCESS_IMCU:
  171098. /* Call postprocessor using previously set pointers */
  171099. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  171100. &main_->rowgroup_ctr, main_->rowgroups_avail,
  171101. output_buf, out_row_ctr, out_rows_avail);
  171102. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  171103. return; /* Need to suspend */
  171104. /* After the first iMCU, change wraparound pointers to normal state */
  171105. if (main_->iMCU_row_ctr == 1)
  171106. set_wraparound_pointers(cinfo);
  171107. /* Prepare to load new iMCU row using other xbuffer list */
  171108. main_->whichptr ^= 1; /* 0=>1 or 1=>0 */
  171109. main_->buffer_full = FALSE;
  171110. /* Still need to process last row group of this iMCU row, */
  171111. /* which is saved at index M+1 of the other xbuffer */
  171112. main_->rowgroup_ctr = (JDIMENSION) (cinfo->min_DCT_scaled_size + 1);
  171113. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size + 2);
  171114. main_->context_state = CTX_POSTPONED_ROW;
  171115. }
  171116. }
  171117. /*
  171118. * Process some data.
  171119. * Final pass of two-pass quantization: just call the postprocessor.
  171120. * Source data will be the postprocessor controller's internal buffer.
  171121. */
  171122. #ifdef QUANT_2PASS_SUPPORTED
  171123. METHODDEF(void)
  171124. process_data_crank_post (j_decompress_ptr cinfo,
  171125. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  171126. JDIMENSION out_rows_avail)
  171127. {
  171128. (*cinfo->post->post_process_data) (cinfo, (JSAMPIMAGE) NULL,
  171129. (JDIMENSION *) NULL, (JDIMENSION) 0,
  171130. output_buf, out_row_ctr, out_rows_avail);
  171131. }
  171132. #endif /* QUANT_2PASS_SUPPORTED */
  171133. /*
  171134. * Initialize main buffer controller.
  171135. */
  171136. GLOBAL(void)
  171137. jinit_d_main_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  171138. {
  171139. my_main_ptr4 main_;
  171140. int ci, rgroup, ngroups;
  171141. jpeg_component_info *compptr;
  171142. main_ = (my_main_ptr4)
  171143. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171144. SIZEOF(my_main_controller4));
  171145. cinfo->main = (struct jpeg_d_main_controller *) main_;
  171146. main_->pub.start_pass = start_pass_main2;
  171147. if (need_full_buffer) /* shouldn't happen */
  171148. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  171149. /* Allocate the workspace.
  171150. * ngroups is the number of row groups we need.
  171151. */
  171152. if (cinfo->upsample->need_context_rows) {
  171153. if (cinfo->min_DCT_scaled_size < 2) /* unsupported, see comments above */
  171154. ERREXIT(cinfo, JERR_NOTIMPL);
  171155. alloc_funny_pointers(cinfo); /* Alloc space for xbuffer[] lists */
  171156. ngroups = cinfo->min_DCT_scaled_size + 2;
  171157. } else {
  171158. ngroups = cinfo->min_DCT_scaled_size;
  171159. }
  171160. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171161. ci++, compptr++) {
  171162. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  171163. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  171164. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  171165. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171166. compptr->width_in_blocks * compptr->DCT_scaled_size,
  171167. (JDIMENSION) (rgroup * ngroups));
  171168. }
  171169. }
  171170. /*** End of inlined file: jdmainct.c ***/
  171171. /*** Start of inlined file: jdmarker.c ***/
  171172. #define JPEG_INTERNALS
  171173. /* Private state */
  171174. typedef struct {
  171175. struct jpeg_marker_reader pub; /* public fields */
  171176. /* Application-overridable marker processing methods */
  171177. jpeg_marker_parser_method process_COM;
  171178. jpeg_marker_parser_method process_APPn[16];
  171179. /* Limit on marker data length to save for each marker type */
  171180. unsigned int length_limit_COM;
  171181. unsigned int length_limit_APPn[16];
  171182. /* Status of COM/APPn marker saving */
  171183. jpeg_saved_marker_ptr cur_marker; /* NULL if not processing a marker */
  171184. unsigned int bytes_read; /* data bytes read so far in marker */
  171185. /* Note: cur_marker is not linked into marker_list until it's all read. */
  171186. } my_marker_reader;
  171187. typedef my_marker_reader * my_marker_ptr2;
  171188. /*
  171189. * Macros for fetching data from the data source module.
  171190. *
  171191. * At all times, cinfo->src->next_input_byte and ->bytes_in_buffer reflect
  171192. * the current restart point; we update them only when we have reached a
  171193. * suitable place to restart if a suspension occurs.
  171194. */
  171195. /* Declare and initialize local copies of input pointer/count */
  171196. #define INPUT_VARS(cinfo) \
  171197. struct jpeg_source_mgr * datasrc = (cinfo)->src; \
  171198. const JOCTET * next_input_byte = datasrc->next_input_byte; \
  171199. size_t bytes_in_buffer = datasrc->bytes_in_buffer
  171200. /* Unload the local copies --- do this only at a restart boundary */
  171201. #define INPUT_SYNC(cinfo) \
  171202. ( datasrc->next_input_byte = next_input_byte, \
  171203. datasrc->bytes_in_buffer = bytes_in_buffer )
  171204. /* Reload the local copies --- used only in MAKE_BYTE_AVAIL */
  171205. #define INPUT_RELOAD(cinfo) \
  171206. ( next_input_byte = datasrc->next_input_byte, \
  171207. bytes_in_buffer = datasrc->bytes_in_buffer )
  171208. /* Internal macro for INPUT_BYTE and INPUT_2BYTES: make a byte available.
  171209. * Note we do *not* do INPUT_SYNC before calling fill_input_buffer,
  171210. * but we must reload the local copies after a successful fill.
  171211. */
  171212. #define MAKE_BYTE_AVAIL(cinfo,action) \
  171213. if (bytes_in_buffer == 0) { \
  171214. if (! (*datasrc->fill_input_buffer) (cinfo)) \
  171215. { action; } \
  171216. INPUT_RELOAD(cinfo); \
  171217. }
  171218. /* Read a byte into variable V.
  171219. * If must suspend, take the specified action (typically "return FALSE").
  171220. */
  171221. #define INPUT_BYTE(cinfo,V,action) \
  171222. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  171223. bytes_in_buffer--; \
  171224. V = GETJOCTET(*next_input_byte++); )
  171225. /* As above, but read two bytes interpreted as an unsigned 16-bit integer.
  171226. * V should be declared unsigned int or perhaps INT32.
  171227. */
  171228. #define INPUT_2BYTES(cinfo,V,action) \
  171229. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  171230. bytes_in_buffer--; \
  171231. V = ((unsigned int) GETJOCTET(*next_input_byte++)) << 8; \
  171232. MAKE_BYTE_AVAIL(cinfo,action); \
  171233. bytes_in_buffer--; \
  171234. V += GETJOCTET(*next_input_byte++); )
  171235. /*
  171236. * Routines to process JPEG markers.
  171237. *
  171238. * Entry condition: JPEG marker itself has been read and its code saved
  171239. * in cinfo->unread_marker; input restart point is just after the marker.
  171240. *
  171241. * Exit: if return TRUE, have read and processed any parameters, and have
  171242. * updated the restart point to point after the parameters.
  171243. * If return FALSE, was forced to suspend before reaching end of
  171244. * marker parameters; restart point has not been moved. Same routine
  171245. * will be called again after application supplies more input data.
  171246. *
  171247. * This approach to suspension assumes that all of a marker's parameters
  171248. * can fit into a single input bufferload. This should hold for "normal"
  171249. * markers. Some COM/APPn markers might have large parameter segments
  171250. * that might not fit. If we are simply dropping such a marker, we use
  171251. * skip_input_data to get past it, and thereby put the problem on the
  171252. * source manager's shoulders. If we are saving the marker's contents
  171253. * into memory, we use a slightly different convention: when forced to
  171254. * suspend, the marker processor updates the restart point to the end of
  171255. * what it's consumed (ie, the end of the buffer) before returning FALSE.
  171256. * On resumption, cinfo->unread_marker still contains the marker code,
  171257. * but the data source will point to the next chunk of marker data.
  171258. * The marker processor must retain internal state to deal with this.
  171259. *
  171260. * Note that we don't bother to avoid duplicate trace messages if a
  171261. * suspension occurs within marker parameters. Other side effects
  171262. * require more care.
  171263. */
  171264. LOCAL(boolean)
  171265. get_soi (j_decompress_ptr cinfo)
  171266. /* Process an SOI marker */
  171267. {
  171268. int i;
  171269. TRACEMS(cinfo, 1, JTRC_SOI);
  171270. if (cinfo->marker->saw_SOI)
  171271. ERREXIT(cinfo, JERR_SOI_DUPLICATE);
  171272. /* Reset all parameters that are defined to be reset by SOI */
  171273. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  171274. cinfo->arith_dc_L[i] = 0;
  171275. cinfo->arith_dc_U[i] = 1;
  171276. cinfo->arith_ac_K[i] = 5;
  171277. }
  171278. cinfo->restart_interval = 0;
  171279. /* Set initial assumptions for colorspace etc */
  171280. cinfo->jpeg_color_space = JCS_UNKNOWN;
  171281. cinfo->CCIR601_sampling = FALSE; /* Assume non-CCIR sampling??? */
  171282. cinfo->saw_JFIF_marker = FALSE;
  171283. cinfo->JFIF_major_version = 1; /* set default JFIF APP0 values */
  171284. cinfo->JFIF_minor_version = 1;
  171285. cinfo->density_unit = 0;
  171286. cinfo->X_density = 1;
  171287. cinfo->Y_density = 1;
  171288. cinfo->saw_Adobe_marker = FALSE;
  171289. cinfo->Adobe_transform = 0;
  171290. cinfo->marker->saw_SOI = TRUE;
  171291. return TRUE;
  171292. }
  171293. LOCAL(boolean)
  171294. get_sof (j_decompress_ptr cinfo, boolean is_prog, boolean is_arith)
  171295. /* Process a SOFn marker */
  171296. {
  171297. INT32 length;
  171298. int c, ci;
  171299. jpeg_component_info * compptr;
  171300. INPUT_VARS(cinfo);
  171301. cinfo->progressive_mode = is_prog;
  171302. cinfo->arith_code = is_arith;
  171303. INPUT_2BYTES(cinfo, length, return FALSE);
  171304. INPUT_BYTE(cinfo, cinfo->data_precision, return FALSE);
  171305. INPUT_2BYTES(cinfo, cinfo->image_height, return FALSE);
  171306. INPUT_2BYTES(cinfo, cinfo->image_width, return FALSE);
  171307. INPUT_BYTE(cinfo, cinfo->num_components, return FALSE);
  171308. length -= 8;
  171309. TRACEMS4(cinfo, 1, JTRC_SOF, cinfo->unread_marker,
  171310. (int) cinfo->image_width, (int) cinfo->image_height,
  171311. cinfo->num_components);
  171312. if (cinfo->marker->saw_SOF)
  171313. ERREXIT(cinfo, JERR_SOF_DUPLICATE);
  171314. /* We don't support files in which the image height is initially specified */
  171315. /* as 0 and is later redefined by DNL. As long as we have to check that, */
  171316. /* might as well have a general sanity check. */
  171317. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  171318. || cinfo->num_components <= 0)
  171319. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  171320. if (length != (cinfo->num_components * 3))
  171321. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171322. if (cinfo->comp_info == NULL) /* do only once, even if suspend */
  171323. cinfo->comp_info = (jpeg_component_info *) (*cinfo->mem->alloc_small)
  171324. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171325. cinfo->num_components * SIZEOF(jpeg_component_info));
  171326. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171327. ci++, compptr++) {
  171328. compptr->component_index = ci;
  171329. INPUT_BYTE(cinfo, compptr->component_id, return FALSE);
  171330. INPUT_BYTE(cinfo, c, return FALSE);
  171331. compptr->h_samp_factor = (c >> 4) & 15;
  171332. compptr->v_samp_factor = (c ) & 15;
  171333. INPUT_BYTE(cinfo, compptr->quant_tbl_no, return FALSE);
  171334. TRACEMS4(cinfo, 1, JTRC_SOF_COMPONENT,
  171335. compptr->component_id, compptr->h_samp_factor,
  171336. compptr->v_samp_factor, compptr->quant_tbl_no);
  171337. }
  171338. cinfo->marker->saw_SOF = TRUE;
  171339. INPUT_SYNC(cinfo);
  171340. return TRUE;
  171341. }
  171342. LOCAL(boolean)
  171343. get_sos (j_decompress_ptr cinfo)
  171344. /* Process a SOS marker */
  171345. {
  171346. INT32 length;
  171347. int i, ci, n, c, cc;
  171348. jpeg_component_info * compptr;
  171349. INPUT_VARS(cinfo);
  171350. if (! cinfo->marker->saw_SOF)
  171351. ERREXIT(cinfo, JERR_SOS_NO_SOF);
  171352. INPUT_2BYTES(cinfo, length, return FALSE);
  171353. INPUT_BYTE(cinfo, n, return FALSE); /* Number of components */
  171354. TRACEMS1(cinfo, 1, JTRC_SOS, n);
  171355. if (length != (n * 2 + 6) || n < 1 || n > MAX_COMPS_IN_SCAN)
  171356. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171357. cinfo->comps_in_scan = n;
  171358. /* Collect the component-spec parameters */
  171359. for (i = 0; i < n; i++) {
  171360. INPUT_BYTE(cinfo, cc, return FALSE);
  171361. INPUT_BYTE(cinfo, c, return FALSE);
  171362. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171363. ci++, compptr++) {
  171364. if (cc == compptr->component_id)
  171365. goto id_found;
  171366. }
  171367. ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc);
  171368. id_found:
  171369. cinfo->cur_comp_info[i] = compptr;
  171370. compptr->dc_tbl_no = (c >> 4) & 15;
  171371. compptr->ac_tbl_no = (c ) & 15;
  171372. TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, cc,
  171373. compptr->dc_tbl_no, compptr->ac_tbl_no);
  171374. }
  171375. /* Collect the additional scan parameters Ss, Se, Ah/Al. */
  171376. INPUT_BYTE(cinfo, c, return FALSE);
  171377. cinfo->Ss = c;
  171378. INPUT_BYTE(cinfo, c, return FALSE);
  171379. cinfo->Se = c;
  171380. INPUT_BYTE(cinfo, c, return FALSE);
  171381. cinfo->Ah = (c >> 4) & 15;
  171382. cinfo->Al = (c ) & 15;
  171383. TRACEMS4(cinfo, 1, JTRC_SOS_PARAMS, cinfo->Ss, cinfo->Se,
  171384. cinfo->Ah, cinfo->Al);
  171385. /* Prepare to scan data & restart markers */
  171386. cinfo->marker->next_restart_num = 0;
  171387. /* Count another SOS marker */
  171388. cinfo->input_scan_number++;
  171389. INPUT_SYNC(cinfo);
  171390. return TRUE;
  171391. }
  171392. #ifdef D_ARITH_CODING_SUPPORTED
  171393. LOCAL(boolean)
  171394. get_dac (j_decompress_ptr cinfo)
  171395. /* Process a DAC marker */
  171396. {
  171397. INT32 length;
  171398. int index, val;
  171399. INPUT_VARS(cinfo);
  171400. INPUT_2BYTES(cinfo, length, return FALSE);
  171401. length -= 2;
  171402. while (length > 0) {
  171403. INPUT_BYTE(cinfo, index, return FALSE);
  171404. INPUT_BYTE(cinfo, val, return FALSE);
  171405. length -= 2;
  171406. TRACEMS2(cinfo, 1, JTRC_DAC, index, val);
  171407. if (index < 0 || index >= (2*NUM_ARITH_TBLS))
  171408. ERREXIT1(cinfo, JERR_DAC_INDEX, index);
  171409. if (index >= NUM_ARITH_TBLS) { /* define AC table */
  171410. cinfo->arith_ac_K[index-NUM_ARITH_TBLS] = (UINT8) val;
  171411. } else { /* define DC table */
  171412. cinfo->arith_dc_L[index] = (UINT8) (val & 0x0F);
  171413. cinfo->arith_dc_U[index] = (UINT8) (val >> 4);
  171414. if (cinfo->arith_dc_L[index] > cinfo->arith_dc_U[index])
  171415. ERREXIT1(cinfo, JERR_DAC_VALUE, val);
  171416. }
  171417. }
  171418. if (length != 0)
  171419. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171420. INPUT_SYNC(cinfo);
  171421. return TRUE;
  171422. }
  171423. #else /* ! D_ARITH_CODING_SUPPORTED */
  171424. #define get_dac(cinfo) skip_variable(cinfo)
  171425. #endif /* D_ARITH_CODING_SUPPORTED */
  171426. LOCAL(boolean)
  171427. get_dht (j_decompress_ptr cinfo)
  171428. /* Process a DHT marker */
  171429. {
  171430. INT32 length;
  171431. UINT8 bits[17];
  171432. UINT8 huffval[256];
  171433. int i, index, count;
  171434. JHUFF_TBL **htblptr;
  171435. INPUT_VARS(cinfo);
  171436. INPUT_2BYTES(cinfo, length, return FALSE);
  171437. length -= 2;
  171438. while (length > 16) {
  171439. INPUT_BYTE(cinfo, index, return FALSE);
  171440. TRACEMS1(cinfo, 1, JTRC_DHT, index);
  171441. bits[0] = 0;
  171442. count = 0;
  171443. for (i = 1; i <= 16; i++) {
  171444. INPUT_BYTE(cinfo, bits[i], return FALSE);
  171445. count += bits[i];
  171446. }
  171447. length -= 1 + 16;
  171448. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  171449. bits[1], bits[2], bits[3], bits[4],
  171450. bits[5], bits[6], bits[7], bits[8]);
  171451. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  171452. bits[9], bits[10], bits[11], bits[12],
  171453. bits[13], bits[14], bits[15], bits[16]);
  171454. /* Here we just do minimal validation of the counts to avoid walking
  171455. * off the end of our table space. jdhuff.c will check more carefully.
  171456. */
  171457. if (count > 256 || ((INT32) count) > length)
  171458. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  171459. for (i = 0; i < count; i++)
  171460. INPUT_BYTE(cinfo, huffval[i], return FALSE);
  171461. length -= count;
  171462. if (index & 0x10) { /* AC table definition */
  171463. index -= 0x10;
  171464. htblptr = &cinfo->ac_huff_tbl_ptrs[index];
  171465. } else { /* DC table definition */
  171466. htblptr = &cinfo->dc_huff_tbl_ptrs[index];
  171467. }
  171468. if (index < 0 || index >= NUM_HUFF_TBLS)
  171469. ERREXIT1(cinfo, JERR_DHT_INDEX, index);
  171470. if (*htblptr == NULL)
  171471. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  171472. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  171473. MEMCOPY((*htblptr)->huffval, huffval, SIZEOF((*htblptr)->huffval));
  171474. }
  171475. if (length != 0)
  171476. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171477. INPUT_SYNC(cinfo);
  171478. return TRUE;
  171479. }
  171480. LOCAL(boolean)
  171481. get_dqt (j_decompress_ptr cinfo)
  171482. /* Process a DQT marker */
  171483. {
  171484. INT32 length;
  171485. int n, i, prec;
  171486. unsigned int tmp;
  171487. JQUANT_TBL *quant_ptr;
  171488. INPUT_VARS(cinfo);
  171489. INPUT_2BYTES(cinfo, length, return FALSE);
  171490. length -= 2;
  171491. while (length > 0) {
  171492. INPUT_BYTE(cinfo, n, return FALSE);
  171493. prec = n >> 4;
  171494. n &= 0x0F;
  171495. TRACEMS2(cinfo, 1, JTRC_DQT, n, prec);
  171496. if (n >= NUM_QUANT_TBLS)
  171497. ERREXIT1(cinfo, JERR_DQT_INDEX, n);
  171498. if (cinfo->quant_tbl_ptrs[n] == NULL)
  171499. cinfo->quant_tbl_ptrs[n] = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  171500. quant_ptr = cinfo->quant_tbl_ptrs[n];
  171501. for (i = 0; i < DCTSIZE2; i++) {
  171502. if (prec)
  171503. INPUT_2BYTES(cinfo, tmp, return FALSE);
  171504. else
  171505. INPUT_BYTE(cinfo, tmp, return FALSE);
  171506. /* We convert the zigzag-order table to natural array order. */
  171507. quant_ptr->quantval[jpeg_natural_order[i]] = (UINT16) tmp;
  171508. }
  171509. if (cinfo->err->trace_level >= 2) {
  171510. for (i = 0; i < DCTSIZE2; i += 8) {
  171511. TRACEMS8(cinfo, 2, JTRC_QUANTVALS,
  171512. quant_ptr->quantval[i], quant_ptr->quantval[i+1],
  171513. quant_ptr->quantval[i+2], quant_ptr->quantval[i+3],
  171514. quant_ptr->quantval[i+4], quant_ptr->quantval[i+5],
  171515. quant_ptr->quantval[i+6], quant_ptr->quantval[i+7]);
  171516. }
  171517. }
  171518. length -= DCTSIZE2+1;
  171519. if (prec) length -= DCTSIZE2;
  171520. }
  171521. if (length != 0)
  171522. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171523. INPUT_SYNC(cinfo);
  171524. return TRUE;
  171525. }
  171526. LOCAL(boolean)
  171527. get_dri (j_decompress_ptr cinfo)
  171528. /* Process a DRI marker */
  171529. {
  171530. INT32 length;
  171531. unsigned int tmp;
  171532. INPUT_VARS(cinfo);
  171533. INPUT_2BYTES(cinfo, length, return FALSE);
  171534. if (length != 4)
  171535. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171536. INPUT_2BYTES(cinfo, tmp, return FALSE);
  171537. TRACEMS1(cinfo, 1, JTRC_DRI, tmp);
  171538. cinfo->restart_interval = tmp;
  171539. INPUT_SYNC(cinfo);
  171540. return TRUE;
  171541. }
  171542. /*
  171543. * Routines for processing APPn and COM markers.
  171544. * These are either saved in memory or discarded, per application request.
  171545. * APP0 and APP14 are specially checked to see if they are
  171546. * JFIF and Adobe markers, respectively.
  171547. */
  171548. #define APP0_DATA_LEN 14 /* Length of interesting data in APP0 */
  171549. #define APP14_DATA_LEN 12 /* Length of interesting data in APP14 */
  171550. #define APPN_DATA_LEN 14 /* Must be the largest of the above!! */
  171551. LOCAL(void)
  171552. examine_app0 (j_decompress_ptr cinfo, JOCTET FAR * data,
  171553. unsigned int datalen, INT32 remaining)
  171554. /* Examine first few bytes from an APP0.
  171555. * Take appropriate action if it is a JFIF marker.
  171556. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  171557. */
  171558. {
  171559. INT32 totallen = (INT32) datalen + remaining;
  171560. if (datalen >= APP0_DATA_LEN &&
  171561. GETJOCTET(data[0]) == 0x4A &&
  171562. GETJOCTET(data[1]) == 0x46 &&
  171563. GETJOCTET(data[2]) == 0x49 &&
  171564. GETJOCTET(data[3]) == 0x46 &&
  171565. GETJOCTET(data[4]) == 0) {
  171566. /* Found JFIF APP0 marker: save info */
  171567. cinfo->saw_JFIF_marker = TRUE;
  171568. cinfo->JFIF_major_version = GETJOCTET(data[5]);
  171569. cinfo->JFIF_minor_version = GETJOCTET(data[6]);
  171570. cinfo->density_unit = GETJOCTET(data[7]);
  171571. cinfo->X_density = (GETJOCTET(data[8]) << 8) + GETJOCTET(data[9]);
  171572. cinfo->Y_density = (GETJOCTET(data[10]) << 8) + GETJOCTET(data[11]);
  171573. /* Check version.
  171574. * Major version must be 1, anything else signals an incompatible change.
  171575. * (We used to treat this as an error, but now it's a nonfatal warning,
  171576. * because some bozo at Hijaak couldn't read the spec.)
  171577. * Minor version should be 0..2, but process anyway if newer.
  171578. */
  171579. if (cinfo->JFIF_major_version != 1)
  171580. WARNMS2(cinfo, JWRN_JFIF_MAJOR,
  171581. cinfo->JFIF_major_version, cinfo->JFIF_minor_version);
  171582. /* Generate trace messages */
  171583. TRACEMS5(cinfo, 1, JTRC_JFIF,
  171584. cinfo->JFIF_major_version, cinfo->JFIF_minor_version,
  171585. cinfo->X_density, cinfo->Y_density, cinfo->density_unit);
  171586. /* Validate thumbnail dimensions and issue appropriate messages */
  171587. if (GETJOCTET(data[12]) | GETJOCTET(data[13]))
  171588. TRACEMS2(cinfo, 1, JTRC_JFIF_THUMBNAIL,
  171589. GETJOCTET(data[12]), GETJOCTET(data[13]));
  171590. totallen -= APP0_DATA_LEN;
  171591. if (totallen !=
  171592. ((INT32)GETJOCTET(data[12]) * (INT32)GETJOCTET(data[13]) * (INT32) 3))
  171593. TRACEMS1(cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, (int) totallen);
  171594. } else if (datalen >= 6 &&
  171595. GETJOCTET(data[0]) == 0x4A &&
  171596. GETJOCTET(data[1]) == 0x46 &&
  171597. GETJOCTET(data[2]) == 0x58 &&
  171598. GETJOCTET(data[3]) == 0x58 &&
  171599. GETJOCTET(data[4]) == 0) {
  171600. /* Found JFIF "JFXX" extension APP0 marker */
  171601. /* The library doesn't actually do anything with these,
  171602. * but we try to produce a helpful trace message.
  171603. */
  171604. switch (GETJOCTET(data[5])) {
  171605. case 0x10:
  171606. TRACEMS1(cinfo, 1, JTRC_THUMB_JPEG, (int) totallen);
  171607. break;
  171608. case 0x11:
  171609. TRACEMS1(cinfo, 1, JTRC_THUMB_PALETTE, (int) totallen);
  171610. break;
  171611. case 0x13:
  171612. TRACEMS1(cinfo, 1, JTRC_THUMB_RGB, (int) totallen);
  171613. break;
  171614. default:
  171615. TRACEMS2(cinfo, 1, JTRC_JFIF_EXTENSION,
  171616. GETJOCTET(data[5]), (int) totallen);
  171617. break;
  171618. }
  171619. } else {
  171620. /* Start of APP0 does not match "JFIF" or "JFXX", or too short */
  171621. TRACEMS1(cinfo, 1, JTRC_APP0, (int) totallen);
  171622. }
  171623. }
  171624. LOCAL(void)
  171625. examine_app14 (j_decompress_ptr cinfo, JOCTET FAR * data,
  171626. unsigned int datalen, INT32 remaining)
  171627. /* Examine first few bytes from an APP14.
  171628. * Take appropriate action if it is an Adobe marker.
  171629. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  171630. */
  171631. {
  171632. unsigned int version, flags0, flags1, transform;
  171633. if (datalen >= APP14_DATA_LEN &&
  171634. GETJOCTET(data[0]) == 0x41 &&
  171635. GETJOCTET(data[1]) == 0x64 &&
  171636. GETJOCTET(data[2]) == 0x6F &&
  171637. GETJOCTET(data[3]) == 0x62 &&
  171638. GETJOCTET(data[4]) == 0x65) {
  171639. /* Found Adobe APP14 marker */
  171640. version = (GETJOCTET(data[5]) << 8) + GETJOCTET(data[6]);
  171641. flags0 = (GETJOCTET(data[7]) << 8) + GETJOCTET(data[8]);
  171642. flags1 = (GETJOCTET(data[9]) << 8) + GETJOCTET(data[10]);
  171643. transform = GETJOCTET(data[11]);
  171644. TRACEMS4(cinfo, 1, JTRC_ADOBE, version, flags0, flags1, transform);
  171645. cinfo->saw_Adobe_marker = TRUE;
  171646. cinfo->Adobe_transform = (UINT8) transform;
  171647. } else {
  171648. /* Start of APP14 does not match "Adobe", or too short */
  171649. TRACEMS1(cinfo, 1, JTRC_APP14, (int) (datalen + remaining));
  171650. }
  171651. }
  171652. METHODDEF(boolean)
  171653. get_interesting_appn (j_decompress_ptr cinfo)
  171654. /* Process an APP0 or APP14 marker without saving it */
  171655. {
  171656. INT32 length;
  171657. JOCTET b[APPN_DATA_LEN];
  171658. unsigned int i, numtoread;
  171659. INPUT_VARS(cinfo);
  171660. INPUT_2BYTES(cinfo, length, return FALSE);
  171661. length -= 2;
  171662. /* get the interesting part of the marker data */
  171663. if (length >= APPN_DATA_LEN)
  171664. numtoread = APPN_DATA_LEN;
  171665. else if (length > 0)
  171666. numtoread = (unsigned int) length;
  171667. else
  171668. numtoread = 0;
  171669. for (i = 0; i < numtoread; i++)
  171670. INPUT_BYTE(cinfo, b[i], return FALSE);
  171671. length -= numtoread;
  171672. /* process it */
  171673. switch (cinfo->unread_marker) {
  171674. case M_APP0:
  171675. examine_app0(cinfo, (JOCTET FAR *) b, numtoread, length);
  171676. break;
  171677. case M_APP14:
  171678. examine_app14(cinfo, (JOCTET FAR *) b, numtoread, length);
  171679. break;
  171680. default:
  171681. /* can't get here unless jpeg_save_markers chooses wrong processor */
  171682. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  171683. break;
  171684. }
  171685. /* skip any remaining data -- could be lots */
  171686. INPUT_SYNC(cinfo);
  171687. if (length > 0)
  171688. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171689. return TRUE;
  171690. }
  171691. #ifdef SAVE_MARKERS_SUPPORTED
  171692. METHODDEF(boolean)
  171693. save_marker (j_decompress_ptr cinfo)
  171694. /* Save an APPn or COM marker into the marker list */
  171695. {
  171696. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  171697. jpeg_saved_marker_ptr cur_marker = marker->cur_marker;
  171698. unsigned int bytes_read, data_length;
  171699. JOCTET FAR * data;
  171700. INT32 length = 0;
  171701. INPUT_VARS(cinfo);
  171702. if (cur_marker == NULL) {
  171703. /* begin reading a marker */
  171704. INPUT_2BYTES(cinfo, length, return FALSE);
  171705. length -= 2;
  171706. if (length >= 0) { /* watch out for bogus length word */
  171707. /* figure out how much we want to save */
  171708. unsigned int limit;
  171709. if (cinfo->unread_marker == (int) M_COM)
  171710. limit = marker->length_limit_COM;
  171711. else
  171712. limit = marker->length_limit_APPn[cinfo->unread_marker - (int) M_APP0];
  171713. if ((unsigned int) length < limit)
  171714. limit = (unsigned int) length;
  171715. /* allocate and initialize the marker item */
  171716. cur_marker = (jpeg_saved_marker_ptr)
  171717. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171718. SIZEOF(struct jpeg_marker_struct) + limit);
  171719. cur_marker->next = NULL;
  171720. cur_marker->marker = (UINT8) cinfo->unread_marker;
  171721. cur_marker->original_length = (unsigned int) length;
  171722. cur_marker->data_length = limit;
  171723. /* data area is just beyond the jpeg_marker_struct */
  171724. data = cur_marker->data = (JOCTET FAR *) (cur_marker + 1);
  171725. marker->cur_marker = cur_marker;
  171726. marker->bytes_read = 0;
  171727. bytes_read = 0;
  171728. data_length = limit;
  171729. } else {
  171730. /* deal with bogus length word */
  171731. bytes_read = data_length = 0;
  171732. data = NULL;
  171733. }
  171734. } else {
  171735. /* resume reading a marker */
  171736. bytes_read = marker->bytes_read;
  171737. data_length = cur_marker->data_length;
  171738. data = cur_marker->data + bytes_read;
  171739. }
  171740. while (bytes_read < data_length) {
  171741. INPUT_SYNC(cinfo); /* move the restart point to here */
  171742. marker->bytes_read = bytes_read;
  171743. /* If there's not at least one byte in buffer, suspend */
  171744. MAKE_BYTE_AVAIL(cinfo, return FALSE);
  171745. /* Copy bytes with reasonable rapidity */
  171746. while (bytes_read < data_length && bytes_in_buffer > 0) {
  171747. *data++ = *next_input_byte++;
  171748. bytes_in_buffer--;
  171749. bytes_read++;
  171750. }
  171751. }
  171752. /* Done reading what we want to read */
  171753. if (cur_marker != NULL) { /* will be NULL if bogus length word */
  171754. /* Add new marker to end of list */
  171755. if (cinfo->marker_list == NULL) {
  171756. cinfo->marker_list = cur_marker;
  171757. } else {
  171758. jpeg_saved_marker_ptr prev = cinfo->marker_list;
  171759. while (prev->next != NULL)
  171760. prev = prev->next;
  171761. prev->next = cur_marker;
  171762. }
  171763. /* Reset pointer & calc remaining data length */
  171764. data = cur_marker->data;
  171765. length = cur_marker->original_length - data_length;
  171766. }
  171767. /* Reset to initial state for next marker */
  171768. marker->cur_marker = NULL;
  171769. /* Process the marker if interesting; else just make a generic trace msg */
  171770. switch (cinfo->unread_marker) {
  171771. case M_APP0:
  171772. examine_app0(cinfo, data, data_length, length);
  171773. break;
  171774. case M_APP14:
  171775. examine_app14(cinfo, data, data_length, length);
  171776. break;
  171777. default:
  171778. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker,
  171779. (int) (data_length + length));
  171780. break;
  171781. }
  171782. /* skip any remaining data -- could be lots */
  171783. INPUT_SYNC(cinfo); /* do before skip_input_data */
  171784. if (length > 0)
  171785. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171786. return TRUE;
  171787. }
  171788. #endif /* SAVE_MARKERS_SUPPORTED */
  171789. METHODDEF(boolean)
  171790. skip_variable (j_decompress_ptr cinfo)
  171791. /* Skip over an unknown or uninteresting variable-length marker */
  171792. {
  171793. INT32 length;
  171794. INPUT_VARS(cinfo);
  171795. INPUT_2BYTES(cinfo, length, return FALSE);
  171796. length -= 2;
  171797. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker, (int) length);
  171798. INPUT_SYNC(cinfo); /* do before skip_input_data */
  171799. if (length > 0)
  171800. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171801. return TRUE;
  171802. }
  171803. /*
  171804. * Find the next JPEG marker, save it in cinfo->unread_marker.
  171805. * Returns FALSE if had to suspend before reaching a marker;
  171806. * in that case cinfo->unread_marker is unchanged.
  171807. *
  171808. * Note that the result might not be a valid marker code,
  171809. * but it will never be 0 or FF.
  171810. */
  171811. LOCAL(boolean)
  171812. next_marker (j_decompress_ptr cinfo)
  171813. {
  171814. int c;
  171815. INPUT_VARS(cinfo);
  171816. for (;;) {
  171817. INPUT_BYTE(cinfo, c, return FALSE);
  171818. /* Skip any non-FF bytes.
  171819. * This may look a bit inefficient, but it will not occur in a valid file.
  171820. * We sync after each discarded byte so that a suspending data source
  171821. * can discard the byte from its buffer.
  171822. */
  171823. while (c != 0xFF) {
  171824. cinfo->marker->discarded_bytes++;
  171825. INPUT_SYNC(cinfo);
  171826. INPUT_BYTE(cinfo, c, return FALSE);
  171827. }
  171828. /* This loop swallows any duplicate FF bytes. Extra FFs are legal as
  171829. * pad bytes, so don't count them in discarded_bytes. We assume there
  171830. * will not be so many consecutive FF bytes as to overflow a suspending
  171831. * data source's input buffer.
  171832. */
  171833. do {
  171834. INPUT_BYTE(cinfo, c, return FALSE);
  171835. } while (c == 0xFF);
  171836. if (c != 0)
  171837. break; /* found a valid marker, exit loop */
  171838. /* Reach here if we found a stuffed-zero data sequence (FF/00).
  171839. * Discard it and loop back to try again.
  171840. */
  171841. cinfo->marker->discarded_bytes += 2;
  171842. INPUT_SYNC(cinfo);
  171843. }
  171844. if (cinfo->marker->discarded_bytes != 0) {
  171845. WARNMS2(cinfo, JWRN_EXTRANEOUS_DATA, cinfo->marker->discarded_bytes, c);
  171846. cinfo->marker->discarded_bytes = 0;
  171847. }
  171848. cinfo->unread_marker = c;
  171849. INPUT_SYNC(cinfo);
  171850. return TRUE;
  171851. }
  171852. LOCAL(boolean)
  171853. first_marker (j_decompress_ptr cinfo)
  171854. /* Like next_marker, but used to obtain the initial SOI marker. */
  171855. /* For this marker, we do not allow preceding garbage or fill; otherwise,
  171856. * we might well scan an entire input file before realizing it ain't JPEG.
  171857. * If an application wants to process non-JFIF files, it must seek to the
  171858. * SOI before calling the JPEG library.
  171859. */
  171860. {
  171861. int c, c2;
  171862. INPUT_VARS(cinfo);
  171863. INPUT_BYTE(cinfo, c, return FALSE);
  171864. INPUT_BYTE(cinfo, c2, return FALSE);
  171865. if (c != 0xFF || c2 != (int) M_SOI)
  171866. ERREXIT2(cinfo, JERR_NO_SOI, c, c2);
  171867. cinfo->unread_marker = c2;
  171868. INPUT_SYNC(cinfo);
  171869. return TRUE;
  171870. }
  171871. /*
  171872. * Read markers until SOS or EOI.
  171873. *
  171874. * Returns same codes as are defined for jpeg_consume_input:
  171875. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  171876. */
  171877. METHODDEF(int)
  171878. read_markers (j_decompress_ptr cinfo)
  171879. {
  171880. /* Outer loop repeats once for each marker. */
  171881. for (;;) {
  171882. /* Collect the marker proper, unless we already did. */
  171883. /* NB: first_marker() enforces the requirement that SOI appear first. */
  171884. if (cinfo->unread_marker == 0) {
  171885. if (! cinfo->marker->saw_SOI) {
  171886. if (! first_marker(cinfo))
  171887. return JPEG_SUSPENDED;
  171888. } else {
  171889. if (! next_marker(cinfo))
  171890. return JPEG_SUSPENDED;
  171891. }
  171892. }
  171893. /* At this point cinfo->unread_marker contains the marker code and the
  171894. * input point is just past the marker proper, but before any parameters.
  171895. * A suspension will cause us to return with this state still true.
  171896. */
  171897. switch (cinfo->unread_marker) {
  171898. case M_SOI:
  171899. if (! get_soi(cinfo))
  171900. return JPEG_SUSPENDED;
  171901. break;
  171902. case M_SOF0: /* Baseline */
  171903. case M_SOF1: /* Extended sequential, Huffman */
  171904. if (! get_sof(cinfo, FALSE, FALSE))
  171905. return JPEG_SUSPENDED;
  171906. break;
  171907. case M_SOF2: /* Progressive, Huffman */
  171908. if (! get_sof(cinfo, TRUE, FALSE))
  171909. return JPEG_SUSPENDED;
  171910. break;
  171911. case M_SOF9: /* Extended sequential, arithmetic */
  171912. if (! get_sof(cinfo, FALSE, TRUE))
  171913. return JPEG_SUSPENDED;
  171914. break;
  171915. case M_SOF10: /* Progressive, arithmetic */
  171916. if (! get_sof(cinfo, TRUE, TRUE))
  171917. return JPEG_SUSPENDED;
  171918. break;
  171919. /* Currently unsupported SOFn types */
  171920. case M_SOF3: /* Lossless, Huffman */
  171921. case M_SOF5: /* Differential sequential, Huffman */
  171922. case M_SOF6: /* Differential progressive, Huffman */
  171923. case M_SOF7: /* Differential lossless, Huffman */
  171924. case M_JPG: /* Reserved for JPEG extensions */
  171925. case M_SOF11: /* Lossless, arithmetic */
  171926. case M_SOF13: /* Differential sequential, arithmetic */
  171927. case M_SOF14: /* Differential progressive, arithmetic */
  171928. case M_SOF15: /* Differential lossless, arithmetic */
  171929. ERREXIT1(cinfo, JERR_SOF_UNSUPPORTED, cinfo->unread_marker);
  171930. break;
  171931. case M_SOS:
  171932. if (! get_sos(cinfo))
  171933. return JPEG_SUSPENDED;
  171934. cinfo->unread_marker = 0; /* processed the marker */
  171935. return JPEG_REACHED_SOS;
  171936. case M_EOI:
  171937. TRACEMS(cinfo, 1, JTRC_EOI);
  171938. cinfo->unread_marker = 0; /* processed the marker */
  171939. return JPEG_REACHED_EOI;
  171940. case M_DAC:
  171941. if (! get_dac(cinfo))
  171942. return JPEG_SUSPENDED;
  171943. break;
  171944. case M_DHT:
  171945. if (! get_dht(cinfo))
  171946. return JPEG_SUSPENDED;
  171947. break;
  171948. case M_DQT:
  171949. if (! get_dqt(cinfo))
  171950. return JPEG_SUSPENDED;
  171951. break;
  171952. case M_DRI:
  171953. if (! get_dri(cinfo))
  171954. return JPEG_SUSPENDED;
  171955. break;
  171956. case M_APP0:
  171957. case M_APP1:
  171958. case M_APP2:
  171959. case M_APP3:
  171960. case M_APP4:
  171961. case M_APP5:
  171962. case M_APP6:
  171963. case M_APP7:
  171964. case M_APP8:
  171965. case M_APP9:
  171966. case M_APP10:
  171967. case M_APP11:
  171968. case M_APP12:
  171969. case M_APP13:
  171970. case M_APP14:
  171971. case M_APP15:
  171972. if (! (*((my_marker_ptr2) cinfo->marker)->process_APPn[
  171973. cinfo->unread_marker - (int) M_APP0]) (cinfo))
  171974. return JPEG_SUSPENDED;
  171975. break;
  171976. case M_COM:
  171977. if (! (*((my_marker_ptr2) cinfo->marker)->process_COM) (cinfo))
  171978. return JPEG_SUSPENDED;
  171979. break;
  171980. case M_RST0: /* these are all parameterless */
  171981. case M_RST1:
  171982. case M_RST2:
  171983. case M_RST3:
  171984. case M_RST4:
  171985. case M_RST5:
  171986. case M_RST6:
  171987. case M_RST7:
  171988. case M_TEM:
  171989. TRACEMS1(cinfo, 1, JTRC_PARMLESS_MARKER, cinfo->unread_marker);
  171990. break;
  171991. case M_DNL: /* Ignore DNL ... perhaps the wrong thing */
  171992. if (! skip_variable(cinfo))
  171993. return JPEG_SUSPENDED;
  171994. break;
  171995. default: /* must be DHP, EXP, JPGn, or RESn */
  171996. /* For now, we treat the reserved markers as fatal errors since they are
  171997. * likely to be used to signal incompatible JPEG Part 3 extensions.
  171998. * Once the JPEG 3 version-number marker is well defined, this code
  171999. * ought to change!
  172000. */
  172001. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  172002. break;
  172003. }
  172004. /* Successfully processed marker, so reset state variable */
  172005. cinfo->unread_marker = 0;
  172006. } /* end loop */
  172007. }
  172008. /*
  172009. * Read a restart marker, which is expected to appear next in the datastream;
  172010. * if the marker is not there, take appropriate recovery action.
  172011. * Returns FALSE if suspension is required.
  172012. *
  172013. * This is called by the entropy decoder after it has read an appropriate
  172014. * number of MCUs. cinfo->unread_marker may be nonzero if the entropy decoder
  172015. * has already read a marker from the data source. Under normal conditions
  172016. * cinfo->unread_marker will be reset to 0 before returning; if not reset,
  172017. * it holds a marker which the decoder will be unable to read past.
  172018. */
  172019. METHODDEF(boolean)
  172020. read_restart_marker (j_decompress_ptr cinfo)
  172021. {
  172022. /* Obtain a marker unless we already did. */
  172023. /* Note that next_marker will complain if it skips any data. */
  172024. if (cinfo->unread_marker == 0) {
  172025. if (! next_marker(cinfo))
  172026. return FALSE;
  172027. }
  172028. if (cinfo->unread_marker ==
  172029. ((int) M_RST0 + cinfo->marker->next_restart_num)) {
  172030. /* Normal case --- swallow the marker and let entropy decoder continue */
  172031. TRACEMS1(cinfo, 3, JTRC_RST, cinfo->marker->next_restart_num);
  172032. cinfo->unread_marker = 0;
  172033. } else {
  172034. /* Uh-oh, the restart markers have been messed up. */
  172035. /* Let the data source manager determine how to resync. */
  172036. if (! (*cinfo->src->resync_to_restart) (cinfo,
  172037. cinfo->marker->next_restart_num))
  172038. return FALSE;
  172039. }
  172040. /* Update next-restart state */
  172041. cinfo->marker->next_restart_num = (cinfo->marker->next_restart_num + 1) & 7;
  172042. return TRUE;
  172043. }
  172044. /*
  172045. * This is the default resync_to_restart method for data source managers
  172046. * to use if they don't have any better approach. Some data source managers
  172047. * may be able to back up, or may have additional knowledge about the data
  172048. * which permits a more intelligent recovery strategy; such managers would
  172049. * presumably supply their own resync method.
  172050. *
  172051. * read_restart_marker calls resync_to_restart if it finds a marker other than
  172052. * the restart marker it was expecting. (This code is *not* used unless
  172053. * a nonzero restart interval has been declared.) cinfo->unread_marker is
  172054. * the marker code actually found (might be anything, except 0 or FF).
  172055. * The desired restart marker number (0..7) is passed as a parameter.
  172056. * This routine is supposed to apply whatever error recovery strategy seems
  172057. * appropriate in order to position the input stream to the next data segment.
  172058. * Note that cinfo->unread_marker is treated as a marker appearing before
  172059. * the current data-source input point; usually it should be reset to zero
  172060. * before returning.
  172061. * Returns FALSE if suspension is required.
  172062. *
  172063. * This implementation is substantially constrained by wanting to treat the
  172064. * input as a data stream; this means we can't back up. Therefore, we have
  172065. * only the following actions to work with:
  172066. * 1. Simply discard the marker and let the entropy decoder resume at next
  172067. * byte of file.
  172068. * 2. Read forward until we find another marker, discarding intervening
  172069. * data. (In theory we could look ahead within the current bufferload,
  172070. * without having to discard data if we don't find the desired marker.
  172071. * This idea is not implemented here, in part because it makes behavior
  172072. * dependent on buffer size and chance buffer-boundary positions.)
  172073. * 3. Leave the marker unread (by failing to zero cinfo->unread_marker).
  172074. * This will cause the entropy decoder to process an empty data segment,
  172075. * inserting dummy zeroes, and then we will reprocess the marker.
  172076. *
  172077. * #2 is appropriate if we think the desired marker lies ahead, while #3 is
  172078. * appropriate if the found marker is a future restart marker (indicating
  172079. * that we have missed the desired restart marker, probably because it got
  172080. * corrupted).
  172081. * We apply #2 or #3 if the found marker is a restart marker no more than
  172082. * two counts behind or ahead of the expected one. We also apply #2 if the
  172083. * found marker is not a legal JPEG marker code (it's certainly bogus data).
  172084. * If the found marker is a restart marker more than 2 counts away, we do #1
  172085. * (too much risk that the marker is erroneous; with luck we will be able to
  172086. * resync at some future point).
  172087. * For any valid non-restart JPEG marker, we apply #3. This keeps us from
  172088. * overrunning the end of a scan. An implementation limited to single-scan
  172089. * files might find it better to apply #2 for markers other than EOI, since
  172090. * any other marker would have to be bogus data in that case.
  172091. */
  172092. GLOBAL(boolean)
  172093. jpeg_resync_to_restart (j_decompress_ptr cinfo, int desired)
  172094. {
  172095. int marker = cinfo->unread_marker;
  172096. int action = 1;
  172097. /* Always put up a warning. */
  172098. WARNMS2(cinfo, JWRN_MUST_RESYNC, marker, desired);
  172099. /* Outer loop handles repeated decision after scanning forward. */
  172100. for (;;) {
  172101. if (marker < (int) M_SOF0)
  172102. action = 2; /* invalid marker */
  172103. else if (marker < (int) M_RST0 || marker > (int) M_RST7)
  172104. action = 3; /* valid non-restart marker */
  172105. else {
  172106. if (marker == ((int) M_RST0 + ((desired+1) & 7)) ||
  172107. marker == ((int) M_RST0 + ((desired+2) & 7)))
  172108. action = 3; /* one of the next two expected restarts */
  172109. else if (marker == ((int) M_RST0 + ((desired-1) & 7)) ||
  172110. marker == ((int) M_RST0 + ((desired-2) & 7)))
  172111. action = 2; /* a prior restart, so advance */
  172112. else
  172113. action = 1; /* desired restart or too far away */
  172114. }
  172115. TRACEMS2(cinfo, 4, JTRC_RECOVERY_ACTION, marker, action);
  172116. switch (action) {
  172117. case 1:
  172118. /* Discard marker and let entropy decoder resume processing. */
  172119. cinfo->unread_marker = 0;
  172120. return TRUE;
  172121. case 2:
  172122. /* Scan to the next marker, and repeat the decision loop. */
  172123. if (! next_marker(cinfo))
  172124. return FALSE;
  172125. marker = cinfo->unread_marker;
  172126. break;
  172127. case 3:
  172128. /* Return without advancing past this marker. */
  172129. /* Entropy decoder will be forced to process an empty segment. */
  172130. return TRUE;
  172131. }
  172132. } /* end loop */
  172133. }
  172134. /*
  172135. * Reset marker processing state to begin a fresh datastream.
  172136. */
  172137. METHODDEF(void)
  172138. reset_marker_reader (j_decompress_ptr cinfo)
  172139. {
  172140. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  172141. cinfo->comp_info = NULL; /* until allocated by get_sof */
  172142. cinfo->input_scan_number = 0; /* no SOS seen yet */
  172143. cinfo->unread_marker = 0; /* no pending marker */
  172144. marker->pub.saw_SOI = FALSE; /* set internal state too */
  172145. marker->pub.saw_SOF = FALSE;
  172146. marker->pub.discarded_bytes = 0;
  172147. marker->cur_marker = NULL;
  172148. }
  172149. /*
  172150. * Initialize the marker reader module.
  172151. * This is called only once, when the decompression object is created.
  172152. */
  172153. GLOBAL(void)
  172154. jinit_marker_reader (j_decompress_ptr cinfo)
  172155. {
  172156. my_marker_ptr2 marker;
  172157. int i;
  172158. /* Create subobject in permanent pool */
  172159. marker = (my_marker_ptr2)
  172160. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  172161. SIZEOF(my_marker_reader));
  172162. cinfo->marker = (struct jpeg_marker_reader *) marker;
  172163. /* Initialize public method pointers */
  172164. marker->pub.reset_marker_reader = reset_marker_reader;
  172165. marker->pub.read_markers = read_markers;
  172166. marker->pub.read_restart_marker = read_restart_marker;
  172167. /* Initialize COM/APPn processing.
  172168. * By default, we examine and then discard APP0 and APP14,
  172169. * but simply discard COM and all other APPn.
  172170. */
  172171. marker->process_COM = skip_variable;
  172172. marker->length_limit_COM = 0;
  172173. for (i = 0; i < 16; i++) {
  172174. marker->process_APPn[i] = skip_variable;
  172175. marker->length_limit_APPn[i] = 0;
  172176. }
  172177. marker->process_APPn[0] = get_interesting_appn;
  172178. marker->process_APPn[14] = get_interesting_appn;
  172179. /* Reset marker processing state */
  172180. reset_marker_reader(cinfo);
  172181. }
  172182. /*
  172183. * Control saving of COM and APPn markers into marker_list.
  172184. */
  172185. #ifdef SAVE_MARKERS_SUPPORTED
  172186. GLOBAL(void)
  172187. jpeg_save_markers (j_decompress_ptr cinfo, int marker_code,
  172188. unsigned int length_limit)
  172189. {
  172190. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  172191. long maxlength;
  172192. jpeg_marker_parser_method processor;
  172193. /* Length limit mustn't be larger than what we can allocate
  172194. * (should only be a concern in a 16-bit environment).
  172195. */
  172196. maxlength = cinfo->mem->max_alloc_chunk - SIZEOF(struct jpeg_marker_struct);
  172197. if (((long) length_limit) > maxlength)
  172198. length_limit = (unsigned int) maxlength;
  172199. /* Choose processor routine to use.
  172200. * APP0/APP14 have special requirements.
  172201. */
  172202. if (length_limit) {
  172203. processor = save_marker;
  172204. /* If saving APP0/APP14, save at least enough for our internal use. */
  172205. if (marker_code == (int) M_APP0 && length_limit < APP0_DATA_LEN)
  172206. length_limit = APP0_DATA_LEN;
  172207. else if (marker_code == (int) M_APP14 && length_limit < APP14_DATA_LEN)
  172208. length_limit = APP14_DATA_LEN;
  172209. } else {
  172210. processor = skip_variable;
  172211. /* If discarding APP0/APP14, use our regular on-the-fly processor. */
  172212. if (marker_code == (int) M_APP0 || marker_code == (int) M_APP14)
  172213. processor = get_interesting_appn;
  172214. }
  172215. if (marker_code == (int) M_COM) {
  172216. marker->process_COM = processor;
  172217. marker->length_limit_COM = length_limit;
  172218. } else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15) {
  172219. marker->process_APPn[marker_code - (int) M_APP0] = processor;
  172220. marker->length_limit_APPn[marker_code - (int) M_APP0] = length_limit;
  172221. } else
  172222. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  172223. }
  172224. #endif /* SAVE_MARKERS_SUPPORTED */
  172225. /*
  172226. * Install a special processing method for COM or APPn markers.
  172227. */
  172228. GLOBAL(void)
  172229. jpeg_set_marker_processor (j_decompress_ptr cinfo, int marker_code,
  172230. jpeg_marker_parser_method routine)
  172231. {
  172232. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  172233. if (marker_code == (int) M_COM)
  172234. marker->process_COM = routine;
  172235. else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15)
  172236. marker->process_APPn[marker_code - (int) M_APP0] = routine;
  172237. else
  172238. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  172239. }
  172240. /*** End of inlined file: jdmarker.c ***/
  172241. /*** Start of inlined file: jdmaster.c ***/
  172242. #define JPEG_INTERNALS
  172243. /* Private state */
  172244. typedef struct {
  172245. struct jpeg_decomp_master pub; /* public fields */
  172246. int pass_number; /* # of passes completed */
  172247. boolean using_merged_upsample; /* TRUE if using merged upsample/cconvert */
  172248. /* Saved references to initialized quantizer modules,
  172249. * in case we need to switch modes.
  172250. */
  172251. struct jpeg_color_quantizer * quantizer_1pass;
  172252. struct jpeg_color_quantizer * quantizer_2pass;
  172253. } my_decomp_master;
  172254. typedef my_decomp_master * my_master_ptr6;
  172255. /*
  172256. * Determine whether merged upsample/color conversion should be used.
  172257. * CRUCIAL: this must match the actual capabilities of jdmerge.c!
  172258. */
  172259. LOCAL(boolean)
  172260. use_merged_upsample (j_decompress_ptr cinfo)
  172261. {
  172262. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172263. /* Merging is the equivalent of plain box-filter upsampling */
  172264. if (cinfo->do_fancy_upsampling || cinfo->CCIR601_sampling)
  172265. return FALSE;
  172266. /* jdmerge.c only supports YCC=>RGB color conversion */
  172267. if (cinfo->jpeg_color_space != JCS_YCbCr || cinfo->num_components != 3 ||
  172268. cinfo->out_color_space != JCS_RGB ||
  172269. cinfo->out_color_components != RGB_PIXELSIZE)
  172270. return FALSE;
  172271. /* and it only handles 2h1v or 2h2v sampling ratios */
  172272. if (cinfo->comp_info[0].h_samp_factor != 2 ||
  172273. cinfo->comp_info[1].h_samp_factor != 1 ||
  172274. cinfo->comp_info[2].h_samp_factor != 1 ||
  172275. cinfo->comp_info[0].v_samp_factor > 2 ||
  172276. cinfo->comp_info[1].v_samp_factor != 1 ||
  172277. cinfo->comp_info[2].v_samp_factor != 1)
  172278. return FALSE;
  172279. /* furthermore, it doesn't work if we've scaled the IDCTs differently */
  172280. if (cinfo->comp_info[0].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  172281. cinfo->comp_info[1].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  172282. cinfo->comp_info[2].DCT_scaled_size != cinfo->min_DCT_scaled_size)
  172283. return FALSE;
  172284. /* ??? also need to test for upsample-time rescaling, when & if supported */
  172285. return TRUE; /* by golly, it'll work... */
  172286. #else
  172287. return FALSE;
  172288. #endif
  172289. }
  172290. /*
  172291. * Compute output image dimensions and related values.
  172292. * NOTE: this is exported for possible use by application.
  172293. * Hence it mustn't do anything that can't be done twice.
  172294. * Also note that it may be called before the master module is initialized!
  172295. */
  172296. GLOBAL(void)
  172297. jpeg_calc_output_dimensions (j_decompress_ptr cinfo)
  172298. /* Do computations that are needed before master selection phase */
  172299. {
  172300. #ifdef IDCT_SCALING_SUPPORTED
  172301. int ci;
  172302. jpeg_component_info *compptr;
  172303. #endif
  172304. /* Prevent application from calling me at wrong times */
  172305. if (cinfo->global_state != DSTATE_READY)
  172306. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  172307. #ifdef IDCT_SCALING_SUPPORTED
  172308. /* Compute actual output image dimensions and DCT scaling choices. */
  172309. if (cinfo->scale_num * 8 <= cinfo->scale_denom) {
  172310. /* Provide 1/8 scaling */
  172311. cinfo->output_width = (JDIMENSION)
  172312. jdiv_round_up((long) cinfo->image_width, 8L);
  172313. cinfo->output_height = (JDIMENSION)
  172314. jdiv_round_up((long) cinfo->image_height, 8L);
  172315. cinfo->min_DCT_scaled_size = 1;
  172316. } else if (cinfo->scale_num * 4 <= cinfo->scale_denom) {
  172317. /* Provide 1/4 scaling */
  172318. cinfo->output_width = (JDIMENSION)
  172319. jdiv_round_up((long) cinfo->image_width, 4L);
  172320. cinfo->output_height = (JDIMENSION)
  172321. jdiv_round_up((long) cinfo->image_height, 4L);
  172322. cinfo->min_DCT_scaled_size = 2;
  172323. } else if (cinfo->scale_num * 2 <= cinfo->scale_denom) {
  172324. /* Provide 1/2 scaling */
  172325. cinfo->output_width = (JDIMENSION)
  172326. jdiv_round_up((long) cinfo->image_width, 2L);
  172327. cinfo->output_height = (JDIMENSION)
  172328. jdiv_round_up((long) cinfo->image_height, 2L);
  172329. cinfo->min_DCT_scaled_size = 4;
  172330. } else {
  172331. /* Provide 1/1 scaling */
  172332. cinfo->output_width = cinfo->image_width;
  172333. cinfo->output_height = cinfo->image_height;
  172334. cinfo->min_DCT_scaled_size = DCTSIZE;
  172335. }
  172336. /* In selecting the actual DCT scaling for each component, we try to
  172337. * scale up the chroma components via IDCT scaling rather than upsampling.
  172338. * This saves time if the upsampler gets to use 1:1 scaling.
  172339. * Note this code assumes that the supported DCT scalings are powers of 2.
  172340. */
  172341. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  172342. ci++, compptr++) {
  172343. int ssize = cinfo->min_DCT_scaled_size;
  172344. while (ssize < DCTSIZE &&
  172345. (compptr->h_samp_factor * ssize * 2 <=
  172346. cinfo->max_h_samp_factor * cinfo->min_DCT_scaled_size) &&
  172347. (compptr->v_samp_factor * ssize * 2 <=
  172348. cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size)) {
  172349. ssize = ssize * 2;
  172350. }
  172351. compptr->DCT_scaled_size = ssize;
  172352. }
  172353. /* Recompute downsampled dimensions of components;
  172354. * application needs to know these if using raw downsampled data.
  172355. */
  172356. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  172357. ci++, compptr++) {
  172358. /* Size in samples, after IDCT scaling */
  172359. compptr->downsampled_width = (JDIMENSION)
  172360. jdiv_round_up((long) cinfo->image_width *
  172361. (long) (compptr->h_samp_factor * compptr->DCT_scaled_size),
  172362. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  172363. compptr->downsampled_height = (JDIMENSION)
  172364. jdiv_round_up((long) cinfo->image_height *
  172365. (long) (compptr->v_samp_factor * compptr->DCT_scaled_size),
  172366. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  172367. }
  172368. #else /* !IDCT_SCALING_SUPPORTED */
  172369. /* Hardwire it to "no scaling" */
  172370. cinfo->output_width = cinfo->image_width;
  172371. cinfo->output_height = cinfo->image_height;
  172372. /* jdinput.c has already initialized DCT_scaled_size to DCTSIZE,
  172373. * and has computed unscaled downsampled_width and downsampled_height.
  172374. */
  172375. #endif /* IDCT_SCALING_SUPPORTED */
  172376. /* Report number of components in selected colorspace. */
  172377. /* Probably this should be in the color conversion module... */
  172378. switch (cinfo->out_color_space) {
  172379. case JCS_GRAYSCALE:
  172380. cinfo->out_color_components = 1;
  172381. break;
  172382. case JCS_RGB:
  172383. #if RGB_PIXELSIZE != 3
  172384. cinfo->out_color_components = RGB_PIXELSIZE;
  172385. break;
  172386. #endif /* else share code with YCbCr */
  172387. case JCS_YCbCr:
  172388. cinfo->out_color_components = 3;
  172389. break;
  172390. case JCS_CMYK:
  172391. case JCS_YCCK:
  172392. cinfo->out_color_components = 4;
  172393. break;
  172394. default: /* else must be same colorspace as in file */
  172395. cinfo->out_color_components = cinfo->num_components;
  172396. break;
  172397. }
  172398. cinfo->output_components = (cinfo->quantize_colors ? 1 :
  172399. cinfo->out_color_components);
  172400. /* See if upsampler will want to emit more than one row at a time */
  172401. if (use_merged_upsample(cinfo))
  172402. cinfo->rec_outbuf_height = cinfo->max_v_samp_factor;
  172403. else
  172404. cinfo->rec_outbuf_height = 1;
  172405. }
  172406. /*
  172407. * Several decompression processes need to range-limit values to the range
  172408. * 0..MAXJSAMPLE; the input value may fall somewhat outside this range
  172409. * due to noise introduced by quantization, roundoff error, etc. These
  172410. * processes are inner loops and need to be as fast as possible. On most
  172411. * machines, particularly CPUs with pipelines or instruction prefetch,
  172412. * a (subscript-check-less) C table lookup
  172413. * x = sample_range_limit[x];
  172414. * is faster than explicit tests
  172415. * if (x < 0) x = 0;
  172416. * else if (x > MAXJSAMPLE) x = MAXJSAMPLE;
  172417. * These processes all use a common table prepared by the routine below.
  172418. *
  172419. * For most steps we can mathematically guarantee that the initial value
  172420. * of x is within MAXJSAMPLE+1 of the legal range, so a table running from
  172421. * -(MAXJSAMPLE+1) to 2*MAXJSAMPLE+1 is sufficient. But for the initial
  172422. * limiting step (just after the IDCT), a wildly out-of-range value is
  172423. * possible if the input data is corrupt. To avoid any chance of indexing
  172424. * off the end of memory and getting a bad-pointer trap, we perform the
  172425. * post-IDCT limiting thus:
  172426. * x = range_limit[x & MASK];
  172427. * where MASK is 2 bits wider than legal sample data, ie 10 bits for 8-bit
  172428. * samples. Under normal circumstances this is more than enough range and
  172429. * a correct output will be generated; with bogus input data the mask will
  172430. * cause wraparound, and we will safely generate a bogus-but-in-range output.
  172431. * For the post-IDCT step, we want to convert the data from signed to unsigned
  172432. * representation by adding CENTERJSAMPLE at the same time that we limit it.
  172433. * So the post-IDCT limiting table ends up looking like this:
  172434. * CENTERJSAMPLE,CENTERJSAMPLE+1,...,MAXJSAMPLE,
  172435. * MAXJSAMPLE (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  172436. * 0 (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  172437. * 0,1,...,CENTERJSAMPLE-1
  172438. * Negative inputs select values from the upper half of the table after
  172439. * masking.
  172440. *
  172441. * We can save some space by overlapping the start of the post-IDCT table
  172442. * with the simpler range limiting table. The post-IDCT table begins at
  172443. * sample_range_limit + CENTERJSAMPLE.
  172444. *
  172445. * Note that the table is allocated in near data space on PCs; it's small
  172446. * enough and used often enough to justify this.
  172447. */
  172448. LOCAL(void)
  172449. prepare_range_limit_table (j_decompress_ptr cinfo)
  172450. /* Allocate and fill in the sample_range_limit table */
  172451. {
  172452. JSAMPLE * table;
  172453. int i;
  172454. table = (JSAMPLE *)
  172455. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172456. (5 * (MAXJSAMPLE+1) + CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  172457. table += (MAXJSAMPLE+1); /* allow negative subscripts of simple table */
  172458. cinfo->sample_range_limit = table;
  172459. /* First segment of "simple" table: limit[x] = 0 for x < 0 */
  172460. MEMZERO(table - (MAXJSAMPLE+1), (MAXJSAMPLE+1) * SIZEOF(JSAMPLE));
  172461. /* Main part of "simple" table: limit[x] = x */
  172462. for (i = 0; i <= MAXJSAMPLE; i++)
  172463. table[i] = (JSAMPLE) i;
  172464. table += CENTERJSAMPLE; /* Point to where post-IDCT table starts */
  172465. /* End of simple table, rest of first half of post-IDCT table */
  172466. for (i = CENTERJSAMPLE; i < 2*(MAXJSAMPLE+1); i++)
  172467. table[i] = MAXJSAMPLE;
  172468. /* Second half of post-IDCT table */
  172469. MEMZERO(table + (2 * (MAXJSAMPLE+1)),
  172470. (2 * (MAXJSAMPLE+1) - CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  172471. MEMCOPY(table + (4 * (MAXJSAMPLE+1) - CENTERJSAMPLE),
  172472. cinfo->sample_range_limit, CENTERJSAMPLE * SIZEOF(JSAMPLE));
  172473. }
  172474. /*
  172475. * Master selection of decompression modules.
  172476. * This is done once at jpeg_start_decompress time. We determine
  172477. * which modules will be used and give them appropriate initialization calls.
  172478. * We also initialize the decompressor input side to begin consuming data.
  172479. *
  172480. * Since jpeg_read_header has finished, we know what is in the SOF
  172481. * and (first) SOS markers. We also have all the application parameter
  172482. * settings.
  172483. */
  172484. LOCAL(void)
  172485. master_selection (j_decompress_ptr cinfo)
  172486. {
  172487. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172488. boolean use_c_buffer;
  172489. long samplesperrow;
  172490. JDIMENSION jd_samplesperrow;
  172491. /* Initialize dimensions and other stuff */
  172492. jpeg_calc_output_dimensions(cinfo);
  172493. prepare_range_limit_table(cinfo);
  172494. /* Width of an output scanline must be representable as JDIMENSION. */
  172495. samplesperrow = (long) cinfo->output_width * (long) cinfo->out_color_components;
  172496. jd_samplesperrow = (JDIMENSION) samplesperrow;
  172497. if ((long) jd_samplesperrow != samplesperrow)
  172498. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  172499. /* Initialize my private state */
  172500. master->pass_number = 0;
  172501. master->using_merged_upsample = use_merged_upsample(cinfo);
  172502. /* Color quantizer selection */
  172503. master->quantizer_1pass = NULL;
  172504. master->quantizer_2pass = NULL;
  172505. /* No mode changes if not using buffered-image mode. */
  172506. if (! cinfo->quantize_colors || ! cinfo->buffered_image) {
  172507. cinfo->enable_1pass_quant = FALSE;
  172508. cinfo->enable_external_quant = FALSE;
  172509. cinfo->enable_2pass_quant = FALSE;
  172510. }
  172511. if (cinfo->quantize_colors) {
  172512. if (cinfo->raw_data_out)
  172513. ERREXIT(cinfo, JERR_NOTIMPL);
  172514. /* 2-pass quantizer only works in 3-component color space. */
  172515. if (cinfo->out_color_components != 3) {
  172516. cinfo->enable_1pass_quant = TRUE;
  172517. cinfo->enable_external_quant = FALSE;
  172518. cinfo->enable_2pass_quant = FALSE;
  172519. cinfo->colormap = NULL;
  172520. } else if (cinfo->colormap != NULL) {
  172521. cinfo->enable_external_quant = TRUE;
  172522. } else if (cinfo->two_pass_quantize) {
  172523. cinfo->enable_2pass_quant = TRUE;
  172524. } else {
  172525. cinfo->enable_1pass_quant = TRUE;
  172526. }
  172527. if (cinfo->enable_1pass_quant) {
  172528. #ifdef QUANT_1PASS_SUPPORTED
  172529. jinit_1pass_quantizer(cinfo);
  172530. master->quantizer_1pass = cinfo->cquantize;
  172531. #else
  172532. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172533. #endif
  172534. }
  172535. /* We use the 2-pass code to map to external colormaps. */
  172536. if (cinfo->enable_2pass_quant || cinfo->enable_external_quant) {
  172537. #ifdef QUANT_2PASS_SUPPORTED
  172538. jinit_2pass_quantizer(cinfo);
  172539. master->quantizer_2pass = cinfo->cquantize;
  172540. #else
  172541. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172542. #endif
  172543. }
  172544. /* If both quantizers are initialized, the 2-pass one is left active;
  172545. * this is necessary for starting with quantization to an external map.
  172546. */
  172547. }
  172548. /* Post-processing: in particular, color conversion first */
  172549. if (! cinfo->raw_data_out) {
  172550. if (master->using_merged_upsample) {
  172551. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172552. jinit_merged_upsampler(cinfo); /* does color conversion too */
  172553. #else
  172554. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172555. #endif
  172556. } else {
  172557. jinit_color_deconverter(cinfo);
  172558. jinit_upsampler(cinfo);
  172559. }
  172560. jinit_d_post_controller(cinfo, cinfo->enable_2pass_quant);
  172561. }
  172562. /* Inverse DCT */
  172563. jinit_inverse_dct(cinfo);
  172564. /* Entropy decoding: either Huffman or arithmetic coding. */
  172565. if (cinfo->arith_code) {
  172566. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  172567. } else {
  172568. if (cinfo->progressive_mode) {
  172569. #ifdef D_PROGRESSIVE_SUPPORTED
  172570. jinit_phuff_decoder(cinfo);
  172571. #else
  172572. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172573. #endif
  172574. } else
  172575. jinit_huff_decoder(cinfo);
  172576. }
  172577. /* Initialize principal buffer controllers. */
  172578. use_c_buffer = cinfo->inputctl->has_multiple_scans || cinfo->buffered_image;
  172579. jinit_d_coef_controller(cinfo, use_c_buffer);
  172580. if (! cinfo->raw_data_out)
  172581. jinit_d_main_controller(cinfo, FALSE /* never need full buffer here */);
  172582. /* We can now tell the memory manager to allocate virtual arrays. */
  172583. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  172584. /* Initialize input side of decompressor to consume first scan. */
  172585. (*cinfo->inputctl->start_input_pass) (cinfo);
  172586. #ifdef D_MULTISCAN_FILES_SUPPORTED
  172587. /* If jpeg_start_decompress will read the whole file, initialize
  172588. * progress monitoring appropriately. The input step is counted
  172589. * as one pass.
  172590. */
  172591. if (cinfo->progress != NULL && ! cinfo->buffered_image &&
  172592. cinfo->inputctl->has_multiple_scans) {
  172593. int nscans;
  172594. /* Estimate number of scans to set pass_limit. */
  172595. if (cinfo->progressive_mode) {
  172596. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  172597. nscans = 2 + 3 * cinfo->num_components;
  172598. } else {
  172599. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  172600. nscans = cinfo->num_components;
  172601. }
  172602. cinfo->progress->pass_counter = 0L;
  172603. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  172604. cinfo->progress->completed_passes = 0;
  172605. cinfo->progress->total_passes = (cinfo->enable_2pass_quant ? 3 : 2);
  172606. /* Count the input pass as done */
  172607. master->pass_number++;
  172608. }
  172609. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  172610. }
  172611. /*
  172612. * Per-pass setup.
  172613. * This is called at the beginning of each output pass. We determine which
  172614. * modules will be active during this pass and give them appropriate
  172615. * start_pass calls. We also set is_dummy_pass to indicate whether this
  172616. * is a "real" output pass or a dummy pass for color quantization.
  172617. * (In the latter case, jdapistd.c will crank the pass to completion.)
  172618. */
  172619. METHODDEF(void)
  172620. prepare_for_output_pass (j_decompress_ptr cinfo)
  172621. {
  172622. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172623. if (master->pub.is_dummy_pass) {
  172624. #ifdef QUANT_2PASS_SUPPORTED
  172625. /* Final pass of 2-pass quantization */
  172626. master->pub.is_dummy_pass = FALSE;
  172627. (*cinfo->cquantize->start_pass) (cinfo, FALSE);
  172628. (*cinfo->post->start_pass) (cinfo, JBUF_CRANK_DEST);
  172629. (*cinfo->main->start_pass) (cinfo, JBUF_CRANK_DEST);
  172630. #else
  172631. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172632. #endif /* QUANT_2PASS_SUPPORTED */
  172633. } else {
  172634. if (cinfo->quantize_colors && cinfo->colormap == NULL) {
  172635. /* Select new quantization method */
  172636. if (cinfo->two_pass_quantize && cinfo->enable_2pass_quant) {
  172637. cinfo->cquantize = master->quantizer_2pass;
  172638. master->pub.is_dummy_pass = TRUE;
  172639. } else if (cinfo->enable_1pass_quant) {
  172640. cinfo->cquantize = master->quantizer_1pass;
  172641. } else {
  172642. ERREXIT(cinfo, JERR_MODE_CHANGE);
  172643. }
  172644. }
  172645. (*cinfo->idct->start_pass) (cinfo);
  172646. (*cinfo->coef->start_output_pass) (cinfo);
  172647. if (! cinfo->raw_data_out) {
  172648. if (! master->using_merged_upsample)
  172649. (*cinfo->cconvert->start_pass) (cinfo);
  172650. (*cinfo->upsample->start_pass) (cinfo);
  172651. if (cinfo->quantize_colors)
  172652. (*cinfo->cquantize->start_pass) (cinfo, master->pub.is_dummy_pass);
  172653. (*cinfo->post->start_pass) (cinfo,
  172654. (master->pub.is_dummy_pass ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  172655. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  172656. }
  172657. }
  172658. /* Set up progress monitor's pass info if present */
  172659. if (cinfo->progress != NULL) {
  172660. cinfo->progress->completed_passes = master->pass_number;
  172661. cinfo->progress->total_passes = master->pass_number +
  172662. (master->pub.is_dummy_pass ? 2 : 1);
  172663. /* In buffered-image mode, we assume one more output pass if EOI not
  172664. * yet reached, but no more passes if EOI has been reached.
  172665. */
  172666. if (cinfo->buffered_image && ! cinfo->inputctl->eoi_reached) {
  172667. cinfo->progress->total_passes += (cinfo->enable_2pass_quant ? 2 : 1);
  172668. }
  172669. }
  172670. }
  172671. /*
  172672. * Finish up at end of an output pass.
  172673. */
  172674. METHODDEF(void)
  172675. finish_output_pass (j_decompress_ptr cinfo)
  172676. {
  172677. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172678. if (cinfo->quantize_colors)
  172679. (*cinfo->cquantize->finish_pass) (cinfo);
  172680. master->pass_number++;
  172681. }
  172682. #ifdef D_MULTISCAN_FILES_SUPPORTED
  172683. /*
  172684. * Switch to a new external colormap between output passes.
  172685. */
  172686. GLOBAL(void)
  172687. jpeg_new_colormap (j_decompress_ptr cinfo)
  172688. {
  172689. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172690. /* Prevent application from calling me at wrong times */
  172691. if (cinfo->global_state != DSTATE_BUFIMAGE)
  172692. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  172693. if (cinfo->quantize_colors && cinfo->enable_external_quant &&
  172694. cinfo->colormap != NULL) {
  172695. /* Select 2-pass quantizer for external colormap use */
  172696. cinfo->cquantize = master->quantizer_2pass;
  172697. /* Notify quantizer of colormap change */
  172698. (*cinfo->cquantize->new_color_map) (cinfo);
  172699. master->pub.is_dummy_pass = FALSE; /* just in case */
  172700. } else
  172701. ERREXIT(cinfo, JERR_MODE_CHANGE);
  172702. }
  172703. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  172704. /*
  172705. * Initialize master decompression control and select active modules.
  172706. * This is performed at the start of jpeg_start_decompress.
  172707. */
  172708. GLOBAL(void)
  172709. jinit_master_decompress (j_decompress_ptr cinfo)
  172710. {
  172711. my_master_ptr6 master;
  172712. master = (my_master_ptr6)
  172713. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172714. SIZEOF(my_decomp_master));
  172715. cinfo->master = (struct jpeg_decomp_master *) master;
  172716. master->pub.prepare_for_output_pass = prepare_for_output_pass;
  172717. master->pub.finish_output_pass = finish_output_pass;
  172718. master->pub.is_dummy_pass = FALSE;
  172719. master_selection(cinfo);
  172720. }
  172721. /*** End of inlined file: jdmaster.c ***/
  172722. #undef FIX
  172723. /*** Start of inlined file: jdmerge.c ***/
  172724. #define JPEG_INTERNALS
  172725. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172726. /* Private subobject */
  172727. typedef struct {
  172728. struct jpeg_upsampler pub; /* public fields */
  172729. /* Pointer to routine to do actual upsampling/conversion of one row group */
  172730. JMETHOD(void, upmethod, (j_decompress_ptr cinfo,
  172731. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172732. JSAMPARRAY output_buf));
  172733. /* Private state for YCC->RGB conversion */
  172734. int * Cr_r_tab; /* => table for Cr to R conversion */
  172735. int * Cb_b_tab; /* => table for Cb to B conversion */
  172736. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  172737. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  172738. /* For 2:1 vertical sampling, we produce two output rows at a time.
  172739. * We need a "spare" row buffer to hold the second output row if the
  172740. * application provides just a one-row buffer; we also use the spare
  172741. * to discard the dummy last row if the image height is odd.
  172742. */
  172743. JSAMPROW spare_row;
  172744. boolean spare_full; /* T if spare buffer is occupied */
  172745. JDIMENSION out_row_width; /* samples per output row */
  172746. JDIMENSION rows_to_go; /* counts rows remaining in image */
  172747. } my_upsampler;
  172748. typedef my_upsampler * my_upsample_ptr;
  172749. #define SCALEBITS 16 /* speediest right-shift on some machines */
  172750. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  172751. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  172752. /*
  172753. * Initialize tables for YCC->RGB colorspace conversion.
  172754. * This is taken directly from jdcolor.c; see that file for more info.
  172755. */
  172756. LOCAL(void)
  172757. build_ycc_rgb_table2 (j_decompress_ptr cinfo)
  172758. {
  172759. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172760. int i;
  172761. INT32 x;
  172762. SHIFT_TEMPS
  172763. upsample->Cr_r_tab = (int *)
  172764. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172765. (MAXJSAMPLE+1) * SIZEOF(int));
  172766. upsample->Cb_b_tab = (int *)
  172767. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172768. (MAXJSAMPLE+1) * SIZEOF(int));
  172769. upsample->Cr_g_tab = (INT32 *)
  172770. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172771. (MAXJSAMPLE+1) * SIZEOF(INT32));
  172772. upsample->Cb_g_tab = (INT32 *)
  172773. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172774. (MAXJSAMPLE+1) * SIZEOF(INT32));
  172775. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  172776. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  172777. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  172778. /* Cr=>R value is nearest int to 1.40200 * x */
  172779. upsample->Cr_r_tab[i] = (int)
  172780. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  172781. /* Cb=>B value is nearest int to 1.77200 * x */
  172782. upsample->Cb_b_tab[i] = (int)
  172783. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  172784. /* Cr=>G value is scaled-up -0.71414 * x */
  172785. upsample->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  172786. /* Cb=>G value is scaled-up -0.34414 * x */
  172787. /* We also add in ONE_HALF so that need not do it in inner loop */
  172788. upsample->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  172789. }
  172790. }
  172791. /*
  172792. * Initialize for an upsampling pass.
  172793. */
  172794. METHODDEF(void)
  172795. start_pass_merged_upsample (j_decompress_ptr cinfo)
  172796. {
  172797. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172798. /* Mark the spare buffer empty */
  172799. upsample->spare_full = FALSE;
  172800. /* Initialize total-height counter for detecting bottom of image */
  172801. upsample->rows_to_go = cinfo->output_height;
  172802. }
  172803. /*
  172804. * Control routine to do upsampling (and color conversion).
  172805. *
  172806. * The control routine just handles the row buffering considerations.
  172807. */
  172808. METHODDEF(void)
  172809. merged_2v_upsample (j_decompress_ptr cinfo,
  172810. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172811. JDIMENSION,
  172812. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172813. JDIMENSION out_rows_avail)
  172814. /* 2:1 vertical sampling case: may need a spare row. */
  172815. {
  172816. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172817. JSAMPROW work_ptrs[2];
  172818. JDIMENSION num_rows; /* number of rows returned to caller */
  172819. if (upsample->spare_full) {
  172820. /* If we have a spare row saved from a previous cycle, just return it. */
  172821. jcopy_sample_rows(& upsample->spare_row, 0, output_buf + *out_row_ctr, 0,
  172822. 1, upsample->out_row_width);
  172823. num_rows = 1;
  172824. upsample->spare_full = FALSE;
  172825. } else {
  172826. /* Figure number of rows to return to caller. */
  172827. num_rows = 2;
  172828. /* Not more than the distance to the end of the image. */
  172829. if (num_rows > upsample->rows_to_go)
  172830. num_rows = upsample->rows_to_go;
  172831. /* And not more than what the client can accept: */
  172832. out_rows_avail -= *out_row_ctr;
  172833. if (num_rows > out_rows_avail)
  172834. num_rows = out_rows_avail;
  172835. /* Create output pointer array for upsampler. */
  172836. work_ptrs[0] = output_buf[*out_row_ctr];
  172837. if (num_rows > 1) {
  172838. work_ptrs[1] = output_buf[*out_row_ctr + 1];
  172839. } else {
  172840. work_ptrs[1] = upsample->spare_row;
  172841. upsample->spare_full = TRUE;
  172842. }
  172843. /* Now do the upsampling. */
  172844. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr, work_ptrs);
  172845. }
  172846. /* Adjust counts */
  172847. *out_row_ctr += num_rows;
  172848. upsample->rows_to_go -= num_rows;
  172849. /* When the buffer is emptied, declare this input row group consumed */
  172850. if (! upsample->spare_full)
  172851. (*in_row_group_ctr)++;
  172852. }
  172853. METHODDEF(void)
  172854. merged_1v_upsample (j_decompress_ptr cinfo,
  172855. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172856. JDIMENSION,
  172857. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172858. JDIMENSION)
  172859. /* 1:1 vertical sampling case: much easier, never need a spare row. */
  172860. {
  172861. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172862. /* Just do the upsampling. */
  172863. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr,
  172864. output_buf + *out_row_ctr);
  172865. /* Adjust counts */
  172866. (*out_row_ctr)++;
  172867. (*in_row_group_ctr)++;
  172868. }
  172869. /*
  172870. * These are the routines invoked by the control routines to do
  172871. * the actual upsampling/conversion. One row group is processed per call.
  172872. *
  172873. * Note: since we may be writing directly into application-supplied buffers,
  172874. * we have to be honest about the output width; we can't assume the buffer
  172875. * has been rounded up to an even width.
  172876. */
  172877. /*
  172878. * Upsample and color convert for the case of 2:1 horizontal and 1:1 vertical.
  172879. */
  172880. METHODDEF(void)
  172881. h2v1_merged_upsample (j_decompress_ptr cinfo,
  172882. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172883. JSAMPARRAY output_buf)
  172884. {
  172885. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172886. register int y, cred, cgreen, cblue;
  172887. int cb, cr;
  172888. register JSAMPROW outptr;
  172889. JSAMPROW inptr0, inptr1, inptr2;
  172890. JDIMENSION col;
  172891. /* copy these pointers into registers if possible */
  172892. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  172893. int * Crrtab = upsample->Cr_r_tab;
  172894. int * Cbbtab = upsample->Cb_b_tab;
  172895. INT32 * Crgtab = upsample->Cr_g_tab;
  172896. INT32 * Cbgtab = upsample->Cb_g_tab;
  172897. SHIFT_TEMPS
  172898. inptr0 = input_buf[0][in_row_group_ctr];
  172899. inptr1 = input_buf[1][in_row_group_ctr];
  172900. inptr2 = input_buf[2][in_row_group_ctr];
  172901. outptr = output_buf[0];
  172902. /* Loop for each pair of output pixels */
  172903. for (col = cinfo->output_width >> 1; col > 0; col--) {
  172904. /* Do the chroma part of the calculation */
  172905. cb = GETJSAMPLE(*inptr1++);
  172906. cr = GETJSAMPLE(*inptr2++);
  172907. cred = Crrtab[cr];
  172908. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172909. cblue = Cbbtab[cb];
  172910. /* Fetch 2 Y values and emit 2 pixels */
  172911. y = GETJSAMPLE(*inptr0++);
  172912. outptr[RGB_RED] = range_limit[y + cred];
  172913. outptr[RGB_GREEN] = range_limit[y + cgreen];
  172914. outptr[RGB_BLUE] = range_limit[y + cblue];
  172915. outptr += RGB_PIXELSIZE;
  172916. y = GETJSAMPLE(*inptr0++);
  172917. outptr[RGB_RED] = range_limit[y + cred];
  172918. outptr[RGB_GREEN] = range_limit[y + cgreen];
  172919. outptr[RGB_BLUE] = range_limit[y + cblue];
  172920. outptr += RGB_PIXELSIZE;
  172921. }
  172922. /* If image width is odd, do the last output column separately */
  172923. if (cinfo->output_width & 1) {
  172924. cb = GETJSAMPLE(*inptr1);
  172925. cr = GETJSAMPLE(*inptr2);
  172926. cred = Crrtab[cr];
  172927. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172928. cblue = Cbbtab[cb];
  172929. y = GETJSAMPLE(*inptr0);
  172930. outptr[RGB_RED] = range_limit[y + cred];
  172931. outptr[RGB_GREEN] = range_limit[y + cgreen];
  172932. outptr[RGB_BLUE] = range_limit[y + cblue];
  172933. }
  172934. }
  172935. /*
  172936. * Upsample and color convert for the case of 2:1 horizontal and 2:1 vertical.
  172937. */
  172938. METHODDEF(void)
  172939. h2v2_merged_upsample (j_decompress_ptr cinfo,
  172940. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172941. JSAMPARRAY output_buf)
  172942. {
  172943. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172944. register int y, cred, cgreen, cblue;
  172945. int cb, cr;
  172946. register JSAMPROW outptr0, outptr1;
  172947. JSAMPROW inptr00, inptr01, inptr1, inptr2;
  172948. JDIMENSION col;
  172949. /* copy these pointers into registers if possible */
  172950. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  172951. int * Crrtab = upsample->Cr_r_tab;
  172952. int * Cbbtab = upsample->Cb_b_tab;
  172953. INT32 * Crgtab = upsample->Cr_g_tab;
  172954. INT32 * Cbgtab = upsample->Cb_g_tab;
  172955. SHIFT_TEMPS
  172956. inptr00 = input_buf[0][in_row_group_ctr*2];
  172957. inptr01 = input_buf[0][in_row_group_ctr*2 + 1];
  172958. inptr1 = input_buf[1][in_row_group_ctr];
  172959. inptr2 = input_buf[2][in_row_group_ctr];
  172960. outptr0 = output_buf[0];
  172961. outptr1 = output_buf[1];
  172962. /* Loop for each group of output pixels */
  172963. for (col = cinfo->output_width >> 1; col > 0; col--) {
  172964. /* Do the chroma part of the calculation */
  172965. cb = GETJSAMPLE(*inptr1++);
  172966. cr = GETJSAMPLE(*inptr2++);
  172967. cred = Crrtab[cr];
  172968. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172969. cblue = Cbbtab[cb];
  172970. /* Fetch 4 Y values and emit 4 pixels */
  172971. y = GETJSAMPLE(*inptr00++);
  172972. outptr0[RGB_RED] = range_limit[y + cred];
  172973. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  172974. outptr0[RGB_BLUE] = range_limit[y + cblue];
  172975. outptr0 += RGB_PIXELSIZE;
  172976. y = GETJSAMPLE(*inptr00++);
  172977. outptr0[RGB_RED] = range_limit[y + cred];
  172978. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  172979. outptr0[RGB_BLUE] = range_limit[y + cblue];
  172980. outptr0 += RGB_PIXELSIZE;
  172981. y = GETJSAMPLE(*inptr01++);
  172982. outptr1[RGB_RED] = range_limit[y + cred];
  172983. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  172984. outptr1[RGB_BLUE] = range_limit[y + cblue];
  172985. outptr1 += RGB_PIXELSIZE;
  172986. y = GETJSAMPLE(*inptr01++);
  172987. outptr1[RGB_RED] = range_limit[y + cred];
  172988. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  172989. outptr1[RGB_BLUE] = range_limit[y + cblue];
  172990. outptr1 += RGB_PIXELSIZE;
  172991. }
  172992. /* If image width is odd, do the last output column separately */
  172993. if (cinfo->output_width & 1) {
  172994. cb = GETJSAMPLE(*inptr1);
  172995. cr = GETJSAMPLE(*inptr2);
  172996. cred = Crrtab[cr];
  172997. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172998. cblue = Cbbtab[cb];
  172999. y = GETJSAMPLE(*inptr00);
  173000. outptr0[RGB_RED] = range_limit[y + cred];
  173001. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  173002. outptr0[RGB_BLUE] = range_limit[y + cblue];
  173003. y = GETJSAMPLE(*inptr01);
  173004. outptr1[RGB_RED] = range_limit[y + cred];
  173005. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  173006. outptr1[RGB_BLUE] = range_limit[y + cblue];
  173007. }
  173008. }
  173009. /*
  173010. * Module initialization routine for merged upsampling/color conversion.
  173011. *
  173012. * NB: this is called under the conditions determined by use_merged_upsample()
  173013. * in jdmaster.c. That routine MUST correspond to the actual capabilities
  173014. * of this module; no safety checks are made here.
  173015. */
  173016. GLOBAL(void)
  173017. jinit_merged_upsampler (j_decompress_ptr cinfo)
  173018. {
  173019. my_upsample_ptr upsample;
  173020. upsample = (my_upsample_ptr)
  173021. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173022. SIZEOF(my_upsampler));
  173023. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  173024. upsample->pub.start_pass = start_pass_merged_upsample;
  173025. upsample->pub.need_context_rows = FALSE;
  173026. upsample->out_row_width = cinfo->output_width * cinfo->out_color_components;
  173027. if (cinfo->max_v_samp_factor == 2) {
  173028. upsample->pub.upsample = merged_2v_upsample;
  173029. upsample->upmethod = h2v2_merged_upsample;
  173030. /* Allocate a spare row buffer */
  173031. upsample->spare_row = (JSAMPROW)
  173032. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173033. (size_t) (upsample->out_row_width * SIZEOF(JSAMPLE)));
  173034. } else {
  173035. upsample->pub.upsample = merged_1v_upsample;
  173036. upsample->upmethod = h2v1_merged_upsample;
  173037. /* No spare row needed */
  173038. upsample->spare_row = NULL;
  173039. }
  173040. build_ycc_rgb_table2(cinfo);
  173041. }
  173042. #endif /* UPSAMPLE_MERGING_SUPPORTED */
  173043. /*** End of inlined file: jdmerge.c ***/
  173044. #undef ASSIGN_STATE
  173045. /*** Start of inlined file: jdphuff.c ***/
  173046. #define JPEG_INTERNALS
  173047. #ifdef D_PROGRESSIVE_SUPPORTED
  173048. /*
  173049. * Expanded entropy decoder object for progressive Huffman decoding.
  173050. *
  173051. * The savable_state subrecord contains fields that change within an MCU,
  173052. * but must not be updated permanently until we complete the MCU.
  173053. */
  173054. typedef struct {
  173055. unsigned int EOBRUN; /* remaining EOBs in EOBRUN */
  173056. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  173057. } savable_state3;
  173058. /* This macro is to work around compilers with missing or broken
  173059. * structure assignment. You'll need to fix this code if you have
  173060. * such a compiler and you change MAX_COMPS_IN_SCAN.
  173061. */
  173062. #ifndef NO_STRUCT_ASSIGN
  173063. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  173064. #else
  173065. #if MAX_COMPS_IN_SCAN == 4
  173066. #define ASSIGN_STATE(dest,src) \
  173067. ((dest).EOBRUN = (src).EOBRUN, \
  173068. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  173069. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  173070. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  173071. (dest).last_dc_val[3] = (src).last_dc_val[3])
  173072. #endif
  173073. #endif
  173074. typedef struct {
  173075. struct jpeg_entropy_decoder pub; /* public fields */
  173076. /* These fields are loaded into local variables at start of each MCU.
  173077. * In case of suspension, we exit WITHOUT updating them.
  173078. */
  173079. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  173080. savable_state3 saved; /* Other state at start of MCU */
  173081. /* These fields are NOT loaded into local working state. */
  173082. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  173083. /* Pointers to derived tables (these workspaces have image lifespan) */
  173084. d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  173085. d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
  173086. } phuff_entropy_decoder;
  173087. typedef phuff_entropy_decoder * phuff_entropy_ptr2;
  173088. /* Forward declarations */
  173089. METHODDEF(boolean) decode_mcu_DC_first JPP((j_decompress_ptr cinfo,
  173090. JBLOCKROW *MCU_data));
  173091. METHODDEF(boolean) decode_mcu_AC_first JPP((j_decompress_ptr cinfo,
  173092. JBLOCKROW *MCU_data));
  173093. METHODDEF(boolean) decode_mcu_DC_refine JPP((j_decompress_ptr cinfo,
  173094. JBLOCKROW *MCU_data));
  173095. METHODDEF(boolean) decode_mcu_AC_refine JPP((j_decompress_ptr cinfo,
  173096. JBLOCKROW *MCU_data));
  173097. /*
  173098. * Initialize for a Huffman-compressed scan.
  173099. */
  173100. METHODDEF(void)
  173101. start_pass_phuff_decoder (j_decompress_ptr cinfo)
  173102. {
  173103. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173104. boolean is_DC_band, bad;
  173105. int ci, coefi, tbl;
  173106. int *coef_bit_ptr;
  173107. jpeg_component_info * compptr;
  173108. is_DC_band = (cinfo->Ss == 0);
  173109. /* Validate scan parameters */
  173110. bad = FALSE;
  173111. if (is_DC_band) {
  173112. if (cinfo->Se != 0)
  173113. bad = TRUE;
  173114. } else {
  173115. /* need not check Ss/Se < 0 since they came from unsigned bytes */
  173116. if (cinfo->Ss > cinfo->Se || cinfo->Se >= DCTSIZE2)
  173117. bad = TRUE;
  173118. /* AC scans may have only one component */
  173119. if (cinfo->comps_in_scan != 1)
  173120. bad = TRUE;
  173121. }
  173122. if (cinfo->Ah != 0) {
  173123. /* Successive approximation refinement scan: must have Al = Ah-1. */
  173124. if (cinfo->Al != cinfo->Ah-1)
  173125. bad = TRUE;
  173126. }
  173127. if (cinfo->Al > 13) /* need not check for < 0 */
  173128. bad = TRUE;
  173129. /* Arguably the maximum Al value should be less than 13 for 8-bit precision,
  173130. * but the spec doesn't say so, and we try to be liberal about what we
  173131. * accept. Note: large Al values could result in out-of-range DC
  173132. * coefficients during early scans, leading to bizarre displays due to
  173133. * overflows in the IDCT math. But we won't crash.
  173134. */
  173135. if (bad)
  173136. ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
  173137. cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
  173138. /* Update progression status, and verify that scan order is legal.
  173139. * Note that inter-scan inconsistencies are treated as warnings
  173140. * not fatal errors ... not clear if this is right way to behave.
  173141. */
  173142. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  173143. int cindex = cinfo->cur_comp_info[ci]->component_index;
  173144. coef_bit_ptr = & cinfo->coef_bits[cindex][0];
  173145. if (!is_DC_band && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
  173146. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
  173147. for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
  173148. int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
  173149. if (cinfo->Ah != expected)
  173150. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
  173151. coef_bit_ptr[coefi] = cinfo->Al;
  173152. }
  173153. }
  173154. /* Select MCU decoding routine */
  173155. if (cinfo->Ah == 0) {
  173156. if (is_DC_band)
  173157. entropy->pub.decode_mcu = decode_mcu_DC_first;
  173158. else
  173159. entropy->pub.decode_mcu = decode_mcu_AC_first;
  173160. } else {
  173161. if (is_DC_band)
  173162. entropy->pub.decode_mcu = decode_mcu_DC_refine;
  173163. else
  173164. entropy->pub.decode_mcu = decode_mcu_AC_refine;
  173165. }
  173166. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  173167. compptr = cinfo->cur_comp_info[ci];
  173168. /* Make sure requested tables are present, and compute derived tables.
  173169. * We may build same derived table more than once, but it's not expensive.
  173170. */
  173171. if (is_DC_band) {
  173172. if (cinfo->Ah == 0) { /* DC refinement needs no table */
  173173. tbl = compptr->dc_tbl_no;
  173174. jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,
  173175. & entropy->derived_tbls[tbl]);
  173176. }
  173177. } else {
  173178. tbl = compptr->ac_tbl_no;
  173179. jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,
  173180. & entropy->derived_tbls[tbl]);
  173181. /* remember the single active table */
  173182. entropy->ac_derived_tbl = entropy->derived_tbls[tbl];
  173183. }
  173184. /* Initialize DC predictions to 0 */
  173185. entropy->saved.last_dc_val[ci] = 0;
  173186. }
  173187. /* Initialize bitread state variables */
  173188. entropy->bitstate.bits_left = 0;
  173189. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  173190. entropy->pub.insufficient_data = FALSE;
  173191. /* Initialize private state variables */
  173192. entropy->saved.EOBRUN = 0;
  173193. /* Initialize restart counter */
  173194. entropy->restarts_to_go = cinfo->restart_interval;
  173195. }
  173196. /*
  173197. * Check for a restart marker & resynchronize decoder.
  173198. * Returns FALSE if must suspend.
  173199. */
  173200. LOCAL(boolean)
  173201. process_restartp (j_decompress_ptr cinfo)
  173202. {
  173203. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173204. int ci;
  173205. /* Throw away any unused bits remaining in bit buffer; */
  173206. /* include any full bytes in next_marker's count of discarded bytes */
  173207. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  173208. entropy->bitstate.bits_left = 0;
  173209. /* Advance past the RSTn marker */
  173210. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  173211. return FALSE;
  173212. /* Re-initialize DC predictions to 0 */
  173213. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  173214. entropy->saved.last_dc_val[ci] = 0;
  173215. /* Re-init EOB run count, too */
  173216. entropy->saved.EOBRUN = 0;
  173217. /* Reset restart counter */
  173218. entropy->restarts_to_go = cinfo->restart_interval;
  173219. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  173220. * against a marker. In that case we will end up treating the next data
  173221. * segment as empty, and we can avoid producing bogus output pixels by
  173222. * leaving the flag set.
  173223. */
  173224. if (cinfo->unread_marker == 0)
  173225. entropy->pub.insufficient_data = FALSE;
  173226. return TRUE;
  173227. }
  173228. /*
  173229. * Huffman MCU decoding.
  173230. * Each of these routines decodes and returns one MCU's worth of
  173231. * Huffman-compressed coefficients.
  173232. * The coefficients are reordered from zigzag order into natural array order,
  173233. * but are not dequantized.
  173234. *
  173235. * The i'th block of the MCU is stored into the block pointed to by
  173236. * MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
  173237. *
  173238. * We return FALSE if data source requested suspension. In that case no
  173239. * changes have been made to permanent state. (Exception: some output
  173240. * coefficients may already have been assigned. This is harmless for
  173241. * spectral selection, since we'll just re-assign them on the next call.
  173242. * Successive approximation AC refinement has to be more careful, however.)
  173243. */
  173244. /*
  173245. * MCU decoding for DC initial scan (either spectral selection,
  173246. * or first pass of successive approximation).
  173247. */
  173248. METHODDEF(boolean)
  173249. decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173250. {
  173251. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173252. int Al = cinfo->Al;
  173253. register int s, r;
  173254. int blkn, ci;
  173255. JBLOCKROW block;
  173256. BITREAD_STATE_VARS;
  173257. savable_state3 state;
  173258. d_derived_tbl * tbl;
  173259. jpeg_component_info * compptr;
  173260. /* Process restart marker if needed; may have to suspend */
  173261. if (cinfo->restart_interval) {
  173262. if (entropy->restarts_to_go == 0)
  173263. if (! process_restartp(cinfo))
  173264. return FALSE;
  173265. }
  173266. /* If we've run out of data, just leave the MCU set to zeroes.
  173267. * This way, we return uniform gray for the remainder of the segment.
  173268. */
  173269. if (! entropy->pub.insufficient_data) {
  173270. /* Load up working state */
  173271. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173272. ASSIGN_STATE(state, entropy->saved);
  173273. /* Outer loop handles each block in the MCU */
  173274. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  173275. block = MCU_data[blkn];
  173276. ci = cinfo->MCU_membership[blkn];
  173277. compptr = cinfo->cur_comp_info[ci];
  173278. tbl = entropy->derived_tbls[compptr->dc_tbl_no];
  173279. /* Decode a single block's worth of coefficients */
  173280. /* Section F.2.2.1: decode the DC coefficient difference */
  173281. HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
  173282. if (s) {
  173283. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  173284. r = GET_BITS(s);
  173285. s = HUFF_EXTEND(r, s);
  173286. }
  173287. /* Convert DC difference to actual value, update last_dc_val */
  173288. s += state.last_dc_val[ci];
  173289. state.last_dc_val[ci] = s;
  173290. /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
  173291. (*block)[0] = (JCOEF) (s << Al);
  173292. }
  173293. /* Completed MCU, so update state */
  173294. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173295. ASSIGN_STATE(entropy->saved, state);
  173296. }
  173297. /* Account for restart interval (no-op if not using restarts) */
  173298. entropy->restarts_to_go--;
  173299. return TRUE;
  173300. }
  173301. /*
  173302. * MCU decoding for AC initial scan (either spectral selection,
  173303. * or first pass of successive approximation).
  173304. */
  173305. METHODDEF(boolean)
  173306. decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173307. {
  173308. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173309. int Se = cinfo->Se;
  173310. int Al = cinfo->Al;
  173311. register int s, k, r;
  173312. unsigned int EOBRUN;
  173313. JBLOCKROW block;
  173314. BITREAD_STATE_VARS;
  173315. d_derived_tbl * tbl;
  173316. /* Process restart marker if needed; may have to suspend */
  173317. if (cinfo->restart_interval) {
  173318. if (entropy->restarts_to_go == 0)
  173319. if (! process_restartp(cinfo))
  173320. return FALSE;
  173321. }
  173322. /* If we've run out of data, just leave the MCU set to zeroes.
  173323. * This way, we return uniform gray for the remainder of the segment.
  173324. */
  173325. if (! entropy->pub.insufficient_data) {
  173326. /* Load up working state.
  173327. * We can avoid loading/saving bitread state if in an EOB run.
  173328. */
  173329. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  173330. /* There is always only one block per MCU */
  173331. if (EOBRUN > 0) /* if it's a band of zeroes... */
  173332. EOBRUN--; /* ...process it now (we do nothing) */
  173333. else {
  173334. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173335. block = MCU_data[0];
  173336. tbl = entropy->ac_derived_tbl;
  173337. for (k = cinfo->Ss; k <= Se; k++) {
  173338. HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
  173339. r = s >> 4;
  173340. s &= 15;
  173341. if (s) {
  173342. k += r;
  173343. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  173344. r = GET_BITS(s);
  173345. s = HUFF_EXTEND(r, s);
  173346. /* Scale and output coefficient in natural (dezigzagged) order */
  173347. (*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al);
  173348. } else {
  173349. if (r == 15) { /* ZRL */
  173350. k += 15; /* skip 15 zeroes in band */
  173351. } else { /* EOBr, run length is 2^r + appended bits */
  173352. EOBRUN = 1 << r;
  173353. if (r) { /* EOBr, r > 0 */
  173354. CHECK_BIT_BUFFER(br_state, r, return FALSE);
  173355. r = GET_BITS(r);
  173356. EOBRUN += r;
  173357. }
  173358. EOBRUN--; /* this band is processed at this moment */
  173359. break; /* force end-of-band */
  173360. }
  173361. }
  173362. }
  173363. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173364. }
  173365. /* Completed MCU, so update state */
  173366. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  173367. }
  173368. /* Account for restart interval (no-op if not using restarts) */
  173369. entropy->restarts_to_go--;
  173370. return TRUE;
  173371. }
  173372. /*
  173373. * MCU decoding for DC successive approximation refinement scan.
  173374. * Note: we assume such scans can be multi-component, although the spec
  173375. * is not very clear on the point.
  173376. */
  173377. METHODDEF(boolean)
  173378. decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173379. {
  173380. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173381. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  173382. int blkn;
  173383. JBLOCKROW block;
  173384. BITREAD_STATE_VARS;
  173385. /* Process restart marker if needed; may have to suspend */
  173386. if (cinfo->restart_interval) {
  173387. if (entropy->restarts_to_go == 0)
  173388. if (! process_restartp(cinfo))
  173389. return FALSE;
  173390. }
  173391. /* Not worth the cycles to check insufficient_data here,
  173392. * since we will not change the data anyway if we read zeroes.
  173393. */
  173394. /* Load up working state */
  173395. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173396. /* Outer loop handles each block in the MCU */
  173397. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  173398. block = MCU_data[blkn];
  173399. /* Encoded data is simply the next bit of the two's-complement DC value */
  173400. CHECK_BIT_BUFFER(br_state, 1, return FALSE);
  173401. if (GET_BITS(1))
  173402. (*block)[0] |= p1;
  173403. /* Note: since we use |=, repeating the assignment later is safe */
  173404. }
  173405. /* Completed MCU, so update state */
  173406. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173407. /* Account for restart interval (no-op if not using restarts) */
  173408. entropy->restarts_to_go--;
  173409. return TRUE;
  173410. }
  173411. /*
  173412. * MCU decoding for AC successive approximation refinement scan.
  173413. */
  173414. METHODDEF(boolean)
  173415. decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173416. {
  173417. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173418. int Se = cinfo->Se;
  173419. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  173420. int m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */
  173421. register int s, k, r;
  173422. unsigned int EOBRUN;
  173423. JBLOCKROW block;
  173424. JCOEFPTR thiscoef;
  173425. BITREAD_STATE_VARS;
  173426. d_derived_tbl * tbl;
  173427. int num_newnz;
  173428. int newnz_pos[DCTSIZE2];
  173429. /* Process restart marker if needed; may have to suspend */
  173430. if (cinfo->restart_interval) {
  173431. if (entropy->restarts_to_go == 0)
  173432. if (! process_restartp(cinfo))
  173433. return FALSE;
  173434. }
  173435. /* If we've run out of data, don't modify the MCU.
  173436. */
  173437. if (! entropy->pub.insufficient_data) {
  173438. /* Load up working state */
  173439. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173440. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  173441. /* There is always only one block per MCU */
  173442. block = MCU_data[0];
  173443. tbl = entropy->ac_derived_tbl;
  173444. /* If we are forced to suspend, we must undo the assignments to any newly
  173445. * nonzero coefficients in the block, because otherwise we'd get confused
  173446. * next time about which coefficients were already nonzero.
  173447. * But we need not undo addition of bits to already-nonzero coefficients;
  173448. * instead, we can test the current bit to see if we already did it.
  173449. */
  173450. num_newnz = 0;
  173451. /* initialize coefficient loop counter to start of band */
  173452. k = cinfo->Ss;
  173453. if (EOBRUN == 0) {
  173454. for (; k <= Se; k++) {
  173455. HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
  173456. r = s >> 4;
  173457. s &= 15;
  173458. if (s) {
  173459. if (s != 1) /* size of new coef should always be 1 */
  173460. WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
  173461. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173462. if (GET_BITS(1))
  173463. s = p1; /* newly nonzero coef is positive */
  173464. else
  173465. s = m1; /* newly nonzero coef is negative */
  173466. } else {
  173467. if (r != 15) {
  173468. EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */
  173469. if (r) {
  173470. CHECK_BIT_BUFFER(br_state, r, goto undoit);
  173471. r = GET_BITS(r);
  173472. EOBRUN += r;
  173473. }
  173474. break; /* rest of block is handled by EOB logic */
  173475. }
  173476. /* note s = 0 for processing ZRL */
  173477. }
  173478. /* Advance over already-nonzero coefs and r still-zero coefs,
  173479. * appending correction bits to the nonzeroes. A correction bit is 1
  173480. * if the absolute value of the coefficient must be increased.
  173481. */
  173482. do {
  173483. thiscoef = *block + jpeg_natural_order[k];
  173484. if (*thiscoef != 0) {
  173485. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173486. if (GET_BITS(1)) {
  173487. if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
  173488. if (*thiscoef >= 0)
  173489. *thiscoef += p1;
  173490. else
  173491. *thiscoef += m1;
  173492. }
  173493. }
  173494. } else {
  173495. if (--r < 0)
  173496. break; /* reached target zero coefficient */
  173497. }
  173498. k++;
  173499. } while (k <= Se);
  173500. if (s) {
  173501. int pos = jpeg_natural_order[k];
  173502. /* Output newly nonzero coefficient */
  173503. (*block)[pos] = (JCOEF) s;
  173504. /* Remember its position in case we have to suspend */
  173505. newnz_pos[num_newnz++] = pos;
  173506. }
  173507. }
  173508. }
  173509. if (EOBRUN > 0) {
  173510. /* Scan any remaining coefficient positions after the end-of-band
  173511. * (the last newly nonzero coefficient, if any). Append a correction
  173512. * bit to each already-nonzero coefficient. A correction bit is 1
  173513. * if the absolute value of the coefficient must be increased.
  173514. */
  173515. for (; k <= Se; k++) {
  173516. thiscoef = *block + jpeg_natural_order[k];
  173517. if (*thiscoef != 0) {
  173518. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173519. if (GET_BITS(1)) {
  173520. if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
  173521. if (*thiscoef >= 0)
  173522. *thiscoef += p1;
  173523. else
  173524. *thiscoef += m1;
  173525. }
  173526. }
  173527. }
  173528. }
  173529. /* Count one block completed in EOB run */
  173530. EOBRUN--;
  173531. }
  173532. /* Completed MCU, so update state */
  173533. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173534. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  173535. }
  173536. /* Account for restart interval (no-op if not using restarts) */
  173537. entropy->restarts_to_go--;
  173538. return TRUE;
  173539. undoit:
  173540. /* Re-zero any output coefficients that we made newly nonzero */
  173541. while (num_newnz > 0)
  173542. (*block)[newnz_pos[--num_newnz]] = 0;
  173543. return FALSE;
  173544. }
  173545. /*
  173546. * Module initialization routine for progressive Huffman entropy decoding.
  173547. */
  173548. GLOBAL(void)
  173549. jinit_phuff_decoder (j_decompress_ptr cinfo)
  173550. {
  173551. phuff_entropy_ptr2 entropy;
  173552. int *coef_bit_ptr;
  173553. int ci, i;
  173554. entropy = (phuff_entropy_ptr2)
  173555. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173556. SIZEOF(phuff_entropy_decoder));
  173557. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  173558. entropy->pub.start_pass = start_pass_phuff_decoder;
  173559. /* Mark derived tables unallocated */
  173560. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  173561. entropy->derived_tbls[i] = NULL;
  173562. }
  173563. /* Create progression status table */
  173564. cinfo->coef_bits = (int (*)[DCTSIZE2])
  173565. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173566. cinfo->num_components*DCTSIZE2*SIZEOF(int));
  173567. coef_bit_ptr = & cinfo->coef_bits[0][0];
  173568. for (ci = 0; ci < cinfo->num_components; ci++)
  173569. for (i = 0; i < DCTSIZE2; i++)
  173570. *coef_bit_ptr++ = -1;
  173571. }
  173572. #endif /* D_PROGRESSIVE_SUPPORTED */
  173573. /*** End of inlined file: jdphuff.c ***/
  173574. /*** Start of inlined file: jdpostct.c ***/
  173575. #define JPEG_INTERNALS
  173576. /* Private buffer controller object */
  173577. typedef struct {
  173578. struct jpeg_d_post_controller pub; /* public fields */
  173579. /* Color quantization source buffer: this holds output data from
  173580. * the upsample/color conversion step to be passed to the quantizer.
  173581. * For two-pass color quantization, we need a full-image buffer;
  173582. * for one-pass operation, a strip buffer is sufficient.
  173583. */
  173584. jvirt_sarray_ptr whole_image; /* virtual array, or NULL if one-pass */
  173585. JSAMPARRAY buffer; /* strip buffer, or current strip of virtual */
  173586. JDIMENSION strip_height; /* buffer size in rows */
  173587. /* for two-pass mode only: */
  173588. JDIMENSION starting_row; /* row # of first row in current strip */
  173589. JDIMENSION next_row; /* index of next row to fill/empty in strip */
  173590. } my_post_controller;
  173591. typedef my_post_controller * my_post_ptr;
  173592. /* Forward declarations */
  173593. METHODDEF(void) post_process_1pass
  173594. JPP((j_decompress_ptr cinfo,
  173595. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173596. JDIMENSION in_row_groups_avail,
  173597. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173598. JDIMENSION out_rows_avail));
  173599. #ifdef QUANT_2PASS_SUPPORTED
  173600. METHODDEF(void) post_process_prepass
  173601. JPP((j_decompress_ptr cinfo,
  173602. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173603. JDIMENSION in_row_groups_avail,
  173604. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173605. JDIMENSION out_rows_avail));
  173606. METHODDEF(void) post_process_2pass
  173607. JPP((j_decompress_ptr cinfo,
  173608. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173609. JDIMENSION in_row_groups_avail,
  173610. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173611. JDIMENSION out_rows_avail));
  173612. #endif
  173613. /*
  173614. * Initialize for a processing pass.
  173615. */
  173616. METHODDEF(void)
  173617. start_pass_dpost (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  173618. {
  173619. my_post_ptr post = (my_post_ptr) cinfo->post;
  173620. switch (pass_mode) {
  173621. case JBUF_PASS_THRU:
  173622. if (cinfo->quantize_colors) {
  173623. /* Single-pass processing with color quantization. */
  173624. post->pub.post_process_data = post_process_1pass;
  173625. /* We could be doing buffered-image output before starting a 2-pass
  173626. * color quantization; in that case, jinit_d_post_controller did not
  173627. * allocate a strip buffer. Use the virtual-array buffer as workspace.
  173628. */
  173629. if (post->buffer == NULL) {
  173630. post->buffer = (*cinfo->mem->access_virt_sarray)
  173631. ((j_common_ptr) cinfo, post->whole_image,
  173632. (JDIMENSION) 0, post->strip_height, TRUE);
  173633. }
  173634. } else {
  173635. /* For single-pass processing without color quantization,
  173636. * I have no work to do; just call the upsampler directly.
  173637. */
  173638. post->pub.post_process_data = cinfo->upsample->upsample;
  173639. }
  173640. break;
  173641. #ifdef QUANT_2PASS_SUPPORTED
  173642. case JBUF_SAVE_AND_PASS:
  173643. /* First pass of 2-pass quantization */
  173644. if (post->whole_image == NULL)
  173645. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173646. post->pub.post_process_data = post_process_prepass;
  173647. break;
  173648. case JBUF_CRANK_DEST:
  173649. /* Second pass of 2-pass quantization */
  173650. if (post->whole_image == NULL)
  173651. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173652. post->pub.post_process_data = post_process_2pass;
  173653. break;
  173654. #endif /* QUANT_2PASS_SUPPORTED */
  173655. default:
  173656. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173657. break;
  173658. }
  173659. post->starting_row = post->next_row = 0;
  173660. }
  173661. /*
  173662. * Process some data in the one-pass (strip buffer) case.
  173663. * This is used for color precision reduction as well as one-pass quantization.
  173664. */
  173665. METHODDEF(void)
  173666. post_process_1pass (j_decompress_ptr cinfo,
  173667. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173668. JDIMENSION in_row_groups_avail,
  173669. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173670. JDIMENSION out_rows_avail)
  173671. {
  173672. my_post_ptr post = (my_post_ptr) cinfo->post;
  173673. JDIMENSION num_rows, max_rows;
  173674. /* Fill the buffer, but not more than what we can dump out in one go. */
  173675. /* Note we rely on the upsampler to detect bottom of image. */
  173676. max_rows = out_rows_avail - *out_row_ctr;
  173677. if (max_rows > post->strip_height)
  173678. max_rows = post->strip_height;
  173679. num_rows = 0;
  173680. (*cinfo->upsample->upsample) (cinfo,
  173681. input_buf, in_row_group_ctr, in_row_groups_avail,
  173682. post->buffer, &num_rows, max_rows);
  173683. /* Quantize and emit data. */
  173684. (*cinfo->cquantize->color_quantize) (cinfo,
  173685. post->buffer, output_buf + *out_row_ctr, (int) num_rows);
  173686. *out_row_ctr += num_rows;
  173687. }
  173688. #ifdef QUANT_2PASS_SUPPORTED
  173689. /*
  173690. * Process some data in the first pass of 2-pass quantization.
  173691. */
  173692. METHODDEF(void)
  173693. post_process_prepass (j_decompress_ptr cinfo,
  173694. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173695. JDIMENSION in_row_groups_avail,
  173696. JSAMPARRAY, JDIMENSION *out_row_ctr,
  173697. JDIMENSION)
  173698. {
  173699. my_post_ptr post = (my_post_ptr) cinfo->post;
  173700. JDIMENSION old_next_row, num_rows;
  173701. /* Reposition virtual buffer if at start of strip. */
  173702. if (post->next_row == 0) {
  173703. post->buffer = (*cinfo->mem->access_virt_sarray)
  173704. ((j_common_ptr) cinfo, post->whole_image,
  173705. post->starting_row, post->strip_height, TRUE);
  173706. }
  173707. /* Upsample some data (up to a strip height's worth). */
  173708. old_next_row = post->next_row;
  173709. (*cinfo->upsample->upsample) (cinfo,
  173710. input_buf, in_row_group_ctr, in_row_groups_avail,
  173711. post->buffer, &post->next_row, post->strip_height);
  173712. /* Allow quantizer to scan new data. No data is emitted, */
  173713. /* but we advance out_row_ctr so outer loop can tell when we're done. */
  173714. if (post->next_row > old_next_row) {
  173715. num_rows = post->next_row - old_next_row;
  173716. (*cinfo->cquantize->color_quantize) (cinfo, post->buffer + old_next_row,
  173717. (JSAMPARRAY) NULL, (int) num_rows);
  173718. *out_row_ctr += num_rows;
  173719. }
  173720. /* Advance if we filled the strip. */
  173721. if (post->next_row >= post->strip_height) {
  173722. post->starting_row += post->strip_height;
  173723. post->next_row = 0;
  173724. }
  173725. }
  173726. /*
  173727. * Process some data in the second pass of 2-pass quantization.
  173728. */
  173729. METHODDEF(void)
  173730. post_process_2pass (j_decompress_ptr cinfo,
  173731. JSAMPIMAGE, JDIMENSION *,
  173732. JDIMENSION,
  173733. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173734. JDIMENSION out_rows_avail)
  173735. {
  173736. my_post_ptr post = (my_post_ptr) cinfo->post;
  173737. JDIMENSION num_rows, max_rows;
  173738. /* Reposition virtual buffer if at start of strip. */
  173739. if (post->next_row == 0) {
  173740. post->buffer = (*cinfo->mem->access_virt_sarray)
  173741. ((j_common_ptr) cinfo, post->whole_image,
  173742. post->starting_row, post->strip_height, FALSE);
  173743. }
  173744. /* Determine number of rows to emit. */
  173745. num_rows = post->strip_height - post->next_row; /* available in strip */
  173746. max_rows = out_rows_avail - *out_row_ctr; /* available in output area */
  173747. if (num_rows > max_rows)
  173748. num_rows = max_rows;
  173749. /* We have to check bottom of image here, can't depend on upsampler. */
  173750. max_rows = cinfo->output_height - post->starting_row;
  173751. if (num_rows > max_rows)
  173752. num_rows = max_rows;
  173753. /* Quantize and emit data. */
  173754. (*cinfo->cquantize->color_quantize) (cinfo,
  173755. post->buffer + post->next_row, output_buf + *out_row_ctr,
  173756. (int) num_rows);
  173757. *out_row_ctr += num_rows;
  173758. /* Advance if we filled the strip. */
  173759. post->next_row += num_rows;
  173760. if (post->next_row >= post->strip_height) {
  173761. post->starting_row += post->strip_height;
  173762. post->next_row = 0;
  173763. }
  173764. }
  173765. #endif /* QUANT_2PASS_SUPPORTED */
  173766. /*
  173767. * Initialize postprocessing controller.
  173768. */
  173769. GLOBAL(void)
  173770. jinit_d_post_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  173771. {
  173772. my_post_ptr post;
  173773. post = (my_post_ptr)
  173774. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173775. SIZEOF(my_post_controller));
  173776. cinfo->post = (struct jpeg_d_post_controller *) post;
  173777. post->pub.start_pass = start_pass_dpost;
  173778. post->whole_image = NULL; /* flag for no virtual arrays */
  173779. post->buffer = NULL; /* flag for no strip buffer */
  173780. /* Create the quantization buffer, if needed */
  173781. if (cinfo->quantize_colors) {
  173782. /* The buffer strip height is max_v_samp_factor, which is typically
  173783. * an efficient number of rows for upsampling to return.
  173784. * (In the presence of output rescaling, we might want to be smarter?)
  173785. */
  173786. post->strip_height = (JDIMENSION) cinfo->max_v_samp_factor;
  173787. if (need_full_buffer) {
  173788. /* Two-pass color quantization: need full-image storage. */
  173789. /* We round up the number of rows to a multiple of the strip height. */
  173790. #ifdef QUANT_2PASS_SUPPORTED
  173791. post->whole_image = (*cinfo->mem->request_virt_sarray)
  173792. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  173793. cinfo->output_width * cinfo->out_color_components,
  173794. (JDIMENSION) jround_up((long) cinfo->output_height,
  173795. (long) post->strip_height),
  173796. post->strip_height);
  173797. #else
  173798. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173799. #endif /* QUANT_2PASS_SUPPORTED */
  173800. } else {
  173801. /* One-pass color quantization: just make a strip buffer. */
  173802. post->buffer = (*cinfo->mem->alloc_sarray)
  173803. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173804. cinfo->output_width * cinfo->out_color_components,
  173805. post->strip_height);
  173806. }
  173807. }
  173808. }
  173809. /*** End of inlined file: jdpostct.c ***/
  173810. #undef FIX
  173811. /*** Start of inlined file: jdsample.c ***/
  173812. #define JPEG_INTERNALS
  173813. /* Pointer to routine to upsample a single component */
  173814. typedef JMETHOD(void, upsample1_ptr,
  173815. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173816. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr));
  173817. /* Private subobject */
  173818. typedef struct {
  173819. struct jpeg_upsampler pub; /* public fields */
  173820. /* Color conversion buffer. When using separate upsampling and color
  173821. * conversion steps, this buffer holds one upsampled row group until it
  173822. * has been color converted and output.
  173823. * Note: we do not allocate any storage for component(s) which are full-size,
  173824. * ie do not need rescaling. The corresponding entry of color_buf[] is
  173825. * simply set to point to the input data array, thereby avoiding copying.
  173826. */
  173827. JSAMPARRAY color_buf[MAX_COMPONENTS];
  173828. /* Per-component upsampling method pointers */
  173829. upsample1_ptr methods[MAX_COMPONENTS];
  173830. int next_row_out; /* counts rows emitted from color_buf */
  173831. JDIMENSION rows_to_go; /* counts rows remaining in image */
  173832. /* Height of an input row group for each component. */
  173833. int rowgroup_height[MAX_COMPONENTS];
  173834. /* These arrays save pixel expansion factors so that int_expand need not
  173835. * recompute them each time. They are unused for other upsampling methods.
  173836. */
  173837. UINT8 h_expand[MAX_COMPONENTS];
  173838. UINT8 v_expand[MAX_COMPONENTS];
  173839. } my_upsampler2;
  173840. typedef my_upsampler2 * my_upsample_ptr2;
  173841. /*
  173842. * Initialize for an upsampling pass.
  173843. */
  173844. METHODDEF(void)
  173845. start_pass_upsample (j_decompress_ptr cinfo)
  173846. {
  173847. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173848. /* Mark the conversion buffer empty */
  173849. upsample->next_row_out = cinfo->max_v_samp_factor;
  173850. /* Initialize total-height counter for detecting bottom of image */
  173851. upsample->rows_to_go = cinfo->output_height;
  173852. }
  173853. /*
  173854. * Control routine to do upsampling (and color conversion).
  173855. *
  173856. * In this version we upsample each component independently.
  173857. * We upsample one row group into the conversion buffer, then apply
  173858. * color conversion a row at a time.
  173859. */
  173860. METHODDEF(void)
  173861. sep_upsample (j_decompress_ptr cinfo,
  173862. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173863. JDIMENSION,
  173864. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173865. JDIMENSION out_rows_avail)
  173866. {
  173867. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173868. int ci;
  173869. jpeg_component_info * compptr;
  173870. JDIMENSION num_rows;
  173871. /* Fill the conversion buffer, if it's empty */
  173872. if (upsample->next_row_out >= cinfo->max_v_samp_factor) {
  173873. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  173874. ci++, compptr++) {
  173875. /* Invoke per-component upsample method. Notice we pass a POINTER
  173876. * to color_buf[ci], so that fullsize_upsample can change it.
  173877. */
  173878. (*upsample->methods[ci]) (cinfo, compptr,
  173879. input_buf[ci] + (*in_row_group_ctr * upsample->rowgroup_height[ci]),
  173880. upsample->color_buf + ci);
  173881. }
  173882. upsample->next_row_out = 0;
  173883. }
  173884. /* Color-convert and emit rows */
  173885. /* How many we have in the buffer: */
  173886. num_rows = (JDIMENSION) (cinfo->max_v_samp_factor - upsample->next_row_out);
  173887. /* Not more than the distance to the end of the image. Need this test
  173888. * in case the image height is not a multiple of max_v_samp_factor:
  173889. */
  173890. if (num_rows > upsample->rows_to_go)
  173891. num_rows = upsample->rows_to_go;
  173892. /* And not more than what the client can accept: */
  173893. out_rows_avail -= *out_row_ctr;
  173894. if (num_rows > out_rows_avail)
  173895. num_rows = out_rows_avail;
  173896. (*cinfo->cconvert->color_convert) (cinfo, upsample->color_buf,
  173897. (JDIMENSION) upsample->next_row_out,
  173898. output_buf + *out_row_ctr,
  173899. (int) num_rows);
  173900. /* Adjust counts */
  173901. *out_row_ctr += num_rows;
  173902. upsample->rows_to_go -= num_rows;
  173903. upsample->next_row_out += num_rows;
  173904. /* When the buffer is emptied, declare this input row group consumed */
  173905. if (upsample->next_row_out >= cinfo->max_v_samp_factor)
  173906. (*in_row_group_ctr)++;
  173907. }
  173908. /*
  173909. * These are the routines invoked by sep_upsample to upsample pixel values
  173910. * of a single component. One row group is processed per call.
  173911. */
  173912. /*
  173913. * For full-size components, we just make color_buf[ci] point at the
  173914. * input buffer, and thus avoid copying any data. Note that this is
  173915. * safe only because sep_upsample doesn't declare the input row group
  173916. * "consumed" until we are done color converting and emitting it.
  173917. */
  173918. METHODDEF(void)
  173919. fullsize_upsample (j_decompress_ptr, jpeg_component_info *,
  173920. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173921. {
  173922. *output_data_ptr = input_data;
  173923. }
  173924. /*
  173925. * This is a no-op version used for "uninteresting" components.
  173926. * These components will not be referenced by color conversion.
  173927. */
  173928. METHODDEF(void)
  173929. noop_upsample (j_decompress_ptr, jpeg_component_info *,
  173930. JSAMPARRAY, JSAMPARRAY * output_data_ptr)
  173931. {
  173932. *output_data_ptr = NULL; /* safety check */
  173933. }
  173934. /*
  173935. * This version handles any integral sampling ratios.
  173936. * This is not used for typical JPEG files, so it need not be fast.
  173937. * Nor, for that matter, is it particularly accurate: the algorithm is
  173938. * simple replication of the input pixel onto the corresponding output
  173939. * pixels. The hi-falutin sampling literature refers to this as a
  173940. * "box filter". A box filter tends to introduce visible artifacts,
  173941. * so if you are actually going to use 3:1 or 4:1 sampling ratios
  173942. * you would be well advised to improve this code.
  173943. */
  173944. METHODDEF(void)
  173945. int_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173946. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173947. {
  173948. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173949. JSAMPARRAY output_data = *output_data_ptr;
  173950. register JSAMPROW inptr, outptr;
  173951. register JSAMPLE invalue;
  173952. register int h;
  173953. JSAMPROW outend;
  173954. int h_expand, v_expand;
  173955. int inrow, outrow;
  173956. h_expand = upsample->h_expand[compptr->component_index];
  173957. v_expand = upsample->v_expand[compptr->component_index];
  173958. inrow = outrow = 0;
  173959. while (outrow < cinfo->max_v_samp_factor) {
  173960. /* Generate one output row with proper horizontal expansion */
  173961. inptr = input_data[inrow];
  173962. outptr = output_data[outrow];
  173963. outend = outptr + cinfo->output_width;
  173964. while (outptr < outend) {
  173965. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  173966. for (h = h_expand; h > 0; h--) {
  173967. *outptr++ = invalue;
  173968. }
  173969. }
  173970. /* Generate any additional output rows by duplicating the first one */
  173971. if (v_expand > 1) {
  173972. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  173973. v_expand-1, cinfo->output_width);
  173974. }
  173975. inrow++;
  173976. outrow += v_expand;
  173977. }
  173978. }
  173979. /*
  173980. * Fast processing for the common case of 2:1 horizontal and 1:1 vertical.
  173981. * It's still a box filter.
  173982. */
  173983. METHODDEF(void)
  173984. h2v1_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  173985. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173986. {
  173987. JSAMPARRAY output_data = *output_data_ptr;
  173988. register JSAMPROW inptr, outptr;
  173989. register JSAMPLE invalue;
  173990. JSAMPROW outend;
  173991. int inrow;
  173992. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  173993. inptr = input_data[inrow];
  173994. outptr = output_data[inrow];
  173995. outend = outptr + cinfo->output_width;
  173996. while (outptr < outend) {
  173997. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  173998. *outptr++ = invalue;
  173999. *outptr++ = invalue;
  174000. }
  174001. }
  174002. }
  174003. /*
  174004. * Fast processing for the common case of 2:1 horizontal and 2:1 vertical.
  174005. * It's still a box filter.
  174006. */
  174007. METHODDEF(void)
  174008. h2v2_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  174009. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174010. {
  174011. JSAMPARRAY output_data = *output_data_ptr;
  174012. register JSAMPROW inptr, outptr;
  174013. register JSAMPLE invalue;
  174014. JSAMPROW outend;
  174015. int inrow, outrow;
  174016. inrow = outrow = 0;
  174017. while (outrow < cinfo->max_v_samp_factor) {
  174018. inptr = input_data[inrow];
  174019. outptr = output_data[outrow];
  174020. outend = outptr + cinfo->output_width;
  174021. while (outptr < outend) {
  174022. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  174023. *outptr++ = invalue;
  174024. *outptr++ = invalue;
  174025. }
  174026. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  174027. 1, cinfo->output_width);
  174028. inrow++;
  174029. outrow += 2;
  174030. }
  174031. }
  174032. /*
  174033. * Fancy processing for the common case of 2:1 horizontal and 1:1 vertical.
  174034. *
  174035. * The upsampling algorithm is linear interpolation between pixel centers,
  174036. * also known as a "triangle filter". This is a good compromise between
  174037. * speed and visual quality. The centers of the output pixels are 1/4 and 3/4
  174038. * of the way between input pixel centers.
  174039. *
  174040. * A note about the "bias" calculations: when rounding fractional values to
  174041. * integer, we do not want to always round 0.5 up to the next integer.
  174042. * If we did that, we'd introduce a noticeable bias towards larger values.
  174043. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  174044. * alternate pixel locations (a simple ordered dither pattern).
  174045. */
  174046. METHODDEF(void)
  174047. h2v1_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174048. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174049. {
  174050. JSAMPARRAY output_data = *output_data_ptr;
  174051. register JSAMPROW inptr, outptr;
  174052. register int invalue;
  174053. register JDIMENSION colctr;
  174054. int inrow;
  174055. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  174056. inptr = input_data[inrow];
  174057. outptr = output_data[inrow];
  174058. /* Special case for first column */
  174059. invalue = GETJSAMPLE(*inptr++);
  174060. *outptr++ = (JSAMPLE) invalue;
  174061. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(*inptr) + 2) >> 2);
  174062. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  174063. /* General case: 3/4 * nearer pixel + 1/4 * further pixel */
  174064. invalue = GETJSAMPLE(*inptr++) * 3;
  174065. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(inptr[-2]) + 1) >> 2);
  174066. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(*inptr) + 2) >> 2);
  174067. }
  174068. /* Special case for last column */
  174069. invalue = GETJSAMPLE(*inptr);
  174070. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(inptr[-1]) + 1) >> 2);
  174071. *outptr++ = (JSAMPLE) invalue;
  174072. }
  174073. }
  174074. /*
  174075. * Fancy processing for the common case of 2:1 horizontal and 2:1 vertical.
  174076. * Again a triangle filter; see comments for h2v1 case, above.
  174077. *
  174078. * It is OK for us to reference the adjacent input rows because we demanded
  174079. * context from the main buffer controller (see initialization code).
  174080. */
  174081. METHODDEF(void)
  174082. h2v2_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174083. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174084. {
  174085. JSAMPARRAY output_data = *output_data_ptr;
  174086. register JSAMPROW inptr0, inptr1, outptr;
  174087. #if BITS_IN_JSAMPLE == 8
  174088. register int thiscolsum, lastcolsum, nextcolsum;
  174089. #else
  174090. register INT32 thiscolsum, lastcolsum, nextcolsum;
  174091. #endif
  174092. register JDIMENSION colctr;
  174093. int inrow, outrow, v;
  174094. inrow = outrow = 0;
  174095. while (outrow < cinfo->max_v_samp_factor) {
  174096. for (v = 0; v < 2; v++) {
  174097. /* inptr0 points to nearest input row, inptr1 points to next nearest */
  174098. inptr0 = input_data[inrow];
  174099. if (v == 0) /* next nearest is row above */
  174100. inptr1 = input_data[inrow-1];
  174101. else /* next nearest is row below */
  174102. inptr1 = input_data[inrow+1];
  174103. outptr = output_data[outrow++];
  174104. /* Special case for first column */
  174105. thiscolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  174106. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  174107. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 8) >> 4);
  174108. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  174109. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  174110. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  174111. /* General case: 3/4 * nearer pixel + 1/4 * further pixel in each */
  174112. /* dimension, thus 9/16, 3/16, 3/16, 1/16 overall */
  174113. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  174114. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  174115. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  174116. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  174117. }
  174118. /* Special case for last column */
  174119. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  174120. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 7) >> 4);
  174121. }
  174122. inrow++;
  174123. }
  174124. }
  174125. /*
  174126. * Module initialization routine for upsampling.
  174127. */
  174128. GLOBAL(void)
  174129. jinit_upsampler (j_decompress_ptr cinfo)
  174130. {
  174131. my_upsample_ptr2 upsample;
  174132. int ci;
  174133. jpeg_component_info * compptr;
  174134. boolean need_buffer, do_fancy;
  174135. int h_in_group, v_in_group, h_out_group, v_out_group;
  174136. upsample = (my_upsample_ptr2)
  174137. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  174138. SIZEOF(my_upsampler2));
  174139. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  174140. upsample->pub.start_pass = start_pass_upsample;
  174141. upsample->pub.upsample = sep_upsample;
  174142. upsample->pub.need_context_rows = FALSE; /* until we find out differently */
  174143. if (cinfo->CCIR601_sampling) /* this isn't supported */
  174144. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  174145. /* jdmainct.c doesn't support context rows when min_DCT_scaled_size = 1,
  174146. * so don't ask for it.
  174147. */
  174148. do_fancy = cinfo->do_fancy_upsampling && cinfo->min_DCT_scaled_size > 1;
  174149. /* Verify we can handle the sampling factors, select per-component methods,
  174150. * and create storage as needed.
  174151. */
  174152. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  174153. ci++, compptr++) {
  174154. /* Compute size of an "input group" after IDCT scaling. This many samples
  174155. * are to be converted to max_h_samp_factor * max_v_samp_factor pixels.
  174156. */
  174157. h_in_group = (compptr->h_samp_factor * compptr->DCT_scaled_size) /
  174158. cinfo->min_DCT_scaled_size;
  174159. v_in_group = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  174160. cinfo->min_DCT_scaled_size;
  174161. h_out_group = cinfo->max_h_samp_factor;
  174162. v_out_group = cinfo->max_v_samp_factor;
  174163. upsample->rowgroup_height[ci] = v_in_group; /* save for use later */
  174164. need_buffer = TRUE;
  174165. if (! compptr->component_needed) {
  174166. /* Don't bother to upsample an uninteresting component. */
  174167. upsample->methods[ci] = noop_upsample;
  174168. need_buffer = FALSE;
  174169. } else if (h_in_group == h_out_group && v_in_group == v_out_group) {
  174170. /* Fullsize components can be processed without any work. */
  174171. upsample->methods[ci] = fullsize_upsample;
  174172. need_buffer = FALSE;
  174173. } else if (h_in_group * 2 == h_out_group &&
  174174. v_in_group == v_out_group) {
  174175. /* Special cases for 2h1v upsampling */
  174176. if (do_fancy && compptr->downsampled_width > 2)
  174177. upsample->methods[ci] = h2v1_fancy_upsample;
  174178. else
  174179. upsample->methods[ci] = h2v1_upsample;
  174180. } else if (h_in_group * 2 == h_out_group &&
  174181. v_in_group * 2 == v_out_group) {
  174182. /* Special cases for 2h2v upsampling */
  174183. if (do_fancy && compptr->downsampled_width > 2) {
  174184. upsample->methods[ci] = h2v2_fancy_upsample;
  174185. upsample->pub.need_context_rows = TRUE;
  174186. } else
  174187. upsample->methods[ci] = h2v2_upsample;
  174188. } else if ((h_out_group % h_in_group) == 0 &&
  174189. (v_out_group % v_in_group) == 0) {
  174190. /* Generic integral-factors upsampling method */
  174191. upsample->methods[ci] = int_upsample;
  174192. upsample->h_expand[ci] = (UINT8) (h_out_group / h_in_group);
  174193. upsample->v_expand[ci] = (UINT8) (v_out_group / v_in_group);
  174194. } else
  174195. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  174196. if (need_buffer) {
  174197. upsample->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  174198. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  174199. (JDIMENSION) jround_up((long) cinfo->output_width,
  174200. (long) cinfo->max_h_samp_factor),
  174201. (JDIMENSION) cinfo->max_v_samp_factor);
  174202. }
  174203. }
  174204. }
  174205. /*** End of inlined file: jdsample.c ***/
  174206. /*** Start of inlined file: jdtrans.c ***/
  174207. #define JPEG_INTERNALS
  174208. /* Forward declarations */
  174209. LOCAL(void) transdecode_master_selection JPP((j_decompress_ptr cinfo));
  174210. /*
  174211. * Read the coefficient arrays from a JPEG file.
  174212. * jpeg_read_header must be completed before calling this.
  174213. *
  174214. * The entire image is read into a set of virtual coefficient-block arrays,
  174215. * one per component. The return value is a pointer to the array of
  174216. * virtual-array descriptors. These can be manipulated directly via the
  174217. * JPEG memory manager, or handed off to jpeg_write_coefficients().
  174218. * To release the memory occupied by the virtual arrays, call
  174219. * jpeg_finish_decompress() when done with the data.
  174220. *
  174221. * An alternative usage is to simply obtain access to the coefficient arrays
  174222. * during a buffered-image-mode decompression operation. This is allowed
  174223. * after any jpeg_finish_output() call. The arrays can be accessed until
  174224. * jpeg_finish_decompress() is called. (Note that any call to the library
  174225. * may reposition the arrays, so don't rely on access_virt_barray() results
  174226. * to stay valid across library calls.)
  174227. *
  174228. * Returns NULL if suspended. This case need be checked only if
  174229. * a suspending data source is used.
  174230. */
  174231. GLOBAL(jvirt_barray_ptr *)
  174232. jpeg_read_coefficients (j_decompress_ptr cinfo)
  174233. {
  174234. if (cinfo->global_state == DSTATE_READY) {
  174235. /* First call: initialize active modules */
  174236. transdecode_master_selection(cinfo);
  174237. cinfo->global_state = DSTATE_RDCOEFS;
  174238. }
  174239. if (cinfo->global_state == DSTATE_RDCOEFS) {
  174240. /* Absorb whole file into the coef buffer */
  174241. for (;;) {
  174242. int retcode;
  174243. /* Call progress monitor hook if present */
  174244. if (cinfo->progress != NULL)
  174245. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  174246. /* Absorb some more input */
  174247. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  174248. if (retcode == JPEG_SUSPENDED)
  174249. return NULL;
  174250. if (retcode == JPEG_REACHED_EOI)
  174251. break;
  174252. /* Advance progress counter if appropriate */
  174253. if (cinfo->progress != NULL &&
  174254. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  174255. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  174256. /* startup underestimated number of scans; ratchet up one scan */
  174257. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  174258. }
  174259. }
  174260. }
  174261. /* Set state so that jpeg_finish_decompress does the right thing */
  174262. cinfo->global_state = DSTATE_STOPPING;
  174263. }
  174264. /* At this point we should be in state DSTATE_STOPPING if being used
  174265. * standalone, or in state DSTATE_BUFIMAGE if being invoked to get access
  174266. * to the coefficients during a full buffered-image-mode decompression.
  174267. */
  174268. if ((cinfo->global_state == DSTATE_STOPPING ||
  174269. cinfo->global_state == DSTATE_BUFIMAGE) && cinfo->buffered_image) {
  174270. return cinfo->coef->coef_arrays;
  174271. }
  174272. /* Oops, improper usage */
  174273. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  174274. return NULL; /* keep compiler happy */
  174275. }
  174276. /*
  174277. * Master selection of decompression modules for transcoding.
  174278. * This substitutes for jdmaster.c's initialization of the full decompressor.
  174279. */
  174280. LOCAL(void)
  174281. transdecode_master_selection (j_decompress_ptr cinfo)
  174282. {
  174283. /* This is effectively a buffered-image operation. */
  174284. cinfo->buffered_image = TRUE;
  174285. /* Entropy decoding: either Huffman or arithmetic coding. */
  174286. if (cinfo->arith_code) {
  174287. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  174288. } else {
  174289. if (cinfo->progressive_mode) {
  174290. #ifdef D_PROGRESSIVE_SUPPORTED
  174291. jinit_phuff_decoder(cinfo);
  174292. #else
  174293. ERREXIT(cinfo, JERR_NOT_COMPILED);
  174294. #endif
  174295. } else
  174296. jinit_huff_decoder(cinfo);
  174297. }
  174298. /* Always get a full-image coefficient buffer. */
  174299. jinit_d_coef_controller(cinfo, TRUE);
  174300. /* We can now tell the memory manager to allocate virtual arrays. */
  174301. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  174302. /* Initialize input side of decompressor to consume first scan. */
  174303. (*cinfo->inputctl->start_input_pass) (cinfo);
  174304. /* Initialize progress monitoring. */
  174305. if (cinfo->progress != NULL) {
  174306. int nscans;
  174307. /* Estimate number of scans to set pass_limit. */
  174308. if (cinfo->progressive_mode) {
  174309. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  174310. nscans = 2 + 3 * cinfo->num_components;
  174311. } else if (cinfo->inputctl->has_multiple_scans) {
  174312. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  174313. nscans = cinfo->num_components;
  174314. } else {
  174315. nscans = 1;
  174316. }
  174317. cinfo->progress->pass_counter = 0L;
  174318. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  174319. cinfo->progress->completed_passes = 0;
  174320. cinfo->progress->total_passes = 1;
  174321. }
  174322. }
  174323. /*** End of inlined file: jdtrans.c ***/
  174324. /*** Start of inlined file: jfdctflt.c ***/
  174325. #define JPEG_INTERNALS
  174326. #ifdef DCT_FLOAT_SUPPORTED
  174327. /*
  174328. * This module is specialized to the case DCTSIZE = 8.
  174329. */
  174330. #if DCTSIZE != 8
  174331. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174332. #endif
  174333. /*
  174334. * Perform the forward DCT on one block of samples.
  174335. */
  174336. GLOBAL(void)
  174337. jpeg_fdct_float (FAST_FLOAT * data)
  174338. {
  174339. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174340. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  174341. FAST_FLOAT z1, z2, z3, z4, z5, z11, z13;
  174342. FAST_FLOAT *dataptr;
  174343. int ctr;
  174344. /* Pass 1: process rows. */
  174345. dataptr = data;
  174346. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174347. tmp0 = dataptr[0] + dataptr[7];
  174348. tmp7 = dataptr[0] - dataptr[7];
  174349. tmp1 = dataptr[1] + dataptr[6];
  174350. tmp6 = dataptr[1] - dataptr[6];
  174351. tmp2 = dataptr[2] + dataptr[5];
  174352. tmp5 = dataptr[2] - dataptr[5];
  174353. tmp3 = dataptr[3] + dataptr[4];
  174354. tmp4 = dataptr[3] - dataptr[4];
  174355. /* Even part */
  174356. tmp10 = tmp0 + tmp3; /* phase 2 */
  174357. tmp13 = tmp0 - tmp3;
  174358. tmp11 = tmp1 + tmp2;
  174359. tmp12 = tmp1 - tmp2;
  174360. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  174361. dataptr[4] = tmp10 - tmp11;
  174362. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  174363. dataptr[2] = tmp13 + z1; /* phase 5 */
  174364. dataptr[6] = tmp13 - z1;
  174365. /* Odd part */
  174366. tmp10 = tmp4 + tmp5; /* phase 2 */
  174367. tmp11 = tmp5 + tmp6;
  174368. tmp12 = tmp6 + tmp7;
  174369. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174370. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  174371. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  174372. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  174373. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  174374. z11 = tmp7 + z3; /* phase 5 */
  174375. z13 = tmp7 - z3;
  174376. dataptr[5] = z13 + z2; /* phase 6 */
  174377. dataptr[3] = z13 - z2;
  174378. dataptr[1] = z11 + z4;
  174379. dataptr[7] = z11 - z4;
  174380. dataptr += DCTSIZE; /* advance pointer to next row */
  174381. }
  174382. /* Pass 2: process columns. */
  174383. dataptr = data;
  174384. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174385. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174386. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174387. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174388. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174389. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174390. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174391. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174392. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174393. /* Even part */
  174394. tmp10 = tmp0 + tmp3; /* phase 2 */
  174395. tmp13 = tmp0 - tmp3;
  174396. tmp11 = tmp1 + tmp2;
  174397. tmp12 = tmp1 - tmp2;
  174398. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  174399. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  174400. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  174401. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  174402. dataptr[DCTSIZE*6] = tmp13 - z1;
  174403. /* Odd part */
  174404. tmp10 = tmp4 + tmp5; /* phase 2 */
  174405. tmp11 = tmp5 + tmp6;
  174406. tmp12 = tmp6 + tmp7;
  174407. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174408. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  174409. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  174410. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  174411. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  174412. z11 = tmp7 + z3; /* phase 5 */
  174413. z13 = tmp7 - z3;
  174414. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  174415. dataptr[DCTSIZE*3] = z13 - z2;
  174416. dataptr[DCTSIZE*1] = z11 + z4;
  174417. dataptr[DCTSIZE*7] = z11 - z4;
  174418. dataptr++; /* advance pointer to next column */
  174419. }
  174420. }
  174421. #endif /* DCT_FLOAT_SUPPORTED */
  174422. /*** End of inlined file: jfdctflt.c ***/
  174423. /*** Start of inlined file: jfdctint.c ***/
  174424. #define JPEG_INTERNALS
  174425. #ifdef DCT_ISLOW_SUPPORTED
  174426. /*
  174427. * This module is specialized to the case DCTSIZE = 8.
  174428. */
  174429. #if DCTSIZE != 8
  174430. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174431. #endif
  174432. /*
  174433. * The poop on this scaling stuff is as follows:
  174434. *
  174435. * Each 1-D DCT step produces outputs which are a factor of sqrt(N)
  174436. * larger than the true DCT outputs. The final outputs are therefore
  174437. * a factor of N larger than desired; since N=8 this can be cured by
  174438. * a simple right shift at the end of the algorithm. The advantage of
  174439. * this arrangement is that we save two multiplications per 1-D DCT,
  174440. * because the y0 and y4 outputs need not be divided by sqrt(N).
  174441. * In the IJG code, this factor of 8 is removed by the quantization step
  174442. * (in jcdctmgr.c), NOT in this module.
  174443. *
  174444. * We have to do addition and subtraction of the integer inputs, which
  174445. * is no problem, and multiplication by fractional constants, which is
  174446. * a problem to do in integer arithmetic. We multiply all the constants
  174447. * by CONST_SCALE and convert them to integer constants (thus retaining
  174448. * CONST_BITS bits of precision in the constants). After doing a
  174449. * multiplication we have to divide the product by CONST_SCALE, with proper
  174450. * rounding, to produce the correct output. This division can be done
  174451. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  174452. * as long as possible so that partial sums can be added together with
  174453. * full fractional precision.
  174454. *
  174455. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  174456. * they are represented to better-than-integral precision. These outputs
  174457. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  174458. * with the recommended scaling. (For 12-bit sample data, the intermediate
  174459. * array is INT32 anyway.)
  174460. *
  174461. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  174462. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  174463. * shows that the values given below are the most effective.
  174464. */
  174465. #if BITS_IN_JSAMPLE == 8
  174466. #define CONST_BITS 13
  174467. #define PASS1_BITS 2
  174468. #else
  174469. #define CONST_BITS 13
  174470. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  174471. #endif
  174472. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174473. * causing a lot of useless floating-point operations at run time.
  174474. * To get around this we use the following pre-calculated constants.
  174475. * If you change CONST_BITS you may want to add appropriate values.
  174476. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174477. */
  174478. #if CONST_BITS == 13
  174479. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  174480. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  174481. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  174482. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  174483. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  174484. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  174485. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  174486. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  174487. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  174488. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  174489. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  174490. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  174491. #else
  174492. #define FIX_0_298631336 FIX(0.298631336)
  174493. #define FIX_0_390180644 FIX(0.390180644)
  174494. #define FIX_0_541196100 FIX(0.541196100)
  174495. #define FIX_0_765366865 FIX(0.765366865)
  174496. #define FIX_0_899976223 FIX(0.899976223)
  174497. #define FIX_1_175875602 FIX(1.175875602)
  174498. #define FIX_1_501321110 FIX(1.501321110)
  174499. #define FIX_1_847759065 FIX(1.847759065)
  174500. #define FIX_1_961570560 FIX(1.961570560)
  174501. #define FIX_2_053119869 FIX(2.053119869)
  174502. #define FIX_2_562915447 FIX(2.562915447)
  174503. #define FIX_3_072711026 FIX(3.072711026)
  174504. #endif
  174505. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  174506. * For 8-bit samples with the recommended scaling, all the variable
  174507. * and constant values involved are no more than 16 bits wide, so a
  174508. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  174509. * For 12-bit samples, a full 32-bit multiplication will be needed.
  174510. */
  174511. #if BITS_IN_JSAMPLE == 8
  174512. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  174513. #else
  174514. #define MULTIPLY(var,const) ((var) * (const))
  174515. #endif
  174516. /*
  174517. * Perform the forward DCT on one block of samples.
  174518. */
  174519. GLOBAL(void)
  174520. jpeg_fdct_islow (DCTELEM * data)
  174521. {
  174522. INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174523. INT32 tmp10, tmp11, tmp12, tmp13;
  174524. INT32 z1, z2, z3, z4, z5;
  174525. DCTELEM *dataptr;
  174526. int ctr;
  174527. SHIFT_TEMPS
  174528. /* Pass 1: process rows. */
  174529. /* Note results are scaled up by sqrt(8) compared to a true DCT; */
  174530. /* furthermore, we scale the results by 2**PASS1_BITS. */
  174531. dataptr = data;
  174532. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174533. tmp0 = dataptr[0] + dataptr[7];
  174534. tmp7 = dataptr[0] - dataptr[7];
  174535. tmp1 = dataptr[1] + dataptr[6];
  174536. tmp6 = dataptr[1] - dataptr[6];
  174537. tmp2 = dataptr[2] + dataptr[5];
  174538. tmp5 = dataptr[2] - dataptr[5];
  174539. tmp3 = dataptr[3] + dataptr[4];
  174540. tmp4 = dataptr[3] - dataptr[4];
  174541. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  174542. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  174543. */
  174544. tmp10 = tmp0 + tmp3;
  174545. tmp13 = tmp0 - tmp3;
  174546. tmp11 = tmp1 + tmp2;
  174547. tmp12 = tmp1 - tmp2;
  174548. dataptr[0] = (DCTELEM) ((tmp10 + tmp11) << PASS1_BITS);
  174549. dataptr[4] = (DCTELEM) ((tmp10 - tmp11) << PASS1_BITS);
  174550. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  174551. dataptr[2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  174552. CONST_BITS-PASS1_BITS);
  174553. dataptr[6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  174554. CONST_BITS-PASS1_BITS);
  174555. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  174556. * cK represents cos(K*pi/16).
  174557. * i0..i3 in the paper are tmp4..tmp7 here.
  174558. */
  174559. z1 = tmp4 + tmp7;
  174560. z2 = tmp5 + tmp6;
  174561. z3 = tmp4 + tmp6;
  174562. z4 = tmp5 + tmp7;
  174563. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174564. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174565. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174566. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174567. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174568. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174569. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174570. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174571. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174572. z3 += z5;
  174573. z4 += z5;
  174574. dataptr[7] = (DCTELEM) DESCALE(tmp4 + z1 + z3, CONST_BITS-PASS1_BITS);
  174575. dataptr[5] = (DCTELEM) DESCALE(tmp5 + z2 + z4, CONST_BITS-PASS1_BITS);
  174576. dataptr[3] = (DCTELEM) DESCALE(tmp6 + z2 + z3, CONST_BITS-PASS1_BITS);
  174577. dataptr[1] = (DCTELEM) DESCALE(tmp7 + z1 + z4, CONST_BITS-PASS1_BITS);
  174578. dataptr += DCTSIZE; /* advance pointer to next row */
  174579. }
  174580. /* Pass 2: process columns.
  174581. * We remove the PASS1_BITS scaling, but leave the results scaled up
  174582. * by an overall factor of 8.
  174583. */
  174584. dataptr = data;
  174585. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174586. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174587. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174588. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174589. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174590. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174591. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174592. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174593. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174594. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  174595. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  174596. */
  174597. tmp10 = tmp0 + tmp3;
  174598. tmp13 = tmp0 - tmp3;
  174599. tmp11 = tmp1 + tmp2;
  174600. tmp12 = tmp1 - tmp2;
  174601. dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(tmp10 + tmp11, PASS1_BITS);
  174602. dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(tmp10 - tmp11, PASS1_BITS);
  174603. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  174604. dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  174605. CONST_BITS+PASS1_BITS);
  174606. dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  174607. CONST_BITS+PASS1_BITS);
  174608. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  174609. * cK represents cos(K*pi/16).
  174610. * i0..i3 in the paper are tmp4..tmp7 here.
  174611. */
  174612. z1 = tmp4 + tmp7;
  174613. z2 = tmp5 + tmp6;
  174614. z3 = tmp4 + tmp6;
  174615. z4 = tmp5 + tmp7;
  174616. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174617. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174618. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174619. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174620. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174621. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174622. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174623. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174624. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174625. z3 += z5;
  174626. z4 += z5;
  174627. dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp4 + z1 + z3,
  174628. CONST_BITS+PASS1_BITS);
  174629. dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp5 + z2 + z4,
  174630. CONST_BITS+PASS1_BITS);
  174631. dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp6 + z2 + z3,
  174632. CONST_BITS+PASS1_BITS);
  174633. dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp7 + z1 + z4,
  174634. CONST_BITS+PASS1_BITS);
  174635. dataptr++; /* advance pointer to next column */
  174636. }
  174637. }
  174638. #endif /* DCT_ISLOW_SUPPORTED */
  174639. /*** End of inlined file: jfdctint.c ***/
  174640. #undef CONST_BITS
  174641. #undef MULTIPLY
  174642. #undef FIX_0_541196100
  174643. /*** Start of inlined file: jfdctfst.c ***/
  174644. #define JPEG_INTERNALS
  174645. #ifdef DCT_IFAST_SUPPORTED
  174646. /*
  174647. * This module is specialized to the case DCTSIZE = 8.
  174648. */
  174649. #if DCTSIZE != 8
  174650. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174651. #endif
  174652. /* Scaling decisions are generally the same as in the LL&M algorithm;
  174653. * see jfdctint.c for more details. However, we choose to descale
  174654. * (right shift) multiplication products as soon as they are formed,
  174655. * rather than carrying additional fractional bits into subsequent additions.
  174656. * This compromises accuracy slightly, but it lets us save a few shifts.
  174657. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  174658. * everywhere except in the multiplications proper; this saves a good deal
  174659. * of work on 16-bit-int machines.
  174660. *
  174661. * Again to save a few shifts, the intermediate results between pass 1 and
  174662. * pass 2 are not upscaled, but are represented only to integral precision.
  174663. *
  174664. * A final compromise is to represent the multiplicative constants to only
  174665. * 8 fractional bits, rather than 13. This saves some shifting work on some
  174666. * machines, and may also reduce the cost of multiplication (since there
  174667. * are fewer one-bits in the constants).
  174668. */
  174669. #define CONST_BITS 8
  174670. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174671. * causing a lot of useless floating-point operations at run time.
  174672. * To get around this we use the following pre-calculated constants.
  174673. * If you change CONST_BITS you may want to add appropriate values.
  174674. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174675. */
  174676. #if CONST_BITS == 8
  174677. #define FIX_0_382683433 ((INT32) 98) /* FIX(0.382683433) */
  174678. #define FIX_0_541196100 ((INT32) 139) /* FIX(0.541196100) */
  174679. #define FIX_0_707106781 ((INT32) 181) /* FIX(0.707106781) */
  174680. #define FIX_1_306562965 ((INT32) 334) /* FIX(1.306562965) */
  174681. #else
  174682. #define FIX_0_382683433 FIX(0.382683433)
  174683. #define FIX_0_541196100 FIX(0.541196100)
  174684. #define FIX_0_707106781 FIX(0.707106781)
  174685. #define FIX_1_306562965 FIX(1.306562965)
  174686. #endif
  174687. /* We can gain a little more speed, with a further compromise in accuracy,
  174688. * by omitting the addition in a descaling shift. This yields an incorrectly
  174689. * rounded result half the time...
  174690. */
  174691. #ifndef USE_ACCURATE_ROUNDING
  174692. #undef DESCALE
  174693. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  174694. #endif
  174695. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  174696. * descale to yield a DCTELEM result.
  174697. */
  174698. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  174699. /*
  174700. * Perform the forward DCT on one block of samples.
  174701. */
  174702. GLOBAL(void)
  174703. jpeg_fdct_ifast (DCTELEM * data)
  174704. {
  174705. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174706. DCTELEM tmp10, tmp11, tmp12, tmp13;
  174707. DCTELEM z1, z2, z3, z4, z5, z11, z13;
  174708. DCTELEM *dataptr;
  174709. int ctr;
  174710. SHIFT_TEMPS
  174711. /* Pass 1: process rows. */
  174712. dataptr = data;
  174713. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174714. tmp0 = dataptr[0] + dataptr[7];
  174715. tmp7 = dataptr[0] - dataptr[7];
  174716. tmp1 = dataptr[1] + dataptr[6];
  174717. tmp6 = dataptr[1] - dataptr[6];
  174718. tmp2 = dataptr[2] + dataptr[5];
  174719. tmp5 = dataptr[2] - dataptr[5];
  174720. tmp3 = dataptr[3] + dataptr[4];
  174721. tmp4 = dataptr[3] - dataptr[4];
  174722. /* Even part */
  174723. tmp10 = tmp0 + tmp3; /* phase 2 */
  174724. tmp13 = tmp0 - tmp3;
  174725. tmp11 = tmp1 + tmp2;
  174726. tmp12 = tmp1 - tmp2;
  174727. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  174728. dataptr[4] = tmp10 - tmp11;
  174729. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  174730. dataptr[2] = tmp13 + z1; /* phase 5 */
  174731. dataptr[6] = tmp13 - z1;
  174732. /* Odd part */
  174733. tmp10 = tmp4 + tmp5; /* phase 2 */
  174734. tmp11 = tmp5 + tmp6;
  174735. tmp12 = tmp6 + tmp7;
  174736. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174737. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  174738. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  174739. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  174740. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  174741. z11 = tmp7 + z3; /* phase 5 */
  174742. z13 = tmp7 - z3;
  174743. dataptr[5] = z13 + z2; /* phase 6 */
  174744. dataptr[3] = z13 - z2;
  174745. dataptr[1] = z11 + z4;
  174746. dataptr[7] = z11 - z4;
  174747. dataptr += DCTSIZE; /* advance pointer to next row */
  174748. }
  174749. /* Pass 2: process columns. */
  174750. dataptr = data;
  174751. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174752. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174753. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174754. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174755. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174756. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174757. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174758. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174759. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174760. /* Even part */
  174761. tmp10 = tmp0 + tmp3; /* phase 2 */
  174762. tmp13 = tmp0 - tmp3;
  174763. tmp11 = tmp1 + tmp2;
  174764. tmp12 = tmp1 - tmp2;
  174765. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  174766. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  174767. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  174768. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  174769. dataptr[DCTSIZE*6] = tmp13 - z1;
  174770. /* Odd part */
  174771. tmp10 = tmp4 + tmp5; /* phase 2 */
  174772. tmp11 = tmp5 + tmp6;
  174773. tmp12 = tmp6 + tmp7;
  174774. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174775. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  174776. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  174777. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  174778. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  174779. z11 = tmp7 + z3; /* phase 5 */
  174780. z13 = tmp7 - z3;
  174781. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  174782. dataptr[DCTSIZE*3] = z13 - z2;
  174783. dataptr[DCTSIZE*1] = z11 + z4;
  174784. dataptr[DCTSIZE*7] = z11 - z4;
  174785. dataptr++; /* advance pointer to next column */
  174786. }
  174787. }
  174788. #endif /* DCT_IFAST_SUPPORTED */
  174789. /*** End of inlined file: jfdctfst.c ***/
  174790. #undef FIX_0_541196100
  174791. /*** Start of inlined file: jidctflt.c ***/
  174792. #define JPEG_INTERNALS
  174793. #ifdef DCT_FLOAT_SUPPORTED
  174794. /*
  174795. * This module is specialized to the case DCTSIZE = 8.
  174796. */
  174797. #if DCTSIZE != 8
  174798. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174799. #endif
  174800. /* Dequantize a coefficient by multiplying it by the multiplier-table
  174801. * entry; produce a float result.
  174802. */
  174803. #define DEQUANTIZE(coef,quantval) (((FAST_FLOAT) (coef)) * (quantval))
  174804. /*
  174805. * Perform dequantization and inverse DCT on one block of coefficients.
  174806. */
  174807. GLOBAL(void)
  174808. jpeg_idct_float (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174809. JCOEFPTR coef_block,
  174810. JSAMPARRAY output_buf, JDIMENSION output_col)
  174811. {
  174812. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174813. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  174814. FAST_FLOAT z5, z10, z11, z12, z13;
  174815. JCOEFPTR inptr;
  174816. FLOAT_MULT_TYPE * quantptr;
  174817. FAST_FLOAT * wsptr;
  174818. JSAMPROW outptr;
  174819. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174820. int ctr;
  174821. FAST_FLOAT workspace[DCTSIZE2]; /* buffers data between passes */
  174822. SHIFT_TEMPS
  174823. /* Pass 1: process columns from input, store into work array. */
  174824. inptr = coef_block;
  174825. quantptr = (FLOAT_MULT_TYPE *) compptr->dct_table;
  174826. wsptr = workspace;
  174827. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  174828. /* Due to quantization, we will usually find that many of the input
  174829. * coefficients are zero, especially the AC terms. We can exploit this
  174830. * by short-circuiting the IDCT calculation for any column in which all
  174831. * the AC terms are zero. In that case each output is equal to the
  174832. * DC coefficient (with scale factor as needed).
  174833. * With typical images and quantization tables, half or more of the
  174834. * column DCT calculations can be simplified this way.
  174835. */
  174836. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  174837. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  174838. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  174839. inptr[DCTSIZE*7] == 0) {
  174840. /* AC terms all zero */
  174841. FAST_FLOAT dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174842. wsptr[DCTSIZE*0] = dcval;
  174843. wsptr[DCTSIZE*1] = dcval;
  174844. wsptr[DCTSIZE*2] = dcval;
  174845. wsptr[DCTSIZE*3] = dcval;
  174846. wsptr[DCTSIZE*4] = dcval;
  174847. wsptr[DCTSIZE*5] = dcval;
  174848. wsptr[DCTSIZE*6] = dcval;
  174849. wsptr[DCTSIZE*7] = dcval;
  174850. inptr++; /* advance pointers to next column */
  174851. quantptr++;
  174852. wsptr++;
  174853. continue;
  174854. }
  174855. /* Even part */
  174856. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174857. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  174858. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  174859. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  174860. tmp10 = tmp0 + tmp2; /* phase 3 */
  174861. tmp11 = tmp0 - tmp2;
  174862. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  174863. tmp12 = (tmp1 - tmp3) * ((FAST_FLOAT) 1.414213562) - tmp13; /* 2*c4 */
  174864. tmp0 = tmp10 + tmp13; /* phase 2 */
  174865. tmp3 = tmp10 - tmp13;
  174866. tmp1 = tmp11 + tmp12;
  174867. tmp2 = tmp11 - tmp12;
  174868. /* Odd part */
  174869. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  174870. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  174871. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  174872. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  174873. z13 = tmp6 + tmp5; /* phase 6 */
  174874. z10 = tmp6 - tmp5;
  174875. z11 = tmp4 + tmp7;
  174876. z12 = tmp4 - tmp7;
  174877. tmp7 = z11 + z13; /* phase 5 */
  174878. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562); /* 2*c4 */
  174879. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  174880. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  174881. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  174882. tmp6 = tmp12 - tmp7; /* phase 2 */
  174883. tmp5 = tmp11 - tmp6;
  174884. tmp4 = tmp10 + tmp5;
  174885. wsptr[DCTSIZE*0] = tmp0 + tmp7;
  174886. wsptr[DCTSIZE*7] = tmp0 - tmp7;
  174887. wsptr[DCTSIZE*1] = tmp1 + tmp6;
  174888. wsptr[DCTSIZE*6] = tmp1 - tmp6;
  174889. wsptr[DCTSIZE*2] = tmp2 + tmp5;
  174890. wsptr[DCTSIZE*5] = tmp2 - tmp5;
  174891. wsptr[DCTSIZE*4] = tmp3 + tmp4;
  174892. wsptr[DCTSIZE*3] = tmp3 - tmp4;
  174893. inptr++; /* advance pointers to next column */
  174894. quantptr++;
  174895. wsptr++;
  174896. }
  174897. /* Pass 2: process rows from work array, store into output array. */
  174898. /* Note that we must descale the results by a factor of 8 == 2**3. */
  174899. wsptr = workspace;
  174900. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  174901. outptr = output_buf[ctr] + output_col;
  174902. /* Rows of zeroes can be exploited in the same way as we did with columns.
  174903. * However, the column calculation has created many nonzero AC terms, so
  174904. * the simplification applies less often (typically 5% to 10% of the time).
  174905. * And testing floats for zero is relatively expensive, so we don't bother.
  174906. */
  174907. /* Even part */
  174908. tmp10 = wsptr[0] + wsptr[4];
  174909. tmp11 = wsptr[0] - wsptr[4];
  174910. tmp13 = wsptr[2] + wsptr[6];
  174911. tmp12 = (wsptr[2] - wsptr[6]) * ((FAST_FLOAT) 1.414213562) - tmp13;
  174912. tmp0 = tmp10 + tmp13;
  174913. tmp3 = tmp10 - tmp13;
  174914. tmp1 = tmp11 + tmp12;
  174915. tmp2 = tmp11 - tmp12;
  174916. /* Odd part */
  174917. z13 = wsptr[5] + wsptr[3];
  174918. z10 = wsptr[5] - wsptr[3];
  174919. z11 = wsptr[1] + wsptr[7];
  174920. z12 = wsptr[1] - wsptr[7];
  174921. tmp7 = z11 + z13;
  174922. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562);
  174923. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  174924. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  174925. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  174926. tmp6 = tmp12 - tmp7;
  174927. tmp5 = tmp11 - tmp6;
  174928. tmp4 = tmp10 + tmp5;
  174929. /* Final output stage: scale down by a factor of 8 and range-limit */
  174930. outptr[0] = range_limit[(int) DESCALE((INT32) (tmp0 + tmp7), 3)
  174931. & RANGE_MASK];
  174932. outptr[7] = range_limit[(int) DESCALE((INT32) (tmp0 - tmp7), 3)
  174933. & RANGE_MASK];
  174934. outptr[1] = range_limit[(int) DESCALE((INT32) (tmp1 + tmp6), 3)
  174935. & RANGE_MASK];
  174936. outptr[6] = range_limit[(int) DESCALE((INT32) (tmp1 - tmp6), 3)
  174937. & RANGE_MASK];
  174938. outptr[2] = range_limit[(int) DESCALE((INT32) (tmp2 + tmp5), 3)
  174939. & RANGE_MASK];
  174940. outptr[5] = range_limit[(int) DESCALE((INT32) (tmp2 - tmp5), 3)
  174941. & RANGE_MASK];
  174942. outptr[4] = range_limit[(int) DESCALE((INT32) (tmp3 + tmp4), 3)
  174943. & RANGE_MASK];
  174944. outptr[3] = range_limit[(int) DESCALE((INT32) (tmp3 - tmp4), 3)
  174945. & RANGE_MASK];
  174946. wsptr += DCTSIZE; /* advance pointer to next row */
  174947. }
  174948. }
  174949. #endif /* DCT_FLOAT_SUPPORTED */
  174950. /*** End of inlined file: jidctflt.c ***/
  174951. #undef CONST_BITS
  174952. #undef FIX_1_847759065
  174953. #undef MULTIPLY
  174954. #undef DEQUANTIZE
  174955. #undef DESCALE
  174956. /*** Start of inlined file: jidctfst.c ***/
  174957. #define JPEG_INTERNALS
  174958. #ifdef DCT_IFAST_SUPPORTED
  174959. /*
  174960. * This module is specialized to the case DCTSIZE = 8.
  174961. */
  174962. #if DCTSIZE != 8
  174963. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174964. #endif
  174965. /* Scaling decisions are generally the same as in the LL&M algorithm;
  174966. * see jidctint.c for more details. However, we choose to descale
  174967. * (right shift) multiplication products as soon as they are formed,
  174968. * rather than carrying additional fractional bits into subsequent additions.
  174969. * This compromises accuracy slightly, but it lets us save a few shifts.
  174970. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  174971. * everywhere except in the multiplications proper; this saves a good deal
  174972. * of work on 16-bit-int machines.
  174973. *
  174974. * The dequantized coefficients are not integers because the AA&N scaling
  174975. * factors have been incorporated. We represent them scaled up by PASS1_BITS,
  174976. * so that the first and second IDCT rounds have the same input scaling.
  174977. * For 8-bit JSAMPLEs, we choose IFAST_SCALE_BITS = PASS1_BITS so as to
  174978. * avoid a descaling shift; this compromises accuracy rather drastically
  174979. * for small quantization table entries, but it saves a lot of shifts.
  174980. * For 12-bit JSAMPLEs, there's no hope of using 16x16 multiplies anyway,
  174981. * so we use a much larger scaling factor to preserve accuracy.
  174982. *
  174983. * A final compromise is to represent the multiplicative constants to only
  174984. * 8 fractional bits, rather than 13. This saves some shifting work on some
  174985. * machines, and may also reduce the cost of multiplication (since there
  174986. * are fewer one-bits in the constants).
  174987. */
  174988. #if BITS_IN_JSAMPLE == 8
  174989. #define CONST_BITS 8
  174990. #define PASS1_BITS 2
  174991. #else
  174992. #define CONST_BITS 8
  174993. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  174994. #endif
  174995. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174996. * causing a lot of useless floating-point operations at run time.
  174997. * To get around this we use the following pre-calculated constants.
  174998. * If you change CONST_BITS you may want to add appropriate values.
  174999. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  175000. */
  175001. #if CONST_BITS == 8
  175002. #define FIX_1_082392200 ((INT32) 277) /* FIX(1.082392200) */
  175003. #define FIX_1_414213562 ((INT32) 362) /* FIX(1.414213562) */
  175004. #define FIX_1_847759065 ((INT32) 473) /* FIX(1.847759065) */
  175005. #define FIX_2_613125930 ((INT32) 669) /* FIX(2.613125930) */
  175006. #else
  175007. #define FIX_1_082392200 FIX(1.082392200)
  175008. #define FIX_1_414213562 FIX(1.414213562)
  175009. #define FIX_1_847759065 FIX(1.847759065)
  175010. #define FIX_2_613125930 FIX(2.613125930)
  175011. #endif
  175012. /* We can gain a little more speed, with a further compromise in accuracy,
  175013. * by omitting the addition in a descaling shift. This yields an incorrectly
  175014. * rounded result half the time...
  175015. */
  175016. #ifndef USE_ACCURATE_ROUNDING
  175017. #undef DESCALE
  175018. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  175019. #endif
  175020. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  175021. * descale to yield a DCTELEM result.
  175022. */
  175023. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  175024. /* Dequantize a coefficient by multiplying it by the multiplier-table
  175025. * entry; produce a DCTELEM result. For 8-bit data a 16x16->16
  175026. * multiplication will do. For 12-bit data, the multiplier table is
  175027. * declared INT32, so a 32-bit multiply will be used.
  175028. */
  175029. #if BITS_IN_JSAMPLE == 8
  175030. #define DEQUANTIZE(coef,quantval) (((IFAST_MULT_TYPE) (coef)) * (quantval))
  175031. #else
  175032. #define DEQUANTIZE(coef,quantval) \
  175033. DESCALE((coef)*(quantval), IFAST_SCALE_BITS-PASS1_BITS)
  175034. #endif
  175035. /* Like DESCALE, but applies to a DCTELEM and produces an int.
  175036. * We assume that int right shift is unsigned if INT32 right shift is.
  175037. */
  175038. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  175039. #define ISHIFT_TEMPS DCTELEM ishift_temp;
  175040. #if BITS_IN_JSAMPLE == 8
  175041. #define DCTELEMBITS 16 /* DCTELEM may be 16 or 32 bits */
  175042. #else
  175043. #define DCTELEMBITS 32 /* DCTELEM must be 32 bits */
  175044. #endif
  175045. #define IRIGHT_SHIFT(x,shft) \
  175046. ((ishift_temp = (x)) < 0 ? \
  175047. (ishift_temp >> (shft)) | ((~((DCTELEM) 0)) << (DCTELEMBITS-(shft))) : \
  175048. (ishift_temp >> (shft)))
  175049. #else
  175050. #define ISHIFT_TEMPS
  175051. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  175052. #endif
  175053. #ifdef USE_ACCURATE_ROUNDING
  175054. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT((x) + (1 << ((n)-1)), n))
  175055. #else
  175056. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT(x, n))
  175057. #endif
  175058. /*
  175059. * Perform dequantization and inverse DCT on one block of coefficients.
  175060. */
  175061. GLOBAL(void)
  175062. jpeg_idct_ifast (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175063. JCOEFPTR coef_block,
  175064. JSAMPARRAY output_buf, JDIMENSION output_col)
  175065. {
  175066. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  175067. DCTELEM tmp10, tmp11, tmp12, tmp13;
  175068. DCTELEM z5, z10, z11, z12, z13;
  175069. JCOEFPTR inptr;
  175070. IFAST_MULT_TYPE * quantptr;
  175071. int * wsptr;
  175072. JSAMPROW outptr;
  175073. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175074. int ctr;
  175075. int workspace[DCTSIZE2]; /* buffers data between passes */
  175076. SHIFT_TEMPS /* for DESCALE */
  175077. ISHIFT_TEMPS /* for IDESCALE */
  175078. /* Pass 1: process columns from input, store into work array. */
  175079. inptr = coef_block;
  175080. quantptr = (IFAST_MULT_TYPE *) compptr->dct_table;
  175081. wsptr = workspace;
  175082. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  175083. /* Due to quantization, we will usually find that many of the input
  175084. * coefficients are zero, especially the AC terms. We can exploit this
  175085. * by short-circuiting the IDCT calculation for any column in which all
  175086. * the AC terms are zero. In that case each output is equal to the
  175087. * DC coefficient (with scale factor as needed).
  175088. * With typical images and quantization tables, half or more of the
  175089. * column DCT calculations can be simplified this way.
  175090. */
  175091. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175092. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  175093. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  175094. inptr[DCTSIZE*7] == 0) {
  175095. /* AC terms all zero */
  175096. int dcval = (int) DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175097. wsptr[DCTSIZE*0] = dcval;
  175098. wsptr[DCTSIZE*1] = dcval;
  175099. wsptr[DCTSIZE*2] = dcval;
  175100. wsptr[DCTSIZE*3] = dcval;
  175101. wsptr[DCTSIZE*4] = dcval;
  175102. wsptr[DCTSIZE*5] = dcval;
  175103. wsptr[DCTSIZE*6] = dcval;
  175104. wsptr[DCTSIZE*7] = dcval;
  175105. inptr++; /* advance pointers to next column */
  175106. quantptr++;
  175107. wsptr++;
  175108. continue;
  175109. }
  175110. /* Even part */
  175111. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175112. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175113. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  175114. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175115. tmp10 = tmp0 + tmp2; /* phase 3 */
  175116. tmp11 = tmp0 - tmp2;
  175117. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  175118. tmp12 = MULTIPLY(tmp1 - tmp3, FIX_1_414213562) - tmp13; /* 2*c4 */
  175119. tmp0 = tmp10 + tmp13; /* phase 2 */
  175120. tmp3 = tmp10 - tmp13;
  175121. tmp1 = tmp11 + tmp12;
  175122. tmp2 = tmp11 - tmp12;
  175123. /* Odd part */
  175124. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175125. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175126. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175127. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175128. z13 = tmp6 + tmp5; /* phase 6 */
  175129. z10 = tmp6 - tmp5;
  175130. z11 = tmp4 + tmp7;
  175131. z12 = tmp4 - tmp7;
  175132. tmp7 = z11 + z13; /* phase 5 */
  175133. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  175134. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  175135. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  175136. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  175137. tmp6 = tmp12 - tmp7; /* phase 2 */
  175138. tmp5 = tmp11 - tmp6;
  175139. tmp4 = tmp10 + tmp5;
  175140. wsptr[DCTSIZE*0] = (int) (tmp0 + tmp7);
  175141. wsptr[DCTSIZE*7] = (int) (tmp0 - tmp7);
  175142. wsptr[DCTSIZE*1] = (int) (tmp1 + tmp6);
  175143. wsptr[DCTSIZE*6] = (int) (tmp1 - tmp6);
  175144. wsptr[DCTSIZE*2] = (int) (tmp2 + tmp5);
  175145. wsptr[DCTSIZE*5] = (int) (tmp2 - tmp5);
  175146. wsptr[DCTSIZE*4] = (int) (tmp3 + tmp4);
  175147. wsptr[DCTSIZE*3] = (int) (tmp3 - tmp4);
  175148. inptr++; /* advance pointers to next column */
  175149. quantptr++;
  175150. wsptr++;
  175151. }
  175152. /* Pass 2: process rows from work array, store into output array. */
  175153. /* Note that we must descale the results by a factor of 8 == 2**3, */
  175154. /* and also undo the PASS1_BITS scaling. */
  175155. wsptr = workspace;
  175156. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  175157. outptr = output_buf[ctr] + output_col;
  175158. /* Rows of zeroes can be exploited in the same way as we did with columns.
  175159. * However, the column calculation has created many nonzero AC terms, so
  175160. * the simplification applies less often (typically 5% to 10% of the time).
  175161. * On machines with very fast multiplication, it's possible that the
  175162. * test takes more time than it's worth. In that case this section
  175163. * may be commented out.
  175164. */
  175165. #ifndef NO_ZERO_ROW_TEST
  175166. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  175167. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175168. /* AC terms all zero */
  175169. JSAMPLE dcval = range_limit[IDESCALE(wsptr[0], PASS1_BITS+3)
  175170. & RANGE_MASK];
  175171. outptr[0] = dcval;
  175172. outptr[1] = dcval;
  175173. outptr[2] = dcval;
  175174. outptr[3] = dcval;
  175175. outptr[4] = dcval;
  175176. outptr[5] = dcval;
  175177. outptr[6] = dcval;
  175178. outptr[7] = dcval;
  175179. wsptr += DCTSIZE; /* advance pointer to next row */
  175180. continue;
  175181. }
  175182. #endif
  175183. /* Even part */
  175184. tmp10 = ((DCTELEM) wsptr[0] + (DCTELEM) wsptr[4]);
  175185. tmp11 = ((DCTELEM) wsptr[0] - (DCTELEM) wsptr[4]);
  175186. tmp13 = ((DCTELEM) wsptr[2] + (DCTELEM) wsptr[6]);
  175187. tmp12 = MULTIPLY((DCTELEM) wsptr[2] - (DCTELEM) wsptr[6], FIX_1_414213562)
  175188. - tmp13;
  175189. tmp0 = tmp10 + tmp13;
  175190. tmp3 = tmp10 - tmp13;
  175191. tmp1 = tmp11 + tmp12;
  175192. tmp2 = tmp11 - tmp12;
  175193. /* Odd part */
  175194. z13 = (DCTELEM) wsptr[5] + (DCTELEM) wsptr[3];
  175195. z10 = (DCTELEM) wsptr[5] - (DCTELEM) wsptr[3];
  175196. z11 = (DCTELEM) wsptr[1] + (DCTELEM) wsptr[7];
  175197. z12 = (DCTELEM) wsptr[1] - (DCTELEM) wsptr[7];
  175198. tmp7 = z11 + z13; /* phase 5 */
  175199. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  175200. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  175201. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  175202. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  175203. tmp6 = tmp12 - tmp7; /* phase 2 */
  175204. tmp5 = tmp11 - tmp6;
  175205. tmp4 = tmp10 + tmp5;
  175206. /* Final output stage: scale down by a factor of 8 and range-limit */
  175207. outptr[0] = range_limit[IDESCALE(tmp0 + tmp7, PASS1_BITS+3)
  175208. & RANGE_MASK];
  175209. outptr[7] = range_limit[IDESCALE(tmp0 - tmp7, PASS1_BITS+3)
  175210. & RANGE_MASK];
  175211. outptr[1] = range_limit[IDESCALE(tmp1 + tmp6, PASS1_BITS+3)
  175212. & RANGE_MASK];
  175213. outptr[6] = range_limit[IDESCALE(tmp1 - tmp6, PASS1_BITS+3)
  175214. & RANGE_MASK];
  175215. outptr[2] = range_limit[IDESCALE(tmp2 + tmp5, PASS1_BITS+3)
  175216. & RANGE_MASK];
  175217. outptr[5] = range_limit[IDESCALE(tmp2 - tmp5, PASS1_BITS+3)
  175218. & RANGE_MASK];
  175219. outptr[4] = range_limit[IDESCALE(tmp3 + tmp4, PASS1_BITS+3)
  175220. & RANGE_MASK];
  175221. outptr[3] = range_limit[IDESCALE(tmp3 - tmp4, PASS1_BITS+3)
  175222. & RANGE_MASK];
  175223. wsptr += DCTSIZE; /* advance pointer to next row */
  175224. }
  175225. }
  175226. #endif /* DCT_IFAST_SUPPORTED */
  175227. /*** End of inlined file: jidctfst.c ***/
  175228. #undef CONST_BITS
  175229. #undef FIX_1_847759065
  175230. #undef MULTIPLY
  175231. #undef DEQUANTIZE
  175232. /*** Start of inlined file: jidctint.c ***/
  175233. #define JPEG_INTERNALS
  175234. #ifdef DCT_ISLOW_SUPPORTED
  175235. /*
  175236. * This module is specialized to the case DCTSIZE = 8.
  175237. */
  175238. #if DCTSIZE != 8
  175239. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  175240. #endif
  175241. /*
  175242. * The poop on this scaling stuff is as follows:
  175243. *
  175244. * Each 1-D IDCT step produces outputs which are a factor of sqrt(N)
  175245. * larger than the true IDCT outputs. The final outputs are therefore
  175246. * a factor of N larger than desired; since N=8 this can be cured by
  175247. * a simple right shift at the end of the algorithm. The advantage of
  175248. * this arrangement is that we save two multiplications per 1-D IDCT,
  175249. * because the y0 and y4 inputs need not be divided by sqrt(N).
  175250. *
  175251. * We have to do addition and subtraction of the integer inputs, which
  175252. * is no problem, and multiplication by fractional constants, which is
  175253. * a problem to do in integer arithmetic. We multiply all the constants
  175254. * by CONST_SCALE and convert them to integer constants (thus retaining
  175255. * CONST_BITS bits of precision in the constants). After doing a
  175256. * multiplication we have to divide the product by CONST_SCALE, with proper
  175257. * rounding, to produce the correct output. This division can be done
  175258. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  175259. * as long as possible so that partial sums can be added together with
  175260. * full fractional precision.
  175261. *
  175262. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  175263. * they are represented to better-than-integral precision. These outputs
  175264. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  175265. * with the recommended scaling. (To scale up 12-bit sample data further, an
  175266. * intermediate INT32 array would be needed.)
  175267. *
  175268. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  175269. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  175270. * shows that the values given below are the most effective.
  175271. */
  175272. #if BITS_IN_JSAMPLE == 8
  175273. #define CONST_BITS 13
  175274. #define PASS1_BITS 2
  175275. #else
  175276. #define CONST_BITS 13
  175277. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  175278. #endif
  175279. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  175280. * causing a lot of useless floating-point operations at run time.
  175281. * To get around this we use the following pre-calculated constants.
  175282. * If you change CONST_BITS you may want to add appropriate values.
  175283. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  175284. */
  175285. #if CONST_BITS == 13
  175286. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  175287. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  175288. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  175289. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  175290. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  175291. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  175292. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  175293. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  175294. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  175295. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  175296. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  175297. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  175298. #else
  175299. #define FIX_0_298631336 FIX(0.298631336)
  175300. #define FIX_0_390180644 FIX(0.390180644)
  175301. #define FIX_0_541196100 FIX(0.541196100)
  175302. #define FIX_0_765366865 FIX(0.765366865)
  175303. #define FIX_0_899976223 FIX(0.899976223)
  175304. #define FIX_1_175875602 FIX(1.175875602)
  175305. #define FIX_1_501321110 FIX(1.501321110)
  175306. #define FIX_1_847759065 FIX(1.847759065)
  175307. #define FIX_1_961570560 FIX(1.961570560)
  175308. #define FIX_2_053119869 FIX(2.053119869)
  175309. #define FIX_2_562915447 FIX(2.562915447)
  175310. #define FIX_3_072711026 FIX(3.072711026)
  175311. #endif
  175312. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  175313. * For 8-bit samples with the recommended scaling, all the variable
  175314. * and constant values involved are no more than 16 bits wide, so a
  175315. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  175316. * For 12-bit samples, a full 32-bit multiplication will be needed.
  175317. */
  175318. #if BITS_IN_JSAMPLE == 8
  175319. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  175320. #else
  175321. #define MULTIPLY(var,const) ((var) * (const))
  175322. #endif
  175323. /* Dequantize a coefficient by multiplying it by the multiplier-table
  175324. * entry; produce an int result. In this module, both inputs and result
  175325. * are 16 bits or less, so either int or short multiply will work.
  175326. */
  175327. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  175328. /*
  175329. * Perform dequantization and inverse DCT on one block of coefficients.
  175330. */
  175331. GLOBAL(void)
  175332. jpeg_idct_islow (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175333. JCOEFPTR coef_block,
  175334. JSAMPARRAY output_buf, JDIMENSION output_col)
  175335. {
  175336. INT32 tmp0, tmp1, tmp2, tmp3;
  175337. INT32 tmp10, tmp11, tmp12, tmp13;
  175338. INT32 z1, z2, z3, z4, z5;
  175339. JCOEFPTR inptr;
  175340. ISLOW_MULT_TYPE * quantptr;
  175341. int * wsptr;
  175342. JSAMPROW outptr;
  175343. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175344. int ctr;
  175345. int workspace[DCTSIZE2]; /* buffers data between passes */
  175346. SHIFT_TEMPS
  175347. /* Pass 1: process columns from input, store into work array. */
  175348. /* Note results are scaled up by sqrt(8) compared to a true IDCT; */
  175349. /* furthermore, we scale the results by 2**PASS1_BITS. */
  175350. inptr = coef_block;
  175351. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175352. wsptr = workspace;
  175353. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  175354. /* Due to quantization, we will usually find that many of the input
  175355. * coefficients are zero, especially the AC terms. We can exploit this
  175356. * by short-circuiting the IDCT calculation for any column in which all
  175357. * the AC terms are zero. In that case each output is equal to the
  175358. * DC coefficient (with scale factor as needed).
  175359. * With typical images and quantization tables, half or more of the
  175360. * column DCT calculations can be simplified this way.
  175361. */
  175362. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175363. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  175364. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  175365. inptr[DCTSIZE*7] == 0) {
  175366. /* AC terms all zero */
  175367. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175368. wsptr[DCTSIZE*0] = dcval;
  175369. wsptr[DCTSIZE*1] = dcval;
  175370. wsptr[DCTSIZE*2] = dcval;
  175371. wsptr[DCTSIZE*3] = dcval;
  175372. wsptr[DCTSIZE*4] = dcval;
  175373. wsptr[DCTSIZE*5] = dcval;
  175374. wsptr[DCTSIZE*6] = dcval;
  175375. wsptr[DCTSIZE*7] = dcval;
  175376. inptr++; /* advance pointers to next column */
  175377. quantptr++;
  175378. wsptr++;
  175379. continue;
  175380. }
  175381. /* Even part: reverse the even part of the forward DCT. */
  175382. /* The rotator is sqrt(2)*c(-6). */
  175383. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175384. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175385. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  175386. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  175387. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  175388. z2 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175389. z3 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  175390. tmp0 = (z2 + z3) << CONST_BITS;
  175391. tmp1 = (z2 - z3) << CONST_BITS;
  175392. tmp10 = tmp0 + tmp3;
  175393. tmp13 = tmp0 - tmp3;
  175394. tmp11 = tmp1 + tmp2;
  175395. tmp12 = tmp1 - tmp2;
  175396. /* Odd part per figure 8; the matrix is unitary and hence its
  175397. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  175398. */
  175399. tmp0 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175400. tmp1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175401. tmp2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175402. tmp3 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175403. z1 = tmp0 + tmp3;
  175404. z2 = tmp1 + tmp2;
  175405. z3 = tmp0 + tmp2;
  175406. z4 = tmp1 + tmp3;
  175407. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  175408. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  175409. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  175410. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  175411. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  175412. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  175413. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  175414. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  175415. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  175416. z3 += z5;
  175417. z4 += z5;
  175418. tmp0 += z1 + z3;
  175419. tmp1 += z2 + z4;
  175420. tmp2 += z2 + z3;
  175421. tmp3 += z1 + z4;
  175422. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  175423. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp3, CONST_BITS-PASS1_BITS);
  175424. wsptr[DCTSIZE*7] = (int) DESCALE(tmp10 - tmp3, CONST_BITS-PASS1_BITS);
  175425. wsptr[DCTSIZE*1] = (int) DESCALE(tmp11 + tmp2, CONST_BITS-PASS1_BITS);
  175426. wsptr[DCTSIZE*6] = (int) DESCALE(tmp11 - tmp2, CONST_BITS-PASS1_BITS);
  175427. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 + tmp1, CONST_BITS-PASS1_BITS);
  175428. wsptr[DCTSIZE*5] = (int) DESCALE(tmp12 - tmp1, CONST_BITS-PASS1_BITS);
  175429. wsptr[DCTSIZE*3] = (int) DESCALE(tmp13 + tmp0, CONST_BITS-PASS1_BITS);
  175430. wsptr[DCTSIZE*4] = (int) DESCALE(tmp13 - tmp0, CONST_BITS-PASS1_BITS);
  175431. inptr++; /* advance pointers to next column */
  175432. quantptr++;
  175433. wsptr++;
  175434. }
  175435. /* Pass 2: process rows from work array, store into output array. */
  175436. /* Note that we must descale the results by a factor of 8 == 2**3, */
  175437. /* and also undo the PASS1_BITS scaling. */
  175438. wsptr = workspace;
  175439. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  175440. outptr = output_buf[ctr] + output_col;
  175441. /* Rows of zeroes can be exploited in the same way as we did with columns.
  175442. * However, the column calculation has created many nonzero AC terms, so
  175443. * the simplification applies less often (typically 5% to 10% of the time).
  175444. * On machines with very fast multiplication, it's possible that the
  175445. * test takes more time than it's worth. In that case this section
  175446. * may be commented out.
  175447. */
  175448. #ifndef NO_ZERO_ROW_TEST
  175449. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  175450. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175451. /* AC terms all zero */
  175452. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175453. & RANGE_MASK];
  175454. outptr[0] = dcval;
  175455. outptr[1] = dcval;
  175456. outptr[2] = dcval;
  175457. outptr[3] = dcval;
  175458. outptr[4] = dcval;
  175459. outptr[5] = dcval;
  175460. outptr[6] = dcval;
  175461. outptr[7] = dcval;
  175462. wsptr += DCTSIZE; /* advance pointer to next row */
  175463. continue;
  175464. }
  175465. #endif
  175466. /* Even part: reverse the even part of the forward DCT. */
  175467. /* The rotator is sqrt(2)*c(-6). */
  175468. z2 = (INT32) wsptr[2];
  175469. z3 = (INT32) wsptr[6];
  175470. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  175471. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  175472. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  175473. tmp0 = ((INT32) wsptr[0] + (INT32) wsptr[4]) << CONST_BITS;
  175474. tmp1 = ((INT32) wsptr[0] - (INT32) wsptr[4]) << CONST_BITS;
  175475. tmp10 = tmp0 + tmp3;
  175476. tmp13 = tmp0 - tmp3;
  175477. tmp11 = tmp1 + tmp2;
  175478. tmp12 = tmp1 - tmp2;
  175479. /* Odd part per figure 8; the matrix is unitary and hence its
  175480. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  175481. */
  175482. tmp0 = (INT32) wsptr[7];
  175483. tmp1 = (INT32) wsptr[5];
  175484. tmp2 = (INT32) wsptr[3];
  175485. tmp3 = (INT32) wsptr[1];
  175486. z1 = tmp0 + tmp3;
  175487. z2 = tmp1 + tmp2;
  175488. z3 = tmp0 + tmp2;
  175489. z4 = tmp1 + tmp3;
  175490. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  175491. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  175492. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  175493. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  175494. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  175495. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  175496. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  175497. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  175498. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  175499. z3 += z5;
  175500. z4 += z5;
  175501. tmp0 += z1 + z3;
  175502. tmp1 += z2 + z4;
  175503. tmp2 += z2 + z3;
  175504. tmp3 += z1 + z4;
  175505. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  175506. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp3,
  175507. CONST_BITS+PASS1_BITS+3)
  175508. & RANGE_MASK];
  175509. outptr[7] = range_limit[(int) DESCALE(tmp10 - tmp3,
  175510. CONST_BITS+PASS1_BITS+3)
  175511. & RANGE_MASK];
  175512. outptr[1] = range_limit[(int) DESCALE(tmp11 + tmp2,
  175513. CONST_BITS+PASS1_BITS+3)
  175514. & RANGE_MASK];
  175515. outptr[6] = range_limit[(int) DESCALE(tmp11 - tmp2,
  175516. CONST_BITS+PASS1_BITS+3)
  175517. & RANGE_MASK];
  175518. outptr[2] = range_limit[(int) DESCALE(tmp12 + tmp1,
  175519. CONST_BITS+PASS1_BITS+3)
  175520. & RANGE_MASK];
  175521. outptr[5] = range_limit[(int) DESCALE(tmp12 - tmp1,
  175522. CONST_BITS+PASS1_BITS+3)
  175523. & RANGE_MASK];
  175524. outptr[3] = range_limit[(int) DESCALE(tmp13 + tmp0,
  175525. CONST_BITS+PASS1_BITS+3)
  175526. & RANGE_MASK];
  175527. outptr[4] = range_limit[(int) DESCALE(tmp13 - tmp0,
  175528. CONST_BITS+PASS1_BITS+3)
  175529. & RANGE_MASK];
  175530. wsptr += DCTSIZE; /* advance pointer to next row */
  175531. }
  175532. }
  175533. #endif /* DCT_ISLOW_SUPPORTED */
  175534. /*** End of inlined file: jidctint.c ***/
  175535. /*** Start of inlined file: jidctred.c ***/
  175536. #define JPEG_INTERNALS
  175537. #ifdef IDCT_SCALING_SUPPORTED
  175538. /*
  175539. * This module is specialized to the case DCTSIZE = 8.
  175540. */
  175541. #if DCTSIZE != 8
  175542. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  175543. #endif
  175544. /* Scaling is the same as in jidctint.c. */
  175545. #if BITS_IN_JSAMPLE == 8
  175546. #define CONST_BITS 13
  175547. #define PASS1_BITS 2
  175548. #else
  175549. #define CONST_BITS 13
  175550. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  175551. #endif
  175552. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  175553. * causing a lot of useless floating-point operations at run time.
  175554. * To get around this we use the following pre-calculated constants.
  175555. * If you change CONST_BITS you may want to add appropriate values.
  175556. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  175557. */
  175558. #if CONST_BITS == 13
  175559. #define FIX_0_211164243 ((INT32) 1730) /* FIX(0.211164243) */
  175560. #define FIX_0_509795579 ((INT32) 4176) /* FIX(0.509795579) */
  175561. #define FIX_0_601344887 ((INT32) 4926) /* FIX(0.601344887) */
  175562. #define FIX_0_720959822 ((INT32) 5906) /* FIX(0.720959822) */
  175563. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  175564. #define FIX_0_850430095 ((INT32) 6967) /* FIX(0.850430095) */
  175565. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  175566. #define FIX_1_061594337 ((INT32) 8697) /* FIX(1.061594337) */
  175567. #define FIX_1_272758580 ((INT32) 10426) /* FIX(1.272758580) */
  175568. #define FIX_1_451774981 ((INT32) 11893) /* FIX(1.451774981) */
  175569. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  175570. #define FIX_2_172734803 ((INT32) 17799) /* FIX(2.172734803) */
  175571. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  175572. #define FIX_3_624509785 ((INT32) 29692) /* FIX(3.624509785) */
  175573. #else
  175574. #define FIX_0_211164243 FIX(0.211164243)
  175575. #define FIX_0_509795579 FIX(0.509795579)
  175576. #define FIX_0_601344887 FIX(0.601344887)
  175577. #define FIX_0_720959822 FIX(0.720959822)
  175578. #define FIX_0_765366865 FIX(0.765366865)
  175579. #define FIX_0_850430095 FIX(0.850430095)
  175580. #define FIX_0_899976223 FIX(0.899976223)
  175581. #define FIX_1_061594337 FIX(1.061594337)
  175582. #define FIX_1_272758580 FIX(1.272758580)
  175583. #define FIX_1_451774981 FIX(1.451774981)
  175584. #define FIX_1_847759065 FIX(1.847759065)
  175585. #define FIX_2_172734803 FIX(2.172734803)
  175586. #define FIX_2_562915447 FIX(2.562915447)
  175587. #define FIX_3_624509785 FIX(3.624509785)
  175588. #endif
  175589. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  175590. * For 8-bit samples with the recommended scaling, all the variable
  175591. * and constant values involved are no more than 16 bits wide, so a
  175592. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  175593. * For 12-bit samples, a full 32-bit multiplication will be needed.
  175594. */
  175595. #if BITS_IN_JSAMPLE == 8
  175596. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  175597. #else
  175598. #define MULTIPLY(var,const) ((var) * (const))
  175599. #endif
  175600. /* Dequantize a coefficient by multiplying it by the multiplier-table
  175601. * entry; produce an int result. In this module, both inputs and result
  175602. * are 16 bits or less, so either int or short multiply will work.
  175603. */
  175604. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  175605. /*
  175606. * Perform dequantization and inverse DCT on one block of coefficients,
  175607. * producing a reduced-size 4x4 output block.
  175608. */
  175609. GLOBAL(void)
  175610. jpeg_idct_4x4 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175611. JCOEFPTR coef_block,
  175612. JSAMPARRAY output_buf, JDIMENSION output_col)
  175613. {
  175614. INT32 tmp0, tmp2, tmp10, tmp12;
  175615. INT32 z1, z2, z3, z4;
  175616. JCOEFPTR inptr;
  175617. ISLOW_MULT_TYPE * quantptr;
  175618. int * wsptr;
  175619. JSAMPROW outptr;
  175620. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175621. int ctr;
  175622. int workspace[DCTSIZE*4]; /* buffers data between passes */
  175623. SHIFT_TEMPS
  175624. /* Pass 1: process columns from input, store into work array. */
  175625. inptr = coef_block;
  175626. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175627. wsptr = workspace;
  175628. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  175629. /* Don't bother to process column 4, because second pass won't use it */
  175630. if (ctr == DCTSIZE-4)
  175631. continue;
  175632. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175633. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*5] == 0 &&
  175634. inptr[DCTSIZE*6] == 0 && inptr[DCTSIZE*7] == 0) {
  175635. /* AC terms all zero; we need not examine term 4 for 4x4 output */
  175636. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175637. wsptr[DCTSIZE*0] = dcval;
  175638. wsptr[DCTSIZE*1] = dcval;
  175639. wsptr[DCTSIZE*2] = dcval;
  175640. wsptr[DCTSIZE*3] = dcval;
  175641. continue;
  175642. }
  175643. /* Even part */
  175644. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175645. tmp0 <<= (CONST_BITS+1);
  175646. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175647. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175648. tmp2 = MULTIPLY(z2, FIX_1_847759065) + MULTIPLY(z3, - FIX_0_765366865);
  175649. tmp10 = tmp0 + tmp2;
  175650. tmp12 = tmp0 - tmp2;
  175651. /* Odd part */
  175652. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175653. z2 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175654. z3 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175655. z4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175656. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  175657. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  175658. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  175659. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  175660. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  175661. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  175662. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  175663. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  175664. /* Final output stage */
  175665. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp2, CONST_BITS-PASS1_BITS+1);
  175666. wsptr[DCTSIZE*3] = (int) DESCALE(tmp10 - tmp2, CONST_BITS-PASS1_BITS+1);
  175667. wsptr[DCTSIZE*1] = (int) DESCALE(tmp12 + tmp0, CONST_BITS-PASS1_BITS+1);
  175668. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 - tmp0, CONST_BITS-PASS1_BITS+1);
  175669. }
  175670. /* Pass 2: process 4 rows from work array, store into output array. */
  175671. wsptr = workspace;
  175672. for (ctr = 0; ctr < 4; ctr++) {
  175673. outptr = output_buf[ctr] + output_col;
  175674. /* It's not clear whether a zero row test is worthwhile here ... */
  175675. #ifndef NO_ZERO_ROW_TEST
  175676. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 &&
  175677. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175678. /* AC terms all zero */
  175679. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175680. & RANGE_MASK];
  175681. outptr[0] = dcval;
  175682. outptr[1] = dcval;
  175683. outptr[2] = dcval;
  175684. outptr[3] = dcval;
  175685. wsptr += DCTSIZE; /* advance pointer to next row */
  175686. continue;
  175687. }
  175688. #endif
  175689. /* Even part */
  175690. tmp0 = ((INT32) wsptr[0]) << (CONST_BITS+1);
  175691. tmp2 = MULTIPLY((INT32) wsptr[2], FIX_1_847759065)
  175692. + MULTIPLY((INT32) wsptr[6], - FIX_0_765366865);
  175693. tmp10 = tmp0 + tmp2;
  175694. tmp12 = tmp0 - tmp2;
  175695. /* Odd part */
  175696. z1 = (INT32) wsptr[7];
  175697. z2 = (INT32) wsptr[5];
  175698. z3 = (INT32) wsptr[3];
  175699. z4 = (INT32) wsptr[1];
  175700. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  175701. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  175702. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  175703. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  175704. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  175705. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  175706. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  175707. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  175708. /* Final output stage */
  175709. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp2,
  175710. CONST_BITS+PASS1_BITS+3+1)
  175711. & RANGE_MASK];
  175712. outptr[3] = range_limit[(int) DESCALE(tmp10 - tmp2,
  175713. CONST_BITS+PASS1_BITS+3+1)
  175714. & RANGE_MASK];
  175715. outptr[1] = range_limit[(int) DESCALE(tmp12 + tmp0,
  175716. CONST_BITS+PASS1_BITS+3+1)
  175717. & RANGE_MASK];
  175718. outptr[2] = range_limit[(int) DESCALE(tmp12 - tmp0,
  175719. CONST_BITS+PASS1_BITS+3+1)
  175720. & RANGE_MASK];
  175721. wsptr += DCTSIZE; /* advance pointer to next row */
  175722. }
  175723. }
  175724. /*
  175725. * Perform dequantization and inverse DCT on one block of coefficients,
  175726. * producing a reduced-size 2x2 output block.
  175727. */
  175728. GLOBAL(void)
  175729. jpeg_idct_2x2 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175730. JCOEFPTR coef_block,
  175731. JSAMPARRAY output_buf, JDIMENSION output_col)
  175732. {
  175733. INT32 tmp0, tmp10, z1;
  175734. JCOEFPTR inptr;
  175735. ISLOW_MULT_TYPE * quantptr;
  175736. int * wsptr;
  175737. JSAMPROW outptr;
  175738. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175739. int ctr;
  175740. int workspace[DCTSIZE*2]; /* buffers data between passes */
  175741. SHIFT_TEMPS
  175742. /* Pass 1: process columns from input, store into work array. */
  175743. inptr = coef_block;
  175744. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175745. wsptr = workspace;
  175746. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  175747. /* Don't bother to process columns 2,4,6 */
  175748. if (ctr == DCTSIZE-2 || ctr == DCTSIZE-4 || ctr == DCTSIZE-6)
  175749. continue;
  175750. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*3] == 0 &&
  175751. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*7] == 0) {
  175752. /* AC terms all zero; we need not examine terms 2,4,6 for 2x2 output */
  175753. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175754. wsptr[DCTSIZE*0] = dcval;
  175755. wsptr[DCTSIZE*1] = dcval;
  175756. continue;
  175757. }
  175758. /* Even part */
  175759. z1 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175760. tmp10 = z1 << (CONST_BITS+2);
  175761. /* Odd part */
  175762. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175763. tmp0 = MULTIPLY(z1, - FIX_0_720959822); /* sqrt(2) * (c7-c5+c3-c1) */
  175764. z1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175765. tmp0 += MULTIPLY(z1, FIX_0_850430095); /* sqrt(2) * (-c1+c3+c5+c7) */
  175766. z1 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175767. tmp0 += MULTIPLY(z1, - FIX_1_272758580); /* sqrt(2) * (-c1+c3-c5-c7) */
  175768. z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175769. tmp0 += MULTIPLY(z1, FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  175770. /* Final output stage */
  175771. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp0, CONST_BITS-PASS1_BITS+2);
  175772. wsptr[DCTSIZE*1] = (int) DESCALE(tmp10 - tmp0, CONST_BITS-PASS1_BITS+2);
  175773. }
  175774. /* Pass 2: process 2 rows from work array, store into output array. */
  175775. wsptr = workspace;
  175776. for (ctr = 0; ctr < 2; ctr++) {
  175777. outptr = output_buf[ctr] + output_col;
  175778. /* It's not clear whether a zero row test is worthwhile here ... */
  175779. #ifndef NO_ZERO_ROW_TEST
  175780. if (wsptr[1] == 0 && wsptr[3] == 0 && wsptr[5] == 0 && wsptr[7] == 0) {
  175781. /* AC terms all zero */
  175782. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175783. & RANGE_MASK];
  175784. outptr[0] = dcval;
  175785. outptr[1] = dcval;
  175786. wsptr += DCTSIZE; /* advance pointer to next row */
  175787. continue;
  175788. }
  175789. #endif
  175790. /* Even part */
  175791. tmp10 = ((INT32) wsptr[0]) << (CONST_BITS+2);
  175792. /* Odd part */
  175793. tmp0 = MULTIPLY((INT32) wsptr[7], - FIX_0_720959822) /* sqrt(2) * (c7-c5+c3-c1) */
  175794. + MULTIPLY((INT32) wsptr[5], FIX_0_850430095) /* sqrt(2) * (-c1+c3+c5+c7) */
  175795. + MULTIPLY((INT32) wsptr[3], - FIX_1_272758580) /* sqrt(2) * (-c1+c3-c5-c7) */
  175796. + MULTIPLY((INT32) wsptr[1], FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  175797. /* Final output stage */
  175798. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp0,
  175799. CONST_BITS+PASS1_BITS+3+2)
  175800. & RANGE_MASK];
  175801. outptr[1] = range_limit[(int) DESCALE(tmp10 - tmp0,
  175802. CONST_BITS+PASS1_BITS+3+2)
  175803. & RANGE_MASK];
  175804. wsptr += DCTSIZE; /* advance pointer to next row */
  175805. }
  175806. }
  175807. /*
  175808. * Perform dequantization and inverse DCT on one block of coefficients,
  175809. * producing a reduced-size 1x1 output block.
  175810. */
  175811. GLOBAL(void)
  175812. jpeg_idct_1x1 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175813. JCOEFPTR coef_block,
  175814. JSAMPARRAY output_buf, JDIMENSION output_col)
  175815. {
  175816. int dcval;
  175817. ISLOW_MULT_TYPE * quantptr;
  175818. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175819. SHIFT_TEMPS
  175820. /* We hardly need an inverse DCT routine for this: just take the
  175821. * average pixel value, which is one-eighth of the DC coefficient.
  175822. */
  175823. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175824. dcval = DEQUANTIZE(coef_block[0], quantptr[0]);
  175825. dcval = (int) DESCALE((INT32) dcval, 3);
  175826. output_buf[0][output_col] = range_limit[dcval & RANGE_MASK];
  175827. }
  175828. #endif /* IDCT_SCALING_SUPPORTED */
  175829. /*** End of inlined file: jidctred.c ***/
  175830. /*** Start of inlined file: jmemmgr.c ***/
  175831. #define JPEG_INTERNALS
  175832. #define AM_MEMORY_MANAGER /* we define jvirt_Xarray_control structs */
  175833. /*** Start of inlined file: jmemsys.h ***/
  175834. #ifndef __jmemsys_h__
  175835. #define __jmemsys_h__
  175836. /* Short forms of external names for systems with brain-damaged linkers. */
  175837. #ifdef NEED_SHORT_EXTERNAL_NAMES
  175838. #define jpeg_get_small jGetSmall
  175839. #define jpeg_free_small jFreeSmall
  175840. #define jpeg_get_large jGetLarge
  175841. #define jpeg_free_large jFreeLarge
  175842. #define jpeg_mem_available jMemAvail
  175843. #define jpeg_open_backing_store jOpenBackStore
  175844. #define jpeg_mem_init jMemInit
  175845. #define jpeg_mem_term jMemTerm
  175846. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  175847. /*
  175848. * These two functions are used to allocate and release small chunks of
  175849. * memory. (Typically the total amount requested through jpeg_get_small is
  175850. * no more than 20K or so; this will be requested in chunks of a few K each.)
  175851. * Behavior should be the same as for the standard library functions malloc
  175852. * and free; in particular, jpeg_get_small must return NULL on failure.
  175853. * On most systems, these ARE malloc and free. jpeg_free_small is passed the
  175854. * size of the object being freed, just in case it's needed.
  175855. * On an 80x86 machine using small-data memory model, these manage near heap.
  175856. */
  175857. EXTERN(void *) jpeg_get_small JPP((j_common_ptr cinfo, size_t sizeofobject));
  175858. EXTERN(void) jpeg_free_small JPP((j_common_ptr cinfo, void * object,
  175859. size_t sizeofobject));
  175860. /*
  175861. * These two functions are used to allocate and release large chunks of
  175862. * memory (up to the total free space designated by jpeg_mem_available).
  175863. * The interface is the same as above, except that on an 80x86 machine,
  175864. * far pointers are used. On most other machines these are identical to
  175865. * the jpeg_get/free_small routines; but we keep them separate anyway,
  175866. * in case a different allocation strategy is desirable for large chunks.
  175867. */
  175868. EXTERN(void FAR *) jpeg_get_large JPP((j_common_ptr cinfo,
  175869. size_t sizeofobject));
  175870. EXTERN(void) jpeg_free_large JPP((j_common_ptr cinfo, void FAR * object,
  175871. size_t sizeofobject));
  175872. /*
  175873. * The macro MAX_ALLOC_CHUNK designates the maximum number of bytes that may
  175874. * be requested in a single call to jpeg_get_large (and jpeg_get_small for that
  175875. * matter, but that case should never come into play). This macro is needed
  175876. * to model the 64Kb-segment-size limit of far addressing on 80x86 machines.
  175877. * On those machines, we expect that jconfig.h will provide a proper value.
  175878. * On machines with 32-bit flat address spaces, any large constant may be used.
  175879. *
  175880. * NB: jmemmgr.c expects that MAX_ALLOC_CHUNK will be representable as type
  175881. * size_t and will be a multiple of sizeof(align_type).
  175882. */
  175883. #ifndef MAX_ALLOC_CHUNK /* may be overridden in jconfig.h */
  175884. #define MAX_ALLOC_CHUNK 1000000000L
  175885. #endif
  175886. /*
  175887. * This routine computes the total space still available for allocation by
  175888. * jpeg_get_large. If more space than this is needed, backing store will be
  175889. * used. NOTE: any memory already allocated must not be counted.
  175890. *
  175891. * There is a minimum space requirement, corresponding to the minimum
  175892. * feasible buffer sizes; jmemmgr.c will request that much space even if
  175893. * jpeg_mem_available returns zero. The maximum space needed, enough to hold
  175894. * all working storage in memory, is also passed in case it is useful.
  175895. * Finally, the total space already allocated is passed. If no better
  175896. * method is available, cinfo->mem->max_memory_to_use - already_allocated
  175897. * is often a suitable calculation.
  175898. *
  175899. * It is OK for jpeg_mem_available to underestimate the space available
  175900. * (that'll just lead to more backing-store access than is really necessary).
  175901. * However, an overestimate will lead to failure. Hence it's wise to subtract
  175902. * a slop factor from the true available space. 5% should be enough.
  175903. *
  175904. * On machines with lots of virtual memory, any large constant may be returned.
  175905. * Conversely, zero may be returned to always use the minimum amount of memory.
  175906. */
  175907. EXTERN(long) jpeg_mem_available JPP((j_common_ptr cinfo,
  175908. long min_bytes_needed,
  175909. long max_bytes_needed,
  175910. long already_allocated));
  175911. /*
  175912. * This structure holds whatever state is needed to access a single
  175913. * backing-store object. The read/write/close method pointers are called
  175914. * by jmemmgr.c to manipulate the backing-store object; all other fields
  175915. * are private to the system-dependent backing store routines.
  175916. */
  175917. #define TEMP_NAME_LENGTH 64 /* max length of a temporary file's name */
  175918. #ifdef USE_MSDOS_MEMMGR /* DOS-specific junk */
  175919. typedef unsigned short XMSH; /* type of extended-memory handles */
  175920. typedef unsigned short EMSH; /* type of expanded-memory handles */
  175921. typedef union {
  175922. short file_handle; /* DOS file handle if it's a temp file */
  175923. XMSH xms_handle; /* handle if it's a chunk of XMS */
  175924. EMSH ems_handle; /* handle if it's a chunk of EMS */
  175925. } handle_union;
  175926. #endif /* USE_MSDOS_MEMMGR */
  175927. #ifdef USE_MAC_MEMMGR /* Mac-specific junk */
  175928. #include <Files.h>
  175929. #endif /* USE_MAC_MEMMGR */
  175930. //typedef struct backing_store_struct * backing_store_ptr;
  175931. typedef struct backing_store_struct {
  175932. /* Methods for reading/writing/closing this backing-store object */
  175933. JMETHOD(void, read_backing_store, (j_common_ptr cinfo,
  175934. struct backing_store_struct *info,
  175935. void FAR * buffer_address,
  175936. long file_offset, long byte_count));
  175937. JMETHOD(void, write_backing_store, (j_common_ptr cinfo,
  175938. struct backing_store_struct *info,
  175939. void FAR * buffer_address,
  175940. long file_offset, long byte_count));
  175941. JMETHOD(void, close_backing_store, (j_common_ptr cinfo,
  175942. struct backing_store_struct *info));
  175943. /* Private fields for system-dependent backing-store management */
  175944. #ifdef USE_MSDOS_MEMMGR
  175945. /* For the MS-DOS manager (jmemdos.c), we need: */
  175946. handle_union handle; /* reference to backing-store storage object */
  175947. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  175948. #else
  175949. #ifdef USE_MAC_MEMMGR
  175950. /* For the Mac manager (jmemmac.c), we need: */
  175951. short temp_file; /* file reference number to temp file */
  175952. FSSpec tempSpec; /* the FSSpec for the temp file */
  175953. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  175954. #else
  175955. /* For a typical implementation with temp files, we need: */
  175956. FILE * temp_file; /* stdio reference to temp file */
  175957. char temp_name[TEMP_NAME_LENGTH]; /* name of temp file */
  175958. #endif
  175959. #endif
  175960. } backing_store_info;
  175961. /*
  175962. * Initial opening of a backing-store object. This must fill in the
  175963. * read/write/close pointers in the object. The read/write routines
  175964. * may take an error exit if the specified maximum file size is exceeded.
  175965. * (If jpeg_mem_available always returns a large value, this routine can
  175966. * just take an error exit.)
  175967. */
  175968. EXTERN(void) jpeg_open_backing_store JPP((j_common_ptr cinfo,
  175969. struct backing_store_struct *info,
  175970. long total_bytes_needed));
  175971. /*
  175972. * These routines take care of any system-dependent initialization and
  175973. * cleanup required. jpeg_mem_init will be called before anything is
  175974. * allocated (and, therefore, nothing in cinfo is of use except the error
  175975. * manager pointer). It should return a suitable default value for
  175976. * max_memory_to_use; this may subsequently be overridden by the surrounding
  175977. * application. (Note that max_memory_to_use is only important if
  175978. * jpeg_mem_available chooses to consult it ... no one else will.)
  175979. * jpeg_mem_term may assume that all requested memory has been freed and that
  175980. * all opened backing-store objects have been closed.
  175981. */
  175982. EXTERN(long) jpeg_mem_init JPP((j_common_ptr cinfo));
  175983. EXTERN(void) jpeg_mem_term JPP((j_common_ptr cinfo));
  175984. #endif
  175985. /*** End of inlined file: jmemsys.h ***/
  175986. /* import the system-dependent declarations */
  175987. #ifndef NO_GETENV
  175988. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare getenv() */
  175989. extern char * getenv JPP((const char * name));
  175990. #endif
  175991. #endif
  175992. /*
  175993. * Some important notes:
  175994. * The allocation routines provided here must never return NULL.
  175995. * They should exit to error_exit if unsuccessful.
  175996. *
  175997. * It's not a good idea to try to merge the sarray and barray routines,
  175998. * even though they are textually almost the same, because samples are
  175999. * usually stored as bytes while coefficients are shorts or ints. Thus,
  176000. * in machines where byte pointers have a different representation from
  176001. * word pointers, the resulting machine code could not be the same.
  176002. */
  176003. /*
  176004. * Many machines require storage alignment: longs must start on 4-byte
  176005. * boundaries, doubles on 8-byte boundaries, etc. On such machines, malloc()
  176006. * always returns pointers that are multiples of the worst-case alignment
  176007. * requirement, and we had better do so too.
  176008. * There isn't any really portable way to determine the worst-case alignment
  176009. * requirement. This module assumes that the alignment requirement is
  176010. * multiples of sizeof(ALIGN_TYPE).
  176011. * By default, we define ALIGN_TYPE as double. This is necessary on some
  176012. * workstations (where doubles really do need 8-byte alignment) and will work
  176013. * fine on nearly everything. If your machine has lesser alignment needs,
  176014. * you can save a few bytes by making ALIGN_TYPE smaller.
  176015. * The only place I know of where this will NOT work is certain Macintosh
  176016. * 680x0 compilers that define double as a 10-byte IEEE extended float.
  176017. * Doing 10-byte alignment is counterproductive because longwords won't be
  176018. * aligned well. Put "#define ALIGN_TYPE long" in jconfig.h if you have
  176019. * such a compiler.
  176020. */
  176021. #ifndef ALIGN_TYPE /* so can override from jconfig.h */
  176022. #define ALIGN_TYPE double
  176023. #endif
  176024. /*
  176025. * We allocate objects from "pools", where each pool is gotten with a single
  176026. * request to jpeg_get_small() or jpeg_get_large(). There is no per-object
  176027. * overhead within a pool, except for alignment padding. Each pool has a
  176028. * header with a link to the next pool of the same class.
  176029. * Small and large pool headers are identical except that the latter's
  176030. * link pointer must be FAR on 80x86 machines.
  176031. * Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE
  176032. * field. This forces the compiler to make SIZEOF(small_pool_hdr) a multiple
  176033. * of the alignment requirement of ALIGN_TYPE.
  176034. */
  176035. typedef union small_pool_struct * small_pool_ptr;
  176036. typedef union small_pool_struct {
  176037. struct {
  176038. small_pool_ptr next; /* next in list of pools */
  176039. size_t bytes_used; /* how many bytes already used within pool */
  176040. size_t bytes_left; /* bytes still available in this pool */
  176041. } hdr;
  176042. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  176043. } small_pool_hdr;
  176044. typedef union large_pool_struct FAR * large_pool_ptr;
  176045. typedef union large_pool_struct {
  176046. struct {
  176047. large_pool_ptr next; /* next in list of pools */
  176048. size_t bytes_used; /* how many bytes already used within pool */
  176049. size_t bytes_left; /* bytes still available in this pool */
  176050. } hdr;
  176051. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  176052. } large_pool_hdr;
  176053. /*
  176054. * Here is the full definition of a memory manager object.
  176055. */
  176056. typedef struct {
  176057. struct jpeg_memory_mgr pub; /* public fields */
  176058. /* Each pool identifier (lifetime class) names a linked list of pools. */
  176059. small_pool_ptr small_list[JPOOL_NUMPOOLS];
  176060. large_pool_ptr large_list[JPOOL_NUMPOOLS];
  176061. /* Since we only have one lifetime class of virtual arrays, only one
  176062. * linked list is necessary (for each datatype). Note that the virtual
  176063. * array control blocks being linked together are actually stored somewhere
  176064. * in the small-pool list.
  176065. */
  176066. jvirt_sarray_ptr virt_sarray_list;
  176067. jvirt_barray_ptr virt_barray_list;
  176068. /* This counts total space obtained from jpeg_get_small/large */
  176069. long total_space_allocated;
  176070. /* alloc_sarray and alloc_barray set this value for use by virtual
  176071. * array routines.
  176072. */
  176073. JDIMENSION last_rowsperchunk; /* from most recent alloc_sarray/barray */
  176074. } my_memory_mgr;
  176075. typedef my_memory_mgr * my_mem_ptr;
  176076. /*
  176077. * The control blocks for virtual arrays.
  176078. * Note that these blocks are allocated in the "small" pool area.
  176079. * System-dependent info for the associated backing store (if any) is hidden
  176080. * inside the backing_store_info struct.
  176081. */
  176082. struct jvirt_sarray_control {
  176083. JSAMPARRAY mem_buffer; /* => the in-memory buffer */
  176084. JDIMENSION rows_in_array; /* total virtual array height */
  176085. JDIMENSION samplesperrow; /* width of array (and of memory buffer) */
  176086. JDIMENSION maxaccess; /* max rows accessed by access_virt_sarray */
  176087. JDIMENSION rows_in_mem; /* height of memory buffer */
  176088. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  176089. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  176090. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  176091. boolean pre_zero; /* pre-zero mode requested? */
  176092. boolean dirty; /* do current buffer contents need written? */
  176093. boolean b_s_open; /* is backing-store data valid? */
  176094. jvirt_sarray_ptr next; /* link to next virtual sarray control block */
  176095. backing_store_info b_s_info; /* System-dependent control info */
  176096. };
  176097. struct jvirt_barray_control {
  176098. JBLOCKARRAY mem_buffer; /* => the in-memory buffer */
  176099. JDIMENSION rows_in_array; /* total virtual array height */
  176100. JDIMENSION blocksperrow; /* width of array (and of memory buffer) */
  176101. JDIMENSION maxaccess; /* max rows accessed by access_virt_barray */
  176102. JDIMENSION rows_in_mem; /* height of memory buffer */
  176103. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  176104. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  176105. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  176106. boolean pre_zero; /* pre-zero mode requested? */
  176107. boolean dirty; /* do current buffer contents need written? */
  176108. boolean b_s_open; /* is backing-store data valid? */
  176109. jvirt_barray_ptr next; /* link to next virtual barray control block */
  176110. backing_store_info b_s_info; /* System-dependent control info */
  176111. };
  176112. #ifdef MEM_STATS /* optional extra stuff for statistics */
  176113. LOCAL(void)
  176114. print_mem_stats (j_common_ptr cinfo, int pool_id)
  176115. {
  176116. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176117. small_pool_ptr shdr_ptr;
  176118. large_pool_ptr lhdr_ptr;
  176119. /* Since this is only a debugging stub, we can cheat a little by using
  176120. * fprintf directly rather than going through the trace message code.
  176121. * This is helpful because message parm array can't handle longs.
  176122. */
  176123. fprintf(stderr, "Freeing pool %d, total space = %ld\n",
  176124. pool_id, mem->total_space_allocated);
  176125. for (lhdr_ptr = mem->large_list[pool_id]; lhdr_ptr != NULL;
  176126. lhdr_ptr = lhdr_ptr->hdr.next) {
  176127. fprintf(stderr, " Large chunk used %ld\n",
  176128. (long) lhdr_ptr->hdr.bytes_used);
  176129. }
  176130. for (shdr_ptr = mem->small_list[pool_id]; shdr_ptr != NULL;
  176131. shdr_ptr = shdr_ptr->hdr.next) {
  176132. fprintf(stderr, " Small chunk used %ld free %ld\n",
  176133. (long) shdr_ptr->hdr.bytes_used,
  176134. (long) shdr_ptr->hdr.bytes_left);
  176135. }
  176136. }
  176137. #endif /* MEM_STATS */
  176138. LOCAL(void)
  176139. out_of_memory (j_common_ptr cinfo, int which)
  176140. /* Report an out-of-memory error and stop execution */
  176141. /* If we compiled MEM_STATS support, report alloc requests before dying */
  176142. {
  176143. #ifdef MEM_STATS
  176144. cinfo->err->trace_level = 2; /* force self_destruct to report stats */
  176145. #endif
  176146. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, which);
  176147. }
  176148. /*
  176149. * Allocation of "small" objects.
  176150. *
  176151. * For these, we use pooled storage. When a new pool must be created,
  176152. * we try to get enough space for the current request plus a "slop" factor,
  176153. * where the slop will be the amount of leftover space in the new pool.
  176154. * The speed vs. space tradeoff is largely determined by the slop values.
  176155. * A different slop value is provided for each pool class (lifetime),
  176156. * and we also distinguish the first pool of a class from later ones.
  176157. * NOTE: the values given work fairly well on both 16- and 32-bit-int
  176158. * machines, but may be too small if longs are 64 bits or more.
  176159. */
  176160. static const size_t first_pool_slop[JPOOL_NUMPOOLS] =
  176161. {
  176162. 1600, /* first PERMANENT pool */
  176163. 16000 /* first IMAGE pool */
  176164. };
  176165. static const size_t extra_pool_slop[JPOOL_NUMPOOLS] =
  176166. {
  176167. 0, /* additional PERMANENT pools */
  176168. 5000 /* additional IMAGE pools */
  176169. };
  176170. #define MIN_SLOP 50 /* greater than 0 to avoid futile looping */
  176171. METHODDEF(void *)
  176172. alloc_small (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  176173. /* Allocate a "small" object */
  176174. {
  176175. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176176. small_pool_ptr hdr_ptr, prev_hdr_ptr;
  176177. char * data_ptr;
  176178. size_t odd_bytes, min_request, slop;
  176179. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  176180. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(small_pool_hdr)))
  176181. out_of_memory(cinfo, 1); /* request exceeds malloc's ability */
  176182. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  176183. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  176184. if (odd_bytes > 0)
  176185. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  176186. /* See if space is available in any existing pool */
  176187. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  176188. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176189. prev_hdr_ptr = NULL;
  176190. hdr_ptr = mem->small_list[pool_id];
  176191. while (hdr_ptr != NULL) {
  176192. if (hdr_ptr->hdr.bytes_left >= sizeofobject)
  176193. break; /* found pool with enough space */
  176194. prev_hdr_ptr = hdr_ptr;
  176195. hdr_ptr = hdr_ptr->hdr.next;
  176196. }
  176197. /* Time to make a new pool? */
  176198. if (hdr_ptr == NULL) {
  176199. /* min_request is what we need now, slop is what will be leftover */
  176200. min_request = sizeofobject + SIZEOF(small_pool_hdr);
  176201. if (prev_hdr_ptr == NULL) /* first pool in class? */
  176202. slop = first_pool_slop[pool_id];
  176203. else
  176204. slop = extra_pool_slop[pool_id];
  176205. /* Don't ask for more than MAX_ALLOC_CHUNK */
  176206. if (slop > (size_t) (MAX_ALLOC_CHUNK-min_request))
  176207. slop = (size_t) (MAX_ALLOC_CHUNK-min_request);
  176208. /* Try to get space, if fail reduce slop and try again */
  176209. for (;;) {
  176210. hdr_ptr = (small_pool_ptr) jpeg_get_small(cinfo, min_request + slop);
  176211. if (hdr_ptr != NULL)
  176212. break;
  176213. slop /= 2;
  176214. if (slop < MIN_SLOP) /* give up when it gets real small */
  176215. out_of_memory(cinfo, 2); /* jpeg_get_small failed */
  176216. }
  176217. mem->total_space_allocated += min_request + slop;
  176218. /* Success, initialize the new pool header and add to end of list */
  176219. hdr_ptr->hdr.next = NULL;
  176220. hdr_ptr->hdr.bytes_used = 0;
  176221. hdr_ptr->hdr.bytes_left = sizeofobject + slop;
  176222. if (prev_hdr_ptr == NULL) /* first pool in class? */
  176223. mem->small_list[pool_id] = hdr_ptr;
  176224. else
  176225. prev_hdr_ptr->hdr.next = hdr_ptr;
  176226. }
  176227. /* OK, allocate the object from the current pool */
  176228. data_ptr = (char *) (hdr_ptr + 1); /* point to first data byte in pool */
  176229. data_ptr += hdr_ptr->hdr.bytes_used; /* point to place for object */
  176230. hdr_ptr->hdr.bytes_used += sizeofobject;
  176231. hdr_ptr->hdr.bytes_left -= sizeofobject;
  176232. return (void *) data_ptr;
  176233. }
  176234. /*
  176235. * Allocation of "large" objects.
  176236. *
  176237. * The external semantics of these are the same as "small" objects,
  176238. * except that FAR pointers are used on 80x86. However the pool
  176239. * management heuristics are quite different. We assume that each
  176240. * request is large enough that it may as well be passed directly to
  176241. * jpeg_get_large; the pool management just links everything together
  176242. * so that we can free it all on demand.
  176243. * Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY
  176244. * structures. The routines that create these structures (see below)
  176245. * deliberately bunch rows together to ensure a large request size.
  176246. */
  176247. METHODDEF(void FAR *)
  176248. alloc_large (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  176249. /* Allocate a "large" object */
  176250. {
  176251. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176252. large_pool_ptr hdr_ptr;
  176253. size_t odd_bytes;
  176254. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  176255. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)))
  176256. out_of_memory(cinfo, 3); /* request exceeds malloc's ability */
  176257. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  176258. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  176259. if (odd_bytes > 0)
  176260. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  176261. /* Always make a new pool */
  176262. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  176263. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176264. hdr_ptr = (large_pool_ptr) jpeg_get_large(cinfo, sizeofobject +
  176265. SIZEOF(large_pool_hdr));
  176266. if (hdr_ptr == NULL)
  176267. out_of_memory(cinfo, 4); /* jpeg_get_large failed */
  176268. mem->total_space_allocated += sizeofobject + SIZEOF(large_pool_hdr);
  176269. /* Success, initialize the new pool header and add to list */
  176270. hdr_ptr->hdr.next = mem->large_list[pool_id];
  176271. /* We maintain space counts in each pool header for statistical purposes,
  176272. * even though they are not needed for allocation.
  176273. */
  176274. hdr_ptr->hdr.bytes_used = sizeofobject;
  176275. hdr_ptr->hdr.bytes_left = 0;
  176276. mem->large_list[pool_id] = hdr_ptr;
  176277. return (void FAR *) (hdr_ptr + 1); /* point to first data byte in pool */
  176278. }
  176279. /*
  176280. * Creation of 2-D sample arrays.
  176281. * The pointers are in near heap, the samples themselves in FAR heap.
  176282. *
  176283. * To minimize allocation overhead and to allow I/O of large contiguous
  176284. * blocks, we allocate the sample rows in groups of as many rows as possible
  176285. * without exceeding MAX_ALLOC_CHUNK total bytes per allocation request.
  176286. * NB: the virtual array control routines, later in this file, know about
  176287. * this chunking of rows. The rowsperchunk value is left in the mem manager
  176288. * object so that it can be saved away if this sarray is the workspace for
  176289. * a virtual array.
  176290. */
  176291. METHODDEF(JSAMPARRAY)
  176292. alloc_sarray (j_common_ptr cinfo, int pool_id,
  176293. JDIMENSION samplesperrow, JDIMENSION numrows)
  176294. /* Allocate a 2-D sample array */
  176295. {
  176296. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176297. JSAMPARRAY result;
  176298. JSAMPROW workspace;
  176299. JDIMENSION rowsperchunk, currow, i;
  176300. long ltemp;
  176301. /* Calculate max # of rows allowed in one allocation chunk */
  176302. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  176303. ((long) samplesperrow * SIZEOF(JSAMPLE));
  176304. if (ltemp <= 0)
  176305. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  176306. if (ltemp < (long) numrows)
  176307. rowsperchunk = (JDIMENSION) ltemp;
  176308. else
  176309. rowsperchunk = numrows;
  176310. mem->last_rowsperchunk = rowsperchunk;
  176311. /* Get space for row pointers (small object) */
  176312. result = (JSAMPARRAY) alloc_small(cinfo, pool_id,
  176313. (size_t) (numrows * SIZEOF(JSAMPROW)));
  176314. /* Get the rows themselves (large objects) */
  176315. currow = 0;
  176316. while (currow < numrows) {
  176317. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  176318. workspace = (JSAMPROW) alloc_large(cinfo, pool_id,
  176319. (size_t) ((size_t) rowsperchunk * (size_t) samplesperrow
  176320. * SIZEOF(JSAMPLE)));
  176321. for (i = rowsperchunk; i > 0; i--) {
  176322. result[currow++] = workspace;
  176323. workspace += samplesperrow;
  176324. }
  176325. }
  176326. return result;
  176327. }
  176328. /*
  176329. * Creation of 2-D coefficient-block arrays.
  176330. * This is essentially the same as the code for sample arrays, above.
  176331. */
  176332. METHODDEF(JBLOCKARRAY)
  176333. alloc_barray (j_common_ptr cinfo, int pool_id,
  176334. JDIMENSION blocksperrow, JDIMENSION numrows)
  176335. /* Allocate a 2-D coefficient-block array */
  176336. {
  176337. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176338. JBLOCKARRAY result;
  176339. JBLOCKROW workspace;
  176340. JDIMENSION rowsperchunk, currow, i;
  176341. long ltemp;
  176342. /* Calculate max # of rows allowed in one allocation chunk */
  176343. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  176344. ((long) blocksperrow * SIZEOF(JBLOCK));
  176345. if (ltemp <= 0)
  176346. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  176347. if (ltemp < (long) numrows)
  176348. rowsperchunk = (JDIMENSION) ltemp;
  176349. else
  176350. rowsperchunk = numrows;
  176351. mem->last_rowsperchunk = rowsperchunk;
  176352. /* Get space for row pointers (small object) */
  176353. result = (JBLOCKARRAY) alloc_small(cinfo, pool_id,
  176354. (size_t) (numrows * SIZEOF(JBLOCKROW)));
  176355. /* Get the rows themselves (large objects) */
  176356. currow = 0;
  176357. while (currow < numrows) {
  176358. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  176359. workspace = (JBLOCKROW) alloc_large(cinfo, pool_id,
  176360. (size_t) ((size_t) rowsperchunk * (size_t) blocksperrow
  176361. * SIZEOF(JBLOCK)));
  176362. for (i = rowsperchunk; i > 0; i--) {
  176363. result[currow++] = workspace;
  176364. workspace += blocksperrow;
  176365. }
  176366. }
  176367. return result;
  176368. }
  176369. /*
  176370. * About virtual array management:
  176371. *
  176372. * The above "normal" array routines are only used to allocate strip buffers
  176373. * (as wide as the image, but just a few rows high). Full-image-sized buffers
  176374. * are handled as "virtual" arrays. The array is still accessed a strip at a
  176375. * time, but the memory manager must save the whole array for repeated
  176376. * accesses. The intended implementation is that there is a strip buffer in
  176377. * memory (as high as is possible given the desired memory limit), plus a
  176378. * backing file that holds the rest of the array.
  176379. *
  176380. * The request_virt_array routines are told the total size of the image and
  176381. * the maximum number of rows that will be accessed at once. The in-memory
  176382. * buffer must be at least as large as the maxaccess value.
  176383. *
  176384. * The request routines create control blocks but not the in-memory buffers.
  176385. * That is postponed until realize_virt_arrays is called. At that time the
  176386. * total amount of space needed is known (approximately, anyway), so free
  176387. * memory can be divided up fairly.
  176388. *
  176389. * The access_virt_array routines are responsible for making a specific strip
  176390. * area accessible (after reading or writing the backing file, if necessary).
  176391. * Note that the access routines are told whether the caller intends to modify
  176392. * the accessed strip; during a read-only pass this saves having to rewrite
  176393. * data to disk. The access routines are also responsible for pre-zeroing
  176394. * any newly accessed rows, if pre-zeroing was requested.
  176395. *
  176396. * In current usage, the access requests are usually for nonoverlapping
  176397. * strips; that is, successive access start_row numbers differ by exactly
  176398. * num_rows = maxaccess. This means we can get good performance with simple
  176399. * buffer dump/reload logic, by making the in-memory buffer be a multiple
  176400. * of the access height; then there will never be accesses across bufferload
  176401. * boundaries. The code will still work with overlapping access requests,
  176402. * but it doesn't handle bufferload overlaps very efficiently.
  176403. */
  176404. METHODDEF(jvirt_sarray_ptr)
  176405. request_virt_sarray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  176406. JDIMENSION samplesperrow, JDIMENSION numrows,
  176407. JDIMENSION maxaccess)
  176408. /* Request a virtual 2-D sample array */
  176409. {
  176410. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176411. jvirt_sarray_ptr result;
  176412. /* Only IMAGE-lifetime virtual arrays are currently supported */
  176413. if (pool_id != JPOOL_IMAGE)
  176414. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176415. /* get control block */
  176416. result = (jvirt_sarray_ptr) alloc_small(cinfo, pool_id,
  176417. SIZEOF(struct jvirt_sarray_control));
  176418. result->mem_buffer = NULL; /* marks array not yet realized */
  176419. result->rows_in_array = numrows;
  176420. result->samplesperrow = samplesperrow;
  176421. result->maxaccess = maxaccess;
  176422. result->pre_zero = pre_zero;
  176423. result->b_s_open = FALSE; /* no associated backing-store object */
  176424. result->next = mem->virt_sarray_list; /* add to list of virtual arrays */
  176425. mem->virt_sarray_list = result;
  176426. return result;
  176427. }
  176428. METHODDEF(jvirt_barray_ptr)
  176429. request_virt_barray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  176430. JDIMENSION blocksperrow, JDIMENSION numrows,
  176431. JDIMENSION maxaccess)
  176432. /* Request a virtual 2-D coefficient-block array */
  176433. {
  176434. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176435. jvirt_barray_ptr result;
  176436. /* Only IMAGE-lifetime virtual arrays are currently supported */
  176437. if (pool_id != JPOOL_IMAGE)
  176438. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176439. /* get control block */
  176440. result = (jvirt_barray_ptr) alloc_small(cinfo, pool_id,
  176441. SIZEOF(struct jvirt_barray_control));
  176442. result->mem_buffer = NULL; /* marks array not yet realized */
  176443. result->rows_in_array = numrows;
  176444. result->blocksperrow = blocksperrow;
  176445. result->maxaccess = maxaccess;
  176446. result->pre_zero = pre_zero;
  176447. result->b_s_open = FALSE; /* no associated backing-store object */
  176448. result->next = mem->virt_barray_list; /* add to list of virtual arrays */
  176449. mem->virt_barray_list = result;
  176450. return result;
  176451. }
  176452. METHODDEF(void)
  176453. realize_virt_arrays (j_common_ptr cinfo)
  176454. /* Allocate the in-memory buffers for any unrealized virtual arrays */
  176455. {
  176456. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176457. long space_per_minheight, maximum_space, avail_mem;
  176458. long minheights, max_minheights;
  176459. jvirt_sarray_ptr sptr;
  176460. jvirt_barray_ptr bptr;
  176461. /* Compute the minimum space needed (maxaccess rows in each buffer)
  176462. * and the maximum space needed (full image height in each buffer).
  176463. * These may be of use to the system-dependent jpeg_mem_available routine.
  176464. */
  176465. space_per_minheight = 0;
  176466. maximum_space = 0;
  176467. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176468. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  176469. space_per_minheight += (long) sptr->maxaccess *
  176470. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  176471. maximum_space += (long) sptr->rows_in_array *
  176472. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  176473. }
  176474. }
  176475. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176476. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  176477. space_per_minheight += (long) bptr->maxaccess *
  176478. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  176479. maximum_space += (long) bptr->rows_in_array *
  176480. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  176481. }
  176482. }
  176483. if (space_per_minheight <= 0)
  176484. return; /* no unrealized arrays, no work */
  176485. /* Determine amount of memory to actually use; this is system-dependent. */
  176486. avail_mem = jpeg_mem_available(cinfo, space_per_minheight, maximum_space,
  176487. mem->total_space_allocated);
  176488. /* If the maximum space needed is available, make all the buffers full
  176489. * height; otherwise parcel it out with the same number of minheights
  176490. * in each buffer.
  176491. */
  176492. if (avail_mem >= maximum_space)
  176493. max_minheights = 1000000000L;
  176494. else {
  176495. max_minheights = avail_mem / space_per_minheight;
  176496. /* If there doesn't seem to be enough space, try to get the minimum
  176497. * anyway. This allows a "stub" implementation of jpeg_mem_available().
  176498. */
  176499. if (max_minheights <= 0)
  176500. max_minheights = 1;
  176501. }
  176502. /* Allocate the in-memory buffers and initialize backing store as needed. */
  176503. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176504. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  176505. minheights = ((long) sptr->rows_in_array - 1L) / sptr->maxaccess + 1L;
  176506. if (minheights <= max_minheights) {
  176507. /* This buffer fits in memory */
  176508. sptr->rows_in_mem = sptr->rows_in_array;
  176509. } else {
  176510. /* It doesn't fit in memory, create backing store. */
  176511. sptr->rows_in_mem = (JDIMENSION) (max_minheights * sptr->maxaccess);
  176512. jpeg_open_backing_store(cinfo, & sptr->b_s_info,
  176513. (long) sptr->rows_in_array *
  176514. (long) sptr->samplesperrow *
  176515. (long) SIZEOF(JSAMPLE));
  176516. sptr->b_s_open = TRUE;
  176517. }
  176518. sptr->mem_buffer = alloc_sarray(cinfo, JPOOL_IMAGE,
  176519. sptr->samplesperrow, sptr->rows_in_mem);
  176520. sptr->rowsperchunk = mem->last_rowsperchunk;
  176521. sptr->cur_start_row = 0;
  176522. sptr->first_undef_row = 0;
  176523. sptr->dirty = FALSE;
  176524. }
  176525. }
  176526. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176527. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  176528. minheights = ((long) bptr->rows_in_array - 1L) / bptr->maxaccess + 1L;
  176529. if (minheights <= max_minheights) {
  176530. /* This buffer fits in memory */
  176531. bptr->rows_in_mem = bptr->rows_in_array;
  176532. } else {
  176533. /* It doesn't fit in memory, create backing store. */
  176534. bptr->rows_in_mem = (JDIMENSION) (max_minheights * bptr->maxaccess);
  176535. jpeg_open_backing_store(cinfo, & bptr->b_s_info,
  176536. (long) bptr->rows_in_array *
  176537. (long) bptr->blocksperrow *
  176538. (long) SIZEOF(JBLOCK));
  176539. bptr->b_s_open = TRUE;
  176540. }
  176541. bptr->mem_buffer = alloc_barray(cinfo, JPOOL_IMAGE,
  176542. bptr->blocksperrow, bptr->rows_in_mem);
  176543. bptr->rowsperchunk = mem->last_rowsperchunk;
  176544. bptr->cur_start_row = 0;
  176545. bptr->first_undef_row = 0;
  176546. bptr->dirty = FALSE;
  176547. }
  176548. }
  176549. }
  176550. LOCAL(void)
  176551. do_sarray_io (j_common_ptr cinfo, jvirt_sarray_ptr ptr, boolean writing)
  176552. /* Do backing store read or write of a virtual sample array */
  176553. {
  176554. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  176555. bytesperrow = (long) ptr->samplesperrow * SIZEOF(JSAMPLE);
  176556. file_offset = ptr->cur_start_row * bytesperrow;
  176557. /* Loop to read or write each allocation chunk in mem_buffer */
  176558. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  176559. /* One chunk, but check for short chunk at end of buffer */
  176560. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  176561. /* Transfer no more than is currently defined */
  176562. thisrow = (long) ptr->cur_start_row + i;
  176563. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  176564. /* Transfer no more than fits in file */
  176565. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  176566. if (rows <= 0) /* this chunk might be past end of file! */
  176567. break;
  176568. byte_count = rows * bytesperrow;
  176569. if (writing)
  176570. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  176571. (void FAR *) ptr->mem_buffer[i],
  176572. file_offset, byte_count);
  176573. else
  176574. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  176575. (void FAR *) ptr->mem_buffer[i],
  176576. file_offset, byte_count);
  176577. file_offset += byte_count;
  176578. }
  176579. }
  176580. LOCAL(void)
  176581. do_barray_io (j_common_ptr cinfo, jvirt_barray_ptr ptr, boolean writing)
  176582. /* Do backing store read or write of a virtual coefficient-block array */
  176583. {
  176584. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  176585. bytesperrow = (long) ptr->blocksperrow * SIZEOF(JBLOCK);
  176586. file_offset = ptr->cur_start_row * bytesperrow;
  176587. /* Loop to read or write each allocation chunk in mem_buffer */
  176588. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  176589. /* One chunk, but check for short chunk at end of buffer */
  176590. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  176591. /* Transfer no more than is currently defined */
  176592. thisrow = (long) ptr->cur_start_row + i;
  176593. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  176594. /* Transfer no more than fits in file */
  176595. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  176596. if (rows <= 0) /* this chunk might be past end of file! */
  176597. break;
  176598. byte_count = rows * bytesperrow;
  176599. if (writing)
  176600. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  176601. (void FAR *) ptr->mem_buffer[i],
  176602. file_offset, byte_count);
  176603. else
  176604. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  176605. (void FAR *) ptr->mem_buffer[i],
  176606. file_offset, byte_count);
  176607. file_offset += byte_count;
  176608. }
  176609. }
  176610. METHODDEF(JSAMPARRAY)
  176611. access_virt_sarray (j_common_ptr cinfo, jvirt_sarray_ptr ptr,
  176612. JDIMENSION start_row, JDIMENSION num_rows,
  176613. boolean writable)
  176614. /* Access the part of a virtual sample array starting at start_row */
  176615. /* and extending for num_rows rows. writable is true if */
  176616. /* caller intends to modify the accessed area. */
  176617. {
  176618. JDIMENSION end_row = start_row + num_rows;
  176619. JDIMENSION undef_row;
  176620. /* debugging check */
  176621. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  176622. ptr->mem_buffer == NULL)
  176623. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176624. /* Make the desired part of the virtual array accessible */
  176625. if (start_row < ptr->cur_start_row ||
  176626. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  176627. if (! ptr->b_s_open)
  176628. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  176629. /* Flush old buffer contents if necessary */
  176630. if (ptr->dirty) {
  176631. do_sarray_io(cinfo, ptr, TRUE);
  176632. ptr->dirty = FALSE;
  176633. }
  176634. /* Decide what part of virtual array to access.
  176635. * Algorithm: if target address > current window, assume forward scan,
  176636. * load starting at target address. If target address < current window,
  176637. * assume backward scan, load so that target area is top of window.
  176638. * Note that when switching from forward write to forward read, will have
  176639. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  176640. */
  176641. if (start_row > ptr->cur_start_row) {
  176642. ptr->cur_start_row = start_row;
  176643. } else {
  176644. /* use long arithmetic here to avoid overflow & unsigned problems */
  176645. long ltemp;
  176646. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  176647. if (ltemp < 0)
  176648. ltemp = 0; /* don't fall off front end of file */
  176649. ptr->cur_start_row = (JDIMENSION) ltemp;
  176650. }
  176651. /* Read in the selected part of the array.
  176652. * During the initial write pass, we will do no actual read
  176653. * because the selected part is all undefined.
  176654. */
  176655. do_sarray_io(cinfo, ptr, FALSE);
  176656. }
  176657. /* Ensure the accessed part of the array is defined; prezero if needed.
  176658. * To improve locality of access, we only prezero the part of the array
  176659. * that the caller is about to access, not the entire in-memory array.
  176660. */
  176661. if (ptr->first_undef_row < end_row) {
  176662. if (ptr->first_undef_row < start_row) {
  176663. if (writable) /* writer skipped over a section of array */
  176664. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176665. undef_row = start_row; /* but reader is allowed to read ahead */
  176666. } else {
  176667. undef_row = ptr->first_undef_row;
  176668. }
  176669. if (writable)
  176670. ptr->first_undef_row = end_row;
  176671. if (ptr->pre_zero) {
  176672. size_t bytesperrow = (size_t) ptr->samplesperrow * SIZEOF(JSAMPLE);
  176673. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  176674. end_row -= ptr->cur_start_row;
  176675. while (undef_row < end_row) {
  176676. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  176677. undef_row++;
  176678. }
  176679. } else {
  176680. if (! writable) /* reader looking at undefined data */
  176681. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176682. }
  176683. }
  176684. /* Flag the buffer dirty if caller will write in it */
  176685. if (writable)
  176686. ptr->dirty = TRUE;
  176687. /* Return address of proper part of the buffer */
  176688. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  176689. }
  176690. METHODDEF(JBLOCKARRAY)
  176691. access_virt_barray (j_common_ptr cinfo, jvirt_barray_ptr ptr,
  176692. JDIMENSION start_row, JDIMENSION num_rows,
  176693. boolean writable)
  176694. /* Access the part of a virtual block array starting at start_row */
  176695. /* and extending for num_rows rows. writable is true if */
  176696. /* caller intends to modify the accessed area. */
  176697. {
  176698. JDIMENSION end_row = start_row + num_rows;
  176699. JDIMENSION undef_row;
  176700. /* debugging check */
  176701. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  176702. ptr->mem_buffer == NULL)
  176703. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176704. /* Make the desired part of the virtual array accessible */
  176705. if (start_row < ptr->cur_start_row ||
  176706. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  176707. if (! ptr->b_s_open)
  176708. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  176709. /* Flush old buffer contents if necessary */
  176710. if (ptr->dirty) {
  176711. do_barray_io(cinfo, ptr, TRUE);
  176712. ptr->dirty = FALSE;
  176713. }
  176714. /* Decide what part of virtual array to access.
  176715. * Algorithm: if target address > current window, assume forward scan,
  176716. * load starting at target address. If target address < current window,
  176717. * assume backward scan, load so that target area is top of window.
  176718. * Note that when switching from forward write to forward read, will have
  176719. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  176720. */
  176721. if (start_row > ptr->cur_start_row) {
  176722. ptr->cur_start_row = start_row;
  176723. } else {
  176724. /* use long arithmetic here to avoid overflow & unsigned problems */
  176725. long ltemp;
  176726. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  176727. if (ltemp < 0)
  176728. ltemp = 0; /* don't fall off front end of file */
  176729. ptr->cur_start_row = (JDIMENSION) ltemp;
  176730. }
  176731. /* Read in the selected part of the array.
  176732. * During the initial write pass, we will do no actual read
  176733. * because the selected part is all undefined.
  176734. */
  176735. do_barray_io(cinfo, ptr, FALSE);
  176736. }
  176737. /* Ensure the accessed part of the array is defined; prezero if needed.
  176738. * To improve locality of access, we only prezero the part of the array
  176739. * that the caller is about to access, not the entire in-memory array.
  176740. */
  176741. if (ptr->first_undef_row < end_row) {
  176742. if (ptr->first_undef_row < start_row) {
  176743. if (writable) /* writer skipped over a section of array */
  176744. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176745. undef_row = start_row; /* but reader is allowed to read ahead */
  176746. } else {
  176747. undef_row = ptr->first_undef_row;
  176748. }
  176749. if (writable)
  176750. ptr->first_undef_row = end_row;
  176751. if (ptr->pre_zero) {
  176752. size_t bytesperrow = (size_t) ptr->blocksperrow * SIZEOF(JBLOCK);
  176753. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  176754. end_row -= ptr->cur_start_row;
  176755. while (undef_row < end_row) {
  176756. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  176757. undef_row++;
  176758. }
  176759. } else {
  176760. if (! writable) /* reader looking at undefined data */
  176761. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176762. }
  176763. }
  176764. /* Flag the buffer dirty if caller will write in it */
  176765. if (writable)
  176766. ptr->dirty = TRUE;
  176767. /* Return address of proper part of the buffer */
  176768. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  176769. }
  176770. /*
  176771. * Release all objects belonging to a specified pool.
  176772. */
  176773. METHODDEF(void)
  176774. free_pool (j_common_ptr cinfo, int pool_id)
  176775. {
  176776. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176777. small_pool_ptr shdr_ptr;
  176778. large_pool_ptr lhdr_ptr;
  176779. size_t space_freed;
  176780. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  176781. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176782. #ifdef MEM_STATS
  176783. if (cinfo->err->trace_level > 1)
  176784. print_mem_stats(cinfo, pool_id); /* print pool's memory usage statistics */
  176785. #endif
  176786. /* If freeing IMAGE pool, close any virtual arrays first */
  176787. if (pool_id == JPOOL_IMAGE) {
  176788. jvirt_sarray_ptr sptr;
  176789. jvirt_barray_ptr bptr;
  176790. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176791. if (sptr->b_s_open) { /* there may be no backing store */
  176792. sptr->b_s_open = FALSE; /* prevent recursive close if error */
  176793. (*sptr->b_s_info.close_backing_store) (cinfo, & sptr->b_s_info);
  176794. }
  176795. }
  176796. mem->virt_sarray_list = NULL;
  176797. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176798. if (bptr->b_s_open) { /* there may be no backing store */
  176799. bptr->b_s_open = FALSE; /* prevent recursive close if error */
  176800. (*bptr->b_s_info.close_backing_store) (cinfo, & bptr->b_s_info);
  176801. }
  176802. }
  176803. mem->virt_barray_list = NULL;
  176804. }
  176805. /* Release large objects */
  176806. lhdr_ptr = mem->large_list[pool_id];
  176807. mem->large_list[pool_id] = NULL;
  176808. while (lhdr_ptr != NULL) {
  176809. large_pool_ptr next_lhdr_ptr = lhdr_ptr->hdr.next;
  176810. space_freed = lhdr_ptr->hdr.bytes_used +
  176811. lhdr_ptr->hdr.bytes_left +
  176812. SIZEOF(large_pool_hdr);
  176813. jpeg_free_large(cinfo, (void FAR *) lhdr_ptr, space_freed);
  176814. mem->total_space_allocated -= space_freed;
  176815. lhdr_ptr = next_lhdr_ptr;
  176816. }
  176817. /* Release small objects */
  176818. shdr_ptr = mem->small_list[pool_id];
  176819. mem->small_list[pool_id] = NULL;
  176820. while (shdr_ptr != NULL) {
  176821. small_pool_ptr next_shdr_ptr = shdr_ptr->hdr.next;
  176822. space_freed = shdr_ptr->hdr.bytes_used +
  176823. shdr_ptr->hdr.bytes_left +
  176824. SIZEOF(small_pool_hdr);
  176825. jpeg_free_small(cinfo, (void *) shdr_ptr, space_freed);
  176826. mem->total_space_allocated -= space_freed;
  176827. shdr_ptr = next_shdr_ptr;
  176828. }
  176829. }
  176830. /*
  176831. * Close up shop entirely.
  176832. * Note that this cannot be called unless cinfo->mem is non-NULL.
  176833. */
  176834. METHODDEF(void)
  176835. self_destruct (j_common_ptr cinfo)
  176836. {
  176837. int pool;
  176838. /* Close all backing store, release all memory.
  176839. * Releasing pools in reverse order might help avoid fragmentation
  176840. * with some (brain-damaged) malloc libraries.
  176841. */
  176842. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  176843. free_pool(cinfo, pool);
  176844. }
  176845. /* Release the memory manager control block too. */
  176846. jpeg_free_small(cinfo, (void *) cinfo->mem, SIZEOF(my_memory_mgr));
  176847. cinfo->mem = NULL; /* ensures I will be called only once */
  176848. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  176849. }
  176850. /*
  176851. * Memory manager initialization.
  176852. * When this is called, only the error manager pointer is valid in cinfo!
  176853. */
  176854. GLOBAL(void)
  176855. jinit_memory_mgr (j_common_ptr cinfo)
  176856. {
  176857. my_mem_ptr mem;
  176858. long max_to_use;
  176859. int pool;
  176860. size_t test_mac;
  176861. cinfo->mem = NULL; /* for safety if init fails */
  176862. /* Check for configuration errors.
  176863. * SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably
  176864. * doesn't reflect any real hardware alignment requirement.
  176865. * The test is a little tricky: for X>0, X and X-1 have no one-bits
  176866. * in common if and only if X is a power of 2, ie has only one one-bit.
  176867. * Some compilers may give an "unreachable code" warning here; ignore it.
  176868. */
  176869. if ((SIZEOF(ALIGN_TYPE) & (SIZEOF(ALIGN_TYPE)-1)) != 0)
  176870. ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE);
  176871. /* MAX_ALLOC_CHUNK must be representable as type size_t, and must be
  176872. * a multiple of SIZEOF(ALIGN_TYPE).
  176873. * Again, an "unreachable code" warning may be ignored here.
  176874. * But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK.
  176875. */
  176876. test_mac = (size_t) MAX_ALLOC_CHUNK;
  176877. if ((long) test_mac != MAX_ALLOC_CHUNK ||
  176878. (MAX_ALLOC_CHUNK % SIZEOF(ALIGN_TYPE)) != 0)
  176879. ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
  176880. max_to_use = jpeg_mem_init(cinfo); /* system-dependent initialization */
  176881. /* Attempt to allocate memory manager's control block */
  176882. mem = (my_mem_ptr) jpeg_get_small(cinfo, SIZEOF(my_memory_mgr));
  176883. if (mem == NULL) {
  176884. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  176885. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0);
  176886. }
  176887. /* OK, fill in the method pointers */
  176888. mem->pub.alloc_small = alloc_small;
  176889. mem->pub.alloc_large = alloc_large;
  176890. mem->pub.alloc_sarray = alloc_sarray;
  176891. mem->pub.alloc_barray = alloc_barray;
  176892. mem->pub.request_virt_sarray = request_virt_sarray;
  176893. mem->pub.request_virt_barray = request_virt_barray;
  176894. mem->pub.realize_virt_arrays = realize_virt_arrays;
  176895. mem->pub.access_virt_sarray = access_virt_sarray;
  176896. mem->pub.access_virt_barray = access_virt_barray;
  176897. mem->pub.free_pool = free_pool;
  176898. mem->pub.self_destruct = self_destruct;
  176899. /* Make MAX_ALLOC_CHUNK accessible to other modules */
  176900. mem->pub.max_alloc_chunk = MAX_ALLOC_CHUNK;
  176901. /* Initialize working state */
  176902. mem->pub.max_memory_to_use = max_to_use;
  176903. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  176904. mem->small_list[pool] = NULL;
  176905. mem->large_list[pool] = NULL;
  176906. }
  176907. mem->virt_sarray_list = NULL;
  176908. mem->virt_barray_list = NULL;
  176909. mem->total_space_allocated = SIZEOF(my_memory_mgr);
  176910. /* Declare ourselves open for business */
  176911. cinfo->mem = & mem->pub;
  176912. /* Check for an environment variable JPEGMEM; if found, override the
  176913. * default max_memory setting from jpeg_mem_init. Note that the
  176914. * surrounding application may again override this value.
  176915. * If your system doesn't support getenv(), define NO_GETENV to disable
  176916. * this feature.
  176917. */
  176918. #ifndef NO_GETENV
  176919. { char * memenv;
  176920. if ((memenv = getenv("JPEGMEM")) != NULL) {
  176921. char ch = 'x';
  176922. if (sscanf(memenv, "%ld%c", &max_to_use, &ch) > 0) {
  176923. if (ch == 'm' || ch == 'M')
  176924. max_to_use *= 1000L;
  176925. mem->pub.max_memory_to_use = max_to_use * 1000L;
  176926. }
  176927. }
  176928. }
  176929. #endif
  176930. }
  176931. /*** End of inlined file: jmemmgr.c ***/
  176932. /*** Start of inlined file: jmemnobs.c ***/
  176933. #define JPEG_INTERNALS
  176934. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare malloc(),free() */
  176935. extern void * malloc JPP((size_t size));
  176936. extern void free JPP((void *ptr));
  176937. #endif
  176938. /*
  176939. * Memory allocation and freeing are controlled by the regular library
  176940. * routines malloc() and free().
  176941. */
  176942. GLOBAL(void *)
  176943. jpeg_get_small (j_common_ptr , size_t sizeofobject)
  176944. {
  176945. return (void *) malloc(sizeofobject);
  176946. }
  176947. GLOBAL(void)
  176948. jpeg_free_small (j_common_ptr , void * object, size_t)
  176949. {
  176950. free(object);
  176951. }
  176952. /*
  176953. * "Large" objects are treated the same as "small" ones.
  176954. * NB: although we include FAR keywords in the routine declarations,
  176955. * this file won't actually work in 80x86 small/medium model; at least,
  176956. * you probably won't be able to process useful-size images in only 64KB.
  176957. */
  176958. GLOBAL(void FAR *)
  176959. jpeg_get_large (j_common_ptr, size_t sizeofobject)
  176960. {
  176961. return (void FAR *) malloc(sizeofobject);
  176962. }
  176963. GLOBAL(void)
  176964. jpeg_free_large (j_common_ptr, void FAR * object, size_t)
  176965. {
  176966. free(object);
  176967. }
  176968. /*
  176969. * This routine computes the total memory space available for allocation.
  176970. * Here we always say, "we got all you want bud!"
  176971. */
  176972. GLOBAL(long)
  176973. jpeg_mem_available (j_common_ptr, long,
  176974. long max_bytes_needed, long)
  176975. {
  176976. return max_bytes_needed;
  176977. }
  176978. /*
  176979. * Backing store (temporary file) management.
  176980. * Since jpeg_mem_available always promised the moon,
  176981. * this should never be called and we can just error out.
  176982. */
  176983. GLOBAL(void)
  176984. jpeg_open_backing_store (j_common_ptr cinfo, struct backing_store_struct *,
  176985. long )
  176986. {
  176987. ERREXIT(cinfo, JERR_NO_BACKING_STORE);
  176988. }
  176989. /*
  176990. * These routines take care of any system-dependent initialization and
  176991. * cleanup required. Here, there isn't any.
  176992. */
  176993. GLOBAL(long)
  176994. jpeg_mem_init (j_common_ptr)
  176995. {
  176996. return 0; /* just set max_memory_to_use to 0 */
  176997. }
  176998. GLOBAL(void)
  176999. jpeg_mem_term (j_common_ptr)
  177000. {
  177001. /* no work */
  177002. }
  177003. /*** End of inlined file: jmemnobs.c ***/
  177004. /*** Start of inlined file: jquant1.c ***/
  177005. #define JPEG_INTERNALS
  177006. #ifdef QUANT_1PASS_SUPPORTED
  177007. /*
  177008. * The main purpose of 1-pass quantization is to provide a fast, if not very
  177009. * high quality, colormapped output capability. A 2-pass quantizer usually
  177010. * gives better visual quality; however, for quantized grayscale output this
  177011. * quantizer is perfectly adequate. Dithering is highly recommended with this
  177012. * quantizer, though you can turn it off if you really want to.
  177013. *
  177014. * In 1-pass quantization the colormap must be chosen in advance of seeing the
  177015. * image. We use a map consisting of all combinations of Ncolors[i] color
  177016. * values for the i'th component. The Ncolors[] values are chosen so that
  177017. * their product, the total number of colors, is no more than that requested.
  177018. * (In most cases, the product will be somewhat less.)
  177019. *
  177020. * Since the colormap is orthogonal, the representative value for each color
  177021. * component can be determined without considering the other components;
  177022. * then these indexes can be combined into a colormap index by a standard
  177023. * N-dimensional-array-subscript calculation. Most of the arithmetic involved
  177024. * can be precalculated and stored in the lookup table colorindex[].
  177025. * colorindex[i][j] maps pixel value j in component i to the nearest
  177026. * representative value (grid plane) for that component; this index is
  177027. * multiplied by the array stride for component i, so that the
  177028. * index of the colormap entry closest to a given pixel value is just
  177029. * sum( colorindex[component-number][pixel-component-value] )
  177030. * Aside from being fast, this scheme allows for variable spacing between
  177031. * representative values with no additional lookup cost.
  177032. *
  177033. * If gamma correction has been applied in color conversion, it might be wise
  177034. * to adjust the color grid spacing so that the representative colors are
  177035. * equidistant in linear space. At this writing, gamma correction is not
  177036. * implemented by jdcolor, so nothing is done here.
  177037. */
  177038. /* Declarations for ordered dithering.
  177039. *
  177040. * We use a standard 16x16 ordered dither array. The basic concept of ordered
  177041. * dithering is described in many references, for instance Dale Schumacher's
  177042. * chapter II.2 of Graphics Gems II (James Arvo, ed. Academic Press, 1991).
  177043. * In place of Schumacher's comparisons against a "threshold" value, we add a
  177044. * "dither" value to the input pixel and then round the result to the nearest
  177045. * output value. The dither value is equivalent to (0.5 - threshold) times
  177046. * the distance between output values. For ordered dithering, we assume that
  177047. * the output colors are equally spaced; if not, results will probably be
  177048. * worse, since the dither may be too much or too little at a given point.
  177049. *
  177050. * The normal calculation would be to form pixel value + dither, range-limit
  177051. * this to 0..MAXJSAMPLE, and then index into the colorindex table as usual.
  177052. * We can skip the separate range-limiting step by extending the colorindex
  177053. * table in both directions.
  177054. */
  177055. #define ODITHER_SIZE 16 /* dimension of dither matrix */
  177056. /* NB: if ODITHER_SIZE is not a power of 2, ODITHER_MASK uses will break */
  177057. #define ODITHER_CELLS (ODITHER_SIZE*ODITHER_SIZE) /* # cells in matrix */
  177058. #define ODITHER_MASK (ODITHER_SIZE-1) /* mask for wrapping around counters */
  177059. typedef int ODITHER_MATRIX[ODITHER_SIZE][ODITHER_SIZE];
  177060. typedef int (*ODITHER_MATRIX_PTR)[ODITHER_SIZE];
  177061. static const UINT8 base_dither_matrix[ODITHER_SIZE][ODITHER_SIZE] = {
  177062. /* Bayer's order-4 dither array. Generated by the code given in
  177063. * Stephen Hawley's article "Ordered Dithering" in Graphics Gems I.
  177064. * The values in this array must range from 0 to ODITHER_CELLS-1.
  177065. */
  177066. { 0,192, 48,240, 12,204, 60,252, 3,195, 51,243, 15,207, 63,255 },
  177067. { 128, 64,176,112,140, 76,188,124,131, 67,179,115,143, 79,191,127 },
  177068. { 32,224, 16,208, 44,236, 28,220, 35,227, 19,211, 47,239, 31,223 },
  177069. { 160, 96,144, 80,172,108,156, 92,163, 99,147, 83,175,111,159, 95 },
  177070. { 8,200, 56,248, 4,196, 52,244, 11,203, 59,251, 7,199, 55,247 },
  177071. { 136, 72,184,120,132, 68,180,116,139, 75,187,123,135, 71,183,119 },
  177072. { 40,232, 24,216, 36,228, 20,212, 43,235, 27,219, 39,231, 23,215 },
  177073. { 168,104,152, 88,164,100,148, 84,171,107,155, 91,167,103,151, 87 },
  177074. { 2,194, 50,242, 14,206, 62,254, 1,193, 49,241, 13,205, 61,253 },
  177075. { 130, 66,178,114,142, 78,190,126,129, 65,177,113,141, 77,189,125 },
  177076. { 34,226, 18,210, 46,238, 30,222, 33,225, 17,209, 45,237, 29,221 },
  177077. { 162, 98,146, 82,174,110,158, 94,161, 97,145, 81,173,109,157, 93 },
  177078. { 10,202, 58,250, 6,198, 54,246, 9,201, 57,249, 5,197, 53,245 },
  177079. { 138, 74,186,122,134, 70,182,118,137, 73,185,121,133, 69,181,117 },
  177080. { 42,234, 26,218, 38,230, 22,214, 41,233, 25,217, 37,229, 21,213 },
  177081. { 170,106,154, 90,166,102,150, 86,169,105,153, 89,165,101,149, 85 }
  177082. };
  177083. /* Declarations for Floyd-Steinberg dithering.
  177084. *
  177085. * Errors are accumulated into the array fserrors[], at a resolution of
  177086. * 1/16th of a pixel count. The error at a given pixel is propagated
  177087. * to its not-yet-processed neighbors using the standard F-S fractions,
  177088. * ... (here) 7/16
  177089. * 3/16 5/16 1/16
  177090. * We work left-to-right on even rows, right-to-left on odd rows.
  177091. *
  177092. * We can get away with a single array (holding one row's worth of errors)
  177093. * by using it to store the current row's errors at pixel columns not yet
  177094. * processed, but the next row's errors at columns already processed. We
  177095. * need only a few extra variables to hold the errors immediately around the
  177096. * current column. (If we are lucky, those variables are in registers, but
  177097. * even if not, they're probably cheaper to access than array elements are.)
  177098. *
  177099. * The fserrors[] array is indexed [component#][position].
  177100. * We provide (#columns + 2) entries per component; the extra entry at each
  177101. * end saves us from special-casing the first and last pixels.
  177102. *
  177103. * Note: on a wide image, we might not have enough room in a PC's near data
  177104. * segment to hold the error array; so it is allocated with alloc_large.
  177105. */
  177106. #if BITS_IN_JSAMPLE == 8
  177107. typedef INT16 FSERROR; /* 16 bits should be enough */
  177108. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  177109. #else
  177110. typedef INT32 FSERROR; /* may need more than 16 bits */
  177111. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  177112. #endif
  177113. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  177114. /* Private subobject */
  177115. #define MAX_Q_COMPS 4 /* max components I can handle */
  177116. typedef struct {
  177117. struct jpeg_color_quantizer pub; /* public fields */
  177118. /* Initially allocated colormap is saved here */
  177119. JSAMPARRAY sv_colormap; /* The color map as a 2-D pixel array */
  177120. int sv_actual; /* number of entries in use */
  177121. JSAMPARRAY colorindex; /* Precomputed mapping for speed */
  177122. /* colorindex[i][j] = index of color closest to pixel value j in component i,
  177123. * premultiplied as described above. Since colormap indexes must fit into
  177124. * JSAMPLEs, the entries of this array will too.
  177125. */
  177126. boolean is_padded; /* is the colorindex padded for odither? */
  177127. int Ncolors[MAX_Q_COMPS]; /* # of values alloced to each component */
  177128. /* Variables for ordered dithering */
  177129. int row_index; /* cur row's vertical index in dither matrix */
  177130. ODITHER_MATRIX_PTR odither[MAX_Q_COMPS]; /* one dither array per component */
  177131. /* Variables for Floyd-Steinberg dithering */
  177132. FSERRPTR fserrors[MAX_Q_COMPS]; /* accumulated errors */
  177133. boolean on_odd_row; /* flag to remember which row we are on */
  177134. } my_cquantizer;
  177135. typedef my_cquantizer * my_cquantize_ptr;
  177136. /*
  177137. * Policy-making subroutines for create_colormap and create_colorindex.
  177138. * These routines determine the colormap to be used. The rest of the module
  177139. * only assumes that the colormap is orthogonal.
  177140. *
  177141. * * select_ncolors decides how to divvy up the available colors
  177142. * among the components.
  177143. * * output_value defines the set of representative values for a component.
  177144. * * largest_input_value defines the mapping from input values to
  177145. * representative values for a component.
  177146. * Note that the latter two routines may impose different policies for
  177147. * different components, though this is not currently done.
  177148. */
  177149. LOCAL(int)
  177150. select_ncolors (j_decompress_ptr cinfo, int Ncolors[])
  177151. /* Determine allocation of desired colors to components, */
  177152. /* and fill in Ncolors[] array to indicate choice. */
  177153. /* Return value is total number of colors (product of Ncolors[] values). */
  177154. {
  177155. int nc = cinfo->out_color_components; /* number of color components */
  177156. int max_colors = cinfo->desired_number_of_colors;
  177157. int total_colors, iroot, i, j;
  177158. boolean changed;
  177159. long temp;
  177160. static const int RGB_order[3] = { RGB_GREEN, RGB_RED, RGB_BLUE };
  177161. /* We can allocate at least the nc'th root of max_colors per component. */
  177162. /* Compute floor(nc'th root of max_colors). */
  177163. iroot = 1;
  177164. do {
  177165. iroot++;
  177166. temp = iroot; /* set temp = iroot ** nc */
  177167. for (i = 1; i < nc; i++)
  177168. temp *= iroot;
  177169. } while (temp <= (long) max_colors); /* repeat till iroot exceeds root */
  177170. iroot--; /* now iroot = floor(root) */
  177171. /* Must have at least 2 color values per component */
  177172. if (iroot < 2)
  177173. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, (int) temp);
  177174. /* Initialize to iroot color values for each component */
  177175. total_colors = 1;
  177176. for (i = 0; i < nc; i++) {
  177177. Ncolors[i] = iroot;
  177178. total_colors *= iroot;
  177179. }
  177180. /* We may be able to increment the count for one or more components without
  177181. * exceeding max_colors, though we know not all can be incremented.
  177182. * Sometimes, the first component can be incremented more than once!
  177183. * (Example: for 16 colors, we start at 2*2*2, go to 3*2*2, then 4*2*2.)
  177184. * In RGB colorspace, try to increment G first, then R, then B.
  177185. */
  177186. do {
  177187. changed = FALSE;
  177188. for (i = 0; i < nc; i++) {
  177189. j = (cinfo->out_color_space == JCS_RGB ? RGB_order[i] : i);
  177190. /* calculate new total_colors if Ncolors[j] is incremented */
  177191. temp = total_colors / Ncolors[j];
  177192. temp *= Ncolors[j]+1; /* done in long arith to avoid oflo */
  177193. if (temp > (long) max_colors)
  177194. break; /* won't fit, done with this pass */
  177195. Ncolors[j]++; /* OK, apply the increment */
  177196. total_colors = (int) temp;
  177197. changed = TRUE;
  177198. }
  177199. } while (changed);
  177200. return total_colors;
  177201. }
  177202. LOCAL(int)
  177203. output_value (j_decompress_ptr, int, int j, int maxj)
  177204. /* Return j'th output value, where j will range from 0 to maxj */
  177205. /* The output values must fall in 0..MAXJSAMPLE in increasing order */
  177206. {
  177207. /* We always provide values 0 and MAXJSAMPLE for each component;
  177208. * any additional values are equally spaced between these limits.
  177209. * (Forcing the upper and lower values to the limits ensures that
  177210. * dithering can't produce a color outside the selected gamut.)
  177211. */
  177212. return (int) (((INT32) j * MAXJSAMPLE + maxj/2) / maxj);
  177213. }
  177214. LOCAL(int)
  177215. largest_input_value (j_decompress_ptr, int, int j, int maxj)
  177216. /* Return largest input value that should map to j'th output value */
  177217. /* Must have largest(j=0) >= 0, and largest(j=maxj) >= MAXJSAMPLE */
  177218. {
  177219. /* Breakpoints are halfway between values returned by output_value */
  177220. return (int) (((INT32) (2*j + 1) * MAXJSAMPLE + maxj) / (2*maxj));
  177221. }
  177222. /*
  177223. * Create the colormap.
  177224. */
  177225. LOCAL(void)
  177226. create_colormap (j_decompress_ptr cinfo)
  177227. {
  177228. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177229. JSAMPARRAY colormap; /* Created colormap */
  177230. int total_colors; /* Number of distinct output colors */
  177231. int i,j,k, nci, blksize, blkdist, ptr, val;
  177232. /* Select number of colors for each component */
  177233. total_colors = select_ncolors(cinfo, cquantize->Ncolors);
  177234. /* Report selected color counts */
  177235. if (cinfo->out_color_components == 3)
  177236. TRACEMS4(cinfo, 1, JTRC_QUANT_3_NCOLORS,
  177237. total_colors, cquantize->Ncolors[0],
  177238. cquantize->Ncolors[1], cquantize->Ncolors[2]);
  177239. else
  177240. TRACEMS1(cinfo, 1, JTRC_QUANT_NCOLORS, total_colors);
  177241. /* Allocate and fill in the colormap. */
  177242. /* The colors are ordered in the map in standard row-major order, */
  177243. /* i.e. rightmost (highest-indexed) color changes most rapidly. */
  177244. colormap = (*cinfo->mem->alloc_sarray)
  177245. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177246. (JDIMENSION) total_colors, (JDIMENSION) cinfo->out_color_components);
  177247. /* blksize is number of adjacent repeated entries for a component */
  177248. /* blkdist is distance between groups of identical entries for a component */
  177249. blkdist = total_colors;
  177250. for (i = 0; i < cinfo->out_color_components; i++) {
  177251. /* fill in colormap entries for i'th color component */
  177252. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  177253. blksize = blkdist / nci;
  177254. for (j = 0; j < nci; j++) {
  177255. /* Compute j'th output value (out of nci) for component */
  177256. val = output_value(cinfo, i, j, nci-1);
  177257. /* Fill in all colormap entries that have this value of this component */
  177258. for (ptr = j * blksize; ptr < total_colors; ptr += blkdist) {
  177259. /* fill in blksize entries beginning at ptr */
  177260. for (k = 0; k < blksize; k++)
  177261. colormap[i][ptr+k] = (JSAMPLE) val;
  177262. }
  177263. }
  177264. blkdist = blksize; /* blksize of this color is blkdist of next */
  177265. }
  177266. /* Save the colormap in private storage,
  177267. * where it will survive color quantization mode changes.
  177268. */
  177269. cquantize->sv_colormap = colormap;
  177270. cquantize->sv_actual = total_colors;
  177271. }
  177272. /*
  177273. * Create the color index table.
  177274. */
  177275. LOCAL(void)
  177276. create_colorindex (j_decompress_ptr cinfo)
  177277. {
  177278. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177279. JSAMPROW indexptr;
  177280. int i,j,k, nci, blksize, val, pad;
  177281. /* For ordered dither, we pad the color index tables by MAXJSAMPLE in
  177282. * each direction (input index values can be -MAXJSAMPLE .. 2*MAXJSAMPLE).
  177283. * This is not necessary in the other dithering modes. However, we
  177284. * flag whether it was done in case user changes dithering mode.
  177285. */
  177286. if (cinfo->dither_mode == JDITHER_ORDERED) {
  177287. pad = MAXJSAMPLE*2;
  177288. cquantize->is_padded = TRUE;
  177289. } else {
  177290. pad = 0;
  177291. cquantize->is_padded = FALSE;
  177292. }
  177293. cquantize->colorindex = (*cinfo->mem->alloc_sarray)
  177294. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177295. (JDIMENSION) (MAXJSAMPLE+1 + pad),
  177296. (JDIMENSION) cinfo->out_color_components);
  177297. /* blksize is number of adjacent repeated entries for a component */
  177298. blksize = cquantize->sv_actual;
  177299. for (i = 0; i < cinfo->out_color_components; i++) {
  177300. /* fill in colorindex entries for i'th color component */
  177301. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  177302. blksize = blksize / nci;
  177303. /* adjust colorindex pointers to provide padding at negative indexes. */
  177304. if (pad)
  177305. cquantize->colorindex[i] += MAXJSAMPLE;
  177306. /* in loop, val = index of current output value, */
  177307. /* and k = largest j that maps to current val */
  177308. indexptr = cquantize->colorindex[i];
  177309. val = 0;
  177310. k = largest_input_value(cinfo, i, 0, nci-1);
  177311. for (j = 0; j <= MAXJSAMPLE; j++) {
  177312. while (j > k) /* advance val if past boundary */
  177313. k = largest_input_value(cinfo, i, ++val, nci-1);
  177314. /* premultiply so that no multiplication needed in main processing */
  177315. indexptr[j] = (JSAMPLE) (val * blksize);
  177316. }
  177317. /* Pad at both ends if necessary */
  177318. if (pad)
  177319. for (j = 1; j <= MAXJSAMPLE; j++) {
  177320. indexptr[-j] = indexptr[0];
  177321. indexptr[MAXJSAMPLE+j] = indexptr[MAXJSAMPLE];
  177322. }
  177323. }
  177324. }
  177325. /*
  177326. * Create an ordered-dither array for a component having ncolors
  177327. * distinct output values.
  177328. */
  177329. LOCAL(ODITHER_MATRIX_PTR)
  177330. make_odither_array (j_decompress_ptr cinfo, int ncolors)
  177331. {
  177332. ODITHER_MATRIX_PTR odither;
  177333. int j,k;
  177334. INT32 num,den;
  177335. odither = (ODITHER_MATRIX_PTR)
  177336. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177337. SIZEOF(ODITHER_MATRIX));
  177338. /* The inter-value distance for this color is MAXJSAMPLE/(ncolors-1).
  177339. * Hence the dither value for the matrix cell with fill order f
  177340. * (f=0..N-1) should be (N-1-2*f)/(2*N) * MAXJSAMPLE/(ncolors-1).
  177341. * On 16-bit-int machine, be careful to avoid overflow.
  177342. */
  177343. den = 2 * ODITHER_CELLS * ((INT32) (ncolors - 1));
  177344. for (j = 0; j < ODITHER_SIZE; j++) {
  177345. for (k = 0; k < ODITHER_SIZE; k++) {
  177346. num = ((INT32) (ODITHER_CELLS-1 - 2*((int)base_dither_matrix[j][k])))
  177347. * MAXJSAMPLE;
  177348. /* Ensure round towards zero despite C's lack of consistency
  177349. * about rounding negative values in integer division...
  177350. */
  177351. odither[j][k] = (int) (num<0 ? -((-num)/den) : num/den);
  177352. }
  177353. }
  177354. return odither;
  177355. }
  177356. /*
  177357. * Create the ordered-dither tables.
  177358. * Components having the same number of representative colors may
  177359. * share a dither table.
  177360. */
  177361. LOCAL(void)
  177362. create_odither_tables (j_decompress_ptr cinfo)
  177363. {
  177364. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177365. ODITHER_MATRIX_PTR odither;
  177366. int i, j, nci;
  177367. for (i = 0; i < cinfo->out_color_components; i++) {
  177368. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  177369. odither = NULL; /* search for matching prior component */
  177370. for (j = 0; j < i; j++) {
  177371. if (nci == cquantize->Ncolors[j]) {
  177372. odither = cquantize->odither[j];
  177373. break;
  177374. }
  177375. }
  177376. if (odither == NULL) /* need a new table? */
  177377. odither = make_odither_array(cinfo, nci);
  177378. cquantize->odither[i] = odither;
  177379. }
  177380. }
  177381. /*
  177382. * Map some rows of pixels to the output colormapped representation.
  177383. */
  177384. METHODDEF(void)
  177385. color_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177386. JSAMPARRAY output_buf, int num_rows)
  177387. /* General case, no dithering */
  177388. {
  177389. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177390. JSAMPARRAY colorindex = cquantize->colorindex;
  177391. register int pixcode, ci;
  177392. register JSAMPROW ptrin, ptrout;
  177393. int row;
  177394. JDIMENSION col;
  177395. JDIMENSION width = cinfo->output_width;
  177396. register int nc = cinfo->out_color_components;
  177397. for (row = 0; row < num_rows; row++) {
  177398. ptrin = input_buf[row];
  177399. ptrout = output_buf[row];
  177400. for (col = width; col > 0; col--) {
  177401. pixcode = 0;
  177402. for (ci = 0; ci < nc; ci++) {
  177403. pixcode += GETJSAMPLE(colorindex[ci][GETJSAMPLE(*ptrin++)]);
  177404. }
  177405. *ptrout++ = (JSAMPLE) pixcode;
  177406. }
  177407. }
  177408. }
  177409. METHODDEF(void)
  177410. color_quantize3 (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177411. JSAMPARRAY output_buf, int num_rows)
  177412. /* Fast path for out_color_components==3, no dithering */
  177413. {
  177414. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177415. register int pixcode;
  177416. register JSAMPROW ptrin, ptrout;
  177417. JSAMPROW colorindex0 = cquantize->colorindex[0];
  177418. JSAMPROW colorindex1 = cquantize->colorindex[1];
  177419. JSAMPROW colorindex2 = cquantize->colorindex[2];
  177420. int row;
  177421. JDIMENSION col;
  177422. JDIMENSION width = cinfo->output_width;
  177423. for (row = 0; row < num_rows; row++) {
  177424. ptrin = input_buf[row];
  177425. ptrout = output_buf[row];
  177426. for (col = width; col > 0; col--) {
  177427. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*ptrin++)]);
  177428. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*ptrin++)]);
  177429. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*ptrin++)]);
  177430. *ptrout++ = (JSAMPLE) pixcode;
  177431. }
  177432. }
  177433. }
  177434. METHODDEF(void)
  177435. quantize_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177436. JSAMPARRAY output_buf, int num_rows)
  177437. /* General case, with ordered dithering */
  177438. {
  177439. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177440. register JSAMPROW input_ptr;
  177441. register JSAMPROW output_ptr;
  177442. JSAMPROW colorindex_ci;
  177443. int * dither; /* points to active row of dither matrix */
  177444. int row_index, col_index; /* current indexes into dither matrix */
  177445. int nc = cinfo->out_color_components;
  177446. int ci;
  177447. int row;
  177448. JDIMENSION col;
  177449. JDIMENSION width = cinfo->output_width;
  177450. for (row = 0; row < num_rows; row++) {
  177451. /* Initialize output values to 0 so can process components separately */
  177452. jzero_far((void FAR *) output_buf[row],
  177453. (size_t) (width * SIZEOF(JSAMPLE)));
  177454. row_index = cquantize->row_index;
  177455. for (ci = 0; ci < nc; ci++) {
  177456. input_ptr = input_buf[row] + ci;
  177457. output_ptr = output_buf[row];
  177458. colorindex_ci = cquantize->colorindex[ci];
  177459. dither = cquantize->odither[ci][row_index];
  177460. col_index = 0;
  177461. for (col = width; col > 0; col--) {
  177462. /* Form pixel value + dither, range-limit to 0..MAXJSAMPLE,
  177463. * select output value, accumulate into output code for this pixel.
  177464. * Range-limiting need not be done explicitly, as we have extended
  177465. * the colorindex table to produce the right answers for out-of-range
  177466. * inputs. The maximum dither is +- MAXJSAMPLE; this sets the
  177467. * required amount of padding.
  177468. */
  177469. *output_ptr += colorindex_ci[GETJSAMPLE(*input_ptr)+dither[col_index]];
  177470. input_ptr += nc;
  177471. output_ptr++;
  177472. col_index = (col_index + 1) & ODITHER_MASK;
  177473. }
  177474. }
  177475. /* Advance row index for next row */
  177476. row_index = (row_index + 1) & ODITHER_MASK;
  177477. cquantize->row_index = row_index;
  177478. }
  177479. }
  177480. METHODDEF(void)
  177481. quantize3_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177482. JSAMPARRAY output_buf, int num_rows)
  177483. /* Fast path for out_color_components==3, with ordered dithering */
  177484. {
  177485. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177486. register int pixcode;
  177487. register JSAMPROW input_ptr;
  177488. register JSAMPROW output_ptr;
  177489. JSAMPROW colorindex0 = cquantize->colorindex[0];
  177490. JSAMPROW colorindex1 = cquantize->colorindex[1];
  177491. JSAMPROW colorindex2 = cquantize->colorindex[2];
  177492. int * dither0; /* points to active row of dither matrix */
  177493. int * dither1;
  177494. int * dither2;
  177495. int row_index, col_index; /* current indexes into dither matrix */
  177496. int row;
  177497. JDIMENSION col;
  177498. JDIMENSION width = cinfo->output_width;
  177499. for (row = 0; row < num_rows; row++) {
  177500. row_index = cquantize->row_index;
  177501. input_ptr = input_buf[row];
  177502. output_ptr = output_buf[row];
  177503. dither0 = cquantize->odither[0][row_index];
  177504. dither1 = cquantize->odither[1][row_index];
  177505. dither2 = cquantize->odither[2][row_index];
  177506. col_index = 0;
  177507. for (col = width; col > 0; col--) {
  177508. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*input_ptr++) +
  177509. dither0[col_index]]);
  177510. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*input_ptr++) +
  177511. dither1[col_index]]);
  177512. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*input_ptr++) +
  177513. dither2[col_index]]);
  177514. *output_ptr++ = (JSAMPLE) pixcode;
  177515. col_index = (col_index + 1) & ODITHER_MASK;
  177516. }
  177517. row_index = (row_index + 1) & ODITHER_MASK;
  177518. cquantize->row_index = row_index;
  177519. }
  177520. }
  177521. METHODDEF(void)
  177522. quantize_fs_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177523. JSAMPARRAY output_buf, int num_rows)
  177524. /* General case, with Floyd-Steinberg dithering */
  177525. {
  177526. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177527. register LOCFSERROR cur; /* current error or pixel value */
  177528. LOCFSERROR belowerr; /* error for pixel below cur */
  177529. LOCFSERROR bpreverr; /* error for below/prev col */
  177530. LOCFSERROR bnexterr; /* error for below/next col */
  177531. LOCFSERROR delta;
  177532. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  177533. register JSAMPROW input_ptr;
  177534. register JSAMPROW output_ptr;
  177535. JSAMPROW colorindex_ci;
  177536. JSAMPROW colormap_ci;
  177537. int pixcode;
  177538. int nc = cinfo->out_color_components;
  177539. int dir; /* 1 for left-to-right, -1 for right-to-left */
  177540. int dirnc; /* dir * nc */
  177541. int ci;
  177542. int row;
  177543. JDIMENSION col;
  177544. JDIMENSION width = cinfo->output_width;
  177545. JSAMPLE *range_limit = cinfo->sample_range_limit;
  177546. SHIFT_TEMPS
  177547. for (row = 0; row < num_rows; row++) {
  177548. /* Initialize output values to 0 so can process components separately */
  177549. jzero_far((void FAR *) output_buf[row],
  177550. (size_t) (width * SIZEOF(JSAMPLE)));
  177551. for (ci = 0; ci < nc; ci++) {
  177552. input_ptr = input_buf[row] + ci;
  177553. output_ptr = output_buf[row];
  177554. if (cquantize->on_odd_row) {
  177555. /* work right to left in this row */
  177556. input_ptr += (width-1) * nc; /* so point to rightmost pixel */
  177557. output_ptr += width-1;
  177558. dir = -1;
  177559. dirnc = -nc;
  177560. errorptr = cquantize->fserrors[ci] + (width+1); /* => entry after last column */
  177561. } else {
  177562. /* work left to right in this row */
  177563. dir = 1;
  177564. dirnc = nc;
  177565. errorptr = cquantize->fserrors[ci]; /* => entry before first column */
  177566. }
  177567. colorindex_ci = cquantize->colorindex[ci];
  177568. colormap_ci = cquantize->sv_colormap[ci];
  177569. /* Preset error values: no error propagated to first pixel from left */
  177570. cur = 0;
  177571. /* and no error propagated to row below yet */
  177572. belowerr = bpreverr = 0;
  177573. for (col = width; col > 0; col--) {
  177574. /* cur holds the error propagated from the previous pixel on the
  177575. * current line. Add the error propagated from the previous line
  177576. * to form the complete error correction term for this pixel, and
  177577. * round the error term (which is expressed * 16) to an integer.
  177578. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  177579. * for either sign of the error value.
  177580. * Note: errorptr points to *previous* column's array entry.
  177581. */
  177582. cur = RIGHT_SHIFT(cur + errorptr[dir] + 8, 4);
  177583. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  177584. * The maximum error is +- MAXJSAMPLE; this sets the required size
  177585. * of the range_limit array.
  177586. */
  177587. cur += GETJSAMPLE(*input_ptr);
  177588. cur = GETJSAMPLE(range_limit[cur]);
  177589. /* Select output value, accumulate into output code for this pixel */
  177590. pixcode = GETJSAMPLE(colorindex_ci[cur]);
  177591. *output_ptr += (JSAMPLE) pixcode;
  177592. /* Compute actual representation error at this pixel */
  177593. /* Note: we can do this even though we don't have the final */
  177594. /* pixel code, because the colormap is orthogonal. */
  177595. cur -= GETJSAMPLE(colormap_ci[pixcode]);
  177596. /* Compute error fractions to be propagated to adjacent pixels.
  177597. * Add these into the running sums, and simultaneously shift the
  177598. * next-line error sums left by 1 column.
  177599. */
  177600. bnexterr = cur;
  177601. delta = cur * 2;
  177602. cur += delta; /* form error * 3 */
  177603. errorptr[0] = (FSERROR) (bpreverr + cur);
  177604. cur += delta; /* form error * 5 */
  177605. bpreverr = belowerr + cur;
  177606. belowerr = bnexterr;
  177607. cur += delta; /* form error * 7 */
  177608. /* At this point cur contains the 7/16 error value to be propagated
  177609. * to the next pixel on the current line, and all the errors for the
  177610. * next line have been shifted over. We are therefore ready to move on.
  177611. */
  177612. input_ptr += dirnc; /* advance input ptr to next column */
  177613. output_ptr += dir; /* advance output ptr to next column */
  177614. errorptr += dir; /* advance errorptr to current column */
  177615. }
  177616. /* Post-loop cleanup: we must unload the final error value into the
  177617. * final fserrors[] entry. Note we need not unload belowerr because
  177618. * it is for the dummy column before or after the actual array.
  177619. */
  177620. errorptr[0] = (FSERROR) bpreverr; /* unload prev err into array */
  177621. }
  177622. cquantize->on_odd_row = (cquantize->on_odd_row ? FALSE : TRUE);
  177623. }
  177624. }
  177625. /*
  177626. * Allocate workspace for Floyd-Steinberg errors.
  177627. */
  177628. LOCAL(void)
  177629. alloc_fs_workspace (j_decompress_ptr cinfo)
  177630. {
  177631. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177632. size_t arraysize;
  177633. int i;
  177634. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  177635. for (i = 0; i < cinfo->out_color_components; i++) {
  177636. cquantize->fserrors[i] = (FSERRPTR)
  177637. (*cinfo->mem->alloc_large)((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  177638. }
  177639. }
  177640. /*
  177641. * Initialize for one-pass color quantization.
  177642. */
  177643. METHODDEF(void)
  177644. start_pass_1_quant (j_decompress_ptr cinfo, boolean)
  177645. {
  177646. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177647. size_t arraysize;
  177648. int i;
  177649. /* Install my colormap. */
  177650. cinfo->colormap = cquantize->sv_colormap;
  177651. cinfo->actual_number_of_colors = cquantize->sv_actual;
  177652. /* Initialize for desired dithering mode. */
  177653. switch (cinfo->dither_mode) {
  177654. case JDITHER_NONE:
  177655. if (cinfo->out_color_components == 3)
  177656. cquantize->pub.color_quantize = color_quantize3;
  177657. else
  177658. cquantize->pub.color_quantize = color_quantize;
  177659. break;
  177660. case JDITHER_ORDERED:
  177661. if (cinfo->out_color_components == 3)
  177662. cquantize->pub.color_quantize = quantize3_ord_dither;
  177663. else
  177664. cquantize->pub.color_quantize = quantize_ord_dither;
  177665. cquantize->row_index = 0; /* initialize state for ordered dither */
  177666. /* If user changed to ordered dither from another mode,
  177667. * we must recreate the color index table with padding.
  177668. * This will cost extra space, but probably isn't very likely.
  177669. */
  177670. if (! cquantize->is_padded)
  177671. create_colorindex(cinfo);
  177672. /* Create ordered-dither tables if we didn't already. */
  177673. if (cquantize->odither[0] == NULL)
  177674. create_odither_tables(cinfo);
  177675. break;
  177676. case JDITHER_FS:
  177677. cquantize->pub.color_quantize = quantize_fs_dither;
  177678. cquantize->on_odd_row = FALSE; /* initialize state for F-S dither */
  177679. /* Allocate Floyd-Steinberg workspace if didn't already. */
  177680. if (cquantize->fserrors[0] == NULL)
  177681. alloc_fs_workspace(cinfo);
  177682. /* Initialize the propagated errors to zero. */
  177683. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  177684. for (i = 0; i < cinfo->out_color_components; i++)
  177685. jzero_far((void FAR *) cquantize->fserrors[i], arraysize);
  177686. break;
  177687. default:
  177688. ERREXIT(cinfo, JERR_NOT_COMPILED);
  177689. break;
  177690. }
  177691. }
  177692. /*
  177693. * Finish up at the end of the pass.
  177694. */
  177695. METHODDEF(void)
  177696. finish_pass_1_quant (j_decompress_ptr)
  177697. {
  177698. /* no work in 1-pass case */
  177699. }
  177700. /*
  177701. * Switch to a new external colormap between output passes.
  177702. * Shouldn't get to this module!
  177703. */
  177704. METHODDEF(void)
  177705. new_color_map_1_quant (j_decompress_ptr cinfo)
  177706. {
  177707. ERREXIT(cinfo, JERR_MODE_CHANGE);
  177708. }
  177709. /*
  177710. * Module initialization routine for 1-pass color quantization.
  177711. */
  177712. GLOBAL(void)
  177713. jinit_1pass_quantizer (j_decompress_ptr cinfo)
  177714. {
  177715. my_cquantize_ptr cquantize;
  177716. cquantize = (my_cquantize_ptr)
  177717. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177718. SIZEOF(my_cquantizer));
  177719. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  177720. cquantize->pub.start_pass = start_pass_1_quant;
  177721. cquantize->pub.finish_pass = finish_pass_1_quant;
  177722. cquantize->pub.new_color_map = new_color_map_1_quant;
  177723. cquantize->fserrors[0] = NULL; /* Flag FS workspace not allocated */
  177724. cquantize->odither[0] = NULL; /* Also flag odither arrays not allocated */
  177725. /* Make sure my internal arrays won't overflow */
  177726. if (cinfo->out_color_components > MAX_Q_COMPS)
  177727. ERREXIT1(cinfo, JERR_QUANT_COMPONENTS, MAX_Q_COMPS);
  177728. /* Make sure colormap indexes can be represented by JSAMPLEs */
  177729. if (cinfo->desired_number_of_colors > (MAXJSAMPLE+1))
  177730. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXJSAMPLE+1);
  177731. /* Create the colormap and color index table. */
  177732. create_colormap(cinfo);
  177733. create_colorindex(cinfo);
  177734. /* Allocate Floyd-Steinberg workspace now if requested.
  177735. * We do this now since it is FAR storage and may affect the memory
  177736. * manager's space calculations. If the user changes to FS dither
  177737. * mode in a later pass, we will allocate the space then, and will
  177738. * possibly overrun the max_memory_to_use setting.
  177739. */
  177740. if (cinfo->dither_mode == JDITHER_FS)
  177741. alloc_fs_workspace(cinfo);
  177742. }
  177743. #endif /* QUANT_1PASS_SUPPORTED */
  177744. /*** End of inlined file: jquant1.c ***/
  177745. /*** Start of inlined file: jquant2.c ***/
  177746. #define JPEG_INTERNALS
  177747. #ifdef QUANT_2PASS_SUPPORTED
  177748. /*
  177749. * This module implements the well-known Heckbert paradigm for color
  177750. * quantization. Most of the ideas used here can be traced back to
  177751. * Heckbert's seminal paper
  177752. * Heckbert, Paul. "Color Image Quantization for Frame Buffer Display",
  177753. * Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
  177754. *
  177755. * In the first pass over the image, we accumulate a histogram showing the
  177756. * usage count of each possible color. To keep the histogram to a reasonable
  177757. * size, we reduce the precision of the input; typical practice is to retain
  177758. * 5 or 6 bits per color, so that 8 or 4 different input values are counted
  177759. * in the same histogram cell.
  177760. *
  177761. * Next, the color-selection step begins with a box representing the whole
  177762. * color space, and repeatedly splits the "largest" remaining box until we
  177763. * have as many boxes as desired colors. Then the mean color in each
  177764. * remaining box becomes one of the possible output colors.
  177765. *
  177766. * The second pass over the image maps each input pixel to the closest output
  177767. * color (optionally after applying a Floyd-Steinberg dithering correction).
  177768. * This mapping is logically trivial, but making it go fast enough requires
  177769. * considerable care.
  177770. *
  177771. * Heckbert-style quantizers vary a good deal in their policies for choosing
  177772. * the "largest" box and deciding where to cut it. The particular policies
  177773. * used here have proved out well in experimental comparisons, but better ones
  177774. * may yet be found.
  177775. *
  177776. * In earlier versions of the IJG code, this module quantized in YCbCr color
  177777. * space, processing the raw upsampled data without a color conversion step.
  177778. * This allowed the color conversion math to be done only once per colormap
  177779. * entry, not once per pixel. However, that optimization precluded other
  177780. * useful optimizations (such as merging color conversion with upsampling)
  177781. * and it also interfered with desired capabilities such as quantizing to an
  177782. * externally-supplied colormap. We have therefore abandoned that approach.
  177783. * The present code works in the post-conversion color space, typically RGB.
  177784. *
  177785. * To improve the visual quality of the results, we actually work in scaled
  177786. * RGB space, giving G distances more weight than R, and R in turn more than
  177787. * B. To do everything in integer math, we must use integer scale factors.
  177788. * The 2/3/1 scale factors used here correspond loosely to the relative
  177789. * weights of the colors in the NTSC grayscale equation.
  177790. * If you want to use this code to quantize a non-RGB color space, you'll
  177791. * probably need to change these scale factors.
  177792. */
  177793. #define R_SCALE 2 /* scale R distances by this much */
  177794. #define G_SCALE 3 /* scale G distances by this much */
  177795. #define B_SCALE 1 /* and B by this much */
  177796. /* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined
  177797. * in jmorecfg.h. As the code stands, it will do the right thing for R,G,B
  177798. * and B,G,R orders. If you define some other weird order in jmorecfg.h,
  177799. * you'll get compile errors until you extend this logic. In that case
  177800. * you'll probably want to tweak the histogram sizes too.
  177801. */
  177802. #if RGB_RED == 0
  177803. #define C0_SCALE R_SCALE
  177804. #endif
  177805. #if RGB_BLUE == 0
  177806. #define C0_SCALE B_SCALE
  177807. #endif
  177808. #if RGB_GREEN == 1
  177809. #define C1_SCALE G_SCALE
  177810. #endif
  177811. #if RGB_RED == 2
  177812. #define C2_SCALE R_SCALE
  177813. #endif
  177814. #if RGB_BLUE == 2
  177815. #define C2_SCALE B_SCALE
  177816. #endif
  177817. /*
  177818. * First we have the histogram data structure and routines for creating it.
  177819. *
  177820. * The number of bits of precision can be adjusted by changing these symbols.
  177821. * We recommend keeping 6 bits for G and 5 each for R and B.
  177822. * If you have plenty of memory and cycles, 6 bits all around gives marginally
  177823. * better results; if you are short of memory, 5 bits all around will save
  177824. * some space but degrade the results.
  177825. * To maintain a fully accurate histogram, we'd need to allocate a "long"
  177826. * (preferably unsigned long) for each cell. In practice this is overkill;
  177827. * we can get by with 16 bits per cell. Few of the cell counts will overflow,
  177828. * and clamping those that do overflow to the maximum value will give close-
  177829. * enough results. This reduces the recommended histogram size from 256Kb
  177830. * to 128Kb, which is a useful savings on PC-class machines.
  177831. * (In the second pass the histogram space is re-used for pixel mapping data;
  177832. * in that capacity, each cell must be able to store zero to the number of
  177833. * desired colors. 16 bits/cell is plenty for that too.)
  177834. * Since the JPEG code is intended to run in small memory model on 80x86
  177835. * machines, we can't just allocate the histogram in one chunk. Instead
  177836. * of a true 3-D array, we use a row of pointers to 2-D arrays. Each
  177837. * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
  177838. * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries. Note that
  177839. * on 80x86 machines, the pointer row is in near memory but the actual
  177840. * arrays are in far memory (same arrangement as we use for image arrays).
  177841. */
  177842. #define MAXNUMCOLORS (MAXJSAMPLE+1) /* maximum size of colormap */
  177843. /* These will do the right thing for either R,G,B or B,G,R color order,
  177844. * but you may not like the results for other color orders.
  177845. */
  177846. #define HIST_C0_BITS 5 /* bits of precision in R/B histogram */
  177847. #define HIST_C1_BITS 6 /* bits of precision in G histogram */
  177848. #define HIST_C2_BITS 5 /* bits of precision in B/R histogram */
  177849. /* Number of elements along histogram axes. */
  177850. #define HIST_C0_ELEMS (1<<HIST_C0_BITS)
  177851. #define HIST_C1_ELEMS (1<<HIST_C1_BITS)
  177852. #define HIST_C2_ELEMS (1<<HIST_C2_BITS)
  177853. /* These are the amounts to shift an input value to get a histogram index. */
  177854. #define C0_SHIFT (BITS_IN_JSAMPLE-HIST_C0_BITS)
  177855. #define C1_SHIFT (BITS_IN_JSAMPLE-HIST_C1_BITS)
  177856. #define C2_SHIFT (BITS_IN_JSAMPLE-HIST_C2_BITS)
  177857. typedef UINT16 histcell; /* histogram cell; prefer an unsigned type */
  177858. typedef histcell FAR * histptr; /* for pointers to histogram cells */
  177859. typedef histcell hist1d[HIST_C2_ELEMS]; /* typedefs for the array */
  177860. typedef hist1d FAR * hist2d; /* type for the 2nd-level pointers */
  177861. typedef hist2d * hist3d; /* type for top-level pointer */
  177862. /* Declarations for Floyd-Steinberg dithering.
  177863. *
  177864. * Errors are accumulated into the array fserrors[], at a resolution of
  177865. * 1/16th of a pixel count. The error at a given pixel is propagated
  177866. * to its not-yet-processed neighbors using the standard F-S fractions,
  177867. * ... (here) 7/16
  177868. * 3/16 5/16 1/16
  177869. * We work left-to-right on even rows, right-to-left on odd rows.
  177870. *
  177871. * We can get away with a single array (holding one row's worth of errors)
  177872. * by using it to store the current row's errors at pixel columns not yet
  177873. * processed, but the next row's errors at columns already processed. We
  177874. * need only a few extra variables to hold the errors immediately around the
  177875. * current column. (If we are lucky, those variables are in registers, but
  177876. * even if not, they're probably cheaper to access than array elements are.)
  177877. *
  177878. * The fserrors[] array has (#columns + 2) entries; the extra entry at
  177879. * each end saves us from special-casing the first and last pixels.
  177880. * Each entry is three values long, one value for each color component.
  177881. *
  177882. * Note: on a wide image, we might not have enough room in a PC's near data
  177883. * segment to hold the error array; so it is allocated with alloc_large.
  177884. */
  177885. #if BITS_IN_JSAMPLE == 8
  177886. typedef INT16 FSERROR; /* 16 bits should be enough */
  177887. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  177888. #else
  177889. typedef INT32 FSERROR; /* may need more than 16 bits */
  177890. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  177891. #endif
  177892. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  177893. /* Private subobject */
  177894. typedef struct {
  177895. struct jpeg_color_quantizer pub; /* public fields */
  177896. /* Space for the eventually created colormap is stashed here */
  177897. JSAMPARRAY sv_colormap; /* colormap allocated at init time */
  177898. int desired; /* desired # of colors = size of colormap */
  177899. /* Variables for accumulating image statistics */
  177900. hist3d histogram; /* pointer to the histogram */
  177901. boolean needs_zeroed; /* TRUE if next pass must zero histogram */
  177902. /* Variables for Floyd-Steinberg dithering */
  177903. FSERRPTR fserrors; /* accumulated errors */
  177904. boolean on_odd_row; /* flag to remember which row we are on */
  177905. int * error_limiter; /* table for clamping the applied error */
  177906. } my_cquantizer2;
  177907. typedef my_cquantizer2 * my_cquantize_ptr2;
  177908. /*
  177909. * Prescan some rows of pixels.
  177910. * In this module the prescan simply updates the histogram, which has been
  177911. * initialized to zeroes by start_pass.
  177912. * An output_buf parameter is required by the method signature, but no data
  177913. * is actually output (in fact the buffer controller is probably passing a
  177914. * NULL pointer).
  177915. */
  177916. METHODDEF(void)
  177917. prescan_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177918. JSAMPARRAY, int num_rows)
  177919. {
  177920. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177921. register JSAMPROW ptr;
  177922. register histptr histp;
  177923. register hist3d histogram = cquantize->histogram;
  177924. int row;
  177925. JDIMENSION col;
  177926. JDIMENSION width = cinfo->output_width;
  177927. for (row = 0; row < num_rows; row++) {
  177928. ptr = input_buf[row];
  177929. for (col = width; col > 0; col--) {
  177930. /* get pixel value and index into the histogram */
  177931. histp = & histogram[GETJSAMPLE(ptr[0]) >> C0_SHIFT]
  177932. [GETJSAMPLE(ptr[1]) >> C1_SHIFT]
  177933. [GETJSAMPLE(ptr[2]) >> C2_SHIFT];
  177934. /* increment, check for overflow and undo increment if so. */
  177935. if (++(*histp) <= 0)
  177936. (*histp)--;
  177937. ptr += 3;
  177938. }
  177939. }
  177940. }
  177941. /*
  177942. * Next we have the really interesting routines: selection of a colormap
  177943. * given the completed histogram.
  177944. * These routines work with a list of "boxes", each representing a rectangular
  177945. * subset of the input color space (to histogram precision).
  177946. */
  177947. typedef struct {
  177948. /* The bounds of the box (inclusive); expressed as histogram indexes */
  177949. int c0min, c0max;
  177950. int c1min, c1max;
  177951. int c2min, c2max;
  177952. /* The volume (actually 2-norm) of the box */
  177953. INT32 volume;
  177954. /* The number of nonzero histogram cells within this box */
  177955. long colorcount;
  177956. } box;
  177957. typedef box * boxptr;
  177958. LOCAL(boxptr)
  177959. find_biggest_color_pop (boxptr boxlist, int numboxes)
  177960. /* Find the splittable box with the largest color population */
  177961. /* Returns NULL if no splittable boxes remain */
  177962. {
  177963. register boxptr boxp;
  177964. register int i;
  177965. register long maxc = 0;
  177966. boxptr which = NULL;
  177967. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  177968. if (boxp->colorcount > maxc && boxp->volume > 0) {
  177969. which = boxp;
  177970. maxc = boxp->colorcount;
  177971. }
  177972. }
  177973. return which;
  177974. }
  177975. LOCAL(boxptr)
  177976. find_biggest_volume (boxptr boxlist, int numboxes)
  177977. /* Find the splittable box with the largest (scaled) volume */
  177978. /* Returns NULL if no splittable boxes remain */
  177979. {
  177980. register boxptr boxp;
  177981. register int i;
  177982. register INT32 maxv = 0;
  177983. boxptr which = NULL;
  177984. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  177985. if (boxp->volume > maxv) {
  177986. which = boxp;
  177987. maxv = boxp->volume;
  177988. }
  177989. }
  177990. return which;
  177991. }
  177992. LOCAL(void)
  177993. update_box (j_decompress_ptr cinfo, boxptr boxp)
  177994. /* Shrink the min/max bounds of a box to enclose only nonzero elements, */
  177995. /* and recompute its volume and population */
  177996. {
  177997. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177998. hist3d histogram = cquantize->histogram;
  177999. histptr histp;
  178000. int c0,c1,c2;
  178001. int c0min,c0max,c1min,c1max,c2min,c2max;
  178002. INT32 dist0,dist1,dist2;
  178003. long ccount;
  178004. c0min = boxp->c0min; c0max = boxp->c0max;
  178005. c1min = boxp->c1min; c1max = boxp->c1max;
  178006. c2min = boxp->c2min; c2max = boxp->c2max;
  178007. if (c0max > c0min)
  178008. for (c0 = c0min; c0 <= c0max; c0++)
  178009. for (c1 = c1min; c1 <= c1max; c1++) {
  178010. histp = & histogram[c0][c1][c2min];
  178011. for (c2 = c2min; c2 <= c2max; c2++)
  178012. if (*histp++ != 0) {
  178013. boxp->c0min = c0min = c0;
  178014. goto have_c0min;
  178015. }
  178016. }
  178017. have_c0min:
  178018. if (c0max > c0min)
  178019. for (c0 = c0max; c0 >= c0min; c0--)
  178020. for (c1 = c1min; c1 <= c1max; c1++) {
  178021. histp = & histogram[c0][c1][c2min];
  178022. for (c2 = c2min; c2 <= c2max; c2++)
  178023. if (*histp++ != 0) {
  178024. boxp->c0max = c0max = c0;
  178025. goto have_c0max;
  178026. }
  178027. }
  178028. have_c0max:
  178029. if (c1max > c1min)
  178030. for (c1 = c1min; c1 <= c1max; c1++)
  178031. for (c0 = c0min; c0 <= c0max; c0++) {
  178032. histp = & histogram[c0][c1][c2min];
  178033. for (c2 = c2min; c2 <= c2max; c2++)
  178034. if (*histp++ != 0) {
  178035. boxp->c1min = c1min = c1;
  178036. goto have_c1min;
  178037. }
  178038. }
  178039. have_c1min:
  178040. if (c1max > c1min)
  178041. for (c1 = c1max; c1 >= c1min; c1--)
  178042. for (c0 = c0min; c0 <= c0max; c0++) {
  178043. histp = & histogram[c0][c1][c2min];
  178044. for (c2 = c2min; c2 <= c2max; c2++)
  178045. if (*histp++ != 0) {
  178046. boxp->c1max = c1max = c1;
  178047. goto have_c1max;
  178048. }
  178049. }
  178050. have_c1max:
  178051. if (c2max > c2min)
  178052. for (c2 = c2min; c2 <= c2max; c2++)
  178053. for (c0 = c0min; c0 <= c0max; c0++) {
  178054. histp = & histogram[c0][c1min][c2];
  178055. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  178056. if (*histp != 0) {
  178057. boxp->c2min = c2min = c2;
  178058. goto have_c2min;
  178059. }
  178060. }
  178061. have_c2min:
  178062. if (c2max > c2min)
  178063. for (c2 = c2max; c2 >= c2min; c2--)
  178064. for (c0 = c0min; c0 <= c0max; c0++) {
  178065. histp = & histogram[c0][c1min][c2];
  178066. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  178067. if (*histp != 0) {
  178068. boxp->c2max = c2max = c2;
  178069. goto have_c2max;
  178070. }
  178071. }
  178072. have_c2max:
  178073. /* Update box volume.
  178074. * We use 2-norm rather than real volume here; this biases the method
  178075. * against making long narrow boxes, and it has the side benefit that
  178076. * a box is splittable iff norm > 0.
  178077. * Since the differences are expressed in histogram-cell units,
  178078. * we have to shift back to JSAMPLE units to get consistent distances;
  178079. * after which, we scale according to the selected distance scale factors.
  178080. */
  178081. dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
  178082. dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
  178083. dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
  178084. boxp->volume = dist0*dist0 + dist1*dist1 + dist2*dist2;
  178085. /* Now scan remaining volume of box and compute population */
  178086. ccount = 0;
  178087. for (c0 = c0min; c0 <= c0max; c0++)
  178088. for (c1 = c1min; c1 <= c1max; c1++) {
  178089. histp = & histogram[c0][c1][c2min];
  178090. for (c2 = c2min; c2 <= c2max; c2++, histp++)
  178091. if (*histp != 0) {
  178092. ccount++;
  178093. }
  178094. }
  178095. boxp->colorcount = ccount;
  178096. }
  178097. LOCAL(int)
  178098. median_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes,
  178099. int desired_colors)
  178100. /* Repeatedly select and split the largest box until we have enough boxes */
  178101. {
  178102. int n,lb;
  178103. int c0,c1,c2,cmax;
  178104. register boxptr b1,b2;
  178105. while (numboxes < desired_colors) {
  178106. /* Select box to split.
  178107. * Current algorithm: by population for first half, then by volume.
  178108. */
  178109. if (numboxes*2 <= desired_colors) {
  178110. b1 = find_biggest_color_pop(boxlist, numboxes);
  178111. } else {
  178112. b1 = find_biggest_volume(boxlist, numboxes);
  178113. }
  178114. if (b1 == NULL) /* no splittable boxes left! */
  178115. break;
  178116. b2 = &boxlist[numboxes]; /* where new box will go */
  178117. /* Copy the color bounds to the new box. */
  178118. b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max;
  178119. b2->c0min = b1->c0min; b2->c1min = b1->c1min; b2->c2min = b1->c2min;
  178120. /* Choose which axis to split the box on.
  178121. * Current algorithm: longest scaled axis.
  178122. * See notes in update_box about scaling distances.
  178123. */
  178124. c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
  178125. c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
  178126. c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE;
  178127. /* We want to break any ties in favor of green, then red, blue last.
  178128. * This code does the right thing for R,G,B or B,G,R color orders only.
  178129. */
  178130. #if RGB_RED == 0
  178131. cmax = c1; n = 1;
  178132. if (c0 > cmax) { cmax = c0; n = 0; }
  178133. if (c2 > cmax) { n = 2; }
  178134. #else
  178135. cmax = c1; n = 1;
  178136. if (c2 > cmax) { cmax = c2; n = 2; }
  178137. if (c0 > cmax) { n = 0; }
  178138. #endif
  178139. /* Choose split point along selected axis, and update box bounds.
  178140. * Current algorithm: split at halfway point.
  178141. * (Since the box has been shrunk to minimum volume,
  178142. * any split will produce two nonempty subboxes.)
  178143. * Note that lb value is max for lower box, so must be < old max.
  178144. */
  178145. switch (n) {
  178146. case 0:
  178147. lb = (b1->c0max + b1->c0min) / 2;
  178148. b1->c0max = lb;
  178149. b2->c0min = lb+1;
  178150. break;
  178151. case 1:
  178152. lb = (b1->c1max + b1->c1min) / 2;
  178153. b1->c1max = lb;
  178154. b2->c1min = lb+1;
  178155. break;
  178156. case 2:
  178157. lb = (b1->c2max + b1->c2min) / 2;
  178158. b1->c2max = lb;
  178159. b2->c2min = lb+1;
  178160. break;
  178161. }
  178162. /* Update stats for boxes */
  178163. update_box(cinfo, b1);
  178164. update_box(cinfo, b2);
  178165. numboxes++;
  178166. }
  178167. return numboxes;
  178168. }
  178169. LOCAL(void)
  178170. compute_color (j_decompress_ptr cinfo, boxptr boxp, int icolor)
  178171. /* Compute representative color for a box, put it in colormap[icolor] */
  178172. {
  178173. /* Current algorithm: mean weighted by pixels (not colors) */
  178174. /* Note it is important to get the rounding correct! */
  178175. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178176. hist3d histogram = cquantize->histogram;
  178177. histptr histp;
  178178. int c0,c1,c2;
  178179. int c0min,c0max,c1min,c1max,c2min,c2max;
  178180. long count;
  178181. long total = 0;
  178182. long c0total = 0;
  178183. long c1total = 0;
  178184. long c2total = 0;
  178185. c0min = boxp->c0min; c0max = boxp->c0max;
  178186. c1min = boxp->c1min; c1max = boxp->c1max;
  178187. c2min = boxp->c2min; c2max = boxp->c2max;
  178188. for (c0 = c0min; c0 <= c0max; c0++)
  178189. for (c1 = c1min; c1 <= c1max; c1++) {
  178190. histp = & histogram[c0][c1][c2min];
  178191. for (c2 = c2min; c2 <= c2max; c2++) {
  178192. if ((count = *histp++) != 0) {
  178193. total += count;
  178194. c0total += ((c0 << C0_SHIFT) + ((1<<C0_SHIFT)>>1)) * count;
  178195. c1total += ((c1 << C1_SHIFT) + ((1<<C1_SHIFT)>>1)) * count;
  178196. c2total += ((c2 << C2_SHIFT) + ((1<<C2_SHIFT)>>1)) * count;
  178197. }
  178198. }
  178199. }
  178200. cinfo->colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total);
  178201. cinfo->colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total);
  178202. cinfo->colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total);
  178203. }
  178204. LOCAL(void)
  178205. select_colors (j_decompress_ptr cinfo, int desired_colors)
  178206. /* Master routine for color selection */
  178207. {
  178208. boxptr boxlist;
  178209. int numboxes;
  178210. int i;
  178211. /* Allocate workspace for box list */
  178212. boxlist = (boxptr) (*cinfo->mem->alloc_small)
  178213. ((j_common_ptr) cinfo, JPOOL_IMAGE, desired_colors * SIZEOF(box));
  178214. /* Initialize one box containing whole space */
  178215. numboxes = 1;
  178216. boxlist[0].c0min = 0;
  178217. boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT;
  178218. boxlist[0].c1min = 0;
  178219. boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT;
  178220. boxlist[0].c2min = 0;
  178221. boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT;
  178222. /* Shrink it to actually-used volume and set its statistics */
  178223. update_box(cinfo, & boxlist[0]);
  178224. /* Perform median-cut to produce final box list */
  178225. numboxes = median_cut(cinfo, boxlist, numboxes, desired_colors);
  178226. /* Compute the representative color for each box, fill colormap */
  178227. for (i = 0; i < numboxes; i++)
  178228. compute_color(cinfo, & boxlist[i], i);
  178229. cinfo->actual_number_of_colors = numboxes;
  178230. TRACEMS1(cinfo, 1, JTRC_QUANT_SELECTED, numboxes);
  178231. }
  178232. /*
  178233. * These routines are concerned with the time-critical task of mapping input
  178234. * colors to the nearest color in the selected colormap.
  178235. *
  178236. * We re-use the histogram space as an "inverse color map", essentially a
  178237. * cache for the results of nearest-color searches. All colors within a
  178238. * histogram cell will be mapped to the same colormap entry, namely the one
  178239. * closest to the cell's center. This may not be quite the closest entry to
  178240. * the actual input color, but it's almost as good. A zero in the cache
  178241. * indicates we haven't found the nearest color for that cell yet; the array
  178242. * is cleared to zeroes before starting the mapping pass. When we find the
  178243. * nearest color for a cell, its colormap index plus one is recorded in the
  178244. * cache for future use. The pass2 scanning routines call fill_inverse_cmap
  178245. * when they need to use an unfilled entry in the cache.
  178246. *
  178247. * Our method of efficiently finding nearest colors is based on the "locally
  178248. * sorted search" idea described by Heckbert and on the incremental distance
  178249. * calculation described by Spencer W. Thomas in chapter III.1 of Graphics
  178250. * Gems II (James Arvo, ed. Academic Press, 1991). Thomas points out that
  178251. * the distances from a given colormap entry to each cell of the histogram can
  178252. * be computed quickly using an incremental method: the differences between
  178253. * distances to adjacent cells themselves differ by a constant. This allows a
  178254. * fairly fast implementation of the "brute force" approach of computing the
  178255. * distance from every colormap entry to every histogram cell. Unfortunately,
  178256. * it needs a work array to hold the best-distance-so-far for each histogram
  178257. * cell (because the inner loop has to be over cells, not colormap entries).
  178258. * The work array elements have to be INT32s, so the work array would need
  178259. * 256Kb at our recommended precision. This is not feasible in DOS machines.
  178260. *
  178261. * To get around these problems, we apply Thomas' method to compute the
  178262. * nearest colors for only the cells within a small subbox of the histogram.
  178263. * The work array need be only as big as the subbox, so the memory usage
  178264. * problem is solved. Furthermore, we need not fill subboxes that are never
  178265. * referenced in pass2; many images use only part of the color gamut, so a
  178266. * fair amount of work is saved. An additional advantage of this
  178267. * approach is that we can apply Heckbert's locality criterion to quickly
  178268. * eliminate colormap entries that are far away from the subbox; typically
  178269. * three-fourths of the colormap entries are rejected by Heckbert's criterion,
  178270. * and we need not compute their distances to individual cells in the subbox.
  178271. * The speed of this approach is heavily influenced by the subbox size: too
  178272. * small means too much overhead, too big loses because Heckbert's criterion
  178273. * can't eliminate as many colormap entries. Empirically the best subbox
  178274. * size seems to be about 1/512th of the histogram (1/8th in each direction).
  178275. *
  178276. * Thomas' article also describes a refined method which is asymptotically
  178277. * faster than the brute-force method, but it is also far more complex and
  178278. * cannot efficiently be applied to small subboxes. It is therefore not
  178279. * useful for programs intended to be portable to DOS machines. On machines
  178280. * with plenty of memory, filling the whole histogram in one shot with Thomas'
  178281. * refined method might be faster than the present code --- but then again,
  178282. * it might not be any faster, and it's certainly more complicated.
  178283. */
  178284. /* log2(histogram cells in update box) for each axis; this can be adjusted */
  178285. #define BOX_C0_LOG (HIST_C0_BITS-3)
  178286. #define BOX_C1_LOG (HIST_C1_BITS-3)
  178287. #define BOX_C2_LOG (HIST_C2_BITS-3)
  178288. #define BOX_C0_ELEMS (1<<BOX_C0_LOG) /* # of hist cells in update box */
  178289. #define BOX_C1_ELEMS (1<<BOX_C1_LOG)
  178290. #define BOX_C2_ELEMS (1<<BOX_C2_LOG)
  178291. #define BOX_C0_SHIFT (C0_SHIFT + BOX_C0_LOG)
  178292. #define BOX_C1_SHIFT (C1_SHIFT + BOX_C1_LOG)
  178293. #define BOX_C2_SHIFT (C2_SHIFT + BOX_C2_LOG)
  178294. /*
  178295. * The next three routines implement inverse colormap filling. They could
  178296. * all be folded into one big routine, but splitting them up this way saves
  178297. * some stack space (the mindist[] and bestdist[] arrays need not coexist)
  178298. * and may allow some compilers to produce better code by registerizing more
  178299. * inner-loop variables.
  178300. */
  178301. LOCAL(int)
  178302. find_nearby_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  178303. JSAMPLE colorlist[])
  178304. /* Locate the colormap entries close enough to an update box to be candidates
  178305. * for the nearest entry to some cell(s) in the update box. The update box
  178306. * is specified by the center coordinates of its first cell. The number of
  178307. * candidate colormap entries is returned, and their colormap indexes are
  178308. * placed in colorlist[].
  178309. * This routine uses Heckbert's "locally sorted search" criterion to select
  178310. * the colors that need further consideration.
  178311. */
  178312. {
  178313. int numcolors = cinfo->actual_number_of_colors;
  178314. int maxc0, maxc1, maxc2;
  178315. int centerc0, centerc1, centerc2;
  178316. int i, x, ncolors;
  178317. INT32 minmaxdist, min_dist, max_dist, tdist;
  178318. INT32 mindist[MAXNUMCOLORS]; /* min distance to colormap entry i */
  178319. /* Compute true coordinates of update box's upper corner and center.
  178320. * Actually we compute the coordinates of the center of the upper-corner
  178321. * histogram cell, which are the upper bounds of the volume we care about.
  178322. * Note that since ">>" rounds down, the "center" values may be closer to
  178323. * min than to max; hence comparisons to them must be "<=", not "<".
  178324. */
  178325. maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT));
  178326. centerc0 = (minc0 + maxc0) >> 1;
  178327. maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT));
  178328. centerc1 = (minc1 + maxc1) >> 1;
  178329. maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT));
  178330. centerc2 = (minc2 + maxc2) >> 1;
  178331. /* For each color in colormap, find:
  178332. * 1. its minimum squared-distance to any point in the update box
  178333. * (zero if color is within update box);
  178334. * 2. its maximum squared-distance to any point in the update box.
  178335. * Both of these can be found by considering only the corners of the box.
  178336. * We save the minimum distance for each color in mindist[];
  178337. * only the smallest maximum distance is of interest.
  178338. */
  178339. minmaxdist = 0x7FFFFFFFL;
  178340. for (i = 0; i < numcolors; i++) {
  178341. /* We compute the squared-c0-distance term, then add in the other two. */
  178342. x = GETJSAMPLE(cinfo->colormap[0][i]);
  178343. if (x < minc0) {
  178344. tdist = (x - minc0) * C0_SCALE;
  178345. min_dist = tdist*tdist;
  178346. tdist = (x - maxc0) * C0_SCALE;
  178347. max_dist = tdist*tdist;
  178348. } else if (x > maxc0) {
  178349. tdist = (x - maxc0) * C0_SCALE;
  178350. min_dist = tdist*tdist;
  178351. tdist = (x - minc0) * C0_SCALE;
  178352. max_dist = tdist*tdist;
  178353. } else {
  178354. /* within cell range so no contribution to min_dist */
  178355. min_dist = 0;
  178356. if (x <= centerc0) {
  178357. tdist = (x - maxc0) * C0_SCALE;
  178358. max_dist = tdist*tdist;
  178359. } else {
  178360. tdist = (x - minc0) * C0_SCALE;
  178361. max_dist = tdist*tdist;
  178362. }
  178363. }
  178364. x = GETJSAMPLE(cinfo->colormap[1][i]);
  178365. if (x < minc1) {
  178366. tdist = (x - minc1) * C1_SCALE;
  178367. min_dist += tdist*tdist;
  178368. tdist = (x - maxc1) * C1_SCALE;
  178369. max_dist += tdist*tdist;
  178370. } else if (x > maxc1) {
  178371. tdist = (x - maxc1) * C1_SCALE;
  178372. min_dist += tdist*tdist;
  178373. tdist = (x - minc1) * C1_SCALE;
  178374. max_dist += tdist*tdist;
  178375. } else {
  178376. /* within cell range so no contribution to min_dist */
  178377. if (x <= centerc1) {
  178378. tdist = (x - maxc1) * C1_SCALE;
  178379. max_dist += tdist*tdist;
  178380. } else {
  178381. tdist = (x - minc1) * C1_SCALE;
  178382. max_dist += tdist*tdist;
  178383. }
  178384. }
  178385. x = GETJSAMPLE(cinfo->colormap[2][i]);
  178386. if (x < minc2) {
  178387. tdist = (x - minc2) * C2_SCALE;
  178388. min_dist += tdist*tdist;
  178389. tdist = (x - maxc2) * C2_SCALE;
  178390. max_dist += tdist*tdist;
  178391. } else if (x > maxc2) {
  178392. tdist = (x - maxc2) * C2_SCALE;
  178393. min_dist += tdist*tdist;
  178394. tdist = (x - minc2) * C2_SCALE;
  178395. max_dist += tdist*tdist;
  178396. } else {
  178397. /* within cell range so no contribution to min_dist */
  178398. if (x <= centerc2) {
  178399. tdist = (x - maxc2) * C2_SCALE;
  178400. max_dist += tdist*tdist;
  178401. } else {
  178402. tdist = (x - minc2) * C2_SCALE;
  178403. max_dist += tdist*tdist;
  178404. }
  178405. }
  178406. mindist[i] = min_dist; /* save away the results */
  178407. if (max_dist < minmaxdist)
  178408. minmaxdist = max_dist;
  178409. }
  178410. /* Now we know that no cell in the update box is more than minmaxdist
  178411. * away from some colormap entry. Therefore, only colors that are
  178412. * within minmaxdist of some part of the box need be considered.
  178413. */
  178414. ncolors = 0;
  178415. for (i = 0; i < numcolors; i++) {
  178416. if (mindist[i] <= minmaxdist)
  178417. colorlist[ncolors++] = (JSAMPLE) i;
  178418. }
  178419. return ncolors;
  178420. }
  178421. LOCAL(void)
  178422. find_best_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  178423. int numcolors, JSAMPLE colorlist[], JSAMPLE bestcolor[])
  178424. /* Find the closest colormap entry for each cell in the update box,
  178425. * given the list of candidate colors prepared by find_nearby_colors.
  178426. * Return the indexes of the closest entries in the bestcolor[] array.
  178427. * This routine uses Thomas' incremental distance calculation method to
  178428. * find the distance from a colormap entry to successive cells in the box.
  178429. */
  178430. {
  178431. int ic0, ic1, ic2;
  178432. int i, icolor;
  178433. register INT32 * bptr; /* pointer into bestdist[] array */
  178434. JSAMPLE * cptr; /* pointer into bestcolor[] array */
  178435. INT32 dist0, dist1; /* initial distance values */
  178436. register INT32 dist2; /* current distance in inner loop */
  178437. INT32 xx0, xx1; /* distance increments */
  178438. register INT32 xx2;
  178439. INT32 inc0, inc1, inc2; /* initial values for increments */
  178440. /* This array holds the distance to the nearest-so-far color for each cell */
  178441. INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  178442. /* Initialize best-distance for each cell of the update box */
  178443. bptr = bestdist;
  178444. for (i = BOX_C0_ELEMS*BOX_C1_ELEMS*BOX_C2_ELEMS-1; i >= 0; i--)
  178445. *bptr++ = 0x7FFFFFFFL;
  178446. /* For each color selected by find_nearby_colors,
  178447. * compute its distance to the center of each cell in the box.
  178448. * If that's less than best-so-far, update best distance and color number.
  178449. */
  178450. /* Nominal steps between cell centers ("x" in Thomas article) */
  178451. #define STEP_C0 ((1 << C0_SHIFT) * C0_SCALE)
  178452. #define STEP_C1 ((1 << C1_SHIFT) * C1_SCALE)
  178453. #define STEP_C2 ((1 << C2_SHIFT) * C2_SCALE)
  178454. for (i = 0; i < numcolors; i++) {
  178455. icolor = GETJSAMPLE(colorlist[i]);
  178456. /* Compute (square of) distance from minc0/c1/c2 to this color */
  178457. inc0 = (minc0 - GETJSAMPLE(cinfo->colormap[0][icolor])) * C0_SCALE;
  178458. dist0 = inc0*inc0;
  178459. inc1 = (minc1 - GETJSAMPLE(cinfo->colormap[1][icolor])) * C1_SCALE;
  178460. dist0 += inc1*inc1;
  178461. inc2 = (minc2 - GETJSAMPLE(cinfo->colormap[2][icolor])) * C2_SCALE;
  178462. dist0 += inc2*inc2;
  178463. /* Form the initial difference increments */
  178464. inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0;
  178465. inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1;
  178466. inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2;
  178467. /* Now loop over all cells in box, updating distance per Thomas method */
  178468. bptr = bestdist;
  178469. cptr = bestcolor;
  178470. xx0 = inc0;
  178471. for (ic0 = BOX_C0_ELEMS-1; ic0 >= 0; ic0--) {
  178472. dist1 = dist0;
  178473. xx1 = inc1;
  178474. for (ic1 = BOX_C1_ELEMS-1; ic1 >= 0; ic1--) {
  178475. dist2 = dist1;
  178476. xx2 = inc2;
  178477. for (ic2 = BOX_C2_ELEMS-1; ic2 >= 0; ic2--) {
  178478. if (dist2 < *bptr) {
  178479. *bptr = dist2;
  178480. *cptr = (JSAMPLE) icolor;
  178481. }
  178482. dist2 += xx2;
  178483. xx2 += 2 * STEP_C2 * STEP_C2;
  178484. bptr++;
  178485. cptr++;
  178486. }
  178487. dist1 += xx1;
  178488. xx1 += 2 * STEP_C1 * STEP_C1;
  178489. }
  178490. dist0 += xx0;
  178491. xx0 += 2 * STEP_C0 * STEP_C0;
  178492. }
  178493. }
  178494. }
  178495. LOCAL(void)
  178496. fill_inverse_cmap (j_decompress_ptr cinfo, int c0, int c1, int c2)
  178497. /* Fill the inverse-colormap entries in the update box that contains */
  178498. /* histogram cell c0/c1/c2. (Only that one cell MUST be filled, but */
  178499. /* we can fill as many others as we wish.) */
  178500. {
  178501. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178502. hist3d histogram = cquantize->histogram;
  178503. int minc0, minc1, minc2; /* lower left corner of update box */
  178504. int ic0, ic1, ic2;
  178505. register JSAMPLE * cptr; /* pointer into bestcolor[] array */
  178506. register histptr cachep; /* pointer into main cache array */
  178507. /* This array lists the candidate colormap indexes. */
  178508. JSAMPLE colorlist[MAXNUMCOLORS];
  178509. int numcolors; /* number of candidate colors */
  178510. /* This array holds the actually closest colormap index for each cell. */
  178511. JSAMPLE bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  178512. /* Convert cell coordinates to update box ID */
  178513. c0 >>= BOX_C0_LOG;
  178514. c1 >>= BOX_C1_LOG;
  178515. c2 >>= BOX_C2_LOG;
  178516. /* Compute true coordinates of update box's origin corner.
  178517. * Actually we compute the coordinates of the center of the corner
  178518. * histogram cell, which are the lower bounds of the volume we care about.
  178519. */
  178520. minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1);
  178521. minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1);
  178522. minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1);
  178523. /* Determine which colormap entries are close enough to be candidates
  178524. * for the nearest entry to some cell in the update box.
  178525. */
  178526. numcolors = find_nearby_colors(cinfo, minc0, minc1, minc2, colorlist);
  178527. /* Determine the actually nearest colors. */
  178528. find_best_colors(cinfo, minc0, minc1, minc2, numcolors, colorlist,
  178529. bestcolor);
  178530. /* Save the best color numbers (plus 1) in the main cache array */
  178531. c0 <<= BOX_C0_LOG; /* convert ID back to base cell indexes */
  178532. c1 <<= BOX_C1_LOG;
  178533. c2 <<= BOX_C2_LOG;
  178534. cptr = bestcolor;
  178535. for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++) {
  178536. for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++) {
  178537. cachep = & histogram[c0+ic0][c1+ic1][c2];
  178538. for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++) {
  178539. *cachep++ = (histcell) (GETJSAMPLE(*cptr++) + 1);
  178540. }
  178541. }
  178542. }
  178543. }
  178544. /*
  178545. * Map some rows of pixels to the output colormapped representation.
  178546. */
  178547. METHODDEF(void)
  178548. pass2_no_dither (j_decompress_ptr cinfo,
  178549. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  178550. /* This version performs no dithering */
  178551. {
  178552. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178553. hist3d histogram = cquantize->histogram;
  178554. register JSAMPROW inptr, outptr;
  178555. register histptr cachep;
  178556. register int c0, c1, c2;
  178557. int row;
  178558. JDIMENSION col;
  178559. JDIMENSION width = cinfo->output_width;
  178560. for (row = 0; row < num_rows; row++) {
  178561. inptr = input_buf[row];
  178562. outptr = output_buf[row];
  178563. for (col = width; col > 0; col--) {
  178564. /* get pixel value and index into the cache */
  178565. c0 = GETJSAMPLE(*inptr++) >> C0_SHIFT;
  178566. c1 = GETJSAMPLE(*inptr++) >> C1_SHIFT;
  178567. c2 = GETJSAMPLE(*inptr++) >> C2_SHIFT;
  178568. cachep = & histogram[c0][c1][c2];
  178569. /* If we have not seen this color before, find nearest colormap entry */
  178570. /* and update the cache */
  178571. if (*cachep == 0)
  178572. fill_inverse_cmap(cinfo, c0,c1,c2);
  178573. /* Now emit the colormap index for this cell */
  178574. *outptr++ = (JSAMPLE) (*cachep - 1);
  178575. }
  178576. }
  178577. }
  178578. METHODDEF(void)
  178579. pass2_fs_dither (j_decompress_ptr cinfo,
  178580. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  178581. /* This version performs Floyd-Steinberg dithering */
  178582. {
  178583. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178584. hist3d histogram = cquantize->histogram;
  178585. register LOCFSERROR cur0, cur1, cur2; /* current error or pixel value */
  178586. LOCFSERROR belowerr0, belowerr1, belowerr2; /* error for pixel below cur */
  178587. LOCFSERROR bpreverr0, bpreverr1, bpreverr2; /* error for below/prev col */
  178588. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  178589. JSAMPROW inptr; /* => current input pixel */
  178590. JSAMPROW outptr; /* => current output pixel */
  178591. histptr cachep;
  178592. int dir; /* +1 or -1 depending on direction */
  178593. int dir3; /* 3*dir, for advancing inptr & errorptr */
  178594. int row;
  178595. JDIMENSION col;
  178596. JDIMENSION width = cinfo->output_width;
  178597. JSAMPLE *range_limit = cinfo->sample_range_limit;
  178598. int *error_limit = cquantize->error_limiter;
  178599. JSAMPROW colormap0 = cinfo->colormap[0];
  178600. JSAMPROW colormap1 = cinfo->colormap[1];
  178601. JSAMPROW colormap2 = cinfo->colormap[2];
  178602. SHIFT_TEMPS
  178603. for (row = 0; row < num_rows; row++) {
  178604. inptr = input_buf[row];
  178605. outptr = output_buf[row];
  178606. if (cquantize->on_odd_row) {
  178607. /* work right to left in this row */
  178608. inptr += (width-1) * 3; /* so point to rightmost pixel */
  178609. outptr += width-1;
  178610. dir = -1;
  178611. dir3 = -3;
  178612. errorptr = cquantize->fserrors + (width+1)*3; /* => entry after last column */
  178613. cquantize->on_odd_row = FALSE; /* flip for next time */
  178614. } else {
  178615. /* work left to right in this row */
  178616. dir = 1;
  178617. dir3 = 3;
  178618. errorptr = cquantize->fserrors; /* => entry before first real column */
  178619. cquantize->on_odd_row = TRUE; /* flip for next time */
  178620. }
  178621. /* Preset error values: no error propagated to first pixel from left */
  178622. cur0 = cur1 = cur2 = 0;
  178623. /* and no error propagated to row below yet */
  178624. belowerr0 = belowerr1 = belowerr2 = 0;
  178625. bpreverr0 = bpreverr1 = bpreverr2 = 0;
  178626. for (col = width; col > 0; col--) {
  178627. /* curN holds the error propagated from the previous pixel on the
  178628. * current line. Add the error propagated from the previous line
  178629. * to form the complete error correction term for this pixel, and
  178630. * round the error term (which is expressed * 16) to an integer.
  178631. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  178632. * for either sign of the error value.
  178633. * Note: errorptr points to *previous* column's array entry.
  178634. */
  178635. cur0 = RIGHT_SHIFT(cur0 + errorptr[dir3+0] + 8, 4);
  178636. cur1 = RIGHT_SHIFT(cur1 + errorptr[dir3+1] + 8, 4);
  178637. cur2 = RIGHT_SHIFT(cur2 + errorptr[dir3+2] + 8, 4);
  178638. /* Limit the error using transfer function set by init_error_limit.
  178639. * See comments with init_error_limit for rationale.
  178640. */
  178641. cur0 = error_limit[cur0];
  178642. cur1 = error_limit[cur1];
  178643. cur2 = error_limit[cur2];
  178644. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  178645. * The maximum error is +- MAXJSAMPLE (or less with error limiting);
  178646. * this sets the required size of the range_limit array.
  178647. */
  178648. cur0 += GETJSAMPLE(inptr[0]);
  178649. cur1 += GETJSAMPLE(inptr[1]);
  178650. cur2 += GETJSAMPLE(inptr[2]);
  178651. cur0 = GETJSAMPLE(range_limit[cur0]);
  178652. cur1 = GETJSAMPLE(range_limit[cur1]);
  178653. cur2 = GETJSAMPLE(range_limit[cur2]);
  178654. /* Index into the cache with adjusted pixel value */
  178655. cachep = & histogram[cur0>>C0_SHIFT][cur1>>C1_SHIFT][cur2>>C2_SHIFT];
  178656. /* If we have not seen this color before, find nearest colormap */
  178657. /* entry and update the cache */
  178658. if (*cachep == 0)
  178659. fill_inverse_cmap(cinfo, cur0>>C0_SHIFT,cur1>>C1_SHIFT,cur2>>C2_SHIFT);
  178660. /* Now emit the colormap index for this cell */
  178661. { register int pixcode = *cachep - 1;
  178662. *outptr = (JSAMPLE) pixcode;
  178663. /* Compute representation error for this pixel */
  178664. cur0 -= GETJSAMPLE(colormap0[pixcode]);
  178665. cur1 -= GETJSAMPLE(colormap1[pixcode]);
  178666. cur2 -= GETJSAMPLE(colormap2[pixcode]);
  178667. }
  178668. /* Compute error fractions to be propagated to adjacent pixels.
  178669. * Add these into the running sums, and simultaneously shift the
  178670. * next-line error sums left by 1 column.
  178671. */
  178672. { register LOCFSERROR bnexterr, delta;
  178673. bnexterr = cur0; /* Process component 0 */
  178674. delta = cur0 * 2;
  178675. cur0 += delta; /* form error * 3 */
  178676. errorptr[0] = (FSERROR) (bpreverr0 + cur0);
  178677. cur0 += delta; /* form error * 5 */
  178678. bpreverr0 = belowerr0 + cur0;
  178679. belowerr0 = bnexterr;
  178680. cur0 += delta; /* form error * 7 */
  178681. bnexterr = cur1; /* Process component 1 */
  178682. delta = cur1 * 2;
  178683. cur1 += delta; /* form error * 3 */
  178684. errorptr[1] = (FSERROR) (bpreverr1 + cur1);
  178685. cur1 += delta; /* form error * 5 */
  178686. bpreverr1 = belowerr1 + cur1;
  178687. belowerr1 = bnexterr;
  178688. cur1 += delta; /* form error * 7 */
  178689. bnexterr = cur2; /* Process component 2 */
  178690. delta = cur2 * 2;
  178691. cur2 += delta; /* form error * 3 */
  178692. errorptr[2] = (FSERROR) (bpreverr2 + cur2);
  178693. cur2 += delta; /* form error * 5 */
  178694. bpreverr2 = belowerr2 + cur2;
  178695. belowerr2 = bnexterr;
  178696. cur2 += delta; /* form error * 7 */
  178697. }
  178698. /* At this point curN contains the 7/16 error value to be propagated
  178699. * to the next pixel on the current line, and all the errors for the
  178700. * next line have been shifted over. We are therefore ready to move on.
  178701. */
  178702. inptr += dir3; /* Advance pixel pointers to next column */
  178703. outptr += dir;
  178704. errorptr += dir3; /* advance errorptr to current column */
  178705. }
  178706. /* Post-loop cleanup: we must unload the final error values into the
  178707. * final fserrors[] entry. Note we need not unload belowerrN because
  178708. * it is for the dummy column before or after the actual array.
  178709. */
  178710. errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */
  178711. errorptr[1] = (FSERROR) bpreverr1;
  178712. errorptr[2] = (FSERROR) bpreverr2;
  178713. }
  178714. }
  178715. /*
  178716. * Initialize the error-limiting transfer function (lookup table).
  178717. * The raw F-S error computation can potentially compute error values of up to
  178718. * +- MAXJSAMPLE. But we want the maximum correction applied to a pixel to be
  178719. * much less, otherwise obviously wrong pixels will be created. (Typical
  178720. * effects include weird fringes at color-area boundaries, isolated bright
  178721. * pixels in a dark area, etc.) The standard advice for avoiding this problem
  178722. * is to ensure that the "corners" of the color cube are allocated as output
  178723. * colors; then repeated errors in the same direction cannot cause cascading
  178724. * error buildup. However, that only prevents the error from getting
  178725. * completely out of hand; Aaron Giles reports that error limiting improves
  178726. * the results even with corner colors allocated.
  178727. * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
  178728. * well, but the smoother transfer function used below is even better. Thanks
  178729. * to Aaron Giles for this idea.
  178730. */
  178731. LOCAL(void)
  178732. init_error_limit (j_decompress_ptr cinfo)
  178733. /* Allocate and fill in the error_limiter table */
  178734. {
  178735. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178736. int * table;
  178737. int in, out;
  178738. table = (int *) (*cinfo->mem->alloc_small)
  178739. ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE*2+1) * SIZEOF(int));
  178740. table += MAXJSAMPLE; /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
  178741. cquantize->error_limiter = table;
  178742. #define STEPSIZE ((MAXJSAMPLE+1)/16)
  178743. /* Map errors 1:1 up to +- MAXJSAMPLE/16 */
  178744. out = 0;
  178745. for (in = 0; in < STEPSIZE; in++, out++) {
  178746. table[in] = out; table[-in] = -out;
  178747. }
  178748. /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
  178749. for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) {
  178750. table[in] = out; table[-in] = -out;
  178751. }
  178752. /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
  178753. for (; in <= MAXJSAMPLE; in++) {
  178754. table[in] = out; table[-in] = -out;
  178755. }
  178756. #undef STEPSIZE
  178757. }
  178758. /*
  178759. * Finish up at the end of each pass.
  178760. */
  178761. METHODDEF(void)
  178762. finish_pass1 (j_decompress_ptr cinfo)
  178763. {
  178764. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178765. /* Select the representative colors and fill in cinfo->colormap */
  178766. cinfo->colormap = cquantize->sv_colormap;
  178767. select_colors(cinfo, cquantize->desired);
  178768. /* Force next pass to zero the color index table */
  178769. cquantize->needs_zeroed = TRUE;
  178770. }
  178771. METHODDEF(void)
  178772. finish_pass2 (j_decompress_ptr)
  178773. {
  178774. /* no work */
  178775. }
  178776. /*
  178777. * Initialize for each processing pass.
  178778. */
  178779. METHODDEF(void)
  178780. start_pass_2_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
  178781. {
  178782. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178783. hist3d histogram = cquantize->histogram;
  178784. int i;
  178785. /* Only F-S dithering or no dithering is supported. */
  178786. /* If user asks for ordered dither, give him F-S. */
  178787. if (cinfo->dither_mode != JDITHER_NONE)
  178788. cinfo->dither_mode = JDITHER_FS;
  178789. if (is_pre_scan) {
  178790. /* Set up method pointers */
  178791. cquantize->pub.color_quantize = prescan_quantize;
  178792. cquantize->pub.finish_pass = finish_pass1;
  178793. cquantize->needs_zeroed = TRUE; /* Always zero histogram */
  178794. } else {
  178795. /* Set up method pointers */
  178796. if (cinfo->dither_mode == JDITHER_FS)
  178797. cquantize->pub.color_quantize = pass2_fs_dither;
  178798. else
  178799. cquantize->pub.color_quantize = pass2_no_dither;
  178800. cquantize->pub.finish_pass = finish_pass2;
  178801. /* Make sure color count is acceptable */
  178802. i = cinfo->actual_number_of_colors;
  178803. if (i < 1)
  178804. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 1);
  178805. if (i > MAXNUMCOLORS)
  178806. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  178807. if (cinfo->dither_mode == JDITHER_FS) {
  178808. size_t arraysize = (size_t) ((cinfo->output_width + 2) *
  178809. (3 * SIZEOF(FSERROR)));
  178810. /* Allocate Floyd-Steinberg workspace if we didn't already. */
  178811. if (cquantize->fserrors == NULL)
  178812. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  178813. ((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  178814. /* Initialize the propagated errors to zero. */
  178815. jzero_far((void FAR *) cquantize->fserrors, arraysize);
  178816. /* Make the error-limit table if we didn't already. */
  178817. if (cquantize->error_limiter == NULL)
  178818. init_error_limit(cinfo);
  178819. cquantize->on_odd_row = FALSE;
  178820. }
  178821. }
  178822. /* Zero the histogram or inverse color map, if necessary */
  178823. if (cquantize->needs_zeroed) {
  178824. for (i = 0; i < HIST_C0_ELEMS; i++) {
  178825. jzero_far((void FAR *) histogram[i],
  178826. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  178827. }
  178828. cquantize->needs_zeroed = FALSE;
  178829. }
  178830. }
  178831. /*
  178832. * Switch to a new external colormap between output passes.
  178833. */
  178834. METHODDEF(void)
  178835. new_color_map_2_quant (j_decompress_ptr cinfo)
  178836. {
  178837. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178838. /* Reset the inverse color map */
  178839. cquantize->needs_zeroed = TRUE;
  178840. }
  178841. /*
  178842. * Module initialization routine for 2-pass color quantization.
  178843. */
  178844. GLOBAL(void)
  178845. jinit_2pass_quantizer (j_decompress_ptr cinfo)
  178846. {
  178847. my_cquantize_ptr2 cquantize;
  178848. int i;
  178849. cquantize = (my_cquantize_ptr2)
  178850. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178851. SIZEOF(my_cquantizer2));
  178852. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  178853. cquantize->pub.start_pass = start_pass_2_quant;
  178854. cquantize->pub.new_color_map = new_color_map_2_quant;
  178855. cquantize->fserrors = NULL; /* flag optional arrays not allocated */
  178856. cquantize->error_limiter = NULL;
  178857. /* Make sure jdmaster didn't give me a case I can't handle */
  178858. if (cinfo->out_color_components != 3)
  178859. ERREXIT(cinfo, JERR_NOTIMPL);
  178860. /* Allocate the histogram/inverse colormap storage */
  178861. cquantize->histogram = (hist3d) (*cinfo->mem->alloc_small)
  178862. ((j_common_ptr) cinfo, JPOOL_IMAGE, HIST_C0_ELEMS * SIZEOF(hist2d));
  178863. for (i = 0; i < HIST_C0_ELEMS; i++) {
  178864. cquantize->histogram[i] = (hist2d) (*cinfo->mem->alloc_large)
  178865. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178866. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  178867. }
  178868. cquantize->needs_zeroed = TRUE; /* histogram is garbage now */
  178869. /* Allocate storage for the completed colormap, if required.
  178870. * We do this now since it is FAR storage and may affect
  178871. * the memory manager's space calculations.
  178872. */
  178873. if (cinfo->enable_2pass_quant) {
  178874. /* Make sure color count is acceptable */
  178875. int desired = cinfo->desired_number_of_colors;
  178876. /* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */
  178877. if (desired < 8)
  178878. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 8);
  178879. /* Make sure colormap indexes can be represented by JSAMPLEs */
  178880. if (desired > MAXNUMCOLORS)
  178881. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  178882. cquantize->sv_colormap = (*cinfo->mem->alloc_sarray)
  178883. ((j_common_ptr) cinfo,JPOOL_IMAGE, (JDIMENSION) desired, (JDIMENSION) 3);
  178884. cquantize->desired = desired;
  178885. } else
  178886. cquantize->sv_colormap = NULL;
  178887. /* Only F-S dithering or no dithering is supported. */
  178888. /* If user asks for ordered dither, give him F-S. */
  178889. if (cinfo->dither_mode != JDITHER_NONE)
  178890. cinfo->dither_mode = JDITHER_FS;
  178891. /* Allocate Floyd-Steinberg workspace if necessary.
  178892. * This isn't really needed until pass 2, but again it is FAR storage.
  178893. * Although we will cope with a later change in dither_mode,
  178894. * we do not promise to honor max_memory_to_use if dither_mode changes.
  178895. */
  178896. if (cinfo->dither_mode == JDITHER_FS) {
  178897. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  178898. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178899. (size_t) ((cinfo->output_width + 2) * (3 * SIZEOF(FSERROR))));
  178900. /* Might as well create the error-limiting table too. */
  178901. init_error_limit(cinfo);
  178902. }
  178903. }
  178904. #endif /* QUANT_2PASS_SUPPORTED */
  178905. /*** End of inlined file: jquant2.c ***/
  178906. /*** Start of inlined file: jutils.c ***/
  178907. #define JPEG_INTERNALS
  178908. /*
  178909. * jpeg_zigzag_order[i] is the zigzag-order position of the i'th element
  178910. * of a DCT block read in natural order (left to right, top to bottom).
  178911. */
  178912. #if 0 /* This table is not actually needed in v6a */
  178913. const int jpeg_zigzag_order[DCTSIZE2] = {
  178914. 0, 1, 5, 6, 14, 15, 27, 28,
  178915. 2, 4, 7, 13, 16, 26, 29, 42,
  178916. 3, 8, 12, 17, 25, 30, 41, 43,
  178917. 9, 11, 18, 24, 31, 40, 44, 53,
  178918. 10, 19, 23, 32, 39, 45, 52, 54,
  178919. 20, 22, 33, 38, 46, 51, 55, 60,
  178920. 21, 34, 37, 47, 50, 56, 59, 61,
  178921. 35, 36, 48, 49, 57, 58, 62, 63
  178922. };
  178923. #endif
  178924. /*
  178925. * jpeg_natural_order[i] is the natural-order position of the i'th element
  178926. * of zigzag order.
  178927. *
  178928. * When reading corrupted data, the Huffman decoders could attempt
  178929. * to reference an entry beyond the end of this array (if the decoded
  178930. * zero run length reaches past the end of the block). To prevent
  178931. * wild stores without adding an inner-loop test, we put some extra
  178932. * "63"s after the real entries. This will cause the extra coefficient
  178933. * to be stored in location 63 of the block, not somewhere random.
  178934. * The worst case would be a run-length of 15, which means we need 16
  178935. * fake entries.
  178936. */
  178937. const int jpeg_natural_order[DCTSIZE2+16] = {
  178938. 0, 1, 8, 16, 9, 2, 3, 10,
  178939. 17, 24, 32, 25, 18, 11, 4, 5,
  178940. 12, 19, 26, 33, 40, 48, 41, 34,
  178941. 27, 20, 13, 6, 7, 14, 21, 28,
  178942. 35, 42, 49, 56, 57, 50, 43, 36,
  178943. 29, 22, 15, 23, 30, 37, 44, 51,
  178944. 58, 59, 52, 45, 38, 31, 39, 46,
  178945. 53, 60, 61, 54, 47, 55, 62, 63,
  178946. 63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */
  178947. 63, 63, 63, 63, 63, 63, 63, 63
  178948. };
  178949. /*
  178950. * Arithmetic utilities
  178951. */
  178952. GLOBAL(long)
  178953. jdiv_round_up (long a, long b)
  178954. /* Compute a/b rounded up to next integer, ie, ceil(a/b) */
  178955. /* Assumes a >= 0, b > 0 */
  178956. {
  178957. return (a + b - 1L) / b;
  178958. }
  178959. GLOBAL(long)
  178960. jround_up (long a, long b)
  178961. /* Compute a rounded up to next multiple of b, ie, ceil(a/b)*b */
  178962. /* Assumes a >= 0, b > 0 */
  178963. {
  178964. a += b - 1L;
  178965. return a - (a % b);
  178966. }
  178967. /* On normal machines we can apply MEMCOPY() and MEMZERO() to sample arrays
  178968. * and coefficient-block arrays. This won't work on 80x86 because the arrays
  178969. * are FAR and we're assuming a small-pointer memory model. However, some
  178970. * DOS compilers provide far-pointer versions of memcpy() and memset() even
  178971. * in the small-model libraries. These will be used if USE_FMEM is defined.
  178972. * Otherwise, the routines below do it the hard way. (The performance cost
  178973. * is not all that great, because these routines aren't very heavily used.)
  178974. */
  178975. #ifndef NEED_FAR_POINTERS /* normal case, same as regular macros */
  178976. #define FMEMCOPY(dest,src,size) MEMCOPY(dest,src,size)
  178977. #define FMEMZERO(target,size) MEMZERO(target,size)
  178978. #else /* 80x86 case, define if we can */
  178979. #ifdef USE_FMEM
  178980. #define FMEMCOPY(dest,src,size) _fmemcpy((void FAR *)(dest), (const void FAR *)(src), (size_t)(size))
  178981. #define FMEMZERO(target,size) _fmemset((void FAR *)(target), 0, (size_t)(size))
  178982. #endif
  178983. #endif
  178984. GLOBAL(void)
  178985. jcopy_sample_rows (JSAMPARRAY input_array, int source_row,
  178986. JSAMPARRAY output_array, int dest_row,
  178987. int num_rows, JDIMENSION num_cols)
  178988. /* Copy some rows of samples from one place to another.
  178989. * num_rows rows are copied from input_array[source_row++]
  178990. * to output_array[dest_row++]; these areas may overlap for duplication.
  178991. * The source and destination arrays must be at least as wide as num_cols.
  178992. */
  178993. {
  178994. register JSAMPROW inptr, outptr;
  178995. #ifdef FMEMCOPY
  178996. register size_t count = (size_t) (num_cols * SIZEOF(JSAMPLE));
  178997. #else
  178998. register JDIMENSION count;
  178999. #endif
  179000. register int row;
  179001. input_array += source_row;
  179002. output_array += dest_row;
  179003. for (row = num_rows; row > 0; row--) {
  179004. inptr = *input_array++;
  179005. outptr = *output_array++;
  179006. #ifdef FMEMCOPY
  179007. FMEMCOPY(outptr, inptr, count);
  179008. #else
  179009. for (count = num_cols; count > 0; count--)
  179010. *outptr++ = *inptr++; /* needn't bother with GETJSAMPLE() here */
  179011. #endif
  179012. }
  179013. }
  179014. GLOBAL(void)
  179015. jcopy_block_row (JBLOCKROW input_row, JBLOCKROW output_row,
  179016. JDIMENSION num_blocks)
  179017. /* Copy a row of coefficient blocks from one place to another. */
  179018. {
  179019. #ifdef FMEMCOPY
  179020. FMEMCOPY(output_row, input_row, num_blocks * (DCTSIZE2 * SIZEOF(JCOEF)));
  179021. #else
  179022. register JCOEFPTR inptr, outptr;
  179023. register long count;
  179024. inptr = (JCOEFPTR) input_row;
  179025. outptr = (JCOEFPTR) output_row;
  179026. for (count = (long) num_blocks * DCTSIZE2; count > 0; count--) {
  179027. *outptr++ = *inptr++;
  179028. }
  179029. #endif
  179030. }
  179031. GLOBAL(void)
  179032. jzero_far (void FAR * target, size_t bytestozero)
  179033. /* Zero out a chunk of FAR memory. */
  179034. /* This might be sample-array data, block-array data, or alloc_large data. */
  179035. {
  179036. #ifdef FMEMZERO
  179037. FMEMZERO(target, bytestozero);
  179038. #else
  179039. register char FAR * ptr = (char FAR *) target;
  179040. register size_t count;
  179041. for (count = bytestozero; count > 0; count--) {
  179042. *ptr++ = 0;
  179043. }
  179044. #endif
  179045. }
  179046. /*** End of inlined file: jutils.c ***/
  179047. /*** Start of inlined file: transupp.c ***/
  179048. /* Although this file really shouldn't have access to the library internals,
  179049. * it's helpful to let it call jround_up() and jcopy_block_row().
  179050. */
  179051. #define JPEG_INTERNALS
  179052. /*** Start of inlined file: transupp.h ***/
  179053. /* If you happen not to want the image transform support, disable it here */
  179054. #ifndef TRANSFORMS_SUPPORTED
  179055. #define TRANSFORMS_SUPPORTED 1 /* 0 disables transform code */
  179056. #endif
  179057. /* Short forms of external names for systems with brain-damaged linkers. */
  179058. #ifdef NEED_SHORT_EXTERNAL_NAMES
  179059. #define jtransform_request_workspace jTrRequest
  179060. #define jtransform_adjust_parameters jTrAdjust
  179061. #define jtransform_execute_transformation jTrExec
  179062. #define jcopy_markers_setup jCMrkSetup
  179063. #define jcopy_markers_execute jCMrkExec
  179064. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  179065. /*
  179066. * Codes for supported types of image transformations.
  179067. */
  179068. typedef enum {
  179069. JXFORM_NONE, /* no transformation */
  179070. JXFORM_FLIP_H, /* horizontal flip */
  179071. JXFORM_FLIP_V, /* vertical flip */
  179072. JXFORM_TRANSPOSE, /* transpose across UL-to-LR axis */
  179073. JXFORM_TRANSVERSE, /* transpose across UR-to-LL axis */
  179074. JXFORM_ROT_90, /* 90-degree clockwise rotation */
  179075. JXFORM_ROT_180, /* 180-degree rotation */
  179076. JXFORM_ROT_270 /* 270-degree clockwise (or 90 ccw) */
  179077. } JXFORM_CODE;
  179078. /*
  179079. * Although rotating and flipping data expressed as DCT coefficients is not
  179080. * hard, there is an asymmetry in the JPEG format specification for images
  179081. * whose dimensions aren't multiples of the iMCU size. The right and bottom
  179082. * image edges are padded out to the next iMCU boundary with junk data; but
  179083. * no padding is possible at the top and left edges. If we were to flip
  179084. * the whole image including the pad data, then pad garbage would become
  179085. * visible at the top and/or left, and real pixels would disappear into the
  179086. * pad margins --- perhaps permanently, since encoders & decoders may not
  179087. * bother to preserve DCT blocks that appear to be completely outside the
  179088. * nominal image area. So, we have to exclude any partial iMCUs from the
  179089. * basic transformation.
  179090. *
  179091. * Transpose is the only transformation that can handle partial iMCUs at the
  179092. * right and bottom edges completely cleanly. flip_h can flip partial iMCUs
  179093. * at the bottom, but leaves any partial iMCUs at the right edge untouched.
  179094. * Similarly flip_v leaves any partial iMCUs at the bottom edge untouched.
  179095. * The other transforms are defined as combinations of these basic transforms
  179096. * and process edge blocks in a way that preserves the equivalence.
  179097. *
  179098. * The "trim" option causes untransformable partial iMCUs to be dropped;
  179099. * this is not strictly lossless, but it usually gives the best-looking
  179100. * result for odd-size images. Note that when this option is active,
  179101. * the expected mathematical equivalences between the transforms may not hold.
  179102. * (For example, -rot 270 -trim trims only the bottom edge, but -rot 90 -trim
  179103. * followed by -rot 180 -trim trims both edges.)
  179104. *
  179105. * We also offer a "force to grayscale" option, which simply discards the
  179106. * chrominance channels of a YCbCr image. This is lossless in the sense that
  179107. * the luminance channel is preserved exactly. It's not the same kind of
  179108. * thing as the rotate/flip transformations, but it's convenient to handle it
  179109. * as part of this package, mainly because the transformation routines have to
  179110. * be aware of the option to know how many components to work on.
  179111. */
  179112. typedef struct {
  179113. /* Options: set by caller */
  179114. JXFORM_CODE transform; /* image transform operator */
  179115. boolean trim; /* if TRUE, trim partial MCUs as needed */
  179116. boolean force_grayscale; /* if TRUE, convert color image to grayscale */
  179117. /* Internal workspace: caller should not touch these */
  179118. int num_components; /* # of components in workspace */
  179119. jvirt_barray_ptr * workspace_coef_arrays; /* workspace for transformations */
  179120. } jpeg_transform_info;
  179121. #if TRANSFORMS_SUPPORTED
  179122. /* Request any required workspace */
  179123. EXTERN(void) jtransform_request_workspace
  179124. JPP((j_decompress_ptr srcinfo, jpeg_transform_info *info));
  179125. /* Adjust output image parameters */
  179126. EXTERN(jvirt_barray_ptr *) jtransform_adjust_parameters
  179127. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179128. jvirt_barray_ptr *src_coef_arrays,
  179129. jpeg_transform_info *info));
  179130. /* Execute the actual transformation, if any */
  179131. EXTERN(void) jtransform_execute_transformation
  179132. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179133. jvirt_barray_ptr *src_coef_arrays,
  179134. jpeg_transform_info *info));
  179135. #endif /* TRANSFORMS_SUPPORTED */
  179136. /*
  179137. * Support for copying optional markers from source to destination file.
  179138. */
  179139. typedef enum {
  179140. JCOPYOPT_NONE, /* copy no optional markers */
  179141. JCOPYOPT_COMMENTS, /* copy only comment (COM) markers */
  179142. JCOPYOPT_ALL /* copy all optional markers */
  179143. } JCOPY_OPTION;
  179144. #define JCOPYOPT_DEFAULT JCOPYOPT_COMMENTS /* recommended default */
  179145. /* Setup decompression object to save desired markers in memory */
  179146. EXTERN(void) jcopy_markers_setup
  179147. JPP((j_decompress_ptr srcinfo, JCOPY_OPTION option));
  179148. /* Copy markers saved in the given source object to the destination object */
  179149. EXTERN(void) jcopy_markers_execute
  179150. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179151. JCOPY_OPTION option));
  179152. /*** End of inlined file: transupp.h ***/
  179153. /* My own external interface */
  179154. #if TRANSFORMS_SUPPORTED
  179155. /*
  179156. * Lossless image transformation routines. These routines work on DCT
  179157. * coefficient arrays and thus do not require any lossy decompression
  179158. * or recompression of the image.
  179159. * Thanks to Guido Vollbeding for the initial design and code of this feature.
  179160. *
  179161. * Horizontal flipping is done in-place, using a single top-to-bottom
  179162. * pass through the virtual source array. It will thus be much the
  179163. * fastest option for images larger than main memory.
  179164. *
  179165. * The other routines require a set of destination virtual arrays, so they
  179166. * need twice as much memory as jpegtran normally does. The destination
  179167. * arrays are always written in normal scan order (top to bottom) because
  179168. * the virtual array manager expects this. The source arrays will be scanned
  179169. * in the corresponding order, which means multiple passes through the source
  179170. * arrays for most of the transforms. That could result in much thrashing
  179171. * if the image is larger than main memory.
  179172. *
  179173. * Some notes about the operating environment of the individual transform
  179174. * routines:
  179175. * 1. Both the source and destination virtual arrays are allocated from the
  179176. * source JPEG object, and therefore should be manipulated by calling the
  179177. * source's memory manager.
  179178. * 2. The destination's component count should be used. It may be smaller
  179179. * than the source's when forcing to grayscale.
  179180. * 3. Likewise the destination's sampling factors should be used. When
  179181. * forcing to grayscale the destination's sampling factors will be all 1,
  179182. * and we may as well take that as the effective iMCU size.
  179183. * 4. When "trim" is in effect, the destination's dimensions will be the
  179184. * trimmed values but the source's will be untrimmed.
  179185. * 5. All the routines assume that the source and destination buffers are
  179186. * padded out to a full iMCU boundary. This is true, although for the
  179187. * source buffer it is an undocumented property of jdcoefct.c.
  179188. * Notes 2,3,4 boil down to this: generally we should use the destination's
  179189. * dimensions and ignore the source's.
  179190. */
  179191. LOCAL(void)
  179192. do_flip_h (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179193. jvirt_barray_ptr *src_coef_arrays)
  179194. /* Horizontal flip; done in-place, so no separate dest array is required */
  179195. {
  179196. JDIMENSION MCU_cols, comp_width, blk_x, blk_y;
  179197. int ci, k, offset_y;
  179198. JBLOCKARRAY buffer;
  179199. JCOEFPTR ptr1, ptr2;
  179200. JCOEF temp1, temp2;
  179201. jpeg_component_info *compptr;
  179202. /* Horizontal mirroring of DCT blocks is accomplished by swapping
  179203. * pairs of blocks in-place. Within a DCT block, we perform horizontal
  179204. * mirroring by changing the signs of odd-numbered columns.
  179205. * Partial iMCUs at the right edge are left untouched.
  179206. */
  179207. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179208. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179209. compptr = dstinfo->comp_info + ci;
  179210. comp_width = MCU_cols * compptr->h_samp_factor;
  179211. for (blk_y = 0; blk_y < compptr->height_in_blocks;
  179212. blk_y += compptr->v_samp_factor) {
  179213. buffer = (*srcinfo->mem->access_virt_barray)
  179214. ((j_common_ptr) srcinfo, src_coef_arrays[ci], blk_y,
  179215. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179216. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179217. for (blk_x = 0; blk_x * 2 < comp_width; blk_x++) {
  179218. ptr1 = buffer[offset_y][blk_x];
  179219. ptr2 = buffer[offset_y][comp_width - blk_x - 1];
  179220. /* this unrolled loop doesn't need to know which row it's on... */
  179221. for (k = 0; k < DCTSIZE2; k += 2) {
  179222. temp1 = *ptr1; /* swap even column */
  179223. temp2 = *ptr2;
  179224. *ptr1++ = temp2;
  179225. *ptr2++ = temp1;
  179226. temp1 = *ptr1; /* swap odd column with sign change */
  179227. temp2 = *ptr2;
  179228. *ptr1++ = -temp2;
  179229. *ptr2++ = -temp1;
  179230. }
  179231. }
  179232. }
  179233. }
  179234. }
  179235. }
  179236. LOCAL(void)
  179237. do_flip_v (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179238. jvirt_barray_ptr *src_coef_arrays,
  179239. jvirt_barray_ptr *dst_coef_arrays)
  179240. /* Vertical flip */
  179241. {
  179242. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  179243. int ci, i, j, offset_y;
  179244. JBLOCKARRAY src_buffer, dst_buffer;
  179245. JBLOCKROW src_row_ptr, dst_row_ptr;
  179246. JCOEFPTR src_ptr, dst_ptr;
  179247. jpeg_component_info *compptr;
  179248. /* We output into a separate array because we can't touch different
  179249. * rows of the source virtual array simultaneously. Otherwise, this
  179250. * is a pretty straightforward analog of horizontal flip.
  179251. * Within a DCT block, vertical mirroring is done by changing the signs
  179252. * of odd-numbered rows.
  179253. * Partial iMCUs at the bottom edge are copied verbatim.
  179254. */
  179255. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179256. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179257. compptr = dstinfo->comp_info + ci;
  179258. comp_height = MCU_rows * compptr->v_samp_factor;
  179259. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179260. dst_blk_y += compptr->v_samp_factor) {
  179261. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179262. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179263. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179264. if (dst_blk_y < comp_height) {
  179265. /* Row is within the mirrorable area. */
  179266. src_buffer = (*srcinfo->mem->access_virt_barray)
  179267. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  179268. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  179269. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179270. } else {
  179271. /* Bottom-edge blocks will be copied verbatim. */
  179272. src_buffer = (*srcinfo->mem->access_virt_barray)
  179273. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  179274. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179275. }
  179276. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179277. if (dst_blk_y < comp_height) {
  179278. /* Row is within the mirrorable area. */
  179279. dst_row_ptr = dst_buffer[offset_y];
  179280. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  179281. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179282. dst_blk_x++) {
  179283. dst_ptr = dst_row_ptr[dst_blk_x];
  179284. src_ptr = src_row_ptr[dst_blk_x];
  179285. for (i = 0; i < DCTSIZE; i += 2) {
  179286. /* copy even row */
  179287. for (j = 0; j < DCTSIZE; j++)
  179288. *dst_ptr++ = *src_ptr++;
  179289. /* copy odd row with sign change */
  179290. for (j = 0; j < DCTSIZE; j++)
  179291. *dst_ptr++ = - *src_ptr++;
  179292. }
  179293. }
  179294. } else {
  179295. /* Just copy row verbatim. */
  179296. jcopy_block_row(src_buffer[offset_y], dst_buffer[offset_y],
  179297. compptr->width_in_blocks);
  179298. }
  179299. }
  179300. }
  179301. }
  179302. }
  179303. LOCAL(void)
  179304. do_transpose (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179305. jvirt_barray_ptr *src_coef_arrays,
  179306. jvirt_barray_ptr *dst_coef_arrays)
  179307. /* Transpose source into destination */
  179308. {
  179309. JDIMENSION dst_blk_x, dst_blk_y;
  179310. int ci, i, j, offset_x, offset_y;
  179311. JBLOCKARRAY src_buffer, dst_buffer;
  179312. JCOEFPTR src_ptr, dst_ptr;
  179313. jpeg_component_info *compptr;
  179314. /* Transposing pixels within a block just requires transposing the
  179315. * DCT coefficients.
  179316. * Partial iMCUs at the edges require no special treatment; we simply
  179317. * process all the available DCT blocks for every component.
  179318. */
  179319. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179320. compptr = dstinfo->comp_info + ci;
  179321. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179322. dst_blk_y += compptr->v_samp_factor) {
  179323. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179324. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179325. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179326. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179327. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179328. dst_blk_x += compptr->h_samp_factor) {
  179329. src_buffer = (*srcinfo->mem->access_virt_barray)
  179330. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179331. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179332. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179333. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179334. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179335. for (i = 0; i < DCTSIZE; i++)
  179336. for (j = 0; j < DCTSIZE; j++)
  179337. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179338. }
  179339. }
  179340. }
  179341. }
  179342. }
  179343. }
  179344. LOCAL(void)
  179345. do_rot_90 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179346. jvirt_barray_ptr *src_coef_arrays,
  179347. jvirt_barray_ptr *dst_coef_arrays)
  179348. /* 90 degree rotation is equivalent to
  179349. * 1. Transposing the image;
  179350. * 2. Horizontal mirroring.
  179351. * These two steps are merged into a single processing routine.
  179352. */
  179353. {
  179354. JDIMENSION MCU_cols, comp_width, dst_blk_x, dst_blk_y;
  179355. int ci, i, j, offset_x, offset_y;
  179356. JBLOCKARRAY src_buffer, dst_buffer;
  179357. JCOEFPTR src_ptr, dst_ptr;
  179358. jpeg_component_info *compptr;
  179359. /* Because of the horizontal mirror step, we can't process partial iMCUs
  179360. * at the (output) right edge properly. They just get transposed and
  179361. * not mirrored.
  179362. */
  179363. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179364. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179365. compptr = dstinfo->comp_info + ci;
  179366. comp_width = MCU_cols * compptr->h_samp_factor;
  179367. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179368. dst_blk_y += compptr->v_samp_factor) {
  179369. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179370. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179371. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179372. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179373. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179374. dst_blk_x += compptr->h_samp_factor) {
  179375. src_buffer = (*srcinfo->mem->access_virt_barray)
  179376. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179377. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179378. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179379. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179380. if (dst_blk_x < comp_width) {
  179381. /* Block is within the mirrorable area. */
  179382. dst_ptr = dst_buffer[offset_y]
  179383. [comp_width - dst_blk_x - offset_x - 1];
  179384. for (i = 0; i < DCTSIZE; i++) {
  179385. for (j = 0; j < DCTSIZE; j++)
  179386. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179387. i++;
  179388. for (j = 0; j < DCTSIZE; j++)
  179389. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179390. }
  179391. } else {
  179392. /* Edge blocks are transposed but not mirrored. */
  179393. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179394. for (i = 0; i < DCTSIZE; i++)
  179395. for (j = 0; j < DCTSIZE; j++)
  179396. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179397. }
  179398. }
  179399. }
  179400. }
  179401. }
  179402. }
  179403. }
  179404. LOCAL(void)
  179405. do_rot_270 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179406. jvirt_barray_ptr *src_coef_arrays,
  179407. jvirt_barray_ptr *dst_coef_arrays)
  179408. /* 270 degree rotation is equivalent to
  179409. * 1. Horizontal mirroring;
  179410. * 2. Transposing the image.
  179411. * These two steps are merged into a single processing routine.
  179412. */
  179413. {
  179414. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  179415. int ci, i, j, offset_x, offset_y;
  179416. JBLOCKARRAY src_buffer, dst_buffer;
  179417. JCOEFPTR src_ptr, dst_ptr;
  179418. jpeg_component_info *compptr;
  179419. /* Because of the horizontal mirror step, we can't process partial iMCUs
  179420. * at the (output) bottom edge properly. They just get transposed and
  179421. * not mirrored.
  179422. */
  179423. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179424. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179425. compptr = dstinfo->comp_info + ci;
  179426. comp_height = MCU_rows * compptr->v_samp_factor;
  179427. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179428. dst_blk_y += compptr->v_samp_factor) {
  179429. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179430. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179431. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179432. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179433. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179434. dst_blk_x += compptr->h_samp_factor) {
  179435. src_buffer = (*srcinfo->mem->access_virt_barray)
  179436. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179437. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179438. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179439. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179440. if (dst_blk_y < comp_height) {
  179441. /* Block is within the mirrorable area. */
  179442. src_ptr = src_buffer[offset_x]
  179443. [comp_height - dst_blk_y - offset_y - 1];
  179444. for (i = 0; i < DCTSIZE; i++) {
  179445. for (j = 0; j < DCTSIZE; j++) {
  179446. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179447. j++;
  179448. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179449. }
  179450. }
  179451. } else {
  179452. /* Edge blocks are transposed but not mirrored. */
  179453. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179454. for (i = 0; i < DCTSIZE; i++)
  179455. for (j = 0; j < DCTSIZE; j++)
  179456. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179457. }
  179458. }
  179459. }
  179460. }
  179461. }
  179462. }
  179463. }
  179464. LOCAL(void)
  179465. do_rot_180 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179466. jvirt_barray_ptr *src_coef_arrays,
  179467. jvirt_barray_ptr *dst_coef_arrays)
  179468. /* 180 degree rotation is equivalent to
  179469. * 1. Vertical mirroring;
  179470. * 2. Horizontal mirroring.
  179471. * These two steps are merged into a single processing routine.
  179472. */
  179473. {
  179474. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  179475. int ci, i, j, offset_y;
  179476. JBLOCKARRAY src_buffer, dst_buffer;
  179477. JBLOCKROW src_row_ptr, dst_row_ptr;
  179478. JCOEFPTR src_ptr, dst_ptr;
  179479. jpeg_component_info *compptr;
  179480. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179481. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179482. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179483. compptr = dstinfo->comp_info + ci;
  179484. comp_width = MCU_cols * compptr->h_samp_factor;
  179485. comp_height = MCU_rows * compptr->v_samp_factor;
  179486. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179487. dst_blk_y += compptr->v_samp_factor) {
  179488. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179489. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179490. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179491. if (dst_blk_y < comp_height) {
  179492. /* Row is within the vertically mirrorable area. */
  179493. src_buffer = (*srcinfo->mem->access_virt_barray)
  179494. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  179495. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  179496. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179497. } else {
  179498. /* Bottom-edge rows are only mirrored horizontally. */
  179499. src_buffer = (*srcinfo->mem->access_virt_barray)
  179500. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  179501. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179502. }
  179503. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179504. if (dst_blk_y < comp_height) {
  179505. /* Row is within the mirrorable area. */
  179506. dst_row_ptr = dst_buffer[offset_y];
  179507. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  179508. /* Process the blocks that can be mirrored both ways. */
  179509. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  179510. dst_ptr = dst_row_ptr[dst_blk_x];
  179511. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  179512. for (i = 0; i < DCTSIZE; i += 2) {
  179513. /* For even row, negate every odd column. */
  179514. for (j = 0; j < DCTSIZE; j += 2) {
  179515. *dst_ptr++ = *src_ptr++;
  179516. *dst_ptr++ = - *src_ptr++;
  179517. }
  179518. /* For odd row, negate every even column. */
  179519. for (j = 0; j < DCTSIZE; j += 2) {
  179520. *dst_ptr++ = - *src_ptr++;
  179521. *dst_ptr++ = *src_ptr++;
  179522. }
  179523. }
  179524. }
  179525. /* Any remaining right-edge blocks are only mirrored vertically. */
  179526. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  179527. dst_ptr = dst_row_ptr[dst_blk_x];
  179528. src_ptr = src_row_ptr[dst_blk_x];
  179529. for (i = 0; i < DCTSIZE; i += 2) {
  179530. for (j = 0; j < DCTSIZE; j++)
  179531. *dst_ptr++ = *src_ptr++;
  179532. for (j = 0; j < DCTSIZE; j++)
  179533. *dst_ptr++ = - *src_ptr++;
  179534. }
  179535. }
  179536. } else {
  179537. /* Remaining rows are just mirrored horizontally. */
  179538. dst_row_ptr = dst_buffer[offset_y];
  179539. src_row_ptr = src_buffer[offset_y];
  179540. /* Process the blocks that can be mirrored. */
  179541. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  179542. dst_ptr = dst_row_ptr[dst_blk_x];
  179543. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  179544. for (i = 0; i < DCTSIZE2; i += 2) {
  179545. *dst_ptr++ = *src_ptr++;
  179546. *dst_ptr++ = - *src_ptr++;
  179547. }
  179548. }
  179549. /* Any remaining right-edge blocks are only copied. */
  179550. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  179551. dst_ptr = dst_row_ptr[dst_blk_x];
  179552. src_ptr = src_row_ptr[dst_blk_x];
  179553. for (i = 0; i < DCTSIZE2; i++)
  179554. *dst_ptr++ = *src_ptr++;
  179555. }
  179556. }
  179557. }
  179558. }
  179559. }
  179560. }
  179561. LOCAL(void)
  179562. do_transverse (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179563. jvirt_barray_ptr *src_coef_arrays,
  179564. jvirt_barray_ptr *dst_coef_arrays)
  179565. /* Transverse transpose is equivalent to
  179566. * 1. 180 degree rotation;
  179567. * 2. Transposition;
  179568. * or
  179569. * 1. Horizontal mirroring;
  179570. * 2. Transposition;
  179571. * 3. Horizontal mirroring.
  179572. * These steps are merged into a single processing routine.
  179573. */
  179574. {
  179575. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  179576. int ci, i, j, offset_x, offset_y;
  179577. JBLOCKARRAY src_buffer, dst_buffer;
  179578. JCOEFPTR src_ptr, dst_ptr;
  179579. jpeg_component_info *compptr;
  179580. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179581. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179582. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179583. compptr = dstinfo->comp_info + ci;
  179584. comp_width = MCU_cols * compptr->h_samp_factor;
  179585. comp_height = MCU_rows * compptr->v_samp_factor;
  179586. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179587. dst_blk_y += compptr->v_samp_factor) {
  179588. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179589. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179590. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179591. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179592. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179593. dst_blk_x += compptr->h_samp_factor) {
  179594. src_buffer = (*srcinfo->mem->access_virt_barray)
  179595. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179596. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179597. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179598. if (dst_blk_y < comp_height) {
  179599. src_ptr = src_buffer[offset_x]
  179600. [comp_height - dst_blk_y - offset_y - 1];
  179601. if (dst_blk_x < comp_width) {
  179602. /* Block is within the mirrorable area. */
  179603. dst_ptr = dst_buffer[offset_y]
  179604. [comp_width - dst_blk_x - offset_x - 1];
  179605. for (i = 0; i < DCTSIZE; i++) {
  179606. for (j = 0; j < DCTSIZE; j++) {
  179607. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179608. j++;
  179609. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179610. }
  179611. i++;
  179612. for (j = 0; j < DCTSIZE; j++) {
  179613. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179614. j++;
  179615. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179616. }
  179617. }
  179618. } else {
  179619. /* Right-edge blocks are mirrored in y only */
  179620. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179621. for (i = 0; i < DCTSIZE; i++) {
  179622. for (j = 0; j < DCTSIZE; j++) {
  179623. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179624. j++;
  179625. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179626. }
  179627. }
  179628. }
  179629. } else {
  179630. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179631. if (dst_blk_x < comp_width) {
  179632. /* Bottom-edge blocks are mirrored in x only */
  179633. dst_ptr = dst_buffer[offset_y]
  179634. [comp_width - dst_blk_x - offset_x - 1];
  179635. for (i = 0; i < DCTSIZE; i++) {
  179636. for (j = 0; j < DCTSIZE; j++)
  179637. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179638. i++;
  179639. for (j = 0; j < DCTSIZE; j++)
  179640. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179641. }
  179642. } else {
  179643. /* At lower right corner, just transpose, no mirroring */
  179644. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179645. for (i = 0; i < DCTSIZE; i++)
  179646. for (j = 0; j < DCTSIZE; j++)
  179647. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179648. }
  179649. }
  179650. }
  179651. }
  179652. }
  179653. }
  179654. }
  179655. }
  179656. /* Request any required workspace.
  179657. *
  179658. * We allocate the workspace virtual arrays from the source decompression
  179659. * object, so that all the arrays (both the original data and the workspace)
  179660. * will be taken into account while making memory management decisions.
  179661. * Hence, this routine must be called after jpeg_read_header (which reads
  179662. * the image dimensions) and before jpeg_read_coefficients (which realizes
  179663. * the source's virtual arrays).
  179664. */
  179665. GLOBAL(void)
  179666. jtransform_request_workspace (j_decompress_ptr srcinfo,
  179667. jpeg_transform_info *info)
  179668. {
  179669. jvirt_barray_ptr *coef_arrays = NULL;
  179670. jpeg_component_info *compptr;
  179671. int ci;
  179672. if (info->force_grayscale &&
  179673. srcinfo->jpeg_color_space == JCS_YCbCr &&
  179674. srcinfo->num_components == 3) {
  179675. /* We'll only process the first component */
  179676. info->num_components = 1;
  179677. } else {
  179678. /* Process all the components */
  179679. info->num_components = srcinfo->num_components;
  179680. }
  179681. switch (info->transform) {
  179682. case JXFORM_NONE:
  179683. case JXFORM_FLIP_H:
  179684. /* Don't need a workspace array */
  179685. break;
  179686. case JXFORM_FLIP_V:
  179687. case JXFORM_ROT_180:
  179688. /* Need workspace arrays having same dimensions as source image.
  179689. * Note that we allocate arrays padded out to the next iMCU boundary,
  179690. * so that transform routines need not worry about missing edge blocks.
  179691. */
  179692. coef_arrays = (jvirt_barray_ptr *)
  179693. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  179694. SIZEOF(jvirt_barray_ptr) * info->num_components);
  179695. for (ci = 0; ci < info->num_components; ci++) {
  179696. compptr = srcinfo->comp_info + ci;
  179697. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  179698. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  179699. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  179700. (long) compptr->h_samp_factor),
  179701. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  179702. (long) compptr->v_samp_factor),
  179703. (JDIMENSION) compptr->v_samp_factor);
  179704. }
  179705. break;
  179706. case JXFORM_TRANSPOSE:
  179707. case JXFORM_TRANSVERSE:
  179708. case JXFORM_ROT_90:
  179709. case JXFORM_ROT_270:
  179710. /* Need workspace arrays having transposed dimensions.
  179711. * Note that we allocate arrays padded out to the next iMCU boundary,
  179712. * so that transform routines need not worry about missing edge blocks.
  179713. */
  179714. coef_arrays = (jvirt_barray_ptr *)
  179715. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  179716. SIZEOF(jvirt_barray_ptr) * info->num_components);
  179717. for (ci = 0; ci < info->num_components; ci++) {
  179718. compptr = srcinfo->comp_info + ci;
  179719. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  179720. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  179721. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  179722. (long) compptr->v_samp_factor),
  179723. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  179724. (long) compptr->h_samp_factor),
  179725. (JDIMENSION) compptr->h_samp_factor);
  179726. }
  179727. break;
  179728. }
  179729. info->workspace_coef_arrays = coef_arrays;
  179730. }
  179731. /* Transpose destination image parameters */
  179732. LOCAL(void)
  179733. transpose_critical_parameters (j_compress_ptr dstinfo)
  179734. {
  179735. int tblno, i, j, ci, itemp;
  179736. jpeg_component_info *compptr;
  179737. JQUANT_TBL *qtblptr;
  179738. JDIMENSION dtemp;
  179739. UINT16 qtemp;
  179740. /* Transpose basic image dimensions */
  179741. dtemp = dstinfo->image_width;
  179742. dstinfo->image_width = dstinfo->image_height;
  179743. dstinfo->image_height = dtemp;
  179744. /* Transpose sampling factors */
  179745. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179746. compptr = dstinfo->comp_info + ci;
  179747. itemp = compptr->h_samp_factor;
  179748. compptr->h_samp_factor = compptr->v_samp_factor;
  179749. compptr->v_samp_factor = itemp;
  179750. }
  179751. /* Transpose quantization tables */
  179752. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  179753. qtblptr = dstinfo->quant_tbl_ptrs[tblno];
  179754. if (qtblptr != NULL) {
  179755. for (i = 0; i < DCTSIZE; i++) {
  179756. for (j = 0; j < i; j++) {
  179757. qtemp = qtblptr->quantval[i*DCTSIZE+j];
  179758. qtblptr->quantval[i*DCTSIZE+j] = qtblptr->quantval[j*DCTSIZE+i];
  179759. qtblptr->quantval[j*DCTSIZE+i] = qtemp;
  179760. }
  179761. }
  179762. }
  179763. }
  179764. }
  179765. /* Trim off any partial iMCUs on the indicated destination edge */
  179766. LOCAL(void)
  179767. trim_right_edge (j_compress_ptr dstinfo)
  179768. {
  179769. int ci, max_h_samp_factor;
  179770. JDIMENSION MCU_cols;
  179771. /* We have to compute max_h_samp_factor ourselves,
  179772. * because it hasn't been set yet in the destination
  179773. * (and we don't want to use the source's value).
  179774. */
  179775. max_h_samp_factor = 1;
  179776. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179777. int h_samp_factor = dstinfo->comp_info[ci].h_samp_factor;
  179778. max_h_samp_factor = MAX(max_h_samp_factor, h_samp_factor);
  179779. }
  179780. MCU_cols = dstinfo->image_width / (max_h_samp_factor * DCTSIZE);
  179781. if (MCU_cols > 0) /* can't trim to 0 pixels */
  179782. dstinfo->image_width = MCU_cols * (max_h_samp_factor * DCTSIZE);
  179783. }
  179784. LOCAL(void)
  179785. trim_bottom_edge (j_compress_ptr dstinfo)
  179786. {
  179787. int ci, max_v_samp_factor;
  179788. JDIMENSION MCU_rows;
  179789. /* We have to compute max_v_samp_factor ourselves,
  179790. * because it hasn't been set yet in the destination
  179791. * (and we don't want to use the source's value).
  179792. */
  179793. max_v_samp_factor = 1;
  179794. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179795. int v_samp_factor = dstinfo->comp_info[ci].v_samp_factor;
  179796. max_v_samp_factor = MAX(max_v_samp_factor, v_samp_factor);
  179797. }
  179798. MCU_rows = dstinfo->image_height / (max_v_samp_factor * DCTSIZE);
  179799. if (MCU_rows > 0) /* can't trim to 0 pixels */
  179800. dstinfo->image_height = MCU_rows * (max_v_samp_factor * DCTSIZE);
  179801. }
  179802. /* Adjust output image parameters as needed.
  179803. *
  179804. * This must be called after jpeg_copy_critical_parameters()
  179805. * and before jpeg_write_coefficients().
  179806. *
  179807. * The return value is the set of virtual coefficient arrays to be written
  179808. * (either the ones allocated by jtransform_request_workspace, or the
  179809. * original source data arrays). The caller will need to pass this value
  179810. * to jpeg_write_coefficients().
  179811. */
  179812. GLOBAL(jvirt_barray_ptr *)
  179813. jtransform_adjust_parameters (j_decompress_ptr,
  179814. j_compress_ptr dstinfo,
  179815. jvirt_barray_ptr *src_coef_arrays,
  179816. jpeg_transform_info *info)
  179817. {
  179818. /* If force-to-grayscale is requested, adjust destination parameters */
  179819. if (info->force_grayscale) {
  179820. /* We use jpeg_set_colorspace to make sure subsidiary settings get fixed
  179821. * properly. Among other things, the target h_samp_factor & v_samp_factor
  179822. * will get set to 1, which typically won't match the source.
  179823. * In fact we do this even if the source is already grayscale; that
  179824. * provides an easy way of coercing a grayscale JPEG with funny sampling
  179825. * factors to the customary 1,1. (Some decoders fail on other factors.)
  179826. */
  179827. if ((dstinfo->jpeg_color_space == JCS_YCbCr &&
  179828. dstinfo->num_components == 3) ||
  179829. (dstinfo->jpeg_color_space == JCS_GRAYSCALE &&
  179830. dstinfo->num_components == 1)) {
  179831. /* We have to preserve the source's quantization table number. */
  179832. int sv_quant_tbl_no = dstinfo->comp_info[0].quant_tbl_no;
  179833. jpeg_set_colorspace(dstinfo, JCS_GRAYSCALE);
  179834. dstinfo->comp_info[0].quant_tbl_no = sv_quant_tbl_no;
  179835. } else {
  179836. /* Sorry, can't do it */
  179837. ERREXIT(dstinfo, JERR_CONVERSION_NOTIMPL);
  179838. }
  179839. }
  179840. /* Correct the destination's image dimensions etc if necessary */
  179841. switch (info->transform) {
  179842. case JXFORM_NONE:
  179843. /* Nothing to do */
  179844. break;
  179845. case JXFORM_FLIP_H:
  179846. if (info->trim)
  179847. trim_right_edge(dstinfo);
  179848. break;
  179849. case JXFORM_FLIP_V:
  179850. if (info->trim)
  179851. trim_bottom_edge(dstinfo);
  179852. break;
  179853. case JXFORM_TRANSPOSE:
  179854. transpose_critical_parameters(dstinfo);
  179855. /* transpose does NOT have to trim anything */
  179856. break;
  179857. case JXFORM_TRANSVERSE:
  179858. transpose_critical_parameters(dstinfo);
  179859. if (info->trim) {
  179860. trim_right_edge(dstinfo);
  179861. trim_bottom_edge(dstinfo);
  179862. }
  179863. break;
  179864. case JXFORM_ROT_90:
  179865. transpose_critical_parameters(dstinfo);
  179866. if (info->trim)
  179867. trim_right_edge(dstinfo);
  179868. break;
  179869. case JXFORM_ROT_180:
  179870. if (info->trim) {
  179871. trim_right_edge(dstinfo);
  179872. trim_bottom_edge(dstinfo);
  179873. }
  179874. break;
  179875. case JXFORM_ROT_270:
  179876. transpose_critical_parameters(dstinfo);
  179877. if (info->trim)
  179878. trim_bottom_edge(dstinfo);
  179879. break;
  179880. }
  179881. /* Return the appropriate output data set */
  179882. if (info->workspace_coef_arrays != NULL)
  179883. return info->workspace_coef_arrays;
  179884. return src_coef_arrays;
  179885. }
  179886. /* Execute the actual transformation, if any.
  179887. *
  179888. * This must be called *after* jpeg_write_coefficients, because it depends
  179889. * on jpeg_write_coefficients to have computed subsidiary values such as
  179890. * the per-component width and height fields in the destination object.
  179891. *
  179892. * Note that some transformations will modify the source data arrays!
  179893. */
  179894. GLOBAL(void)
  179895. jtransform_execute_transformation (j_decompress_ptr srcinfo,
  179896. j_compress_ptr dstinfo,
  179897. jvirt_barray_ptr *src_coef_arrays,
  179898. jpeg_transform_info *info)
  179899. {
  179900. jvirt_barray_ptr *dst_coef_arrays = info->workspace_coef_arrays;
  179901. switch (info->transform) {
  179902. case JXFORM_NONE:
  179903. break;
  179904. case JXFORM_FLIP_H:
  179905. do_flip_h(srcinfo, dstinfo, src_coef_arrays);
  179906. break;
  179907. case JXFORM_FLIP_V:
  179908. do_flip_v(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179909. break;
  179910. case JXFORM_TRANSPOSE:
  179911. do_transpose(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179912. break;
  179913. case JXFORM_TRANSVERSE:
  179914. do_transverse(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179915. break;
  179916. case JXFORM_ROT_90:
  179917. do_rot_90(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179918. break;
  179919. case JXFORM_ROT_180:
  179920. do_rot_180(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179921. break;
  179922. case JXFORM_ROT_270:
  179923. do_rot_270(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179924. break;
  179925. }
  179926. }
  179927. #endif /* TRANSFORMS_SUPPORTED */
  179928. /* Setup decompression object to save desired markers in memory.
  179929. * This must be called before jpeg_read_header() to have the desired effect.
  179930. */
  179931. GLOBAL(void)
  179932. jcopy_markers_setup (j_decompress_ptr srcinfo, JCOPY_OPTION option)
  179933. {
  179934. #ifdef SAVE_MARKERS_SUPPORTED
  179935. int m;
  179936. /* Save comments except under NONE option */
  179937. if (option != JCOPYOPT_NONE) {
  179938. jpeg_save_markers(srcinfo, JPEG_COM, 0xFFFF);
  179939. }
  179940. /* Save all types of APPn markers iff ALL option */
  179941. if (option == JCOPYOPT_ALL) {
  179942. for (m = 0; m < 16; m++)
  179943. jpeg_save_markers(srcinfo, JPEG_APP0 + m, 0xFFFF);
  179944. }
  179945. #endif /* SAVE_MARKERS_SUPPORTED */
  179946. }
  179947. /* Copy markers saved in the given source object to the destination object.
  179948. * This should be called just after jpeg_start_compress() or
  179949. * jpeg_write_coefficients().
  179950. * Note that those routines will have written the SOI, and also the
  179951. * JFIF APP0 or Adobe APP14 markers if selected.
  179952. */
  179953. GLOBAL(void)
  179954. jcopy_markers_execute (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179955. JCOPY_OPTION)
  179956. {
  179957. jpeg_saved_marker_ptr marker;
  179958. /* In the current implementation, we don't actually need to examine the
  179959. * option flag here; we just copy everything that got saved.
  179960. * But to avoid confusion, we do not output JFIF and Adobe APP14 markers
  179961. * if the encoder library already wrote one.
  179962. */
  179963. for (marker = srcinfo->marker_list; marker != NULL; marker = marker->next) {
  179964. if (dstinfo->write_JFIF_header &&
  179965. marker->marker == JPEG_APP0 &&
  179966. marker->data_length >= 5 &&
  179967. GETJOCTET(marker->data[0]) == 0x4A &&
  179968. GETJOCTET(marker->data[1]) == 0x46 &&
  179969. GETJOCTET(marker->data[2]) == 0x49 &&
  179970. GETJOCTET(marker->data[3]) == 0x46 &&
  179971. GETJOCTET(marker->data[4]) == 0)
  179972. continue; /* reject duplicate JFIF */
  179973. if (dstinfo->write_Adobe_marker &&
  179974. marker->marker == JPEG_APP0+14 &&
  179975. marker->data_length >= 5 &&
  179976. GETJOCTET(marker->data[0]) == 0x41 &&
  179977. GETJOCTET(marker->data[1]) == 0x64 &&
  179978. GETJOCTET(marker->data[2]) == 0x6F &&
  179979. GETJOCTET(marker->data[3]) == 0x62 &&
  179980. GETJOCTET(marker->data[4]) == 0x65)
  179981. continue; /* reject duplicate Adobe */
  179982. #ifdef NEED_FAR_POINTERS
  179983. /* We could use jpeg_write_marker if the data weren't FAR... */
  179984. {
  179985. unsigned int i;
  179986. jpeg_write_m_header(dstinfo, marker->marker, marker->data_length);
  179987. for (i = 0; i < marker->data_length; i++)
  179988. jpeg_write_m_byte(dstinfo, marker->data[i]);
  179989. }
  179990. #else
  179991. jpeg_write_marker(dstinfo, marker->marker,
  179992. marker->data, marker->data_length);
  179993. #endif
  179994. }
  179995. }
  179996. /*** End of inlined file: transupp.c ***/
  179997. #else
  179998. #define JPEG_INTERNALS
  179999. #undef FAR
  180000. #include <jpeglib.h>
  180001. #endif
  180002. }
  180003. #undef max
  180004. #undef min
  180005. #if JUCE_MSVC
  180006. #pragma warning (pop)
  180007. #endif
  180008. BEGIN_JUCE_NAMESPACE
  180009. namespace JPEGHelpers
  180010. {
  180011. using namespace jpeglibNamespace;
  180012. #if ! JUCE_MSVC
  180013. using jpeglibNamespace::boolean;
  180014. #endif
  180015. struct JPEGDecodingFailure {};
  180016. static void fatalErrorHandler (j_common_ptr)
  180017. {
  180018. throw JPEGDecodingFailure();
  180019. }
  180020. static void silentErrorCallback1 (j_common_ptr) {}
  180021. static void silentErrorCallback2 (j_common_ptr, int) {}
  180022. static void silentErrorCallback3 (j_common_ptr, char*) {}
  180023. static void setupSilentErrorHandler (struct jpeg_error_mgr& err)
  180024. {
  180025. zerostruct (err);
  180026. err.error_exit = fatalErrorHandler;
  180027. err.emit_message = silentErrorCallback2;
  180028. err.output_message = silentErrorCallback1;
  180029. err.format_message = silentErrorCallback3;
  180030. err.reset_error_mgr = silentErrorCallback1;
  180031. }
  180032. static void dummyCallback1 (j_decompress_ptr)
  180033. {
  180034. }
  180035. static void jpegSkip (j_decompress_ptr decompStruct, long num)
  180036. {
  180037. decompStruct->src->next_input_byte += num;
  180038. num = jmin (num, (long) decompStruct->src->bytes_in_buffer);
  180039. decompStruct->src->bytes_in_buffer -= num;
  180040. }
  180041. static boolean jpegFill (j_decompress_ptr)
  180042. {
  180043. return 0;
  180044. }
  180045. static const int jpegBufferSize = 512;
  180046. struct JuceJpegDest : public jpeg_destination_mgr
  180047. {
  180048. OutputStream* output;
  180049. char* buffer;
  180050. };
  180051. static void jpegWriteInit (j_compress_ptr)
  180052. {
  180053. }
  180054. static void jpegWriteTerminate (j_compress_ptr cinfo)
  180055. {
  180056. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  180057. const size_t numToWrite = jpegBufferSize - dest->free_in_buffer;
  180058. dest->output->write (dest->buffer, (int) numToWrite);
  180059. }
  180060. static boolean jpegWriteFlush (j_compress_ptr cinfo)
  180061. {
  180062. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  180063. const int numToWrite = jpegBufferSize;
  180064. dest->next_output_byte = reinterpret_cast <JOCTET*> (dest->buffer);
  180065. dest->free_in_buffer = jpegBufferSize;
  180066. return dest->output->write (dest->buffer, numToWrite);
  180067. }
  180068. }
  180069. JPEGImageFormat::JPEGImageFormat()
  180070. : quality (-1.0f)
  180071. {
  180072. }
  180073. JPEGImageFormat::~JPEGImageFormat() {}
  180074. void JPEGImageFormat::setQuality (const float newQuality)
  180075. {
  180076. quality = newQuality;
  180077. }
  180078. const String JPEGImageFormat::getFormatName()
  180079. {
  180080. return "JPEG";
  180081. }
  180082. bool JPEGImageFormat::canUnderstand (InputStream& in)
  180083. {
  180084. const int bytesNeeded = 10;
  180085. uint8 header [bytesNeeded];
  180086. if (in.read (header, bytesNeeded) == bytesNeeded)
  180087. {
  180088. return header[0] == 0xff
  180089. && header[1] == 0xd8
  180090. && header[2] == 0xff
  180091. && (header[3] == 0xe0 || header[3] == 0xe1);
  180092. }
  180093. return false;
  180094. }
  180095. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  180096. const Image juce_loadWithCoreImage (InputStream& input);
  180097. #endif
  180098. const Image JPEGImageFormat::decodeImage (InputStream& in)
  180099. {
  180100. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  180101. return juce_loadWithCoreImage (in);
  180102. #else
  180103. using namespace jpeglibNamespace;
  180104. using namespace JPEGHelpers;
  180105. MemoryOutputStream mb;
  180106. mb.writeFromInputStream (in, -1);
  180107. Image image;
  180108. if (mb.getDataSize() > 16)
  180109. {
  180110. struct jpeg_decompress_struct jpegDecompStruct;
  180111. struct jpeg_error_mgr jerr;
  180112. setupSilentErrorHandler (jerr);
  180113. jpegDecompStruct.err = &jerr;
  180114. jpeg_create_decompress (&jpegDecompStruct);
  180115. jpegDecompStruct.src = (jpeg_source_mgr*)(jpegDecompStruct.mem->alloc_small)
  180116. ((j_common_ptr)(&jpegDecompStruct), JPOOL_PERMANENT, sizeof (jpeg_source_mgr));
  180117. jpegDecompStruct.src->init_source = dummyCallback1;
  180118. jpegDecompStruct.src->fill_input_buffer = jpegFill;
  180119. jpegDecompStruct.src->skip_input_data = jpegSkip;
  180120. jpegDecompStruct.src->resync_to_restart = jpeg_resync_to_restart;
  180121. jpegDecompStruct.src->term_source = dummyCallback1;
  180122. jpegDecompStruct.src->next_input_byte = static_cast <const unsigned char*> (mb.getData());
  180123. jpegDecompStruct.src->bytes_in_buffer = mb.getDataSize();
  180124. try
  180125. {
  180126. jpeg_read_header (&jpegDecompStruct, TRUE);
  180127. jpeg_calc_output_dimensions (&jpegDecompStruct);
  180128. const int width = jpegDecompStruct.output_width;
  180129. const int height = jpegDecompStruct.output_height;
  180130. jpegDecompStruct.out_color_space = JCS_RGB;
  180131. JSAMPARRAY buffer
  180132. = (*jpegDecompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegDecompStruct,
  180133. JPOOL_IMAGE,
  180134. width * 3, 1);
  180135. if (jpeg_start_decompress (&jpegDecompStruct))
  180136. {
  180137. image = Image (Image::RGB, width, height, false);
  180138. const bool hasAlphaChan = image.hasAlphaChannel(); // (the native image creator may not give back what we expect)
  180139. const Image::BitmapData destData (image, true);
  180140. for (int y = 0; y < height; ++y)
  180141. {
  180142. jpeg_read_scanlines (&jpegDecompStruct, buffer, 1);
  180143. const uint8* src = *buffer;
  180144. uint8* dest = destData.getLinePointer (y);
  180145. if (hasAlphaChan)
  180146. {
  180147. for (int i = width; --i >= 0;)
  180148. {
  180149. ((PixelARGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  180150. ((PixelARGB*) dest)->premultiply();
  180151. dest += destData.pixelStride;
  180152. src += 3;
  180153. }
  180154. }
  180155. else
  180156. {
  180157. for (int i = width; --i >= 0;)
  180158. {
  180159. ((PixelRGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  180160. dest += destData.pixelStride;
  180161. src += 3;
  180162. }
  180163. }
  180164. }
  180165. jpeg_finish_decompress (&jpegDecompStruct);
  180166. in.setPosition (((char*) jpegDecompStruct.src->next_input_byte) - (char*) mb.getData());
  180167. }
  180168. jpeg_destroy_decompress (&jpegDecompStruct);
  180169. }
  180170. catch (...)
  180171. {}
  180172. }
  180173. return image;
  180174. #endif
  180175. }
  180176. bool JPEGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  180177. {
  180178. using namespace jpeglibNamespace;
  180179. using namespace JPEGHelpers;
  180180. if (image.hasAlphaChannel())
  180181. {
  180182. // this method could fill the background in white and still save the image..
  180183. jassertfalse;
  180184. return true;
  180185. }
  180186. struct jpeg_compress_struct jpegCompStruct;
  180187. struct jpeg_error_mgr jerr;
  180188. setupSilentErrorHandler (jerr);
  180189. jpegCompStruct.err = &jerr;
  180190. jpeg_create_compress (&jpegCompStruct);
  180191. JuceJpegDest dest;
  180192. jpegCompStruct.dest = &dest;
  180193. dest.output = &out;
  180194. HeapBlock <char> tempBuffer (jpegBufferSize);
  180195. dest.buffer = tempBuffer;
  180196. dest.next_output_byte = (JOCTET*) dest.buffer;
  180197. dest.free_in_buffer = jpegBufferSize;
  180198. dest.init_destination = jpegWriteInit;
  180199. dest.empty_output_buffer = jpegWriteFlush;
  180200. dest.term_destination = jpegWriteTerminate;
  180201. jpegCompStruct.image_width = image.getWidth();
  180202. jpegCompStruct.image_height = image.getHeight();
  180203. jpegCompStruct.input_components = 3;
  180204. jpegCompStruct.in_color_space = JCS_RGB;
  180205. jpegCompStruct.write_JFIF_header = 1;
  180206. jpegCompStruct.X_density = 72;
  180207. jpegCompStruct.Y_density = 72;
  180208. jpeg_set_defaults (&jpegCompStruct);
  180209. jpegCompStruct.dct_method = JDCT_FLOAT;
  180210. jpegCompStruct.optimize_coding = 1;
  180211. //jpegCompStruct.smoothing_factor = 10;
  180212. if (quality < 0.0f)
  180213. quality = 0.85f;
  180214. jpeg_set_quality (&jpegCompStruct, jlimit (0, 100, roundToInt (quality * 100.0f)), TRUE);
  180215. jpeg_start_compress (&jpegCompStruct, TRUE);
  180216. const int strideBytes = jpegCompStruct.image_width * jpegCompStruct.input_components;
  180217. JSAMPARRAY buffer = (*jpegCompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegCompStruct,
  180218. JPOOL_IMAGE, strideBytes, 1);
  180219. const Image::BitmapData srcData (image, false);
  180220. while (jpegCompStruct.next_scanline < jpegCompStruct.image_height)
  180221. {
  180222. const uint8* src = srcData.getLinePointer (jpegCompStruct.next_scanline);
  180223. uint8* dst = *buffer;
  180224. for (int i = jpegCompStruct.image_width; --i >= 0;)
  180225. {
  180226. *dst++ = ((const PixelRGB*) src)->getRed();
  180227. *dst++ = ((const PixelRGB*) src)->getGreen();
  180228. *dst++ = ((const PixelRGB*) src)->getBlue();
  180229. src += srcData.pixelStride;
  180230. }
  180231. jpeg_write_scanlines (&jpegCompStruct, buffer, 1);
  180232. }
  180233. jpeg_finish_compress (&jpegCompStruct);
  180234. jpeg_destroy_compress (&jpegCompStruct);
  180235. out.flush();
  180236. return true;
  180237. }
  180238. END_JUCE_NAMESPACE
  180239. /*** End of inlined file: juce_JPEGLoader.cpp ***/
  180240. /*** Start of inlined file: juce_PNGLoader.cpp ***/
  180241. #if JUCE_MSVC
  180242. #pragma warning (push)
  180243. #pragma warning (disable: 4390 4611)
  180244. #endif
  180245. namespace zlibNamespace
  180246. {
  180247. #if JUCE_INCLUDE_ZLIB_CODE
  180248. #undef OS_CODE
  180249. #undef fdopen
  180250. #undef OS_CODE
  180251. #else
  180252. #include <zlib.h>
  180253. #endif
  180254. }
  180255. namespace pnglibNamespace
  180256. {
  180257. using namespace zlibNamespace;
  180258. #if JUCE_INCLUDE_PNGLIB_CODE
  180259. #if _MSC_VER != 1310
  180260. using ::calloc; // (causes conflict in VS.NET 2003)
  180261. using ::malloc;
  180262. using ::free;
  180263. #endif
  180264. using ::abs;
  180265. #define PNG_INTERNAL
  180266. #define NO_DUMMY_DECL
  180267. #define PNG_SETJMP_NOT_SUPPORTED
  180268. /*** Start of inlined file: png.h ***/
  180269. /* png.h - header file for PNG reference library
  180270. *
  180271. * libpng version 1.2.21 - October 4, 2007
  180272. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  180273. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  180274. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  180275. *
  180276. * Authors and maintainers:
  180277. * libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalnat
  180278. * libpng versions 0.89c, June 1996, through 0.96, May 1997: Andreas Dilger
  180279. * libpng versions 0.97, January 1998, through 1.2.21 - October 4, 2007: Glenn
  180280. * See also "Contributing Authors", below.
  180281. *
  180282. * Note about libpng version numbers:
  180283. *
  180284. * Due to various miscommunications, unforeseen code incompatibilities
  180285. * and occasional factors outside the authors' control, version numbering
  180286. * on the library has not always been consistent and straightforward.
  180287. * The following table summarizes matters since version 0.89c, which was
  180288. * the first widely used release:
  180289. *
  180290. * source png.h png.h shared-lib
  180291. * version string int version
  180292. * ------- ------ ----- ----------
  180293. * 0.89c "1.0 beta 3" 0.89 89 1.0.89
  180294. * 0.90 "1.0 beta 4" 0.90 90 0.90 [should have been 2.0.90]
  180295. * 0.95 "1.0 beta 5" 0.95 95 0.95 [should have been 2.0.95]
  180296. * 0.96 "1.0 beta 6" 0.96 96 0.96 [should have been 2.0.96]
  180297. * 0.97b "1.00.97 beta 7" 1.00.97 97 1.0.1 [should have been 2.0.97]
  180298. * 0.97c 0.97 97 2.0.97
  180299. * 0.98 0.98 98 2.0.98
  180300. * 0.99 0.99 98 2.0.99
  180301. * 0.99a-m 0.99 99 2.0.99
  180302. * 1.00 1.00 100 2.1.0 [100 should be 10000]
  180303. * 1.0.0 (from here on, the 100 2.1.0 [100 should be 10000]
  180304. * 1.0.1 png.h string is 10001 2.1.0
  180305. * 1.0.1a-e identical to the 10002 from here on, the shared library
  180306. * 1.0.2 source version) 10002 is 2.V where V is the source code
  180307. * 1.0.2a-b 10003 version, except as noted.
  180308. * 1.0.3 10003
  180309. * 1.0.3a-d 10004
  180310. * 1.0.4 10004
  180311. * 1.0.4a-f 10005
  180312. * 1.0.5 (+ 2 patches) 10005
  180313. * 1.0.5a-d 10006
  180314. * 1.0.5e-r 10100 (not source compatible)
  180315. * 1.0.5s-v 10006 (not binary compatible)
  180316. * 1.0.6 (+ 3 patches) 10006 (still binary incompatible)
  180317. * 1.0.6d-f 10007 (still binary incompatible)
  180318. * 1.0.6g 10007
  180319. * 1.0.6h 10007 10.6h (testing xy.z so-numbering)
  180320. * 1.0.6i 10007 10.6i
  180321. * 1.0.6j 10007 2.1.0.6j (incompatible with 1.0.0)
  180322. * 1.0.7beta11-14 DLLNUM 10007 2.1.0.7beta11-14 (binary compatible)
  180323. * 1.0.7beta15-18 1 10007 2.1.0.7beta15-18 (binary compatible)
  180324. * 1.0.7rc1-2 1 10007 2.1.0.7rc1-2 (binary compatible)
  180325. * 1.0.7 1 10007 (still compatible)
  180326. * 1.0.8beta1-4 1 10008 2.1.0.8beta1-4
  180327. * 1.0.8rc1 1 10008 2.1.0.8rc1
  180328. * 1.0.8 1 10008 2.1.0.8
  180329. * 1.0.9beta1-6 1 10009 2.1.0.9beta1-6
  180330. * 1.0.9rc1 1 10009 2.1.0.9rc1
  180331. * 1.0.9beta7-10 1 10009 2.1.0.9beta7-10
  180332. * 1.0.9rc2 1 10009 2.1.0.9rc2
  180333. * 1.0.9 1 10009 2.1.0.9
  180334. * 1.0.10beta1 1 10010 2.1.0.10beta1
  180335. * 1.0.10rc1 1 10010 2.1.0.10rc1
  180336. * 1.0.10 1 10010 2.1.0.10
  180337. * 1.0.11beta1-3 1 10011 2.1.0.11beta1-3
  180338. * 1.0.11rc1 1 10011 2.1.0.11rc1
  180339. * 1.0.11 1 10011 2.1.0.11
  180340. * 1.0.12beta1-2 2 10012 2.1.0.12beta1-2
  180341. * 1.0.12rc1 2 10012 2.1.0.12rc1
  180342. * 1.0.12 2 10012 2.1.0.12
  180343. * 1.1.0a-f - 10100 2.1.1.0a-f (branch abandoned)
  180344. * 1.2.0beta1-2 2 10200 2.1.2.0beta1-2
  180345. * 1.2.0beta3-5 3 10200 3.1.2.0beta3-5
  180346. * 1.2.0rc1 3 10200 3.1.2.0rc1
  180347. * 1.2.0 3 10200 3.1.2.0
  180348. * 1.2.1beta1-4 3 10201 3.1.2.1beta1-4
  180349. * 1.2.1rc1-2 3 10201 3.1.2.1rc1-2
  180350. * 1.2.1 3 10201 3.1.2.1
  180351. * 1.2.2beta1-6 12 10202 12.so.0.1.2.2beta1-6
  180352. * 1.0.13beta1 10 10013 10.so.0.1.0.13beta1
  180353. * 1.0.13rc1 10 10013 10.so.0.1.0.13rc1
  180354. * 1.2.2rc1 12 10202 12.so.0.1.2.2rc1
  180355. * 1.0.13 10 10013 10.so.0.1.0.13
  180356. * 1.2.2 12 10202 12.so.0.1.2.2
  180357. * 1.2.3rc1-6 12 10203 12.so.0.1.2.3rc1-6
  180358. * 1.2.3 12 10203 12.so.0.1.2.3
  180359. * 1.2.4beta1-3 13 10204 12.so.0.1.2.4beta1-3
  180360. * 1.0.14rc1 13 10014 10.so.0.1.0.14rc1
  180361. * 1.2.4rc1 13 10204 12.so.0.1.2.4rc1
  180362. * 1.0.14 10 10014 10.so.0.1.0.14
  180363. * 1.2.4 13 10204 12.so.0.1.2.4
  180364. * 1.2.5beta1-2 13 10205 12.so.0.1.2.5beta1-2
  180365. * 1.0.15rc1-3 10 10015 10.so.0.1.0.15rc1-3
  180366. * 1.2.5rc1-3 13 10205 12.so.0.1.2.5rc1-3
  180367. * 1.0.15 10 10015 10.so.0.1.0.15
  180368. * 1.2.5 13 10205 12.so.0.1.2.5
  180369. * 1.2.6beta1-4 13 10206 12.so.0.1.2.6beta1-4
  180370. * 1.0.16 10 10016 10.so.0.1.0.16
  180371. * 1.2.6 13 10206 12.so.0.1.2.6
  180372. * 1.2.7beta1-2 13 10207 12.so.0.1.2.7beta1-2
  180373. * 1.0.17rc1 10 10017 10.so.0.1.0.17rc1
  180374. * 1.2.7rc1 13 10207 12.so.0.1.2.7rc1
  180375. * 1.0.17 10 10017 10.so.0.1.0.17
  180376. * 1.2.7 13 10207 12.so.0.1.2.7
  180377. * 1.2.8beta1-5 13 10208 12.so.0.1.2.8beta1-5
  180378. * 1.0.18rc1-5 10 10018 10.so.0.1.0.18rc1-5
  180379. * 1.2.8rc1-5 13 10208 12.so.0.1.2.8rc1-5
  180380. * 1.0.18 10 10018 10.so.0.1.0.18
  180381. * 1.2.8 13 10208 12.so.0.1.2.8
  180382. * 1.2.9beta1-3 13 10209 12.so.0.1.2.9beta1-3
  180383. * 1.2.9beta4-11 13 10209 12.so.0.9[.0]
  180384. * 1.2.9rc1 13 10209 12.so.0.9[.0]
  180385. * 1.2.9 13 10209 12.so.0.9[.0]
  180386. * 1.2.10beta1-8 13 10210 12.so.0.10[.0]
  180387. * 1.2.10rc1-3 13 10210 12.so.0.10[.0]
  180388. * 1.2.10 13 10210 12.so.0.10[.0]
  180389. * 1.2.11beta1-4 13 10211 12.so.0.11[.0]
  180390. * 1.0.19rc1-5 10 10019 10.so.0.19[.0]
  180391. * 1.2.11rc1-5 13 10211 12.so.0.11[.0]
  180392. * 1.0.19 10 10019 10.so.0.19[.0]
  180393. * 1.2.11 13 10211 12.so.0.11[.0]
  180394. * 1.0.20 10 10020 10.so.0.20[.0]
  180395. * 1.2.12 13 10212 12.so.0.12[.0]
  180396. * 1.2.13beta1 13 10213 12.so.0.13[.0]
  180397. * 1.0.21 10 10021 10.so.0.21[.0]
  180398. * 1.2.13 13 10213 12.so.0.13[.0]
  180399. * 1.2.14beta1-2 13 10214 12.so.0.14[.0]
  180400. * 1.0.22rc1 10 10022 10.so.0.22[.0]
  180401. * 1.2.14rc1 13 10214 12.so.0.14[.0]
  180402. * 1.0.22 10 10022 10.so.0.22[.0]
  180403. * 1.2.14 13 10214 12.so.0.14[.0]
  180404. * 1.2.15beta1-6 13 10215 12.so.0.15[.0]
  180405. * 1.0.23rc1-5 10 10023 10.so.0.23[.0]
  180406. * 1.2.15rc1-5 13 10215 12.so.0.15[.0]
  180407. * 1.0.23 10 10023 10.so.0.23[.0]
  180408. * 1.2.15 13 10215 12.so.0.15[.0]
  180409. * 1.2.16beta1-2 13 10216 12.so.0.16[.0]
  180410. * 1.2.16rc1 13 10216 12.so.0.16[.0]
  180411. * 1.0.24 10 10024 10.so.0.24[.0]
  180412. * 1.2.16 13 10216 12.so.0.16[.0]
  180413. * 1.2.17beta1-2 13 10217 12.so.0.17[.0]
  180414. * 1.0.25rc1 10 10025 10.so.0.25[.0]
  180415. * 1.2.17rc1-3 13 10217 12.so.0.17[.0]
  180416. * 1.0.25 10 10025 10.so.0.25[.0]
  180417. * 1.2.17 13 10217 12.so.0.17[.0]
  180418. * 1.0.26 10 10026 10.so.0.26[.0]
  180419. * 1.2.18 13 10218 12.so.0.18[.0]
  180420. * 1.2.19beta1-31 13 10219 12.so.0.19[.0]
  180421. * 1.0.27rc1-6 10 10027 10.so.0.27[.0]
  180422. * 1.2.19rc1-6 13 10219 12.so.0.19[.0]
  180423. * 1.0.27 10 10027 10.so.0.27[.0]
  180424. * 1.2.19 13 10219 12.so.0.19[.0]
  180425. * 1.2.20beta01-04 13 10220 12.so.0.20[.0]
  180426. * 1.0.28rc1-6 10 10028 10.so.0.28[.0]
  180427. * 1.2.20rc1-6 13 10220 12.so.0.20[.0]
  180428. * 1.0.28 10 10028 10.so.0.28[.0]
  180429. * 1.2.20 13 10220 12.so.0.20[.0]
  180430. * 1.2.21beta1-2 13 10221 12.so.0.21[.0]
  180431. * 1.2.21rc1-3 13 10221 12.so.0.21[.0]
  180432. * 1.0.29 10 10029 10.so.0.29[.0]
  180433. * 1.2.21 13 10221 12.so.0.21[.0]
  180434. *
  180435. * Henceforth the source version will match the shared-library major
  180436. * and minor numbers; the shared-library major version number will be
  180437. * used for changes in backward compatibility, as it is intended. The
  180438. * PNG_LIBPNG_VER macro, which is not used within libpng but is available
  180439. * for applications, is an unsigned integer of the form xyyzz corresponding
  180440. * to the source version x.y.z (leading zeros in y and z). Beta versions
  180441. * were given the previous public release number plus a letter, until
  180442. * version 1.0.6j; from then on they were given the upcoming public
  180443. * release number plus "betaNN" or "rcN".
  180444. *
  180445. * Binary incompatibility exists only when applications make direct access
  180446. * to the info_ptr or png_ptr members through png.h, and the compiled
  180447. * application is loaded with a different version of the library.
  180448. *
  180449. * DLLNUM will change each time there are forward or backward changes
  180450. * in binary compatibility (e.g., when a new feature is added).
  180451. *
  180452. * See libpng.txt or libpng.3 for more information. The PNG specification
  180453. * is available as a W3C Recommendation and as an ISO Specification,
  180454. * <http://www.w3.org/TR/2003/REC-PNG-20031110/
  180455. */
  180456. /*
  180457. * COPYRIGHT NOTICE, DISCLAIMER, and LICENSE:
  180458. *
  180459. * If you modify libpng you may insert additional notices immediately following
  180460. * this sentence.
  180461. *
  180462. * libpng versions 1.2.6, August 15, 2004, through 1.2.21, October 4, 2007, are
  180463. * Copyright (c) 2004, 2006-2007 Glenn Randers-Pehrson, and are
  180464. * distributed according to the same disclaimer and license as libpng-1.2.5
  180465. * with the following individual added to the list of Contributing Authors:
  180466. *
  180467. * Cosmin Truta
  180468. *
  180469. * libpng versions 1.0.7, July 1, 2000, through 1.2.5, October 3, 2002, are
  180470. * Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are
  180471. * distributed according to the same disclaimer and license as libpng-1.0.6
  180472. * with the following individuals added to the list of Contributing Authors:
  180473. *
  180474. * Simon-Pierre Cadieux
  180475. * Eric S. Raymond
  180476. * Gilles Vollant
  180477. *
  180478. * and with the following additions to the disclaimer:
  180479. *
  180480. * There is no warranty against interference with your enjoyment of the
  180481. * library or against infringement. There is no warranty that our
  180482. * efforts or the library will fulfill any of your particular purposes
  180483. * or needs. This library is provided with all faults, and the entire
  180484. * risk of satisfactory quality, performance, accuracy, and effort is with
  180485. * the user.
  180486. *
  180487. * libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
  180488. * Copyright (c) 1998, 1999, 2000 Glenn Randers-Pehrson, and are
  180489. * distributed according to the same disclaimer and license as libpng-0.96,
  180490. * with the following individuals added to the list of Contributing Authors:
  180491. *
  180492. * Tom Lane
  180493. * Glenn Randers-Pehrson
  180494. * Willem van Schaik
  180495. *
  180496. * libpng versions 0.89, June 1996, through 0.96, May 1997, are
  180497. * Copyright (c) 1996, 1997 Andreas Dilger
  180498. * Distributed according to the same disclaimer and license as libpng-0.88,
  180499. * with the following individuals added to the list of Contributing Authors:
  180500. *
  180501. * John Bowler
  180502. * Kevin Bracey
  180503. * Sam Bushell
  180504. * Magnus Holmgren
  180505. * Greg Roelofs
  180506. * Tom Tanner
  180507. *
  180508. * libpng versions 0.5, May 1995, through 0.88, January 1996, are
  180509. * Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.
  180510. *
  180511. * For the purposes of this copyright and license, "Contributing Authors"
  180512. * is defined as the following set of individuals:
  180513. *
  180514. * Andreas Dilger
  180515. * Dave Martindale
  180516. * Guy Eric Schalnat
  180517. * Paul Schmidt
  180518. * Tim Wegner
  180519. *
  180520. * The PNG Reference Library is supplied "AS IS". The Contributing Authors
  180521. * and Group 42, Inc. disclaim all warranties, expressed or implied,
  180522. * including, without limitation, the warranties of merchantability and of
  180523. * fitness for any purpose. The Contributing Authors and Group 42, Inc.
  180524. * assume no liability for direct, indirect, incidental, special, exemplary,
  180525. * or consequential damages, which may result from the use of the PNG
  180526. * Reference Library, even if advised of the possibility of such damage.
  180527. *
  180528. * Permission is hereby granted to use, copy, modify, and distribute this
  180529. * source code, or portions hereof, for any purpose, without fee, subject
  180530. * to the following restrictions:
  180531. *
  180532. * 1. The origin of this source code must not be misrepresented.
  180533. *
  180534. * 2. Altered versions must be plainly marked as such and
  180535. * must not be misrepresented as being the original source.
  180536. *
  180537. * 3. This Copyright notice may not be removed or altered from
  180538. * any source or altered source distribution.
  180539. *
  180540. * The Contributing Authors and Group 42, Inc. specifically permit, without
  180541. * fee, and encourage the use of this source code as a component to
  180542. * supporting the PNG file format in commercial products. If you use this
  180543. * source code in a product, acknowledgment is not required but would be
  180544. * appreciated.
  180545. */
  180546. /*
  180547. * A "png_get_copyright" function is available, for convenient use in "about"
  180548. * boxes and the like:
  180549. *
  180550. * printf("%s",png_get_copyright(NULL));
  180551. *
  180552. * Also, the PNG logo (in PNG format, of course) is supplied in the
  180553. * files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31).
  180554. */
  180555. /*
  180556. * Libpng is OSI Certified Open Source Software. OSI Certified is a
  180557. * certification mark of the Open Source Initiative.
  180558. */
  180559. /*
  180560. * The contributing authors would like to thank all those who helped
  180561. * with testing, bug fixes, and patience. This wouldn't have been
  180562. * possible without all of you.
  180563. *
  180564. * Thanks to Frank J. T. Wojcik for helping with the documentation.
  180565. */
  180566. /*
  180567. * Y2K compliance in libpng:
  180568. * =========================
  180569. *
  180570. * October 4, 2007
  180571. *
  180572. * Since the PNG Development group is an ad-hoc body, we can't make
  180573. * an official declaration.
  180574. *
  180575. * This is your unofficial assurance that libpng from version 0.71 and
  180576. * upward through 1.2.21 are Y2K compliant. It is my belief that earlier
  180577. * versions were also Y2K compliant.
  180578. *
  180579. * Libpng only has three year fields. One is a 2-byte unsigned integer
  180580. * that will hold years up to 65535. The other two hold the date in text
  180581. * format, and will hold years up to 9999.
  180582. *
  180583. * The integer is
  180584. * "png_uint_16 year" in png_time_struct.
  180585. *
  180586. * The strings are
  180587. * "png_charp time_buffer" in png_struct and
  180588. * "near_time_buffer", which is a local character string in png.c.
  180589. *
  180590. * There are seven time-related functions:
  180591. * png.c: png_convert_to_rfc_1123() in png.c
  180592. * (formerly png_convert_to_rfc_1152() in error)
  180593. * png_convert_from_struct_tm() in pngwrite.c, called in pngwrite.c
  180594. * png_convert_from_time_t() in pngwrite.c
  180595. * png_get_tIME() in pngget.c
  180596. * png_handle_tIME() in pngrutil.c, called in pngread.c
  180597. * png_set_tIME() in pngset.c
  180598. * png_write_tIME() in pngwutil.c, called in pngwrite.c
  180599. *
  180600. * All handle dates properly in a Y2K environment. The
  180601. * png_convert_from_time_t() function calls gmtime() to convert from system
  180602. * clock time, which returns (year - 1900), which we properly convert to
  180603. * the full 4-digit year. There is a possibility that applications using
  180604. * libpng are not passing 4-digit years into the png_convert_to_rfc_1123()
  180605. * function, or that they are incorrectly passing only a 2-digit year
  180606. * instead of "year - 1900" into the png_convert_from_struct_tm() function,
  180607. * but this is not under our control. The libpng documentation has always
  180608. * stated that it works with 4-digit years, and the APIs have been
  180609. * documented as such.
  180610. *
  180611. * The tIME chunk itself is also Y2K compliant. It uses a 2-byte unsigned
  180612. * integer to hold the year, and can hold years as large as 65535.
  180613. *
  180614. * zlib, upon which libpng depends, is also Y2K compliant. It contains
  180615. * no date-related code.
  180616. *
  180617. * Glenn Randers-Pehrson
  180618. * libpng maintainer
  180619. * PNG Development Group
  180620. */
  180621. #ifndef PNG_H
  180622. #define PNG_H
  180623. /* This is not the place to learn how to use libpng. The file libpng.txt
  180624. * describes how to use libpng, and the file example.c summarizes it
  180625. * with some code on which to build. This file is useful for looking
  180626. * at the actual function definitions and structure components.
  180627. */
  180628. /* Version information for png.h - this should match the version in png.c */
  180629. #define PNG_LIBPNG_VER_STRING "1.2.21"
  180630. #define PNG_HEADER_VERSION_STRING \
  180631. " libpng version 1.2.21 - October 4, 2007\n"
  180632. #define PNG_LIBPNG_VER_SONUM 0
  180633. #define PNG_LIBPNG_VER_DLLNUM 13
  180634. /* These should match the first 3 components of PNG_LIBPNG_VER_STRING: */
  180635. #define PNG_LIBPNG_VER_MAJOR 1
  180636. #define PNG_LIBPNG_VER_MINOR 2
  180637. #define PNG_LIBPNG_VER_RELEASE 21
  180638. /* This should match the numeric part of the final component of
  180639. * PNG_LIBPNG_VER_STRING, omitting any leading zero: */
  180640. #define PNG_LIBPNG_VER_BUILD 0
  180641. /* Release Status */
  180642. #define PNG_LIBPNG_BUILD_ALPHA 1
  180643. #define PNG_LIBPNG_BUILD_BETA 2
  180644. #define PNG_LIBPNG_BUILD_RC 3
  180645. #define PNG_LIBPNG_BUILD_STABLE 4
  180646. #define PNG_LIBPNG_BUILD_RELEASE_STATUS_MASK 7
  180647. /* Release-Specific Flags */
  180648. #define PNG_LIBPNG_BUILD_PATCH 8 /* Can be OR'ed with
  180649. PNG_LIBPNG_BUILD_STABLE only */
  180650. #define PNG_LIBPNG_BUILD_PRIVATE 16 /* Cannot be OR'ed with
  180651. PNG_LIBPNG_BUILD_SPECIAL */
  180652. #define PNG_LIBPNG_BUILD_SPECIAL 32 /* Cannot be OR'ed with
  180653. PNG_LIBPNG_BUILD_PRIVATE */
  180654. #define PNG_LIBPNG_BUILD_BASE_TYPE PNG_LIBPNG_BUILD_STABLE
  180655. /* Careful here. At one time, Guy wanted to use 082, but that would be octal.
  180656. * We must not include leading zeros.
  180657. * Versions 0.7 through 1.0.0 were in the range 0 to 100 here (only
  180658. * version 1.0.0 was mis-numbered 100 instead of 10000). From
  180659. * version 1.0.1 it's xxyyzz, where x=major, y=minor, z=release */
  180660. #define PNG_LIBPNG_VER 10221 /* 1.2.21 */
  180661. #ifndef PNG_VERSION_INFO_ONLY
  180662. /* include the compression library's header */
  180663. #endif
  180664. /* include all user configurable info, including optional assembler routines */
  180665. /*** Start of inlined file: pngconf.h ***/
  180666. /* pngconf.h - machine configurable file for libpng
  180667. *
  180668. * libpng version 1.2.21 - October 4, 2007
  180669. * For conditions of distribution and use, see copyright notice in png.h
  180670. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  180671. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  180672. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  180673. */
  180674. /* Any machine specific code is near the front of this file, so if you
  180675. * are configuring libpng for a machine, you may want to read the section
  180676. * starting here down to where it starts to typedef png_color, png_text,
  180677. * and png_info.
  180678. */
  180679. #ifndef PNGCONF_H
  180680. #define PNGCONF_H
  180681. #define PNG_1_2_X
  180682. // These are some Juce config settings that should remove any unnecessary code bloat..
  180683. #define PNG_NO_STDIO 1
  180684. #define PNG_DEBUG 0
  180685. #define PNG_NO_WARNINGS 1
  180686. #define PNG_NO_ERROR_TEXT 1
  180687. #define PNG_NO_ERROR_NUMBERS 1
  180688. #define PNG_NO_USER_MEM 1
  180689. #define PNG_NO_READ_iCCP 1
  180690. #define PNG_NO_READ_UNKNOWN_CHUNKS 1
  180691. #define PNG_NO_READ_USER_CHUNKS 1
  180692. #define PNG_NO_READ_iTXt 1
  180693. #define PNG_NO_READ_sCAL 1
  180694. #define PNG_NO_READ_sPLT 1
  180695. #define png_error(a, b) png_err(a)
  180696. #define png_warning(a, b)
  180697. #define png_chunk_error(a, b) png_err(a)
  180698. #define png_chunk_warning(a, b)
  180699. /*
  180700. * PNG_USER_CONFIG has to be defined on the compiler command line. This
  180701. * includes the resource compiler for Windows DLL configurations.
  180702. */
  180703. #ifdef PNG_USER_CONFIG
  180704. # ifndef PNG_USER_PRIVATEBUILD
  180705. # define PNG_USER_PRIVATEBUILD
  180706. # endif
  180707. #include "pngusr.h"
  180708. #endif
  180709. /* PNG_CONFIGURE_LIBPNG is set by the "configure" script. */
  180710. #ifdef PNG_CONFIGURE_LIBPNG
  180711. #ifdef HAVE_CONFIG_H
  180712. #include "config.h"
  180713. #endif
  180714. #endif
  180715. /*
  180716. * Added at libpng-1.2.8
  180717. *
  180718. * If you create a private DLL you need to define in "pngusr.h" the followings:
  180719. * #define PNG_USER_PRIVATEBUILD <Describes by whom and why this version of
  180720. * the DLL was built>
  180721. * e.g. #define PNG_USER_PRIVATEBUILD "Build by MyCompany for xyz reasons."
  180722. * #define PNG_USER_DLLFNAME_POSTFIX <two-letter postfix that serve to
  180723. * distinguish your DLL from those of the official release. These
  180724. * correspond to the trailing letters that come after the version
  180725. * number and must match your private DLL name>
  180726. * e.g. // private DLL "libpng13gx.dll"
  180727. * #define PNG_USER_DLLFNAME_POSTFIX "gx"
  180728. *
  180729. * The following macros are also at your disposal if you want to complete the
  180730. * DLL VERSIONINFO structure.
  180731. * - PNG_USER_VERSIONINFO_COMMENTS
  180732. * - PNG_USER_VERSIONINFO_COMPANYNAME
  180733. * - PNG_USER_VERSIONINFO_LEGALTRADEMARKS
  180734. */
  180735. #ifdef __STDC__
  180736. #ifdef SPECIALBUILD
  180737. # pragma message("PNG_LIBPNG_SPECIALBUILD (and deprecated SPECIALBUILD)\
  180738. are now LIBPNG reserved macros. Use PNG_USER_PRIVATEBUILD instead.")
  180739. #endif
  180740. #ifdef PRIVATEBUILD
  180741. # pragma message("PRIVATEBUILD is deprecated.\
  180742. Use PNG_USER_PRIVATEBUILD instead.")
  180743. # define PNG_USER_PRIVATEBUILD PRIVATEBUILD
  180744. #endif
  180745. #endif /* __STDC__ */
  180746. #ifndef PNG_VERSION_INFO_ONLY
  180747. /* End of material added to libpng-1.2.8 */
  180748. /* Added at libpng-1.2.19, removed at libpng-1.2.20 because it caused trouble
  180749. Restored at libpng-1.2.21 */
  180750. # define PNG_WARN_UNINITIALIZED_ROW 1
  180751. /* End of material added at libpng-1.2.19/1.2.21 */
  180752. /* This is the size of the compression buffer, and thus the size of
  180753. * an IDAT chunk. Make this whatever size you feel is best for your
  180754. * machine. One of these will be allocated per png_struct. When this
  180755. * is full, it writes the data to the disk, and does some other
  180756. * calculations. Making this an extremely small size will slow
  180757. * the library down, but you may want to experiment to determine
  180758. * where it becomes significant, if you are concerned with memory
  180759. * usage. Note that zlib allocates at least 32Kb also. For readers,
  180760. * this describes the size of the buffer available to read the data in.
  180761. * Unless this gets smaller than the size of a row (compressed),
  180762. * it should not make much difference how big this is.
  180763. */
  180764. #ifndef PNG_ZBUF_SIZE
  180765. # define PNG_ZBUF_SIZE 8192
  180766. #endif
  180767. /* Enable if you want a write-only libpng */
  180768. #ifndef PNG_NO_READ_SUPPORTED
  180769. # define PNG_READ_SUPPORTED
  180770. #endif
  180771. /* Enable if you want a read-only libpng */
  180772. #ifndef PNG_NO_WRITE_SUPPORTED
  180773. # define PNG_WRITE_SUPPORTED
  180774. #endif
  180775. /* Enabled by default in 1.2.0. You can disable this if you don't need to
  180776. support PNGs that are embedded in MNG datastreams */
  180777. #if !defined(PNG_1_0_X) && !defined(PNG_NO_MNG_FEATURES)
  180778. # ifndef PNG_MNG_FEATURES_SUPPORTED
  180779. # define PNG_MNG_FEATURES_SUPPORTED
  180780. # endif
  180781. #endif
  180782. #ifndef PNG_NO_FLOATING_POINT_SUPPORTED
  180783. # ifndef PNG_FLOATING_POINT_SUPPORTED
  180784. # define PNG_FLOATING_POINT_SUPPORTED
  180785. # endif
  180786. #endif
  180787. /* If you are running on a machine where you cannot allocate more
  180788. * than 64K of memory at once, uncomment this. While libpng will not
  180789. * normally need that much memory in a chunk (unless you load up a very
  180790. * large file), zlib needs to know how big of a chunk it can use, and
  180791. * libpng thus makes sure to check any memory allocation to verify it
  180792. * will fit into memory.
  180793. #define PNG_MAX_MALLOC_64K
  180794. */
  180795. #if defined(MAXSEG_64K) && !defined(PNG_MAX_MALLOC_64K)
  180796. # define PNG_MAX_MALLOC_64K
  180797. #endif
  180798. /* Special munging to support doing things the 'cygwin' way:
  180799. * 'Normal' png-on-win32 defines/defaults:
  180800. * PNG_BUILD_DLL -- building dll
  180801. * PNG_USE_DLL -- building an application, linking to dll
  180802. * (no define) -- building static library, or building an
  180803. * application and linking to the static lib
  180804. * 'Cygwin' defines/defaults:
  180805. * PNG_BUILD_DLL -- (ignored) building the dll
  180806. * (no define) -- (ignored) building an application, linking to the dll
  180807. * PNG_STATIC -- (ignored) building the static lib, or building an
  180808. * application that links to the static lib.
  180809. * ALL_STATIC -- (ignored) building various static libs, or building an
  180810. * application that links to the static libs.
  180811. * Thus,
  180812. * a cygwin user should define either PNG_BUILD_DLL or PNG_STATIC, and
  180813. * this bit of #ifdefs will define the 'correct' config variables based on
  180814. * that. If a cygwin user *wants* to define 'PNG_USE_DLL' that's okay, but
  180815. * unnecessary.
  180816. *
  180817. * Also, the precedence order is:
  180818. * ALL_STATIC (since we can't #undef something outside our namespace)
  180819. * PNG_BUILD_DLL
  180820. * PNG_STATIC
  180821. * (nothing) == PNG_USE_DLL
  180822. *
  180823. * CYGWIN (2002-01-20): The preceding is now obsolete. With the advent
  180824. * of auto-import in binutils, we no longer need to worry about
  180825. * __declspec(dllexport) / __declspec(dllimport) and friends. Therefore,
  180826. * we don't need to worry about PNG_STATIC or ALL_STATIC when it comes
  180827. * to __declspec() stuff. However, we DO need to worry about
  180828. * PNG_BUILD_DLL and PNG_STATIC because those change some defaults
  180829. * such as CONSOLE_IO and whether GLOBAL_ARRAYS are allowed.
  180830. */
  180831. #if defined(__CYGWIN__)
  180832. # if defined(ALL_STATIC)
  180833. # if defined(PNG_BUILD_DLL)
  180834. # undef PNG_BUILD_DLL
  180835. # endif
  180836. # if defined(PNG_USE_DLL)
  180837. # undef PNG_USE_DLL
  180838. # endif
  180839. # if defined(PNG_DLL)
  180840. # undef PNG_DLL
  180841. # endif
  180842. # if !defined(PNG_STATIC)
  180843. # define PNG_STATIC
  180844. # endif
  180845. # else
  180846. # if defined (PNG_BUILD_DLL)
  180847. # if defined(PNG_STATIC)
  180848. # undef PNG_STATIC
  180849. # endif
  180850. # if defined(PNG_USE_DLL)
  180851. # undef PNG_USE_DLL
  180852. # endif
  180853. # if !defined(PNG_DLL)
  180854. # define PNG_DLL
  180855. # endif
  180856. # else
  180857. # if defined(PNG_STATIC)
  180858. # if defined(PNG_USE_DLL)
  180859. # undef PNG_USE_DLL
  180860. # endif
  180861. # if defined(PNG_DLL)
  180862. # undef PNG_DLL
  180863. # endif
  180864. # else
  180865. # if !defined(PNG_USE_DLL)
  180866. # define PNG_USE_DLL
  180867. # endif
  180868. # if !defined(PNG_DLL)
  180869. # define PNG_DLL
  180870. # endif
  180871. # endif
  180872. # endif
  180873. # endif
  180874. #endif
  180875. /* This protects us against compilers that run on a windowing system
  180876. * and thus don't have or would rather us not use the stdio types:
  180877. * stdin, stdout, and stderr. The only one currently used is stderr
  180878. * in png_error() and png_warning(). #defining PNG_NO_CONSOLE_IO will
  180879. * prevent these from being compiled and used. #defining PNG_NO_STDIO
  180880. * will also prevent these, plus will prevent the entire set of stdio
  180881. * macros and functions (FILE *, printf, etc.) from being compiled and used,
  180882. * unless (PNG_DEBUG > 0) has been #defined.
  180883. *
  180884. * #define PNG_NO_CONSOLE_IO
  180885. * #define PNG_NO_STDIO
  180886. */
  180887. #if defined(_WIN32_WCE)
  180888. # include <windows.h>
  180889. /* Console I/O functions are not supported on WindowsCE */
  180890. # define PNG_NO_CONSOLE_IO
  180891. # ifdef PNG_DEBUG
  180892. # undef PNG_DEBUG
  180893. # endif
  180894. #endif
  180895. #ifdef PNG_BUILD_DLL
  180896. # ifndef PNG_CONSOLE_IO_SUPPORTED
  180897. # ifndef PNG_NO_CONSOLE_IO
  180898. # define PNG_NO_CONSOLE_IO
  180899. # endif
  180900. # endif
  180901. #endif
  180902. # ifdef PNG_NO_STDIO
  180903. # ifndef PNG_NO_CONSOLE_IO
  180904. # define PNG_NO_CONSOLE_IO
  180905. # endif
  180906. # ifdef PNG_DEBUG
  180907. # if (PNG_DEBUG > 0)
  180908. # include <stdio.h>
  180909. # endif
  180910. # endif
  180911. # else
  180912. # if !defined(_WIN32_WCE)
  180913. /* "stdio.h" functions are not supported on WindowsCE */
  180914. # include <stdio.h>
  180915. # endif
  180916. # endif
  180917. /* This macro protects us against machines that don't have function
  180918. * prototypes (ie K&R style headers). If your compiler does not handle
  180919. * function prototypes, define this macro and use the included ansi2knr.
  180920. * I've always been able to use _NO_PROTO as the indicator, but you may
  180921. * need to drag the empty declaration out in front of here, or change the
  180922. * ifdef to suit your own needs.
  180923. */
  180924. #ifndef PNGARG
  180925. #ifdef OF /* zlib prototype munger */
  180926. # define PNGARG(arglist) OF(arglist)
  180927. #else
  180928. #ifdef _NO_PROTO
  180929. # define PNGARG(arglist) ()
  180930. # ifndef PNG_TYPECAST_NULL
  180931. # define PNG_TYPECAST_NULL
  180932. # endif
  180933. #else
  180934. # define PNGARG(arglist) arglist
  180935. #endif /* _NO_PROTO */
  180936. #endif /* OF */
  180937. #endif /* PNGARG */
  180938. /* Try to determine if we are compiling on a Mac. Note that testing for
  180939. * just __MWERKS__ is not good enough, because the Codewarrior is now used
  180940. * on non-Mac platforms.
  180941. */
  180942. #ifndef MACOS
  180943. # if (defined(__MWERKS__) && defined(macintosh)) || defined(applec) || \
  180944. defined(THINK_C) || defined(__SC__) || defined(TARGET_OS_MAC)
  180945. # define MACOS
  180946. # endif
  180947. #endif
  180948. /* enough people need this for various reasons to include it here */
  180949. #if !defined(MACOS) && !defined(RISCOS) && !defined(_WIN32_WCE)
  180950. # include <sys/types.h>
  180951. #endif
  180952. #if !defined(PNG_SETJMP_NOT_SUPPORTED) && !defined(PNG_NO_SETJMP_SUPPORTED)
  180953. # define PNG_SETJMP_SUPPORTED
  180954. #endif
  180955. #ifdef PNG_SETJMP_SUPPORTED
  180956. /* This is an attempt to force a single setjmp behaviour on Linux. If
  180957. * the X config stuff didn't define _BSD_SOURCE we wouldn't need this.
  180958. */
  180959. # ifdef __linux__
  180960. # ifdef _BSD_SOURCE
  180961. # define PNG_SAVE_BSD_SOURCE
  180962. # undef _BSD_SOURCE
  180963. # endif
  180964. # ifdef _SETJMP_H
  180965. /* If you encounter a compiler error here, see the explanation
  180966. * near the end of INSTALL.
  180967. */
  180968. __png.h__ already includes setjmp.h;
  180969. __dont__ include it again.;
  180970. # endif
  180971. # endif /* __linux__ */
  180972. /* include setjmp.h for error handling */
  180973. # include <setjmp.h>
  180974. # ifdef __linux__
  180975. # ifdef PNG_SAVE_BSD_SOURCE
  180976. # define _BSD_SOURCE
  180977. # undef PNG_SAVE_BSD_SOURCE
  180978. # endif
  180979. # endif /* __linux__ */
  180980. #endif /* PNG_SETJMP_SUPPORTED */
  180981. #ifdef BSD
  180982. #if ! JUCE_MAC
  180983. # include <strings.h>
  180984. #endif
  180985. #else
  180986. # include <string.h>
  180987. #endif
  180988. /* Other defines for things like memory and the like can go here. */
  180989. #ifdef PNG_INTERNAL
  180990. #include <stdlib.h>
  180991. /* The functions exported by PNG_EXTERN are PNG_INTERNAL functions, which
  180992. * aren't usually used outside the library (as far as I know), so it is
  180993. * debatable if they should be exported at all. In the future, when it is
  180994. * possible to have run-time registry of chunk-handling functions, some of
  180995. * these will be made available again.
  180996. #define PNG_EXTERN extern
  180997. */
  180998. #define PNG_EXTERN
  180999. /* Other defines specific to compilers can go here. Try to keep
  181000. * them inside an appropriate ifdef/endif pair for portability.
  181001. */
  181002. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  181003. # if defined(MACOS)
  181004. /* We need to check that <math.h> hasn't already been included earlier
  181005. * as it seems it doesn't agree with <fp.h>, yet we should really use
  181006. * <fp.h> if possible.
  181007. */
  181008. # if !defined(__MATH_H__) && !defined(__MATH_H) && !defined(__cmath__)
  181009. # include <fp.h>
  181010. # endif
  181011. # else
  181012. # include <math.h>
  181013. # endif
  181014. # if defined(_AMIGA) && defined(__SASC) && defined(_M68881)
  181015. /* Amiga SAS/C: We must include builtin FPU functions when compiling using
  181016. * MATH=68881
  181017. */
  181018. # include <m68881.h>
  181019. # endif
  181020. #endif
  181021. /* Codewarrior on NT has linking problems without this. */
  181022. #if (defined(__MWERKS__) && defined(WIN32)) || defined(__STDC__)
  181023. # define PNG_ALWAYS_EXTERN
  181024. #endif
  181025. /* This provides the non-ANSI (far) memory allocation routines. */
  181026. #if defined(__TURBOC__) && defined(__MSDOS__)
  181027. # include <mem.h>
  181028. # include <alloc.h>
  181029. #endif
  181030. /* I have no idea why is this necessary... */
  181031. #if defined(_MSC_VER) && (defined(WIN32) || defined(_Windows) || \
  181032. defined(_WINDOWS) || defined(_WIN32) || defined(__WIN32__))
  181033. # include <malloc.h>
  181034. #endif
  181035. /* This controls how fine the dithering gets. As this allocates
  181036. * a largish chunk of memory (32K), those who are not as concerned
  181037. * with dithering quality can decrease some or all of these.
  181038. */
  181039. #ifndef PNG_DITHER_RED_BITS
  181040. # define PNG_DITHER_RED_BITS 5
  181041. #endif
  181042. #ifndef PNG_DITHER_GREEN_BITS
  181043. # define PNG_DITHER_GREEN_BITS 5
  181044. #endif
  181045. #ifndef PNG_DITHER_BLUE_BITS
  181046. # define PNG_DITHER_BLUE_BITS 5
  181047. #endif
  181048. /* This controls how fine the gamma correction becomes when you
  181049. * are only interested in 8 bits anyway. Increasing this value
  181050. * results in more memory being used, and more pow() functions
  181051. * being called to fill in the gamma tables. Don't set this value
  181052. * less then 8, and even that may not work (I haven't tested it).
  181053. */
  181054. #ifndef PNG_MAX_GAMMA_8
  181055. # define PNG_MAX_GAMMA_8 11
  181056. #endif
  181057. /* This controls how much a difference in gamma we can tolerate before
  181058. * we actually start doing gamma conversion.
  181059. */
  181060. #ifndef PNG_GAMMA_THRESHOLD
  181061. # define PNG_GAMMA_THRESHOLD 0.05
  181062. #endif
  181063. #endif /* PNG_INTERNAL */
  181064. /* The following uses const char * instead of char * for error
  181065. * and warning message functions, so some compilers won't complain.
  181066. * If you do not want to use const, define PNG_NO_CONST here.
  181067. */
  181068. #ifndef PNG_NO_CONST
  181069. # define PNG_CONST const
  181070. #else
  181071. # define PNG_CONST
  181072. #endif
  181073. /* The following defines give you the ability to remove code from the
  181074. * library that you will not be using. I wish I could figure out how to
  181075. * automate this, but I can't do that without making it seriously hard
  181076. * on the users. So if you are not using an ability, change the #define
  181077. * to and #undef, and that part of the library will not be compiled. If
  181078. * your linker can't find a function, you may want to make sure the
  181079. * ability is defined here. Some of these depend upon some others being
  181080. * defined. I haven't figured out all the interactions here, so you may
  181081. * have to experiment awhile to get everything to compile. If you are
  181082. * creating or using a shared library, you probably shouldn't touch this,
  181083. * as it will affect the size of the structures, and this will cause bad
  181084. * things to happen if the library and/or application ever change.
  181085. */
  181086. /* Any features you will not be using can be undef'ed here */
  181087. /* GR-P, 0.96a: Set "*TRANSFORMS_SUPPORTED as default but allow user
  181088. * to turn it off with "*TRANSFORMS_NOT_SUPPORTED" or *PNG_NO_*_TRANSFORMS
  181089. * on the compile line, then pick and choose which ones to define without
  181090. * having to edit this file. It is safe to use the *TRANSFORMS_NOT_SUPPORTED
  181091. * if you only want to have a png-compliant reader/writer but don't need
  181092. * any of the extra transformations. This saves about 80 kbytes in a
  181093. * typical installation of the library. (PNG_NO_* form added in version
  181094. * 1.0.1c, for consistency)
  181095. */
  181096. /* The size of the png_text structure changed in libpng-1.0.6 when
  181097. * iTXt support was added. iTXt support was turned off by default through
  181098. * libpng-1.2.x, to support old apps that malloc the png_text structure
  181099. * instead of calling png_set_text() and letting libpng malloc it. It
  181100. * was turned on by default in libpng-1.3.0.
  181101. */
  181102. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181103. # ifndef PNG_NO_iTXt_SUPPORTED
  181104. # define PNG_NO_iTXt_SUPPORTED
  181105. # endif
  181106. # ifndef PNG_NO_READ_iTXt
  181107. # define PNG_NO_READ_iTXt
  181108. # endif
  181109. # ifndef PNG_NO_WRITE_iTXt
  181110. # define PNG_NO_WRITE_iTXt
  181111. # endif
  181112. #endif
  181113. #if !defined(PNG_NO_iTXt_SUPPORTED)
  181114. # if !defined(PNG_READ_iTXt_SUPPORTED) && !defined(PNG_NO_READ_iTXt)
  181115. # define PNG_READ_iTXt
  181116. # endif
  181117. # if !defined(PNG_WRITE_iTXt_SUPPORTED) && !defined(PNG_NO_WRITE_iTXt)
  181118. # define PNG_WRITE_iTXt
  181119. # endif
  181120. #endif
  181121. /* The following support, added after version 1.0.0, can be turned off here en
  181122. * masse by defining PNG_LEGACY_SUPPORTED in case you need binary compatibility
  181123. * with old applications that require the length of png_struct and png_info
  181124. * to remain unchanged.
  181125. */
  181126. #ifdef PNG_LEGACY_SUPPORTED
  181127. # define PNG_NO_FREE_ME
  181128. # define PNG_NO_READ_UNKNOWN_CHUNKS
  181129. # define PNG_NO_WRITE_UNKNOWN_CHUNKS
  181130. # define PNG_NO_READ_USER_CHUNKS
  181131. # define PNG_NO_READ_iCCP
  181132. # define PNG_NO_WRITE_iCCP
  181133. # define PNG_NO_READ_iTXt
  181134. # define PNG_NO_WRITE_iTXt
  181135. # define PNG_NO_READ_sCAL
  181136. # define PNG_NO_WRITE_sCAL
  181137. # define PNG_NO_READ_sPLT
  181138. # define PNG_NO_WRITE_sPLT
  181139. # define PNG_NO_INFO_IMAGE
  181140. # define PNG_NO_READ_RGB_TO_GRAY
  181141. # define PNG_NO_READ_USER_TRANSFORM
  181142. # define PNG_NO_WRITE_USER_TRANSFORM
  181143. # define PNG_NO_USER_MEM
  181144. # define PNG_NO_READ_EMPTY_PLTE
  181145. # define PNG_NO_MNG_FEATURES
  181146. # define PNG_NO_FIXED_POINT_SUPPORTED
  181147. #endif
  181148. /* Ignore attempt to turn off both floating and fixed point support */
  181149. #if !defined(PNG_FLOATING_POINT_SUPPORTED) || \
  181150. !defined(PNG_NO_FIXED_POINT_SUPPORTED)
  181151. # define PNG_FIXED_POINT_SUPPORTED
  181152. #endif
  181153. #ifndef PNG_NO_FREE_ME
  181154. # define PNG_FREE_ME_SUPPORTED
  181155. #endif
  181156. #if defined(PNG_READ_SUPPORTED)
  181157. #if !defined(PNG_READ_TRANSFORMS_NOT_SUPPORTED) && \
  181158. !defined(PNG_NO_READ_TRANSFORMS)
  181159. # define PNG_READ_TRANSFORMS_SUPPORTED
  181160. #endif
  181161. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  181162. # ifndef PNG_NO_READ_EXPAND
  181163. # define PNG_READ_EXPAND_SUPPORTED
  181164. # endif
  181165. # ifndef PNG_NO_READ_SHIFT
  181166. # define PNG_READ_SHIFT_SUPPORTED
  181167. # endif
  181168. # ifndef PNG_NO_READ_PACK
  181169. # define PNG_READ_PACK_SUPPORTED
  181170. # endif
  181171. # ifndef PNG_NO_READ_BGR
  181172. # define PNG_READ_BGR_SUPPORTED
  181173. # endif
  181174. # ifndef PNG_NO_READ_SWAP
  181175. # define PNG_READ_SWAP_SUPPORTED
  181176. # endif
  181177. # ifndef PNG_NO_READ_PACKSWAP
  181178. # define PNG_READ_PACKSWAP_SUPPORTED
  181179. # endif
  181180. # ifndef PNG_NO_READ_INVERT
  181181. # define PNG_READ_INVERT_SUPPORTED
  181182. # endif
  181183. # ifndef PNG_NO_READ_DITHER
  181184. # define PNG_READ_DITHER_SUPPORTED
  181185. # endif
  181186. # ifndef PNG_NO_READ_BACKGROUND
  181187. # define PNG_READ_BACKGROUND_SUPPORTED
  181188. # endif
  181189. # ifndef PNG_NO_READ_16_TO_8
  181190. # define PNG_READ_16_TO_8_SUPPORTED
  181191. # endif
  181192. # ifndef PNG_NO_READ_FILLER
  181193. # define PNG_READ_FILLER_SUPPORTED
  181194. # endif
  181195. # ifndef PNG_NO_READ_GAMMA
  181196. # define PNG_READ_GAMMA_SUPPORTED
  181197. # endif
  181198. # ifndef PNG_NO_READ_GRAY_TO_RGB
  181199. # define PNG_READ_GRAY_TO_RGB_SUPPORTED
  181200. # endif
  181201. # ifndef PNG_NO_READ_SWAP_ALPHA
  181202. # define PNG_READ_SWAP_ALPHA_SUPPORTED
  181203. # endif
  181204. # ifndef PNG_NO_READ_INVERT_ALPHA
  181205. # define PNG_READ_INVERT_ALPHA_SUPPORTED
  181206. # endif
  181207. # ifndef PNG_NO_READ_STRIP_ALPHA
  181208. # define PNG_READ_STRIP_ALPHA_SUPPORTED
  181209. # endif
  181210. # ifndef PNG_NO_READ_USER_TRANSFORM
  181211. # define PNG_READ_USER_TRANSFORM_SUPPORTED
  181212. # endif
  181213. # ifndef PNG_NO_READ_RGB_TO_GRAY
  181214. # define PNG_READ_RGB_TO_GRAY_SUPPORTED
  181215. # endif
  181216. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  181217. #if !defined(PNG_NO_PROGRESSIVE_READ) && \
  181218. !defined(PNG_PROGRESSIVE_READ_SUPPORTED) /* if you don't do progressive */
  181219. # define PNG_PROGRESSIVE_READ_SUPPORTED /* reading. This is not talking */
  181220. #endif /* about interlacing capability! You'll */
  181221. /* still have interlacing unless you change the following line: */
  181222. #define PNG_READ_INTERLACING_SUPPORTED /* required in PNG-compliant decoders */
  181223. #ifndef PNG_NO_READ_COMPOSITE_NODIV
  181224. # ifndef PNG_NO_READ_COMPOSITED_NODIV /* libpng-1.0.x misspelling */
  181225. # define PNG_READ_COMPOSITE_NODIV_SUPPORTED /* well tested on Intel, SGI */
  181226. # endif
  181227. #endif
  181228. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181229. /* Deprecated, will be removed from version 2.0.0.
  181230. Use PNG_MNG_FEATURES_SUPPORTED instead. */
  181231. #ifndef PNG_NO_READ_EMPTY_PLTE
  181232. # define PNG_READ_EMPTY_PLTE_SUPPORTED
  181233. #endif
  181234. #endif
  181235. #endif /* PNG_READ_SUPPORTED */
  181236. #if defined(PNG_WRITE_SUPPORTED)
  181237. # if !defined(PNG_WRITE_TRANSFORMS_NOT_SUPPORTED) && \
  181238. !defined(PNG_NO_WRITE_TRANSFORMS)
  181239. # define PNG_WRITE_TRANSFORMS_SUPPORTED
  181240. #endif
  181241. #ifdef PNG_WRITE_TRANSFORMS_SUPPORTED
  181242. # ifndef PNG_NO_WRITE_SHIFT
  181243. # define PNG_WRITE_SHIFT_SUPPORTED
  181244. # endif
  181245. # ifndef PNG_NO_WRITE_PACK
  181246. # define PNG_WRITE_PACK_SUPPORTED
  181247. # endif
  181248. # ifndef PNG_NO_WRITE_BGR
  181249. # define PNG_WRITE_BGR_SUPPORTED
  181250. # endif
  181251. # ifndef PNG_NO_WRITE_SWAP
  181252. # define PNG_WRITE_SWAP_SUPPORTED
  181253. # endif
  181254. # ifndef PNG_NO_WRITE_PACKSWAP
  181255. # define PNG_WRITE_PACKSWAP_SUPPORTED
  181256. # endif
  181257. # ifndef PNG_NO_WRITE_INVERT
  181258. # define PNG_WRITE_INVERT_SUPPORTED
  181259. # endif
  181260. # ifndef PNG_NO_WRITE_FILLER
  181261. # define PNG_WRITE_FILLER_SUPPORTED /* same as WRITE_STRIP_ALPHA */
  181262. # endif
  181263. # ifndef PNG_NO_WRITE_SWAP_ALPHA
  181264. # define PNG_WRITE_SWAP_ALPHA_SUPPORTED
  181265. # endif
  181266. # ifndef PNG_NO_WRITE_INVERT_ALPHA
  181267. # define PNG_WRITE_INVERT_ALPHA_SUPPORTED
  181268. # endif
  181269. # ifndef PNG_NO_WRITE_USER_TRANSFORM
  181270. # define PNG_WRITE_USER_TRANSFORM_SUPPORTED
  181271. # endif
  181272. #endif /* PNG_WRITE_TRANSFORMS_SUPPORTED */
  181273. #if !defined(PNG_NO_WRITE_INTERLACING_SUPPORTED) && \
  181274. !defined(PNG_WRITE_INTERLACING_SUPPORTED)
  181275. #define PNG_WRITE_INTERLACING_SUPPORTED /* not required for PNG-compliant
  181276. encoders, but can cause trouble
  181277. if left undefined */
  181278. #endif
  181279. #if !defined(PNG_NO_WRITE_WEIGHTED_FILTER) && \
  181280. !defined(PNG_WRITE_WEIGHTED_FILTER) && \
  181281. defined(PNG_FLOATING_POINT_SUPPORTED)
  181282. # define PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
  181283. #endif
  181284. #ifndef PNG_NO_WRITE_FLUSH
  181285. # define PNG_WRITE_FLUSH_SUPPORTED
  181286. #endif
  181287. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181288. /* Deprecated, see PNG_MNG_FEATURES_SUPPORTED, above */
  181289. #ifndef PNG_NO_WRITE_EMPTY_PLTE
  181290. # define PNG_WRITE_EMPTY_PLTE_SUPPORTED
  181291. #endif
  181292. #endif
  181293. #endif /* PNG_WRITE_SUPPORTED */
  181294. #ifndef PNG_1_0_X
  181295. # ifndef PNG_NO_ERROR_NUMBERS
  181296. # define PNG_ERROR_NUMBERS_SUPPORTED
  181297. # endif
  181298. #endif /* PNG_1_0_X */
  181299. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  181300. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  181301. # ifndef PNG_NO_USER_TRANSFORM_PTR
  181302. # define PNG_USER_TRANSFORM_PTR_SUPPORTED
  181303. # endif
  181304. #endif
  181305. #ifndef PNG_NO_STDIO
  181306. # define PNG_TIME_RFC1123_SUPPORTED
  181307. #endif
  181308. /* This adds extra functions in pngget.c for accessing data from the
  181309. * info pointer (added in version 0.99)
  181310. * png_get_image_width()
  181311. * png_get_image_height()
  181312. * png_get_bit_depth()
  181313. * png_get_color_type()
  181314. * png_get_compression_type()
  181315. * png_get_filter_type()
  181316. * png_get_interlace_type()
  181317. * png_get_pixel_aspect_ratio()
  181318. * png_get_pixels_per_meter()
  181319. * png_get_x_offset_pixels()
  181320. * png_get_y_offset_pixels()
  181321. * png_get_x_offset_microns()
  181322. * png_get_y_offset_microns()
  181323. */
  181324. #if !defined(PNG_NO_EASY_ACCESS) && !defined(PNG_EASY_ACCESS_SUPPORTED)
  181325. # define PNG_EASY_ACCESS_SUPPORTED
  181326. #endif
  181327. /* PNG_ASSEMBLER_CODE was enabled by default in version 1.2.0
  181328. * and removed from version 1.2.20. The following will be removed
  181329. * from libpng-1.4.0
  181330. */
  181331. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_OPTIMIZED_CODE)
  181332. # ifndef PNG_OPTIMIZED_CODE_SUPPORTED
  181333. # define PNG_OPTIMIZED_CODE_SUPPORTED
  181334. # endif
  181335. #endif
  181336. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_ASSEMBLER_CODE)
  181337. # ifndef PNG_ASSEMBLER_CODE_SUPPORTED
  181338. # define PNG_ASSEMBLER_CODE_SUPPORTED
  181339. # endif
  181340. # if defined(__GNUC__) && defined(__x86_64__) && (__GNUC__ < 4)
  181341. /* work around 64-bit gcc compiler bugs in gcc-3.x */
  181342. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181343. # define PNG_NO_MMX_CODE
  181344. # endif
  181345. # endif
  181346. # if defined(__APPLE__)
  181347. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181348. # define PNG_NO_MMX_CODE
  181349. # endif
  181350. # endif
  181351. # if (defined(__MWERKS__) && ((__MWERKS__ < 0x0900) || macintosh))
  181352. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181353. # define PNG_NO_MMX_CODE
  181354. # endif
  181355. # endif
  181356. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181357. # define PNG_MMX_CODE_SUPPORTED
  181358. # endif
  181359. #endif
  181360. /* end of obsolete code to be removed from libpng-1.4.0 */
  181361. #if !defined(PNG_1_0_X)
  181362. #if !defined(PNG_NO_USER_MEM) && !defined(PNG_USER_MEM_SUPPORTED)
  181363. # define PNG_USER_MEM_SUPPORTED
  181364. #endif
  181365. #endif /* PNG_1_0_X */
  181366. /* Added at libpng-1.2.6 */
  181367. #if !defined(PNG_1_0_X)
  181368. #ifndef PNG_SET_USER_LIMITS_SUPPORTED
  181369. #if !defined(PNG_NO_SET_USER_LIMITS) && !defined(PNG_SET_USER_LIMITS_SUPPORTED)
  181370. # define PNG_SET_USER_LIMITS_SUPPORTED
  181371. #endif
  181372. #endif
  181373. #endif /* PNG_1_0_X */
  181374. /* Added at libpng-1.0.16 and 1.2.6. To accept all valid PNGS no matter
  181375. * how large, set these limits to 0x7fffffffL
  181376. */
  181377. #ifndef PNG_USER_WIDTH_MAX
  181378. # define PNG_USER_WIDTH_MAX 1000000L
  181379. #endif
  181380. #ifndef PNG_USER_HEIGHT_MAX
  181381. # define PNG_USER_HEIGHT_MAX 1000000L
  181382. #endif
  181383. /* These are currently experimental features, define them if you want */
  181384. /* very little testing */
  181385. /*
  181386. #ifdef PNG_READ_SUPPORTED
  181387. # ifndef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  181388. # define PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  181389. # endif
  181390. #endif
  181391. */
  181392. /* This is only for PowerPC big-endian and 680x0 systems */
  181393. /* some testing */
  181394. /*
  181395. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  181396. # define PNG_READ_BIG_ENDIAN_SUPPORTED
  181397. #endif
  181398. */
  181399. /* Buggy compilers (e.g., gcc 2.7.2.2) need this */
  181400. /*
  181401. #define PNG_NO_POINTER_INDEXING
  181402. */
  181403. /* These functions are turned off by default, as they will be phased out. */
  181404. /*
  181405. #define PNG_USELESS_TESTS_SUPPORTED
  181406. #define PNG_CORRECT_PALETTE_SUPPORTED
  181407. */
  181408. /* Any chunks you are not interested in, you can undef here. The
  181409. * ones that allocate memory may be expecially important (hIST,
  181410. * tEXt, zTXt, tRNS, pCAL). Others will just save time and make png_info
  181411. * a bit smaller.
  181412. */
  181413. #if defined(PNG_READ_SUPPORTED) && \
  181414. !defined(PNG_READ_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  181415. !defined(PNG_NO_READ_ANCILLARY_CHUNKS)
  181416. # define PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  181417. #endif
  181418. #if defined(PNG_WRITE_SUPPORTED) && \
  181419. !defined(PNG_WRITE_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  181420. !defined(PNG_NO_WRITE_ANCILLARY_CHUNKS)
  181421. # define PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  181422. #endif
  181423. #ifdef PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  181424. #ifdef PNG_NO_READ_TEXT
  181425. # define PNG_NO_READ_iTXt
  181426. # define PNG_NO_READ_tEXt
  181427. # define PNG_NO_READ_zTXt
  181428. #endif
  181429. #ifndef PNG_NO_READ_bKGD
  181430. # define PNG_READ_bKGD_SUPPORTED
  181431. # define PNG_bKGD_SUPPORTED
  181432. #endif
  181433. #ifndef PNG_NO_READ_cHRM
  181434. # define PNG_READ_cHRM_SUPPORTED
  181435. # define PNG_cHRM_SUPPORTED
  181436. #endif
  181437. #ifndef PNG_NO_READ_gAMA
  181438. # define PNG_READ_gAMA_SUPPORTED
  181439. # define PNG_gAMA_SUPPORTED
  181440. #endif
  181441. #ifndef PNG_NO_READ_hIST
  181442. # define PNG_READ_hIST_SUPPORTED
  181443. # define PNG_hIST_SUPPORTED
  181444. #endif
  181445. #ifndef PNG_NO_READ_iCCP
  181446. # define PNG_READ_iCCP_SUPPORTED
  181447. # define PNG_iCCP_SUPPORTED
  181448. #endif
  181449. #ifndef PNG_NO_READ_iTXt
  181450. # ifndef PNG_READ_iTXt_SUPPORTED
  181451. # define PNG_READ_iTXt_SUPPORTED
  181452. # endif
  181453. # ifndef PNG_iTXt_SUPPORTED
  181454. # define PNG_iTXt_SUPPORTED
  181455. # endif
  181456. #endif
  181457. #ifndef PNG_NO_READ_oFFs
  181458. # define PNG_READ_oFFs_SUPPORTED
  181459. # define PNG_oFFs_SUPPORTED
  181460. #endif
  181461. #ifndef PNG_NO_READ_pCAL
  181462. # define PNG_READ_pCAL_SUPPORTED
  181463. # define PNG_pCAL_SUPPORTED
  181464. #endif
  181465. #ifndef PNG_NO_READ_sCAL
  181466. # define PNG_READ_sCAL_SUPPORTED
  181467. # define PNG_sCAL_SUPPORTED
  181468. #endif
  181469. #ifndef PNG_NO_READ_pHYs
  181470. # define PNG_READ_pHYs_SUPPORTED
  181471. # define PNG_pHYs_SUPPORTED
  181472. #endif
  181473. #ifndef PNG_NO_READ_sBIT
  181474. # define PNG_READ_sBIT_SUPPORTED
  181475. # define PNG_sBIT_SUPPORTED
  181476. #endif
  181477. #ifndef PNG_NO_READ_sPLT
  181478. # define PNG_READ_sPLT_SUPPORTED
  181479. # define PNG_sPLT_SUPPORTED
  181480. #endif
  181481. #ifndef PNG_NO_READ_sRGB
  181482. # define PNG_READ_sRGB_SUPPORTED
  181483. # define PNG_sRGB_SUPPORTED
  181484. #endif
  181485. #ifndef PNG_NO_READ_tEXt
  181486. # define PNG_READ_tEXt_SUPPORTED
  181487. # define PNG_tEXt_SUPPORTED
  181488. #endif
  181489. #ifndef PNG_NO_READ_tIME
  181490. # define PNG_READ_tIME_SUPPORTED
  181491. # define PNG_tIME_SUPPORTED
  181492. #endif
  181493. #ifndef PNG_NO_READ_tRNS
  181494. # define PNG_READ_tRNS_SUPPORTED
  181495. # define PNG_tRNS_SUPPORTED
  181496. #endif
  181497. #ifndef PNG_NO_READ_zTXt
  181498. # define PNG_READ_zTXt_SUPPORTED
  181499. # define PNG_zTXt_SUPPORTED
  181500. #endif
  181501. #ifndef PNG_NO_READ_UNKNOWN_CHUNKS
  181502. # define PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
  181503. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  181504. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  181505. # endif
  181506. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  181507. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181508. # endif
  181509. #endif
  181510. #if !defined(PNG_NO_READ_USER_CHUNKS) && \
  181511. defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  181512. # define PNG_READ_USER_CHUNKS_SUPPORTED
  181513. # define PNG_USER_CHUNKS_SUPPORTED
  181514. # ifdef PNG_NO_READ_UNKNOWN_CHUNKS
  181515. # undef PNG_NO_READ_UNKNOWN_CHUNKS
  181516. # endif
  181517. # ifdef PNG_NO_HANDLE_AS_UNKNOWN
  181518. # undef PNG_NO_HANDLE_AS_UNKNOWN
  181519. # endif
  181520. #endif
  181521. #ifndef PNG_NO_READ_OPT_PLTE
  181522. # define PNG_READ_OPT_PLTE_SUPPORTED /* only affects support of the */
  181523. #endif /* optional PLTE chunk in RGB and RGBA images */
  181524. #if defined(PNG_READ_iTXt_SUPPORTED) || defined(PNG_READ_tEXt_SUPPORTED) || \
  181525. defined(PNG_READ_zTXt_SUPPORTED)
  181526. # define PNG_READ_TEXT_SUPPORTED
  181527. # define PNG_TEXT_SUPPORTED
  181528. #endif
  181529. #endif /* PNG_READ_ANCILLARY_CHUNKS_SUPPORTED */
  181530. #ifdef PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  181531. #ifdef PNG_NO_WRITE_TEXT
  181532. # define PNG_NO_WRITE_iTXt
  181533. # define PNG_NO_WRITE_tEXt
  181534. # define PNG_NO_WRITE_zTXt
  181535. #endif
  181536. #ifndef PNG_NO_WRITE_bKGD
  181537. # define PNG_WRITE_bKGD_SUPPORTED
  181538. # ifndef PNG_bKGD_SUPPORTED
  181539. # define PNG_bKGD_SUPPORTED
  181540. # endif
  181541. #endif
  181542. #ifndef PNG_NO_WRITE_cHRM
  181543. # define PNG_WRITE_cHRM_SUPPORTED
  181544. # ifndef PNG_cHRM_SUPPORTED
  181545. # define PNG_cHRM_SUPPORTED
  181546. # endif
  181547. #endif
  181548. #ifndef PNG_NO_WRITE_gAMA
  181549. # define PNG_WRITE_gAMA_SUPPORTED
  181550. # ifndef PNG_gAMA_SUPPORTED
  181551. # define PNG_gAMA_SUPPORTED
  181552. # endif
  181553. #endif
  181554. #ifndef PNG_NO_WRITE_hIST
  181555. # define PNG_WRITE_hIST_SUPPORTED
  181556. # ifndef PNG_hIST_SUPPORTED
  181557. # define PNG_hIST_SUPPORTED
  181558. # endif
  181559. #endif
  181560. #ifndef PNG_NO_WRITE_iCCP
  181561. # define PNG_WRITE_iCCP_SUPPORTED
  181562. # ifndef PNG_iCCP_SUPPORTED
  181563. # define PNG_iCCP_SUPPORTED
  181564. # endif
  181565. #endif
  181566. #ifndef PNG_NO_WRITE_iTXt
  181567. # ifndef PNG_WRITE_iTXt_SUPPORTED
  181568. # define PNG_WRITE_iTXt_SUPPORTED
  181569. # endif
  181570. # ifndef PNG_iTXt_SUPPORTED
  181571. # define PNG_iTXt_SUPPORTED
  181572. # endif
  181573. #endif
  181574. #ifndef PNG_NO_WRITE_oFFs
  181575. # define PNG_WRITE_oFFs_SUPPORTED
  181576. # ifndef PNG_oFFs_SUPPORTED
  181577. # define PNG_oFFs_SUPPORTED
  181578. # endif
  181579. #endif
  181580. #ifndef PNG_NO_WRITE_pCAL
  181581. # define PNG_WRITE_pCAL_SUPPORTED
  181582. # ifndef PNG_pCAL_SUPPORTED
  181583. # define PNG_pCAL_SUPPORTED
  181584. # endif
  181585. #endif
  181586. #ifndef PNG_NO_WRITE_sCAL
  181587. # define PNG_WRITE_sCAL_SUPPORTED
  181588. # ifndef PNG_sCAL_SUPPORTED
  181589. # define PNG_sCAL_SUPPORTED
  181590. # endif
  181591. #endif
  181592. #ifndef PNG_NO_WRITE_pHYs
  181593. # define PNG_WRITE_pHYs_SUPPORTED
  181594. # ifndef PNG_pHYs_SUPPORTED
  181595. # define PNG_pHYs_SUPPORTED
  181596. # endif
  181597. #endif
  181598. #ifndef PNG_NO_WRITE_sBIT
  181599. # define PNG_WRITE_sBIT_SUPPORTED
  181600. # ifndef PNG_sBIT_SUPPORTED
  181601. # define PNG_sBIT_SUPPORTED
  181602. # endif
  181603. #endif
  181604. #ifndef PNG_NO_WRITE_sPLT
  181605. # define PNG_WRITE_sPLT_SUPPORTED
  181606. # ifndef PNG_sPLT_SUPPORTED
  181607. # define PNG_sPLT_SUPPORTED
  181608. # endif
  181609. #endif
  181610. #ifndef PNG_NO_WRITE_sRGB
  181611. # define PNG_WRITE_sRGB_SUPPORTED
  181612. # ifndef PNG_sRGB_SUPPORTED
  181613. # define PNG_sRGB_SUPPORTED
  181614. # endif
  181615. #endif
  181616. #ifndef PNG_NO_WRITE_tEXt
  181617. # define PNG_WRITE_tEXt_SUPPORTED
  181618. # ifndef PNG_tEXt_SUPPORTED
  181619. # define PNG_tEXt_SUPPORTED
  181620. # endif
  181621. #endif
  181622. #ifndef PNG_NO_WRITE_tIME
  181623. # define PNG_WRITE_tIME_SUPPORTED
  181624. # ifndef PNG_tIME_SUPPORTED
  181625. # define PNG_tIME_SUPPORTED
  181626. # endif
  181627. #endif
  181628. #ifndef PNG_NO_WRITE_tRNS
  181629. # define PNG_WRITE_tRNS_SUPPORTED
  181630. # ifndef PNG_tRNS_SUPPORTED
  181631. # define PNG_tRNS_SUPPORTED
  181632. # endif
  181633. #endif
  181634. #ifndef PNG_NO_WRITE_zTXt
  181635. # define PNG_WRITE_zTXt_SUPPORTED
  181636. # ifndef PNG_zTXt_SUPPORTED
  181637. # define PNG_zTXt_SUPPORTED
  181638. # endif
  181639. #endif
  181640. #ifndef PNG_NO_WRITE_UNKNOWN_CHUNKS
  181641. # define PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
  181642. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  181643. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  181644. # endif
  181645. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  181646. # ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181647. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181648. # endif
  181649. # endif
  181650. #endif
  181651. #if defined(PNG_WRITE_iTXt_SUPPORTED) || defined(PNG_WRITE_tEXt_SUPPORTED) || \
  181652. defined(PNG_WRITE_zTXt_SUPPORTED)
  181653. # define PNG_WRITE_TEXT_SUPPORTED
  181654. # ifndef PNG_TEXT_SUPPORTED
  181655. # define PNG_TEXT_SUPPORTED
  181656. # endif
  181657. #endif
  181658. #endif /* PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED */
  181659. /* Turn this off to disable png_read_png() and
  181660. * png_write_png() and leave the row_pointers member
  181661. * out of the info structure.
  181662. */
  181663. #ifndef PNG_NO_INFO_IMAGE
  181664. # define PNG_INFO_IMAGE_SUPPORTED
  181665. #endif
  181666. /* need the time information for reading tIME chunks */
  181667. #if defined(PNG_tIME_SUPPORTED)
  181668. # if !defined(_WIN32_WCE)
  181669. /* "time.h" functions are not supported on WindowsCE */
  181670. # include <time.h>
  181671. # endif
  181672. #endif
  181673. /* Some typedefs to get us started. These should be safe on most of the
  181674. * common platforms. The typedefs should be at least as large as the
  181675. * numbers suggest (a png_uint_32 must be at least 32 bits long), but they
  181676. * don't have to be exactly that size. Some compilers dislike passing
  181677. * unsigned shorts as function parameters, so you may be better off using
  181678. * unsigned int for png_uint_16. Likewise, for 64-bit systems, you may
  181679. * want to have unsigned int for png_uint_32 instead of unsigned long.
  181680. */
  181681. typedef unsigned long png_uint_32;
  181682. typedef long png_int_32;
  181683. typedef unsigned short png_uint_16;
  181684. typedef short png_int_16;
  181685. typedef unsigned char png_byte;
  181686. /* This is usually size_t. It is typedef'ed just in case you need it to
  181687. change (I'm not sure if you will or not, so I thought I'd be safe) */
  181688. #ifdef PNG_SIZE_T
  181689. typedef PNG_SIZE_T png_size_t;
  181690. # define png_sizeof(x) png_convert_size(sizeof (x))
  181691. #else
  181692. typedef size_t png_size_t;
  181693. # define png_sizeof(x) sizeof (x)
  181694. #endif
  181695. /* The following is needed for medium model support. It cannot be in the
  181696. * PNG_INTERNAL section. Needs modification for other compilers besides
  181697. * MSC. Model independent support declares all arrays and pointers to be
  181698. * large using the far keyword. The zlib version used must also support
  181699. * model independent data. As of version zlib 1.0.4, the necessary changes
  181700. * have been made in zlib. The USE_FAR_KEYWORD define triggers other
  181701. * changes that are needed. (Tim Wegner)
  181702. */
  181703. /* Separate compiler dependencies (problem here is that zlib.h always
  181704. defines FAR. (SJT) */
  181705. #ifdef __BORLANDC__
  181706. # if defined(__LARGE__) || defined(__HUGE__) || defined(__COMPACT__)
  181707. # define LDATA 1
  181708. # else
  181709. # define LDATA 0
  181710. # endif
  181711. /* GRR: why is Cygwin in here? Cygwin is not Borland C... */
  181712. # if !defined(__WIN32__) && !defined(__FLAT__) && !defined(__CYGWIN__)
  181713. # define PNG_MAX_MALLOC_64K
  181714. # if (LDATA != 1)
  181715. # ifndef FAR
  181716. # define FAR __far
  181717. # endif
  181718. # define USE_FAR_KEYWORD
  181719. # endif /* LDATA != 1 */
  181720. /* Possibly useful for moving data out of default segment.
  181721. * Uncomment it if you want. Could also define FARDATA as
  181722. * const if your compiler supports it. (SJT)
  181723. # define FARDATA FAR
  181724. */
  181725. # endif /* __WIN32__, __FLAT__, __CYGWIN__ */
  181726. #endif /* __BORLANDC__ */
  181727. /* Suggest testing for specific compiler first before testing for
  181728. * FAR. The Watcom compiler defines both __MEDIUM__ and M_I86MM,
  181729. * making reliance oncertain keywords suspect. (SJT)
  181730. */
  181731. /* MSC Medium model */
  181732. #if defined(FAR)
  181733. # if defined(M_I86MM)
  181734. # define USE_FAR_KEYWORD
  181735. # define FARDATA FAR
  181736. # include <dos.h>
  181737. # endif
  181738. #endif
  181739. /* SJT: default case */
  181740. #ifndef FAR
  181741. # define FAR
  181742. #endif
  181743. /* At this point FAR is always defined */
  181744. #ifndef FARDATA
  181745. # define FARDATA
  181746. #endif
  181747. /* Typedef for floating-point numbers that are converted
  181748. to fixed-point with a multiple of 100,000, e.g., int_gamma */
  181749. typedef png_int_32 png_fixed_point;
  181750. /* Add typedefs for pointers */
  181751. typedef void FAR * png_voidp;
  181752. typedef png_byte FAR * png_bytep;
  181753. typedef png_uint_32 FAR * png_uint_32p;
  181754. typedef png_int_32 FAR * png_int_32p;
  181755. typedef png_uint_16 FAR * png_uint_16p;
  181756. typedef png_int_16 FAR * png_int_16p;
  181757. typedef PNG_CONST char FAR * png_const_charp;
  181758. typedef char FAR * png_charp;
  181759. typedef png_fixed_point FAR * png_fixed_point_p;
  181760. #ifndef PNG_NO_STDIO
  181761. #if defined(_WIN32_WCE)
  181762. typedef HANDLE png_FILE_p;
  181763. #else
  181764. typedef FILE * png_FILE_p;
  181765. #endif
  181766. #endif
  181767. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181768. typedef double FAR * png_doublep;
  181769. #endif
  181770. /* Pointers to pointers; i.e. arrays */
  181771. typedef png_byte FAR * FAR * png_bytepp;
  181772. typedef png_uint_32 FAR * FAR * png_uint_32pp;
  181773. typedef png_int_32 FAR * FAR * png_int_32pp;
  181774. typedef png_uint_16 FAR * FAR * png_uint_16pp;
  181775. typedef png_int_16 FAR * FAR * png_int_16pp;
  181776. typedef PNG_CONST char FAR * FAR * png_const_charpp;
  181777. typedef char FAR * FAR * png_charpp;
  181778. typedef png_fixed_point FAR * FAR * png_fixed_point_pp;
  181779. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181780. typedef double FAR * FAR * png_doublepp;
  181781. #endif
  181782. /* Pointers to pointers to pointers; i.e., pointer to array */
  181783. typedef char FAR * FAR * FAR * png_charppp;
  181784. #if 0
  181785. /* SPC - Is this stuff deprecated? */
  181786. /* It'll be removed as of libpng-1.3.0 - GR-P */
  181787. /* libpng typedefs for types in zlib. If zlib changes
  181788. * or another compression library is used, then change these.
  181789. * Eliminates need to change all the source files.
  181790. */
  181791. typedef charf * png_zcharp;
  181792. typedef charf * FAR * png_zcharpp;
  181793. typedef z_stream FAR * png_zstreamp;
  181794. #endif /* (PNG_1_0_X) || defined(PNG_1_2_X) */
  181795. /*
  181796. * Define PNG_BUILD_DLL if the module being built is a Windows
  181797. * LIBPNG DLL.
  181798. *
  181799. * Define PNG_USE_DLL if you want to *link* to the Windows LIBPNG DLL.
  181800. * It is equivalent to Microsoft predefined macro _DLL that is
  181801. * automatically defined when you compile using the share
  181802. * version of the CRT (C Run-Time library)
  181803. *
  181804. * The cygwin mods make this behavior a little different:
  181805. * Define PNG_BUILD_DLL if you are building a dll for use with cygwin
  181806. * Define PNG_STATIC if you are building a static library for use with cygwin,
  181807. * -or- if you are building an application that you want to link to the
  181808. * static library.
  181809. * PNG_USE_DLL is defined by default (no user action needed) unless one of
  181810. * the other flags is defined.
  181811. */
  181812. #if !defined(PNG_DLL) && (defined(PNG_BUILD_DLL) || defined(PNG_USE_DLL))
  181813. # define PNG_DLL
  181814. #endif
  181815. /* If CYGWIN, then disallow GLOBAL ARRAYS unless building a static lib.
  181816. * When building a static lib, default to no GLOBAL ARRAYS, but allow
  181817. * command-line override
  181818. */
  181819. #if defined(__CYGWIN__)
  181820. # if !defined(PNG_STATIC)
  181821. # if defined(PNG_USE_GLOBAL_ARRAYS)
  181822. # undef PNG_USE_GLOBAL_ARRAYS
  181823. # endif
  181824. # if !defined(PNG_USE_LOCAL_ARRAYS)
  181825. # define PNG_USE_LOCAL_ARRAYS
  181826. # endif
  181827. # else
  181828. # if defined(PNG_USE_LOCAL_ARRAYS) || defined(PNG_NO_GLOBAL_ARRAYS)
  181829. # if defined(PNG_USE_GLOBAL_ARRAYS)
  181830. # undef PNG_USE_GLOBAL_ARRAYS
  181831. # endif
  181832. # endif
  181833. # endif
  181834. # if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  181835. # define PNG_USE_LOCAL_ARRAYS
  181836. # endif
  181837. #endif
  181838. /* Do not use global arrays (helps with building DLL's)
  181839. * They are no longer used in libpng itself, since version 1.0.5c,
  181840. * but might be required for some pre-1.0.5c applications.
  181841. */
  181842. #if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  181843. # if defined(PNG_NO_GLOBAL_ARRAYS) || \
  181844. (defined(__GNUC__) && defined(PNG_DLL)) || defined(_MSC_VER)
  181845. # define PNG_USE_LOCAL_ARRAYS
  181846. # else
  181847. # define PNG_USE_GLOBAL_ARRAYS
  181848. # endif
  181849. #endif
  181850. #if defined(__CYGWIN__)
  181851. # undef PNGAPI
  181852. # define PNGAPI __cdecl
  181853. # undef PNG_IMPEXP
  181854. # define PNG_IMPEXP
  181855. #endif
  181856. /* If you define PNGAPI, e.g., with compiler option "-DPNGAPI=__stdcall",
  181857. * you may get warnings regarding the linkage of png_zalloc and png_zfree.
  181858. * Don't ignore those warnings; you must also reset the default calling
  181859. * convention in your compiler to match your PNGAPI, and you must build
  181860. * zlib and your applications the same way you build libpng.
  181861. */
  181862. #if defined(__MINGW32__) && !defined(PNG_MODULEDEF)
  181863. # ifndef PNG_NO_MODULEDEF
  181864. # define PNG_NO_MODULEDEF
  181865. # endif
  181866. #endif
  181867. #if !defined(PNG_IMPEXP) && defined(PNG_BUILD_DLL) && !defined(PNG_NO_MODULEDEF)
  181868. # define PNG_IMPEXP
  181869. #endif
  181870. #if defined(PNG_DLL) || defined(_DLL) || defined(__DLL__ ) || \
  181871. (( defined(_Windows) || defined(_WINDOWS) || \
  181872. defined(WIN32) || defined(_WIN32) || defined(__WIN32__) ))
  181873. # ifndef PNGAPI
  181874. # if defined(__GNUC__) || (defined (_MSC_VER) && (_MSC_VER >= 800))
  181875. # define PNGAPI __cdecl
  181876. # else
  181877. # define PNGAPI _cdecl
  181878. # endif
  181879. # endif
  181880. # if !defined(PNG_IMPEXP) && (!defined(PNG_DLL) || \
  181881. 0 /* WINCOMPILER_WITH_NO_SUPPORT_FOR_DECLIMPEXP */)
  181882. # define PNG_IMPEXP
  181883. # endif
  181884. # if !defined(PNG_IMPEXP)
  181885. # define PNG_EXPORT_TYPE1(type,symbol) PNG_IMPEXP type PNGAPI symbol
  181886. # define PNG_EXPORT_TYPE2(type,symbol) type PNG_IMPEXP PNGAPI symbol
  181887. /* Borland/Microsoft */
  181888. # if defined(_MSC_VER) || defined(__BORLANDC__)
  181889. # if (_MSC_VER >= 800) || (__BORLANDC__ >= 0x500)
  181890. # define PNG_EXPORT PNG_EXPORT_TYPE1
  181891. # else
  181892. # define PNG_EXPORT PNG_EXPORT_TYPE2
  181893. # if defined(PNG_BUILD_DLL)
  181894. # define PNG_IMPEXP __export
  181895. # else
  181896. # define PNG_IMPEXP /*__import */ /* doesn't exist AFAIK in
  181897. VC++ */
  181898. # endif /* Exists in Borland C++ for
  181899. C++ classes (== huge) */
  181900. # endif
  181901. # endif
  181902. # if !defined(PNG_IMPEXP)
  181903. # if defined(PNG_BUILD_DLL)
  181904. # define PNG_IMPEXP __declspec(dllexport)
  181905. # else
  181906. # define PNG_IMPEXP __declspec(dllimport)
  181907. # endif
  181908. # endif
  181909. # endif /* PNG_IMPEXP */
  181910. #else /* !(DLL || non-cygwin WINDOWS) */
  181911. # if (defined(__IBMC__) || defined(__IBMCPP__)) && defined(__OS2__)
  181912. # ifndef PNGAPI
  181913. # define PNGAPI _System
  181914. # endif
  181915. # else
  181916. # if 0 /* ... other platforms, with other meanings */
  181917. # endif
  181918. # endif
  181919. #endif
  181920. #ifndef PNGAPI
  181921. # define PNGAPI
  181922. #endif
  181923. #ifndef PNG_IMPEXP
  181924. # define PNG_IMPEXP
  181925. #endif
  181926. #ifdef PNG_BUILDSYMS
  181927. # ifndef PNG_EXPORT
  181928. # define PNG_EXPORT(type,symbol) PNG_FUNCTION_EXPORT symbol END
  181929. # endif
  181930. # ifdef PNG_USE_GLOBAL_ARRAYS
  181931. # ifndef PNG_EXPORT_VAR
  181932. # define PNG_EXPORT_VAR(type) PNG_DATA_EXPORT
  181933. # endif
  181934. # endif
  181935. #endif
  181936. #ifndef PNG_EXPORT
  181937. # define PNG_EXPORT(type,symbol) PNG_IMPEXP type PNGAPI symbol
  181938. #endif
  181939. #ifdef PNG_USE_GLOBAL_ARRAYS
  181940. # ifndef PNG_EXPORT_VAR
  181941. # define PNG_EXPORT_VAR(type) extern PNG_IMPEXP type
  181942. # endif
  181943. #endif
  181944. /* User may want to use these so they are not in PNG_INTERNAL. Any library
  181945. * functions that are passed far data must be model independent.
  181946. */
  181947. #ifndef PNG_ABORT
  181948. # define PNG_ABORT() abort()
  181949. #endif
  181950. #ifdef PNG_SETJMP_SUPPORTED
  181951. # define png_jmpbuf(png_ptr) ((png_ptr)->jmpbuf)
  181952. #else
  181953. # define png_jmpbuf(png_ptr) \
  181954. (LIBPNG_WAS_COMPILED_WITH__PNG_SETJMP_NOT_SUPPORTED)
  181955. #endif
  181956. #if defined(USE_FAR_KEYWORD) /* memory model independent fns */
  181957. /* use this to make far-to-near assignments */
  181958. # define CHECK 1
  181959. # define NOCHECK 0
  181960. # define CVT_PTR(ptr) (png_far_to_near(png_ptr,ptr,CHECK))
  181961. # define CVT_PTR_NOCHECK(ptr) (png_far_to_near(png_ptr,ptr,NOCHECK))
  181962. # define png_snprintf _fsnprintf /* Added to v 1.2.19 */
  181963. # define png_strcpy _fstrcpy
  181964. # define png_strncpy _fstrncpy /* Added to v 1.2.6 */
  181965. # define png_strlen _fstrlen
  181966. # define png_memcmp _fmemcmp /* SJT: added */
  181967. # define png_memcpy _fmemcpy
  181968. # define png_memset _fmemset
  181969. #else /* use the usual functions */
  181970. # define CVT_PTR(ptr) (ptr)
  181971. # define CVT_PTR_NOCHECK(ptr) (ptr)
  181972. # ifndef PNG_NO_SNPRINTF
  181973. # ifdef _MSC_VER
  181974. # define png_snprintf _snprintf /* Added to v 1.2.19 */
  181975. # define png_snprintf2 _snprintf
  181976. # define png_snprintf6 _snprintf
  181977. # else
  181978. # define png_snprintf snprintf /* Added to v 1.2.19 */
  181979. # define png_snprintf2 snprintf
  181980. # define png_snprintf6 snprintf
  181981. # endif
  181982. # else
  181983. /* You don't have or don't want to use snprintf(). Caution: Using
  181984. * sprintf instead of snprintf exposes your application to accidental
  181985. * or malevolent buffer overflows. If you don't have snprintf()
  181986. * as a general rule you should provide one (you can get one from
  181987. * Portable OpenSSH). */
  181988. # define png_snprintf(s1,n,fmt,x1) sprintf(s1,fmt,x1)
  181989. # define png_snprintf2(s1,n,fmt,x1,x2) sprintf(s1,fmt,x1,x2)
  181990. # define png_snprintf6(s1,n,fmt,x1,x2,x3,x4,x5,x6) \
  181991. sprintf(s1,fmt,x1,x2,x3,x4,x5,x6)
  181992. # endif
  181993. # define png_strcpy strcpy
  181994. # define png_strncpy strncpy /* Added to v 1.2.6 */
  181995. # define png_strlen strlen
  181996. # define png_memcmp memcmp /* SJT: added */
  181997. # define png_memcpy memcpy
  181998. # define png_memset memset
  181999. #endif
  182000. /* End of memory model independent support */
  182001. /* Just a little check that someone hasn't tried to define something
  182002. * contradictory.
  182003. */
  182004. #if (PNG_ZBUF_SIZE > 65536L) && defined(PNG_MAX_MALLOC_64K)
  182005. # undef PNG_ZBUF_SIZE
  182006. # define PNG_ZBUF_SIZE 65536L
  182007. #endif
  182008. /* Added at libpng-1.2.8 */
  182009. #endif /* PNG_VERSION_INFO_ONLY */
  182010. #endif /* PNGCONF_H */
  182011. /*** End of inlined file: pngconf.h ***/
  182012. #ifdef _MSC_VER
  182013. #pragma warning (disable: 4996 4100)
  182014. #endif
  182015. /*
  182016. * Added at libpng-1.2.8 */
  182017. /* Ref MSDN: Private as priority over Special
  182018. * VS_FF_PRIVATEBUILD File *was not* built using standard release
  182019. * procedures. If this value is given, the StringFileInfo block must
  182020. * contain a PrivateBuild string.
  182021. *
  182022. * VS_FF_SPECIALBUILD File *was* built by the original company using
  182023. * standard release procedures but is a variation of the standard
  182024. * file of the same version number. If this value is given, the
  182025. * StringFileInfo block must contain a SpecialBuild string.
  182026. */
  182027. #if defined(PNG_USER_PRIVATEBUILD)
  182028. # define PNG_LIBPNG_BUILD_TYPE \
  182029. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_PRIVATE)
  182030. #else
  182031. # if defined(PNG_LIBPNG_SPECIALBUILD)
  182032. # define PNG_LIBPNG_BUILD_TYPE \
  182033. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_SPECIAL)
  182034. # else
  182035. # define PNG_LIBPNG_BUILD_TYPE (PNG_LIBPNG_BUILD_BASE_TYPE)
  182036. # endif
  182037. #endif
  182038. #ifndef PNG_VERSION_INFO_ONLY
  182039. /* Inhibit C++ name-mangling for libpng functions but not for system calls. */
  182040. #ifdef __cplusplus
  182041. //extern "C" {
  182042. #endif /* __cplusplus */
  182043. /* This file is arranged in several sections. The first section contains
  182044. * structure and type definitions. The second section contains the external
  182045. * library functions, while the third has the internal library functions,
  182046. * which applications aren't expected to use directly.
  182047. */
  182048. #ifndef PNG_NO_TYPECAST_NULL
  182049. #define int_p_NULL (int *)NULL
  182050. #define png_bytep_NULL (png_bytep)NULL
  182051. #define png_bytepp_NULL (png_bytepp)NULL
  182052. #define png_doublep_NULL (png_doublep)NULL
  182053. #define png_error_ptr_NULL (png_error_ptr)NULL
  182054. #define png_flush_ptr_NULL (png_flush_ptr)NULL
  182055. #define png_free_ptr_NULL (png_free_ptr)NULL
  182056. #define png_infopp_NULL (png_infopp)NULL
  182057. #define png_malloc_ptr_NULL (png_malloc_ptr)NULL
  182058. #define png_read_status_ptr_NULL (png_read_status_ptr)NULL
  182059. #define png_rw_ptr_NULL (png_rw_ptr)NULL
  182060. #define png_structp_NULL (png_structp)NULL
  182061. #define png_uint_16p_NULL (png_uint_16p)NULL
  182062. #define png_voidp_NULL (png_voidp)NULL
  182063. #define png_write_status_ptr_NULL (png_write_status_ptr)NULL
  182064. #else
  182065. #define int_p_NULL NULL
  182066. #define png_bytep_NULL NULL
  182067. #define png_bytepp_NULL NULL
  182068. #define png_doublep_NULL NULL
  182069. #define png_error_ptr_NULL NULL
  182070. #define png_flush_ptr_NULL NULL
  182071. #define png_free_ptr_NULL NULL
  182072. #define png_infopp_NULL NULL
  182073. #define png_malloc_ptr_NULL NULL
  182074. #define png_read_status_ptr_NULL NULL
  182075. #define png_rw_ptr_NULL NULL
  182076. #define png_structp_NULL NULL
  182077. #define png_uint_16p_NULL NULL
  182078. #define png_voidp_NULL NULL
  182079. #define png_write_status_ptr_NULL NULL
  182080. #endif
  182081. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  182082. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  182083. /* Version information for C files, stored in png.c. This had better match
  182084. * the version above.
  182085. */
  182086. #ifdef PNG_USE_GLOBAL_ARRAYS
  182087. PNG_EXPORT_VAR (PNG_CONST char) png_libpng_ver[18];
  182088. /* need room for 99.99.99beta99z */
  182089. #else
  182090. #define png_libpng_ver png_get_header_ver(NULL)
  182091. #endif
  182092. #ifdef PNG_USE_GLOBAL_ARRAYS
  182093. /* This was removed in version 1.0.5c */
  182094. /* Structures to facilitate easy interlacing. See png.c for more details */
  182095. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_start[7];
  182096. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_inc[7];
  182097. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_ystart[7];
  182098. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_yinc[7];
  182099. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_mask[7];
  182100. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_dsp_mask[7];
  182101. /* This isn't currently used. If you need it, see png.c for more details.
  182102. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_height[7];
  182103. */
  182104. #endif
  182105. #endif /* PNG_NO_EXTERN */
  182106. /* Three color definitions. The order of the red, green, and blue, (and the
  182107. * exact size) is not important, although the size of the fields need to
  182108. * be png_byte or png_uint_16 (as defined below).
  182109. */
  182110. typedef struct png_color_struct
  182111. {
  182112. png_byte red;
  182113. png_byte green;
  182114. png_byte blue;
  182115. } png_color;
  182116. typedef png_color FAR * png_colorp;
  182117. typedef png_color FAR * FAR * png_colorpp;
  182118. typedef struct png_color_16_struct
  182119. {
  182120. png_byte index; /* used for palette files */
  182121. png_uint_16 red; /* for use in red green blue files */
  182122. png_uint_16 green;
  182123. png_uint_16 blue;
  182124. png_uint_16 gray; /* for use in grayscale files */
  182125. } png_color_16;
  182126. typedef png_color_16 FAR * png_color_16p;
  182127. typedef png_color_16 FAR * FAR * png_color_16pp;
  182128. typedef struct png_color_8_struct
  182129. {
  182130. png_byte red; /* for use in red green blue files */
  182131. png_byte green;
  182132. png_byte blue;
  182133. png_byte gray; /* for use in grayscale files */
  182134. png_byte alpha; /* for alpha channel files */
  182135. } png_color_8;
  182136. typedef png_color_8 FAR * png_color_8p;
  182137. typedef png_color_8 FAR * FAR * png_color_8pp;
  182138. /*
  182139. * The following two structures are used for the in-core representation
  182140. * of sPLT chunks.
  182141. */
  182142. typedef struct png_sPLT_entry_struct
  182143. {
  182144. png_uint_16 red;
  182145. png_uint_16 green;
  182146. png_uint_16 blue;
  182147. png_uint_16 alpha;
  182148. png_uint_16 frequency;
  182149. } png_sPLT_entry;
  182150. typedef png_sPLT_entry FAR * png_sPLT_entryp;
  182151. typedef png_sPLT_entry FAR * FAR * png_sPLT_entrypp;
  182152. /* When the depth of the sPLT palette is 8 bits, the color and alpha samples
  182153. * occupy the LSB of their respective members, and the MSB of each member
  182154. * is zero-filled. The frequency member always occupies the full 16 bits.
  182155. */
  182156. typedef struct png_sPLT_struct
  182157. {
  182158. png_charp name; /* palette name */
  182159. png_byte depth; /* depth of palette samples */
  182160. png_sPLT_entryp entries; /* palette entries */
  182161. png_int_32 nentries; /* number of palette entries */
  182162. } png_sPLT_t;
  182163. typedef png_sPLT_t FAR * png_sPLT_tp;
  182164. typedef png_sPLT_t FAR * FAR * png_sPLT_tpp;
  182165. #ifdef PNG_TEXT_SUPPORTED
  182166. /* png_text holds the contents of a text/ztxt/itxt chunk in a PNG file,
  182167. * and whether that contents is compressed or not. The "key" field
  182168. * points to a regular zero-terminated C string. The "text", "lang", and
  182169. * "lang_key" fields can be regular C strings, empty strings, or NULL pointers.
  182170. * However, the * structure returned by png_get_text() will always contain
  182171. * regular zero-terminated C strings (possibly empty), never NULL pointers,
  182172. * so they can be safely used in printf() and other string-handling functions.
  182173. */
  182174. typedef struct png_text_struct
  182175. {
  182176. int compression; /* compression value:
  182177. -1: tEXt, none
  182178. 0: zTXt, deflate
  182179. 1: iTXt, none
  182180. 2: iTXt, deflate */
  182181. png_charp key; /* keyword, 1-79 character description of "text" */
  182182. png_charp text; /* comment, may be an empty string (ie "")
  182183. or a NULL pointer */
  182184. png_size_t text_length; /* length of the text string */
  182185. #ifdef PNG_iTXt_SUPPORTED
  182186. png_size_t itxt_length; /* length of the itxt string */
  182187. png_charp lang; /* language code, 0-79 characters
  182188. or a NULL pointer */
  182189. png_charp lang_key; /* keyword translated UTF-8 string, 0 or more
  182190. chars or a NULL pointer */
  182191. #endif
  182192. } png_text;
  182193. typedef png_text FAR * png_textp;
  182194. typedef png_text FAR * FAR * png_textpp;
  182195. #endif
  182196. /* Supported compression types for text in PNG files (tEXt, and zTXt).
  182197. * The values of the PNG_TEXT_COMPRESSION_ defines should NOT be changed. */
  182198. #define PNG_TEXT_COMPRESSION_NONE_WR -3
  182199. #define PNG_TEXT_COMPRESSION_zTXt_WR -2
  182200. #define PNG_TEXT_COMPRESSION_NONE -1
  182201. #define PNG_TEXT_COMPRESSION_zTXt 0
  182202. #define PNG_ITXT_COMPRESSION_NONE 1
  182203. #define PNG_ITXT_COMPRESSION_zTXt 2
  182204. #define PNG_TEXT_COMPRESSION_LAST 3 /* Not a valid value */
  182205. /* png_time is a way to hold the time in an machine independent way.
  182206. * Two conversions are provided, both from time_t and struct tm. There
  182207. * is no portable way to convert to either of these structures, as far
  182208. * as I know. If you know of a portable way, send it to me. As a side
  182209. * note - PNG has always been Year 2000 compliant!
  182210. */
  182211. typedef struct png_time_struct
  182212. {
  182213. png_uint_16 year; /* full year, as in, 1995 */
  182214. png_byte month; /* month of year, 1 - 12 */
  182215. png_byte day; /* day of month, 1 - 31 */
  182216. png_byte hour; /* hour of day, 0 - 23 */
  182217. png_byte minute; /* minute of hour, 0 - 59 */
  182218. png_byte second; /* second of minute, 0 - 60 (for leap seconds) */
  182219. } png_time;
  182220. typedef png_time FAR * png_timep;
  182221. typedef png_time FAR * FAR * png_timepp;
  182222. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182223. /* png_unknown_chunk is a structure to hold queued chunks for which there is
  182224. * no specific support. The idea is that we can use this to queue
  182225. * up private chunks for output even though the library doesn't actually
  182226. * know about their semantics.
  182227. */
  182228. typedef struct png_unknown_chunk_t
  182229. {
  182230. png_byte name[5];
  182231. png_byte *data;
  182232. png_size_t size;
  182233. /* libpng-using applications should NOT directly modify this byte. */
  182234. png_byte location; /* mode of operation at read time */
  182235. }
  182236. png_unknown_chunk;
  182237. typedef png_unknown_chunk FAR * png_unknown_chunkp;
  182238. typedef png_unknown_chunk FAR * FAR * png_unknown_chunkpp;
  182239. #endif
  182240. /* png_info is a structure that holds the information in a PNG file so
  182241. * that the application can find out the characteristics of the image.
  182242. * If you are reading the file, this structure will tell you what is
  182243. * in the PNG file. If you are writing the file, fill in the information
  182244. * you want to put into the PNG file, then call png_write_info().
  182245. * The names chosen should be very close to the PNG specification, so
  182246. * consult that document for information about the meaning of each field.
  182247. *
  182248. * With libpng < 0.95, it was only possible to directly set and read the
  182249. * the values in the png_info_struct, which meant that the contents and
  182250. * order of the values had to remain fixed. With libpng 0.95 and later,
  182251. * however, there are now functions that abstract the contents of
  182252. * png_info_struct from the application, so this makes it easier to use
  182253. * libpng with dynamic libraries, and even makes it possible to use
  182254. * libraries that don't have all of the libpng ancillary chunk-handing
  182255. * functionality.
  182256. *
  182257. * In any case, the order of the parameters in png_info_struct should NOT
  182258. * be changed for as long as possible to keep compatibility with applications
  182259. * that use the old direct-access method with png_info_struct.
  182260. *
  182261. * The following members may have allocated storage attached that should be
  182262. * cleaned up before the structure is discarded: palette, trans, text,
  182263. * pcal_purpose, pcal_units, pcal_params, hist, iccp_name, iccp_profile,
  182264. * splt_palettes, scal_unit, row_pointers, and unknowns. By default, these
  182265. * are automatically freed when the info structure is deallocated, if they were
  182266. * allocated internally by libpng. This behavior can be changed by means
  182267. * of the png_data_freer() function.
  182268. *
  182269. * More allocation details: all the chunk-reading functions that
  182270. * change these members go through the corresponding png_set_*
  182271. * functions. A function to clear these members is available: see
  182272. * png_free_data(). The png_set_* functions do not depend on being
  182273. * able to point info structure members to any of the storage they are
  182274. * passed (they make their own copies), EXCEPT that the png_set_text
  182275. * functions use the same storage passed to them in the text_ptr or
  182276. * itxt_ptr structure argument, and the png_set_rows and png_set_unknowns
  182277. * functions do not make their own copies.
  182278. */
  182279. typedef struct png_info_struct
  182280. {
  182281. /* the following are necessary for every PNG file */
  182282. png_uint_32 width; /* width of image in pixels (from IHDR) */
  182283. png_uint_32 height; /* height of image in pixels (from IHDR) */
  182284. png_uint_32 valid; /* valid chunk data (see PNG_INFO_ below) */
  182285. png_uint_32 rowbytes; /* bytes needed to hold an untransformed row */
  182286. png_colorp palette; /* array of color values (valid & PNG_INFO_PLTE) */
  182287. png_uint_16 num_palette; /* number of color entries in "palette" (PLTE) */
  182288. png_uint_16 num_trans; /* number of transparent palette color (tRNS) */
  182289. png_byte bit_depth; /* 1, 2, 4, 8, or 16 bits/channel (from IHDR) */
  182290. png_byte color_type; /* see PNG_COLOR_TYPE_ below (from IHDR) */
  182291. /* The following three should have been named *_method not *_type */
  182292. png_byte compression_type; /* must be PNG_COMPRESSION_TYPE_BASE (IHDR) */
  182293. png_byte filter_type; /* must be PNG_FILTER_TYPE_BASE (from IHDR) */
  182294. png_byte interlace_type; /* One of PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  182295. /* The following is informational only on read, and not used on writes. */
  182296. png_byte channels; /* number of data channels per pixel (1, 2, 3, 4) */
  182297. png_byte pixel_depth; /* number of bits per pixel */
  182298. png_byte spare_byte; /* to align the data, and for future use */
  182299. png_byte signature[8]; /* magic bytes read by libpng from start of file */
  182300. /* The rest of the data is optional. If you are reading, check the
  182301. * valid field to see if the information in these are valid. If you
  182302. * are writing, set the valid field to those chunks you want written,
  182303. * and initialize the appropriate fields below.
  182304. */
  182305. #if defined(PNG_gAMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  182306. /* The gAMA chunk describes the gamma characteristics of the system
  182307. * on which the image was created, normally in the range [1.0, 2.5].
  182308. * Data is valid if (valid & PNG_INFO_gAMA) is non-zero.
  182309. */
  182310. float gamma; /* gamma value of image, if (valid & PNG_INFO_gAMA) */
  182311. #endif
  182312. #if defined(PNG_sRGB_SUPPORTED)
  182313. /* GR-P, 0.96a */
  182314. /* Data valid if (valid & PNG_INFO_sRGB) non-zero. */
  182315. png_byte srgb_intent; /* sRGB rendering intent [0, 1, 2, or 3] */
  182316. #endif
  182317. #if defined(PNG_TEXT_SUPPORTED)
  182318. /* The tEXt, and zTXt chunks contain human-readable textual data in
  182319. * uncompressed, compressed, and optionally compressed forms, respectively.
  182320. * The data in "text" is an array of pointers to uncompressed,
  182321. * null-terminated C strings. Each chunk has a keyword that describes the
  182322. * textual data contained in that chunk. Keywords are not required to be
  182323. * unique, and the text string may be empty. Any number of text chunks may
  182324. * be in an image.
  182325. */
  182326. int num_text; /* number of comments read/to write */
  182327. int max_text; /* current size of text array */
  182328. png_textp text; /* array of comments read/to write */
  182329. #endif /* PNG_TEXT_SUPPORTED */
  182330. #if defined(PNG_tIME_SUPPORTED)
  182331. /* The tIME chunk holds the last time the displayed image data was
  182332. * modified. See the png_time struct for the contents of this struct.
  182333. */
  182334. png_time mod_time;
  182335. #endif
  182336. #if defined(PNG_sBIT_SUPPORTED)
  182337. /* The sBIT chunk specifies the number of significant high-order bits
  182338. * in the pixel data. Values are in the range [1, bit_depth], and are
  182339. * only specified for the channels in the pixel data. The contents of
  182340. * the low-order bits is not specified. Data is valid if
  182341. * (valid & PNG_INFO_sBIT) is non-zero.
  182342. */
  182343. png_color_8 sig_bit; /* significant bits in color channels */
  182344. #endif
  182345. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_EXPAND_SUPPORTED) || \
  182346. defined(PNG_READ_BACKGROUND_SUPPORTED)
  182347. /* The tRNS chunk supplies transparency data for paletted images and
  182348. * other image types that don't need a full alpha channel. There are
  182349. * "num_trans" transparency values for a paletted image, stored in the
  182350. * same order as the palette colors, starting from index 0. Values
  182351. * for the data are in the range [0, 255], ranging from fully transparent
  182352. * to fully opaque, respectively. For non-paletted images, there is a
  182353. * single color specified that should be treated as fully transparent.
  182354. * Data is valid if (valid & PNG_INFO_tRNS) is non-zero.
  182355. */
  182356. png_bytep trans; /* transparent values for paletted image */
  182357. png_color_16 trans_values; /* transparent color for non-palette image */
  182358. #endif
  182359. #if defined(PNG_bKGD_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182360. /* The bKGD chunk gives the suggested image background color if the
  182361. * display program does not have its own background color and the image
  182362. * is needs to composited onto a background before display. The colors
  182363. * in "background" are normally in the same color space/depth as the
  182364. * pixel data. Data is valid if (valid & PNG_INFO_bKGD) is non-zero.
  182365. */
  182366. png_color_16 background;
  182367. #endif
  182368. #if defined(PNG_oFFs_SUPPORTED)
  182369. /* The oFFs chunk gives the offset in "offset_unit_type" units rightwards
  182370. * and downwards from the top-left corner of the display, page, or other
  182371. * application-specific co-ordinate space. See the PNG_OFFSET_ defines
  182372. * below for the unit types. Valid if (valid & PNG_INFO_oFFs) non-zero.
  182373. */
  182374. png_int_32 x_offset; /* x offset on page */
  182375. png_int_32 y_offset; /* y offset on page */
  182376. png_byte offset_unit_type; /* offset units type */
  182377. #endif
  182378. #if defined(PNG_pHYs_SUPPORTED)
  182379. /* The pHYs chunk gives the physical pixel density of the image for
  182380. * display or printing in "phys_unit_type" units (see PNG_RESOLUTION_
  182381. * defines below). Data is valid if (valid & PNG_INFO_pHYs) is non-zero.
  182382. */
  182383. png_uint_32 x_pixels_per_unit; /* horizontal pixel density */
  182384. png_uint_32 y_pixels_per_unit; /* vertical pixel density */
  182385. png_byte phys_unit_type; /* resolution type (see PNG_RESOLUTION_ below) */
  182386. #endif
  182387. #if defined(PNG_hIST_SUPPORTED)
  182388. /* The hIST chunk contains the relative frequency or importance of the
  182389. * various palette entries, so that a viewer can intelligently select a
  182390. * reduced-color palette, if required. Data is an array of "num_palette"
  182391. * values in the range [0,65535]. Data valid if (valid & PNG_INFO_hIST)
  182392. * is non-zero.
  182393. */
  182394. png_uint_16p hist;
  182395. #endif
  182396. #ifdef PNG_cHRM_SUPPORTED
  182397. /* The cHRM chunk describes the CIE color characteristics of the monitor
  182398. * on which the PNG was created. This data allows the viewer to do gamut
  182399. * mapping of the input image to ensure that the viewer sees the same
  182400. * colors in the image as the creator. Values are in the range
  182401. * [0.0, 0.8]. Data valid if (valid & PNG_INFO_cHRM) non-zero.
  182402. */
  182403. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182404. float x_white;
  182405. float y_white;
  182406. float x_red;
  182407. float y_red;
  182408. float x_green;
  182409. float y_green;
  182410. float x_blue;
  182411. float y_blue;
  182412. #endif
  182413. #endif
  182414. #if defined(PNG_pCAL_SUPPORTED)
  182415. /* The pCAL chunk describes a transformation between the stored pixel
  182416. * values and original physical data values used to create the image.
  182417. * The integer range [0, 2^bit_depth - 1] maps to the floating-point
  182418. * range given by [pcal_X0, pcal_X1], and are further transformed by a
  182419. * (possibly non-linear) transformation function given by "pcal_type"
  182420. * and "pcal_params" into "pcal_units". Please see the PNG_EQUATION_
  182421. * defines below, and the PNG-Group's PNG extensions document for a
  182422. * complete description of the transformations and how they should be
  182423. * implemented, and for a description of the ASCII parameter strings.
  182424. * Data values are valid if (valid & PNG_INFO_pCAL) non-zero.
  182425. */
  182426. png_charp pcal_purpose; /* pCAL chunk description string */
  182427. png_int_32 pcal_X0; /* minimum value */
  182428. png_int_32 pcal_X1; /* maximum value */
  182429. png_charp pcal_units; /* Latin-1 string giving physical units */
  182430. png_charpp pcal_params; /* ASCII strings containing parameter values */
  182431. png_byte pcal_type; /* equation type (see PNG_EQUATION_ below) */
  182432. png_byte pcal_nparams; /* number of parameters given in pcal_params */
  182433. #endif
  182434. /* New members added in libpng-1.0.6 */
  182435. #ifdef PNG_FREE_ME_SUPPORTED
  182436. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  182437. #endif
  182438. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182439. /* storage for unknown chunks that the library doesn't recognize. */
  182440. png_unknown_chunkp unknown_chunks;
  182441. png_size_t unknown_chunks_num;
  182442. #endif
  182443. #if defined(PNG_iCCP_SUPPORTED)
  182444. /* iCCP chunk data. */
  182445. png_charp iccp_name; /* profile name */
  182446. png_charp iccp_profile; /* International Color Consortium profile data */
  182447. /* Note to maintainer: should be png_bytep */
  182448. png_uint_32 iccp_proflen; /* ICC profile data length */
  182449. png_byte iccp_compression; /* Always zero */
  182450. #endif
  182451. #if defined(PNG_sPLT_SUPPORTED)
  182452. /* data on sPLT chunks (there may be more than one). */
  182453. png_sPLT_tp splt_palettes;
  182454. png_uint_32 splt_palettes_num;
  182455. #endif
  182456. #if defined(PNG_sCAL_SUPPORTED)
  182457. /* The sCAL chunk describes the actual physical dimensions of the
  182458. * subject matter of the graphic. The chunk contains a unit specification
  182459. * a byte value, and two ASCII strings representing floating-point
  182460. * values. The values are width and height corresponsing to one pixel
  182461. * in the image. This external representation is converted to double
  182462. * here. Data values are valid if (valid & PNG_INFO_sCAL) is non-zero.
  182463. */
  182464. png_byte scal_unit; /* unit of physical scale */
  182465. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182466. double scal_pixel_width; /* width of one pixel */
  182467. double scal_pixel_height; /* height of one pixel */
  182468. #endif
  182469. #ifdef PNG_FIXED_POINT_SUPPORTED
  182470. png_charp scal_s_width; /* string containing height */
  182471. png_charp scal_s_height; /* string containing width */
  182472. #endif
  182473. #endif
  182474. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  182475. /* Memory has been allocated if (valid & PNG_ALLOCATED_INFO_ROWS) non-zero */
  182476. /* Data valid if (valid & PNG_INFO_IDAT) non-zero */
  182477. png_bytepp row_pointers; /* the image bits */
  182478. #endif
  182479. #if defined(PNG_FIXED_POINT_SUPPORTED) && defined(PNG_gAMA_SUPPORTED)
  182480. png_fixed_point int_gamma; /* gamma of image, if (valid & PNG_INFO_gAMA) */
  182481. #endif
  182482. #if defined(PNG_cHRM_SUPPORTED) && defined(PNG_FIXED_POINT_SUPPORTED)
  182483. png_fixed_point int_x_white;
  182484. png_fixed_point int_y_white;
  182485. png_fixed_point int_x_red;
  182486. png_fixed_point int_y_red;
  182487. png_fixed_point int_x_green;
  182488. png_fixed_point int_y_green;
  182489. png_fixed_point int_x_blue;
  182490. png_fixed_point int_y_blue;
  182491. #endif
  182492. } png_info;
  182493. typedef png_info FAR * png_infop;
  182494. typedef png_info FAR * FAR * png_infopp;
  182495. /* Maximum positive integer used in PNG is (2^31)-1 */
  182496. #define PNG_UINT_31_MAX ((png_uint_32)0x7fffffffL)
  182497. #define PNG_UINT_32_MAX ((png_uint_32)(-1))
  182498. #define PNG_SIZE_MAX ((png_size_t)(-1))
  182499. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182500. /* PNG_MAX_UINT is deprecated; use PNG_UINT_31_MAX instead. */
  182501. #define PNG_MAX_UINT PNG_UINT_31_MAX
  182502. #endif
  182503. /* These describe the color_type field in png_info. */
  182504. /* color type masks */
  182505. #define PNG_COLOR_MASK_PALETTE 1
  182506. #define PNG_COLOR_MASK_COLOR 2
  182507. #define PNG_COLOR_MASK_ALPHA 4
  182508. /* color types. Note that not all combinations are legal */
  182509. #define PNG_COLOR_TYPE_GRAY 0
  182510. #define PNG_COLOR_TYPE_PALETTE (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE)
  182511. #define PNG_COLOR_TYPE_RGB (PNG_COLOR_MASK_COLOR)
  182512. #define PNG_COLOR_TYPE_RGB_ALPHA (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA)
  182513. #define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA)
  182514. /* aliases */
  182515. #define PNG_COLOR_TYPE_RGBA PNG_COLOR_TYPE_RGB_ALPHA
  182516. #define PNG_COLOR_TYPE_GA PNG_COLOR_TYPE_GRAY_ALPHA
  182517. /* This is for compression type. PNG 1.0-1.2 only define the single type. */
  182518. #define PNG_COMPRESSION_TYPE_BASE 0 /* Deflate method 8, 32K window */
  182519. #define PNG_COMPRESSION_TYPE_DEFAULT PNG_COMPRESSION_TYPE_BASE
  182520. /* This is for filter type. PNG 1.0-1.2 only define the single type. */
  182521. #define PNG_FILTER_TYPE_BASE 0 /* Single row per-byte filtering */
  182522. #define PNG_INTRAPIXEL_DIFFERENCING 64 /* Used only in MNG datastreams */
  182523. #define PNG_FILTER_TYPE_DEFAULT PNG_FILTER_TYPE_BASE
  182524. /* These are for the interlacing type. These values should NOT be changed. */
  182525. #define PNG_INTERLACE_NONE 0 /* Non-interlaced image */
  182526. #define PNG_INTERLACE_ADAM7 1 /* Adam7 interlacing */
  182527. #define PNG_INTERLACE_LAST 2 /* Not a valid value */
  182528. /* These are for the oFFs chunk. These values should NOT be changed. */
  182529. #define PNG_OFFSET_PIXEL 0 /* Offset in pixels */
  182530. #define PNG_OFFSET_MICROMETER 1 /* Offset in micrometers (1/10^6 meter) */
  182531. #define PNG_OFFSET_LAST 2 /* Not a valid value */
  182532. /* These are for the pCAL chunk. These values should NOT be changed. */
  182533. #define PNG_EQUATION_LINEAR 0 /* Linear transformation */
  182534. #define PNG_EQUATION_BASE_E 1 /* Exponential base e transform */
  182535. #define PNG_EQUATION_ARBITRARY 2 /* Arbitrary base exponential transform */
  182536. #define PNG_EQUATION_HYPERBOLIC 3 /* Hyperbolic sine transformation */
  182537. #define PNG_EQUATION_LAST 4 /* Not a valid value */
  182538. /* These are for the sCAL chunk. These values should NOT be changed. */
  182539. #define PNG_SCALE_UNKNOWN 0 /* unknown unit (image scale) */
  182540. #define PNG_SCALE_METER 1 /* meters per pixel */
  182541. #define PNG_SCALE_RADIAN 2 /* radians per pixel */
  182542. #define PNG_SCALE_LAST 3 /* Not a valid value */
  182543. /* These are for the pHYs chunk. These values should NOT be changed. */
  182544. #define PNG_RESOLUTION_UNKNOWN 0 /* pixels/unknown unit (aspect ratio) */
  182545. #define PNG_RESOLUTION_METER 1 /* pixels/meter */
  182546. #define PNG_RESOLUTION_LAST 2 /* Not a valid value */
  182547. /* These are for the sRGB chunk. These values should NOT be changed. */
  182548. #define PNG_sRGB_INTENT_PERCEPTUAL 0
  182549. #define PNG_sRGB_INTENT_RELATIVE 1
  182550. #define PNG_sRGB_INTENT_SATURATION 2
  182551. #define PNG_sRGB_INTENT_ABSOLUTE 3
  182552. #define PNG_sRGB_INTENT_LAST 4 /* Not a valid value */
  182553. /* This is for text chunks */
  182554. #define PNG_KEYWORD_MAX_LENGTH 79
  182555. /* Maximum number of entries in PLTE/sPLT/tRNS arrays */
  182556. #define PNG_MAX_PALETTE_LENGTH 256
  182557. /* These determine if an ancillary chunk's data has been successfully read
  182558. * from the PNG header, or if the application has filled in the corresponding
  182559. * data in the info_struct to be written into the output file. The values
  182560. * of the PNG_INFO_<chunk> defines should NOT be changed.
  182561. */
  182562. #define PNG_INFO_gAMA 0x0001
  182563. #define PNG_INFO_sBIT 0x0002
  182564. #define PNG_INFO_cHRM 0x0004
  182565. #define PNG_INFO_PLTE 0x0008
  182566. #define PNG_INFO_tRNS 0x0010
  182567. #define PNG_INFO_bKGD 0x0020
  182568. #define PNG_INFO_hIST 0x0040
  182569. #define PNG_INFO_pHYs 0x0080
  182570. #define PNG_INFO_oFFs 0x0100
  182571. #define PNG_INFO_tIME 0x0200
  182572. #define PNG_INFO_pCAL 0x0400
  182573. #define PNG_INFO_sRGB 0x0800 /* GR-P, 0.96a */
  182574. #define PNG_INFO_iCCP 0x1000 /* ESR, 1.0.6 */
  182575. #define PNG_INFO_sPLT 0x2000 /* ESR, 1.0.6 */
  182576. #define PNG_INFO_sCAL 0x4000 /* ESR, 1.0.6 */
  182577. #define PNG_INFO_IDAT 0x8000L /* ESR, 1.0.6 */
  182578. /* This is used for the transformation routines, as some of them
  182579. * change these values for the row. It also should enable using
  182580. * the routines for other purposes.
  182581. */
  182582. typedef struct png_row_info_struct
  182583. {
  182584. png_uint_32 width; /* width of row */
  182585. png_uint_32 rowbytes; /* number of bytes in row */
  182586. png_byte color_type; /* color type of row */
  182587. png_byte bit_depth; /* bit depth of row */
  182588. png_byte channels; /* number of channels (1, 2, 3, or 4) */
  182589. png_byte pixel_depth; /* bits per pixel (depth * channels) */
  182590. } png_row_info;
  182591. typedef png_row_info FAR * png_row_infop;
  182592. typedef png_row_info FAR * FAR * png_row_infopp;
  182593. /* These are the function types for the I/O functions and for the functions
  182594. * that allow the user to override the default I/O functions with his or her
  182595. * own. The png_error_ptr type should match that of user-supplied warning
  182596. * and error functions, while the png_rw_ptr type should match that of the
  182597. * user read/write data functions.
  182598. */
  182599. typedef struct png_struct_def png_struct;
  182600. typedef png_struct FAR * png_structp;
  182601. typedef void (PNGAPI *png_error_ptr) PNGARG((png_structp, png_const_charp));
  182602. typedef void (PNGAPI *png_rw_ptr) PNGARG((png_structp, png_bytep, png_size_t));
  182603. typedef void (PNGAPI *png_flush_ptr) PNGARG((png_structp));
  182604. typedef void (PNGAPI *png_read_status_ptr) PNGARG((png_structp, png_uint_32,
  182605. int));
  182606. typedef void (PNGAPI *png_write_status_ptr) PNGARG((png_structp, png_uint_32,
  182607. int));
  182608. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182609. typedef void (PNGAPI *png_progressive_info_ptr) PNGARG((png_structp, png_infop));
  182610. typedef void (PNGAPI *png_progressive_end_ptr) PNGARG((png_structp, png_infop));
  182611. typedef void (PNGAPI *png_progressive_row_ptr) PNGARG((png_structp, png_bytep,
  182612. png_uint_32, int));
  182613. #endif
  182614. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182615. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  182616. defined(PNG_LEGACY_SUPPORTED)
  182617. typedef void (PNGAPI *png_user_transform_ptr) PNGARG((png_structp,
  182618. png_row_infop, png_bytep));
  182619. #endif
  182620. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  182621. typedef int (PNGAPI *png_user_chunk_ptr) PNGARG((png_structp, png_unknown_chunkp));
  182622. #endif
  182623. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182624. typedef void (PNGAPI *png_unknown_chunk_ptr) PNGARG((png_structp));
  182625. #endif
  182626. /* Transform masks for the high-level interface */
  182627. #define PNG_TRANSFORM_IDENTITY 0x0000 /* read and write */
  182628. #define PNG_TRANSFORM_STRIP_16 0x0001 /* read only */
  182629. #define PNG_TRANSFORM_STRIP_ALPHA 0x0002 /* read only */
  182630. #define PNG_TRANSFORM_PACKING 0x0004 /* read and write */
  182631. #define PNG_TRANSFORM_PACKSWAP 0x0008 /* read and write */
  182632. #define PNG_TRANSFORM_EXPAND 0x0010 /* read only */
  182633. #define PNG_TRANSFORM_INVERT_MONO 0x0020 /* read and write */
  182634. #define PNG_TRANSFORM_SHIFT 0x0040 /* read and write */
  182635. #define PNG_TRANSFORM_BGR 0x0080 /* read and write */
  182636. #define PNG_TRANSFORM_SWAP_ALPHA 0x0100 /* read and write */
  182637. #define PNG_TRANSFORM_SWAP_ENDIAN 0x0200 /* read and write */
  182638. #define PNG_TRANSFORM_INVERT_ALPHA 0x0400 /* read and write */
  182639. #define PNG_TRANSFORM_STRIP_FILLER 0x0800 /* WRITE only */
  182640. /* Flags for MNG supported features */
  182641. #define PNG_FLAG_MNG_EMPTY_PLTE 0x01
  182642. #define PNG_FLAG_MNG_FILTER_64 0x04
  182643. #define PNG_ALL_MNG_FEATURES 0x05
  182644. typedef png_voidp (*png_malloc_ptr) PNGARG((png_structp, png_size_t));
  182645. typedef void (*png_free_ptr) PNGARG((png_structp, png_voidp));
  182646. /* The structure that holds the information to read and write PNG files.
  182647. * The only people who need to care about what is inside of this are the
  182648. * people who will be modifying the library for their own special needs.
  182649. * It should NOT be accessed directly by an application, except to store
  182650. * the jmp_buf.
  182651. */
  182652. struct png_struct_def
  182653. {
  182654. #ifdef PNG_SETJMP_SUPPORTED
  182655. jmp_buf jmpbuf; /* used in png_error */
  182656. #endif
  182657. png_error_ptr error_fn; /* function for printing errors and aborting */
  182658. png_error_ptr warning_fn; /* function for printing warnings */
  182659. png_voidp error_ptr; /* user supplied struct for error functions */
  182660. png_rw_ptr write_data_fn; /* function for writing output data */
  182661. png_rw_ptr read_data_fn; /* function for reading input data */
  182662. png_voidp io_ptr; /* ptr to application struct for I/O functions */
  182663. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  182664. png_user_transform_ptr read_user_transform_fn; /* user read transform */
  182665. #endif
  182666. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  182667. png_user_transform_ptr write_user_transform_fn; /* user write transform */
  182668. #endif
  182669. /* These were added in libpng-1.0.2 */
  182670. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  182671. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182672. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  182673. png_voidp user_transform_ptr; /* user supplied struct for user transform */
  182674. png_byte user_transform_depth; /* bit depth of user transformed pixels */
  182675. png_byte user_transform_channels; /* channels in user transformed pixels */
  182676. #endif
  182677. #endif
  182678. png_uint_32 mode; /* tells us where we are in the PNG file */
  182679. png_uint_32 flags; /* flags indicating various things to libpng */
  182680. png_uint_32 transformations; /* which transformations to perform */
  182681. z_stream zstream; /* pointer to decompression structure (below) */
  182682. png_bytep zbuf; /* buffer for zlib */
  182683. png_size_t zbuf_size; /* size of zbuf */
  182684. int zlib_level; /* holds zlib compression level */
  182685. int zlib_method; /* holds zlib compression method */
  182686. int zlib_window_bits; /* holds zlib compression window bits */
  182687. int zlib_mem_level; /* holds zlib compression memory level */
  182688. int zlib_strategy; /* holds zlib compression strategy */
  182689. png_uint_32 width; /* width of image in pixels */
  182690. png_uint_32 height; /* height of image in pixels */
  182691. png_uint_32 num_rows; /* number of rows in current pass */
  182692. png_uint_32 usr_width; /* width of row at start of write */
  182693. png_uint_32 rowbytes; /* size of row in bytes */
  182694. png_uint_32 irowbytes; /* size of current interlaced row in bytes */
  182695. png_uint_32 iwidth; /* width of current interlaced row in pixels */
  182696. png_uint_32 row_number; /* current row in interlace pass */
  182697. png_bytep prev_row; /* buffer to save previous (unfiltered) row */
  182698. png_bytep row_buf; /* buffer to save current (unfiltered) row */
  182699. png_bytep sub_row; /* buffer to save "sub" row when filtering */
  182700. png_bytep up_row; /* buffer to save "up" row when filtering */
  182701. png_bytep avg_row; /* buffer to save "avg" row when filtering */
  182702. png_bytep paeth_row; /* buffer to save "Paeth" row when filtering */
  182703. png_row_info row_info; /* used for transformation routines */
  182704. png_uint_32 idat_size; /* current IDAT size for read */
  182705. png_uint_32 crc; /* current chunk CRC value */
  182706. png_colorp palette; /* palette from the input file */
  182707. png_uint_16 num_palette; /* number of color entries in palette */
  182708. png_uint_16 num_trans; /* number of transparency values */
  182709. png_byte chunk_name[5]; /* null-terminated name of current chunk */
  182710. png_byte compression; /* file compression type (always 0) */
  182711. png_byte filter; /* file filter type (always 0) */
  182712. png_byte interlaced; /* PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  182713. png_byte pass; /* current interlace pass (0 - 6) */
  182714. png_byte do_filter; /* row filter flags (see PNG_FILTER_ below ) */
  182715. png_byte color_type; /* color type of file */
  182716. png_byte bit_depth; /* bit depth of file */
  182717. png_byte usr_bit_depth; /* bit depth of users row */
  182718. png_byte pixel_depth; /* number of bits per pixel */
  182719. png_byte channels; /* number of channels in file */
  182720. png_byte usr_channels; /* channels at start of write */
  182721. png_byte sig_bytes; /* magic bytes read/written from start of file */
  182722. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  182723. #ifdef PNG_LEGACY_SUPPORTED
  182724. png_byte filler; /* filler byte for pixel expansion */
  182725. #else
  182726. png_uint_16 filler; /* filler bytes for pixel expansion */
  182727. #endif
  182728. #endif
  182729. #if defined(PNG_bKGD_SUPPORTED)
  182730. png_byte background_gamma_type;
  182731. # ifdef PNG_FLOATING_POINT_SUPPORTED
  182732. float background_gamma;
  182733. # endif
  182734. png_color_16 background; /* background color in screen gamma space */
  182735. #if defined(PNG_READ_GAMMA_SUPPORTED)
  182736. png_color_16 background_1; /* background normalized to gamma 1.0 */
  182737. #endif
  182738. #endif /* PNG_bKGD_SUPPORTED */
  182739. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  182740. png_flush_ptr output_flush_fn;/* Function for flushing output */
  182741. png_uint_32 flush_dist; /* how many rows apart to flush, 0 - no flush */
  182742. png_uint_32 flush_rows; /* number of rows written since last flush */
  182743. #endif
  182744. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182745. int gamma_shift; /* number of "insignificant" bits 16-bit gamma */
  182746. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182747. float gamma; /* file gamma value */
  182748. float screen_gamma; /* screen gamma value (display_exponent) */
  182749. #endif
  182750. #endif
  182751. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182752. png_bytep gamma_table; /* gamma table for 8-bit depth files */
  182753. png_bytep gamma_from_1; /* converts from 1.0 to screen */
  182754. png_bytep gamma_to_1; /* converts from file to 1.0 */
  182755. png_uint_16pp gamma_16_table; /* gamma table for 16-bit depth files */
  182756. png_uint_16pp gamma_16_from_1; /* converts from 1.0 to screen */
  182757. png_uint_16pp gamma_16_to_1; /* converts from file to 1.0 */
  182758. #endif
  182759. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_sBIT_SUPPORTED)
  182760. png_color_8 sig_bit; /* significant bits in each available channel */
  182761. #endif
  182762. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  182763. png_color_8 shift; /* shift for significant bit tranformation */
  182764. #endif
  182765. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) \
  182766. || defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182767. png_bytep trans; /* transparency values for paletted files */
  182768. png_color_16 trans_values; /* transparency values for non-paletted files */
  182769. #endif
  182770. png_read_status_ptr read_row_fn; /* called after each row is decoded */
  182771. png_write_status_ptr write_row_fn; /* called after each row is encoded */
  182772. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182773. png_progressive_info_ptr info_fn; /* called after header data fully read */
  182774. png_progressive_row_ptr row_fn; /* called after each prog. row is decoded */
  182775. png_progressive_end_ptr end_fn; /* called after image is complete */
  182776. png_bytep save_buffer_ptr; /* current location in save_buffer */
  182777. png_bytep save_buffer; /* buffer for previously read data */
  182778. png_bytep current_buffer_ptr; /* current location in current_buffer */
  182779. png_bytep current_buffer; /* buffer for recently used data */
  182780. png_uint_32 push_length; /* size of current input chunk */
  182781. png_uint_32 skip_length; /* bytes to skip in input data */
  182782. png_size_t save_buffer_size; /* amount of data now in save_buffer */
  182783. png_size_t save_buffer_max; /* total size of save_buffer */
  182784. png_size_t buffer_size; /* total amount of available input data */
  182785. png_size_t current_buffer_size; /* amount of data now in current_buffer */
  182786. int process_mode; /* what push library is currently doing */
  182787. int cur_palette; /* current push library palette index */
  182788. # if defined(PNG_TEXT_SUPPORTED)
  182789. png_size_t current_text_size; /* current size of text input data */
  182790. png_size_t current_text_left; /* how much text left to read in input */
  182791. png_charp current_text; /* current text chunk buffer */
  182792. png_charp current_text_ptr; /* current location in current_text */
  182793. # endif /* PNG_TEXT_SUPPORTED */
  182794. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  182795. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  182796. /* for the Borland special 64K segment handler */
  182797. png_bytepp offset_table_ptr;
  182798. png_bytep offset_table;
  182799. png_uint_16 offset_table_number;
  182800. png_uint_16 offset_table_count;
  182801. png_uint_16 offset_table_count_free;
  182802. #endif
  182803. #if defined(PNG_READ_DITHER_SUPPORTED)
  182804. png_bytep palette_lookup; /* lookup table for dithering */
  182805. png_bytep dither_index; /* index translation for palette files */
  182806. #endif
  182807. #if defined(PNG_READ_DITHER_SUPPORTED) || defined(PNG_hIST_SUPPORTED)
  182808. png_uint_16p hist; /* histogram */
  182809. #endif
  182810. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  182811. png_byte heuristic_method; /* heuristic for row filter selection */
  182812. png_byte num_prev_filters; /* number of weights for previous rows */
  182813. png_bytep prev_filters; /* filter type(s) of previous row(s) */
  182814. png_uint_16p filter_weights; /* weight(s) for previous line(s) */
  182815. png_uint_16p inv_filter_weights; /* 1/weight(s) for previous line(s) */
  182816. png_uint_16p filter_costs; /* relative filter calculation cost */
  182817. png_uint_16p inv_filter_costs; /* 1/relative filter calculation cost */
  182818. #endif
  182819. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  182820. png_charp time_buffer; /* String to hold RFC 1123 time text */
  182821. #endif
  182822. /* New members added in libpng-1.0.6 */
  182823. #ifdef PNG_FREE_ME_SUPPORTED
  182824. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  182825. #endif
  182826. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  182827. png_voidp user_chunk_ptr;
  182828. png_user_chunk_ptr read_user_chunk_fn; /* user read chunk handler */
  182829. #endif
  182830. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182831. int num_chunk_list;
  182832. png_bytep chunk_list;
  182833. #endif
  182834. /* New members added in libpng-1.0.3 */
  182835. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  182836. png_byte rgb_to_gray_status;
  182837. /* These were changed from png_byte in libpng-1.0.6 */
  182838. png_uint_16 rgb_to_gray_red_coeff;
  182839. png_uint_16 rgb_to_gray_green_coeff;
  182840. png_uint_16 rgb_to_gray_blue_coeff;
  182841. #endif
  182842. /* New member added in libpng-1.0.4 (renamed in 1.0.9) */
  182843. #if defined(PNG_MNG_FEATURES_SUPPORTED) || \
  182844. defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  182845. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  182846. /* changed from png_byte to png_uint_32 at version 1.2.0 */
  182847. #ifdef PNG_1_0_X
  182848. png_byte mng_features_permitted;
  182849. #else
  182850. png_uint_32 mng_features_permitted;
  182851. #endif /* PNG_1_0_X */
  182852. #endif
  182853. /* New member added in libpng-1.0.7 */
  182854. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182855. png_fixed_point int_gamma;
  182856. #endif
  182857. /* New member added in libpng-1.0.9, ifdef'ed out in 1.0.12, enabled in 1.2.0 */
  182858. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  182859. png_byte filter_type;
  182860. #endif
  182861. #if defined(PNG_1_0_X)
  182862. /* New member added in libpng-1.0.10, ifdef'ed out in 1.2.0 */
  182863. png_uint_32 row_buf_size;
  182864. #endif
  182865. /* New members added in libpng-1.2.0 */
  182866. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  182867. # if !defined(PNG_1_0_X)
  182868. # if defined(PNG_MMX_CODE_SUPPORTED)
  182869. png_byte mmx_bitdepth_threshold;
  182870. png_uint_32 mmx_rowbytes_threshold;
  182871. # endif
  182872. png_uint_32 asm_flags;
  182873. # endif
  182874. #endif
  182875. /* New members added in libpng-1.0.2 but first enabled by default in 1.2.0 */
  182876. #ifdef PNG_USER_MEM_SUPPORTED
  182877. png_voidp mem_ptr; /* user supplied struct for mem functions */
  182878. png_malloc_ptr malloc_fn; /* function for allocating memory */
  182879. png_free_ptr free_fn; /* function for freeing memory */
  182880. #endif
  182881. /* New member added in libpng-1.0.13 and 1.2.0 */
  182882. png_bytep big_row_buf; /* buffer to save current (unfiltered) row */
  182883. #if defined(PNG_READ_DITHER_SUPPORTED)
  182884. /* The following three members were added at version 1.0.14 and 1.2.4 */
  182885. png_bytep dither_sort; /* working sort array */
  182886. png_bytep index_to_palette; /* where the original index currently is */
  182887. /* in the palette */
  182888. png_bytep palette_to_index; /* which original index points to this */
  182889. /* palette color */
  182890. #endif
  182891. /* New members added in libpng-1.0.16 and 1.2.6 */
  182892. png_byte compression_type;
  182893. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  182894. png_uint_32 user_width_max;
  182895. png_uint_32 user_height_max;
  182896. #endif
  182897. /* New member added in libpng-1.0.25 and 1.2.17 */
  182898. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182899. /* storage for unknown chunk that the library doesn't recognize. */
  182900. png_unknown_chunk unknown_chunk;
  182901. #endif
  182902. };
  182903. /* This triggers a compiler error in png.c, if png.c and png.h
  182904. * do not agree upon the version number.
  182905. */
  182906. typedef png_structp version_1_2_21;
  182907. typedef png_struct FAR * FAR * png_structpp;
  182908. /* Here are the function definitions most commonly used. This is not
  182909. * the place to find out how to use libpng. See libpng.txt for the
  182910. * full explanation, see example.c for the summary. This just provides
  182911. * a simple one line description of the use of each function.
  182912. */
  182913. /* Returns the version number of the library */
  182914. extern PNG_EXPORT(png_uint_32,png_access_version_number) PNGARG((void));
  182915. /* Tell lib we have already handled the first <num_bytes> magic bytes.
  182916. * Handling more than 8 bytes from the beginning of the file is an error.
  182917. */
  182918. extern PNG_EXPORT(void,png_set_sig_bytes) PNGARG((png_structp png_ptr,
  182919. int num_bytes));
  182920. /* Check sig[start] through sig[start + num_to_check - 1] to see if it's a
  182921. * PNG file. Returns zero if the supplied bytes match the 8-byte PNG
  182922. * signature, and non-zero otherwise. Having num_to_check == 0 or
  182923. * start > 7 will always fail (ie return non-zero).
  182924. */
  182925. extern PNG_EXPORT(int,png_sig_cmp) PNGARG((png_bytep sig, png_size_t start,
  182926. png_size_t num_to_check));
  182927. /* Simple signature checking function. This is the same as calling
  182928. * png_check_sig(sig, n) := !png_sig_cmp(sig, 0, n).
  182929. */
  182930. extern PNG_EXPORT(int,png_check_sig) PNGARG((png_bytep sig, int num));
  182931. /* Allocate and initialize png_ptr struct for reading, and any other memory. */
  182932. extern PNG_EXPORT(png_structp,png_create_read_struct)
  182933. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182934. png_error_ptr error_fn, png_error_ptr warn_fn));
  182935. /* Allocate and initialize png_ptr struct for writing, and any other memory */
  182936. extern PNG_EXPORT(png_structp,png_create_write_struct)
  182937. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182938. png_error_ptr error_fn, png_error_ptr warn_fn));
  182939. #ifdef PNG_WRITE_SUPPORTED
  182940. extern PNG_EXPORT(png_uint_32,png_get_compression_buffer_size)
  182941. PNGARG((png_structp png_ptr));
  182942. #endif
  182943. #ifdef PNG_WRITE_SUPPORTED
  182944. extern PNG_EXPORT(void,png_set_compression_buffer_size)
  182945. PNGARG((png_structp png_ptr, png_uint_32 size));
  182946. #endif
  182947. /* Reset the compression stream */
  182948. extern PNG_EXPORT(int,png_reset_zstream) PNGARG((png_structp png_ptr));
  182949. /* New functions added in libpng-1.0.2 (not enabled by default until 1.2.0) */
  182950. #ifdef PNG_USER_MEM_SUPPORTED
  182951. extern PNG_EXPORT(png_structp,png_create_read_struct_2)
  182952. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182953. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  182954. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  182955. extern PNG_EXPORT(png_structp,png_create_write_struct_2)
  182956. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182957. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  182958. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  182959. #endif
  182960. /* Write a PNG chunk - size, type, (optional) data, CRC. */
  182961. extern PNG_EXPORT(void,png_write_chunk) PNGARG((png_structp png_ptr,
  182962. png_bytep chunk_name, png_bytep data, png_size_t length));
  182963. /* Write the start of a PNG chunk - length and chunk name. */
  182964. extern PNG_EXPORT(void,png_write_chunk_start) PNGARG((png_structp png_ptr,
  182965. png_bytep chunk_name, png_uint_32 length));
  182966. /* Write the data of a PNG chunk started with png_write_chunk_start(). */
  182967. extern PNG_EXPORT(void,png_write_chunk_data) PNGARG((png_structp png_ptr,
  182968. png_bytep data, png_size_t length));
  182969. /* Finish a chunk started with png_write_chunk_start() (includes CRC). */
  182970. extern PNG_EXPORT(void,png_write_chunk_end) PNGARG((png_structp png_ptr));
  182971. /* Allocate and initialize the info structure */
  182972. extern PNG_EXPORT(png_infop,png_create_info_struct)
  182973. PNGARG((png_structp png_ptr));
  182974. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182975. /* Initialize the info structure (old interface - DEPRECATED) */
  182976. extern PNG_EXPORT(void,png_info_init) PNGARG((png_infop info_ptr));
  182977. #undef png_info_init
  182978. #define png_info_init(info_ptr) png_info_init_3(&info_ptr,\
  182979. png_sizeof(png_info));
  182980. #endif
  182981. extern PNG_EXPORT(void,png_info_init_3) PNGARG((png_infopp info_ptr,
  182982. png_size_t png_info_struct_size));
  182983. /* Writes all the PNG information before the image. */
  182984. extern PNG_EXPORT(void,png_write_info_before_PLTE) PNGARG((png_structp png_ptr,
  182985. png_infop info_ptr));
  182986. extern PNG_EXPORT(void,png_write_info) PNGARG((png_structp png_ptr,
  182987. png_infop info_ptr));
  182988. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182989. /* read the information before the actual image data. */
  182990. extern PNG_EXPORT(void,png_read_info) PNGARG((png_structp png_ptr,
  182991. png_infop info_ptr));
  182992. #endif
  182993. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  182994. extern PNG_EXPORT(png_charp,png_convert_to_rfc1123)
  182995. PNGARG((png_structp png_ptr, png_timep ptime));
  182996. #endif
  182997. #if !defined(_WIN32_WCE)
  182998. /* "time.h" functions are not supported on WindowsCE */
  182999. #if defined(PNG_WRITE_tIME_SUPPORTED)
  183000. /* convert from a struct tm to png_time */
  183001. extern PNG_EXPORT(void,png_convert_from_struct_tm) PNGARG((png_timep ptime,
  183002. struct tm FAR * ttime));
  183003. /* convert from time_t to png_time. Uses gmtime() */
  183004. extern PNG_EXPORT(void,png_convert_from_time_t) PNGARG((png_timep ptime,
  183005. time_t ttime));
  183006. #endif /* PNG_WRITE_tIME_SUPPORTED */
  183007. #endif /* _WIN32_WCE */
  183008. #if defined(PNG_READ_EXPAND_SUPPORTED)
  183009. /* Expand data to 24-bit RGB, or 8-bit grayscale, with alpha if available. */
  183010. extern PNG_EXPORT(void,png_set_expand) PNGARG((png_structp png_ptr));
  183011. #if !defined(PNG_1_0_X)
  183012. extern PNG_EXPORT(void,png_set_expand_gray_1_2_4_to_8) PNGARG((png_structp
  183013. png_ptr));
  183014. #endif
  183015. extern PNG_EXPORT(void,png_set_palette_to_rgb) PNGARG((png_structp png_ptr));
  183016. extern PNG_EXPORT(void,png_set_tRNS_to_alpha) PNGARG((png_structp png_ptr));
  183017. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183018. /* Deprecated */
  183019. extern PNG_EXPORT(void,png_set_gray_1_2_4_to_8) PNGARG((png_structp png_ptr));
  183020. #endif
  183021. #endif
  183022. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  183023. /* Use blue, green, red order for pixels. */
  183024. extern PNG_EXPORT(void,png_set_bgr) PNGARG((png_structp png_ptr));
  183025. #endif
  183026. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  183027. /* Expand the grayscale to 24-bit RGB if necessary. */
  183028. extern PNG_EXPORT(void,png_set_gray_to_rgb) PNGARG((png_structp png_ptr));
  183029. #endif
  183030. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  183031. /* Reduce RGB to grayscale. */
  183032. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183033. extern PNG_EXPORT(void,png_set_rgb_to_gray) PNGARG((png_structp png_ptr,
  183034. int error_action, double red, double green ));
  183035. #endif
  183036. extern PNG_EXPORT(void,png_set_rgb_to_gray_fixed) PNGARG((png_structp png_ptr,
  183037. int error_action, png_fixed_point red, png_fixed_point green ));
  183038. extern PNG_EXPORT(png_byte,png_get_rgb_to_gray_status) PNGARG((png_structp
  183039. png_ptr));
  183040. #endif
  183041. extern PNG_EXPORT(void,png_build_grayscale_palette) PNGARG((int bit_depth,
  183042. png_colorp palette));
  183043. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  183044. extern PNG_EXPORT(void,png_set_strip_alpha) PNGARG((png_structp png_ptr));
  183045. #endif
  183046. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  183047. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  183048. extern PNG_EXPORT(void,png_set_swap_alpha) PNGARG((png_structp png_ptr));
  183049. #endif
  183050. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  183051. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  183052. extern PNG_EXPORT(void,png_set_invert_alpha) PNGARG((png_structp png_ptr));
  183053. #endif
  183054. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  183055. /* Add a filler byte to 8-bit Gray or 24-bit RGB images. */
  183056. extern PNG_EXPORT(void,png_set_filler) PNGARG((png_structp png_ptr,
  183057. png_uint_32 filler, int flags));
  183058. /* The values of the PNG_FILLER_ defines should NOT be changed */
  183059. #define PNG_FILLER_BEFORE 0
  183060. #define PNG_FILLER_AFTER 1
  183061. /* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
  183062. #if !defined(PNG_1_0_X)
  183063. extern PNG_EXPORT(void,png_set_add_alpha) PNGARG((png_structp png_ptr,
  183064. png_uint_32 filler, int flags));
  183065. #endif
  183066. #endif /* PNG_READ_FILLER_SUPPORTED || PNG_WRITE_FILLER_SUPPORTED */
  183067. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  183068. /* Swap bytes in 16-bit depth files. */
  183069. extern PNG_EXPORT(void,png_set_swap) PNGARG((png_structp png_ptr));
  183070. #endif
  183071. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  183072. /* Use 1 byte per pixel in 1, 2, or 4-bit depth files. */
  183073. extern PNG_EXPORT(void,png_set_packing) PNGARG((png_structp png_ptr));
  183074. #endif
  183075. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  183076. /* Swap packing order of pixels in bytes. */
  183077. extern PNG_EXPORT(void,png_set_packswap) PNGARG((png_structp png_ptr));
  183078. #endif
  183079. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  183080. /* Converts files to legal bit depths. */
  183081. extern PNG_EXPORT(void,png_set_shift) PNGARG((png_structp png_ptr,
  183082. png_color_8p true_bits));
  183083. #endif
  183084. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  183085. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  183086. /* Have the code handle the interlacing. Returns the number of passes. */
  183087. extern PNG_EXPORT(int,png_set_interlace_handling) PNGARG((png_structp png_ptr));
  183088. #endif
  183089. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  183090. /* Invert monochrome files */
  183091. extern PNG_EXPORT(void,png_set_invert_mono) PNGARG((png_structp png_ptr));
  183092. #endif
  183093. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  183094. /* Handle alpha and tRNS by replacing with a background color. */
  183095. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183096. extern PNG_EXPORT(void,png_set_background) PNGARG((png_structp png_ptr,
  183097. png_color_16p background_color, int background_gamma_code,
  183098. int need_expand, double background_gamma));
  183099. #endif
  183100. #define PNG_BACKGROUND_GAMMA_UNKNOWN 0
  183101. #define PNG_BACKGROUND_GAMMA_SCREEN 1
  183102. #define PNG_BACKGROUND_GAMMA_FILE 2
  183103. #define PNG_BACKGROUND_GAMMA_UNIQUE 3
  183104. #endif
  183105. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  183106. /* strip the second byte of information from a 16-bit depth file. */
  183107. extern PNG_EXPORT(void,png_set_strip_16) PNGARG((png_structp png_ptr));
  183108. #endif
  183109. #if defined(PNG_READ_DITHER_SUPPORTED)
  183110. /* Turn on dithering, and reduce the palette to the number of colors available. */
  183111. extern PNG_EXPORT(void,png_set_dither) PNGARG((png_structp png_ptr,
  183112. png_colorp palette, int num_palette, int maximum_colors,
  183113. png_uint_16p histogram, int full_dither));
  183114. #endif
  183115. #if defined(PNG_READ_GAMMA_SUPPORTED)
  183116. /* Handle gamma correction. Screen_gamma=(display_exponent) */
  183117. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183118. extern PNG_EXPORT(void,png_set_gamma) PNGARG((png_structp png_ptr,
  183119. double screen_gamma, double default_file_gamma));
  183120. #endif
  183121. #endif
  183122. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183123. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  183124. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  183125. /* Permit or disallow empty PLTE (0: not permitted, 1: permitted) */
  183126. /* Deprecated and will be removed. Use png_permit_mng_features() instead. */
  183127. extern PNG_EXPORT(void,png_permit_empty_plte) PNGARG((png_structp png_ptr,
  183128. int empty_plte_permitted));
  183129. #endif
  183130. #endif
  183131. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  183132. /* Set how many lines between output flushes - 0 for no flushing */
  183133. extern PNG_EXPORT(void,png_set_flush) PNGARG((png_structp png_ptr, int nrows));
  183134. /* Flush the current PNG output buffer */
  183135. extern PNG_EXPORT(void,png_write_flush) PNGARG((png_structp png_ptr));
  183136. #endif
  183137. /* optional update palette with requested transformations */
  183138. extern PNG_EXPORT(void,png_start_read_image) PNGARG((png_structp png_ptr));
  183139. /* optional call to update the users info structure */
  183140. extern PNG_EXPORT(void,png_read_update_info) PNGARG((png_structp png_ptr,
  183141. png_infop info_ptr));
  183142. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183143. /* read one or more rows of image data. */
  183144. extern PNG_EXPORT(void,png_read_rows) PNGARG((png_structp png_ptr,
  183145. png_bytepp row, png_bytepp display_row, png_uint_32 num_rows));
  183146. #endif
  183147. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183148. /* read a row of data. */
  183149. extern PNG_EXPORT(void,png_read_row) PNGARG((png_structp png_ptr,
  183150. png_bytep row,
  183151. png_bytep display_row));
  183152. #endif
  183153. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183154. /* read the whole image into memory at once. */
  183155. extern PNG_EXPORT(void,png_read_image) PNGARG((png_structp png_ptr,
  183156. png_bytepp image));
  183157. #endif
  183158. /* write a row of image data */
  183159. extern PNG_EXPORT(void,png_write_row) PNGARG((png_structp png_ptr,
  183160. png_bytep row));
  183161. /* write a few rows of image data */
  183162. extern PNG_EXPORT(void,png_write_rows) PNGARG((png_structp png_ptr,
  183163. png_bytepp row, png_uint_32 num_rows));
  183164. /* write the image data */
  183165. extern PNG_EXPORT(void,png_write_image) PNGARG((png_structp png_ptr,
  183166. png_bytepp image));
  183167. /* writes the end of the PNG file. */
  183168. extern PNG_EXPORT(void,png_write_end) PNGARG((png_structp png_ptr,
  183169. png_infop info_ptr));
  183170. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183171. /* read the end of the PNG file. */
  183172. extern PNG_EXPORT(void,png_read_end) PNGARG((png_structp png_ptr,
  183173. png_infop info_ptr));
  183174. #endif
  183175. /* free any memory associated with the png_info_struct */
  183176. extern PNG_EXPORT(void,png_destroy_info_struct) PNGARG((png_structp png_ptr,
  183177. png_infopp info_ptr_ptr));
  183178. /* free any memory associated with the png_struct and the png_info_structs */
  183179. extern PNG_EXPORT(void,png_destroy_read_struct) PNGARG((png_structpp
  183180. png_ptr_ptr, png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr));
  183181. /* free all memory used by the read (old method - NOT DLL EXPORTED) */
  183182. extern void png_read_destroy PNGARG((png_structp png_ptr, png_infop info_ptr,
  183183. png_infop end_info_ptr));
  183184. /* free any memory associated with the png_struct and the png_info_structs */
  183185. extern PNG_EXPORT(void,png_destroy_write_struct)
  183186. PNGARG((png_structpp png_ptr_ptr, png_infopp info_ptr_ptr));
  183187. /* free any memory used in png_ptr struct (old method - NOT DLL EXPORTED) */
  183188. extern void png_write_destroy PNGARG((png_structp png_ptr));
  183189. /* set the libpng method of handling chunk CRC errors */
  183190. extern PNG_EXPORT(void,png_set_crc_action) PNGARG((png_structp png_ptr,
  183191. int crit_action, int ancil_action));
  183192. /* Values for png_set_crc_action() to say how to handle CRC errors in
  183193. * ancillary and critical chunks, and whether to use the data contained
  183194. * therein. Note that it is impossible to "discard" data in a critical
  183195. * chunk. For versions prior to 0.90, the action was always error/quit,
  183196. * whereas in version 0.90 and later, the action for CRC errors in ancillary
  183197. * chunks is warn/discard. These values should NOT be changed.
  183198. *
  183199. * value action:critical action:ancillary
  183200. */
  183201. #define PNG_CRC_DEFAULT 0 /* error/quit warn/discard data */
  183202. #define PNG_CRC_ERROR_QUIT 1 /* error/quit error/quit */
  183203. #define PNG_CRC_WARN_DISCARD 2 /* (INVALID) warn/discard data */
  183204. #define PNG_CRC_WARN_USE 3 /* warn/use data warn/use data */
  183205. #define PNG_CRC_QUIET_USE 4 /* quiet/use data quiet/use data */
  183206. #define PNG_CRC_NO_CHANGE 5 /* use current value use current value */
  183207. /* These functions give the user control over the scan-line filtering in
  183208. * libpng and the compression methods used by zlib. These functions are
  183209. * mainly useful for testing, as the defaults should work with most users.
  183210. * Those users who are tight on memory or want faster performance at the
  183211. * expense of compression can modify them. See the compression library
  183212. * header file (zlib.h) for an explination of the compression functions.
  183213. */
  183214. /* set the filtering method(s) used by libpng. Currently, the only valid
  183215. * value for "method" is 0.
  183216. */
  183217. extern PNG_EXPORT(void,png_set_filter) PNGARG((png_structp png_ptr, int method,
  183218. int filters));
  183219. /* Flags for png_set_filter() to say which filters to use. The flags
  183220. * are chosen so that they don't conflict with real filter types
  183221. * below, in case they are supplied instead of the #defined constants.
  183222. * These values should NOT be changed.
  183223. */
  183224. #define PNG_NO_FILTERS 0x00
  183225. #define PNG_FILTER_NONE 0x08
  183226. #define PNG_FILTER_SUB 0x10
  183227. #define PNG_FILTER_UP 0x20
  183228. #define PNG_FILTER_AVG 0x40
  183229. #define PNG_FILTER_PAETH 0x80
  183230. #define PNG_ALL_FILTERS (PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP | \
  183231. PNG_FILTER_AVG | PNG_FILTER_PAETH)
  183232. /* Filter values (not flags) - used in pngwrite.c, pngwutil.c for now.
  183233. * These defines should NOT be changed.
  183234. */
  183235. #define PNG_FILTER_VALUE_NONE 0
  183236. #define PNG_FILTER_VALUE_SUB 1
  183237. #define PNG_FILTER_VALUE_UP 2
  183238. #define PNG_FILTER_VALUE_AVG 3
  183239. #define PNG_FILTER_VALUE_PAETH 4
  183240. #define PNG_FILTER_VALUE_LAST 5
  183241. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* EXPERIMENTAL */
  183242. /* The "heuristic_method" is given by one of the PNG_FILTER_HEURISTIC_
  183243. * defines, either the default (minimum-sum-of-absolute-differences), or
  183244. * the experimental method (weighted-minimum-sum-of-absolute-differences).
  183245. *
  183246. * Weights are factors >= 1.0, indicating how important it is to keep the
  183247. * filter type consistent between rows. Larger numbers mean the current
  183248. * filter is that many times as likely to be the same as the "num_weights"
  183249. * previous filters. This is cumulative for each previous row with a weight.
  183250. * There needs to be "num_weights" values in "filter_weights", or it can be
  183251. * NULL if the weights aren't being specified. Weights have no influence on
  183252. * the selection of the first row filter. Well chosen weights can (in theory)
  183253. * improve the compression for a given image.
  183254. *
  183255. * Costs are factors >= 1.0 indicating the relative decoding costs of a
  183256. * filter type. Higher costs indicate more decoding expense, and are
  183257. * therefore less likely to be selected over a filter with lower computational
  183258. * costs. There needs to be a value in "filter_costs" for each valid filter
  183259. * type (given by PNG_FILTER_VALUE_LAST), or it can be NULL if you aren't
  183260. * setting the costs. Costs try to improve the speed of decompression without
  183261. * unduly increasing the compressed image size.
  183262. *
  183263. * A negative weight or cost indicates the default value is to be used, and
  183264. * values in the range [0.0, 1.0) indicate the value is to remain unchanged.
  183265. * The default values for both weights and costs are currently 1.0, but may
  183266. * change if good general weighting/cost heuristics can be found. If both
  183267. * the weights and costs are set to 1.0, this degenerates the WEIGHTED method
  183268. * to the UNWEIGHTED method, but with added encoding time/computation.
  183269. */
  183270. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183271. extern PNG_EXPORT(void,png_set_filter_heuristics) PNGARG((png_structp png_ptr,
  183272. int heuristic_method, int num_weights, png_doublep filter_weights,
  183273. png_doublep filter_costs));
  183274. #endif
  183275. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  183276. /* Heuristic used for row filter selection. These defines should NOT be
  183277. * changed.
  183278. */
  183279. #define PNG_FILTER_HEURISTIC_DEFAULT 0 /* Currently "UNWEIGHTED" */
  183280. #define PNG_FILTER_HEURISTIC_UNWEIGHTED 1 /* Used by libpng < 0.95 */
  183281. #define PNG_FILTER_HEURISTIC_WEIGHTED 2 /* Experimental feature */
  183282. #define PNG_FILTER_HEURISTIC_LAST 3 /* Not a valid value */
  183283. /* Set the library compression level. Currently, valid values range from
  183284. * 0 - 9, corresponding directly to the zlib compression levels 0 - 9
  183285. * (0 - no compression, 9 - "maximal" compression). Note that tests have
  183286. * shown that zlib compression levels 3-6 usually perform as well as level 9
  183287. * for PNG images, and do considerably fewer caclulations. In the future,
  183288. * these values may not correspond directly to the zlib compression levels.
  183289. */
  183290. extern PNG_EXPORT(void,png_set_compression_level) PNGARG((png_structp png_ptr,
  183291. int level));
  183292. extern PNG_EXPORT(void,png_set_compression_mem_level)
  183293. PNGARG((png_structp png_ptr, int mem_level));
  183294. extern PNG_EXPORT(void,png_set_compression_strategy)
  183295. PNGARG((png_structp png_ptr, int strategy));
  183296. extern PNG_EXPORT(void,png_set_compression_window_bits)
  183297. PNGARG((png_structp png_ptr, int window_bits));
  183298. extern PNG_EXPORT(void,png_set_compression_method) PNGARG((png_structp png_ptr,
  183299. int method));
  183300. /* These next functions are called for input/output, memory, and error
  183301. * handling. They are in the file pngrio.c, pngwio.c, and pngerror.c,
  183302. * and call standard C I/O routines such as fread(), fwrite(), and
  183303. * fprintf(). These functions can be made to use other I/O routines
  183304. * at run time for those applications that need to handle I/O in a
  183305. * different manner by calling png_set_???_fn(). See libpng.txt for
  183306. * more information.
  183307. */
  183308. #if !defined(PNG_NO_STDIO)
  183309. /* Initialize the input/output for the PNG file to the default functions. */
  183310. extern PNG_EXPORT(void,png_init_io) PNGARG((png_structp png_ptr, png_FILE_p fp));
  183311. #endif
  183312. /* Replace the (error and abort), and warning functions with user
  183313. * supplied functions. If no messages are to be printed you must still
  183314. * write and use replacement functions. The replacement error_fn should
  183315. * still do a longjmp to the last setjmp location if you are using this
  183316. * method of error handling. If error_fn or warning_fn is NULL, the
  183317. * default function will be used.
  183318. */
  183319. extern PNG_EXPORT(void,png_set_error_fn) PNGARG((png_structp png_ptr,
  183320. png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warning_fn));
  183321. /* Return the user pointer associated with the error functions */
  183322. extern PNG_EXPORT(png_voidp,png_get_error_ptr) PNGARG((png_structp png_ptr));
  183323. /* Replace the default data output functions with a user supplied one(s).
  183324. * If buffered output is not used, then output_flush_fn can be set to NULL.
  183325. * If PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile time
  183326. * output_flush_fn will be ignored (and thus can be NULL).
  183327. */
  183328. extern PNG_EXPORT(void,png_set_write_fn) PNGARG((png_structp png_ptr,
  183329. png_voidp io_ptr, png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn));
  183330. /* Replace the default data input function with a user supplied one. */
  183331. extern PNG_EXPORT(void,png_set_read_fn) PNGARG((png_structp png_ptr,
  183332. png_voidp io_ptr, png_rw_ptr read_data_fn));
  183333. /* Return the user pointer associated with the I/O functions */
  183334. extern PNG_EXPORT(png_voidp,png_get_io_ptr) PNGARG((png_structp png_ptr));
  183335. extern PNG_EXPORT(void,png_set_read_status_fn) PNGARG((png_structp png_ptr,
  183336. png_read_status_ptr read_row_fn));
  183337. extern PNG_EXPORT(void,png_set_write_status_fn) PNGARG((png_structp png_ptr,
  183338. png_write_status_ptr write_row_fn));
  183339. #ifdef PNG_USER_MEM_SUPPORTED
  183340. /* Replace the default memory allocation functions with user supplied one(s). */
  183341. extern PNG_EXPORT(void,png_set_mem_fn) PNGARG((png_structp png_ptr,
  183342. png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  183343. /* Return the user pointer associated with the memory functions */
  183344. extern PNG_EXPORT(png_voidp,png_get_mem_ptr) PNGARG((png_structp png_ptr));
  183345. #endif
  183346. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  183347. defined(PNG_LEGACY_SUPPORTED)
  183348. extern PNG_EXPORT(void,png_set_read_user_transform_fn) PNGARG((png_structp
  183349. png_ptr, png_user_transform_ptr read_user_transform_fn));
  183350. #endif
  183351. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  183352. defined(PNG_LEGACY_SUPPORTED)
  183353. extern PNG_EXPORT(void,png_set_write_user_transform_fn) PNGARG((png_structp
  183354. png_ptr, png_user_transform_ptr write_user_transform_fn));
  183355. #endif
  183356. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  183357. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  183358. defined(PNG_LEGACY_SUPPORTED)
  183359. extern PNG_EXPORT(void,png_set_user_transform_info) PNGARG((png_structp
  183360. png_ptr, png_voidp user_transform_ptr, int user_transform_depth,
  183361. int user_transform_channels));
  183362. /* Return the user pointer associated with the user transform functions */
  183363. extern PNG_EXPORT(png_voidp,png_get_user_transform_ptr)
  183364. PNGARG((png_structp png_ptr));
  183365. #endif
  183366. #ifdef PNG_USER_CHUNKS_SUPPORTED
  183367. extern PNG_EXPORT(void,png_set_read_user_chunk_fn) PNGARG((png_structp png_ptr,
  183368. png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn));
  183369. extern PNG_EXPORT(png_voidp,png_get_user_chunk_ptr) PNGARG((png_structp
  183370. png_ptr));
  183371. #endif
  183372. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183373. /* Sets the function callbacks for the push reader, and a pointer to a
  183374. * user-defined structure available to the callback functions.
  183375. */
  183376. extern PNG_EXPORT(void,png_set_progressive_read_fn) PNGARG((png_structp png_ptr,
  183377. png_voidp progressive_ptr,
  183378. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  183379. png_progressive_end_ptr end_fn));
  183380. /* returns the user pointer associated with the push read functions */
  183381. extern PNG_EXPORT(png_voidp,png_get_progressive_ptr)
  183382. PNGARG((png_structp png_ptr));
  183383. /* function to be called when data becomes available */
  183384. extern PNG_EXPORT(void,png_process_data) PNGARG((png_structp png_ptr,
  183385. png_infop info_ptr, png_bytep buffer, png_size_t buffer_size));
  183386. /* function that combines rows. Not very much different than the
  183387. * png_combine_row() call. Is this even used?????
  183388. */
  183389. extern PNG_EXPORT(void,png_progressive_combine_row) PNGARG((png_structp png_ptr,
  183390. png_bytep old_row, png_bytep new_row));
  183391. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  183392. extern PNG_EXPORT(png_voidp,png_malloc) PNGARG((png_structp png_ptr,
  183393. png_uint_32 size));
  183394. #if defined(PNG_1_0_X)
  183395. # define png_malloc_warn png_malloc
  183396. #else
  183397. /* Added at libpng version 1.2.4 */
  183398. extern PNG_EXPORT(png_voidp,png_malloc_warn) PNGARG((png_structp png_ptr,
  183399. png_uint_32 size));
  183400. #endif
  183401. /* frees a pointer allocated by png_malloc() */
  183402. extern PNG_EXPORT(void,png_free) PNGARG((png_structp png_ptr, png_voidp ptr));
  183403. #if defined(PNG_1_0_X)
  183404. /* Function to allocate memory for zlib. */
  183405. extern PNG_EXPORT(voidpf,png_zalloc) PNGARG((voidpf png_ptr, uInt items,
  183406. uInt size));
  183407. /* Function to free memory for zlib */
  183408. extern PNG_EXPORT(void,png_zfree) PNGARG((voidpf png_ptr, voidpf ptr));
  183409. #endif
  183410. /* Free data that was allocated internally */
  183411. extern PNG_EXPORT(void,png_free_data) PNGARG((png_structp png_ptr,
  183412. png_infop info_ptr, png_uint_32 free_me, int num));
  183413. #ifdef PNG_FREE_ME_SUPPORTED
  183414. /* Reassign responsibility for freeing existing data, whether allocated
  183415. * by libpng or by the application */
  183416. extern PNG_EXPORT(void,png_data_freer) PNGARG((png_structp png_ptr,
  183417. png_infop info_ptr, int freer, png_uint_32 mask));
  183418. #endif
  183419. /* assignments for png_data_freer */
  183420. #define PNG_DESTROY_WILL_FREE_DATA 1
  183421. #define PNG_SET_WILL_FREE_DATA 1
  183422. #define PNG_USER_WILL_FREE_DATA 2
  183423. /* Flags for png_ptr->free_me and info_ptr->free_me */
  183424. #define PNG_FREE_HIST 0x0008
  183425. #define PNG_FREE_ICCP 0x0010
  183426. #define PNG_FREE_SPLT 0x0020
  183427. #define PNG_FREE_ROWS 0x0040
  183428. #define PNG_FREE_PCAL 0x0080
  183429. #define PNG_FREE_SCAL 0x0100
  183430. #define PNG_FREE_UNKN 0x0200
  183431. #define PNG_FREE_LIST 0x0400
  183432. #define PNG_FREE_PLTE 0x1000
  183433. #define PNG_FREE_TRNS 0x2000
  183434. #define PNG_FREE_TEXT 0x4000
  183435. #define PNG_FREE_ALL 0x7fff
  183436. #define PNG_FREE_MUL 0x4220 /* PNG_FREE_SPLT|PNG_FREE_TEXT|PNG_FREE_UNKN */
  183437. #ifdef PNG_USER_MEM_SUPPORTED
  183438. extern PNG_EXPORT(png_voidp,png_malloc_default) PNGARG((png_structp png_ptr,
  183439. png_uint_32 size));
  183440. extern PNG_EXPORT(void,png_free_default) PNGARG((png_structp png_ptr,
  183441. png_voidp ptr));
  183442. #endif
  183443. extern PNG_EXPORT(png_voidp,png_memcpy_check) PNGARG((png_structp png_ptr,
  183444. png_voidp s1, png_voidp s2, png_uint_32 size));
  183445. extern PNG_EXPORT(png_voidp,png_memset_check) PNGARG((png_structp png_ptr,
  183446. png_voidp s1, int value, png_uint_32 size));
  183447. #if defined(USE_FAR_KEYWORD) /* memory model conversion function */
  183448. extern void *png_far_to_near PNGARG((png_structp png_ptr,png_voidp ptr,
  183449. int check));
  183450. #endif /* USE_FAR_KEYWORD */
  183451. #ifndef PNG_NO_ERROR_TEXT
  183452. /* Fatal error in PNG image of libpng - can't continue */
  183453. extern PNG_EXPORT(void,png_error) PNGARG((png_structp png_ptr,
  183454. png_const_charp error_message));
  183455. /* The same, but the chunk name is prepended to the error string. */
  183456. extern PNG_EXPORT(void,png_chunk_error) PNGARG((png_structp png_ptr,
  183457. png_const_charp error_message));
  183458. #else
  183459. /* Fatal error in PNG image of libpng - can't continue */
  183460. extern PNG_EXPORT(void,png_err) PNGARG((png_structp png_ptr));
  183461. #endif
  183462. #ifndef PNG_NO_WARNINGS
  183463. /* Non-fatal error in libpng. Can continue, but may have a problem. */
  183464. extern PNG_EXPORT(void,png_warning) PNGARG((png_structp png_ptr,
  183465. png_const_charp warning_message));
  183466. #ifdef PNG_READ_SUPPORTED
  183467. /* Non-fatal error in libpng, chunk name is prepended to message. */
  183468. extern PNG_EXPORT(void,png_chunk_warning) PNGARG((png_structp png_ptr,
  183469. png_const_charp warning_message));
  183470. #endif /* PNG_READ_SUPPORTED */
  183471. #endif /* PNG_NO_WARNINGS */
  183472. /* The png_set_<chunk> functions are for storing values in the png_info_struct.
  183473. * Similarly, the png_get_<chunk> calls are used to read values from the
  183474. * png_info_struct, either storing the parameters in the passed variables, or
  183475. * setting pointers into the png_info_struct where the data is stored. The
  183476. * png_get_<chunk> functions return a non-zero value if the data was available
  183477. * in info_ptr, or return zero and do not change any of the parameters if the
  183478. * data was not available.
  183479. *
  183480. * These functions should be used instead of directly accessing png_info
  183481. * to avoid problems with future changes in the size and internal layout of
  183482. * png_info_struct.
  183483. */
  183484. /* Returns "flag" if chunk data is valid in info_ptr. */
  183485. extern PNG_EXPORT(png_uint_32,png_get_valid) PNGARG((png_structp png_ptr,
  183486. png_infop info_ptr, png_uint_32 flag));
  183487. /* Returns number of bytes needed to hold a transformed row. */
  183488. extern PNG_EXPORT(png_uint_32,png_get_rowbytes) PNGARG((png_structp png_ptr,
  183489. png_infop info_ptr));
  183490. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  183491. /* Returns row_pointers, which is an array of pointers to scanlines that was
  183492. returned from png_read_png(). */
  183493. extern PNG_EXPORT(png_bytepp,png_get_rows) PNGARG((png_structp png_ptr,
  183494. png_infop info_ptr));
  183495. /* Set row_pointers, which is an array of pointers to scanlines for use
  183496. by png_write_png(). */
  183497. extern PNG_EXPORT(void,png_set_rows) PNGARG((png_structp png_ptr,
  183498. png_infop info_ptr, png_bytepp row_pointers));
  183499. #endif
  183500. /* Returns number of color channels in image. */
  183501. extern PNG_EXPORT(png_byte,png_get_channels) PNGARG((png_structp png_ptr,
  183502. png_infop info_ptr));
  183503. #ifdef PNG_EASY_ACCESS_SUPPORTED
  183504. /* Returns image width in pixels. */
  183505. extern PNG_EXPORT(png_uint_32, png_get_image_width) PNGARG((png_structp
  183506. png_ptr, png_infop info_ptr));
  183507. /* Returns image height in pixels. */
  183508. extern PNG_EXPORT(png_uint_32, png_get_image_height) PNGARG((png_structp
  183509. png_ptr, png_infop info_ptr));
  183510. /* Returns image bit_depth. */
  183511. extern PNG_EXPORT(png_byte, png_get_bit_depth) PNGARG((png_structp
  183512. png_ptr, png_infop info_ptr));
  183513. /* Returns image color_type. */
  183514. extern PNG_EXPORT(png_byte, png_get_color_type) PNGARG((png_structp
  183515. png_ptr, png_infop info_ptr));
  183516. /* Returns image filter_type. */
  183517. extern PNG_EXPORT(png_byte, png_get_filter_type) PNGARG((png_structp
  183518. png_ptr, png_infop info_ptr));
  183519. /* Returns image interlace_type. */
  183520. extern PNG_EXPORT(png_byte, png_get_interlace_type) PNGARG((png_structp
  183521. png_ptr, png_infop info_ptr));
  183522. /* Returns image compression_type. */
  183523. extern PNG_EXPORT(png_byte, png_get_compression_type) PNGARG((png_structp
  183524. png_ptr, png_infop info_ptr));
  183525. /* Returns image resolution in pixels per meter, from pHYs chunk data. */
  183526. extern PNG_EXPORT(png_uint_32, png_get_pixels_per_meter) PNGARG((png_structp
  183527. png_ptr, png_infop info_ptr));
  183528. extern PNG_EXPORT(png_uint_32, png_get_x_pixels_per_meter) PNGARG((png_structp
  183529. png_ptr, png_infop info_ptr));
  183530. extern PNG_EXPORT(png_uint_32, png_get_y_pixels_per_meter) PNGARG((png_structp
  183531. png_ptr, png_infop info_ptr));
  183532. /* Returns pixel aspect ratio, computed from pHYs chunk data. */
  183533. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183534. extern PNG_EXPORT(float, png_get_pixel_aspect_ratio) PNGARG((png_structp
  183535. png_ptr, png_infop info_ptr));
  183536. #endif
  183537. /* Returns image x, y offset in pixels or microns, from oFFs chunk data. */
  183538. extern PNG_EXPORT(png_int_32, png_get_x_offset_pixels) PNGARG((png_structp
  183539. png_ptr, png_infop info_ptr));
  183540. extern PNG_EXPORT(png_int_32, png_get_y_offset_pixels) PNGARG((png_structp
  183541. png_ptr, png_infop info_ptr));
  183542. extern PNG_EXPORT(png_int_32, png_get_x_offset_microns) PNGARG((png_structp
  183543. png_ptr, png_infop info_ptr));
  183544. extern PNG_EXPORT(png_int_32, png_get_y_offset_microns) PNGARG((png_structp
  183545. png_ptr, png_infop info_ptr));
  183546. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  183547. /* Returns pointer to signature string read from PNG header */
  183548. extern PNG_EXPORT(png_bytep,png_get_signature) PNGARG((png_structp png_ptr,
  183549. png_infop info_ptr));
  183550. #if defined(PNG_bKGD_SUPPORTED)
  183551. extern PNG_EXPORT(png_uint_32,png_get_bKGD) PNGARG((png_structp png_ptr,
  183552. png_infop info_ptr, png_color_16p *background));
  183553. #endif
  183554. #if defined(PNG_bKGD_SUPPORTED)
  183555. extern PNG_EXPORT(void,png_set_bKGD) PNGARG((png_structp png_ptr,
  183556. png_infop info_ptr, png_color_16p background));
  183557. #endif
  183558. #if defined(PNG_cHRM_SUPPORTED)
  183559. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183560. extern PNG_EXPORT(png_uint_32,png_get_cHRM) PNGARG((png_structp png_ptr,
  183561. png_infop info_ptr, double *white_x, double *white_y, double *red_x,
  183562. double *red_y, double *green_x, double *green_y, double *blue_x,
  183563. double *blue_y));
  183564. #endif
  183565. #ifdef PNG_FIXED_POINT_SUPPORTED
  183566. extern PNG_EXPORT(png_uint_32,png_get_cHRM_fixed) PNGARG((png_structp png_ptr,
  183567. png_infop info_ptr, png_fixed_point *int_white_x, png_fixed_point
  183568. *int_white_y, png_fixed_point *int_red_x, png_fixed_point *int_red_y,
  183569. png_fixed_point *int_green_x, png_fixed_point *int_green_y, png_fixed_point
  183570. *int_blue_x, png_fixed_point *int_blue_y));
  183571. #endif
  183572. #endif
  183573. #if defined(PNG_cHRM_SUPPORTED)
  183574. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183575. extern PNG_EXPORT(void,png_set_cHRM) PNGARG((png_structp png_ptr,
  183576. png_infop info_ptr, double white_x, double white_y, double red_x,
  183577. double red_y, double green_x, double green_y, double blue_x, double blue_y));
  183578. #endif
  183579. #ifdef PNG_FIXED_POINT_SUPPORTED
  183580. extern PNG_EXPORT(void,png_set_cHRM_fixed) PNGARG((png_structp png_ptr,
  183581. png_infop info_ptr, png_fixed_point int_white_x, png_fixed_point int_white_y,
  183582. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  183583. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  183584. png_fixed_point int_blue_y));
  183585. #endif
  183586. #endif
  183587. #if defined(PNG_gAMA_SUPPORTED)
  183588. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183589. extern PNG_EXPORT(png_uint_32,png_get_gAMA) PNGARG((png_structp png_ptr,
  183590. png_infop info_ptr, double *file_gamma));
  183591. #endif
  183592. extern PNG_EXPORT(png_uint_32,png_get_gAMA_fixed) PNGARG((png_structp png_ptr,
  183593. png_infop info_ptr, png_fixed_point *int_file_gamma));
  183594. #endif
  183595. #if defined(PNG_gAMA_SUPPORTED)
  183596. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183597. extern PNG_EXPORT(void,png_set_gAMA) PNGARG((png_structp png_ptr,
  183598. png_infop info_ptr, double file_gamma));
  183599. #endif
  183600. extern PNG_EXPORT(void,png_set_gAMA_fixed) PNGARG((png_structp png_ptr,
  183601. png_infop info_ptr, png_fixed_point int_file_gamma));
  183602. #endif
  183603. #if defined(PNG_hIST_SUPPORTED)
  183604. extern PNG_EXPORT(png_uint_32,png_get_hIST) PNGARG((png_structp png_ptr,
  183605. png_infop info_ptr, png_uint_16p *hist));
  183606. #endif
  183607. #if defined(PNG_hIST_SUPPORTED)
  183608. extern PNG_EXPORT(void,png_set_hIST) PNGARG((png_structp png_ptr,
  183609. png_infop info_ptr, png_uint_16p hist));
  183610. #endif
  183611. extern PNG_EXPORT(png_uint_32,png_get_IHDR) PNGARG((png_structp png_ptr,
  183612. png_infop info_ptr, png_uint_32 *width, png_uint_32 *height,
  183613. int *bit_depth, int *color_type, int *interlace_method,
  183614. int *compression_method, int *filter_method));
  183615. extern PNG_EXPORT(void,png_set_IHDR) PNGARG((png_structp png_ptr,
  183616. png_infop info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth,
  183617. int color_type, int interlace_method, int compression_method,
  183618. int filter_method));
  183619. #if defined(PNG_oFFs_SUPPORTED)
  183620. extern PNG_EXPORT(png_uint_32,png_get_oFFs) PNGARG((png_structp png_ptr,
  183621. png_infop info_ptr, png_int_32 *offset_x, png_int_32 *offset_y,
  183622. int *unit_type));
  183623. #endif
  183624. #if defined(PNG_oFFs_SUPPORTED)
  183625. extern PNG_EXPORT(void,png_set_oFFs) PNGARG((png_structp png_ptr,
  183626. png_infop info_ptr, png_int_32 offset_x, png_int_32 offset_y,
  183627. int unit_type));
  183628. #endif
  183629. #if defined(PNG_pCAL_SUPPORTED)
  183630. extern PNG_EXPORT(png_uint_32,png_get_pCAL) PNGARG((png_structp png_ptr,
  183631. png_infop info_ptr, png_charp *purpose, png_int_32 *X0, png_int_32 *X1,
  183632. int *type, int *nparams, png_charp *units, png_charpp *params));
  183633. #endif
  183634. #if defined(PNG_pCAL_SUPPORTED)
  183635. extern PNG_EXPORT(void,png_set_pCAL) PNGARG((png_structp png_ptr,
  183636. png_infop info_ptr, png_charp purpose, png_int_32 X0, png_int_32 X1,
  183637. int type, int nparams, png_charp units, png_charpp params));
  183638. #endif
  183639. #if defined(PNG_pHYs_SUPPORTED)
  183640. extern PNG_EXPORT(png_uint_32,png_get_pHYs) PNGARG((png_structp png_ptr,
  183641. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  183642. #endif
  183643. #if defined(PNG_pHYs_SUPPORTED)
  183644. extern PNG_EXPORT(void,png_set_pHYs) PNGARG((png_structp png_ptr,
  183645. png_infop info_ptr, png_uint_32 res_x, png_uint_32 res_y, int unit_type));
  183646. #endif
  183647. extern PNG_EXPORT(png_uint_32,png_get_PLTE) PNGARG((png_structp png_ptr,
  183648. png_infop info_ptr, png_colorp *palette, int *num_palette));
  183649. extern PNG_EXPORT(void,png_set_PLTE) PNGARG((png_structp png_ptr,
  183650. png_infop info_ptr, png_colorp palette, int num_palette));
  183651. #if defined(PNG_sBIT_SUPPORTED)
  183652. extern PNG_EXPORT(png_uint_32,png_get_sBIT) PNGARG((png_structp png_ptr,
  183653. png_infop info_ptr, png_color_8p *sig_bit));
  183654. #endif
  183655. #if defined(PNG_sBIT_SUPPORTED)
  183656. extern PNG_EXPORT(void,png_set_sBIT) PNGARG((png_structp png_ptr,
  183657. png_infop info_ptr, png_color_8p sig_bit));
  183658. #endif
  183659. #if defined(PNG_sRGB_SUPPORTED)
  183660. extern PNG_EXPORT(png_uint_32,png_get_sRGB) PNGARG((png_structp png_ptr,
  183661. png_infop info_ptr, int *intent));
  183662. #endif
  183663. #if defined(PNG_sRGB_SUPPORTED)
  183664. extern PNG_EXPORT(void,png_set_sRGB) PNGARG((png_structp png_ptr,
  183665. png_infop info_ptr, int intent));
  183666. extern PNG_EXPORT(void,png_set_sRGB_gAMA_and_cHRM) PNGARG((png_structp png_ptr,
  183667. png_infop info_ptr, int intent));
  183668. #endif
  183669. #if defined(PNG_iCCP_SUPPORTED)
  183670. extern PNG_EXPORT(png_uint_32,png_get_iCCP) PNGARG((png_structp png_ptr,
  183671. png_infop info_ptr, png_charpp name, int *compression_type,
  183672. png_charpp profile, png_uint_32 *proflen));
  183673. /* Note to maintainer: profile should be png_bytepp */
  183674. #endif
  183675. #if defined(PNG_iCCP_SUPPORTED)
  183676. extern PNG_EXPORT(void,png_set_iCCP) PNGARG((png_structp png_ptr,
  183677. png_infop info_ptr, png_charp name, int compression_type,
  183678. png_charp profile, png_uint_32 proflen));
  183679. /* Note to maintainer: profile should be png_bytep */
  183680. #endif
  183681. #if defined(PNG_sPLT_SUPPORTED)
  183682. extern PNG_EXPORT(png_uint_32,png_get_sPLT) PNGARG((png_structp png_ptr,
  183683. png_infop info_ptr, png_sPLT_tpp entries));
  183684. #endif
  183685. #if defined(PNG_sPLT_SUPPORTED)
  183686. extern PNG_EXPORT(void,png_set_sPLT) PNGARG((png_structp png_ptr,
  183687. png_infop info_ptr, png_sPLT_tp entries, int nentries));
  183688. #endif
  183689. #if defined(PNG_TEXT_SUPPORTED)
  183690. /* png_get_text also returns the number of text chunks in *num_text */
  183691. extern PNG_EXPORT(png_uint_32,png_get_text) PNGARG((png_structp png_ptr,
  183692. png_infop info_ptr, png_textp *text_ptr, int *num_text));
  183693. #endif
  183694. /*
  183695. * Note while png_set_text() will accept a structure whose text,
  183696. * language, and translated keywords are NULL pointers, the structure
  183697. * returned by png_get_text will always contain regular
  183698. * zero-terminated C strings. They might be empty strings but
  183699. * they will never be NULL pointers.
  183700. */
  183701. #if defined(PNG_TEXT_SUPPORTED)
  183702. extern PNG_EXPORT(void,png_set_text) PNGARG((png_structp png_ptr,
  183703. png_infop info_ptr, png_textp text_ptr, int num_text));
  183704. #endif
  183705. #if defined(PNG_tIME_SUPPORTED)
  183706. extern PNG_EXPORT(png_uint_32,png_get_tIME) PNGARG((png_structp png_ptr,
  183707. png_infop info_ptr, png_timep *mod_time));
  183708. #endif
  183709. #if defined(PNG_tIME_SUPPORTED)
  183710. extern PNG_EXPORT(void,png_set_tIME) PNGARG((png_structp png_ptr,
  183711. png_infop info_ptr, png_timep mod_time));
  183712. #endif
  183713. #if defined(PNG_tRNS_SUPPORTED)
  183714. extern PNG_EXPORT(png_uint_32,png_get_tRNS) PNGARG((png_structp png_ptr,
  183715. png_infop info_ptr, png_bytep *trans, int *num_trans,
  183716. png_color_16p *trans_values));
  183717. #endif
  183718. #if defined(PNG_tRNS_SUPPORTED)
  183719. extern PNG_EXPORT(void,png_set_tRNS) PNGARG((png_structp png_ptr,
  183720. png_infop info_ptr, png_bytep trans, int num_trans,
  183721. png_color_16p trans_values));
  183722. #endif
  183723. #if defined(PNG_tRNS_SUPPORTED)
  183724. #endif
  183725. #if defined(PNG_sCAL_SUPPORTED)
  183726. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183727. extern PNG_EXPORT(png_uint_32,png_get_sCAL) PNGARG((png_structp png_ptr,
  183728. png_infop info_ptr, int *unit, double *width, double *height));
  183729. #else
  183730. #ifdef PNG_FIXED_POINT_SUPPORTED
  183731. extern PNG_EXPORT(png_uint_32,png_get_sCAL_s) PNGARG((png_structp png_ptr,
  183732. png_infop info_ptr, int *unit, png_charpp swidth, png_charpp sheight));
  183733. #endif
  183734. #endif
  183735. #endif /* PNG_sCAL_SUPPORTED */
  183736. #if defined(PNG_sCAL_SUPPORTED)
  183737. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183738. extern PNG_EXPORT(void,png_set_sCAL) PNGARG((png_structp png_ptr,
  183739. png_infop info_ptr, int unit, double width, double height));
  183740. #else
  183741. #ifdef PNG_FIXED_POINT_SUPPORTED
  183742. extern PNG_EXPORT(void,png_set_sCAL_s) PNGARG((png_structp png_ptr,
  183743. png_infop info_ptr, int unit, png_charp swidth, png_charp sheight));
  183744. #endif
  183745. #endif
  183746. #endif /* PNG_sCAL_SUPPORTED || PNG_WRITE_sCAL_SUPPORTED */
  183747. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  183748. /* provide a list of chunks and how they are to be handled, if the built-in
  183749. handling or default unknown chunk handling is not desired. Any chunks not
  183750. listed will be handled in the default manner. The IHDR and IEND chunks
  183751. must not be listed.
  183752. keep = 0: follow default behaviour
  183753. = 1: do not keep
  183754. = 2: keep only if safe-to-copy
  183755. = 3: keep even if unsafe-to-copy
  183756. */
  183757. extern PNG_EXPORT(void, png_set_keep_unknown_chunks) PNGARG((png_structp
  183758. png_ptr, int keep, png_bytep chunk_list, int num_chunks));
  183759. extern PNG_EXPORT(void, png_set_unknown_chunks) PNGARG((png_structp png_ptr,
  183760. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns));
  183761. extern PNG_EXPORT(void, png_set_unknown_chunk_location)
  183762. PNGARG((png_structp png_ptr, png_infop info_ptr, int chunk, int location));
  183763. extern PNG_EXPORT(png_uint_32,png_get_unknown_chunks) PNGARG((png_structp
  183764. png_ptr, png_infop info_ptr, png_unknown_chunkpp entries));
  183765. #endif
  183766. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  183767. PNG_EXPORT(int,png_handle_as_unknown) PNGARG((png_structp png_ptr, png_bytep
  183768. chunk_name));
  183769. #endif
  183770. /* Png_free_data() will turn off the "valid" flag for anything it frees.
  183771. If you need to turn it off for a chunk that your application has freed,
  183772. you can use png_set_invalid(png_ptr, info_ptr, PNG_INFO_CHNK); */
  183773. extern PNG_EXPORT(void, png_set_invalid) PNGARG((png_structp png_ptr,
  183774. png_infop info_ptr, int mask));
  183775. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  183776. /* The "params" pointer is currently not used and is for future expansion. */
  183777. extern PNG_EXPORT(void, png_read_png) PNGARG((png_structp png_ptr,
  183778. png_infop info_ptr,
  183779. int transforms,
  183780. png_voidp params));
  183781. extern PNG_EXPORT(void, png_write_png) PNGARG((png_structp png_ptr,
  183782. png_infop info_ptr,
  183783. int transforms,
  183784. png_voidp params));
  183785. #endif
  183786. /* Define PNG_DEBUG at compile time for debugging information. Higher
  183787. * numbers for PNG_DEBUG mean more debugging information. This has
  183788. * only been added since version 0.95 so it is not implemented throughout
  183789. * libpng yet, but more support will be added as needed.
  183790. */
  183791. #ifdef PNG_DEBUG
  183792. #if (PNG_DEBUG > 0)
  183793. #if !defined(PNG_DEBUG_FILE) && defined(_MSC_VER)
  183794. #include <crtdbg.h>
  183795. #if (PNG_DEBUG > 1)
  183796. #define png_debug(l,m) _RPT0(_CRT_WARN,m)
  183797. #define png_debug1(l,m,p1) _RPT1(_CRT_WARN,m,p1)
  183798. #define png_debug2(l,m,p1,p2) _RPT2(_CRT_WARN,m,p1,p2)
  183799. #endif
  183800. #else /* PNG_DEBUG_FILE || !_MSC_VER */
  183801. #ifndef PNG_DEBUG_FILE
  183802. #define PNG_DEBUG_FILE stderr
  183803. #endif /* PNG_DEBUG_FILE */
  183804. #if (PNG_DEBUG > 1)
  183805. #define png_debug(l,m) \
  183806. { \
  183807. int num_tabs=l; \
  183808. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183809. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":"")))); \
  183810. }
  183811. #define png_debug1(l,m,p1) \
  183812. { \
  183813. int num_tabs=l; \
  183814. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183815. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1); \
  183816. }
  183817. #define png_debug2(l,m,p1,p2) \
  183818. { \
  183819. int num_tabs=l; \
  183820. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183821. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1,p2); \
  183822. }
  183823. #endif /* (PNG_DEBUG > 1) */
  183824. #endif /* _MSC_VER */
  183825. #endif /* (PNG_DEBUG > 0) */
  183826. #endif /* PNG_DEBUG */
  183827. #ifndef png_debug
  183828. #define png_debug(l, m)
  183829. #endif
  183830. #ifndef png_debug1
  183831. #define png_debug1(l, m, p1)
  183832. #endif
  183833. #ifndef png_debug2
  183834. #define png_debug2(l, m, p1, p2)
  183835. #endif
  183836. extern PNG_EXPORT(png_charp,png_get_copyright) PNGARG((png_structp png_ptr));
  183837. extern PNG_EXPORT(png_charp,png_get_header_ver) PNGARG((png_structp png_ptr));
  183838. extern PNG_EXPORT(png_charp,png_get_header_version) PNGARG((png_structp png_ptr));
  183839. extern PNG_EXPORT(png_charp,png_get_libpng_ver) PNGARG((png_structp png_ptr));
  183840. #ifdef PNG_MNG_FEATURES_SUPPORTED
  183841. extern PNG_EXPORT(png_uint_32,png_permit_mng_features) PNGARG((png_structp
  183842. png_ptr, png_uint_32 mng_features_permitted));
  183843. #endif
  183844. /* For use in png_set_keep_unknown, added to version 1.2.6 */
  183845. #define PNG_HANDLE_CHUNK_AS_DEFAULT 0
  183846. #define PNG_HANDLE_CHUNK_NEVER 1
  183847. #define PNG_HANDLE_CHUNK_IF_SAFE 2
  183848. #define PNG_HANDLE_CHUNK_ALWAYS 3
  183849. /* Added to version 1.2.0 */
  183850. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  183851. #if defined(PNG_MMX_CODE_SUPPORTED)
  183852. #define PNG_ASM_FLAG_MMX_SUPPORT_COMPILED 0x01 /* not user-settable */
  183853. #define PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU 0x02 /* not user-settable */
  183854. #define PNG_ASM_FLAG_MMX_READ_COMBINE_ROW 0x04
  183855. #define PNG_ASM_FLAG_MMX_READ_INTERLACE 0x08
  183856. #define PNG_ASM_FLAG_MMX_READ_FILTER_SUB 0x10
  183857. #define PNG_ASM_FLAG_MMX_READ_FILTER_UP 0x20
  183858. #define PNG_ASM_FLAG_MMX_READ_FILTER_AVG 0x40
  183859. #define PNG_ASM_FLAG_MMX_READ_FILTER_PAETH 0x80
  183860. #define PNG_ASM_FLAGS_INITIALIZED 0x80000000 /* not user-settable */
  183861. #define PNG_MMX_READ_FLAGS ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \
  183862. | PNG_ASM_FLAG_MMX_READ_INTERLACE \
  183863. | PNG_ASM_FLAG_MMX_READ_FILTER_SUB \
  183864. | PNG_ASM_FLAG_MMX_READ_FILTER_UP \
  183865. | PNG_ASM_FLAG_MMX_READ_FILTER_AVG \
  183866. | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH )
  183867. #define PNG_MMX_WRITE_FLAGS ( 0 )
  183868. #define PNG_MMX_FLAGS ( PNG_ASM_FLAG_MMX_SUPPORT_COMPILED \
  183869. | PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU \
  183870. | PNG_MMX_READ_FLAGS \
  183871. | PNG_MMX_WRITE_FLAGS )
  183872. #define PNG_SELECT_READ 1
  183873. #define PNG_SELECT_WRITE 2
  183874. #endif /* PNG_MMX_CODE_SUPPORTED */
  183875. #if !defined(PNG_1_0_X)
  183876. /* pngget.c */
  183877. extern PNG_EXPORT(png_uint_32,png_get_mmx_flagmask)
  183878. PNGARG((int flag_select, int *compilerID));
  183879. /* pngget.c */
  183880. extern PNG_EXPORT(png_uint_32,png_get_asm_flagmask)
  183881. PNGARG((int flag_select));
  183882. /* pngget.c */
  183883. extern PNG_EXPORT(png_uint_32,png_get_asm_flags)
  183884. PNGARG((png_structp png_ptr));
  183885. /* pngget.c */
  183886. extern PNG_EXPORT(png_byte,png_get_mmx_bitdepth_threshold)
  183887. PNGARG((png_structp png_ptr));
  183888. /* pngget.c */
  183889. extern PNG_EXPORT(png_uint_32,png_get_mmx_rowbytes_threshold)
  183890. PNGARG((png_structp png_ptr));
  183891. /* pngset.c */
  183892. extern PNG_EXPORT(void,png_set_asm_flags)
  183893. PNGARG((png_structp png_ptr, png_uint_32 asm_flags));
  183894. /* pngset.c */
  183895. extern PNG_EXPORT(void,png_set_mmx_thresholds)
  183896. PNGARG((png_structp png_ptr, png_byte mmx_bitdepth_threshold,
  183897. png_uint_32 mmx_rowbytes_threshold));
  183898. #endif /* PNG_1_0_X */
  183899. #if !defined(PNG_1_0_X)
  183900. /* png.c, pnggccrd.c, or pngvcrd.c */
  183901. extern PNG_EXPORT(int,png_mmx_support) PNGARG((void));
  183902. #endif /* PNG_ASSEMBLER_CODE_SUPPORTED */
  183903. /* Strip the prepended error numbers ("#nnn ") from error and warning
  183904. * messages before passing them to the error or warning handler. */
  183905. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  183906. extern PNG_EXPORT(void,png_set_strip_error_numbers) PNGARG((png_structp
  183907. png_ptr, png_uint_32 strip_mode));
  183908. #endif
  183909. #endif /* PNG_1_0_X */
  183910. /* Added at libpng-1.2.6 */
  183911. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  183912. extern PNG_EXPORT(void,png_set_user_limits) PNGARG((png_structp
  183913. png_ptr, png_uint_32 user_width_max, png_uint_32 user_height_max));
  183914. extern PNG_EXPORT(png_uint_32,png_get_user_width_max) PNGARG((png_structp
  183915. png_ptr));
  183916. extern PNG_EXPORT(png_uint_32,png_get_user_height_max) PNGARG((png_structp
  183917. png_ptr));
  183918. #endif
  183919. /* Maintainer: Put new public prototypes here ^, in libpng.3, and project defs */
  183920. #ifdef PNG_READ_COMPOSITE_NODIV_SUPPORTED
  183921. /* With these routines we avoid an integer divide, which will be slower on
  183922. * most machines. However, it does take more operations than the corresponding
  183923. * divide method, so it may be slower on a few RISC systems. There are two
  183924. * shifts (by 8 or 16 bits) and an addition, versus a single integer divide.
  183925. *
  183926. * Note that the rounding factors are NOT supposed to be the same! 128 and
  183927. * 32768 are correct for the NODIV code; 127 and 32767 are correct for the
  183928. * standard method.
  183929. *
  183930. * [Optimized code by Greg Roelofs and Mark Adler...blame us for bugs. :-) ]
  183931. */
  183932. /* fg and bg should be in `gamma 1.0' space; alpha is the opacity */
  183933. # define png_composite(composite, fg, alpha, bg) \
  183934. { png_uint_16 temp = (png_uint_16)((png_uint_16)(fg) * (png_uint_16)(alpha) \
  183935. + (png_uint_16)(bg)*(png_uint_16)(255 - \
  183936. (png_uint_16)(alpha)) + (png_uint_16)128); \
  183937. (composite) = (png_byte)((temp + (temp >> 8)) >> 8); }
  183938. # define png_composite_16(composite, fg, alpha, bg) \
  183939. { png_uint_32 temp = (png_uint_32)((png_uint_32)(fg) * (png_uint_32)(alpha) \
  183940. + (png_uint_32)(bg)*(png_uint_32)(65535L - \
  183941. (png_uint_32)(alpha)) + (png_uint_32)32768L); \
  183942. (composite) = (png_uint_16)((temp + (temp >> 16)) >> 16); }
  183943. #else /* standard method using integer division */
  183944. # define png_composite(composite, fg, alpha, bg) \
  183945. (composite) = (png_byte)(((png_uint_16)(fg) * (png_uint_16)(alpha) + \
  183946. (png_uint_16)(bg) * (png_uint_16)(255 - (png_uint_16)(alpha)) + \
  183947. (png_uint_16)127) / 255)
  183948. # define png_composite_16(composite, fg, alpha, bg) \
  183949. (composite) = (png_uint_16)(((png_uint_32)(fg) * (png_uint_32)(alpha) + \
  183950. (png_uint_32)(bg)*(png_uint_32)(65535L - (png_uint_32)(alpha)) + \
  183951. (png_uint_32)32767) / (png_uint_32)65535L)
  183952. #endif /* PNG_READ_COMPOSITE_NODIV_SUPPORTED */
  183953. /* Inline macros to do direct reads of bytes from the input buffer. These
  183954. * require that you are using an architecture that uses PNG byte ordering
  183955. * (MSB first) and supports unaligned data storage. I think that PowerPC
  183956. * in big-endian mode and 680x0 are the only ones that will support this.
  183957. * The x86 line of processors definitely do not. The png_get_int_32()
  183958. * routine also assumes we are using two's complement format for negative
  183959. * values, which is almost certainly true.
  183960. */
  183961. #if defined(PNG_READ_BIG_ENDIAN_SUPPORTED)
  183962. # define png_get_uint_32(buf) ( *((png_uint_32p) (buf)))
  183963. # define png_get_uint_16(buf) ( *((png_uint_16p) (buf)))
  183964. # define png_get_int_32(buf) ( *((png_int_32p) (buf)))
  183965. #else
  183966. extern PNG_EXPORT(png_uint_32,png_get_uint_32) PNGARG((png_bytep buf));
  183967. extern PNG_EXPORT(png_uint_16,png_get_uint_16) PNGARG((png_bytep buf));
  183968. extern PNG_EXPORT(png_int_32,png_get_int_32) PNGARG((png_bytep buf));
  183969. #endif /* !PNG_READ_BIG_ENDIAN_SUPPORTED */
  183970. extern PNG_EXPORT(png_uint_32,png_get_uint_31)
  183971. PNGARG((png_structp png_ptr, png_bytep buf));
  183972. /* No png_get_int_16 -- may be added if there's a real need for it. */
  183973. /* Place a 32-bit number into a buffer in PNG byte order (big-endian).
  183974. */
  183975. extern PNG_EXPORT(void,png_save_uint_32)
  183976. PNGARG((png_bytep buf, png_uint_32 i));
  183977. extern PNG_EXPORT(void,png_save_int_32)
  183978. PNGARG((png_bytep buf, png_int_32 i));
  183979. /* Place a 16-bit number into a buffer in PNG byte order.
  183980. * The parameter is declared unsigned int, not png_uint_16,
  183981. * just to avoid potential problems on pre-ANSI C compilers.
  183982. */
  183983. extern PNG_EXPORT(void,png_save_uint_16)
  183984. PNGARG((png_bytep buf, unsigned int i));
  183985. /* No png_save_int_16 -- may be added if there's a real need for it. */
  183986. /* ************************************************************************* */
  183987. /* These next functions are used internally in the code. They generally
  183988. * shouldn't be used unless you are writing code to add or replace some
  183989. * functionality in libpng. More information about most functions can
  183990. * be found in the files where the functions are located.
  183991. */
  183992. /* Various modes of operation, that are visible to applications because
  183993. * they are used for unknown chunk location.
  183994. */
  183995. #define PNG_HAVE_IHDR 0x01
  183996. #define PNG_HAVE_PLTE 0x02
  183997. #define PNG_HAVE_IDAT 0x04
  183998. #define PNG_AFTER_IDAT 0x08 /* Have complete zlib datastream */
  183999. #define PNG_HAVE_IEND 0x10
  184000. #if defined(PNG_INTERNAL)
  184001. /* More modes of operation. Note that after an init, mode is set to
  184002. * zero automatically when the structure is created.
  184003. */
  184004. #define PNG_HAVE_gAMA 0x20
  184005. #define PNG_HAVE_cHRM 0x40
  184006. #define PNG_HAVE_sRGB 0x80
  184007. #define PNG_HAVE_CHUNK_HEADER 0x100
  184008. #define PNG_WROTE_tIME 0x200
  184009. #define PNG_WROTE_INFO_BEFORE_PLTE 0x400
  184010. #define PNG_BACKGROUND_IS_GRAY 0x800
  184011. #define PNG_HAVE_PNG_SIGNATURE 0x1000
  184012. #define PNG_HAVE_CHUNK_AFTER_IDAT 0x2000 /* Have another chunk after IDAT */
  184013. /* flags for the transformations the PNG library does on the image data */
  184014. #define PNG_BGR 0x0001
  184015. #define PNG_INTERLACE 0x0002
  184016. #define PNG_PACK 0x0004
  184017. #define PNG_SHIFT 0x0008
  184018. #define PNG_SWAP_BYTES 0x0010
  184019. #define PNG_INVERT_MONO 0x0020
  184020. #define PNG_DITHER 0x0040
  184021. #define PNG_BACKGROUND 0x0080
  184022. #define PNG_BACKGROUND_EXPAND 0x0100
  184023. /* 0x0200 unused */
  184024. #define PNG_16_TO_8 0x0400
  184025. #define PNG_RGBA 0x0800
  184026. #define PNG_EXPAND 0x1000
  184027. #define PNG_GAMMA 0x2000
  184028. #define PNG_GRAY_TO_RGB 0x4000
  184029. #define PNG_FILLER 0x8000L
  184030. #define PNG_PACKSWAP 0x10000L
  184031. #define PNG_SWAP_ALPHA 0x20000L
  184032. #define PNG_STRIP_ALPHA 0x40000L
  184033. #define PNG_INVERT_ALPHA 0x80000L
  184034. #define PNG_USER_TRANSFORM 0x100000L
  184035. #define PNG_RGB_TO_GRAY_ERR 0x200000L
  184036. #define PNG_RGB_TO_GRAY_WARN 0x400000L
  184037. #define PNG_RGB_TO_GRAY 0x600000L /* two bits, RGB_TO_GRAY_ERR|WARN */
  184038. /* 0x800000L Unused */
  184039. #define PNG_ADD_ALPHA 0x1000000L /* Added to libpng-1.2.7 */
  184040. #define PNG_EXPAND_tRNS 0x2000000L /* Added to libpng-1.2.9 */
  184041. /* 0x4000000L unused */
  184042. /* 0x8000000L unused */
  184043. /* 0x10000000L unused */
  184044. /* 0x20000000L unused */
  184045. /* 0x40000000L unused */
  184046. /* flags for png_create_struct */
  184047. #define PNG_STRUCT_PNG 0x0001
  184048. #define PNG_STRUCT_INFO 0x0002
  184049. /* Scaling factor for filter heuristic weighting calculations */
  184050. #define PNG_WEIGHT_SHIFT 8
  184051. #define PNG_WEIGHT_FACTOR (1<<(PNG_WEIGHT_SHIFT))
  184052. #define PNG_COST_SHIFT 3
  184053. #define PNG_COST_FACTOR (1<<(PNG_COST_SHIFT))
  184054. /* flags for the png_ptr->flags rather than declaring a byte for each one */
  184055. #define PNG_FLAG_ZLIB_CUSTOM_STRATEGY 0x0001
  184056. #define PNG_FLAG_ZLIB_CUSTOM_LEVEL 0x0002
  184057. #define PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL 0x0004
  184058. #define PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS 0x0008
  184059. #define PNG_FLAG_ZLIB_CUSTOM_METHOD 0x0010
  184060. #define PNG_FLAG_ZLIB_FINISHED 0x0020
  184061. #define PNG_FLAG_ROW_INIT 0x0040
  184062. #define PNG_FLAG_FILLER_AFTER 0x0080
  184063. #define PNG_FLAG_CRC_ANCILLARY_USE 0x0100
  184064. #define PNG_FLAG_CRC_ANCILLARY_NOWARN 0x0200
  184065. #define PNG_FLAG_CRC_CRITICAL_USE 0x0400
  184066. #define PNG_FLAG_CRC_CRITICAL_IGNORE 0x0800
  184067. #define PNG_FLAG_FREE_PLTE 0x1000
  184068. #define PNG_FLAG_FREE_TRNS 0x2000
  184069. #define PNG_FLAG_FREE_HIST 0x4000
  184070. #define PNG_FLAG_KEEP_UNKNOWN_CHUNKS 0x8000L
  184071. #define PNG_FLAG_KEEP_UNSAFE_CHUNKS 0x10000L
  184072. #define PNG_FLAG_LIBRARY_MISMATCH 0x20000L
  184073. #define PNG_FLAG_STRIP_ERROR_NUMBERS 0x40000L
  184074. #define PNG_FLAG_STRIP_ERROR_TEXT 0x80000L
  184075. #define PNG_FLAG_MALLOC_NULL_MEM_OK 0x100000L
  184076. #define PNG_FLAG_ADD_ALPHA 0x200000L /* Added to libpng-1.2.8 */
  184077. #define PNG_FLAG_STRIP_ALPHA 0x400000L /* Added to libpng-1.2.8 */
  184078. /* 0x800000L unused */
  184079. /* 0x1000000L unused */
  184080. /* 0x2000000L unused */
  184081. /* 0x4000000L unused */
  184082. /* 0x8000000L unused */
  184083. /* 0x10000000L unused */
  184084. /* 0x20000000L unused */
  184085. /* 0x40000000L unused */
  184086. #define PNG_FLAG_CRC_ANCILLARY_MASK (PNG_FLAG_CRC_ANCILLARY_USE | \
  184087. PNG_FLAG_CRC_ANCILLARY_NOWARN)
  184088. #define PNG_FLAG_CRC_CRITICAL_MASK (PNG_FLAG_CRC_CRITICAL_USE | \
  184089. PNG_FLAG_CRC_CRITICAL_IGNORE)
  184090. #define PNG_FLAG_CRC_MASK (PNG_FLAG_CRC_ANCILLARY_MASK | \
  184091. PNG_FLAG_CRC_CRITICAL_MASK)
  184092. /* save typing and make code easier to understand */
  184093. #define PNG_COLOR_DIST(c1, c2) (abs((int)((c1).red) - (int)((c2).red)) + \
  184094. abs((int)((c1).green) - (int)((c2).green)) + \
  184095. abs((int)((c1).blue) - (int)((c2).blue)))
  184096. /* Added to libpng-1.2.6 JB */
  184097. #define PNG_ROWBYTES(pixel_bits, width) \
  184098. ((pixel_bits) >= 8 ? \
  184099. ((width) * (((png_uint_32)(pixel_bits)) >> 3)) : \
  184100. (( ((width) * ((png_uint_32)(pixel_bits))) + 7) >> 3) )
  184101. /* PNG_OUT_OF_RANGE returns true if value is outside the range
  184102. ideal-delta..ideal+delta. Each argument is evaluated twice.
  184103. "ideal" and "delta" should be constants, normally simple
  184104. integers, "value" a variable. Added to libpng-1.2.6 JB */
  184105. #define PNG_OUT_OF_RANGE(value, ideal, delta) \
  184106. ( (value) < (ideal)-(delta) || (value) > (ideal)+(delta) )
  184107. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  184108. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  184109. /* place to hold the signature string for a PNG file. */
  184110. #ifdef PNG_USE_GLOBAL_ARRAYS
  184111. PNG_EXPORT_VAR (PNG_CONST png_byte FARDATA) png_sig[8];
  184112. #else
  184113. #endif
  184114. #endif /* PNG_NO_EXTERN */
  184115. /* Constant strings for known chunk types. If you need to add a chunk,
  184116. * define the name here, and add an invocation of the macro in png.c and
  184117. * wherever it's needed.
  184118. */
  184119. #define PNG_IHDR png_byte png_IHDR[5] = { 73, 72, 68, 82, '\0'}
  184120. #define PNG_IDAT png_byte png_IDAT[5] = { 73, 68, 65, 84, '\0'}
  184121. #define PNG_IEND png_byte png_IEND[5] = { 73, 69, 78, 68, '\0'}
  184122. #define PNG_PLTE png_byte png_PLTE[5] = { 80, 76, 84, 69, '\0'}
  184123. #define PNG_bKGD png_byte png_bKGD[5] = { 98, 75, 71, 68, '\0'}
  184124. #define PNG_cHRM png_byte png_cHRM[5] = { 99, 72, 82, 77, '\0'}
  184125. #define PNG_gAMA png_byte png_gAMA[5] = {103, 65, 77, 65, '\0'}
  184126. #define PNG_hIST png_byte png_hIST[5] = {104, 73, 83, 84, '\0'}
  184127. #define PNG_iCCP png_byte png_iCCP[5] = {105, 67, 67, 80, '\0'}
  184128. #define PNG_iTXt png_byte png_iTXt[5] = {105, 84, 88, 116, '\0'}
  184129. #define PNG_oFFs png_byte png_oFFs[5] = {111, 70, 70, 115, '\0'}
  184130. #define PNG_pCAL png_byte png_pCAL[5] = {112, 67, 65, 76, '\0'}
  184131. #define PNG_sCAL png_byte png_sCAL[5] = {115, 67, 65, 76, '\0'}
  184132. #define PNG_pHYs png_byte png_pHYs[5] = {112, 72, 89, 115, '\0'}
  184133. #define PNG_sBIT png_byte png_sBIT[5] = {115, 66, 73, 84, '\0'}
  184134. #define PNG_sPLT png_byte png_sPLT[5] = {115, 80, 76, 84, '\0'}
  184135. #define PNG_sRGB png_byte png_sRGB[5] = {115, 82, 71, 66, '\0'}
  184136. #define PNG_tEXt png_byte png_tEXt[5] = {116, 69, 88, 116, '\0'}
  184137. #define PNG_tIME png_byte png_tIME[5] = {116, 73, 77, 69, '\0'}
  184138. #define PNG_tRNS png_byte png_tRNS[5] = {116, 82, 78, 83, '\0'}
  184139. #define PNG_zTXt png_byte png_zTXt[5] = {122, 84, 88, 116, '\0'}
  184140. #ifdef PNG_USE_GLOBAL_ARRAYS
  184141. PNG_EXPORT_VAR (png_byte FARDATA) png_IHDR[5];
  184142. PNG_EXPORT_VAR (png_byte FARDATA) png_IDAT[5];
  184143. PNG_EXPORT_VAR (png_byte FARDATA) png_IEND[5];
  184144. PNG_EXPORT_VAR (png_byte FARDATA) png_PLTE[5];
  184145. PNG_EXPORT_VAR (png_byte FARDATA) png_bKGD[5];
  184146. PNG_EXPORT_VAR (png_byte FARDATA) png_cHRM[5];
  184147. PNG_EXPORT_VAR (png_byte FARDATA) png_gAMA[5];
  184148. PNG_EXPORT_VAR (png_byte FARDATA) png_hIST[5];
  184149. PNG_EXPORT_VAR (png_byte FARDATA) png_iCCP[5];
  184150. PNG_EXPORT_VAR (png_byte FARDATA) png_iTXt[5];
  184151. PNG_EXPORT_VAR (png_byte FARDATA) png_oFFs[5];
  184152. PNG_EXPORT_VAR (png_byte FARDATA) png_pCAL[5];
  184153. PNG_EXPORT_VAR (png_byte FARDATA) png_sCAL[5];
  184154. PNG_EXPORT_VAR (png_byte FARDATA) png_pHYs[5];
  184155. PNG_EXPORT_VAR (png_byte FARDATA) png_sBIT[5];
  184156. PNG_EXPORT_VAR (png_byte FARDATA) png_sPLT[5];
  184157. PNG_EXPORT_VAR (png_byte FARDATA) png_sRGB[5];
  184158. PNG_EXPORT_VAR (png_byte FARDATA) png_tEXt[5];
  184159. PNG_EXPORT_VAR (png_byte FARDATA) png_tIME[5];
  184160. PNG_EXPORT_VAR (png_byte FARDATA) png_tRNS[5];
  184161. PNG_EXPORT_VAR (png_byte FARDATA) png_zTXt[5];
  184162. #endif /* PNG_USE_GLOBAL_ARRAYS */
  184163. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  184164. /* Initialize png_ptr struct for reading, and allocate any other memory.
  184165. * (old interface - DEPRECATED - use png_create_read_struct instead).
  184166. */
  184167. extern PNG_EXPORT(void,png_read_init) PNGARG((png_structp png_ptr));
  184168. #undef png_read_init
  184169. #define png_read_init(png_ptr) png_read_init_3(&png_ptr, \
  184170. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  184171. #endif
  184172. extern PNG_EXPORT(void,png_read_init_3) PNGARG((png_structpp ptr_ptr,
  184173. png_const_charp user_png_ver, png_size_t png_struct_size));
  184174. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  184175. extern PNG_EXPORT(void,png_read_init_2) PNGARG((png_structp png_ptr,
  184176. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  184177. png_info_size));
  184178. #endif
  184179. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  184180. /* Initialize png_ptr struct for writing, and allocate any other memory.
  184181. * (old interface - DEPRECATED - use png_create_write_struct instead).
  184182. */
  184183. extern PNG_EXPORT(void,png_write_init) PNGARG((png_structp png_ptr));
  184184. #undef png_write_init
  184185. #define png_write_init(png_ptr) png_write_init_3(&png_ptr, \
  184186. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  184187. #endif
  184188. extern PNG_EXPORT(void,png_write_init_3) PNGARG((png_structpp ptr_ptr,
  184189. png_const_charp user_png_ver, png_size_t png_struct_size));
  184190. extern PNG_EXPORT(void,png_write_init_2) PNGARG((png_structp png_ptr,
  184191. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  184192. png_info_size));
  184193. /* Allocate memory for an internal libpng struct */
  184194. PNG_EXTERN png_voidp png_create_struct PNGARG((int type));
  184195. /* Free memory from internal libpng struct */
  184196. PNG_EXTERN void png_destroy_struct PNGARG((png_voidp struct_ptr));
  184197. PNG_EXTERN png_voidp png_create_struct_2 PNGARG((int type, png_malloc_ptr
  184198. malloc_fn, png_voidp mem_ptr));
  184199. PNG_EXTERN void png_destroy_struct_2 PNGARG((png_voidp struct_ptr,
  184200. png_free_ptr free_fn, png_voidp mem_ptr));
  184201. /* Free any memory that info_ptr points to and reset struct. */
  184202. PNG_EXTERN void png_info_destroy PNGARG((png_structp png_ptr,
  184203. png_infop info_ptr));
  184204. #ifndef PNG_1_0_X
  184205. /* Function to allocate memory for zlib. */
  184206. PNG_EXTERN voidpf png_zalloc PNGARG((voidpf png_ptr, uInt items, uInt size));
  184207. /* Function to free memory for zlib */
  184208. PNG_EXTERN void png_zfree PNGARG((voidpf png_ptr, voidpf ptr));
  184209. #ifdef PNG_SIZE_T
  184210. /* Function to convert a sizeof an item to png_sizeof item */
  184211. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  184212. #endif
  184213. /* Next four functions are used internally as callbacks. PNGAPI is required
  184214. * but not PNG_EXPORT. PNGAPI added at libpng version 1.2.3. */
  184215. PNG_EXTERN void PNGAPI png_default_read_data PNGARG((png_structp png_ptr,
  184216. png_bytep data, png_size_t length));
  184217. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184218. PNG_EXTERN void PNGAPI png_push_fill_buffer PNGARG((png_structp png_ptr,
  184219. png_bytep buffer, png_size_t length));
  184220. #endif
  184221. PNG_EXTERN void PNGAPI png_default_write_data PNGARG((png_structp png_ptr,
  184222. png_bytep data, png_size_t length));
  184223. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  184224. #if !defined(PNG_NO_STDIO)
  184225. PNG_EXTERN void PNGAPI png_default_flush PNGARG((png_structp png_ptr));
  184226. #endif
  184227. #endif
  184228. #else /* PNG_1_0_X */
  184229. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184230. PNG_EXTERN void png_push_fill_buffer PNGARG((png_structp png_ptr,
  184231. png_bytep buffer, png_size_t length));
  184232. #endif
  184233. #endif /* PNG_1_0_X */
  184234. /* Reset the CRC variable */
  184235. PNG_EXTERN void png_reset_crc PNGARG((png_structp png_ptr));
  184236. /* Write the "data" buffer to whatever output you are using. */
  184237. PNG_EXTERN void png_write_data PNGARG((png_structp png_ptr, png_bytep data,
  184238. png_size_t length));
  184239. /* Read data from whatever input you are using into the "data" buffer */
  184240. PNG_EXTERN void png_read_data PNGARG((png_structp png_ptr, png_bytep data,
  184241. png_size_t length));
  184242. /* Read bytes into buf, and update png_ptr->crc */
  184243. PNG_EXTERN void png_crc_read PNGARG((png_structp png_ptr, png_bytep buf,
  184244. png_size_t length));
  184245. /* Decompress data in a chunk that uses compression */
  184246. #if defined(PNG_zTXt_SUPPORTED) || defined(PNG_iTXt_SUPPORTED) || \
  184247. defined(PNG_iCCP_SUPPORTED) || defined(PNG_sPLT_SUPPORTED)
  184248. PNG_EXTERN png_charp png_decompress_chunk PNGARG((png_structp png_ptr,
  184249. int comp_type, png_charp chunkdata, png_size_t chunklength,
  184250. png_size_t prefix_length, png_size_t *data_length));
  184251. #endif
  184252. /* Read "skip" bytes, read the file crc, and (optionally) verify png_ptr->crc */
  184253. PNG_EXTERN int png_crc_finish PNGARG((png_structp png_ptr, png_uint_32 skip));
  184254. /* Read the CRC from the file and compare it to the libpng calculated CRC */
  184255. PNG_EXTERN int png_crc_error PNGARG((png_structp png_ptr));
  184256. /* Calculate the CRC over a section of data. Note that we are only
  184257. * passing a maximum of 64K on systems that have this as a memory limit,
  184258. * since this is the maximum buffer size we can specify.
  184259. */
  184260. PNG_EXTERN void png_calculate_crc PNGARG((png_structp png_ptr, png_bytep ptr,
  184261. png_size_t length));
  184262. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  184263. PNG_EXTERN void png_flush PNGARG((png_structp png_ptr));
  184264. #endif
  184265. /* simple function to write the signature */
  184266. PNG_EXTERN void png_write_sig PNGARG((png_structp png_ptr));
  184267. /* write various chunks */
  184268. /* Write the IHDR chunk, and update the png_struct with the necessary
  184269. * information.
  184270. */
  184271. PNG_EXTERN void png_write_IHDR PNGARG((png_structp png_ptr, png_uint_32 width,
  184272. png_uint_32 height,
  184273. int bit_depth, int color_type, int compression_method, int filter_method,
  184274. int interlace_method));
  184275. PNG_EXTERN void png_write_PLTE PNGARG((png_structp png_ptr, png_colorp palette,
  184276. png_uint_32 num_pal));
  184277. PNG_EXTERN void png_write_IDAT PNGARG((png_structp png_ptr, png_bytep data,
  184278. png_size_t length));
  184279. PNG_EXTERN void png_write_IEND PNGARG((png_structp png_ptr));
  184280. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  184281. #ifdef PNG_FLOATING_POINT_SUPPORTED
  184282. PNG_EXTERN void png_write_gAMA PNGARG((png_structp png_ptr, double file_gamma));
  184283. #endif
  184284. #ifdef PNG_FIXED_POINT_SUPPORTED
  184285. PNG_EXTERN void png_write_gAMA_fixed PNGARG((png_structp png_ptr, png_fixed_point
  184286. file_gamma));
  184287. #endif
  184288. #endif
  184289. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  184290. PNG_EXTERN void png_write_sBIT PNGARG((png_structp png_ptr, png_color_8p sbit,
  184291. int color_type));
  184292. #endif
  184293. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  184294. #ifdef PNG_FLOATING_POINT_SUPPORTED
  184295. PNG_EXTERN void png_write_cHRM PNGARG((png_structp png_ptr,
  184296. double white_x, double white_y,
  184297. double red_x, double red_y, double green_x, double green_y,
  184298. double blue_x, double blue_y));
  184299. #endif
  184300. #ifdef PNG_FIXED_POINT_SUPPORTED
  184301. PNG_EXTERN void png_write_cHRM_fixed PNGARG((png_structp png_ptr,
  184302. png_fixed_point int_white_x, png_fixed_point int_white_y,
  184303. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  184304. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  184305. png_fixed_point int_blue_y));
  184306. #endif
  184307. #endif
  184308. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  184309. PNG_EXTERN void png_write_sRGB PNGARG((png_structp png_ptr,
  184310. int intent));
  184311. #endif
  184312. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  184313. PNG_EXTERN void png_write_iCCP PNGARG((png_structp png_ptr,
  184314. png_charp name, int compression_type,
  184315. png_charp profile, int proflen));
  184316. /* Note to maintainer: profile should be png_bytep */
  184317. #endif
  184318. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  184319. PNG_EXTERN void png_write_sPLT PNGARG((png_structp png_ptr,
  184320. png_sPLT_tp palette));
  184321. #endif
  184322. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  184323. PNG_EXTERN void png_write_tRNS PNGARG((png_structp png_ptr, png_bytep trans,
  184324. png_color_16p values, int number, int color_type));
  184325. #endif
  184326. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  184327. PNG_EXTERN void png_write_bKGD PNGARG((png_structp png_ptr,
  184328. png_color_16p values, int color_type));
  184329. #endif
  184330. #if defined(PNG_WRITE_hIST_SUPPORTED)
  184331. PNG_EXTERN void png_write_hIST PNGARG((png_structp png_ptr, png_uint_16p hist,
  184332. int num_hist));
  184333. #endif
  184334. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  184335. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  184336. PNG_EXTERN png_size_t png_check_keyword PNGARG((png_structp png_ptr,
  184337. png_charp key, png_charpp new_key));
  184338. #endif
  184339. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  184340. PNG_EXTERN void png_write_tEXt PNGARG((png_structp png_ptr, png_charp key,
  184341. png_charp text, png_size_t text_len));
  184342. #endif
  184343. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  184344. PNG_EXTERN void png_write_zTXt PNGARG((png_structp png_ptr, png_charp key,
  184345. png_charp text, png_size_t text_len, int compression));
  184346. #endif
  184347. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  184348. PNG_EXTERN void png_write_iTXt PNGARG((png_structp png_ptr,
  184349. int compression, png_charp key, png_charp lang, png_charp lang_key,
  184350. png_charp text));
  184351. #endif
  184352. #if defined(PNG_TEXT_SUPPORTED) /* Added at version 1.0.14 and 1.2.4 */
  184353. PNG_EXTERN int png_set_text_2 PNGARG((png_structp png_ptr,
  184354. png_infop info_ptr, png_textp text_ptr, int num_text));
  184355. #endif
  184356. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  184357. PNG_EXTERN void png_write_oFFs PNGARG((png_structp png_ptr,
  184358. png_int_32 x_offset, png_int_32 y_offset, int unit_type));
  184359. #endif
  184360. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  184361. PNG_EXTERN void png_write_pCAL PNGARG((png_structp png_ptr, png_charp purpose,
  184362. png_int_32 X0, png_int_32 X1, int type, int nparams,
  184363. png_charp units, png_charpp params));
  184364. #endif
  184365. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  184366. PNG_EXTERN void png_write_pHYs PNGARG((png_structp png_ptr,
  184367. png_uint_32 x_pixels_per_unit, png_uint_32 y_pixels_per_unit,
  184368. int unit_type));
  184369. #endif
  184370. #if defined(PNG_WRITE_tIME_SUPPORTED)
  184371. PNG_EXTERN void png_write_tIME PNGARG((png_structp png_ptr,
  184372. png_timep mod_time));
  184373. #endif
  184374. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  184375. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  184376. PNG_EXTERN void png_write_sCAL PNGARG((png_structp png_ptr,
  184377. int unit, double width, double height));
  184378. #else
  184379. #ifdef PNG_FIXED_POINT_SUPPORTED
  184380. PNG_EXTERN void png_write_sCAL_s PNGARG((png_structp png_ptr,
  184381. int unit, png_charp width, png_charp height));
  184382. #endif
  184383. #endif
  184384. #endif
  184385. /* Called when finished processing a row of data */
  184386. PNG_EXTERN void png_write_finish_row PNGARG((png_structp png_ptr));
  184387. /* Internal use only. Called before first row of data */
  184388. PNG_EXTERN void png_write_start_row PNGARG((png_structp png_ptr));
  184389. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184390. PNG_EXTERN void png_build_gamma_table PNGARG((png_structp png_ptr));
  184391. #endif
  184392. /* combine a row of data, dealing with alpha, etc. if requested */
  184393. PNG_EXTERN void png_combine_row PNGARG((png_structp png_ptr, png_bytep row,
  184394. int mask));
  184395. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  184396. /* expand an interlaced row */
  184397. /* OLD pre-1.0.9 interface:
  184398. PNG_EXTERN void png_do_read_interlace PNGARG((png_row_infop row_info,
  184399. png_bytep row, int pass, png_uint_32 transformations));
  184400. */
  184401. PNG_EXTERN void png_do_read_interlace PNGARG((png_structp png_ptr));
  184402. #endif
  184403. /* GRR TO DO (2.0 or whenever): simplify other internal calling interfaces */
  184404. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  184405. /* grab pixels out of a row for an interlaced pass */
  184406. PNG_EXTERN void png_do_write_interlace PNGARG((png_row_infop row_info,
  184407. png_bytep row, int pass));
  184408. #endif
  184409. /* unfilter a row */
  184410. PNG_EXTERN void png_read_filter_row PNGARG((png_structp png_ptr,
  184411. png_row_infop row_info, png_bytep row, png_bytep prev_row, int filter));
  184412. /* Choose the best filter to use and filter the row data */
  184413. PNG_EXTERN void png_write_find_filter PNGARG((png_structp png_ptr,
  184414. png_row_infop row_info));
  184415. /* Write out the filtered row. */
  184416. PNG_EXTERN void png_write_filtered_row PNGARG((png_structp png_ptr,
  184417. png_bytep filtered_row));
  184418. /* finish a row while reading, dealing with interlacing passes, etc. */
  184419. PNG_EXTERN void png_read_finish_row PNGARG((png_structp png_ptr));
  184420. /* initialize the row buffers, etc. */
  184421. PNG_EXTERN void png_read_start_row PNGARG((png_structp png_ptr));
  184422. /* optional call to update the users info structure */
  184423. PNG_EXTERN void png_read_transform_info PNGARG((png_structp png_ptr,
  184424. png_infop info_ptr));
  184425. /* these are the functions that do the transformations */
  184426. #if defined(PNG_READ_FILLER_SUPPORTED)
  184427. PNG_EXTERN void png_do_read_filler PNGARG((png_row_infop row_info,
  184428. png_bytep row, png_uint_32 filler, png_uint_32 flags));
  184429. #endif
  184430. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  184431. PNG_EXTERN void png_do_read_swap_alpha PNGARG((png_row_infop row_info,
  184432. png_bytep row));
  184433. #endif
  184434. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  184435. PNG_EXTERN void png_do_write_swap_alpha PNGARG((png_row_infop row_info,
  184436. png_bytep row));
  184437. #endif
  184438. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  184439. PNG_EXTERN void png_do_read_invert_alpha PNGARG((png_row_infop row_info,
  184440. png_bytep row));
  184441. #endif
  184442. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  184443. PNG_EXTERN void png_do_write_invert_alpha PNGARG((png_row_infop row_info,
  184444. png_bytep row));
  184445. #endif
  184446. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  184447. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  184448. PNG_EXTERN void png_do_strip_filler PNGARG((png_row_infop row_info,
  184449. png_bytep row, png_uint_32 flags));
  184450. #endif
  184451. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  184452. PNG_EXTERN void png_do_swap PNGARG((png_row_infop row_info, png_bytep row));
  184453. #endif
  184454. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  184455. PNG_EXTERN void png_do_packswap PNGARG((png_row_infop row_info, png_bytep row));
  184456. #endif
  184457. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  184458. PNG_EXTERN int png_do_rgb_to_gray PNGARG((png_structp png_ptr, png_row_infop
  184459. row_info, png_bytep row));
  184460. #endif
  184461. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  184462. PNG_EXTERN void png_do_gray_to_rgb PNGARG((png_row_infop row_info,
  184463. png_bytep row));
  184464. #endif
  184465. #if defined(PNG_READ_PACK_SUPPORTED)
  184466. PNG_EXTERN void png_do_unpack PNGARG((png_row_infop row_info, png_bytep row));
  184467. #endif
  184468. #if defined(PNG_READ_SHIFT_SUPPORTED)
  184469. PNG_EXTERN void png_do_unshift PNGARG((png_row_infop row_info, png_bytep row,
  184470. png_color_8p sig_bits));
  184471. #endif
  184472. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  184473. PNG_EXTERN void png_do_invert PNGARG((png_row_infop row_info, png_bytep row));
  184474. #endif
  184475. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  184476. PNG_EXTERN void png_do_chop PNGARG((png_row_infop row_info, png_bytep row));
  184477. #endif
  184478. #if defined(PNG_READ_DITHER_SUPPORTED)
  184479. PNG_EXTERN void png_do_dither PNGARG((png_row_infop row_info,
  184480. png_bytep row, png_bytep palette_lookup, png_bytep dither_lookup));
  184481. # if defined(PNG_CORRECT_PALETTE_SUPPORTED)
  184482. PNG_EXTERN void png_correct_palette PNGARG((png_structp png_ptr,
  184483. png_colorp palette, int num_palette));
  184484. # endif
  184485. #endif
  184486. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  184487. PNG_EXTERN void png_do_bgr PNGARG((png_row_infop row_info, png_bytep row));
  184488. #endif
  184489. #if defined(PNG_WRITE_PACK_SUPPORTED)
  184490. PNG_EXTERN void png_do_pack PNGARG((png_row_infop row_info,
  184491. png_bytep row, png_uint_32 bit_depth));
  184492. #endif
  184493. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  184494. PNG_EXTERN void png_do_shift PNGARG((png_row_infop row_info, png_bytep row,
  184495. png_color_8p bit_depth));
  184496. #endif
  184497. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  184498. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184499. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  184500. png_color_16p trans_values, png_color_16p background,
  184501. png_color_16p background_1,
  184502. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  184503. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  184504. png_uint_16pp gamma_16_to_1, int gamma_shift));
  184505. #else
  184506. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  184507. png_color_16p trans_values, png_color_16p background));
  184508. #endif
  184509. #endif
  184510. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184511. PNG_EXTERN void png_do_gamma PNGARG((png_row_infop row_info, png_bytep row,
  184512. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  184513. int gamma_shift));
  184514. #endif
  184515. #if defined(PNG_READ_EXPAND_SUPPORTED)
  184516. PNG_EXTERN void png_do_expand_palette PNGARG((png_row_infop row_info,
  184517. png_bytep row, png_colorp palette, png_bytep trans, int num_trans));
  184518. PNG_EXTERN void png_do_expand PNGARG((png_row_infop row_info,
  184519. png_bytep row, png_color_16p trans_value));
  184520. #endif
  184521. /* The following decodes the appropriate chunks, and does error correction,
  184522. * then calls the appropriate callback for the chunk if it is valid.
  184523. */
  184524. /* decode the IHDR chunk */
  184525. PNG_EXTERN void png_handle_IHDR PNGARG((png_structp png_ptr, png_infop info_ptr,
  184526. png_uint_32 length));
  184527. PNG_EXTERN void png_handle_PLTE PNGARG((png_structp png_ptr, png_infop info_ptr,
  184528. png_uint_32 length));
  184529. PNG_EXTERN void png_handle_IEND PNGARG((png_structp png_ptr, png_infop info_ptr,
  184530. png_uint_32 length));
  184531. #if defined(PNG_READ_bKGD_SUPPORTED)
  184532. PNG_EXTERN void png_handle_bKGD PNGARG((png_structp png_ptr, png_infop info_ptr,
  184533. png_uint_32 length));
  184534. #endif
  184535. #if defined(PNG_READ_cHRM_SUPPORTED)
  184536. PNG_EXTERN void png_handle_cHRM PNGARG((png_structp png_ptr, png_infop info_ptr,
  184537. png_uint_32 length));
  184538. #endif
  184539. #if defined(PNG_READ_gAMA_SUPPORTED)
  184540. PNG_EXTERN void png_handle_gAMA PNGARG((png_structp png_ptr, png_infop info_ptr,
  184541. png_uint_32 length));
  184542. #endif
  184543. #if defined(PNG_READ_hIST_SUPPORTED)
  184544. PNG_EXTERN void png_handle_hIST PNGARG((png_structp png_ptr, png_infop info_ptr,
  184545. png_uint_32 length));
  184546. #endif
  184547. #if defined(PNG_READ_iCCP_SUPPORTED)
  184548. extern void png_handle_iCCP PNGARG((png_structp png_ptr, png_infop info_ptr,
  184549. png_uint_32 length));
  184550. #endif /* PNG_READ_iCCP_SUPPORTED */
  184551. #if defined(PNG_READ_iTXt_SUPPORTED)
  184552. PNG_EXTERN void png_handle_iTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184553. png_uint_32 length));
  184554. #endif
  184555. #if defined(PNG_READ_oFFs_SUPPORTED)
  184556. PNG_EXTERN void png_handle_oFFs PNGARG((png_structp png_ptr, png_infop info_ptr,
  184557. png_uint_32 length));
  184558. #endif
  184559. #if defined(PNG_READ_pCAL_SUPPORTED)
  184560. PNG_EXTERN void png_handle_pCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  184561. png_uint_32 length));
  184562. #endif
  184563. #if defined(PNG_READ_pHYs_SUPPORTED)
  184564. PNG_EXTERN void png_handle_pHYs PNGARG((png_structp png_ptr, png_infop info_ptr,
  184565. png_uint_32 length));
  184566. #endif
  184567. #if defined(PNG_READ_sBIT_SUPPORTED)
  184568. PNG_EXTERN void png_handle_sBIT PNGARG((png_structp png_ptr, png_infop info_ptr,
  184569. png_uint_32 length));
  184570. #endif
  184571. #if defined(PNG_READ_sCAL_SUPPORTED)
  184572. PNG_EXTERN void png_handle_sCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  184573. png_uint_32 length));
  184574. #endif
  184575. #if defined(PNG_READ_sPLT_SUPPORTED)
  184576. extern void png_handle_sPLT PNGARG((png_structp png_ptr, png_infop info_ptr,
  184577. png_uint_32 length));
  184578. #endif /* PNG_READ_sPLT_SUPPORTED */
  184579. #if defined(PNG_READ_sRGB_SUPPORTED)
  184580. PNG_EXTERN void png_handle_sRGB PNGARG((png_structp png_ptr, png_infop info_ptr,
  184581. png_uint_32 length));
  184582. #endif
  184583. #if defined(PNG_READ_tEXt_SUPPORTED)
  184584. PNG_EXTERN void png_handle_tEXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184585. png_uint_32 length));
  184586. #endif
  184587. #if defined(PNG_READ_tIME_SUPPORTED)
  184588. PNG_EXTERN void png_handle_tIME PNGARG((png_structp png_ptr, png_infop info_ptr,
  184589. png_uint_32 length));
  184590. #endif
  184591. #if defined(PNG_READ_tRNS_SUPPORTED)
  184592. PNG_EXTERN void png_handle_tRNS PNGARG((png_structp png_ptr, png_infop info_ptr,
  184593. png_uint_32 length));
  184594. #endif
  184595. #if defined(PNG_READ_zTXt_SUPPORTED)
  184596. PNG_EXTERN void png_handle_zTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184597. png_uint_32 length));
  184598. #endif
  184599. PNG_EXTERN void png_handle_unknown PNGARG((png_structp png_ptr,
  184600. png_infop info_ptr, png_uint_32 length));
  184601. PNG_EXTERN void png_check_chunk_name PNGARG((png_structp png_ptr,
  184602. png_bytep chunk_name));
  184603. /* handle the transformations for reading and writing */
  184604. PNG_EXTERN void png_do_read_transformations PNGARG((png_structp png_ptr));
  184605. PNG_EXTERN void png_do_write_transformations PNGARG((png_structp png_ptr));
  184606. PNG_EXTERN void png_init_read_transformations PNGARG((png_structp png_ptr));
  184607. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184608. PNG_EXTERN void png_push_read_chunk PNGARG((png_structp png_ptr,
  184609. png_infop info_ptr));
  184610. PNG_EXTERN void png_push_read_sig PNGARG((png_structp png_ptr,
  184611. png_infop info_ptr));
  184612. PNG_EXTERN void png_push_check_crc PNGARG((png_structp png_ptr));
  184613. PNG_EXTERN void png_push_crc_skip PNGARG((png_structp png_ptr,
  184614. png_uint_32 length));
  184615. PNG_EXTERN void png_push_crc_finish PNGARG((png_structp png_ptr));
  184616. PNG_EXTERN void png_push_save_buffer PNGARG((png_structp png_ptr));
  184617. PNG_EXTERN void png_push_restore_buffer PNGARG((png_structp png_ptr,
  184618. png_bytep buffer, png_size_t buffer_length));
  184619. PNG_EXTERN void png_push_read_IDAT PNGARG((png_structp png_ptr));
  184620. PNG_EXTERN void png_process_IDAT_data PNGARG((png_structp png_ptr,
  184621. png_bytep buffer, png_size_t buffer_length));
  184622. PNG_EXTERN void png_push_process_row PNGARG((png_structp png_ptr));
  184623. PNG_EXTERN void png_push_handle_unknown PNGARG((png_structp png_ptr,
  184624. png_infop info_ptr, png_uint_32 length));
  184625. PNG_EXTERN void png_push_have_info PNGARG((png_structp png_ptr,
  184626. png_infop info_ptr));
  184627. PNG_EXTERN void png_push_have_end PNGARG((png_structp png_ptr,
  184628. png_infop info_ptr));
  184629. PNG_EXTERN void png_push_have_row PNGARG((png_structp png_ptr, png_bytep row));
  184630. PNG_EXTERN void png_push_read_end PNGARG((png_structp png_ptr,
  184631. png_infop info_ptr));
  184632. PNG_EXTERN void png_process_some_data PNGARG((png_structp png_ptr,
  184633. png_infop info_ptr));
  184634. PNG_EXTERN void png_read_push_finish_row PNGARG((png_structp png_ptr));
  184635. #if defined(PNG_READ_tEXt_SUPPORTED)
  184636. PNG_EXTERN void png_push_handle_tEXt PNGARG((png_structp png_ptr,
  184637. png_infop info_ptr, png_uint_32 length));
  184638. PNG_EXTERN void png_push_read_tEXt PNGARG((png_structp png_ptr,
  184639. png_infop info_ptr));
  184640. #endif
  184641. #if defined(PNG_READ_zTXt_SUPPORTED)
  184642. PNG_EXTERN void png_push_handle_zTXt PNGARG((png_structp png_ptr,
  184643. png_infop info_ptr, png_uint_32 length));
  184644. PNG_EXTERN void png_push_read_zTXt PNGARG((png_structp png_ptr,
  184645. png_infop info_ptr));
  184646. #endif
  184647. #if defined(PNG_READ_iTXt_SUPPORTED)
  184648. PNG_EXTERN void png_push_handle_iTXt PNGARG((png_structp png_ptr,
  184649. png_infop info_ptr, png_uint_32 length));
  184650. PNG_EXTERN void png_push_read_iTXt PNGARG((png_structp png_ptr,
  184651. png_infop info_ptr));
  184652. #endif
  184653. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  184654. #ifdef PNG_MNG_FEATURES_SUPPORTED
  184655. PNG_EXTERN void png_do_read_intrapixel PNGARG((png_row_infop row_info,
  184656. png_bytep row));
  184657. PNG_EXTERN void png_do_write_intrapixel PNGARG((png_row_infop row_info,
  184658. png_bytep row));
  184659. #endif
  184660. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  184661. #if defined(PNG_MMX_CODE_SUPPORTED)
  184662. /* png.c */ /* PRIVATE */
  184663. PNG_EXTERN void png_init_mmx_flags PNGARG((png_structp png_ptr));
  184664. #endif
  184665. #endif
  184666. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  184667. PNG_EXTERN png_uint_32 png_get_pixels_per_inch PNGARG((png_structp png_ptr,
  184668. png_infop info_ptr));
  184669. PNG_EXTERN png_uint_32 png_get_x_pixels_per_inch PNGARG((png_structp png_ptr,
  184670. png_infop info_ptr));
  184671. PNG_EXTERN png_uint_32 png_get_y_pixels_per_inch PNGARG((png_structp png_ptr,
  184672. png_infop info_ptr));
  184673. PNG_EXTERN float png_get_x_offset_inches PNGARG((png_structp png_ptr,
  184674. png_infop info_ptr));
  184675. PNG_EXTERN float png_get_y_offset_inches PNGARG((png_structp png_ptr,
  184676. png_infop info_ptr));
  184677. #if defined(PNG_pHYs_SUPPORTED)
  184678. PNG_EXTERN png_uint_32 png_get_pHYs_dpi PNGARG((png_structp png_ptr,
  184679. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  184680. #endif /* PNG_pHYs_SUPPORTED */
  184681. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  184682. /* Maintainer: Put new private prototypes here ^ and in libpngpf.3 */
  184683. #endif /* PNG_INTERNAL */
  184684. #ifdef __cplusplus
  184685. //}
  184686. #endif
  184687. #endif /* PNG_VERSION_INFO_ONLY */
  184688. /* do not put anything past this line */
  184689. #endif /* PNG_H */
  184690. /*** End of inlined file: png.h ***/
  184691. #define PNG_NO_EXTERN
  184692. /*** Start of inlined file: png.c ***/
  184693. /* png.c - location for general purpose libpng functions
  184694. *
  184695. * Last changed in libpng 1.2.21 [October 4, 2007]
  184696. * For conditions of distribution and use, see copyright notice in png.h
  184697. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  184698. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  184699. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  184700. */
  184701. #define PNG_INTERNAL
  184702. #define PNG_NO_EXTERN
  184703. /* Generate a compiler error if there is an old png.h in the search path. */
  184704. typedef version_1_2_21 Your_png_h_is_not_version_1_2_21;
  184705. /* Version information for C files. This had better match the version
  184706. * string defined in png.h. */
  184707. #ifdef PNG_USE_GLOBAL_ARRAYS
  184708. /* png_libpng_ver was changed to a function in version 1.0.5c */
  184709. PNG_CONST char png_libpng_ver[18] = PNG_LIBPNG_VER_STRING;
  184710. #ifdef PNG_READ_SUPPORTED
  184711. /* png_sig was changed to a function in version 1.0.5c */
  184712. /* Place to hold the signature string for a PNG file. */
  184713. PNG_CONST png_byte FARDATA png_sig[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  184714. #endif /* PNG_READ_SUPPORTED */
  184715. /* Invoke global declarations for constant strings for known chunk types */
  184716. PNG_IHDR;
  184717. PNG_IDAT;
  184718. PNG_IEND;
  184719. PNG_PLTE;
  184720. PNG_bKGD;
  184721. PNG_cHRM;
  184722. PNG_gAMA;
  184723. PNG_hIST;
  184724. PNG_iCCP;
  184725. PNG_iTXt;
  184726. PNG_oFFs;
  184727. PNG_pCAL;
  184728. PNG_sCAL;
  184729. PNG_pHYs;
  184730. PNG_sBIT;
  184731. PNG_sPLT;
  184732. PNG_sRGB;
  184733. PNG_tEXt;
  184734. PNG_tIME;
  184735. PNG_tRNS;
  184736. PNG_zTXt;
  184737. #ifdef PNG_READ_SUPPORTED
  184738. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  184739. /* start of interlace block */
  184740. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  184741. /* offset to next interlace block */
  184742. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  184743. /* start of interlace block in the y direction */
  184744. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  184745. /* offset to next interlace block in the y direction */
  184746. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  184747. /* Height of interlace block. This is not currently used - if you need
  184748. * it, uncomment it here and in png.h
  184749. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  184750. */
  184751. /* Mask to determine which pixels are valid in a pass */
  184752. PNG_CONST int FARDATA png_pass_mask[] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  184753. /* Mask to determine which pixels to overwrite while displaying */
  184754. PNG_CONST int FARDATA png_pass_dsp_mask[]
  184755. = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  184756. #endif /* PNG_READ_SUPPORTED */
  184757. #endif /* PNG_USE_GLOBAL_ARRAYS */
  184758. /* Tells libpng that we have already handled the first "num_bytes" bytes
  184759. * of the PNG file signature. If the PNG data is embedded into another
  184760. * stream we can set num_bytes = 8 so that libpng will not attempt to read
  184761. * or write any of the magic bytes before it starts on the IHDR.
  184762. */
  184763. #ifdef PNG_READ_SUPPORTED
  184764. void PNGAPI
  184765. png_set_sig_bytes(png_structp png_ptr, int num_bytes)
  184766. {
  184767. if(png_ptr == NULL) return;
  184768. png_debug(1, "in png_set_sig_bytes\n");
  184769. if (num_bytes > 8)
  184770. png_error(png_ptr, "Too many bytes for PNG signature.");
  184771. png_ptr->sig_bytes = (png_byte)(num_bytes < 0 ? 0 : num_bytes);
  184772. }
  184773. /* Checks whether the supplied bytes match the PNG signature. We allow
  184774. * checking less than the full 8-byte signature so that those apps that
  184775. * already read the first few bytes of a file to determine the file type
  184776. * can simply check the remaining bytes for extra assurance. Returns
  184777. * an integer less than, equal to, or greater than zero if sig is found,
  184778. * respectively, to be less than, to match, or be greater than the correct
  184779. * PNG signature (this is the same behaviour as strcmp, memcmp, etc).
  184780. */
  184781. int PNGAPI
  184782. png_sig_cmp(png_bytep sig, png_size_t start, png_size_t num_to_check)
  184783. {
  184784. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  184785. if (num_to_check > 8)
  184786. num_to_check = 8;
  184787. else if (num_to_check < 1)
  184788. return (-1);
  184789. if (start > 7)
  184790. return (-1);
  184791. if (start + num_to_check > 8)
  184792. num_to_check = 8 - start;
  184793. return ((int)(png_memcmp(&sig[start], &png_signature[start], num_to_check)));
  184794. }
  184795. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  184796. /* (Obsolete) function to check signature bytes. It does not allow one
  184797. * to check a partial signature. This function might be removed in the
  184798. * future - use png_sig_cmp(). Returns true (nonzero) if the file is PNG.
  184799. */
  184800. int PNGAPI
  184801. png_check_sig(png_bytep sig, int num)
  184802. {
  184803. return ((int)!png_sig_cmp(sig, (png_size_t)0, (png_size_t)num));
  184804. }
  184805. #endif
  184806. #endif /* PNG_READ_SUPPORTED */
  184807. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184808. /* Function to allocate memory for zlib and clear it to 0. */
  184809. #ifdef PNG_1_0_X
  184810. voidpf PNGAPI
  184811. #else
  184812. voidpf /* private */
  184813. #endif
  184814. png_zalloc(voidpf png_ptr, uInt items, uInt size)
  184815. {
  184816. png_voidp ptr;
  184817. png_structp p=(png_structp)png_ptr;
  184818. png_uint_32 save_flags=p->flags;
  184819. png_uint_32 num_bytes;
  184820. if(png_ptr == NULL) return (NULL);
  184821. if (items > PNG_UINT_32_MAX/size)
  184822. {
  184823. png_warning (p, "Potential overflow in png_zalloc()");
  184824. return (NULL);
  184825. }
  184826. num_bytes = (png_uint_32)items * size;
  184827. p->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  184828. ptr = (png_voidp)png_malloc((png_structp)png_ptr, num_bytes);
  184829. p->flags=save_flags;
  184830. #if defined(PNG_1_0_X) && !defined(PNG_NO_ZALLOC_ZERO)
  184831. if (ptr == NULL)
  184832. return ((voidpf)ptr);
  184833. if (num_bytes > (png_uint_32)0x8000L)
  184834. {
  184835. png_memset(ptr, 0, (png_size_t)0x8000L);
  184836. png_memset((png_bytep)ptr + (png_size_t)0x8000L, 0,
  184837. (png_size_t)(num_bytes - (png_uint_32)0x8000L));
  184838. }
  184839. else
  184840. {
  184841. png_memset(ptr, 0, (png_size_t)num_bytes);
  184842. }
  184843. #endif
  184844. return ((voidpf)ptr);
  184845. }
  184846. /* function to free memory for zlib */
  184847. #ifdef PNG_1_0_X
  184848. void PNGAPI
  184849. #else
  184850. void /* private */
  184851. #endif
  184852. png_zfree(voidpf png_ptr, voidpf ptr)
  184853. {
  184854. png_free((png_structp)png_ptr, (png_voidp)ptr);
  184855. }
  184856. /* Reset the CRC variable to 32 bits of 1's. Care must be taken
  184857. * in case CRC is > 32 bits to leave the top bits 0.
  184858. */
  184859. void /* PRIVATE */
  184860. png_reset_crc(png_structp png_ptr)
  184861. {
  184862. png_ptr->crc = crc32(0, Z_NULL, 0);
  184863. }
  184864. /* Calculate the CRC over a section of data. We can only pass as
  184865. * much data to this routine as the largest single buffer size. We
  184866. * also check that this data will actually be used before going to the
  184867. * trouble of calculating it.
  184868. */
  184869. void /* PRIVATE */
  184870. png_calculate_crc(png_structp png_ptr, png_bytep ptr, png_size_t length)
  184871. {
  184872. int need_crc = 1;
  184873. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  184874. {
  184875. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  184876. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  184877. need_crc = 0;
  184878. }
  184879. else /* critical */
  184880. {
  184881. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  184882. need_crc = 0;
  184883. }
  184884. if (need_crc)
  184885. png_ptr->crc = crc32(png_ptr->crc, ptr, (uInt)length);
  184886. }
  184887. /* Allocate the memory for an info_struct for the application. We don't
  184888. * really need the png_ptr, but it could potentially be useful in the
  184889. * future. This should be used in favour of malloc(png_sizeof(png_info))
  184890. * and png_info_init() so that applications that want to use a shared
  184891. * libpng don't have to be recompiled if png_info changes size.
  184892. */
  184893. png_infop PNGAPI
  184894. png_create_info_struct(png_structp png_ptr)
  184895. {
  184896. png_infop info_ptr;
  184897. png_debug(1, "in png_create_info_struct\n");
  184898. if(png_ptr == NULL) return (NULL);
  184899. #ifdef PNG_USER_MEM_SUPPORTED
  184900. info_ptr = (png_infop)png_create_struct_2(PNG_STRUCT_INFO,
  184901. png_ptr->malloc_fn, png_ptr->mem_ptr);
  184902. #else
  184903. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  184904. #endif
  184905. if (info_ptr != NULL)
  184906. png_info_init_3(&info_ptr, png_sizeof(png_info));
  184907. return (info_ptr);
  184908. }
  184909. /* This function frees the memory associated with a single info struct.
  184910. * Normally, one would use either png_destroy_read_struct() or
  184911. * png_destroy_write_struct() to free an info struct, but this may be
  184912. * useful for some applications.
  184913. */
  184914. void PNGAPI
  184915. png_destroy_info_struct(png_structp png_ptr, png_infopp info_ptr_ptr)
  184916. {
  184917. png_infop info_ptr = NULL;
  184918. if(png_ptr == NULL) return;
  184919. png_debug(1, "in png_destroy_info_struct\n");
  184920. if (info_ptr_ptr != NULL)
  184921. info_ptr = *info_ptr_ptr;
  184922. if (info_ptr != NULL)
  184923. {
  184924. png_info_destroy(png_ptr, info_ptr);
  184925. #ifdef PNG_USER_MEM_SUPPORTED
  184926. png_destroy_struct_2((png_voidp)info_ptr, png_ptr->free_fn,
  184927. png_ptr->mem_ptr);
  184928. #else
  184929. png_destroy_struct((png_voidp)info_ptr);
  184930. #endif
  184931. *info_ptr_ptr = NULL;
  184932. }
  184933. }
  184934. /* Initialize the info structure. This is now an internal function (0.89)
  184935. * and applications using it are urged to use png_create_info_struct()
  184936. * instead.
  184937. */
  184938. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  184939. #undef png_info_init
  184940. void PNGAPI
  184941. png_info_init(png_infop info_ptr)
  184942. {
  184943. /* We only come here via pre-1.0.12-compiled applications */
  184944. png_info_init_3(&info_ptr, 0);
  184945. }
  184946. #endif
  184947. void PNGAPI
  184948. png_info_init_3(png_infopp ptr_ptr, png_size_t png_info_struct_size)
  184949. {
  184950. png_infop info_ptr = *ptr_ptr;
  184951. if(info_ptr == NULL) return;
  184952. png_debug(1, "in png_info_init_3\n");
  184953. if(png_sizeof(png_info) > png_info_struct_size)
  184954. {
  184955. png_destroy_struct(info_ptr);
  184956. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  184957. *ptr_ptr = info_ptr;
  184958. }
  184959. /* set everything to 0 */
  184960. png_memset(info_ptr, 0, png_sizeof (png_info));
  184961. }
  184962. #ifdef PNG_FREE_ME_SUPPORTED
  184963. void PNGAPI
  184964. png_data_freer(png_structp png_ptr, png_infop info_ptr,
  184965. int freer, png_uint_32 mask)
  184966. {
  184967. png_debug(1, "in png_data_freer\n");
  184968. if (png_ptr == NULL || info_ptr == NULL)
  184969. return;
  184970. if(freer == PNG_DESTROY_WILL_FREE_DATA)
  184971. info_ptr->free_me |= mask;
  184972. else if(freer == PNG_USER_WILL_FREE_DATA)
  184973. info_ptr->free_me &= ~mask;
  184974. else
  184975. png_warning(png_ptr,
  184976. "Unknown freer parameter in png_data_freer.");
  184977. }
  184978. #endif
  184979. void PNGAPI
  184980. png_free_data(png_structp png_ptr, png_infop info_ptr, png_uint_32 mask,
  184981. int num)
  184982. {
  184983. png_debug(1, "in png_free_data\n");
  184984. if (png_ptr == NULL || info_ptr == NULL)
  184985. return;
  184986. #if defined(PNG_TEXT_SUPPORTED)
  184987. /* free text item num or (if num == -1) all text items */
  184988. #ifdef PNG_FREE_ME_SUPPORTED
  184989. if ((mask & PNG_FREE_TEXT) & info_ptr->free_me)
  184990. #else
  184991. if (mask & PNG_FREE_TEXT)
  184992. #endif
  184993. {
  184994. if (num != -1)
  184995. {
  184996. if (info_ptr->text && info_ptr->text[num].key)
  184997. {
  184998. png_free(png_ptr, info_ptr->text[num].key);
  184999. info_ptr->text[num].key = NULL;
  185000. }
  185001. }
  185002. else
  185003. {
  185004. int i;
  185005. for (i = 0; i < info_ptr->num_text; i++)
  185006. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, i);
  185007. png_free(png_ptr, info_ptr->text);
  185008. info_ptr->text = NULL;
  185009. info_ptr->num_text=0;
  185010. }
  185011. }
  185012. #endif
  185013. #if defined(PNG_tRNS_SUPPORTED)
  185014. /* free any tRNS entry */
  185015. #ifdef PNG_FREE_ME_SUPPORTED
  185016. if ((mask & PNG_FREE_TRNS) & info_ptr->free_me)
  185017. #else
  185018. if ((mask & PNG_FREE_TRNS) && (png_ptr->flags & PNG_FLAG_FREE_TRNS))
  185019. #endif
  185020. {
  185021. png_free(png_ptr, info_ptr->trans);
  185022. info_ptr->valid &= ~PNG_INFO_tRNS;
  185023. #ifndef PNG_FREE_ME_SUPPORTED
  185024. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  185025. #endif
  185026. info_ptr->trans = NULL;
  185027. }
  185028. #endif
  185029. #if defined(PNG_sCAL_SUPPORTED)
  185030. /* free any sCAL entry */
  185031. #ifdef PNG_FREE_ME_SUPPORTED
  185032. if ((mask & PNG_FREE_SCAL) & info_ptr->free_me)
  185033. #else
  185034. if (mask & PNG_FREE_SCAL)
  185035. #endif
  185036. {
  185037. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  185038. png_free(png_ptr, info_ptr->scal_s_width);
  185039. png_free(png_ptr, info_ptr->scal_s_height);
  185040. info_ptr->scal_s_width = NULL;
  185041. info_ptr->scal_s_height = NULL;
  185042. #endif
  185043. info_ptr->valid &= ~PNG_INFO_sCAL;
  185044. }
  185045. #endif
  185046. #if defined(PNG_pCAL_SUPPORTED)
  185047. /* free any pCAL entry */
  185048. #ifdef PNG_FREE_ME_SUPPORTED
  185049. if ((mask & PNG_FREE_PCAL) & info_ptr->free_me)
  185050. #else
  185051. if (mask & PNG_FREE_PCAL)
  185052. #endif
  185053. {
  185054. png_free(png_ptr, info_ptr->pcal_purpose);
  185055. png_free(png_ptr, info_ptr->pcal_units);
  185056. info_ptr->pcal_purpose = NULL;
  185057. info_ptr->pcal_units = NULL;
  185058. if (info_ptr->pcal_params != NULL)
  185059. {
  185060. int i;
  185061. for (i = 0; i < (int)info_ptr->pcal_nparams; i++)
  185062. {
  185063. png_free(png_ptr, info_ptr->pcal_params[i]);
  185064. info_ptr->pcal_params[i]=NULL;
  185065. }
  185066. png_free(png_ptr, info_ptr->pcal_params);
  185067. info_ptr->pcal_params = NULL;
  185068. }
  185069. info_ptr->valid &= ~PNG_INFO_pCAL;
  185070. }
  185071. #endif
  185072. #if defined(PNG_iCCP_SUPPORTED)
  185073. /* free any iCCP entry */
  185074. #ifdef PNG_FREE_ME_SUPPORTED
  185075. if ((mask & PNG_FREE_ICCP) & info_ptr->free_me)
  185076. #else
  185077. if (mask & PNG_FREE_ICCP)
  185078. #endif
  185079. {
  185080. png_free(png_ptr, info_ptr->iccp_name);
  185081. png_free(png_ptr, info_ptr->iccp_profile);
  185082. info_ptr->iccp_name = NULL;
  185083. info_ptr->iccp_profile = NULL;
  185084. info_ptr->valid &= ~PNG_INFO_iCCP;
  185085. }
  185086. #endif
  185087. #if defined(PNG_sPLT_SUPPORTED)
  185088. /* free a given sPLT entry, or (if num == -1) all sPLT entries */
  185089. #ifdef PNG_FREE_ME_SUPPORTED
  185090. if ((mask & PNG_FREE_SPLT) & info_ptr->free_me)
  185091. #else
  185092. if (mask & PNG_FREE_SPLT)
  185093. #endif
  185094. {
  185095. if (num != -1)
  185096. {
  185097. if(info_ptr->splt_palettes)
  185098. {
  185099. png_free(png_ptr, info_ptr->splt_palettes[num].name);
  185100. png_free(png_ptr, info_ptr->splt_palettes[num].entries);
  185101. info_ptr->splt_palettes[num].name = NULL;
  185102. info_ptr->splt_palettes[num].entries = NULL;
  185103. }
  185104. }
  185105. else
  185106. {
  185107. if(info_ptr->splt_palettes_num)
  185108. {
  185109. int i;
  185110. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  185111. png_free_data(png_ptr, info_ptr, PNG_FREE_SPLT, i);
  185112. png_free(png_ptr, info_ptr->splt_palettes);
  185113. info_ptr->splt_palettes = NULL;
  185114. info_ptr->splt_palettes_num = 0;
  185115. }
  185116. info_ptr->valid &= ~PNG_INFO_sPLT;
  185117. }
  185118. }
  185119. #endif
  185120. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  185121. if(png_ptr->unknown_chunk.data)
  185122. {
  185123. png_free(png_ptr, png_ptr->unknown_chunk.data);
  185124. png_ptr->unknown_chunk.data = NULL;
  185125. }
  185126. #ifdef PNG_FREE_ME_SUPPORTED
  185127. if ((mask & PNG_FREE_UNKN) & info_ptr->free_me)
  185128. #else
  185129. if (mask & PNG_FREE_UNKN)
  185130. #endif
  185131. {
  185132. if (num != -1)
  185133. {
  185134. if(info_ptr->unknown_chunks)
  185135. {
  185136. png_free(png_ptr, info_ptr->unknown_chunks[num].data);
  185137. info_ptr->unknown_chunks[num].data = NULL;
  185138. }
  185139. }
  185140. else
  185141. {
  185142. int i;
  185143. if(info_ptr->unknown_chunks_num)
  185144. {
  185145. for (i = 0; i < (int)info_ptr->unknown_chunks_num; i++)
  185146. png_free_data(png_ptr, info_ptr, PNG_FREE_UNKN, i);
  185147. png_free(png_ptr, info_ptr->unknown_chunks);
  185148. info_ptr->unknown_chunks = NULL;
  185149. info_ptr->unknown_chunks_num = 0;
  185150. }
  185151. }
  185152. }
  185153. #endif
  185154. #if defined(PNG_hIST_SUPPORTED)
  185155. /* free any hIST entry */
  185156. #ifdef PNG_FREE_ME_SUPPORTED
  185157. if ((mask & PNG_FREE_HIST) & info_ptr->free_me)
  185158. #else
  185159. if ((mask & PNG_FREE_HIST) && (png_ptr->flags & PNG_FLAG_FREE_HIST))
  185160. #endif
  185161. {
  185162. png_free(png_ptr, info_ptr->hist);
  185163. info_ptr->hist = NULL;
  185164. info_ptr->valid &= ~PNG_INFO_hIST;
  185165. #ifndef PNG_FREE_ME_SUPPORTED
  185166. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  185167. #endif
  185168. }
  185169. #endif
  185170. /* free any PLTE entry that was internally allocated */
  185171. #ifdef PNG_FREE_ME_SUPPORTED
  185172. if ((mask & PNG_FREE_PLTE) & info_ptr->free_me)
  185173. #else
  185174. if ((mask & PNG_FREE_PLTE) && (png_ptr->flags & PNG_FLAG_FREE_PLTE))
  185175. #endif
  185176. {
  185177. png_zfree(png_ptr, info_ptr->palette);
  185178. info_ptr->palette = NULL;
  185179. info_ptr->valid &= ~PNG_INFO_PLTE;
  185180. #ifndef PNG_FREE_ME_SUPPORTED
  185181. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  185182. #endif
  185183. info_ptr->num_palette = 0;
  185184. }
  185185. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  185186. /* free any image bits attached to the info structure */
  185187. #ifdef PNG_FREE_ME_SUPPORTED
  185188. if ((mask & PNG_FREE_ROWS) & info_ptr->free_me)
  185189. #else
  185190. if (mask & PNG_FREE_ROWS)
  185191. #endif
  185192. {
  185193. if(info_ptr->row_pointers)
  185194. {
  185195. int row;
  185196. for (row = 0; row < (int)info_ptr->height; row++)
  185197. {
  185198. png_free(png_ptr, info_ptr->row_pointers[row]);
  185199. info_ptr->row_pointers[row]=NULL;
  185200. }
  185201. png_free(png_ptr, info_ptr->row_pointers);
  185202. info_ptr->row_pointers=NULL;
  185203. }
  185204. info_ptr->valid &= ~PNG_INFO_IDAT;
  185205. }
  185206. #endif
  185207. #ifdef PNG_FREE_ME_SUPPORTED
  185208. if(num == -1)
  185209. info_ptr->free_me &= ~mask;
  185210. else
  185211. info_ptr->free_me &= ~(mask & ~PNG_FREE_MUL);
  185212. #endif
  185213. }
  185214. /* This is an internal routine to free any memory that the info struct is
  185215. * pointing to before re-using it or freeing the struct itself. Recall
  185216. * that png_free() checks for NULL pointers for us.
  185217. */
  185218. void /* PRIVATE */
  185219. png_info_destroy(png_structp png_ptr, png_infop info_ptr)
  185220. {
  185221. png_debug(1, "in png_info_destroy\n");
  185222. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  185223. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  185224. if (png_ptr->num_chunk_list)
  185225. {
  185226. png_free(png_ptr, png_ptr->chunk_list);
  185227. png_ptr->chunk_list=NULL;
  185228. png_ptr->num_chunk_list=0;
  185229. }
  185230. #endif
  185231. png_info_init_3(&info_ptr, png_sizeof(png_info));
  185232. }
  185233. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185234. /* This function returns a pointer to the io_ptr associated with the user
  185235. * functions. The application should free any memory associated with this
  185236. * pointer before png_write_destroy() or png_read_destroy() are called.
  185237. */
  185238. png_voidp PNGAPI
  185239. png_get_io_ptr(png_structp png_ptr)
  185240. {
  185241. if(png_ptr == NULL) return (NULL);
  185242. return (png_ptr->io_ptr);
  185243. }
  185244. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185245. #if !defined(PNG_NO_STDIO)
  185246. /* Initialize the default input/output functions for the PNG file. If you
  185247. * use your own read or write routines, you can call either png_set_read_fn()
  185248. * or png_set_write_fn() instead of png_init_io(). If you have defined
  185249. * PNG_NO_STDIO, you must use a function of your own because "FILE *" isn't
  185250. * necessarily available.
  185251. */
  185252. void PNGAPI
  185253. png_init_io(png_structp png_ptr, png_FILE_p fp)
  185254. {
  185255. png_debug(1, "in png_init_io\n");
  185256. if(png_ptr == NULL) return;
  185257. png_ptr->io_ptr = (png_voidp)fp;
  185258. }
  185259. #endif
  185260. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  185261. /* Convert the supplied time into an RFC 1123 string suitable for use in
  185262. * a "Creation Time" or other text-based time string.
  185263. */
  185264. png_charp PNGAPI
  185265. png_convert_to_rfc1123(png_structp png_ptr, png_timep ptime)
  185266. {
  185267. static PNG_CONST char short_months[12][4] =
  185268. {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  185269. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  185270. if(png_ptr == NULL) return (NULL);
  185271. if (png_ptr->time_buffer == NULL)
  185272. {
  185273. png_ptr->time_buffer = (png_charp)png_malloc(png_ptr, (png_uint_32)(29*
  185274. png_sizeof(char)));
  185275. }
  185276. #if defined(_WIN32_WCE)
  185277. {
  185278. wchar_t time_buf[29];
  185279. wsprintf(time_buf, TEXT("%d %S %d %02d:%02d:%02d +0000"),
  185280. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  185281. ptime->year, ptime->hour % 24, ptime->minute % 60,
  185282. ptime->second % 61);
  185283. WideCharToMultiByte(CP_ACP, 0, time_buf, -1, png_ptr->time_buffer, 29,
  185284. NULL, NULL);
  185285. }
  185286. #else
  185287. #ifdef USE_FAR_KEYWORD
  185288. {
  185289. char near_time_buf[29];
  185290. png_snprintf6(near_time_buf,29,"%d %s %d %02d:%02d:%02d +0000",
  185291. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  185292. ptime->year, ptime->hour % 24, ptime->minute % 60,
  185293. ptime->second % 61);
  185294. png_memcpy(png_ptr->time_buffer, near_time_buf,
  185295. 29*png_sizeof(char));
  185296. }
  185297. #else
  185298. png_snprintf6(png_ptr->time_buffer,29,"%d %s %d %02d:%02d:%02d +0000",
  185299. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  185300. ptime->year, ptime->hour % 24, ptime->minute % 60,
  185301. ptime->second % 61);
  185302. #endif
  185303. #endif /* _WIN32_WCE */
  185304. return ((png_charp)png_ptr->time_buffer);
  185305. }
  185306. #endif /* PNG_TIME_RFC1123_SUPPORTED */
  185307. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185308. png_charp PNGAPI
  185309. png_get_copyright(png_structp png_ptr)
  185310. {
  185311. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185312. return ((png_charp) "\n libpng version 1.2.21 - October 4, 2007\n\
  185313. Copyright (c) 1998-2007 Glenn Randers-Pehrson\n\
  185314. Copyright (c) 1996-1997 Andreas Dilger\n\
  185315. Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.\n");
  185316. }
  185317. /* The following return the library version as a short string in the
  185318. * format 1.0.0 through 99.99.99zz. To get the version of *.h files
  185319. * used with your application, print out PNG_LIBPNG_VER_STRING, which
  185320. * is defined in png.h.
  185321. * Note: now there is no difference between png_get_libpng_ver() and
  185322. * png_get_header_ver(). Due to the version_nn_nn_nn typedef guard,
  185323. * it is guaranteed that png.c uses the correct version of png.h.
  185324. */
  185325. png_charp PNGAPI
  185326. png_get_libpng_ver(png_structp png_ptr)
  185327. {
  185328. /* Version of *.c files used when building libpng */
  185329. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185330. return ((png_charp) PNG_LIBPNG_VER_STRING);
  185331. }
  185332. png_charp PNGAPI
  185333. png_get_header_ver(png_structp png_ptr)
  185334. {
  185335. /* Version of *.h files used when building libpng */
  185336. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185337. return ((png_charp) PNG_LIBPNG_VER_STRING);
  185338. }
  185339. png_charp PNGAPI
  185340. png_get_header_version(png_structp png_ptr)
  185341. {
  185342. /* Returns longer string containing both version and date */
  185343. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185344. return ((png_charp) PNG_HEADER_VERSION_STRING
  185345. #ifndef PNG_READ_SUPPORTED
  185346. " (NO READ SUPPORT)"
  185347. #endif
  185348. "\n");
  185349. }
  185350. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185351. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  185352. int PNGAPI
  185353. png_handle_as_unknown(png_structp png_ptr, png_bytep chunk_name)
  185354. {
  185355. /* check chunk_name and return "keep" value if it's on the list, else 0 */
  185356. int i;
  185357. png_bytep p;
  185358. if(png_ptr == NULL || chunk_name == NULL || png_ptr->num_chunk_list<=0)
  185359. return 0;
  185360. p=png_ptr->chunk_list+png_ptr->num_chunk_list*5-5;
  185361. for (i = png_ptr->num_chunk_list; i; i--, p-=5)
  185362. if (!png_memcmp(chunk_name, p, 4))
  185363. return ((int)*(p+4));
  185364. return 0;
  185365. }
  185366. #endif
  185367. /* This function, added to libpng-1.0.6g, is untested. */
  185368. int PNGAPI
  185369. png_reset_zstream(png_structp png_ptr)
  185370. {
  185371. if (png_ptr == NULL) return Z_STREAM_ERROR;
  185372. return (inflateReset(&png_ptr->zstream));
  185373. }
  185374. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185375. /* This function was added to libpng-1.0.7 */
  185376. png_uint_32 PNGAPI
  185377. png_access_version_number(void)
  185378. {
  185379. /* Version of *.c files used when building libpng */
  185380. return((png_uint_32) PNG_LIBPNG_VER);
  185381. }
  185382. #if defined(PNG_READ_SUPPORTED) && defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  185383. #if !defined(PNG_1_0_X)
  185384. /* this function was added to libpng 1.2.0 */
  185385. int PNGAPI
  185386. png_mmx_support(void)
  185387. {
  185388. /* obsolete, to be removed from libpng-1.4.0 */
  185389. return -1;
  185390. }
  185391. #endif /* PNG_1_0_X */
  185392. #endif /* PNG_READ_SUPPORTED && PNG_ASSEMBLER_CODE_SUPPORTED */
  185393. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185394. #ifdef PNG_SIZE_T
  185395. /* Added at libpng version 1.2.6 */
  185396. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  185397. png_size_t PNGAPI
  185398. png_convert_size(size_t size)
  185399. {
  185400. if (size > (png_size_t)-1)
  185401. PNG_ABORT(); /* We haven't got access to png_ptr, so no png_error() */
  185402. return ((png_size_t)size);
  185403. }
  185404. #endif /* PNG_SIZE_T */
  185405. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185406. /*** End of inlined file: png.c ***/
  185407. /*** Start of inlined file: pngerror.c ***/
  185408. /* pngerror.c - stub functions for i/o and memory allocation
  185409. *
  185410. * Last changed in libpng 1.2.20 October 4, 2007
  185411. * For conditions of distribution and use, see copyright notice in png.h
  185412. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  185413. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185414. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185415. *
  185416. * This file provides a location for all error handling. Users who
  185417. * need special error handling are expected to write replacement functions
  185418. * and use png_set_error_fn() to use those functions. See the instructions
  185419. * at each function.
  185420. */
  185421. #define PNG_INTERNAL
  185422. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185423. static void /* PRIVATE */
  185424. png_default_error PNGARG((png_structp png_ptr,
  185425. png_const_charp error_message));
  185426. #ifndef PNG_NO_WARNINGS
  185427. static void /* PRIVATE */
  185428. png_default_warning PNGARG((png_structp png_ptr,
  185429. png_const_charp warning_message));
  185430. #endif /* PNG_NO_WARNINGS */
  185431. /* This function is called whenever there is a fatal error. This function
  185432. * should not be changed. If there is a need to handle errors differently,
  185433. * you should supply a replacement error function and use png_set_error_fn()
  185434. * to replace the error function at run-time.
  185435. */
  185436. #ifndef PNG_NO_ERROR_TEXT
  185437. void PNGAPI
  185438. png_error(png_structp png_ptr, png_const_charp error_message)
  185439. {
  185440. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185441. char msg[16];
  185442. if (png_ptr != NULL)
  185443. {
  185444. if (png_ptr->flags&
  185445. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  185446. {
  185447. if (*error_message == '#')
  185448. {
  185449. int offset;
  185450. for (offset=1; offset<15; offset++)
  185451. if (*(error_message+offset) == ' ')
  185452. break;
  185453. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  185454. {
  185455. int i;
  185456. for (i=0; i<offset-1; i++)
  185457. msg[i]=error_message[i+1];
  185458. msg[i]='\0';
  185459. error_message=msg;
  185460. }
  185461. else
  185462. error_message+=offset;
  185463. }
  185464. else
  185465. {
  185466. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  185467. {
  185468. msg[0]='0';
  185469. msg[1]='\0';
  185470. error_message=msg;
  185471. }
  185472. }
  185473. }
  185474. }
  185475. #endif
  185476. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  185477. (*(png_ptr->error_fn))(png_ptr, error_message);
  185478. /* If the custom handler doesn't exist, or if it returns,
  185479. use the default handler, which will not return. */
  185480. png_default_error(png_ptr, error_message);
  185481. }
  185482. #else
  185483. void PNGAPI
  185484. png_err(png_structp png_ptr)
  185485. {
  185486. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  185487. (*(png_ptr->error_fn))(png_ptr, '\0');
  185488. /* If the custom handler doesn't exist, or if it returns,
  185489. use the default handler, which will not return. */
  185490. png_default_error(png_ptr, '\0');
  185491. }
  185492. #endif /* PNG_NO_ERROR_TEXT */
  185493. #ifndef PNG_NO_WARNINGS
  185494. /* This function is called whenever there is a non-fatal error. This function
  185495. * should not be changed. If there is a need to handle warnings differently,
  185496. * you should supply a replacement warning function and use
  185497. * png_set_error_fn() to replace the warning function at run-time.
  185498. */
  185499. void PNGAPI
  185500. png_warning(png_structp png_ptr, png_const_charp warning_message)
  185501. {
  185502. int offset = 0;
  185503. if (png_ptr != NULL)
  185504. {
  185505. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185506. if (png_ptr->flags&
  185507. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  185508. #endif
  185509. {
  185510. if (*warning_message == '#')
  185511. {
  185512. for (offset=1; offset<15; offset++)
  185513. if (*(warning_message+offset) == ' ')
  185514. break;
  185515. }
  185516. }
  185517. if (png_ptr != NULL && png_ptr->warning_fn != NULL)
  185518. (*(png_ptr->warning_fn))(png_ptr, warning_message+offset);
  185519. }
  185520. else
  185521. png_default_warning(png_ptr, warning_message+offset);
  185522. }
  185523. #endif /* PNG_NO_WARNINGS */
  185524. /* These utilities are used internally to build an error message that relates
  185525. * to the current chunk. The chunk name comes from png_ptr->chunk_name,
  185526. * this is used to prefix the message. The message is limited in length
  185527. * to 63 bytes, the name characters are output as hex digits wrapped in []
  185528. * if the character is invalid.
  185529. */
  185530. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  185531. /*static PNG_CONST char png_digit[16] = {
  185532. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  185533. 'A', 'B', 'C', 'D', 'E', 'F'
  185534. };*/
  185535. #if !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT)
  185536. static void /* PRIVATE */
  185537. png_format_buffer(png_structp png_ptr, png_charp buffer, png_const_charp
  185538. error_message)
  185539. {
  185540. int iout = 0, iin = 0;
  185541. while (iin < 4)
  185542. {
  185543. int c = png_ptr->chunk_name[iin++];
  185544. if (isnonalpha(c))
  185545. {
  185546. buffer[iout++] = '[';
  185547. buffer[iout++] = png_digit[(c & 0xf0) >> 4];
  185548. buffer[iout++] = png_digit[c & 0x0f];
  185549. buffer[iout++] = ']';
  185550. }
  185551. else
  185552. {
  185553. buffer[iout++] = (png_byte)c;
  185554. }
  185555. }
  185556. if (error_message == NULL)
  185557. buffer[iout] = 0;
  185558. else
  185559. {
  185560. buffer[iout++] = ':';
  185561. buffer[iout++] = ' ';
  185562. png_strncpy(buffer+iout, error_message, 63);
  185563. buffer[iout+63] = 0;
  185564. }
  185565. }
  185566. #ifdef PNG_READ_SUPPORTED
  185567. void PNGAPI
  185568. png_chunk_error(png_structp png_ptr, png_const_charp error_message)
  185569. {
  185570. char msg[18+64];
  185571. if (png_ptr == NULL)
  185572. png_error(png_ptr, error_message);
  185573. else
  185574. {
  185575. png_format_buffer(png_ptr, msg, error_message);
  185576. png_error(png_ptr, msg);
  185577. }
  185578. }
  185579. #endif /* PNG_READ_SUPPORTED */
  185580. #endif /* !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT) */
  185581. #ifndef PNG_NO_WARNINGS
  185582. void PNGAPI
  185583. png_chunk_warning(png_structp png_ptr, png_const_charp warning_message)
  185584. {
  185585. char msg[18+64];
  185586. if (png_ptr == NULL)
  185587. png_warning(png_ptr, warning_message);
  185588. else
  185589. {
  185590. png_format_buffer(png_ptr, msg, warning_message);
  185591. png_warning(png_ptr, msg);
  185592. }
  185593. }
  185594. #endif /* PNG_NO_WARNINGS */
  185595. /* This is the default error handling function. Note that replacements for
  185596. * this function MUST NOT RETURN, or the program will likely crash. This
  185597. * function is used by default, or if the program supplies NULL for the
  185598. * error function pointer in png_set_error_fn().
  185599. */
  185600. static void /* PRIVATE */
  185601. png_default_error(png_structp, png_const_charp error_message)
  185602. {
  185603. #ifndef PNG_NO_CONSOLE_IO
  185604. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185605. if (*error_message == '#')
  185606. {
  185607. int offset;
  185608. char error_number[16];
  185609. for (offset=0; offset<15; offset++)
  185610. {
  185611. error_number[offset] = *(error_message+offset+1);
  185612. if (*(error_message+offset) == ' ')
  185613. break;
  185614. }
  185615. if((offset > 1) && (offset < 15))
  185616. {
  185617. error_number[offset-1]='\0';
  185618. fprintf(stderr, "libpng error no. %s: %s\n", error_number,
  185619. error_message+offset);
  185620. }
  185621. else
  185622. fprintf(stderr, "libpng error: %s, offset=%d\n", error_message,offset);
  185623. }
  185624. else
  185625. #endif
  185626. fprintf(stderr, "libpng error: %s\n", error_message);
  185627. #endif
  185628. #ifdef PNG_SETJMP_SUPPORTED
  185629. if (png_ptr)
  185630. {
  185631. # ifdef USE_FAR_KEYWORD
  185632. {
  185633. jmp_buf jmpbuf;
  185634. png_memcpy(jmpbuf, png_ptr->jmpbuf, png_sizeof(jmp_buf));
  185635. longjmp(jmpbuf, 1);
  185636. }
  185637. # else
  185638. longjmp(png_ptr->jmpbuf, 1);
  185639. # endif
  185640. }
  185641. #else
  185642. PNG_ABORT();
  185643. #endif
  185644. #ifdef PNG_NO_CONSOLE_IO
  185645. error_message = error_message; /* make compiler happy */
  185646. #endif
  185647. }
  185648. #ifndef PNG_NO_WARNINGS
  185649. /* This function is called when there is a warning, but the library thinks
  185650. * it can continue anyway. Replacement functions don't have to do anything
  185651. * here if you don't want them to. In the default configuration, png_ptr is
  185652. * not used, but it is passed in case it may be useful.
  185653. */
  185654. static void /* PRIVATE */
  185655. png_default_warning(png_structp png_ptr, png_const_charp warning_message)
  185656. {
  185657. #ifndef PNG_NO_CONSOLE_IO
  185658. # ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185659. if (*warning_message == '#')
  185660. {
  185661. int offset;
  185662. char warning_number[16];
  185663. for (offset=0; offset<15; offset++)
  185664. {
  185665. warning_number[offset]=*(warning_message+offset+1);
  185666. if (*(warning_message+offset) == ' ')
  185667. break;
  185668. }
  185669. if((offset > 1) && (offset < 15))
  185670. {
  185671. warning_number[offset-1]='\0';
  185672. fprintf(stderr, "libpng warning no. %s: %s\n", warning_number,
  185673. warning_message+offset);
  185674. }
  185675. else
  185676. fprintf(stderr, "libpng warning: %s\n", warning_message);
  185677. }
  185678. else
  185679. # endif
  185680. fprintf(stderr, "libpng warning: %s\n", warning_message);
  185681. #else
  185682. warning_message = warning_message; /* make compiler happy */
  185683. #endif
  185684. png_ptr = png_ptr; /* make compiler happy */
  185685. }
  185686. #endif /* PNG_NO_WARNINGS */
  185687. /* This function is called when the application wants to use another method
  185688. * of handling errors and warnings. Note that the error function MUST NOT
  185689. * return to the calling routine or serious problems will occur. The return
  185690. * method used in the default routine calls longjmp(png_ptr->jmpbuf, 1)
  185691. */
  185692. void PNGAPI
  185693. png_set_error_fn(png_structp png_ptr, png_voidp error_ptr,
  185694. png_error_ptr error_fn, png_error_ptr warning_fn)
  185695. {
  185696. if (png_ptr == NULL)
  185697. return;
  185698. png_ptr->error_ptr = error_ptr;
  185699. png_ptr->error_fn = error_fn;
  185700. png_ptr->warning_fn = warning_fn;
  185701. }
  185702. /* This function returns a pointer to the error_ptr associated with the user
  185703. * functions. The application should free any memory associated with this
  185704. * pointer before png_write_destroy and png_read_destroy are called.
  185705. */
  185706. png_voidp PNGAPI
  185707. png_get_error_ptr(png_structp png_ptr)
  185708. {
  185709. if (png_ptr == NULL)
  185710. return NULL;
  185711. return ((png_voidp)png_ptr->error_ptr);
  185712. }
  185713. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185714. void PNGAPI
  185715. png_set_strip_error_numbers(png_structp png_ptr, png_uint_32 strip_mode)
  185716. {
  185717. if(png_ptr != NULL)
  185718. {
  185719. png_ptr->flags &=
  185720. ((~(PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))&strip_mode);
  185721. }
  185722. }
  185723. #endif
  185724. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  185725. /*** End of inlined file: pngerror.c ***/
  185726. /*** Start of inlined file: pngget.c ***/
  185727. /* pngget.c - retrieval of values from info struct
  185728. *
  185729. * Last changed in libpng 1.2.15 January 5, 2007
  185730. * For conditions of distribution and use, see copyright notice in png.h
  185731. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  185732. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185733. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185734. */
  185735. #define PNG_INTERNAL
  185736. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185737. png_uint_32 PNGAPI
  185738. png_get_valid(png_structp png_ptr, png_infop info_ptr, png_uint_32 flag)
  185739. {
  185740. if (png_ptr != NULL && info_ptr != NULL)
  185741. return(info_ptr->valid & flag);
  185742. else
  185743. return(0);
  185744. }
  185745. png_uint_32 PNGAPI
  185746. png_get_rowbytes(png_structp png_ptr, png_infop info_ptr)
  185747. {
  185748. if (png_ptr != NULL && info_ptr != NULL)
  185749. return(info_ptr->rowbytes);
  185750. else
  185751. return(0);
  185752. }
  185753. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  185754. png_bytepp PNGAPI
  185755. png_get_rows(png_structp png_ptr, png_infop info_ptr)
  185756. {
  185757. if (png_ptr != NULL && info_ptr != NULL)
  185758. return(info_ptr->row_pointers);
  185759. else
  185760. return(0);
  185761. }
  185762. #endif
  185763. #ifdef PNG_EASY_ACCESS_SUPPORTED
  185764. /* easy access to info, added in libpng-0.99 */
  185765. png_uint_32 PNGAPI
  185766. png_get_image_width(png_structp png_ptr, png_infop info_ptr)
  185767. {
  185768. if (png_ptr != NULL && info_ptr != NULL)
  185769. {
  185770. return info_ptr->width;
  185771. }
  185772. return (0);
  185773. }
  185774. png_uint_32 PNGAPI
  185775. png_get_image_height(png_structp png_ptr, png_infop info_ptr)
  185776. {
  185777. if (png_ptr != NULL && info_ptr != NULL)
  185778. {
  185779. return info_ptr->height;
  185780. }
  185781. return (0);
  185782. }
  185783. png_byte PNGAPI
  185784. png_get_bit_depth(png_structp png_ptr, png_infop info_ptr)
  185785. {
  185786. if (png_ptr != NULL && info_ptr != NULL)
  185787. {
  185788. return info_ptr->bit_depth;
  185789. }
  185790. return (0);
  185791. }
  185792. png_byte PNGAPI
  185793. png_get_color_type(png_structp png_ptr, png_infop info_ptr)
  185794. {
  185795. if (png_ptr != NULL && info_ptr != NULL)
  185796. {
  185797. return info_ptr->color_type;
  185798. }
  185799. return (0);
  185800. }
  185801. png_byte PNGAPI
  185802. png_get_filter_type(png_structp png_ptr, png_infop info_ptr)
  185803. {
  185804. if (png_ptr != NULL && info_ptr != NULL)
  185805. {
  185806. return info_ptr->filter_type;
  185807. }
  185808. return (0);
  185809. }
  185810. png_byte PNGAPI
  185811. png_get_interlace_type(png_structp png_ptr, png_infop info_ptr)
  185812. {
  185813. if (png_ptr != NULL && info_ptr != NULL)
  185814. {
  185815. return info_ptr->interlace_type;
  185816. }
  185817. return (0);
  185818. }
  185819. png_byte PNGAPI
  185820. png_get_compression_type(png_structp png_ptr, png_infop info_ptr)
  185821. {
  185822. if (png_ptr != NULL && info_ptr != NULL)
  185823. {
  185824. return info_ptr->compression_type;
  185825. }
  185826. return (0);
  185827. }
  185828. png_uint_32 PNGAPI
  185829. png_get_x_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185830. {
  185831. if (png_ptr != NULL && info_ptr != NULL)
  185832. #if defined(PNG_pHYs_SUPPORTED)
  185833. if (info_ptr->valid & PNG_INFO_pHYs)
  185834. {
  185835. png_debug1(1, "in %s retrieval function\n", "png_get_x_pixels_per_meter");
  185836. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  185837. return (0);
  185838. else return (info_ptr->x_pixels_per_unit);
  185839. }
  185840. #else
  185841. return (0);
  185842. #endif
  185843. return (0);
  185844. }
  185845. png_uint_32 PNGAPI
  185846. png_get_y_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185847. {
  185848. if (png_ptr != NULL && info_ptr != NULL)
  185849. #if defined(PNG_pHYs_SUPPORTED)
  185850. if (info_ptr->valid & PNG_INFO_pHYs)
  185851. {
  185852. png_debug1(1, "in %s retrieval function\n", "png_get_y_pixels_per_meter");
  185853. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  185854. return (0);
  185855. else return (info_ptr->y_pixels_per_unit);
  185856. }
  185857. #else
  185858. return (0);
  185859. #endif
  185860. return (0);
  185861. }
  185862. png_uint_32 PNGAPI
  185863. png_get_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185864. {
  185865. if (png_ptr != NULL && info_ptr != NULL)
  185866. #if defined(PNG_pHYs_SUPPORTED)
  185867. if (info_ptr->valid & PNG_INFO_pHYs)
  185868. {
  185869. png_debug1(1, "in %s retrieval function\n", "png_get_pixels_per_meter");
  185870. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER ||
  185871. info_ptr->x_pixels_per_unit != info_ptr->y_pixels_per_unit)
  185872. return (0);
  185873. else return (info_ptr->x_pixels_per_unit);
  185874. }
  185875. #else
  185876. return (0);
  185877. #endif
  185878. return (0);
  185879. }
  185880. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185881. float PNGAPI
  185882. png_get_pixel_aspect_ratio(png_structp png_ptr, png_infop info_ptr)
  185883. {
  185884. if (png_ptr != NULL && info_ptr != NULL)
  185885. #if defined(PNG_pHYs_SUPPORTED)
  185886. if (info_ptr->valid & PNG_INFO_pHYs)
  185887. {
  185888. png_debug1(1, "in %s retrieval function\n", "png_get_aspect_ratio");
  185889. if (info_ptr->x_pixels_per_unit == 0)
  185890. return ((float)0.0);
  185891. else
  185892. return ((float)((float)info_ptr->y_pixels_per_unit
  185893. /(float)info_ptr->x_pixels_per_unit));
  185894. }
  185895. #else
  185896. return (0.0);
  185897. #endif
  185898. return ((float)0.0);
  185899. }
  185900. #endif
  185901. png_int_32 PNGAPI
  185902. png_get_x_offset_microns(png_structp png_ptr, png_infop info_ptr)
  185903. {
  185904. if (png_ptr != NULL && info_ptr != NULL)
  185905. #if defined(PNG_oFFs_SUPPORTED)
  185906. if (info_ptr->valid & PNG_INFO_oFFs)
  185907. {
  185908. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  185909. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  185910. return (0);
  185911. else return (info_ptr->x_offset);
  185912. }
  185913. #else
  185914. return (0);
  185915. #endif
  185916. return (0);
  185917. }
  185918. png_int_32 PNGAPI
  185919. png_get_y_offset_microns(png_structp png_ptr, png_infop info_ptr)
  185920. {
  185921. if (png_ptr != NULL && info_ptr != NULL)
  185922. #if defined(PNG_oFFs_SUPPORTED)
  185923. if (info_ptr->valid & PNG_INFO_oFFs)
  185924. {
  185925. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  185926. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  185927. return (0);
  185928. else return (info_ptr->y_offset);
  185929. }
  185930. #else
  185931. return (0);
  185932. #endif
  185933. return (0);
  185934. }
  185935. png_int_32 PNGAPI
  185936. png_get_x_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  185937. {
  185938. if (png_ptr != NULL && info_ptr != NULL)
  185939. #if defined(PNG_oFFs_SUPPORTED)
  185940. if (info_ptr->valid & PNG_INFO_oFFs)
  185941. {
  185942. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  185943. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  185944. return (0);
  185945. else return (info_ptr->x_offset);
  185946. }
  185947. #else
  185948. return (0);
  185949. #endif
  185950. return (0);
  185951. }
  185952. png_int_32 PNGAPI
  185953. png_get_y_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  185954. {
  185955. if (png_ptr != NULL && info_ptr != NULL)
  185956. #if defined(PNG_oFFs_SUPPORTED)
  185957. if (info_ptr->valid & PNG_INFO_oFFs)
  185958. {
  185959. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  185960. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  185961. return (0);
  185962. else return (info_ptr->y_offset);
  185963. }
  185964. #else
  185965. return (0);
  185966. #endif
  185967. return (0);
  185968. }
  185969. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  185970. png_uint_32 PNGAPI
  185971. png_get_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  185972. {
  185973. return ((png_uint_32)((float)png_get_pixels_per_meter(png_ptr, info_ptr)
  185974. *.0254 +.5));
  185975. }
  185976. png_uint_32 PNGAPI
  185977. png_get_x_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  185978. {
  185979. return ((png_uint_32)((float)png_get_x_pixels_per_meter(png_ptr, info_ptr)
  185980. *.0254 +.5));
  185981. }
  185982. png_uint_32 PNGAPI
  185983. png_get_y_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  185984. {
  185985. return ((png_uint_32)((float)png_get_y_pixels_per_meter(png_ptr, info_ptr)
  185986. *.0254 +.5));
  185987. }
  185988. float PNGAPI
  185989. png_get_x_offset_inches(png_structp png_ptr, png_infop info_ptr)
  185990. {
  185991. return ((float)png_get_x_offset_microns(png_ptr, info_ptr)
  185992. *.00003937);
  185993. }
  185994. float PNGAPI
  185995. png_get_y_offset_inches(png_structp png_ptr, png_infop info_ptr)
  185996. {
  185997. return ((float)png_get_y_offset_microns(png_ptr, info_ptr)
  185998. *.00003937);
  185999. }
  186000. #if defined(PNG_pHYs_SUPPORTED)
  186001. png_uint_32 PNGAPI
  186002. png_get_pHYs_dpi(png_structp png_ptr, png_infop info_ptr,
  186003. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  186004. {
  186005. png_uint_32 retval = 0;
  186006. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  186007. {
  186008. png_debug1(1, "in %s retrieval function\n", "pHYs");
  186009. if (res_x != NULL)
  186010. {
  186011. *res_x = info_ptr->x_pixels_per_unit;
  186012. retval |= PNG_INFO_pHYs;
  186013. }
  186014. if (res_y != NULL)
  186015. {
  186016. *res_y = info_ptr->y_pixels_per_unit;
  186017. retval |= PNG_INFO_pHYs;
  186018. }
  186019. if (unit_type != NULL)
  186020. {
  186021. *unit_type = (int)info_ptr->phys_unit_type;
  186022. retval |= PNG_INFO_pHYs;
  186023. if(*unit_type == 1)
  186024. {
  186025. if (res_x != NULL) *res_x = (png_uint_32)(*res_x * .0254 + .50);
  186026. if (res_y != NULL) *res_y = (png_uint_32)(*res_y * .0254 + .50);
  186027. }
  186028. }
  186029. }
  186030. return (retval);
  186031. }
  186032. #endif /* PNG_pHYs_SUPPORTED */
  186033. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  186034. /* png_get_channels really belongs in here, too, but it's been around longer */
  186035. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  186036. png_byte PNGAPI
  186037. png_get_channels(png_structp png_ptr, png_infop info_ptr)
  186038. {
  186039. if (png_ptr != NULL && info_ptr != NULL)
  186040. return(info_ptr->channels);
  186041. else
  186042. return (0);
  186043. }
  186044. png_bytep PNGAPI
  186045. png_get_signature(png_structp png_ptr, png_infop info_ptr)
  186046. {
  186047. if (png_ptr != NULL && info_ptr != NULL)
  186048. return(info_ptr->signature);
  186049. else
  186050. return (NULL);
  186051. }
  186052. #if defined(PNG_bKGD_SUPPORTED)
  186053. png_uint_32 PNGAPI
  186054. png_get_bKGD(png_structp png_ptr, png_infop info_ptr,
  186055. png_color_16p *background)
  186056. {
  186057. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD)
  186058. && background != NULL)
  186059. {
  186060. png_debug1(1, "in %s retrieval function\n", "bKGD");
  186061. *background = &(info_ptr->background);
  186062. return (PNG_INFO_bKGD);
  186063. }
  186064. return (0);
  186065. }
  186066. #endif
  186067. #if defined(PNG_cHRM_SUPPORTED)
  186068. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186069. png_uint_32 PNGAPI
  186070. png_get_cHRM(png_structp png_ptr, png_infop info_ptr,
  186071. double *white_x, double *white_y, double *red_x, double *red_y,
  186072. double *green_x, double *green_y, double *blue_x, double *blue_y)
  186073. {
  186074. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  186075. {
  186076. png_debug1(1, "in %s retrieval function\n", "cHRM");
  186077. if (white_x != NULL)
  186078. *white_x = (double)info_ptr->x_white;
  186079. if (white_y != NULL)
  186080. *white_y = (double)info_ptr->y_white;
  186081. if (red_x != NULL)
  186082. *red_x = (double)info_ptr->x_red;
  186083. if (red_y != NULL)
  186084. *red_y = (double)info_ptr->y_red;
  186085. if (green_x != NULL)
  186086. *green_x = (double)info_ptr->x_green;
  186087. if (green_y != NULL)
  186088. *green_y = (double)info_ptr->y_green;
  186089. if (blue_x != NULL)
  186090. *blue_x = (double)info_ptr->x_blue;
  186091. if (blue_y != NULL)
  186092. *blue_y = (double)info_ptr->y_blue;
  186093. return (PNG_INFO_cHRM);
  186094. }
  186095. return (0);
  186096. }
  186097. #endif
  186098. #ifdef PNG_FIXED_POINT_SUPPORTED
  186099. png_uint_32 PNGAPI
  186100. png_get_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  186101. png_fixed_point *white_x, png_fixed_point *white_y, png_fixed_point *red_x,
  186102. png_fixed_point *red_y, png_fixed_point *green_x, png_fixed_point *green_y,
  186103. png_fixed_point *blue_x, png_fixed_point *blue_y)
  186104. {
  186105. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  186106. {
  186107. png_debug1(1, "in %s retrieval function\n", "cHRM");
  186108. if (white_x != NULL)
  186109. *white_x = info_ptr->int_x_white;
  186110. if (white_y != NULL)
  186111. *white_y = info_ptr->int_y_white;
  186112. if (red_x != NULL)
  186113. *red_x = info_ptr->int_x_red;
  186114. if (red_y != NULL)
  186115. *red_y = info_ptr->int_y_red;
  186116. if (green_x != NULL)
  186117. *green_x = info_ptr->int_x_green;
  186118. if (green_y != NULL)
  186119. *green_y = info_ptr->int_y_green;
  186120. if (blue_x != NULL)
  186121. *blue_x = info_ptr->int_x_blue;
  186122. if (blue_y != NULL)
  186123. *blue_y = info_ptr->int_y_blue;
  186124. return (PNG_INFO_cHRM);
  186125. }
  186126. return (0);
  186127. }
  186128. #endif
  186129. #endif
  186130. #if defined(PNG_gAMA_SUPPORTED)
  186131. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186132. png_uint_32 PNGAPI
  186133. png_get_gAMA(png_structp png_ptr, png_infop info_ptr, double *file_gamma)
  186134. {
  186135. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  186136. && file_gamma != NULL)
  186137. {
  186138. png_debug1(1, "in %s retrieval function\n", "gAMA");
  186139. *file_gamma = (double)info_ptr->gamma;
  186140. return (PNG_INFO_gAMA);
  186141. }
  186142. return (0);
  186143. }
  186144. #endif
  186145. #ifdef PNG_FIXED_POINT_SUPPORTED
  186146. png_uint_32 PNGAPI
  186147. png_get_gAMA_fixed(png_structp png_ptr, png_infop info_ptr,
  186148. png_fixed_point *int_file_gamma)
  186149. {
  186150. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  186151. && int_file_gamma != NULL)
  186152. {
  186153. png_debug1(1, "in %s retrieval function\n", "gAMA");
  186154. *int_file_gamma = info_ptr->int_gamma;
  186155. return (PNG_INFO_gAMA);
  186156. }
  186157. return (0);
  186158. }
  186159. #endif
  186160. #endif
  186161. #if defined(PNG_sRGB_SUPPORTED)
  186162. png_uint_32 PNGAPI
  186163. png_get_sRGB(png_structp png_ptr, png_infop info_ptr, int *file_srgb_intent)
  186164. {
  186165. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB)
  186166. && file_srgb_intent != NULL)
  186167. {
  186168. png_debug1(1, "in %s retrieval function\n", "sRGB");
  186169. *file_srgb_intent = (int)info_ptr->srgb_intent;
  186170. return (PNG_INFO_sRGB);
  186171. }
  186172. return (0);
  186173. }
  186174. #endif
  186175. #if defined(PNG_iCCP_SUPPORTED)
  186176. png_uint_32 PNGAPI
  186177. png_get_iCCP(png_structp png_ptr, png_infop info_ptr,
  186178. png_charpp name, int *compression_type,
  186179. png_charpp profile, png_uint_32 *proflen)
  186180. {
  186181. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP)
  186182. && name != NULL && profile != NULL && proflen != NULL)
  186183. {
  186184. png_debug1(1, "in %s retrieval function\n", "iCCP");
  186185. *name = info_ptr->iccp_name;
  186186. *profile = info_ptr->iccp_profile;
  186187. /* compression_type is a dummy so the API won't have to change
  186188. if we introduce multiple compression types later. */
  186189. *proflen = (int)info_ptr->iccp_proflen;
  186190. *compression_type = (int)info_ptr->iccp_compression;
  186191. return (PNG_INFO_iCCP);
  186192. }
  186193. return (0);
  186194. }
  186195. #endif
  186196. #if defined(PNG_sPLT_SUPPORTED)
  186197. png_uint_32 PNGAPI
  186198. png_get_sPLT(png_structp png_ptr, png_infop info_ptr,
  186199. png_sPLT_tpp spalettes)
  186200. {
  186201. if (png_ptr != NULL && info_ptr != NULL && spalettes != NULL)
  186202. {
  186203. *spalettes = info_ptr->splt_palettes;
  186204. return ((png_uint_32)info_ptr->splt_palettes_num);
  186205. }
  186206. return (0);
  186207. }
  186208. #endif
  186209. #if defined(PNG_hIST_SUPPORTED)
  186210. png_uint_32 PNGAPI
  186211. png_get_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p *hist)
  186212. {
  186213. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST)
  186214. && hist != NULL)
  186215. {
  186216. png_debug1(1, "in %s retrieval function\n", "hIST");
  186217. *hist = info_ptr->hist;
  186218. return (PNG_INFO_hIST);
  186219. }
  186220. return (0);
  186221. }
  186222. #endif
  186223. png_uint_32 PNGAPI
  186224. png_get_IHDR(png_structp png_ptr, png_infop info_ptr,
  186225. png_uint_32 *width, png_uint_32 *height, int *bit_depth,
  186226. int *color_type, int *interlace_type, int *compression_type,
  186227. int *filter_type)
  186228. {
  186229. if (png_ptr != NULL && info_ptr != NULL && width != NULL && height != NULL &&
  186230. bit_depth != NULL && color_type != NULL)
  186231. {
  186232. png_debug1(1, "in %s retrieval function\n", "IHDR");
  186233. *width = info_ptr->width;
  186234. *height = info_ptr->height;
  186235. *bit_depth = info_ptr->bit_depth;
  186236. if (info_ptr->bit_depth < 1 || info_ptr->bit_depth > 16)
  186237. png_error(png_ptr, "Invalid bit depth");
  186238. *color_type = info_ptr->color_type;
  186239. if (info_ptr->color_type > 6)
  186240. png_error(png_ptr, "Invalid color type");
  186241. if (compression_type != NULL)
  186242. *compression_type = info_ptr->compression_type;
  186243. if (filter_type != NULL)
  186244. *filter_type = info_ptr->filter_type;
  186245. if (interlace_type != NULL)
  186246. *interlace_type = info_ptr->interlace_type;
  186247. /* check for potential overflow of rowbytes */
  186248. if (*width == 0 || *width > PNG_UINT_31_MAX)
  186249. png_error(png_ptr, "Invalid image width");
  186250. if (*height == 0 || *height > PNG_UINT_31_MAX)
  186251. png_error(png_ptr, "Invalid image height");
  186252. if (info_ptr->width > (PNG_UINT_32_MAX
  186253. >> 3) /* 8-byte RGBA pixels */
  186254. - 64 /* bigrowbuf hack */
  186255. - 1 /* filter byte */
  186256. - 7*8 /* rounding of width to multiple of 8 pixels */
  186257. - 8) /* extra max_pixel_depth pad */
  186258. {
  186259. png_warning(png_ptr,
  186260. "Width too large for libpng to process image data.");
  186261. }
  186262. return (1);
  186263. }
  186264. return (0);
  186265. }
  186266. #if defined(PNG_oFFs_SUPPORTED)
  186267. png_uint_32 PNGAPI
  186268. png_get_oFFs(png_structp png_ptr, png_infop info_ptr,
  186269. png_int_32 *offset_x, png_int_32 *offset_y, int *unit_type)
  186270. {
  186271. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs)
  186272. && offset_x != NULL && offset_y != NULL && unit_type != NULL)
  186273. {
  186274. png_debug1(1, "in %s retrieval function\n", "oFFs");
  186275. *offset_x = info_ptr->x_offset;
  186276. *offset_y = info_ptr->y_offset;
  186277. *unit_type = (int)info_ptr->offset_unit_type;
  186278. return (PNG_INFO_oFFs);
  186279. }
  186280. return (0);
  186281. }
  186282. #endif
  186283. #if defined(PNG_pCAL_SUPPORTED)
  186284. png_uint_32 PNGAPI
  186285. png_get_pCAL(png_structp png_ptr, png_infop info_ptr,
  186286. png_charp *purpose, png_int_32 *X0, png_int_32 *X1, int *type, int *nparams,
  186287. png_charp *units, png_charpp *params)
  186288. {
  186289. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL)
  186290. && purpose != NULL && X0 != NULL && X1 != NULL && type != NULL &&
  186291. nparams != NULL && units != NULL && params != NULL)
  186292. {
  186293. png_debug1(1, "in %s retrieval function\n", "pCAL");
  186294. *purpose = info_ptr->pcal_purpose;
  186295. *X0 = info_ptr->pcal_X0;
  186296. *X1 = info_ptr->pcal_X1;
  186297. *type = (int)info_ptr->pcal_type;
  186298. *nparams = (int)info_ptr->pcal_nparams;
  186299. *units = info_ptr->pcal_units;
  186300. *params = info_ptr->pcal_params;
  186301. return (PNG_INFO_pCAL);
  186302. }
  186303. return (0);
  186304. }
  186305. #endif
  186306. #if defined(PNG_sCAL_SUPPORTED)
  186307. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186308. png_uint_32 PNGAPI
  186309. png_get_sCAL(png_structp png_ptr, png_infop info_ptr,
  186310. int *unit, double *width, double *height)
  186311. {
  186312. if (png_ptr != NULL && info_ptr != NULL &&
  186313. (info_ptr->valid & PNG_INFO_sCAL))
  186314. {
  186315. *unit = info_ptr->scal_unit;
  186316. *width = info_ptr->scal_pixel_width;
  186317. *height = info_ptr->scal_pixel_height;
  186318. return (PNG_INFO_sCAL);
  186319. }
  186320. return(0);
  186321. }
  186322. #else
  186323. #ifdef PNG_FIXED_POINT_SUPPORTED
  186324. png_uint_32 PNGAPI
  186325. png_get_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  186326. int *unit, png_charpp width, png_charpp height)
  186327. {
  186328. if (png_ptr != NULL && info_ptr != NULL &&
  186329. (info_ptr->valid & PNG_INFO_sCAL))
  186330. {
  186331. *unit = info_ptr->scal_unit;
  186332. *width = info_ptr->scal_s_width;
  186333. *height = info_ptr->scal_s_height;
  186334. return (PNG_INFO_sCAL);
  186335. }
  186336. return(0);
  186337. }
  186338. #endif
  186339. #endif
  186340. #endif
  186341. #if defined(PNG_pHYs_SUPPORTED)
  186342. png_uint_32 PNGAPI
  186343. png_get_pHYs(png_structp png_ptr, png_infop info_ptr,
  186344. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  186345. {
  186346. png_uint_32 retval = 0;
  186347. if (png_ptr != NULL && info_ptr != NULL &&
  186348. (info_ptr->valid & PNG_INFO_pHYs))
  186349. {
  186350. png_debug1(1, "in %s retrieval function\n", "pHYs");
  186351. if (res_x != NULL)
  186352. {
  186353. *res_x = info_ptr->x_pixels_per_unit;
  186354. retval |= PNG_INFO_pHYs;
  186355. }
  186356. if (res_y != NULL)
  186357. {
  186358. *res_y = info_ptr->y_pixels_per_unit;
  186359. retval |= PNG_INFO_pHYs;
  186360. }
  186361. if (unit_type != NULL)
  186362. {
  186363. *unit_type = (int)info_ptr->phys_unit_type;
  186364. retval |= PNG_INFO_pHYs;
  186365. }
  186366. }
  186367. return (retval);
  186368. }
  186369. #endif
  186370. png_uint_32 PNGAPI
  186371. png_get_PLTE(png_structp png_ptr, png_infop info_ptr, png_colorp *palette,
  186372. int *num_palette)
  186373. {
  186374. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_PLTE)
  186375. && palette != NULL)
  186376. {
  186377. png_debug1(1, "in %s retrieval function\n", "PLTE");
  186378. *palette = info_ptr->palette;
  186379. *num_palette = info_ptr->num_palette;
  186380. png_debug1(3, "num_palette = %d\n", *num_palette);
  186381. return (PNG_INFO_PLTE);
  186382. }
  186383. return (0);
  186384. }
  186385. #if defined(PNG_sBIT_SUPPORTED)
  186386. png_uint_32 PNGAPI
  186387. png_get_sBIT(png_structp png_ptr, png_infop info_ptr, png_color_8p *sig_bit)
  186388. {
  186389. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT)
  186390. && sig_bit != NULL)
  186391. {
  186392. png_debug1(1, "in %s retrieval function\n", "sBIT");
  186393. *sig_bit = &(info_ptr->sig_bit);
  186394. return (PNG_INFO_sBIT);
  186395. }
  186396. return (0);
  186397. }
  186398. #endif
  186399. #if defined(PNG_TEXT_SUPPORTED)
  186400. png_uint_32 PNGAPI
  186401. png_get_text(png_structp png_ptr, png_infop info_ptr, png_textp *text_ptr,
  186402. int *num_text)
  186403. {
  186404. if (png_ptr != NULL && info_ptr != NULL && info_ptr->num_text > 0)
  186405. {
  186406. png_debug1(1, "in %s retrieval function\n",
  186407. (png_ptr->chunk_name[0] == '\0' ? "text"
  186408. : (png_const_charp)png_ptr->chunk_name));
  186409. if (text_ptr != NULL)
  186410. *text_ptr = info_ptr->text;
  186411. if (num_text != NULL)
  186412. *num_text = info_ptr->num_text;
  186413. return ((png_uint_32)info_ptr->num_text);
  186414. }
  186415. if (num_text != NULL)
  186416. *num_text = 0;
  186417. return(0);
  186418. }
  186419. #endif
  186420. #if defined(PNG_tIME_SUPPORTED)
  186421. png_uint_32 PNGAPI
  186422. png_get_tIME(png_structp png_ptr, png_infop info_ptr, png_timep *mod_time)
  186423. {
  186424. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME)
  186425. && mod_time != NULL)
  186426. {
  186427. png_debug1(1, "in %s retrieval function\n", "tIME");
  186428. *mod_time = &(info_ptr->mod_time);
  186429. return (PNG_INFO_tIME);
  186430. }
  186431. return (0);
  186432. }
  186433. #endif
  186434. #if defined(PNG_tRNS_SUPPORTED)
  186435. png_uint_32 PNGAPI
  186436. png_get_tRNS(png_structp png_ptr, png_infop info_ptr,
  186437. png_bytep *trans, int *num_trans, png_color_16p *trans_values)
  186438. {
  186439. png_uint_32 retval = 0;
  186440. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  186441. {
  186442. png_debug1(1, "in %s retrieval function\n", "tRNS");
  186443. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  186444. {
  186445. if (trans != NULL)
  186446. {
  186447. *trans = info_ptr->trans;
  186448. retval |= PNG_INFO_tRNS;
  186449. }
  186450. if (trans_values != NULL)
  186451. *trans_values = &(info_ptr->trans_values);
  186452. }
  186453. else /* if (info_ptr->color_type != PNG_COLOR_TYPE_PALETTE) */
  186454. {
  186455. if (trans_values != NULL)
  186456. {
  186457. *trans_values = &(info_ptr->trans_values);
  186458. retval |= PNG_INFO_tRNS;
  186459. }
  186460. if(trans != NULL)
  186461. *trans = NULL;
  186462. }
  186463. if(num_trans != NULL)
  186464. {
  186465. *num_trans = info_ptr->num_trans;
  186466. retval |= PNG_INFO_tRNS;
  186467. }
  186468. }
  186469. return (retval);
  186470. }
  186471. #endif
  186472. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  186473. png_uint_32 PNGAPI
  186474. png_get_unknown_chunks(png_structp png_ptr, png_infop info_ptr,
  186475. png_unknown_chunkpp unknowns)
  186476. {
  186477. if (png_ptr != NULL && info_ptr != NULL && unknowns != NULL)
  186478. {
  186479. *unknowns = info_ptr->unknown_chunks;
  186480. return ((png_uint_32)info_ptr->unknown_chunks_num);
  186481. }
  186482. return (0);
  186483. }
  186484. #endif
  186485. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  186486. png_byte PNGAPI
  186487. png_get_rgb_to_gray_status (png_structp png_ptr)
  186488. {
  186489. return (png_byte)(png_ptr? png_ptr->rgb_to_gray_status : 0);
  186490. }
  186491. #endif
  186492. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  186493. png_voidp PNGAPI
  186494. png_get_user_chunk_ptr(png_structp png_ptr)
  186495. {
  186496. return (png_ptr? png_ptr->user_chunk_ptr : NULL);
  186497. }
  186498. #endif
  186499. #ifdef PNG_WRITE_SUPPORTED
  186500. png_uint_32 PNGAPI
  186501. png_get_compression_buffer_size(png_structp png_ptr)
  186502. {
  186503. return (png_uint_32)(png_ptr? png_ptr->zbuf_size : 0L);
  186504. }
  186505. #endif
  186506. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  186507. #ifndef PNG_1_0_X
  186508. /* this function was added to libpng 1.2.0 and should exist by default */
  186509. png_uint_32 PNGAPI
  186510. png_get_asm_flags (png_structp png_ptr)
  186511. {
  186512. /* obsolete, to be removed from libpng-1.4.0 */
  186513. return (png_ptr? 0L: 0L);
  186514. }
  186515. /* this function was added to libpng 1.2.0 and should exist by default */
  186516. png_uint_32 PNGAPI
  186517. png_get_asm_flagmask (int flag_select)
  186518. {
  186519. /* obsolete, to be removed from libpng-1.4.0 */
  186520. flag_select=flag_select;
  186521. return 0L;
  186522. }
  186523. /* GRR: could add this: && defined(PNG_MMX_CODE_SUPPORTED) */
  186524. /* this function was added to libpng 1.2.0 */
  186525. png_uint_32 PNGAPI
  186526. png_get_mmx_flagmask (int flag_select, int *compilerID)
  186527. {
  186528. /* obsolete, to be removed from libpng-1.4.0 */
  186529. flag_select=flag_select;
  186530. *compilerID = -1; /* unknown (i.e., no asm/MMX code compiled) */
  186531. return 0L;
  186532. }
  186533. /* this function was added to libpng 1.2.0 */
  186534. png_byte PNGAPI
  186535. png_get_mmx_bitdepth_threshold (png_structp png_ptr)
  186536. {
  186537. /* obsolete, to be removed from libpng-1.4.0 */
  186538. return (png_ptr? 0: 0);
  186539. }
  186540. /* this function was added to libpng 1.2.0 */
  186541. png_uint_32 PNGAPI
  186542. png_get_mmx_rowbytes_threshold (png_structp png_ptr)
  186543. {
  186544. /* obsolete, to be removed from libpng-1.4.0 */
  186545. return (png_ptr? 0L: 0L);
  186546. }
  186547. #endif /* ?PNG_1_0_X */
  186548. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  186549. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  186550. /* these functions were added to libpng 1.2.6 */
  186551. png_uint_32 PNGAPI
  186552. png_get_user_width_max (png_structp png_ptr)
  186553. {
  186554. return (png_ptr? png_ptr->user_width_max : 0);
  186555. }
  186556. png_uint_32 PNGAPI
  186557. png_get_user_height_max (png_structp png_ptr)
  186558. {
  186559. return (png_ptr? png_ptr->user_height_max : 0);
  186560. }
  186561. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  186562. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  186563. /*** End of inlined file: pngget.c ***/
  186564. /*** Start of inlined file: pngmem.c ***/
  186565. /* pngmem.c - stub functions for memory allocation
  186566. *
  186567. * Last changed in libpng 1.2.13 November 13, 2006
  186568. * For conditions of distribution and use, see copyright notice in png.h
  186569. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  186570. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  186571. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  186572. *
  186573. * This file provides a location for all memory allocation. Users who
  186574. * need special memory handling are expected to supply replacement
  186575. * functions for png_malloc() and png_free(), and to use
  186576. * png_create_read_struct_2() and png_create_write_struct_2() to
  186577. * identify the replacement functions.
  186578. */
  186579. #define PNG_INTERNAL
  186580. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  186581. /* Borland DOS special memory handler */
  186582. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  186583. /* if you change this, be sure to change the one in png.h also */
  186584. /* Allocate memory for a png_struct. The malloc and memset can be replaced
  186585. by a single call to calloc() if this is thought to improve performance. */
  186586. png_voidp /* PRIVATE */
  186587. png_create_struct(int type)
  186588. {
  186589. #ifdef PNG_USER_MEM_SUPPORTED
  186590. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  186591. }
  186592. /* Alternate version of png_create_struct, for use with user-defined malloc. */
  186593. png_voidp /* PRIVATE */
  186594. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  186595. {
  186596. #endif /* PNG_USER_MEM_SUPPORTED */
  186597. png_size_t size;
  186598. png_voidp struct_ptr;
  186599. if (type == PNG_STRUCT_INFO)
  186600. size = png_sizeof(png_info);
  186601. else if (type == PNG_STRUCT_PNG)
  186602. size = png_sizeof(png_struct);
  186603. else
  186604. return (png_get_copyright(NULL));
  186605. #ifdef PNG_USER_MEM_SUPPORTED
  186606. if(malloc_fn != NULL)
  186607. {
  186608. png_struct dummy_struct;
  186609. png_structp png_ptr = &dummy_struct;
  186610. png_ptr->mem_ptr=mem_ptr;
  186611. struct_ptr = (*(malloc_fn))(png_ptr, (png_uint_32)size);
  186612. }
  186613. else
  186614. #endif /* PNG_USER_MEM_SUPPORTED */
  186615. struct_ptr = (png_voidp)farmalloc(size);
  186616. if (struct_ptr != NULL)
  186617. png_memset(struct_ptr, 0, size);
  186618. return (struct_ptr);
  186619. }
  186620. /* Free memory allocated by a png_create_struct() call */
  186621. void /* PRIVATE */
  186622. png_destroy_struct(png_voidp struct_ptr)
  186623. {
  186624. #ifdef PNG_USER_MEM_SUPPORTED
  186625. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  186626. }
  186627. /* Free memory allocated by a png_create_struct() call */
  186628. void /* PRIVATE */
  186629. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  186630. png_voidp mem_ptr)
  186631. {
  186632. #endif
  186633. if (struct_ptr != NULL)
  186634. {
  186635. #ifdef PNG_USER_MEM_SUPPORTED
  186636. if(free_fn != NULL)
  186637. {
  186638. png_struct dummy_struct;
  186639. png_structp png_ptr = &dummy_struct;
  186640. png_ptr->mem_ptr=mem_ptr;
  186641. (*(free_fn))(png_ptr, struct_ptr);
  186642. return;
  186643. }
  186644. #endif /* PNG_USER_MEM_SUPPORTED */
  186645. farfree (struct_ptr);
  186646. }
  186647. }
  186648. /* Allocate memory. For reasonable files, size should never exceed
  186649. * 64K. However, zlib may allocate more then 64K if you don't tell
  186650. * it not to. See zconf.h and png.h for more information. zlib does
  186651. * need to allocate exactly 64K, so whatever you call here must
  186652. * have the ability to do that.
  186653. *
  186654. * Borland seems to have a problem in DOS mode for exactly 64K.
  186655. * It gives you a segment with an offset of 8 (perhaps to store its
  186656. * memory stuff). zlib doesn't like this at all, so we have to
  186657. * detect and deal with it. This code should not be needed in
  186658. * Windows or OS/2 modes, and only in 16 bit mode. This code has
  186659. * been updated by Alexander Lehmann for version 0.89 to waste less
  186660. * memory.
  186661. *
  186662. * Note that we can't use png_size_t for the "size" declaration,
  186663. * since on some systems a png_size_t is a 16-bit quantity, and as a
  186664. * result, we would be truncating potentially larger memory requests
  186665. * (which should cause a fatal error) and introducing major problems.
  186666. */
  186667. png_voidp PNGAPI
  186668. png_malloc(png_structp png_ptr, png_uint_32 size)
  186669. {
  186670. png_voidp ret;
  186671. if (png_ptr == NULL || size == 0)
  186672. return (NULL);
  186673. #ifdef PNG_USER_MEM_SUPPORTED
  186674. if(png_ptr->malloc_fn != NULL)
  186675. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  186676. else
  186677. ret = (png_malloc_default(png_ptr, size));
  186678. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186679. png_error(png_ptr, "Out of memory!");
  186680. return (ret);
  186681. }
  186682. png_voidp PNGAPI
  186683. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  186684. {
  186685. png_voidp ret;
  186686. #endif /* PNG_USER_MEM_SUPPORTED */
  186687. if (png_ptr == NULL || size == 0)
  186688. return (NULL);
  186689. #ifdef PNG_MAX_MALLOC_64K
  186690. if (size > (png_uint_32)65536L)
  186691. {
  186692. png_warning(png_ptr, "Cannot Allocate > 64K");
  186693. ret = NULL;
  186694. }
  186695. else
  186696. #endif
  186697. if (size != (size_t)size)
  186698. ret = NULL;
  186699. else if (size == (png_uint_32)65536L)
  186700. {
  186701. if (png_ptr->offset_table == NULL)
  186702. {
  186703. /* try to see if we need to do any of this fancy stuff */
  186704. ret = farmalloc(size);
  186705. if (ret == NULL || ((png_size_t)ret & 0xffff))
  186706. {
  186707. int num_blocks;
  186708. png_uint_32 total_size;
  186709. png_bytep table;
  186710. int i;
  186711. png_byte huge * hptr;
  186712. if (ret != NULL)
  186713. {
  186714. farfree(ret);
  186715. ret = NULL;
  186716. }
  186717. if(png_ptr->zlib_window_bits > 14)
  186718. num_blocks = (int)(1 << (png_ptr->zlib_window_bits - 14));
  186719. else
  186720. num_blocks = 1;
  186721. if (png_ptr->zlib_mem_level >= 7)
  186722. num_blocks += (int)(1 << (png_ptr->zlib_mem_level - 7));
  186723. else
  186724. num_blocks++;
  186725. total_size = ((png_uint_32)65536L) * (png_uint_32)num_blocks+16;
  186726. table = farmalloc(total_size);
  186727. if (table == NULL)
  186728. {
  186729. #ifndef PNG_USER_MEM_SUPPORTED
  186730. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186731. png_error(png_ptr, "Out Of Memory."); /* Note "O" and "M" */
  186732. else
  186733. png_warning(png_ptr, "Out Of Memory.");
  186734. #endif
  186735. return (NULL);
  186736. }
  186737. if ((png_size_t)table & 0xfff0)
  186738. {
  186739. #ifndef PNG_USER_MEM_SUPPORTED
  186740. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186741. png_error(png_ptr,
  186742. "Farmalloc didn't return normalized pointer");
  186743. else
  186744. png_warning(png_ptr,
  186745. "Farmalloc didn't return normalized pointer");
  186746. #endif
  186747. return (NULL);
  186748. }
  186749. png_ptr->offset_table = table;
  186750. png_ptr->offset_table_ptr = farmalloc(num_blocks *
  186751. png_sizeof (png_bytep));
  186752. if (png_ptr->offset_table_ptr == NULL)
  186753. {
  186754. #ifndef PNG_USER_MEM_SUPPORTED
  186755. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186756. png_error(png_ptr, "Out Of memory."); /* Note "O" and "M" */
  186757. else
  186758. png_warning(png_ptr, "Out Of memory.");
  186759. #endif
  186760. return (NULL);
  186761. }
  186762. hptr = (png_byte huge *)table;
  186763. if ((png_size_t)hptr & 0xf)
  186764. {
  186765. hptr = (png_byte huge *)((long)(hptr) & 0xfffffff0L);
  186766. hptr = hptr + 16L; /* "hptr += 16L" fails on Turbo C++ 3.0 */
  186767. }
  186768. for (i = 0; i < num_blocks; i++)
  186769. {
  186770. png_ptr->offset_table_ptr[i] = (png_bytep)hptr;
  186771. hptr = hptr + (png_uint_32)65536L; /* "+=" fails on TC++3.0 */
  186772. }
  186773. png_ptr->offset_table_number = num_blocks;
  186774. png_ptr->offset_table_count = 0;
  186775. png_ptr->offset_table_count_free = 0;
  186776. }
  186777. }
  186778. if (png_ptr->offset_table_count >= png_ptr->offset_table_number)
  186779. {
  186780. #ifndef PNG_USER_MEM_SUPPORTED
  186781. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186782. png_error(png_ptr, "Out of Memory."); /* Note "o" and "M" */
  186783. else
  186784. png_warning(png_ptr, "Out of Memory.");
  186785. #endif
  186786. return (NULL);
  186787. }
  186788. ret = png_ptr->offset_table_ptr[png_ptr->offset_table_count++];
  186789. }
  186790. else
  186791. ret = farmalloc(size);
  186792. #ifndef PNG_USER_MEM_SUPPORTED
  186793. if (ret == NULL)
  186794. {
  186795. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186796. png_error(png_ptr, "Out of memory."); /* Note "o" and "m" */
  186797. else
  186798. png_warning(png_ptr, "Out of memory."); /* Note "o" and "m" */
  186799. }
  186800. #endif
  186801. return (ret);
  186802. }
  186803. /* free a pointer allocated by png_malloc(). In the default
  186804. configuration, png_ptr is not used, but is passed in case it
  186805. is needed. If ptr is NULL, return without taking any action. */
  186806. void PNGAPI
  186807. png_free(png_structp png_ptr, png_voidp ptr)
  186808. {
  186809. if (png_ptr == NULL || ptr == NULL)
  186810. return;
  186811. #ifdef PNG_USER_MEM_SUPPORTED
  186812. if (png_ptr->free_fn != NULL)
  186813. {
  186814. (*(png_ptr->free_fn))(png_ptr, ptr);
  186815. return;
  186816. }
  186817. else png_free_default(png_ptr, ptr);
  186818. }
  186819. void PNGAPI
  186820. png_free_default(png_structp png_ptr, png_voidp ptr)
  186821. {
  186822. #endif /* PNG_USER_MEM_SUPPORTED */
  186823. if(png_ptr == NULL) return;
  186824. if (png_ptr->offset_table != NULL)
  186825. {
  186826. int i;
  186827. for (i = 0; i < png_ptr->offset_table_count; i++)
  186828. {
  186829. if (ptr == png_ptr->offset_table_ptr[i])
  186830. {
  186831. ptr = NULL;
  186832. png_ptr->offset_table_count_free++;
  186833. break;
  186834. }
  186835. }
  186836. if (png_ptr->offset_table_count_free == png_ptr->offset_table_count)
  186837. {
  186838. farfree(png_ptr->offset_table);
  186839. farfree(png_ptr->offset_table_ptr);
  186840. png_ptr->offset_table = NULL;
  186841. png_ptr->offset_table_ptr = NULL;
  186842. }
  186843. }
  186844. if (ptr != NULL)
  186845. {
  186846. farfree(ptr);
  186847. }
  186848. }
  186849. #else /* Not the Borland DOS special memory handler */
  186850. /* Allocate memory for a png_struct or a png_info. The malloc and
  186851. memset can be replaced by a single call to calloc() if this is thought
  186852. to improve performance noticably. */
  186853. png_voidp /* PRIVATE */
  186854. png_create_struct(int type)
  186855. {
  186856. #ifdef PNG_USER_MEM_SUPPORTED
  186857. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  186858. }
  186859. /* Allocate memory for a png_struct or a png_info. The malloc and
  186860. memset can be replaced by a single call to calloc() if this is thought
  186861. to improve performance noticably. */
  186862. png_voidp /* PRIVATE */
  186863. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  186864. {
  186865. #endif /* PNG_USER_MEM_SUPPORTED */
  186866. png_size_t size;
  186867. png_voidp struct_ptr;
  186868. if (type == PNG_STRUCT_INFO)
  186869. size = png_sizeof(png_info);
  186870. else if (type == PNG_STRUCT_PNG)
  186871. size = png_sizeof(png_struct);
  186872. else
  186873. return (NULL);
  186874. #ifdef PNG_USER_MEM_SUPPORTED
  186875. if(malloc_fn != NULL)
  186876. {
  186877. png_struct dummy_struct;
  186878. png_structp png_ptr = &dummy_struct;
  186879. png_ptr->mem_ptr=mem_ptr;
  186880. struct_ptr = (*(malloc_fn))(png_ptr, size);
  186881. if (struct_ptr != NULL)
  186882. png_memset(struct_ptr, 0, size);
  186883. return (struct_ptr);
  186884. }
  186885. #endif /* PNG_USER_MEM_SUPPORTED */
  186886. #if defined(__TURBOC__) && !defined(__FLAT__)
  186887. struct_ptr = (png_voidp)farmalloc(size);
  186888. #else
  186889. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186890. struct_ptr = (png_voidp)halloc(size,1);
  186891. # else
  186892. struct_ptr = (png_voidp)malloc(size);
  186893. # endif
  186894. #endif
  186895. if (struct_ptr != NULL)
  186896. png_memset(struct_ptr, 0, size);
  186897. return (struct_ptr);
  186898. }
  186899. /* Free memory allocated by a png_create_struct() call */
  186900. void /* PRIVATE */
  186901. png_destroy_struct(png_voidp struct_ptr)
  186902. {
  186903. #ifdef PNG_USER_MEM_SUPPORTED
  186904. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  186905. }
  186906. /* Free memory allocated by a png_create_struct() call */
  186907. void /* PRIVATE */
  186908. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  186909. png_voidp mem_ptr)
  186910. {
  186911. #endif /* PNG_USER_MEM_SUPPORTED */
  186912. if (struct_ptr != NULL)
  186913. {
  186914. #ifdef PNG_USER_MEM_SUPPORTED
  186915. if(free_fn != NULL)
  186916. {
  186917. png_struct dummy_struct;
  186918. png_structp png_ptr = &dummy_struct;
  186919. png_ptr->mem_ptr=mem_ptr;
  186920. (*(free_fn))(png_ptr, struct_ptr);
  186921. return;
  186922. }
  186923. #endif /* PNG_USER_MEM_SUPPORTED */
  186924. #if defined(__TURBOC__) && !defined(__FLAT__)
  186925. farfree(struct_ptr);
  186926. #else
  186927. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186928. hfree(struct_ptr);
  186929. # else
  186930. free(struct_ptr);
  186931. # endif
  186932. #endif
  186933. }
  186934. }
  186935. /* Allocate memory. For reasonable files, size should never exceed
  186936. 64K. However, zlib may allocate more then 64K if you don't tell
  186937. it not to. See zconf.h and png.h for more information. zlib does
  186938. need to allocate exactly 64K, so whatever you call here must
  186939. have the ability to do that. */
  186940. png_voidp PNGAPI
  186941. png_malloc(png_structp png_ptr, png_uint_32 size)
  186942. {
  186943. png_voidp ret;
  186944. #ifdef PNG_USER_MEM_SUPPORTED
  186945. if (png_ptr == NULL || size == 0)
  186946. return (NULL);
  186947. if(png_ptr->malloc_fn != NULL)
  186948. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  186949. else
  186950. ret = (png_malloc_default(png_ptr, size));
  186951. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186952. png_error(png_ptr, "Out of Memory!");
  186953. return (ret);
  186954. }
  186955. png_voidp PNGAPI
  186956. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  186957. {
  186958. png_voidp ret;
  186959. #endif /* PNG_USER_MEM_SUPPORTED */
  186960. if (png_ptr == NULL || size == 0)
  186961. return (NULL);
  186962. #ifdef PNG_MAX_MALLOC_64K
  186963. if (size > (png_uint_32)65536L)
  186964. {
  186965. #ifndef PNG_USER_MEM_SUPPORTED
  186966. if(png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186967. png_error(png_ptr, "Cannot Allocate > 64K");
  186968. else
  186969. #endif
  186970. return NULL;
  186971. }
  186972. #endif
  186973. /* Check for overflow */
  186974. #if defined(__TURBOC__) && !defined(__FLAT__)
  186975. if (size != (unsigned long)size)
  186976. ret = NULL;
  186977. else
  186978. ret = farmalloc(size);
  186979. #else
  186980. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186981. if (size != (unsigned long)size)
  186982. ret = NULL;
  186983. else
  186984. ret = halloc(size, 1);
  186985. # else
  186986. if (size != (size_t)size)
  186987. ret = NULL;
  186988. else
  186989. ret = malloc((size_t)size);
  186990. # endif
  186991. #endif
  186992. #ifndef PNG_USER_MEM_SUPPORTED
  186993. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186994. png_error(png_ptr, "Out of Memory");
  186995. #endif
  186996. return (ret);
  186997. }
  186998. /* Free a pointer allocated by png_malloc(). If ptr is NULL, return
  186999. without taking any action. */
  187000. void PNGAPI
  187001. png_free(png_structp png_ptr, png_voidp ptr)
  187002. {
  187003. if (png_ptr == NULL || ptr == NULL)
  187004. return;
  187005. #ifdef PNG_USER_MEM_SUPPORTED
  187006. if (png_ptr->free_fn != NULL)
  187007. {
  187008. (*(png_ptr->free_fn))(png_ptr, ptr);
  187009. return;
  187010. }
  187011. else png_free_default(png_ptr, ptr);
  187012. }
  187013. void PNGAPI
  187014. png_free_default(png_structp png_ptr, png_voidp ptr)
  187015. {
  187016. if (png_ptr == NULL || ptr == NULL)
  187017. return;
  187018. #endif /* PNG_USER_MEM_SUPPORTED */
  187019. #if defined(__TURBOC__) && !defined(__FLAT__)
  187020. farfree(ptr);
  187021. #else
  187022. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  187023. hfree(ptr);
  187024. # else
  187025. free(ptr);
  187026. # endif
  187027. #endif
  187028. }
  187029. #endif /* Not Borland DOS special memory handler */
  187030. #if defined(PNG_1_0_X)
  187031. # define png_malloc_warn png_malloc
  187032. #else
  187033. /* This function was added at libpng version 1.2.3. The png_malloc_warn()
  187034. * function will set up png_malloc() to issue a png_warning and return NULL
  187035. * instead of issuing a png_error, if it fails to allocate the requested
  187036. * memory.
  187037. */
  187038. png_voidp PNGAPI
  187039. png_malloc_warn(png_structp png_ptr, png_uint_32 size)
  187040. {
  187041. png_voidp ptr;
  187042. png_uint_32 save_flags;
  187043. if(png_ptr == NULL) return (NULL);
  187044. save_flags=png_ptr->flags;
  187045. png_ptr->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  187046. ptr = (png_voidp)png_malloc((png_structp)png_ptr, size);
  187047. png_ptr->flags=save_flags;
  187048. return(ptr);
  187049. }
  187050. #endif
  187051. png_voidp PNGAPI
  187052. png_memcpy_check (png_structp png_ptr, png_voidp s1, png_voidp s2,
  187053. png_uint_32 length)
  187054. {
  187055. png_size_t size;
  187056. size = (png_size_t)length;
  187057. if ((png_uint_32)size != length)
  187058. png_error(png_ptr,"Overflow in png_memcpy_check.");
  187059. return(png_memcpy (s1, s2, size));
  187060. }
  187061. png_voidp PNGAPI
  187062. png_memset_check (png_structp png_ptr, png_voidp s1, int value,
  187063. png_uint_32 length)
  187064. {
  187065. png_size_t size;
  187066. size = (png_size_t)length;
  187067. if ((png_uint_32)size != length)
  187068. png_error(png_ptr,"Overflow in png_memset_check.");
  187069. return (png_memset (s1, value, size));
  187070. }
  187071. #ifdef PNG_USER_MEM_SUPPORTED
  187072. /* This function is called when the application wants to use another method
  187073. * of allocating and freeing memory.
  187074. */
  187075. void PNGAPI
  187076. png_set_mem_fn(png_structp png_ptr, png_voidp mem_ptr, png_malloc_ptr
  187077. malloc_fn, png_free_ptr free_fn)
  187078. {
  187079. if(png_ptr != NULL) {
  187080. png_ptr->mem_ptr = mem_ptr;
  187081. png_ptr->malloc_fn = malloc_fn;
  187082. png_ptr->free_fn = free_fn;
  187083. }
  187084. }
  187085. /* This function returns a pointer to the mem_ptr associated with the user
  187086. * functions. The application should free any memory associated with this
  187087. * pointer before png_write_destroy and png_read_destroy are called.
  187088. */
  187089. png_voidp PNGAPI
  187090. png_get_mem_ptr(png_structp png_ptr)
  187091. {
  187092. if(png_ptr == NULL) return (NULL);
  187093. return ((png_voidp)png_ptr->mem_ptr);
  187094. }
  187095. #endif /* PNG_USER_MEM_SUPPORTED */
  187096. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  187097. /*** End of inlined file: pngmem.c ***/
  187098. /*** Start of inlined file: pngread.c ***/
  187099. /* pngread.c - read a PNG file
  187100. *
  187101. * Last changed in libpng 1.2.20 September 7, 2007
  187102. * For conditions of distribution and use, see copyright notice in png.h
  187103. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  187104. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  187105. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  187106. *
  187107. * This file contains routines that an application calls directly to
  187108. * read a PNG file or stream.
  187109. */
  187110. #define PNG_INTERNAL
  187111. #if defined(PNG_READ_SUPPORTED)
  187112. /* Create a PNG structure for reading, and allocate any memory needed. */
  187113. png_structp PNGAPI
  187114. png_create_read_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  187115. png_error_ptr error_fn, png_error_ptr warn_fn)
  187116. {
  187117. #ifdef PNG_USER_MEM_SUPPORTED
  187118. return (png_create_read_struct_2(user_png_ver, error_ptr, error_fn,
  187119. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  187120. }
  187121. /* Alternate create PNG structure for reading, and allocate any memory needed. */
  187122. png_structp PNGAPI
  187123. png_create_read_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  187124. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  187125. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  187126. {
  187127. #endif /* PNG_USER_MEM_SUPPORTED */
  187128. png_structp png_ptr;
  187129. #ifdef PNG_SETJMP_SUPPORTED
  187130. #ifdef USE_FAR_KEYWORD
  187131. jmp_buf jmpbuf;
  187132. #endif
  187133. #endif
  187134. int i;
  187135. png_debug(1, "in png_create_read_struct\n");
  187136. #ifdef PNG_USER_MEM_SUPPORTED
  187137. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  187138. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  187139. #else
  187140. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  187141. #endif
  187142. if (png_ptr == NULL)
  187143. return (NULL);
  187144. /* added at libpng-1.2.6 */
  187145. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  187146. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  187147. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  187148. #endif
  187149. #ifdef PNG_SETJMP_SUPPORTED
  187150. #ifdef USE_FAR_KEYWORD
  187151. if (setjmp(jmpbuf))
  187152. #else
  187153. if (setjmp(png_ptr->jmpbuf))
  187154. #endif
  187155. {
  187156. png_free(png_ptr, png_ptr->zbuf);
  187157. png_ptr->zbuf=NULL;
  187158. #ifdef PNG_USER_MEM_SUPPORTED
  187159. png_destroy_struct_2((png_voidp)png_ptr,
  187160. (png_free_ptr)free_fn, (png_voidp)mem_ptr);
  187161. #else
  187162. png_destroy_struct((png_voidp)png_ptr);
  187163. #endif
  187164. return (NULL);
  187165. }
  187166. #ifdef USE_FAR_KEYWORD
  187167. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  187168. #endif
  187169. #endif
  187170. #ifdef PNG_USER_MEM_SUPPORTED
  187171. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  187172. #endif
  187173. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  187174. i=0;
  187175. do
  187176. {
  187177. if(user_png_ver[i] != png_libpng_ver[i])
  187178. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  187179. } while (png_libpng_ver[i++]);
  187180. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  187181. {
  187182. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  187183. * we must recompile any applications that use any older library version.
  187184. * For versions after libpng 1.0, we will be compatible, so we need
  187185. * only check the first digit.
  187186. */
  187187. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  187188. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  187189. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  187190. {
  187191. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  187192. char msg[80];
  187193. if (user_png_ver)
  187194. {
  187195. png_snprintf(msg, 80,
  187196. "Application was compiled with png.h from libpng-%.20s",
  187197. user_png_ver);
  187198. png_warning(png_ptr, msg);
  187199. }
  187200. png_snprintf(msg, 80,
  187201. "Application is running with png.c from libpng-%.20s",
  187202. png_libpng_ver);
  187203. png_warning(png_ptr, msg);
  187204. #endif
  187205. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  187206. png_ptr->flags=0;
  187207. #endif
  187208. png_error(png_ptr,
  187209. "Incompatible libpng version in application and library");
  187210. }
  187211. }
  187212. /* initialize zbuf - compression buffer */
  187213. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  187214. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  187215. (png_uint_32)png_ptr->zbuf_size);
  187216. png_ptr->zstream.zalloc = png_zalloc;
  187217. png_ptr->zstream.zfree = png_zfree;
  187218. png_ptr->zstream.opaque = (voidpf)png_ptr;
  187219. switch (inflateInit(&png_ptr->zstream))
  187220. {
  187221. case Z_OK: /* Do nothing */ break;
  187222. case Z_MEM_ERROR:
  187223. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory error"); break;
  187224. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version error"); break;
  187225. default: png_error(png_ptr, "Unknown zlib error");
  187226. }
  187227. png_ptr->zstream.next_out = png_ptr->zbuf;
  187228. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  187229. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  187230. #ifdef PNG_SETJMP_SUPPORTED
  187231. /* Applications that neglect to set up their own setjmp() and then encounter
  187232. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  187233. abort instead of returning. */
  187234. #ifdef USE_FAR_KEYWORD
  187235. if (setjmp(jmpbuf))
  187236. PNG_ABORT();
  187237. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  187238. #else
  187239. if (setjmp(png_ptr->jmpbuf))
  187240. PNG_ABORT();
  187241. #endif
  187242. #endif
  187243. return (png_ptr);
  187244. }
  187245. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  187246. /* Initialize PNG structure for reading, and allocate any memory needed.
  187247. This interface is deprecated in favour of the png_create_read_struct(),
  187248. and it will disappear as of libpng-1.3.0. */
  187249. #undef png_read_init
  187250. void PNGAPI
  187251. png_read_init(png_structp png_ptr)
  187252. {
  187253. /* We only come here via pre-1.0.7-compiled applications */
  187254. png_read_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  187255. }
  187256. void PNGAPI
  187257. png_read_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  187258. png_size_t png_struct_size, png_size_t png_info_size)
  187259. {
  187260. /* We only come here via pre-1.0.12-compiled applications */
  187261. if(png_ptr == NULL) return;
  187262. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  187263. if(png_sizeof(png_struct) > png_struct_size ||
  187264. png_sizeof(png_info) > png_info_size)
  187265. {
  187266. char msg[80];
  187267. png_ptr->warning_fn=NULL;
  187268. if (user_png_ver)
  187269. {
  187270. png_snprintf(msg, 80,
  187271. "Application was compiled with png.h from libpng-%.20s",
  187272. user_png_ver);
  187273. png_warning(png_ptr, msg);
  187274. }
  187275. png_snprintf(msg, 80,
  187276. "Application is running with png.c from libpng-%.20s",
  187277. png_libpng_ver);
  187278. png_warning(png_ptr, msg);
  187279. }
  187280. #endif
  187281. if(png_sizeof(png_struct) > png_struct_size)
  187282. {
  187283. png_ptr->error_fn=NULL;
  187284. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  187285. png_ptr->flags=0;
  187286. #endif
  187287. png_error(png_ptr,
  187288. "The png struct allocated by the application for reading is too small.");
  187289. }
  187290. if(png_sizeof(png_info) > png_info_size)
  187291. {
  187292. png_ptr->error_fn=NULL;
  187293. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  187294. png_ptr->flags=0;
  187295. #endif
  187296. png_error(png_ptr,
  187297. "The info struct allocated by application for reading is too small.");
  187298. }
  187299. png_read_init_3(&png_ptr, user_png_ver, png_struct_size);
  187300. }
  187301. #endif /* PNG_1_0_X || PNG_1_2_X */
  187302. void PNGAPI
  187303. png_read_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  187304. png_size_t png_struct_size)
  187305. {
  187306. #ifdef PNG_SETJMP_SUPPORTED
  187307. jmp_buf tmp_jmp; /* to save current jump buffer */
  187308. #endif
  187309. int i=0;
  187310. png_structp png_ptr=*ptr_ptr;
  187311. if(png_ptr == NULL) return;
  187312. do
  187313. {
  187314. if(user_png_ver[i] != png_libpng_ver[i])
  187315. {
  187316. #ifdef PNG_LEGACY_SUPPORTED
  187317. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  187318. #else
  187319. png_ptr->warning_fn=NULL;
  187320. png_warning(png_ptr,
  187321. "Application uses deprecated png_read_init() and should be recompiled.");
  187322. break;
  187323. #endif
  187324. }
  187325. } while (png_libpng_ver[i++]);
  187326. png_debug(1, "in png_read_init_3\n");
  187327. #ifdef PNG_SETJMP_SUPPORTED
  187328. /* save jump buffer and error functions */
  187329. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  187330. #endif
  187331. if(png_sizeof(png_struct) > png_struct_size)
  187332. {
  187333. png_destroy_struct(png_ptr);
  187334. *ptr_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  187335. png_ptr = *ptr_ptr;
  187336. }
  187337. /* reset all variables to 0 */
  187338. png_memset(png_ptr, 0, png_sizeof (png_struct));
  187339. #ifdef PNG_SETJMP_SUPPORTED
  187340. /* restore jump buffer */
  187341. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  187342. #endif
  187343. /* added at libpng-1.2.6 */
  187344. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  187345. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  187346. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  187347. #endif
  187348. /* initialize zbuf - compression buffer */
  187349. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  187350. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  187351. (png_uint_32)png_ptr->zbuf_size);
  187352. png_ptr->zstream.zalloc = png_zalloc;
  187353. png_ptr->zstream.zfree = png_zfree;
  187354. png_ptr->zstream.opaque = (voidpf)png_ptr;
  187355. switch (inflateInit(&png_ptr->zstream))
  187356. {
  187357. case Z_OK: /* Do nothing */ break;
  187358. case Z_MEM_ERROR:
  187359. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory"); break;
  187360. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version"); break;
  187361. default: png_error(png_ptr, "Unknown zlib error");
  187362. }
  187363. png_ptr->zstream.next_out = png_ptr->zbuf;
  187364. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  187365. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  187366. }
  187367. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187368. /* Read the information before the actual image data. This has been
  187369. * changed in v0.90 to allow reading a file that already has the magic
  187370. * bytes read from the stream. You can tell libpng how many bytes have
  187371. * been read from the beginning of the stream (up to the maximum of 8)
  187372. * via png_set_sig_bytes(), and we will only check the remaining bytes
  187373. * here. The application can then have access to the signature bytes we
  187374. * read if it is determined that this isn't a valid PNG file.
  187375. */
  187376. void PNGAPI
  187377. png_read_info(png_structp png_ptr, png_infop info_ptr)
  187378. {
  187379. if(png_ptr == NULL) return;
  187380. png_debug(1, "in png_read_info\n");
  187381. /* If we haven't checked all of the PNG signature bytes, do so now. */
  187382. if (png_ptr->sig_bytes < 8)
  187383. {
  187384. png_size_t num_checked = png_ptr->sig_bytes,
  187385. num_to_check = 8 - num_checked;
  187386. png_read_data(png_ptr, &(info_ptr->signature[num_checked]), num_to_check);
  187387. png_ptr->sig_bytes = 8;
  187388. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  187389. {
  187390. if (num_checked < 4 &&
  187391. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  187392. png_error(png_ptr, "Not a PNG file");
  187393. else
  187394. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  187395. }
  187396. if (num_checked < 3)
  187397. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  187398. }
  187399. for(;;)
  187400. {
  187401. #ifdef PNG_USE_LOCAL_ARRAYS
  187402. PNG_CONST PNG_IHDR;
  187403. PNG_CONST PNG_IDAT;
  187404. PNG_CONST PNG_IEND;
  187405. PNG_CONST PNG_PLTE;
  187406. #if defined(PNG_READ_bKGD_SUPPORTED)
  187407. PNG_CONST PNG_bKGD;
  187408. #endif
  187409. #if defined(PNG_READ_cHRM_SUPPORTED)
  187410. PNG_CONST PNG_cHRM;
  187411. #endif
  187412. #if defined(PNG_READ_gAMA_SUPPORTED)
  187413. PNG_CONST PNG_gAMA;
  187414. #endif
  187415. #if defined(PNG_READ_hIST_SUPPORTED)
  187416. PNG_CONST PNG_hIST;
  187417. #endif
  187418. #if defined(PNG_READ_iCCP_SUPPORTED)
  187419. PNG_CONST PNG_iCCP;
  187420. #endif
  187421. #if defined(PNG_READ_iTXt_SUPPORTED)
  187422. PNG_CONST PNG_iTXt;
  187423. #endif
  187424. #if defined(PNG_READ_oFFs_SUPPORTED)
  187425. PNG_CONST PNG_oFFs;
  187426. #endif
  187427. #if defined(PNG_READ_pCAL_SUPPORTED)
  187428. PNG_CONST PNG_pCAL;
  187429. #endif
  187430. #if defined(PNG_READ_pHYs_SUPPORTED)
  187431. PNG_CONST PNG_pHYs;
  187432. #endif
  187433. #if defined(PNG_READ_sBIT_SUPPORTED)
  187434. PNG_CONST PNG_sBIT;
  187435. #endif
  187436. #if defined(PNG_READ_sCAL_SUPPORTED)
  187437. PNG_CONST PNG_sCAL;
  187438. #endif
  187439. #if defined(PNG_READ_sPLT_SUPPORTED)
  187440. PNG_CONST PNG_sPLT;
  187441. #endif
  187442. #if defined(PNG_READ_sRGB_SUPPORTED)
  187443. PNG_CONST PNG_sRGB;
  187444. #endif
  187445. #if defined(PNG_READ_tEXt_SUPPORTED)
  187446. PNG_CONST PNG_tEXt;
  187447. #endif
  187448. #if defined(PNG_READ_tIME_SUPPORTED)
  187449. PNG_CONST PNG_tIME;
  187450. #endif
  187451. #if defined(PNG_READ_tRNS_SUPPORTED)
  187452. PNG_CONST PNG_tRNS;
  187453. #endif
  187454. #if defined(PNG_READ_zTXt_SUPPORTED)
  187455. PNG_CONST PNG_zTXt;
  187456. #endif
  187457. #endif /* PNG_USE_LOCAL_ARRAYS */
  187458. png_byte chunk_length[4];
  187459. png_uint_32 length;
  187460. png_read_data(png_ptr, chunk_length, 4);
  187461. length = png_get_uint_31(png_ptr,chunk_length);
  187462. png_reset_crc(png_ptr);
  187463. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187464. png_debug2(0, "Reading %s chunk, length=%lu.\n", png_ptr->chunk_name,
  187465. length);
  187466. /* This should be a binary subdivision search or a hash for
  187467. * matching the chunk name rather than a linear search.
  187468. */
  187469. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187470. if(png_ptr->mode & PNG_AFTER_IDAT)
  187471. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  187472. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  187473. png_handle_IHDR(png_ptr, info_ptr, length);
  187474. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  187475. png_handle_IEND(png_ptr, info_ptr, length);
  187476. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  187477. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  187478. {
  187479. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187480. png_ptr->mode |= PNG_HAVE_IDAT;
  187481. png_handle_unknown(png_ptr, info_ptr, length);
  187482. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187483. png_ptr->mode |= PNG_HAVE_PLTE;
  187484. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187485. {
  187486. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187487. png_error(png_ptr, "Missing IHDR before IDAT");
  187488. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  187489. !(png_ptr->mode & PNG_HAVE_PLTE))
  187490. png_error(png_ptr, "Missing PLTE before IDAT");
  187491. break;
  187492. }
  187493. }
  187494. #endif
  187495. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187496. png_handle_PLTE(png_ptr, info_ptr, length);
  187497. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187498. {
  187499. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187500. png_error(png_ptr, "Missing IHDR before IDAT");
  187501. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  187502. !(png_ptr->mode & PNG_HAVE_PLTE))
  187503. png_error(png_ptr, "Missing PLTE before IDAT");
  187504. png_ptr->idat_size = length;
  187505. png_ptr->mode |= PNG_HAVE_IDAT;
  187506. break;
  187507. }
  187508. #if defined(PNG_READ_bKGD_SUPPORTED)
  187509. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  187510. png_handle_bKGD(png_ptr, info_ptr, length);
  187511. #endif
  187512. #if defined(PNG_READ_cHRM_SUPPORTED)
  187513. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  187514. png_handle_cHRM(png_ptr, info_ptr, length);
  187515. #endif
  187516. #if defined(PNG_READ_gAMA_SUPPORTED)
  187517. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  187518. png_handle_gAMA(png_ptr, info_ptr, length);
  187519. #endif
  187520. #if defined(PNG_READ_hIST_SUPPORTED)
  187521. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  187522. png_handle_hIST(png_ptr, info_ptr, length);
  187523. #endif
  187524. #if defined(PNG_READ_oFFs_SUPPORTED)
  187525. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  187526. png_handle_oFFs(png_ptr, info_ptr, length);
  187527. #endif
  187528. #if defined(PNG_READ_pCAL_SUPPORTED)
  187529. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  187530. png_handle_pCAL(png_ptr, info_ptr, length);
  187531. #endif
  187532. #if defined(PNG_READ_sCAL_SUPPORTED)
  187533. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  187534. png_handle_sCAL(png_ptr, info_ptr, length);
  187535. #endif
  187536. #if defined(PNG_READ_pHYs_SUPPORTED)
  187537. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  187538. png_handle_pHYs(png_ptr, info_ptr, length);
  187539. #endif
  187540. #if defined(PNG_READ_sBIT_SUPPORTED)
  187541. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  187542. png_handle_sBIT(png_ptr, info_ptr, length);
  187543. #endif
  187544. #if defined(PNG_READ_sRGB_SUPPORTED)
  187545. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  187546. png_handle_sRGB(png_ptr, info_ptr, length);
  187547. #endif
  187548. #if defined(PNG_READ_iCCP_SUPPORTED)
  187549. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  187550. png_handle_iCCP(png_ptr, info_ptr, length);
  187551. #endif
  187552. #if defined(PNG_READ_sPLT_SUPPORTED)
  187553. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  187554. png_handle_sPLT(png_ptr, info_ptr, length);
  187555. #endif
  187556. #if defined(PNG_READ_tEXt_SUPPORTED)
  187557. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  187558. png_handle_tEXt(png_ptr, info_ptr, length);
  187559. #endif
  187560. #if defined(PNG_READ_tIME_SUPPORTED)
  187561. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  187562. png_handle_tIME(png_ptr, info_ptr, length);
  187563. #endif
  187564. #if defined(PNG_READ_tRNS_SUPPORTED)
  187565. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  187566. png_handle_tRNS(png_ptr, info_ptr, length);
  187567. #endif
  187568. #if defined(PNG_READ_zTXt_SUPPORTED)
  187569. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  187570. png_handle_zTXt(png_ptr, info_ptr, length);
  187571. #endif
  187572. #if defined(PNG_READ_iTXt_SUPPORTED)
  187573. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  187574. png_handle_iTXt(png_ptr, info_ptr, length);
  187575. #endif
  187576. else
  187577. png_handle_unknown(png_ptr, info_ptr, length);
  187578. }
  187579. }
  187580. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187581. /* optional call to update the users info_ptr structure */
  187582. void PNGAPI
  187583. png_read_update_info(png_structp png_ptr, png_infop info_ptr)
  187584. {
  187585. png_debug(1, "in png_read_update_info\n");
  187586. if(png_ptr == NULL) return;
  187587. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187588. png_read_start_row(png_ptr);
  187589. else
  187590. png_warning(png_ptr,
  187591. "Ignoring extra png_read_update_info() call; row buffer not reallocated");
  187592. png_read_transform_info(png_ptr, info_ptr);
  187593. }
  187594. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187595. /* Initialize palette, background, etc, after transformations
  187596. * are set, but before any reading takes place. This allows
  187597. * the user to obtain a gamma-corrected palette, for example.
  187598. * If the user doesn't call this, we will do it ourselves.
  187599. */
  187600. void PNGAPI
  187601. png_start_read_image(png_structp png_ptr)
  187602. {
  187603. png_debug(1, "in png_start_read_image\n");
  187604. if(png_ptr == NULL) return;
  187605. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187606. png_read_start_row(png_ptr);
  187607. }
  187608. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187609. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187610. void PNGAPI
  187611. png_read_row(png_structp png_ptr, png_bytep row, png_bytep dsp_row)
  187612. {
  187613. #ifdef PNG_USE_LOCAL_ARRAYS
  187614. PNG_CONST PNG_IDAT;
  187615. PNG_CONST int png_pass_dsp_mask[7] = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
  187616. 0xff};
  187617. PNG_CONST int png_pass_mask[7] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  187618. #endif
  187619. int ret;
  187620. if(png_ptr == NULL) return;
  187621. png_debug2(1, "in png_read_row (row %lu, pass %d)\n",
  187622. png_ptr->row_number, png_ptr->pass);
  187623. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187624. png_read_start_row(png_ptr);
  187625. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  187626. {
  187627. /* check for transforms that have been set but were defined out */
  187628. #if defined(PNG_WRITE_INVERT_SUPPORTED) && !defined(PNG_READ_INVERT_SUPPORTED)
  187629. if (png_ptr->transformations & PNG_INVERT_MONO)
  187630. png_warning(png_ptr, "PNG_READ_INVERT_SUPPORTED is not defined.");
  187631. #endif
  187632. #if defined(PNG_WRITE_FILLER_SUPPORTED) && !defined(PNG_READ_FILLER_SUPPORTED)
  187633. if (png_ptr->transformations & PNG_FILLER)
  187634. png_warning(png_ptr, "PNG_READ_FILLER_SUPPORTED is not defined.");
  187635. #endif
  187636. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED) && !defined(PNG_READ_PACKSWAP_SUPPORTED)
  187637. if (png_ptr->transformations & PNG_PACKSWAP)
  187638. png_warning(png_ptr, "PNG_READ_PACKSWAP_SUPPORTED is not defined.");
  187639. #endif
  187640. #if defined(PNG_WRITE_PACK_SUPPORTED) && !defined(PNG_READ_PACK_SUPPORTED)
  187641. if (png_ptr->transformations & PNG_PACK)
  187642. png_warning(png_ptr, "PNG_READ_PACK_SUPPORTED is not defined.");
  187643. #endif
  187644. #if defined(PNG_WRITE_SHIFT_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED)
  187645. if (png_ptr->transformations & PNG_SHIFT)
  187646. png_warning(png_ptr, "PNG_READ_SHIFT_SUPPORTED is not defined.");
  187647. #endif
  187648. #if defined(PNG_WRITE_BGR_SUPPORTED) && !defined(PNG_READ_BGR_SUPPORTED)
  187649. if (png_ptr->transformations & PNG_BGR)
  187650. png_warning(png_ptr, "PNG_READ_BGR_SUPPORTED is not defined.");
  187651. #endif
  187652. #if defined(PNG_WRITE_SWAP_SUPPORTED) && !defined(PNG_READ_SWAP_SUPPORTED)
  187653. if (png_ptr->transformations & PNG_SWAP_BYTES)
  187654. png_warning(png_ptr, "PNG_READ_SWAP_SUPPORTED is not defined.");
  187655. #endif
  187656. }
  187657. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  187658. /* if interlaced and we do not need a new row, combine row and return */
  187659. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  187660. {
  187661. switch (png_ptr->pass)
  187662. {
  187663. case 0:
  187664. if (png_ptr->row_number & 0x07)
  187665. {
  187666. if (dsp_row != NULL)
  187667. png_combine_row(png_ptr, dsp_row,
  187668. png_pass_dsp_mask[png_ptr->pass]);
  187669. png_read_finish_row(png_ptr);
  187670. return;
  187671. }
  187672. break;
  187673. case 1:
  187674. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  187675. {
  187676. if (dsp_row != NULL)
  187677. png_combine_row(png_ptr, dsp_row,
  187678. png_pass_dsp_mask[png_ptr->pass]);
  187679. png_read_finish_row(png_ptr);
  187680. return;
  187681. }
  187682. break;
  187683. case 2:
  187684. if ((png_ptr->row_number & 0x07) != 4)
  187685. {
  187686. if (dsp_row != NULL && (png_ptr->row_number & 4))
  187687. png_combine_row(png_ptr, dsp_row,
  187688. png_pass_dsp_mask[png_ptr->pass]);
  187689. png_read_finish_row(png_ptr);
  187690. return;
  187691. }
  187692. break;
  187693. case 3:
  187694. if ((png_ptr->row_number & 3) || png_ptr->width < 3)
  187695. {
  187696. if (dsp_row != NULL)
  187697. png_combine_row(png_ptr, dsp_row,
  187698. png_pass_dsp_mask[png_ptr->pass]);
  187699. png_read_finish_row(png_ptr);
  187700. return;
  187701. }
  187702. break;
  187703. case 4:
  187704. if ((png_ptr->row_number & 3) != 2)
  187705. {
  187706. if (dsp_row != NULL && (png_ptr->row_number & 2))
  187707. png_combine_row(png_ptr, dsp_row,
  187708. png_pass_dsp_mask[png_ptr->pass]);
  187709. png_read_finish_row(png_ptr);
  187710. return;
  187711. }
  187712. break;
  187713. case 5:
  187714. if ((png_ptr->row_number & 1) || png_ptr->width < 2)
  187715. {
  187716. if (dsp_row != NULL)
  187717. png_combine_row(png_ptr, dsp_row,
  187718. png_pass_dsp_mask[png_ptr->pass]);
  187719. png_read_finish_row(png_ptr);
  187720. return;
  187721. }
  187722. break;
  187723. case 6:
  187724. if (!(png_ptr->row_number & 1))
  187725. {
  187726. png_read_finish_row(png_ptr);
  187727. return;
  187728. }
  187729. break;
  187730. }
  187731. }
  187732. #endif
  187733. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  187734. png_error(png_ptr, "Invalid attempt to read row data");
  187735. png_ptr->zstream.next_out = png_ptr->row_buf;
  187736. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  187737. do
  187738. {
  187739. if (!(png_ptr->zstream.avail_in))
  187740. {
  187741. while (!png_ptr->idat_size)
  187742. {
  187743. png_byte chunk_length[4];
  187744. png_crc_finish(png_ptr, 0);
  187745. png_read_data(png_ptr, chunk_length, 4);
  187746. png_ptr->idat_size = png_get_uint_31(png_ptr,chunk_length);
  187747. png_reset_crc(png_ptr);
  187748. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187749. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187750. png_error(png_ptr, "Not enough image data");
  187751. }
  187752. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  187753. png_ptr->zstream.next_in = png_ptr->zbuf;
  187754. if (png_ptr->zbuf_size > png_ptr->idat_size)
  187755. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  187756. png_crc_read(png_ptr, png_ptr->zbuf,
  187757. (png_size_t)png_ptr->zstream.avail_in);
  187758. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  187759. }
  187760. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  187761. if (ret == Z_STREAM_END)
  187762. {
  187763. if (png_ptr->zstream.avail_out || png_ptr->zstream.avail_in ||
  187764. png_ptr->idat_size)
  187765. png_error(png_ptr, "Extra compressed data");
  187766. png_ptr->mode |= PNG_AFTER_IDAT;
  187767. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  187768. break;
  187769. }
  187770. if (ret != Z_OK)
  187771. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  187772. "Decompression error");
  187773. } while (png_ptr->zstream.avail_out);
  187774. png_ptr->row_info.color_type = png_ptr->color_type;
  187775. png_ptr->row_info.width = png_ptr->iwidth;
  187776. png_ptr->row_info.channels = png_ptr->channels;
  187777. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  187778. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  187779. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  187780. png_ptr->row_info.width);
  187781. if(png_ptr->row_buf[0])
  187782. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  187783. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  187784. (int)(png_ptr->row_buf[0]));
  187785. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  187786. png_ptr->rowbytes + 1);
  187787. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  187788. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  187789. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  187790. {
  187791. /* Intrapixel differencing */
  187792. png_do_read_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  187793. }
  187794. #endif
  187795. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  187796. png_do_read_transformations(png_ptr);
  187797. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  187798. /* blow up interlaced rows to full size */
  187799. if (png_ptr->interlaced &&
  187800. (png_ptr->transformations & PNG_INTERLACE))
  187801. {
  187802. if (png_ptr->pass < 6)
  187803. /* old interface (pre-1.0.9):
  187804. png_do_read_interlace(&(png_ptr->row_info),
  187805. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  187806. */
  187807. png_do_read_interlace(png_ptr);
  187808. if (dsp_row != NULL)
  187809. png_combine_row(png_ptr, dsp_row,
  187810. png_pass_dsp_mask[png_ptr->pass]);
  187811. if (row != NULL)
  187812. png_combine_row(png_ptr, row,
  187813. png_pass_mask[png_ptr->pass]);
  187814. }
  187815. else
  187816. #endif
  187817. {
  187818. if (row != NULL)
  187819. png_combine_row(png_ptr, row, 0xff);
  187820. if (dsp_row != NULL)
  187821. png_combine_row(png_ptr, dsp_row, 0xff);
  187822. }
  187823. png_read_finish_row(png_ptr);
  187824. if (png_ptr->read_row_fn != NULL)
  187825. (*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  187826. }
  187827. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187828. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187829. /* Read one or more rows of image data. If the image is interlaced,
  187830. * and png_set_interlace_handling() has been called, the rows need to
  187831. * contain the contents of the rows from the previous pass. If the
  187832. * image has alpha or transparency, and png_handle_alpha()[*] has been
  187833. * called, the rows contents must be initialized to the contents of the
  187834. * screen.
  187835. *
  187836. * "row" holds the actual image, and pixels are placed in it
  187837. * as they arrive. If the image is displayed after each pass, it will
  187838. * appear to "sparkle" in. "display_row" can be used to display a
  187839. * "chunky" progressive image, with finer detail added as it becomes
  187840. * available. If you do not want this "chunky" display, you may pass
  187841. * NULL for display_row. If you do not want the sparkle display, and
  187842. * you have not called png_handle_alpha(), you may pass NULL for rows.
  187843. * If you have called png_handle_alpha(), and the image has either an
  187844. * alpha channel or a transparency chunk, you must provide a buffer for
  187845. * rows. In this case, you do not have to provide a display_row buffer
  187846. * also, but you may. If the image is not interlaced, or if you have
  187847. * not called png_set_interlace_handling(), the display_row buffer will
  187848. * be ignored, so pass NULL to it.
  187849. *
  187850. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  187851. */
  187852. void PNGAPI
  187853. png_read_rows(png_structp png_ptr, png_bytepp row,
  187854. png_bytepp display_row, png_uint_32 num_rows)
  187855. {
  187856. png_uint_32 i;
  187857. png_bytepp rp;
  187858. png_bytepp dp;
  187859. png_debug(1, "in png_read_rows\n");
  187860. if(png_ptr == NULL) return;
  187861. rp = row;
  187862. dp = display_row;
  187863. if (rp != NULL && dp != NULL)
  187864. for (i = 0; i < num_rows; i++)
  187865. {
  187866. png_bytep rptr = *rp++;
  187867. png_bytep dptr = *dp++;
  187868. png_read_row(png_ptr, rptr, dptr);
  187869. }
  187870. else if(rp != NULL)
  187871. for (i = 0; i < num_rows; i++)
  187872. {
  187873. png_bytep rptr = *rp;
  187874. png_read_row(png_ptr, rptr, png_bytep_NULL);
  187875. rp++;
  187876. }
  187877. else if(dp != NULL)
  187878. for (i = 0; i < num_rows; i++)
  187879. {
  187880. png_bytep dptr = *dp;
  187881. png_read_row(png_ptr, png_bytep_NULL, dptr);
  187882. dp++;
  187883. }
  187884. }
  187885. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187886. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187887. /* Read the entire image. If the image has an alpha channel or a tRNS
  187888. * chunk, and you have called png_handle_alpha()[*], you will need to
  187889. * initialize the image to the current image that PNG will be overlaying.
  187890. * We set the num_rows again here, in case it was incorrectly set in
  187891. * png_read_start_row() by a call to png_read_update_info() or
  187892. * png_start_read_image() if png_set_interlace_handling() wasn't called
  187893. * prior to either of these functions like it should have been. You can
  187894. * only call this function once. If you desire to have an image for
  187895. * each pass of a interlaced image, use png_read_rows() instead.
  187896. *
  187897. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  187898. */
  187899. void PNGAPI
  187900. png_read_image(png_structp png_ptr, png_bytepp image)
  187901. {
  187902. png_uint_32 i,image_height;
  187903. int pass, j;
  187904. png_bytepp rp;
  187905. png_debug(1, "in png_read_image\n");
  187906. if(png_ptr == NULL) return;
  187907. #ifdef PNG_READ_INTERLACING_SUPPORTED
  187908. pass = png_set_interlace_handling(png_ptr);
  187909. #else
  187910. if (png_ptr->interlaced)
  187911. png_error(png_ptr,
  187912. "Cannot read interlaced image -- interlace handler disabled.");
  187913. pass = 1;
  187914. #endif
  187915. image_height=png_ptr->height;
  187916. png_ptr->num_rows = image_height; /* Make sure this is set correctly */
  187917. for (j = 0; j < pass; j++)
  187918. {
  187919. rp = image;
  187920. for (i = 0; i < image_height; i++)
  187921. {
  187922. png_read_row(png_ptr, *rp, png_bytep_NULL);
  187923. rp++;
  187924. }
  187925. }
  187926. }
  187927. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187928. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187929. /* Read the end of the PNG file. Will not read past the end of the
  187930. * file, will verify the end is accurate, and will read any comments
  187931. * or time information at the end of the file, if info is not NULL.
  187932. */
  187933. void PNGAPI
  187934. png_read_end(png_structp png_ptr, png_infop info_ptr)
  187935. {
  187936. png_byte chunk_length[4];
  187937. png_uint_32 length;
  187938. png_debug(1, "in png_read_end\n");
  187939. if(png_ptr == NULL) return;
  187940. png_crc_finish(png_ptr, 0); /* Finish off CRC from last IDAT chunk */
  187941. do
  187942. {
  187943. #ifdef PNG_USE_LOCAL_ARRAYS
  187944. PNG_CONST PNG_IHDR;
  187945. PNG_CONST PNG_IDAT;
  187946. PNG_CONST PNG_IEND;
  187947. PNG_CONST PNG_PLTE;
  187948. #if defined(PNG_READ_bKGD_SUPPORTED)
  187949. PNG_CONST PNG_bKGD;
  187950. #endif
  187951. #if defined(PNG_READ_cHRM_SUPPORTED)
  187952. PNG_CONST PNG_cHRM;
  187953. #endif
  187954. #if defined(PNG_READ_gAMA_SUPPORTED)
  187955. PNG_CONST PNG_gAMA;
  187956. #endif
  187957. #if defined(PNG_READ_hIST_SUPPORTED)
  187958. PNG_CONST PNG_hIST;
  187959. #endif
  187960. #if defined(PNG_READ_iCCP_SUPPORTED)
  187961. PNG_CONST PNG_iCCP;
  187962. #endif
  187963. #if defined(PNG_READ_iTXt_SUPPORTED)
  187964. PNG_CONST PNG_iTXt;
  187965. #endif
  187966. #if defined(PNG_READ_oFFs_SUPPORTED)
  187967. PNG_CONST PNG_oFFs;
  187968. #endif
  187969. #if defined(PNG_READ_pCAL_SUPPORTED)
  187970. PNG_CONST PNG_pCAL;
  187971. #endif
  187972. #if defined(PNG_READ_pHYs_SUPPORTED)
  187973. PNG_CONST PNG_pHYs;
  187974. #endif
  187975. #if defined(PNG_READ_sBIT_SUPPORTED)
  187976. PNG_CONST PNG_sBIT;
  187977. #endif
  187978. #if defined(PNG_READ_sCAL_SUPPORTED)
  187979. PNG_CONST PNG_sCAL;
  187980. #endif
  187981. #if defined(PNG_READ_sPLT_SUPPORTED)
  187982. PNG_CONST PNG_sPLT;
  187983. #endif
  187984. #if defined(PNG_READ_sRGB_SUPPORTED)
  187985. PNG_CONST PNG_sRGB;
  187986. #endif
  187987. #if defined(PNG_READ_tEXt_SUPPORTED)
  187988. PNG_CONST PNG_tEXt;
  187989. #endif
  187990. #if defined(PNG_READ_tIME_SUPPORTED)
  187991. PNG_CONST PNG_tIME;
  187992. #endif
  187993. #if defined(PNG_READ_tRNS_SUPPORTED)
  187994. PNG_CONST PNG_tRNS;
  187995. #endif
  187996. #if defined(PNG_READ_zTXt_SUPPORTED)
  187997. PNG_CONST PNG_zTXt;
  187998. #endif
  187999. #endif /* PNG_USE_LOCAL_ARRAYS */
  188000. png_read_data(png_ptr, chunk_length, 4);
  188001. length = png_get_uint_31(png_ptr,chunk_length);
  188002. png_reset_crc(png_ptr);
  188003. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  188004. png_debug1(0, "Reading %s chunk.\n", png_ptr->chunk_name);
  188005. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  188006. png_handle_IHDR(png_ptr, info_ptr, length);
  188007. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  188008. png_handle_IEND(png_ptr, info_ptr, length);
  188009. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  188010. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  188011. {
  188012. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188013. {
  188014. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  188015. png_error(png_ptr, "Too many IDAT's found");
  188016. }
  188017. png_handle_unknown(png_ptr, info_ptr, length);
  188018. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188019. png_ptr->mode |= PNG_HAVE_PLTE;
  188020. }
  188021. #endif
  188022. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188023. {
  188024. /* Zero length IDATs are legal after the last IDAT has been
  188025. * read, but not after other chunks have been read.
  188026. */
  188027. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  188028. png_error(png_ptr, "Too many IDAT's found");
  188029. png_crc_finish(png_ptr, length);
  188030. }
  188031. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188032. png_handle_PLTE(png_ptr, info_ptr, length);
  188033. #if defined(PNG_READ_bKGD_SUPPORTED)
  188034. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  188035. png_handle_bKGD(png_ptr, info_ptr, length);
  188036. #endif
  188037. #if defined(PNG_READ_cHRM_SUPPORTED)
  188038. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  188039. png_handle_cHRM(png_ptr, info_ptr, length);
  188040. #endif
  188041. #if defined(PNG_READ_gAMA_SUPPORTED)
  188042. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  188043. png_handle_gAMA(png_ptr, info_ptr, length);
  188044. #endif
  188045. #if defined(PNG_READ_hIST_SUPPORTED)
  188046. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  188047. png_handle_hIST(png_ptr, info_ptr, length);
  188048. #endif
  188049. #if defined(PNG_READ_oFFs_SUPPORTED)
  188050. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  188051. png_handle_oFFs(png_ptr, info_ptr, length);
  188052. #endif
  188053. #if defined(PNG_READ_pCAL_SUPPORTED)
  188054. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  188055. png_handle_pCAL(png_ptr, info_ptr, length);
  188056. #endif
  188057. #if defined(PNG_READ_sCAL_SUPPORTED)
  188058. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  188059. png_handle_sCAL(png_ptr, info_ptr, length);
  188060. #endif
  188061. #if defined(PNG_READ_pHYs_SUPPORTED)
  188062. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  188063. png_handle_pHYs(png_ptr, info_ptr, length);
  188064. #endif
  188065. #if defined(PNG_READ_sBIT_SUPPORTED)
  188066. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  188067. png_handle_sBIT(png_ptr, info_ptr, length);
  188068. #endif
  188069. #if defined(PNG_READ_sRGB_SUPPORTED)
  188070. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  188071. png_handle_sRGB(png_ptr, info_ptr, length);
  188072. #endif
  188073. #if defined(PNG_READ_iCCP_SUPPORTED)
  188074. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  188075. png_handle_iCCP(png_ptr, info_ptr, length);
  188076. #endif
  188077. #if defined(PNG_READ_sPLT_SUPPORTED)
  188078. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  188079. png_handle_sPLT(png_ptr, info_ptr, length);
  188080. #endif
  188081. #if defined(PNG_READ_tEXt_SUPPORTED)
  188082. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  188083. png_handle_tEXt(png_ptr, info_ptr, length);
  188084. #endif
  188085. #if defined(PNG_READ_tIME_SUPPORTED)
  188086. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  188087. png_handle_tIME(png_ptr, info_ptr, length);
  188088. #endif
  188089. #if defined(PNG_READ_tRNS_SUPPORTED)
  188090. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  188091. png_handle_tRNS(png_ptr, info_ptr, length);
  188092. #endif
  188093. #if defined(PNG_READ_zTXt_SUPPORTED)
  188094. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  188095. png_handle_zTXt(png_ptr, info_ptr, length);
  188096. #endif
  188097. #if defined(PNG_READ_iTXt_SUPPORTED)
  188098. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  188099. png_handle_iTXt(png_ptr, info_ptr, length);
  188100. #endif
  188101. else
  188102. png_handle_unknown(png_ptr, info_ptr, length);
  188103. } while (!(png_ptr->mode & PNG_HAVE_IEND));
  188104. }
  188105. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  188106. /* free all memory used by the read */
  188107. void PNGAPI
  188108. png_destroy_read_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr,
  188109. png_infopp end_info_ptr_ptr)
  188110. {
  188111. png_structp png_ptr = NULL;
  188112. png_infop info_ptr = NULL, end_info_ptr = NULL;
  188113. #ifdef PNG_USER_MEM_SUPPORTED
  188114. png_free_ptr free_fn;
  188115. png_voidp mem_ptr;
  188116. #endif
  188117. png_debug(1, "in png_destroy_read_struct\n");
  188118. if (png_ptr_ptr != NULL)
  188119. png_ptr = *png_ptr_ptr;
  188120. if (info_ptr_ptr != NULL)
  188121. info_ptr = *info_ptr_ptr;
  188122. if (end_info_ptr_ptr != NULL)
  188123. end_info_ptr = *end_info_ptr_ptr;
  188124. #ifdef PNG_USER_MEM_SUPPORTED
  188125. free_fn = png_ptr->free_fn;
  188126. mem_ptr = png_ptr->mem_ptr;
  188127. #endif
  188128. png_read_destroy(png_ptr, info_ptr, end_info_ptr);
  188129. if (info_ptr != NULL)
  188130. {
  188131. #if defined(PNG_TEXT_SUPPORTED)
  188132. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, -1);
  188133. #endif
  188134. #ifdef PNG_USER_MEM_SUPPORTED
  188135. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  188136. (png_voidp)mem_ptr);
  188137. #else
  188138. png_destroy_struct((png_voidp)info_ptr);
  188139. #endif
  188140. *info_ptr_ptr = NULL;
  188141. }
  188142. if (end_info_ptr != NULL)
  188143. {
  188144. #if defined(PNG_READ_TEXT_SUPPORTED)
  188145. png_free_data(png_ptr, end_info_ptr, PNG_FREE_TEXT, -1);
  188146. #endif
  188147. #ifdef PNG_USER_MEM_SUPPORTED
  188148. png_destroy_struct_2((png_voidp)end_info_ptr, (png_free_ptr)free_fn,
  188149. (png_voidp)mem_ptr);
  188150. #else
  188151. png_destroy_struct((png_voidp)end_info_ptr);
  188152. #endif
  188153. *end_info_ptr_ptr = NULL;
  188154. }
  188155. if (png_ptr != NULL)
  188156. {
  188157. #ifdef PNG_USER_MEM_SUPPORTED
  188158. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  188159. (png_voidp)mem_ptr);
  188160. #else
  188161. png_destroy_struct((png_voidp)png_ptr);
  188162. #endif
  188163. *png_ptr_ptr = NULL;
  188164. }
  188165. }
  188166. /* free all memory used by the read (old method) */
  188167. void /* PRIVATE */
  188168. png_read_destroy(png_structp png_ptr, png_infop info_ptr, png_infop end_info_ptr)
  188169. {
  188170. #ifdef PNG_SETJMP_SUPPORTED
  188171. jmp_buf tmp_jmp;
  188172. #endif
  188173. png_error_ptr error_fn;
  188174. png_error_ptr warning_fn;
  188175. png_voidp error_ptr;
  188176. #ifdef PNG_USER_MEM_SUPPORTED
  188177. png_free_ptr free_fn;
  188178. #endif
  188179. png_debug(1, "in png_read_destroy\n");
  188180. if (info_ptr != NULL)
  188181. png_info_destroy(png_ptr, info_ptr);
  188182. if (end_info_ptr != NULL)
  188183. png_info_destroy(png_ptr, end_info_ptr);
  188184. png_free(png_ptr, png_ptr->zbuf);
  188185. png_free(png_ptr, png_ptr->big_row_buf);
  188186. png_free(png_ptr, png_ptr->prev_row);
  188187. #if defined(PNG_READ_DITHER_SUPPORTED)
  188188. png_free(png_ptr, png_ptr->palette_lookup);
  188189. png_free(png_ptr, png_ptr->dither_index);
  188190. #endif
  188191. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188192. png_free(png_ptr, png_ptr->gamma_table);
  188193. #endif
  188194. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  188195. png_free(png_ptr, png_ptr->gamma_from_1);
  188196. png_free(png_ptr, png_ptr->gamma_to_1);
  188197. #endif
  188198. #ifdef PNG_FREE_ME_SUPPORTED
  188199. if (png_ptr->free_me & PNG_FREE_PLTE)
  188200. png_zfree(png_ptr, png_ptr->palette);
  188201. png_ptr->free_me &= ~PNG_FREE_PLTE;
  188202. #else
  188203. if (png_ptr->flags & PNG_FLAG_FREE_PLTE)
  188204. png_zfree(png_ptr, png_ptr->palette);
  188205. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  188206. #endif
  188207. #if defined(PNG_tRNS_SUPPORTED) || \
  188208. defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  188209. #ifdef PNG_FREE_ME_SUPPORTED
  188210. if (png_ptr->free_me & PNG_FREE_TRNS)
  188211. png_free(png_ptr, png_ptr->trans);
  188212. png_ptr->free_me &= ~PNG_FREE_TRNS;
  188213. #else
  188214. if (png_ptr->flags & PNG_FLAG_FREE_TRNS)
  188215. png_free(png_ptr, png_ptr->trans);
  188216. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  188217. #endif
  188218. #endif
  188219. #if defined(PNG_READ_hIST_SUPPORTED)
  188220. #ifdef PNG_FREE_ME_SUPPORTED
  188221. if (png_ptr->free_me & PNG_FREE_HIST)
  188222. png_free(png_ptr, png_ptr->hist);
  188223. png_ptr->free_me &= ~PNG_FREE_HIST;
  188224. #else
  188225. if (png_ptr->flags & PNG_FLAG_FREE_HIST)
  188226. png_free(png_ptr, png_ptr->hist);
  188227. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  188228. #endif
  188229. #endif
  188230. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188231. if (png_ptr->gamma_16_table != NULL)
  188232. {
  188233. int i;
  188234. int istop = (1 << (8 - png_ptr->gamma_shift));
  188235. for (i = 0; i < istop; i++)
  188236. {
  188237. png_free(png_ptr, png_ptr->gamma_16_table[i]);
  188238. }
  188239. png_free(png_ptr, png_ptr->gamma_16_table);
  188240. }
  188241. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  188242. if (png_ptr->gamma_16_from_1 != NULL)
  188243. {
  188244. int i;
  188245. int istop = (1 << (8 - png_ptr->gamma_shift));
  188246. for (i = 0; i < istop; i++)
  188247. {
  188248. png_free(png_ptr, png_ptr->gamma_16_from_1[i]);
  188249. }
  188250. png_free(png_ptr, png_ptr->gamma_16_from_1);
  188251. }
  188252. if (png_ptr->gamma_16_to_1 != NULL)
  188253. {
  188254. int i;
  188255. int istop = (1 << (8 - png_ptr->gamma_shift));
  188256. for (i = 0; i < istop; i++)
  188257. {
  188258. png_free(png_ptr, png_ptr->gamma_16_to_1[i]);
  188259. }
  188260. png_free(png_ptr, png_ptr->gamma_16_to_1);
  188261. }
  188262. #endif
  188263. #endif
  188264. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  188265. png_free(png_ptr, png_ptr->time_buffer);
  188266. #endif
  188267. inflateEnd(&png_ptr->zstream);
  188268. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  188269. png_free(png_ptr, png_ptr->save_buffer);
  188270. #endif
  188271. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  188272. #ifdef PNG_TEXT_SUPPORTED
  188273. png_free(png_ptr, png_ptr->current_text);
  188274. #endif /* PNG_TEXT_SUPPORTED */
  188275. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  188276. /* Save the important info out of the png_struct, in case it is
  188277. * being used again.
  188278. */
  188279. #ifdef PNG_SETJMP_SUPPORTED
  188280. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  188281. #endif
  188282. error_fn = png_ptr->error_fn;
  188283. warning_fn = png_ptr->warning_fn;
  188284. error_ptr = png_ptr->error_ptr;
  188285. #ifdef PNG_USER_MEM_SUPPORTED
  188286. free_fn = png_ptr->free_fn;
  188287. #endif
  188288. png_memset(png_ptr, 0, png_sizeof (png_struct));
  188289. png_ptr->error_fn = error_fn;
  188290. png_ptr->warning_fn = warning_fn;
  188291. png_ptr->error_ptr = error_ptr;
  188292. #ifdef PNG_USER_MEM_SUPPORTED
  188293. png_ptr->free_fn = free_fn;
  188294. #endif
  188295. #ifdef PNG_SETJMP_SUPPORTED
  188296. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  188297. #endif
  188298. }
  188299. void PNGAPI
  188300. png_set_read_status_fn(png_structp png_ptr, png_read_status_ptr read_row_fn)
  188301. {
  188302. if(png_ptr == NULL) return;
  188303. png_ptr->read_row_fn = read_row_fn;
  188304. }
  188305. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  188306. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  188307. void PNGAPI
  188308. png_read_png(png_structp png_ptr, png_infop info_ptr,
  188309. int transforms,
  188310. voidp params)
  188311. {
  188312. int row;
  188313. if(png_ptr == NULL) return;
  188314. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  188315. /* invert the alpha channel from opacity to transparency
  188316. */
  188317. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  188318. png_set_invert_alpha(png_ptr);
  188319. #endif
  188320. /* png_read_info() gives us all of the information from the
  188321. * PNG file before the first IDAT (image data chunk).
  188322. */
  188323. png_read_info(png_ptr, info_ptr);
  188324. if (info_ptr->height > PNG_UINT_32_MAX/png_sizeof(png_bytep))
  188325. png_error(png_ptr,"Image is too high to process with png_read_png()");
  188326. /* -------------- image transformations start here ------------------- */
  188327. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  188328. /* tell libpng to strip 16 bit/color files down to 8 bits per color
  188329. */
  188330. if (transforms & PNG_TRANSFORM_STRIP_16)
  188331. png_set_strip_16(png_ptr);
  188332. #endif
  188333. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  188334. /* Strip alpha bytes from the input data without combining with
  188335. * the background (not recommended).
  188336. */
  188337. if (transforms & PNG_TRANSFORM_STRIP_ALPHA)
  188338. png_set_strip_alpha(png_ptr);
  188339. #endif
  188340. #if defined(PNG_READ_PACK_SUPPORTED) && !defined(PNG_READ_EXPAND_SUPPORTED)
  188341. /* Extract multiple pixels with bit depths of 1, 2, or 4 from a single
  188342. * byte into separate bytes (useful for paletted and grayscale images).
  188343. */
  188344. if (transforms & PNG_TRANSFORM_PACKING)
  188345. png_set_packing(png_ptr);
  188346. #endif
  188347. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  188348. /* Change the order of packed pixels to least significant bit first
  188349. * (not useful if you are using png_set_packing).
  188350. */
  188351. if (transforms & PNG_TRANSFORM_PACKSWAP)
  188352. png_set_packswap(png_ptr);
  188353. #endif
  188354. #if defined(PNG_READ_EXPAND_SUPPORTED)
  188355. /* Expand paletted colors into true RGB triplets
  188356. * Expand grayscale images to full 8 bits from 1, 2, or 4 bits/pixel
  188357. * Expand paletted or RGB images with transparency to full alpha
  188358. * channels so the data will be available as RGBA quartets.
  188359. */
  188360. if (transforms & PNG_TRANSFORM_EXPAND)
  188361. if ((png_ptr->bit_depth < 8) ||
  188362. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ||
  188363. (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)))
  188364. png_set_expand(png_ptr);
  188365. #endif
  188366. /* We don't handle background color or gamma transformation or dithering.
  188367. */
  188368. #if defined(PNG_READ_INVERT_SUPPORTED)
  188369. /* invert monochrome files to have 0 as white and 1 as black
  188370. */
  188371. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  188372. png_set_invert_mono(png_ptr);
  188373. #endif
  188374. #if defined(PNG_READ_SHIFT_SUPPORTED)
  188375. /* If you want to shift the pixel values from the range [0,255] or
  188376. * [0,65535] to the original [0,7] or [0,31], or whatever range the
  188377. * colors were originally in:
  188378. */
  188379. if ((transforms & PNG_TRANSFORM_SHIFT)
  188380. && png_get_valid(png_ptr, info_ptr, PNG_INFO_sBIT))
  188381. {
  188382. png_color_8p sig_bit;
  188383. png_get_sBIT(png_ptr, info_ptr, &sig_bit);
  188384. png_set_shift(png_ptr, sig_bit);
  188385. }
  188386. #endif
  188387. #if defined(PNG_READ_BGR_SUPPORTED)
  188388. /* flip the RGB pixels to BGR (or RGBA to BGRA)
  188389. */
  188390. if (transforms & PNG_TRANSFORM_BGR)
  188391. png_set_bgr(png_ptr);
  188392. #endif
  188393. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  188394. /* swap the RGBA or GA data to ARGB or AG (or BGRA to ABGR)
  188395. */
  188396. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  188397. png_set_swap_alpha(png_ptr);
  188398. #endif
  188399. #if defined(PNG_READ_SWAP_SUPPORTED)
  188400. /* swap bytes of 16 bit files to least significant byte first
  188401. */
  188402. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  188403. png_set_swap(png_ptr);
  188404. #endif
  188405. /* We don't handle adding filler bytes */
  188406. /* Optional call to gamma correct and add the background to the palette
  188407. * and update info structure. REQUIRED if you are expecting libpng to
  188408. * update the palette for you (i.e., you selected such a transform above).
  188409. */
  188410. png_read_update_info(png_ptr, info_ptr);
  188411. /* -------------- image transformations end here ------------------- */
  188412. #ifdef PNG_FREE_ME_SUPPORTED
  188413. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  188414. #endif
  188415. if(info_ptr->row_pointers == NULL)
  188416. {
  188417. info_ptr->row_pointers = (png_bytepp)png_malloc(png_ptr,
  188418. info_ptr->height * png_sizeof(png_bytep));
  188419. #ifdef PNG_FREE_ME_SUPPORTED
  188420. info_ptr->free_me |= PNG_FREE_ROWS;
  188421. #endif
  188422. for (row = 0; row < (int)info_ptr->height; row++)
  188423. {
  188424. info_ptr->row_pointers[row] = (png_bytep)png_malloc(png_ptr,
  188425. png_get_rowbytes(png_ptr, info_ptr));
  188426. }
  188427. }
  188428. png_read_image(png_ptr, info_ptr->row_pointers);
  188429. info_ptr->valid |= PNG_INFO_IDAT;
  188430. /* read rest of file, and get additional chunks in info_ptr - REQUIRED */
  188431. png_read_end(png_ptr, info_ptr);
  188432. transforms = transforms; /* quiet compiler warnings */
  188433. params = params;
  188434. }
  188435. #endif /* PNG_INFO_IMAGE_SUPPORTED */
  188436. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  188437. #endif /* PNG_READ_SUPPORTED */
  188438. /*** End of inlined file: pngread.c ***/
  188439. /*** Start of inlined file: pngpread.c ***/
  188440. /* pngpread.c - read a png file in push mode
  188441. *
  188442. * Last changed in libpng 1.2.21 October 4, 2007
  188443. * For conditions of distribution and use, see copyright notice in png.h
  188444. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  188445. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  188446. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  188447. */
  188448. #define PNG_INTERNAL
  188449. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  188450. /* push model modes */
  188451. #define PNG_READ_SIG_MODE 0
  188452. #define PNG_READ_CHUNK_MODE 1
  188453. #define PNG_READ_IDAT_MODE 2
  188454. #define PNG_SKIP_MODE 3
  188455. #define PNG_READ_tEXt_MODE 4
  188456. #define PNG_READ_zTXt_MODE 5
  188457. #define PNG_READ_DONE_MODE 6
  188458. #define PNG_READ_iTXt_MODE 7
  188459. #define PNG_ERROR_MODE 8
  188460. void PNGAPI
  188461. png_process_data(png_structp png_ptr, png_infop info_ptr,
  188462. png_bytep buffer, png_size_t buffer_size)
  188463. {
  188464. if(png_ptr == NULL) return;
  188465. png_push_restore_buffer(png_ptr, buffer, buffer_size);
  188466. while (png_ptr->buffer_size)
  188467. {
  188468. png_process_some_data(png_ptr, info_ptr);
  188469. }
  188470. }
  188471. /* What we do with the incoming data depends on what we were previously
  188472. * doing before we ran out of data...
  188473. */
  188474. void /* PRIVATE */
  188475. png_process_some_data(png_structp png_ptr, png_infop info_ptr)
  188476. {
  188477. if(png_ptr == NULL) return;
  188478. switch (png_ptr->process_mode)
  188479. {
  188480. case PNG_READ_SIG_MODE:
  188481. {
  188482. png_push_read_sig(png_ptr, info_ptr);
  188483. break;
  188484. }
  188485. case PNG_READ_CHUNK_MODE:
  188486. {
  188487. png_push_read_chunk(png_ptr, info_ptr);
  188488. break;
  188489. }
  188490. case PNG_READ_IDAT_MODE:
  188491. {
  188492. png_push_read_IDAT(png_ptr);
  188493. break;
  188494. }
  188495. #if defined(PNG_READ_tEXt_SUPPORTED)
  188496. case PNG_READ_tEXt_MODE:
  188497. {
  188498. png_push_read_tEXt(png_ptr, info_ptr);
  188499. break;
  188500. }
  188501. #endif
  188502. #if defined(PNG_READ_zTXt_SUPPORTED)
  188503. case PNG_READ_zTXt_MODE:
  188504. {
  188505. png_push_read_zTXt(png_ptr, info_ptr);
  188506. break;
  188507. }
  188508. #endif
  188509. #if defined(PNG_READ_iTXt_SUPPORTED)
  188510. case PNG_READ_iTXt_MODE:
  188511. {
  188512. png_push_read_iTXt(png_ptr, info_ptr);
  188513. break;
  188514. }
  188515. #endif
  188516. case PNG_SKIP_MODE:
  188517. {
  188518. png_push_crc_finish(png_ptr);
  188519. break;
  188520. }
  188521. default:
  188522. {
  188523. png_ptr->buffer_size = 0;
  188524. break;
  188525. }
  188526. }
  188527. }
  188528. /* Read any remaining signature bytes from the stream and compare them with
  188529. * the correct PNG signature. It is possible that this routine is called
  188530. * with bytes already read from the signature, either because they have been
  188531. * checked by the calling application, or because of multiple calls to this
  188532. * routine.
  188533. */
  188534. void /* PRIVATE */
  188535. png_push_read_sig(png_structp png_ptr, png_infop info_ptr)
  188536. {
  188537. png_size_t num_checked = png_ptr->sig_bytes,
  188538. num_to_check = 8 - num_checked;
  188539. if (png_ptr->buffer_size < num_to_check)
  188540. {
  188541. num_to_check = png_ptr->buffer_size;
  188542. }
  188543. png_push_fill_buffer(png_ptr, &(info_ptr->signature[num_checked]),
  188544. num_to_check);
  188545. png_ptr->sig_bytes = (png_byte)(png_ptr->sig_bytes+num_to_check);
  188546. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  188547. {
  188548. if (num_checked < 4 &&
  188549. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  188550. png_error(png_ptr, "Not a PNG file");
  188551. else
  188552. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  188553. }
  188554. else
  188555. {
  188556. if (png_ptr->sig_bytes >= 8)
  188557. {
  188558. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  188559. }
  188560. }
  188561. }
  188562. void /* PRIVATE */
  188563. png_push_read_chunk(png_structp png_ptr, png_infop info_ptr)
  188564. {
  188565. #ifdef PNG_USE_LOCAL_ARRAYS
  188566. PNG_CONST PNG_IHDR;
  188567. PNG_CONST PNG_IDAT;
  188568. PNG_CONST PNG_IEND;
  188569. PNG_CONST PNG_PLTE;
  188570. #if defined(PNG_READ_bKGD_SUPPORTED)
  188571. PNG_CONST PNG_bKGD;
  188572. #endif
  188573. #if defined(PNG_READ_cHRM_SUPPORTED)
  188574. PNG_CONST PNG_cHRM;
  188575. #endif
  188576. #if defined(PNG_READ_gAMA_SUPPORTED)
  188577. PNG_CONST PNG_gAMA;
  188578. #endif
  188579. #if defined(PNG_READ_hIST_SUPPORTED)
  188580. PNG_CONST PNG_hIST;
  188581. #endif
  188582. #if defined(PNG_READ_iCCP_SUPPORTED)
  188583. PNG_CONST PNG_iCCP;
  188584. #endif
  188585. #if defined(PNG_READ_iTXt_SUPPORTED)
  188586. PNG_CONST PNG_iTXt;
  188587. #endif
  188588. #if defined(PNG_READ_oFFs_SUPPORTED)
  188589. PNG_CONST PNG_oFFs;
  188590. #endif
  188591. #if defined(PNG_READ_pCAL_SUPPORTED)
  188592. PNG_CONST PNG_pCAL;
  188593. #endif
  188594. #if defined(PNG_READ_pHYs_SUPPORTED)
  188595. PNG_CONST PNG_pHYs;
  188596. #endif
  188597. #if defined(PNG_READ_sBIT_SUPPORTED)
  188598. PNG_CONST PNG_sBIT;
  188599. #endif
  188600. #if defined(PNG_READ_sCAL_SUPPORTED)
  188601. PNG_CONST PNG_sCAL;
  188602. #endif
  188603. #if defined(PNG_READ_sRGB_SUPPORTED)
  188604. PNG_CONST PNG_sRGB;
  188605. #endif
  188606. #if defined(PNG_READ_sPLT_SUPPORTED)
  188607. PNG_CONST PNG_sPLT;
  188608. #endif
  188609. #if defined(PNG_READ_tEXt_SUPPORTED)
  188610. PNG_CONST PNG_tEXt;
  188611. #endif
  188612. #if defined(PNG_READ_tIME_SUPPORTED)
  188613. PNG_CONST PNG_tIME;
  188614. #endif
  188615. #if defined(PNG_READ_tRNS_SUPPORTED)
  188616. PNG_CONST PNG_tRNS;
  188617. #endif
  188618. #if defined(PNG_READ_zTXt_SUPPORTED)
  188619. PNG_CONST PNG_zTXt;
  188620. #endif
  188621. #endif /* PNG_USE_LOCAL_ARRAYS */
  188622. /* First we make sure we have enough data for the 4 byte chunk name
  188623. * and the 4 byte chunk length before proceeding with decoding the
  188624. * chunk data. To fully decode each of these chunks, we also make
  188625. * sure we have enough data in the buffer for the 4 byte CRC at the
  188626. * end of every chunk (except IDAT, which is handled separately).
  188627. */
  188628. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  188629. {
  188630. png_byte chunk_length[4];
  188631. if (png_ptr->buffer_size < 8)
  188632. {
  188633. png_push_save_buffer(png_ptr);
  188634. return;
  188635. }
  188636. png_push_fill_buffer(png_ptr, chunk_length, 4);
  188637. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  188638. png_reset_crc(png_ptr);
  188639. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  188640. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  188641. }
  188642. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188643. if(png_ptr->mode & PNG_AFTER_IDAT)
  188644. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  188645. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  188646. {
  188647. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188648. {
  188649. png_push_save_buffer(png_ptr);
  188650. return;
  188651. }
  188652. png_handle_IHDR(png_ptr, info_ptr, png_ptr->push_length);
  188653. }
  188654. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  188655. {
  188656. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188657. {
  188658. png_push_save_buffer(png_ptr);
  188659. return;
  188660. }
  188661. png_handle_IEND(png_ptr, info_ptr, png_ptr->push_length);
  188662. png_ptr->process_mode = PNG_READ_DONE_MODE;
  188663. png_push_have_end(png_ptr, info_ptr);
  188664. }
  188665. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  188666. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  188667. {
  188668. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188669. {
  188670. png_push_save_buffer(png_ptr);
  188671. return;
  188672. }
  188673. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188674. png_ptr->mode |= PNG_HAVE_IDAT;
  188675. png_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  188676. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188677. png_ptr->mode |= PNG_HAVE_PLTE;
  188678. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188679. {
  188680. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188681. png_error(png_ptr, "Missing IHDR before IDAT");
  188682. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  188683. !(png_ptr->mode & PNG_HAVE_PLTE))
  188684. png_error(png_ptr, "Missing PLTE before IDAT");
  188685. }
  188686. }
  188687. #endif
  188688. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188689. {
  188690. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188691. {
  188692. png_push_save_buffer(png_ptr);
  188693. return;
  188694. }
  188695. png_handle_PLTE(png_ptr, info_ptr, png_ptr->push_length);
  188696. }
  188697. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188698. {
  188699. /* If we reach an IDAT chunk, this means we have read all of the
  188700. * header chunks, and we can start reading the image (or if this
  188701. * is called after the image has been read - we have an error).
  188702. */
  188703. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188704. png_error(png_ptr, "Missing IHDR before IDAT");
  188705. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  188706. !(png_ptr->mode & PNG_HAVE_PLTE))
  188707. png_error(png_ptr, "Missing PLTE before IDAT");
  188708. if (png_ptr->mode & PNG_HAVE_IDAT)
  188709. {
  188710. if (!(png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  188711. if (png_ptr->push_length == 0)
  188712. return;
  188713. if (png_ptr->mode & PNG_AFTER_IDAT)
  188714. png_error(png_ptr, "Too many IDAT's found");
  188715. }
  188716. png_ptr->idat_size = png_ptr->push_length;
  188717. png_ptr->mode |= PNG_HAVE_IDAT;
  188718. png_ptr->process_mode = PNG_READ_IDAT_MODE;
  188719. png_push_have_info(png_ptr, info_ptr);
  188720. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  188721. png_ptr->zstream.next_out = png_ptr->row_buf;
  188722. return;
  188723. }
  188724. #if defined(PNG_READ_gAMA_SUPPORTED)
  188725. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  188726. {
  188727. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188728. {
  188729. png_push_save_buffer(png_ptr);
  188730. return;
  188731. }
  188732. png_handle_gAMA(png_ptr, info_ptr, png_ptr->push_length);
  188733. }
  188734. #endif
  188735. #if defined(PNG_READ_sBIT_SUPPORTED)
  188736. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  188737. {
  188738. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188739. {
  188740. png_push_save_buffer(png_ptr);
  188741. return;
  188742. }
  188743. png_handle_sBIT(png_ptr, info_ptr, png_ptr->push_length);
  188744. }
  188745. #endif
  188746. #if defined(PNG_READ_cHRM_SUPPORTED)
  188747. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  188748. {
  188749. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188750. {
  188751. png_push_save_buffer(png_ptr);
  188752. return;
  188753. }
  188754. png_handle_cHRM(png_ptr, info_ptr, png_ptr->push_length);
  188755. }
  188756. #endif
  188757. #if defined(PNG_READ_sRGB_SUPPORTED)
  188758. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  188759. {
  188760. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188761. {
  188762. png_push_save_buffer(png_ptr);
  188763. return;
  188764. }
  188765. png_handle_sRGB(png_ptr, info_ptr, png_ptr->push_length);
  188766. }
  188767. #endif
  188768. #if defined(PNG_READ_iCCP_SUPPORTED)
  188769. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  188770. {
  188771. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188772. {
  188773. png_push_save_buffer(png_ptr);
  188774. return;
  188775. }
  188776. png_handle_iCCP(png_ptr, info_ptr, png_ptr->push_length);
  188777. }
  188778. #endif
  188779. #if defined(PNG_READ_sPLT_SUPPORTED)
  188780. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  188781. {
  188782. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188783. {
  188784. png_push_save_buffer(png_ptr);
  188785. return;
  188786. }
  188787. png_handle_sPLT(png_ptr, info_ptr, png_ptr->push_length);
  188788. }
  188789. #endif
  188790. #if defined(PNG_READ_tRNS_SUPPORTED)
  188791. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  188792. {
  188793. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188794. {
  188795. png_push_save_buffer(png_ptr);
  188796. return;
  188797. }
  188798. png_handle_tRNS(png_ptr, info_ptr, png_ptr->push_length);
  188799. }
  188800. #endif
  188801. #if defined(PNG_READ_bKGD_SUPPORTED)
  188802. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  188803. {
  188804. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188805. {
  188806. png_push_save_buffer(png_ptr);
  188807. return;
  188808. }
  188809. png_handle_bKGD(png_ptr, info_ptr, png_ptr->push_length);
  188810. }
  188811. #endif
  188812. #if defined(PNG_READ_hIST_SUPPORTED)
  188813. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  188814. {
  188815. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188816. {
  188817. png_push_save_buffer(png_ptr);
  188818. return;
  188819. }
  188820. png_handle_hIST(png_ptr, info_ptr, png_ptr->push_length);
  188821. }
  188822. #endif
  188823. #if defined(PNG_READ_pHYs_SUPPORTED)
  188824. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  188825. {
  188826. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188827. {
  188828. png_push_save_buffer(png_ptr);
  188829. return;
  188830. }
  188831. png_handle_pHYs(png_ptr, info_ptr, png_ptr->push_length);
  188832. }
  188833. #endif
  188834. #if defined(PNG_READ_oFFs_SUPPORTED)
  188835. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  188836. {
  188837. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188838. {
  188839. png_push_save_buffer(png_ptr);
  188840. return;
  188841. }
  188842. png_handle_oFFs(png_ptr, info_ptr, png_ptr->push_length);
  188843. }
  188844. #endif
  188845. #if defined(PNG_READ_pCAL_SUPPORTED)
  188846. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  188847. {
  188848. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188849. {
  188850. png_push_save_buffer(png_ptr);
  188851. return;
  188852. }
  188853. png_handle_pCAL(png_ptr, info_ptr, png_ptr->push_length);
  188854. }
  188855. #endif
  188856. #if defined(PNG_READ_sCAL_SUPPORTED)
  188857. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  188858. {
  188859. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188860. {
  188861. png_push_save_buffer(png_ptr);
  188862. return;
  188863. }
  188864. png_handle_sCAL(png_ptr, info_ptr, png_ptr->push_length);
  188865. }
  188866. #endif
  188867. #if defined(PNG_READ_tIME_SUPPORTED)
  188868. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  188869. {
  188870. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188871. {
  188872. png_push_save_buffer(png_ptr);
  188873. return;
  188874. }
  188875. png_handle_tIME(png_ptr, info_ptr, png_ptr->push_length);
  188876. }
  188877. #endif
  188878. #if defined(PNG_READ_tEXt_SUPPORTED)
  188879. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  188880. {
  188881. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188882. {
  188883. png_push_save_buffer(png_ptr);
  188884. return;
  188885. }
  188886. png_push_handle_tEXt(png_ptr, info_ptr, png_ptr->push_length);
  188887. }
  188888. #endif
  188889. #if defined(PNG_READ_zTXt_SUPPORTED)
  188890. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  188891. {
  188892. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188893. {
  188894. png_push_save_buffer(png_ptr);
  188895. return;
  188896. }
  188897. png_push_handle_zTXt(png_ptr, info_ptr, png_ptr->push_length);
  188898. }
  188899. #endif
  188900. #if defined(PNG_READ_iTXt_SUPPORTED)
  188901. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  188902. {
  188903. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188904. {
  188905. png_push_save_buffer(png_ptr);
  188906. return;
  188907. }
  188908. png_push_handle_iTXt(png_ptr, info_ptr, png_ptr->push_length);
  188909. }
  188910. #endif
  188911. else
  188912. {
  188913. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188914. {
  188915. png_push_save_buffer(png_ptr);
  188916. return;
  188917. }
  188918. png_push_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  188919. }
  188920. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  188921. }
  188922. void /* PRIVATE */
  188923. png_push_crc_skip(png_structp png_ptr, png_uint_32 skip)
  188924. {
  188925. png_ptr->process_mode = PNG_SKIP_MODE;
  188926. png_ptr->skip_length = skip;
  188927. }
  188928. void /* PRIVATE */
  188929. png_push_crc_finish(png_structp png_ptr)
  188930. {
  188931. if (png_ptr->skip_length && png_ptr->save_buffer_size)
  188932. {
  188933. png_size_t save_size;
  188934. if (png_ptr->skip_length < (png_uint_32)png_ptr->save_buffer_size)
  188935. save_size = (png_size_t)png_ptr->skip_length;
  188936. else
  188937. save_size = png_ptr->save_buffer_size;
  188938. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  188939. png_ptr->skip_length -= save_size;
  188940. png_ptr->buffer_size -= save_size;
  188941. png_ptr->save_buffer_size -= save_size;
  188942. png_ptr->save_buffer_ptr += save_size;
  188943. }
  188944. if (png_ptr->skip_length && png_ptr->current_buffer_size)
  188945. {
  188946. png_size_t save_size;
  188947. if (png_ptr->skip_length < (png_uint_32)png_ptr->current_buffer_size)
  188948. save_size = (png_size_t)png_ptr->skip_length;
  188949. else
  188950. save_size = png_ptr->current_buffer_size;
  188951. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  188952. png_ptr->skip_length -= save_size;
  188953. png_ptr->buffer_size -= save_size;
  188954. png_ptr->current_buffer_size -= save_size;
  188955. png_ptr->current_buffer_ptr += save_size;
  188956. }
  188957. if (!png_ptr->skip_length)
  188958. {
  188959. if (png_ptr->buffer_size < 4)
  188960. {
  188961. png_push_save_buffer(png_ptr);
  188962. return;
  188963. }
  188964. png_crc_finish(png_ptr, 0);
  188965. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  188966. }
  188967. }
  188968. void PNGAPI
  188969. png_push_fill_buffer(png_structp png_ptr, png_bytep buffer, png_size_t length)
  188970. {
  188971. png_bytep ptr;
  188972. if(png_ptr == NULL) return;
  188973. ptr = buffer;
  188974. if (png_ptr->save_buffer_size)
  188975. {
  188976. png_size_t save_size;
  188977. if (length < png_ptr->save_buffer_size)
  188978. save_size = length;
  188979. else
  188980. save_size = png_ptr->save_buffer_size;
  188981. png_memcpy(ptr, png_ptr->save_buffer_ptr, save_size);
  188982. length -= save_size;
  188983. ptr += save_size;
  188984. png_ptr->buffer_size -= save_size;
  188985. png_ptr->save_buffer_size -= save_size;
  188986. png_ptr->save_buffer_ptr += save_size;
  188987. }
  188988. if (length && png_ptr->current_buffer_size)
  188989. {
  188990. png_size_t save_size;
  188991. if (length < png_ptr->current_buffer_size)
  188992. save_size = length;
  188993. else
  188994. save_size = png_ptr->current_buffer_size;
  188995. png_memcpy(ptr, png_ptr->current_buffer_ptr, save_size);
  188996. png_ptr->buffer_size -= save_size;
  188997. png_ptr->current_buffer_size -= save_size;
  188998. png_ptr->current_buffer_ptr += save_size;
  188999. }
  189000. }
  189001. void /* PRIVATE */
  189002. png_push_save_buffer(png_structp png_ptr)
  189003. {
  189004. if (png_ptr->save_buffer_size)
  189005. {
  189006. if (png_ptr->save_buffer_ptr != png_ptr->save_buffer)
  189007. {
  189008. png_size_t i,istop;
  189009. png_bytep sp;
  189010. png_bytep dp;
  189011. istop = png_ptr->save_buffer_size;
  189012. for (i = 0, sp = png_ptr->save_buffer_ptr, dp = png_ptr->save_buffer;
  189013. i < istop; i++, sp++, dp++)
  189014. {
  189015. *dp = *sp;
  189016. }
  189017. }
  189018. }
  189019. if (png_ptr->save_buffer_size + png_ptr->current_buffer_size >
  189020. png_ptr->save_buffer_max)
  189021. {
  189022. png_size_t new_max;
  189023. png_bytep old_buffer;
  189024. if (png_ptr->save_buffer_size > PNG_SIZE_MAX -
  189025. (png_ptr->current_buffer_size + 256))
  189026. {
  189027. png_error(png_ptr, "Potential overflow of save_buffer");
  189028. }
  189029. new_max = png_ptr->save_buffer_size + png_ptr->current_buffer_size + 256;
  189030. old_buffer = png_ptr->save_buffer;
  189031. png_ptr->save_buffer = (png_bytep)png_malloc(png_ptr,
  189032. (png_uint_32)new_max);
  189033. png_memcpy(png_ptr->save_buffer, old_buffer, png_ptr->save_buffer_size);
  189034. png_free(png_ptr, old_buffer);
  189035. png_ptr->save_buffer_max = new_max;
  189036. }
  189037. if (png_ptr->current_buffer_size)
  189038. {
  189039. png_memcpy(png_ptr->save_buffer + png_ptr->save_buffer_size,
  189040. png_ptr->current_buffer_ptr, png_ptr->current_buffer_size);
  189041. png_ptr->save_buffer_size += png_ptr->current_buffer_size;
  189042. png_ptr->current_buffer_size = 0;
  189043. }
  189044. png_ptr->save_buffer_ptr = png_ptr->save_buffer;
  189045. png_ptr->buffer_size = 0;
  189046. }
  189047. void /* PRIVATE */
  189048. png_push_restore_buffer(png_structp png_ptr, png_bytep buffer,
  189049. png_size_t buffer_length)
  189050. {
  189051. png_ptr->current_buffer = buffer;
  189052. png_ptr->current_buffer_size = buffer_length;
  189053. png_ptr->buffer_size = buffer_length + png_ptr->save_buffer_size;
  189054. png_ptr->current_buffer_ptr = png_ptr->current_buffer;
  189055. }
  189056. void /* PRIVATE */
  189057. png_push_read_IDAT(png_structp png_ptr)
  189058. {
  189059. #ifdef PNG_USE_LOCAL_ARRAYS
  189060. PNG_CONST PNG_IDAT;
  189061. #endif
  189062. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  189063. {
  189064. png_byte chunk_length[4];
  189065. if (png_ptr->buffer_size < 8)
  189066. {
  189067. png_push_save_buffer(png_ptr);
  189068. return;
  189069. }
  189070. png_push_fill_buffer(png_ptr, chunk_length, 4);
  189071. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  189072. png_reset_crc(png_ptr);
  189073. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  189074. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  189075. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  189076. {
  189077. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  189078. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  189079. png_error(png_ptr, "Not enough compressed data");
  189080. return;
  189081. }
  189082. png_ptr->idat_size = png_ptr->push_length;
  189083. }
  189084. if (png_ptr->idat_size && png_ptr->save_buffer_size)
  189085. {
  189086. png_size_t save_size;
  189087. if (png_ptr->idat_size < (png_uint_32)png_ptr->save_buffer_size)
  189088. {
  189089. save_size = (png_size_t)png_ptr->idat_size;
  189090. /* check for overflow */
  189091. if((png_uint_32)save_size != png_ptr->idat_size)
  189092. png_error(png_ptr, "save_size overflowed in pngpread");
  189093. }
  189094. else
  189095. save_size = png_ptr->save_buffer_size;
  189096. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  189097. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  189098. png_process_IDAT_data(png_ptr, png_ptr->save_buffer_ptr, save_size);
  189099. png_ptr->idat_size -= save_size;
  189100. png_ptr->buffer_size -= save_size;
  189101. png_ptr->save_buffer_size -= save_size;
  189102. png_ptr->save_buffer_ptr += save_size;
  189103. }
  189104. if (png_ptr->idat_size && png_ptr->current_buffer_size)
  189105. {
  189106. png_size_t save_size;
  189107. if (png_ptr->idat_size < (png_uint_32)png_ptr->current_buffer_size)
  189108. {
  189109. save_size = (png_size_t)png_ptr->idat_size;
  189110. /* check for overflow */
  189111. if((png_uint_32)save_size != png_ptr->idat_size)
  189112. png_error(png_ptr, "save_size overflowed in pngpread");
  189113. }
  189114. else
  189115. save_size = png_ptr->current_buffer_size;
  189116. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  189117. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  189118. png_process_IDAT_data(png_ptr, png_ptr->current_buffer_ptr, save_size);
  189119. png_ptr->idat_size -= save_size;
  189120. png_ptr->buffer_size -= save_size;
  189121. png_ptr->current_buffer_size -= save_size;
  189122. png_ptr->current_buffer_ptr += save_size;
  189123. }
  189124. if (!png_ptr->idat_size)
  189125. {
  189126. if (png_ptr->buffer_size < 4)
  189127. {
  189128. png_push_save_buffer(png_ptr);
  189129. return;
  189130. }
  189131. png_crc_finish(png_ptr, 0);
  189132. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  189133. png_ptr->mode |= PNG_AFTER_IDAT;
  189134. }
  189135. }
  189136. void /* PRIVATE */
  189137. png_process_IDAT_data(png_structp png_ptr, png_bytep buffer,
  189138. png_size_t buffer_length)
  189139. {
  189140. int ret;
  189141. if ((png_ptr->flags & PNG_FLAG_ZLIB_FINISHED) && buffer_length)
  189142. png_error(png_ptr, "Extra compression data");
  189143. png_ptr->zstream.next_in = buffer;
  189144. png_ptr->zstream.avail_in = (uInt)buffer_length;
  189145. for(;;)
  189146. {
  189147. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  189148. if (ret != Z_OK)
  189149. {
  189150. if (ret == Z_STREAM_END)
  189151. {
  189152. if (png_ptr->zstream.avail_in)
  189153. png_error(png_ptr, "Extra compressed data");
  189154. if (!(png_ptr->zstream.avail_out))
  189155. {
  189156. png_push_process_row(png_ptr);
  189157. }
  189158. png_ptr->mode |= PNG_AFTER_IDAT;
  189159. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  189160. break;
  189161. }
  189162. else if (ret == Z_BUF_ERROR)
  189163. break;
  189164. else
  189165. png_error(png_ptr, "Decompression Error");
  189166. }
  189167. if (!(png_ptr->zstream.avail_out))
  189168. {
  189169. if ((
  189170. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  189171. png_ptr->interlaced && png_ptr->pass > 6) ||
  189172. (!png_ptr->interlaced &&
  189173. #endif
  189174. png_ptr->row_number == png_ptr->num_rows))
  189175. {
  189176. if (png_ptr->zstream.avail_in)
  189177. {
  189178. png_warning(png_ptr, "Too much data in IDAT chunks");
  189179. }
  189180. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  189181. break;
  189182. }
  189183. png_push_process_row(png_ptr);
  189184. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  189185. png_ptr->zstream.next_out = png_ptr->row_buf;
  189186. }
  189187. else
  189188. break;
  189189. }
  189190. }
  189191. void /* PRIVATE */
  189192. png_push_process_row(png_structp png_ptr)
  189193. {
  189194. png_ptr->row_info.color_type = png_ptr->color_type;
  189195. png_ptr->row_info.width = png_ptr->iwidth;
  189196. png_ptr->row_info.channels = png_ptr->channels;
  189197. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  189198. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  189199. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  189200. png_ptr->row_info.width);
  189201. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  189202. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  189203. (int)(png_ptr->row_buf[0]));
  189204. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  189205. png_ptr->rowbytes + 1);
  189206. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  189207. png_do_read_transformations(png_ptr);
  189208. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  189209. /* blow up interlaced rows to full size */
  189210. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  189211. {
  189212. if (png_ptr->pass < 6)
  189213. /* old interface (pre-1.0.9):
  189214. png_do_read_interlace(&(png_ptr->row_info),
  189215. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  189216. */
  189217. png_do_read_interlace(png_ptr);
  189218. switch (png_ptr->pass)
  189219. {
  189220. case 0:
  189221. {
  189222. int i;
  189223. for (i = 0; i < 8 && png_ptr->pass == 0; i++)
  189224. {
  189225. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189226. png_read_push_finish_row(png_ptr); /* updates png_ptr->pass */
  189227. }
  189228. if (png_ptr->pass == 2) /* pass 1 might be empty */
  189229. {
  189230. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189231. {
  189232. png_push_have_row(png_ptr, png_bytep_NULL);
  189233. png_read_push_finish_row(png_ptr);
  189234. }
  189235. }
  189236. if (png_ptr->pass == 4 && png_ptr->height <= 4)
  189237. {
  189238. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189239. {
  189240. png_push_have_row(png_ptr, png_bytep_NULL);
  189241. png_read_push_finish_row(png_ptr);
  189242. }
  189243. }
  189244. if (png_ptr->pass == 6 && png_ptr->height <= 4)
  189245. {
  189246. png_push_have_row(png_ptr, png_bytep_NULL);
  189247. png_read_push_finish_row(png_ptr);
  189248. }
  189249. break;
  189250. }
  189251. case 1:
  189252. {
  189253. int i;
  189254. for (i = 0; i < 8 && png_ptr->pass == 1; i++)
  189255. {
  189256. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189257. png_read_push_finish_row(png_ptr);
  189258. }
  189259. if (png_ptr->pass == 2) /* skip top 4 generated rows */
  189260. {
  189261. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189262. {
  189263. png_push_have_row(png_ptr, png_bytep_NULL);
  189264. png_read_push_finish_row(png_ptr);
  189265. }
  189266. }
  189267. break;
  189268. }
  189269. case 2:
  189270. {
  189271. int i;
  189272. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189273. {
  189274. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189275. png_read_push_finish_row(png_ptr);
  189276. }
  189277. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189278. {
  189279. png_push_have_row(png_ptr, png_bytep_NULL);
  189280. png_read_push_finish_row(png_ptr);
  189281. }
  189282. if (png_ptr->pass == 4) /* pass 3 might be empty */
  189283. {
  189284. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189285. {
  189286. png_push_have_row(png_ptr, png_bytep_NULL);
  189287. png_read_push_finish_row(png_ptr);
  189288. }
  189289. }
  189290. break;
  189291. }
  189292. case 3:
  189293. {
  189294. int i;
  189295. for (i = 0; i < 4 && png_ptr->pass == 3; i++)
  189296. {
  189297. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189298. png_read_push_finish_row(png_ptr);
  189299. }
  189300. if (png_ptr->pass == 4) /* skip top two generated rows */
  189301. {
  189302. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189303. {
  189304. png_push_have_row(png_ptr, png_bytep_NULL);
  189305. png_read_push_finish_row(png_ptr);
  189306. }
  189307. }
  189308. break;
  189309. }
  189310. case 4:
  189311. {
  189312. int i;
  189313. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189314. {
  189315. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189316. png_read_push_finish_row(png_ptr);
  189317. }
  189318. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189319. {
  189320. png_push_have_row(png_ptr, png_bytep_NULL);
  189321. png_read_push_finish_row(png_ptr);
  189322. }
  189323. if (png_ptr->pass == 6) /* pass 5 might be empty */
  189324. {
  189325. png_push_have_row(png_ptr, png_bytep_NULL);
  189326. png_read_push_finish_row(png_ptr);
  189327. }
  189328. break;
  189329. }
  189330. case 5:
  189331. {
  189332. int i;
  189333. for (i = 0; i < 2 && png_ptr->pass == 5; i++)
  189334. {
  189335. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189336. png_read_push_finish_row(png_ptr);
  189337. }
  189338. if (png_ptr->pass == 6) /* skip top generated row */
  189339. {
  189340. png_push_have_row(png_ptr, png_bytep_NULL);
  189341. png_read_push_finish_row(png_ptr);
  189342. }
  189343. break;
  189344. }
  189345. case 6:
  189346. {
  189347. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189348. png_read_push_finish_row(png_ptr);
  189349. if (png_ptr->pass != 6)
  189350. break;
  189351. png_push_have_row(png_ptr, png_bytep_NULL);
  189352. png_read_push_finish_row(png_ptr);
  189353. }
  189354. }
  189355. }
  189356. else
  189357. #endif
  189358. {
  189359. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189360. png_read_push_finish_row(png_ptr);
  189361. }
  189362. }
  189363. void /* PRIVATE */
  189364. png_read_push_finish_row(png_structp png_ptr)
  189365. {
  189366. #ifdef PNG_USE_LOCAL_ARRAYS
  189367. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  189368. /* start of interlace block */
  189369. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  189370. /* offset to next interlace block */
  189371. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  189372. /* start of interlace block in the y direction */
  189373. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  189374. /* offset to next interlace block in the y direction */
  189375. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  189376. /* Height of interlace block. This is not currently used - if you need
  189377. * it, uncomment it here and in png.h
  189378. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  189379. */
  189380. #endif
  189381. png_ptr->row_number++;
  189382. if (png_ptr->row_number < png_ptr->num_rows)
  189383. return;
  189384. if (png_ptr->interlaced)
  189385. {
  189386. png_ptr->row_number = 0;
  189387. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  189388. png_ptr->rowbytes + 1);
  189389. do
  189390. {
  189391. png_ptr->pass++;
  189392. if ((png_ptr->pass == 1 && png_ptr->width < 5) ||
  189393. (png_ptr->pass == 3 && png_ptr->width < 3) ||
  189394. (png_ptr->pass == 5 && png_ptr->width < 2))
  189395. png_ptr->pass++;
  189396. if (png_ptr->pass > 7)
  189397. png_ptr->pass--;
  189398. if (png_ptr->pass >= 7)
  189399. break;
  189400. png_ptr->iwidth = (png_ptr->width +
  189401. png_pass_inc[png_ptr->pass] - 1 -
  189402. png_pass_start[png_ptr->pass]) /
  189403. png_pass_inc[png_ptr->pass];
  189404. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  189405. png_ptr->iwidth) + 1;
  189406. if (png_ptr->transformations & PNG_INTERLACE)
  189407. break;
  189408. png_ptr->num_rows = (png_ptr->height +
  189409. png_pass_yinc[png_ptr->pass] - 1 -
  189410. png_pass_ystart[png_ptr->pass]) /
  189411. png_pass_yinc[png_ptr->pass];
  189412. } while (png_ptr->iwidth == 0 || png_ptr->num_rows == 0);
  189413. }
  189414. }
  189415. #if defined(PNG_READ_tEXt_SUPPORTED)
  189416. void /* PRIVATE */
  189417. png_push_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189418. length)
  189419. {
  189420. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189421. {
  189422. png_error(png_ptr, "Out of place tEXt");
  189423. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189424. }
  189425. #ifdef PNG_MAX_MALLOC_64K
  189426. png_ptr->skip_length = 0; /* This may not be necessary */
  189427. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  189428. {
  189429. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  189430. png_ptr->skip_length = length - (png_uint_32)65535L;
  189431. length = (png_uint_32)65535L;
  189432. }
  189433. #endif
  189434. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189435. (png_uint_32)(length+1));
  189436. png_ptr->current_text[length] = '\0';
  189437. png_ptr->current_text_ptr = png_ptr->current_text;
  189438. png_ptr->current_text_size = (png_size_t)length;
  189439. png_ptr->current_text_left = (png_size_t)length;
  189440. png_ptr->process_mode = PNG_READ_tEXt_MODE;
  189441. }
  189442. void /* PRIVATE */
  189443. png_push_read_tEXt(png_structp png_ptr, png_infop info_ptr)
  189444. {
  189445. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189446. {
  189447. png_size_t text_size;
  189448. if (png_ptr->buffer_size < png_ptr->current_text_left)
  189449. text_size = png_ptr->buffer_size;
  189450. else
  189451. text_size = png_ptr->current_text_left;
  189452. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189453. png_ptr->current_text_left -= text_size;
  189454. png_ptr->current_text_ptr += text_size;
  189455. }
  189456. if (!(png_ptr->current_text_left))
  189457. {
  189458. png_textp text_ptr;
  189459. png_charp text;
  189460. png_charp key;
  189461. int ret;
  189462. if (png_ptr->buffer_size < 4)
  189463. {
  189464. png_push_save_buffer(png_ptr);
  189465. return;
  189466. }
  189467. png_push_crc_finish(png_ptr);
  189468. #if defined(PNG_MAX_MALLOC_64K)
  189469. if (png_ptr->skip_length)
  189470. return;
  189471. #endif
  189472. key = png_ptr->current_text;
  189473. for (text = key; *text; text++)
  189474. /* empty loop */ ;
  189475. if (text < key + png_ptr->current_text_size)
  189476. text++;
  189477. text_ptr = (png_textp)png_malloc(png_ptr,
  189478. (png_uint_32)png_sizeof(png_text));
  189479. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  189480. text_ptr->key = key;
  189481. #ifdef PNG_iTXt_SUPPORTED
  189482. text_ptr->lang = NULL;
  189483. text_ptr->lang_key = NULL;
  189484. #endif
  189485. text_ptr->text = text;
  189486. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189487. png_free(png_ptr, key);
  189488. png_free(png_ptr, text_ptr);
  189489. png_ptr->current_text = NULL;
  189490. if (ret)
  189491. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  189492. }
  189493. }
  189494. #endif
  189495. #if defined(PNG_READ_zTXt_SUPPORTED)
  189496. void /* PRIVATE */
  189497. png_push_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189498. length)
  189499. {
  189500. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189501. {
  189502. png_error(png_ptr, "Out of place zTXt");
  189503. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189504. }
  189505. #ifdef PNG_MAX_MALLOC_64K
  189506. /* We can't handle zTXt chunks > 64K, since we don't have enough space
  189507. * to be able to store the uncompressed data. Actually, the threshold
  189508. * is probably around 32K, but it isn't as definite as 64K is.
  189509. */
  189510. if (length > (png_uint_32)65535L)
  189511. {
  189512. png_warning(png_ptr, "zTXt chunk too large to fit in memory");
  189513. png_push_crc_skip(png_ptr, length);
  189514. return;
  189515. }
  189516. #endif
  189517. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189518. (png_uint_32)(length+1));
  189519. png_ptr->current_text[length] = '\0';
  189520. png_ptr->current_text_ptr = png_ptr->current_text;
  189521. png_ptr->current_text_size = (png_size_t)length;
  189522. png_ptr->current_text_left = (png_size_t)length;
  189523. png_ptr->process_mode = PNG_READ_zTXt_MODE;
  189524. }
  189525. void /* PRIVATE */
  189526. png_push_read_zTXt(png_structp png_ptr, png_infop info_ptr)
  189527. {
  189528. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189529. {
  189530. png_size_t text_size;
  189531. if (png_ptr->buffer_size < (png_uint_32)png_ptr->current_text_left)
  189532. text_size = png_ptr->buffer_size;
  189533. else
  189534. text_size = png_ptr->current_text_left;
  189535. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189536. png_ptr->current_text_left -= text_size;
  189537. png_ptr->current_text_ptr += text_size;
  189538. }
  189539. if (!(png_ptr->current_text_left))
  189540. {
  189541. png_textp text_ptr;
  189542. png_charp text;
  189543. png_charp key;
  189544. int ret;
  189545. png_size_t text_size, key_size;
  189546. if (png_ptr->buffer_size < 4)
  189547. {
  189548. png_push_save_buffer(png_ptr);
  189549. return;
  189550. }
  189551. png_push_crc_finish(png_ptr);
  189552. key = png_ptr->current_text;
  189553. for (text = key; *text; text++)
  189554. /* empty loop */ ;
  189555. /* zTXt can't have zero text */
  189556. if (text >= key + png_ptr->current_text_size)
  189557. {
  189558. png_ptr->current_text = NULL;
  189559. png_free(png_ptr, key);
  189560. return;
  189561. }
  189562. text++;
  189563. if (*text != PNG_TEXT_COMPRESSION_zTXt) /* check compression byte */
  189564. {
  189565. png_ptr->current_text = NULL;
  189566. png_free(png_ptr, key);
  189567. return;
  189568. }
  189569. text++;
  189570. png_ptr->zstream.next_in = (png_bytep )text;
  189571. png_ptr->zstream.avail_in = (uInt)(png_ptr->current_text_size -
  189572. (text - key));
  189573. png_ptr->zstream.next_out = png_ptr->zbuf;
  189574. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  189575. key_size = text - key;
  189576. text_size = 0;
  189577. text = NULL;
  189578. ret = Z_STREAM_END;
  189579. while (png_ptr->zstream.avail_in)
  189580. {
  189581. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  189582. if (ret != Z_OK && ret != Z_STREAM_END)
  189583. {
  189584. inflateReset(&png_ptr->zstream);
  189585. png_ptr->zstream.avail_in = 0;
  189586. png_ptr->current_text = NULL;
  189587. png_free(png_ptr, key);
  189588. png_free(png_ptr, text);
  189589. return;
  189590. }
  189591. if (!(png_ptr->zstream.avail_out) || ret == Z_STREAM_END)
  189592. {
  189593. if (text == NULL)
  189594. {
  189595. text = (png_charp)png_malloc(png_ptr,
  189596. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  189597. + key_size + 1));
  189598. png_memcpy(text + key_size, png_ptr->zbuf,
  189599. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  189600. png_memcpy(text, key, key_size);
  189601. text_size = key_size + png_ptr->zbuf_size -
  189602. png_ptr->zstream.avail_out;
  189603. *(text + text_size) = '\0';
  189604. }
  189605. else
  189606. {
  189607. png_charp tmp;
  189608. tmp = text;
  189609. text = (png_charp)png_malloc(png_ptr, text_size +
  189610. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  189611. + 1));
  189612. png_memcpy(text, tmp, text_size);
  189613. png_free(png_ptr, tmp);
  189614. png_memcpy(text + text_size, png_ptr->zbuf,
  189615. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  189616. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  189617. *(text + text_size) = '\0';
  189618. }
  189619. if (ret != Z_STREAM_END)
  189620. {
  189621. png_ptr->zstream.next_out = png_ptr->zbuf;
  189622. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  189623. }
  189624. }
  189625. else
  189626. {
  189627. break;
  189628. }
  189629. if (ret == Z_STREAM_END)
  189630. break;
  189631. }
  189632. inflateReset(&png_ptr->zstream);
  189633. png_ptr->zstream.avail_in = 0;
  189634. if (ret != Z_STREAM_END)
  189635. {
  189636. png_ptr->current_text = NULL;
  189637. png_free(png_ptr, key);
  189638. png_free(png_ptr, text);
  189639. return;
  189640. }
  189641. png_ptr->current_text = NULL;
  189642. png_free(png_ptr, key);
  189643. key = text;
  189644. text += key_size;
  189645. text_ptr = (png_textp)png_malloc(png_ptr,
  189646. (png_uint_32)png_sizeof(png_text));
  189647. text_ptr->compression = PNG_TEXT_COMPRESSION_zTXt;
  189648. text_ptr->key = key;
  189649. #ifdef PNG_iTXt_SUPPORTED
  189650. text_ptr->lang = NULL;
  189651. text_ptr->lang_key = NULL;
  189652. #endif
  189653. text_ptr->text = text;
  189654. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189655. png_free(png_ptr, key);
  189656. png_free(png_ptr, text_ptr);
  189657. if (ret)
  189658. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  189659. }
  189660. }
  189661. #endif
  189662. #if defined(PNG_READ_iTXt_SUPPORTED)
  189663. void /* PRIVATE */
  189664. png_push_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189665. length)
  189666. {
  189667. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189668. {
  189669. png_error(png_ptr, "Out of place iTXt");
  189670. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189671. }
  189672. #ifdef PNG_MAX_MALLOC_64K
  189673. png_ptr->skip_length = 0; /* This may not be necessary */
  189674. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  189675. {
  189676. png_warning(png_ptr, "iTXt chunk too large to fit in memory");
  189677. png_ptr->skip_length = length - (png_uint_32)65535L;
  189678. length = (png_uint_32)65535L;
  189679. }
  189680. #endif
  189681. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189682. (png_uint_32)(length+1));
  189683. png_ptr->current_text[length] = '\0';
  189684. png_ptr->current_text_ptr = png_ptr->current_text;
  189685. png_ptr->current_text_size = (png_size_t)length;
  189686. png_ptr->current_text_left = (png_size_t)length;
  189687. png_ptr->process_mode = PNG_READ_iTXt_MODE;
  189688. }
  189689. void /* PRIVATE */
  189690. png_push_read_iTXt(png_structp png_ptr, png_infop info_ptr)
  189691. {
  189692. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189693. {
  189694. png_size_t text_size;
  189695. if (png_ptr->buffer_size < png_ptr->current_text_left)
  189696. text_size = png_ptr->buffer_size;
  189697. else
  189698. text_size = png_ptr->current_text_left;
  189699. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189700. png_ptr->current_text_left -= text_size;
  189701. png_ptr->current_text_ptr += text_size;
  189702. }
  189703. if (!(png_ptr->current_text_left))
  189704. {
  189705. png_textp text_ptr;
  189706. png_charp key;
  189707. int comp_flag;
  189708. png_charp lang;
  189709. png_charp lang_key;
  189710. png_charp text;
  189711. int ret;
  189712. if (png_ptr->buffer_size < 4)
  189713. {
  189714. png_push_save_buffer(png_ptr);
  189715. return;
  189716. }
  189717. png_push_crc_finish(png_ptr);
  189718. #if defined(PNG_MAX_MALLOC_64K)
  189719. if (png_ptr->skip_length)
  189720. return;
  189721. #endif
  189722. key = png_ptr->current_text;
  189723. for (lang = key; *lang; lang++)
  189724. /* empty loop */ ;
  189725. if (lang < key + png_ptr->current_text_size - 3)
  189726. lang++;
  189727. comp_flag = *lang++;
  189728. lang++; /* skip comp_type, always zero */
  189729. for (lang_key = lang; *lang_key; lang_key++)
  189730. /* empty loop */ ;
  189731. lang_key++; /* skip NUL separator */
  189732. text=lang_key;
  189733. if (lang_key < key + png_ptr->current_text_size - 1)
  189734. {
  189735. for (; *text; text++)
  189736. /* empty loop */ ;
  189737. }
  189738. if (text < key + png_ptr->current_text_size)
  189739. text++;
  189740. text_ptr = (png_textp)png_malloc(png_ptr,
  189741. (png_uint_32)png_sizeof(png_text));
  189742. text_ptr->compression = comp_flag + 2;
  189743. text_ptr->key = key;
  189744. text_ptr->lang = lang;
  189745. text_ptr->lang_key = lang_key;
  189746. text_ptr->text = text;
  189747. text_ptr->text_length = 0;
  189748. text_ptr->itxt_length = png_strlen(text);
  189749. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189750. png_ptr->current_text = NULL;
  189751. png_free(png_ptr, text_ptr);
  189752. if (ret)
  189753. png_warning(png_ptr, "Insufficient memory to store iTXt chunk.");
  189754. }
  189755. }
  189756. #endif
  189757. /* This function is called when we haven't found a handler for this
  189758. * chunk. If there isn't a problem with the chunk itself (ie a bad chunk
  189759. * name or a critical chunk), the chunk is (currently) silently ignored.
  189760. */
  189761. void /* PRIVATE */
  189762. png_push_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189763. length)
  189764. {
  189765. png_uint_32 skip=0;
  189766. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  189767. if (!(png_ptr->chunk_name[0] & 0x20))
  189768. {
  189769. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  189770. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  189771. PNG_HANDLE_CHUNK_ALWAYS
  189772. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189773. && png_ptr->read_user_chunk_fn == NULL
  189774. #endif
  189775. )
  189776. #endif
  189777. png_chunk_error(png_ptr, "unknown critical chunk");
  189778. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189779. }
  189780. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  189781. if (png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS)
  189782. {
  189783. #ifdef PNG_MAX_MALLOC_64K
  189784. if (length > (png_uint_32)65535L)
  189785. {
  189786. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  189787. skip = length - (png_uint_32)65535L;
  189788. length = (png_uint_32)65535L;
  189789. }
  189790. #endif
  189791. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  189792. (png_charp)png_ptr->chunk_name, 5);
  189793. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  189794. png_ptr->unknown_chunk.size = (png_size_t)length;
  189795. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  189796. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189797. if(png_ptr->read_user_chunk_fn != NULL)
  189798. {
  189799. /* callback to user unknown chunk handler */
  189800. int ret;
  189801. ret = (*(png_ptr->read_user_chunk_fn))
  189802. (png_ptr, &png_ptr->unknown_chunk);
  189803. if (ret < 0)
  189804. png_chunk_error(png_ptr, "error in user chunk");
  189805. if (ret == 0)
  189806. {
  189807. if (!(png_ptr->chunk_name[0] & 0x20))
  189808. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  189809. PNG_HANDLE_CHUNK_ALWAYS)
  189810. png_chunk_error(png_ptr, "unknown critical chunk");
  189811. png_set_unknown_chunks(png_ptr, info_ptr,
  189812. &png_ptr->unknown_chunk, 1);
  189813. }
  189814. }
  189815. #else
  189816. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  189817. #endif
  189818. png_free(png_ptr, png_ptr->unknown_chunk.data);
  189819. png_ptr->unknown_chunk.data = NULL;
  189820. }
  189821. else
  189822. #endif
  189823. skip=length;
  189824. png_push_crc_skip(png_ptr, skip);
  189825. }
  189826. void /* PRIVATE */
  189827. png_push_have_info(png_structp png_ptr, png_infop info_ptr)
  189828. {
  189829. if (png_ptr->info_fn != NULL)
  189830. (*(png_ptr->info_fn))(png_ptr, info_ptr);
  189831. }
  189832. void /* PRIVATE */
  189833. png_push_have_end(png_structp png_ptr, png_infop info_ptr)
  189834. {
  189835. if (png_ptr->end_fn != NULL)
  189836. (*(png_ptr->end_fn))(png_ptr, info_ptr);
  189837. }
  189838. void /* PRIVATE */
  189839. png_push_have_row(png_structp png_ptr, png_bytep row)
  189840. {
  189841. if (png_ptr->row_fn != NULL)
  189842. (*(png_ptr->row_fn))(png_ptr, row, png_ptr->row_number,
  189843. (int)png_ptr->pass);
  189844. }
  189845. void PNGAPI
  189846. png_progressive_combine_row (png_structp png_ptr,
  189847. png_bytep old_row, png_bytep new_row)
  189848. {
  189849. #ifdef PNG_USE_LOCAL_ARRAYS
  189850. PNG_CONST int FARDATA png_pass_dsp_mask[7] =
  189851. {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  189852. #endif
  189853. if(png_ptr == NULL) return;
  189854. if (new_row != NULL) /* new_row must == png_ptr->row_buf here. */
  189855. png_combine_row(png_ptr, old_row, png_pass_dsp_mask[png_ptr->pass]);
  189856. }
  189857. void PNGAPI
  189858. png_set_progressive_read_fn(png_structp png_ptr, png_voidp progressive_ptr,
  189859. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  189860. png_progressive_end_ptr end_fn)
  189861. {
  189862. if(png_ptr == NULL) return;
  189863. png_ptr->info_fn = info_fn;
  189864. png_ptr->row_fn = row_fn;
  189865. png_ptr->end_fn = end_fn;
  189866. png_set_read_fn(png_ptr, progressive_ptr, png_push_fill_buffer);
  189867. }
  189868. png_voidp PNGAPI
  189869. png_get_progressive_ptr(png_structp png_ptr)
  189870. {
  189871. if(png_ptr == NULL) return (NULL);
  189872. return png_ptr->io_ptr;
  189873. }
  189874. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  189875. /*** End of inlined file: pngpread.c ***/
  189876. /*** Start of inlined file: pngrio.c ***/
  189877. /* pngrio.c - functions for data input
  189878. *
  189879. * Last changed in libpng 1.2.13 November 13, 2006
  189880. * For conditions of distribution and use, see copyright notice in png.h
  189881. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  189882. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  189883. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  189884. *
  189885. * This file provides a location for all input. Users who need
  189886. * special handling are expected to write a function that has the same
  189887. * arguments as this and performs a similar function, but that possibly
  189888. * has a different input method. Note that you shouldn't change this
  189889. * function, but rather write a replacement function and then make
  189890. * libpng use it at run time with png_set_read_fn(...).
  189891. */
  189892. #define PNG_INTERNAL
  189893. #if defined(PNG_READ_SUPPORTED)
  189894. /* Read the data from whatever input you are using. The default routine
  189895. reads from a file pointer. Note that this routine sometimes gets called
  189896. with very small lengths, so you should implement some kind of simple
  189897. buffering if you are using unbuffered reads. This should never be asked
  189898. to read more then 64K on a 16 bit machine. */
  189899. void /* PRIVATE */
  189900. png_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  189901. {
  189902. png_debug1(4,"reading %d bytes\n", (int)length);
  189903. if (png_ptr->read_data_fn != NULL)
  189904. (*(png_ptr->read_data_fn))(png_ptr, data, length);
  189905. else
  189906. png_error(png_ptr, "Call to NULL read function");
  189907. }
  189908. #if !defined(PNG_NO_STDIO)
  189909. /* This is the function that does the actual reading of data. If you are
  189910. not reading from a standard C stream, you should create a replacement
  189911. read_data function and use it at run time with png_set_read_fn(), rather
  189912. than changing the library. */
  189913. #ifndef USE_FAR_KEYWORD
  189914. void PNGAPI
  189915. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  189916. {
  189917. png_size_t check;
  189918. if(png_ptr == NULL) return;
  189919. /* fread() returns 0 on error, so it is OK to store this in a png_size_t
  189920. * instead of an int, which is what fread() actually returns.
  189921. */
  189922. #if defined(_WIN32_WCE)
  189923. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  189924. check = 0;
  189925. #else
  189926. check = (png_size_t)fread(data, (png_size_t)1, length,
  189927. (png_FILE_p)png_ptr->io_ptr);
  189928. #endif
  189929. if (check != length)
  189930. png_error(png_ptr, "Read Error");
  189931. }
  189932. #else
  189933. /* this is the model-independent version. Since the standard I/O library
  189934. can't handle far buffers in the medium and small models, we have to copy
  189935. the data.
  189936. */
  189937. #define NEAR_BUF_SIZE 1024
  189938. #define MIN(a,b) (a <= b ? a : b)
  189939. static void PNGAPI
  189940. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  189941. {
  189942. int check;
  189943. png_byte *n_data;
  189944. png_FILE_p io_ptr;
  189945. if(png_ptr == NULL) return;
  189946. /* Check if data really is near. If so, use usual code. */
  189947. n_data = (png_byte *)CVT_PTR_NOCHECK(data);
  189948. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  189949. if ((png_bytep)n_data == data)
  189950. {
  189951. #if defined(_WIN32_WCE)
  189952. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  189953. check = 0;
  189954. #else
  189955. check = fread(n_data, 1, length, io_ptr);
  189956. #endif
  189957. }
  189958. else
  189959. {
  189960. png_byte buf[NEAR_BUF_SIZE];
  189961. png_size_t read, remaining, err;
  189962. check = 0;
  189963. remaining = length;
  189964. do
  189965. {
  189966. read = MIN(NEAR_BUF_SIZE, remaining);
  189967. #if defined(_WIN32_WCE)
  189968. if ( !ReadFile((HANDLE)(io_ptr), buf, read, &err, NULL) )
  189969. err = 0;
  189970. #else
  189971. err = fread(buf, (png_size_t)1, read, io_ptr);
  189972. #endif
  189973. png_memcpy(data, buf, read); /* copy far buffer to near buffer */
  189974. if(err != read)
  189975. break;
  189976. else
  189977. check += err;
  189978. data += read;
  189979. remaining -= read;
  189980. }
  189981. while (remaining != 0);
  189982. }
  189983. if ((png_uint_32)check != (png_uint_32)length)
  189984. png_error(png_ptr, "read Error");
  189985. }
  189986. #endif
  189987. #endif
  189988. /* This function allows the application to supply a new input function
  189989. for libpng if standard C streams aren't being used.
  189990. This function takes as its arguments:
  189991. png_ptr - pointer to a png input data structure
  189992. io_ptr - pointer to user supplied structure containing info about
  189993. the input functions. May be NULL.
  189994. read_data_fn - pointer to a new input function that takes as its
  189995. arguments a pointer to a png_struct, a pointer to
  189996. a location where input data can be stored, and a 32-bit
  189997. unsigned int that is the number of bytes to be read.
  189998. To exit and output any fatal error messages the new write
  189999. function should call png_error(png_ptr, "Error msg"). */
  190000. void PNGAPI
  190001. png_set_read_fn(png_structp png_ptr, png_voidp io_ptr,
  190002. png_rw_ptr read_data_fn)
  190003. {
  190004. if(png_ptr == NULL) return;
  190005. png_ptr->io_ptr = io_ptr;
  190006. #if !defined(PNG_NO_STDIO)
  190007. if (read_data_fn != NULL)
  190008. png_ptr->read_data_fn = read_data_fn;
  190009. else
  190010. png_ptr->read_data_fn = png_default_read_data;
  190011. #else
  190012. png_ptr->read_data_fn = read_data_fn;
  190013. #endif
  190014. /* It is an error to write to a read device */
  190015. if (png_ptr->write_data_fn != NULL)
  190016. {
  190017. png_ptr->write_data_fn = NULL;
  190018. png_warning(png_ptr,
  190019. "It's an error to set both read_data_fn and write_data_fn in the ");
  190020. png_warning(png_ptr,
  190021. "same structure. Resetting write_data_fn to NULL.");
  190022. }
  190023. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  190024. png_ptr->output_flush_fn = NULL;
  190025. #endif
  190026. }
  190027. #endif /* PNG_READ_SUPPORTED */
  190028. /*** End of inlined file: pngrio.c ***/
  190029. /*** Start of inlined file: pngrtran.c ***/
  190030. /* pngrtran.c - transforms the data in a row for PNG readers
  190031. *
  190032. * Last changed in libpng 1.2.21 [October 4, 2007]
  190033. * For conditions of distribution and use, see copyright notice in png.h
  190034. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  190035. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  190036. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  190037. *
  190038. * This file contains functions optionally called by an application
  190039. * in order to tell libpng how to handle data when reading a PNG.
  190040. * Transformations that are used in both reading and writing are
  190041. * in pngtrans.c.
  190042. */
  190043. #define PNG_INTERNAL
  190044. #if defined(PNG_READ_SUPPORTED)
  190045. /* Set the action on getting a CRC error for an ancillary or critical chunk. */
  190046. void PNGAPI
  190047. png_set_crc_action(png_structp png_ptr, int crit_action, int ancil_action)
  190048. {
  190049. png_debug(1, "in png_set_crc_action\n");
  190050. /* Tell libpng how we react to CRC errors in critical chunks */
  190051. if(png_ptr == NULL) return;
  190052. switch (crit_action)
  190053. {
  190054. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  190055. break;
  190056. case PNG_CRC_WARN_USE: /* warn/use data */
  190057. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  190058. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE;
  190059. break;
  190060. case PNG_CRC_QUIET_USE: /* quiet/use data */
  190061. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  190062. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE |
  190063. PNG_FLAG_CRC_CRITICAL_IGNORE;
  190064. break;
  190065. case PNG_CRC_WARN_DISCARD: /* not a valid action for critical data */
  190066. png_warning(png_ptr, "Can't discard critical data on CRC error.");
  190067. case PNG_CRC_ERROR_QUIT: /* error/quit */
  190068. case PNG_CRC_DEFAULT:
  190069. default:
  190070. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  190071. break;
  190072. }
  190073. switch (ancil_action)
  190074. {
  190075. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  190076. break;
  190077. case PNG_CRC_WARN_USE: /* warn/use data */
  190078. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  190079. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE;
  190080. break;
  190081. case PNG_CRC_QUIET_USE: /* quiet/use data */
  190082. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  190083. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE |
  190084. PNG_FLAG_CRC_ANCILLARY_NOWARN;
  190085. break;
  190086. case PNG_CRC_ERROR_QUIT: /* error/quit */
  190087. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  190088. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_NOWARN;
  190089. break;
  190090. case PNG_CRC_WARN_DISCARD: /* warn/discard data */
  190091. case PNG_CRC_DEFAULT:
  190092. default:
  190093. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  190094. break;
  190095. }
  190096. }
  190097. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  190098. defined(PNG_FLOATING_POINT_SUPPORTED)
  190099. /* handle alpha and tRNS via a background color */
  190100. void PNGAPI
  190101. png_set_background(png_structp png_ptr,
  190102. png_color_16p background_color, int background_gamma_code,
  190103. int need_expand, double background_gamma)
  190104. {
  190105. png_debug(1, "in png_set_background\n");
  190106. if(png_ptr == NULL) return;
  190107. if (background_gamma_code == PNG_BACKGROUND_GAMMA_UNKNOWN)
  190108. {
  190109. png_warning(png_ptr, "Application must supply a known background gamma");
  190110. return;
  190111. }
  190112. png_ptr->transformations |= PNG_BACKGROUND;
  190113. png_memcpy(&(png_ptr->background), background_color,
  190114. png_sizeof(png_color_16));
  190115. png_ptr->background_gamma = (float)background_gamma;
  190116. png_ptr->background_gamma_type = (png_byte)(background_gamma_code);
  190117. png_ptr->transformations |= (need_expand ? PNG_BACKGROUND_EXPAND : 0);
  190118. }
  190119. #endif
  190120. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  190121. /* strip 16 bit depth files to 8 bit depth */
  190122. void PNGAPI
  190123. png_set_strip_16(png_structp png_ptr)
  190124. {
  190125. png_debug(1, "in png_set_strip_16\n");
  190126. if(png_ptr == NULL) return;
  190127. png_ptr->transformations |= PNG_16_TO_8;
  190128. }
  190129. #endif
  190130. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  190131. void PNGAPI
  190132. png_set_strip_alpha(png_structp png_ptr)
  190133. {
  190134. png_debug(1, "in png_set_strip_alpha\n");
  190135. if(png_ptr == NULL) return;
  190136. png_ptr->flags |= PNG_FLAG_STRIP_ALPHA;
  190137. }
  190138. #endif
  190139. #if defined(PNG_READ_DITHER_SUPPORTED)
  190140. /* Dither file to 8 bit. Supply a palette, the current number
  190141. * of elements in the palette, the maximum number of elements
  190142. * allowed, and a histogram if possible. If the current number
  190143. * of colors is greater then the maximum number, the palette will be
  190144. * modified to fit in the maximum number. "full_dither" indicates
  190145. * whether we need a dithering cube set up for RGB images, or if we
  190146. * simply are reducing the number of colors in a paletted image.
  190147. */
  190148. typedef struct png_dsort_struct
  190149. {
  190150. struct png_dsort_struct FAR * next;
  190151. png_byte left;
  190152. png_byte right;
  190153. } png_dsort;
  190154. typedef png_dsort FAR * png_dsortp;
  190155. typedef png_dsort FAR * FAR * png_dsortpp;
  190156. void PNGAPI
  190157. png_set_dither(png_structp png_ptr, png_colorp palette,
  190158. int num_palette, int maximum_colors, png_uint_16p histogram,
  190159. int full_dither)
  190160. {
  190161. png_debug(1, "in png_set_dither\n");
  190162. if(png_ptr == NULL) return;
  190163. png_ptr->transformations |= PNG_DITHER;
  190164. if (!full_dither)
  190165. {
  190166. int i;
  190167. png_ptr->dither_index = (png_bytep)png_malloc(png_ptr,
  190168. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190169. for (i = 0; i < num_palette; i++)
  190170. png_ptr->dither_index[i] = (png_byte)i;
  190171. }
  190172. if (num_palette > maximum_colors)
  190173. {
  190174. if (histogram != NULL)
  190175. {
  190176. /* This is easy enough, just throw out the least used colors.
  190177. Perhaps not the best solution, but good enough. */
  190178. int i;
  190179. /* initialize an array to sort colors */
  190180. png_ptr->dither_sort = (png_bytep)png_malloc(png_ptr,
  190181. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190182. /* initialize the dither_sort array */
  190183. for (i = 0; i < num_palette; i++)
  190184. png_ptr->dither_sort[i] = (png_byte)i;
  190185. /* Find the least used palette entries by starting a
  190186. bubble sort, and running it until we have sorted
  190187. out enough colors. Note that we don't care about
  190188. sorting all the colors, just finding which are
  190189. least used. */
  190190. for (i = num_palette - 1; i >= maximum_colors; i--)
  190191. {
  190192. int done; /* to stop early if the list is pre-sorted */
  190193. int j;
  190194. done = 1;
  190195. for (j = 0; j < i; j++)
  190196. {
  190197. if (histogram[png_ptr->dither_sort[j]]
  190198. < histogram[png_ptr->dither_sort[j + 1]])
  190199. {
  190200. png_byte t;
  190201. t = png_ptr->dither_sort[j];
  190202. png_ptr->dither_sort[j] = png_ptr->dither_sort[j + 1];
  190203. png_ptr->dither_sort[j + 1] = t;
  190204. done = 0;
  190205. }
  190206. }
  190207. if (done)
  190208. break;
  190209. }
  190210. /* swap the palette around, and set up a table, if necessary */
  190211. if (full_dither)
  190212. {
  190213. int j = num_palette;
  190214. /* put all the useful colors within the max, but don't
  190215. move the others */
  190216. for (i = 0; i < maximum_colors; i++)
  190217. {
  190218. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  190219. {
  190220. do
  190221. j--;
  190222. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  190223. palette[i] = palette[j];
  190224. }
  190225. }
  190226. }
  190227. else
  190228. {
  190229. int j = num_palette;
  190230. /* move all the used colors inside the max limit, and
  190231. develop a translation table */
  190232. for (i = 0; i < maximum_colors; i++)
  190233. {
  190234. /* only move the colors we need to */
  190235. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  190236. {
  190237. png_color tmp_color;
  190238. do
  190239. j--;
  190240. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  190241. tmp_color = palette[j];
  190242. palette[j] = palette[i];
  190243. palette[i] = tmp_color;
  190244. /* indicate where the color went */
  190245. png_ptr->dither_index[j] = (png_byte)i;
  190246. png_ptr->dither_index[i] = (png_byte)j;
  190247. }
  190248. }
  190249. /* find closest color for those colors we are not using */
  190250. for (i = 0; i < num_palette; i++)
  190251. {
  190252. if ((int)png_ptr->dither_index[i] >= maximum_colors)
  190253. {
  190254. int min_d, k, min_k, d_index;
  190255. /* find the closest color to one we threw out */
  190256. d_index = png_ptr->dither_index[i];
  190257. min_d = PNG_COLOR_DIST(palette[d_index], palette[0]);
  190258. for (k = 1, min_k = 0; k < maximum_colors; k++)
  190259. {
  190260. int d;
  190261. d = PNG_COLOR_DIST(palette[d_index], palette[k]);
  190262. if (d < min_d)
  190263. {
  190264. min_d = d;
  190265. min_k = k;
  190266. }
  190267. }
  190268. /* point to closest color */
  190269. png_ptr->dither_index[i] = (png_byte)min_k;
  190270. }
  190271. }
  190272. }
  190273. png_free(png_ptr, png_ptr->dither_sort);
  190274. png_ptr->dither_sort=NULL;
  190275. }
  190276. else
  190277. {
  190278. /* This is much harder to do simply (and quickly). Perhaps
  190279. we need to go through a median cut routine, but those
  190280. don't always behave themselves with only a few colors
  190281. as input. So we will just find the closest two colors,
  190282. and throw out one of them (chosen somewhat randomly).
  190283. [We don't understand this at all, so if someone wants to
  190284. work on improving it, be our guest - AED, GRP]
  190285. */
  190286. int i;
  190287. int max_d;
  190288. int num_new_palette;
  190289. png_dsortp t;
  190290. png_dsortpp hash;
  190291. t=NULL;
  190292. /* initialize palette index arrays */
  190293. png_ptr->index_to_palette = (png_bytep)png_malloc(png_ptr,
  190294. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190295. png_ptr->palette_to_index = (png_bytep)png_malloc(png_ptr,
  190296. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190297. /* initialize the sort array */
  190298. for (i = 0; i < num_palette; i++)
  190299. {
  190300. png_ptr->index_to_palette[i] = (png_byte)i;
  190301. png_ptr->palette_to_index[i] = (png_byte)i;
  190302. }
  190303. hash = (png_dsortpp)png_malloc(png_ptr, (png_uint_32)(769 *
  190304. png_sizeof (png_dsortp)));
  190305. for (i = 0; i < 769; i++)
  190306. hash[i] = NULL;
  190307. /* png_memset(hash, 0, 769 * png_sizeof (png_dsortp)); */
  190308. num_new_palette = num_palette;
  190309. /* initial wild guess at how far apart the farthest pixel
  190310. pair we will be eliminating will be. Larger
  190311. numbers mean more areas will be allocated, Smaller
  190312. numbers run the risk of not saving enough data, and
  190313. having to do this all over again.
  190314. I have not done extensive checking on this number.
  190315. */
  190316. max_d = 96;
  190317. while (num_new_palette > maximum_colors)
  190318. {
  190319. for (i = 0; i < num_new_palette - 1; i++)
  190320. {
  190321. int j;
  190322. for (j = i + 1; j < num_new_palette; j++)
  190323. {
  190324. int d;
  190325. d = PNG_COLOR_DIST(palette[i], palette[j]);
  190326. if (d <= max_d)
  190327. {
  190328. t = (png_dsortp)png_malloc_warn(png_ptr,
  190329. (png_uint_32)(png_sizeof(png_dsort)));
  190330. if (t == NULL)
  190331. break;
  190332. t->next = hash[d];
  190333. t->left = (png_byte)i;
  190334. t->right = (png_byte)j;
  190335. hash[d] = t;
  190336. }
  190337. }
  190338. if (t == NULL)
  190339. break;
  190340. }
  190341. if (t != NULL)
  190342. for (i = 0; i <= max_d; i++)
  190343. {
  190344. if (hash[i] != NULL)
  190345. {
  190346. png_dsortp p;
  190347. for (p = hash[i]; p; p = p->next)
  190348. {
  190349. if ((int)png_ptr->index_to_palette[p->left]
  190350. < num_new_palette &&
  190351. (int)png_ptr->index_to_palette[p->right]
  190352. < num_new_palette)
  190353. {
  190354. int j, next_j;
  190355. if (num_new_palette & 0x01)
  190356. {
  190357. j = p->left;
  190358. next_j = p->right;
  190359. }
  190360. else
  190361. {
  190362. j = p->right;
  190363. next_j = p->left;
  190364. }
  190365. num_new_palette--;
  190366. palette[png_ptr->index_to_palette[j]]
  190367. = palette[num_new_palette];
  190368. if (!full_dither)
  190369. {
  190370. int k;
  190371. for (k = 0; k < num_palette; k++)
  190372. {
  190373. if (png_ptr->dither_index[k] ==
  190374. png_ptr->index_to_palette[j])
  190375. png_ptr->dither_index[k] =
  190376. png_ptr->index_to_palette[next_j];
  190377. if ((int)png_ptr->dither_index[k] ==
  190378. num_new_palette)
  190379. png_ptr->dither_index[k] =
  190380. png_ptr->index_to_palette[j];
  190381. }
  190382. }
  190383. png_ptr->index_to_palette[png_ptr->palette_to_index
  190384. [num_new_palette]] = png_ptr->index_to_palette[j];
  190385. png_ptr->palette_to_index[png_ptr->index_to_palette[j]]
  190386. = png_ptr->palette_to_index[num_new_palette];
  190387. png_ptr->index_to_palette[j] = (png_byte)num_new_palette;
  190388. png_ptr->palette_to_index[num_new_palette] = (png_byte)j;
  190389. }
  190390. if (num_new_palette <= maximum_colors)
  190391. break;
  190392. }
  190393. if (num_new_palette <= maximum_colors)
  190394. break;
  190395. }
  190396. }
  190397. for (i = 0; i < 769; i++)
  190398. {
  190399. if (hash[i] != NULL)
  190400. {
  190401. png_dsortp p = hash[i];
  190402. while (p)
  190403. {
  190404. t = p->next;
  190405. png_free(png_ptr, p);
  190406. p = t;
  190407. }
  190408. }
  190409. hash[i] = 0;
  190410. }
  190411. max_d += 96;
  190412. }
  190413. png_free(png_ptr, hash);
  190414. png_free(png_ptr, png_ptr->palette_to_index);
  190415. png_free(png_ptr, png_ptr->index_to_palette);
  190416. png_ptr->palette_to_index=NULL;
  190417. png_ptr->index_to_palette=NULL;
  190418. }
  190419. num_palette = maximum_colors;
  190420. }
  190421. if (png_ptr->palette == NULL)
  190422. {
  190423. png_ptr->palette = palette;
  190424. }
  190425. png_ptr->num_palette = (png_uint_16)num_palette;
  190426. if (full_dither)
  190427. {
  190428. int i;
  190429. png_bytep distance;
  190430. int total_bits = PNG_DITHER_RED_BITS + PNG_DITHER_GREEN_BITS +
  190431. PNG_DITHER_BLUE_BITS;
  190432. int num_red = (1 << PNG_DITHER_RED_BITS);
  190433. int num_green = (1 << PNG_DITHER_GREEN_BITS);
  190434. int num_blue = (1 << PNG_DITHER_BLUE_BITS);
  190435. png_size_t num_entries = ((png_size_t)1 << total_bits);
  190436. png_ptr->palette_lookup = (png_bytep )png_malloc(png_ptr,
  190437. (png_uint_32)(num_entries * png_sizeof (png_byte)));
  190438. png_memset(png_ptr->palette_lookup, 0, num_entries *
  190439. png_sizeof (png_byte));
  190440. distance = (png_bytep)png_malloc(png_ptr, (png_uint_32)(num_entries *
  190441. png_sizeof(png_byte)));
  190442. png_memset(distance, 0xff, num_entries * png_sizeof(png_byte));
  190443. for (i = 0; i < num_palette; i++)
  190444. {
  190445. int ir, ig, ib;
  190446. int r = (palette[i].red >> (8 - PNG_DITHER_RED_BITS));
  190447. int g = (palette[i].green >> (8 - PNG_DITHER_GREEN_BITS));
  190448. int b = (palette[i].blue >> (8 - PNG_DITHER_BLUE_BITS));
  190449. for (ir = 0; ir < num_red; ir++)
  190450. {
  190451. /* int dr = abs(ir - r); */
  190452. int dr = ((ir > r) ? ir - r : r - ir);
  190453. int index_r = (ir << (PNG_DITHER_BLUE_BITS + PNG_DITHER_GREEN_BITS));
  190454. for (ig = 0; ig < num_green; ig++)
  190455. {
  190456. /* int dg = abs(ig - g); */
  190457. int dg = ((ig > g) ? ig - g : g - ig);
  190458. int dt = dr + dg;
  190459. int dm = ((dr > dg) ? dr : dg);
  190460. int index_g = index_r | (ig << PNG_DITHER_BLUE_BITS);
  190461. for (ib = 0; ib < num_blue; ib++)
  190462. {
  190463. int d_index = index_g | ib;
  190464. /* int db = abs(ib - b); */
  190465. int db = ((ib > b) ? ib - b : b - ib);
  190466. int dmax = ((dm > db) ? dm : db);
  190467. int d = dmax + dt + db;
  190468. if (d < (int)distance[d_index])
  190469. {
  190470. distance[d_index] = (png_byte)d;
  190471. png_ptr->palette_lookup[d_index] = (png_byte)i;
  190472. }
  190473. }
  190474. }
  190475. }
  190476. }
  190477. png_free(png_ptr, distance);
  190478. }
  190479. }
  190480. #endif
  190481. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  190482. /* Transform the image from the file_gamma to the screen_gamma. We
  190483. * only do transformations on images where the file_gamma and screen_gamma
  190484. * are not close reciprocals, otherwise it slows things down slightly, and
  190485. * also needlessly introduces small errors.
  190486. *
  190487. * We will turn off gamma transformation later if no semitransparent entries
  190488. * are present in the tRNS array for palette images. We can't do it here
  190489. * because we don't necessarily have the tRNS chunk yet.
  190490. */
  190491. void PNGAPI
  190492. png_set_gamma(png_structp png_ptr, double scrn_gamma, double file_gamma)
  190493. {
  190494. png_debug(1, "in png_set_gamma\n");
  190495. if(png_ptr == NULL) return;
  190496. if ((fabs(scrn_gamma * file_gamma - 1.0) > PNG_GAMMA_THRESHOLD) ||
  190497. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA) ||
  190498. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE))
  190499. png_ptr->transformations |= PNG_GAMMA;
  190500. png_ptr->gamma = (float)file_gamma;
  190501. png_ptr->screen_gamma = (float)scrn_gamma;
  190502. }
  190503. #endif
  190504. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190505. /* Expand paletted images to RGB, expand grayscale images of
  190506. * less than 8-bit depth to 8-bit depth, and expand tRNS chunks
  190507. * to alpha channels.
  190508. */
  190509. void PNGAPI
  190510. png_set_expand(png_structp png_ptr)
  190511. {
  190512. png_debug(1, "in png_set_expand\n");
  190513. if(png_ptr == NULL) return;
  190514. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190515. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190516. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190517. #endif
  190518. }
  190519. /* GRR 19990627: the following three functions currently are identical
  190520. * to png_set_expand(). However, it is entirely reasonable that someone
  190521. * might wish to expand an indexed image to RGB but *not* expand a single,
  190522. * fully transparent palette entry to a full alpha channel--perhaps instead
  190523. * convert tRNS to the grayscale/RGB format (16-bit RGB value), or replace
  190524. * the transparent color with a particular RGB value, or drop tRNS entirely.
  190525. * IOW, a future version of the library may make the transformations flag
  190526. * a bit more fine-grained, with separate bits for each of these three
  190527. * functions.
  190528. *
  190529. * More to the point, these functions make it obvious what libpng will be
  190530. * doing, whereas "expand" can (and does) mean any number of things.
  190531. *
  190532. * GRP 20060307: In libpng-1.4.0, png_set_gray_1_2_4_to_8() was modified
  190533. * to expand only the sample depth but not to expand the tRNS to alpha.
  190534. */
  190535. /* Expand paletted images to RGB. */
  190536. void PNGAPI
  190537. png_set_palette_to_rgb(png_structp png_ptr)
  190538. {
  190539. png_debug(1, "in png_set_palette_to_rgb\n");
  190540. if(png_ptr == NULL) return;
  190541. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190542. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190543. png_ptr->flags &= !(PNG_FLAG_ROW_INIT);
  190544. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190545. #endif
  190546. }
  190547. #if !defined(PNG_1_0_X)
  190548. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  190549. void PNGAPI
  190550. png_set_expand_gray_1_2_4_to_8(png_structp png_ptr)
  190551. {
  190552. png_debug(1, "in png_set_expand_gray_1_2_4_to_8\n");
  190553. if(png_ptr == NULL) return;
  190554. png_ptr->transformations |= PNG_EXPAND;
  190555. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190556. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190557. #endif
  190558. }
  190559. #endif
  190560. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  190561. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  190562. /* Deprecated as of libpng-1.2.9 */
  190563. void PNGAPI
  190564. png_set_gray_1_2_4_to_8(png_structp png_ptr)
  190565. {
  190566. png_debug(1, "in png_set_gray_1_2_4_to_8\n");
  190567. if(png_ptr == NULL) return;
  190568. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190569. }
  190570. #endif
  190571. /* Expand tRNS chunks to alpha channels. */
  190572. void PNGAPI
  190573. png_set_tRNS_to_alpha(png_structp png_ptr)
  190574. {
  190575. png_debug(1, "in png_set_tRNS_to_alpha\n");
  190576. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190577. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190578. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190579. #endif
  190580. }
  190581. #endif /* defined(PNG_READ_EXPAND_SUPPORTED) */
  190582. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190583. void PNGAPI
  190584. png_set_gray_to_rgb(png_structp png_ptr)
  190585. {
  190586. png_debug(1, "in png_set_gray_to_rgb\n");
  190587. png_ptr->transformations |= PNG_GRAY_TO_RGB;
  190588. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190589. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190590. #endif
  190591. }
  190592. #endif
  190593. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  190594. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  190595. /* Convert a RGB image to a grayscale of the same width. This allows us,
  190596. * for example, to convert a 24 bpp RGB image into an 8 bpp grayscale image.
  190597. */
  190598. void PNGAPI
  190599. png_set_rgb_to_gray(png_structp png_ptr, int error_action, double red,
  190600. double green)
  190601. {
  190602. int red_fixed = (int)((float)red*100000.0 + 0.5);
  190603. int green_fixed = (int)((float)green*100000.0 + 0.5);
  190604. if(png_ptr == NULL) return;
  190605. png_set_rgb_to_gray_fixed(png_ptr, error_action, red_fixed, green_fixed);
  190606. }
  190607. #endif
  190608. void PNGAPI
  190609. png_set_rgb_to_gray_fixed(png_structp png_ptr, int error_action,
  190610. png_fixed_point red, png_fixed_point green)
  190611. {
  190612. png_debug(1, "in png_set_rgb_to_gray\n");
  190613. if(png_ptr == NULL) return;
  190614. switch(error_action)
  190615. {
  190616. case 1: png_ptr->transformations |= PNG_RGB_TO_GRAY;
  190617. break;
  190618. case 2: png_ptr->transformations |= PNG_RGB_TO_GRAY_WARN;
  190619. break;
  190620. case 3: png_ptr->transformations |= PNG_RGB_TO_GRAY_ERR;
  190621. }
  190622. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190623. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190624. png_ptr->transformations |= PNG_EXPAND;
  190625. #else
  190626. {
  190627. png_warning(png_ptr, "Cannot do RGB_TO_GRAY without EXPAND_SUPPORTED.");
  190628. png_ptr->transformations &= ~PNG_RGB_TO_GRAY;
  190629. }
  190630. #endif
  190631. {
  190632. png_uint_16 red_int, green_int;
  190633. if(red < 0 || green < 0)
  190634. {
  190635. red_int = 6968; /* .212671 * 32768 + .5 */
  190636. green_int = 23434; /* .715160 * 32768 + .5 */
  190637. }
  190638. else if(red + green < 100000L)
  190639. {
  190640. red_int = (png_uint_16)(((png_uint_32)red*32768L)/100000L);
  190641. green_int = (png_uint_16)(((png_uint_32)green*32768L)/100000L);
  190642. }
  190643. else
  190644. {
  190645. png_warning(png_ptr, "ignoring out of range rgb_to_gray coefficients");
  190646. red_int = 6968;
  190647. green_int = 23434;
  190648. }
  190649. png_ptr->rgb_to_gray_red_coeff = red_int;
  190650. png_ptr->rgb_to_gray_green_coeff = green_int;
  190651. png_ptr->rgb_to_gray_blue_coeff = (png_uint_16)(32768-red_int-green_int);
  190652. }
  190653. }
  190654. #endif
  190655. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  190656. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  190657. defined(PNG_LEGACY_SUPPORTED)
  190658. void PNGAPI
  190659. png_set_read_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  190660. read_user_transform_fn)
  190661. {
  190662. png_debug(1, "in png_set_read_user_transform_fn\n");
  190663. if(png_ptr == NULL) return;
  190664. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  190665. png_ptr->transformations |= PNG_USER_TRANSFORM;
  190666. png_ptr->read_user_transform_fn = read_user_transform_fn;
  190667. #endif
  190668. #ifdef PNG_LEGACY_SUPPORTED
  190669. if(read_user_transform_fn)
  190670. png_warning(png_ptr,
  190671. "This version of libpng does not support user transforms");
  190672. #endif
  190673. }
  190674. #endif
  190675. /* Initialize everything needed for the read. This includes modifying
  190676. * the palette.
  190677. */
  190678. void /* PRIVATE */
  190679. png_init_read_transformations(png_structp png_ptr)
  190680. {
  190681. png_debug(1, "in png_init_read_transformations\n");
  190682. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190683. if(png_ptr != NULL)
  190684. #endif
  190685. {
  190686. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || defined(PNG_READ_SHIFT_SUPPORTED) \
  190687. || defined(PNG_READ_GAMMA_SUPPORTED)
  190688. int color_type = png_ptr->color_type;
  190689. #endif
  190690. #if defined(PNG_READ_EXPAND_SUPPORTED) && defined(PNG_READ_BACKGROUND_SUPPORTED)
  190691. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190692. /* Detect gray background and attempt to enable optimization
  190693. * for gray --> RGB case */
  190694. /* Note: if PNG_BACKGROUND_EXPAND is set and color_type is either RGB or
  190695. * RGB_ALPHA (in which case need_expand is superfluous anyway), the
  190696. * background color might actually be gray yet not be flagged as such.
  190697. * This is not a problem for the current code, which uses
  190698. * PNG_BACKGROUND_IS_GRAY only to decide when to do the
  190699. * png_do_gray_to_rgb() transformation.
  190700. */
  190701. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190702. !(color_type & PNG_COLOR_MASK_COLOR))
  190703. {
  190704. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  190705. } else if ((png_ptr->transformations & PNG_BACKGROUND) &&
  190706. !(png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190707. (png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  190708. png_ptr->background.red == png_ptr->background.green &&
  190709. png_ptr->background.red == png_ptr->background.blue)
  190710. {
  190711. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  190712. png_ptr->background.gray = png_ptr->background.red;
  190713. }
  190714. #endif
  190715. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190716. (png_ptr->transformations & PNG_EXPAND))
  190717. {
  190718. if (!(color_type & PNG_COLOR_MASK_COLOR)) /* i.e., GRAY or GRAY_ALPHA */
  190719. {
  190720. /* expand background and tRNS chunks */
  190721. switch (png_ptr->bit_depth)
  190722. {
  190723. case 1:
  190724. png_ptr->background.gray *= (png_uint_16)0xff;
  190725. png_ptr->background.red = png_ptr->background.green
  190726. = png_ptr->background.blue = png_ptr->background.gray;
  190727. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190728. {
  190729. png_ptr->trans_values.gray *= (png_uint_16)0xff;
  190730. png_ptr->trans_values.red = png_ptr->trans_values.green
  190731. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190732. }
  190733. break;
  190734. case 2:
  190735. png_ptr->background.gray *= (png_uint_16)0x55;
  190736. png_ptr->background.red = png_ptr->background.green
  190737. = png_ptr->background.blue = png_ptr->background.gray;
  190738. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190739. {
  190740. png_ptr->trans_values.gray *= (png_uint_16)0x55;
  190741. png_ptr->trans_values.red = png_ptr->trans_values.green
  190742. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190743. }
  190744. break;
  190745. case 4:
  190746. png_ptr->background.gray *= (png_uint_16)0x11;
  190747. png_ptr->background.red = png_ptr->background.green
  190748. = png_ptr->background.blue = png_ptr->background.gray;
  190749. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190750. {
  190751. png_ptr->trans_values.gray *= (png_uint_16)0x11;
  190752. png_ptr->trans_values.red = png_ptr->trans_values.green
  190753. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190754. }
  190755. break;
  190756. case 8:
  190757. case 16:
  190758. png_ptr->background.red = png_ptr->background.green
  190759. = png_ptr->background.blue = png_ptr->background.gray;
  190760. break;
  190761. }
  190762. }
  190763. else if (color_type == PNG_COLOR_TYPE_PALETTE)
  190764. {
  190765. png_ptr->background.red =
  190766. png_ptr->palette[png_ptr->background.index].red;
  190767. png_ptr->background.green =
  190768. png_ptr->palette[png_ptr->background.index].green;
  190769. png_ptr->background.blue =
  190770. png_ptr->palette[png_ptr->background.index].blue;
  190771. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  190772. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  190773. {
  190774. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190775. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190776. #endif
  190777. {
  190778. /* invert the alpha channel (in tRNS) unless the pixels are
  190779. going to be expanded, in which case leave it for later */
  190780. int i,istop;
  190781. istop=(int)png_ptr->num_trans;
  190782. for (i=0; i<istop; i++)
  190783. png_ptr->trans[i] = (png_byte)(255 - png_ptr->trans[i]);
  190784. }
  190785. }
  190786. #endif
  190787. }
  190788. }
  190789. #endif
  190790. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  190791. png_ptr->background_1 = png_ptr->background;
  190792. #endif
  190793. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  190794. if ((color_type == PNG_COLOR_TYPE_PALETTE && png_ptr->num_trans != 0)
  190795. && (fabs(png_ptr->screen_gamma * png_ptr->gamma - 1.0)
  190796. < PNG_GAMMA_THRESHOLD))
  190797. {
  190798. int i,k;
  190799. k=0;
  190800. for (i=0; i<png_ptr->num_trans; i++)
  190801. {
  190802. if (png_ptr->trans[i] != 0 && png_ptr->trans[i] != 0xff)
  190803. k=1; /* partial transparency is present */
  190804. }
  190805. if (k == 0)
  190806. png_ptr->transformations &= (~PNG_GAMMA);
  190807. }
  190808. if ((png_ptr->transformations & (PNG_GAMMA | PNG_RGB_TO_GRAY)) &&
  190809. png_ptr->gamma != 0.0)
  190810. {
  190811. png_build_gamma_table(png_ptr);
  190812. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190813. if (png_ptr->transformations & PNG_BACKGROUND)
  190814. {
  190815. if (color_type == PNG_COLOR_TYPE_PALETTE)
  190816. {
  190817. /* could skip if no transparency and
  190818. */
  190819. png_color back, back_1;
  190820. png_colorp palette = png_ptr->palette;
  190821. int num_palette = png_ptr->num_palette;
  190822. int i;
  190823. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  190824. {
  190825. back.red = png_ptr->gamma_table[png_ptr->background.red];
  190826. back.green = png_ptr->gamma_table[png_ptr->background.green];
  190827. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  190828. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  190829. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  190830. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  190831. }
  190832. else
  190833. {
  190834. double g, gs;
  190835. switch (png_ptr->background_gamma_type)
  190836. {
  190837. case PNG_BACKGROUND_GAMMA_SCREEN:
  190838. g = (png_ptr->screen_gamma);
  190839. gs = 1.0;
  190840. break;
  190841. case PNG_BACKGROUND_GAMMA_FILE:
  190842. g = 1.0 / (png_ptr->gamma);
  190843. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  190844. break;
  190845. case PNG_BACKGROUND_GAMMA_UNIQUE:
  190846. g = 1.0 / (png_ptr->background_gamma);
  190847. gs = 1.0 / (png_ptr->background_gamma *
  190848. png_ptr->screen_gamma);
  190849. break;
  190850. default:
  190851. g = 1.0; /* back_1 */
  190852. gs = 1.0; /* back */
  190853. }
  190854. if ( fabs(gs - 1.0) < PNG_GAMMA_THRESHOLD)
  190855. {
  190856. back.red = (png_byte)png_ptr->background.red;
  190857. back.green = (png_byte)png_ptr->background.green;
  190858. back.blue = (png_byte)png_ptr->background.blue;
  190859. }
  190860. else
  190861. {
  190862. back.red = (png_byte)(pow(
  190863. (double)png_ptr->background.red/255, gs) * 255.0 + .5);
  190864. back.green = (png_byte)(pow(
  190865. (double)png_ptr->background.green/255, gs) * 255.0 + .5);
  190866. back.blue = (png_byte)(pow(
  190867. (double)png_ptr->background.blue/255, gs) * 255.0 + .5);
  190868. }
  190869. back_1.red = (png_byte)(pow(
  190870. (double)png_ptr->background.red/255, g) * 255.0 + .5);
  190871. back_1.green = (png_byte)(pow(
  190872. (double)png_ptr->background.green/255, g) * 255.0 + .5);
  190873. back_1.blue = (png_byte)(pow(
  190874. (double)png_ptr->background.blue/255, g) * 255.0 + .5);
  190875. }
  190876. for (i = 0; i < num_palette; i++)
  190877. {
  190878. if (i < (int)png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  190879. {
  190880. if (png_ptr->trans[i] == 0)
  190881. {
  190882. palette[i] = back;
  190883. }
  190884. else /* if (png_ptr->trans[i] != 0xff) */
  190885. {
  190886. png_byte v, w;
  190887. v = png_ptr->gamma_to_1[palette[i].red];
  190888. png_composite(w, v, png_ptr->trans[i], back_1.red);
  190889. palette[i].red = png_ptr->gamma_from_1[w];
  190890. v = png_ptr->gamma_to_1[palette[i].green];
  190891. png_composite(w, v, png_ptr->trans[i], back_1.green);
  190892. palette[i].green = png_ptr->gamma_from_1[w];
  190893. v = png_ptr->gamma_to_1[palette[i].blue];
  190894. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  190895. palette[i].blue = png_ptr->gamma_from_1[w];
  190896. }
  190897. }
  190898. else
  190899. {
  190900. palette[i].red = png_ptr->gamma_table[palette[i].red];
  190901. palette[i].green = png_ptr->gamma_table[palette[i].green];
  190902. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  190903. }
  190904. }
  190905. }
  190906. /* if (png_ptr->background_gamma_type!=PNG_BACKGROUND_GAMMA_UNKNOWN) */
  190907. else
  190908. /* color_type != PNG_COLOR_TYPE_PALETTE */
  190909. {
  190910. double m = (double)(((png_uint_32)1 << png_ptr->bit_depth) - 1);
  190911. double g = 1.0;
  190912. double gs = 1.0;
  190913. switch (png_ptr->background_gamma_type)
  190914. {
  190915. case PNG_BACKGROUND_GAMMA_SCREEN:
  190916. g = (png_ptr->screen_gamma);
  190917. gs = 1.0;
  190918. break;
  190919. case PNG_BACKGROUND_GAMMA_FILE:
  190920. g = 1.0 / (png_ptr->gamma);
  190921. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  190922. break;
  190923. case PNG_BACKGROUND_GAMMA_UNIQUE:
  190924. g = 1.0 / (png_ptr->background_gamma);
  190925. gs = 1.0 / (png_ptr->background_gamma *
  190926. png_ptr->screen_gamma);
  190927. break;
  190928. }
  190929. png_ptr->background_1.gray = (png_uint_16)(pow(
  190930. (double)png_ptr->background.gray / m, g) * m + .5);
  190931. png_ptr->background.gray = (png_uint_16)(pow(
  190932. (double)png_ptr->background.gray / m, gs) * m + .5);
  190933. if ((png_ptr->background.red != png_ptr->background.green) ||
  190934. (png_ptr->background.red != png_ptr->background.blue) ||
  190935. (png_ptr->background.red != png_ptr->background.gray))
  190936. {
  190937. /* RGB or RGBA with color background */
  190938. png_ptr->background_1.red = (png_uint_16)(pow(
  190939. (double)png_ptr->background.red / m, g) * m + .5);
  190940. png_ptr->background_1.green = (png_uint_16)(pow(
  190941. (double)png_ptr->background.green / m, g) * m + .5);
  190942. png_ptr->background_1.blue = (png_uint_16)(pow(
  190943. (double)png_ptr->background.blue / m, g) * m + .5);
  190944. png_ptr->background.red = (png_uint_16)(pow(
  190945. (double)png_ptr->background.red / m, gs) * m + .5);
  190946. png_ptr->background.green = (png_uint_16)(pow(
  190947. (double)png_ptr->background.green / m, gs) * m + .5);
  190948. png_ptr->background.blue = (png_uint_16)(pow(
  190949. (double)png_ptr->background.blue / m, gs) * m + .5);
  190950. }
  190951. else
  190952. {
  190953. /* GRAY, GRAY ALPHA, RGB, or RGBA with gray background */
  190954. png_ptr->background_1.red = png_ptr->background_1.green
  190955. = png_ptr->background_1.blue = png_ptr->background_1.gray;
  190956. png_ptr->background.red = png_ptr->background.green
  190957. = png_ptr->background.blue = png_ptr->background.gray;
  190958. }
  190959. }
  190960. }
  190961. else
  190962. /* transformation does not include PNG_BACKGROUND */
  190963. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  190964. if (color_type == PNG_COLOR_TYPE_PALETTE)
  190965. {
  190966. png_colorp palette = png_ptr->palette;
  190967. int num_palette = png_ptr->num_palette;
  190968. int i;
  190969. for (i = 0; i < num_palette; i++)
  190970. {
  190971. palette[i].red = png_ptr->gamma_table[palette[i].red];
  190972. palette[i].green = png_ptr->gamma_table[palette[i].green];
  190973. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  190974. }
  190975. }
  190976. }
  190977. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190978. else
  190979. #endif
  190980. #endif /* PNG_READ_GAMMA_SUPPORTED && PNG_FLOATING_POINT_SUPPORTED */
  190981. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190982. /* No GAMMA transformation */
  190983. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  190984. (color_type == PNG_COLOR_TYPE_PALETTE))
  190985. {
  190986. int i;
  190987. int istop = (int)png_ptr->num_trans;
  190988. png_color back;
  190989. png_colorp palette = png_ptr->palette;
  190990. back.red = (png_byte)png_ptr->background.red;
  190991. back.green = (png_byte)png_ptr->background.green;
  190992. back.blue = (png_byte)png_ptr->background.blue;
  190993. for (i = 0; i < istop; i++)
  190994. {
  190995. if (png_ptr->trans[i] == 0)
  190996. {
  190997. palette[i] = back;
  190998. }
  190999. else if (png_ptr->trans[i] != 0xff)
  191000. {
  191001. /* The png_composite() macro is defined in png.h */
  191002. png_composite(palette[i].red, palette[i].red,
  191003. png_ptr->trans[i], back.red);
  191004. png_composite(palette[i].green, palette[i].green,
  191005. png_ptr->trans[i], back.green);
  191006. png_composite(palette[i].blue, palette[i].blue,
  191007. png_ptr->trans[i], back.blue);
  191008. }
  191009. }
  191010. }
  191011. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  191012. #if defined(PNG_READ_SHIFT_SUPPORTED)
  191013. if ((png_ptr->transformations & PNG_SHIFT) &&
  191014. (color_type == PNG_COLOR_TYPE_PALETTE))
  191015. {
  191016. png_uint_16 i;
  191017. png_uint_16 istop = png_ptr->num_palette;
  191018. int sr = 8 - png_ptr->sig_bit.red;
  191019. int sg = 8 - png_ptr->sig_bit.green;
  191020. int sb = 8 - png_ptr->sig_bit.blue;
  191021. if (sr < 0 || sr > 8)
  191022. sr = 0;
  191023. if (sg < 0 || sg > 8)
  191024. sg = 0;
  191025. if (sb < 0 || sb > 8)
  191026. sb = 0;
  191027. for (i = 0; i < istop; i++)
  191028. {
  191029. png_ptr->palette[i].red >>= sr;
  191030. png_ptr->palette[i].green >>= sg;
  191031. png_ptr->palette[i].blue >>= sb;
  191032. }
  191033. }
  191034. #endif /* PNG_READ_SHIFT_SUPPORTED */
  191035. }
  191036. #if !defined(PNG_READ_GAMMA_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED) \
  191037. && !defined(PNG_READ_BACKGROUND_SUPPORTED)
  191038. if(png_ptr)
  191039. return;
  191040. #endif
  191041. }
  191042. /* Modify the info structure to reflect the transformations. The
  191043. * info should be updated so a PNG file could be written with it,
  191044. * assuming the transformations result in valid PNG data.
  191045. */
  191046. void /* PRIVATE */
  191047. png_read_transform_info(png_structp png_ptr, png_infop info_ptr)
  191048. {
  191049. png_debug(1, "in png_read_transform_info\n");
  191050. #if defined(PNG_READ_EXPAND_SUPPORTED)
  191051. if (png_ptr->transformations & PNG_EXPAND)
  191052. {
  191053. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191054. {
  191055. if (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND_tRNS))
  191056. info_ptr->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  191057. else
  191058. info_ptr->color_type = PNG_COLOR_TYPE_RGB;
  191059. info_ptr->bit_depth = 8;
  191060. info_ptr->num_trans = 0;
  191061. }
  191062. else
  191063. {
  191064. if (png_ptr->num_trans)
  191065. {
  191066. if (png_ptr->transformations & PNG_EXPAND_tRNS)
  191067. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  191068. else
  191069. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  191070. }
  191071. if (info_ptr->bit_depth < 8)
  191072. info_ptr->bit_depth = 8;
  191073. info_ptr->num_trans = 0;
  191074. }
  191075. }
  191076. #endif
  191077. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191078. if (png_ptr->transformations & PNG_BACKGROUND)
  191079. {
  191080. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  191081. info_ptr->num_trans = 0;
  191082. info_ptr->background = png_ptr->background;
  191083. }
  191084. #endif
  191085. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191086. if (png_ptr->transformations & PNG_GAMMA)
  191087. {
  191088. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191089. info_ptr->gamma = png_ptr->gamma;
  191090. #endif
  191091. #ifdef PNG_FIXED_POINT_SUPPORTED
  191092. info_ptr->int_gamma = png_ptr->int_gamma;
  191093. #endif
  191094. }
  191095. #endif
  191096. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  191097. if ((png_ptr->transformations & PNG_16_TO_8) && (info_ptr->bit_depth == 16))
  191098. info_ptr->bit_depth = 8;
  191099. #endif
  191100. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191101. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  191102. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  191103. #endif
  191104. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  191105. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  191106. info_ptr->color_type &= ~PNG_COLOR_MASK_COLOR;
  191107. #endif
  191108. #if defined(PNG_READ_DITHER_SUPPORTED)
  191109. if (png_ptr->transformations & PNG_DITHER)
  191110. {
  191111. if (((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  191112. (info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)) &&
  191113. png_ptr->palette_lookup && info_ptr->bit_depth == 8)
  191114. {
  191115. info_ptr->color_type = PNG_COLOR_TYPE_PALETTE;
  191116. }
  191117. }
  191118. #endif
  191119. #if defined(PNG_READ_PACK_SUPPORTED)
  191120. if ((png_ptr->transformations & PNG_PACK) && (info_ptr->bit_depth < 8))
  191121. info_ptr->bit_depth = 8;
  191122. #endif
  191123. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191124. info_ptr->channels = 1;
  191125. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  191126. info_ptr->channels = 3;
  191127. else
  191128. info_ptr->channels = 1;
  191129. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  191130. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  191131. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  191132. #endif
  191133. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  191134. info_ptr->channels++;
  191135. #if defined(PNG_READ_FILLER_SUPPORTED)
  191136. /* STRIP_ALPHA and FILLER allowed: MASK_ALPHA bit stripped above */
  191137. if ((png_ptr->transformations & PNG_FILLER) &&
  191138. ((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  191139. (info_ptr->color_type == PNG_COLOR_TYPE_GRAY)))
  191140. {
  191141. info_ptr->channels++;
  191142. /* if adding a true alpha channel not just filler */
  191143. #if !defined(PNG_1_0_X)
  191144. if (png_ptr->transformations & PNG_ADD_ALPHA)
  191145. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  191146. #endif
  191147. }
  191148. #endif
  191149. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) && \
  191150. defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  191151. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  191152. {
  191153. if(info_ptr->bit_depth < png_ptr->user_transform_depth)
  191154. info_ptr->bit_depth = png_ptr->user_transform_depth;
  191155. if(info_ptr->channels < png_ptr->user_transform_channels)
  191156. info_ptr->channels = png_ptr->user_transform_channels;
  191157. }
  191158. #endif
  191159. info_ptr->pixel_depth = (png_byte)(info_ptr->channels *
  191160. info_ptr->bit_depth);
  191161. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,info_ptr->width);
  191162. #if !defined(PNG_READ_EXPAND_SUPPORTED)
  191163. if(png_ptr)
  191164. return;
  191165. #endif
  191166. }
  191167. /* Transform the row. The order of transformations is significant,
  191168. * and is very touchy. If you add a transformation, take care to
  191169. * decide how it fits in with the other transformations here.
  191170. */
  191171. void /* PRIVATE */
  191172. png_do_read_transformations(png_structp png_ptr)
  191173. {
  191174. png_debug(1, "in png_do_read_transformations\n");
  191175. if (png_ptr->row_buf == NULL)
  191176. {
  191177. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  191178. char msg[50];
  191179. png_snprintf2(msg, 50,
  191180. "NULL row buffer for row %ld, pass %d", png_ptr->row_number,
  191181. png_ptr->pass);
  191182. png_error(png_ptr, msg);
  191183. #else
  191184. png_error(png_ptr, "NULL row buffer");
  191185. #endif
  191186. }
  191187. #ifdef PNG_WARN_UNINITIALIZED_ROW
  191188. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  191189. /* Application has failed to call either png_read_start_image()
  191190. * or png_read_update_info() after setting transforms that expand
  191191. * pixels. This check added to libpng-1.2.19 */
  191192. #if (PNG_WARN_UNINITIALIZED_ROW==1)
  191193. png_error(png_ptr, "Uninitialized row");
  191194. #else
  191195. png_warning(png_ptr, "Uninitialized row");
  191196. #endif
  191197. #endif
  191198. #if defined(PNG_READ_EXPAND_SUPPORTED)
  191199. if (png_ptr->transformations & PNG_EXPAND)
  191200. {
  191201. if (png_ptr->row_info.color_type == PNG_COLOR_TYPE_PALETTE)
  191202. {
  191203. png_do_expand_palette(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191204. png_ptr->palette, png_ptr->trans, png_ptr->num_trans);
  191205. }
  191206. else
  191207. {
  191208. if (png_ptr->num_trans &&
  191209. (png_ptr->transformations & PNG_EXPAND_tRNS))
  191210. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191211. &(png_ptr->trans_values));
  191212. else
  191213. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191214. NULL);
  191215. }
  191216. }
  191217. #endif
  191218. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  191219. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  191220. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191221. PNG_FLAG_FILLER_AFTER | (png_ptr->flags & PNG_FLAG_STRIP_ALPHA));
  191222. #endif
  191223. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  191224. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  191225. {
  191226. int rgb_error =
  191227. png_do_rgb_to_gray(png_ptr, &(png_ptr->row_info), png_ptr->row_buf + 1);
  191228. if(rgb_error)
  191229. {
  191230. png_ptr->rgb_to_gray_status=1;
  191231. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  191232. PNG_RGB_TO_GRAY_WARN)
  191233. png_warning(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  191234. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  191235. PNG_RGB_TO_GRAY_ERR)
  191236. png_error(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  191237. }
  191238. }
  191239. #endif
  191240. /*
  191241. From Andreas Dilger e-mail to png-implement, 26 March 1998:
  191242. In most cases, the "simple transparency" should be done prior to doing
  191243. gray-to-RGB, or you will have to test 3x as many bytes to check if a
  191244. pixel is transparent. You would also need to make sure that the
  191245. transparency information is upgraded to RGB.
  191246. To summarize, the current flow is:
  191247. - Gray + simple transparency -> compare 1 or 2 gray bytes and composite
  191248. with background "in place" if transparent,
  191249. convert to RGB if necessary
  191250. - Gray + alpha -> composite with gray background and remove alpha bytes,
  191251. convert to RGB if necessary
  191252. To support RGB backgrounds for gray images we need:
  191253. - Gray + simple transparency -> convert to RGB + simple transparency, compare
  191254. 3 or 6 bytes and composite with background
  191255. "in place" if transparent (3x compare/pixel
  191256. compared to doing composite with gray bkgrnd)
  191257. - Gray + alpha -> convert to RGB + alpha, composite with background and
  191258. remove alpha bytes (3x float operations/pixel
  191259. compared with composite on gray background)
  191260. Greg's change will do this. The reason it wasn't done before is for
  191261. performance, as this increases the per-pixel operations. If we would check
  191262. in advance if the background was gray or RGB, and position the gray-to-RGB
  191263. transform appropriately, then it would save a lot of work/time.
  191264. */
  191265. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191266. /* if gray -> RGB, do so now only if background is non-gray; else do later
  191267. * for performance reasons */
  191268. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  191269. !(png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  191270. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191271. #endif
  191272. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191273. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  191274. ((png_ptr->num_trans != 0 ) ||
  191275. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA)))
  191276. png_do_background(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191277. &(png_ptr->trans_values), &(png_ptr->background)
  191278. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191279. , &(png_ptr->background_1),
  191280. png_ptr->gamma_table, png_ptr->gamma_from_1,
  191281. png_ptr->gamma_to_1, png_ptr->gamma_16_table,
  191282. png_ptr->gamma_16_from_1, png_ptr->gamma_16_to_1,
  191283. png_ptr->gamma_shift
  191284. #endif
  191285. );
  191286. #endif
  191287. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191288. if ((png_ptr->transformations & PNG_GAMMA) &&
  191289. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191290. !((png_ptr->transformations & PNG_BACKGROUND) &&
  191291. ((png_ptr->num_trans != 0) ||
  191292. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA))) &&
  191293. #endif
  191294. (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE))
  191295. png_do_gamma(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191296. png_ptr->gamma_table, png_ptr->gamma_16_table,
  191297. png_ptr->gamma_shift);
  191298. #endif
  191299. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  191300. if (png_ptr->transformations & PNG_16_TO_8)
  191301. png_do_chop(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191302. #endif
  191303. #if defined(PNG_READ_DITHER_SUPPORTED)
  191304. if (png_ptr->transformations & PNG_DITHER)
  191305. {
  191306. png_do_dither((png_row_infop)&(png_ptr->row_info), png_ptr->row_buf + 1,
  191307. png_ptr->palette_lookup, png_ptr->dither_index);
  191308. if(png_ptr->row_info.rowbytes == (png_uint_32)0)
  191309. png_error(png_ptr, "png_do_dither returned rowbytes=0");
  191310. }
  191311. #endif
  191312. #if defined(PNG_READ_INVERT_SUPPORTED)
  191313. if (png_ptr->transformations & PNG_INVERT_MONO)
  191314. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191315. #endif
  191316. #if defined(PNG_READ_SHIFT_SUPPORTED)
  191317. if (png_ptr->transformations & PNG_SHIFT)
  191318. png_do_unshift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191319. &(png_ptr->shift));
  191320. #endif
  191321. #if defined(PNG_READ_PACK_SUPPORTED)
  191322. if (png_ptr->transformations & PNG_PACK)
  191323. png_do_unpack(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191324. #endif
  191325. #if defined(PNG_READ_BGR_SUPPORTED)
  191326. if (png_ptr->transformations & PNG_BGR)
  191327. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191328. #endif
  191329. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  191330. if (png_ptr->transformations & PNG_PACKSWAP)
  191331. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191332. #endif
  191333. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191334. /* if gray -> RGB, do so now only if we did not do so above */
  191335. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  191336. (png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  191337. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191338. #endif
  191339. #if defined(PNG_READ_FILLER_SUPPORTED)
  191340. if (png_ptr->transformations & PNG_FILLER)
  191341. png_do_read_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191342. (png_uint_32)png_ptr->filler, png_ptr->flags);
  191343. #endif
  191344. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  191345. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  191346. png_do_read_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191347. #endif
  191348. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  191349. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  191350. png_do_read_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191351. #endif
  191352. #if defined(PNG_READ_SWAP_SUPPORTED)
  191353. if (png_ptr->transformations & PNG_SWAP_BYTES)
  191354. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191355. #endif
  191356. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  191357. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  191358. {
  191359. if(png_ptr->read_user_transform_fn != NULL)
  191360. (*(png_ptr->read_user_transform_fn)) /* user read transform function */
  191361. (png_ptr, /* png_ptr */
  191362. &(png_ptr->row_info), /* row_info: */
  191363. /* png_uint_32 width; width of row */
  191364. /* png_uint_32 rowbytes; number of bytes in row */
  191365. /* png_byte color_type; color type of pixels */
  191366. /* png_byte bit_depth; bit depth of samples */
  191367. /* png_byte channels; number of channels (1-4) */
  191368. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  191369. png_ptr->row_buf + 1); /* start of pixel data for row */
  191370. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  191371. if(png_ptr->user_transform_depth)
  191372. png_ptr->row_info.bit_depth = png_ptr->user_transform_depth;
  191373. if(png_ptr->user_transform_channels)
  191374. png_ptr->row_info.channels = png_ptr->user_transform_channels;
  191375. #endif
  191376. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  191377. png_ptr->row_info.channels);
  191378. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  191379. png_ptr->row_info.width);
  191380. }
  191381. #endif
  191382. }
  191383. #if defined(PNG_READ_PACK_SUPPORTED)
  191384. /* Unpack pixels of 1, 2, or 4 bits per pixel into 1 byte per pixel,
  191385. * without changing the actual values. Thus, if you had a row with
  191386. * a bit depth of 1, you would end up with bytes that only contained
  191387. * the numbers 0 or 1. If you would rather they contain 0 and 255, use
  191388. * png_do_shift() after this.
  191389. */
  191390. void /* PRIVATE */
  191391. png_do_unpack(png_row_infop row_info, png_bytep row)
  191392. {
  191393. png_debug(1, "in png_do_unpack\n");
  191394. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191395. if (row != NULL && row_info != NULL && row_info->bit_depth < 8)
  191396. #else
  191397. if (row_info->bit_depth < 8)
  191398. #endif
  191399. {
  191400. png_uint_32 i;
  191401. png_uint_32 row_width=row_info->width;
  191402. switch (row_info->bit_depth)
  191403. {
  191404. case 1:
  191405. {
  191406. png_bytep sp = row + (png_size_t)((row_width - 1) >> 3);
  191407. png_bytep dp = row + (png_size_t)row_width - 1;
  191408. png_uint_32 shift = 7 - (int)((row_width + 7) & 0x07);
  191409. for (i = 0; i < row_width; i++)
  191410. {
  191411. *dp = (png_byte)((*sp >> shift) & 0x01);
  191412. if (shift == 7)
  191413. {
  191414. shift = 0;
  191415. sp--;
  191416. }
  191417. else
  191418. shift++;
  191419. dp--;
  191420. }
  191421. break;
  191422. }
  191423. case 2:
  191424. {
  191425. png_bytep sp = row + (png_size_t)((row_width - 1) >> 2);
  191426. png_bytep dp = row + (png_size_t)row_width - 1;
  191427. png_uint_32 shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  191428. for (i = 0; i < row_width; i++)
  191429. {
  191430. *dp = (png_byte)((*sp >> shift) & 0x03);
  191431. if (shift == 6)
  191432. {
  191433. shift = 0;
  191434. sp--;
  191435. }
  191436. else
  191437. shift += 2;
  191438. dp--;
  191439. }
  191440. break;
  191441. }
  191442. case 4:
  191443. {
  191444. png_bytep sp = row + (png_size_t)((row_width - 1) >> 1);
  191445. png_bytep dp = row + (png_size_t)row_width - 1;
  191446. png_uint_32 shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  191447. for (i = 0; i < row_width; i++)
  191448. {
  191449. *dp = (png_byte)((*sp >> shift) & 0x0f);
  191450. if (shift == 4)
  191451. {
  191452. shift = 0;
  191453. sp--;
  191454. }
  191455. else
  191456. shift = 4;
  191457. dp--;
  191458. }
  191459. break;
  191460. }
  191461. }
  191462. row_info->bit_depth = 8;
  191463. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  191464. row_info->rowbytes = row_width * row_info->channels;
  191465. }
  191466. }
  191467. #endif
  191468. #if defined(PNG_READ_SHIFT_SUPPORTED)
  191469. /* Reverse the effects of png_do_shift. This routine merely shifts the
  191470. * pixels back to their significant bits values. Thus, if you have
  191471. * a row of bit depth 8, but only 5 are significant, this will shift
  191472. * the values back to 0 through 31.
  191473. */
  191474. void /* PRIVATE */
  191475. png_do_unshift(png_row_infop row_info, png_bytep row, png_color_8p sig_bits)
  191476. {
  191477. png_debug(1, "in png_do_unshift\n");
  191478. if (
  191479. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191480. row != NULL && row_info != NULL && sig_bits != NULL &&
  191481. #endif
  191482. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  191483. {
  191484. int shift[4];
  191485. int channels = 0;
  191486. int c;
  191487. png_uint_16 value = 0;
  191488. png_uint_32 row_width = row_info->width;
  191489. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  191490. {
  191491. shift[channels++] = row_info->bit_depth - sig_bits->red;
  191492. shift[channels++] = row_info->bit_depth - sig_bits->green;
  191493. shift[channels++] = row_info->bit_depth - sig_bits->blue;
  191494. }
  191495. else
  191496. {
  191497. shift[channels++] = row_info->bit_depth - sig_bits->gray;
  191498. }
  191499. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  191500. {
  191501. shift[channels++] = row_info->bit_depth - sig_bits->alpha;
  191502. }
  191503. for (c = 0; c < channels; c++)
  191504. {
  191505. if (shift[c] <= 0)
  191506. shift[c] = 0;
  191507. else
  191508. value = 1;
  191509. }
  191510. if (!value)
  191511. return;
  191512. switch (row_info->bit_depth)
  191513. {
  191514. case 2:
  191515. {
  191516. png_bytep bp;
  191517. png_uint_32 i;
  191518. png_uint_32 istop = row_info->rowbytes;
  191519. for (bp = row, i = 0; i < istop; i++)
  191520. {
  191521. *bp >>= 1;
  191522. *bp++ &= 0x55;
  191523. }
  191524. break;
  191525. }
  191526. case 4:
  191527. {
  191528. png_bytep bp = row;
  191529. png_uint_32 i;
  191530. png_uint_32 istop = row_info->rowbytes;
  191531. png_byte mask = (png_byte)((((int)0xf0 >> shift[0]) & (int)0xf0) |
  191532. (png_byte)((int)0xf >> shift[0]));
  191533. for (i = 0; i < istop; i++)
  191534. {
  191535. *bp >>= shift[0];
  191536. *bp++ &= mask;
  191537. }
  191538. break;
  191539. }
  191540. case 8:
  191541. {
  191542. png_bytep bp = row;
  191543. png_uint_32 i;
  191544. png_uint_32 istop = row_width * channels;
  191545. for (i = 0; i < istop; i++)
  191546. {
  191547. *bp++ >>= shift[i%channels];
  191548. }
  191549. break;
  191550. }
  191551. case 16:
  191552. {
  191553. png_bytep bp = row;
  191554. png_uint_32 i;
  191555. png_uint_32 istop = channels * row_width;
  191556. for (i = 0; i < istop; i++)
  191557. {
  191558. value = (png_uint_16)((*bp << 8) + *(bp + 1));
  191559. value >>= shift[i%channels];
  191560. *bp++ = (png_byte)(value >> 8);
  191561. *bp++ = (png_byte)(value & 0xff);
  191562. }
  191563. break;
  191564. }
  191565. }
  191566. }
  191567. }
  191568. #endif
  191569. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  191570. /* chop rows of bit depth 16 down to 8 */
  191571. void /* PRIVATE */
  191572. png_do_chop(png_row_infop row_info, png_bytep row)
  191573. {
  191574. png_debug(1, "in png_do_chop\n");
  191575. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191576. if (row != NULL && row_info != NULL && row_info->bit_depth == 16)
  191577. #else
  191578. if (row_info->bit_depth == 16)
  191579. #endif
  191580. {
  191581. png_bytep sp = row;
  191582. png_bytep dp = row;
  191583. png_uint_32 i;
  191584. png_uint_32 istop = row_info->width * row_info->channels;
  191585. for (i = 0; i<istop; i++, sp += 2, dp++)
  191586. {
  191587. #if defined(PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED)
  191588. /* This does a more accurate scaling of the 16-bit color
  191589. * value, rather than a simple low-byte truncation.
  191590. *
  191591. * What the ideal calculation should be:
  191592. * *dp = (((((png_uint_32)(*sp) << 8) |
  191593. * (png_uint_32)(*(sp + 1))) * 255 + 127) / (png_uint_32)65535L;
  191594. *
  191595. * GRR: no, I think this is what it really should be:
  191596. * *dp = (((((png_uint_32)(*sp) << 8) |
  191597. * (png_uint_32)(*(sp + 1))) + 128L) / (png_uint_32)257L;
  191598. *
  191599. * GRR: here's the exact calculation with shifts:
  191600. * temp = (((png_uint_32)(*sp) << 8) | (png_uint_32)(*(sp + 1))) + 128L;
  191601. * *dp = (temp - (temp >> 8)) >> 8;
  191602. *
  191603. * Approximate calculation with shift/add instead of multiply/divide:
  191604. * *dp = ((((png_uint_32)(*sp) << 8) |
  191605. * (png_uint_32)((int)(*(sp + 1)) - *sp)) + 128) >> 8;
  191606. *
  191607. * What we actually do to avoid extra shifting and conversion:
  191608. */
  191609. *dp = *sp + ((((int)(*(sp + 1)) - *sp) > 128) ? 1 : 0);
  191610. #else
  191611. /* Simply discard the low order byte */
  191612. *dp = *sp;
  191613. #endif
  191614. }
  191615. row_info->bit_depth = 8;
  191616. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  191617. row_info->rowbytes = row_info->width * row_info->channels;
  191618. }
  191619. }
  191620. #endif
  191621. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  191622. void /* PRIVATE */
  191623. png_do_read_swap_alpha(png_row_infop row_info, png_bytep row)
  191624. {
  191625. png_debug(1, "in png_do_read_swap_alpha\n");
  191626. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191627. if (row != NULL && row_info != NULL)
  191628. #endif
  191629. {
  191630. png_uint_32 row_width = row_info->width;
  191631. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191632. {
  191633. /* This converts from RGBA to ARGB */
  191634. if (row_info->bit_depth == 8)
  191635. {
  191636. png_bytep sp = row + row_info->rowbytes;
  191637. png_bytep dp = sp;
  191638. png_byte save;
  191639. png_uint_32 i;
  191640. for (i = 0; i < row_width; i++)
  191641. {
  191642. save = *(--sp);
  191643. *(--dp) = *(--sp);
  191644. *(--dp) = *(--sp);
  191645. *(--dp) = *(--sp);
  191646. *(--dp) = save;
  191647. }
  191648. }
  191649. /* This converts from RRGGBBAA to AARRGGBB */
  191650. else
  191651. {
  191652. png_bytep sp = row + row_info->rowbytes;
  191653. png_bytep dp = sp;
  191654. png_byte save[2];
  191655. png_uint_32 i;
  191656. for (i = 0; i < row_width; i++)
  191657. {
  191658. save[0] = *(--sp);
  191659. save[1] = *(--sp);
  191660. *(--dp) = *(--sp);
  191661. *(--dp) = *(--sp);
  191662. *(--dp) = *(--sp);
  191663. *(--dp) = *(--sp);
  191664. *(--dp) = *(--sp);
  191665. *(--dp) = *(--sp);
  191666. *(--dp) = save[0];
  191667. *(--dp) = save[1];
  191668. }
  191669. }
  191670. }
  191671. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191672. {
  191673. /* This converts from GA to AG */
  191674. if (row_info->bit_depth == 8)
  191675. {
  191676. png_bytep sp = row + row_info->rowbytes;
  191677. png_bytep dp = sp;
  191678. png_byte save;
  191679. png_uint_32 i;
  191680. for (i = 0; i < row_width; i++)
  191681. {
  191682. save = *(--sp);
  191683. *(--dp) = *(--sp);
  191684. *(--dp) = save;
  191685. }
  191686. }
  191687. /* This converts from GGAA to AAGG */
  191688. else
  191689. {
  191690. png_bytep sp = row + row_info->rowbytes;
  191691. png_bytep dp = sp;
  191692. png_byte save[2];
  191693. png_uint_32 i;
  191694. for (i = 0; i < row_width; i++)
  191695. {
  191696. save[0] = *(--sp);
  191697. save[1] = *(--sp);
  191698. *(--dp) = *(--sp);
  191699. *(--dp) = *(--sp);
  191700. *(--dp) = save[0];
  191701. *(--dp) = save[1];
  191702. }
  191703. }
  191704. }
  191705. }
  191706. }
  191707. #endif
  191708. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  191709. void /* PRIVATE */
  191710. png_do_read_invert_alpha(png_row_infop row_info, png_bytep row)
  191711. {
  191712. png_debug(1, "in png_do_read_invert_alpha\n");
  191713. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191714. if (row != NULL && row_info != NULL)
  191715. #endif
  191716. {
  191717. png_uint_32 row_width = row_info->width;
  191718. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191719. {
  191720. /* This inverts the alpha channel in RGBA */
  191721. if (row_info->bit_depth == 8)
  191722. {
  191723. png_bytep sp = row + row_info->rowbytes;
  191724. png_bytep dp = sp;
  191725. png_uint_32 i;
  191726. for (i = 0; i < row_width; i++)
  191727. {
  191728. *(--dp) = (png_byte)(255 - *(--sp));
  191729. /* This does nothing:
  191730. *(--dp) = *(--sp);
  191731. *(--dp) = *(--sp);
  191732. *(--dp) = *(--sp);
  191733. We can replace it with:
  191734. */
  191735. sp-=3;
  191736. dp=sp;
  191737. }
  191738. }
  191739. /* This inverts the alpha channel in RRGGBBAA */
  191740. else
  191741. {
  191742. png_bytep sp = row + row_info->rowbytes;
  191743. png_bytep dp = sp;
  191744. png_uint_32 i;
  191745. for (i = 0; i < row_width; i++)
  191746. {
  191747. *(--dp) = (png_byte)(255 - *(--sp));
  191748. *(--dp) = (png_byte)(255 - *(--sp));
  191749. /* This does nothing:
  191750. *(--dp) = *(--sp);
  191751. *(--dp) = *(--sp);
  191752. *(--dp) = *(--sp);
  191753. *(--dp) = *(--sp);
  191754. *(--dp) = *(--sp);
  191755. *(--dp) = *(--sp);
  191756. We can replace it with:
  191757. */
  191758. sp-=6;
  191759. dp=sp;
  191760. }
  191761. }
  191762. }
  191763. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191764. {
  191765. /* This inverts the alpha channel in GA */
  191766. if (row_info->bit_depth == 8)
  191767. {
  191768. png_bytep sp = row + row_info->rowbytes;
  191769. png_bytep dp = sp;
  191770. png_uint_32 i;
  191771. for (i = 0; i < row_width; i++)
  191772. {
  191773. *(--dp) = (png_byte)(255 - *(--sp));
  191774. *(--dp) = *(--sp);
  191775. }
  191776. }
  191777. /* This inverts the alpha channel in GGAA */
  191778. else
  191779. {
  191780. png_bytep sp = row + row_info->rowbytes;
  191781. png_bytep dp = sp;
  191782. png_uint_32 i;
  191783. for (i = 0; i < row_width; i++)
  191784. {
  191785. *(--dp) = (png_byte)(255 - *(--sp));
  191786. *(--dp) = (png_byte)(255 - *(--sp));
  191787. /*
  191788. *(--dp) = *(--sp);
  191789. *(--dp) = *(--sp);
  191790. */
  191791. sp-=2;
  191792. dp=sp;
  191793. }
  191794. }
  191795. }
  191796. }
  191797. }
  191798. #endif
  191799. #if defined(PNG_READ_FILLER_SUPPORTED)
  191800. /* Add filler channel if we have RGB color */
  191801. void /* PRIVATE */
  191802. png_do_read_filler(png_row_infop row_info, png_bytep row,
  191803. png_uint_32 filler, png_uint_32 flags)
  191804. {
  191805. png_uint_32 i;
  191806. png_uint_32 row_width = row_info->width;
  191807. png_byte hi_filler = (png_byte)((filler>>8) & 0xff);
  191808. png_byte lo_filler = (png_byte)(filler & 0xff);
  191809. png_debug(1, "in png_do_read_filler\n");
  191810. if (
  191811. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191812. row != NULL && row_info != NULL &&
  191813. #endif
  191814. row_info->color_type == PNG_COLOR_TYPE_GRAY)
  191815. {
  191816. if(row_info->bit_depth == 8)
  191817. {
  191818. /* This changes the data from G to GX */
  191819. if (flags & PNG_FLAG_FILLER_AFTER)
  191820. {
  191821. png_bytep sp = row + (png_size_t)row_width;
  191822. png_bytep dp = sp + (png_size_t)row_width;
  191823. for (i = 1; i < row_width; i++)
  191824. {
  191825. *(--dp) = lo_filler;
  191826. *(--dp) = *(--sp);
  191827. }
  191828. *(--dp) = lo_filler;
  191829. row_info->channels = 2;
  191830. row_info->pixel_depth = 16;
  191831. row_info->rowbytes = row_width * 2;
  191832. }
  191833. /* This changes the data from G to XG */
  191834. else
  191835. {
  191836. png_bytep sp = row + (png_size_t)row_width;
  191837. png_bytep dp = sp + (png_size_t)row_width;
  191838. for (i = 0; i < row_width; i++)
  191839. {
  191840. *(--dp) = *(--sp);
  191841. *(--dp) = lo_filler;
  191842. }
  191843. row_info->channels = 2;
  191844. row_info->pixel_depth = 16;
  191845. row_info->rowbytes = row_width * 2;
  191846. }
  191847. }
  191848. else if(row_info->bit_depth == 16)
  191849. {
  191850. /* This changes the data from GG to GGXX */
  191851. if (flags & PNG_FLAG_FILLER_AFTER)
  191852. {
  191853. png_bytep sp = row + (png_size_t)row_width * 2;
  191854. png_bytep dp = sp + (png_size_t)row_width * 2;
  191855. for (i = 1; i < row_width; i++)
  191856. {
  191857. *(--dp) = hi_filler;
  191858. *(--dp) = lo_filler;
  191859. *(--dp) = *(--sp);
  191860. *(--dp) = *(--sp);
  191861. }
  191862. *(--dp) = hi_filler;
  191863. *(--dp) = lo_filler;
  191864. row_info->channels = 2;
  191865. row_info->pixel_depth = 32;
  191866. row_info->rowbytes = row_width * 4;
  191867. }
  191868. /* This changes the data from GG to XXGG */
  191869. else
  191870. {
  191871. png_bytep sp = row + (png_size_t)row_width * 2;
  191872. png_bytep dp = sp + (png_size_t)row_width * 2;
  191873. for (i = 0; i < row_width; i++)
  191874. {
  191875. *(--dp) = *(--sp);
  191876. *(--dp) = *(--sp);
  191877. *(--dp) = hi_filler;
  191878. *(--dp) = lo_filler;
  191879. }
  191880. row_info->channels = 2;
  191881. row_info->pixel_depth = 32;
  191882. row_info->rowbytes = row_width * 4;
  191883. }
  191884. }
  191885. } /* COLOR_TYPE == GRAY */
  191886. else if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  191887. {
  191888. if(row_info->bit_depth == 8)
  191889. {
  191890. /* This changes the data from RGB to RGBX */
  191891. if (flags & PNG_FLAG_FILLER_AFTER)
  191892. {
  191893. png_bytep sp = row + (png_size_t)row_width * 3;
  191894. png_bytep dp = sp + (png_size_t)row_width;
  191895. for (i = 1; i < row_width; i++)
  191896. {
  191897. *(--dp) = lo_filler;
  191898. *(--dp) = *(--sp);
  191899. *(--dp) = *(--sp);
  191900. *(--dp) = *(--sp);
  191901. }
  191902. *(--dp) = lo_filler;
  191903. row_info->channels = 4;
  191904. row_info->pixel_depth = 32;
  191905. row_info->rowbytes = row_width * 4;
  191906. }
  191907. /* This changes the data from RGB to XRGB */
  191908. else
  191909. {
  191910. png_bytep sp = row + (png_size_t)row_width * 3;
  191911. png_bytep dp = sp + (png_size_t)row_width;
  191912. for (i = 0; i < row_width; i++)
  191913. {
  191914. *(--dp) = *(--sp);
  191915. *(--dp) = *(--sp);
  191916. *(--dp) = *(--sp);
  191917. *(--dp) = lo_filler;
  191918. }
  191919. row_info->channels = 4;
  191920. row_info->pixel_depth = 32;
  191921. row_info->rowbytes = row_width * 4;
  191922. }
  191923. }
  191924. else if(row_info->bit_depth == 16)
  191925. {
  191926. /* This changes the data from RRGGBB to RRGGBBXX */
  191927. if (flags & PNG_FLAG_FILLER_AFTER)
  191928. {
  191929. png_bytep sp = row + (png_size_t)row_width * 6;
  191930. png_bytep dp = sp + (png_size_t)row_width * 2;
  191931. for (i = 1; i < row_width; i++)
  191932. {
  191933. *(--dp) = hi_filler;
  191934. *(--dp) = lo_filler;
  191935. *(--dp) = *(--sp);
  191936. *(--dp) = *(--sp);
  191937. *(--dp) = *(--sp);
  191938. *(--dp) = *(--sp);
  191939. *(--dp) = *(--sp);
  191940. *(--dp) = *(--sp);
  191941. }
  191942. *(--dp) = hi_filler;
  191943. *(--dp) = lo_filler;
  191944. row_info->channels = 4;
  191945. row_info->pixel_depth = 64;
  191946. row_info->rowbytes = row_width * 8;
  191947. }
  191948. /* This changes the data from RRGGBB to XXRRGGBB */
  191949. else
  191950. {
  191951. png_bytep sp = row + (png_size_t)row_width * 6;
  191952. png_bytep dp = sp + (png_size_t)row_width * 2;
  191953. for (i = 0; i < row_width; i++)
  191954. {
  191955. *(--dp) = *(--sp);
  191956. *(--dp) = *(--sp);
  191957. *(--dp) = *(--sp);
  191958. *(--dp) = *(--sp);
  191959. *(--dp) = *(--sp);
  191960. *(--dp) = *(--sp);
  191961. *(--dp) = hi_filler;
  191962. *(--dp) = lo_filler;
  191963. }
  191964. row_info->channels = 4;
  191965. row_info->pixel_depth = 64;
  191966. row_info->rowbytes = row_width * 8;
  191967. }
  191968. }
  191969. } /* COLOR_TYPE == RGB */
  191970. }
  191971. #endif
  191972. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191973. /* expand grayscale files to RGB, with or without alpha */
  191974. void /* PRIVATE */
  191975. png_do_gray_to_rgb(png_row_infop row_info, png_bytep row)
  191976. {
  191977. png_uint_32 i;
  191978. png_uint_32 row_width = row_info->width;
  191979. png_debug(1, "in png_do_gray_to_rgb\n");
  191980. if (row_info->bit_depth >= 8 &&
  191981. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191982. row != NULL && row_info != NULL &&
  191983. #endif
  191984. !(row_info->color_type & PNG_COLOR_MASK_COLOR))
  191985. {
  191986. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  191987. {
  191988. if (row_info->bit_depth == 8)
  191989. {
  191990. png_bytep sp = row + (png_size_t)row_width - 1;
  191991. png_bytep dp = sp + (png_size_t)row_width * 2;
  191992. for (i = 0; i < row_width; i++)
  191993. {
  191994. *(dp--) = *sp;
  191995. *(dp--) = *sp;
  191996. *(dp--) = *(sp--);
  191997. }
  191998. }
  191999. else
  192000. {
  192001. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  192002. png_bytep dp = sp + (png_size_t)row_width * 4;
  192003. for (i = 0; i < row_width; i++)
  192004. {
  192005. *(dp--) = *sp;
  192006. *(dp--) = *(sp - 1);
  192007. *(dp--) = *sp;
  192008. *(dp--) = *(sp - 1);
  192009. *(dp--) = *(sp--);
  192010. *(dp--) = *(sp--);
  192011. }
  192012. }
  192013. }
  192014. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  192015. {
  192016. if (row_info->bit_depth == 8)
  192017. {
  192018. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  192019. png_bytep dp = sp + (png_size_t)row_width * 2;
  192020. for (i = 0; i < row_width; i++)
  192021. {
  192022. *(dp--) = *(sp--);
  192023. *(dp--) = *sp;
  192024. *(dp--) = *sp;
  192025. *(dp--) = *(sp--);
  192026. }
  192027. }
  192028. else
  192029. {
  192030. png_bytep sp = row + (png_size_t)row_width * 4 - 1;
  192031. png_bytep dp = sp + (png_size_t)row_width * 4;
  192032. for (i = 0; i < row_width; i++)
  192033. {
  192034. *(dp--) = *(sp--);
  192035. *(dp--) = *(sp--);
  192036. *(dp--) = *sp;
  192037. *(dp--) = *(sp - 1);
  192038. *(dp--) = *sp;
  192039. *(dp--) = *(sp - 1);
  192040. *(dp--) = *(sp--);
  192041. *(dp--) = *(sp--);
  192042. }
  192043. }
  192044. }
  192045. row_info->channels += (png_byte)2;
  192046. row_info->color_type |= PNG_COLOR_MASK_COLOR;
  192047. row_info->pixel_depth = (png_byte)(row_info->channels *
  192048. row_info->bit_depth);
  192049. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  192050. }
  192051. }
  192052. #endif
  192053. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  192054. /* reduce RGB files to grayscale, with or without alpha
  192055. * using the equation given in Poynton's ColorFAQ at
  192056. * <http://www.inforamp.net/~poynton/>
  192057. * Copyright (c) 1998-01-04 Charles Poynton poynton at inforamp.net
  192058. *
  192059. * Y = 0.212671 * R + 0.715160 * G + 0.072169 * B
  192060. *
  192061. * We approximate this with
  192062. *
  192063. * Y = 0.21268 * R + 0.7151 * G + 0.07217 * B
  192064. *
  192065. * which can be expressed with integers as
  192066. *
  192067. * Y = (6969 * R + 23434 * G + 2365 * B)/32768
  192068. *
  192069. * The calculation is to be done in a linear colorspace.
  192070. *
  192071. * Other integer coefficents can be used via png_set_rgb_to_gray().
  192072. */
  192073. int /* PRIVATE */
  192074. png_do_rgb_to_gray(png_structp png_ptr, png_row_infop row_info, png_bytep row)
  192075. {
  192076. png_uint_32 i;
  192077. png_uint_32 row_width = row_info->width;
  192078. int rgb_error = 0;
  192079. png_debug(1, "in png_do_rgb_to_gray\n");
  192080. if (
  192081. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192082. row != NULL && row_info != NULL &&
  192083. #endif
  192084. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  192085. {
  192086. png_uint_32 rc = png_ptr->rgb_to_gray_red_coeff;
  192087. png_uint_32 gc = png_ptr->rgb_to_gray_green_coeff;
  192088. png_uint_32 bc = png_ptr->rgb_to_gray_blue_coeff;
  192089. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  192090. {
  192091. if (row_info->bit_depth == 8)
  192092. {
  192093. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192094. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  192095. {
  192096. png_bytep sp = row;
  192097. png_bytep dp = row;
  192098. for (i = 0; i < row_width; i++)
  192099. {
  192100. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  192101. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  192102. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  192103. if(red != green || red != blue)
  192104. {
  192105. rgb_error |= 1;
  192106. *(dp++) = png_ptr->gamma_from_1[
  192107. (rc*red+gc*green+bc*blue)>>15];
  192108. }
  192109. else
  192110. *(dp++) = *(sp-1);
  192111. }
  192112. }
  192113. else
  192114. #endif
  192115. {
  192116. png_bytep sp = row;
  192117. png_bytep dp = row;
  192118. for (i = 0; i < row_width; i++)
  192119. {
  192120. png_byte red = *(sp++);
  192121. png_byte green = *(sp++);
  192122. png_byte blue = *(sp++);
  192123. if(red != green || red != blue)
  192124. {
  192125. rgb_error |= 1;
  192126. *(dp++) = (png_byte)((rc*red+gc*green+bc*blue)>>15);
  192127. }
  192128. else
  192129. *(dp++) = *(sp-1);
  192130. }
  192131. }
  192132. }
  192133. else /* RGB bit_depth == 16 */
  192134. {
  192135. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192136. if (png_ptr->gamma_16_to_1 != NULL &&
  192137. png_ptr->gamma_16_from_1 != NULL)
  192138. {
  192139. png_bytep sp = row;
  192140. png_bytep dp = row;
  192141. for (i = 0; i < row_width; i++)
  192142. {
  192143. png_uint_16 red, green, blue, w;
  192144. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192145. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192146. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192147. if(red == green && red == blue)
  192148. w = red;
  192149. else
  192150. {
  192151. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  192152. png_ptr->gamma_shift][red>>8];
  192153. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  192154. png_ptr->gamma_shift][green>>8];
  192155. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  192156. png_ptr->gamma_shift][blue>>8];
  192157. png_uint_16 gray16 = (png_uint_16)((rc*red_1 + gc*green_1
  192158. + bc*blue_1)>>15);
  192159. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  192160. png_ptr->gamma_shift][gray16 >> 8];
  192161. rgb_error |= 1;
  192162. }
  192163. *(dp++) = (png_byte)((w>>8) & 0xff);
  192164. *(dp++) = (png_byte)(w & 0xff);
  192165. }
  192166. }
  192167. else
  192168. #endif
  192169. {
  192170. png_bytep sp = row;
  192171. png_bytep dp = row;
  192172. for (i = 0; i < row_width; i++)
  192173. {
  192174. png_uint_16 red, green, blue, gray16;
  192175. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192176. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192177. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192178. if(red != green || red != blue)
  192179. rgb_error |= 1;
  192180. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  192181. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  192182. *(dp++) = (png_byte)(gray16 & 0xff);
  192183. }
  192184. }
  192185. }
  192186. }
  192187. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  192188. {
  192189. if (row_info->bit_depth == 8)
  192190. {
  192191. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192192. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  192193. {
  192194. png_bytep sp = row;
  192195. png_bytep dp = row;
  192196. for (i = 0; i < row_width; i++)
  192197. {
  192198. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  192199. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  192200. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  192201. if(red != green || red != blue)
  192202. rgb_error |= 1;
  192203. *(dp++) = png_ptr->gamma_from_1
  192204. [(rc*red + gc*green + bc*blue)>>15];
  192205. *(dp++) = *(sp++); /* alpha */
  192206. }
  192207. }
  192208. else
  192209. #endif
  192210. {
  192211. png_bytep sp = row;
  192212. png_bytep dp = row;
  192213. for (i = 0; i < row_width; i++)
  192214. {
  192215. png_byte red = *(sp++);
  192216. png_byte green = *(sp++);
  192217. png_byte blue = *(sp++);
  192218. if(red != green || red != blue)
  192219. rgb_error |= 1;
  192220. *(dp++) = (png_byte)((rc*red + gc*green + bc*blue)>>15);
  192221. *(dp++) = *(sp++); /* alpha */
  192222. }
  192223. }
  192224. }
  192225. else /* RGBA bit_depth == 16 */
  192226. {
  192227. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192228. if (png_ptr->gamma_16_to_1 != NULL &&
  192229. png_ptr->gamma_16_from_1 != NULL)
  192230. {
  192231. png_bytep sp = row;
  192232. png_bytep dp = row;
  192233. for (i = 0; i < row_width; i++)
  192234. {
  192235. png_uint_16 red, green, blue, w;
  192236. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192237. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192238. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192239. if(red == green && red == blue)
  192240. w = red;
  192241. else
  192242. {
  192243. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  192244. png_ptr->gamma_shift][red>>8];
  192245. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  192246. png_ptr->gamma_shift][green>>8];
  192247. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  192248. png_ptr->gamma_shift][blue>>8];
  192249. png_uint_16 gray16 = (png_uint_16)((rc * red_1
  192250. + gc * green_1 + bc * blue_1)>>15);
  192251. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  192252. png_ptr->gamma_shift][gray16 >> 8];
  192253. rgb_error |= 1;
  192254. }
  192255. *(dp++) = (png_byte)((w>>8) & 0xff);
  192256. *(dp++) = (png_byte)(w & 0xff);
  192257. *(dp++) = *(sp++); /* alpha */
  192258. *(dp++) = *(sp++);
  192259. }
  192260. }
  192261. else
  192262. #endif
  192263. {
  192264. png_bytep sp = row;
  192265. png_bytep dp = row;
  192266. for (i = 0; i < row_width; i++)
  192267. {
  192268. png_uint_16 red, green, blue, gray16;
  192269. red = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  192270. green = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  192271. blue = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  192272. if(red != green || red != blue)
  192273. rgb_error |= 1;
  192274. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  192275. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  192276. *(dp++) = (png_byte)(gray16 & 0xff);
  192277. *(dp++) = *(sp++); /* alpha */
  192278. *(dp++) = *(sp++);
  192279. }
  192280. }
  192281. }
  192282. }
  192283. row_info->channels -= (png_byte)2;
  192284. row_info->color_type &= ~PNG_COLOR_MASK_COLOR;
  192285. row_info->pixel_depth = (png_byte)(row_info->channels *
  192286. row_info->bit_depth);
  192287. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  192288. }
  192289. return rgb_error;
  192290. }
  192291. #endif
  192292. /* Build a grayscale palette. Palette is assumed to be 1 << bit_depth
  192293. * large of png_color. This lets grayscale images be treated as
  192294. * paletted. Most useful for gamma correction and simplification
  192295. * of code.
  192296. */
  192297. void PNGAPI
  192298. png_build_grayscale_palette(int bit_depth, png_colorp palette)
  192299. {
  192300. int num_palette;
  192301. int color_inc;
  192302. int i;
  192303. int v;
  192304. png_debug(1, "in png_do_build_grayscale_palette\n");
  192305. if (palette == NULL)
  192306. return;
  192307. switch (bit_depth)
  192308. {
  192309. case 1:
  192310. num_palette = 2;
  192311. color_inc = 0xff;
  192312. break;
  192313. case 2:
  192314. num_palette = 4;
  192315. color_inc = 0x55;
  192316. break;
  192317. case 4:
  192318. num_palette = 16;
  192319. color_inc = 0x11;
  192320. break;
  192321. case 8:
  192322. num_palette = 256;
  192323. color_inc = 1;
  192324. break;
  192325. default:
  192326. num_palette = 0;
  192327. color_inc = 0;
  192328. break;
  192329. }
  192330. for (i = 0, v = 0; i < num_palette; i++, v += color_inc)
  192331. {
  192332. palette[i].red = (png_byte)v;
  192333. palette[i].green = (png_byte)v;
  192334. palette[i].blue = (png_byte)v;
  192335. }
  192336. }
  192337. /* This function is currently unused. Do we really need it? */
  192338. #if defined(PNG_READ_DITHER_SUPPORTED) && defined(PNG_CORRECT_PALETTE_SUPPORTED)
  192339. void /* PRIVATE */
  192340. png_correct_palette(png_structp png_ptr, png_colorp palette,
  192341. int num_palette)
  192342. {
  192343. png_debug(1, "in png_correct_palette\n");
  192344. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  192345. defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  192346. if (png_ptr->transformations & (PNG_GAMMA | PNG_BACKGROUND))
  192347. {
  192348. png_color back, back_1;
  192349. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  192350. {
  192351. back.red = png_ptr->gamma_table[png_ptr->background.red];
  192352. back.green = png_ptr->gamma_table[png_ptr->background.green];
  192353. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  192354. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  192355. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  192356. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  192357. }
  192358. else
  192359. {
  192360. double g;
  192361. g = 1.0 / (png_ptr->background_gamma * png_ptr->screen_gamma);
  192362. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_SCREEN ||
  192363. fabs(g - 1.0) < PNG_GAMMA_THRESHOLD)
  192364. {
  192365. back.red = png_ptr->background.red;
  192366. back.green = png_ptr->background.green;
  192367. back.blue = png_ptr->background.blue;
  192368. }
  192369. else
  192370. {
  192371. back.red =
  192372. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  192373. 255.0 + 0.5);
  192374. back.green =
  192375. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  192376. 255.0 + 0.5);
  192377. back.blue =
  192378. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  192379. 255.0 + 0.5);
  192380. }
  192381. g = 1.0 / png_ptr->background_gamma;
  192382. back_1.red =
  192383. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  192384. 255.0 + 0.5);
  192385. back_1.green =
  192386. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  192387. 255.0 + 0.5);
  192388. back_1.blue =
  192389. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  192390. 255.0 + 0.5);
  192391. }
  192392. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192393. {
  192394. png_uint_32 i;
  192395. for (i = 0; i < (png_uint_32)num_palette; i++)
  192396. {
  192397. if (i < png_ptr->num_trans && png_ptr->trans[i] == 0)
  192398. {
  192399. palette[i] = back;
  192400. }
  192401. else if (i < png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  192402. {
  192403. png_byte v, w;
  192404. v = png_ptr->gamma_to_1[png_ptr->palette[i].red];
  192405. png_composite(w, v, png_ptr->trans[i], back_1.red);
  192406. palette[i].red = png_ptr->gamma_from_1[w];
  192407. v = png_ptr->gamma_to_1[png_ptr->palette[i].green];
  192408. png_composite(w, v, png_ptr->trans[i], back_1.green);
  192409. palette[i].green = png_ptr->gamma_from_1[w];
  192410. v = png_ptr->gamma_to_1[png_ptr->palette[i].blue];
  192411. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  192412. palette[i].blue = png_ptr->gamma_from_1[w];
  192413. }
  192414. else
  192415. {
  192416. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192417. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192418. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192419. }
  192420. }
  192421. }
  192422. else
  192423. {
  192424. int i;
  192425. for (i = 0; i < num_palette; i++)
  192426. {
  192427. if (palette[i].red == (png_byte)png_ptr->trans_values.gray)
  192428. {
  192429. palette[i] = back;
  192430. }
  192431. else
  192432. {
  192433. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192434. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192435. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192436. }
  192437. }
  192438. }
  192439. }
  192440. else
  192441. #endif
  192442. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192443. if (png_ptr->transformations & PNG_GAMMA)
  192444. {
  192445. int i;
  192446. for (i = 0; i < num_palette; i++)
  192447. {
  192448. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192449. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192450. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192451. }
  192452. }
  192453. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192454. else
  192455. #endif
  192456. #endif
  192457. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192458. if (png_ptr->transformations & PNG_BACKGROUND)
  192459. {
  192460. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192461. {
  192462. png_color back;
  192463. back.red = (png_byte)png_ptr->background.red;
  192464. back.green = (png_byte)png_ptr->background.green;
  192465. back.blue = (png_byte)png_ptr->background.blue;
  192466. for (i = 0; i < (int)png_ptr->num_trans; i++)
  192467. {
  192468. if (png_ptr->trans[i] == 0)
  192469. {
  192470. palette[i].red = back.red;
  192471. palette[i].green = back.green;
  192472. palette[i].blue = back.blue;
  192473. }
  192474. else if (png_ptr->trans[i] != 0xff)
  192475. {
  192476. png_composite(palette[i].red, png_ptr->palette[i].red,
  192477. png_ptr->trans[i], back.red);
  192478. png_composite(palette[i].green, png_ptr->palette[i].green,
  192479. png_ptr->trans[i], back.green);
  192480. png_composite(palette[i].blue, png_ptr->palette[i].blue,
  192481. png_ptr->trans[i], back.blue);
  192482. }
  192483. }
  192484. }
  192485. else /* assume grayscale palette (what else could it be?) */
  192486. {
  192487. int i;
  192488. for (i = 0; i < num_palette; i++)
  192489. {
  192490. if (i == (png_byte)png_ptr->trans_values.gray)
  192491. {
  192492. palette[i].red = (png_byte)png_ptr->background.red;
  192493. palette[i].green = (png_byte)png_ptr->background.green;
  192494. palette[i].blue = (png_byte)png_ptr->background.blue;
  192495. }
  192496. }
  192497. }
  192498. }
  192499. #endif
  192500. }
  192501. #endif
  192502. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192503. /* Replace any alpha or transparency with the supplied background color.
  192504. * "background" is already in the screen gamma, while "background_1" is
  192505. * at a gamma of 1.0. Paletted files have already been taken care of.
  192506. */
  192507. void /* PRIVATE */
  192508. png_do_background(png_row_infop row_info, png_bytep row,
  192509. png_color_16p trans_values, png_color_16p background
  192510. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192511. , png_color_16p background_1,
  192512. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  192513. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  192514. png_uint_16pp gamma_16_to_1, int gamma_shift
  192515. #endif
  192516. )
  192517. {
  192518. png_bytep sp, dp;
  192519. png_uint_32 i;
  192520. png_uint_32 row_width=row_info->width;
  192521. int shift;
  192522. png_debug(1, "in png_do_background\n");
  192523. if (background != NULL &&
  192524. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192525. row != NULL && row_info != NULL &&
  192526. #endif
  192527. (!(row_info->color_type & PNG_COLOR_MASK_ALPHA) ||
  192528. (row_info->color_type != PNG_COLOR_TYPE_PALETTE && trans_values)))
  192529. {
  192530. switch (row_info->color_type)
  192531. {
  192532. case PNG_COLOR_TYPE_GRAY:
  192533. {
  192534. switch (row_info->bit_depth)
  192535. {
  192536. case 1:
  192537. {
  192538. sp = row;
  192539. shift = 7;
  192540. for (i = 0; i < row_width; i++)
  192541. {
  192542. if ((png_uint_16)((*sp >> shift) & 0x01)
  192543. == trans_values->gray)
  192544. {
  192545. *sp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  192546. *sp |= (png_byte)(background->gray << shift);
  192547. }
  192548. if (!shift)
  192549. {
  192550. shift = 7;
  192551. sp++;
  192552. }
  192553. else
  192554. shift--;
  192555. }
  192556. break;
  192557. }
  192558. case 2:
  192559. {
  192560. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192561. if (gamma_table != NULL)
  192562. {
  192563. sp = row;
  192564. shift = 6;
  192565. for (i = 0; i < row_width; i++)
  192566. {
  192567. if ((png_uint_16)((*sp >> shift) & 0x03)
  192568. == trans_values->gray)
  192569. {
  192570. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192571. *sp |= (png_byte)(background->gray << shift);
  192572. }
  192573. else
  192574. {
  192575. png_byte p = (png_byte)((*sp >> shift) & 0x03);
  192576. png_byte g = (png_byte)((gamma_table [p | (p << 2) |
  192577. (p << 4) | (p << 6)] >> 6) & 0x03);
  192578. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192579. *sp |= (png_byte)(g << shift);
  192580. }
  192581. if (!shift)
  192582. {
  192583. shift = 6;
  192584. sp++;
  192585. }
  192586. else
  192587. shift -= 2;
  192588. }
  192589. }
  192590. else
  192591. #endif
  192592. {
  192593. sp = row;
  192594. shift = 6;
  192595. for (i = 0; i < row_width; i++)
  192596. {
  192597. if ((png_uint_16)((*sp >> shift) & 0x03)
  192598. == trans_values->gray)
  192599. {
  192600. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192601. *sp |= (png_byte)(background->gray << shift);
  192602. }
  192603. if (!shift)
  192604. {
  192605. shift = 6;
  192606. sp++;
  192607. }
  192608. else
  192609. shift -= 2;
  192610. }
  192611. }
  192612. break;
  192613. }
  192614. case 4:
  192615. {
  192616. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192617. if (gamma_table != NULL)
  192618. {
  192619. sp = row;
  192620. shift = 4;
  192621. for (i = 0; i < row_width; i++)
  192622. {
  192623. if ((png_uint_16)((*sp >> shift) & 0x0f)
  192624. == trans_values->gray)
  192625. {
  192626. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192627. *sp |= (png_byte)(background->gray << shift);
  192628. }
  192629. else
  192630. {
  192631. png_byte p = (png_byte)((*sp >> shift) & 0x0f);
  192632. png_byte g = (png_byte)((gamma_table[p |
  192633. (p << 4)] >> 4) & 0x0f);
  192634. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192635. *sp |= (png_byte)(g << shift);
  192636. }
  192637. if (!shift)
  192638. {
  192639. shift = 4;
  192640. sp++;
  192641. }
  192642. else
  192643. shift -= 4;
  192644. }
  192645. }
  192646. else
  192647. #endif
  192648. {
  192649. sp = row;
  192650. shift = 4;
  192651. for (i = 0; i < row_width; i++)
  192652. {
  192653. if ((png_uint_16)((*sp >> shift) & 0x0f)
  192654. == trans_values->gray)
  192655. {
  192656. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192657. *sp |= (png_byte)(background->gray << shift);
  192658. }
  192659. if (!shift)
  192660. {
  192661. shift = 4;
  192662. sp++;
  192663. }
  192664. else
  192665. shift -= 4;
  192666. }
  192667. }
  192668. break;
  192669. }
  192670. case 8:
  192671. {
  192672. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192673. if (gamma_table != NULL)
  192674. {
  192675. sp = row;
  192676. for (i = 0; i < row_width; i++, sp++)
  192677. {
  192678. if (*sp == trans_values->gray)
  192679. {
  192680. *sp = (png_byte)background->gray;
  192681. }
  192682. else
  192683. {
  192684. *sp = gamma_table[*sp];
  192685. }
  192686. }
  192687. }
  192688. else
  192689. #endif
  192690. {
  192691. sp = row;
  192692. for (i = 0; i < row_width; i++, sp++)
  192693. {
  192694. if (*sp == trans_values->gray)
  192695. {
  192696. *sp = (png_byte)background->gray;
  192697. }
  192698. }
  192699. }
  192700. break;
  192701. }
  192702. case 16:
  192703. {
  192704. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192705. if (gamma_16 != NULL)
  192706. {
  192707. sp = row;
  192708. for (i = 0; i < row_width; i++, sp += 2)
  192709. {
  192710. png_uint_16 v;
  192711. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192712. if (v == trans_values->gray)
  192713. {
  192714. /* background is already in screen gamma */
  192715. *sp = (png_byte)((background->gray >> 8) & 0xff);
  192716. *(sp + 1) = (png_byte)(background->gray & 0xff);
  192717. }
  192718. else
  192719. {
  192720. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192721. *sp = (png_byte)((v >> 8) & 0xff);
  192722. *(sp + 1) = (png_byte)(v & 0xff);
  192723. }
  192724. }
  192725. }
  192726. else
  192727. #endif
  192728. {
  192729. sp = row;
  192730. for (i = 0; i < row_width; i++, sp += 2)
  192731. {
  192732. png_uint_16 v;
  192733. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192734. if (v == trans_values->gray)
  192735. {
  192736. *sp = (png_byte)((background->gray >> 8) & 0xff);
  192737. *(sp + 1) = (png_byte)(background->gray & 0xff);
  192738. }
  192739. }
  192740. }
  192741. break;
  192742. }
  192743. }
  192744. break;
  192745. }
  192746. case PNG_COLOR_TYPE_RGB:
  192747. {
  192748. if (row_info->bit_depth == 8)
  192749. {
  192750. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192751. if (gamma_table != NULL)
  192752. {
  192753. sp = row;
  192754. for (i = 0; i < row_width; i++, sp += 3)
  192755. {
  192756. if (*sp == trans_values->red &&
  192757. *(sp + 1) == trans_values->green &&
  192758. *(sp + 2) == trans_values->blue)
  192759. {
  192760. *sp = (png_byte)background->red;
  192761. *(sp + 1) = (png_byte)background->green;
  192762. *(sp + 2) = (png_byte)background->blue;
  192763. }
  192764. else
  192765. {
  192766. *sp = gamma_table[*sp];
  192767. *(sp + 1) = gamma_table[*(sp + 1)];
  192768. *(sp + 2) = gamma_table[*(sp + 2)];
  192769. }
  192770. }
  192771. }
  192772. else
  192773. #endif
  192774. {
  192775. sp = row;
  192776. for (i = 0; i < row_width; i++, sp += 3)
  192777. {
  192778. if (*sp == trans_values->red &&
  192779. *(sp + 1) == trans_values->green &&
  192780. *(sp + 2) == trans_values->blue)
  192781. {
  192782. *sp = (png_byte)background->red;
  192783. *(sp + 1) = (png_byte)background->green;
  192784. *(sp + 2) = (png_byte)background->blue;
  192785. }
  192786. }
  192787. }
  192788. }
  192789. else /* if (row_info->bit_depth == 16) */
  192790. {
  192791. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192792. if (gamma_16 != NULL)
  192793. {
  192794. sp = row;
  192795. for (i = 0; i < row_width; i++, sp += 6)
  192796. {
  192797. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192798. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192799. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  192800. if (r == trans_values->red && g == trans_values->green &&
  192801. b == trans_values->blue)
  192802. {
  192803. /* background is already in screen gamma */
  192804. *sp = (png_byte)((background->red >> 8) & 0xff);
  192805. *(sp + 1) = (png_byte)(background->red & 0xff);
  192806. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192807. *(sp + 3) = (png_byte)(background->green & 0xff);
  192808. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192809. *(sp + 5) = (png_byte)(background->blue & 0xff);
  192810. }
  192811. else
  192812. {
  192813. png_uint_16 v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192814. *sp = (png_byte)((v >> 8) & 0xff);
  192815. *(sp + 1) = (png_byte)(v & 0xff);
  192816. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  192817. *(sp + 2) = (png_byte)((v >> 8) & 0xff);
  192818. *(sp + 3) = (png_byte)(v & 0xff);
  192819. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  192820. *(sp + 4) = (png_byte)((v >> 8) & 0xff);
  192821. *(sp + 5) = (png_byte)(v & 0xff);
  192822. }
  192823. }
  192824. }
  192825. else
  192826. #endif
  192827. {
  192828. sp = row;
  192829. for (i = 0; i < row_width; i++, sp += 6)
  192830. {
  192831. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp+1));
  192832. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192833. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  192834. if (r == trans_values->red && g == trans_values->green &&
  192835. b == trans_values->blue)
  192836. {
  192837. *sp = (png_byte)((background->red >> 8) & 0xff);
  192838. *(sp + 1) = (png_byte)(background->red & 0xff);
  192839. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192840. *(sp + 3) = (png_byte)(background->green & 0xff);
  192841. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192842. *(sp + 5) = (png_byte)(background->blue & 0xff);
  192843. }
  192844. }
  192845. }
  192846. }
  192847. break;
  192848. }
  192849. case PNG_COLOR_TYPE_GRAY_ALPHA:
  192850. {
  192851. if (row_info->bit_depth == 8)
  192852. {
  192853. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192854. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  192855. gamma_table != NULL)
  192856. {
  192857. sp = row;
  192858. dp = row;
  192859. for (i = 0; i < row_width; i++, sp += 2, dp++)
  192860. {
  192861. png_uint_16 a = *(sp + 1);
  192862. if (a == 0xff)
  192863. {
  192864. *dp = gamma_table[*sp];
  192865. }
  192866. else if (a == 0)
  192867. {
  192868. /* background is already in screen gamma */
  192869. *dp = (png_byte)background->gray;
  192870. }
  192871. else
  192872. {
  192873. png_byte v, w;
  192874. v = gamma_to_1[*sp];
  192875. png_composite(w, v, a, background_1->gray);
  192876. *dp = gamma_from_1[w];
  192877. }
  192878. }
  192879. }
  192880. else
  192881. #endif
  192882. {
  192883. sp = row;
  192884. dp = row;
  192885. for (i = 0; i < row_width; i++, sp += 2, dp++)
  192886. {
  192887. png_byte a = *(sp + 1);
  192888. if (a == 0xff)
  192889. {
  192890. *dp = *sp;
  192891. }
  192892. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192893. else if (a == 0)
  192894. {
  192895. *dp = (png_byte)background->gray;
  192896. }
  192897. else
  192898. {
  192899. png_composite(*dp, *sp, a, background_1->gray);
  192900. }
  192901. #else
  192902. *dp = (png_byte)background->gray;
  192903. #endif
  192904. }
  192905. }
  192906. }
  192907. else /* if (png_ptr->bit_depth == 16) */
  192908. {
  192909. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192910. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  192911. gamma_16_to_1 != NULL)
  192912. {
  192913. sp = row;
  192914. dp = row;
  192915. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  192916. {
  192917. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192918. if (a == (png_uint_16)0xffff)
  192919. {
  192920. png_uint_16 v;
  192921. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192922. *dp = (png_byte)((v >> 8) & 0xff);
  192923. *(dp + 1) = (png_byte)(v & 0xff);
  192924. }
  192925. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192926. else if (a == 0)
  192927. #else
  192928. else
  192929. #endif
  192930. {
  192931. /* background is already in screen gamma */
  192932. *dp = (png_byte)((background->gray >> 8) & 0xff);
  192933. *(dp + 1) = (png_byte)(background->gray & 0xff);
  192934. }
  192935. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192936. else
  192937. {
  192938. png_uint_16 g, v, w;
  192939. g = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  192940. png_composite_16(v, g, a, background_1->gray);
  192941. w = gamma_16_from_1[(v&0xff) >> gamma_shift][v >> 8];
  192942. *dp = (png_byte)((w >> 8) & 0xff);
  192943. *(dp + 1) = (png_byte)(w & 0xff);
  192944. }
  192945. #endif
  192946. }
  192947. }
  192948. else
  192949. #endif
  192950. {
  192951. sp = row;
  192952. dp = row;
  192953. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  192954. {
  192955. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192956. if (a == (png_uint_16)0xffff)
  192957. {
  192958. png_memcpy(dp, sp, 2);
  192959. }
  192960. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192961. else if (a == 0)
  192962. #else
  192963. else
  192964. #endif
  192965. {
  192966. *dp = (png_byte)((background->gray >> 8) & 0xff);
  192967. *(dp + 1) = (png_byte)(background->gray & 0xff);
  192968. }
  192969. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192970. else
  192971. {
  192972. png_uint_16 g, v;
  192973. g = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192974. png_composite_16(v, g, a, background_1->gray);
  192975. *dp = (png_byte)((v >> 8) & 0xff);
  192976. *(dp + 1) = (png_byte)(v & 0xff);
  192977. }
  192978. #endif
  192979. }
  192980. }
  192981. }
  192982. break;
  192983. }
  192984. case PNG_COLOR_TYPE_RGB_ALPHA:
  192985. {
  192986. if (row_info->bit_depth == 8)
  192987. {
  192988. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192989. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  192990. gamma_table != NULL)
  192991. {
  192992. sp = row;
  192993. dp = row;
  192994. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  192995. {
  192996. png_byte a = *(sp + 3);
  192997. if (a == 0xff)
  192998. {
  192999. *dp = gamma_table[*sp];
  193000. *(dp + 1) = gamma_table[*(sp + 1)];
  193001. *(dp + 2) = gamma_table[*(sp + 2)];
  193002. }
  193003. else if (a == 0)
  193004. {
  193005. /* background is already in screen gamma */
  193006. *dp = (png_byte)background->red;
  193007. *(dp + 1) = (png_byte)background->green;
  193008. *(dp + 2) = (png_byte)background->blue;
  193009. }
  193010. else
  193011. {
  193012. png_byte v, w;
  193013. v = gamma_to_1[*sp];
  193014. png_composite(w, v, a, background_1->red);
  193015. *dp = gamma_from_1[w];
  193016. v = gamma_to_1[*(sp + 1)];
  193017. png_composite(w, v, a, background_1->green);
  193018. *(dp + 1) = gamma_from_1[w];
  193019. v = gamma_to_1[*(sp + 2)];
  193020. png_composite(w, v, a, background_1->blue);
  193021. *(dp + 2) = gamma_from_1[w];
  193022. }
  193023. }
  193024. }
  193025. else
  193026. #endif
  193027. {
  193028. sp = row;
  193029. dp = row;
  193030. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  193031. {
  193032. png_byte a = *(sp + 3);
  193033. if (a == 0xff)
  193034. {
  193035. *dp = *sp;
  193036. *(dp + 1) = *(sp + 1);
  193037. *(dp + 2) = *(sp + 2);
  193038. }
  193039. else if (a == 0)
  193040. {
  193041. *dp = (png_byte)background->red;
  193042. *(dp + 1) = (png_byte)background->green;
  193043. *(dp + 2) = (png_byte)background->blue;
  193044. }
  193045. else
  193046. {
  193047. png_composite(*dp, *sp, a, background->red);
  193048. png_composite(*(dp + 1), *(sp + 1), a,
  193049. background->green);
  193050. png_composite(*(dp + 2), *(sp + 2), a,
  193051. background->blue);
  193052. }
  193053. }
  193054. }
  193055. }
  193056. else /* if (row_info->bit_depth == 16) */
  193057. {
  193058. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193059. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  193060. gamma_16_to_1 != NULL)
  193061. {
  193062. sp = row;
  193063. dp = row;
  193064. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  193065. {
  193066. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  193067. << 8) + (png_uint_16)(*(sp + 7)));
  193068. if (a == (png_uint_16)0xffff)
  193069. {
  193070. png_uint_16 v;
  193071. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  193072. *dp = (png_byte)((v >> 8) & 0xff);
  193073. *(dp + 1) = (png_byte)(v & 0xff);
  193074. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  193075. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  193076. *(dp + 3) = (png_byte)(v & 0xff);
  193077. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  193078. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  193079. *(dp + 5) = (png_byte)(v & 0xff);
  193080. }
  193081. else if (a == 0)
  193082. {
  193083. /* background is already in screen gamma */
  193084. *dp = (png_byte)((background->red >> 8) & 0xff);
  193085. *(dp + 1) = (png_byte)(background->red & 0xff);
  193086. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  193087. *(dp + 3) = (png_byte)(background->green & 0xff);
  193088. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  193089. *(dp + 5) = (png_byte)(background->blue & 0xff);
  193090. }
  193091. else
  193092. {
  193093. png_uint_16 v, w, x;
  193094. v = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  193095. png_composite_16(w, v, a, background_1->red);
  193096. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  193097. *dp = (png_byte)((x >> 8) & 0xff);
  193098. *(dp + 1) = (png_byte)(x & 0xff);
  193099. v = gamma_16_to_1[*(sp + 3) >> gamma_shift][*(sp + 2)];
  193100. png_composite_16(w, v, a, background_1->green);
  193101. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  193102. *(dp + 2) = (png_byte)((x >> 8) & 0xff);
  193103. *(dp + 3) = (png_byte)(x & 0xff);
  193104. v = gamma_16_to_1[*(sp + 5) >> gamma_shift][*(sp + 4)];
  193105. png_composite_16(w, v, a, background_1->blue);
  193106. x = gamma_16_from_1[(w & 0xff) >> gamma_shift][w >> 8];
  193107. *(dp + 4) = (png_byte)((x >> 8) & 0xff);
  193108. *(dp + 5) = (png_byte)(x & 0xff);
  193109. }
  193110. }
  193111. }
  193112. else
  193113. #endif
  193114. {
  193115. sp = row;
  193116. dp = row;
  193117. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  193118. {
  193119. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  193120. << 8) + (png_uint_16)(*(sp + 7)));
  193121. if (a == (png_uint_16)0xffff)
  193122. {
  193123. png_memcpy(dp, sp, 6);
  193124. }
  193125. else if (a == 0)
  193126. {
  193127. *dp = (png_byte)((background->red >> 8) & 0xff);
  193128. *(dp + 1) = (png_byte)(background->red & 0xff);
  193129. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  193130. *(dp + 3) = (png_byte)(background->green & 0xff);
  193131. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  193132. *(dp + 5) = (png_byte)(background->blue & 0xff);
  193133. }
  193134. else
  193135. {
  193136. png_uint_16 v;
  193137. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  193138. png_uint_16 g = (png_uint_16)(((*(sp + 2)) << 8)
  193139. + *(sp + 3));
  193140. png_uint_16 b = (png_uint_16)(((*(sp + 4)) << 8)
  193141. + *(sp + 5));
  193142. png_composite_16(v, r, a, background->red);
  193143. *dp = (png_byte)((v >> 8) & 0xff);
  193144. *(dp + 1) = (png_byte)(v & 0xff);
  193145. png_composite_16(v, g, a, background->green);
  193146. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  193147. *(dp + 3) = (png_byte)(v & 0xff);
  193148. png_composite_16(v, b, a, background->blue);
  193149. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  193150. *(dp + 5) = (png_byte)(v & 0xff);
  193151. }
  193152. }
  193153. }
  193154. }
  193155. break;
  193156. }
  193157. }
  193158. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  193159. {
  193160. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  193161. row_info->channels--;
  193162. row_info->pixel_depth = (png_byte)(row_info->channels *
  193163. row_info->bit_depth);
  193164. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193165. }
  193166. }
  193167. }
  193168. #endif
  193169. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193170. /* Gamma correct the image, avoiding the alpha channel. Make sure
  193171. * you do this after you deal with the transparency issue on grayscale
  193172. * or RGB images. If your bit depth is 8, use gamma_table, if it
  193173. * is 16, use gamma_16_table and gamma_shift. Build these with
  193174. * build_gamma_table().
  193175. */
  193176. void /* PRIVATE */
  193177. png_do_gamma(png_row_infop row_info, png_bytep row,
  193178. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  193179. int gamma_shift)
  193180. {
  193181. png_bytep sp;
  193182. png_uint_32 i;
  193183. png_uint_32 row_width=row_info->width;
  193184. png_debug(1, "in png_do_gamma\n");
  193185. if (
  193186. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193187. row != NULL && row_info != NULL &&
  193188. #endif
  193189. ((row_info->bit_depth <= 8 && gamma_table != NULL) ||
  193190. (row_info->bit_depth == 16 && gamma_16_table != NULL)))
  193191. {
  193192. switch (row_info->color_type)
  193193. {
  193194. case PNG_COLOR_TYPE_RGB:
  193195. {
  193196. if (row_info->bit_depth == 8)
  193197. {
  193198. sp = row;
  193199. for (i = 0; i < row_width; i++)
  193200. {
  193201. *sp = gamma_table[*sp];
  193202. sp++;
  193203. *sp = gamma_table[*sp];
  193204. sp++;
  193205. *sp = gamma_table[*sp];
  193206. sp++;
  193207. }
  193208. }
  193209. else /* if (row_info->bit_depth == 16) */
  193210. {
  193211. sp = row;
  193212. for (i = 0; i < row_width; i++)
  193213. {
  193214. png_uint_16 v;
  193215. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193216. *sp = (png_byte)((v >> 8) & 0xff);
  193217. *(sp + 1) = (png_byte)(v & 0xff);
  193218. sp += 2;
  193219. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193220. *sp = (png_byte)((v >> 8) & 0xff);
  193221. *(sp + 1) = (png_byte)(v & 0xff);
  193222. sp += 2;
  193223. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193224. *sp = (png_byte)((v >> 8) & 0xff);
  193225. *(sp + 1) = (png_byte)(v & 0xff);
  193226. sp += 2;
  193227. }
  193228. }
  193229. break;
  193230. }
  193231. case PNG_COLOR_TYPE_RGB_ALPHA:
  193232. {
  193233. if (row_info->bit_depth == 8)
  193234. {
  193235. sp = row;
  193236. for (i = 0; i < row_width; i++)
  193237. {
  193238. *sp = gamma_table[*sp];
  193239. sp++;
  193240. *sp = gamma_table[*sp];
  193241. sp++;
  193242. *sp = gamma_table[*sp];
  193243. sp++;
  193244. sp++;
  193245. }
  193246. }
  193247. else /* if (row_info->bit_depth == 16) */
  193248. {
  193249. sp = row;
  193250. for (i = 0; i < row_width; i++)
  193251. {
  193252. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193253. *sp = (png_byte)((v >> 8) & 0xff);
  193254. *(sp + 1) = (png_byte)(v & 0xff);
  193255. sp += 2;
  193256. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193257. *sp = (png_byte)((v >> 8) & 0xff);
  193258. *(sp + 1) = (png_byte)(v & 0xff);
  193259. sp += 2;
  193260. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193261. *sp = (png_byte)((v >> 8) & 0xff);
  193262. *(sp + 1) = (png_byte)(v & 0xff);
  193263. sp += 4;
  193264. }
  193265. }
  193266. break;
  193267. }
  193268. case PNG_COLOR_TYPE_GRAY_ALPHA:
  193269. {
  193270. if (row_info->bit_depth == 8)
  193271. {
  193272. sp = row;
  193273. for (i = 0; i < row_width; i++)
  193274. {
  193275. *sp = gamma_table[*sp];
  193276. sp += 2;
  193277. }
  193278. }
  193279. else /* if (row_info->bit_depth == 16) */
  193280. {
  193281. sp = row;
  193282. for (i = 0; i < row_width; i++)
  193283. {
  193284. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193285. *sp = (png_byte)((v >> 8) & 0xff);
  193286. *(sp + 1) = (png_byte)(v & 0xff);
  193287. sp += 4;
  193288. }
  193289. }
  193290. break;
  193291. }
  193292. case PNG_COLOR_TYPE_GRAY:
  193293. {
  193294. if (row_info->bit_depth == 2)
  193295. {
  193296. sp = row;
  193297. for (i = 0; i < row_width; i += 4)
  193298. {
  193299. int a = *sp & 0xc0;
  193300. int b = *sp & 0x30;
  193301. int c = *sp & 0x0c;
  193302. int d = *sp & 0x03;
  193303. *sp = (png_byte)(
  193304. ((((int)gamma_table[a|(a>>2)|(a>>4)|(a>>6)]) ) & 0xc0)|
  193305. ((((int)gamma_table[(b<<2)|b|(b>>2)|(b>>4)])>>2) & 0x30)|
  193306. ((((int)gamma_table[(c<<4)|(c<<2)|c|(c>>2)])>>4) & 0x0c)|
  193307. ((((int)gamma_table[(d<<6)|(d<<4)|(d<<2)|d])>>6) ));
  193308. sp++;
  193309. }
  193310. }
  193311. if (row_info->bit_depth == 4)
  193312. {
  193313. sp = row;
  193314. for (i = 0; i < row_width; i += 2)
  193315. {
  193316. int msb = *sp & 0xf0;
  193317. int lsb = *sp & 0x0f;
  193318. *sp = (png_byte)((((int)gamma_table[msb | (msb >> 4)]) & 0xf0)
  193319. | (((int)gamma_table[(lsb << 4) | lsb]) >> 4));
  193320. sp++;
  193321. }
  193322. }
  193323. else if (row_info->bit_depth == 8)
  193324. {
  193325. sp = row;
  193326. for (i = 0; i < row_width; i++)
  193327. {
  193328. *sp = gamma_table[*sp];
  193329. sp++;
  193330. }
  193331. }
  193332. else if (row_info->bit_depth == 16)
  193333. {
  193334. sp = row;
  193335. for (i = 0; i < row_width; i++)
  193336. {
  193337. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193338. *sp = (png_byte)((v >> 8) & 0xff);
  193339. *(sp + 1) = (png_byte)(v & 0xff);
  193340. sp += 2;
  193341. }
  193342. }
  193343. break;
  193344. }
  193345. }
  193346. }
  193347. }
  193348. #endif
  193349. #if defined(PNG_READ_EXPAND_SUPPORTED)
  193350. /* Expands a palette row to an RGB or RGBA row depending
  193351. * upon whether you supply trans and num_trans.
  193352. */
  193353. void /* PRIVATE */
  193354. png_do_expand_palette(png_row_infop row_info, png_bytep row,
  193355. png_colorp palette, png_bytep trans, int num_trans)
  193356. {
  193357. int shift, value;
  193358. png_bytep sp, dp;
  193359. png_uint_32 i;
  193360. png_uint_32 row_width=row_info->width;
  193361. png_debug(1, "in png_do_expand_palette\n");
  193362. if (
  193363. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193364. row != NULL && row_info != NULL &&
  193365. #endif
  193366. row_info->color_type == PNG_COLOR_TYPE_PALETTE)
  193367. {
  193368. if (row_info->bit_depth < 8)
  193369. {
  193370. switch (row_info->bit_depth)
  193371. {
  193372. case 1:
  193373. {
  193374. sp = row + (png_size_t)((row_width - 1) >> 3);
  193375. dp = row + (png_size_t)row_width - 1;
  193376. shift = 7 - (int)((row_width + 7) & 0x07);
  193377. for (i = 0; i < row_width; i++)
  193378. {
  193379. if ((*sp >> shift) & 0x01)
  193380. *dp = 1;
  193381. else
  193382. *dp = 0;
  193383. if (shift == 7)
  193384. {
  193385. shift = 0;
  193386. sp--;
  193387. }
  193388. else
  193389. shift++;
  193390. dp--;
  193391. }
  193392. break;
  193393. }
  193394. case 2:
  193395. {
  193396. sp = row + (png_size_t)((row_width - 1) >> 2);
  193397. dp = row + (png_size_t)row_width - 1;
  193398. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  193399. for (i = 0; i < row_width; i++)
  193400. {
  193401. value = (*sp >> shift) & 0x03;
  193402. *dp = (png_byte)value;
  193403. if (shift == 6)
  193404. {
  193405. shift = 0;
  193406. sp--;
  193407. }
  193408. else
  193409. shift += 2;
  193410. dp--;
  193411. }
  193412. break;
  193413. }
  193414. case 4:
  193415. {
  193416. sp = row + (png_size_t)((row_width - 1) >> 1);
  193417. dp = row + (png_size_t)row_width - 1;
  193418. shift = (int)((row_width & 0x01) << 2);
  193419. for (i = 0; i < row_width; i++)
  193420. {
  193421. value = (*sp >> shift) & 0x0f;
  193422. *dp = (png_byte)value;
  193423. if (shift == 4)
  193424. {
  193425. shift = 0;
  193426. sp--;
  193427. }
  193428. else
  193429. shift += 4;
  193430. dp--;
  193431. }
  193432. break;
  193433. }
  193434. }
  193435. row_info->bit_depth = 8;
  193436. row_info->pixel_depth = 8;
  193437. row_info->rowbytes = row_width;
  193438. }
  193439. switch (row_info->bit_depth)
  193440. {
  193441. case 8:
  193442. {
  193443. if (trans != NULL)
  193444. {
  193445. sp = row + (png_size_t)row_width - 1;
  193446. dp = row + (png_size_t)(row_width << 2) - 1;
  193447. for (i = 0; i < row_width; i++)
  193448. {
  193449. if ((int)(*sp) >= num_trans)
  193450. *dp-- = 0xff;
  193451. else
  193452. *dp-- = trans[*sp];
  193453. *dp-- = palette[*sp].blue;
  193454. *dp-- = palette[*sp].green;
  193455. *dp-- = palette[*sp].red;
  193456. sp--;
  193457. }
  193458. row_info->bit_depth = 8;
  193459. row_info->pixel_depth = 32;
  193460. row_info->rowbytes = row_width * 4;
  193461. row_info->color_type = 6;
  193462. row_info->channels = 4;
  193463. }
  193464. else
  193465. {
  193466. sp = row + (png_size_t)row_width - 1;
  193467. dp = row + (png_size_t)(row_width * 3) - 1;
  193468. for (i = 0; i < row_width; i++)
  193469. {
  193470. *dp-- = palette[*sp].blue;
  193471. *dp-- = palette[*sp].green;
  193472. *dp-- = palette[*sp].red;
  193473. sp--;
  193474. }
  193475. row_info->bit_depth = 8;
  193476. row_info->pixel_depth = 24;
  193477. row_info->rowbytes = row_width * 3;
  193478. row_info->color_type = 2;
  193479. row_info->channels = 3;
  193480. }
  193481. break;
  193482. }
  193483. }
  193484. }
  193485. }
  193486. /* If the bit depth < 8, it is expanded to 8. Also, if the already
  193487. * expanded transparency value is supplied, an alpha channel is built.
  193488. */
  193489. void /* PRIVATE */
  193490. png_do_expand(png_row_infop row_info, png_bytep row,
  193491. png_color_16p trans_value)
  193492. {
  193493. int shift, value;
  193494. png_bytep sp, dp;
  193495. png_uint_32 i;
  193496. png_uint_32 row_width=row_info->width;
  193497. png_debug(1, "in png_do_expand\n");
  193498. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193499. if (row != NULL && row_info != NULL)
  193500. #endif
  193501. {
  193502. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  193503. {
  193504. png_uint_16 gray = (png_uint_16)(trans_value ? trans_value->gray : 0);
  193505. if (row_info->bit_depth < 8)
  193506. {
  193507. switch (row_info->bit_depth)
  193508. {
  193509. case 1:
  193510. {
  193511. gray = (png_uint_16)((gray&0x01)*0xff);
  193512. sp = row + (png_size_t)((row_width - 1) >> 3);
  193513. dp = row + (png_size_t)row_width - 1;
  193514. shift = 7 - (int)((row_width + 7) & 0x07);
  193515. for (i = 0; i < row_width; i++)
  193516. {
  193517. if ((*sp >> shift) & 0x01)
  193518. *dp = 0xff;
  193519. else
  193520. *dp = 0;
  193521. if (shift == 7)
  193522. {
  193523. shift = 0;
  193524. sp--;
  193525. }
  193526. else
  193527. shift++;
  193528. dp--;
  193529. }
  193530. break;
  193531. }
  193532. case 2:
  193533. {
  193534. gray = (png_uint_16)((gray&0x03)*0x55);
  193535. sp = row + (png_size_t)((row_width - 1) >> 2);
  193536. dp = row + (png_size_t)row_width - 1;
  193537. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  193538. for (i = 0; i < row_width; i++)
  193539. {
  193540. value = (*sp >> shift) & 0x03;
  193541. *dp = (png_byte)(value | (value << 2) | (value << 4) |
  193542. (value << 6));
  193543. if (shift == 6)
  193544. {
  193545. shift = 0;
  193546. sp--;
  193547. }
  193548. else
  193549. shift += 2;
  193550. dp--;
  193551. }
  193552. break;
  193553. }
  193554. case 4:
  193555. {
  193556. gray = (png_uint_16)((gray&0x0f)*0x11);
  193557. sp = row + (png_size_t)((row_width - 1) >> 1);
  193558. dp = row + (png_size_t)row_width - 1;
  193559. shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  193560. for (i = 0; i < row_width; i++)
  193561. {
  193562. value = (*sp >> shift) & 0x0f;
  193563. *dp = (png_byte)(value | (value << 4));
  193564. if (shift == 4)
  193565. {
  193566. shift = 0;
  193567. sp--;
  193568. }
  193569. else
  193570. shift = 4;
  193571. dp--;
  193572. }
  193573. break;
  193574. }
  193575. }
  193576. row_info->bit_depth = 8;
  193577. row_info->pixel_depth = 8;
  193578. row_info->rowbytes = row_width;
  193579. }
  193580. if (trans_value != NULL)
  193581. {
  193582. if (row_info->bit_depth == 8)
  193583. {
  193584. gray = gray & 0xff;
  193585. sp = row + (png_size_t)row_width - 1;
  193586. dp = row + (png_size_t)(row_width << 1) - 1;
  193587. for (i = 0; i < row_width; i++)
  193588. {
  193589. if (*sp == gray)
  193590. *dp-- = 0;
  193591. else
  193592. *dp-- = 0xff;
  193593. *dp-- = *sp--;
  193594. }
  193595. }
  193596. else if (row_info->bit_depth == 16)
  193597. {
  193598. png_byte gray_high = (gray >> 8) & 0xff;
  193599. png_byte gray_low = gray & 0xff;
  193600. sp = row + row_info->rowbytes - 1;
  193601. dp = row + (row_info->rowbytes << 1) - 1;
  193602. for (i = 0; i < row_width; i++)
  193603. {
  193604. if (*(sp-1) == gray_high && *(sp) == gray_low)
  193605. {
  193606. *dp-- = 0;
  193607. *dp-- = 0;
  193608. }
  193609. else
  193610. {
  193611. *dp-- = 0xff;
  193612. *dp-- = 0xff;
  193613. }
  193614. *dp-- = *sp--;
  193615. *dp-- = *sp--;
  193616. }
  193617. }
  193618. row_info->color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
  193619. row_info->channels = 2;
  193620. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 1);
  193621. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  193622. row_width);
  193623. }
  193624. }
  193625. else if (row_info->color_type == PNG_COLOR_TYPE_RGB && trans_value)
  193626. {
  193627. if (row_info->bit_depth == 8)
  193628. {
  193629. png_byte red = trans_value->red & 0xff;
  193630. png_byte green = trans_value->green & 0xff;
  193631. png_byte blue = trans_value->blue & 0xff;
  193632. sp = row + (png_size_t)row_info->rowbytes - 1;
  193633. dp = row + (png_size_t)(row_width << 2) - 1;
  193634. for (i = 0; i < row_width; i++)
  193635. {
  193636. if (*(sp - 2) == red && *(sp - 1) == green && *(sp) == blue)
  193637. *dp-- = 0;
  193638. else
  193639. *dp-- = 0xff;
  193640. *dp-- = *sp--;
  193641. *dp-- = *sp--;
  193642. *dp-- = *sp--;
  193643. }
  193644. }
  193645. else if (row_info->bit_depth == 16)
  193646. {
  193647. png_byte red_high = (trans_value->red >> 8) & 0xff;
  193648. png_byte green_high = (trans_value->green >> 8) & 0xff;
  193649. png_byte blue_high = (trans_value->blue >> 8) & 0xff;
  193650. png_byte red_low = trans_value->red & 0xff;
  193651. png_byte green_low = trans_value->green & 0xff;
  193652. png_byte blue_low = trans_value->blue & 0xff;
  193653. sp = row + row_info->rowbytes - 1;
  193654. dp = row + (png_size_t)(row_width << 3) - 1;
  193655. for (i = 0; i < row_width; i++)
  193656. {
  193657. if (*(sp - 5) == red_high &&
  193658. *(sp - 4) == red_low &&
  193659. *(sp - 3) == green_high &&
  193660. *(sp - 2) == green_low &&
  193661. *(sp - 1) == blue_high &&
  193662. *(sp ) == blue_low)
  193663. {
  193664. *dp-- = 0;
  193665. *dp-- = 0;
  193666. }
  193667. else
  193668. {
  193669. *dp-- = 0xff;
  193670. *dp-- = 0xff;
  193671. }
  193672. *dp-- = *sp--;
  193673. *dp-- = *sp--;
  193674. *dp-- = *sp--;
  193675. *dp-- = *sp--;
  193676. *dp-- = *sp--;
  193677. *dp-- = *sp--;
  193678. }
  193679. }
  193680. row_info->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  193681. row_info->channels = 4;
  193682. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 2);
  193683. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193684. }
  193685. }
  193686. }
  193687. #endif
  193688. #if defined(PNG_READ_DITHER_SUPPORTED)
  193689. void /* PRIVATE */
  193690. png_do_dither(png_row_infop row_info, png_bytep row,
  193691. png_bytep palette_lookup, png_bytep dither_lookup)
  193692. {
  193693. png_bytep sp, dp;
  193694. png_uint_32 i;
  193695. png_uint_32 row_width=row_info->width;
  193696. png_debug(1, "in png_do_dither\n");
  193697. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193698. if (row != NULL && row_info != NULL)
  193699. #endif
  193700. {
  193701. if (row_info->color_type == PNG_COLOR_TYPE_RGB &&
  193702. palette_lookup && row_info->bit_depth == 8)
  193703. {
  193704. int r, g, b, p;
  193705. sp = row;
  193706. dp = row;
  193707. for (i = 0; i < row_width; i++)
  193708. {
  193709. r = *sp++;
  193710. g = *sp++;
  193711. b = *sp++;
  193712. /* this looks real messy, but the compiler will reduce
  193713. it down to a reasonable formula. For example, with
  193714. 5 bits per color, we get:
  193715. p = (((r >> 3) & 0x1f) << 10) |
  193716. (((g >> 3) & 0x1f) << 5) |
  193717. ((b >> 3) & 0x1f);
  193718. */
  193719. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  193720. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  193721. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  193722. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  193723. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  193724. (PNG_DITHER_BLUE_BITS)) |
  193725. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  193726. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  193727. *dp++ = palette_lookup[p];
  193728. }
  193729. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  193730. row_info->channels = 1;
  193731. row_info->pixel_depth = row_info->bit_depth;
  193732. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193733. }
  193734. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  193735. palette_lookup != NULL && row_info->bit_depth == 8)
  193736. {
  193737. int r, g, b, p;
  193738. sp = row;
  193739. dp = row;
  193740. for (i = 0; i < row_width; i++)
  193741. {
  193742. r = *sp++;
  193743. g = *sp++;
  193744. b = *sp++;
  193745. sp++;
  193746. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  193747. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  193748. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  193749. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  193750. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  193751. (PNG_DITHER_BLUE_BITS)) |
  193752. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  193753. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  193754. *dp++ = palette_lookup[p];
  193755. }
  193756. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  193757. row_info->channels = 1;
  193758. row_info->pixel_depth = row_info->bit_depth;
  193759. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193760. }
  193761. else if (row_info->color_type == PNG_COLOR_TYPE_PALETTE &&
  193762. dither_lookup && row_info->bit_depth == 8)
  193763. {
  193764. sp = row;
  193765. for (i = 0; i < row_width; i++, sp++)
  193766. {
  193767. *sp = dither_lookup[*sp];
  193768. }
  193769. }
  193770. }
  193771. }
  193772. #endif
  193773. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193774. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193775. static PNG_CONST int png_gamma_shift[] =
  193776. {0x10, 0x21, 0x42, 0x84, 0x110, 0x248, 0x550, 0xff0, 0x00};
  193777. /* We build the 8- or 16-bit gamma tables here. Note that for 16-bit
  193778. * tables, we don't make a full table if we are reducing to 8-bit in
  193779. * the future. Note also how the gamma_16 tables are segmented so that
  193780. * we don't need to allocate > 64K chunks for a full 16-bit table.
  193781. */
  193782. void /* PRIVATE */
  193783. png_build_gamma_table(png_structp png_ptr)
  193784. {
  193785. png_debug(1, "in png_build_gamma_table\n");
  193786. if (png_ptr->bit_depth <= 8)
  193787. {
  193788. int i;
  193789. double g;
  193790. if (png_ptr->screen_gamma > .000001)
  193791. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  193792. else
  193793. g = 1.0;
  193794. png_ptr->gamma_table = (png_bytep)png_malloc(png_ptr,
  193795. (png_uint_32)256);
  193796. for (i = 0; i < 256; i++)
  193797. {
  193798. png_ptr->gamma_table[i] = (png_byte)(pow((double)i / 255.0,
  193799. g) * 255.0 + .5);
  193800. }
  193801. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  193802. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  193803. if (png_ptr->transformations & ((PNG_BACKGROUND) | PNG_RGB_TO_GRAY))
  193804. {
  193805. g = 1.0 / (png_ptr->gamma);
  193806. png_ptr->gamma_to_1 = (png_bytep)png_malloc(png_ptr,
  193807. (png_uint_32)256);
  193808. for (i = 0; i < 256; i++)
  193809. {
  193810. png_ptr->gamma_to_1[i] = (png_byte)(pow((double)i / 255.0,
  193811. g) * 255.0 + .5);
  193812. }
  193813. png_ptr->gamma_from_1 = (png_bytep)png_malloc(png_ptr,
  193814. (png_uint_32)256);
  193815. if(png_ptr->screen_gamma > 0.000001)
  193816. g = 1.0 / png_ptr->screen_gamma;
  193817. else
  193818. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  193819. for (i = 0; i < 256; i++)
  193820. {
  193821. png_ptr->gamma_from_1[i] = (png_byte)(pow((double)i / 255.0,
  193822. g) * 255.0 + .5);
  193823. }
  193824. }
  193825. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  193826. }
  193827. else
  193828. {
  193829. double g;
  193830. int i, j, shift, num;
  193831. int sig_bit;
  193832. png_uint_32 ig;
  193833. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  193834. {
  193835. sig_bit = (int)png_ptr->sig_bit.red;
  193836. if ((int)png_ptr->sig_bit.green > sig_bit)
  193837. sig_bit = png_ptr->sig_bit.green;
  193838. if ((int)png_ptr->sig_bit.blue > sig_bit)
  193839. sig_bit = png_ptr->sig_bit.blue;
  193840. }
  193841. else
  193842. {
  193843. sig_bit = (int)png_ptr->sig_bit.gray;
  193844. }
  193845. if (sig_bit > 0)
  193846. shift = 16 - sig_bit;
  193847. else
  193848. shift = 0;
  193849. if (png_ptr->transformations & PNG_16_TO_8)
  193850. {
  193851. if (shift < (16 - PNG_MAX_GAMMA_8))
  193852. shift = (16 - PNG_MAX_GAMMA_8);
  193853. }
  193854. if (shift > 8)
  193855. shift = 8;
  193856. if (shift < 0)
  193857. shift = 0;
  193858. png_ptr->gamma_shift = (png_byte)shift;
  193859. num = (1 << (8 - shift));
  193860. if (png_ptr->screen_gamma > .000001)
  193861. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  193862. else
  193863. g = 1.0;
  193864. png_ptr->gamma_16_table = (png_uint_16pp)png_malloc(png_ptr,
  193865. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  193866. if (png_ptr->transformations & (PNG_16_TO_8 | PNG_BACKGROUND))
  193867. {
  193868. double fin, fout;
  193869. png_uint_32 last, max;
  193870. for (i = 0; i < num; i++)
  193871. {
  193872. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  193873. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193874. }
  193875. g = 1.0 / g;
  193876. last = 0;
  193877. for (i = 0; i < 256; i++)
  193878. {
  193879. fout = ((double)i + 0.5) / 256.0;
  193880. fin = pow(fout, g);
  193881. max = (png_uint_32)(fin * (double)((png_uint_32)num << 8));
  193882. while (last <= max)
  193883. {
  193884. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  193885. [(int)(last >> (8 - shift))] = (png_uint_16)(
  193886. (png_uint_16)i | ((png_uint_16)i << 8));
  193887. last++;
  193888. }
  193889. }
  193890. while (last < ((png_uint_32)num << 8))
  193891. {
  193892. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  193893. [(int)(last >> (8 - shift))] = (png_uint_16)65535L;
  193894. last++;
  193895. }
  193896. }
  193897. else
  193898. {
  193899. for (i = 0; i < num; i++)
  193900. {
  193901. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  193902. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193903. ig = (((png_uint_32)i * (png_uint_32)png_gamma_shift[shift]) >> 4);
  193904. for (j = 0; j < 256; j++)
  193905. {
  193906. png_ptr->gamma_16_table[i][j] =
  193907. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  193908. 65535.0, g) * 65535.0 + .5);
  193909. }
  193910. }
  193911. }
  193912. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  193913. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  193914. if (png_ptr->transformations & (PNG_BACKGROUND | PNG_RGB_TO_GRAY))
  193915. {
  193916. g = 1.0 / (png_ptr->gamma);
  193917. png_ptr->gamma_16_to_1 = (png_uint_16pp)png_malloc(png_ptr,
  193918. (png_uint_32)(num * png_sizeof (png_uint_16p )));
  193919. for (i = 0; i < num; i++)
  193920. {
  193921. png_ptr->gamma_16_to_1[i] = (png_uint_16p)png_malloc(png_ptr,
  193922. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193923. ig = (((png_uint_32)i *
  193924. (png_uint_32)png_gamma_shift[shift]) >> 4);
  193925. for (j = 0; j < 256; j++)
  193926. {
  193927. png_ptr->gamma_16_to_1[i][j] =
  193928. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  193929. 65535.0, g) * 65535.0 + .5);
  193930. }
  193931. }
  193932. if(png_ptr->screen_gamma > 0.000001)
  193933. g = 1.0 / png_ptr->screen_gamma;
  193934. else
  193935. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  193936. png_ptr->gamma_16_from_1 = (png_uint_16pp)png_malloc(png_ptr,
  193937. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  193938. for (i = 0; i < num; i++)
  193939. {
  193940. png_ptr->gamma_16_from_1[i] = (png_uint_16p)png_malloc(png_ptr,
  193941. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193942. ig = (((png_uint_32)i *
  193943. (png_uint_32)png_gamma_shift[shift]) >> 4);
  193944. for (j = 0; j < 256; j++)
  193945. {
  193946. png_ptr->gamma_16_from_1[i][j] =
  193947. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  193948. 65535.0, g) * 65535.0 + .5);
  193949. }
  193950. }
  193951. }
  193952. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  193953. }
  193954. }
  193955. #endif
  193956. /* To do: install integer version of png_build_gamma_table here */
  193957. #endif
  193958. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  193959. /* undoes intrapixel differencing */
  193960. void /* PRIVATE */
  193961. png_do_read_intrapixel(png_row_infop row_info, png_bytep row)
  193962. {
  193963. png_debug(1, "in png_do_read_intrapixel\n");
  193964. if (
  193965. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193966. row != NULL && row_info != NULL &&
  193967. #endif
  193968. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  193969. {
  193970. int bytes_per_pixel;
  193971. png_uint_32 row_width = row_info->width;
  193972. if (row_info->bit_depth == 8)
  193973. {
  193974. png_bytep rp;
  193975. png_uint_32 i;
  193976. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  193977. bytes_per_pixel = 3;
  193978. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193979. bytes_per_pixel = 4;
  193980. else
  193981. return;
  193982. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  193983. {
  193984. *(rp) = (png_byte)((256 + *rp + *(rp+1))&0xff);
  193985. *(rp+2) = (png_byte)((256 + *(rp+2) + *(rp+1))&0xff);
  193986. }
  193987. }
  193988. else if (row_info->bit_depth == 16)
  193989. {
  193990. png_bytep rp;
  193991. png_uint_32 i;
  193992. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  193993. bytes_per_pixel = 6;
  193994. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193995. bytes_per_pixel = 8;
  193996. else
  193997. return;
  193998. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  193999. {
  194000. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  194001. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  194002. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  194003. png_uint_32 red = (png_uint_32)((s0+s1+65536L) & 0xffffL);
  194004. png_uint_32 blue = (png_uint_32)((s2+s1+65536L) & 0xffffL);
  194005. *(rp ) = (png_byte)((red >> 8) & 0xff);
  194006. *(rp+1) = (png_byte)(red & 0xff);
  194007. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  194008. *(rp+5) = (png_byte)(blue & 0xff);
  194009. }
  194010. }
  194011. }
  194012. }
  194013. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  194014. #endif /* PNG_READ_SUPPORTED */
  194015. /*** End of inlined file: pngrtran.c ***/
  194016. /*** Start of inlined file: pngrutil.c ***/
  194017. /* pngrutil.c - utilities to read a PNG file
  194018. *
  194019. * Last changed in libpng 1.2.21 [October 4, 2007]
  194020. * For conditions of distribution and use, see copyright notice in png.h
  194021. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  194022. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  194023. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  194024. *
  194025. * This file contains routines that are only called from within
  194026. * libpng itself during the course of reading an image.
  194027. */
  194028. #define PNG_INTERNAL
  194029. #if defined(PNG_READ_SUPPORTED)
  194030. #if defined(_WIN32_WCE) && (_WIN32_WCE<0x500)
  194031. # define WIN32_WCE_OLD
  194032. #endif
  194033. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194034. # if defined(WIN32_WCE_OLD)
  194035. /* strtod() function is not supported on WindowsCE */
  194036. __inline double png_strtod(png_structp png_ptr, PNG_CONST char *nptr, char **endptr)
  194037. {
  194038. double result = 0;
  194039. int len;
  194040. wchar_t *str, *end;
  194041. len = MultiByteToWideChar(CP_ACP, 0, nptr, -1, NULL, 0);
  194042. str = (wchar_t *)png_malloc(png_ptr, len * sizeof(wchar_t));
  194043. if ( NULL != str )
  194044. {
  194045. MultiByteToWideChar(CP_ACP, 0, nptr, -1, str, len);
  194046. result = wcstod(str, &end);
  194047. len = WideCharToMultiByte(CP_ACP, 0, end, -1, NULL, 0, NULL, NULL);
  194048. *endptr = (char *)nptr + (png_strlen(nptr) - len + 1);
  194049. png_free(png_ptr, str);
  194050. }
  194051. return result;
  194052. }
  194053. # else
  194054. # define png_strtod(p,a,b) strtod(a,b)
  194055. # endif
  194056. #endif
  194057. png_uint_32 PNGAPI
  194058. png_get_uint_31(png_structp png_ptr, png_bytep buf)
  194059. {
  194060. png_uint_32 i = png_get_uint_32(buf);
  194061. if (i > PNG_UINT_31_MAX)
  194062. png_error(png_ptr, "PNG unsigned integer out of range.");
  194063. return (i);
  194064. }
  194065. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  194066. /* Grab an unsigned 32-bit integer from a buffer in big-endian format. */
  194067. png_uint_32 PNGAPI
  194068. png_get_uint_32(png_bytep buf)
  194069. {
  194070. png_uint_32 i = ((png_uint_32)(*buf) << 24) +
  194071. ((png_uint_32)(*(buf + 1)) << 16) +
  194072. ((png_uint_32)(*(buf + 2)) << 8) +
  194073. (png_uint_32)(*(buf + 3));
  194074. return (i);
  194075. }
  194076. /* Grab a signed 32-bit integer from a buffer in big-endian format. The
  194077. * data is stored in the PNG file in two's complement format, and it is
  194078. * assumed that the machine format for signed integers is the same. */
  194079. png_int_32 PNGAPI
  194080. png_get_int_32(png_bytep buf)
  194081. {
  194082. png_int_32 i = ((png_int_32)(*buf) << 24) +
  194083. ((png_int_32)(*(buf + 1)) << 16) +
  194084. ((png_int_32)(*(buf + 2)) << 8) +
  194085. (png_int_32)(*(buf + 3));
  194086. return (i);
  194087. }
  194088. /* Grab an unsigned 16-bit integer from a buffer in big-endian format. */
  194089. png_uint_16 PNGAPI
  194090. png_get_uint_16(png_bytep buf)
  194091. {
  194092. png_uint_16 i = (png_uint_16)(((png_uint_16)(*buf) << 8) +
  194093. (png_uint_16)(*(buf + 1)));
  194094. return (i);
  194095. }
  194096. #endif /* PNG_READ_BIG_ENDIAN_SUPPORTED */
  194097. /* Read data, and (optionally) run it through the CRC. */
  194098. void /* PRIVATE */
  194099. png_crc_read(png_structp png_ptr, png_bytep buf, png_size_t length)
  194100. {
  194101. if(png_ptr == NULL) return;
  194102. png_read_data(png_ptr, buf, length);
  194103. png_calculate_crc(png_ptr, buf, length);
  194104. }
  194105. /* Optionally skip data and then check the CRC. Depending on whether we
  194106. are reading a ancillary or critical chunk, and how the program has set
  194107. things up, we may calculate the CRC on the data and print a message.
  194108. Returns '1' if there was a CRC error, '0' otherwise. */
  194109. int /* PRIVATE */
  194110. png_crc_finish(png_structp png_ptr, png_uint_32 skip)
  194111. {
  194112. png_size_t i;
  194113. png_size_t istop = png_ptr->zbuf_size;
  194114. for (i = (png_size_t)skip; i > istop; i -= istop)
  194115. {
  194116. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  194117. }
  194118. if (i)
  194119. {
  194120. png_crc_read(png_ptr, png_ptr->zbuf, i);
  194121. }
  194122. if (png_crc_error(png_ptr))
  194123. {
  194124. if (((png_ptr->chunk_name[0] & 0x20) && /* Ancillary */
  194125. !(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)) ||
  194126. (!(png_ptr->chunk_name[0] & 0x20) && /* Critical */
  194127. (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_USE)))
  194128. {
  194129. png_chunk_warning(png_ptr, "CRC error");
  194130. }
  194131. else
  194132. {
  194133. png_chunk_error(png_ptr, "CRC error");
  194134. }
  194135. return (1);
  194136. }
  194137. return (0);
  194138. }
  194139. /* Compare the CRC stored in the PNG file with that calculated by libpng from
  194140. the data it has read thus far. */
  194141. int /* PRIVATE */
  194142. png_crc_error(png_structp png_ptr)
  194143. {
  194144. png_byte crc_bytes[4];
  194145. png_uint_32 crc;
  194146. int need_crc = 1;
  194147. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  194148. {
  194149. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  194150. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  194151. need_crc = 0;
  194152. }
  194153. else /* critical */
  194154. {
  194155. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  194156. need_crc = 0;
  194157. }
  194158. png_read_data(png_ptr, crc_bytes, 4);
  194159. if (need_crc)
  194160. {
  194161. crc = png_get_uint_32(crc_bytes);
  194162. return ((int)(crc != png_ptr->crc));
  194163. }
  194164. else
  194165. return (0);
  194166. }
  194167. #if defined(PNG_READ_zTXt_SUPPORTED) || defined(PNG_READ_iTXt_SUPPORTED) || \
  194168. defined(PNG_READ_iCCP_SUPPORTED)
  194169. /*
  194170. * Decompress trailing data in a chunk. The assumption is that chunkdata
  194171. * points at an allocated area holding the contents of a chunk with a
  194172. * trailing compressed part. What we get back is an allocated area
  194173. * holding the original prefix part and an uncompressed version of the
  194174. * trailing part (the malloc area passed in is freed).
  194175. */
  194176. png_charp /* PRIVATE */
  194177. png_decompress_chunk(png_structp png_ptr, int comp_type,
  194178. png_charp chunkdata, png_size_t chunklength,
  194179. png_size_t prefix_size, png_size_t *newlength)
  194180. {
  194181. static PNG_CONST char msg[] = "Error decoding compressed text";
  194182. png_charp text;
  194183. png_size_t text_size;
  194184. if (comp_type == PNG_COMPRESSION_TYPE_BASE)
  194185. {
  194186. int ret = Z_OK;
  194187. png_ptr->zstream.next_in = (png_bytep)(chunkdata + prefix_size);
  194188. png_ptr->zstream.avail_in = (uInt)(chunklength - prefix_size);
  194189. png_ptr->zstream.next_out = png_ptr->zbuf;
  194190. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  194191. text_size = 0;
  194192. text = NULL;
  194193. while (png_ptr->zstream.avail_in)
  194194. {
  194195. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  194196. if (ret != Z_OK && ret != Z_STREAM_END)
  194197. {
  194198. if (png_ptr->zstream.msg != NULL)
  194199. png_warning(png_ptr, png_ptr->zstream.msg);
  194200. else
  194201. png_warning(png_ptr, msg);
  194202. inflateReset(&png_ptr->zstream);
  194203. png_ptr->zstream.avail_in = 0;
  194204. if (text == NULL)
  194205. {
  194206. text_size = prefix_size + png_sizeof(msg) + 1;
  194207. text = (png_charp)png_malloc_warn(png_ptr, text_size);
  194208. if (text == NULL)
  194209. {
  194210. png_free(png_ptr,chunkdata);
  194211. png_error(png_ptr,"Not enough memory to decompress chunk");
  194212. }
  194213. png_memcpy(text, chunkdata, prefix_size);
  194214. }
  194215. text[text_size - 1] = 0x00;
  194216. /* Copy what we can of the error message into the text chunk */
  194217. text_size = (png_size_t)(chunklength - (text - chunkdata) - 1);
  194218. text_size = png_sizeof(msg) > text_size ? text_size :
  194219. png_sizeof(msg);
  194220. png_memcpy(text + prefix_size, msg, text_size + 1);
  194221. break;
  194222. }
  194223. if (!png_ptr->zstream.avail_out || ret == Z_STREAM_END)
  194224. {
  194225. if (text == NULL)
  194226. {
  194227. text_size = prefix_size +
  194228. png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  194229. text = (png_charp)png_malloc_warn(png_ptr, text_size + 1);
  194230. if (text == NULL)
  194231. {
  194232. png_free(png_ptr,chunkdata);
  194233. png_error(png_ptr,"Not enough memory to decompress chunk.");
  194234. }
  194235. png_memcpy(text + prefix_size, png_ptr->zbuf,
  194236. text_size - prefix_size);
  194237. png_memcpy(text, chunkdata, prefix_size);
  194238. *(text + text_size) = 0x00;
  194239. }
  194240. else
  194241. {
  194242. png_charp tmp;
  194243. tmp = text;
  194244. text = (png_charp)png_malloc_warn(png_ptr,
  194245. (png_uint_32)(text_size +
  194246. png_ptr->zbuf_size - png_ptr->zstream.avail_out + 1));
  194247. if (text == NULL)
  194248. {
  194249. png_free(png_ptr, tmp);
  194250. png_free(png_ptr, chunkdata);
  194251. png_error(png_ptr,"Not enough memory to decompress chunk..");
  194252. }
  194253. png_memcpy(text, tmp, text_size);
  194254. png_free(png_ptr, tmp);
  194255. png_memcpy(text + text_size, png_ptr->zbuf,
  194256. (png_ptr->zbuf_size - png_ptr->zstream.avail_out));
  194257. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  194258. *(text + text_size) = 0x00;
  194259. }
  194260. if (ret == Z_STREAM_END)
  194261. break;
  194262. else
  194263. {
  194264. png_ptr->zstream.next_out = png_ptr->zbuf;
  194265. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  194266. }
  194267. }
  194268. }
  194269. if (ret != Z_STREAM_END)
  194270. {
  194271. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  194272. char umsg[52];
  194273. if (ret == Z_BUF_ERROR)
  194274. png_snprintf(umsg, 52,
  194275. "Buffer error in compressed datastream in %s chunk",
  194276. png_ptr->chunk_name);
  194277. else if (ret == Z_DATA_ERROR)
  194278. png_snprintf(umsg, 52,
  194279. "Data error in compressed datastream in %s chunk",
  194280. png_ptr->chunk_name);
  194281. else
  194282. png_snprintf(umsg, 52,
  194283. "Incomplete compressed datastream in %s chunk",
  194284. png_ptr->chunk_name);
  194285. png_warning(png_ptr, umsg);
  194286. #else
  194287. png_warning(png_ptr,
  194288. "Incomplete compressed datastream in chunk other than IDAT");
  194289. #endif
  194290. text_size=prefix_size;
  194291. if (text == NULL)
  194292. {
  194293. text = (png_charp)png_malloc_warn(png_ptr, text_size+1);
  194294. if (text == NULL)
  194295. {
  194296. png_free(png_ptr, chunkdata);
  194297. png_error(png_ptr,"Not enough memory for text.");
  194298. }
  194299. png_memcpy(text, chunkdata, prefix_size);
  194300. }
  194301. *(text + text_size) = 0x00;
  194302. }
  194303. inflateReset(&png_ptr->zstream);
  194304. png_ptr->zstream.avail_in = 0;
  194305. png_free(png_ptr, chunkdata);
  194306. chunkdata = text;
  194307. *newlength=text_size;
  194308. }
  194309. else /* if (comp_type != PNG_COMPRESSION_TYPE_BASE) */
  194310. {
  194311. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  194312. char umsg[50];
  194313. png_snprintf(umsg, 50,
  194314. "Unknown zTXt compression type %d", comp_type);
  194315. png_warning(png_ptr, umsg);
  194316. #else
  194317. png_warning(png_ptr, "Unknown zTXt compression type");
  194318. #endif
  194319. *(chunkdata + prefix_size) = 0x00;
  194320. *newlength=prefix_size;
  194321. }
  194322. return chunkdata;
  194323. }
  194324. #endif
  194325. /* read and check the IDHR chunk */
  194326. void /* PRIVATE */
  194327. png_handle_IHDR(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194328. {
  194329. png_byte buf[13];
  194330. png_uint_32 width, height;
  194331. int bit_depth, color_type, compression_type, filter_type;
  194332. int interlace_type;
  194333. png_debug(1, "in png_handle_IHDR\n");
  194334. if (png_ptr->mode & PNG_HAVE_IHDR)
  194335. png_error(png_ptr, "Out of place IHDR");
  194336. /* check the length */
  194337. if (length != 13)
  194338. png_error(png_ptr, "Invalid IHDR chunk");
  194339. png_ptr->mode |= PNG_HAVE_IHDR;
  194340. png_crc_read(png_ptr, buf, 13);
  194341. png_crc_finish(png_ptr, 0);
  194342. width = png_get_uint_31(png_ptr, buf);
  194343. height = png_get_uint_31(png_ptr, buf + 4);
  194344. bit_depth = buf[8];
  194345. color_type = buf[9];
  194346. compression_type = buf[10];
  194347. filter_type = buf[11];
  194348. interlace_type = buf[12];
  194349. /* set internal variables */
  194350. png_ptr->width = width;
  194351. png_ptr->height = height;
  194352. png_ptr->bit_depth = (png_byte)bit_depth;
  194353. png_ptr->interlaced = (png_byte)interlace_type;
  194354. png_ptr->color_type = (png_byte)color_type;
  194355. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  194356. png_ptr->filter_type = (png_byte)filter_type;
  194357. #endif
  194358. png_ptr->compression_type = (png_byte)compression_type;
  194359. /* find number of channels */
  194360. switch (png_ptr->color_type)
  194361. {
  194362. case PNG_COLOR_TYPE_GRAY:
  194363. case PNG_COLOR_TYPE_PALETTE:
  194364. png_ptr->channels = 1;
  194365. break;
  194366. case PNG_COLOR_TYPE_RGB:
  194367. png_ptr->channels = 3;
  194368. break;
  194369. case PNG_COLOR_TYPE_GRAY_ALPHA:
  194370. png_ptr->channels = 2;
  194371. break;
  194372. case PNG_COLOR_TYPE_RGB_ALPHA:
  194373. png_ptr->channels = 4;
  194374. break;
  194375. }
  194376. /* set up other useful info */
  194377. png_ptr->pixel_depth = (png_byte)(png_ptr->bit_depth *
  194378. png_ptr->channels);
  194379. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->width);
  194380. png_debug1(3,"bit_depth = %d\n", png_ptr->bit_depth);
  194381. png_debug1(3,"channels = %d\n", png_ptr->channels);
  194382. png_debug1(3,"rowbytes = %lu\n", png_ptr->rowbytes);
  194383. png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
  194384. color_type, interlace_type, compression_type, filter_type);
  194385. }
  194386. /* read and check the palette */
  194387. void /* PRIVATE */
  194388. png_handle_PLTE(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194389. {
  194390. png_color palette[PNG_MAX_PALETTE_LENGTH];
  194391. int num, i;
  194392. #ifndef PNG_NO_POINTER_INDEXING
  194393. png_colorp pal_ptr;
  194394. #endif
  194395. png_debug(1, "in png_handle_PLTE\n");
  194396. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194397. png_error(png_ptr, "Missing IHDR before PLTE");
  194398. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194399. {
  194400. png_warning(png_ptr, "Invalid PLTE after IDAT");
  194401. png_crc_finish(png_ptr, length);
  194402. return;
  194403. }
  194404. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194405. png_error(png_ptr, "Duplicate PLTE chunk");
  194406. png_ptr->mode |= PNG_HAVE_PLTE;
  194407. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  194408. {
  194409. png_warning(png_ptr,
  194410. "Ignoring PLTE chunk in grayscale PNG");
  194411. png_crc_finish(png_ptr, length);
  194412. return;
  194413. }
  194414. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194415. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  194416. {
  194417. png_crc_finish(png_ptr, length);
  194418. return;
  194419. }
  194420. #endif
  194421. if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3)
  194422. {
  194423. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  194424. {
  194425. png_warning(png_ptr, "Invalid palette chunk");
  194426. png_crc_finish(png_ptr, length);
  194427. return;
  194428. }
  194429. else
  194430. {
  194431. png_error(png_ptr, "Invalid palette chunk");
  194432. }
  194433. }
  194434. num = (int)length / 3;
  194435. #ifndef PNG_NO_POINTER_INDEXING
  194436. for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++)
  194437. {
  194438. png_byte buf[3];
  194439. png_crc_read(png_ptr, buf, 3);
  194440. pal_ptr->red = buf[0];
  194441. pal_ptr->green = buf[1];
  194442. pal_ptr->blue = buf[2];
  194443. }
  194444. #else
  194445. for (i = 0; i < num; i++)
  194446. {
  194447. png_byte buf[3];
  194448. png_crc_read(png_ptr, buf, 3);
  194449. /* don't depend upon png_color being any order */
  194450. palette[i].red = buf[0];
  194451. palette[i].green = buf[1];
  194452. palette[i].blue = buf[2];
  194453. }
  194454. #endif
  194455. /* If we actually NEED the PLTE chunk (ie for a paletted image), we do
  194456. whatever the normal CRC configuration tells us. However, if we
  194457. have an RGB image, the PLTE can be considered ancillary, so
  194458. we will act as though it is. */
  194459. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194460. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194461. #endif
  194462. {
  194463. png_crc_finish(png_ptr, 0);
  194464. }
  194465. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194466. else if (png_crc_error(png_ptr)) /* Only if we have a CRC error */
  194467. {
  194468. /* If we don't want to use the data from an ancillary chunk,
  194469. we have two options: an error abort, or a warning and we
  194470. ignore the data in this chunk (which should be OK, since
  194471. it's considered ancillary for a RGB or RGBA image). */
  194472. if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE))
  194473. {
  194474. if (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)
  194475. {
  194476. png_chunk_error(png_ptr, "CRC error");
  194477. }
  194478. else
  194479. {
  194480. png_chunk_warning(png_ptr, "CRC error");
  194481. return;
  194482. }
  194483. }
  194484. /* Otherwise, we (optionally) emit a warning and use the chunk. */
  194485. else if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN))
  194486. {
  194487. png_chunk_warning(png_ptr, "CRC error");
  194488. }
  194489. }
  194490. #endif
  194491. png_set_PLTE(png_ptr, info_ptr, palette, num);
  194492. #if defined(PNG_READ_tRNS_SUPPORTED)
  194493. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194494. {
  194495. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  194496. {
  194497. if (png_ptr->num_trans > (png_uint_16)num)
  194498. {
  194499. png_warning(png_ptr, "Truncating incorrect tRNS chunk length");
  194500. png_ptr->num_trans = (png_uint_16)num;
  194501. }
  194502. if (info_ptr->num_trans > (png_uint_16)num)
  194503. {
  194504. png_warning(png_ptr, "Truncating incorrect info tRNS chunk length");
  194505. info_ptr->num_trans = (png_uint_16)num;
  194506. }
  194507. }
  194508. }
  194509. #endif
  194510. }
  194511. void /* PRIVATE */
  194512. png_handle_IEND(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194513. {
  194514. png_debug(1, "in png_handle_IEND\n");
  194515. if (!(png_ptr->mode & PNG_HAVE_IHDR) || !(png_ptr->mode & PNG_HAVE_IDAT))
  194516. {
  194517. png_error(png_ptr, "No image in file");
  194518. }
  194519. png_ptr->mode |= (PNG_AFTER_IDAT | PNG_HAVE_IEND);
  194520. if (length != 0)
  194521. {
  194522. png_warning(png_ptr, "Incorrect IEND chunk length");
  194523. }
  194524. png_crc_finish(png_ptr, length);
  194525. info_ptr =info_ptr; /* quiet compiler warnings about unused info_ptr */
  194526. }
  194527. #if defined(PNG_READ_gAMA_SUPPORTED)
  194528. void /* PRIVATE */
  194529. png_handle_gAMA(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194530. {
  194531. png_fixed_point igamma;
  194532. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194533. float file_gamma;
  194534. #endif
  194535. png_byte buf[4];
  194536. png_debug(1, "in png_handle_gAMA\n");
  194537. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194538. png_error(png_ptr, "Missing IHDR before gAMA");
  194539. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194540. {
  194541. png_warning(png_ptr, "Invalid gAMA after IDAT");
  194542. png_crc_finish(png_ptr, length);
  194543. return;
  194544. }
  194545. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194546. /* Should be an error, but we can cope with it */
  194547. png_warning(png_ptr, "Out of place gAMA chunk");
  194548. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  194549. #if defined(PNG_READ_sRGB_SUPPORTED)
  194550. && !(info_ptr->valid & PNG_INFO_sRGB)
  194551. #endif
  194552. )
  194553. {
  194554. png_warning(png_ptr, "Duplicate gAMA chunk");
  194555. png_crc_finish(png_ptr, length);
  194556. return;
  194557. }
  194558. if (length != 4)
  194559. {
  194560. png_warning(png_ptr, "Incorrect gAMA chunk length");
  194561. png_crc_finish(png_ptr, length);
  194562. return;
  194563. }
  194564. png_crc_read(png_ptr, buf, 4);
  194565. if (png_crc_finish(png_ptr, 0))
  194566. return;
  194567. igamma = (png_fixed_point)png_get_uint_32(buf);
  194568. /* check for zero gamma */
  194569. if (igamma == 0)
  194570. {
  194571. png_warning(png_ptr,
  194572. "Ignoring gAMA chunk with gamma=0");
  194573. return;
  194574. }
  194575. #if defined(PNG_READ_sRGB_SUPPORTED)
  194576. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  194577. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  194578. {
  194579. png_warning(png_ptr,
  194580. "Ignoring incorrect gAMA value when sRGB is also present");
  194581. #ifndef PNG_NO_CONSOLE_IO
  194582. fprintf(stderr, "gamma = (%d/100000)\n", (int)igamma);
  194583. #endif
  194584. return;
  194585. }
  194586. #endif /* PNG_READ_sRGB_SUPPORTED */
  194587. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194588. file_gamma = (float)igamma / (float)100000.0;
  194589. # ifdef PNG_READ_GAMMA_SUPPORTED
  194590. png_ptr->gamma = file_gamma;
  194591. # endif
  194592. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  194593. #endif
  194594. #ifdef PNG_FIXED_POINT_SUPPORTED
  194595. png_set_gAMA_fixed(png_ptr, info_ptr, igamma);
  194596. #endif
  194597. }
  194598. #endif
  194599. #if defined(PNG_READ_sBIT_SUPPORTED)
  194600. void /* PRIVATE */
  194601. png_handle_sBIT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194602. {
  194603. png_size_t truelen;
  194604. png_byte buf[4];
  194605. png_debug(1, "in png_handle_sBIT\n");
  194606. buf[0] = buf[1] = buf[2] = buf[3] = 0;
  194607. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194608. png_error(png_ptr, "Missing IHDR before sBIT");
  194609. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194610. {
  194611. png_warning(png_ptr, "Invalid sBIT after IDAT");
  194612. png_crc_finish(png_ptr, length);
  194613. return;
  194614. }
  194615. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194616. {
  194617. /* Should be an error, but we can cope with it */
  194618. png_warning(png_ptr, "Out of place sBIT chunk");
  194619. }
  194620. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT))
  194621. {
  194622. png_warning(png_ptr, "Duplicate sBIT chunk");
  194623. png_crc_finish(png_ptr, length);
  194624. return;
  194625. }
  194626. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194627. truelen = 3;
  194628. else
  194629. truelen = (png_size_t)png_ptr->channels;
  194630. if (length != truelen || length > 4)
  194631. {
  194632. png_warning(png_ptr, "Incorrect sBIT chunk length");
  194633. png_crc_finish(png_ptr, length);
  194634. return;
  194635. }
  194636. png_crc_read(png_ptr, buf, truelen);
  194637. if (png_crc_finish(png_ptr, 0))
  194638. return;
  194639. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  194640. {
  194641. png_ptr->sig_bit.red = buf[0];
  194642. png_ptr->sig_bit.green = buf[1];
  194643. png_ptr->sig_bit.blue = buf[2];
  194644. png_ptr->sig_bit.alpha = buf[3];
  194645. }
  194646. else
  194647. {
  194648. png_ptr->sig_bit.gray = buf[0];
  194649. png_ptr->sig_bit.red = buf[0];
  194650. png_ptr->sig_bit.green = buf[0];
  194651. png_ptr->sig_bit.blue = buf[0];
  194652. png_ptr->sig_bit.alpha = buf[1];
  194653. }
  194654. png_set_sBIT(png_ptr, info_ptr, &(png_ptr->sig_bit));
  194655. }
  194656. #endif
  194657. #if defined(PNG_READ_cHRM_SUPPORTED)
  194658. void /* PRIVATE */
  194659. png_handle_cHRM(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194660. {
  194661. png_byte buf[4];
  194662. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194663. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  194664. #endif
  194665. png_fixed_point int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  194666. int_y_green, int_x_blue, int_y_blue;
  194667. png_uint_32 uint_x, uint_y;
  194668. png_debug(1, "in png_handle_cHRM\n");
  194669. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194670. png_error(png_ptr, "Missing IHDR before cHRM");
  194671. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194672. {
  194673. png_warning(png_ptr, "Invalid cHRM after IDAT");
  194674. png_crc_finish(png_ptr, length);
  194675. return;
  194676. }
  194677. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194678. /* Should be an error, but we can cope with it */
  194679. png_warning(png_ptr, "Missing PLTE before cHRM");
  194680. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM)
  194681. #if defined(PNG_READ_sRGB_SUPPORTED)
  194682. && !(info_ptr->valid & PNG_INFO_sRGB)
  194683. #endif
  194684. )
  194685. {
  194686. png_warning(png_ptr, "Duplicate cHRM chunk");
  194687. png_crc_finish(png_ptr, length);
  194688. return;
  194689. }
  194690. if (length != 32)
  194691. {
  194692. png_warning(png_ptr, "Incorrect cHRM chunk length");
  194693. png_crc_finish(png_ptr, length);
  194694. return;
  194695. }
  194696. png_crc_read(png_ptr, buf, 4);
  194697. uint_x = png_get_uint_32(buf);
  194698. png_crc_read(png_ptr, buf, 4);
  194699. uint_y = png_get_uint_32(buf);
  194700. if (uint_x > 80000L || uint_y > 80000L ||
  194701. uint_x + uint_y > 100000L)
  194702. {
  194703. png_warning(png_ptr, "Invalid cHRM white point");
  194704. png_crc_finish(png_ptr, 24);
  194705. return;
  194706. }
  194707. int_x_white = (png_fixed_point)uint_x;
  194708. int_y_white = (png_fixed_point)uint_y;
  194709. png_crc_read(png_ptr, buf, 4);
  194710. uint_x = png_get_uint_32(buf);
  194711. png_crc_read(png_ptr, buf, 4);
  194712. uint_y = png_get_uint_32(buf);
  194713. if (uint_x + uint_y > 100000L)
  194714. {
  194715. png_warning(png_ptr, "Invalid cHRM red point");
  194716. png_crc_finish(png_ptr, 16);
  194717. return;
  194718. }
  194719. int_x_red = (png_fixed_point)uint_x;
  194720. int_y_red = (png_fixed_point)uint_y;
  194721. png_crc_read(png_ptr, buf, 4);
  194722. uint_x = png_get_uint_32(buf);
  194723. png_crc_read(png_ptr, buf, 4);
  194724. uint_y = png_get_uint_32(buf);
  194725. if (uint_x + uint_y > 100000L)
  194726. {
  194727. png_warning(png_ptr, "Invalid cHRM green point");
  194728. png_crc_finish(png_ptr, 8);
  194729. return;
  194730. }
  194731. int_x_green = (png_fixed_point)uint_x;
  194732. int_y_green = (png_fixed_point)uint_y;
  194733. png_crc_read(png_ptr, buf, 4);
  194734. uint_x = png_get_uint_32(buf);
  194735. png_crc_read(png_ptr, buf, 4);
  194736. uint_y = png_get_uint_32(buf);
  194737. if (uint_x + uint_y > 100000L)
  194738. {
  194739. png_warning(png_ptr, "Invalid cHRM blue point");
  194740. png_crc_finish(png_ptr, 0);
  194741. return;
  194742. }
  194743. int_x_blue = (png_fixed_point)uint_x;
  194744. int_y_blue = (png_fixed_point)uint_y;
  194745. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194746. white_x = (float)int_x_white / (float)100000.0;
  194747. white_y = (float)int_y_white / (float)100000.0;
  194748. red_x = (float)int_x_red / (float)100000.0;
  194749. red_y = (float)int_y_red / (float)100000.0;
  194750. green_x = (float)int_x_green / (float)100000.0;
  194751. green_y = (float)int_y_green / (float)100000.0;
  194752. blue_x = (float)int_x_blue / (float)100000.0;
  194753. blue_y = (float)int_y_blue / (float)100000.0;
  194754. #endif
  194755. #if defined(PNG_READ_sRGB_SUPPORTED)
  194756. if ((info_ptr != NULL) && (info_ptr->valid & PNG_INFO_sRGB))
  194757. {
  194758. if (PNG_OUT_OF_RANGE(int_x_white, 31270, 1000) ||
  194759. PNG_OUT_OF_RANGE(int_y_white, 32900, 1000) ||
  194760. PNG_OUT_OF_RANGE(int_x_red, 64000L, 1000) ||
  194761. PNG_OUT_OF_RANGE(int_y_red, 33000, 1000) ||
  194762. PNG_OUT_OF_RANGE(int_x_green, 30000, 1000) ||
  194763. PNG_OUT_OF_RANGE(int_y_green, 60000L, 1000) ||
  194764. PNG_OUT_OF_RANGE(int_x_blue, 15000, 1000) ||
  194765. PNG_OUT_OF_RANGE(int_y_blue, 6000, 1000))
  194766. {
  194767. png_warning(png_ptr,
  194768. "Ignoring incorrect cHRM value when sRGB is also present");
  194769. #ifndef PNG_NO_CONSOLE_IO
  194770. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194771. fprintf(stderr,"wx=%f, wy=%f, rx=%f, ry=%f\n",
  194772. white_x, white_y, red_x, red_y);
  194773. fprintf(stderr,"gx=%f, gy=%f, bx=%f, by=%f\n",
  194774. green_x, green_y, blue_x, blue_y);
  194775. #else
  194776. fprintf(stderr,"wx=%ld, wy=%ld, rx=%ld, ry=%ld\n",
  194777. int_x_white, int_y_white, int_x_red, int_y_red);
  194778. fprintf(stderr,"gx=%ld, gy=%ld, bx=%ld, by=%ld\n",
  194779. int_x_green, int_y_green, int_x_blue, int_y_blue);
  194780. #endif
  194781. #endif /* PNG_NO_CONSOLE_IO */
  194782. }
  194783. png_crc_finish(png_ptr, 0);
  194784. return;
  194785. }
  194786. #endif /* PNG_READ_sRGB_SUPPORTED */
  194787. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194788. png_set_cHRM(png_ptr, info_ptr,
  194789. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  194790. #endif
  194791. #ifdef PNG_FIXED_POINT_SUPPORTED
  194792. png_set_cHRM_fixed(png_ptr, info_ptr,
  194793. int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  194794. int_y_green, int_x_blue, int_y_blue);
  194795. #endif
  194796. if (png_crc_finish(png_ptr, 0))
  194797. return;
  194798. }
  194799. #endif
  194800. #if defined(PNG_READ_sRGB_SUPPORTED)
  194801. void /* PRIVATE */
  194802. png_handle_sRGB(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194803. {
  194804. int intent;
  194805. png_byte buf[1];
  194806. png_debug(1, "in png_handle_sRGB\n");
  194807. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194808. png_error(png_ptr, "Missing IHDR before sRGB");
  194809. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194810. {
  194811. png_warning(png_ptr, "Invalid sRGB after IDAT");
  194812. png_crc_finish(png_ptr, length);
  194813. return;
  194814. }
  194815. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194816. /* Should be an error, but we can cope with it */
  194817. png_warning(png_ptr, "Out of place sRGB chunk");
  194818. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  194819. {
  194820. png_warning(png_ptr, "Duplicate sRGB chunk");
  194821. png_crc_finish(png_ptr, length);
  194822. return;
  194823. }
  194824. if (length != 1)
  194825. {
  194826. png_warning(png_ptr, "Incorrect sRGB chunk length");
  194827. png_crc_finish(png_ptr, length);
  194828. return;
  194829. }
  194830. png_crc_read(png_ptr, buf, 1);
  194831. if (png_crc_finish(png_ptr, 0))
  194832. return;
  194833. intent = buf[0];
  194834. /* check for bad intent */
  194835. if (intent >= PNG_sRGB_INTENT_LAST)
  194836. {
  194837. png_warning(png_ptr, "Unknown sRGB intent");
  194838. return;
  194839. }
  194840. #if defined(PNG_READ_gAMA_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  194841. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA))
  194842. {
  194843. png_fixed_point igamma;
  194844. #ifdef PNG_FIXED_POINT_SUPPORTED
  194845. igamma=info_ptr->int_gamma;
  194846. #else
  194847. # ifdef PNG_FLOATING_POINT_SUPPORTED
  194848. igamma=(png_fixed_point)(info_ptr->gamma * 100000.);
  194849. # endif
  194850. #endif
  194851. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  194852. {
  194853. png_warning(png_ptr,
  194854. "Ignoring incorrect gAMA value when sRGB is also present");
  194855. #ifndef PNG_NO_CONSOLE_IO
  194856. # ifdef PNG_FIXED_POINT_SUPPORTED
  194857. fprintf(stderr,"incorrect gamma=(%d/100000)\n",(int)png_ptr->int_gamma);
  194858. # else
  194859. # ifdef PNG_FLOATING_POINT_SUPPORTED
  194860. fprintf(stderr,"incorrect gamma=%f\n",png_ptr->gamma);
  194861. # endif
  194862. # endif
  194863. #endif
  194864. }
  194865. }
  194866. #endif /* PNG_READ_gAMA_SUPPORTED */
  194867. #ifdef PNG_READ_cHRM_SUPPORTED
  194868. #ifdef PNG_FIXED_POINT_SUPPORTED
  194869. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  194870. if (PNG_OUT_OF_RANGE(info_ptr->int_x_white, 31270, 1000) ||
  194871. PNG_OUT_OF_RANGE(info_ptr->int_y_white, 32900, 1000) ||
  194872. PNG_OUT_OF_RANGE(info_ptr->int_x_red, 64000L, 1000) ||
  194873. PNG_OUT_OF_RANGE(info_ptr->int_y_red, 33000, 1000) ||
  194874. PNG_OUT_OF_RANGE(info_ptr->int_x_green, 30000, 1000) ||
  194875. PNG_OUT_OF_RANGE(info_ptr->int_y_green, 60000L, 1000) ||
  194876. PNG_OUT_OF_RANGE(info_ptr->int_x_blue, 15000, 1000) ||
  194877. PNG_OUT_OF_RANGE(info_ptr->int_y_blue, 6000, 1000))
  194878. {
  194879. png_warning(png_ptr,
  194880. "Ignoring incorrect cHRM value when sRGB is also present");
  194881. }
  194882. #endif /* PNG_FIXED_POINT_SUPPORTED */
  194883. #endif /* PNG_READ_cHRM_SUPPORTED */
  194884. png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr, intent);
  194885. }
  194886. #endif /* PNG_READ_sRGB_SUPPORTED */
  194887. #if defined(PNG_READ_iCCP_SUPPORTED)
  194888. void /* PRIVATE */
  194889. png_handle_iCCP(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194890. /* Note: this does not properly handle chunks that are > 64K under DOS */
  194891. {
  194892. png_charp chunkdata;
  194893. png_byte compression_type;
  194894. png_bytep pC;
  194895. png_charp profile;
  194896. png_uint_32 skip = 0;
  194897. png_uint_32 profile_size, profile_length;
  194898. png_size_t slength, prefix_length, data_length;
  194899. png_debug(1, "in png_handle_iCCP\n");
  194900. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194901. png_error(png_ptr, "Missing IHDR before iCCP");
  194902. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194903. {
  194904. png_warning(png_ptr, "Invalid iCCP after IDAT");
  194905. png_crc_finish(png_ptr, length);
  194906. return;
  194907. }
  194908. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194909. /* Should be an error, but we can cope with it */
  194910. png_warning(png_ptr, "Out of place iCCP chunk");
  194911. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP))
  194912. {
  194913. png_warning(png_ptr, "Duplicate iCCP chunk");
  194914. png_crc_finish(png_ptr, length);
  194915. return;
  194916. }
  194917. #ifdef PNG_MAX_MALLOC_64K
  194918. if (length > (png_uint_32)65535L)
  194919. {
  194920. png_warning(png_ptr, "iCCP chunk too large to fit in memory");
  194921. skip = length - (png_uint_32)65535L;
  194922. length = (png_uint_32)65535L;
  194923. }
  194924. #endif
  194925. chunkdata = (png_charp)png_malloc(png_ptr, length + 1);
  194926. slength = (png_size_t)length;
  194927. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  194928. if (png_crc_finish(png_ptr, skip))
  194929. {
  194930. png_free(png_ptr, chunkdata);
  194931. return;
  194932. }
  194933. chunkdata[slength] = 0x00;
  194934. for (profile = chunkdata; *profile; profile++)
  194935. /* empty loop to find end of name */ ;
  194936. ++profile;
  194937. /* there should be at least one zero (the compression type byte)
  194938. following the separator, and we should be on it */
  194939. if ( profile >= chunkdata + slength - 1)
  194940. {
  194941. png_free(png_ptr, chunkdata);
  194942. png_warning(png_ptr, "Malformed iCCP chunk");
  194943. return;
  194944. }
  194945. /* compression_type should always be zero */
  194946. compression_type = *profile++;
  194947. if (compression_type)
  194948. {
  194949. png_warning(png_ptr, "Ignoring nonzero compression type in iCCP chunk");
  194950. compression_type=0x00; /* Reset it to zero (libpng-1.0.6 through 1.0.8
  194951. wrote nonzero) */
  194952. }
  194953. prefix_length = profile - chunkdata;
  194954. chunkdata = png_decompress_chunk(png_ptr, compression_type, chunkdata,
  194955. slength, prefix_length, &data_length);
  194956. profile_length = data_length - prefix_length;
  194957. if ( prefix_length > data_length || profile_length < 4)
  194958. {
  194959. png_free(png_ptr, chunkdata);
  194960. png_warning(png_ptr, "Profile size field missing from iCCP chunk");
  194961. return;
  194962. }
  194963. /* Check the profile_size recorded in the first 32 bits of the ICC profile */
  194964. pC = (png_bytep)(chunkdata+prefix_length);
  194965. profile_size = ((*(pC ))<<24) |
  194966. ((*(pC+1))<<16) |
  194967. ((*(pC+2))<< 8) |
  194968. ((*(pC+3)) );
  194969. if(profile_size < profile_length)
  194970. profile_length = profile_size;
  194971. if(profile_size > profile_length)
  194972. {
  194973. png_free(png_ptr, chunkdata);
  194974. png_warning(png_ptr, "Ignoring truncated iCCP profile.");
  194975. return;
  194976. }
  194977. png_set_iCCP(png_ptr, info_ptr, chunkdata, compression_type,
  194978. chunkdata + prefix_length, profile_length);
  194979. png_free(png_ptr, chunkdata);
  194980. }
  194981. #endif /* PNG_READ_iCCP_SUPPORTED */
  194982. #if defined(PNG_READ_sPLT_SUPPORTED)
  194983. void /* PRIVATE */
  194984. png_handle_sPLT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194985. /* Note: this does not properly handle chunks that are > 64K under DOS */
  194986. {
  194987. png_bytep chunkdata;
  194988. png_bytep entry_start;
  194989. png_sPLT_t new_palette;
  194990. #ifdef PNG_NO_POINTER_INDEXING
  194991. png_sPLT_entryp pp;
  194992. #endif
  194993. int data_length, entry_size, i;
  194994. png_uint_32 skip = 0;
  194995. png_size_t slength;
  194996. png_debug(1, "in png_handle_sPLT\n");
  194997. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194998. png_error(png_ptr, "Missing IHDR before sPLT");
  194999. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195000. {
  195001. png_warning(png_ptr, "Invalid sPLT after IDAT");
  195002. png_crc_finish(png_ptr, length);
  195003. return;
  195004. }
  195005. #ifdef PNG_MAX_MALLOC_64K
  195006. if (length > (png_uint_32)65535L)
  195007. {
  195008. png_warning(png_ptr, "sPLT chunk too large to fit in memory");
  195009. skip = length - (png_uint_32)65535L;
  195010. length = (png_uint_32)65535L;
  195011. }
  195012. #endif
  195013. chunkdata = (png_bytep)png_malloc(png_ptr, length + 1);
  195014. slength = (png_size_t)length;
  195015. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195016. if (png_crc_finish(png_ptr, skip))
  195017. {
  195018. png_free(png_ptr, chunkdata);
  195019. return;
  195020. }
  195021. chunkdata[slength] = 0x00;
  195022. for (entry_start = chunkdata; *entry_start; entry_start++)
  195023. /* empty loop to find end of name */ ;
  195024. ++entry_start;
  195025. /* a sample depth should follow the separator, and we should be on it */
  195026. if (entry_start > chunkdata + slength - 2)
  195027. {
  195028. png_free(png_ptr, chunkdata);
  195029. png_warning(png_ptr, "malformed sPLT chunk");
  195030. return;
  195031. }
  195032. new_palette.depth = *entry_start++;
  195033. entry_size = (new_palette.depth == 8 ? 6 : 10);
  195034. data_length = (slength - (entry_start - chunkdata));
  195035. /* integrity-check the data length */
  195036. if (data_length % entry_size)
  195037. {
  195038. png_free(png_ptr, chunkdata);
  195039. png_warning(png_ptr, "sPLT chunk has bad length");
  195040. return;
  195041. }
  195042. new_palette.nentries = (png_int_32) ( data_length / entry_size);
  195043. if ((png_uint_32) new_palette.nentries > (png_uint_32) (PNG_SIZE_MAX /
  195044. png_sizeof(png_sPLT_entry)))
  195045. {
  195046. png_warning(png_ptr, "sPLT chunk too long");
  195047. return;
  195048. }
  195049. new_palette.entries = (png_sPLT_entryp)png_malloc_warn(
  195050. png_ptr, new_palette.nentries * png_sizeof(png_sPLT_entry));
  195051. if (new_palette.entries == NULL)
  195052. {
  195053. png_warning(png_ptr, "sPLT chunk requires too much memory");
  195054. return;
  195055. }
  195056. #ifndef PNG_NO_POINTER_INDEXING
  195057. for (i = 0; i < new_palette.nentries; i++)
  195058. {
  195059. png_sPLT_entryp pp = new_palette.entries + i;
  195060. if (new_palette.depth == 8)
  195061. {
  195062. pp->red = *entry_start++;
  195063. pp->green = *entry_start++;
  195064. pp->blue = *entry_start++;
  195065. pp->alpha = *entry_start++;
  195066. }
  195067. else
  195068. {
  195069. pp->red = png_get_uint_16(entry_start); entry_start += 2;
  195070. pp->green = png_get_uint_16(entry_start); entry_start += 2;
  195071. pp->blue = png_get_uint_16(entry_start); entry_start += 2;
  195072. pp->alpha = png_get_uint_16(entry_start); entry_start += 2;
  195073. }
  195074. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  195075. }
  195076. #else
  195077. pp = new_palette.entries;
  195078. for (i = 0; i < new_palette.nentries; i++)
  195079. {
  195080. if (new_palette.depth == 8)
  195081. {
  195082. pp[i].red = *entry_start++;
  195083. pp[i].green = *entry_start++;
  195084. pp[i].blue = *entry_start++;
  195085. pp[i].alpha = *entry_start++;
  195086. }
  195087. else
  195088. {
  195089. pp[i].red = png_get_uint_16(entry_start); entry_start += 2;
  195090. pp[i].green = png_get_uint_16(entry_start); entry_start += 2;
  195091. pp[i].blue = png_get_uint_16(entry_start); entry_start += 2;
  195092. pp[i].alpha = png_get_uint_16(entry_start); entry_start += 2;
  195093. }
  195094. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  195095. }
  195096. #endif
  195097. /* discard all chunk data except the name and stash that */
  195098. new_palette.name = (png_charp)chunkdata;
  195099. png_set_sPLT(png_ptr, info_ptr, &new_palette, 1);
  195100. png_free(png_ptr, chunkdata);
  195101. png_free(png_ptr, new_palette.entries);
  195102. }
  195103. #endif /* PNG_READ_sPLT_SUPPORTED */
  195104. #if defined(PNG_READ_tRNS_SUPPORTED)
  195105. void /* PRIVATE */
  195106. png_handle_tRNS(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195107. {
  195108. png_byte readbuf[PNG_MAX_PALETTE_LENGTH];
  195109. int bit_mask;
  195110. png_debug(1, "in png_handle_tRNS\n");
  195111. /* For non-indexed color, mask off any bits in the tRNS value that
  195112. * exceed the bit depth. Some creators were writing extra bits there.
  195113. * This is not needed for indexed color. */
  195114. bit_mask = (1 << png_ptr->bit_depth) - 1;
  195115. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195116. png_error(png_ptr, "Missing IHDR before tRNS");
  195117. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195118. {
  195119. png_warning(png_ptr, "Invalid tRNS after IDAT");
  195120. png_crc_finish(png_ptr, length);
  195121. return;
  195122. }
  195123. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  195124. {
  195125. png_warning(png_ptr, "Duplicate tRNS chunk");
  195126. png_crc_finish(png_ptr, length);
  195127. return;
  195128. }
  195129. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  195130. {
  195131. png_byte buf[2];
  195132. if (length != 2)
  195133. {
  195134. png_warning(png_ptr, "Incorrect tRNS chunk length");
  195135. png_crc_finish(png_ptr, length);
  195136. return;
  195137. }
  195138. png_crc_read(png_ptr, buf, 2);
  195139. png_ptr->num_trans = 1;
  195140. png_ptr->trans_values.gray = png_get_uint_16(buf) & bit_mask;
  195141. }
  195142. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  195143. {
  195144. png_byte buf[6];
  195145. if (length != 6)
  195146. {
  195147. png_warning(png_ptr, "Incorrect tRNS chunk length");
  195148. png_crc_finish(png_ptr, length);
  195149. return;
  195150. }
  195151. png_crc_read(png_ptr, buf, (png_size_t)length);
  195152. png_ptr->num_trans = 1;
  195153. png_ptr->trans_values.red = png_get_uint_16(buf) & bit_mask;
  195154. png_ptr->trans_values.green = png_get_uint_16(buf + 2) & bit_mask;
  195155. png_ptr->trans_values.blue = png_get_uint_16(buf + 4) & bit_mask;
  195156. }
  195157. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195158. {
  195159. if (!(png_ptr->mode & PNG_HAVE_PLTE))
  195160. {
  195161. /* Should be an error, but we can cope with it. */
  195162. png_warning(png_ptr, "Missing PLTE before tRNS");
  195163. }
  195164. if (length > (png_uint_32)png_ptr->num_palette ||
  195165. length > PNG_MAX_PALETTE_LENGTH)
  195166. {
  195167. png_warning(png_ptr, "Incorrect tRNS chunk length");
  195168. png_crc_finish(png_ptr, length);
  195169. return;
  195170. }
  195171. if (length == 0)
  195172. {
  195173. png_warning(png_ptr, "Zero length tRNS chunk");
  195174. png_crc_finish(png_ptr, length);
  195175. return;
  195176. }
  195177. png_crc_read(png_ptr, readbuf, (png_size_t)length);
  195178. png_ptr->num_trans = (png_uint_16)length;
  195179. }
  195180. else
  195181. {
  195182. png_warning(png_ptr, "tRNS chunk not allowed with alpha channel");
  195183. png_crc_finish(png_ptr, length);
  195184. return;
  195185. }
  195186. if (png_crc_finish(png_ptr, 0))
  195187. {
  195188. png_ptr->num_trans = 0;
  195189. return;
  195190. }
  195191. png_set_tRNS(png_ptr, info_ptr, readbuf, png_ptr->num_trans,
  195192. &(png_ptr->trans_values));
  195193. }
  195194. #endif
  195195. #if defined(PNG_READ_bKGD_SUPPORTED)
  195196. void /* PRIVATE */
  195197. png_handle_bKGD(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195198. {
  195199. png_size_t truelen;
  195200. png_byte buf[6];
  195201. png_debug(1, "in png_handle_bKGD\n");
  195202. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195203. png_error(png_ptr, "Missing IHDR before bKGD");
  195204. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195205. {
  195206. png_warning(png_ptr, "Invalid bKGD after IDAT");
  195207. png_crc_finish(png_ptr, length);
  195208. return;
  195209. }
  195210. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  195211. !(png_ptr->mode & PNG_HAVE_PLTE))
  195212. {
  195213. png_warning(png_ptr, "Missing PLTE before bKGD");
  195214. png_crc_finish(png_ptr, length);
  195215. return;
  195216. }
  195217. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD))
  195218. {
  195219. png_warning(png_ptr, "Duplicate bKGD chunk");
  195220. png_crc_finish(png_ptr, length);
  195221. return;
  195222. }
  195223. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195224. truelen = 1;
  195225. else if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  195226. truelen = 6;
  195227. else
  195228. truelen = 2;
  195229. if (length != truelen)
  195230. {
  195231. png_warning(png_ptr, "Incorrect bKGD chunk length");
  195232. png_crc_finish(png_ptr, length);
  195233. return;
  195234. }
  195235. png_crc_read(png_ptr, buf, truelen);
  195236. if (png_crc_finish(png_ptr, 0))
  195237. return;
  195238. /* We convert the index value into RGB components so that we can allow
  195239. * arbitrary RGB values for background when we have transparency, and
  195240. * so it is easy to determine the RGB values of the background color
  195241. * from the info_ptr struct. */
  195242. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195243. {
  195244. png_ptr->background.index = buf[0];
  195245. if(info_ptr->num_palette)
  195246. {
  195247. if(buf[0] > info_ptr->num_palette)
  195248. {
  195249. png_warning(png_ptr, "Incorrect bKGD chunk index value");
  195250. return;
  195251. }
  195252. png_ptr->background.red =
  195253. (png_uint_16)png_ptr->palette[buf[0]].red;
  195254. png_ptr->background.green =
  195255. (png_uint_16)png_ptr->palette[buf[0]].green;
  195256. png_ptr->background.blue =
  195257. (png_uint_16)png_ptr->palette[buf[0]].blue;
  195258. }
  195259. }
  195260. else if (!(png_ptr->color_type & PNG_COLOR_MASK_COLOR)) /* GRAY */
  195261. {
  195262. png_ptr->background.red =
  195263. png_ptr->background.green =
  195264. png_ptr->background.blue =
  195265. png_ptr->background.gray = png_get_uint_16(buf);
  195266. }
  195267. else
  195268. {
  195269. png_ptr->background.red = png_get_uint_16(buf);
  195270. png_ptr->background.green = png_get_uint_16(buf + 2);
  195271. png_ptr->background.blue = png_get_uint_16(buf + 4);
  195272. }
  195273. png_set_bKGD(png_ptr, info_ptr, &(png_ptr->background));
  195274. }
  195275. #endif
  195276. #if defined(PNG_READ_hIST_SUPPORTED)
  195277. void /* PRIVATE */
  195278. png_handle_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195279. {
  195280. unsigned int num, i;
  195281. png_uint_16 readbuf[PNG_MAX_PALETTE_LENGTH];
  195282. png_debug(1, "in png_handle_hIST\n");
  195283. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195284. png_error(png_ptr, "Missing IHDR before hIST");
  195285. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195286. {
  195287. png_warning(png_ptr, "Invalid hIST after IDAT");
  195288. png_crc_finish(png_ptr, length);
  195289. return;
  195290. }
  195291. else if (!(png_ptr->mode & PNG_HAVE_PLTE))
  195292. {
  195293. png_warning(png_ptr, "Missing PLTE before hIST");
  195294. png_crc_finish(png_ptr, length);
  195295. return;
  195296. }
  195297. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST))
  195298. {
  195299. png_warning(png_ptr, "Duplicate hIST chunk");
  195300. png_crc_finish(png_ptr, length);
  195301. return;
  195302. }
  195303. num = length / 2 ;
  195304. if (num != (unsigned int) png_ptr->num_palette || num >
  195305. (unsigned int) PNG_MAX_PALETTE_LENGTH)
  195306. {
  195307. png_warning(png_ptr, "Incorrect hIST chunk length");
  195308. png_crc_finish(png_ptr, length);
  195309. return;
  195310. }
  195311. for (i = 0; i < num; i++)
  195312. {
  195313. png_byte buf[2];
  195314. png_crc_read(png_ptr, buf, 2);
  195315. readbuf[i] = png_get_uint_16(buf);
  195316. }
  195317. if (png_crc_finish(png_ptr, 0))
  195318. return;
  195319. png_set_hIST(png_ptr, info_ptr, readbuf);
  195320. }
  195321. #endif
  195322. #if defined(PNG_READ_pHYs_SUPPORTED)
  195323. void /* PRIVATE */
  195324. png_handle_pHYs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195325. {
  195326. png_byte buf[9];
  195327. png_uint_32 res_x, res_y;
  195328. int unit_type;
  195329. png_debug(1, "in png_handle_pHYs\n");
  195330. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195331. png_error(png_ptr, "Missing IHDR before pHYs");
  195332. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195333. {
  195334. png_warning(png_ptr, "Invalid pHYs after IDAT");
  195335. png_crc_finish(png_ptr, length);
  195336. return;
  195337. }
  195338. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  195339. {
  195340. png_warning(png_ptr, "Duplicate pHYs chunk");
  195341. png_crc_finish(png_ptr, length);
  195342. return;
  195343. }
  195344. if (length != 9)
  195345. {
  195346. png_warning(png_ptr, "Incorrect pHYs chunk length");
  195347. png_crc_finish(png_ptr, length);
  195348. return;
  195349. }
  195350. png_crc_read(png_ptr, buf, 9);
  195351. if (png_crc_finish(png_ptr, 0))
  195352. return;
  195353. res_x = png_get_uint_32(buf);
  195354. res_y = png_get_uint_32(buf + 4);
  195355. unit_type = buf[8];
  195356. png_set_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type);
  195357. }
  195358. #endif
  195359. #if defined(PNG_READ_oFFs_SUPPORTED)
  195360. void /* PRIVATE */
  195361. png_handle_oFFs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195362. {
  195363. png_byte buf[9];
  195364. png_int_32 offset_x, offset_y;
  195365. int unit_type;
  195366. png_debug(1, "in png_handle_oFFs\n");
  195367. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195368. png_error(png_ptr, "Missing IHDR before oFFs");
  195369. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195370. {
  195371. png_warning(png_ptr, "Invalid oFFs after IDAT");
  195372. png_crc_finish(png_ptr, length);
  195373. return;
  195374. }
  195375. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs))
  195376. {
  195377. png_warning(png_ptr, "Duplicate oFFs chunk");
  195378. png_crc_finish(png_ptr, length);
  195379. return;
  195380. }
  195381. if (length != 9)
  195382. {
  195383. png_warning(png_ptr, "Incorrect oFFs chunk length");
  195384. png_crc_finish(png_ptr, length);
  195385. return;
  195386. }
  195387. png_crc_read(png_ptr, buf, 9);
  195388. if (png_crc_finish(png_ptr, 0))
  195389. return;
  195390. offset_x = png_get_int_32(buf);
  195391. offset_y = png_get_int_32(buf + 4);
  195392. unit_type = buf[8];
  195393. png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y, unit_type);
  195394. }
  195395. #endif
  195396. #if defined(PNG_READ_pCAL_SUPPORTED)
  195397. /* read the pCAL chunk (described in the PNG Extensions document) */
  195398. void /* PRIVATE */
  195399. png_handle_pCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195400. {
  195401. png_charp purpose;
  195402. png_int_32 X0, X1;
  195403. png_byte type, nparams;
  195404. png_charp buf, units, endptr;
  195405. png_charpp params;
  195406. png_size_t slength;
  195407. int i;
  195408. png_debug(1, "in png_handle_pCAL\n");
  195409. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195410. png_error(png_ptr, "Missing IHDR before pCAL");
  195411. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195412. {
  195413. png_warning(png_ptr, "Invalid pCAL after IDAT");
  195414. png_crc_finish(png_ptr, length);
  195415. return;
  195416. }
  195417. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL))
  195418. {
  195419. png_warning(png_ptr, "Duplicate pCAL chunk");
  195420. png_crc_finish(png_ptr, length);
  195421. return;
  195422. }
  195423. png_debug1(2, "Allocating and reading pCAL chunk data (%lu bytes)\n",
  195424. length + 1);
  195425. purpose = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195426. if (purpose == NULL)
  195427. {
  195428. png_warning(png_ptr, "No memory for pCAL purpose.");
  195429. return;
  195430. }
  195431. slength = (png_size_t)length;
  195432. png_crc_read(png_ptr, (png_bytep)purpose, slength);
  195433. if (png_crc_finish(png_ptr, 0))
  195434. {
  195435. png_free(png_ptr, purpose);
  195436. return;
  195437. }
  195438. purpose[slength] = 0x00; /* null terminate the last string */
  195439. png_debug(3, "Finding end of pCAL purpose string\n");
  195440. for (buf = purpose; *buf; buf++)
  195441. /* empty loop */ ;
  195442. endptr = purpose + slength;
  195443. /* We need to have at least 12 bytes after the purpose string
  195444. in order to get the parameter information. */
  195445. if (endptr <= buf + 12)
  195446. {
  195447. png_warning(png_ptr, "Invalid pCAL data");
  195448. png_free(png_ptr, purpose);
  195449. return;
  195450. }
  195451. png_debug(3, "Reading pCAL X0, X1, type, nparams, and units\n");
  195452. X0 = png_get_int_32((png_bytep)buf+1);
  195453. X1 = png_get_int_32((png_bytep)buf+5);
  195454. type = buf[9];
  195455. nparams = buf[10];
  195456. units = buf + 11;
  195457. png_debug(3, "Checking pCAL equation type and number of parameters\n");
  195458. /* Check that we have the right number of parameters for known
  195459. equation types. */
  195460. if ((type == PNG_EQUATION_LINEAR && nparams != 2) ||
  195461. (type == PNG_EQUATION_BASE_E && nparams != 3) ||
  195462. (type == PNG_EQUATION_ARBITRARY && nparams != 3) ||
  195463. (type == PNG_EQUATION_HYPERBOLIC && nparams != 4))
  195464. {
  195465. png_warning(png_ptr, "Invalid pCAL parameters for equation type");
  195466. png_free(png_ptr, purpose);
  195467. return;
  195468. }
  195469. else if (type >= PNG_EQUATION_LAST)
  195470. {
  195471. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  195472. }
  195473. for (buf = units; *buf; buf++)
  195474. /* Empty loop to move past the units string. */ ;
  195475. png_debug(3, "Allocating pCAL parameters array\n");
  195476. params = (png_charpp)png_malloc_warn(png_ptr, (png_uint_32)(nparams
  195477. *png_sizeof(png_charp))) ;
  195478. if (params == NULL)
  195479. {
  195480. png_free(png_ptr, purpose);
  195481. png_warning(png_ptr, "No memory for pCAL params.");
  195482. return;
  195483. }
  195484. /* Get pointers to the start of each parameter string. */
  195485. for (i = 0; i < (int)nparams; i++)
  195486. {
  195487. buf++; /* Skip the null string terminator from previous parameter. */
  195488. png_debug1(3, "Reading pCAL parameter %d\n", i);
  195489. for (params[i] = buf; buf <= endptr && *buf != 0x00; buf++)
  195490. /* Empty loop to move past each parameter string */ ;
  195491. /* Make sure we haven't run out of data yet */
  195492. if (buf > endptr)
  195493. {
  195494. png_warning(png_ptr, "Invalid pCAL data");
  195495. png_free(png_ptr, purpose);
  195496. png_free(png_ptr, params);
  195497. return;
  195498. }
  195499. }
  195500. png_set_pCAL(png_ptr, info_ptr, purpose, X0, X1, type, nparams,
  195501. units, params);
  195502. png_free(png_ptr, purpose);
  195503. png_free(png_ptr, params);
  195504. }
  195505. #endif
  195506. #if defined(PNG_READ_sCAL_SUPPORTED)
  195507. /* read the sCAL chunk */
  195508. void /* PRIVATE */
  195509. png_handle_sCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195510. {
  195511. png_charp buffer, ep;
  195512. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195513. double width, height;
  195514. png_charp vp;
  195515. #else
  195516. #ifdef PNG_FIXED_POINT_SUPPORTED
  195517. png_charp swidth, sheight;
  195518. #endif
  195519. #endif
  195520. png_size_t slength;
  195521. png_debug(1, "in png_handle_sCAL\n");
  195522. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195523. png_error(png_ptr, "Missing IHDR before sCAL");
  195524. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195525. {
  195526. png_warning(png_ptr, "Invalid sCAL after IDAT");
  195527. png_crc_finish(png_ptr, length);
  195528. return;
  195529. }
  195530. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sCAL))
  195531. {
  195532. png_warning(png_ptr, "Duplicate sCAL chunk");
  195533. png_crc_finish(png_ptr, length);
  195534. return;
  195535. }
  195536. png_debug1(2, "Allocating and reading sCAL chunk data (%lu bytes)\n",
  195537. length + 1);
  195538. buffer = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195539. if (buffer == NULL)
  195540. {
  195541. png_warning(png_ptr, "Out of memory while processing sCAL chunk");
  195542. return;
  195543. }
  195544. slength = (png_size_t)length;
  195545. png_crc_read(png_ptr, (png_bytep)buffer, slength);
  195546. if (png_crc_finish(png_ptr, 0))
  195547. {
  195548. png_free(png_ptr, buffer);
  195549. return;
  195550. }
  195551. buffer[slength] = 0x00; /* null terminate the last string */
  195552. ep = buffer + 1; /* skip unit byte */
  195553. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195554. width = png_strtod(png_ptr, ep, &vp);
  195555. if (*vp)
  195556. {
  195557. png_warning(png_ptr, "malformed width string in sCAL chunk");
  195558. return;
  195559. }
  195560. #else
  195561. #ifdef PNG_FIXED_POINT_SUPPORTED
  195562. swidth = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  195563. if (swidth == NULL)
  195564. {
  195565. png_warning(png_ptr, "Out of memory while processing sCAL chunk width");
  195566. return;
  195567. }
  195568. png_memcpy(swidth, ep, (png_size_t)png_strlen(ep));
  195569. #endif
  195570. #endif
  195571. for (ep = buffer; *ep; ep++)
  195572. /* empty loop */ ;
  195573. ep++;
  195574. if (buffer + slength < ep)
  195575. {
  195576. png_warning(png_ptr, "Truncated sCAL chunk");
  195577. #if defined(PNG_FIXED_POINT_SUPPORTED) && \
  195578. !defined(PNG_FLOATING_POINT_SUPPORTED)
  195579. png_free(png_ptr, swidth);
  195580. #endif
  195581. png_free(png_ptr, buffer);
  195582. return;
  195583. }
  195584. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195585. height = png_strtod(png_ptr, ep, &vp);
  195586. if (*vp)
  195587. {
  195588. png_warning(png_ptr, "malformed height string in sCAL chunk");
  195589. return;
  195590. }
  195591. #else
  195592. #ifdef PNG_FIXED_POINT_SUPPORTED
  195593. sheight = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  195594. if (swidth == NULL)
  195595. {
  195596. png_warning(png_ptr, "Out of memory while processing sCAL chunk height");
  195597. return;
  195598. }
  195599. png_memcpy(sheight, ep, (png_size_t)png_strlen(ep));
  195600. #endif
  195601. #endif
  195602. if (buffer + slength < ep
  195603. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195604. || width <= 0. || height <= 0.
  195605. #endif
  195606. )
  195607. {
  195608. png_warning(png_ptr, "Invalid sCAL data");
  195609. png_free(png_ptr, buffer);
  195610. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  195611. png_free(png_ptr, swidth);
  195612. png_free(png_ptr, sheight);
  195613. #endif
  195614. return;
  195615. }
  195616. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195617. png_set_sCAL(png_ptr, info_ptr, buffer[0], width, height);
  195618. #else
  195619. #ifdef PNG_FIXED_POINT_SUPPORTED
  195620. png_set_sCAL_s(png_ptr, info_ptr, buffer[0], swidth, sheight);
  195621. #endif
  195622. #endif
  195623. png_free(png_ptr, buffer);
  195624. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  195625. png_free(png_ptr, swidth);
  195626. png_free(png_ptr, sheight);
  195627. #endif
  195628. }
  195629. #endif
  195630. #if defined(PNG_READ_tIME_SUPPORTED)
  195631. void /* PRIVATE */
  195632. png_handle_tIME(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195633. {
  195634. png_byte buf[7];
  195635. png_time mod_time;
  195636. png_debug(1, "in png_handle_tIME\n");
  195637. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195638. png_error(png_ptr, "Out of place tIME chunk");
  195639. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME))
  195640. {
  195641. png_warning(png_ptr, "Duplicate tIME chunk");
  195642. png_crc_finish(png_ptr, length);
  195643. return;
  195644. }
  195645. if (png_ptr->mode & PNG_HAVE_IDAT)
  195646. png_ptr->mode |= PNG_AFTER_IDAT;
  195647. if (length != 7)
  195648. {
  195649. png_warning(png_ptr, "Incorrect tIME chunk length");
  195650. png_crc_finish(png_ptr, length);
  195651. return;
  195652. }
  195653. png_crc_read(png_ptr, buf, 7);
  195654. if (png_crc_finish(png_ptr, 0))
  195655. return;
  195656. mod_time.second = buf[6];
  195657. mod_time.minute = buf[5];
  195658. mod_time.hour = buf[4];
  195659. mod_time.day = buf[3];
  195660. mod_time.month = buf[2];
  195661. mod_time.year = png_get_uint_16(buf);
  195662. png_set_tIME(png_ptr, info_ptr, &mod_time);
  195663. }
  195664. #endif
  195665. #if defined(PNG_READ_tEXt_SUPPORTED)
  195666. /* Note: this does not properly handle chunks that are > 64K under DOS */
  195667. void /* PRIVATE */
  195668. png_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195669. {
  195670. png_textp text_ptr;
  195671. png_charp key;
  195672. png_charp text;
  195673. png_uint_32 skip = 0;
  195674. png_size_t slength;
  195675. int ret;
  195676. png_debug(1, "in png_handle_tEXt\n");
  195677. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195678. png_error(png_ptr, "Missing IHDR before tEXt");
  195679. if (png_ptr->mode & PNG_HAVE_IDAT)
  195680. png_ptr->mode |= PNG_AFTER_IDAT;
  195681. #ifdef PNG_MAX_MALLOC_64K
  195682. if (length > (png_uint_32)65535L)
  195683. {
  195684. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  195685. skip = length - (png_uint_32)65535L;
  195686. length = (png_uint_32)65535L;
  195687. }
  195688. #endif
  195689. key = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195690. if (key == NULL)
  195691. {
  195692. png_warning(png_ptr, "No memory to process text chunk.");
  195693. return;
  195694. }
  195695. slength = (png_size_t)length;
  195696. png_crc_read(png_ptr, (png_bytep)key, slength);
  195697. if (png_crc_finish(png_ptr, skip))
  195698. {
  195699. png_free(png_ptr, key);
  195700. return;
  195701. }
  195702. key[slength] = 0x00;
  195703. for (text = key; *text; text++)
  195704. /* empty loop to find end of key */ ;
  195705. if (text != key + slength)
  195706. text++;
  195707. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195708. (png_uint_32)png_sizeof(png_text));
  195709. if (text_ptr == NULL)
  195710. {
  195711. png_warning(png_ptr, "Not enough memory to process text chunk.");
  195712. png_free(png_ptr, key);
  195713. return;
  195714. }
  195715. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  195716. text_ptr->key = key;
  195717. #ifdef PNG_iTXt_SUPPORTED
  195718. text_ptr->lang = NULL;
  195719. text_ptr->lang_key = NULL;
  195720. text_ptr->itxt_length = 0;
  195721. #endif
  195722. text_ptr->text = text;
  195723. text_ptr->text_length = png_strlen(text);
  195724. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195725. png_free(png_ptr, key);
  195726. png_free(png_ptr, text_ptr);
  195727. if (ret)
  195728. png_warning(png_ptr, "Insufficient memory to process text chunk.");
  195729. }
  195730. #endif
  195731. #if defined(PNG_READ_zTXt_SUPPORTED)
  195732. /* note: this does not correctly handle chunks that are > 64K under DOS */
  195733. void /* PRIVATE */
  195734. png_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195735. {
  195736. png_textp text_ptr;
  195737. png_charp chunkdata;
  195738. png_charp text;
  195739. int comp_type;
  195740. int ret;
  195741. png_size_t slength, prefix_len, data_len;
  195742. png_debug(1, "in png_handle_zTXt\n");
  195743. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195744. png_error(png_ptr, "Missing IHDR before zTXt");
  195745. if (png_ptr->mode & PNG_HAVE_IDAT)
  195746. png_ptr->mode |= PNG_AFTER_IDAT;
  195747. #ifdef PNG_MAX_MALLOC_64K
  195748. /* We will no doubt have problems with chunks even half this size, but
  195749. there is no hard and fast rule to tell us where to stop. */
  195750. if (length > (png_uint_32)65535L)
  195751. {
  195752. png_warning(png_ptr,"zTXt chunk too large to fit in memory");
  195753. png_crc_finish(png_ptr, length);
  195754. return;
  195755. }
  195756. #endif
  195757. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195758. if (chunkdata == NULL)
  195759. {
  195760. png_warning(png_ptr,"Out of memory processing zTXt chunk.");
  195761. return;
  195762. }
  195763. slength = (png_size_t)length;
  195764. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195765. if (png_crc_finish(png_ptr, 0))
  195766. {
  195767. png_free(png_ptr, chunkdata);
  195768. return;
  195769. }
  195770. chunkdata[slength] = 0x00;
  195771. for (text = chunkdata; *text; text++)
  195772. /* empty loop */ ;
  195773. /* zTXt must have some text after the chunkdataword */
  195774. if (text >= chunkdata + slength - 2)
  195775. {
  195776. png_warning(png_ptr, "Truncated zTXt chunk");
  195777. png_free(png_ptr, chunkdata);
  195778. return;
  195779. }
  195780. else
  195781. {
  195782. comp_type = *(++text);
  195783. if (comp_type != PNG_TEXT_COMPRESSION_zTXt)
  195784. {
  195785. png_warning(png_ptr, "Unknown compression type in zTXt chunk");
  195786. comp_type = PNG_TEXT_COMPRESSION_zTXt;
  195787. }
  195788. text++; /* skip the compression_method byte */
  195789. }
  195790. prefix_len = text - chunkdata;
  195791. chunkdata = (png_charp)png_decompress_chunk(png_ptr, comp_type, chunkdata,
  195792. (png_size_t)length, prefix_len, &data_len);
  195793. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195794. (png_uint_32)png_sizeof(png_text));
  195795. if (text_ptr == NULL)
  195796. {
  195797. png_warning(png_ptr,"Not enough memory to process zTXt chunk.");
  195798. png_free(png_ptr, chunkdata);
  195799. return;
  195800. }
  195801. text_ptr->compression = comp_type;
  195802. text_ptr->key = chunkdata;
  195803. #ifdef PNG_iTXt_SUPPORTED
  195804. text_ptr->lang = NULL;
  195805. text_ptr->lang_key = NULL;
  195806. text_ptr->itxt_length = 0;
  195807. #endif
  195808. text_ptr->text = chunkdata + prefix_len;
  195809. text_ptr->text_length = data_len;
  195810. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195811. png_free(png_ptr, text_ptr);
  195812. png_free(png_ptr, chunkdata);
  195813. if (ret)
  195814. png_error(png_ptr, "Insufficient memory to store zTXt chunk.");
  195815. }
  195816. #endif
  195817. #if defined(PNG_READ_iTXt_SUPPORTED)
  195818. /* note: this does not correctly handle chunks that are > 64K under DOS */
  195819. void /* PRIVATE */
  195820. png_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195821. {
  195822. png_textp text_ptr;
  195823. png_charp chunkdata;
  195824. png_charp key, lang, text, lang_key;
  195825. int comp_flag;
  195826. int comp_type = 0;
  195827. int ret;
  195828. png_size_t slength, prefix_len, data_len;
  195829. png_debug(1, "in png_handle_iTXt\n");
  195830. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195831. png_error(png_ptr, "Missing IHDR before iTXt");
  195832. if (png_ptr->mode & PNG_HAVE_IDAT)
  195833. png_ptr->mode |= PNG_AFTER_IDAT;
  195834. #ifdef PNG_MAX_MALLOC_64K
  195835. /* We will no doubt have problems with chunks even half this size, but
  195836. there is no hard and fast rule to tell us where to stop. */
  195837. if (length > (png_uint_32)65535L)
  195838. {
  195839. png_warning(png_ptr,"iTXt chunk too large to fit in memory");
  195840. png_crc_finish(png_ptr, length);
  195841. return;
  195842. }
  195843. #endif
  195844. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195845. if (chunkdata == NULL)
  195846. {
  195847. png_warning(png_ptr, "No memory to process iTXt chunk.");
  195848. return;
  195849. }
  195850. slength = (png_size_t)length;
  195851. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195852. if (png_crc_finish(png_ptr, 0))
  195853. {
  195854. png_free(png_ptr, chunkdata);
  195855. return;
  195856. }
  195857. chunkdata[slength] = 0x00;
  195858. for (lang = chunkdata; *lang; lang++)
  195859. /* empty loop */ ;
  195860. lang++; /* skip NUL separator */
  195861. /* iTXt must have a language tag (possibly empty), two compression bytes,
  195862. translated keyword (possibly empty), and possibly some text after the
  195863. keyword */
  195864. if (lang >= chunkdata + slength - 3)
  195865. {
  195866. png_warning(png_ptr, "Truncated iTXt chunk");
  195867. png_free(png_ptr, chunkdata);
  195868. return;
  195869. }
  195870. else
  195871. {
  195872. comp_flag = *lang++;
  195873. comp_type = *lang++;
  195874. }
  195875. for (lang_key = lang; *lang_key; lang_key++)
  195876. /* empty loop */ ;
  195877. lang_key++; /* skip NUL separator */
  195878. if (lang_key >= chunkdata + slength)
  195879. {
  195880. png_warning(png_ptr, "Truncated iTXt chunk");
  195881. png_free(png_ptr, chunkdata);
  195882. return;
  195883. }
  195884. for (text = lang_key; *text; text++)
  195885. /* empty loop */ ;
  195886. text++; /* skip NUL separator */
  195887. if (text >= chunkdata + slength)
  195888. {
  195889. png_warning(png_ptr, "Malformed iTXt chunk");
  195890. png_free(png_ptr, chunkdata);
  195891. return;
  195892. }
  195893. prefix_len = text - chunkdata;
  195894. key=chunkdata;
  195895. if (comp_flag)
  195896. chunkdata = png_decompress_chunk(png_ptr, comp_type, chunkdata,
  195897. (size_t)length, prefix_len, &data_len);
  195898. else
  195899. data_len=png_strlen(chunkdata + prefix_len);
  195900. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195901. (png_uint_32)png_sizeof(png_text));
  195902. if (text_ptr == NULL)
  195903. {
  195904. png_warning(png_ptr,"Not enough memory to process iTXt chunk.");
  195905. png_free(png_ptr, chunkdata);
  195906. return;
  195907. }
  195908. text_ptr->compression = (int)comp_flag + 1;
  195909. text_ptr->lang_key = chunkdata+(lang_key-key);
  195910. text_ptr->lang = chunkdata+(lang-key);
  195911. text_ptr->itxt_length = data_len;
  195912. text_ptr->text_length = 0;
  195913. text_ptr->key = chunkdata;
  195914. text_ptr->text = chunkdata + prefix_len;
  195915. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195916. png_free(png_ptr, text_ptr);
  195917. png_free(png_ptr, chunkdata);
  195918. if (ret)
  195919. png_error(png_ptr, "Insufficient memory to store iTXt chunk.");
  195920. }
  195921. #endif
  195922. /* This function is called when we haven't found a handler for a
  195923. chunk. If there isn't a problem with the chunk itself (ie bad
  195924. chunk name, CRC, or a critical chunk), the chunk is silently ignored
  195925. -- unless the PNG_FLAG_UNKNOWN_CHUNKS_SUPPORTED flag is on in which
  195926. case it will be saved away to be written out later. */
  195927. void /* PRIVATE */
  195928. png_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195929. {
  195930. png_uint_32 skip = 0;
  195931. png_debug(1, "in png_handle_unknown\n");
  195932. if (png_ptr->mode & PNG_HAVE_IDAT)
  195933. {
  195934. #ifdef PNG_USE_LOCAL_ARRAYS
  195935. PNG_CONST PNG_IDAT;
  195936. #endif
  195937. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4)) /* not an IDAT */
  195938. png_ptr->mode |= PNG_AFTER_IDAT;
  195939. }
  195940. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  195941. if (!(png_ptr->chunk_name[0] & 0x20))
  195942. {
  195943. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  195944. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  195945. PNG_HANDLE_CHUNK_ALWAYS
  195946. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  195947. && png_ptr->read_user_chunk_fn == NULL
  195948. #endif
  195949. )
  195950. #endif
  195951. png_chunk_error(png_ptr, "unknown critical chunk");
  195952. }
  195953. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  195954. if ((png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS) ||
  195955. (png_ptr->read_user_chunk_fn != NULL))
  195956. {
  195957. #ifdef PNG_MAX_MALLOC_64K
  195958. if (length > (png_uint_32)65535L)
  195959. {
  195960. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  195961. skip = length - (png_uint_32)65535L;
  195962. length = (png_uint_32)65535L;
  195963. }
  195964. #endif
  195965. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  195966. (png_charp)png_ptr->chunk_name, 5);
  195967. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  195968. png_ptr->unknown_chunk.size = (png_size_t)length;
  195969. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  195970. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  195971. if(png_ptr->read_user_chunk_fn != NULL)
  195972. {
  195973. /* callback to user unknown chunk handler */
  195974. int ret;
  195975. ret = (*(png_ptr->read_user_chunk_fn))
  195976. (png_ptr, &png_ptr->unknown_chunk);
  195977. if (ret < 0)
  195978. png_chunk_error(png_ptr, "error in user chunk");
  195979. if (ret == 0)
  195980. {
  195981. if (!(png_ptr->chunk_name[0] & 0x20))
  195982. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  195983. PNG_HANDLE_CHUNK_ALWAYS)
  195984. png_chunk_error(png_ptr, "unknown critical chunk");
  195985. png_set_unknown_chunks(png_ptr, info_ptr,
  195986. &png_ptr->unknown_chunk, 1);
  195987. }
  195988. }
  195989. #else
  195990. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  195991. #endif
  195992. png_free(png_ptr, png_ptr->unknown_chunk.data);
  195993. png_ptr->unknown_chunk.data = NULL;
  195994. }
  195995. else
  195996. #endif
  195997. skip = length;
  195998. png_crc_finish(png_ptr, skip);
  195999. #if !defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  196000. info_ptr = info_ptr; /* quiet compiler warnings about unused info_ptr */
  196001. #endif
  196002. }
  196003. /* This function is called to verify that a chunk name is valid.
  196004. This function can't have the "critical chunk check" incorporated
  196005. into it, since in the future we will need to be able to call user
  196006. functions to handle unknown critical chunks after we check that
  196007. the chunk name itself is valid. */
  196008. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  196009. void /* PRIVATE */
  196010. png_check_chunk_name(png_structp png_ptr, png_bytep chunk_name)
  196011. {
  196012. png_debug(1, "in png_check_chunk_name\n");
  196013. if (isnonalpha(chunk_name[0]) || isnonalpha(chunk_name[1]) ||
  196014. isnonalpha(chunk_name[2]) || isnonalpha(chunk_name[3]))
  196015. {
  196016. png_chunk_error(png_ptr, "invalid chunk type");
  196017. }
  196018. }
  196019. /* Combines the row recently read in with the existing pixels in the
  196020. row. This routine takes care of alpha and transparency if requested.
  196021. This routine also handles the two methods of progressive display
  196022. of interlaced images, depending on the mask value.
  196023. The mask value describes which pixels are to be combined with
  196024. the row. The pattern always repeats every 8 pixels, so just 8
  196025. bits are needed. A one indicates the pixel is to be combined,
  196026. a zero indicates the pixel is to be skipped. This is in addition
  196027. to any alpha or transparency value associated with the pixel. If
  196028. you want all pixels to be combined, pass 0xff (255) in mask. */
  196029. void /* PRIVATE */
  196030. png_combine_row(png_structp png_ptr, png_bytep row, int mask)
  196031. {
  196032. png_debug(1,"in png_combine_row\n");
  196033. if (mask == 0xff)
  196034. {
  196035. png_memcpy(row, png_ptr->row_buf + 1,
  196036. PNG_ROWBYTES(png_ptr->row_info.pixel_depth, png_ptr->width));
  196037. }
  196038. else
  196039. {
  196040. switch (png_ptr->row_info.pixel_depth)
  196041. {
  196042. case 1:
  196043. {
  196044. png_bytep sp = png_ptr->row_buf + 1;
  196045. png_bytep dp = row;
  196046. int s_inc, s_start, s_end;
  196047. int m = 0x80;
  196048. int shift;
  196049. png_uint_32 i;
  196050. png_uint_32 row_width = png_ptr->width;
  196051. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196052. if (png_ptr->transformations & PNG_PACKSWAP)
  196053. {
  196054. s_start = 0;
  196055. s_end = 7;
  196056. s_inc = 1;
  196057. }
  196058. else
  196059. #endif
  196060. {
  196061. s_start = 7;
  196062. s_end = 0;
  196063. s_inc = -1;
  196064. }
  196065. shift = s_start;
  196066. for (i = 0; i < row_width; i++)
  196067. {
  196068. if (m & mask)
  196069. {
  196070. int value;
  196071. value = (*sp >> shift) & 0x01;
  196072. *dp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  196073. *dp |= (png_byte)(value << shift);
  196074. }
  196075. if (shift == s_end)
  196076. {
  196077. shift = s_start;
  196078. sp++;
  196079. dp++;
  196080. }
  196081. else
  196082. shift += s_inc;
  196083. if (m == 1)
  196084. m = 0x80;
  196085. else
  196086. m >>= 1;
  196087. }
  196088. break;
  196089. }
  196090. case 2:
  196091. {
  196092. png_bytep sp = png_ptr->row_buf + 1;
  196093. png_bytep dp = row;
  196094. int s_start, s_end, s_inc;
  196095. int m = 0x80;
  196096. int shift;
  196097. png_uint_32 i;
  196098. png_uint_32 row_width = png_ptr->width;
  196099. int value;
  196100. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196101. if (png_ptr->transformations & PNG_PACKSWAP)
  196102. {
  196103. s_start = 0;
  196104. s_end = 6;
  196105. s_inc = 2;
  196106. }
  196107. else
  196108. #endif
  196109. {
  196110. s_start = 6;
  196111. s_end = 0;
  196112. s_inc = -2;
  196113. }
  196114. shift = s_start;
  196115. for (i = 0; i < row_width; i++)
  196116. {
  196117. if (m & mask)
  196118. {
  196119. value = (*sp >> shift) & 0x03;
  196120. *dp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  196121. *dp |= (png_byte)(value << shift);
  196122. }
  196123. if (shift == s_end)
  196124. {
  196125. shift = s_start;
  196126. sp++;
  196127. dp++;
  196128. }
  196129. else
  196130. shift += s_inc;
  196131. if (m == 1)
  196132. m = 0x80;
  196133. else
  196134. m >>= 1;
  196135. }
  196136. break;
  196137. }
  196138. case 4:
  196139. {
  196140. png_bytep sp = png_ptr->row_buf + 1;
  196141. png_bytep dp = row;
  196142. int s_start, s_end, s_inc;
  196143. int m = 0x80;
  196144. int shift;
  196145. png_uint_32 i;
  196146. png_uint_32 row_width = png_ptr->width;
  196147. int value;
  196148. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196149. if (png_ptr->transformations & PNG_PACKSWAP)
  196150. {
  196151. s_start = 0;
  196152. s_end = 4;
  196153. s_inc = 4;
  196154. }
  196155. else
  196156. #endif
  196157. {
  196158. s_start = 4;
  196159. s_end = 0;
  196160. s_inc = -4;
  196161. }
  196162. shift = s_start;
  196163. for (i = 0; i < row_width; i++)
  196164. {
  196165. if (m & mask)
  196166. {
  196167. value = (*sp >> shift) & 0xf;
  196168. *dp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  196169. *dp |= (png_byte)(value << shift);
  196170. }
  196171. if (shift == s_end)
  196172. {
  196173. shift = s_start;
  196174. sp++;
  196175. dp++;
  196176. }
  196177. else
  196178. shift += s_inc;
  196179. if (m == 1)
  196180. m = 0x80;
  196181. else
  196182. m >>= 1;
  196183. }
  196184. break;
  196185. }
  196186. default:
  196187. {
  196188. png_bytep sp = png_ptr->row_buf + 1;
  196189. png_bytep dp = row;
  196190. png_size_t pixel_bytes = (png_ptr->row_info.pixel_depth >> 3);
  196191. png_uint_32 i;
  196192. png_uint_32 row_width = png_ptr->width;
  196193. png_byte m = 0x80;
  196194. for (i = 0; i < row_width; i++)
  196195. {
  196196. if (m & mask)
  196197. {
  196198. png_memcpy(dp, sp, pixel_bytes);
  196199. }
  196200. sp += pixel_bytes;
  196201. dp += pixel_bytes;
  196202. if (m == 1)
  196203. m = 0x80;
  196204. else
  196205. m >>= 1;
  196206. }
  196207. break;
  196208. }
  196209. }
  196210. }
  196211. }
  196212. #ifdef PNG_READ_INTERLACING_SUPPORTED
  196213. /* OLD pre-1.0.9 interface:
  196214. void png_do_read_interlace(png_row_infop row_info, png_bytep row, int pass,
  196215. png_uint_32 transformations)
  196216. */
  196217. void /* PRIVATE */
  196218. png_do_read_interlace(png_structp png_ptr)
  196219. {
  196220. png_row_infop row_info = &(png_ptr->row_info);
  196221. png_bytep row = png_ptr->row_buf + 1;
  196222. int pass = png_ptr->pass;
  196223. png_uint_32 transformations = png_ptr->transformations;
  196224. #ifdef PNG_USE_LOCAL_ARRAYS
  196225. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196226. /* offset to next interlace block */
  196227. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196228. #endif
  196229. png_debug(1,"in png_do_read_interlace\n");
  196230. if (row != NULL && row_info != NULL)
  196231. {
  196232. png_uint_32 final_width;
  196233. final_width = row_info->width * png_pass_inc[pass];
  196234. switch (row_info->pixel_depth)
  196235. {
  196236. case 1:
  196237. {
  196238. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 3);
  196239. png_bytep dp = row + (png_size_t)((final_width - 1) >> 3);
  196240. int sshift, dshift;
  196241. int s_start, s_end, s_inc;
  196242. int jstop = png_pass_inc[pass];
  196243. png_byte v;
  196244. png_uint_32 i;
  196245. int j;
  196246. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196247. if (transformations & PNG_PACKSWAP)
  196248. {
  196249. sshift = (int)((row_info->width + 7) & 0x07);
  196250. dshift = (int)((final_width + 7) & 0x07);
  196251. s_start = 7;
  196252. s_end = 0;
  196253. s_inc = -1;
  196254. }
  196255. else
  196256. #endif
  196257. {
  196258. sshift = 7 - (int)((row_info->width + 7) & 0x07);
  196259. dshift = 7 - (int)((final_width + 7) & 0x07);
  196260. s_start = 0;
  196261. s_end = 7;
  196262. s_inc = 1;
  196263. }
  196264. for (i = 0; i < row_info->width; i++)
  196265. {
  196266. v = (png_byte)((*sp >> sshift) & 0x01);
  196267. for (j = 0; j < jstop; j++)
  196268. {
  196269. *dp &= (png_byte)((0x7f7f >> (7 - dshift)) & 0xff);
  196270. *dp |= (png_byte)(v << dshift);
  196271. if (dshift == s_end)
  196272. {
  196273. dshift = s_start;
  196274. dp--;
  196275. }
  196276. else
  196277. dshift += s_inc;
  196278. }
  196279. if (sshift == s_end)
  196280. {
  196281. sshift = s_start;
  196282. sp--;
  196283. }
  196284. else
  196285. sshift += s_inc;
  196286. }
  196287. break;
  196288. }
  196289. case 2:
  196290. {
  196291. png_bytep sp = row + (png_uint_32)((row_info->width - 1) >> 2);
  196292. png_bytep dp = row + (png_uint_32)((final_width - 1) >> 2);
  196293. int sshift, dshift;
  196294. int s_start, s_end, s_inc;
  196295. int jstop = png_pass_inc[pass];
  196296. png_uint_32 i;
  196297. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196298. if (transformations & PNG_PACKSWAP)
  196299. {
  196300. sshift = (int)(((row_info->width + 3) & 0x03) << 1);
  196301. dshift = (int)(((final_width + 3) & 0x03) << 1);
  196302. s_start = 6;
  196303. s_end = 0;
  196304. s_inc = -2;
  196305. }
  196306. else
  196307. #endif
  196308. {
  196309. sshift = (int)((3 - ((row_info->width + 3) & 0x03)) << 1);
  196310. dshift = (int)((3 - ((final_width + 3) & 0x03)) << 1);
  196311. s_start = 0;
  196312. s_end = 6;
  196313. s_inc = 2;
  196314. }
  196315. for (i = 0; i < row_info->width; i++)
  196316. {
  196317. png_byte v;
  196318. int j;
  196319. v = (png_byte)((*sp >> sshift) & 0x03);
  196320. for (j = 0; j < jstop; j++)
  196321. {
  196322. *dp &= (png_byte)((0x3f3f >> (6 - dshift)) & 0xff);
  196323. *dp |= (png_byte)(v << dshift);
  196324. if (dshift == s_end)
  196325. {
  196326. dshift = s_start;
  196327. dp--;
  196328. }
  196329. else
  196330. dshift += s_inc;
  196331. }
  196332. if (sshift == s_end)
  196333. {
  196334. sshift = s_start;
  196335. sp--;
  196336. }
  196337. else
  196338. sshift += s_inc;
  196339. }
  196340. break;
  196341. }
  196342. case 4:
  196343. {
  196344. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 1);
  196345. png_bytep dp = row + (png_size_t)((final_width - 1) >> 1);
  196346. int sshift, dshift;
  196347. int s_start, s_end, s_inc;
  196348. png_uint_32 i;
  196349. int jstop = png_pass_inc[pass];
  196350. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196351. if (transformations & PNG_PACKSWAP)
  196352. {
  196353. sshift = (int)(((row_info->width + 1) & 0x01) << 2);
  196354. dshift = (int)(((final_width + 1) & 0x01) << 2);
  196355. s_start = 4;
  196356. s_end = 0;
  196357. s_inc = -4;
  196358. }
  196359. else
  196360. #endif
  196361. {
  196362. sshift = (int)((1 - ((row_info->width + 1) & 0x01)) << 2);
  196363. dshift = (int)((1 - ((final_width + 1) & 0x01)) << 2);
  196364. s_start = 0;
  196365. s_end = 4;
  196366. s_inc = 4;
  196367. }
  196368. for (i = 0; i < row_info->width; i++)
  196369. {
  196370. png_byte v = (png_byte)((*sp >> sshift) & 0xf);
  196371. int j;
  196372. for (j = 0; j < jstop; j++)
  196373. {
  196374. *dp &= (png_byte)((0xf0f >> (4 - dshift)) & 0xff);
  196375. *dp |= (png_byte)(v << dshift);
  196376. if (dshift == s_end)
  196377. {
  196378. dshift = s_start;
  196379. dp--;
  196380. }
  196381. else
  196382. dshift += s_inc;
  196383. }
  196384. if (sshift == s_end)
  196385. {
  196386. sshift = s_start;
  196387. sp--;
  196388. }
  196389. else
  196390. sshift += s_inc;
  196391. }
  196392. break;
  196393. }
  196394. default:
  196395. {
  196396. png_size_t pixel_bytes = (row_info->pixel_depth >> 3);
  196397. png_bytep sp = row + (png_size_t)(row_info->width - 1) * pixel_bytes;
  196398. png_bytep dp = row + (png_size_t)(final_width - 1) * pixel_bytes;
  196399. int jstop = png_pass_inc[pass];
  196400. png_uint_32 i;
  196401. for (i = 0; i < row_info->width; i++)
  196402. {
  196403. png_byte v[8];
  196404. int j;
  196405. png_memcpy(v, sp, pixel_bytes);
  196406. for (j = 0; j < jstop; j++)
  196407. {
  196408. png_memcpy(dp, v, pixel_bytes);
  196409. dp -= pixel_bytes;
  196410. }
  196411. sp -= pixel_bytes;
  196412. }
  196413. break;
  196414. }
  196415. }
  196416. row_info->width = final_width;
  196417. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,final_width);
  196418. }
  196419. #if !defined(PNG_READ_PACKSWAP_SUPPORTED)
  196420. transformations = transformations; /* silence compiler warning */
  196421. #endif
  196422. }
  196423. #endif /* PNG_READ_INTERLACING_SUPPORTED */
  196424. void /* PRIVATE */
  196425. png_read_filter_row(png_structp, png_row_infop row_info, png_bytep row,
  196426. png_bytep prev_row, int filter)
  196427. {
  196428. png_debug(1, "in png_read_filter_row\n");
  196429. png_debug2(2,"row = %lu, filter = %d\n", png_ptr->row_number, filter);
  196430. switch (filter)
  196431. {
  196432. case PNG_FILTER_VALUE_NONE:
  196433. break;
  196434. case PNG_FILTER_VALUE_SUB:
  196435. {
  196436. png_uint_32 i;
  196437. png_uint_32 istop = row_info->rowbytes;
  196438. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196439. png_bytep rp = row + bpp;
  196440. png_bytep lp = row;
  196441. for (i = bpp; i < istop; i++)
  196442. {
  196443. *rp = (png_byte)(((int)(*rp) + (int)(*lp++)) & 0xff);
  196444. rp++;
  196445. }
  196446. break;
  196447. }
  196448. case PNG_FILTER_VALUE_UP:
  196449. {
  196450. png_uint_32 i;
  196451. png_uint_32 istop = row_info->rowbytes;
  196452. png_bytep rp = row;
  196453. png_bytep pp = prev_row;
  196454. for (i = 0; i < istop; i++)
  196455. {
  196456. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  196457. rp++;
  196458. }
  196459. break;
  196460. }
  196461. case PNG_FILTER_VALUE_AVG:
  196462. {
  196463. png_uint_32 i;
  196464. png_bytep rp = row;
  196465. png_bytep pp = prev_row;
  196466. png_bytep lp = row;
  196467. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196468. png_uint_32 istop = row_info->rowbytes - bpp;
  196469. for (i = 0; i < bpp; i++)
  196470. {
  196471. *rp = (png_byte)(((int)(*rp) +
  196472. ((int)(*pp++) / 2 )) & 0xff);
  196473. rp++;
  196474. }
  196475. for (i = 0; i < istop; i++)
  196476. {
  196477. *rp = (png_byte)(((int)(*rp) +
  196478. (int)(*pp++ + *lp++) / 2 ) & 0xff);
  196479. rp++;
  196480. }
  196481. break;
  196482. }
  196483. case PNG_FILTER_VALUE_PAETH:
  196484. {
  196485. png_uint_32 i;
  196486. png_bytep rp = row;
  196487. png_bytep pp = prev_row;
  196488. png_bytep lp = row;
  196489. png_bytep cp = prev_row;
  196490. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196491. png_uint_32 istop=row_info->rowbytes - bpp;
  196492. for (i = 0; i < bpp; i++)
  196493. {
  196494. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  196495. rp++;
  196496. }
  196497. for (i = 0; i < istop; i++) /* use leftover rp,pp */
  196498. {
  196499. int a, b, c, pa, pb, pc, p;
  196500. a = *lp++;
  196501. b = *pp++;
  196502. c = *cp++;
  196503. p = b - c;
  196504. pc = a - c;
  196505. #ifdef PNG_USE_ABS
  196506. pa = abs(p);
  196507. pb = abs(pc);
  196508. pc = abs(p + pc);
  196509. #else
  196510. pa = p < 0 ? -p : p;
  196511. pb = pc < 0 ? -pc : pc;
  196512. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  196513. #endif
  196514. /*
  196515. if (pa <= pb && pa <= pc)
  196516. p = a;
  196517. else if (pb <= pc)
  196518. p = b;
  196519. else
  196520. p = c;
  196521. */
  196522. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  196523. *rp = (png_byte)(((int)(*rp) + p) & 0xff);
  196524. rp++;
  196525. }
  196526. break;
  196527. }
  196528. default:
  196529. png_warning(png_ptr, "Ignoring bad adaptive filter type");
  196530. *row=0;
  196531. break;
  196532. }
  196533. }
  196534. void /* PRIVATE */
  196535. png_read_finish_row(png_structp png_ptr)
  196536. {
  196537. #ifdef PNG_USE_LOCAL_ARRAYS
  196538. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196539. /* start of interlace block */
  196540. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  196541. /* offset to next interlace block */
  196542. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196543. /* start of interlace block in the y direction */
  196544. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  196545. /* offset to next interlace block in the y direction */
  196546. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  196547. #endif
  196548. png_debug(1, "in png_read_finish_row\n");
  196549. png_ptr->row_number++;
  196550. if (png_ptr->row_number < png_ptr->num_rows)
  196551. return;
  196552. if (png_ptr->interlaced)
  196553. {
  196554. png_ptr->row_number = 0;
  196555. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  196556. png_ptr->rowbytes + 1);
  196557. do
  196558. {
  196559. png_ptr->pass++;
  196560. if (png_ptr->pass >= 7)
  196561. break;
  196562. png_ptr->iwidth = (png_ptr->width +
  196563. png_pass_inc[png_ptr->pass] - 1 -
  196564. png_pass_start[png_ptr->pass]) /
  196565. png_pass_inc[png_ptr->pass];
  196566. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  196567. png_ptr->iwidth) + 1;
  196568. if (!(png_ptr->transformations & PNG_INTERLACE))
  196569. {
  196570. png_ptr->num_rows = (png_ptr->height +
  196571. png_pass_yinc[png_ptr->pass] - 1 -
  196572. png_pass_ystart[png_ptr->pass]) /
  196573. png_pass_yinc[png_ptr->pass];
  196574. if (!(png_ptr->num_rows))
  196575. continue;
  196576. }
  196577. else /* if (png_ptr->transformations & PNG_INTERLACE) */
  196578. break;
  196579. } while (png_ptr->iwidth == 0);
  196580. if (png_ptr->pass < 7)
  196581. return;
  196582. }
  196583. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  196584. {
  196585. #ifdef PNG_USE_LOCAL_ARRAYS
  196586. PNG_CONST PNG_IDAT;
  196587. #endif
  196588. char extra;
  196589. int ret;
  196590. png_ptr->zstream.next_out = (Bytef *)&extra;
  196591. png_ptr->zstream.avail_out = (uInt)1;
  196592. for(;;)
  196593. {
  196594. if (!(png_ptr->zstream.avail_in))
  196595. {
  196596. while (!png_ptr->idat_size)
  196597. {
  196598. png_byte chunk_length[4];
  196599. png_crc_finish(png_ptr, 0);
  196600. png_read_data(png_ptr, chunk_length, 4);
  196601. png_ptr->idat_size = png_get_uint_31(png_ptr, chunk_length);
  196602. png_reset_crc(png_ptr);
  196603. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  196604. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  196605. png_error(png_ptr, "Not enough image data");
  196606. }
  196607. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  196608. png_ptr->zstream.next_in = png_ptr->zbuf;
  196609. if (png_ptr->zbuf_size > png_ptr->idat_size)
  196610. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  196611. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zstream.avail_in);
  196612. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  196613. }
  196614. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  196615. if (ret == Z_STREAM_END)
  196616. {
  196617. if (!(png_ptr->zstream.avail_out) || png_ptr->zstream.avail_in ||
  196618. png_ptr->idat_size)
  196619. png_warning(png_ptr, "Extra compressed data");
  196620. png_ptr->mode |= PNG_AFTER_IDAT;
  196621. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  196622. break;
  196623. }
  196624. if (ret != Z_OK)
  196625. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  196626. "Decompression Error");
  196627. if (!(png_ptr->zstream.avail_out))
  196628. {
  196629. png_warning(png_ptr, "Extra compressed data.");
  196630. png_ptr->mode |= PNG_AFTER_IDAT;
  196631. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  196632. break;
  196633. }
  196634. }
  196635. png_ptr->zstream.avail_out = 0;
  196636. }
  196637. if (png_ptr->idat_size || png_ptr->zstream.avail_in)
  196638. png_warning(png_ptr, "Extra compression data");
  196639. inflateReset(&png_ptr->zstream);
  196640. png_ptr->mode |= PNG_AFTER_IDAT;
  196641. }
  196642. void /* PRIVATE */
  196643. png_read_start_row(png_structp png_ptr)
  196644. {
  196645. #ifdef PNG_USE_LOCAL_ARRAYS
  196646. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196647. /* start of interlace block */
  196648. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  196649. /* offset to next interlace block */
  196650. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196651. /* start of interlace block in the y direction */
  196652. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  196653. /* offset to next interlace block in the y direction */
  196654. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  196655. #endif
  196656. int max_pixel_depth;
  196657. png_uint_32 row_bytes;
  196658. png_debug(1, "in png_read_start_row\n");
  196659. png_ptr->zstream.avail_in = 0;
  196660. png_init_read_transformations(png_ptr);
  196661. if (png_ptr->interlaced)
  196662. {
  196663. if (!(png_ptr->transformations & PNG_INTERLACE))
  196664. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  196665. png_pass_ystart[0]) / png_pass_yinc[0];
  196666. else
  196667. png_ptr->num_rows = png_ptr->height;
  196668. png_ptr->iwidth = (png_ptr->width +
  196669. png_pass_inc[png_ptr->pass] - 1 -
  196670. png_pass_start[png_ptr->pass]) /
  196671. png_pass_inc[png_ptr->pass];
  196672. row_bytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->iwidth) + 1;
  196673. png_ptr->irowbytes = (png_size_t)row_bytes;
  196674. if((png_uint_32)png_ptr->irowbytes != row_bytes)
  196675. png_error(png_ptr, "Rowbytes overflow in png_read_start_row");
  196676. }
  196677. else
  196678. {
  196679. png_ptr->num_rows = png_ptr->height;
  196680. png_ptr->iwidth = png_ptr->width;
  196681. png_ptr->irowbytes = png_ptr->rowbytes + 1;
  196682. }
  196683. max_pixel_depth = png_ptr->pixel_depth;
  196684. #if defined(PNG_READ_PACK_SUPPORTED)
  196685. if ((png_ptr->transformations & PNG_PACK) && png_ptr->bit_depth < 8)
  196686. max_pixel_depth = 8;
  196687. #endif
  196688. #if defined(PNG_READ_EXPAND_SUPPORTED)
  196689. if (png_ptr->transformations & PNG_EXPAND)
  196690. {
  196691. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196692. {
  196693. if (png_ptr->num_trans)
  196694. max_pixel_depth = 32;
  196695. else
  196696. max_pixel_depth = 24;
  196697. }
  196698. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  196699. {
  196700. if (max_pixel_depth < 8)
  196701. max_pixel_depth = 8;
  196702. if (png_ptr->num_trans)
  196703. max_pixel_depth *= 2;
  196704. }
  196705. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  196706. {
  196707. if (png_ptr->num_trans)
  196708. {
  196709. max_pixel_depth *= 4;
  196710. max_pixel_depth /= 3;
  196711. }
  196712. }
  196713. }
  196714. #endif
  196715. #if defined(PNG_READ_FILLER_SUPPORTED)
  196716. if (png_ptr->transformations & (PNG_FILLER))
  196717. {
  196718. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196719. max_pixel_depth = 32;
  196720. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  196721. {
  196722. if (max_pixel_depth <= 8)
  196723. max_pixel_depth = 16;
  196724. else
  196725. max_pixel_depth = 32;
  196726. }
  196727. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  196728. {
  196729. if (max_pixel_depth <= 32)
  196730. max_pixel_depth = 32;
  196731. else
  196732. max_pixel_depth = 64;
  196733. }
  196734. }
  196735. #endif
  196736. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  196737. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  196738. {
  196739. if (
  196740. #if defined(PNG_READ_EXPAND_SUPPORTED)
  196741. (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND)) ||
  196742. #endif
  196743. #if defined(PNG_READ_FILLER_SUPPORTED)
  196744. (png_ptr->transformations & (PNG_FILLER)) ||
  196745. #endif
  196746. png_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  196747. {
  196748. if (max_pixel_depth <= 16)
  196749. max_pixel_depth = 32;
  196750. else
  196751. max_pixel_depth = 64;
  196752. }
  196753. else
  196754. {
  196755. if (max_pixel_depth <= 8)
  196756. {
  196757. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196758. max_pixel_depth = 32;
  196759. else
  196760. max_pixel_depth = 24;
  196761. }
  196762. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196763. max_pixel_depth = 64;
  196764. else
  196765. max_pixel_depth = 48;
  196766. }
  196767. }
  196768. #endif
  196769. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) && \
  196770. defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  196771. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  196772. {
  196773. int user_pixel_depth=png_ptr->user_transform_depth*
  196774. png_ptr->user_transform_channels;
  196775. if(user_pixel_depth > max_pixel_depth)
  196776. max_pixel_depth=user_pixel_depth;
  196777. }
  196778. #endif
  196779. /* align the width on the next larger 8 pixels. Mainly used
  196780. for interlacing */
  196781. row_bytes = ((png_ptr->width + 7) & ~((png_uint_32)7));
  196782. /* calculate the maximum bytes needed, adding a byte and a pixel
  196783. for safety's sake */
  196784. row_bytes = PNG_ROWBYTES(max_pixel_depth,row_bytes) +
  196785. 1 + ((max_pixel_depth + 7) >> 3);
  196786. #ifdef PNG_MAX_MALLOC_64K
  196787. if (row_bytes > (png_uint_32)65536L)
  196788. png_error(png_ptr, "This image requires a row greater than 64KB");
  196789. #endif
  196790. png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr, row_bytes+64);
  196791. png_ptr->row_buf = png_ptr->big_row_buf+32;
  196792. #ifdef PNG_MAX_MALLOC_64K
  196793. if ((png_uint_32)png_ptr->rowbytes + 1 > (png_uint_32)65536L)
  196794. png_error(png_ptr, "This image requires a row greater than 64KB");
  196795. #endif
  196796. if ((png_uint_32)png_ptr->rowbytes > (png_uint_32)(PNG_SIZE_MAX - 1))
  196797. png_error(png_ptr, "Row has too many bytes to allocate in memory.");
  196798. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)(
  196799. png_ptr->rowbytes + 1));
  196800. png_memset_check(png_ptr, png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
  196801. png_debug1(3, "width = %lu,\n", png_ptr->width);
  196802. png_debug1(3, "height = %lu,\n", png_ptr->height);
  196803. png_debug1(3, "iwidth = %lu,\n", png_ptr->iwidth);
  196804. png_debug1(3, "num_rows = %lu\n", png_ptr->num_rows);
  196805. png_debug1(3, "rowbytes = %lu,\n", png_ptr->rowbytes);
  196806. png_debug1(3, "irowbytes = %lu,\n", png_ptr->irowbytes);
  196807. png_ptr->flags |= PNG_FLAG_ROW_INIT;
  196808. }
  196809. #endif /* PNG_READ_SUPPORTED */
  196810. /*** End of inlined file: pngrutil.c ***/
  196811. /*** Start of inlined file: pngset.c ***/
  196812. /* pngset.c - storage of image information into info struct
  196813. *
  196814. * Last changed in libpng 1.2.21 [October 4, 2007]
  196815. * For conditions of distribution and use, see copyright notice in png.h
  196816. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  196817. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  196818. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  196819. *
  196820. * The functions here are used during reads to store data from the file
  196821. * into the info struct, and during writes to store application data
  196822. * into the info struct for writing into the file. This abstracts the
  196823. * info struct and allows us to change the structure in the future.
  196824. */
  196825. #define PNG_INTERNAL
  196826. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  196827. #if defined(PNG_bKGD_SUPPORTED)
  196828. void PNGAPI
  196829. png_set_bKGD(png_structp png_ptr, png_infop info_ptr, png_color_16p background)
  196830. {
  196831. png_debug1(1, "in %s storage function\n", "bKGD");
  196832. if (png_ptr == NULL || info_ptr == NULL)
  196833. return;
  196834. png_memcpy(&(info_ptr->background), background, png_sizeof(png_color_16));
  196835. info_ptr->valid |= PNG_INFO_bKGD;
  196836. }
  196837. #endif
  196838. #if defined(PNG_cHRM_SUPPORTED)
  196839. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196840. void PNGAPI
  196841. png_set_cHRM(png_structp png_ptr, png_infop info_ptr,
  196842. double white_x, double white_y, double red_x, double red_y,
  196843. double green_x, double green_y, double blue_x, double blue_y)
  196844. {
  196845. png_debug1(1, "in %s storage function\n", "cHRM");
  196846. if (png_ptr == NULL || info_ptr == NULL)
  196847. return;
  196848. if (white_x < 0.0 || white_y < 0.0 ||
  196849. red_x < 0.0 || red_y < 0.0 ||
  196850. green_x < 0.0 || green_y < 0.0 ||
  196851. blue_x < 0.0 || blue_y < 0.0)
  196852. {
  196853. png_warning(png_ptr,
  196854. "Ignoring attempt to set negative chromaticity value");
  196855. return;
  196856. }
  196857. if (white_x > 21474.83 || white_y > 21474.83 ||
  196858. red_x > 21474.83 || red_y > 21474.83 ||
  196859. green_x > 21474.83 || green_y > 21474.83 ||
  196860. blue_x > 21474.83 || blue_y > 21474.83)
  196861. {
  196862. png_warning(png_ptr,
  196863. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  196864. return;
  196865. }
  196866. info_ptr->x_white = (float)white_x;
  196867. info_ptr->y_white = (float)white_y;
  196868. info_ptr->x_red = (float)red_x;
  196869. info_ptr->y_red = (float)red_y;
  196870. info_ptr->x_green = (float)green_x;
  196871. info_ptr->y_green = (float)green_y;
  196872. info_ptr->x_blue = (float)blue_x;
  196873. info_ptr->y_blue = (float)blue_y;
  196874. #ifdef PNG_FIXED_POINT_SUPPORTED
  196875. info_ptr->int_x_white = (png_fixed_point)(white_x*100000.+0.5);
  196876. info_ptr->int_y_white = (png_fixed_point)(white_y*100000.+0.5);
  196877. info_ptr->int_x_red = (png_fixed_point)( red_x*100000.+0.5);
  196878. info_ptr->int_y_red = (png_fixed_point)( red_y*100000.+0.5);
  196879. info_ptr->int_x_green = (png_fixed_point)(green_x*100000.+0.5);
  196880. info_ptr->int_y_green = (png_fixed_point)(green_y*100000.+0.5);
  196881. info_ptr->int_x_blue = (png_fixed_point)( blue_x*100000.+0.5);
  196882. info_ptr->int_y_blue = (png_fixed_point)( blue_y*100000.+0.5);
  196883. #endif
  196884. info_ptr->valid |= PNG_INFO_cHRM;
  196885. }
  196886. #endif
  196887. #ifdef PNG_FIXED_POINT_SUPPORTED
  196888. void PNGAPI
  196889. png_set_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  196890. png_fixed_point white_x, png_fixed_point white_y, png_fixed_point red_x,
  196891. png_fixed_point red_y, png_fixed_point green_x, png_fixed_point green_y,
  196892. png_fixed_point blue_x, png_fixed_point blue_y)
  196893. {
  196894. png_debug1(1, "in %s storage function\n", "cHRM");
  196895. if (png_ptr == NULL || info_ptr == NULL)
  196896. return;
  196897. if (white_x < 0 || white_y < 0 ||
  196898. red_x < 0 || red_y < 0 ||
  196899. green_x < 0 || green_y < 0 ||
  196900. blue_x < 0 || blue_y < 0)
  196901. {
  196902. png_warning(png_ptr,
  196903. "Ignoring attempt to set negative chromaticity value");
  196904. return;
  196905. }
  196906. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196907. if (white_x > (double) PNG_UINT_31_MAX ||
  196908. white_y > (double) PNG_UINT_31_MAX ||
  196909. red_x > (double) PNG_UINT_31_MAX ||
  196910. red_y > (double) PNG_UINT_31_MAX ||
  196911. green_x > (double) PNG_UINT_31_MAX ||
  196912. green_y > (double) PNG_UINT_31_MAX ||
  196913. blue_x > (double) PNG_UINT_31_MAX ||
  196914. blue_y > (double) PNG_UINT_31_MAX)
  196915. #else
  196916. if (white_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196917. white_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196918. red_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196919. red_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196920. green_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196921. green_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196922. blue_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196923. blue_y > (png_fixed_point) PNG_UINT_31_MAX/100000L)
  196924. #endif
  196925. {
  196926. png_warning(png_ptr,
  196927. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  196928. return;
  196929. }
  196930. info_ptr->int_x_white = white_x;
  196931. info_ptr->int_y_white = white_y;
  196932. info_ptr->int_x_red = red_x;
  196933. info_ptr->int_y_red = red_y;
  196934. info_ptr->int_x_green = green_x;
  196935. info_ptr->int_y_green = green_y;
  196936. info_ptr->int_x_blue = blue_x;
  196937. info_ptr->int_y_blue = blue_y;
  196938. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196939. info_ptr->x_white = (float)(white_x/100000.);
  196940. info_ptr->y_white = (float)(white_y/100000.);
  196941. info_ptr->x_red = (float)( red_x/100000.);
  196942. info_ptr->y_red = (float)( red_y/100000.);
  196943. info_ptr->x_green = (float)(green_x/100000.);
  196944. info_ptr->y_green = (float)(green_y/100000.);
  196945. info_ptr->x_blue = (float)( blue_x/100000.);
  196946. info_ptr->y_blue = (float)( blue_y/100000.);
  196947. #endif
  196948. info_ptr->valid |= PNG_INFO_cHRM;
  196949. }
  196950. #endif
  196951. #endif
  196952. #if defined(PNG_gAMA_SUPPORTED)
  196953. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196954. void PNGAPI
  196955. png_set_gAMA(png_structp png_ptr, png_infop info_ptr, double file_gamma)
  196956. {
  196957. double gamma;
  196958. png_debug1(1, "in %s storage function\n", "gAMA");
  196959. if (png_ptr == NULL || info_ptr == NULL)
  196960. return;
  196961. /* Check for overflow */
  196962. if (file_gamma > 21474.83)
  196963. {
  196964. png_warning(png_ptr, "Limiting gamma to 21474.83");
  196965. gamma=21474.83;
  196966. }
  196967. else
  196968. gamma=file_gamma;
  196969. info_ptr->gamma = (float)gamma;
  196970. #ifdef PNG_FIXED_POINT_SUPPORTED
  196971. info_ptr->int_gamma = (int)(gamma*100000.+.5);
  196972. #endif
  196973. info_ptr->valid |= PNG_INFO_gAMA;
  196974. if(gamma == 0.0)
  196975. png_warning(png_ptr, "Setting gamma=0");
  196976. }
  196977. #endif
  196978. void PNGAPI
  196979. png_set_gAMA_fixed(png_structp png_ptr, png_infop info_ptr, png_fixed_point
  196980. int_gamma)
  196981. {
  196982. png_fixed_point gamma;
  196983. png_debug1(1, "in %s storage function\n", "gAMA");
  196984. if (png_ptr == NULL || info_ptr == NULL)
  196985. return;
  196986. if (int_gamma > (png_fixed_point) PNG_UINT_31_MAX)
  196987. {
  196988. png_warning(png_ptr, "Limiting gamma to 21474.83");
  196989. gamma=PNG_UINT_31_MAX;
  196990. }
  196991. else
  196992. {
  196993. if (int_gamma < 0)
  196994. {
  196995. png_warning(png_ptr, "Setting negative gamma to zero");
  196996. gamma=0;
  196997. }
  196998. else
  196999. gamma=int_gamma;
  197000. }
  197001. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197002. info_ptr->gamma = (float)(gamma/100000.);
  197003. #endif
  197004. #ifdef PNG_FIXED_POINT_SUPPORTED
  197005. info_ptr->int_gamma = gamma;
  197006. #endif
  197007. info_ptr->valid |= PNG_INFO_gAMA;
  197008. if(gamma == 0)
  197009. png_warning(png_ptr, "Setting gamma=0");
  197010. }
  197011. #endif
  197012. #if defined(PNG_hIST_SUPPORTED)
  197013. void PNGAPI
  197014. png_set_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p hist)
  197015. {
  197016. int i;
  197017. png_debug1(1, "in %s storage function\n", "hIST");
  197018. if (png_ptr == NULL || info_ptr == NULL)
  197019. return;
  197020. if (info_ptr->num_palette == 0 || info_ptr->num_palette
  197021. > PNG_MAX_PALETTE_LENGTH)
  197022. {
  197023. png_warning(png_ptr,
  197024. "Invalid palette size, hIST allocation skipped.");
  197025. return;
  197026. }
  197027. #ifdef PNG_FREE_ME_SUPPORTED
  197028. png_free_data(png_ptr, info_ptr, PNG_FREE_HIST, 0);
  197029. #endif
  197030. /* Changed from info->num_palette to PNG_MAX_PALETTE_LENGTH in version
  197031. 1.2.1 */
  197032. png_ptr->hist = (png_uint_16p)png_malloc_warn(png_ptr,
  197033. (png_uint_32)(PNG_MAX_PALETTE_LENGTH * png_sizeof (png_uint_16)));
  197034. if (png_ptr->hist == NULL)
  197035. {
  197036. png_warning(png_ptr, "Insufficient memory for hIST chunk data.");
  197037. return;
  197038. }
  197039. for (i = 0; i < info_ptr->num_palette; i++)
  197040. png_ptr->hist[i] = hist[i];
  197041. info_ptr->hist = png_ptr->hist;
  197042. info_ptr->valid |= PNG_INFO_hIST;
  197043. #ifdef PNG_FREE_ME_SUPPORTED
  197044. info_ptr->free_me |= PNG_FREE_HIST;
  197045. #else
  197046. png_ptr->flags |= PNG_FLAG_FREE_HIST;
  197047. #endif
  197048. }
  197049. #endif
  197050. void PNGAPI
  197051. png_set_IHDR(png_structp png_ptr, png_infop info_ptr,
  197052. png_uint_32 width, png_uint_32 height, int bit_depth,
  197053. int color_type, int interlace_type, int compression_type,
  197054. int filter_type)
  197055. {
  197056. png_debug1(1, "in %s storage function\n", "IHDR");
  197057. if (png_ptr == NULL || info_ptr == NULL)
  197058. return;
  197059. /* check for width and height valid values */
  197060. if (width == 0 || height == 0)
  197061. png_error(png_ptr, "Image width or height is zero in IHDR");
  197062. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  197063. if (width > png_ptr->user_width_max || height > png_ptr->user_height_max)
  197064. png_error(png_ptr, "image size exceeds user limits in IHDR");
  197065. #else
  197066. if (width > PNG_USER_WIDTH_MAX || height > PNG_USER_HEIGHT_MAX)
  197067. png_error(png_ptr, "image size exceeds user limits in IHDR");
  197068. #endif
  197069. if (width > PNG_UINT_31_MAX || height > PNG_UINT_31_MAX)
  197070. png_error(png_ptr, "Invalid image size in IHDR");
  197071. if ( width > (PNG_UINT_32_MAX
  197072. >> 3) /* 8-byte RGBA pixels */
  197073. - 64 /* bigrowbuf hack */
  197074. - 1 /* filter byte */
  197075. - 7*8 /* rounding of width to multiple of 8 pixels */
  197076. - 8) /* extra max_pixel_depth pad */
  197077. png_warning(png_ptr, "Width is too large for libpng to process pixels");
  197078. /* check other values */
  197079. if (bit_depth != 1 && bit_depth != 2 && bit_depth != 4 &&
  197080. bit_depth != 8 && bit_depth != 16)
  197081. png_error(png_ptr, "Invalid bit depth in IHDR");
  197082. if (color_type < 0 || color_type == 1 ||
  197083. color_type == 5 || color_type > 6)
  197084. png_error(png_ptr, "Invalid color type in IHDR");
  197085. if (((color_type == PNG_COLOR_TYPE_PALETTE) && bit_depth > 8) ||
  197086. ((color_type == PNG_COLOR_TYPE_RGB ||
  197087. color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
  197088. color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8))
  197089. png_error(png_ptr, "Invalid color type/bit depth combination in IHDR");
  197090. if (interlace_type >= PNG_INTERLACE_LAST)
  197091. png_error(png_ptr, "Unknown interlace method in IHDR");
  197092. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  197093. png_error(png_ptr, "Unknown compression method in IHDR");
  197094. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  197095. /* Accept filter_method 64 (intrapixel differencing) only if
  197096. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  197097. * 2. Libpng did not read a PNG signature (this filter_method is only
  197098. * used in PNG datastreams that are embedded in MNG datastreams) and
  197099. * 3. The application called png_permit_mng_features with a mask that
  197100. * included PNG_FLAG_MNG_FILTER_64 and
  197101. * 4. The filter_method is 64 and
  197102. * 5. The color_type is RGB or RGBA
  197103. */
  197104. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&png_ptr->mng_features_permitted)
  197105. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  197106. if(filter_type != PNG_FILTER_TYPE_BASE)
  197107. {
  197108. if(!((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  197109. (filter_type == PNG_INTRAPIXEL_DIFFERENCING) &&
  197110. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  197111. (color_type == PNG_COLOR_TYPE_RGB ||
  197112. color_type == PNG_COLOR_TYPE_RGB_ALPHA)))
  197113. png_error(png_ptr, "Unknown filter method in IHDR");
  197114. if(png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)
  197115. png_warning(png_ptr, "Invalid filter method in IHDR");
  197116. }
  197117. #else
  197118. if(filter_type != PNG_FILTER_TYPE_BASE)
  197119. png_error(png_ptr, "Unknown filter method in IHDR");
  197120. #endif
  197121. info_ptr->width = width;
  197122. info_ptr->height = height;
  197123. info_ptr->bit_depth = (png_byte)bit_depth;
  197124. info_ptr->color_type =(png_byte) color_type;
  197125. info_ptr->compression_type = (png_byte)compression_type;
  197126. info_ptr->filter_type = (png_byte)filter_type;
  197127. info_ptr->interlace_type = (png_byte)interlace_type;
  197128. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  197129. info_ptr->channels = 1;
  197130. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  197131. info_ptr->channels = 3;
  197132. else
  197133. info_ptr->channels = 1;
  197134. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  197135. info_ptr->channels++;
  197136. info_ptr->pixel_depth = (png_byte)(info_ptr->channels * info_ptr->bit_depth);
  197137. /* check for potential overflow */
  197138. if (width > (PNG_UINT_32_MAX
  197139. >> 3) /* 8-byte RGBA pixels */
  197140. - 64 /* bigrowbuf hack */
  197141. - 1 /* filter byte */
  197142. - 7*8 /* rounding of width to multiple of 8 pixels */
  197143. - 8) /* extra max_pixel_depth pad */
  197144. info_ptr->rowbytes = (png_size_t)0;
  197145. else
  197146. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,width);
  197147. }
  197148. #if defined(PNG_oFFs_SUPPORTED)
  197149. void PNGAPI
  197150. png_set_oFFs(png_structp png_ptr, png_infop info_ptr,
  197151. png_int_32 offset_x, png_int_32 offset_y, int unit_type)
  197152. {
  197153. png_debug1(1, "in %s storage function\n", "oFFs");
  197154. if (png_ptr == NULL || info_ptr == NULL)
  197155. return;
  197156. info_ptr->x_offset = offset_x;
  197157. info_ptr->y_offset = offset_y;
  197158. info_ptr->offset_unit_type = (png_byte)unit_type;
  197159. info_ptr->valid |= PNG_INFO_oFFs;
  197160. }
  197161. #endif
  197162. #if defined(PNG_pCAL_SUPPORTED)
  197163. void PNGAPI
  197164. png_set_pCAL(png_structp png_ptr, png_infop info_ptr,
  197165. png_charp purpose, png_int_32 X0, png_int_32 X1, int type, int nparams,
  197166. png_charp units, png_charpp params)
  197167. {
  197168. png_uint_32 length;
  197169. int i;
  197170. png_debug1(1, "in %s storage function\n", "pCAL");
  197171. if (png_ptr == NULL || info_ptr == NULL)
  197172. return;
  197173. length = png_strlen(purpose) + 1;
  197174. png_debug1(3, "allocating purpose for info (%lu bytes)\n", length);
  197175. info_ptr->pcal_purpose = (png_charp)png_malloc_warn(png_ptr, length);
  197176. if (info_ptr->pcal_purpose == NULL)
  197177. {
  197178. png_warning(png_ptr, "Insufficient memory for pCAL purpose.");
  197179. return;
  197180. }
  197181. png_memcpy(info_ptr->pcal_purpose, purpose, (png_size_t)length);
  197182. png_debug(3, "storing X0, X1, type, and nparams in info\n");
  197183. info_ptr->pcal_X0 = X0;
  197184. info_ptr->pcal_X1 = X1;
  197185. info_ptr->pcal_type = (png_byte)type;
  197186. info_ptr->pcal_nparams = (png_byte)nparams;
  197187. length = png_strlen(units) + 1;
  197188. png_debug1(3, "allocating units for info (%lu bytes)\n", length);
  197189. info_ptr->pcal_units = (png_charp)png_malloc_warn(png_ptr, length);
  197190. if (info_ptr->pcal_units == NULL)
  197191. {
  197192. png_warning(png_ptr, "Insufficient memory for pCAL units.");
  197193. return;
  197194. }
  197195. png_memcpy(info_ptr->pcal_units, units, (png_size_t)length);
  197196. info_ptr->pcal_params = (png_charpp)png_malloc_warn(png_ptr,
  197197. (png_uint_32)((nparams + 1) * png_sizeof(png_charp)));
  197198. if (info_ptr->pcal_params == NULL)
  197199. {
  197200. png_warning(png_ptr, "Insufficient memory for pCAL params.");
  197201. return;
  197202. }
  197203. info_ptr->pcal_params[nparams] = NULL;
  197204. for (i = 0; i < nparams; i++)
  197205. {
  197206. length = png_strlen(params[i]) + 1;
  197207. png_debug2(3, "allocating parameter %d for info (%lu bytes)\n", i, length);
  197208. info_ptr->pcal_params[i] = (png_charp)png_malloc_warn(png_ptr, length);
  197209. if (info_ptr->pcal_params[i] == NULL)
  197210. {
  197211. png_warning(png_ptr, "Insufficient memory for pCAL parameter.");
  197212. return;
  197213. }
  197214. png_memcpy(info_ptr->pcal_params[i], params[i], (png_size_t)length);
  197215. }
  197216. info_ptr->valid |= PNG_INFO_pCAL;
  197217. #ifdef PNG_FREE_ME_SUPPORTED
  197218. info_ptr->free_me |= PNG_FREE_PCAL;
  197219. #endif
  197220. }
  197221. #endif
  197222. #if defined(PNG_READ_sCAL_SUPPORTED) || defined(PNG_WRITE_sCAL_SUPPORTED)
  197223. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197224. void PNGAPI
  197225. png_set_sCAL(png_structp png_ptr, png_infop info_ptr,
  197226. int unit, double width, double height)
  197227. {
  197228. png_debug1(1, "in %s storage function\n", "sCAL");
  197229. if (png_ptr == NULL || info_ptr == NULL)
  197230. return;
  197231. info_ptr->scal_unit = (png_byte)unit;
  197232. info_ptr->scal_pixel_width = width;
  197233. info_ptr->scal_pixel_height = height;
  197234. info_ptr->valid |= PNG_INFO_sCAL;
  197235. }
  197236. #else
  197237. #ifdef PNG_FIXED_POINT_SUPPORTED
  197238. void PNGAPI
  197239. png_set_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  197240. int unit, png_charp swidth, png_charp sheight)
  197241. {
  197242. png_uint_32 length;
  197243. png_debug1(1, "in %s storage function\n", "sCAL");
  197244. if (png_ptr == NULL || info_ptr == NULL)
  197245. return;
  197246. info_ptr->scal_unit = (png_byte)unit;
  197247. length = png_strlen(swidth) + 1;
  197248. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  197249. info_ptr->scal_s_width = (png_charp)png_malloc_warn(png_ptr, length);
  197250. if (info_ptr->scal_s_width == NULL)
  197251. {
  197252. png_warning(png_ptr,
  197253. "Memory allocation failed while processing sCAL.");
  197254. }
  197255. png_memcpy(info_ptr->scal_s_width, swidth, (png_size_t)length);
  197256. length = png_strlen(sheight) + 1;
  197257. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  197258. info_ptr->scal_s_height = (png_charp)png_malloc_warn(png_ptr, length);
  197259. if (info_ptr->scal_s_height == NULL)
  197260. {
  197261. png_free (png_ptr, info_ptr->scal_s_width);
  197262. png_warning(png_ptr,
  197263. "Memory allocation failed while processing sCAL.");
  197264. }
  197265. png_memcpy(info_ptr->scal_s_height, sheight, (png_size_t)length);
  197266. info_ptr->valid |= PNG_INFO_sCAL;
  197267. #ifdef PNG_FREE_ME_SUPPORTED
  197268. info_ptr->free_me |= PNG_FREE_SCAL;
  197269. #endif
  197270. }
  197271. #endif
  197272. #endif
  197273. #endif
  197274. #if defined(PNG_pHYs_SUPPORTED)
  197275. void PNGAPI
  197276. png_set_pHYs(png_structp png_ptr, png_infop info_ptr,
  197277. png_uint_32 res_x, png_uint_32 res_y, int unit_type)
  197278. {
  197279. png_debug1(1, "in %s storage function\n", "pHYs");
  197280. if (png_ptr == NULL || info_ptr == NULL)
  197281. return;
  197282. info_ptr->x_pixels_per_unit = res_x;
  197283. info_ptr->y_pixels_per_unit = res_y;
  197284. info_ptr->phys_unit_type = (png_byte)unit_type;
  197285. info_ptr->valid |= PNG_INFO_pHYs;
  197286. }
  197287. #endif
  197288. void PNGAPI
  197289. png_set_PLTE(png_structp png_ptr, png_infop info_ptr,
  197290. png_colorp palette, int num_palette)
  197291. {
  197292. png_debug1(1, "in %s storage function\n", "PLTE");
  197293. if (png_ptr == NULL || info_ptr == NULL)
  197294. return;
  197295. if (num_palette < 0 || num_palette > PNG_MAX_PALETTE_LENGTH)
  197296. {
  197297. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  197298. png_error(png_ptr, "Invalid palette length");
  197299. else
  197300. {
  197301. png_warning(png_ptr, "Invalid palette length");
  197302. return;
  197303. }
  197304. }
  197305. /*
  197306. * It may not actually be necessary to set png_ptr->palette here;
  197307. * we do it for backward compatibility with the way the png_handle_tRNS
  197308. * function used to do the allocation.
  197309. */
  197310. #ifdef PNG_FREE_ME_SUPPORTED
  197311. png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0);
  197312. #endif
  197313. /* Changed in libpng-1.2.1 to allocate PNG_MAX_PALETTE_LENGTH instead
  197314. of num_palette entries,
  197315. in case of an invalid PNG file that has too-large sample values. */
  197316. png_ptr->palette = (png_colorp)png_malloc(png_ptr,
  197317. PNG_MAX_PALETTE_LENGTH * png_sizeof(png_color));
  197318. png_memset(png_ptr->palette, 0, PNG_MAX_PALETTE_LENGTH *
  197319. png_sizeof(png_color));
  197320. png_memcpy(png_ptr->palette, palette, num_palette * png_sizeof (png_color));
  197321. info_ptr->palette = png_ptr->palette;
  197322. info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette;
  197323. #ifdef PNG_FREE_ME_SUPPORTED
  197324. info_ptr->free_me |= PNG_FREE_PLTE;
  197325. #else
  197326. png_ptr->flags |= PNG_FLAG_FREE_PLTE;
  197327. #endif
  197328. info_ptr->valid |= PNG_INFO_PLTE;
  197329. }
  197330. #if defined(PNG_sBIT_SUPPORTED)
  197331. void PNGAPI
  197332. png_set_sBIT(png_structp png_ptr, png_infop info_ptr,
  197333. png_color_8p sig_bit)
  197334. {
  197335. png_debug1(1, "in %s storage function\n", "sBIT");
  197336. if (png_ptr == NULL || info_ptr == NULL)
  197337. return;
  197338. png_memcpy(&(info_ptr->sig_bit), sig_bit, png_sizeof (png_color_8));
  197339. info_ptr->valid |= PNG_INFO_sBIT;
  197340. }
  197341. #endif
  197342. #if defined(PNG_sRGB_SUPPORTED)
  197343. void PNGAPI
  197344. png_set_sRGB(png_structp png_ptr, png_infop info_ptr, int intent)
  197345. {
  197346. png_debug1(1, "in %s storage function\n", "sRGB");
  197347. if (png_ptr == NULL || info_ptr == NULL)
  197348. return;
  197349. info_ptr->srgb_intent = (png_byte)intent;
  197350. info_ptr->valid |= PNG_INFO_sRGB;
  197351. }
  197352. void PNGAPI
  197353. png_set_sRGB_gAMA_and_cHRM(png_structp png_ptr, png_infop info_ptr,
  197354. int intent)
  197355. {
  197356. #if defined(PNG_gAMA_SUPPORTED)
  197357. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197358. float file_gamma;
  197359. #endif
  197360. #ifdef PNG_FIXED_POINT_SUPPORTED
  197361. png_fixed_point int_file_gamma;
  197362. #endif
  197363. #endif
  197364. #if defined(PNG_cHRM_SUPPORTED)
  197365. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197366. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  197367. #endif
  197368. #ifdef PNG_FIXED_POINT_SUPPORTED
  197369. png_fixed_point int_white_x, int_white_y, int_red_x, int_red_y, int_green_x,
  197370. int_green_y, int_blue_x, int_blue_y;
  197371. #endif
  197372. #endif
  197373. png_debug1(1, "in %s storage function\n", "sRGB_gAMA_and_cHRM");
  197374. if (png_ptr == NULL || info_ptr == NULL)
  197375. return;
  197376. png_set_sRGB(png_ptr, info_ptr, intent);
  197377. #if defined(PNG_gAMA_SUPPORTED)
  197378. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197379. file_gamma = (float).45455;
  197380. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  197381. #endif
  197382. #ifdef PNG_FIXED_POINT_SUPPORTED
  197383. int_file_gamma = 45455L;
  197384. png_set_gAMA_fixed(png_ptr, info_ptr, int_file_gamma);
  197385. #endif
  197386. #endif
  197387. #if defined(PNG_cHRM_SUPPORTED)
  197388. #ifdef PNG_FIXED_POINT_SUPPORTED
  197389. int_white_x = 31270L;
  197390. int_white_y = 32900L;
  197391. int_red_x = 64000L;
  197392. int_red_y = 33000L;
  197393. int_green_x = 30000L;
  197394. int_green_y = 60000L;
  197395. int_blue_x = 15000L;
  197396. int_blue_y = 6000L;
  197397. png_set_cHRM_fixed(png_ptr, info_ptr,
  197398. int_white_x, int_white_y, int_red_x, int_red_y, int_green_x, int_green_y,
  197399. int_blue_x, int_blue_y);
  197400. #endif
  197401. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197402. white_x = (float).3127;
  197403. white_y = (float).3290;
  197404. red_x = (float).64;
  197405. red_y = (float).33;
  197406. green_x = (float).30;
  197407. green_y = (float).60;
  197408. blue_x = (float).15;
  197409. blue_y = (float).06;
  197410. png_set_cHRM(png_ptr, info_ptr,
  197411. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  197412. #endif
  197413. #endif
  197414. }
  197415. #endif
  197416. #if defined(PNG_iCCP_SUPPORTED)
  197417. void PNGAPI
  197418. png_set_iCCP(png_structp png_ptr, png_infop info_ptr,
  197419. png_charp name, int compression_type,
  197420. png_charp profile, png_uint_32 proflen)
  197421. {
  197422. png_charp new_iccp_name;
  197423. png_charp new_iccp_profile;
  197424. png_debug1(1, "in %s storage function\n", "iCCP");
  197425. if (png_ptr == NULL || info_ptr == NULL || name == NULL || profile == NULL)
  197426. return;
  197427. new_iccp_name = (png_charp)png_malloc_warn(png_ptr, png_strlen(name)+1);
  197428. if (new_iccp_name == NULL)
  197429. {
  197430. png_warning(png_ptr, "Insufficient memory to process iCCP chunk.");
  197431. return;
  197432. }
  197433. png_strncpy(new_iccp_name, name, png_strlen(name)+1);
  197434. new_iccp_profile = (png_charp)png_malloc_warn(png_ptr, proflen);
  197435. if (new_iccp_profile == NULL)
  197436. {
  197437. png_free (png_ptr, new_iccp_name);
  197438. png_warning(png_ptr, "Insufficient memory to process iCCP profile.");
  197439. return;
  197440. }
  197441. png_memcpy(new_iccp_profile, profile, (png_size_t)proflen);
  197442. png_free_data(png_ptr, info_ptr, PNG_FREE_ICCP, 0);
  197443. info_ptr->iccp_proflen = proflen;
  197444. info_ptr->iccp_name = new_iccp_name;
  197445. info_ptr->iccp_profile = new_iccp_profile;
  197446. /* Compression is always zero but is here so the API and info structure
  197447. * does not have to change if we introduce multiple compression types */
  197448. info_ptr->iccp_compression = (png_byte)compression_type;
  197449. #ifdef PNG_FREE_ME_SUPPORTED
  197450. info_ptr->free_me |= PNG_FREE_ICCP;
  197451. #endif
  197452. info_ptr->valid |= PNG_INFO_iCCP;
  197453. }
  197454. #endif
  197455. #if defined(PNG_TEXT_SUPPORTED)
  197456. void PNGAPI
  197457. png_set_text(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  197458. int num_text)
  197459. {
  197460. int ret;
  197461. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, num_text);
  197462. if (ret)
  197463. png_error(png_ptr, "Insufficient memory to store text");
  197464. }
  197465. int /* PRIVATE */
  197466. png_set_text_2(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  197467. int num_text)
  197468. {
  197469. int i;
  197470. png_debug1(1, "in %s storage function\n", (png_ptr->chunk_name[0] == '\0' ?
  197471. "text" : (png_const_charp)png_ptr->chunk_name));
  197472. if (png_ptr == NULL || info_ptr == NULL || num_text == 0)
  197473. return(0);
  197474. /* Make sure we have enough space in the "text" array in info_struct
  197475. * to hold all of the incoming text_ptr objects.
  197476. */
  197477. if (info_ptr->num_text + num_text > info_ptr->max_text)
  197478. {
  197479. if (info_ptr->text != NULL)
  197480. {
  197481. png_textp old_text;
  197482. int old_max;
  197483. old_max = info_ptr->max_text;
  197484. info_ptr->max_text = info_ptr->num_text + num_text + 8;
  197485. old_text = info_ptr->text;
  197486. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  197487. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  197488. if (info_ptr->text == NULL)
  197489. {
  197490. png_free(png_ptr, old_text);
  197491. return(1);
  197492. }
  197493. png_memcpy(info_ptr->text, old_text, (png_size_t)(old_max *
  197494. png_sizeof(png_text)));
  197495. png_free(png_ptr, old_text);
  197496. }
  197497. else
  197498. {
  197499. info_ptr->max_text = num_text + 8;
  197500. info_ptr->num_text = 0;
  197501. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  197502. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  197503. if (info_ptr->text == NULL)
  197504. return(1);
  197505. #ifdef PNG_FREE_ME_SUPPORTED
  197506. info_ptr->free_me |= PNG_FREE_TEXT;
  197507. #endif
  197508. }
  197509. png_debug1(3, "allocated %d entries for info_ptr->text\n",
  197510. info_ptr->max_text);
  197511. }
  197512. for (i = 0; i < num_text; i++)
  197513. {
  197514. png_size_t text_length,key_len;
  197515. png_size_t lang_len,lang_key_len;
  197516. png_textp textp = &(info_ptr->text[info_ptr->num_text]);
  197517. if (text_ptr[i].key == NULL)
  197518. continue;
  197519. key_len = png_strlen(text_ptr[i].key);
  197520. if(text_ptr[i].compression <= 0)
  197521. {
  197522. lang_len = 0;
  197523. lang_key_len = 0;
  197524. }
  197525. else
  197526. #ifdef PNG_iTXt_SUPPORTED
  197527. {
  197528. /* set iTXt data */
  197529. if (text_ptr[i].lang != NULL)
  197530. lang_len = png_strlen(text_ptr[i].lang);
  197531. else
  197532. lang_len = 0;
  197533. if (text_ptr[i].lang_key != NULL)
  197534. lang_key_len = png_strlen(text_ptr[i].lang_key);
  197535. else
  197536. lang_key_len = 0;
  197537. }
  197538. #else
  197539. {
  197540. png_warning(png_ptr, "iTXt chunk not supported.");
  197541. continue;
  197542. }
  197543. #endif
  197544. if (text_ptr[i].text == NULL || text_ptr[i].text[0] == '\0')
  197545. {
  197546. text_length = 0;
  197547. #ifdef PNG_iTXt_SUPPORTED
  197548. if(text_ptr[i].compression > 0)
  197549. textp->compression = PNG_ITXT_COMPRESSION_NONE;
  197550. else
  197551. #endif
  197552. textp->compression = PNG_TEXT_COMPRESSION_NONE;
  197553. }
  197554. else
  197555. {
  197556. text_length = png_strlen(text_ptr[i].text);
  197557. textp->compression = text_ptr[i].compression;
  197558. }
  197559. textp->key = (png_charp)png_malloc_warn(png_ptr,
  197560. (png_uint_32)(key_len + text_length + lang_len + lang_key_len + 4));
  197561. if (textp->key == NULL)
  197562. return(1);
  197563. png_debug2(2, "Allocated %lu bytes at %x in png_set_text\n",
  197564. (png_uint_32)(key_len + lang_len + lang_key_len + text_length + 4),
  197565. (int)textp->key);
  197566. png_memcpy(textp->key, text_ptr[i].key,
  197567. (png_size_t)(key_len));
  197568. *(textp->key+key_len) = '\0';
  197569. #ifdef PNG_iTXt_SUPPORTED
  197570. if (text_ptr[i].compression > 0)
  197571. {
  197572. textp->lang=textp->key + key_len + 1;
  197573. png_memcpy(textp->lang, text_ptr[i].lang, lang_len);
  197574. *(textp->lang+lang_len) = '\0';
  197575. textp->lang_key=textp->lang + lang_len + 1;
  197576. png_memcpy(textp->lang_key, text_ptr[i].lang_key, lang_key_len);
  197577. *(textp->lang_key+lang_key_len) = '\0';
  197578. textp->text=textp->lang_key + lang_key_len + 1;
  197579. }
  197580. else
  197581. #endif
  197582. {
  197583. #ifdef PNG_iTXt_SUPPORTED
  197584. textp->lang=NULL;
  197585. textp->lang_key=NULL;
  197586. #endif
  197587. textp->text=textp->key + key_len + 1;
  197588. }
  197589. if(text_length)
  197590. png_memcpy(textp->text, text_ptr[i].text,
  197591. (png_size_t)(text_length));
  197592. *(textp->text+text_length) = '\0';
  197593. #ifdef PNG_iTXt_SUPPORTED
  197594. if(textp->compression > 0)
  197595. {
  197596. textp->text_length = 0;
  197597. textp->itxt_length = text_length;
  197598. }
  197599. else
  197600. #endif
  197601. {
  197602. textp->text_length = text_length;
  197603. #ifdef PNG_iTXt_SUPPORTED
  197604. textp->itxt_length = 0;
  197605. #endif
  197606. }
  197607. info_ptr->num_text++;
  197608. png_debug1(3, "transferred text chunk %d\n", info_ptr->num_text);
  197609. }
  197610. return(0);
  197611. }
  197612. #endif
  197613. #if defined(PNG_tIME_SUPPORTED)
  197614. void PNGAPI
  197615. png_set_tIME(png_structp png_ptr, png_infop info_ptr, png_timep mod_time)
  197616. {
  197617. png_debug1(1, "in %s storage function\n", "tIME");
  197618. if (png_ptr == NULL || info_ptr == NULL ||
  197619. (png_ptr->mode & PNG_WROTE_tIME))
  197620. return;
  197621. png_memcpy(&(info_ptr->mod_time), mod_time, png_sizeof (png_time));
  197622. info_ptr->valid |= PNG_INFO_tIME;
  197623. }
  197624. #endif
  197625. #if defined(PNG_tRNS_SUPPORTED)
  197626. void PNGAPI
  197627. png_set_tRNS(png_structp png_ptr, png_infop info_ptr,
  197628. png_bytep trans, int num_trans, png_color_16p trans_values)
  197629. {
  197630. png_debug1(1, "in %s storage function\n", "tRNS");
  197631. if (png_ptr == NULL || info_ptr == NULL)
  197632. return;
  197633. if (trans != NULL)
  197634. {
  197635. /*
  197636. * It may not actually be necessary to set png_ptr->trans here;
  197637. * we do it for backward compatibility with the way the png_handle_tRNS
  197638. * function used to do the allocation.
  197639. */
  197640. #ifdef PNG_FREE_ME_SUPPORTED
  197641. png_free_data(png_ptr, info_ptr, PNG_FREE_TRNS, 0);
  197642. #endif
  197643. /* Changed from num_trans to PNG_MAX_PALETTE_LENGTH in version 1.2.1 */
  197644. png_ptr->trans = info_ptr->trans = (png_bytep)png_malloc(png_ptr,
  197645. (png_uint_32)PNG_MAX_PALETTE_LENGTH);
  197646. if (num_trans <= PNG_MAX_PALETTE_LENGTH)
  197647. png_memcpy(info_ptr->trans, trans, (png_size_t)num_trans);
  197648. #ifdef PNG_FREE_ME_SUPPORTED
  197649. info_ptr->free_me |= PNG_FREE_TRNS;
  197650. #else
  197651. png_ptr->flags |= PNG_FLAG_FREE_TRNS;
  197652. #endif
  197653. }
  197654. if (trans_values != NULL)
  197655. {
  197656. png_memcpy(&(info_ptr->trans_values), trans_values,
  197657. png_sizeof(png_color_16));
  197658. if (num_trans == 0)
  197659. num_trans = 1;
  197660. }
  197661. info_ptr->num_trans = (png_uint_16)num_trans;
  197662. info_ptr->valid |= PNG_INFO_tRNS;
  197663. }
  197664. #endif
  197665. #if defined(PNG_sPLT_SUPPORTED)
  197666. void PNGAPI
  197667. png_set_sPLT(png_structp png_ptr,
  197668. png_infop info_ptr, png_sPLT_tp entries, int nentries)
  197669. {
  197670. png_sPLT_tp np;
  197671. int i;
  197672. if (png_ptr == NULL || info_ptr == NULL)
  197673. return;
  197674. np = (png_sPLT_tp)png_malloc_warn(png_ptr,
  197675. (info_ptr->splt_palettes_num + nentries) * png_sizeof(png_sPLT_t));
  197676. if (np == NULL)
  197677. {
  197678. png_warning(png_ptr, "No memory for sPLT palettes.");
  197679. return;
  197680. }
  197681. png_memcpy(np, info_ptr->splt_palettes,
  197682. info_ptr->splt_palettes_num * png_sizeof(png_sPLT_t));
  197683. png_free(png_ptr, info_ptr->splt_palettes);
  197684. info_ptr->splt_palettes=NULL;
  197685. for (i = 0; i < nentries; i++)
  197686. {
  197687. png_sPLT_tp to = np + info_ptr->splt_palettes_num + i;
  197688. png_sPLT_tp from = entries + i;
  197689. to->name = (png_charp)png_malloc_warn(png_ptr,
  197690. png_strlen(from->name) + 1);
  197691. if (to->name == NULL)
  197692. {
  197693. png_warning(png_ptr,
  197694. "Out of memory while processing sPLT chunk");
  197695. }
  197696. /* TODO: use png_malloc_warn */
  197697. png_strncpy(to->name, from->name, png_strlen(from->name)+1);
  197698. to->entries = (png_sPLT_entryp)png_malloc_warn(png_ptr,
  197699. from->nentries * png_sizeof(png_sPLT_entry));
  197700. /* TODO: use png_malloc_warn */
  197701. png_memcpy(to->entries, from->entries,
  197702. from->nentries * png_sizeof(png_sPLT_entry));
  197703. if (to->entries == NULL)
  197704. {
  197705. png_warning(png_ptr,
  197706. "Out of memory while processing sPLT chunk");
  197707. png_free(png_ptr,to->name);
  197708. to->name = NULL;
  197709. }
  197710. to->nentries = from->nentries;
  197711. to->depth = from->depth;
  197712. }
  197713. info_ptr->splt_palettes = np;
  197714. info_ptr->splt_palettes_num += nentries;
  197715. info_ptr->valid |= PNG_INFO_sPLT;
  197716. #ifdef PNG_FREE_ME_SUPPORTED
  197717. info_ptr->free_me |= PNG_FREE_SPLT;
  197718. #endif
  197719. }
  197720. #endif /* PNG_sPLT_SUPPORTED */
  197721. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  197722. void PNGAPI
  197723. png_set_unknown_chunks(png_structp png_ptr,
  197724. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns)
  197725. {
  197726. png_unknown_chunkp np;
  197727. int i;
  197728. if (png_ptr == NULL || info_ptr == NULL || num_unknowns == 0)
  197729. return;
  197730. np = (png_unknown_chunkp)png_malloc_warn(png_ptr,
  197731. (info_ptr->unknown_chunks_num + num_unknowns) *
  197732. png_sizeof(png_unknown_chunk));
  197733. if (np == NULL)
  197734. {
  197735. png_warning(png_ptr,
  197736. "Out of memory while processing unknown chunk.");
  197737. return;
  197738. }
  197739. png_memcpy(np, info_ptr->unknown_chunks,
  197740. info_ptr->unknown_chunks_num * png_sizeof(png_unknown_chunk));
  197741. png_free(png_ptr, info_ptr->unknown_chunks);
  197742. info_ptr->unknown_chunks=NULL;
  197743. for (i = 0; i < num_unknowns; i++)
  197744. {
  197745. png_unknown_chunkp to = np + info_ptr->unknown_chunks_num + i;
  197746. png_unknown_chunkp from = unknowns + i;
  197747. png_strncpy((png_charp)to->name, (png_charp)from->name, 5);
  197748. to->data = (png_bytep)png_malloc_warn(png_ptr, from->size);
  197749. if (to->data == NULL)
  197750. {
  197751. png_warning(png_ptr,
  197752. "Out of memory while processing unknown chunk.");
  197753. }
  197754. else
  197755. {
  197756. png_memcpy(to->data, from->data, from->size);
  197757. to->size = from->size;
  197758. /* note our location in the read or write sequence */
  197759. to->location = (png_byte)(png_ptr->mode & 0xff);
  197760. }
  197761. }
  197762. info_ptr->unknown_chunks = np;
  197763. info_ptr->unknown_chunks_num += num_unknowns;
  197764. #ifdef PNG_FREE_ME_SUPPORTED
  197765. info_ptr->free_me |= PNG_FREE_UNKN;
  197766. #endif
  197767. }
  197768. void PNGAPI
  197769. png_set_unknown_chunk_location(png_structp png_ptr, png_infop info_ptr,
  197770. int chunk, int location)
  197771. {
  197772. if(png_ptr != NULL && info_ptr != NULL && chunk >= 0 && chunk <
  197773. (int)info_ptr->unknown_chunks_num)
  197774. info_ptr->unknown_chunks[chunk].location = (png_byte)location;
  197775. }
  197776. #endif
  197777. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  197778. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  197779. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  197780. void PNGAPI
  197781. png_permit_empty_plte (png_structp png_ptr, int empty_plte_permitted)
  197782. {
  197783. /* This function is deprecated in favor of png_permit_mng_features()
  197784. and will be removed from libpng-1.3.0 */
  197785. png_debug(1, "in png_permit_empty_plte, DEPRECATED.\n");
  197786. if (png_ptr == NULL)
  197787. return;
  197788. png_ptr->mng_features_permitted = (png_byte)
  197789. ((png_ptr->mng_features_permitted & (~(PNG_FLAG_MNG_EMPTY_PLTE))) |
  197790. ((empty_plte_permitted & PNG_FLAG_MNG_EMPTY_PLTE)));
  197791. }
  197792. #endif
  197793. #endif
  197794. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  197795. png_uint_32 PNGAPI
  197796. png_permit_mng_features (png_structp png_ptr, png_uint_32 mng_features)
  197797. {
  197798. png_debug(1, "in png_permit_mng_features\n");
  197799. if (png_ptr == NULL)
  197800. return (png_uint_32)0;
  197801. png_ptr->mng_features_permitted =
  197802. (png_byte)(mng_features & PNG_ALL_MNG_FEATURES);
  197803. return (png_uint_32)png_ptr->mng_features_permitted;
  197804. }
  197805. #endif
  197806. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  197807. void PNGAPI
  197808. png_set_keep_unknown_chunks(png_structp png_ptr, int keep, png_bytep
  197809. chunk_list, int num_chunks)
  197810. {
  197811. png_bytep new_list, p;
  197812. int i, old_num_chunks;
  197813. if (png_ptr == NULL)
  197814. return;
  197815. if (num_chunks == 0)
  197816. {
  197817. if(keep == PNG_HANDLE_CHUNK_ALWAYS || keep == PNG_HANDLE_CHUNK_IF_SAFE)
  197818. png_ptr->flags |= PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  197819. else
  197820. png_ptr->flags &= ~PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  197821. if(keep == PNG_HANDLE_CHUNK_ALWAYS)
  197822. png_ptr->flags |= PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  197823. else
  197824. png_ptr->flags &= ~PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  197825. return;
  197826. }
  197827. if (chunk_list == NULL)
  197828. return;
  197829. old_num_chunks=png_ptr->num_chunk_list;
  197830. new_list=(png_bytep)png_malloc(png_ptr,
  197831. (png_uint_32)(5*(num_chunks+old_num_chunks)));
  197832. if(png_ptr->chunk_list != NULL)
  197833. {
  197834. png_memcpy(new_list, png_ptr->chunk_list,
  197835. (png_size_t)(5*old_num_chunks));
  197836. png_free(png_ptr, png_ptr->chunk_list);
  197837. png_ptr->chunk_list=NULL;
  197838. }
  197839. png_memcpy(new_list+5*old_num_chunks, chunk_list,
  197840. (png_size_t)(5*num_chunks));
  197841. for (p=new_list+5*old_num_chunks+4, i=0; i<num_chunks; i++, p+=5)
  197842. *p=(png_byte)keep;
  197843. png_ptr->num_chunk_list=old_num_chunks+num_chunks;
  197844. png_ptr->chunk_list=new_list;
  197845. #ifdef PNG_FREE_ME_SUPPORTED
  197846. png_ptr->free_me |= PNG_FREE_LIST;
  197847. #endif
  197848. }
  197849. #endif
  197850. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  197851. void PNGAPI
  197852. png_set_read_user_chunk_fn(png_structp png_ptr, png_voidp user_chunk_ptr,
  197853. png_user_chunk_ptr read_user_chunk_fn)
  197854. {
  197855. png_debug(1, "in png_set_read_user_chunk_fn\n");
  197856. if (png_ptr == NULL)
  197857. return;
  197858. png_ptr->read_user_chunk_fn = read_user_chunk_fn;
  197859. png_ptr->user_chunk_ptr = user_chunk_ptr;
  197860. }
  197861. #endif
  197862. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  197863. void PNGAPI
  197864. png_set_rows(png_structp png_ptr, png_infop info_ptr, png_bytepp row_pointers)
  197865. {
  197866. png_debug1(1, "in %s storage function\n", "rows");
  197867. if (png_ptr == NULL || info_ptr == NULL)
  197868. return;
  197869. if(info_ptr->row_pointers && (info_ptr->row_pointers != row_pointers))
  197870. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  197871. info_ptr->row_pointers = row_pointers;
  197872. if(row_pointers)
  197873. info_ptr->valid |= PNG_INFO_IDAT;
  197874. }
  197875. #endif
  197876. #ifdef PNG_WRITE_SUPPORTED
  197877. void PNGAPI
  197878. png_set_compression_buffer_size(png_structp png_ptr, png_uint_32 size)
  197879. {
  197880. if (png_ptr == NULL)
  197881. return;
  197882. if(png_ptr->zbuf)
  197883. png_free(png_ptr, png_ptr->zbuf);
  197884. png_ptr->zbuf_size = (png_size_t)size;
  197885. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, size);
  197886. png_ptr->zstream.next_out = png_ptr->zbuf;
  197887. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  197888. }
  197889. #endif
  197890. void PNGAPI
  197891. png_set_invalid(png_structp png_ptr, png_infop info_ptr, int mask)
  197892. {
  197893. if (png_ptr && info_ptr)
  197894. info_ptr->valid &= ~(mask);
  197895. }
  197896. #ifndef PNG_1_0_X
  197897. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  197898. /* function was added to libpng 1.2.0 and should always exist by default */
  197899. void PNGAPI
  197900. png_set_asm_flags (png_structp png_ptr, png_uint_32)
  197901. {
  197902. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  197903. if (png_ptr != NULL)
  197904. png_ptr->asm_flags = 0;
  197905. }
  197906. /* this function was added to libpng 1.2.0 */
  197907. void PNGAPI
  197908. png_set_mmx_thresholds (png_structp png_ptr,
  197909. png_byte,
  197910. png_uint_32)
  197911. {
  197912. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  197913. if (png_ptr == NULL)
  197914. return;
  197915. }
  197916. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  197917. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  197918. /* this function was added to libpng 1.2.6 */
  197919. void PNGAPI
  197920. png_set_user_limits (png_structp png_ptr, png_uint_32 user_width_max,
  197921. png_uint_32 user_height_max)
  197922. {
  197923. /* Images with dimensions larger than these limits will be
  197924. * rejected by png_set_IHDR(). To accept any PNG datastream
  197925. * regardless of dimensions, set both limits to 0x7ffffffL.
  197926. */
  197927. if(png_ptr == NULL) return;
  197928. png_ptr->user_width_max = user_width_max;
  197929. png_ptr->user_height_max = user_height_max;
  197930. }
  197931. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  197932. #endif /* ?PNG_1_0_X */
  197933. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  197934. /*** End of inlined file: pngset.c ***/
  197935. /*** Start of inlined file: pngtrans.c ***/
  197936. /* pngtrans.c - transforms the data in a row (used by both readers and writers)
  197937. *
  197938. * Last changed in libpng 1.2.17 May 15, 2007
  197939. * For conditions of distribution and use, see copyright notice in png.h
  197940. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  197941. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  197942. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  197943. */
  197944. #define PNG_INTERNAL
  197945. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  197946. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  197947. /* turn on BGR-to-RGB mapping */
  197948. void PNGAPI
  197949. png_set_bgr(png_structp png_ptr)
  197950. {
  197951. png_debug(1, "in png_set_bgr\n");
  197952. if(png_ptr == NULL) return;
  197953. png_ptr->transformations |= PNG_BGR;
  197954. }
  197955. #endif
  197956. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  197957. /* turn on 16 bit byte swapping */
  197958. void PNGAPI
  197959. png_set_swap(png_structp png_ptr)
  197960. {
  197961. png_debug(1, "in png_set_swap\n");
  197962. if(png_ptr == NULL) return;
  197963. if (png_ptr->bit_depth == 16)
  197964. png_ptr->transformations |= PNG_SWAP_BYTES;
  197965. }
  197966. #endif
  197967. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  197968. /* turn on pixel packing */
  197969. void PNGAPI
  197970. png_set_packing(png_structp png_ptr)
  197971. {
  197972. png_debug(1, "in png_set_packing\n");
  197973. if(png_ptr == NULL) return;
  197974. if (png_ptr->bit_depth < 8)
  197975. {
  197976. png_ptr->transformations |= PNG_PACK;
  197977. png_ptr->usr_bit_depth = 8;
  197978. }
  197979. }
  197980. #endif
  197981. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  197982. /* turn on packed pixel swapping */
  197983. void PNGAPI
  197984. png_set_packswap(png_structp png_ptr)
  197985. {
  197986. png_debug(1, "in png_set_packswap\n");
  197987. if(png_ptr == NULL) return;
  197988. if (png_ptr->bit_depth < 8)
  197989. png_ptr->transformations |= PNG_PACKSWAP;
  197990. }
  197991. #endif
  197992. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  197993. void PNGAPI
  197994. png_set_shift(png_structp png_ptr, png_color_8p true_bits)
  197995. {
  197996. png_debug(1, "in png_set_shift\n");
  197997. if(png_ptr == NULL) return;
  197998. png_ptr->transformations |= PNG_SHIFT;
  197999. png_ptr->shift = *true_bits;
  198000. }
  198001. #endif
  198002. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  198003. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  198004. int PNGAPI
  198005. png_set_interlace_handling(png_structp png_ptr)
  198006. {
  198007. png_debug(1, "in png_set_interlace handling\n");
  198008. if (png_ptr && png_ptr->interlaced)
  198009. {
  198010. png_ptr->transformations |= PNG_INTERLACE;
  198011. return (7);
  198012. }
  198013. return (1);
  198014. }
  198015. #endif
  198016. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  198017. /* Add a filler byte on read, or remove a filler or alpha byte on write.
  198018. * The filler type has changed in v0.95 to allow future 2-byte fillers
  198019. * for 48-bit input data, as well as to avoid problems with some compilers
  198020. * that don't like bytes as parameters.
  198021. */
  198022. void PNGAPI
  198023. png_set_filler(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  198024. {
  198025. png_debug(1, "in png_set_filler\n");
  198026. if(png_ptr == NULL) return;
  198027. png_ptr->transformations |= PNG_FILLER;
  198028. png_ptr->filler = (png_byte)filler;
  198029. if (filler_loc == PNG_FILLER_AFTER)
  198030. png_ptr->flags |= PNG_FLAG_FILLER_AFTER;
  198031. else
  198032. png_ptr->flags &= ~PNG_FLAG_FILLER_AFTER;
  198033. /* This should probably go in the "do_read_filler" routine.
  198034. * I attempted to do that in libpng-1.0.1a but that caused problems
  198035. * so I restored it in libpng-1.0.2a
  198036. */
  198037. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  198038. {
  198039. png_ptr->usr_channels = 4;
  198040. }
  198041. /* Also I added this in libpng-1.0.2a (what happens when we expand
  198042. * a less-than-8-bit grayscale to GA? */
  198043. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY && png_ptr->bit_depth >= 8)
  198044. {
  198045. png_ptr->usr_channels = 2;
  198046. }
  198047. }
  198048. #if !defined(PNG_1_0_X)
  198049. /* Added to libpng-1.2.7 */
  198050. void PNGAPI
  198051. png_set_add_alpha(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  198052. {
  198053. png_debug(1, "in png_set_add_alpha\n");
  198054. if(png_ptr == NULL) return;
  198055. png_set_filler(png_ptr, filler, filler_loc);
  198056. png_ptr->transformations |= PNG_ADD_ALPHA;
  198057. }
  198058. #endif
  198059. #endif
  198060. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  198061. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  198062. void PNGAPI
  198063. png_set_swap_alpha(png_structp png_ptr)
  198064. {
  198065. png_debug(1, "in png_set_swap_alpha\n");
  198066. if(png_ptr == NULL) return;
  198067. png_ptr->transformations |= PNG_SWAP_ALPHA;
  198068. }
  198069. #endif
  198070. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  198071. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  198072. void PNGAPI
  198073. png_set_invert_alpha(png_structp png_ptr)
  198074. {
  198075. png_debug(1, "in png_set_invert_alpha\n");
  198076. if(png_ptr == NULL) return;
  198077. png_ptr->transformations |= PNG_INVERT_ALPHA;
  198078. }
  198079. #endif
  198080. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  198081. void PNGAPI
  198082. png_set_invert_mono(png_structp png_ptr)
  198083. {
  198084. png_debug(1, "in png_set_invert_mono\n");
  198085. if(png_ptr == NULL) return;
  198086. png_ptr->transformations |= PNG_INVERT_MONO;
  198087. }
  198088. /* invert monochrome grayscale data */
  198089. void /* PRIVATE */
  198090. png_do_invert(png_row_infop row_info, png_bytep row)
  198091. {
  198092. png_debug(1, "in png_do_invert\n");
  198093. /* This test removed from libpng version 1.0.13 and 1.2.0:
  198094. * if (row_info->bit_depth == 1 &&
  198095. */
  198096. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198097. if (row == NULL || row_info == NULL)
  198098. return;
  198099. #endif
  198100. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  198101. {
  198102. png_bytep rp = row;
  198103. png_uint_32 i;
  198104. png_uint_32 istop = row_info->rowbytes;
  198105. for (i = 0; i < istop; i++)
  198106. {
  198107. *rp = (png_byte)(~(*rp));
  198108. rp++;
  198109. }
  198110. }
  198111. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  198112. row_info->bit_depth == 8)
  198113. {
  198114. png_bytep rp = row;
  198115. png_uint_32 i;
  198116. png_uint_32 istop = row_info->rowbytes;
  198117. for (i = 0; i < istop; i+=2)
  198118. {
  198119. *rp = (png_byte)(~(*rp));
  198120. rp+=2;
  198121. }
  198122. }
  198123. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  198124. row_info->bit_depth == 16)
  198125. {
  198126. png_bytep rp = row;
  198127. png_uint_32 i;
  198128. png_uint_32 istop = row_info->rowbytes;
  198129. for (i = 0; i < istop; i+=4)
  198130. {
  198131. *rp = (png_byte)(~(*rp));
  198132. *(rp+1) = (png_byte)(~(*(rp+1)));
  198133. rp+=4;
  198134. }
  198135. }
  198136. }
  198137. #endif
  198138. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  198139. /* swaps byte order on 16 bit depth images */
  198140. void /* PRIVATE */
  198141. png_do_swap(png_row_infop row_info, png_bytep row)
  198142. {
  198143. png_debug(1, "in png_do_swap\n");
  198144. if (
  198145. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198146. row != NULL && row_info != NULL &&
  198147. #endif
  198148. row_info->bit_depth == 16)
  198149. {
  198150. png_bytep rp = row;
  198151. png_uint_32 i;
  198152. png_uint_32 istop= row_info->width * row_info->channels;
  198153. for (i = 0; i < istop; i++, rp += 2)
  198154. {
  198155. png_byte t = *rp;
  198156. *rp = *(rp + 1);
  198157. *(rp + 1) = t;
  198158. }
  198159. }
  198160. }
  198161. #endif
  198162. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  198163. static PNG_CONST png_byte onebppswaptable[256] = {
  198164. 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0,
  198165. 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0,
  198166. 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8,
  198167. 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8,
  198168. 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4,
  198169. 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4,
  198170. 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC,
  198171. 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC,
  198172. 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2,
  198173. 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2,
  198174. 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA,
  198175. 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA,
  198176. 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6,
  198177. 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6,
  198178. 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE,
  198179. 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE,
  198180. 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1,
  198181. 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1,
  198182. 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9,
  198183. 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9,
  198184. 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5,
  198185. 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5,
  198186. 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED,
  198187. 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD,
  198188. 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3,
  198189. 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3,
  198190. 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB,
  198191. 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB,
  198192. 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7,
  198193. 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7,
  198194. 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF,
  198195. 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF
  198196. };
  198197. static PNG_CONST png_byte twobppswaptable[256] = {
  198198. 0x00, 0x40, 0x80, 0xC0, 0x10, 0x50, 0x90, 0xD0,
  198199. 0x20, 0x60, 0xA0, 0xE0, 0x30, 0x70, 0xB0, 0xF0,
  198200. 0x04, 0x44, 0x84, 0xC4, 0x14, 0x54, 0x94, 0xD4,
  198201. 0x24, 0x64, 0xA4, 0xE4, 0x34, 0x74, 0xB4, 0xF4,
  198202. 0x08, 0x48, 0x88, 0xC8, 0x18, 0x58, 0x98, 0xD8,
  198203. 0x28, 0x68, 0xA8, 0xE8, 0x38, 0x78, 0xB8, 0xF8,
  198204. 0x0C, 0x4C, 0x8C, 0xCC, 0x1C, 0x5C, 0x9C, 0xDC,
  198205. 0x2C, 0x6C, 0xAC, 0xEC, 0x3C, 0x7C, 0xBC, 0xFC,
  198206. 0x01, 0x41, 0x81, 0xC1, 0x11, 0x51, 0x91, 0xD1,
  198207. 0x21, 0x61, 0xA1, 0xE1, 0x31, 0x71, 0xB1, 0xF1,
  198208. 0x05, 0x45, 0x85, 0xC5, 0x15, 0x55, 0x95, 0xD5,
  198209. 0x25, 0x65, 0xA5, 0xE5, 0x35, 0x75, 0xB5, 0xF5,
  198210. 0x09, 0x49, 0x89, 0xC9, 0x19, 0x59, 0x99, 0xD9,
  198211. 0x29, 0x69, 0xA9, 0xE9, 0x39, 0x79, 0xB9, 0xF9,
  198212. 0x0D, 0x4D, 0x8D, 0xCD, 0x1D, 0x5D, 0x9D, 0xDD,
  198213. 0x2D, 0x6D, 0xAD, 0xED, 0x3D, 0x7D, 0xBD, 0xFD,
  198214. 0x02, 0x42, 0x82, 0xC2, 0x12, 0x52, 0x92, 0xD2,
  198215. 0x22, 0x62, 0xA2, 0xE2, 0x32, 0x72, 0xB2, 0xF2,
  198216. 0x06, 0x46, 0x86, 0xC6, 0x16, 0x56, 0x96, 0xD6,
  198217. 0x26, 0x66, 0xA6, 0xE6, 0x36, 0x76, 0xB6, 0xF6,
  198218. 0x0A, 0x4A, 0x8A, 0xCA, 0x1A, 0x5A, 0x9A, 0xDA,
  198219. 0x2A, 0x6A, 0xAA, 0xEA, 0x3A, 0x7A, 0xBA, 0xFA,
  198220. 0x0E, 0x4E, 0x8E, 0xCE, 0x1E, 0x5E, 0x9E, 0xDE,
  198221. 0x2E, 0x6E, 0xAE, 0xEE, 0x3E, 0x7E, 0xBE, 0xFE,
  198222. 0x03, 0x43, 0x83, 0xC3, 0x13, 0x53, 0x93, 0xD3,
  198223. 0x23, 0x63, 0xA3, 0xE3, 0x33, 0x73, 0xB3, 0xF3,
  198224. 0x07, 0x47, 0x87, 0xC7, 0x17, 0x57, 0x97, 0xD7,
  198225. 0x27, 0x67, 0xA7, 0xE7, 0x37, 0x77, 0xB7, 0xF7,
  198226. 0x0B, 0x4B, 0x8B, 0xCB, 0x1B, 0x5B, 0x9B, 0xDB,
  198227. 0x2B, 0x6B, 0xAB, 0xEB, 0x3B, 0x7B, 0xBB, 0xFB,
  198228. 0x0F, 0x4F, 0x8F, 0xCF, 0x1F, 0x5F, 0x9F, 0xDF,
  198229. 0x2F, 0x6F, 0xAF, 0xEF, 0x3F, 0x7F, 0xBF, 0xFF
  198230. };
  198231. static PNG_CONST png_byte fourbppswaptable[256] = {
  198232. 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70,
  198233. 0x80, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0,
  198234. 0x01, 0x11, 0x21, 0x31, 0x41, 0x51, 0x61, 0x71,
  198235. 0x81, 0x91, 0xA1, 0xB1, 0xC1, 0xD1, 0xE1, 0xF1,
  198236. 0x02, 0x12, 0x22, 0x32, 0x42, 0x52, 0x62, 0x72,
  198237. 0x82, 0x92, 0xA2, 0xB2, 0xC2, 0xD2, 0xE2, 0xF2,
  198238. 0x03, 0x13, 0x23, 0x33, 0x43, 0x53, 0x63, 0x73,
  198239. 0x83, 0x93, 0xA3, 0xB3, 0xC3, 0xD3, 0xE3, 0xF3,
  198240. 0x04, 0x14, 0x24, 0x34, 0x44, 0x54, 0x64, 0x74,
  198241. 0x84, 0x94, 0xA4, 0xB4, 0xC4, 0xD4, 0xE4, 0xF4,
  198242. 0x05, 0x15, 0x25, 0x35, 0x45, 0x55, 0x65, 0x75,
  198243. 0x85, 0x95, 0xA5, 0xB5, 0xC5, 0xD5, 0xE5, 0xF5,
  198244. 0x06, 0x16, 0x26, 0x36, 0x46, 0x56, 0x66, 0x76,
  198245. 0x86, 0x96, 0xA6, 0xB6, 0xC6, 0xD6, 0xE6, 0xF6,
  198246. 0x07, 0x17, 0x27, 0x37, 0x47, 0x57, 0x67, 0x77,
  198247. 0x87, 0x97, 0xA7, 0xB7, 0xC7, 0xD7, 0xE7, 0xF7,
  198248. 0x08, 0x18, 0x28, 0x38, 0x48, 0x58, 0x68, 0x78,
  198249. 0x88, 0x98, 0xA8, 0xB8, 0xC8, 0xD8, 0xE8, 0xF8,
  198250. 0x09, 0x19, 0x29, 0x39, 0x49, 0x59, 0x69, 0x79,
  198251. 0x89, 0x99, 0xA9, 0xB9, 0xC9, 0xD9, 0xE9, 0xF9,
  198252. 0x0A, 0x1A, 0x2A, 0x3A, 0x4A, 0x5A, 0x6A, 0x7A,
  198253. 0x8A, 0x9A, 0xAA, 0xBA, 0xCA, 0xDA, 0xEA, 0xFA,
  198254. 0x0B, 0x1B, 0x2B, 0x3B, 0x4B, 0x5B, 0x6B, 0x7B,
  198255. 0x8B, 0x9B, 0xAB, 0xBB, 0xCB, 0xDB, 0xEB, 0xFB,
  198256. 0x0C, 0x1C, 0x2C, 0x3C, 0x4C, 0x5C, 0x6C, 0x7C,
  198257. 0x8C, 0x9C, 0xAC, 0xBC, 0xCC, 0xDC, 0xEC, 0xFC,
  198258. 0x0D, 0x1D, 0x2D, 0x3D, 0x4D, 0x5D, 0x6D, 0x7D,
  198259. 0x8D, 0x9D, 0xAD, 0xBD, 0xCD, 0xDD, 0xED, 0xFD,
  198260. 0x0E, 0x1E, 0x2E, 0x3E, 0x4E, 0x5E, 0x6E, 0x7E,
  198261. 0x8E, 0x9E, 0xAE, 0xBE, 0xCE, 0xDE, 0xEE, 0xFE,
  198262. 0x0F, 0x1F, 0x2F, 0x3F, 0x4F, 0x5F, 0x6F, 0x7F,
  198263. 0x8F, 0x9F, 0xAF, 0xBF, 0xCF, 0xDF, 0xEF, 0xFF
  198264. };
  198265. /* swaps pixel packing order within bytes */
  198266. void /* PRIVATE */
  198267. png_do_packswap(png_row_infop row_info, png_bytep row)
  198268. {
  198269. png_debug(1, "in png_do_packswap\n");
  198270. if (
  198271. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198272. row != NULL && row_info != NULL &&
  198273. #endif
  198274. row_info->bit_depth < 8)
  198275. {
  198276. png_bytep rp, end, table;
  198277. end = row + row_info->rowbytes;
  198278. if (row_info->bit_depth == 1)
  198279. table = (png_bytep)onebppswaptable;
  198280. else if (row_info->bit_depth == 2)
  198281. table = (png_bytep)twobppswaptable;
  198282. else if (row_info->bit_depth == 4)
  198283. table = (png_bytep)fourbppswaptable;
  198284. else
  198285. return;
  198286. for (rp = row; rp < end; rp++)
  198287. *rp = table[*rp];
  198288. }
  198289. }
  198290. #endif /* PNG_READ_PACKSWAP_SUPPORTED or PNG_WRITE_PACKSWAP_SUPPORTED */
  198291. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  198292. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  198293. /* remove filler or alpha byte(s) */
  198294. void /* PRIVATE */
  198295. png_do_strip_filler(png_row_infop row_info, png_bytep row, png_uint_32 flags)
  198296. {
  198297. png_debug(1, "in png_do_strip_filler\n");
  198298. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198299. if (row != NULL && row_info != NULL)
  198300. #endif
  198301. {
  198302. png_bytep sp=row;
  198303. png_bytep dp=row;
  198304. png_uint_32 row_width=row_info->width;
  198305. png_uint_32 i;
  198306. if ((row_info->color_type == PNG_COLOR_TYPE_RGB ||
  198307. (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  198308. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  198309. row_info->channels == 4)
  198310. {
  198311. if (row_info->bit_depth == 8)
  198312. {
  198313. /* This converts from RGBX or RGBA to RGB */
  198314. if (flags & PNG_FLAG_FILLER_AFTER)
  198315. {
  198316. dp+=3; sp+=4;
  198317. for (i = 1; i < row_width; i++)
  198318. {
  198319. *dp++ = *sp++;
  198320. *dp++ = *sp++;
  198321. *dp++ = *sp++;
  198322. sp++;
  198323. }
  198324. }
  198325. /* This converts from XRGB or ARGB to RGB */
  198326. else
  198327. {
  198328. for (i = 0; i < row_width; i++)
  198329. {
  198330. sp++;
  198331. *dp++ = *sp++;
  198332. *dp++ = *sp++;
  198333. *dp++ = *sp++;
  198334. }
  198335. }
  198336. row_info->pixel_depth = 24;
  198337. row_info->rowbytes = row_width * 3;
  198338. }
  198339. else /* if (row_info->bit_depth == 16) */
  198340. {
  198341. if (flags & PNG_FLAG_FILLER_AFTER)
  198342. {
  198343. /* This converts from RRGGBBXX or RRGGBBAA to RRGGBB */
  198344. sp += 8; dp += 6;
  198345. for (i = 1; i < row_width; i++)
  198346. {
  198347. /* This could be (although png_memcpy is probably slower):
  198348. png_memcpy(dp, sp, 6);
  198349. sp += 8;
  198350. dp += 6;
  198351. */
  198352. *dp++ = *sp++;
  198353. *dp++ = *sp++;
  198354. *dp++ = *sp++;
  198355. *dp++ = *sp++;
  198356. *dp++ = *sp++;
  198357. *dp++ = *sp++;
  198358. sp += 2;
  198359. }
  198360. }
  198361. else
  198362. {
  198363. /* This converts from XXRRGGBB or AARRGGBB to RRGGBB */
  198364. for (i = 0; i < row_width; i++)
  198365. {
  198366. /* This could be (although png_memcpy is probably slower):
  198367. png_memcpy(dp, sp, 6);
  198368. sp += 8;
  198369. dp += 6;
  198370. */
  198371. sp+=2;
  198372. *dp++ = *sp++;
  198373. *dp++ = *sp++;
  198374. *dp++ = *sp++;
  198375. *dp++ = *sp++;
  198376. *dp++ = *sp++;
  198377. *dp++ = *sp++;
  198378. }
  198379. }
  198380. row_info->pixel_depth = 48;
  198381. row_info->rowbytes = row_width * 6;
  198382. }
  198383. row_info->channels = 3;
  198384. }
  198385. else if ((row_info->color_type == PNG_COLOR_TYPE_GRAY ||
  198386. (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  198387. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  198388. row_info->channels == 2)
  198389. {
  198390. if (row_info->bit_depth == 8)
  198391. {
  198392. /* This converts from GX or GA to G */
  198393. if (flags & PNG_FLAG_FILLER_AFTER)
  198394. {
  198395. for (i = 0; i < row_width; i++)
  198396. {
  198397. *dp++ = *sp++;
  198398. sp++;
  198399. }
  198400. }
  198401. /* This converts from XG or AG to G */
  198402. else
  198403. {
  198404. for (i = 0; i < row_width; i++)
  198405. {
  198406. sp++;
  198407. *dp++ = *sp++;
  198408. }
  198409. }
  198410. row_info->pixel_depth = 8;
  198411. row_info->rowbytes = row_width;
  198412. }
  198413. else /* if (row_info->bit_depth == 16) */
  198414. {
  198415. if (flags & PNG_FLAG_FILLER_AFTER)
  198416. {
  198417. /* This converts from GGXX or GGAA to GG */
  198418. sp += 4; dp += 2;
  198419. for (i = 1; i < row_width; i++)
  198420. {
  198421. *dp++ = *sp++;
  198422. *dp++ = *sp++;
  198423. sp += 2;
  198424. }
  198425. }
  198426. else
  198427. {
  198428. /* This converts from XXGG or AAGG to GG */
  198429. for (i = 0; i < row_width; i++)
  198430. {
  198431. sp += 2;
  198432. *dp++ = *sp++;
  198433. *dp++ = *sp++;
  198434. }
  198435. }
  198436. row_info->pixel_depth = 16;
  198437. row_info->rowbytes = row_width * 2;
  198438. }
  198439. row_info->channels = 1;
  198440. }
  198441. if (flags & PNG_FLAG_STRIP_ALPHA)
  198442. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  198443. }
  198444. }
  198445. #endif
  198446. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  198447. /* swaps red and blue bytes within a pixel */
  198448. void /* PRIVATE */
  198449. png_do_bgr(png_row_infop row_info, png_bytep row)
  198450. {
  198451. png_debug(1, "in png_do_bgr\n");
  198452. if (
  198453. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198454. row != NULL && row_info != NULL &&
  198455. #endif
  198456. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  198457. {
  198458. png_uint_32 row_width = row_info->width;
  198459. if (row_info->bit_depth == 8)
  198460. {
  198461. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  198462. {
  198463. png_bytep rp;
  198464. png_uint_32 i;
  198465. for (i = 0, rp = row; i < row_width; i++, rp += 3)
  198466. {
  198467. png_byte save = *rp;
  198468. *rp = *(rp + 2);
  198469. *(rp + 2) = save;
  198470. }
  198471. }
  198472. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  198473. {
  198474. png_bytep rp;
  198475. png_uint_32 i;
  198476. for (i = 0, rp = row; i < row_width; i++, rp += 4)
  198477. {
  198478. png_byte save = *rp;
  198479. *rp = *(rp + 2);
  198480. *(rp + 2) = save;
  198481. }
  198482. }
  198483. }
  198484. else if (row_info->bit_depth == 16)
  198485. {
  198486. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  198487. {
  198488. png_bytep rp;
  198489. png_uint_32 i;
  198490. for (i = 0, rp = row; i < row_width; i++, rp += 6)
  198491. {
  198492. png_byte save = *rp;
  198493. *rp = *(rp + 4);
  198494. *(rp + 4) = save;
  198495. save = *(rp + 1);
  198496. *(rp + 1) = *(rp + 5);
  198497. *(rp + 5) = save;
  198498. }
  198499. }
  198500. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  198501. {
  198502. png_bytep rp;
  198503. png_uint_32 i;
  198504. for (i = 0, rp = row; i < row_width; i++, rp += 8)
  198505. {
  198506. png_byte save = *rp;
  198507. *rp = *(rp + 4);
  198508. *(rp + 4) = save;
  198509. save = *(rp + 1);
  198510. *(rp + 1) = *(rp + 5);
  198511. *(rp + 5) = save;
  198512. }
  198513. }
  198514. }
  198515. }
  198516. }
  198517. #endif /* PNG_READ_BGR_SUPPORTED or PNG_WRITE_BGR_SUPPORTED */
  198518. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  198519. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  198520. defined(PNG_LEGACY_SUPPORTED)
  198521. void PNGAPI
  198522. png_set_user_transform_info(png_structp png_ptr, png_voidp
  198523. user_transform_ptr, int user_transform_depth, int user_transform_channels)
  198524. {
  198525. png_debug(1, "in png_set_user_transform_info\n");
  198526. if(png_ptr == NULL) return;
  198527. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  198528. png_ptr->user_transform_ptr = user_transform_ptr;
  198529. png_ptr->user_transform_depth = (png_byte)user_transform_depth;
  198530. png_ptr->user_transform_channels = (png_byte)user_transform_channels;
  198531. #else
  198532. if(user_transform_ptr || user_transform_depth || user_transform_channels)
  198533. png_warning(png_ptr,
  198534. "This version of libpng does not support user transform info");
  198535. #endif
  198536. }
  198537. #endif
  198538. /* This function returns a pointer to the user_transform_ptr associated with
  198539. * the user transform functions. The application should free any memory
  198540. * associated with this pointer before png_write_destroy and png_read_destroy
  198541. * are called.
  198542. */
  198543. png_voidp PNGAPI
  198544. png_get_user_transform_ptr(png_structp png_ptr)
  198545. {
  198546. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  198547. if (png_ptr == NULL) return (NULL);
  198548. return ((png_voidp)png_ptr->user_transform_ptr);
  198549. #else
  198550. return (NULL);
  198551. #endif
  198552. }
  198553. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  198554. /*** End of inlined file: pngtrans.c ***/
  198555. /*** Start of inlined file: pngwio.c ***/
  198556. /* pngwio.c - functions for data output
  198557. *
  198558. * Last changed in libpng 1.2.13 November 13, 2006
  198559. * For conditions of distribution and use, see copyright notice in png.h
  198560. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  198561. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  198562. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  198563. *
  198564. * This file provides a location for all output. Users who need
  198565. * special handling are expected to write functions that have the same
  198566. * arguments as these and perform similar functions, but that possibly
  198567. * use different output methods. Note that you shouldn't change these
  198568. * functions, but rather write replacement functions and then change
  198569. * them at run time with png_set_write_fn(...).
  198570. */
  198571. #define PNG_INTERNAL
  198572. #ifdef PNG_WRITE_SUPPORTED
  198573. /* Write the data to whatever output you are using. The default routine
  198574. writes to a file pointer. Note that this routine sometimes gets called
  198575. with very small lengths, so you should implement some kind of simple
  198576. buffering if you are using unbuffered writes. This should never be asked
  198577. to write more than 64K on a 16 bit machine. */
  198578. void /* PRIVATE */
  198579. png_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198580. {
  198581. if (png_ptr->write_data_fn != NULL )
  198582. (*(png_ptr->write_data_fn))(png_ptr, data, length);
  198583. else
  198584. png_error(png_ptr, "Call to NULL write function");
  198585. }
  198586. #if !defined(PNG_NO_STDIO)
  198587. /* This is the function that does the actual writing of data. If you are
  198588. not writing to a standard C stream, you should create a replacement
  198589. write_data function and use it at run time with png_set_write_fn(), rather
  198590. than changing the library. */
  198591. #ifndef USE_FAR_KEYWORD
  198592. void PNGAPI
  198593. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198594. {
  198595. png_uint_32 check;
  198596. if(png_ptr == NULL) return;
  198597. #if defined(_WIN32_WCE)
  198598. if ( !WriteFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  198599. check = 0;
  198600. #else
  198601. check = fwrite(data, 1, length, (png_FILE_p)(png_ptr->io_ptr));
  198602. #endif
  198603. if (check != length)
  198604. png_error(png_ptr, "Write Error");
  198605. }
  198606. #else
  198607. /* this is the model-independent version. Since the standard I/O library
  198608. can't handle far buffers in the medium and small models, we have to copy
  198609. the data.
  198610. */
  198611. #define NEAR_BUF_SIZE 1024
  198612. #define MIN(a,b) (a <= b ? a : b)
  198613. void PNGAPI
  198614. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198615. {
  198616. png_uint_32 check;
  198617. png_byte *near_data; /* Needs to be "png_byte *" instead of "png_bytep" */
  198618. png_FILE_p io_ptr;
  198619. if(png_ptr == NULL) return;
  198620. /* Check if data really is near. If so, use usual code. */
  198621. near_data = (png_byte *)CVT_PTR_NOCHECK(data);
  198622. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  198623. if ((png_bytep)near_data == data)
  198624. {
  198625. #if defined(_WIN32_WCE)
  198626. if ( !WriteFile(io_ptr, near_data, length, &check, NULL) )
  198627. check = 0;
  198628. #else
  198629. check = fwrite(near_data, 1, length, io_ptr);
  198630. #endif
  198631. }
  198632. else
  198633. {
  198634. png_byte buf[NEAR_BUF_SIZE];
  198635. png_size_t written, remaining, err;
  198636. check = 0;
  198637. remaining = length;
  198638. do
  198639. {
  198640. written = MIN(NEAR_BUF_SIZE, remaining);
  198641. png_memcpy(buf, data, written); /* copy far buffer to near buffer */
  198642. #if defined(_WIN32_WCE)
  198643. if ( !WriteFile(io_ptr, buf, written, &err, NULL) )
  198644. err = 0;
  198645. #else
  198646. err = fwrite(buf, 1, written, io_ptr);
  198647. #endif
  198648. if (err != written)
  198649. break;
  198650. else
  198651. check += err;
  198652. data += written;
  198653. remaining -= written;
  198654. }
  198655. while (remaining != 0);
  198656. }
  198657. if (check != length)
  198658. png_error(png_ptr, "Write Error");
  198659. }
  198660. #endif
  198661. #endif
  198662. /* This function is called to output any data pending writing (normally
  198663. to disk). After png_flush is called, there should be no data pending
  198664. writing in any buffers. */
  198665. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198666. void /* PRIVATE */
  198667. png_flush(png_structp png_ptr)
  198668. {
  198669. if (png_ptr->output_flush_fn != NULL)
  198670. (*(png_ptr->output_flush_fn))(png_ptr);
  198671. }
  198672. #if !defined(PNG_NO_STDIO)
  198673. void PNGAPI
  198674. png_default_flush(png_structp png_ptr)
  198675. {
  198676. #if !defined(_WIN32_WCE)
  198677. png_FILE_p io_ptr;
  198678. #endif
  198679. if(png_ptr == NULL) return;
  198680. #if !defined(_WIN32_WCE)
  198681. io_ptr = (png_FILE_p)CVT_PTR((png_ptr->io_ptr));
  198682. if (io_ptr != NULL)
  198683. fflush(io_ptr);
  198684. #endif
  198685. }
  198686. #endif
  198687. #endif
  198688. /* This function allows the application to supply new output functions for
  198689. libpng if standard C streams aren't being used.
  198690. This function takes as its arguments:
  198691. png_ptr - pointer to a png output data structure
  198692. io_ptr - pointer to user supplied structure containing info about
  198693. the output functions. May be NULL.
  198694. write_data_fn - pointer to a new output function that takes as its
  198695. arguments a pointer to a png_struct, a pointer to
  198696. data to be written, and a 32-bit unsigned int that is
  198697. the number of bytes to be written. The new write
  198698. function should call png_error(png_ptr, "Error msg")
  198699. to exit and output any fatal error messages.
  198700. flush_data_fn - pointer to a new flush function that takes as its
  198701. arguments a pointer to a png_struct. After a call to
  198702. the flush function, there should be no data in any buffers
  198703. or pending transmission. If the output method doesn't do
  198704. any buffering of ouput, a function prototype must still be
  198705. supplied although it doesn't have to do anything. If
  198706. PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile
  198707. time, output_flush_fn will be ignored, although it must be
  198708. supplied for compatibility. */
  198709. void PNGAPI
  198710. png_set_write_fn(png_structp png_ptr, png_voidp io_ptr,
  198711. png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn)
  198712. {
  198713. if(png_ptr == NULL) return;
  198714. png_ptr->io_ptr = io_ptr;
  198715. #if !defined(PNG_NO_STDIO)
  198716. if (write_data_fn != NULL)
  198717. png_ptr->write_data_fn = write_data_fn;
  198718. else
  198719. png_ptr->write_data_fn = png_default_write_data;
  198720. #else
  198721. png_ptr->write_data_fn = write_data_fn;
  198722. #endif
  198723. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198724. #if !defined(PNG_NO_STDIO)
  198725. if (output_flush_fn != NULL)
  198726. png_ptr->output_flush_fn = output_flush_fn;
  198727. else
  198728. png_ptr->output_flush_fn = png_default_flush;
  198729. #else
  198730. png_ptr->output_flush_fn = output_flush_fn;
  198731. #endif
  198732. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  198733. /* It is an error to read while writing a png file */
  198734. if (png_ptr->read_data_fn != NULL)
  198735. {
  198736. png_ptr->read_data_fn = NULL;
  198737. png_warning(png_ptr,
  198738. "Attempted to set both read_data_fn and write_data_fn in");
  198739. png_warning(png_ptr,
  198740. "the same structure. Resetting read_data_fn to NULL.");
  198741. }
  198742. }
  198743. #if defined(USE_FAR_KEYWORD)
  198744. #if defined(_MSC_VER)
  198745. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  198746. {
  198747. void *near_ptr;
  198748. void FAR *far_ptr;
  198749. FP_OFF(near_ptr) = FP_OFF(ptr);
  198750. far_ptr = (void FAR *)near_ptr;
  198751. if(check != 0)
  198752. if(FP_SEG(ptr) != FP_SEG(far_ptr))
  198753. png_error(png_ptr,"segment lost in conversion");
  198754. return(near_ptr);
  198755. }
  198756. # else
  198757. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  198758. {
  198759. void *near_ptr;
  198760. void FAR *far_ptr;
  198761. near_ptr = (void FAR *)ptr;
  198762. far_ptr = (void FAR *)near_ptr;
  198763. if(check != 0)
  198764. if(far_ptr != ptr)
  198765. png_error(png_ptr,"segment lost in conversion");
  198766. return(near_ptr);
  198767. }
  198768. # endif
  198769. # endif
  198770. #endif /* PNG_WRITE_SUPPORTED */
  198771. /*** End of inlined file: pngwio.c ***/
  198772. /*** Start of inlined file: pngwrite.c ***/
  198773. /* pngwrite.c - general routines to write a PNG file
  198774. *
  198775. * Last changed in libpng 1.2.15 January 5, 2007
  198776. * For conditions of distribution and use, see copyright notice in png.h
  198777. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  198778. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  198779. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  198780. */
  198781. /* get internal access to png.h */
  198782. #define PNG_INTERNAL
  198783. #ifdef PNG_WRITE_SUPPORTED
  198784. /* Writes all the PNG information. This is the suggested way to use the
  198785. * library. If you have a new chunk to add, make a function to write it,
  198786. * and put it in the correct location here. If you want the chunk written
  198787. * after the image data, put it in png_write_end(). I strongly encourage
  198788. * you to supply a PNG_INFO_ flag, and check info_ptr->valid before writing
  198789. * the chunk, as that will keep the code from breaking if you want to just
  198790. * write a plain PNG file. If you have long comments, I suggest writing
  198791. * them in png_write_end(), and compressing them.
  198792. */
  198793. void PNGAPI
  198794. png_write_info_before_PLTE(png_structp png_ptr, png_infop info_ptr)
  198795. {
  198796. png_debug(1, "in png_write_info_before_PLTE\n");
  198797. if (png_ptr == NULL || info_ptr == NULL)
  198798. return;
  198799. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  198800. {
  198801. png_write_sig(png_ptr); /* write PNG signature */
  198802. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  198803. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&(png_ptr->mng_features_permitted))
  198804. {
  198805. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  198806. png_ptr->mng_features_permitted=0;
  198807. }
  198808. #endif
  198809. /* write IHDR information. */
  198810. png_write_IHDR(png_ptr, info_ptr->width, info_ptr->height,
  198811. info_ptr->bit_depth, info_ptr->color_type, info_ptr->compression_type,
  198812. info_ptr->filter_type,
  198813. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  198814. info_ptr->interlace_type);
  198815. #else
  198816. 0);
  198817. #endif
  198818. /* the rest of these check to see if the valid field has the appropriate
  198819. flag set, and if it does, writes the chunk. */
  198820. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  198821. if (info_ptr->valid & PNG_INFO_gAMA)
  198822. {
  198823. # ifdef PNG_FLOATING_POINT_SUPPORTED
  198824. png_write_gAMA(png_ptr, info_ptr->gamma);
  198825. #else
  198826. #ifdef PNG_FIXED_POINT_SUPPORTED
  198827. png_write_gAMA_fixed(png_ptr, info_ptr->int_gamma);
  198828. # endif
  198829. #endif
  198830. }
  198831. #endif
  198832. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  198833. if (info_ptr->valid & PNG_INFO_sRGB)
  198834. png_write_sRGB(png_ptr, (int)info_ptr->srgb_intent);
  198835. #endif
  198836. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  198837. if (info_ptr->valid & PNG_INFO_iCCP)
  198838. png_write_iCCP(png_ptr, info_ptr->iccp_name, PNG_COMPRESSION_TYPE_BASE,
  198839. info_ptr->iccp_profile, (int)info_ptr->iccp_proflen);
  198840. #endif
  198841. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  198842. if (info_ptr->valid & PNG_INFO_sBIT)
  198843. png_write_sBIT(png_ptr, &(info_ptr->sig_bit), info_ptr->color_type);
  198844. #endif
  198845. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  198846. if (info_ptr->valid & PNG_INFO_cHRM)
  198847. {
  198848. #ifdef PNG_FLOATING_POINT_SUPPORTED
  198849. png_write_cHRM(png_ptr,
  198850. info_ptr->x_white, info_ptr->y_white,
  198851. info_ptr->x_red, info_ptr->y_red,
  198852. info_ptr->x_green, info_ptr->y_green,
  198853. info_ptr->x_blue, info_ptr->y_blue);
  198854. #else
  198855. # ifdef PNG_FIXED_POINT_SUPPORTED
  198856. png_write_cHRM_fixed(png_ptr,
  198857. info_ptr->int_x_white, info_ptr->int_y_white,
  198858. info_ptr->int_x_red, info_ptr->int_y_red,
  198859. info_ptr->int_x_green, info_ptr->int_y_green,
  198860. info_ptr->int_x_blue, info_ptr->int_y_blue);
  198861. # endif
  198862. #endif
  198863. }
  198864. #endif
  198865. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  198866. if (info_ptr->unknown_chunks_num)
  198867. {
  198868. png_unknown_chunk *up;
  198869. png_debug(5, "writing extra chunks\n");
  198870. for (up = info_ptr->unknown_chunks;
  198871. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  198872. up++)
  198873. {
  198874. int keep=png_handle_as_unknown(png_ptr, up->name);
  198875. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  198876. up->location && !(up->location & PNG_HAVE_PLTE) &&
  198877. !(up->location & PNG_HAVE_IDAT) &&
  198878. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  198879. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  198880. {
  198881. png_write_chunk(png_ptr, up->name, up->data, up->size);
  198882. }
  198883. }
  198884. }
  198885. #endif
  198886. png_ptr->mode |= PNG_WROTE_INFO_BEFORE_PLTE;
  198887. }
  198888. }
  198889. void PNGAPI
  198890. png_write_info(png_structp png_ptr, png_infop info_ptr)
  198891. {
  198892. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  198893. int i;
  198894. #endif
  198895. png_debug(1, "in png_write_info\n");
  198896. if (png_ptr == NULL || info_ptr == NULL)
  198897. return;
  198898. png_write_info_before_PLTE(png_ptr, info_ptr);
  198899. if (info_ptr->valid & PNG_INFO_PLTE)
  198900. png_write_PLTE(png_ptr, info_ptr->palette,
  198901. (png_uint_32)info_ptr->num_palette);
  198902. else if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  198903. png_error(png_ptr, "Valid palette required for paletted images");
  198904. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  198905. if (info_ptr->valid & PNG_INFO_tRNS)
  198906. {
  198907. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  198908. /* invert the alpha channel (in tRNS) */
  198909. if ((png_ptr->transformations & PNG_INVERT_ALPHA) &&
  198910. info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  198911. {
  198912. int j;
  198913. for (j=0; j<(int)info_ptr->num_trans; j++)
  198914. info_ptr->trans[j] = (png_byte)(255 - info_ptr->trans[j]);
  198915. }
  198916. #endif
  198917. png_write_tRNS(png_ptr, info_ptr->trans, &(info_ptr->trans_values),
  198918. info_ptr->num_trans, info_ptr->color_type);
  198919. }
  198920. #endif
  198921. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  198922. if (info_ptr->valid & PNG_INFO_bKGD)
  198923. png_write_bKGD(png_ptr, &(info_ptr->background), info_ptr->color_type);
  198924. #endif
  198925. #if defined(PNG_WRITE_hIST_SUPPORTED)
  198926. if (info_ptr->valid & PNG_INFO_hIST)
  198927. png_write_hIST(png_ptr, info_ptr->hist, info_ptr->num_palette);
  198928. #endif
  198929. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  198930. if (info_ptr->valid & PNG_INFO_oFFs)
  198931. png_write_oFFs(png_ptr, info_ptr->x_offset, info_ptr->y_offset,
  198932. info_ptr->offset_unit_type);
  198933. #endif
  198934. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  198935. if (info_ptr->valid & PNG_INFO_pCAL)
  198936. png_write_pCAL(png_ptr, info_ptr->pcal_purpose, info_ptr->pcal_X0,
  198937. info_ptr->pcal_X1, info_ptr->pcal_type, info_ptr->pcal_nparams,
  198938. info_ptr->pcal_units, info_ptr->pcal_params);
  198939. #endif
  198940. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  198941. if (info_ptr->valid & PNG_INFO_sCAL)
  198942. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  198943. png_write_sCAL(png_ptr, (int)info_ptr->scal_unit,
  198944. info_ptr->scal_pixel_width, info_ptr->scal_pixel_height);
  198945. #else
  198946. #ifdef PNG_FIXED_POINT_SUPPORTED
  198947. png_write_sCAL_s(png_ptr, (int)info_ptr->scal_unit,
  198948. info_ptr->scal_s_width, info_ptr->scal_s_height);
  198949. #else
  198950. png_warning(png_ptr,
  198951. "png_write_sCAL not supported; sCAL chunk not written.");
  198952. #endif
  198953. #endif
  198954. #endif
  198955. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  198956. if (info_ptr->valid & PNG_INFO_pHYs)
  198957. png_write_pHYs(png_ptr, info_ptr->x_pixels_per_unit,
  198958. info_ptr->y_pixels_per_unit, info_ptr->phys_unit_type);
  198959. #endif
  198960. #if defined(PNG_WRITE_tIME_SUPPORTED)
  198961. if (info_ptr->valid & PNG_INFO_tIME)
  198962. {
  198963. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  198964. png_ptr->mode |= PNG_WROTE_tIME;
  198965. }
  198966. #endif
  198967. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  198968. if (info_ptr->valid & PNG_INFO_sPLT)
  198969. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  198970. png_write_sPLT(png_ptr, info_ptr->splt_palettes + i);
  198971. #endif
  198972. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  198973. /* Check to see if we need to write text chunks */
  198974. for (i = 0; i < info_ptr->num_text; i++)
  198975. {
  198976. png_debug2(2, "Writing header text chunk %d, type %d\n", i,
  198977. info_ptr->text[i].compression);
  198978. /* an internationalized chunk? */
  198979. if (info_ptr->text[i].compression > 0)
  198980. {
  198981. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  198982. /* write international chunk */
  198983. png_write_iTXt(png_ptr,
  198984. info_ptr->text[i].compression,
  198985. info_ptr->text[i].key,
  198986. info_ptr->text[i].lang,
  198987. info_ptr->text[i].lang_key,
  198988. info_ptr->text[i].text);
  198989. #else
  198990. png_warning(png_ptr, "Unable to write international text");
  198991. #endif
  198992. /* Mark this chunk as written */
  198993. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198994. }
  198995. /* If we want a compressed text chunk */
  198996. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_zTXt)
  198997. {
  198998. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  198999. /* write compressed chunk */
  199000. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  199001. info_ptr->text[i].text, 0,
  199002. info_ptr->text[i].compression);
  199003. #else
  199004. png_warning(png_ptr, "Unable to write compressed text");
  199005. #endif
  199006. /* Mark this chunk as written */
  199007. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  199008. }
  199009. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  199010. {
  199011. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  199012. /* write uncompressed chunk */
  199013. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  199014. info_ptr->text[i].text,
  199015. 0);
  199016. #else
  199017. png_warning(png_ptr, "Unable to write uncompressed text");
  199018. #endif
  199019. /* Mark this chunk as written */
  199020. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  199021. }
  199022. }
  199023. #endif
  199024. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  199025. if (info_ptr->unknown_chunks_num)
  199026. {
  199027. png_unknown_chunk *up;
  199028. png_debug(5, "writing extra chunks\n");
  199029. for (up = info_ptr->unknown_chunks;
  199030. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  199031. up++)
  199032. {
  199033. int keep=png_handle_as_unknown(png_ptr, up->name);
  199034. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  199035. up->location && (up->location & PNG_HAVE_PLTE) &&
  199036. !(up->location & PNG_HAVE_IDAT) &&
  199037. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  199038. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  199039. {
  199040. png_write_chunk(png_ptr, up->name, up->data, up->size);
  199041. }
  199042. }
  199043. }
  199044. #endif
  199045. }
  199046. /* Writes the end of the PNG file. If you don't want to write comments or
  199047. * time information, you can pass NULL for info. If you already wrote these
  199048. * in png_write_info(), do not write them again here. If you have long
  199049. * comments, I suggest writing them here, and compressing them.
  199050. */
  199051. void PNGAPI
  199052. png_write_end(png_structp png_ptr, png_infop info_ptr)
  199053. {
  199054. png_debug(1, "in png_write_end\n");
  199055. if (png_ptr == NULL)
  199056. return;
  199057. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  199058. png_error(png_ptr, "No IDATs written into file");
  199059. /* see if user wants us to write information chunks */
  199060. if (info_ptr != NULL)
  199061. {
  199062. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  199063. int i; /* local index variable */
  199064. #endif
  199065. #if defined(PNG_WRITE_tIME_SUPPORTED)
  199066. /* check to see if user has supplied a time chunk */
  199067. if ((info_ptr->valid & PNG_INFO_tIME) &&
  199068. !(png_ptr->mode & PNG_WROTE_tIME))
  199069. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  199070. #endif
  199071. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  199072. /* loop through comment chunks */
  199073. for (i = 0; i < info_ptr->num_text; i++)
  199074. {
  199075. png_debug2(2, "Writing trailer text chunk %d, type %d\n", i,
  199076. info_ptr->text[i].compression);
  199077. /* an internationalized chunk? */
  199078. if (info_ptr->text[i].compression > 0)
  199079. {
  199080. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  199081. /* write international chunk */
  199082. png_write_iTXt(png_ptr,
  199083. info_ptr->text[i].compression,
  199084. info_ptr->text[i].key,
  199085. info_ptr->text[i].lang,
  199086. info_ptr->text[i].lang_key,
  199087. info_ptr->text[i].text);
  199088. #else
  199089. png_warning(png_ptr, "Unable to write international text");
  199090. #endif
  199091. /* Mark this chunk as written */
  199092. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  199093. }
  199094. else if (info_ptr->text[i].compression >= PNG_TEXT_COMPRESSION_zTXt)
  199095. {
  199096. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  199097. /* write compressed chunk */
  199098. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  199099. info_ptr->text[i].text, 0,
  199100. info_ptr->text[i].compression);
  199101. #else
  199102. png_warning(png_ptr, "Unable to write compressed text");
  199103. #endif
  199104. /* Mark this chunk as written */
  199105. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  199106. }
  199107. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  199108. {
  199109. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  199110. /* write uncompressed chunk */
  199111. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  199112. info_ptr->text[i].text, 0);
  199113. #else
  199114. png_warning(png_ptr, "Unable to write uncompressed text");
  199115. #endif
  199116. /* Mark this chunk as written */
  199117. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  199118. }
  199119. }
  199120. #endif
  199121. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  199122. if (info_ptr->unknown_chunks_num)
  199123. {
  199124. png_unknown_chunk *up;
  199125. png_debug(5, "writing extra chunks\n");
  199126. for (up = info_ptr->unknown_chunks;
  199127. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  199128. up++)
  199129. {
  199130. int keep=png_handle_as_unknown(png_ptr, up->name);
  199131. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  199132. up->location && (up->location & PNG_AFTER_IDAT) &&
  199133. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  199134. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  199135. {
  199136. png_write_chunk(png_ptr, up->name, up->data, up->size);
  199137. }
  199138. }
  199139. }
  199140. #endif
  199141. }
  199142. png_ptr->mode |= PNG_AFTER_IDAT;
  199143. /* write end of PNG file */
  199144. png_write_IEND(png_ptr);
  199145. }
  199146. #if defined(PNG_WRITE_tIME_SUPPORTED)
  199147. #if !defined(_WIN32_WCE)
  199148. /* "time.h" functions are not supported on WindowsCE */
  199149. void PNGAPI
  199150. png_convert_from_struct_tm(png_timep ptime, struct tm FAR * ttime)
  199151. {
  199152. png_debug(1, "in png_convert_from_struct_tm\n");
  199153. ptime->year = (png_uint_16)(1900 + ttime->tm_year);
  199154. ptime->month = (png_byte)(ttime->tm_mon + 1);
  199155. ptime->day = (png_byte)ttime->tm_mday;
  199156. ptime->hour = (png_byte)ttime->tm_hour;
  199157. ptime->minute = (png_byte)ttime->tm_min;
  199158. ptime->second = (png_byte)ttime->tm_sec;
  199159. }
  199160. void PNGAPI
  199161. png_convert_from_time_t(png_timep ptime, time_t ttime)
  199162. {
  199163. struct tm *tbuf;
  199164. png_debug(1, "in png_convert_from_time_t\n");
  199165. tbuf = gmtime(&ttime);
  199166. png_convert_from_struct_tm(ptime, tbuf);
  199167. }
  199168. #endif
  199169. #endif
  199170. /* Initialize png_ptr structure, and allocate any memory needed */
  199171. png_structp PNGAPI
  199172. png_create_write_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  199173. png_error_ptr error_fn, png_error_ptr warn_fn)
  199174. {
  199175. #ifdef PNG_USER_MEM_SUPPORTED
  199176. return (png_create_write_struct_2(user_png_ver, error_ptr, error_fn,
  199177. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  199178. }
  199179. /* Alternate initialize png_ptr structure, and allocate any memory needed */
  199180. png_structp PNGAPI
  199181. png_create_write_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  199182. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  199183. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  199184. {
  199185. #endif /* PNG_USER_MEM_SUPPORTED */
  199186. png_structp png_ptr;
  199187. #ifdef PNG_SETJMP_SUPPORTED
  199188. #ifdef USE_FAR_KEYWORD
  199189. jmp_buf jmpbuf;
  199190. #endif
  199191. #endif
  199192. int i;
  199193. png_debug(1, "in png_create_write_struct\n");
  199194. #ifdef PNG_USER_MEM_SUPPORTED
  199195. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  199196. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  199197. #else
  199198. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  199199. #endif /* PNG_USER_MEM_SUPPORTED */
  199200. if (png_ptr == NULL)
  199201. return (NULL);
  199202. /* added at libpng-1.2.6 */
  199203. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  199204. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  199205. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  199206. #endif
  199207. #ifdef PNG_SETJMP_SUPPORTED
  199208. #ifdef USE_FAR_KEYWORD
  199209. if (setjmp(jmpbuf))
  199210. #else
  199211. if (setjmp(png_ptr->jmpbuf))
  199212. #endif
  199213. {
  199214. png_free(png_ptr, png_ptr->zbuf);
  199215. png_ptr->zbuf=NULL;
  199216. png_destroy_struct(png_ptr);
  199217. return (NULL);
  199218. }
  199219. #ifdef USE_FAR_KEYWORD
  199220. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  199221. #endif
  199222. #endif
  199223. #ifdef PNG_USER_MEM_SUPPORTED
  199224. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  199225. #endif /* PNG_USER_MEM_SUPPORTED */
  199226. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  199227. i=0;
  199228. do
  199229. {
  199230. if(user_png_ver[i] != png_libpng_ver[i])
  199231. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  199232. } while (png_libpng_ver[i++]);
  199233. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  199234. {
  199235. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  199236. * we must recompile any applications that use any older library version.
  199237. * For versions after libpng 1.0, we will be compatible, so we need
  199238. * only check the first digit.
  199239. */
  199240. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  199241. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  199242. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  199243. {
  199244. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  199245. char msg[80];
  199246. if (user_png_ver)
  199247. {
  199248. png_snprintf(msg, 80,
  199249. "Application was compiled with png.h from libpng-%.20s",
  199250. user_png_ver);
  199251. png_warning(png_ptr, msg);
  199252. }
  199253. png_snprintf(msg, 80,
  199254. "Application is running with png.c from libpng-%.20s",
  199255. png_libpng_ver);
  199256. png_warning(png_ptr, msg);
  199257. #endif
  199258. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  199259. png_ptr->flags=0;
  199260. #endif
  199261. png_error(png_ptr,
  199262. "Incompatible libpng version in application and library");
  199263. }
  199264. }
  199265. /* initialize zbuf - compression buffer */
  199266. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  199267. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  199268. (png_uint_32)png_ptr->zbuf_size);
  199269. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  199270. png_flush_ptr_NULL);
  199271. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199272. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  199273. 1, png_doublep_NULL, png_doublep_NULL);
  199274. #endif
  199275. #ifdef PNG_SETJMP_SUPPORTED
  199276. /* Applications that neglect to set up their own setjmp() and then encounter
  199277. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  199278. abort instead of returning. */
  199279. #ifdef USE_FAR_KEYWORD
  199280. if (setjmp(jmpbuf))
  199281. PNG_ABORT();
  199282. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  199283. #else
  199284. if (setjmp(png_ptr->jmpbuf))
  199285. PNG_ABORT();
  199286. #endif
  199287. #endif
  199288. return (png_ptr);
  199289. }
  199290. /* Initialize png_ptr structure, and allocate any memory needed */
  199291. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  199292. /* Deprecated. */
  199293. #undef png_write_init
  199294. void PNGAPI
  199295. png_write_init(png_structp png_ptr)
  199296. {
  199297. /* We only come here via pre-1.0.7-compiled applications */
  199298. png_write_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  199299. }
  199300. void PNGAPI
  199301. png_write_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  199302. png_size_t png_struct_size, png_size_t png_info_size)
  199303. {
  199304. /* We only come here via pre-1.0.12-compiled applications */
  199305. if(png_ptr == NULL) return;
  199306. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  199307. if(png_sizeof(png_struct) > png_struct_size ||
  199308. png_sizeof(png_info) > png_info_size)
  199309. {
  199310. char msg[80];
  199311. png_ptr->warning_fn=NULL;
  199312. if (user_png_ver)
  199313. {
  199314. png_snprintf(msg, 80,
  199315. "Application was compiled with png.h from libpng-%.20s",
  199316. user_png_ver);
  199317. png_warning(png_ptr, msg);
  199318. }
  199319. png_snprintf(msg, 80,
  199320. "Application is running with png.c from libpng-%.20s",
  199321. png_libpng_ver);
  199322. png_warning(png_ptr, msg);
  199323. }
  199324. #endif
  199325. if(png_sizeof(png_struct) > png_struct_size)
  199326. {
  199327. png_ptr->error_fn=NULL;
  199328. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  199329. png_ptr->flags=0;
  199330. #endif
  199331. png_error(png_ptr,
  199332. "The png struct allocated by the application for writing is too small.");
  199333. }
  199334. if(png_sizeof(png_info) > png_info_size)
  199335. {
  199336. png_ptr->error_fn=NULL;
  199337. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  199338. png_ptr->flags=0;
  199339. #endif
  199340. png_error(png_ptr,
  199341. "The info struct allocated by the application for writing is too small.");
  199342. }
  199343. png_write_init_3(&png_ptr, user_png_ver, png_struct_size);
  199344. }
  199345. #endif /* PNG_1_0_X || PNG_1_2_X */
  199346. void PNGAPI
  199347. png_write_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  199348. png_size_t png_struct_size)
  199349. {
  199350. png_structp png_ptr=*ptr_ptr;
  199351. #ifdef PNG_SETJMP_SUPPORTED
  199352. jmp_buf tmp_jmp; /* to save current jump buffer */
  199353. #endif
  199354. int i = 0;
  199355. if (png_ptr == NULL)
  199356. return;
  199357. do
  199358. {
  199359. if (user_png_ver[i] != png_libpng_ver[i])
  199360. {
  199361. #ifdef PNG_LEGACY_SUPPORTED
  199362. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  199363. #else
  199364. png_ptr->warning_fn=NULL;
  199365. png_warning(png_ptr,
  199366. "Application uses deprecated png_write_init() and should be recompiled.");
  199367. break;
  199368. #endif
  199369. }
  199370. } while (png_libpng_ver[i++]);
  199371. png_debug(1, "in png_write_init_3\n");
  199372. #ifdef PNG_SETJMP_SUPPORTED
  199373. /* save jump buffer and error functions */
  199374. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  199375. #endif
  199376. if (png_sizeof(png_struct) > png_struct_size)
  199377. {
  199378. png_destroy_struct(png_ptr);
  199379. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  199380. *ptr_ptr = png_ptr;
  199381. }
  199382. /* reset all variables to 0 */
  199383. png_memset(png_ptr, 0, png_sizeof (png_struct));
  199384. /* added at libpng-1.2.6 */
  199385. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  199386. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  199387. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  199388. #endif
  199389. #ifdef PNG_SETJMP_SUPPORTED
  199390. /* restore jump buffer */
  199391. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  199392. #endif
  199393. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  199394. png_flush_ptr_NULL);
  199395. /* initialize zbuf - compression buffer */
  199396. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  199397. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  199398. (png_uint_32)png_ptr->zbuf_size);
  199399. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199400. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  199401. 1, png_doublep_NULL, png_doublep_NULL);
  199402. #endif
  199403. }
  199404. /* Write a few rows of image data. If the image is interlaced,
  199405. * either you will have to write the 7 sub images, or, if you
  199406. * have called png_set_interlace_handling(), you will have to
  199407. * "write" the image seven times.
  199408. */
  199409. void PNGAPI
  199410. png_write_rows(png_structp png_ptr, png_bytepp row,
  199411. png_uint_32 num_rows)
  199412. {
  199413. png_uint_32 i; /* row counter */
  199414. png_bytepp rp; /* row pointer */
  199415. png_debug(1, "in png_write_rows\n");
  199416. if (png_ptr == NULL)
  199417. return;
  199418. /* loop through the rows */
  199419. for (i = 0, rp = row; i < num_rows; i++, rp++)
  199420. {
  199421. png_write_row(png_ptr, *rp);
  199422. }
  199423. }
  199424. /* Write the image. You only need to call this function once, even
  199425. * if you are writing an interlaced image.
  199426. */
  199427. void PNGAPI
  199428. png_write_image(png_structp png_ptr, png_bytepp image)
  199429. {
  199430. png_uint_32 i; /* row index */
  199431. int pass, num_pass; /* pass variables */
  199432. png_bytepp rp; /* points to current row */
  199433. if (png_ptr == NULL)
  199434. return;
  199435. png_debug(1, "in png_write_image\n");
  199436. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199437. /* intialize interlace handling. If image is not interlaced,
  199438. this will set pass to 1 */
  199439. num_pass = png_set_interlace_handling(png_ptr);
  199440. #else
  199441. num_pass = 1;
  199442. #endif
  199443. /* loop through passes */
  199444. for (pass = 0; pass < num_pass; pass++)
  199445. {
  199446. /* loop through image */
  199447. for (i = 0, rp = image; i < png_ptr->height; i++, rp++)
  199448. {
  199449. png_write_row(png_ptr, *rp);
  199450. }
  199451. }
  199452. }
  199453. /* called by user to write a row of image data */
  199454. void PNGAPI
  199455. png_write_row(png_structp png_ptr, png_bytep row)
  199456. {
  199457. if (png_ptr == NULL)
  199458. return;
  199459. png_debug2(1, "in png_write_row (row %ld, pass %d)\n",
  199460. png_ptr->row_number, png_ptr->pass);
  199461. /* initialize transformations and other stuff if first time */
  199462. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  199463. {
  199464. /* make sure we wrote the header info */
  199465. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  199466. png_error(png_ptr,
  199467. "png_write_info was never called before png_write_row.");
  199468. /* check for transforms that have been set but were defined out */
  199469. #if !defined(PNG_WRITE_INVERT_SUPPORTED) && defined(PNG_READ_INVERT_SUPPORTED)
  199470. if (png_ptr->transformations & PNG_INVERT_MONO)
  199471. png_warning(png_ptr, "PNG_WRITE_INVERT_SUPPORTED is not defined.");
  199472. #endif
  199473. #if !defined(PNG_WRITE_FILLER_SUPPORTED) && defined(PNG_READ_FILLER_SUPPORTED)
  199474. if (png_ptr->transformations & PNG_FILLER)
  199475. png_warning(png_ptr, "PNG_WRITE_FILLER_SUPPORTED is not defined.");
  199476. #endif
  199477. #if !defined(PNG_WRITE_PACKSWAP_SUPPORTED) && defined(PNG_READ_PACKSWAP_SUPPORTED)
  199478. if (png_ptr->transformations & PNG_PACKSWAP)
  199479. png_warning(png_ptr, "PNG_WRITE_PACKSWAP_SUPPORTED is not defined.");
  199480. #endif
  199481. #if !defined(PNG_WRITE_PACK_SUPPORTED) && defined(PNG_READ_PACK_SUPPORTED)
  199482. if (png_ptr->transformations & PNG_PACK)
  199483. png_warning(png_ptr, "PNG_WRITE_PACK_SUPPORTED is not defined.");
  199484. #endif
  199485. #if !defined(PNG_WRITE_SHIFT_SUPPORTED) && defined(PNG_READ_SHIFT_SUPPORTED)
  199486. if (png_ptr->transformations & PNG_SHIFT)
  199487. png_warning(png_ptr, "PNG_WRITE_SHIFT_SUPPORTED is not defined.");
  199488. #endif
  199489. #if !defined(PNG_WRITE_BGR_SUPPORTED) && defined(PNG_READ_BGR_SUPPORTED)
  199490. if (png_ptr->transformations & PNG_BGR)
  199491. png_warning(png_ptr, "PNG_WRITE_BGR_SUPPORTED is not defined.");
  199492. #endif
  199493. #if !defined(PNG_WRITE_SWAP_SUPPORTED) && defined(PNG_READ_SWAP_SUPPORTED)
  199494. if (png_ptr->transformations & PNG_SWAP_BYTES)
  199495. png_warning(png_ptr, "PNG_WRITE_SWAP_SUPPORTED is not defined.");
  199496. #endif
  199497. png_write_start_row(png_ptr);
  199498. }
  199499. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199500. /* if interlaced and not interested in row, return */
  199501. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  199502. {
  199503. switch (png_ptr->pass)
  199504. {
  199505. case 0:
  199506. if (png_ptr->row_number & 0x07)
  199507. {
  199508. png_write_finish_row(png_ptr);
  199509. return;
  199510. }
  199511. break;
  199512. case 1:
  199513. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  199514. {
  199515. png_write_finish_row(png_ptr);
  199516. return;
  199517. }
  199518. break;
  199519. case 2:
  199520. if ((png_ptr->row_number & 0x07) != 4)
  199521. {
  199522. png_write_finish_row(png_ptr);
  199523. return;
  199524. }
  199525. break;
  199526. case 3:
  199527. if ((png_ptr->row_number & 0x03) || png_ptr->width < 3)
  199528. {
  199529. png_write_finish_row(png_ptr);
  199530. return;
  199531. }
  199532. break;
  199533. case 4:
  199534. if ((png_ptr->row_number & 0x03) != 2)
  199535. {
  199536. png_write_finish_row(png_ptr);
  199537. return;
  199538. }
  199539. break;
  199540. case 5:
  199541. if ((png_ptr->row_number & 0x01) || png_ptr->width < 2)
  199542. {
  199543. png_write_finish_row(png_ptr);
  199544. return;
  199545. }
  199546. break;
  199547. case 6:
  199548. if (!(png_ptr->row_number & 0x01))
  199549. {
  199550. png_write_finish_row(png_ptr);
  199551. return;
  199552. }
  199553. break;
  199554. }
  199555. }
  199556. #endif
  199557. /* set up row info for transformations */
  199558. png_ptr->row_info.color_type = png_ptr->color_type;
  199559. png_ptr->row_info.width = png_ptr->usr_width;
  199560. png_ptr->row_info.channels = png_ptr->usr_channels;
  199561. png_ptr->row_info.bit_depth = png_ptr->usr_bit_depth;
  199562. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  199563. png_ptr->row_info.channels);
  199564. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  199565. png_ptr->row_info.width);
  199566. png_debug1(3, "row_info->color_type = %d\n", png_ptr->row_info.color_type);
  199567. png_debug1(3, "row_info->width = %lu\n", png_ptr->row_info.width);
  199568. png_debug1(3, "row_info->channels = %d\n", png_ptr->row_info.channels);
  199569. png_debug1(3, "row_info->bit_depth = %d\n", png_ptr->row_info.bit_depth);
  199570. png_debug1(3, "row_info->pixel_depth = %d\n", png_ptr->row_info.pixel_depth);
  199571. png_debug1(3, "row_info->rowbytes = %lu\n", png_ptr->row_info.rowbytes);
  199572. /* Copy user's row into buffer, leaving room for filter byte. */
  199573. png_memcpy_check(png_ptr, png_ptr->row_buf + 1, row,
  199574. png_ptr->row_info.rowbytes);
  199575. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199576. /* handle interlacing */
  199577. if (png_ptr->interlaced && png_ptr->pass < 6 &&
  199578. (png_ptr->transformations & PNG_INTERLACE))
  199579. {
  199580. png_do_write_interlace(&(png_ptr->row_info),
  199581. png_ptr->row_buf + 1, png_ptr->pass);
  199582. /* this should always get caught above, but still ... */
  199583. if (!(png_ptr->row_info.width))
  199584. {
  199585. png_write_finish_row(png_ptr);
  199586. return;
  199587. }
  199588. }
  199589. #endif
  199590. /* handle other transformations */
  199591. if (png_ptr->transformations)
  199592. png_do_write_transformations(png_ptr);
  199593. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  199594. /* Write filter_method 64 (intrapixel differencing) only if
  199595. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  199596. * 2. Libpng did not write a PNG signature (this filter_method is only
  199597. * used in PNG datastreams that are embedded in MNG datastreams) and
  199598. * 3. The application called png_permit_mng_features with a mask that
  199599. * included PNG_FLAG_MNG_FILTER_64 and
  199600. * 4. The filter_method is 64 and
  199601. * 5. The color_type is RGB or RGBA
  199602. */
  199603. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  199604. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  199605. {
  199606. /* Intrapixel differencing */
  199607. png_do_write_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199608. }
  199609. #endif
  199610. /* Find a filter if necessary, filter the row and write it out. */
  199611. png_write_find_filter(png_ptr, &(png_ptr->row_info));
  199612. if (png_ptr->write_row_fn != NULL)
  199613. (*(png_ptr->write_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  199614. }
  199615. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  199616. /* Set the automatic flush interval or 0 to turn flushing off */
  199617. void PNGAPI
  199618. png_set_flush(png_structp png_ptr, int nrows)
  199619. {
  199620. png_debug(1, "in png_set_flush\n");
  199621. if (png_ptr == NULL)
  199622. return;
  199623. png_ptr->flush_dist = (nrows < 0 ? 0 : nrows);
  199624. }
  199625. /* flush the current output buffers now */
  199626. void PNGAPI
  199627. png_write_flush(png_structp png_ptr)
  199628. {
  199629. int wrote_IDAT;
  199630. png_debug(1, "in png_write_flush\n");
  199631. if (png_ptr == NULL)
  199632. return;
  199633. /* We have already written out all of the data */
  199634. if (png_ptr->row_number >= png_ptr->num_rows)
  199635. return;
  199636. do
  199637. {
  199638. int ret;
  199639. /* compress the data */
  199640. ret = deflate(&png_ptr->zstream, Z_SYNC_FLUSH);
  199641. wrote_IDAT = 0;
  199642. /* check for compression errors */
  199643. if (ret != Z_OK)
  199644. {
  199645. if (png_ptr->zstream.msg != NULL)
  199646. png_error(png_ptr, png_ptr->zstream.msg);
  199647. else
  199648. png_error(png_ptr, "zlib error");
  199649. }
  199650. if (!(png_ptr->zstream.avail_out))
  199651. {
  199652. /* write the IDAT and reset the zlib output buffer */
  199653. png_write_IDAT(png_ptr, png_ptr->zbuf,
  199654. png_ptr->zbuf_size);
  199655. png_ptr->zstream.next_out = png_ptr->zbuf;
  199656. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199657. wrote_IDAT = 1;
  199658. }
  199659. } while(wrote_IDAT == 1);
  199660. /* If there is any data left to be output, write it into a new IDAT */
  199661. if (png_ptr->zbuf_size != png_ptr->zstream.avail_out)
  199662. {
  199663. /* write the IDAT and reset the zlib output buffer */
  199664. png_write_IDAT(png_ptr, png_ptr->zbuf,
  199665. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  199666. png_ptr->zstream.next_out = png_ptr->zbuf;
  199667. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199668. }
  199669. png_ptr->flush_rows = 0;
  199670. png_flush(png_ptr);
  199671. }
  199672. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  199673. /* free all memory used by the write */
  199674. void PNGAPI
  199675. png_destroy_write_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr)
  199676. {
  199677. png_structp png_ptr = NULL;
  199678. png_infop info_ptr = NULL;
  199679. #ifdef PNG_USER_MEM_SUPPORTED
  199680. png_free_ptr free_fn = NULL;
  199681. png_voidp mem_ptr = NULL;
  199682. #endif
  199683. png_debug(1, "in png_destroy_write_struct\n");
  199684. if (png_ptr_ptr != NULL)
  199685. {
  199686. png_ptr = *png_ptr_ptr;
  199687. #ifdef PNG_USER_MEM_SUPPORTED
  199688. free_fn = png_ptr->free_fn;
  199689. mem_ptr = png_ptr->mem_ptr;
  199690. #endif
  199691. }
  199692. if (info_ptr_ptr != NULL)
  199693. info_ptr = *info_ptr_ptr;
  199694. if (info_ptr != NULL)
  199695. {
  199696. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  199697. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  199698. if (png_ptr->num_chunk_list)
  199699. {
  199700. png_free(png_ptr, png_ptr->chunk_list);
  199701. png_ptr->chunk_list=NULL;
  199702. png_ptr->num_chunk_list=0;
  199703. }
  199704. #endif
  199705. #ifdef PNG_USER_MEM_SUPPORTED
  199706. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  199707. (png_voidp)mem_ptr);
  199708. #else
  199709. png_destroy_struct((png_voidp)info_ptr);
  199710. #endif
  199711. *info_ptr_ptr = NULL;
  199712. }
  199713. if (png_ptr != NULL)
  199714. {
  199715. png_write_destroy(png_ptr);
  199716. #ifdef PNG_USER_MEM_SUPPORTED
  199717. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  199718. (png_voidp)mem_ptr);
  199719. #else
  199720. png_destroy_struct((png_voidp)png_ptr);
  199721. #endif
  199722. *png_ptr_ptr = NULL;
  199723. }
  199724. }
  199725. /* Free any memory used in png_ptr struct (old method) */
  199726. void /* PRIVATE */
  199727. png_write_destroy(png_structp png_ptr)
  199728. {
  199729. #ifdef PNG_SETJMP_SUPPORTED
  199730. jmp_buf tmp_jmp; /* save jump buffer */
  199731. #endif
  199732. png_error_ptr error_fn;
  199733. png_error_ptr warning_fn;
  199734. png_voidp error_ptr;
  199735. #ifdef PNG_USER_MEM_SUPPORTED
  199736. png_free_ptr free_fn;
  199737. #endif
  199738. png_debug(1, "in png_write_destroy\n");
  199739. /* free any memory zlib uses */
  199740. deflateEnd(&png_ptr->zstream);
  199741. /* free our memory. png_free checks NULL for us. */
  199742. png_free(png_ptr, png_ptr->zbuf);
  199743. png_free(png_ptr, png_ptr->row_buf);
  199744. png_free(png_ptr, png_ptr->prev_row);
  199745. png_free(png_ptr, png_ptr->sub_row);
  199746. png_free(png_ptr, png_ptr->up_row);
  199747. png_free(png_ptr, png_ptr->avg_row);
  199748. png_free(png_ptr, png_ptr->paeth_row);
  199749. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  199750. png_free(png_ptr, png_ptr->time_buffer);
  199751. #endif
  199752. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199753. png_free(png_ptr, png_ptr->prev_filters);
  199754. png_free(png_ptr, png_ptr->filter_weights);
  199755. png_free(png_ptr, png_ptr->inv_filter_weights);
  199756. png_free(png_ptr, png_ptr->filter_costs);
  199757. png_free(png_ptr, png_ptr->inv_filter_costs);
  199758. #endif
  199759. #ifdef PNG_SETJMP_SUPPORTED
  199760. /* reset structure */
  199761. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  199762. #endif
  199763. error_fn = png_ptr->error_fn;
  199764. warning_fn = png_ptr->warning_fn;
  199765. error_ptr = png_ptr->error_ptr;
  199766. #ifdef PNG_USER_MEM_SUPPORTED
  199767. free_fn = png_ptr->free_fn;
  199768. #endif
  199769. png_memset(png_ptr, 0, png_sizeof (png_struct));
  199770. png_ptr->error_fn = error_fn;
  199771. png_ptr->warning_fn = warning_fn;
  199772. png_ptr->error_ptr = error_ptr;
  199773. #ifdef PNG_USER_MEM_SUPPORTED
  199774. png_ptr->free_fn = free_fn;
  199775. #endif
  199776. #ifdef PNG_SETJMP_SUPPORTED
  199777. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  199778. #endif
  199779. }
  199780. /* Allow the application to select one or more row filters to use. */
  199781. void PNGAPI
  199782. png_set_filter(png_structp png_ptr, int method, int filters)
  199783. {
  199784. png_debug(1, "in png_set_filter\n");
  199785. if (png_ptr == NULL)
  199786. return;
  199787. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  199788. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  199789. (method == PNG_INTRAPIXEL_DIFFERENCING))
  199790. method = PNG_FILTER_TYPE_BASE;
  199791. #endif
  199792. if (method == PNG_FILTER_TYPE_BASE)
  199793. {
  199794. switch (filters & (PNG_ALL_FILTERS | 0x07))
  199795. {
  199796. #ifndef PNG_NO_WRITE_FILTER
  199797. case 5:
  199798. case 6:
  199799. case 7: png_warning(png_ptr, "Unknown row filter for method 0");
  199800. #endif /* PNG_NO_WRITE_FILTER */
  199801. case PNG_FILTER_VALUE_NONE:
  199802. png_ptr->do_filter=PNG_FILTER_NONE; break;
  199803. #ifndef PNG_NO_WRITE_FILTER
  199804. case PNG_FILTER_VALUE_SUB:
  199805. png_ptr->do_filter=PNG_FILTER_SUB; break;
  199806. case PNG_FILTER_VALUE_UP:
  199807. png_ptr->do_filter=PNG_FILTER_UP; break;
  199808. case PNG_FILTER_VALUE_AVG:
  199809. png_ptr->do_filter=PNG_FILTER_AVG; break;
  199810. case PNG_FILTER_VALUE_PAETH:
  199811. png_ptr->do_filter=PNG_FILTER_PAETH; break;
  199812. default: png_ptr->do_filter = (png_byte)filters; break;
  199813. #else
  199814. default: png_warning(png_ptr, "Unknown row filter for method 0");
  199815. #endif /* PNG_NO_WRITE_FILTER */
  199816. }
  199817. /* If we have allocated the row_buf, this means we have already started
  199818. * with the image and we should have allocated all of the filter buffers
  199819. * that have been selected. If prev_row isn't already allocated, then
  199820. * it is too late to start using the filters that need it, since we
  199821. * will be missing the data in the previous row. If an application
  199822. * wants to start and stop using particular filters during compression,
  199823. * it should start out with all of the filters, and then add and
  199824. * remove them after the start of compression.
  199825. */
  199826. if (png_ptr->row_buf != NULL)
  199827. {
  199828. #ifndef PNG_NO_WRITE_FILTER
  199829. if ((png_ptr->do_filter & PNG_FILTER_SUB) && png_ptr->sub_row == NULL)
  199830. {
  199831. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  199832. (png_ptr->rowbytes + 1));
  199833. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  199834. }
  199835. if ((png_ptr->do_filter & PNG_FILTER_UP) && png_ptr->up_row == NULL)
  199836. {
  199837. if (png_ptr->prev_row == NULL)
  199838. {
  199839. png_warning(png_ptr, "Can't add Up filter after starting");
  199840. png_ptr->do_filter &= ~PNG_FILTER_UP;
  199841. }
  199842. else
  199843. {
  199844. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  199845. (png_ptr->rowbytes + 1));
  199846. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  199847. }
  199848. }
  199849. if ((png_ptr->do_filter & PNG_FILTER_AVG) && png_ptr->avg_row == NULL)
  199850. {
  199851. if (png_ptr->prev_row == NULL)
  199852. {
  199853. png_warning(png_ptr, "Can't add Average filter after starting");
  199854. png_ptr->do_filter &= ~PNG_FILTER_AVG;
  199855. }
  199856. else
  199857. {
  199858. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  199859. (png_ptr->rowbytes + 1));
  199860. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  199861. }
  199862. }
  199863. if ((png_ptr->do_filter & PNG_FILTER_PAETH) &&
  199864. png_ptr->paeth_row == NULL)
  199865. {
  199866. if (png_ptr->prev_row == NULL)
  199867. {
  199868. png_warning(png_ptr, "Can't add Paeth filter after starting");
  199869. png_ptr->do_filter &= (png_byte)(~PNG_FILTER_PAETH);
  199870. }
  199871. else
  199872. {
  199873. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  199874. (png_ptr->rowbytes + 1));
  199875. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  199876. }
  199877. }
  199878. if (png_ptr->do_filter == PNG_NO_FILTERS)
  199879. #endif /* PNG_NO_WRITE_FILTER */
  199880. png_ptr->do_filter = PNG_FILTER_NONE;
  199881. }
  199882. }
  199883. else
  199884. png_error(png_ptr, "Unknown custom filter method");
  199885. }
  199886. /* This allows us to influence the way in which libpng chooses the "best"
  199887. * filter for the current scanline. While the "minimum-sum-of-absolute-
  199888. * differences metric is relatively fast and effective, there is some
  199889. * question as to whether it can be improved upon by trying to keep the
  199890. * filtered data going to zlib more consistent, hopefully resulting in
  199891. * better compression.
  199892. */
  199893. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* GRR 970116 */
  199894. void PNGAPI
  199895. png_set_filter_heuristics(png_structp png_ptr, int heuristic_method,
  199896. int num_weights, png_doublep filter_weights,
  199897. png_doublep filter_costs)
  199898. {
  199899. int i;
  199900. png_debug(1, "in png_set_filter_heuristics\n");
  199901. if (png_ptr == NULL)
  199902. return;
  199903. if (heuristic_method >= PNG_FILTER_HEURISTIC_LAST)
  199904. {
  199905. png_warning(png_ptr, "Unknown filter heuristic method");
  199906. return;
  199907. }
  199908. if (heuristic_method == PNG_FILTER_HEURISTIC_DEFAULT)
  199909. {
  199910. heuristic_method = PNG_FILTER_HEURISTIC_UNWEIGHTED;
  199911. }
  199912. if (num_weights < 0 || filter_weights == NULL ||
  199913. heuristic_method == PNG_FILTER_HEURISTIC_UNWEIGHTED)
  199914. {
  199915. num_weights = 0;
  199916. }
  199917. png_ptr->num_prev_filters = (png_byte)num_weights;
  199918. png_ptr->heuristic_method = (png_byte)heuristic_method;
  199919. if (num_weights > 0)
  199920. {
  199921. if (png_ptr->prev_filters == NULL)
  199922. {
  199923. png_ptr->prev_filters = (png_bytep)png_malloc(png_ptr,
  199924. (png_uint_32)(png_sizeof(png_byte) * num_weights));
  199925. /* To make sure that the weighting starts out fairly */
  199926. for (i = 0; i < num_weights; i++)
  199927. {
  199928. png_ptr->prev_filters[i] = 255;
  199929. }
  199930. }
  199931. if (png_ptr->filter_weights == NULL)
  199932. {
  199933. png_ptr->filter_weights = (png_uint_16p)png_malloc(png_ptr,
  199934. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  199935. png_ptr->inv_filter_weights = (png_uint_16p)png_malloc(png_ptr,
  199936. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  199937. for (i = 0; i < num_weights; i++)
  199938. {
  199939. png_ptr->inv_filter_weights[i] =
  199940. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  199941. }
  199942. }
  199943. for (i = 0; i < num_weights; i++)
  199944. {
  199945. if (filter_weights[i] < 0.0)
  199946. {
  199947. png_ptr->inv_filter_weights[i] =
  199948. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  199949. }
  199950. else
  199951. {
  199952. png_ptr->inv_filter_weights[i] =
  199953. (png_uint_16)((double)PNG_WEIGHT_FACTOR*filter_weights[i]+0.5);
  199954. png_ptr->filter_weights[i] =
  199955. (png_uint_16)((double)PNG_WEIGHT_FACTOR/filter_weights[i]+0.5);
  199956. }
  199957. }
  199958. }
  199959. /* If, in the future, there are other filter methods, this would
  199960. * need to be based on png_ptr->filter.
  199961. */
  199962. if (png_ptr->filter_costs == NULL)
  199963. {
  199964. png_ptr->filter_costs = (png_uint_16p)png_malloc(png_ptr,
  199965. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  199966. png_ptr->inv_filter_costs = (png_uint_16p)png_malloc(png_ptr,
  199967. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  199968. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  199969. {
  199970. png_ptr->inv_filter_costs[i] =
  199971. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  199972. }
  199973. }
  199974. /* Here is where we set the relative costs of the different filters. We
  199975. * should take the desired compression level into account when setting
  199976. * the costs, so that Paeth, for instance, has a high relative cost at low
  199977. * compression levels, while it has a lower relative cost at higher
  199978. * compression settings. The filter types are in order of increasing
  199979. * relative cost, so it would be possible to do this with an algorithm.
  199980. */
  199981. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  199982. {
  199983. if (filter_costs == NULL || filter_costs[i] < 0.0)
  199984. {
  199985. png_ptr->inv_filter_costs[i] =
  199986. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  199987. }
  199988. else if (filter_costs[i] >= 1.0)
  199989. {
  199990. png_ptr->inv_filter_costs[i] =
  199991. (png_uint_16)((double)PNG_COST_FACTOR / filter_costs[i] + 0.5);
  199992. png_ptr->filter_costs[i] =
  199993. (png_uint_16)((double)PNG_COST_FACTOR * filter_costs[i] + 0.5);
  199994. }
  199995. }
  199996. }
  199997. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  199998. void PNGAPI
  199999. png_set_compression_level(png_structp png_ptr, int level)
  200000. {
  200001. png_debug(1, "in png_set_compression_level\n");
  200002. if (png_ptr == NULL)
  200003. return;
  200004. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_LEVEL;
  200005. png_ptr->zlib_level = level;
  200006. }
  200007. void PNGAPI
  200008. png_set_compression_mem_level(png_structp png_ptr, int mem_level)
  200009. {
  200010. png_debug(1, "in png_set_compression_mem_level\n");
  200011. if (png_ptr == NULL)
  200012. return;
  200013. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL;
  200014. png_ptr->zlib_mem_level = mem_level;
  200015. }
  200016. void PNGAPI
  200017. png_set_compression_strategy(png_structp png_ptr, int strategy)
  200018. {
  200019. png_debug(1, "in png_set_compression_strategy\n");
  200020. if (png_ptr == NULL)
  200021. return;
  200022. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_STRATEGY;
  200023. png_ptr->zlib_strategy = strategy;
  200024. }
  200025. void PNGAPI
  200026. png_set_compression_window_bits(png_structp png_ptr, int window_bits)
  200027. {
  200028. if (png_ptr == NULL)
  200029. return;
  200030. if (window_bits > 15)
  200031. png_warning(png_ptr, "Only compression windows <= 32k supported by PNG");
  200032. else if (window_bits < 8)
  200033. png_warning(png_ptr, "Only compression windows >= 256 supported by PNG");
  200034. #ifndef WBITS_8_OK
  200035. /* avoid libpng bug with 256-byte windows */
  200036. if (window_bits == 8)
  200037. {
  200038. png_warning(png_ptr, "Compression window is being reset to 512");
  200039. window_bits=9;
  200040. }
  200041. #endif
  200042. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS;
  200043. png_ptr->zlib_window_bits = window_bits;
  200044. }
  200045. void PNGAPI
  200046. png_set_compression_method(png_structp png_ptr, int method)
  200047. {
  200048. png_debug(1, "in png_set_compression_method\n");
  200049. if (png_ptr == NULL)
  200050. return;
  200051. if (method != 8)
  200052. png_warning(png_ptr, "Only compression method 8 is supported by PNG");
  200053. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_METHOD;
  200054. png_ptr->zlib_method = method;
  200055. }
  200056. void PNGAPI
  200057. png_set_write_status_fn(png_structp png_ptr, png_write_status_ptr write_row_fn)
  200058. {
  200059. if (png_ptr == NULL)
  200060. return;
  200061. png_ptr->write_row_fn = write_row_fn;
  200062. }
  200063. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  200064. void PNGAPI
  200065. png_set_write_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  200066. write_user_transform_fn)
  200067. {
  200068. png_debug(1, "in png_set_write_user_transform_fn\n");
  200069. if (png_ptr == NULL)
  200070. return;
  200071. png_ptr->transformations |= PNG_USER_TRANSFORM;
  200072. png_ptr->write_user_transform_fn = write_user_transform_fn;
  200073. }
  200074. #endif
  200075. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  200076. void PNGAPI
  200077. png_write_png(png_structp png_ptr, png_infop info_ptr,
  200078. int transforms, voidp params)
  200079. {
  200080. if (png_ptr == NULL || info_ptr == NULL)
  200081. return;
  200082. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  200083. /* invert the alpha channel from opacity to transparency */
  200084. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  200085. png_set_invert_alpha(png_ptr);
  200086. #endif
  200087. /* Write the file header information. */
  200088. png_write_info(png_ptr, info_ptr);
  200089. /* ------ these transformations don't touch the info structure ------- */
  200090. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  200091. /* invert monochrome pixels */
  200092. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  200093. png_set_invert_mono(png_ptr);
  200094. #endif
  200095. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  200096. /* Shift the pixels up to a legal bit depth and fill in
  200097. * as appropriate to correctly scale the image.
  200098. */
  200099. if ((transforms & PNG_TRANSFORM_SHIFT)
  200100. && (info_ptr->valid & PNG_INFO_sBIT))
  200101. png_set_shift(png_ptr, &info_ptr->sig_bit);
  200102. #endif
  200103. #if defined(PNG_WRITE_PACK_SUPPORTED)
  200104. /* pack pixels into bytes */
  200105. if (transforms & PNG_TRANSFORM_PACKING)
  200106. png_set_packing(png_ptr);
  200107. #endif
  200108. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  200109. /* swap location of alpha bytes from ARGB to RGBA */
  200110. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  200111. png_set_swap_alpha(png_ptr);
  200112. #endif
  200113. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  200114. /* Get rid of filler (OR ALPHA) bytes, pack XRGB/RGBX/ARGB/RGBA into
  200115. * RGB (4 channels -> 3 channels). The second parameter is not used.
  200116. */
  200117. if (transforms & PNG_TRANSFORM_STRIP_FILLER)
  200118. png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
  200119. #endif
  200120. #if defined(PNG_WRITE_BGR_SUPPORTED)
  200121. /* flip BGR pixels to RGB */
  200122. if (transforms & PNG_TRANSFORM_BGR)
  200123. png_set_bgr(png_ptr);
  200124. #endif
  200125. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  200126. /* swap bytes of 16-bit files to most significant byte first */
  200127. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  200128. png_set_swap(png_ptr);
  200129. #endif
  200130. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  200131. /* swap bits of 1, 2, 4 bit packed pixel formats */
  200132. if (transforms & PNG_TRANSFORM_PACKSWAP)
  200133. png_set_packswap(png_ptr);
  200134. #endif
  200135. /* ----------------------- end of transformations ------------------- */
  200136. /* write the bits */
  200137. if (info_ptr->valid & PNG_INFO_IDAT)
  200138. png_write_image(png_ptr, info_ptr->row_pointers);
  200139. /* It is REQUIRED to call this to finish writing the rest of the file */
  200140. png_write_end(png_ptr, info_ptr);
  200141. transforms = transforms; /* quiet compiler warnings */
  200142. params = params;
  200143. }
  200144. #endif
  200145. #endif /* PNG_WRITE_SUPPORTED */
  200146. /*** End of inlined file: pngwrite.c ***/
  200147. /*** Start of inlined file: pngwtran.c ***/
  200148. /* pngwtran.c - transforms the data in a row for PNG writers
  200149. *
  200150. * Last changed in libpng 1.2.9 April 14, 2006
  200151. * For conditions of distribution and use, see copyright notice in png.h
  200152. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  200153. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  200154. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  200155. */
  200156. #define PNG_INTERNAL
  200157. #ifdef PNG_WRITE_SUPPORTED
  200158. /* Transform the data according to the user's wishes. The order of
  200159. * transformations is significant.
  200160. */
  200161. void /* PRIVATE */
  200162. png_do_write_transformations(png_structp png_ptr)
  200163. {
  200164. png_debug(1, "in png_do_write_transformations\n");
  200165. if (png_ptr == NULL)
  200166. return;
  200167. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  200168. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  200169. if(png_ptr->write_user_transform_fn != NULL)
  200170. (*(png_ptr->write_user_transform_fn)) /* user write transform function */
  200171. (png_ptr, /* png_ptr */
  200172. &(png_ptr->row_info), /* row_info: */
  200173. /* png_uint_32 width; width of row */
  200174. /* png_uint_32 rowbytes; number of bytes in row */
  200175. /* png_byte color_type; color type of pixels */
  200176. /* png_byte bit_depth; bit depth of samples */
  200177. /* png_byte channels; number of channels (1-4) */
  200178. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  200179. png_ptr->row_buf + 1); /* start of pixel data for row */
  200180. #endif
  200181. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  200182. if (png_ptr->transformations & PNG_FILLER)
  200183. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  200184. png_ptr->flags);
  200185. #endif
  200186. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  200187. if (png_ptr->transformations & PNG_PACKSWAP)
  200188. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200189. #endif
  200190. #if defined(PNG_WRITE_PACK_SUPPORTED)
  200191. if (png_ptr->transformations & PNG_PACK)
  200192. png_do_pack(&(png_ptr->row_info), png_ptr->row_buf + 1,
  200193. (png_uint_32)png_ptr->bit_depth);
  200194. #endif
  200195. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  200196. if (png_ptr->transformations & PNG_SWAP_BYTES)
  200197. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200198. #endif
  200199. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  200200. if (png_ptr->transformations & PNG_SHIFT)
  200201. png_do_shift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  200202. &(png_ptr->shift));
  200203. #endif
  200204. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  200205. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  200206. png_do_write_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200207. #endif
  200208. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  200209. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  200210. png_do_write_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200211. #endif
  200212. #if defined(PNG_WRITE_BGR_SUPPORTED)
  200213. if (png_ptr->transformations & PNG_BGR)
  200214. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200215. #endif
  200216. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  200217. if (png_ptr->transformations & PNG_INVERT_MONO)
  200218. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200219. #endif
  200220. }
  200221. #if defined(PNG_WRITE_PACK_SUPPORTED)
  200222. /* Pack pixels into bytes. Pass the true bit depth in bit_depth. The
  200223. * row_info bit depth should be 8 (one pixel per byte). The channels
  200224. * should be 1 (this only happens on grayscale and paletted images).
  200225. */
  200226. void /* PRIVATE */
  200227. png_do_pack(png_row_infop row_info, png_bytep row, png_uint_32 bit_depth)
  200228. {
  200229. png_debug(1, "in png_do_pack\n");
  200230. if (row_info->bit_depth == 8 &&
  200231. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200232. row != NULL && row_info != NULL &&
  200233. #endif
  200234. row_info->channels == 1)
  200235. {
  200236. switch ((int)bit_depth)
  200237. {
  200238. case 1:
  200239. {
  200240. png_bytep sp, dp;
  200241. int mask, v;
  200242. png_uint_32 i;
  200243. png_uint_32 row_width = row_info->width;
  200244. sp = row;
  200245. dp = row;
  200246. mask = 0x80;
  200247. v = 0;
  200248. for (i = 0; i < row_width; i++)
  200249. {
  200250. if (*sp != 0)
  200251. v |= mask;
  200252. sp++;
  200253. if (mask > 1)
  200254. mask >>= 1;
  200255. else
  200256. {
  200257. mask = 0x80;
  200258. *dp = (png_byte)v;
  200259. dp++;
  200260. v = 0;
  200261. }
  200262. }
  200263. if (mask != 0x80)
  200264. *dp = (png_byte)v;
  200265. break;
  200266. }
  200267. case 2:
  200268. {
  200269. png_bytep sp, dp;
  200270. int shift, v;
  200271. png_uint_32 i;
  200272. png_uint_32 row_width = row_info->width;
  200273. sp = row;
  200274. dp = row;
  200275. shift = 6;
  200276. v = 0;
  200277. for (i = 0; i < row_width; i++)
  200278. {
  200279. png_byte value;
  200280. value = (png_byte)(*sp & 0x03);
  200281. v |= (value << shift);
  200282. if (shift == 0)
  200283. {
  200284. shift = 6;
  200285. *dp = (png_byte)v;
  200286. dp++;
  200287. v = 0;
  200288. }
  200289. else
  200290. shift -= 2;
  200291. sp++;
  200292. }
  200293. if (shift != 6)
  200294. *dp = (png_byte)v;
  200295. break;
  200296. }
  200297. case 4:
  200298. {
  200299. png_bytep sp, dp;
  200300. int shift, v;
  200301. png_uint_32 i;
  200302. png_uint_32 row_width = row_info->width;
  200303. sp = row;
  200304. dp = row;
  200305. shift = 4;
  200306. v = 0;
  200307. for (i = 0; i < row_width; i++)
  200308. {
  200309. png_byte value;
  200310. value = (png_byte)(*sp & 0x0f);
  200311. v |= (value << shift);
  200312. if (shift == 0)
  200313. {
  200314. shift = 4;
  200315. *dp = (png_byte)v;
  200316. dp++;
  200317. v = 0;
  200318. }
  200319. else
  200320. shift -= 4;
  200321. sp++;
  200322. }
  200323. if (shift != 4)
  200324. *dp = (png_byte)v;
  200325. break;
  200326. }
  200327. }
  200328. row_info->bit_depth = (png_byte)bit_depth;
  200329. row_info->pixel_depth = (png_byte)(bit_depth * row_info->channels);
  200330. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  200331. row_info->width);
  200332. }
  200333. }
  200334. #endif
  200335. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  200336. /* Shift pixel values to take advantage of whole range. Pass the
  200337. * true number of bits in bit_depth. The row should be packed
  200338. * according to row_info->bit_depth. Thus, if you had a row of
  200339. * bit depth 4, but the pixels only had values from 0 to 7, you
  200340. * would pass 3 as bit_depth, and this routine would translate the
  200341. * data to 0 to 15.
  200342. */
  200343. void /* PRIVATE */
  200344. png_do_shift(png_row_infop row_info, png_bytep row, png_color_8p bit_depth)
  200345. {
  200346. png_debug(1, "in png_do_shift\n");
  200347. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200348. if (row != NULL && row_info != NULL &&
  200349. #else
  200350. if (
  200351. #endif
  200352. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  200353. {
  200354. int shift_start[4], shift_dec[4];
  200355. int channels = 0;
  200356. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  200357. {
  200358. shift_start[channels] = row_info->bit_depth - bit_depth->red;
  200359. shift_dec[channels] = bit_depth->red;
  200360. channels++;
  200361. shift_start[channels] = row_info->bit_depth - bit_depth->green;
  200362. shift_dec[channels] = bit_depth->green;
  200363. channels++;
  200364. shift_start[channels] = row_info->bit_depth - bit_depth->blue;
  200365. shift_dec[channels] = bit_depth->blue;
  200366. channels++;
  200367. }
  200368. else
  200369. {
  200370. shift_start[channels] = row_info->bit_depth - bit_depth->gray;
  200371. shift_dec[channels] = bit_depth->gray;
  200372. channels++;
  200373. }
  200374. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  200375. {
  200376. shift_start[channels] = row_info->bit_depth - bit_depth->alpha;
  200377. shift_dec[channels] = bit_depth->alpha;
  200378. channels++;
  200379. }
  200380. /* with low row depths, could only be grayscale, so one channel */
  200381. if (row_info->bit_depth < 8)
  200382. {
  200383. png_bytep bp = row;
  200384. png_uint_32 i;
  200385. png_byte mask;
  200386. png_uint_32 row_bytes = row_info->rowbytes;
  200387. if (bit_depth->gray == 1 && row_info->bit_depth == 2)
  200388. mask = 0x55;
  200389. else if (row_info->bit_depth == 4 && bit_depth->gray == 3)
  200390. mask = 0x11;
  200391. else
  200392. mask = 0xff;
  200393. for (i = 0; i < row_bytes; i++, bp++)
  200394. {
  200395. png_uint_16 v;
  200396. int j;
  200397. v = *bp;
  200398. *bp = 0;
  200399. for (j = shift_start[0]; j > -shift_dec[0]; j -= shift_dec[0])
  200400. {
  200401. if (j > 0)
  200402. *bp |= (png_byte)((v << j) & 0xff);
  200403. else
  200404. *bp |= (png_byte)((v >> (-j)) & mask);
  200405. }
  200406. }
  200407. }
  200408. else if (row_info->bit_depth == 8)
  200409. {
  200410. png_bytep bp = row;
  200411. png_uint_32 i;
  200412. png_uint_32 istop = channels * row_info->width;
  200413. for (i = 0; i < istop; i++, bp++)
  200414. {
  200415. png_uint_16 v;
  200416. int j;
  200417. int c = (int)(i%channels);
  200418. v = *bp;
  200419. *bp = 0;
  200420. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  200421. {
  200422. if (j > 0)
  200423. *bp |= (png_byte)((v << j) & 0xff);
  200424. else
  200425. *bp |= (png_byte)((v >> (-j)) & 0xff);
  200426. }
  200427. }
  200428. }
  200429. else
  200430. {
  200431. png_bytep bp;
  200432. png_uint_32 i;
  200433. png_uint_32 istop = channels * row_info->width;
  200434. for (bp = row, i = 0; i < istop; i++)
  200435. {
  200436. int c = (int)(i%channels);
  200437. png_uint_16 value, v;
  200438. int j;
  200439. v = (png_uint_16)(((png_uint_16)(*bp) << 8) + *(bp + 1));
  200440. value = 0;
  200441. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  200442. {
  200443. if (j > 0)
  200444. value |= (png_uint_16)((v << j) & (png_uint_16)0xffff);
  200445. else
  200446. value |= (png_uint_16)((v >> (-j)) & (png_uint_16)0xffff);
  200447. }
  200448. *bp++ = (png_byte)(value >> 8);
  200449. *bp++ = (png_byte)(value & 0xff);
  200450. }
  200451. }
  200452. }
  200453. }
  200454. #endif
  200455. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  200456. void /* PRIVATE */
  200457. png_do_write_swap_alpha(png_row_infop row_info, png_bytep row)
  200458. {
  200459. png_debug(1, "in png_do_write_swap_alpha\n");
  200460. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200461. if (row != NULL && row_info != NULL)
  200462. #endif
  200463. {
  200464. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200465. {
  200466. /* This converts from ARGB to RGBA */
  200467. if (row_info->bit_depth == 8)
  200468. {
  200469. png_bytep sp, dp;
  200470. png_uint_32 i;
  200471. png_uint_32 row_width = row_info->width;
  200472. for (i = 0, sp = dp = row; i < row_width; i++)
  200473. {
  200474. png_byte save = *(sp++);
  200475. *(dp++) = *(sp++);
  200476. *(dp++) = *(sp++);
  200477. *(dp++) = *(sp++);
  200478. *(dp++) = save;
  200479. }
  200480. }
  200481. /* This converts from AARRGGBB to RRGGBBAA */
  200482. else
  200483. {
  200484. png_bytep sp, dp;
  200485. png_uint_32 i;
  200486. png_uint_32 row_width = row_info->width;
  200487. for (i = 0, sp = dp = row; i < row_width; i++)
  200488. {
  200489. png_byte save[2];
  200490. save[0] = *(sp++);
  200491. save[1] = *(sp++);
  200492. *(dp++) = *(sp++);
  200493. *(dp++) = *(sp++);
  200494. *(dp++) = *(sp++);
  200495. *(dp++) = *(sp++);
  200496. *(dp++) = *(sp++);
  200497. *(dp++) = *(sp++);
  200498. *(dp++) = save[0];
  200499. *(dp++) = save[1];
  200500. }
  200501. }
  200502. }
  200503. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  200504. {
  200505. /* This converts from AG to GA */
  200506. if (row_info->bit_depth == 8)
  200507. {
  200508. png_bytep sp, dp;
  200509. png_uint_32 i;
  200510. png_uint_32 row_width = row_info->width;
  200511. for (i = 0, sp = dp = row; i < row_width; i++)
  200512. {
  200513. png_byte save = *(sp++);
  200514. *(dp++) = *(sp++);
  200515. *(dp++) = save;
  200516. }
  200517. }
  200518. /* This converts from AAGG to GGAA */
  200519. else
  200520. {
  200521. png_bytep sp, dp;
  200522. png_uint_32 i;
  200523. png_uint_32 row_width = row_info->width;
  200524. for (i = 0, sp = dp = row; i < row_width; i++)
  200525. {
  200526. png_byte save[2];
  200527. save[0] = *(sp++);
  200528. save[1] = *(sp++);
  200529. *(dp++) = *(sp++);
  200530. *(dp++) = *(sp++);
  200531. *(dp++) = save[0];
  200532. *(dp++) = save[1];
  200533. }
  200534. }
  200535. }
  200536. }
  200537. }
  200538. #endif
  200539. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  200540. void /* PRIVATE */
  200541. png_do_write_invert_alpha(png_row_infop row_info, png_bytep row)
  200542. {
  200543. png_debug(1, "in png_do_write_invert_alpha\n");
  200544. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200545. if (row != NULL && row_info != NULL)
  200546. #endif
  200547. {
  200548. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200549. {
  200550. /* This inverts the alpha channel in RGBA */
  200551. if (row_info->bit_depth == 8)
  200552. {
  200553. png_bytep sp, dp;
  200554. png_uint_32 i;
  200555. png_uint_32 row_width = row_info->width;
  200556. for (i = 0, sp = dp = row; i < row_width; i++)
  200557. {
  200558. /* does nothing
  200559. *(dp++) = *(sp++);
  200560. *(dp++) = *(sp++);
  200561. *(dp++) = *(sp++);
  200562. */
  200563. sp+=3; dp = sp;
  200564. *(dp++) = (png_byte)(255 - *(sp++));
  200565. }
  200566. }
  200567. /* This inverts the alpha channel in RRGGBBAA */
  200568. else
  200569. {
  200570. png_bytep sp, dp;
  200571. png_uint_32 i;
  200572. png_uint_32 row_width = row_info->width;
  200573. for (i = 0, sp = dp = row; i < row_width; i++)
  200574. {
  200575. /* does nothing
  200576. *(dp++) = *(sp++);
  200577. *(dp++) = *(sp++);
  200578. *(dp++) = *(sp++);
  200579. *(dp++) = *(sp++);
  200580. *(dp++) = *(sp++);
  200581. *(dp++) = *(sp++);
  200582. */
  200583. sp+=6; dp = sp;
  200584. *(dp++) = (png_byte)(255 - *(sp++));
  200585. *(dp++) = (png_byte)(255 - *(sp++));
  200586. }
  200587. }
  200588. }
  200589. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  200590. {
  200591. /* This inverts the alpha channel in GA */
  200592. if (row_info->bit_depth == 8)
  200593. {
  200594. png_bytep sp, dp;
  200595. png_uint_32 i;
  200596. png_uint_32 row_width = row_info->width;
  200597. for (i = 0, sp = dp = row; i < row_width; i++)
  200598. {
  200599. *(dp++) = *(sp++);
  200600. *(dp++) = (png_byte)(255 - *(sp++));
  200601. }
  200602. }
  200603. /* This inverts the alpha channel in GGAA */
  200604. else
  200605. {
  200606. png_bytep sp, dp;
  200607. png_uint_32 i;
  200608. png_uint_32 row_width = row_info->width;
  200609. for (i = 0, sp = dp = row; i < row_width; i++)
  200610. {
  200611. /* does nothing
  200612. *(dp++) = *(sp++);
  200613. *(dp++) = *(sp++);
  200614. */
  200615. sp+=2; dp = sp;
  200616. *(dp++) = (png_byte)(255 - *(sp++));
  200617. *(dp++) = (png_byte)(255 - *(sp++));
  200618. }
  200619. }
  200620. }
  200621. }
  200622. }
  200623. #endif
  200624. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200625. /* undoes intrapixel differencing */
  200626. void /* PRIVATE */
  200627. png_do_write_intrapixel(png_row_infop row_info, png_bytep row)
  200628. {
  200629. png_debug(1, "in png_do_write_intrapixel\n");
  200630. if (
  200631. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200632. row != NULL && row_info != NULL &&
  200633. #endif
  200634. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  200635. {
  200636. int bytes_per_pixel;
  200637. png_uint_32 row_width = row_info->width;
  200638. if (row_info->bit_depth == 8)
  200639. {
  200640. png_bytep rp;
  200641. png_uint_32 i;
  200642. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  200643. bytes_per_pixel = 3;
  200644. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200645. bytes_per_pixel = 4;
  200646. else
  200647. return;
  200648. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  200649. {
  200650. *(rp) = (png_byte)((*rp - *(rp+1))&0xff);
  200651. *(rp+2) = (png_byte)((*(rp+2) - *(rp+1))&0xff);
  200652. }
  200653. }
  200654. else if (row_info->bit_depth == 16)
  200655. {
  200656. png_bytep rp;
  200657. png_uint_32 i;
  200658. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  200659. bytes_per_pixel = 6;
  200660. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200661. bytes_per_pixel = 8;
  200662. else
  200663. return;
  200664. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  200665. {
  200666. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  200667. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  200668. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  200669. png_uint_32 red = (png_uint_32)((s0-s1) & 0xffffL);
  200670. png_uint_32 blue = (png_uint_32)((s2-s1) & 0xffffL);
  200671. *(rp ) = (png_byte)((red >> 8) & 0xff);
  200672. *(rp+1) = (png_byte)(red & 0xff);
  200673. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  200674. *(rp+5) = (png_byte)(blue & 0xff);
  200675. }
  200676. }
  200677. }
  200678. }
  200679. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  200680. #endif /* PNG_WRITE_SUPPORTED */
  200681. /*** End of inlined file: pngwtran.c ***/
  200682. /*** Start of inlined file: pngwutil.c ***/
  200683. /* pngwutil.c - utilities to write a PNG file
  200684. *
  200685. * Last changed in libpng 1.2.20 Septhember 3, 2007
  200686. * For conditions of distribution and use, see copyright notice in png.h
  200687. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  200688. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  200689. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  200690. */
  200691. #define PNG_INTERNAL
  200692. #ifdef PNG_WRITE_SUPPORTED
  200693. /* Place a 32-bit number into a buffer in PNG byte order. We work
  200694. * with unsigned numbers for convenience, although one supported
  200695. * ancillary chunk uses signed (two's complement) numbers.
  200696. */
  200697. void PNGAPI
  200698. png_save_uint_32(png_bytep buf, png_uint_32 i)
  200699. {
  200700. buf[0] = (png_byte)((i >> 24) & 0xff);
  200701. buf[1] = (png_byte)((i >> 16) & 0xff);
  200702. buf[2] = (png_byte)((i >> 8) & 0xff);
  200703. buf[3] = (png_byte)(i & 0xff);
  200704. }
  200705. /* The png_save_int_32 function assumes integers are stored in two's
  200706. * complement format. If this isn't the case, then this routine needs to
  200707. * be modified to write data in two's complement format.
  200708. */
  200709. void PNGAPI
  200710. png_save_int_32(png_bytep buf, png_int_32 i)
  200711. {
  200712. buf[0] = (png_byte)((i >> 24) & 0xff);
  200713. buf[1] = (png_byte)((i >> 16) & 0xff);
  200714. buf[2] = (png_byte)((i >> 8) & 0xff);
  200715. buf[3] = (png_byte)(i & 0xff);
  200716. }
  200717. /* Place a 16-bit number into a buffer in PNG byte order.
  200718. * The parameter is declared unsigned int, not png_uint_16,
  200719. * just to avoid potential problems on pre-ANSI C compilers.
  200720. */
  200721. void PNGAPI
  200722. png_save_uint_16(png_bytep buf, unsigned int i)
  200723. {
  200724. buf[0] = (png_byte)((i >> 8) & 0xff);
  200725. buf[1] = (png_byte)(i & 0xff);
  200726. }
  200727. /* Write a PNG chunk all at once. The type is an array of ASCII characters
  200728. * representing the chunk name. The array must be at least 4 bytes in
  200729. * length, and does not need to be null terminated. To be safe, pass the
  200730. * pre-defined chunk names here, and if you need a new one, define it
  200731. * where the others are defined. The length is the length of the data.
  200732. * All the data must be present. If that is not possible, use the
  200733. * png_write_chunk_start(), png_write_chunk_data(), and png_write_chunk_end()
  200734. * functions instead.
  200735. */
  200736. void PNGAPI
  200737. png_write_chunk(png_structp png_ptr, png_bytep chunk_name,
  200738. png_bytep data, png_size_t length)
  200739. {
  200740. if(png_ptr == NULL) return;
  200741. png_write_chunk_start(png_ptr, chunk_name, (png_uint_32)length);
  200742. png_write_chunk_data(png_ptr, data, length);
  200743. png_write_chunk_end(png_ptr);
  200744. }
  200745. /* Write the start of a PNG chunk. The type is the chunk type.
  200746. * The total_length is the sum of the lengths of all the data you will be
  200747. * passing in png_write_chunk_data().
  200748. */
  200749. void PNGAPI
  200750. png_write_chunk_start(png_structp png_ptr, png_bytep chunk_name,
  200751. png_uint_32 length)
  200752. {
  200753. png_byte buf[4];
  200754. png_debug2(0, "Writing %s chunk (%lu bytes)\n", chunk_name, length);
  200755. if(png_ptr == NULL) return;
  200756. /* write the length */
  200757. png_save_uint_32(buf, length);
  200758. png_write_data(png_ptr, buf, (png_size_t)4);
  200759. /* write the chunk name */
  200760. png_write_data(png_ptr, chunk_name, (png_size_t)4);
  200761. /* reset the crc and run it over the chunk name */
  200762. png_reset_crc(png_ptr);
  200763. png_calculate_crc(png_ptr, chunk_name, (png_size_t)4);
  200764. }
  200765. /* Write the data of a PNG chunk started with png_write_chunk_start().
  200766. * Note that multiple calls to this function are allowed, and that the
  200767. * sum of the lengths from these calls *must* add up to the total_length
  200768. * given to png_write_chunk_start().
  200769. */
  200770. void PNGAPI
  200771. png_write_chunk_data(png_structp png_ptr, png_bytep data, png_size_t length)
  200772. {
  200773. /* write the data, and run the CRC over it */
  200774. if(png_ptr == NULL) return;
  200775. if (data != NULL && length > 0)
  200776. {
  200777. png_calculate_crc(png_ptr, data, length);
  200778. png_write_data(png_ptr, data, length);
  200779. }
  200780. }
  200781. /* Finish a chunk started with png_write_chunk_start(). */
  200782. void PNGAPI
  200783. png_write_chunk_end(png_structp png_ptr)
  200784. {
  200785. png_byte buf[4];
  200786. if(png_ptr == NULL) return;
  200787. /* write the crc */
  200788. png_save_uint_32(buf, png_ptr->crc);
  200789. png_write_data(png_ptr, buf, (png_size_t)4);
  200790. }
  200791. /* Simple function to write the signature. If we have already written
  200792. * the magic bytes of the signature, or more likely, the PNG stream is
  200793. * being embedded into another stream and doesn't need its own signature,
  200794. * we should call png_set_sig_bytes() to tell libpng how many of the
  200795. * bytes have already been written.
  200796. */
  200797. void /* PRIVATE */
  200798. png_write_sig(png_structp png_ptr)
  200799. {
  200800. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  200801. /* write the rest of the 8 byte signature */
  200802. png_write_data(png_ptr, &png_signature[png_ptr->sig_bytes],
  200803. (png_size_t)8 - png_ptr->sig_bytes);
  200804. if(png_ptr->sig_bytes < 3)
  200805. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  200806. }
  200807. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_iCCP_SUPPORTED)
  200808. /*
  200809. * This pair of functions encapsulates the operation of (a) compressing a
  200810. * text string, and (b) issuing it later as a series of chunk data writes.
  200811. * The compression_state structure is shared context for these functions
  200812. * set up by the caller in order to make the whole mess thread-safe.
  200813. */
  200814. typedef struct
  200815. {
  200816. char *input; /* the uncompressed input data */
  200817. int input_len; /* its length */
  200818. int num_output_ptr; /* number of output pointers used */
  200819. int max_output_ptr; /* size of output_ptr */
  200820. png_charpp output_ptr; /* array of pointers to output */
  200821. } compression_state;
  200822. /* compress given text into storage in the png_ptr structure */
  200823. static int /* PRIVATE */
  200824. png_text_compress(png_structp png_ptr,
  200825. png_charp text, png_size_t text_len, int compression,
  200826. compression_state *comp)
  200827. {
  200828. int ret;
  200829. comp->num_output_ptr = 0;
  200830. comp->max_output_ptr = 0;
  200831. comp->output_ptr = NULL;
  200832. comp->input = NULL;
  200833. comp->input_len = 0;
  200834. /* we may just want to pass the text right through */
  200835. if (compression == PNG_TEXT_COMPRESSION_NONE)
  200836. {
  200837. comp->input = text;
  200838. comp->input_len = text_len;
  200839. return((int)text_len);
  200840. }
  200841. if (compression >= PNG_TEXT_COMPRESSION_LAST)
  200842. {
  200843. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  200844. char msg[50];
  200845. png_snprintf(msg, 50, "Unknown compression type %d", compression);
  200846. png_warning(png_ptr, msg);
  200847. #else
  200848. png_warning(png_ptr, "Unknown compression type");
  200849. #endif
  200850. }
  200851. /* We can't write the chunk until we find out how much data we have,
  200852. * which means we need to run the compressor first and save the
  200853. * output. This shouldn't be a problem, as the vast majority of
  200854. * comments should be reasonable, but we will set up an array of
  200855. * malloc'd pointers to be sure.
  200856. *
  200857. * If we knew the application was well behaved, we could simplify this
  200858. * greatly by assuming we can always malloc an output buffer large
  200859. * enough to hold the compressed text ((1001 * text_len / 1000) + 12)
  200860. * and malloc this directly. The only time this would be a bad idea is
  200861. * if we can't malloc more than 64K and we have 64K of random input
  200862. * data, or if the input string is incredibly large (although this
  200863. * wouldn't cause a failure, just a slowdown due to swapping).
  200864. */
  200865. /* set up the compression buffers */
  200866. png_ptr->zstream.avail_in = (uInt)text_len;
  200867. png_ptr->zstream.next_in = (Bytef *)text;
  200868. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200869. png_ptr->zstream.next_out = (Bytef *)png_ptr->zbuf;
  200870. /* this is the same compression loop as in png_write_row() */
  200871. do
  200872. {
  200873. /* compress the data */
  200874. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  200875. if (ret != Z_OK)
  200876. {
  200877. /* error */
  200878. if (png_ptr->zstream.msg != NULL)
  200879. png_error(png_ptr, png_ptr->zstream.msg);
  200880. else
  200881. png_error(png_ptr, "zlib error");
  200882. }
  200883. /* check to see if we need more room */
  200884. if (!(png_ptr->zstream.avail_out))
  200885. {
  200886. /* make sure the output array has room */
  200887. if (comp->num_output_ptr >= comp->max_output_ptr)
  200888. {
  200889. int old_max;
  200890. old_max = comp->max_output_ptr;
  200891. comp->max_output_ptr = comp->num_output_ptr + 4;
  200892. if (comp->output_ptr != NULL)
  200893. {
  200894. png_charpp old_ptr;
  200895. old_ptr = comp->output_ptr;
  200896. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200897. (png_uint_32)(comp->max_output_ptr *
  200898. png_sizeof (png_charpp)));
  200899. png_memcpy(comp->output_ptr, old_ptr, old_max
  200900. * png_sizeof (png_charp));
  200901. png_free(png_ptr, old_ptr);
  200902. }
  200903. else
  200904. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200905. (png_uint_32)(comp->max_output_ptr *
  200906. png_sizeof (png_charp)));
  200907. }
  200908. /* save the data */
  200909. comp->output_ptr[comp->num_output_ptr] = (png_charp)png_malloc(png_ptr,
  200910. (png_uint_32)png_ptr->zbuf_size);
  200911. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  200912. png_ptr->zbuf_size);
  200913. comp->num_output_ptr++;
  200914. /* and reset the buffer */
  200915. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200916. png_ptr->zstream.next_out = png_ptr->zbuf;
  200917. }
  200918. /* continue until we don't have any more to compress */
  200919. } while (png_ptr->zstream.avail_in);
  200920. /* finish the compression */
  200921. do
  200922. {
  200923. /* tell zlib we are finished */
  200924. ret = deflate(&png_ptr->zstream, Z_FINISH);
  200925. if (ret == Z_OK)
  200926. {
  200927. /* check to see if we need more room */
  200928. if (!(png_ptr->zstream.avail_out))
  200929. {
  200930. /* check to make sure our output array has room */
  200931. if (comp->num_output_ptr >= comp->max_output_ptr)
  200932. {
  200933. int old_max;
  200934. old_max = comp->max_output_ptr;
  200935. comp->max_output_ptr = comp->num_output_ptr + 4;
  200936. if (comp->output_ptr != NULL)
  200937. {
  200938. png_charpp old_ptr;
  200939. old_ptr = comp->output_ptr;
  200940. /* This could be optimized to realloc() */
  200941. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200942. (png_uint_32)(comp->max_output_ptr *
  200943. png_sizeof (png_charpp)));
  200944. png_memcpy(comp->output_ptr, old_ptr,
  200945. old_max * png_sizeof (png_charp));
  200946. png_free(png_ptr, old_ptr);
  200947. }
  200948. else
  200949. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200950. (png_uint_32)(comp->max_output_ptr *
  200951. png_sizeof (png_charp)));
  200952. }
  200953. /* save off the data */
  200954. comp->output_ptr[comp->num_output_ptr] =
  200955. (png_charp)png_malloc(png_ptr, (png_uint_32)png_ptr->zbuf_size);
  200956. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  200957. png_ptr->zbuf_size);
  200958. comp->num_output_ptr++;
  200959. /* and reset the buffer pointers */
  200960. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200961. png_ptr->zstream.next_out = png_ptr->zbuf;
  200962. }
  200963. }
  200964. else if (ret != Z_STREAM_END)
  200965. {
  200966. /* we got an error */
  200967. if (png_ptr->zstream.msg != NULL)
  200968. png_error(png_ptr, png_ptr->zstream.msg);
  200969. else
  200970. png_error(png_ptr, "zlib error");
  200971. }
  200972. } while (ret != Z_STREAM_END);
  200973. /* text length is number of buffers plus last buffer */
  200974. text_len = png_ptr->zbuf_size * comp->num_output_ptr;
  200975. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  200976. text_len += png_ptr->zbuf_size - (png_size_t)png_ptr->zstream.avail_out;
  200977. return((int)text_len);
  200978. }
  200979. /* ship the compressed text out via chunk writes */
  200980. static void /* PRIVATE */
  200981. png_write_compressed_data_out(png_structp png_ptr, compression_state *comp)
  200982. {
  200983. int i;
  200984. /* handle the no-compression case */
  200985. if (comp->input)
  200986. {
  200987. png_write_chunk_data(png_ptr, (png_bytep)comp->input,
  200988. (png_size_t)comp->input_len);
  200989. return;
  200990. }
  200991. /* write saved output buffers, if any */
  200992. for (i = 0; i < comp->num_output_ptr; i++)
  200993. {
  200994. png_write_chunk_data(png_ptr,(png_bytep)comp->output_ptr[i],
  200995. png_ptr->zbuf_size);
  200996. png_free(png_ptr, comp->output_ptr[i]);
  200997. comp->output_ptr[i]=NULL;
  200998. }
  200999. if (comp->max_output_ptr != 0)
  201000. png_free(png_ptr, comp->output_ptr);
  201001. comp->output_ptr=NULL;
  201002. /* write anything left in zbuf */
  201003. if (png_ptr->zstream.avail_out < (png_uint_32)png_ptr->zbuf_size)
  201004. png_write_chunk_data(png_ptr, png_ptr->zbuf,
  201005. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  201006. /* reset zlib for another zTXt/iTXt or image data */
  201007. deflateReset(&png_ptr->zstream);
  201008. png_ptr->zstream.data_type = Z_BINARY;
  201009. }
  201010. #endif
  201011. /* Write the IHDR chunk, and update the png_struct with the necessary
  201012. * information. Note that the rest of this code depends upon this
  201013. * information being correct.
  201014. */
  201015. void /* PRIVATE */
  201016. png_write_IHDR(png_structp png_ptr, png_uint_32 width, png_uint_32 height,
  201017. int bit_depth, int color_type, int compression_type, int filter_type,
  201018. int interlace_type)
  201019. {
  201020. #ifdef PNG_USE_LOCAL_ARRAYS
  201021. PNG_IHDR;
  201022. #endif
  201023. png_byte buf[13]; /* buffer to store the IHDR info */
  201024. png_debug(1, "in png_write_IHDR\n");
  201025. /* Check that we have valid input data from the application info */
  201026. switch (color_type)
  201027. {
  201028. case PNG_COLOR_TYPE_GRAY:
  201029. switch (bit_depth)
  201030. {
  201031. case 1:
  201032. case 2:
  201033. case 4:
  201034. case 8:
  201035. case 16: png_ptr->channels = 1; break;
  201036. default: png_error(png_ptr,"Invalid bit depth for grayscale image");
  201037. }
  201038. break;
  201039. case PNG_COLOR_TYPE_RGB:
  201040. if (bit_depth != 8 && bit_depth != 16)
  201041. png_error(png_ptr, "Invalid bit depth for RGB image");
  201042. png_ptr->channels = 3;
  201043. break;
  201044. case PNG_COLOR_TYPE_PALETTE:
  201045. switch (bit_depth)
  201046. {
  201047. case 1:
  201048. case 2:
  201049. case 4:
  201050. case 8: png_ptr->channels = 1; break;
  201051. default: png_error(png_ptr, "Invalid bit depth for paletted image");
  201052. }
  201053. break;
  201054. case PNG_COLOR_TYPE_GRAY_ALPHA:
  201055. if (bit_depth != 8 && bit_depth != 16)
  201056. png_error(png_ptr, "Invalid bit depth for grayscale+alpha image");
  201057. png_ptr->channels = 2;
  201058. break;
  201059. case PNG_COLOR_TYPE_RGB_ALPHA:
  201060. if (bit_depth != 8 && bit_depth != 16)
  201061. png_error(png_ptr, "Invalid bit depth for RGBA image");
  201062. png_ptr->channels = 4;
  201063. break;
  201064. default:
  201065. png_error(png_ptr, "Invalid image color type specified");
  201066. }
  201067. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  201068. {
  201069. png_warning(png_ptr, "Invalid compression type specified");
  201070. compression_type = PNG_COMPRESSION_TYPE_BASE;
  201071. }
  201072. /* Write filter_method 64 (intrapixel differencing) only if
  201073. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  201074. * 2. Libpng did not write a PNG signature (this filter_method is only
  201075. * used in PNG datastreams that are embedded in MNG datastreams) and
  201076. * 3. The application called png_permit_mng_features with a mask that
  201077. * included PNG_FLAG_MNG_FILTER_64 and
  201078. * 4. The filter_method is 64 and
  201079. * 5. The color_type is RGB or RGBA
  201080. */
  201081. if (
  201082. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201083. !((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  201084. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  201085. (color_type == PNG_COLOR_TYPE_RGB ||
  201086. color_type == PNG_COLOR_TYPE_RGB_ALPHA) &&
  201087. (filter_type == PNG_INTRAPIXEL_DIFFERENCING)) &&
  201088. #endif
  201089. filter_type != PNG_FILTER_TYPE_BASE)
  201090. {
  201091. png_warning(png_ptr, "Invalid filter type specified");
  201092. filter_type = PNG_FILTER_TYPE_BASE;
  201093. }
  201094. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  201095. if (interlace_type != PNG_INTERLACE_NONE &&
  201096. interlace_type != PNG_INTERLACE_ADAM7)
  201097. {
  201098. png_warning(png_ptr, "Invalid interlace type specified");
  201099. interlace_type = PNG_INTERLACE_ADAM7;
  201100. }
  201101. #else
  201102. interlace_type=PNG_INTERLACE_NONE;
  201103. #endif
  201104. /* save off the relevent information */
  201105. png_ptr->bit_depth = (png_byte)bit_depth;
  201106. png_ptr->color_type = (png_byte)color_type;
  201107. png_ptr->interlaced = (png_byte)interlace_type;
  201108. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201109. png_ptr->filter_type = (png_byte)filter_type;
  201110. #endif
  201111. png_ptr->compression_type = (png_byte)compression_type;
  201112. png_ptr->width = width;
  201113. png_ptr->height = height;
  201114. png_ptr->pixel_depth = (png_byte)(bit_depth * png_ptr->channels);
  201115. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, width);
  201116. /* set the usr info, so any transformations can modify it */
  201117. png_ptr->usr_width = png_ptr->width;
  201118. png_ptr->usr_bit_depth = png_ptr->bit_depth;
  201119. png_ptr->usr_channels = png_ptr->channels;
  201120. /* pack the header information into the buffer */
  201121. png_save_uint_32(buf, width);
  201122. png_save_uint_32(buf + 4, height);
  201123. buf[8] = (png_byte)bit_depth;
  201124. buf[9] = (png_byte)color_type;
  201125. buf[10] = (png_byte)compression_type;
  201126. buf[11] = (png_byte)filter_type;
  201127. buf[12] = (png_byte)interlace_type;
  201128. /* write the chunk */
  201129. png_write_chunk(png_ptr, png_IHDR, buf, (png_size_t)13);
  201130. /* initialize zlib with PNG info */
  201131. png_ptr->zstream.zalloc = png_zalloc;
  201132. png_ptr->zstream.zfree = png_zfree;
  201133. png_ptr->zstream.opaque = (voidpf)png_ptr;
  201134. if (!(png_ptr->do_filter))
  201135. {
  201136. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
  201137. png_ptr->bit_depth < 8)
  201138. png_ptr->do_filter = PNG_FILTER_NONE;
  201139. else
  201140. png_ptr->do_filter = PNG_ALL_FILTERS;
  201141. }
  201142. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_STRATEGY))
  201143. {
  201144. if (png_ptr->do_filter != PNG_FILTER_NONE)
  201145. png_ptr->zlib_strategy = Z_FILTERED;
  201146. else
  201147. png_ptr->zlib_strategy = Z_DEFAULT_STRATEGY;
  201148. }
  201149. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_LEVEL))
  201150. png_ptr->zlib_level = Z_DEFAULT_COMPRESSION;
  201151. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL))
  201152. png_ptr->zlib_mem_level = 8;
  201153. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS))
  201154. png_ptr->zlib_window_bits = 15;
  201155. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_METHOD))
  201156. png_ptr->zlib_method = 8;
  201157. if (deflateInit2(&png_ptr->zstream, png_ptr->zlib_level,
  201158. png_ptr->zlib_method, png_ptr->zlib_window_bits,
  201159. png_ptr->zlib_mem_level, png_ptr->zlib_strategy) != Z_OK)
  201160. png_error(png_ptr, "zlib failed to initialize compressor");
  201161. png_ptr->zstream.next_out = png_ptr->zbuf;
  201162. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201163. /* libpng is not interested in zstream.data_type */
  201164. /* set it to a predefined value, to avoid its evaluation inside zlib */
  201165. png_ptr->zstream.data_type = Z_BINARY;
  201166. png_ptr->mode = PNG_HAVE_IHDR;
  201167. }
  201168. /* write the palette. We are careful not to trust png_color to be in the
  201169. * correct order for PNG, so people can redefine it to any convenient
  201170. * structure.
  201171. */
  201172. void /* PRIVATE */
  201173. png_write_PLTE(png_structp png_ptr, png_colorp palette, png_uint_32 num_pal)
  201174. {
  201175. #ifdef PNG_USE_LOCAL_ARRAYS
  201176. PNG_PLTE;
  201177. #endif
  201178. png_uint_32 i;
  201179. png_colorp pal_ptr;
  201180. png_byte buf[3];
  201181. png_debug(1, "in png_write_PLTE\n");
  201182. if ((
  201183. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201184. !(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) &&
  201185. #endif
  201186. num_pal == 0) || num_pal > 256)
  201187. {
  201188. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  201189. {
  201190. png_error(png_ptr, "Invalid number of colors in palette");
  201191. }
  201192. else
  201193. {
  201194. png_warning(png_ptr, "Invalid number of colors in palette");
  201195. return;
  201196. }
  201197. }
  201198. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  201199. {
  201200. png_warning(png_ptr,
  201201. "Ignoring request to write a PLTE chunk in grayscale PNG");
  201202. return;
  201203. }
  201204. png_ptr->num_palette = (png_uint_16)num_pal;
  201205. png_debug1(3, "num_palette = %d\n", png_ptr->num_palette);
  201206. png_write_chunk_start(png_ptr, png_PLTE, num_pal * 3);
  201207. #ifndef PNG_NO_POINTER_INDEXING
  201208. for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++)
  201209. {
  201210. buf[0] = pal_ptr->red;
  201211. buf[1] = pal_ptr->green;
  201212. buf[2] = pal_ptr->blue;
  201213. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  201214. }
  201215. #else
  201216. /* This is a little slower but some buggy compilers need to do this instead */
  201217. pal_ptr=palette;
  201218. for (i = 0; i < num_pal; i++)
  201219. {
  201220. buf[0] = pal_ptr[i].red;
  201221. buf[1] = pal_ptr[i].green;
  201222. buf[2] = pal_ptr[i].blue;
  201223. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  201224. }
  201225. #endif
  201226. png_write_chunk_end(png_ptr);
  201227. png_ptr->mode |= PNG_HAVE_PLTE;
  201228. }
  201229. /* write an IDAT chunk */
  201230. void /* PRIVATE */
  201231. png_write_IDAT(png_structp png_ptr, png_bytep data, png_size_t length)
  201232. {
  201233. #ifdef PNG_USE_LOCAL_ARRAYS
  201234. PNG_IDAT;
  201235. #endif
  201236. png_debug(1, "in png_write_IDAT\n");
  201237. /* Optimize the CMF field in the zlib stream. */
  201238. /* This hack of the zlib stream is compliant to the stream specification. */
  201239. if (!(png_ptr->mode & PNG_HAVE_IDAT) &&
  201240. png_ptr->compression_type == PNG_COMPRESSION_TYPE_BASE)
  201241. {
  201242. unsigned int z_cmf = data[0]; /* zlib compression method and flags */
  201243. if ((z_cmf & 0x0f) == 8 && (z_cmf & 0xf0) <= 0x70)
  201244. {
  201245. /* Avoid memory underflows and multiplication overflows. */
  201246. /* The conditions below are practically always satisfied;
  201247. however, they still must be checked. */
  201248. if (length >= 2 &&
  201249. png_ptr->height < 16384 && png_ptr->width < 16384)
  201250. {
  201251. png_uint_32 uncompressed_idat_size = png_ptr->height *
  201252. ((png_ptr->width *
  201253. png_ptr->channels * png_ptr->bit_depth + 15) >> 3);
  201254. unsigned int z_cinfo = z_cmf >> 4;
  201255. unsigned int half_z_window_size = 1 << (z_cinfo + 7);
  201256. while (uncompressed_idat_size <= half_z_window_size &&
  201257. half_z_window_size >= 256)
  201258. {
  201259. z_cinfo--;
  201260. half_z_window_size >>= 1;
  201261. }
  201262. z_cmf = (z_cmf & 0x0f) | (z_cinfo << 4);
  201263. if (data[0] != (png_byte)z_cmf)
  201264. {
  201265. data[0] = (png_byte)z_cmf;
  201266. data[1] &= 0xe0;
  201267. data[1] += (png_byte)(0x1f - ((z_cmf << 8) + data[1]) % 0x1f);
  201268. }
  201269. }
  201270. }
  201271. else
  201272. png_error(png_ptr,
  201273. "Invalid zlib compression method or flags in IDAT");
  201274. }
  201275. png_write_chunk(png_ptr, png_IDAT, data, length);
  201276. png_ptr->mode |= PNG_HAVE_IDAT;
  201277. }
  201278. /* write an IEND chunk */
  201279. void /* PRIVATE */
  201280. png_write_IEND(png_structp png_ptr)
  201281. {
  201282. #ifdef PNG_USE_LOCAL_ARRAYS
  201283. PNG_IEND;
  201284. #endif
  201285. png_debug(1, "in png_write_IEND\n");
  201286. png_write_chunk(png_ptr, png_IEND, png_bytep_NULL,
  201287. (png_size_t)0);
  201288. png_ptr->mode |= PNG_HAVE_IEND;
  201289. }
  201290. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  201291. /* write a gAMA chunk */
  201292. #ifdef PNG_FLOATING_POINT_SUPPORTED
  201293. void /* PRIVATE */
  201294. png_write_gAMA(png_structp png_ptr, double file_gamma)
  201295. {
  201296. #ifdef PNG_USE_LOCAL_ARRAYS
  201297. PNG_gAMA;
  201298. #endif
  201299. png_uint_32 igamma;
  201300. png_byte buf[4];
  201301. png_debug(1, "in png_write_gAMA\n");
  201302. /* file_gamma is saved in 1/100,000ths */
  201303. igamma = (png_uint_32)(file_gamma * 100000.0 + 0.5);
  201304. png_save_uint_32(buf, igamma);
  201305. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  201306. }
  201307. #endif
  201308. #ifdef PNG_FIXED_POINT_SUPPORTED
  201309. void /* PRIVATE */
  201310. png_write_gAMA_fixed(png_structp png_ptr, png_fixed_point file_gamma)
  201311. {
  201312. #ifdef PNG_USE_LOCAL_ARRAYS
  201313. PNG_gAMA;
  201314. #endif
  201315. png_byte buf[4];
  201316. png_debug(1, "in png_write_gAMA\n");
  201317. /* file_gamma is saved in 1/100,000ths */
  201318. png_save_uint_32(buf, (png_uint_32)file_gamma);
  201319. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  201320. }
  201321. #endif
  201322. #endif
  201323. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  201324. /* write a sRGB chunk */
  201325. void /* PRIVATE */
  201326. png_write_sRGB(png_structp png_ptr, int srgb_intent)
  201327. {
  201328. #ifdef PNG_USE_LOCAL_ARRAYS
  201329. PNG_sRGB;
  201330. #endif
  201331. png_byte buf[1];
  201332. png_debug(1, "in png_write_sRGB\n");
  201333. if(srgb_intent >= PNG_sRGB_INTENT_LAST)
  201334. png_warning(png_ptr,
  201335. "Invalid sRGB rendering intent specified");
  201336. buf[0]=(png_byte)srgb_intent;
  201337. png_write_chunk(png_ptr, png_sRGB, buf, (png_size_t)1);
  201338. }
  201339. #endif
  201340. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  201341. /* write an iCCP chunk */
  201342. void /* PRIVATE */
  201343. png_write_iCCP(png_structp png_ptr, png_charp name, int compression_type,
  201344. png_charp profile, int profile_len)
  201345. {
  201346. #ifdef PNG_USE_LOCAL_ARRAYS
  201347. PNG_iCCP;
  201348. #endif
  201349. png_size_t name_len;
  201350. png_charp new_name;
  201351. compression_state comp;
  201352. int embedded_profile_len = 0;
  201353. png_debug(1, "in png_write_iCCP\n");
  201354. comp.num_output_ptr = 0;
  201355. comp.max_output_ptr = 0;
  201356. comp.output_ptr = NULL;
  201357. comp.input = NULL;
  201358. comp.input_len = 0;
  201359. if (name == NULL || (name_len = png_check_keyword(png_ptr, name,
  201360. &new_name)) == 0)
  201361. {
  201362. png_warning(png_ptr, "Empty keyword in iCCP chunk");
  201363. return;
  201364. }
  201365. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  201366. png_warning(png_ptr, "Unknown compression type in iCCP chunk");
  201367. if (profile == NULL)
  201368. profile_len = 0;
  201369. if (profile_len > 3)
  201370. embedded_profile_len =
  201371. ((*( (png_bytep)profile ))<<24) |
  201372. ((*( (png_bytep)profile+1))<<16) |
  201373. ((*( (png_bytep)profile+2))<< 8) |
  201374. ((*( (png_bytep)profile+3)) );
  201375. if (profile_len < embedded_profile_len)
  201376. {
  201377. png_warning(png_ptr,
  201378. "Embedded profile length too large in iCCP chunk");
  201379. return;
  201380. }
  201381. if (profile_len > embedded_profile_len)
  201382. {
  201383. png_warning(png_ptr,
  201384. "Truncating profile to actual length in iCCP chunk");
  201385. profile_len = embedded_profile_len;
  201386. }
  201387. if (profile_len)
  201388. profile_len = png_text_compress(png_ptr, profile, (png_size_t)profile_len,
  201389. PNG_COMPRESSION_TYPE_BASE, &comp);
  201390. /* make sure we include the NULL after the name and the compression type */
  201391. png_write_chunk_start(png_ptr, png_iCCP,
  201392. (png_uint_32)name_len+profile_len+2);
  201393. new_name[name_len+1]=0x00;
  201394. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 2);
  201395. if (profile_len)
  201396. png_write_compressed_data_out(png_ptr, &comp);
  201397. png_write_chunk_end(png_ptr);
  201398. png_free(png_ptr, new_name);
  201399. }
  201400. #endif
  201401. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  201402. /* write a sPLT chunk */
  201403. void /* PRIVATE */
  201404. png_write_sPLT(png_structp png_ptr, png_sPLT_tp spalette)
  201405. {
  201406. #ifdef PNG_USE_LOCAL_ARRAYS
  201407. PNG_sPLT;
  201408. #endif
  201409. png_size_t name_len;
  201410. png_charp new_name;
  201411. png_byte entrybuf[10];
  201412. int entry_size = (spalette->depth == 8 ? 6 : 10);
  201413. int palette_size = entry_size * spalette->nentries;
  201414. png_sPLT_entryp ep;
  201415. #ifdef PNG_NO_POINTER_INDEXING
  201416. int i;
  201417. #endif
  201418. png_debug(1, "in png_write_sPLT\n");
  201419. if (spalette->name == NULL || (name_len = png_check_keyword(png_ptr,
  201420. spalette->name, &new_name))==0)
  201421. {
  201422. png_warning(png_ptr, "Empty keyword in sPLT chunk");
  201423. return;
  201424. }
  201425. /* make sure we include the NULL after the name */
  201426. png_write_chunk_start(png_ptr, png_sPLT,
  201427. (png_uint_32)(name_len + 2 + palette_size));
  201428. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 1);
  201429. png_write_chunk_data(png_ptr, (png_bytep)&spalette->depth, 1);
  201430. /* loop through each palette entry, writing appropriately */
  201431. #ifndef PNG_NO_POINTER_INDEXING
  201432. for (ep = spalette->entries; ep<spalette->entries+spalette->nentries; ep++)
  201433. {
  201434. if (spalette->depth == 8)
  201435. {
  201436. entrybuf[0] = (png_byte)ep->red;
  201437. entrybuf[1] = (png_byte)ep->green;
  201438. entrybuf[2] = (png_byte)ep->blue;
  201439. entrybuf[3] = (png_byte)ep->alpha;
  201440. png_save_uint_16(entrybuf + 4, ep->frequency);
  201441. }
  201442. else
  201443. {
  201444. png_save_uint_16(entrybuf + 0, ep->red);
  201445. png_save_uint_16(entrybuf + 2, ep->green);
  201446. png_save_uint_16(entrybuf + 4, ep->blue);
  201447. png_save_uint_16(entrybuf + 6, ep->alpha);
  201448. png_save_uint_16(entrybuf + 8, ep->frequency);
  201449. }
  201450. png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
  201451. }
  201452. #else
  201453. ep=spalette->entries;
  201454. for (i=0; i>spalette->nentries; i++)
  201455. {
  201456. if (spalette->depth == 8)
  201457. {
  201458. entrybuf[0] = (png_byte)ep[i].red;
  201459. entrybuf[1] = (png_byte)ep[i].green;
  201460. entrybuf[2] = (png_byte)ep[i].blue;
  201461. entrybuf[3] = (png_byte)ep[i].alpha;
  201462. png_save_uint_16(entrybuf + 4, ep[i].frequency);
  201463. }
  201464. else
  201465. {
  201466. png_save_uint_16(entrybuf + 0, ep[i].red);
  201467. png_save_uint_16(entrybuf + 2, ep[i].green);
  201468. png_save_uint_16(entrybuf + 4, ep[i].blue);
  201469. png_save_uint_16(entrybuf + 6, ep[i].alpha);
  201470. png_save_uint_16(entrybuf + 8, ep[i].frequency);
  201471. }
  201472. png_write_chunk_data(png_ptr, entrybuf, entry_size);
  201473. }
  201474. #endif
  201475. png_write_chunk_end(png_ptr);
  201476. png_free(png_ptr, new_name);
  201477. }
  201478. #endif
  201479. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  201480. /* write the sBIT chunk */
  201481. void /* PRIVATE */
  201482. png_write_sBIT(png_structp png_ptr, png_color_8p sbit, int color_type)
  201483. {
  201484. #ifdef PNG_USE_LOCAL_ARRAYS
  201485. PNG_sBIT;
  201486. #endif
  201487. png_byte buf[4];
  201488. png_size_t size;
  201489. png_debug(1, "in png_write_sBIT\n");
  201490. /* make sure we don't depend upon the order of PNG_COLOR_8 */
  201491. if (color_type & PNG_COLOR_MASK_COLOR)
  201492. {
  201493. png_byte maxbits;
  201494. maxbits = (png_byte)(color_type==PNG_COLOR_TYPE_PALETTE ? 8 :
  201495. png_ptr->usr_bit_depth);
  201496. if (sbit->red == 0 || sbit->red > maxbits ||
  201497. sbit->green == 0 || sbit->green > maxbits ||
  201498. sbit->blue == 0 || sbit->blue > maxbits)
  201499. {
  201500. png_warning(png_ptr, "Invalid sBIT depth specified");
  201501. return;
  201502. }
  201503. buf[0] = sbit->red;
  201504. buf[1] = sbit->green;
  201505. buf[2] = sbit->blue;
  201506. size = 3;
  201507. }
  201508. else
  201509. {
  201510. if (sbit->gray == 0 || sbit->gray > png_ptr->usr_bit_depth)
  201511. {
  201512. png_warning(png_ptr, "Invalid sBIT depth specified");
  201513. return;
  201514. }
  201515. buf[0] = sbit->gray;
  201516. size = 1;
  201517. }
  201518. if (color_type & PNG_COLOR_MASK_ALPHA)
  201519. {
  201520. if (sbit->alpha == 0 || sbit->alpha > png_ptr->usr_bit_depth)
  201521. {
  201522. png_warning(png_ptr, "Invalid sBIT depth specified");
  201523. return;
  201524. }
  201525. buf[size++] = sbit->alpha;
  201526. }
  201527. png_write_chunk(png_ptr, png_sBIT, buf, size);
  201528. }
  201529. #endif
  201530. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  201531. /* write the cHRM chunk */
  201532. #ifdef PNG_FLOATING_POINT_SUPPORTED
  201533. void /* PRIVATE */
  201534. png_write_cHRM(png_structp png_ptr, double white_x, double white_y,
  201535. double red_x, double red_y, double green_x, double green_y,
  201536. double blue_x, double blue_y)
  201537. {
  201538. #ifdef PNG_USE_LOCAL_ARRAYS
  201539. PNG_cHRM;
  201540. #endif
  201541. png_byte buf[32];
  201542. png_uint_32 itemp;
  201543. png_debug(1, "in png_write_cHRM\n");
  201544. /* each value is saved in 1/100,000ths */
  201545. if (white_x < 0 || white_x > 0.8 || white_y < 0 || white_y > 0.8 ||
  201546. white_x + white_y > 1.0)
  201547. {
  201548. png_warning(png_ptr, "Invalid cHRM white point specified");
  201549. #if !defined(PNG_NO_CONSOLE_IO)
  201550. fprintf(stderr,"white_x=%f, white_y=%f\n",white_x, white_y);
  201551. #endif
  201552. return;
  201553. }
  201554. itemp = (png_uint_32)(white_x * 100000.0 + 0.5);
  201555. png_save_uint_32(buf, itemp);
  201556. itemp = (png_uint_32)(white_y * 100000.0 + 0.5);
  201557. png_save_uint_32(buf + 4, itemp);
  201558. if (red_x < 0 || red_y < 0 || red_x + red_y > 1.0)
  201559. {
  201560. png_warning(png_ptr, "Invalid cHRM red point specified");
  201561. return;
  201562. }
  201563. itemp = (png_uint_32)(red_x * 100000.0 + 0.5);
  201564. png_save_uint_32(buf + 8, itemp);
  201565. itemp = (png_uint_32)(red_y * 100000.0 + 0.5);
  201566. png_save_uint_32(buf + 12, itemp);
  201567. if (green_x < 0 || green_y < 0 || green_x + green_y > 1.0)
  201568. {
  201569. png_warning(png_ptr, "Invalid cHRM green point specified");
  201570. return;
  201571. }
  201572. itemp = (png_uint_32)(green_x * 100000.0 + 0.5);
  201573. png_save_uint_32(buf + 16, itemp);
  201574. itemp = (png_uint_32)(green_y * 100000.0 + 0.5);
  201575. png_save_uint_32(buf + 20, itemp);
  201576. if (blue_x < 0 || blue_y < 0 || blue_x + blue_y > 1.0)
  201577. {
  201578. png_warning(png_ptr, "Invalid cHRM blue point specified");
  201579. return;
  201580. }
  201581. itemp = (png_uint_32)(blue_x * 100000.0 + 0.5);
  201582. png_save_uint_32(buf + 24, itemp);
  201583. itemp = (png_uint_32)(blue_y * 100000.0 + 0.5);
  201584. png_save_uint_32(buf + 28, itemp);
  201585. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  201586. }
  201587. #endif
  201588. #ifdef PNG_FIXED_POINT_SUPPORTED
  201589. void /* PRIVATE */
  201590. png_write_cHRM_fixed(png_structp png_ptr, png_fixed_point white_x,
  201591. png_fixed_point white_y, png_fixed_point red_x, png_fixed_point red_y,
  201592. png_fixed_point green_x, png_fixed_point green_y, png_fixed_point blue_x,
  201593. png_fixed_point blue_y)
  201594. {
  201595. #ifdef PNG_USE_LOCAL_ARRAYS
  201596. PNG_cHRM;
  201597. #endif
  201598. png_byte buf[32];
  201599. png_debug(1, "in png_write_cHRM\n");
  201600. /* each value is saved in 1/100,000ths */
  201601. if (white_x > 80000L || white_y > 80000L || white_x + white_y > 100000L)
  201602. {
  201603. png_warning(png_ptr, "Invalid fixed cHRM white point specified");
  201604. #if !defined(PNG_NO_CONSOLE_IO)
  201605. fprintf(stderr,"white_x=%ld, white_y=%ld\n",white_x, white_y);
  201606. #endif
  201607. return;
  201608. }
  201609. png_save_uint_32(buf, (png_uint_32)white_x);
  201610. png_save_uint_32(buf + 4, (png_uint_32)white_y);
  201611. if (red_x + red_y > 100000L)
  201612. {
  201613. png_warning(png_ptr, "Invalid cHRM fixed red point specified");
  201614. return;
  201615. }
  201616. png_save_uint_32(buf + 8, (png_uint_32)red_x);
  201617. png_save_uint_32(buf + 12, (png_uint_32)red_y);
  201618. if (green_x + green_y > 100000L)
  201619. {
  201620. png_warning(png_ptr, "Invalid fixed cHRM green point specified");
  201621. return;
  201622. }
  201623. png_save_uint_32(buf + 16, (png_uint_32)green_x);
  201624. png_save_uint_32(buf + 20, (png_uint_32)green_y);
  201625. if (blue_x + blue_y > 100000L)
  201626. {
  201627. png_warning(png_ptr, "Invalid fixed cHRM blue point specified");
  201628. return;
  201629. }
  201630. png_save_uint_32(buf + 24, (png_uint_32)blue_x);
  201631. png_save_uint_32(buf + 28, (png_uint_32)blue_y);
  201632. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  201633. }
  201634. #endif
  201635. #endif
  201636. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  201637. /* write the tRNS chunk */
  201638. void /* PRIVATE */
  201639. png_write_tRNS(png_structp png_ptr, png_bytep trans, png_color_16p tran,
  201640. int num_trans, int color_type)
  201641. {
  201642. #ifdef PNG_USE_LOCAL_ARRAYS
  201643. PNG_tRNS;
  201644. #endif
  201645. png_byte buf[6];
  201646. png_debug(1, "in png_write_tRNS\n");
  201647. if (color_type == PNG_COLOR_TYPE_PALETTE)
  201648. {
  201649. if (num_trans <= 0 || num_trans > (int)png_ptr->num_palette)
  201650. {
  201651. png_warning(png_ptr,"Invalid number of transparent colors specified");
  201652. return;
  201653. }
  201654. /* write the chunk out as it is */
  201655. png_write_chunk(png_ptr, png_tRNS, trans, (png_size_t)num_trans);
  201656. }
  201657. else if (color_type == PNG_COLOR_TYPE_GRAY)
  201658. {
  201659. /* one 16 bit value */
  201660. if(tran->gray >= (1 << png_ptr->bit_depth))
  201661. {
  201662. png_warning(png_ptr,
  201663. "Ignoring attempt to write tRNS chunk out-of-range for bit_depth");
  201664. return;
  201665. }
  201666. png_save_uint_16(buf, tran->gray);
  201667. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)2);
  201668. }
  201669. else if (color_type == PNG_COLOR_TYPE_RGB)
  201670. {
  201671. /* three 16 bit values */
  201672. png_save_uint_16(buf, tran->red);
  201673. png_save_uint_16(buf + 2, tran->green);
  201674. png_save_uint_16(buf + 4, tran->blue);
  201675. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  201676. {
  201677. png_warning(png_ptr,
  201678. "Ignoring attempt to write 16-bit tRNS chunk when bit_depth is 8");
  201679. return;
  201680. }
  201681. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)6);
  201682. }
  201683. else
  201684. {
  201685. png_warning(png_ptr, "Can't write tRNS with an alpha channel");
  201686. }
  201687. }
  201688. #endif
  201689. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  201690. /* write the background chunk */
  201691. void /* PRIVATE */
  201692. png_write_bKGD(png_structp png_ptr, png_color_16p back, int color_type)
  201693. {
  201694. #ifdef PNG_USE_LOCAL_ARRAYS
  201695. PNG_bKGD;
  201696. #endif
  201697. png_byte buf[6];
  201698. png_debug(1, "in png_write_bKGD\n");
  201699. if (color_type == PNG_COLOR_TYPE_PALETTE)
  201700. {
  201701. if (
  201702. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201703. (png_ptr->num_palette ||
  201704. (!(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE))) &&
  201705. #endif
  201706. back->index > png_ptr->num_palette)
  201707. {
  201708. png_warning(png_ptr, "Invalid background palette index");
  201709. return;
  201710. }
  201711. buf[0] = back->index;
  201712. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)1);
  201713. }
  201714. else if (color_type & PNG_COLOR_MASK_COLOR)
  201715. {
  201716. png_save_uint_16(buf, back->red);
  201717. png_save_uint_16(buf + 2, back->green);
  201718. png_save_uint_16(buf + 4, back->blue);
  201719. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  201720. {
  201721. png_warning(png_ptr,
  201722. "Ignoring attempt to write 16-bit bKGD chunk when bit_depth is 8");
  201723. return;
  201724. }
  201725. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)6);
  201726. }
  201727. else
  201728. {
  201729. if(back->gray >= (1 << png_ptr->bit_depth))
  201730. {
  201731. png_warning(png_ptr,
  201732. "Ignoring attempt to write bKGD chunk out-of-range for bit_depth");
  201733. return;
  201734. }
  201735. png_save_uint_16(buf, back->gray);
  201736. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)2);
  201737. }
  201738. }
  201739. #endif
  201740. #if defined(PNG_WRITE_hIST_SUPPORTED)
  201741. /* write the histogram */
  201742. void /* PRIVATE */
  201743. png_write_hIST(png_structp png_ptr, png_uint_16p hist, int num_hist)
  201744. {
  201745. #ifdef PNG_USE_LOCAL_ARRAYS
  201746. PNG_hIST;
  201747. #endif
  201748. int i;
  201749. png_byte buf[3];
  201750. png_debug(1, "in png_write_hIST\n");
  201751. if (num_hist > (int)png_ptr->num_palette)
  201752. {
  201753. png_debug2(3, "num_hist = %d, num_palette = %d\n", num_hist,
  201754. png_ptr->num_palette);
  201755. png_warning(png_ptr, "Invalid number of histogram entries specified");
  201756. return;
  201757. }
  201758. png_write_chunk_start(png_ptr, png_hIST, (png_uint_32)(num_hist * 2));
  201759. for (i = 0; i < num_hist; i++)
  201760. {
  201761. png_save_uint_16(buf, hist[i]);
  201762. png_write_chunk_data(png_ptr, buf, (png_size_t)2);
  201763. }
  201764. png_write_chunk_end(png_ptr);
  201765. }
  201766. #endif
  201767. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  201768. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  201769. /* Check that the tEXt or zTXt keyword is valid per PNG 1.0 specification,
  201770. * and if invalid, correct the keyword rather than discarding the entire
  201771. * chunk. The PNG 1.0 specification requires keywords 1-79 characters in
  201772. * length, forbids leading or trailing whitespace, multiple internal spaces,
  201773. * and the non-break space (0x80) from ISO 8859-1. Returns keyword length.
  201774. *
  201775. * The new_key is allocated to hold the corrected keyword and must be freed
  201776. * by the calling routine. This avoids problems with trying to write to
  201777. * static keywords without having to have duplicate copies of the strings.
  201778. */
  201779. png_size_t /* PRIVATE */
  201780. png_check_keyword(png_structp png_ptr, png_charp key, png_charpp new_key)
  201781. {
  201782. png_size_t key_len;
  201783. png_charp kp, dp;
  201784. int kflag;
  201785. int kwarn=0;
  201786. png_debug(1, "in png_check_keyword\n");
  201787. *new_key = NULL;
  201788. if (key == NULL || (key_len = png_strlen(key)) == 0)
  201789. {
  201790. png_warning(png_ptr, "zero length keyword");
  201791. return ((png_size_t)0);
  201792. }
  201793. png_debug1(2, "Keyword to be checked is '%s'\n", key);
  201794. *new_key = (png_charp)png_malloc_warn(png_ptr, (png_uint_32)(key_len + 2));
  201795. if (*new_key == NULL)
  201796. {
  201797. png_warning(png_ptr, "Out of memory while procesing keyword");
  201798. return ((png_size_t)0);
  201799. }
  201800. /* Replace non-printing characters with a blank and print a warning */
  201801. for (kp = key, dp = *new_key; *kp != '\0'; kp++, dp++)
  201802. {
  201803. if ((png_byte)*kp < 0x20 ||
  201804. ((png_byte)*kp > 0x7E && (png_byte)*kp < 0xA1))
  201805. {
  201806. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  201807. char msg[40];
  201808. png_snprintf(msg, 40,
  201809. "invalid keyword character 0x%02X", (png_byte)*kp);
  201810. png_warning(png_ptr, msg);
  201811. #else
  201812. png_warning(png_ptr, "invalid character in keyword");
  201813. #endif
  201814. *dp = ' ';
  201815. }
  201816. else
  201817. {
  201818. *dp = *kp;
  201819. }
  201820. }
  201821. *dp = '\0';
  201822. /* Remove any trailing white space. */
  201823. kp = *new_key + key_len - 1;
  201824. if (*kp == ' ')
  201825. {
  201826. png_warning(png_ptr, "trailing spaces removed from keyword");
  201827. while (*kp == ' ')
  201828. {
  201829. *(kp--) = '\0';
  201830. key_len--;
  201831. }
  201832. }
  201833. /* Remove any leading white space. */
  201834. kp = *new_key;
  201835. if (*kp == ' ')
  201836. {
  201837. png_warning(png_ptr, "leading spaces removed from keyword");
  201838. while (*kp == ' ')
  201839. {
  201840. kp++;
  201841. key_len--;
  201842. }
  201843. }
  201844. png_debug1(2, "Checking for multiple internal spaces in '%s'\n", kp);
  201845. /* Remove multiple internal spaces. */
  201846. for (kflag = 0, dp = *new_key; *kp != '\0'; kp++)
  201847. {
  201848. if (*kp == ' ' && kflag == 0)
  201849. {
  201850. *(dp++) = *kp;
  201851. kflag = 1;
  201852. }
  201853. else if (*kp == ' ')
  201854. {
  201855. key_len--;
  201856. kwarn=1;
  201857. }
  201858. else
  201859. {
  201860. *(dp++) = *kp;
  201861. kflag = 0;
  201862. }
  201863. }
  201864. *dp = '\0';
  201865. if(kwarn)
  201866. png_warning(png_ptr, "extra interior spaces removed from keyword");
  201867. if (key_len == 0)
  201868. {
  201869. png_free(png_ptr, *new_key);
  201870. *new_key=NULL;
  201871. png_warning(png_ptr, "Zero length keyword");
  201872. }
  201873. if (key_len > 79)
  201874. {
  201875. png_warning(png_ptr, "keyword length must be 1 - 79 characters");
  201876. new_key[79] = '\0';
  201877. key_len = 79;
  201878. }
  201879. return (key_len);
  201880. }
  201881. #endif
  201882. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  201883. /* write a tEXt chunk */
  201884. void /* PRIVATE */
  201885. png_write_tEXt(png_structp png_ptr, png_charp key, png_charp text,
  201886. png_size_t text_len)
  201887. {
  201888. #ifdef PNG_USE_LOCAL_ARRAYS
  201889. PNG_tEXt;
  201890. #endif
  201891. png_size_t key_len;
  201892. png_charp new_key;
  201893. png_debug(1, "in png_write_tEXt\n");
  201894. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  201895. {
  201896. png_warning(png_ptr, "Empty keyword in tEXt chunk");
  201897. return;
  201898. }
  201899. if (text == NULL || *text == '\0')
  201900. text_len = 0;
  201901. else
  201902. text_len = png_strlen(text);
  201903. /* make sure we include the 0 after the key */
  201904. png_write_chunk_start(png_ptr, png_tEXt, (png_uint_32)key_len+text_len+1);
  201905. /*
  201906. * We leave it to the application to meet PNG-1.0 requirements on the
  201907. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  201908. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  201909. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  201910. */
  201911. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  201912. if (text_len)
  201913. png_write_chunk_data(png_ptr, (png_bytep)text, text_len);
  201914. png_write_chunk_end(png_ptr);
  201915. png_free(png_ptr, new_key);
  201916. }
  201917. #endif
  201918. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  201919. /* write a compressed text chunk */
  201920. void /* PRIVATE */
  201921. png_write_zTXt(png_structp png_ptr, png_charp key, png_charp text,
  201922. png_size_t text_len, int compression)
  201923. {
  201924. #ifdef PNG_USE_LOCAL_ARRAYS
  201925. PNG_zTXt;
  201926. #endif
  201927. png_size_t key_len;
  201928. char buf[1];
  201929. png_charp new_key;
  201930. compression_state comp;
  201931. png_debug(1, "in png_write_zTXt\n");
  201932. comp.num_output_ptr = 0;
  201933. comp.max_output_ptr = 0;
  201934. comp.output_ptr = NULL;
  201935. comp.input = NULL;
  201936. comp.input_len = 0;
  201937. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  201938. {
  201939. png_warning(png_ptr, "Empty keyword in zTXt chunk");
  201940. return;
  201941. }
  201942. if (text == NULL || *text == '\0' || compression==PNG_TEXT_COMPRESSION_NONE)
  201943. {
  201944. png_write_tEXt(png_ptr, new_key, text, (png_size_t)0);
  201945. png_free(png_ptr, new_key);
  201946. return;
  201947. }
  201948. text_len = png_strlen(text);
  201949. /* compute the compressed data; do it now for the length */
  201950. text_len = png_text_compress(png_ptr, text, text_len, compression,
  201951. &comp);
  201952. /* write start of chunk */
  201953. png_write_chunk_start(png_ptr, png_zTXt, (png_uint_32)
  201954. (key_len+text_len+2));
  201955. /* write key */
  201956. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  201957. png_free(png_ptr, new_key);
  201958. buf[0] = (png_byte)compression;
  201959. /* write compression */
  201960. png_write_chunk_data(png_ptr, (png_bytep)buf, (png_size_t)1);
  201961. /* write the compressed data */
  201962. png_write_compressed_data_out(png_ptr, &comp);
  201963. /* close the chunk */
  201964. png_write_chunk_end(png_ptr);
  201965. }
  201966. #endif
  201967. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  201968. /* write an iTXt chunk */
  201969. void /* PRIVATE */
  201970. png_write_iTXt(png_structp png_ptr, int compression, png_charp key,
  201971. png_charp lang, png_charp lang_key, png_charp text)
  201972. {
  201973. #ifdef PNG_USE_LOCAL_ARRAYS
  201974. PNG_iTXt;
  201975. #endif
  201976. png_size_t lang_len, key_len, lang_key_len, text_len;
  201977. png_charp new_lang, new_key;
  201978. png_byte cbuf[2];
  201979. compression_state comp;
  201980. png_debug(1, "in png_write_iTXt\n");
  201981. comp.num_output_ptr = 0;
  201982. comp.max_output_ptr = 0;
  201983. comp.output_ptr = NULL;
  201984. comp.input = NULL;
  201985. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  201986. {
  201987. png_warning(png_ptr, "Empty keyword in iTXt chunk");
  201988. return;
  201989. }
  201990. if (lang == NULL || (lang_len = png_check_keyword(png_ptr, lang, &new_lang))==0)
  201991. {
  201992. png_warning(png_ptr, "Empty language field in iTXt chunk");
  201993. new_lang = NULL;
  201994. lang_len = 0;
  201995. }
  201996. if (lang_key == NULL)
  201997. lang_key_len = 0;
  201998. else
  201999. lang_key_len = png_strlen(lang_key);
  202000. if (text == NULL)
  202001. text_len = 0;
  202002. else
  202003. text_len = png_strlen(text);
  202004. /* compute the compressed data; do it now for the length */
  202005. text_len = png_text_compress(png_ptr, text, text_len, compression-2,
  202006. &comp);
  202007. /* make sure we include the compression flag, the compression byte,
  202008. * and the NULs after the key, lang, and lang_key parts */
  202009. png_write_chunk_start(png_ptr, png_iTXt,
  202010. (png_uint_32)(
  202011. 5 /* comp byte, comp flag, terminators for key, lang and lang_key */
  202012. + key_len
  202013. + lang_len
  202014. + lang_key_len
  202015. + text_len));
  202016. /*
  202017. * We leave it to the application to meet PNG-1.0 requirements on the
  202018. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  202019. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  202020. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  202021. */
  202022. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  202023. /* set the compression flag */
  202024. if (compression == PNG_ITXT_COMPRESSION_NONE || \
  202025. compression == PNG_TEXT_COMPRESSION_NONE)
  202026. cbuf[0] = 0;
  202027. else /* compression == PNG_ITXT_COMPRESSION_zTXt */
  202028. cbuf[0] = 1;
  202029. /* set the compression method */
  202030. cbuf[1] = 0;
  202031. png_write_chunk_data(png_ptr, cbuf, 2);
  202032. cbuf[0] = 0;
  202033. png_write_chunk_data(png_ptr, (new_lang ? (png_bytep)new_lang : cbuf), lang_len + 1);
  202034. png_write_chunk_data(png_ptr, (lang_key ? (png_bytep)lang_key : cbuf), lang_key_len + 1);
  202035. png_write_compressed_data_out(png_ptr, &comp);
  202036. png_write_chunk_end(png_ptr);
  202037. png_free(png_ptr, new_key);
  202038. if (new_lang)
  202039. png_free(png_ptr, new_lang);
  202040. }
  202041. #endif
  202042. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  202043. /* write the oFFs chunk */
  202044. void /* PRIVATE */
  202045. png_write_oFFs(png_structp png_ptr, png_int_32 x_offset, png_int_32 y_offset,
  202046. int unit_type)
  202047. {
  202048. #ifdef PNG_USE_LOCAL_ARRAYS
  202049. PNG_oFFs;
  202050. #endif
  202051. png_byte buf[9];
  202052. png_debug(1, "in png_write_oFFs\n");
  202053. if (unit_type >= PNG_OFFSET_LAST)
  202054. png_warning(png_ptr, "Unrecognized unit type for oFFs chunk");
  202055. png_save_int_32(buf, x_offset);
  202056. png_save_int_32(buf + 4, y_offset);
  202057. buf[8] = (png_byte)unit_type;
  202058. png_write_chunk(png_ptr, png_oFFs, buf, (png_size_t)9);
  202059. }
  202060. #endif
  202061. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  202062. /* write the pCAL chunk (described in the PNG extensions document) */
  202063. void /* PRIVATE */
  202064. png_write_pCAL(png_structp png_ptr, png_charp purpose, png_int_32 X0,
  202065. png_int_32 X1, int type, int nparams, png_charp units, png_charpp params)
  202066. {
  202067. #ifdef PNG_USE_LOCAL_ARRAYS
  202068. PNG_pCAL;
  202069. #endif
  202070. png_size_t purpose_len, units_len, total_len;
  202071. png_uint_32p params_len;
  202072. png_byte buf[10];
  202073. png_charp new_purpose;
  202074. int i;
  202075. png_debug1(1, "in png_write_pCAL (%d parameters)\n", nparams);
  202076. if (type >= PNG_EQUATION_LAST)
  202077. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  202078. purpose_len = png_check_keyword(png_ptr, purpose, &new_purpose) + 1;
  202079. png_debug1(3, "pCAL purpose length = %d\n", (int)purpose_len);
  202080. units_len = png_strlen(units) + (nparams == 0 ? 0 : 1);
  202081. png_debug1(3, "pCAL units length = %d\n", (int)units_len);
  202082. total_len = purpose_len + units_len + 10;
  202083. params_len = (png_uint_32p)png_malloc(png_ptr, (png_uint_32)(nparams
  202084. *png_sizeof(png_uint_32)));
  202085. /* Find the length of each parameter, making sure we don't count the
  202086. null terminator for the last parameter. */
  202087. for (i = 0; i < nparams; i++)
  202088. {
  202089. params_len[i] = png_strlen(params[i]) + (i == nparams - 1 ? 0 : 1);
  202090. png_debug2(3, "pCAL parameter %d length = %lu\n", i, params_len[i]);
  202091. total_len += (png_size_t)params_len[i];
  202092. }
  202093. png_debug1(3, "pCAL total length = %d\n", (int)total_len);
  202094. png_write_chunk_start(png_ptr, png_pCAL, (png_uint_32)total_len);
  202095. png_write_chunk_data(png_ptr, (png_bytep)new_purpose, purpose_len);
  202096. png_save_int_32(buf, X0);
  202097. png_save_int_32(buf + 4, X1);
  202098. buf[8] = (png_byte)type;
  202099. buf[9] = (png_byte)nparams;
  202100. png_write_chunk_data(png_ptr, buf, (png_size_t)10);
  202101. png_write_chunk_data(png_ptr, (png_bytep)units, (png_size_t)units_len);
  202102. png_free(png_ptr, new_purpose);
  202103. for (i = 0; i < nparams; i++)
  202104. {
  202105. png_write_chunk_data(png_ptr, (png_bytep)params[i],
  202106. (png_size_t)params_len[i]);
  202107. }
  202108. png_free(png_ptr, params_len);
  202109. png_write_chunk_end(png_ptr);
  202110. }
  202111. #endif
  202112. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  202113. /* write the sCAL chunk */
  202114. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  202115. void /* PRIVATE */
  202116. png_write_sCAL(png_structp png_ptr, int unit, double width, double height)
  202117. {
  202118. #ifdef PNG_USE_LOCAL_ARRAYS
  202119. PNG_sCAL;
  202120. #endif
  202121. char buf[64];
  202122. png_size_t total_len;
  202123. png_debug(1, "in png_write_sCAL\n");
  202124. buf[0] = (char)unit;
  202125. #if defined(_WIN32_WCE)
  202126. /* sprintf() function is not supported on WindowsCE */
  202127. {
  202128. wchar_t wc_buf[32];
  202129. size_t wc_len;
  202130. swprintf(wc_buf, TEXT("%12.12e"), width);
  202131. wc_len = wcslen(wc_buf);
  202132. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + 1, wc_len, NULL, NULL);
  202133. total_len = wc_len + 2;
  202134. swprintf(wc_buf, TEXT("%12.12e"), height);
  202135. wc_len = wcslen(wc_buf);
  202136. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + total_len, wc_len,
  202137. NULL, NULL);
  202138. total_len += wc_len;
  202139. }
  202140. #else
  202141. png_snprintf(buf + 1, 63, "%12.12e", width);
  202142. total_len = 1 + png_strlen(buf + 1) + 1;
  202143. png_snprintf(buf + total_len, 64-total_len, "%12.12e", height);
  202144. total_len += png_strlen(buf + total_len);
  202145. #endif
  202146. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  202147. png_write_chunk(png_ptr, png_sCAL, (png_bytep)buf, total_len);
  202148. }
  202149. #else
  202150. #ifdef PNG_FIXED_POINT_SUPPORTED
  202151. void /* PRIVATE */
  202152. png_write_sCAL_s(png_structp png_ptr, int unit, png_charp width,
  202153. png_charp height)
  202154. {
  202155. #ifdef PNG_USE_LOCAL_ARRAYS
  202156. PNG_sCAL;
  202157. #endif
  202158. png_byte buf[64];
  202159. png_size_t wlen, hlen, total_len;
  202160. png_debug(1, "in png_write_sCAL_s\n");
  202161. wlen = png_strlen(width);
  202162. hlen = png_strlen(height);
  202163. total_len = wlen + hlen + 2;
  202164. if (total_len > 64)
  202165. {
  202166. png_warning(png_ptr, "Can't write sCAL (buffer too small)");
  202167. return;
  202168. }
  202169. buf[0] = (png_byte)unit;
  202170. png_memcpy(buf + 1, width, wlen + 1); /* append the '\0' here */
  202171. png_memcpy(buf + wlen + 2, height, hlen); /* do NOT append the '\0' here */
  202172. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  202173. png_write_chunk(png_ptr, png_sCAL, buf, total_len);
  202174. }
  202175. #endif
  202176. #endif
  202177. #endif
  202178. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  202179. /* write the pHYs chunk */
  202180. void /* PRIVATE */
  202181. png_write_pHYs(png_structp png_ptr, png_uint_32 x_pixels_per_unit,
  202182. png_uint_32 y_pixels_per_unit,
  202183. int unit_type)
  202184. {
  202185. #ifdef PNG_USE_LOCAL_ARRAYS
  202186. PNG_pHYs;
  202187. #endif
  202188. png_byte buf[9];
  202189. png_debug(1, "in png_write_pHYs\n");
  202190. if (unit_type >= PNG_RESOLUTION_LAST)
  202191. png_warning(png_ptr, "Unrecognized unit type for pHYs chunk");
  202192. png_save_uint_32(buf, x_pixels_per_unit);
  202193. png_save_uint_32(buf + 4, y_pixels_per_unit);
  202194. buf[8] = (png_byte)unit_type;
  202195. png_write_chunk(png_ptr, png_pHYs, buf, (png_size_t)9);
  202196. }
  202197. #endif
  202198. #if defined(PNG_WRITE_tIME_SUPPORTED)
  202199. /* Write the tIME chunk. Use either png_convert_from_struct_tm()
  202200. * or png_convert_from_time_t(), or fill in the structure yourself.
  202201. */
  202202. void /* PRIVATE */
  202203. png_write_tIME(png_structp png_ptr, png_timep mod_time)
  202204. {
  202205. #ifdef PNG_USE_LOCAL_ARRAYS
  202206. PNG_tIME;
  202207. #endif
  202208. png_byte buf[7];
  202209. png_debug(1, "in png_write_tIME\n");
  202210. if (mod_time->month > 12 || mod_time->month < 1 ||
  202211. mod_time->day > 31 || mod_time->day < 1 ||
  202212. mod_time->hour > 23 || mod_time->second > 60)
  202213. {
  202214. png_warning(png_ptr, "Invalid time specified for tIME chunk");
  202215. return;
  202216. }
  202217. png_save_uint_16(buf, mod_time->year);
  202218. buf[2] = mod_time->month;
  202219. buf[3] = mod_time->day;
  202220. buf[4] = mod_time->hour;
  202221. buf[5] = mod_time->minute;
  202222. buf[6] = mod_time->second;
  202223. png_write_chunk(png_ptr, png_tIME, buf, (png_size_t)7);
  202224. }
  202225. #endif
  202226. /* initializes the row writing capability of libpng */
  202227. void /* PRIVATE */
  202228. png_write_start_row(png_structp png_ptr)
  202229. {
  202230. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202231. #ifdef PNG_USE_LOCAL_ARRAYS
  202232. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  202233. /* start of interlace block */
  202234. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  202235. /* offset to next interlace block */
  202236. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  202237. /* start of interlace block in the y direction */
  202238. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  202239. /* offset to next interlace block in the y direction */
  202240. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  202241. #endif
  202242. #endif
  202243. png_size_t buf_size;
  202244. png_debug(1, "in png_write_start_row\n");
  202245. buf_size = (png_size_t)(PNG_ROWBYTES(
  202246. png_ptr->usr_channels*png_ptr->usr_bit_depth,png_ptr->width)+1);
  202247. /* set up row buffer */
  202248. png_ptr->row_buf = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  202249. png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE;
  202250. #ifndef PNG_NO_WRITE_FILTERING
  202251. /* set up filtering buffer, if using this filter */
  202252. if (png_ptr->do_filter & PNG_FILTER_SUB)
  202253. {
  202254. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  202255. (png_ptr->rowbytes + 1));
  202256. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  202257. }
  202258. /* We only need to keep the previous row if we are using one of these. */
  202259. if (png_ptr->do_filter & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH))
  202260. {
  202261. /* set up previous row buffer */
  202262. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  202263. png_memset(png_ptr->prev_row, 0, buf_size);
  202264. if (png_ptr->do_filter & PNG_FILTER_UP)
  202265. {
  202266. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  202267. (png_ptr->rowbytes + 1));
  202268. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  202269. }
  202270. if (png_ptr->do_filter & PNG_FILTER_AVG)
  202271. {
  202272. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  202273. (png_ptr->rowbytes + 1));
  202274. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  202275. }
  202276. if (png_ptr->do_filter & PNG_FILTER_PAETH)
  202277. {
  202278. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  202279. (png_ptr->rowbytes + 1));
  202280. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  202281. }
  202282. #endif /* PNG_NO_WRITE_FILTERING */
  202283. }
  202284. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202285. /* if interlaced, we need to set up width and height of pass */
  202286. if (png_ptr->interlaced)
  202287. {
  202288. if (!(png_ptr->transformations & PNG_INTERLACE))
  202289. {
  202290. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  202291. png_pass_ystart[0]) / png_pass_yinc[0];
  202292. png_ptr->usr_width = (png_ptr->width + png_pass_inc[0] - 1 -
  202293. png_pass_start[0]) / png_pass_inc[0];
  202294. }
  202295. else
  202296. {
  202297. png_ptr->num_rows = png_ptr->height;
  202298. png_ptr->usr_width = png_ptr->width;
  202299. }
  202300. }
  202301. else
  202302. #endif
  202303. {
  202304. png_ptr->num_rows = png_ptr->height;
  202305. png_ptr->usr_width = png_ptr->width;
  202306. }
  202307. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  202308. png_ptr->zstream.next_out = png_ptr->zbuf;
  202309. }
  202310. /* Internal use only. Called when finished processing a row of data. */
  202311. void /* PRIVATE */
  202312. png_write_finish_row(png_structp png_ptr)
  202313. {
  202314. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202315. #ifdef PNG_USE_LOCAL_ARRAYS
  202316. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  202317. /* start of interlace block */
  202318. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  202319. /* offset to next interlace block */
  202320. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  202321. /* start of interlace block in the y direction */
  202322. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  202323. /* offset to next interlace block in the y direction */
  202324. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  202325. #endif
  202326. #endif
  202327. int ret;
  202328. png_debug(1, "in png_write_finish_row\n");
  202329. /* next row */
  202330. png_ptr->row_number++;
  202331. /* see if we are done */
  202332. if (png_ptr->row_number < png_ptr->num_rows)
  202333. return;
  202334. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202335. /* if interlaced, go to next pass */
  202336. if (png_ptr->interlaced)
  202337. {
  202338. png_ptr->row_number = 0;
  202339. if (png_ptr->transformations & PNG_INTERLACE)
  202340. {
  202341. png_ptr->pass++;
  202342. }
  202343. else
  202344. {
  202345. /* loop until we find a non-zero width or height pass */
  202346. do
  202347. {
  202348. png_ptr->pass++;
  202349. if (png_ptr->pass >= 7)
  202350. break;
  202351. png_ptr->usr_width = (png_ptr->width +
  202352. png_pass_inc[png_ptr->pass] - 1 -
  202353. png_pass_start[png_ptr->pass]) /
  202354. png_pass_inc[png_ptr->pass];
  202355. png_ptr->num_rows = (png_ptr->height +
  202356. png_pass_yinc[png_ptr->pass] - 1 -
  202357. png_pass_ystart[png_ptr->pass]) /
  202358. png_pass_yinc[png_ptr->pass];
  202359. if (png_ptr->transformations & PNG_INTERLACE)
  202360. break;
  202361. } while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0);
  202362. }
  202363. /* reset the row above the image for the next pass */
  202364. if (png_ptr->pass < 7)
  202365. {
  202366. if (png_ptr->prev_row != NULL)
  202367. png_memset(png_ptr->prev_row, 0,
  202368. (png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels*
  202369. png_ptr->usr_bit_depth,png_ptr->width))+1);
  202370. return;
  202371. }
  202372. }
  202373. #endif
  202374. /* if we get here, we've just written the last row, so we need
  202375. to flush the compressor */
  202376. do
  202377. {
  202378. /* tell the compressor we are done */
  202379. ret = deflate(&png_ptr->zstream, Z_FINISH);
  202380. /* check for an error */
  202381. if (ret == Z_OK)
  202382. {
  202383. /* check to see if we need more room */
  202384. if (!(png_ptr->zstream.avail_out))
  202385. {
  202386. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  202387. png_ptr->zstream.next_out = png_ptr->zbuf;
  202388. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  202389. }
  202390. }
  202391. else if (ret != Z_STREAM_END)
  202392. {
  202393. if (png_ptr->zstream.msg != NULL)
  202394. png_error(png_ptr, png_ptr->zstream.msg);
  202395. else
  202396. png_error(png_ptr, "zlib error");
  202397. }
  202398. } while (ret != Z_STREAM_END);
  202399. /* write any extra space */
  202400. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  202401. {
  202402. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size -
  202403. png_ptr->zstream.avail_out);
  202404. }
  202405. deflateReset(&png_ptr->zstream);
  202406. png_ptr->zstream.data_type = Z_BINARY;
  202407. }
  202408. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  202409. /* Pick out the correct pixels for the interlace pass.
  202410. * The basic idea here is to go through the row with a source
  202411. * pointer and a destination pointer (sp and dp), and copy the
  202412. * correct pixels for the pass. As the row gets compacted,
  202413. * sp will always be >= dp, so we should never overwrite anything.
  202414. * See the default: case for the easiest code to understand.
  202415. */
  202416. void /* PRIVATE */
  202417. png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
  202418. {
  202419. #ifdef PNG_USE_LOCAL_ARRAYS
  202420. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  202421. /* start of interlace block */
  202422. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  202423. /* offset to next interlace block */
  202424. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  202425. #endif
  202426. png_debug(1, "in png_do_write_interlace\n");
  202427. /* we don't have to do anything on the last pass (6) */
  202428. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  202429. if (row != NULL && row_info != NULL && pass < 6)
  202430. #else
  202431. if (pass < 6)
  202432. #endif
  202433. {
  202434. /* each pixel depth is handled separately */
  202435. switch (row_info->pixel_depth)
  202436. {
  202437. case 1:
  202438. {
  202439. png_bytep sp;
  202440. png_bytep dp;
  202441. int shift;
  202442. int d;
  202443. int value;
  202444. png_uint_32 i;
  202445. png_uint_32 row_width = row_info->width;
  202446. dp = row;
  202447. d = 0;
  202448. shift = 7;
  202449. for (i = png_pass_start[pass]; i < row_width;
  202450. i += png_pass_inc[pass])
  202451. {
  202452. sp = row + (png_size_t)(i >> 3);
  202453. value = (int)(*sp >> (7 - (int)(i & 0x07))) & 0x01;
  202454. d |= (value << shift);
  202455. if (shift == 0)
  202456. {
  202457. shift = 7;
  202458. *dp++ = (png_byte)d;
  202459. d = 0;
  202460. }
  202461. else
  202462. shift--;
  202463. }
  202464. if (shift != 7)
  202465. *dp = (png_byte)d;
  202466. break;
  202467. }
  202468. case 2:
  202469. {
  202470. png_bytep sp;
  202471. png_bytep dp;
  202472. int shift;
  202473. int d;
  202474. int value;
  202475. png_uint_32 i;
  202476. png_uint_32 row_width = row_info->width;
  202477. dp = row;
  202478. shift = 6;
  202479. d = 0;
  202480. for (i = png_pass_start[pass]; i < row_width;
  202481. i += png_pass_inc[pass])
  202482. {
  202483. sp = row + (png_size_t)(i >> 2);
  202484. value = (*sp >> ((3 - (int)(i & 0x03)) << 1)) & 0x03;
  202485. d |= (value << shift);
  202486. if (shift == 0)
  202487. {
  202488. shift = 6;
  202489. *dp++ = (png_byte)d;
  202490. d = 0;
  202491. }
  202492. else
  202493. shift -= 2;
  202494. }
  202495. if (shift != 6)
  202496. *dp = (png_byte)d;
  202497. break;
  202498. }
  202499. case 4:
  202500. {
  202501. png_bytep sp;
  202502. png_bytep dp;
  202503. int shift;
  202504. int d;
  202505. int value;
  202506. png_uint_32 i;
  202507. png_uint_32 row_width = row_info->width;
  202508. dp = row;
  202509. shift = 4;
  202510. d = 0;
  202511. for (i = png_pass_start[pass]; i < row_width;
  202512. i += png_pass_inc[pass])
  202513. {
  202514. sp = row + (png_size_t)(i >> 1);
  202515. value = (*sp >> ((1 - (int)(i & 0x01)) << 2)) & 0x0f;
  202516. d |= (value << shift);
  202517. if (shift == 0)
  202518. {
  202519. shift = 4;
  202520. *dp++ = (png_byte)d;
  202521. d = 0;
  202522. }
  202523. else
  202524. shift -= 4;
  202525. }
  202526. if (shift != 4)
  202527. *dp = (png_byte)d;
  202528. break;
  202529. }
  202530. default:
  202531. {
  202532. png_bytep sp;
  202533. png_bytep dp;
  202534. png_uint_32 i;
  202535. png_uint_32 row_width = row_info->width;
  202536. png_size_t pixel_bytes;
  202537. /* start at the beginning */
  202538. dp = row;
  202539. /* find out how many bytes each pixel takes up */
  202540. pixel_bytes = (row_info->pixel_depth >> 3);
  202541. /* loop through the row, only looking at the pixels that
  202542. matter */
  202543. for (i = png_pass_start[pass]; i < row_width;
  202544. i += png_pass_inc[pass])
  202545. {
  202546. /* find out where the original pixel is */
  202547. sp = row + (png_size_t)i * pixel_bytes;
  202548. /* move the pixel */
  202549. if (dp != sp)
  202550. png_memcpy(dp, sp, pixel_bytes);
  202551. /* next pixel */
  202552. dp += pixel_bytes;
  202553. }
  202554. break;
  202555. }
  202556. }
  202557. /* set new row width */
  202558. row_info->width = (row_info->width +
  202559. png_pass_inc[pass] - 1 -
  202560. png_pass_start[pass]) /
  202561. png_pass_inc[pass];
  202562. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  202563. row_info->width);
  202564. }
  202565. }
  202566. #endif
  202567. /* This filters the row, chooses which filter to use, if it has not already
  202568. * been specified by the application, and then writes the row out with the
  202569. * chosen filter.
  202570. */
  202571. #define PNG_MAXSUM (((png_uint_32)(-1)) >> 1)
  202572. #define PNG_HISHIFT 10
  202573. #define PNG_LOMASK ((png_uint_32)0xffffL)
  202574. #define PNG_HIMASK ((png_uint_32)(~PNG_LOMASK >> PNG_HISHIFT))
  202575. void /* PRIVATE */
  202576. png_write_find_filter(png_structp png_ptr, png_row_infop row_info)
  202577. {
  202578. png_bytep best_row;
  202579. #ifndef PNG_NO_WRITE_FILTER
  202580. png_bytep prev_row, row_buf;
  202581. png_uint_32 mins, bpp;
  202582. png_byte filter_to_do = png_ptr->do_filter;
  202583. png_uint_32 row_bytes = row_info->rowbytes;
  202584. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202585. int num_p_filters = (int)png_ptr->num_prev_filters;
  202586. #endif
  202587. png_debug(1, "in png_write_find_filter\n");
  202588. /* find out how many bytes offset each pixel is */
  202589. bpp = (row_info->pixel_depth + 7) >> 3;
  202590. prev_row = png_ptr->prev_row;
  202591. #endif
  202592. best_row = png_ptr->row_buf;
  202593. #ifndef PNG_NO_WRITE_FILTER
  202594. row_buf = best_row;
  202595. mins = PNG_MAXSUM;
  202596. /* The prediction method we use is to find which method provides the
  202597. * smallest value when summing the absolute values of the distances
  202598. * from zero, using anything >= 128 as negative numbers. This is known
  202599. * as the "minimum sum of absolute differences" heuristic. Other
  202600. * heuristics are the "weighted minimum sum of absolute differences"
  202601. * (experimental and can in theory improve compression), and the "zlib
  202602. * predictive" method (not implemented yet), which does test compressions
  202603. * of lines using different filter methods, and then chooses the
  202604. * (series of) filter(s) that give minimum compressed data size (VERY
  202605. * computationally expensive).
  202606. *
  202607. * GRR 980525: consider also
  202608. * (1) minimum sum of absolute differences from running average (i.e.,
  202609. * keep running sum of non-absolute differences & count of bytes)
  202610. * [track dispersion, too? restart average if dispersion too large?]
  202611. * (1b) minimum sum of absolute differences from sliding average, probably
  202612. * with window size <= deflate window (usually 32K)
  202613. * (2) minimum sum of squared differences from zero or running average
  202614. * (i.e., ~ root-mean-square approach)
  202615. */
  202616. /* We don't need to test the 'no filter' case if this is the only filter
  202617. * that has been chosen, as it doesn't actually do anything to the data.
  202618. */
  202619. if ((filter_to_do & PNG_FILTER_NONE) &&
  202620. filter_to_do != PNG_FILTER_NONE)
  202621. {
  202622. png_bytep rp;
  202623. png_uint_32 sum = 0;
  202624. png_uint_32 i;
  202625. int v;
  202626. for (i = 0, rp = row_buf + 1; i < row_bytes; i++, rp++)
  202627. {
  202628. v = *rp;
  202629. sum += (v < 128) ? v : 256 - v;
  202630. }
  202631. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202632. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202633. {
  202634. png_uint_32 sumhi, sumlo;
  202635. int j;
  202636. sumlo = sum & PNG_LOMASK;
  202637. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK; /* Gives us some footroom */
  202638. /* Reduce the sum if we match any of the previous rows */
  202639. for (j = 0; j < num_p_filters; j++)
  202640. {
  202641. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  202642. {
  202643. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202644. PNG_WEIGHT_SHIFT;
  202645. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202646. PNG_WEIGHT_SHIFT;
  202647. }
  202648. }
  202649. /* Factor in the cost of this filter (this is here for completeness,
  202650. * but it makes no sense to have a "cost" for the NONE filter, as
  202651. * it has the minimum possible computational cost - none).
  202652. */
  202653. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  202654. PNG_COST_SHIFT;
  202655. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  202656. PNG_COST_SHIFT;
  202657. if (sumhi > PNG_HIMASK)
  202658. sum = PNG_MAXSUM;
  202659. else
  202660. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202661. }
  202662. #endif
  202663. mins = sum;
  202664. }
  202665. /* sub filter */
  202666. if (filter_to_do == PNG_FILTER_SUB)
  202667. /* it's the only filter so no testing is needed */
  202668. {
  202669. png_bytep rp, lp, dp;
  202670. png_uint_32 i;
  202671. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  202672. i++, rp++, dp++)
  202673. {
  202674. *dp = *rp;
  202675. }
  202676. for (lp = row_buf + 1; i < row_bytes;
  202677. i++, rp++, lp++, dp++)
  202678. {
  202679. *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  202680. }
  202681. best_row = png_ptr->sub_row;
  202682. }
  202683. else if (filter_to_do & PNG_FILTER_SUB)
  202684. {
  202685. png_bytep rp, dp, lp;
  202686. png_uint_32 sum = 0, lmins = mins;
  202687. png_uint_32 i;
  202688. int v;
  202689. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202690. /* We temporarily increase the "minimum sum" by the factor we
  202691. * would reduce the sum of this filter, so that we can do the
  202692. * early exit comparison without scaling the sum each time.
  202693. */
  202694. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202695. {
  202696. int j;
  202697. png_uint_32 lmhi, lmlo;
  202698. lmlo = lmins & PNG_LOMASK;
  202699. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202700. for (j = 0; j < num_p_filters; j++)
  202701. {
  202702. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  202703. {
  202704. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202705. PNG_WEIGHT_SHIFT;
  202706. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202707. PNG_WEIGHT_SHIFT;
  202708. }
  202709. }
  202710. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202711. PNG_COST_SHIFT;
  202712. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202713. PNG_COST_SHIFT;
  202714. if (lmhi > PNG_HIMASK)
  202715. lmins = PNG_MAXSUM;
  202716. else
  202717. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202718. }
  202719. #endif
  202720. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  202721. i++, rp++, dp++)
  202722. {
  202723. v = *dp = *rp;
  202724. sum += (v < 128) ? v : 256 - v;
  202725. }
  202726. for (lp = row_buf + 1; i < row_bytes;
  202727. i++, rp++, lp++, dp++)
  202728. {
  202729. v = *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  202730. sum += (v < 128) ? v : 256 - v;
  202731. if (sum > lmins) /* We are already worse, don't continue. */
  202732. break;
  202733. }
  202734. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202735. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202736. {
  202737. int j;
  202738. png_uint_32 sumhi, sumlo;
  202739. sumlo = sum & PNG_LOMASK;
  202740. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202741. for (j = 0; j < num_p_filters; j++)
  202742. {
  202743. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  202744. {
  202745. sumlo = (sumlo * png_ptr->inv_filter_weights[j]) >>
  202746. PNG_WEIGHT_SHIFT;
  202747. sumhi = (sumhi * png_ptr->inv_filter_weights[j]) >>
  202748. PNG_WEIGHT_SHIFT;
  202749. }
  202750. }
  202751. sumlo = (sumlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202752. PNG_COST_SHIFT;
  202753. sumhi = (sumhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202754. PNG_COST_SHIFT;
  202755. if (sumhi > PNG_HIMASK)
  202756. sum = PNG_MAXSUM;
  202757. else
  202758. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202759. }
  202760. #endif
  202761. if (sum < mins)
  202762. {
  202763. mins = sum;
  202764. best_row = png_ptr->sub_row;
  202765. }
  202766. }
  202767. /* up filter */
  202768. if (filter_to_do == PNG_FILTER_UP)
  202769. {
  202770. png_bytep rp, dp, pp;
  202771. png_uint_32 i;
  202772. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  202773. pp = prev_row + 1; i < row_bytes;
  202774. i++, rp++, pp++, dp++)
  202775. {
  202776. *dp = (png_byte)(((int)*rp - (int)*pp) & 0xff);
  202777. }
  202778. best_row = png_ptr->up_row;
  202779. }
  202780. else if (filter_to_do & PNG_FILTER_UP)
  202781. {
  202782. png_bytep rp, dp, pp;
  202783. png_uint_32 sum = 0, lmins = mins;
  202784. png_uint_32 i;
  202785. int v;
  202786. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202787. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202788. {
  202789. int j;
  202790. png_uint_32 lmhi, lmlo;
  202791. lmlo = lmins & PNG_LOMASK;
  202792. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202793. for (j = 0; j < num_p_filters; j++)
  202794. {
  202795. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  202796. {
  202797. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202798. PNG_WEIGHT_SHIFT;
  202799. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202800. PNG_WEIGHT_SHIFT;
  202801. }
  202802. }
  202803. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  202804. PNG_COST_SHIFT;
  202805. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  202806. PNG_COST_SHIFT;
  202807. if (lmhi > PNG_HIMASK)
  202808. lmins = PNG_MAXSUM;
  202809. else
  202810. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202811. }
  202812. #endif
  202813. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  202814. pp = prev_row + 1; i < row_bytes; i++)
  202815. {
  202816. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202817. sum += (v < 128) ? v : 256 - v;
  202818. if (sum > lmins) /* We are already worse, don't continue. */
  202819. break;
  202820. }
  202821. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202822. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202823. {
  202824. int j;
  202825. png_uint_32 sumhi, sumlo;
  202826. sumlo = sum & PNG_LOMASK;
  202827. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202828. for (j = 0; j < num_p_filters; j++)
  202829. {
  202830. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  202831. {
  202832. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202833. PNG_WEIGHT_SHIFT;
  202834. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202835. PNG_WEIGHT_SHIFT;
  202836. }
  202837. }
  202838. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  202839. PNG_COST_SHIFT;
  202840. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  202841. PNG_COST_SHIFT;
  202842. if (sumhi > PNG_HIMASK)
  202843. sum = PNG_MAXSUM;
  202844. else
  202845. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202846. }
  202847. #endif
  202848. if (sum < mins)
  202849. {
  202850. mins = sum;
  202851. best_row = png_ptr->up_row;
  202852. }
  202853. }
  202854. /* avg filter */
  202855. if (filter_to_do == PNG_FILTER_AVG)
  202856. {
  202857. png_bytep rp, dp, pp, lp;
  202858. png_uint_32 i;
  202859. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  202860. pp = prev_row + 1; i < bpp; i++)
  202861. {
  202862. *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  202863. }
  202864. for (lp = row_buf + 1; i < row_bytes; i++)
  202865. {
  202866. *dp++ = (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2))
  202867. & 0xff);
  202868. }
  202869. best_row = png_ptr->avg_row;
  202870. }
  202871. else if (filter_to_do & PNG_FILTER_AVG)
  202872. {
  202873. png_bytep rp, dp, pp, lp;
  202874. png_uint_32 sum = 0, lmins = mins;
  202875. png_uint_32 i;
  202876. int v;
  202877. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202878. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202879. {
  202880. int j;
  202881. png_uint_32 lmhi, lmlo;
  202882. lmlo = lmins & PNG_LOMASK;
  202883. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202884. for (j = 0; j < num_p_filters; j++)
  202885. {
  202886. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_AVG)
  202887. {
  202888. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202889. PNG_WEIGHT_SHIFT;
  202890. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202891. PNG_WEIGHT_SHIFT;
  202892. }
  202893. }
  202894. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202895. PNG_COST_SHIFT;
  202896. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202897. PNG_COST_SHIFT;
  202898. if (lmhi > PNG_HIMASK)
  202899. lmins = PNG_MAXSUM;
  202900. else
  202901. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202902. }
  202903. #endif
  202904. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  202905. pp = prev_row + 1; i < bpp; i++)
  202906. {
  202907. v = *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  202908. sum += (v < 128) ? v : 256 - v;
  202909. }
  202910. for (lp = row_buf + 1; i < row_bytes; i++)
  202911. {
  202912. v = *dp++ =
  202913. (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2)) & 0xff);
  202914. sum += (v < 128) ? v : 256 - v;
  202915. if (sum > lmins) /* We are already worse, don't continue. */
  202916. break;
  202917. }
  202918. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202919. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202920. {
  202921. int j;
  202922. png_uint_32 sumhi, sumlo;
  202923. sumlo = sum & PNG_LOMASK;
  202924. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202925. for (j = 0; j < num_p_filters; j++)
  202926. {
  202927. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  202928. {
  202929. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202930. PNG_WEIGHT_SHIFT;
  202931. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202932. PNG_WEIGHT_SHIFT;
  202933. }
  202934. }
  202935. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202936. PNG_COST_SHIFT;
  202937. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202938. PNG_COST_SHIFT;
  202939. if (sumhi > PNG_HIMASK)
  202940. sum = PNG_MAXSUM;
  202941. else
  202942. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202943. }
  202944. #endif
  202945. if (sum < mins)
  202946. {
  202947. mins = sum;
  202948. best_row = png_ptr->avg_row;
  202949. }
  202950. }
  202951. /* Paeth filter */
  202952. if (filter_to_do == PNG_FILTER_PAETH)
  202953. {
  202954. png_bytep rp, dp, pp, cp, lp;
  202955. png_uint_32 i;
  202956. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  202957. pp = prev_row + 1; i < bpp; i++)
  202958. {
  202959. *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202960. }
  202961. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  202962. {
  202963. int a, b, c, pa, pb, pc, p;
  202964. b = *pp++;
  202965. c = *cp++;
  202966. a = *lp++;
  202967. p = b - c;
  202968. pc = a - c;
  202969. #ifdef PNG_USE_ABS
  202970. pa = abs(p);
  202971. pb = abs(pc);
  202972. pc = abs(p + pc);
  202973. #else
  202974. pa = p < 0 ? -p : p;
  202975. pb = pc < 0 ? -pc : pc;
  202976. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  202977. #endif
  202978. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  202979. *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  202980. }
  202981. best_row = png_ptr->paeth_row;
  202982. }
  202983. else if (filter_to_do & PNG_FILTER_PAETH)
  202984. {
  202985. png_bytep rp, dp, pp, cp, lp;
  202986. png_uint_32 sum = 0, lmins = mins;
  202987. png_uint_32 i;
  202988. int v;
  202989. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202990. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202991. {
  202992. int j;
  202993. png_uint_32 lmhi, lmlo;
  202994. lmlo = lmins & PNG_LOMASK;
  202995. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202996. for (j = 0; j < num_p_filters; j++)
  202997. {
  202998. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  202999. {
  203000. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  203001. PNG_WEIGHT_SHIFT;
  203002. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  203003. PNG_WEIGHT_SHIFT;
  203004. }
  203005. }
  203006. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  203007. PNG_COST_SHIFT;
  203008. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  203009. PNG_COST_SHIFT;
  203010. if (lmhi > PNG_HIMASK)
  203011. lmins = PNG_MAXSUM;
  203012. else
  203013. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  203014. }
  203015. #endif
  203016. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  203017. pp = prev_row + 1; i < bpp; i++)
  203018. {
  203019. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  203020. sum += (v < 128) ? v : 256 - v;
  203021. }
  203022. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  203023. {
  203024. int a, b, c, pa, pb, pc, p;
  203025. b = *pp++;
  203026. c = *cp++;
  203027. a = *lp++;
  203028. #ifndef PNG_SLOW_PAETH
  203029. p = b - c;
  203030. pc = a - c;
  203031. #ifdef PNG_USE_ABS
  203032. pa = abs(p);
  203033. pb = abs(pc);
  203034. pc = abs(p + pc);
  203035. #else
  203036. pa = p < 0 ? -p : p;
  203037. pb = pc < 0 ? -pc : pc;
  203038. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  203039. #endif
  203040. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  203041. #else /* PNG_SLOW_PAETH */
  203042. p = a + b - c;
  203043. pa = abs(p - a);
  203044. pb = abs(p - b);
  203045. pc = abs(p - c);
  203046. if (pa <= pb && pa <= pc)
  203047. p = a;
  203048. else if (pb <= pc)
  203049. p = b;
  203050. else
  203051. p = c;
  203052. #endif /* PNG_SLOW_PAETH */
  203053. v = *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  203054. sum += (v < 128) ? v : 256 - v;
  203055. if (sum > lmins) /* We are already worse, don't continue. */
  203056. break;
  203057. }
  203058. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203059. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  203060. {
  203061. int j;
  203062. png_uint_32 sumhi, sumlo;
  203063. sumlo = sum & PNG_LOMASK;
  203064. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  203065. for (j = 0; j < num_p_filters; j++)
  203066. {
  203067. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  203068. {
  203069. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  203070. PNG_WEIGHT_SHIFT;
  203071. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  203072. PNG_WEIGHT_SHIFT;
  203073. }
  203074. }
  203075. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  203076. PNG_COST_SHIFT;
  203077. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  203078. PNG_COST_SHIFT;
  203079. if (sumhi > PNG_HIMASK)
  203080. sum = PNG_MAXSUM;
  203081. else
  203082. sum = (sumhi << PNG_HISHIFT) + sumlo;
  203083. }
  203084. #endif
  203085. if (sum < mins)
  203086. {
  203087. best_row = png_ptr->paeth_row;
  203088. }
  203089. }
  203090. #endif /* PNG_NO_WRITE_FILTER */
  203091. /* Do the actual writing of the filtered row data from the chosen filter. */
  203092. png_write_filtered_row(png_ptr, best_row);
  203093. #ifndef PNG_NO_WRITE_FILTER
  203094. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203095. /* Save the type of filter we picked this time for future calculations */
  203096. if (png_ptr->num_prev_filters > 0)
  203097. {
  203098. int j;
  203099. for (j = 1; j < num_p_filters; j++)
  203100. {
  203101. png_ptr->prev_filters[j] = png_ptr->prev_filters[j - 1];
  203102. }
  203103. png_ptr->prev_filters[j] = best_row[0];
  203104. }
  203105. #endif
  203106. #endif /* PNG_NO_WRITE_FILTER */
  203107. }
  203108. /* Do the actual writing of a previously filtered row. */
  203109. void /* PRIVATE */
  203110. png_write_filtered_row(png_structp png_ptr, png_bytep filtered_row)
  203111. {
  203112. png_debug(1, "in png_write_filtered_row\n");
  203113. png_debug1(2, "filter = %d\n", filtered_row[0]);
  203114. /* set up the zlib input buffer */
  203115. png_ptr->zstream.next_in = filtered_row;
  203116. png_ptr->zstream.avail_in = (uInt)png_ptr->row_info.rowbytes + 1;
  203117. /* repeat until we have compressed all the data */
  203118. do
  203119. {
  203120. int ret; /* return of zlib */
  203121. /* compress the data */
  203122. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  203123. /* check for compression errors */
  203124. if (ret != Z_OK)
  203125. {
  203126. if (png_ptr->zstream.msg != NULL)
  203127. png_error(png_ptr, png_ptr->zstream.msg);
  203128. else
  203129. png_error(png_ptr, "zlib error");
  203130. }
  203131. /* see if it is time to write another IDAT */
  203132. if (!(png_ptr->zstream.avail_out))
  203133. {
  203134. /* write the IDAT and reset the zlib output buffer */
  203135. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  203136. png_ptr->zstream.next_out = png_ptr->zbuf;
  203137. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  203138. }
  203139. /* repeat until all data has been compressed */
  203140. } while (png_ptr->zstream.avail_in);
  203141. /* swap the current and previous rows */
  203142. if (png_ptr->prev_row != NULL)
  203143. {
  203144. png_bytep tptr;
  203145. tptr = png_ptr->prev_row;
  203146. png_ptr->prev_row = png_ptr->row_buf;
  203147. png_ptr->row_buf = tptr;
  203148. }
  203149. /* finish row - updates counters and flushes zlib if last row */
  203150. png_write_finish_row(png_ptr);
  203151. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  203152. png_ptr->flush_rows++;
  203153. if (png_ptr->flush_dist > 0 &&
  203154. png_ptr->flush_rows >= png_ptr->flush_dist)
  203155. {
  203156. png_write_flush(png_ptr);
  203157. }
  203158. #endif
  203159. }
  203160. #endif /* PNG_WRITE_SUPPORTED */
  203161. /*** End of inlined file: pngwutil.c ***/
  203162. #else
  203163. extern "C"
  203164. {
  203165. #include <png.h>
  203166. #include <pngconf.h>
  203167. }
  203168. #endif
  203169. }
  203170. #undef max
  203171. #undef min
  203172. #if JUCE_MSVC
  203173. #pragma warning (pop)
  203174. #endif
  203175. BEGIN_JUCE_NAMESPACE
  203176. using ::calloc;
  203177. using ::malloc;
  203178. using ::free;
  203179. namespace PNGHelpers
  203180. {
  203181. using namespace pnglibNamespace;
  203182. static void JUCE_CDECL readCallback (png_structp png, png_bytep data, png_size_t length)
  203183. {
  203184. static_cast<InputStream*> (png_get_io_ptr (png))->read (data, (int) length);
  203185. }
  203186. static void JUCE_CDECL writeDataCallback (png_structp png, png_bytep data, png_size_t length)
  203187. {
  203188. static_cast<OutputStream*> (png_get_io_ptr (png))->write (data, (int) length);
  203189. }
  203190. struct PNGErrorStruct {};
  203191. static void JUCE_CDECL errorCallback (png_structp, png_const_charp)
  203192. {
  203193. throw PNGErrorStruct();
  203194. }
  203195. }
  203196. PNGImageFormat::PNGImageFormat() {}
  203197. PNGImageFormat::~PNGImageFormat() {}
  203198. const String PNGImageFormat::getFormatName()
  203199. {
  203200. return "PNG";
  203201. }
  203202. bool PNGImageFormat::canUnderstand (InputStream& in)
  203203. {
  203204. const int bytesNeeded = 4;
  203205. char header [bytesNeeded];
  203206. return in.read (header, bytesNeeded) == bytesNeeded
  203207. && header[1] == 'P'
  203208. && header[2] == 'N'
  203209. && header[3] == 'G';
  203210. }
  203211. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  203212. const Image juce_loadWithCoreImage (InputStream& input);
  203213. #endif
  203214. const Image PNGImageFormat::decodeImage (InputStream& in)
  203215. {
  203216. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  203217. return juce_loadWithCoreImage (in);
  203218. #else
  203219. using namespace pnglibNamespace;
  203220. Image image;
  203221. png_structp pngReadStruct;
  203222. png_infop pngInfoStruct;
  203223. pngReadStruct = png_create_read_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  203224. if (pngReadStruct != 0)
  203225. {
  203226. pngInfoStruct = png_create_info_struct (pngReadStruct);
  203227. if (pngInfoStruct == 0)
  203228. {
  203229. png_destroy_read_struct (&pngReadStruct, 0, 0);
  203230. return Image::null;
  203231. }
  203232. png_set_error_fn (pngReadStruct, 0, PNGHelpers::errorCallback, PNGHelpers::errorCallback );
  203233. // read the header..
  203234. png_set_read_fn (pngReadStruct, &in, PNGHelpers::readCallback);
  203235. png_uint_32 width, height;
  203236. int bitDepth, colorType, interlaceType;
  203237. png_read_info (pngReadStruct, pngInfoStruct);
  203238. png_get_IHDR (pngReadStruct, pngInfoStruct,
  203239. &width, &height,
  203240. &bitDepth, &colorType,
  203241. &interlaceType, 0, 0);
  203242. if (bitDepth == 16)
  203243. png_set_strip_16 (pngReadStruct);
  203244. if (colorType == PNG_COLOR_TYPE_PALETTE)
  203245. png_set_expand (pngReadStruct);
  203246. if (bitDepth < 8)
  203247. png_set_expand (pngReadStruct);
  203248. if (png_get_valid (pngReadStruct, pngInfoStruct, PNG_INFO_tRNS))
  203249. png_set_expand (pngReadStruct);
  203250. if (colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_GRAY_ALPHA)
  203251. png_set_gray_to_rgb (pngReadStruct);
  203252. png_set_add_alpha (pngReadStruct, 0xff, PNG_FILLER_AFTER);
  203253. bool hasAlphaChan = (colorType & PNG_COLOR_MASK_ALPHA) != 0
  203254. || pngInfoStruct->num_trans > 0;
  203255. // Load the image into a temp buffer in the pnglib format..
  203256. HeapBlock <uint8> tempBuffer (height * (width << 2));
  203257. {
  203258. HeapBlock <png_bytep> rows (height);
  203259. for (int y = (int) height; --y >= 0;)
  203260. rows[y] = (png_bytep) (tempBuffer + (width << 2) * y);
  203261. png_read_image (pngReadStruct, rows);
  203262. png_read_end (pngReadStruct, pngInfoStruct);
  203263. }
  203264. png_destroy_read_struct (&pngReadStruct, &pngInfoStruct, 0);
  203265. // now convert the data to a juce image format..
  203266. image = Image (hasAlphaChan ? Image::ARGB : Image::RGB,
  203267. (int) width, (int) height, hasAlphaChan);
  203268. hasAlphaChan = image.hasAlphaChannel(); // (the native image creator may not give back what we expect)
  203269. const Image::BitmapData destData (image, true);
  203270. uint8* srcRow = tempBuffer;
  203271. uint8* destRow = destData.data;
  203272. for (int y = 0; y < (int) height; ++y)
  203273. {
  203274. const uint8* src = srcRow;
  203275. srcRow += (width << 2);
  203276. uint8* dest = destRow;
  203277. destRow += destData.lineStride;
  203278. if (hasAlphaChan)
  203279. {
  203280. for (int i = (int) width; --i >= 0;)
  203281. {
  203282. ((PixelARGB*) dest)->setARGB (src[3], src[0], src[1], src[2]);
  203283. ((PixelARGB*) dest)->premultiply();
  203284. dest += destData.pixelStride;
  203285. src += 4;
  203286. }
  203287. }
  203288. else
  203289. {
  203290. for (int i = (int) width; --i >= 0;)
  203291. {
  203292. ((PixelRGB*) dest)->setARGB (0, src[0], src[1], src[2]);
  203293. dest += destData.pixelStride;
  203294. src += 4;
  203295. }
  203296. }
  203297. }
  203298. }
  203299. return image;
  203300. #endif
  203301. }
  203302. bool PNGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  203303. {
  203304. using namespace pnglibNamespace;
  203305. const int width = image.getWidth();
  203306. const int height = image.getHeight();
  203307. png_structp pngWriteStruct = png_create_write_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  203308. if (pngWriteStruct == 0)
  203309. return false;
  203310. png_infop pngInfoStruct = png_create_info_struct (pngWriteStruct);
  203311. if (pngInfoStruct == 0)
  203312. {
  203313. png_destroy_write_struct (&pngWriteStruct, (png_infopp) 0);
  203314. return false;
  203315. }
  203316. png_set_write_fn (pngWriteStruct, &out, PNGHelpers::writeDataCallback, 0);
  203317. png_set_IHDR (pngWriteStruct, pngInfoStruct, width, height, 8,
  203318. image.hasAlphaChannel() ? PNG_COLOR_TYPE_RGB_ALPHA
  203319. : PNG_COLOR_TYPE_RGB,
  203320. PNG_INTERLACE_NONE,
  203321. PNG_COMPRESSION_TYPE_BASE,
  203322. PNG_FILTER_TYPE_BASE);
  203323. HeapBlock <uint8> rowData (width * 4);
  203324. png_color_8 sig_bit;
  203325. sig_bit.red = 8;
  203326. sig_bit.green = 8;
  203327. sig_bit.blue = 8;
  203328. sig_bit.alpha = 8;
  203329. png_set_sBIT (pngWriteStruct, pngInfoStruct, &sig_bit);
  203330. png_write_info (pngWriteStruct, pngInfoStruct);
  203331. png_set_shift (pngWriteStruct, &sig_bit);
  203332. png_set_packing (pngWriteStruct);
  203333. const Image::BitmapData srcData (image, false);
  203334. for (int y = 0; y < height; ++y)
  203335. {
  203336. uint8* dst = rowData;
  203337. const uint8* src = srcData.getLinePointer (y);
  203338. if (image.hasAlphaChannel())
  203339. {
  203340. for (int i = width; --i >= 0;)
  203341. {
  203342. PixelARGB p (*(const PixelARGB*) src);
  203343. p.unpremultiply();
  203344. *dst++ = p.getRed();
  203345. *dst++ = p.getGreen();
  203346. *dst++ = p.getBlue();
  203347. *dst++ = p.getAlpha();
  203348. src += srcData.pixelStride;
  203349. }
  203350. }
  203351. else
  203352. {
  203353. for (int i = width; --i >= 0;)
  203354. {
  203355. *dst++ = ((const PixelRGB*) src)->getRed();
  203356. *dst++ = ((const PixelRGB*) src)->getGreen();
  203357. *dst++ = ((const PixelRGB*) src)->getBlue();
  203358. src += srcData.pixelStride;
  203359. }
  203360. }
  203361. png_bytep rowPtr = rowData;
  203362. png_write_rows (pngWriteStruct, &rowPtr, 1);
  203363. }
  203364. png_write_end (pngWriteStruct, pngInfoStruct);
  203365. png_destroy_write_struct (&pngWriteStruct, &pngInfoStruct);
  203366. out.flush();
  203367. return true;
  203368. }
  203369. END_JUCE_NAMESPACE
  203370. /*** End of inlined file: juce_PNGLoader.cpp ***/
  203371. #endif
  203372. //==============================================================================
  203373. #if JUCE_BUILD_NATIVE
  203374. // Non-public headers that are needed by more than one platform must be included
  203375. // before the platform-specific sections..
  203376. BEGIN_JUCE_NAMESPACE
  203377. /*** Start of inlined file: juce_MidiDataConcatenator.h ***/
  203378. #ifndef __JUCE_MIDIDATACONCATENATOR_JUCEHEADER__
  203379. #define __JUCE_MIDIDATACONCATENATOR_JUCEHEADER__
  203380. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  203381. /**
  203382. Helper class that takes chunks of incoming midi bytes, packages them into
  203383. messages, and dispatches them to a midi callback.
  203384. */
  203385. class MidiDataConcatenator
  203386. {
  203387. public:
  203388. MidiDataConcatenator (const int initialBufferSize)
  203389. : pendingData (initialBufferSize),
  203390. pendingBytes (0), pendingDataTime (0)
  203391. {
  203392. }
  203393. void reset()
  203394. {
  203395. pendingBytes = 0;
  203396. pendingDataTime = 0;
  203397. }
  203398. void pushMidiData (const void* data, int numBytes, double time,
  203399. MidiInput* input, MidiInputCallback& callback)
  203400. {
  203401. const uint8* d = static_cast <const uint8*> (data);
  203402. while (numBytes > 0)
  203403. {
  203404. if (pendingBytes > 0 || d[0] == 0xf0)
  203405. {
  203406. processSysex (d, numBytes, time, input, callback);
  203407. }
  203408. else
  203409. {
  203410. int used = 0;
  203411. const MidiMessage m (d, numBytes, used, 0, time);
  203412. if (used <= 0)
  203413. break; // malformed message..
  203414. callback.handleIncomingMidiMessage (input, m);
  203415. numBytes -= used;
  203416. d += used;
  203417. }
  203418. }
  203419. }
  203420. private:
  203421. void processSysex (const uint8*& d, int& numBytes, double time,
  203422. MidiInput* input, MidiInputCallback& callback)
  203423. {
  203424. if (*d == 0xf0)
  203425. {
  203426. pendingBytes = 0;
  203427. pendingDataTime = time;
  203428. }
  203429. pendingData.ensureSize (pendingBytes + numBytes, false);
  203430. uint8* totalMessage = static_cast<uint8*> (pendingData.getData());
  203431. uint8* dest = totalMessage + pendingBytes;
  203432. do
  203433. {
  203434. if (pendingBytes > 0 && *d >= 0x80)
  203435. {
  203436. if (*d >= 0xfa || *d == 0xf8)
  203437. {
  203438. callback.handleIncomingMidiMessage (input, MidiMessage (*d, time));
  203439. ++d;
  203440. --numBytes;
  203441. }
  203442. else
  203443. {
  203444. if (*d == 0xf7)
  203445. {
  203446. *dest++ = *d++;
  203447. pendingBytes++;
  203448. --numBytes;
  203449. }
  203450. break;
  203451. }
  203452. }
  203453. else
  203454. {
  203455. *dest++ = *d++;
  203456. pendingBytes++;
  203457. --numBytes;
  203458. }
  203459. }
  203460. while (numBytes > 0);
  203461. if (pendingBytes > 0)
  203462. {
  203463. if (totalMessage [pendingBytes - 1] == 0xf7)
  203464. {
  203465. callback.handleIncomingMidiMessage (input, MidiMessage (totalMessage, pendingBytes, pendingDataTime));
  203466. pendingBytes = 0;
  203467. }
  203468. else
  203469. {
  203470. callback.handlePartialSysexMessage (input, totalMessage, pendingBytes, pendingDataTime);
  203471. }
  203472. }
  203473. }
  203474. MemoryBlock pendingData;
  203475. int pendingBytes;
  203476. double pendingDataTime;
  203477. MidiDataConcatenator (const MidiDataConcatenator&);
  203478. MidiDataConcatenator& operator= (const MidiDataConcatenator&);
  203479. };
  203480. #endif
  203481. #endif // __JUCE_MIDIDATACONCATENATOR_JUCEHEADER__
  203482. /*** End of inlined file: juce_MidiDataConcatenator.h ***/
  203483. END_JUCE_NAMESPACE
  203484. #if JUCE_WINDOWS
  203485. /*** Start of inlined file: juce_win32_NativeCode.cpp ***/
  203486. /*
  203487. This file wraps together all the win32-specific code, so that
  203488. we can include all the native headers just once, and compile all our
  203489. platform-specific stuff in one big lump, keeping it out of the way of
  203490. the rest of the codebase.
  203491. */
  203492. #if JUCE_WINDOWS
  203493. BEGIN_JUCE_NAMESPACE
  203494. #define JUCE_INCLUDED_FILE 1
  203495. // Now include the actual code files..
  203496. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  203497. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203498. // compiled on its own).
  203499. #if JUCE_INCLUDED_FILE
  203500. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  203501. #ifndef __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203502. #define __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203503. #ifndef DOXYGEN
  203504. // use with DynamicLibraryLoader to simplify importing functions
  203505. //
  203506. // functionName: function to import
  203507. // localFunctionName: name you want to use to actually call it (must be different)
  203508. // returnType: the return type
  203509. // object: the DynamicLibraryLoader to use
  203510. // params: list of params (bracketed)
  203511. //
  203512. #define DynamicLibraryImport(functionName, localFunctionName, returnType, object, params) \
  203513. typedef returnType (WINAPI *type##localFunctionName) params; \
  203514. type##localFunctionName localFunctionName \
  203515. = (type##localFunctionName)object.findProcAddress (#functionName);
  203516. // loads and unloads a DLL automatically
  203517. class JUCE_API DynamicLibraryLoader
  203518. {
  203519. public:
  203520. DynamicLibraryLoader (const String& name);
  203521. ~DynamicLibraryLoader();
  203522. void* findProcAddress (const String& functionName);
  203523. private:
  203524. void* libHandle;
  203525. };
  203526. #endif
  203527. #endif // __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203528. /*** End of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  203529. DynamicLibraryLoader::DynamicLibraryLoader (const String& name)
  203530. {
  203531. libHandle = LoadLibrary (name);
  203532. }
  203533. DynamicLibraryLoader::~DynamicLibraryLoader()
  203534. {
  203535. FreeLibrary ((HMODULE) libHandle);
  203536. }
  203537. void* DynamicLibraryLoader::findProcAddress (const String& functionName)
  203538. {
  203539. return (void*) GetProcAddress ((HMODULE) libHandle, functionName.toCString()); // (void* cast is required for mingw)
  203540. }
  203541. #endif
  203542. /*** End of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  203543. /*** Start of inlined file: juce_win32_SystemStats.cpp ***/
  203544. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203545. // compiled on its own).
  203546. #if JUCE_INCLUDED_FILE
  203547. extern void juce_initialiseThreadEvents();
  203548. void Logger::outputDebugString (const String& text)
  203549. {
  203550. OutputDebugString (text + "\n");
  203551. }
  203552. static int64 hiResTicksPerSecond;
  203553. static double hiResTicksScaleFactor;
  203554. #if JUCE_USE_INTRINSICS
  203555. // CPU info functions using intrinsics...
  203556. #pragma intrinsic (__cpuid)
  203557. #pragma intrinsic (__rdtsc)
  203558. const String SystemStats::getCpuVendor()
  203559. {
  203560. int info [4];
  203561. __cpuid (info, 0);
  203562. char v [12];
  203563. memcpy (v, info + 1, 4);
  203564. memcpy (v + 4, info + 3, 4);
  203565. memcpy (v + 8, info + 2, 4);
  203566. return String (v, 12);
  203567. }
  203568. #else
  203569. // CPU info functions using old fashioned inline asm...
  203570. static void juce_getCpuVendor (char* const v)
  203571. {
  203572. int vendor[4];
  203573. zeromem (vendor, 16);
  203574. #ifdef JUCE_64BIT
  203575. #else
  203576. #ifndef __MINGW32__
  203577. __try
  203578. #endif
  203579. {
  203580. #if JUCE_GCC
  203581. unsigned int dummy = 0;
  203582. __asm__ ("cpuid" : "=a" (dummy), "=b" (vendor[0]), "=c" (vendor[2]),"=d" (vendor[1]) : "a" (0));
  203583. #else
  203584. __asm
  203585. {
  203586. mov eax, 0
  203587. cpuid
  203588. mov [vendor], ebx
  203589. mov [vendor + 4], edx
  203590. mov [vendor + 8], ecx
  203591. }
  203592. #endif
  203593. }
  203594. #ifndef __MINGW32__
  203595. __except (EXCEPTION_EXECUTE_HANDLER)
  203596. {
  203597. *v = 0;
  203598. }
  203599. #endif
  203600. #endif
  203601. memcpy (v, vendor, 16);
  203602. }
  203603. const String SystemStats::getCpuVendor()
  203604. {
  203605. char v [16];
  203606. juce_getCpuVendor (v);
  203607. return String (v, 16);
  203608. }
  203609. #endif
  203610. void SystemStats::initialiseStats()
  203611. {
  203612. juce_initialiseThreadEvents();
  203613. cpuFlags.hasMMX = IsProcessorFeaturePresent (PF_MMX_INSTRUCTIONS_AVAILABLE) != 0;
  203614. cpuFlags.hasSSE = IsProcessorFeaturePresent (PF_XMMI_INSTRUCTIONS_AVAILABLE) != 0;
  203615. cpuFlags.hasSSE2 = IsProcessorFeaturePresent (PF_XMMI64_INSTRUCTIONS_AVAILABLE) != 0;
  203616. #ifdef PF_AMD3D_INSTRUCTIONS_AVAILABLE
  203617. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_AMD3D_INSTRUCTIONS_AVAILABLE) != 0;
  203618. #else
  203619. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_3DNOW_INSTRUCTIONS_AVAILABLE) != 0;
  203620. #endif
  203621. {
  203622. SYSTEM_INFO systemInfo;
  203623. GetSystemInfo (&systemInfo);
  203624. cpuFlags.numCpus = systemInfo.dwNumberOfProcessors;
  203625. }
  203626. LARGE_INTEGER f;
  203627. QueryPerformanceFrequency (&f);
  203628. hiResTicksPerSecond = f.QuadPart;
  203629. hiResTicksScaleFactor = 1000.0 / hiResTicksPerSecond;
  203630. String s (SystemStats::getJUCEVersion());
  203631. const MMRESULT res = timeBeginPeriod (1);
  203632. (void) res;
  203633. jassert (res == TIMERR_NOERROR);
  203634. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  203635. _CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
  203636. #endif
  203637. }
  203638. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  203639. {
  203640. OSVERSIONINFO info;
  203641. info.dwOSVersionInfoSize = sizeof (info);
  203642. GetVersionEx (&info);
  203643. if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
  203644. {
  203645. switch (info.dwMajorVersion)
  203646. {
  203647. case 5: return (info.dwMinorVersion == 0) ? Win2000 : WinXP;
  203648. case 6: return (info.dwMinorVersion == 0) ? WinVista : Windows7;
  203649. default: jassertfalse; break; // !! not a supported OS!
  203650. }
  203651. }
  203652. else if (info.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
  203653. {
  203654. jassert (info.dwMinorVersion != 0); // !! still running on Windows 95??
  203655. return Win98;
  203656. }
  203657. return UnknownOS;
  203658. }
  203659. const String SystemStats::getOperatingSystemName()
  203660. {
  203661. const char* name = "Unknown OS";
  203662. switch (getOperatingSystemType())
  203663. {
  203664. case Windows7: name = "Windows 7"; break;
  203665. case WinVista: name = "Windows Vista"; break;
  203666. case WinXP: name = "Windows XP"; break;
  203667. case Win2000: name = "Windows 2000"; break;
  203668. case Win98: name = "Windows 98"; break;
  203669. default: jassertfalse; break; // !! new type of OS?
  203670. }
  203671. return name;
  203672. }
  203673. bool SystemStats::isOperatingSystem64Bit()
  203674. {
  203675. #ifdef _WIN64
  203676. return true;
  203677. #else
  203678. typedef BOOL (WINAPI* LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
  203679. LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress (GetModuleHandle (L"kernel32"), "IsWow64Process");
  203680. BOOL isWow64 = FALSE;
  203681. return (fnIsWow64Process != 0)
  203682. && fnIsWow64Process (GetCurrentProcess(), &isWow64)
  203683. && (isWow64 != FALSE);
  203684. #endif
  203685. }
  203686. int SystemStats::getMemorySizeInMegabytes()
  203687. {
  203688. MEMORYSTATUSEX mem;
  203689. mem.dwLength = sizeof (mem);
  203690. GlobalMemoryStatusEx (&mem);
  203691. return (int) (mem.ullTotalPhys / (1024 * 1024)) + 1;
  203692. }
  203693. uint32 juce_millisecondsSinceStartup() throw()
  203694. {
  203695. return (uint32) timeGetTime();
  203696. }
  203697. int64 Time::getHighResolutionTicks() throw()
  203698. {
  203699. LARGE_INTEGER ticks;
  203700. QueryPerformanceCounter (&ticks);
  203701. const int64 mainCounterAsHiResTicks = (GetTickCount() * hiResTicksPerSecond) / 1000;
  203702. const int64 newOffset = mainCounterAsHiResTicks - ticks.QuadPart;
  203703. // fix for a very obscure PCI hardware bug that can make the counter
  203704. // sometimes jump forwards by a few seconds..
  203705. static int64 hiResTicksOffset = 0;
  203706. const int64 offsetDrift = abs64 (newOffset - hiResTicksOffset);
  203707. if (offsetDrift > (hiResTicksPerSecond >> 1))
  203708. hiResTicksOffset = newOffset;
  203709. return ticks.QuadPart + hiResTicksOffset;
  203710. }
  203711. double Time::getMillisecondCounterHiRes() throw()
  203712. {
  203713. return getHighResolutionTicks() * hiResTicksScaleFactor;
  203714. }
  203715. int64 Time::getHighResolutionTicksPerSecond() throw()
  203716. {
  203717. return hiResTicksPerSecond;
  203718. }
  203719. static int64 juce_getClockCycleCounter() throw()
  203720. {
  203721. #if JUCE_USE_INTRINSICS
  203722. // MS intrinsics version...
  203723. return __rdtsc();
  203724. #elif JUCE_GCC
  203725. // GNU inline asm version...
  203726. unsigned int hi = 0, lo = 0;
  203727. __asm__ __volatile__ (
  203728. "xor %%eax, %%eax \n\
  203729. xor %%edx, %%edx \n\
  203730. rdtsc \n\
  203731. movl %%eax, %[lo] \n\
  203732. movl %%edx, %[hi]"
  203733. :
  203734. : [hi] "m" (hi),
  203735. [lo] "m" (lo)
  203736. : "cc", "eax", "ebx", "ecx", "edx", "memory");
  203737. return (int64) ((((uint64) hi) << 32) | lo);
  203738. #else
  203739. // MSVC inline asm version...
  203740. unsigned int hi = 0, lo = 0;
  203741. __asm
  203742. {
  203743. xor eax, eax
  203744. xor edx, edx
  203745. rdtsc
  203746. mov lo, eax
  203747. mov hi, edx
  203748. }
  203749. return (int64) ((((uint64) hi) << 32) | lo);
  203750. #endif
  203751. }
  203752. int SystemStats::getCpuSpeedInMegaherz()
  203753. {
  203754. const int64 cycles = juce_getClockCycleCounter();
  203755. const uint32 millis = Time::getMillisecondCounter();
  203756. int lastResult = 0;
  203757. for (;;)
  203758. {
  203759. int n = 1000000;
  203760. while (--n > 0) {}
  203761. const uint32 millisElapsed = Time::getMillisecondCounter() - millis;
  203762. const int64 cyclesNow = juce_getClockCycleCounter();
  203763. if (millisElapsed > 80)
  203764. {
  203765. const int newResult = (int) (((cyclesNow - cycles) / millisElapsed) / 1000);
  203766. if (millisElapsed > 500 || (lastResult == newResult && newResult > 100))
  203767. return newResult;
  203768. lastResult = newResult;
  203769. }
  203770. }
  203771. }
  203772. bool Time::setSystemTimeToThisTime() const
  203773. {
  203774. SYSTEMTIME st;
  203775. st.wDayOfWeek = 0;
  203776. st.wYear = (WORD) getYear();
  203777. st.wMonth = (WORD) (getMonth() + 1);
  203778. st.wDay = (WORD) getDayOfMonth();
  203779. st.wHour = (WORD) getHours();
  203780. st.wMinute = (WORD) getMinutes();
  203781. st.wSecond = (WORD) getSeconds();
  203782. st.wMilliseconds = (WORD) (millisSinceEpoch % 1000);
  203783. // do this twice because of daylight saving conversion problems - the
  203784. // first one sets it up, the second one kicks it in.
  203785. return SetLocalTime (&st) != 0
  203786. && SetLocalTime (&st) != 0;
  203787. }
  203788. int SystemStats::getPageSize()
  203789. {
  203790. SYSTEM_INFO systemInfo;
  203791. GetSystemInfo (&systemInfo);
  203792. return systemInfo.dwPageSize;
  203793. }
  203794. const String SystemStats::getLogonName()
  203795. {
  203796. TCHAR text [256];
  203797. DWORD len = numElementsInArray (text) - 2;
  203798. zerostruct (text);
  203799. GetUserName (text, &len);
  203800. return String (text, len);
  203801. }
  203802. const String SystemStats::getFullUserName()
  203803. {
  203804. return getLogonName();
  203805. }
  203806. #endif
  203807. /*** End of inlined file: juce_win32_SystemStats.cpp ***/
  203808. /*** Start of inlined file: juce_win32_Threads.cpp ***/
  203809. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203810. // compiled on its own).
  203811. #if JUCE_INCLUDED_FILE
  203812. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  203813. extern HWND juce_messageWindowHandle;
  203814. #endif
  203815. #if ! JUCE_USE_INTRINSICS
  203816. // In newer compilers, the inline versions of these are used (in juce_Atomic.h), but in
  203817. // older ones we have to actually call the ops as win32 functions..
  203818. long juce_InterlockedExchange (volatile long* a, long b) throw() { return InterlockedExchange (a, b); }
  203819. long juce_InterlockedIncrement (volatile long* a) throw() { return InterlockedIncrement (a); }
  203820. long juce_InterlockedDecrement (volatile long* a) throw() { return InterlockedDecrement (a); }
  203821. long juce_InterlockedExchangeAdd (volatile long* a, long b) throw() { return InterlockedExchangeAdd (a, b); }
  203822. long juce_InterlockedCompareExchange (volatile long* a, long b, long c) throw() { return InterlockedCompareExchange (a, b, c); }
  203823. __int64 juce_InterlockedCompareExchange64 (volatile __int64* value, __int64 newValue, __int64 valueToCompare) throw()
  203824. {
  203825. jassertfalse; // This operation isn't available in old MS compiler versions!
  203826. __int64 oldValue = *value;
  203827. if (oldValue == valueToCompare)
  203828. *value = newValue;
  203829. return oldValue;
  203830. }
  203831. #endif
  203832. CriticalSection::CriticalSection() throw()
  203833. {
  203834. // (just to check the MS haven't changed this structure and broken things...)
  203835. #if _MSC_VER >= 1400
  203836. static_jassert (sizeof (CRITICAL_SECTION) <= sizeof (internal));
  203837. #else
  203838. static_jassert (sizeof (CRITICAL_SECTION) <= 24);
  203839. #endif
  203840. InitializeCriticalSection ((CRITICAL_SECTION*) internal);
  203841. }
  203842. CriticalSection::~CriticalSection() throw()
  203843. {
  203844. DeleteCriticalSection ((CRITICAL_SECTION*) internal);
  203845. }
  203846. void CriticalSection::enter() const throw()
  203847. {
  203848. EnterCriticalSection ((CRITICAL_SECTION*) internal);
  203849. }
  203850. bool CriticalSection::tryEnter() const throw()
  203851. {
  203852. return TryEnterCriticalSection ((CRITICAL_SECTION*) internal) != FALSE;
  203853. }
  203854. void CriticalSection::exit() const throw()
  203855. {
  203856. LeaveCriticalSection ((CRITICAL_SECTION*) internal);
  203857. }
  203858. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  203859. : internal (CreateEvent (0, manualReset ? TRUE : FALSE, FALSE, 0))
  203860. {
  203861. }
  203862. WaitableEvent::~WaitableEvent() throw()
  203863. {
  203864. CloseHandle (internal);
  203865. }
  203866. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  203867. {
  203868. return WaitForSingleObject (internal, timeOutMillisecs) == WAIT_OBJECT_0;
  203869. }
  203870. void WaitableEvent::signal() const throw()
  203871. {
  203872. SetEvent (internal);
  203873. }
  203874. void WaitableEvent::reset() const throw()
  203875. {
  203876. ResetEvent (internal);
  203877. }
  203878. void JUCE_API juce_threadEntryPoint (void*);
  203879. static unsigned int __stdcall threadEntryProc (void* userData)
  203880. {
  203881. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  203882. AttachThreadInput (GetWindowThreadProcessId (juce_messageWindowHandle, 0),
  203883. GetCurrentThreadId(), TRUE);
  203884. #endif
  203885. juce_threadEntryPoint (userData);
  203886. _endthreadex (0);
  203887. return 0;
  203888. }
  203889. void juce_CloseThreadHandle (void* handle)
  203890. {
  203891. CloseHandle ((HANDLE) handle);
  203892. }
  203893. void* juce_createThread (void* userData)
  203894. {
  203895. unsigned int threadId;
  203896. return (void*) _beginthreadex (0, 0, &threadEntryProc, userData, 0, &threadId);
  203897. }
  203898. void juce_killThread (void* handle)
  203899. {
  203900. if (handle != 0)
  203901. {
  203902. #if JUCE_DEBUG
  203903. OutputDebugString (_T("** Warning - Forced thread termination **\n"));
  203904. #endif
  203905. TerminateThread (handle, 0);
  203906. }
  203907. }
  203908. void juce_setCurrentThreadName (const String& name)
  203909. {
  203910. #if JUCE_DEBUG && JUCE_MSVC
  203911. struct
  203912. {
  203913. DWORD dwType;
  203914. LPCSTR szName;
  203915. DWORD dwThreadID;
  203916. DWORD dwFlags;
  203917. } info;
  203918. info.dwType = 0x1000;
  203919. info.szName = name.toCString();
  203920. info.dwThreadID = GetCurrentThreadId();
  203921. info.dwFlags = 0;
  203922. __try
  203923. {
  203924. RaiseException (0x406d1388 /*MS_VC_EXCEPTION*/, 0, sizeof (info) / sizeof (ULONG_PTR), (ULONG_PTR*) &info);
  203925. }
  203926. __except (EXCEPTION_CONTINUE_EXECUTION)
  203927. {}
  203928. #else
  203929. (void) name;
  203930. #endif
  203931. }
  203932. Thread::ThreadID Thread::getCurrentThreadId()
  203933. {
  203934. return (ThreadID) (pointer_sized_int) GetCurrentThreadId();
  203935. }
  203936. // priority 1 to 10 where 5=normal, 1=low
  203937. bool juce_setThreadPriority (void* threadHandle, int priority)
  203938. {
  203939. int pri = THREAD_PRIORITY_TIME_CRITICAL;
  203940. if (priority < 1) pri = THREAD_PRIORITY_IDLE;
  203941. else if (priority < 2) pri = THREAD_PRIORITY_LOWEST;
  203942. else if (priority < 5) pri = THREAD_PRIORITY_BELOW_NORMAL;
  203943. else if (priority < 7) pri = THREAD_PRIORITY_NORMAL;
  203944. else if (priority < 9) pri = THREAD_PRIORITY_ABOVE_NORMAL;
  203945. else if (priority < 10) pri = THREAD_PRIORITY_HIGHEST;
  203946. if (threadHandle == 0)
  203947. threadHandle = GetCurrentThread();
  203948. return SetThreadPriority (threadHandle, pri) != FALSE;
  203949. }
  203950. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  203951. {
  203952. SetThreadAffinityMask (GetCurrentThread(), affinityMask);
  203953. }
  203954. static HANDLE sleepEvent = 0;
  203955. void juce_initialiseThreadEvents()
  203956. {
  203957. if (sleepEvent == 0)
  203958. #if JUCE_DEBUG
  203959. sleepEvent = CreateEvent (0, 0, 0, _T("Juce Sleep Event"));
  203960. #else
  203961. sleepEvent = CreateEvent (0, 0, 0, 0);
  203962. #endif
  203963. }
  203964. void Thread::yield()
  203965. {
  203966. Sleep (0);
  203967. }
  203968. void JUCE_CALLTYPE Thread::sleep (const int millisecs)
  203969. {
  203970. if (millisecs >= 10)
  203971. {
  203972. Sleep (millisecs);
  203973. }
  203974. else
  203975. {
  203976. jassert (sleepEvent != 0);
  203977. // unlike Sleep() this is guaranteed to return to the current thread after
  203978. // the time expires, so we'll use this for short waits, which are more likely
  203979. // to need to be accurate
  203980. WaitForSingleObject (sleepEvent, millisecs);
  203981. }
  203982. }
  203983. static int lastProcessPriority = -1;
  203984. // called by WindowDriver because Windows does wierd things to process priority
  203985. // when you swap apps, and this forces an update when the app is brought to the front.
  203986. void juce_repeatLastProcessPriority()
  203987. {
  203988. if (lastProcessPriority >= 0) // (avoid changing this if it's not been explicitly set by the app..)
  203989. {
  203990. DWORD p;
  203991. switch (lastProcessPriority)
  203992. {
  203993. case Process::LowPriority: p = IDLE_PRIORITY_CLASS; break;
  203994. case Process::NormalPriority: p = NORMAL_PRIORITY_CLASS; break;
  203995. case Process::HighPriority: p = HIGH_PRIORITY_CLASS; break;
  203996. case Process::RealtimePriority: p = REALTIME_PRIORITY_CLASS; break;
  203997. default: jassertfalse; return; // bad priority value
  203998. }
  203999. SetPriorityClass (GetCurrentProcess(), p);
  204000. }
  204001. }
  204002. void Process::setPriority (ProcessPriority prior)
  204003. {
  204004. if (lastProcessPriority != (int) prior)
  204005. {
  204006. lastProcessPriority = (int) prior;
  204007. juce_repeatLastProcessPriority();
  204008. }
  204009. }
  204010. bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger()
  204011. {
  204012. return IsDebuggerPresent() != FALSE;
  204013. }
  204014. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  204015. {
  204016. return juce_isRunningUnderDebugger();
  204017. }
  204018. void Process::raisePrivilege()
  204019. {
  204020. jassertfalse; // xxx not implemented
  204021. }
  204022. void Process::lowerPrivilege()
  204023. {
  204024. jassertfalse; // xxx not implemented
  204025. }
  204026. void Process::terminate()
  204027. {
  204028. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  204029. _CrtDumpMemoryLeaks();
  204030. #endif
  204031. // bullet in the head in case there's a problem shutting down..
  204032. ExitProcess (0);
  204033. }
  204034. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  204035. {
  204036. void* result = 0;
  204037. JUCE_TRY
  204038. {
  204039. result = LoadLibrary (name);
  204040. }
  204041. JUCE_CATCH_ALL
  204042. return result;
  204043. }
  204044. void PlatformUtilities::freeDynamicLibrary (void* h)
  204045. {
  204046. JUCE_TRY
  204047. {
  204048. if (h != 0)
  204049. FreeLibrary ((HMODULE) h);
  204050. }
  204051. JUCE_CATCH_ALL
  204052. }
  204053. void* PlatformUtilities::getProcedureEntryPoint (void* h, const String& name)
  204054. {
  204055. return (h != 0) ? (void*) GetProcAddress ((HMODULE) h, name.toCString()) : 0; // (void* cast is required for mingw)
  204056. }
  204057. class InterProcessLock::Pimpl
  204058. {
  204059. public:
  204060. Pimpl (const String& name, const int timeOutMillisecs)
  204061. : handle (0), refCount (1)
  204062. {
  204063. handle = CreateMutex (0, TRUE, "Global\\" + name.replaceCharacter ('\\','/'));
  204064. if (handle != 0 && GetLastError() == ERROR_ALREADY_EXISTS)
  204065. {
  204066. if (timeOutMillisecs == 0)
  204067. {
  204068. close();
  204069. return;
  204070. }
  204071. switch (WaitForSingleObject (handle, timeOutMillisecs < 0 ? INFINITE : timeOutMillisecs))
  204072. {
  204073. case WAIT_OBJECT_0:
  204074. case WAIT_ABANDONED:
  204075. break;
  204076. case WAIT_TIMEOUT:
  204077. default:
  204078. close();
  204079. break;
  204080. }
  204081. }
  204082. }
  204083. ~Pimpl()
  204084. {
  204085. close();
  204086. }
  204087. void close()
  204088. {
  204089. if (handle != 0)
  204090. {
  204091. ReleaseMutex (handle);
  204092. CloseHandle (handle);
  204093. handle = 0;
  204094. }
  204095. }
  204096. HANDLE handle;
  204097. int refCount;
  204098. };
  204099. InterProcessLock::InterProcessLock (const String& name_)
  204100. : name (name_)
  204101. {
  204102. }
  204103. InterProcessLock::~InterProcessLock()
  204104. {
  204105. }
  204106. bool InterProcessLock::enter (const int timeOutMillisecs)
  204107. {
  204108. const ScopedLock sl (lock);
  204109. if (pimpl == 0)
  204110. {
  204111. pimpl = new Pimpl (name, timeOutMillisecs);
  204112. if (pimpl->handle == 0)
  204113. pimpl = 0;
  204114. }
  204115. else
  204116. {
  204117. pimpl->refCount++;
  204118. }
  204119. return pimpl != 0;
  204120. }
  204121. void InterProcessLock::exit()
  204122. {
  204123. const ScopedLock sl (lock);
  204124. // Trying to release the lock too many times!
  204125. jassert (pimpl != 0);
  204126. if (pimpl != 0 && --(pimpl->refCount) == 0)
  204127. pimpl = 0;
  204128. }
  204129. #endif
  204130. /*** End of inlined file: juce_win32_Threads.cpp ***/
  204131. /*** Start of inlined file: juce_win32_Files.cpp ***/
  204132. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204133. // compiled on its own).
  204134. #if JUCE_INCLUDED_FILE
  204135. #ifndef CSIDL_MYMUSIC
  204136. #define CSIDL_MYMUSIC 0x000d
  204137. #endif
  204138. #ifndef CSIDL_MYVIDEO
  204139. #define CSIDL_MYVIDEO 0x000e
  204140. #endif
  204141. #ifndef INVALID_FILE_ATTRIBUTES
  204142. #define INVALID_FILE_ATTRIBUTES ((DWORD) -1)
  204143. #endif
  204144. const juce_wchar File::separator = '\\';
  204145. const String File::separatorString ("\\");
  204146. bool File::exists() const
  204147. {
  204148. return fullPath.isNotEmpty()
  204149. && GetFileAttributes (fullPath) != INVALID_FILE_ATTRIBUTES;
  204150. }
  204151. bool File::existsAsFile() const
  204152. {
  204153. return fullPath.isNotEmpty()
  204154. && (GetFileAttributes (fullPath) & FILE_ATTRIBUTE_DIRECTORY) == 0;
  204155. }
  204156. bool File::isDirectory() const
  204157. {
  204158. const DWORD attr = GetFileAttributes (fullPath);
  204159. return ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) && (attr != INVALID_FILE_ATTRIBUTES);
  204160. }
  204161. bool File::hasWriteAccess() const
  204162. {
  204163. if (exists())
  204164. return (GetFileAttributes (fullPath) & FILE_ATTRIBUTE_READONLY) == 0;
  204165. // on windows, it seems that even read-only directories can still be written into,
  204166. // so checking the parent directory's permissions would return the wrong result..
  204167. return true;
  204168. }
  204169. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  204170. {
  204171. DWORD attr = GetFileAttributes (fullPath);
  204172. if (attr == INVALID_FILE_ATTRIBUTES)
  204173. return false;
  204174. if (shouldBeReadOnly == ((attr & FILE_ATTRIBUTE_READONLY) != 0))
  204175. return true;
  204176. if (shouldBeReadOnly)
  204177. attr |= FILE_ATTRIBUTE_READONLY;
  204178. else
  204179. attr &= ~FILE_ATTRIBUTE_READONLY;
  204180. return SetFileAttributes (fullPath, attr) != FALSE;
  204181. }
  204182. bool File::isHidden() const
  204183. {
  204184. return (GetFileAttributes (getFullPathName()) & FILE_ATTRIBUTE_HIDDEN) != 0;
  204185. }
  204186. bool File::deleteFile() const
  204187. {
  204188. if (! exists())
  204189. return true;
  204190. else if (isDirectory())
  204191. return RemoveDirectory (fullPath) != 0;
  204192. else
  204193. return DeleteFile (fullPath) != 0;
  204194. }
  204195. bool File::moveToTrash() const
  204196. {
  204197. if (! exists())
  204198. return true;
  204199. SHFILEOPSTRUCT fos;
  204200. zerostruct (fos);
  204201. // The string we pass in must be double null terminated..
  204202. String doubleNullTermPath (getFullPathName() + " ");
  204203. TCHAR* const p = const_cast <TCHAR*> (static_cast <const TCHAR*> (doubleNullTermPath));
  204204. p [getFullPathName().length()] = 0;
  204205. fos.wFunc = FO_DELETE;
  204206. fos.pFrom = p;
  204207. fos.fFlags = FOF_ALLOWUNDO | FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMATION
  204208. | FOF_NOCONFIRMMKDIR | FOF_RENAMEONCOLLISION;
  204209. return SHFileOperation (&fos) == 0;
  204210. }
  204211. bool File::copyInternal (const File& dest) const
  204212. {
  204213. return CopyFile (fullPath, dest.getFullPathName(), false) != 0;
  204214. }
  204215. bool File::moveInternal (const File& dest) const
  204216. {
  204217. return MoveFile (fullPath, dest.getFullPathName()) != 0;
  204218. }
  204219. void File::createDirectoryInternal (const String& fileName) const
  204220. {
  204221. CreateDirectory (fileName, 0);
  204222. }
  204223. int64 juce_fileSetPosition (void* handle, int64 pos)
  204224. {
  204225. LARGE_INTEGER li;
  204226. li.QuadPart = pos;
  204227. li.LowPart = SetFilePointer ((HANDLE) handle, li.LowPart, &li.HighPart, FILE_BEGIN); // (returns -1 if it fails)
  204228. return li.QuadPart;
  204229. }
  204230. void FileInputStream::openHandle()
  204231. {
  204232. totalSize = file.getSize();
  204233. HANDLE h = CreateFile (file.getFullPathName(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
  204234. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, 0);
  204235. if (h != INVALID_HANDLE_VALUE)
  204236. fileHandle = (void*) h;
  204237. }
  204238. void FileInputStream::closeHandle()
  204239. {
  204240. CloseHandle ((HANDLE) fileHandle);
  204241. }
  204242. size_t FileInputStream::readInternal (void* buffer, size_t numBytes)
  204243. {
  204244. if (fileHandle != 0)
  204245. {
  204246. DWORD actualNum = 0;
  204247. ReadFile ((HANDLE) fileHandle, buffer, numBytes, &actualNum, 0);
  204248. return (size_t) actualNum;
  204249. }
  204250. return 0;
  204251. }
  204252. void FileOutputStream::openHandle()
  204253. {
  204254. HANDLE h = CreateFile (file.getFullPathName(), GENERIC_WRITE, FILE_SHARE_READ, 0,
  204255. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  204256. if (h != INVALID_HANDLE_VALUE)
  204257. {
  204258. LARGE_INTEGER li;
  204259. li.QuadPart = 0;
  204260. li.LowPart = SetFilePointer (h, 0, &li.HighPart, FILE_END);
  204261. if (li.LowPart != INVALID_SET_FILE_POINTER)
  204262. {
  204263. fileHandle = (void*) h;
  204264. currentPosition = li.QuadPart;
  204265. }
  204266. }
  204267. }
  204268. void FileOutputStream::closeHandle()
  204269. {
  204270. CloseHandle ((HANDLE) fileHandle);
  204271. }
  204272. int FileOutputStream::writeInternal (const void* buffer, int numBytes)
  204273. {
  204274. if (fileHandle != 0)
  204275. {
  204276. DWORD actualNum = 0;
  204277. WriteFile ((HANDLE) fileHandle, buffer, numBytes, &actualNum, 0);
  204278. return (int) actualNum;
  204279. }
  204280. return 0;
  204281. }
  204282. void FileOutputStream::flushInternal()
  204283. {
  204284. if (fileHandle != 0)
  204285. FlushFileBuffers ((HANDLE) fileHandle);
  204286. }
  204287. int64 File::getSize() const
  204288. {
  204289. WIN32_FILE_ATTRIBUTE_DATA attributes;
  204290. if (GetFileAttributesEx (fullPath, GetFileExInfoStandard, &attributes))
  204291. return (((int64) attributes.nFileSizeHigh) << 32) | attributes.nFileSizeLow;
  204292. return 0;
  204293. }
  204294. static int64 fileTimeToTime (const FILETIME* const ft)
  204295. {
  204296. static_jassert (sizeof (ULARGE_INTEGER) == sizeof (FILETIME)); // tell me if this fails!
  204297. return (reinterpret_cast<const ULARGE_INTEGER*> (ft)->QuadPart - literal64bit (116444736000000000)) / 10000;
  204298. }
  204299. static void timeToFileTime (const int64 time, FILETIME* const ft)
  204300. {
  204301. reinterpret_cast<ULARGE_INTEGER*> (ft)->QuadPart = time * 10000 + literal64bit (116444736000000000);
  204302. }
  204303. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  204304. {
  204305. WIN32_FILE_ATTRIBUTE_DATA attributes;
  204306. if (GetFileAttributesEx (fullPath, GetFileExInfoStandard, &attributes))
  204307. {
  204308. modificationTime = fileTimeToTime (&attributes.ftLastWriteTime);
  204309. creationTime = fileTimeToTime (&attributes.ftCreationTime);
  204310. accessTime = fileTimeToTime (&attributes.ftLastAccessTime);
  204311. }
  204312. else
  204313. {
  204314. creationTime = accessTime = modificationTime = 0;
  204315. }
  204316. }
  204317. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 creationTime) const
  204318. {
  204319. bool ok = false;
  204320. HANDLE h = CreateFile (fullPath, GENERIC_WRITE, FILE_SHARE_READ, 0,
  204321. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  204322. if (h != INVALID_HANDLE_VALUE)
  204323. {
  204324. FILETIME m, a, c;
  204325. timeToFileTime (modificationTime, &m);
  204326. timeToFileTime (accessTime, &a);
  204327. timeToFileTime (creationTime, &c);
  204328. ok = SetFileTime (h,
  204329. creationTime > 0 ? &c : 0,
  204330. accessTime > 0 ? &a : 0,
  204331. modificationTime > 0 ? &m : 0) != 0;
  204332. CloseHandle (h);
  204333. }
  204334. return ok;
  204335. }
  204336. void File::findFileSystemRoots (Array<File>& destArray)
  204337. {
  204338. TCHAR buffer [2048];
  204339. buffer[0] = 0;
  204340. buffer[1] = 0;
  204341. GetLogicalDriveStrings (2048, buffer);
  204342. const TCHAR* n = buffer;
  204343. StringArray roots;
  204344. while (*n != 0)
  204345. {
  204346. roots.add (String (n));
  204347. while (*n++ != 0)
  204348. {}
  204349. }
  204350. roots.sort (true);
  204351. for (int i = 0; i < roots.size(); ++i)
  204352. destArray.add (roots [i]);
  204353. }
  204354. static const String getDriveFromPath (const String& path)
  204355. {
  204356. if (path.isNotEmpty() && path[1] == ':')
  204357. return path.substring (0, 2) + '\\';
  204358. return path;
  204359. }
  204360. const String File::getVolumeLabel() const
  204361. {
  204362. TCHAR dest[64];
  204363. if (! GetVolumeInformation (getDriveFromPath (getFullPathName()), dest,
  204364. numElementsInArray (dest), 0, 0, 0, 0, 0))
  204365. dest[0] = 0;
  204366. return dest;
  204367. }
  204368. int File::getVolumeSerialNumber() const
  204369. {
  204370. TCHAR dest[64];
  204371. DWORD serialNum;
  204372. if (! GetVolumeInformation (getDriveFromPath (getFullPathName()), dest,
  204373. numElementsInArray (dest), &serialNum, 0, 0, 0, 0))
  204374. return 0;
  204375. return (int) serialNum;
  204376. }
  204377. static int64 getDiskSpaceInfo (const String& path, const bool total)
  204378. {
  204379. ULARGE_INTEGER spc, tot, totFree;
  204380. if (GetDiskFreeSpaceEx (getDriveFromPath (path), &spc, &tot, &totFree))
  204381. return total ? (int64) tot.QuadPart
  204382. : (int64) spc.QuadPart;
  204383. return 0;
  204384. }
  204385. int64 File::getBytesFreeOnVolume() const
  204386. {
  204387. return getDiskSpaceInfo (getFullPathName(), false);
  204388. }
  204389. int64 File::getVolumeTotalSize() const
  204390. {
  204391. return getDiskSpaceInfo (getFullPathName(), true);
  204392. }
  204393. static unsigned int getWindowsDriveType (const String& path)
  204394. {
  204395. return GetDriveType (getDriveFromPath (path));
  204396. }
  204397. bool File::isOnCDRomDrive() const
  204398. {
  204399. return getWindowsDriveType (getFullPathName()) == DRIVE_CDROM;
  204400. }
  204401. bool File::isOnHardDisk() const
  204402. {
  204403. if (fullPath.isEmpty())
  204404. return false;
  204405. const unsigned int n = getWindowsDriveType (getFullPathName());
  204406. if (fullPath.toLowerCase()[0] <= 'b' && fullPath[1] == ':')
  204407. return n != DRIVE_REMOVABLE;
  204408. else
  204409. return n != DRIVE_CDROM && n != DRIVE_REMOTE;
  204410. }
  204411. bool File::isOnRemovableDrive() const
  204412. {
  204413. if (fullPath.isEmpty())
  204414. return false;
  204415. const unsigned int n = getWindowsDriveType (getFullPathName());
  204416. return n == DRIVE_CDROM
  204417. || n == DRIVE_REMOTE
  204418. || n == DRIVE_REMOVABLE
  204419. || n == DRIVE_RAMDISK;
  204420. }
  204421. static const File juce_getSpecialFolderPath (int type)
  204422. {
  204423. WCHAR path [MAX_PATH + 256];
  204424. if (SHGetSpecialFolderPath (0, path, type, FALSE))
  204425. return File (String (path));
  204426. return File::nonexistent;
  204427. }
  204428. const File JUCE_CALLTYPE File::getSpecialLocation (const SpecialLocationType type)
  204429. {
  204430. int csidlType = 0;
  204431. switch (type)
  204432. {
  204433. case userHomeDirectory: csidlType = CSIDL_PROFILE; break;
  204434. case userDocumentsDirectory: csidlType = CSIDL_PERSONAL; break;
  204435. case userDesktopDirectory: csidlType = CSIDL_DESKTOP; break;
  204436. case userApplicationDataDirectory: csidlType = CSIDL_APPDATA; break;
  204437. case commonApplicationDataDirectory: csidlType = CSIDL_COMMON_APPDATA; break;
  204438. case globalApplicationsDirectory: csidlType = CSIDL_PROGRAM_FILES; break;
  204439. case userMusicDirectory: csidlType = CSIDL_MYMUSIC; break;
  204440. case userMoviesDirectory: csidlType = CSIDL_MYVIDEO; break;
  204441. case tempDirectory:
  204442. {
  204443. WCHAR dest [2048];
  204444. dest[0] = 0;
  204445. GetTempPath (numElementsInArray (dest), dest);
  204446. return File (String (dest));
  204447. }
  204448. case invokedExecutableFile:
  204449. case currentExecutableFile:
  204450. case currentApplicationFile:
  204451. {
  204452. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  204453. WCHAR dest [MAX_PATH + 256];
  204454. dest[0] = 0;
  204455. GetModuleFileName (moduleHandle, dest, numElementsInArray (dest));
  204456. return File (String (dest));
  204457. }
  204458. case hostApplicationPath:
  204459. {
  204460. WCHAR dest [MAX_PATH + 256];
  204461. dest[0] = 0;
  204462. GetModuleFileName (0, dest, numElementsInArray (dest));
  204463. return File (String (dest));
  204464. }
  204465. default:
  204466. jassertfalse; // unknown type?
  204467. return File::nonexistent;
  204468. }
  204469. return juce_getSpecialFolderPath (csidlType);
  204470. }
  204471. const File File::getCurrentWorkingDirectory()
  204472. {
  204473. WCHAR dest [MAX_PATH + 256];
  204474. dest[0] = 0;
  204475. GetCurrentDirectory (numElementsInArray (dest), dest);
  204476. return File (String (dest));
  204477. }
  204478. bool File::setAsCurrentWorkingDirectory() const
  204479. {
  204480. return SetCurrentDirectory (getFullPathName()) != FALSE;
  204481. }
  204482. const String File::getVersion() const
  204483. {
  204484. String result;
  204485. DWORD handle = 0;
  204486. DWORD bufferSize = GetFileVersionInfoSize (getFullPathName(), &handle);
  204487. HeapBlock<char> buffer;
  204488. buffer.calloc (bufferSize);
  204489. if (GetFileVersionInfo (getFullPathName(), 0, bufferSize, buffer))
  204490. {
  204491. VS_FIXEDFILEINFO* vffi;
  204492. UINT len = 0;
  204493. if (VerQueryValue (buffer, (LPTSTR) _T("\\"), (LPVOID*) &vffi, &len))
  204494. {
  204495. result << (int) HIWORD (vffi->dwFileVersionMS) << '.'
  204496. << (int) LOWORD (vffi->dwFileVersionMS) << '.'
  204497. << (int) HIWORD (vffi->dwFileVersionLS) << '.'
  204498. << (int) LOWORD (vffi->dwFileVersionLS);
  204499. }
  204500. }
  204501. return result;
  204502. }
  204503. const File File::getLinkedTarget() const
  204504. {
  204505. File result (*this);
  204506. String p (getFullPathName());
  204507. if (! exists())
  204508. p += ".lnk";
  204509. else if (getFileExtension() != ".lnk")
  204510. return result;
  204511. ComSmartPtr <IShellLink> shellLink;
  204512. if (SUCCEEDED (shellLink.CoCreateInstance (CLSID_ShellLink)))
  204513. {
  204514. ComSmartPtr <IPersistFile> persistFile;
  204515. if (SUCCEEDED (shellLink.QueryInterface (IID_IPersistFile, persistFile)))
  204516. {
  204517. if (SUCCEEDED (persistFile->Load ((const WCHAR*) p, STGM_READ))
  204518. && SUCCEEDED (shellLink->Resolve (0, SLR_ANY_MATCH | SLR_NO_UI)))
  204519. {
  204520. WIN32_FIND_DATA winFindData;
  204521. WCHAR resolvedPath [MAX_PATH];
  204522. if (SUCCEEDED (shellLink->GetPath (resolvedPath, MAX_PATH, &winFindData, SLGP_UNCPRIORITY)))
  204523. result = File (resolvedPath);
  204524. }
  204525. }
  204526. }
  204527. return result;
  204528. }
  204529. class DirectoryIterator::NativeIterator::Pimpl
  204530. {
  204531. public:
  204532. Pimpl (const File& directory, const String& wildCard)
  204533. : directoryWithWildCard (File::addTrailingSeparator (directory.getFullPathName()) + wildCard),
  204534. handle (INVALID_HANDLE_VALUE)
  204535. {
  204536. }
  204537. ~Pimpl()
  204538. {
  204539. if (handle != INVALID_HANDLE_VALUE)
  204540. FindClose (handle);
  204541. }
  204542. bool next (String& filenameFound,
  204543. bool* const isDir, bool* const isHidden, int64* const fileSize,
  204544. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  204545. {
  204546. WIN32_FIND_DATA findData;
  204547. if (handle == INVALID_HANDLE_VALUE)
  204548. {
  204549. handle = FindFirstFile (directoryWithWildCard, &findData);
  204550. if (handle == INVALID_HANDLE_VALUE)
  204551. return false;
  204552. }
  204553. else
  204554. {
  204555. if (FindNextFile (handle, &findData) == 0)
  204556. return false;
  204557. }
  204558. filenameFound = findData.cFileName;
  204559. if (isDir != 0) *isDir = ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
  204560. if (isHidden != 0) *isHidden = ((findData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) != 0);
  204561. if (fileSize != 0) *fileSize = findData.nFileSizeLow + (((int64) findData.nFileSizeHigh) << 32);
  204562. if (modTime != 0) *modTime = fileTimeToTime (&findData.ftLastWriteTime);
  204563. if (creationTime != 0) *creationTime = fileTimeToTime (&findData.ftCreationTime);
  204564. if (isReadOnly != 0) *isReadOnly = ((findData.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0);
  204565. return true;
  204566. }
  204567. juce_UseDebuggingNewOperator
  204568. private:
  204569. const String directoryWithWildCard;
  204570. HANDLE handle;
  204571. Pimpl (const Pimpl&);
  204572. Pimpl& operator= (const Pimpl&);
  204573. };
  204574. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  204575. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  204576. {
  204577. }
  204578. DirectoryIterator::NativeIterator::~NativeIterator()
  204579. {
  204580. }
  204581. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  204582. bool* const isDir, bool* const isHidden, int64* const fileSize,
  204583. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  204584. {
  204585. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  204586. }
  204587. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  204588. {
  204589. HINSTANCE hInstance = 0;
  204590. JUCE_TRY
  204591. {
  204592. hInstance = ShellExecute (0, 0, fileName, parameters, 0, SW_SHOWDEFAULT);
  204593. }
  204594. JUCE_CATCH_ALL
  204595. return hInstance > (HINSTANCE) 32;
  204596. }
  204597. void File::revealToUser() const
  204598. {
  204599. if (isDirectory())
  204600. startAsProcess();
  204601. else if (getParentDirectory().exists())
  204602. getParentDirectory().startAsProcess();
  204603. }
  204604. class NamedPipeInternal
  204605. {
  204606. public:
  204607. NamedPipeInternal (const String& file, const bool isPipe_)
  204608. : pipeH (0),
  204609. cancelEvent (0),
  204610. connected (false),
  204611. isPipe (isPipe_)
  204612. {
  204613. cancelEvent = CreateEvent (0, FALSE, FALSE, 0);
  204614. pipeH = isPipe ? CreateNamedPipe (file, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, 0,
  204615. PIPE_UNLIMITED_INSTANCES, 4096, 4096, 0, 0)
  204616. : CreateFile (file, GENERIC_READ | GENERIC_WRITE, 0, 0,
  204617. OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
  204618. }
  204619. ~NamedPipeInternal()
  204620. {
  204621. disconnectPipe();
  204622. if (pipeH != 0)
  204623. CloseHandle (pipeH);
  204624. CloseHandle (cancelEvent);
  204625. }
  204626. bool connect (const int timeOutMs)
  204627. {
  204628. if (! isPipe)
  204629. return true;
  204630. if (! connected)
  204631. {
  204632. OVERLAPPED over;
  204633. zerostruct (over);
  204634. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204635. if (ConnectNamedPipe (pipeH, &over))
  204636. {
  204637. connected = false; // yes, you read that right. In overlapped mode it should always return 0.
  204638. }
  204639. else
  204640. {
  204641. const int err = GetLastError();
  204642. if (err == ERROR_IO_PENDING || err == ERROR_PIPE_LISTENING)
  204643. {
  204644. HANDLE handles[] = { over.hEvent, cancelEvent };
  204645. if (WaitForMultipleObjects (2, handles, FALSE,
  204646. timeOutMs >= 0 ? timeOutMs : INFINITE) == WAIT_OBJECT_0)
  204647. connected = true;
  204648. }
  204649. else if (err == ERROR_PIPE_CONNECTED)
  204650. {
  204651. connected = true;
  204652. }
  204653. }
  204654. CloseHandle (over.hEvent);
  204655. }
  204656. return connected;
  204657. }
  204658. void disconnectPipe()
  204659. {
  204660. if (connected)
  204661. {
  204662. DisconnectNamedPipe (pipeH);
  204663. connected = false;
  204664. }
  204665. }
  204666. HANDLE pipeH;
  204667. HANDLE cancelEvent;
  204668. bool connected, isPipe;
  204669. };
  204670. void NamedPipe::close()
  204671. {
  204672. cancelPendingReads();
  204673. const ScopedLock sl (lock);
  204674. delete static_cast<NamedPipeInternal*> (internal);
  204675. internal = 0;
  204676. }
  204677. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  204678. {
  204679. close();
  204680. ScopedPointer<NamedPipeInternal> intern (new NamedPipeInternal ("\\\\.\\pipe\\" + pipeName, createPipe));
  204681. if (intern->pipeH != INVALID_HANDLE_VALUE)
  204682. {
  204683. internal = intern.release();
  204684. return true;
  204685. }
  204686. return false;
  204687. }
  204688. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds)
  204689. {
  204690. const ScopedLock sl (lock);
  204691. int bytesRead = -1;
  204692. bool waitAgain = true;
  204693. while (waitAgain && internal != 0)
  204694. {
  204695. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  204696. waitAgain = false;
  204697. if (! intern->connect (timeOutMilliseconds))
  204698. break;
  204699. if (maxBytesToRead <= 0)
  204700. return 0;
  204701. OVERLAPPED over;
  204702. zerostruct (over);
  204703. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204704. unsigned long numRead;
  204705. if (ReadFile (intern->pipeH, destBuffer, maxBytesToRead, &numRead, &over))
  204706. {
  204707. bytesRead = (int) numRead;
  204708. }
  204709. else if (GetLastError() == ERROR_IO_PENDING)
  204710. {
  204711. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  204712. DWORD waitResult = WaitForMultipleObjects (2, handles, FALSE,
  204713. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  204714. : INFINITE);
  204715. if (waitResult != WAIT_OBJECT_0)
  204716. {
  204717. // if the operation timed out, let's cancel it...
  204718. CancelIo (intern->pipeH);
  204719. WaitForSingleObject (over.hEvent, INFINITE); // makes sure cancel is complete
  204720. }
  204721. if (GetOverlappedResult (intern->pipeH, &over, &numRead, FALSE))
  204722. {
  204723. bytesRead = (int) numRead;
  204724. }
  204725. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  204726. {
  204727. intern->disconnectPipe();
  204728. waitAgain = true;
  204729. }
  204730. }
  204731. else
  204732. {
  204733. waitAgain = internal != 0;
  204734. Sleep (5);
  204735. }
  204736. CloseHandle (over.hEvent);
  204737. }
  204738. return bytesRead;
  204739. }
  204740. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  204741. {
  204742. int bytesWritten = -1;
  204743. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  204744. if (intern != 0 && intern->connect (timeOutMilliseconds))
  204745. {
  204746. if (numBytesToWrite <= 0)
  204747. return 0;
  204748. OVERLAPPED over;
  204749. zerostruct (over);
  204750. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204751. unsigned long numWritten;
  204752. if (WriteFile (intern->pipeH, sourceBuffer, numBytesToWrite, &numWritten, &over))
  204753. {
  204754. bytesWritten = (int) numWritten;
  204755. }
  204756. else if (GetLastError() == ERROR_IO_PENDING)
  204757. {
  204758. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  204759. DWORD waitResult;
  204760. waitResult = WaitForMultipleObjects (2, handles, FALSE,
  204761. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  204762. : INFINITE);
  204763. if (waitResult != WAIT_OBJECT_0)
  204764. {
  204765. CancelIo (intern->pipeH);
  204766. WaitForSingleObject (over.hEvent, INFINITE);
  204767. }
  204768. if (GetOverlappedResult (intern->pipeH, &over, &numWritten, FALSE))
  204769. {
  204770. bytesWritten = (int) numWritten;
  204771. }
  204772. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  204773. {
  204774. intern->disconnectPipe();
  204775. }
  204776. }
  204777. CloseHandle (over.hEvent);
  204778. }
  204779. return bytesWritten;
  204780. }
  204781. void NamedPipe::cancelPendingReads()
  204782. {
  204783. if (internal != 0)
  204784. SetEvent (static_cast<NamedPipeInternal*> (internal)->cancelEvent);
  204785. }
  204786. #endif
  204787. /*** End of inlined file: juce_win32_Files.cpp ***/
  204788. /*** Start of inlined file: juce_win32_Network.cpp ***/
  204789. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204790. // compiled on its own).
  204791. #if JUCE_INCLUDED_FILE
  204792. #ifndef INTERNET_FLAG_NEED_FILE
  204793. #define INTERNET_FLAG_NEED_FILE 0x00000010
  204794. #endif
  204795. #ifndef INTERNET_OPTION_DISABLE_AUTODIAL
  204796. #define INTERNET_OPTION_DISABLE_AUTODIAL 70
  204797. #endif
  204798. struct ConnectionAndRequestStruct
  204799. {
  204800. HINTERNET connection, request;
  204801. };
  204802. static HINTERNET sessionHandle = 0;
  204803. #ifndef WORKAROUND_TIMEOUT_BUG
  204804. //#define WORKAROUND_TIMEOUT_BUG 1
  204805. #endif
  204806. #if WORKAROUND_TIMEOUT_BUG
  204807. // Required because of a Microsoft bug in setting a timeout
  204808. class InternetConnectThread : public Thread
  204809. {
  204810. public:
  204811. InternetConnectThread (URL_COMPONENTS& uc_, HINTERNET& connection_, const bool isFtp_)
  204812. : Thread ("Internet"), uc (uc_), connection (connection_), isFtp (isFtp_)
  204813. {
  204814. startThread();
  204815. }
  204816. ~InternetConnectThread()
  204817. {
  204818. stopThread (60000);
  204819. }
  204820. void run()
  204821. {
  204822. connection = InternetConnect (sessionHandle, uc.lpszHostName,
  204823. uc.nPort, _T(""), _T(""),
  204824. isFtp ? INTERNET_SERVICE_FTP
  204825. : INTERNET_SERVICE_HTTP,
  204826. 0, 0);
  204827. notify();
  204828. }
  204829. juce_UseDebuggingNewOperator
  204830. private:
  204831. URL_COMPONENTS& uc;
  204832. HINTERNET& connection;
  204833. const bool isFtp;
  204834. InternetConnectThread (const InternetConnectThread&);
  204835. InternetConnectThread& operator= (const InternetConnectThread&);
  204836. };
  204837. #endif
  204838. void* juce_openInternetFile (const String& url,
  204839. const String& headers,
  204840. const MemoryBlock& postData,
  204841. const bool isPost,
  204842. URL::OpenStreamProgressCallback* callback,
  204843. void* callbackContext,
  204844. int timeOutMs)
  204845. {
  204846. if (sessionHandle == 0)
  204847. sessionHandle = InternetOpen (_T("juce"),
  204848. INTERNET_OPEN_TYPE_PRECONFIG,
  204849. 0, 0, 0);
  204850. if (sessionHandle != 0)
  204851. {
  204852. // break up the url..
  204853. TCHAR file[1024], server[1024];
  204854. URL_COMPONENTS uc;
  204855. zerostruct (uc);
  204856. uc.dwStructSize = sizeof (uc);
  204857. uc.dwUrlPathLength = sizeof (file);
  204858. uc.dwHostNameLength = sizeof (server);
  204859. uc.lpszUrlPath = file;
  204860. uc.lpszHostName = server;
  204861. if (InternetCrackUrl (url, 0, 0, &uc))
  204862. {
  204863. int disable = 1;
  204864. InternetSetOption (sessionHandle, INTERNET_OPTION_DISABLE_AUTODIAL, &disable, sizeof (disable));
  204865. if (timeOutMs == 0)
  204866. timeOutMs = 30000;
  204867. else if (timeOutMs < 0)
  204868. timeOutMs = -1;
  204869. InternetSetOption (sessionHandle, INTERNET_OPTION_CONNECT_TIMEOUT, &timeOutMs, sizeof (timeOutMs));
  204870. const bool isFtp = url.startsWithIgnoreCase ("ftp:");
  204871. #if WORKAROUND_TIMEOUT_BUG
  204872. HINTERNET connection = 0;
  204873. {
  204874. InternetConnectThread connectThread (uc, connection, isFtp);
  204875. connectThread.wait (timeOutMs);
  204876. if (connection == 0)
  204877. {
  204878. InternetCloseHandle (sessionHandle);
  204879. sessionHandle = 0;
  204880. }
  204881. }
  204882. #else
  204883. HINTERNET connection = InternetConnect (sessionHandle,
  204884. uc.lpszHostName,
  204885. uc.nPort,
  204886. _T(""), _T(""),
  204887. isFtp ? INTERNET_SERVICE_FTP
  204888. : INTERNET_SERVICE_HTTP,
  204889. 0, 0);
  204890. #endif
  204891. if (connection != 0)
  204892. {
  204893. if (isFtp)
  204894. {
  204895. HINTERNET request = FtpOpenFile (connection,
  204896. uc.lpszUrlPath,
  204897. GENERIC_READ,
  204898. FTP_TRANSFER_TYPE_BINARY | INTERNET_FLAG_NEED_FILE,
  204899. 0);
  204900. ConnectionAndRequestStruct* const result = new ConnectionAndRequestStruct();
  204901. result->connection = connection;
  204902. result->request = request;
  204903. return result;
  204904. }
  204905. else
  204906. {
  204907. const TCHAR* mimeTypes[] = { _T("*/*"), 0 };
  204908. DWORD flags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_NO_COOKIES;
  204909. if (url.startsWithIgnoreCase ("https:"))
  204910. flags |= INTERNET_FLAG_SECURE; // (this flag only seems necessary if the OS is running IE6 -
  204911. // IE7 seems to automatically work out when it's https)
  204912. HINTERNET request = HttpOpenRequest (connection,
  204913. isPost ? _T("POST")
  204914. : _T("GET"),
  204915. uc.lpszUrlPath,
  204916. 0, 0, mimeTypes, flags, 0);
  204917. if (request != 0)
  204918. {
  204919. INTERNET_BUFFERS buffers;
  204920. zerostruct (buffers);
  204921. buffers.dwStructSize = sizeof (INTERNET_BUFFERS);
  204922. buffers.lpcszHeader = (LPCTSTR) headers;
  204923. buffers.dwHeadersLength = headers.length();
  204924. buffers.dwBufferTotal = (DWORD) postData.getSize();
  204925. ConnectionAndRequestStruct* result = 0;
  204926. if (HttpSendRequestEx (request, &buffers, 0, HSR_INITIATE, 0))
  204927. {
  204928. int bytesSent = 0;
  204929. for (;;)
  204930. {
  204931. const int bytesToDo = jmin (1024, (int) postData.getSize() - bytesSent);
  204932. DWORD bytesDone = 0;
  204933. if (bytesToDo > 0
  204934. && ! InternetWriteFile (request,
  204935. static_cast <const char*> (postData.getData()) + bytesSent,
  204936. bytesToDo, &bytesDone))
  204937. {
  204938. break;
  204939. }
  204940. if (bytesToDo == 0 || (int) bytesDone < bytesToDo)
  204941. {
  204942. result = new ConnectionAndRequestStruct();
  204943. result->connection = connection;
  204944. result->request = request;
  204945. if (! HttpEndRequest (request, 0, 0, 0))
  204946. break;
  204947. return result;
  204948. }
  204949. bytesSent += bytesDone;
  204950. if (callback != 0 && ! callback (callbackContext, bytesSent, postData.getSize()))
  204951. break;
  204952. }
  204953. }
  204954. InternetCloseHandle (request);
  204955. }
  204956. InternetCloseHandle (connection);
  204957. }
  204958. }
  204959. }
  204960. }
  204961. return 0;
  204962. }
  204963. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  204964. {
  204965. DWORD bytesRead = 0;
  204966. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  204967. if (crs != 0)
  204968. InternetReadFile (crs->request,
  204969. buffer, bytesToRead,
  204970. &bytesRead);
  204971. return bytesRead;
  204972. }
  204973. int juce_seekInInternetFile (void* handle, int newPosition)
  204974. {
  204975. if (handle != 0)
  204976. {
  204977. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  204978. return InternetSetFilePointer (crs->request, newPosition, 0, FILE_BEGIN, 0);
  204979. }
  204980. return -1;
  204981. }
  204982. int64 juce_getInternetFileContentLength (void* handle)
  204983. {
  204984. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  204985. if (crs != 0)
  204986. {
  204987. DWORD index = 0, result = 0, size = sizeof (result);
  204988. if (HttpQueryInfo (crs->request, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &result, &size, &index))
  204989. return (int64) result;
  204990. }
  204991. return -1;
  204992. }
  204993. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers)
  204994. {
  204995. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  204996. if (crs != 0)
  204997. {
  204998. DWORD bufferSizeBytes = 4096;
  204999. for (;;)
  205000. {
  205001. HeapBlock<char> buffer ((size_t) bufferSizeBytes);
  205002. if (HttpQueryInfo (crs->request, HTTP_QUERY_RAW_HEADERS_CRLF, buffer.getData(), &bufferSizeBytes, 0))
  205003. {
  205004. StringArray headersArray;
  205005. headersArray.addLines (reinterpret_cast <const WCHAR*> (buffer.getData()));
  205006. for (int i = 0; i < headersArray.size(); ++i)
  205007. {
  205008. const String& header = headersArray[i];
  205009. const String key (header.upToFirstOccurrenceOf (": ", false, false));
  205010. const String value (header.fromFirstOccurrenceOf (": ", false, false));
  205011. const String previousValue (headers [key]);
  205012. headers.set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
  205013. }
  205014. break;
  205015. }
  205016. if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
  205017. break;
  205018. }
  205019. }
  205020. }
  205021. void juce_closeInternetFile (void* handle)
  205022. {
  205023. if (handle != 0)
  205024. {
  205025. ScopedPointer <ConnectionAndRequestStruct> crs (static_cast <ConnectionAndRequestStruct*> (handle));
  205026. InternetCloseHandle (crs->request);
  205027. InternetCloseHandle (crs->connection);
  205028. }
  205029. }
  205030. static int getMACAddressViaGetAdaptersInfo (int64* addresses, int maxNum, const bool littleEndian) throw()
  205031. {
  205032. int numFound = 0;
  205033. DynamicLibraryLoader dll ("iphlpapi.dll");
  205034. DynamicLibraryImport (GetAdaptersInfo, getAdaptersInfo, DWORD, dll, (PIP_ADAPTER_INFO, PULONG))
  205035. if (getAdaptersInfo != 0)
  205036. {
  205037. ULONG len = sizeof (IP_ADAPTER_INFO);
  205038. MemoryBlock mb;
  205039. PIP_ADAPTER_INFO adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  205040. if (getAdaptersInfo (adapterInfo, &len) == ERROR_BUFFER_OVERFLOW)
  205041. {
  205042. mb.setSize (len);
  205043. adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  205044. }
  205045. if (getAdaptersInfo (adapterInfo, &len) == NO_ERROR)
  205046. {
  205047. PIP_ADAPTER_INFO adapter = adapterInfo;
  205048. while (adapter != 0)
  205049. {
  205050. int64 mac = 0;
  205051. for (unsigned int i = 0; i < adapter->AddressLength; ++i)
  205052. mac = (mac << 8) | adapter->Address[i];
  205053. if (littleEndian)
  205054. mac = (int64) ByteOrder::swap ((uint64) mac);
  205055. if (numFound < maxNum && mac != 0)
  205056. addresses [numFound++] = mac;
  205057. adapter = adapter->Next;
  205058. }
  205059. }
  205060. }
  205061. return numFound;
  205062. }
  205063. static int getMACAddressesViaNetBios (int64* addresses, int maxNum, const bool littleEndian) throw()
  205064. {
  205065. int numFound = 0;
  205066. DynamicLibraryLoader dll ("netapi32.dll");
  205067. DynamicLibraryImport (Netbios, NetbiosCall, UCHAR, dll, (PNCB))
  205068. if (NetbiosCall != 0)
  205069. {
  205070. NCB ncb;
  205071. zerostruct (ncb);
  205072. struct ASTAT
  205073. {
  205074. ADAPTER_STATUS adapt;
  205075. NAME_BUFFER NameBuff [30];
  205076. };
  205077. ASTAT astat;
  205078. zeromem (&astat, sizeof (astat)); // (can't use zerostruct here in VC6)
  205079. LANA_ENUM enums;
  205080. zerostruct (enums);
  205081. ncb.ncb_command = NCBENUM;
  205082. ncb.ncb_buffer = (unsigned char*) &enums;
  205083. ncb.ncb_length = sizeof (LANA_ENUM);
  205084. NetbiosCall (&ncb);
  205085. for (int i = 0; i < enums.length; ++i)
  205086. {
  205087. zerostruct (ncb);
  205088. ncb.ncb_command = NCBRESET;
  205089. ncb.ncb_lana_num = enums.lana[i];
  205090. if (NetbiosCall (&ncb) == 0)
  205091. {
  205092. zerostruct (ncb);
  205093. memcpy (ncb.ncb_callname, "* ", NCBNAMSZ);
  205094. ncb.ncb_command = NCBASTAT;
  205095. ncb.ncb_lana_num = enums.lana[i];
  205096. ncb.ncb_buffer = (unsigned char*) &astat;
  205097. ncb.ncb_length = sizeof (ASTAT);
  205098. if (NetbiosCall (&ncb) == 0)
  205099. {
  205100. if (astat.adapt.adapter_type == 0xfe)
  205101. {
  205102. uint64 mac = 0;
  205103. for (int i = 6; --i >= 0;)
  205104. mac = (mac << 8) | astat.adapt.adapter_address [littleEndian ? i : (5 - i)];
  205105. if (numFound < maxNum && mac != 0)
  205106. addresses [numFound++] = mac;
  205107. }
  205108. }
  205109. }
  205110. }
  205111. }
  205112. return numFound;
  205113. }
  205114. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  205115. {
  205116. int numFound = getMACAddressViaGetAdaptersInfo (addresses, maxNum, littleEndian);
  205117. if (numFound == 0)
  205118. numFound = getMACAddressesViaNetBios (addresses, maxNum, littleEndian);
  205119. return numFound;
  205120. }
  205121. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  205122. const String& emailSubject,
  205123. const String& bodyText,
  205124. const StringArray& filesToAttach)
  205125. {
  205126. HMODULE h = LoadLibraryA ("MAPI32.dll");
  205127. typedef ULONG (WINAPI *MAPISendMailType) (LHANDLE, ULONG, lpMapiMessage, ::FLAGS, ULONG);
  205128. MAPISendMailType mapiSendMail = (MAPISendMailType) GetProcAddress (h, "MAPISendMail");
  205129. bool ok = false;
  205130. if (mapiSendMail != 0)
  205131. {
  205132. MapiMessage message;
  205133. zerostruct (message);
  205134. message.lpszSubject = (LPSTR) emailSubject.toCString();
  205135. message.lpszNoteText = (LPSTR) bodyText.toCString();
  205136. MapiRecipDesc recip;
  205137. zerostruct (recip);
  205138. recip.ulRecipClass = MAPI_TO;
  205139. String targetEmailAddress_ (targetEmailAddress);
  205140. if (targetEmailAddress_.isEmpty())
  205141. targetEmailAddress_ = " "; // (Windows Mail can't deal with a blank address)
  205142. recip.lpszName = (LPSTR) targetEmailAddress_.toCString();
  205143. message.nRecipCount = 1;
  205144. message.lpRecips = &recip;
  205145. HeapBlock <MapiFileDesc> files;
  205146. files.calloc (filesToAttach.size());
  205147. message.nFileCount = filesToAttach.size();
  205148. message.lpFiles = files;
  205149. for (int i = 0; i < filesToAttach.size(); ++i)
  205150. {
  205151. files[i].nPosition = (ULONG) -1;
  205152. files[i].lpszPathName = (LPSTR) filesToAttach[i].toCString();
  205153. }
  205154. ok = (mapiSendMail (0, 0, &message, MAPI_DIALOG | MAPI_LOGON_UI, 0) == SUCCESS_SUCCESS);
  205155. }
  205156. FreeLibrary (h);
  205157. return ok;
  205158. }
  205159. #endif
  205160. /*** End of inlined file: juce_win32_Network.cpp ***/
  205161. /*** Start of inlined file: juce_win32_PlatformUtils.cpp ***/
  205162. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205163. // compiled on its own).
  205164. #if JUCE_INCLUDED_FILE
  205165. static HKEY findKeyForPath (String name,
  205166. const bool createForWriting,
  205167. String& valueName)
  205168. {
  205169. HKEY rootKey = 0;
  205170. if (name.startsWithIgnoreCase ("HKEY_CURRENT_USER\\"))
  205171. rootKey = HKEY_CURRENT_USER;
  205172. else if (name.startsWithIgnoreCase ("HKEY_LOCAL_MACHINE\\"))
  205173. rootKey = HKEY_LOCAL_MACHINE;
  205174. else if (name.startsWithIgnoreCase ("HKEY_CLASSES_ROOT\\"))
  205175. rootKey = HKEY_CLASSES_ROOT;
  205176. if (rootKey != 0)
  205177. {
  205178. name = name.substring (name.indexOfChar ('\\') + 1);
  205179. const int lastSlash = name.lastIndexOfChar ('\\');
  205180. valueName = name.substring (lastSlash + 1);
  205181. name = name.substring (0, lastSlash);
  205182. HKEY key;
  205183. DWORD result;
  205184. if (createForWriting)
  205185. {
  205186. if (RegCreateKeyEx (rootKey, name, 0, 0, REG_OPTION_NON_VOLATILE,
  205187. (KEY_WRITE | KEY_QUERY_VALUE), 0, &key, &result) == ERROR_SUCCESS)
  205188. return key;
  205189. }
  205190. else
  205191. {
  205192. if (RegOpenKeyEx (rootKey, name, 0, KEY_READ, &key) == ERROR_SUCCESS)
  205193. return key;
  205194. }
  205195. }
  205196. return 0;
  205197. }
  205198. const String PlatformUtilities::getRegistryValue (const String& regValuePath,
  205199. const String& defaultValue)
  205200. {
  205201. String valueName, result (defaultValue);
  205202. HKEY k = findKeyForPath (regValuePath, false, valueName);
  205203. if (k != 0)
  205204. {
  205205. WCHAR buffer [2048];
  205206. unsigned long bufferSize = sizeof (buffer);
  205207. DWORD type = REG_SZ;
  205208. if (RegQueryValueEx (k, valueName, 0, &type, (LPBYTE) buffer, &bufferSize) == ERROR_SUCCESS)
  205209. {
  205210. if (type == REG_SZ)
  205211. result = buffer;
  205212. else if (type == REG_DWORD)
  205213. result = String ((int) *(DWORD*) buffer);
  205214. }
  205215. RegCloseKey (k);
  205216. }
  205217. return result;
  205218. }
  205219. void PlatformUtilities::setRegistryValue (const String& regValuePath,
  205220. const String& value)
  205221. {
  205222. String valueName;
  205223. HKEY k = findKeyForPath (regValuePath, true, valueName);
  205224. if (k != 0)
  205225. {
  205226. RegSetValueEx (k, valueName, 0, REG_SZ,
  205227. (const BYTE*) (const WCHAR*) value,
  205228. sizeof (WCHAR) * (value.length() + 1));
  205229. RegCloseKey (k);
  205230. }
  205231. }
  205232. bool PlatformUtilities::registryValueExists (const String& regValuePath)
  205233. {
  205234. bool exists = false;
  205235. String valueName;
  205236. HKEY k = findKeyForPath (regValuePath, false, valueName);
  205237. if (k != 0)
  205238. {
  205239. unsigned char buffer [2048];
  205240. unsigned long bufferSize = sizeof (buffer);
  205241. DWORD type = 0;
  205242. if (RegQueryValueEx (k, valueName, 0, &type, buffer, &bufferSize) == ERROR_SUCCESS)
  205243. exists = true;
  205244. RegCloseKey (k);
  205245. }
  205246. return exists;
  205247. }
  205248. void PlatformUtilities::deleteRegistryValue (const String& regValuePath)
  205249. {
  205250. String valueName;
  205251. HKEY k = findKeyForPath (regValuePath, true, valueName);
  205252. if (k != 0)
  205253. {
  205254. RegDeleteValue (k, valueName);
  205255. RegCloseKey (k);
  205256. }
  205257. }
  205258. void PlatformUtilities::deleteRegistryKey (const String& regKeyPath)
  205259. {
  205260. String valueName;
  205261. HKEY k = findKeyForPath (regKeyPath, true, valueName);
  205262. if (k != 0)
  205263. {
  205264. RegDeleteKey (k, valueName);
  205265. RegCloseKey (k);
  205266. }
  205267. }
  205268. void PlatformUtilities::registerFileAssociation (const String& fileExtension,
  205269. const String& symbolicDescription,
  205270. const String& fullDescription,
  205271. const File& targetExecutable,
  205272. int iconResourceNumber)
  205273. {
  205274. setRegistryValue ("HKEY_CLASSES_ROOT\\" + fileExtension + "\\", symbolicDescription);
  205275. const String key ("HKEY_CLASSES_ROOT\\" + symbolicDescription);
  205276. if (iconResourceNumber != 0)
  205277. setRegistryValue (key + "\\DefaultIcon\\",
  205278. targetExecutable.getFullPathName() + "," + String (-iconResourceNumber));
  205279. setRegistryValue (key + "\\", fullDescription);
  205280. setRegistryValue (key + "\\shell\\open\\command\\",
  205281. targetExecutable.getFullPathName() + " %1");
  205282. }
  205283. bool juce_IsRunningInWine()
  205284. {
  205285. HKEY key;
  205286. if (RegOpenKeyEx (HKEY_CURRENT_USER, _T("Software\\Wine"), 0, KEY_READ, &key) == ERROR_SUCCESS)
  205287. {
  205288. RegCloseKey (key);
  205289. return true;
  205290. }
  205291. return false;
  205292. }
  205293. const String JUCE_CALLTYPE PlatformUtilities::getCurrentCommandLineParams()
  205294. {
  205295. String s (::GetCommandLineW());
  205296. StringArray tokens;
  205297. tokens.addTokens (s, true); // tokenise so that we can remove the initial filename argument
  205298. return tokens.joinIntoString (" ", 1);
  205299. }
  205300. static void* currentModuleHandle = 0;
  205301. void* PlatformUtilities::getCurrentModuleInstanceHandle() throw()
  205302. {
  205303. if (currentModuleHandle == 0)
  205304. currentModuleHandle = GetModuleHandle (0);
  205305. return currentModuleHandle;
  205306. }
  205307. void PlatformUtilities::setCurrentModuleInstanceHandle (void* const newHandle) throw()
  205308. {
  205309. currentModuleHandle = newHandle;
  205310. }
  205311. void PlatformUtilities::fpuReset()
  205312. {
  205313. #if JUCE_MSVC
  205314. _clearfp();
  205315. #endif
  205316. }
  205317. void PlatformUtilities::beep()
  205318. {
  205319. MessageBeep (MB_OK);
  205320. }
  205321. #endif
  205322. /*** End of inlined file: juce_win32_PlatformUtils.cpp ***/
  205323. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  205324. /*** Start of inlined file: juce_win32_Messaging.cpp ***/
  205325. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205326. // compiled on its own).
  205327. #if JUCE_INCLUDED_FILE
  205328. static const unsigned int specialId = WM_APP + 0x4400;
  205329. static const unsigned int broadcastId = WM_APP + 0x4403;
  205330. static const unsigned int specialCallbackId = WM_APP + 0x4402;
  205331. static const TCHAR* const messageWindowName = _T("JUCEWindow");
  205332. HWND juce_messageWindowHandle = 0;
  205333. extern long improbableWindowNumber; // defined in windowing.cpp
  205334. #ifndef WM_APPCOMMAND
  205335. #define WM_APPCOMMAND 0x0319
  205336. #endif
  205337. static LRESULT CALLBACK juce_MessageWndProc (HWND h,
  205338. const UINT message,
  205339. const WPARAM wParam,
  205340. const LPARAM lParam) throw()
  205341. {
  205342. JUCE_TRY
  205343. {
  205344. if (h == juce_messageWindowHandle)
  205345. {
  205346. if (message == specialCallbackId)
  205347. {
  205348. MessageCallbackFunction* const func = (MessageCallbackFunction*) wParam;
  205349. return (LRESULT) (*func) ((void*) lParam);
  205350. }
  205351. else if (message == specialId)
  205352. {
  205353. // these are trapped early in the dispatch call, but must also be checked
  205354. // here in case there are windows modal dialog boxes doing their own
  205355. // dispatch loop and not calling our version
  205356. MessageManager::getInstance()->deliverMessage ((Message*) lParam);
  205357. return 0;
  205358. }
  205359. else if (message == broadcastId)
  205360. {
  205361. const ScopedPointer <String> messageString ((String*) lParam);
  205362. MessageManager::getInstance()->deliverBroadcastMessage (*messageString);
  205363. return 0;
  205364. }
  205365. else if (message == WM_COPYDATA && ((const COPYDATASTRUCT*) lParam)->dwData == broadcastId)
  205366. {
  205367. const String messageString ((const juce_wchar*) ((const COPYDATASTRUCT*) lParam)->lpData,
  205368. ((const COPYDATASTRUCT*) lParam)->cbData / sizeof (juce_wchar));
  205369. PostMessage (juce_messageWindowHandle, broadcastId, 0, (LPARAM) new String (messageString));
  205370. return 0;
  205371. }
  205372. }
  205373. }
  205374. JUCE_CATCH_EXCEPTION
  205375. return DefWindowProc (h, message, wParam, lParam);
  205376. }
  205377. static bool isEventBlockedByModalComps (MSG& m)
  205378. {
  205379. if (Component::getNumCurrentlyModalComponents() == 0
  205380. || GetWindowLong (m.hwnd, GWLP_USERDATA) == improbableWindowNumber)
  205381. return false;
  205382. switch (m.message)
  205383. {
  205384. case WM_MOUSEMOVE:
  205385. case WM_NCMOUSEMOVE:
  205386. case 0x020A: /* WM_MOUSEWHEEL */
  205387. case 0x020E: /* WM_MOUSEHWHEEL */
  205388. case WM_KEYUP:
  205389. case WM_SYSKEYUP:
  205390. case WM_CHAR:
  205391. case WM_APPCOMMAND:
  205392. case WM_LBUTTONUP:
  205393. case WM_MBUTTONUP:
  205394. case WM_RBUTTONUP:
  205395. case WM_MOUSEACTIVATE:
  205396. case WM_NCMOUSEHOVER:
  205397. case WM_MOUSEHOVER:
  205398. return true;
  205399. case WM_NCLBUTTONDOWN:
  205400. case WM_NCLBUTTONDBLCLK:
  205401. case WM_NCRBUTTONDOWN:
  205402. case WM_NCRBUTTONDBLCLK:
  205403. case WM_NCMBUTTONDOWN:
  205404. case WM_NCMBUTTONDBLCLK:
  205405. case WM_LBUTTONDOWN:
  205406. case WM_LBUTTONDBLCLK:
  205407. case WM_MBUTTONDOWN:
  205408. case WM_MBUTTONDBLCLK:
  205409. case WM_RBUTTONDOWN:
  205410. case WM_RBUTTONDBLCLK:
  205411. case WM_KEYDOWN:
  205412. case WM_SYSKEYDOWN:
  205413. {
  205414. Component* const modal = Component::getCurrentlyModalComponent (0);
  205415. if (modal != 0)
  205416. modal->inputAttemptWhenModal();
  205417. return true;
  205418. }
  205419. default:
  205420. break;
  205421. }
  205422. return false;
  205423. }
  205424. bool juce_dispatchNextMessageOnSystemQueue (const bool returnIfNoPendingMessages)
  205425. {
  205426. MSG m;
  205427. if (returnIfNoPendingMessages && ! PeekMessage (&m, (HWND) 0, 0, 0, 0))
  205428. return false;
  205429. if (GetMessage (&m, (HWND) 0, 0, 0) >= 0)
  205430. {
  205431. if (m.message == specialId && m.hwnd == juce_messageWindowHandle)
  205432. {
  205433. MessageManager::getInstance()->deliverMessage ((Message*) (void*) m.lParam);
  205434. }
  205435. else if (m.message == WM_QUIT)
  205436. {
  205437. if (JUCEApplication::getInstance() != 0)
  205438. JUCEApplication::getInstance()->systemRequestedQuit();
  205439. }
  205440. else if (! isEventBlockedByModalComps (m))
  205441. {
  205442. if ((m.message == WM_LBUTTONDOWN || m.message == WM_RBUTTONDOWN)
  205443. && GetWindowLong (m.hwnd, GWLP_USERDATA) != improbableWindowNumber)
  205444. {
  205445. // if it's someone else's window being clicked on, and the focus is
  205446. // currently on a juce window, pass the kb focus over..
  205447. HWND currentFocus = GetFocus();
  205448. if (currentFocus == 0 || GetWindowLong (currentFocus, GWLP_USERDATA) == improbableWindowNumber)
  205449. SetFocus (m.hwnd);
  205450. }
  205451. TranslateMessage (&m);
  205452. DispatchMessage (&m);
  205453. }
  205454. }
  205455. return true;
  205456. }
  205457. bool juce_postMessageToSystemQueue (Message* message)
  205458. {
  205459. return PostMessage (juce_messageWindowHandle, specialId, 0, (LPARAM) message) != 0;
  205460. }
  205461. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  205462. void* userData)
  205463. {
  205464. if (MessageManager::getInstance()->isThisTheMessageThread())
  205465. {
  205466. return (*callback) (userData);
  205467. }
  205468. else
  205469. {
  205470. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  205471. // deadlock because the message manager is blocked from running, and can't
  205472. // call your function..
  205473. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  205474. return (void*) SendMessage (juce_messageWindowHandle,
  205475. specialCallbackId,
  205476. (WPARAM) callback,
  205477. (LPARAM) userData);
  205478. }
  205479. }
  205480. static BOOL CALLBACK BroadcastEnumWindowProc (HWND hwnd, LPARAM lParam)
  205481. {
  205482. if (hwnd != juce_messageWindowHandle)
  205483. reinterpret_cast <Array<void*>*> (lParam)->add ((void*) hwnd);
  205484. return TRUE;
  205485. }
  205486. void MessageManager::broadcastMessage (const String& value)
  205487. {
  205488. Array<void*> windows;
  205489. EnumWindows (&BroadcastEnumWindowProc, (LPARAM) &windows);
  205490. const String localCopy (value);
  205491. COPYDATASTRUCT data;
  205492. data.dwData = broadcastId;
  205493. data.cbData = (localCopy.length() + 1) * sizeof (juce_wchar);
  205494. data.lpData = (void*) static_cast <const juce_wchar*> (localCopy);
  205495. for (int i = windows.size(); --i >= 0;)
  205496. {
  205497. HWND hwnd = (HWND) windows.getUnchecked(i);
  205498. TCHAR windowName [64]; // no need to read longer strings than this
  205499. GetWindowText (hwnd, windowName, 64);
  205500. windowName [63] = 0;
  205501. if (String (windowName) == messageWindowName)
  205502. {
  205503. DWORD_PTR result;
  205504. SendMessageTimeout (hwnd, WM_COPYDATA,
  205505. (WPARAM) juce_messageWindowHandle,
  205506. (LPARAM) &data,
  205507. SMTO_BLOCK | SMTO_ABORTIFHUNG,
  205508. 8000,
  205509. &result);
  205510. }
  205511. }
  205512. }
  205513. static const String getMessageWindowClassName()
  205514. {
  205515. // this name has to be different for each app/dll instance because otherwise
  205516. // poor old Win32 can get a bit confused (even despite it not being a process-global
  205517. // window class).
  205518. static int number = 0;
  205519. if (number == 0)
  205520. number = 0x7fffffff & (int) Time::getHighResolutionTicks();
  205521. return "JUCEcs_" + String (number);
  205522. }
  205523. void MessageManager::doPlatformSpecificInitialisation()
  205524. {
  205525. OleInitialize (0);
  205526. const String className (getMessageWindowClassName());
  205527. HMODULE hmod = (HMODULE) PlatformUtilities::getCurrentModuleInstanceHandle();
  205528. WNDCLASSEX wc;
  205529. zerostruct (wc);
  205530. wc.cbSize = sizeof (wc);
  205531. wc.lpfnWndProc = (WNDPROC) juce_MessageWndProc;
  205532. wc.cbWndExtra = 4;
  205533. wc.hInstance = hmod;
  205534. wc.lpszClassName = className;
  205535. RegisterClassEx (&wc);
  205536. juce_messageWindowHandle = CreateWindow (wc.lpszClassName,
  205537. messageWindowName,
  205538. 0, 0, 0, 0, 0, 0, 0,
  205539. hmod, 0);
  205540. }
  205541. void MessageManager::doPlatformSpecificShutdown()
  205542. {
  205543. DestroyWindow (juce_messageWindowHandle);
  205544. UnregisterClass (getMessageWindowClassName(), 0);
  205545. OleUninitialize();
  205546. }
  205547. #endif
  205548. /*** End of inlined file: juce_win32_Messaging.cpp ***/
  205549. /*** Start of inlined file: juce_win32_Fonts.cpp ***/
  205550. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205551. // compiled on its own).
  205552. #if JUCE_INCLUDED_FILE
  205553. static int CALLBACK wfontEnum2 (ENUMLOGFONTEXW* lpelfe,
  205554. NEWTEXTMETRICEXW*,
  205555. int type,
  205556. LPARAM lParam)
  205557. {
  205558. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  205559. {
  205560. const String fontName (lpelfe->elfLogFont.lfFaceName);
  205561. ((StringArray*) lParam)->addIfNotAlreadyThere (fontName.removeCharacters ("@"));
  205562. }
  205563. return 1;
  205564. }
  205565. static int CALLBACK wfontEnum1 (ENUMLOGFONTEXW* lpelfe,
  205566. NEWTEXTMETRICEXW*,
  205567. int type,
  205568. LPARAM lParam)
  205569. {
  205570. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  205571. {
  205572. LOGFONTW lf;
  205573. zerostruct (lf);
  205574. lf.lfWeight = FW_DONTCARE;
  205575. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205576. lf.lfQuality = DEFAULT_QUALITY;
  205577. lf.lfCharSet = DEFAULT_CHARSET;
  205578. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205579. lf.lfPitchAndFamily = FF_DONTCARE;
  205580. const String fontName (lpelfe->elfLogFont.lfFaceName);
  205581. fontName.copyToUnicode (lf.lfFaceName, LF_FACESIZE - 1);
  205582. HDC dc = CreateCompatibleDC (0);
  205583. EnumFontFamiliesEx (dc, &lf,
  205584. (FONTENUMPROCW) &wfontEnum2,
  205585. lParam, 0);
  205586. DeleteDC (dc);
  205587. }
  205588. return 1;
  205589. }
  205590. const StringArray Font::findAllTypefaceNames()
  205591. {
  205592. StringArray results;
  205593. HDC dc = CreateCompatibleDC (0);
  205594. {
  205595. LOGFONTW lf;
  205596. zerostruct (lf);
  205597. lf.lfWeight = FW_DONTCARE;
  205598. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205599. lf.lfQuality = DEFAULT_QUALITY;
  205600. lf.lfCharSet = DEFAULT_CHARSET;
  205601. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205602. lf.lfPitchAndFamily = FF_DONTCARE;
  205603. lf.lfFaceName[0] = 0;
  205604. EnumFontFamiliesEx (dc, &lf,
  205605. (FONTENUMPROCW) &wfontEnum1,
  205606. (LPARAM) &results, 0);
  205607. }
  205608. DeleteDC (dc);
  205609. results.sort (true);
  205610. return results;
  205611. }
  205612. extern bool juce_IsRunningInWine();
  205613. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  205614. {
  205615. if (juce_IsRunningInWine())
  205616. {
  205617. // If we're running in Wine, then use fonts that might be available on Linux..
  205618. defaultSans = "Bitstream Vera Sans";
  205619. defaultSerif = "Bitstream Vera Serif";
  205620. defaultFixed = "Bitstream Vera Sans Mono";
  205621. }
  205622. else
  205623. {
  205624. defaultSans = "Verdana";
  205625. defaultSerif = "Times";
  205626. defaultFixed = "Lucida Console";
  205627. }
  205628. }
  205629. class FontDCHolder : private DeletedAtShutdown
  205630. {
  205631. public:
  205632. FontDCHolder()
  205633. : dc (0), numKPs (0), size (0),
  205634. bold (false), italic (false)
  205635. {
  205636. }
  205637. ~FontDCHolder()
  205638. {
  205639. if (dc != 0)
  205640. {
  205641. DeleteDC (dc);
  205642. DeleteObject (fontH);
  205643. }
  205644. clearSingletonInstance();
  205645. }
  205646. juce_DeclareSingleton_SingleThreaded_Minimal (FontDCHolder);
  205647. HDC loadFont (const String& fontName_, const bool bold_, const bool italic_, const int size_)
  205648. {
  205649. if (fontName != fontName_ || bold != bold_ || italic != italic_ || size != size_)
  205650. {
  205651. fontName = fontName_;
  205652. bold = bold_;
  205653. italic = italic_;
  205654. size = size_;
  205655. if (dc != 0)
  205656. {
  205657. DeleteDC (dc);
  205658. DeleteObject (fontH);
  205659. kps.free();
  205660. }
  205661. fontH = 0;
  205662. dc = CreateCompatibleDC (0);
  205663. SetMapperFlags (dc, 0);
  205664. SetMapMode (dc, MM_TEXT);
  205665. LOGFONTW lfw;
  205666. zerostruct (lfw);
  205667. lfw.lfCharSet = DEFAULT_CHARSET;
  205668. lfw.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205669. lfw.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205670. lfw.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
  205671. lfw.lfQuality = PROOF_QUALITY;
  205672. lfw.lfItalic = (BYTE) (italic ? TRUE : FALSE);
  205673. lfw.lfWeight = bold ? FW_BOLD : FW_NORMAL;
  205674. fontName.copyToUnicode (lfw.lfFaceName, LF_FACESIZE - 1);
  205675. lfw.lfHeight = size > 0 ? size : -256;
  205676. HFONT standardSizedFont = CreateFontIndirect (&lfw);
  205677. if (standardSizedFont != 0)
  205678. {
  205679. if (SelectObject (dc, standardSizedFont) != 0)
  205680. {
  205681. fontH = standardSizedFont;
  205682. if (size == 0)
  205683. {
  205684. OUTLINETEXTMETRIC otm;
  205685. if (GetOutlineTextMetrics (dc, sizeof (otm), &otm) != 0)
  205686. {
  205687. lfw.lfHeight = -(int) otm.otmEMSquare;
  205688. fontH = CreateFontIndirect (&lfw);
  205689. SelectObject (dc, fontH);
  205690. DeleteObject (standardSizedFont);
  205691. }
  205692. }
  205693. }
  205694. else
  205695. {
  205696. jassertfalse;
  205697. }
  205698. }
  205699. else
  205700. {
  205701. jassertfalse;
  205702. }
  205703. }
  205704. return dc;
  205705. }
  205706. KERNINGPAIR* getKerningPairs (int& numKPs_)
  205707. {
  205708. if (kps == 0)
  205709. {
  205710. numKPs = GetKerningPairs (dc, 0, 0);
  205711. kps.calloc (numKPs);
  205712. GetKerningPairs (dc, numKPs, kps);
  205713. }
  205714. numKPs_ = numKPs;
  205715. return kps;
  205716. }
  205717. private:
  205718. HFONT fontH;
  205719. HDC dc;
  205720. String fontName;
  205721. HeapBlock <KERNINGPAIR> kps;
  205722. int numKPs, size;
  205723. bool bold, italic;
  205724. FontDCHolder (const FontDCHolder&);
  205725. FontDCHolder& operator= (const FontDCHolder&);
  205726. };
  205727. juce_ImplementSingleton_SingleThreaded (FontDCHolder);
  205728. class WindowsTypeface : public CustomTypeface
  205729. {
  205730. public:
  205731. WindowsTypeface (const Font& font)
  205732. {
  205733. HDC dc = FontDCHolder::getInstance()->loadFont (font.getTypefaceName(),
  205734. font.isBold(), font.isItalic(), 0);
  205735. TEXTMETRIC tm;
  205736. tm.tmAscent = tm.tmHeight = 1;
  205737. tm.tmDefaultChar = 0;
  205738. GetTextMetrics (dc, &tm);
  205739. setCharacteristics (font.getTypefaceName(),
  205740. tm.tmAscent / (float) tm.tmHeight,
  205741. font.isBold(), font.isItalic(),
  205742. tm.tmDefaultChar);
  205743. }
  205744. bool loadGlyphIfPossible (juce_wchar character)
  205745. {
  205746. HDC dc = FontDCHolder::getInstance()->loadFont (name, isBold, isItalic, 0);
  205747. GLYPHMETRICS gm;
  205748. {
  205749. const WCHAR charToTest[] = { (WCHAR) character, 0 };
  205750. WORD index = 0;
  205751. if (GetGlyphIndices (dc, charToTest, 1, &index, GGI_MARK_NONEXISTING_GLYPHS) != GDI_ERROR
  205752. && index == 0xffff)
  205753. {
  205754. return false;
  205755. }
  205756. }
  205757. Path glyphPath;
  205758. TEXTMETRIC tm;
  205759. if (! GetTextMetrics (dc, &tm))
  205760. {
  205761. addGlyph (character, glyphPath, 0);
  205762. return true;
  205763. }
  205764. const float height = (float) tm.tmHeight;
  205765. static const MAT2 identityMatrix = { { 0, 1 }, { 0, 0 }, { 0, 0 }, { 0, 1 } };
  205766. const int bufSize = GetGlyphOutline (dc, character, GGO_NATIVE,
  205767. &gm, 0, 0, &identityMatrix);
  205768. if (bufSize > 0)
  205769. {
  205770. HeapBlock<char> data (bufSize);
  205771. GetGlyphOutline (dc, character, GGO_NATIVE, &gm,
  205772. bufSize, data, &identityMatrix);
  205773. const TTPOLYGONHEADER* pheader = reinterpret_cast<TTPOLYGONHEADER*> (data.getData());
  205774. const float scaleX = 1.0f / height;
  205775. const float scaleY = -1.0f / height;
  205776. while ((char*) pheader < data + bufSize)
  205777. {
  205778. float x = scaleX * pheader->pfxStart.x.value;
  205779. float y = scaleY * pheader->pfxStart.y.value;
  205780. glyphPath.startNewSubPath (x, y);
  205781. const TTPOLYCURVE* curve = (const TTPOLYCURVE*) ((const char*) pheader + sizeof (TTPOLYGONHEADER));
  205782. const char* const curveEnd = ((const char*) pheader) + pheader->cb;
  205783. while ((const char*) curve < curveEnd)
  205784. {
  205785. if (curve->wType == TT_PRIM_LINE)
  205786. {
  205787. for (int i = 0; i < curve->cpfx; ++i)
  205788. {
  205789. x = scaleX * curve->apfx[i].x.value;
  205790. y = scaleY * curve->apfx[i].y.value;
  205791. glyphPath.lineTo (x, y);
  205792. }
  205793. }
  205794. else if (curve->wType == TT_PRIM_QSPLINE)
  205795. {
  205796. for (int i = 0; i < curve->cpfx - 1; ++i)
  205797. {
  205798. const float x2 = scaleX * curve->apfx[i].x.value;
  205799. const float y2 = scaleY * curve->apfx[i].y.value;
  205800. float x3, y3;
  205801. if (i < curve->cpfx - 2)
  205802. {
  205803. x3 = 0.5f * (x2 + scaleX * curve->apfx[i + 1].x.value);
  205804. y3 = 0.5f * (y2 + scaleY * curve->apfx[i + 1].y.value);
  205805. }
  205806. else
  205807. {
  205808. x3 = scaleX * curve->apfx[i + 1].x.value;
  205809. y3 = scaleY * curve->apfx[i + 1].y.value;
  205810. }
  205811. glyphPath.quadraticTo (x2, y2, x3, y3);
  205812. x = x3;
  205813. y = y3;
  205814. }
  205815. }
  205816. curve = (const TTPOLYCURVE*) &(curve->apfx [curve->cpfx]);
  205817. }
  205818. pheader = (const TTPOLYGONHEADER*) curve;
  205819. glyphPath.closeSubPath();
  205820. }
  205821. }
  205822. addGlyph (character, glyphPath, gm.gmCellIncX / height);
  205823. int numKPs;
  205824. const KERNINGPAIR* const kps = FontDCHolder::getInstance()->getKerningPairs (numKPs);
  205825. for (int i = 0; i < numKPs; ++i)
  205826. {
  205827. if (kps[i].wFirst == character)
  205828. addKerningPair (kps[i].wFirst, kps[i].wSecond,
  205829. kps[i].iKernAmount / height);
  205830. }
  205831. return true;
  205832. }
  205833. juce_UseDebuggingNewOperator
  205834. };
  205835. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  205836. {
  205837. return new WindowsTypeface (font);
  205838. }
  205839. #endif
  205840. /*** End of inlined file: juce_win32_Fonts.cpp ***/
  205841. /*** Start of inlined file: juce_win32_Direct2DGraphicsContext.cpp ***/
  205842. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205843. // compiled on its own).
  205844. #if JUCE_INCLUDED_FILE && JUCE_DIRECT2D
  205845. class SharedD2DFactory : public DeletedAtShutdown
  205846. {
  205847. public:
  205848. SharedD2DFactory()
  205849. {
  205850. D2D1CreateFactory (D2D1_FACTORY_TYPE_SINGLE_THREADED, &d2dFactory);
  205851. DWriteCreateFactory (DWRITE_FACTORY_TYPE_SHARED, __uuidof (IDWriteFactory), (IUnknown**) &directWriteFactory);
  205852. if (directWriteFactory != 0)
  205853. directWriteFactory->GetSystemFontCollection (&systemFonts);
  205854. }
  205855. ~SharedD2DFactory()
  205856. {
  205857. clearSingletonInstance();
  205858. }
  205859. juce_DeclareSingleton (SharedD2DFactory, false);
  205860. ComSmartPtr <ID2D1Factory> d2dFactory;
  205861. ComSmartPtr <IDWriteFactory> directWriteFactory;
  205862. ComSmartPtr <IDWriteFontCollection> systemFonts;
  205863. };
  205864. juce_ImplementSingleton (SharedD2DFactory)
  205865. class Direct2DLowLevelGraphicsContext : public LowLevelGraphicsContext
  205866. {
  205867. public:
  205868. Direct2DLowLevelGraphicsContext (HWND hwnd_)
  205869. : hwnd (hwnd_),
  205870. currentState (0)
  205871. {
  205872. RECT windowRect;
  205873. GetClientRect (hwnd, &windowRect);
  205874. D2D1_SIZE_U size = { windowRect.right - windowRect.left, windowRect.bottom - windowRect.top };
  205875. bounds.setSize (size.width, size.height);
  205876. D2D1_RENDER_TARGET_PROPERTIES props = D2D1::RenderTargetProperties();
  205877. D2D1_HWND_RENDER_TARGET_PROPERTIES propsHwnd = D2D1::HwndRenderTargetProperties (hwnd, size);
  205878. HRESULT hr = SharedD2DFactory::getInstance()->d2dFactory->CreateHwndRenderTarget (props, propsHwnd, &renderingTarget);
  205879. // xxx check for error
  205880. hr = renderingTarget->CreateSolidColorBrush (D2D1::ColorF::ColorF (0.0f, 0.0f, 0.0f, 1.0f), &colourBrush);
  205881. }
  205882. ~Direct2DLowLevelGraphicsContext()
  205883. {
  205884. states.clear();
  205885. }
  205886. void resized()
  205887. {
  205888. RECT windowRect;
  205889. GetClientRect (hwnd, &windowRect);
  205890. D2D1_SIZE_U size = { windowRect.right - windowRect.left, windowRect.bottom - windowRect.top };
  205891. renderingTarget->Resize (size);
  205892. bounds.setSize (size.width, size.height);
  205893. }
  205894. void clear()
  205895. {
  205896. renderingTarget->Clear (D2D1::ColorF (D2D1::ColorF::White, 0.0f)); // xxx why white and not black?
  205897. }
  205898. void start()
  205899. {
  205900. renderingTarget->BeginDraw();
  205901. saveState();
  205902. }
  205903. void end()
  205904. {
  205905. states.clear();
  205906. currentState = 0;
  205907. renderingTarget->EndDraw();
  205908. renderingTarget->CheckWindowState();
  205909. }
  205910. bool isVectorDevice() const { return false; }
  205911. void setOrigin (int x, int y)
  205912. {
  205913. currentState->origin.addXY (x, y);
  205914. }
  205915. bool clipToRectangle (const Rectangle<int>& r)
  205916. {
  205917. currentState->clipToRectangle (r);
  205918. return ! isClipEmpty();
  205919. }
  205920. bool clipToRectangleList (const RectangleList& clipRegion)
  205921. {
  205922. currentState->clipToRectList (rectListToPathGeometry (clipRegion));
  205923. return ! isClipEmpty();
  205924. }
  205925. void excludeClipRectangle (const Rectangle<int>&)
  205926. {
  205927. //xxx
  205928. }
  205929. void clipToPath (const Path& path, const AffineTransform& transform)
  205930. {
  205931. currentState->clipToPath (pathToPathGeometry (path, transform, currentState->origin));
  205932. }
  205933. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  205934. {
  205935. currentState->clipToImage (sourceImage,transform);
  205936. }
  205937. bool clipRegionIntersects (const Rectangle<int>& r)
  205938. {
  205939. const Rectangle<int> r2 (r + currentState->origin);
  205940. return currentState->clipRect.intersects (r2);
  205941. }
  205942. const Rectangle<int> getClipBounds() const
  205943. {
  205944. // xxx could this take into account complex clip regions?
  205945. return currentState->clipRect - currentState->origin;
  205946. }
  205947. bool isClipEmpty() const
  205948. {
  205949. return currentState->clipRect.isEmpty();
  205950. }
  205951. void saveState()
  205952. {
  205953. states.add (new SavedState (*this));
  205954. currentState = states.getLast();
  205955. }
  205956. void restoreState()
  205957. {
  205958. jassert (states.size() > 1) //you should never pop the last state!
  205959. states.removeLast (1);
  205960. currentState = states.getLast();
  205961. }
  205962. void setFill (const FillType& fillType)
  205963. {
  205964. currentState->setFill (fillType);
  205965. }
  205966. void setOpacity (float newOpacity)
  205967. {
  205968. currentState->setOpacity (newOpacity);
  205969. }
  205970. void setInterpolationQuality (Graphics::ResamplingQuality /*quality*/)
  205971. {
  205972. }
  205973. void fillRect (const Rectangle<int>& r, bool replaceExistingContents)
  205974. {
  205975. currentState->createBrush();
  205976. renderingTarget->FillRectangle (rectangleToRectF (r + currentState->origin), currentState->currentBrush);
  205977. }
  205978. void fillPath (const Path& p, const AffineTransform& transform)
  205979. {
  205980. currentState->createBrush();
  205981. ComSmartPtr <ID2D1Geometry> geometry (pathToPathGeometry (p, transform, currentState->origin));
  205982. if (renderingTarget != 0)
  205983. renderingTarget->FillGeometry (geometry, currentState->currentBrush);
  205984. }
  205985. void drawImage (const Image& image, const AffineTransform& transform, bool fillEntireClipAsTiles)
  205986. {
  205987. const int x = currentState->origin.getX();
  205988. const int y = currentState->origin.getY();
  205989. renderingTarget->SetTransform (transfromToMatrix (transform) * D2D1::Matrix3x2F::Translation (x, y));
  205990. D2D1_SIZE_U size;
  205991. size.width = image.getWidth();
  205992. size.height = image.getHeight();
  205993. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  205994. Image img (image.convertedToFormat (Image::ARGB));
  205995. Image::BitmapData bd (img, false);
  205996. bp.pixelFormat = renderingTarget->GetPixelFormat();
  205997. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  205998. {
  205999. ComSmartPtr <ID2D1Bitmap> tempBitmap;
  206000. renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, &tempBitmap);
  206001. if (tempBitmap != 0)
  206002. renderingTarget->DrawBitmap (tempBitmap);
  206003. }
  206004. renderingTarget->SetTransform (D2D1::IdentityMatrix());
  206005. }
  206006. void drawLine (const Line <float>& line)
  206007. {
  206008. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  206009. const Line<float> l (line.getStart() + currentState->origin.toFloat(),
  206010. line.getEnd() + currentState->origin.toFloat());
  206011. currentState->createBrush();
  206012. renderingTarget->DrawLine (D2D1::Point2F (l.getStartX(), l.getStartY()),
  206013. D2D1::Point2F (l.getEndX(), l.getEndY()),
  206014. currentState->currentBrush);
  206015. }
  206016. void drawVerticalLine (int x, float top, float bottom)
  206017. {
  206018. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  206019. currentState->createBrush();
  206020. x += currentState->origin.getX();
  206021. const int y = currentState->origin.getY();
  206022. renderingTarget->DrawLine (D2D1::Point2F (x, y + top),
  206023. D2D1::Point2F (x, y + bottom),
  206024. currentState->currentBrush);
  206025. }
  206026. void drawHorizontalLine (int y, float left, float right)
  206027. {
  206028. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  206029. currentState->createBrush();
  206030. y += currentState->origin.getY();
  206031. const int x = currentState->origin.getX();
  206032. renderingTarget->DrawLine (D2D1::Point2F (x + left, y),
  206033. D2D1::Point2F (x + right, y),
  206034. currentState->currentBrush);
  206035. }
  206036. void setFont (const Font& newFont)
  206037. {
  206038. currentState->setFont (newFont);
  206039. }
  206040. const Font getFont()
  206041. {
  206042. return currentState->font;
  206043. }
  206044. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  206045. {
  206046. const float x = currentState->origin.getX();
  206047. const float y = currentState->origin.getY();
  206048. currentState->createBrush();
  206049. currentState->createFont();
  206050. float kerning = currentState->font.getExtraKerningFactor(); // xxx why does removing this line mess up the kerning??
  206051. float hScale = currentState->font.getHorizontalScale();
  206052. renderingTarget->SetTransform (D2D1::Matrix3x2F::Scale (hScale, 1) * transfromToMatrix (transform) * D2D1::Matrix3x2F::Translation (x, y));
  206053. float dpiX = 0, dpiY = 0;
  206054. SharedD2DFactory::getInstance()->d2dFactory->GetDesktopDpi (&dpiX, &dpiY);
  206055. UINT32 glyphNum = glyphNumber;
  206056. UINT16 glyphNum1 = 0; // xxx needs a better name - what is this for?
  206057. currentState->currentFontFace->GetGlyphIndices (&glyphNum, 1, &glyphNum1);
  206058. DWRITE_GLYPH_OFFSET offset;
  206059. offset.advanceOffset = 0;
  206060. offset.ascenderOffset = 0;
  206061. float glyphAdvances = 0;
  206062. DWRITE_GLYPH_RUN glyph;
  206063. glyph.fontFace = currentState->currentFontFace;
  206064. glyph.glyphCount = 1;
  206065. glyph.glyphIndices = &glyphNum1;
  206066. glyph.isSideways = FALSE;
  206067. glyph.glyphAdvances = &glyphAdvances;
  206068. glyph.glyphOffsets = &offset;
  206069. glyph.fontEmSize = (float) currentState->font.getHeight() * dpiX / 96.0f * (1 + currentState->fontScaling) / 2;
  206070. renderingTarget->DrawGlyphRun (D2D1::Point2F (0, 0), &glyph, currentState->currentBrush);
  206071. renderingTarget->SetTransform (D2D1::IdentityMatrix());
  206072. }
  206073. class SavedState
  206074. {
  206075. public:
  206076. SavedState (Direct2DLowLevelGraphicsContext& owner_)
  206077. : owner (owner_), currentBrush (0),
  206078. fontScaling (1.0f), currentFontFace (0),
  206079. clipsRect (false), shouldClipRect (false),
  206080. clipsRectList (false), shouldClipRectList (false),
  206081. clipsComplex (false), shouldClipComplex (false),
  206082. clipsBitmap (false), shouldClipBitmap (false)
  206083. {
  206084. if (owner.currentState != 0)
  206085. {
  206086. // xxx seems like a very slow way to create one of these, and this is a performance
  206087. // bottleneck.. Can the same internal objects be shared by multiple state objects, maybe using copy-on-write?
  206088. setFill (owner.currentState->fillType);
  206089. currentBrush = owner.currentState->currentBrush;
  206090. origin = owner.currentState->origin;
  206091. clipRect = owner.currentState->clipRect;
  206092. font = owner.currentState->font;
  206093. currentFontFace = owner.currentState->currentFontFace;
  206094. }
  206095. else
  206096. {
  206097. const D2D1_SIZE_U size (owner.renderingTarget->GetPixelSize());
  206098. clipRect.setSize (size.width, size.height);
  206099. setFill (FillType (Colours::black));
  206100. }
  206101. }
  206102. ~SavedState()
  206103. {
  206104. clearClip();
  206105. clearFont();
  206106. clearFill();
  206107. clearPathClip();
  206108. clearImageClip();
  206109. complexClipLayer = 0;
  206110. bitmapMaskLayer = 0;
  206111. }
  206112. void clearClip()
  206113. {
  206114. popClips();
  206115. shouldClipRect = false;
  206116. }
  206117. void clipToRectangle (const Rectangle<int>& r)
  206118. {
  206119. clearClip();
  206120. clipRect = r + origin;
  206121. shouldClipRect = true;
  206122. pushClips();
  206123. }
  206124. void clearPathClip()
  206125. {
  206126. popClips();
  206127. if (shouldClipComplex)
  206128. {
  206129. complexClipGeometry = 0;
  206130. shouldClipComplex = false;
  206131. }
  206132. }
  206133. void clipToPath (ID2D1Geometry* geometry)
  206134. {
  206135. clearPathClip();
  206136. if (complexClipLayer == 0)
  206137. owner.renderingTarget->CreateLayer (&complexClipLayer);
  206138. complexClipGeometry = geometry;
  206139. shouldClipComplex = true;
  206140. pushClips();
  206141. }
  206142. void clearRectListClip()
  206143. {
  206144. popClips();
  206145. if (shouldClipRectList)
  206146. {
  206147. rectListGeometry = 0;
  206148. shouldClipRectList = false;
  206149. }
  206150. }
  206151. void clipToRectList (ID2D1Geometry* geometry)
  206152. {
  206153. clearRectListClip();
  206154. if (rectListLayer == 0)
  206155. owner.renderingTarget->CreateLayer (&rectListLayer);
  206156. rectListGeometry = geometry;
  206157. shouldClipRectList = true;
  206158. pushClips();
  206159. }
  206160. void clearImageClip()
  206161. {
  206162. popClips();
  206163. if (shouldClipBitmap)
  206164. {
  206165. maskBitmap = 0;
  206166. bitmapMaskBrush = 0;
  206167. shouldClipBitmap = false;
  206168. }
  206169. }
  206170. void clipToImage (const Image& image, const AffineTransform& transform)
  206171. {
  206172. clearImageClip();
  206173. if (bitmapMaskLayer == 0)
  206174. owner.renderingTarget->CreateLayer (&bitmapMaskLayer);
  206175. D2D1_BRUSH_PROPERTIES brushProps;
  206176. brushProps.opacity = 1;
  206177. brushProps.transform = transfromToMatrix (transform);
  206178. D2D1_BITMAP_BRUSH_PROPERTIES bmProps = D2D1::BitmapBrushProperties (D2D1_EXTEND_MODE_WRAP, D2D1_EXTEND_MODE_WRAP);
  206179. D2D1_SIZE_U size;
  206180. size.width = image.getWidth();
  206181. size.height = image.getHeight();
  206182. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  206183. maskImage = image.convertedToFormat (Image::ARGB);
  206184. Image::BitmapData bd (this->image, false); // xxx should be maskImage?
  206185. bp.pixelFormat = owner.renderingTarget->GetPixelFormat();
  206186. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  206187. HRESULT hr = owner.renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, &maskBitmap);
  206188. hr = owner.renderingTarget->CreateBitmapBrush (maskBitmap, bmProps, brushProps, &bitmapMaskBrush);
  206189. imageMaskLayerParams = D2D1::LayerParameters();
  206190. imageMaskLayerParams.opacityBrush = bitmapMaskBrush;
  206191. shouldClipBitmap = true;
  206192. pushClips();
  206193. }
  206194. void popClips()
  206195. {
  206196. if (clipsBitmap)
  206197. {
  206198. owner.renderingTarget->PopLayer();
  206199. clipsBitmap = false;
  206200. }
  206201. if (clipsComplex)
  206202. {
  206203. owner.renderingTarget->PopLayer();
  206204. clipsComplex = false;
  206205. }
  206206. if (clipsRectList)
  206207. {
  206208. owner.renderingTarget->PopLayer();
  206209. clipsRectList = false;
  206210. }
  206211. if (clipsRect)
  206212. {
  206213. owner.renderingTarget->PopAxisAlignedClip();
  206214. clipsRect = false;
  206215. }
  206216. }
  206217. void pushClips()
  206218. {
  206219. if (shouldClipRect && ! clipsRect)
  206220. {
  206221. owner.renderingTarget->PushAxisAlignedClip (rectangleToRectF (clipRect), D2D1_ANTIALIAS_MODE_PER_PRIMITIVE);
  206222. clipsRect = true;
  206223. }
  206224. if (shouldClipRectList && ! clipsRectList)
  206225. {
  206226. D2D1_LAYER_PARAMETERS layerParams = D2D1::LayerParameters();
  206227. rectListGeometry->GetBounds (D2D1::IdentityMatrix(), &layerParams.contentBounds);
  206228. layerParams.geometricMask = rectListGeometry;
  206229. owner.renderingTarget->PushLayer (layerParams, rectListLayer);
  206230. clipsRectList = true;
  206231. }
  206232. if (shouldClipComplex && ! clipsComplex)
  206233. {
  206234. D2D1_LAYER_PARAMETERS layerParams = D2D1::LayerParameters();
  206235. complexClipGeometry->GetBounds (D2D1::IdentityMatrix(), &layerParams.contentBounds);
  206236. layerParams.geometricMask = complexClipGeometry;
  206237. owner.renderingTarget->PushLayer (layerParams, complexClipLayer);
  206238. clipsComplex = true;
  206239. }
  206240. if (shouldClipBitmap && ! clipsBitmap)
  206241. {
  206242. owner.renderingTarget->PushLayer (imageMaskLayerParams, bitmapMaskLayer);
  206243. clipsBitmap = true;
  206244. }
  206245. }
  206246. void setFill (const FillType& newFillType)
  206247. {
  206248. if (fillType != newFillType)
  206249. {
  206250. fillType = newFillType;
  206251. clearFill();
  206252. }
  206253. }
  206254. void clearFont()
  206255. {
  206256. currentFontFace = localFontFace = 0;
  206257. }
  206258. void setFont (const Font& newFont)
  206259. {
  206260. if (font != newFont)
  206261. {
  206262. font = newFont;
  206263. clearFont();
  206264. }
  206265. }
  206266. void createFont()
  206267. {
  206268. // xxx The font shouldn't be managed by the graphics context.
  206269. // The correct way to handle font lifetimes is to use a subclass of Typeface - see
  206270. // MacTypeface and WindowsTypeface classes. D2D support could probably just be added to the
  206271. // WindowsTypeface class.
  206272. if (currentFontFace == 0)
  206273. {
  206274. WindowsTypeface* systemType = dynamic_cast<WindowsTypeface*> (font.getTypeface());
  206275. fontScaling = systemType->getAscent();
  206276. BOOL fontFound;
  206277. uint32 fontIndex;
  206278. IDWriteFontCollection* fonts = SharedD2DFactory::getInstance()->systemFonts;
  206279. fonts->FindFamilyName (systemType->getName(), &fontIndex, &fontFound);
  206280. if (! fontFound)
  206281. fontIndex = 0;
  206282. ComSmartPtr <IDWriteFontFamily> fontFam;
  206283. fonts->GetFontFamily (fontIndex, &fontFam);
  206284. ComSmartPtr <IDWriteFont> font;
  206285. DWRITE_FONT_WEIGHT weight = this->font.isBold() ? DWRITE_FONT_WEIGHT_BOLD : DWRITE_FONT_WEIGHT_NORMAL;
  206286. DWRITE_FONT_STYLE style = this->font.isItalic() ? DWRITE_FONT_STYLE_ITALIC : DWRITE_FONT_STYLE_NORMAL;
  206287. fontFam->GetFirstMatchingFont (weight, DWRITE_FONT_STRETCH_NORMAL, style, &font);
  206288. font->CreateFontFace (&localFontFace);
  206289. currentFontFace = localFontFace;
  206290. }
  206291. }
  206292. void setOpacity (float newOpacity)
  206293. {
  206294. fillType.setOpacity (newOpacity);
  206295. if (currentBrush != 0)
  206296. currentBrush->SetOpacity (newOpacity);
  206297. }
  206298. void clearFill()
  206299. {
  206300. gradientStops = 0;
  206301. linearGradient = 0;
  206302. radialGradient = 0;
  206303. bitmap = 0;
  206304. bitmapBrush = 0;
  206305. currentBrush = 0;
  206306. }
  206307. void createBrush()
  206308. {
  206309. if (currentBrush == 0)
  206310. {
  206311. const int x = origin.getX();
  206312. const int y = origin.getY();
  206313. if (fillType.isColour())
  206314. {
  206315. D2D1_COLOR_F colour = colourToD2D (fillType.colour);
  206316. owner.colourBrush->SetColor (colour);
  206317. currentBrush = owner.colourBrush;
  206318. }
  206319. else if (fillType.isTiledImage())
  206320. {
  206321. D2D1_BRUSH_PROPERTIES brushProps;
  206322. brushProps.opacity = fillType.getOpacity();
  206323. brushProps.transform = transfromToMatrix (fillType.transform);
  206324. D2D1_BITMAP_BRUSH_PROPERTIES bmProps = D2D1::BitmapBrushProperties (D2D1_EXTEND_MODE_WRAP,D2D1_EXTEND_MODE_WRAP);
  206325. image = fillType.image;
  206326. D2D1_SIZE_U size;
  206327. size.width = image.getWidth();
  206328. size.height = image.getHeight();
  206329. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  206330. this->image = image.convertedToFormat (Image::ARGB);
  206331. Image::BitmapData bd (this->image, false);
  206332. bp.pixelFormat = owner.renderingTarget->GetPixelFormat();
  206333. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  206334. HRESULT hr = owner.renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, &bitmap);
  206335. hr = owner.renderingTarget->CreateBitmapBrush (bitmap, bmProps, brushProps, &bitmapBrush);
  206336. currentBrush = bitmapBrush;
  206337. }
  206338. else if (fillType.isGradient())
  206339. {
  206340. gradientStops = 0;
  206341. D2D1_BRUSH_PROPERTIES brushProps;
  206342. brushProps.opacity = fillType.getOpacity();
  206343. brushProps.transform = transfromToMatrix (fillType.transform);
  206344. const int numColors = fillType.gradient->getNumColours();
  206345. HeapBlock<D2D1_GRADIENT_STOP> stops (numColors);
  206346. for (int i = fillType.gradient->getNumColours(); --i >= 0;)
  206347. {
  206348. stops[i].color = colourToD2D (fillType.gradient->getColour(i));
  206349. stops[i].position = fillType.gradient->getColourPosition(i);
  206350. }
  206351. owner.renderingTarget->CreateGradientStopCollection (stops.getData(), numColors, &gradientStops);
  206352. if (fillType.gradient->isRadial)
  206353. {
  206354. radialGradient = 0;
  206355. const Point<float>& p1 = fillType.gradient->point1;
  206356. const Point<float>& p2 = fillType.gradient->point2;
  206357. float r = p1.getDistanceFrom (p2);
  206358. D2D1_RADIAL_GRADIENT_BRUSH_PROPERTIES props =
  206359. D2D1::RadialGradientBrushProperties (D2D1::Point2F (p1.getX() + x, p1.getY() + y),
  206360. D2D1::Point2F (0, 0),
  206361. r, r);
  206362. owner.renderingTarget->CreateRadialGradientBrush (props, brushProps, gradientStops, &radialGradient);
  206363. currentBrush = radialGradient;
  206364. }
  206365. else
  206366. {
  206367. linearGradient = 0;
  206368. const Point<float>& p1 = fillType.gradient->point1;
  206369. const Point<float>& p2 = fillType.gradient->point2;
  206370. D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES props =
  206371. D2D1::LinearGradientBrushProperties (D2D1::Point2F (p1.getX() + x, p1.getY() + y),
  206372. D2D1::Point2F (p2.getX() + x, p2.getY() + y));
  206373. owner.renderingTarget->CreateLinearGradientBrush (props, brushProps, gradientStops, &linearGradient);
  206374. currentBrush = linearGradient;
  206375. }
  206376. }
  206377. }
  206378. }
  206379. juce_UseDebuggingNewOperator
  206380. //xxx most of these members should probably be private...
  206381. Direct2DLowLevelGraphicsContext& owner;
  206382. Point<int> origin;
  206383. Font font;
  206384. float fontScaling;
  206385. IDWriteFontFace* currentFontFace;
  206386. ComSmartPtr <IDWriteFontFace> localFontFace;
  206387. FillType fillType;
  206388. Image image;
  206389. ComSmartPtr <ID2D1Bitmap> bitmap; // xxx needs a better name - what is this for??
  206390. Rectangle<int> clipRect;
  206391. bool clipsRect, shouldClipRect;
  206392. ComSmartPtr <ID2D1Geometry> complexClipGeometry;
  206393. D2D1_LAYER_PARAMETERS complexClipLayerParams;
  206394. ComSmartPtr <ID2D1Layer> complexClipLayer;
  206395. bool clipsComplex, shouldClipComplex;
  206396. ComSmartPtr <ID2D1Geometry> rectListGeometry;
  206397. D2D1_LAYER_PARAMETERS rectListLayerParams;
  206398. ComSmartPtr <ID2D1Layer> rectListLayer;
  206399. bool clipsRectList, shouldClipRectList;
  206400. Image maskImage;
  206401. D2D1_LAYER_PARAMETERS imageMaskLayerParams;
  206402. ComSmartPtr <ID2D1Layer> bitmapMaskLayer;
  206403. ComSmartPtr <ID2D1Bitmap> maskBitmap;
  206404. ComSmartPtr <ID2D1BitmapBrush> bitmapMaskBrush;
  206405. bool clipsBitmap, shouldClipBitmap;
  206406. ID2D1Brush* currentBrush;
  206407. ComSmartPtr <ID2D1BitmapBrush> bitmapBrush;
  206408. ComSmartPtr <ID2D1LinearGradientBrush> linearGradient;
  206409. ComSmartPtr <ID2D1RadialGradientBrush> radialGradient;
  206410. ComSmartPtr <ID2D1GradientStopCollection> gradientStops;
  206411. private:
  206412. SavedState (const SavedState&);
  206413. SavedState& operator= (const SavedState& other);
  206414. };
  206415. juce_UseDebuggingNewOperator
  206416. private:
  206417. HWND hwnd;
  206418. ComSmartPtr <ID2D1HwndRenderTarget> renderingTarget;
  206419. ComSmartPtr <ID2D1SolidColorBrush> colourBrush;
  206420. Rectangle<int> bounds;
  206421. SavedState* currentState;
  206422. OwnedArray<SavedState> states;
  206423. static D2D1_RECT_F rectangleToRectF (const Rectangle<int>& r)
  206424. {
  206425. return D2D1::RectF ((float) r.getX(), (float) r.getY(), (float) r.getRight(), (float) r.getBottom());
  206426. }
  206427. static const D2D1_COLOR_F colourToD2D (const Colour& c)
  206428. {
  206429. return D2D1::ColorF::ColorF (c.getFloatRed(), c.getFloatGreen(), c.getFloatBlue(), c.getFloatAlpha());
  206430. }
  206431. static const D2D1_POINT_2F pointTransformed (int x, int y, const AffineTransform& transform = AffineTransform::identity)
  206432. {
  206433. transform.transformPoint (x, y);
  206434. return D2D1::Point2F (x, y);
  206435. }
  206436. static void rectToGeometrySink (const Rectangle<int>& rect, ID2D1GeometrySink* sink)
  206437. {
  206438. sink->BeginFigure (pointTransformed (rect.getX(), rect.getY()), D2D1_FIGURE_BEGIN_FILLED);
  206439. sink->AddLine (pointTransformed (rect.getRight(), rect.getY()));
  206440. sink->AddLine (pointTransformed (rect.getRight(), rect.getBottom()));
  206441. sink->AddLine (pointTransformed (rect.getX(), rect.getBottom()));
  206442. sink->EndFigure (D2D1_FIGURE_END_CLOSED);
  206443. }
  206444. static ID2D1PathGeometry* rectListToPathGeometry (const RectangleList& clipRegion)
  206445. {
  206446. ID2D1PathGeometry* p = 0;
  206447. SharedD2DFactory::getInstance()->d2dFactory->CreatePathGeometry (&p);
  206448. ComSmartPtr <ID2D1GeometrySink> sink;
  206449. HRESULT hr = p->Open (&sink); // xxx handle error
  206450. sink->SetFillMode (D2D1_FILL_MODE_WINDING);
  206451. for (int i = clipRegion.getNumRectangles(); --i >= 0;)
  206452. rectToGeometrySink (clipRegion.getRectangle(i), sink);
  206453. hr = sink->Close();
  206454. return p;
  206455. }
  206456. static void pathToGeometrySink (const Path& path, ID2D1GeometrySink* sink, const AffineTransform& transform, int x, int y)
  206457. {
  206458. Path::Iterator it (path);
  206459. while (it.next())
  206460. {
  206461. switch (it.elementType)
  206462. {
  206463. case Path::Iterator::cubicTo:
  206464. {
  206465. D2D1_BEZIER_SEGMENT seg;
  206466. transform.transformPoint (it.x1, it.y1);
  206467. seg.point1 = D2D1::Point2F (it.x1 + x, it.y1 + y);
  206468. transform.transformPoint (it.x2, it.y2);
  206469. seg.point2 = D2D1::Point2F (it.x2 + x, it.y2 + y);
  206470. transform.transformPoint(it.x3, it.y3);
  206471. seg.point3 = D2D1::Point2F (it.x3 + x, it.y3 + y);
  206472. sink->AddBezier (seg);
  206473. break;
  206474. }
  206475. case Path::Iterator::lineTo:
  206476. {
  206477. transform.transformPoint (it.x1, it.y1);
  206478. sink->AddLine (D2D1::Point2F (it.x1 + x, it.y1 + y));
  206479. break;
  206480. }
  206481. case Path::Iterator::quadraticTo:
  206482. {
  206483. D2D1_QUADRATIC_BEZIER_SEGMENT seg;
  206484. transform.transformPoint (it.x1, it.y1);
  206485. seg.point1 = D2D1::Point2F (it.x1 + x, it.y1 + y);
  206486. transform.transformPoint (it.x2, it.y2);
  206487. seg.point2 = D2D1::Point2F (it.x2 + x, it.y2 + y);
  206488. sink->AddQuadraticBezier (seg);
  206489. break;
  206490. }
  206491. case Path::Iterator::closePath:
  206492. {
  206493. sink->EndFigure (D2D1_FIGURE_END_CLOSED);
  206494. break;
  206495. }
  206496. case Path::Iterator::startNewSubPath:
  206497. {
  206498. transform.transformPoint (it.x1, it.y1);
  206499. sink->BeginFigure (D2D1::Point2F (it.x1 + x, it.y1 + y), D2D1_FIGURE_BEGIN_FILLED);
  206500. break;
  206501. }
  206502. }
  206503. }
  206504. }
  206505. static ID2D1PathGeometry* pathToPathGeometry (const Path& path, const AffineTransform& transform, const Point<int>& point)
  206506. {
  206507. ID2D1PathGeometry* p = 0;
  206508. SharedD2DFactory::getInstance()->d2dFactory->CreatePathGeometry (&p);
  206509. ComSmartPtr <ID2D1GeometrySink> sink;
  206510. HRESULT hr = p->Open (&sink);
  206511. sink->SetFillMode (D2D1_FILL_MODE_WINDING); // xxx need to check Path::isUsingNonZeroWinding()
  206512. pathToGeometrySink (path, sink, transform, point.getX(), point.getY());
  206513. hr = sink->Close();
  206514. return p;
  206515. }
  206516. static const D2D1::Matrix3x2F transfromToMatrix (const AffineTransform& transform)
  206517. {
  206518. D2D1::Matrix3x2F matrix;
  206519. matrix._11 = transform.mat00;
  206520. matrix._12 = transform.mat10;
  206521. matrix._21 = transform.mat01;
  206522. matrix._22 = transform.mat11;
  206523. matrix._31 = transform.mat02;
  206524. matrix._32 = transform.mat12;
  206525. return matrix;
  206526. }
  206527. };
  206528. #endif
  206529. /*** End of inlined file: juce_win32_Direct2DGraphicsContext.cpp ***/
  206530. /*** Start of inlined file: juce_win32_Windowing.cpp ***/
  206531. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  206532. // compiled on its own).
  206533. #if JUCE_INCLUDED_FILE
  206534. #undef GetSystemMetrics // multimon overrides this for some reason and causes a mess..
  206535. // these are in the windows SDK, but need to be repeated here for GCC..
  206536. #ifndef GET_APPCOMMAND_LPARAM
  206537. #define FAPPCOMMAND_MASK 0xF000
  206538. #define GET_APPCOMMAND_LPARAM(lParam) ((short) (HIWORD (lParam) & ~FAPPCOMMAND_MASK))
  206539. #define APPCOMMAND_MEDIA_NEXTTRACK 11
  206540. #define APPCOMMAND_MEDIA_PREVIOUSTRACK 12
  206541. #define APPCOMMAND_MEDIA_STOP 13
  206542. #define APPCOMMAND_MEDIA_PLAY_PAUSE 14
  206543. #define WM_APPCOMMAND 0x0319
  206544. #endif
  206545. extern void juce_repeatLastProcessPriority(); // in juce_win32_Threads.cpp
  206546. extern void juce_CheckCurrentlyFocusedTopLevelWindow(); // in juce_TopLevelWindow.cpp
  206547. extern bool juce_IsRunningInWine();
  206548. #ifndef ULW_ALPHA
  206549. #define ULW_ALPHA 0x00000002
  206550. #endif
  206551. #ifndef AC_SRC_ALPHA
  206552. #define AC_SRC_ALPHA 0x01
  206553. #endif
  206554. static HPALETTE palette = 0;
  206555. static bool createPaletteIfNeeded = true;
  206556. static bool shouldDeactivateTitleBar = true;
  206557. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY);
  206558. #define WM_TRAYNOTIFY WM_USER + 100
  206559. using ::abs;
  206560. typedef BOOL (WINAPI* UpdateLayeredWinFunc) (HWND, HDC, POINT*, SIZE*, HDC, POINT*, COLORREF, BLENDFUNCTION*, DWORD);
  206561. static UpdateLayeredWinFunc updateLayeredWindow = 0;
  206562. bool Desktop::canUseSemiTransparentWindows() throw()
  206563. {
  206564. if (updateLayeredWindow == 0)
  206565. {
  206566. if (! juce_IsRunningInWine())
  206567. {
  206568. HMODULE user32Mod = GetModuleHandle (_T("user32.dll"));
  206569. updateLayeredWindow = (UpdateLayeredWinFunc) GetProcAddress (user32Mod, "UpdateLayeredWindow");
  206570. }
  206571. }
  206572. return updateLayeredWindow != 0;
  206573. }
  206574. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  206575. {
  206576. return upright;
  206577. }
  206578. const int extendedKeyModifier = 0x10000;
  206579. const int KeyPress::spaceKey = VK_SPACE;
  206580. const int KeyPress::returnKey = VK_RETURN;
  206581. const int KeyPress::escapeKey = VK_ESCAPE;
  206582. const int KeyPress::backspaceKey = VK_BACK;
  206583. const int KeyPress::deleteKey = VK_DELETE | extendedKeyModifier;
  206584. const int KeyPress::insertKey = VK_INSERT | extendedKeyModifier;
  206585. const int KeyPress::tabKey = VK_TAB;
  206586. const int KeyPress::leftKey = VK_LEFT | extendedKeyModifier;
  206587. const int KeyPress::rightKey = VK_RIGHT | extendedKeyModifier;
  206588. const int KeyPress::upKey = VK_UP | extendedKeyModifier;
  206589. const int KeyPress::downKey = VK_DOWN | extendedKeyModifier;
  206590. const int KeyPress::homeKey = VK_HOME | extendedKeyModifier;
  206591. const int KeyPress::endKey = VK_END | extendedKeyModifier;
  206592. const int KeyPress::pageUpKey = VK_PRIOR | extendedKeyModifier;
  206593. const int KeyPress::pageDownKey = VK_NEXT | extendedKeyModifier;
  206594. const int KeyPress::F1Key = VK_F1 | extendedKeyModifier;
  206595. const int KeyPress::F2Key = VK_F2 | extendedKeyModifier;
  206596. const int KeyPress::F3Key = VK_F3 | extendedKeyModifier;
  206597. const int KeyPress::F4Key = VK_F4 | extendedKeyModifier;
  206598. const int KeyPress::F5Key = VK_F5 | extendedKeyModifier;
  206599. const int KeyPress::F6Key = VK_F6 | extendedKeyModifier;
  206600. const int KeyPress::F7Key = VK_F7 | extendedKeyModifier;
  206601. const int KeyPress::F8Key = VK_F8 | extendedKeyModifier;
  206602. const int KeyPress::F9Key = VK_F9 | extendedKeyModifier;
  206603. const int KeyPress::F10Key = VK_F10 | extendedKeyModifier;
  206604. const int KeyPress::F11Key = VK_F11 | extendedKeyModifier;
  206605. const int KeyPress::F12Key = VK_F12 | extendedKeyModifier;
  206606. const int KeyPress::F13Key = VK_F13 | extendedKeyModifier;
  206607. const int KeyPress::F14Key = VK_F14 | extendedKeyModifier;
  206608. const int KeyPress::F15Key = VK_F15 | extendedKeyModifier;
  206609. const int KeyPress::F16Key = VK_F16 | extendedKeyModifier;
  206610. const int KeyPress::numberPad0 = VK_NUMPAD0 | extendedKeyModifier;
  206611. const int KeyPress::numberPad1 = VK_NUMPAD1 | extendedKeyModifier;
  206612. const int KeyPress::numberPad2 = VK_NUMPAD2 | extendedKeyModifier;
  206613. const int KeyPress::numberPad3 = VK_NUMPAD3 | extendedKeyModifier;
  206614. const int KeyPress::numberPad4 = VK_NUMPAD4 | extendedKeyModifier;
  206615. const int KeyPress::numberPad5 = VK_NUMPAD5 | extendedKeyModifier;
  206616. const int KeyPress::numberPad6 = VK_NUMPAD6 | extendedKeyModifier;
  206617. const int KeyPress::numberPad7 = VK_NUMPAD7 | extendedKeyModifier;
  206618. const int KeyPress::numberPad8 = VK_NUMPAD8 | extendedKeyModifier;
  206619. const int KeyPress::numberPad9 = VK_NUMPAD9 | extendedKeyModifier;
  206620. const int KeyPress::numberPadAdd = VK_ADD | extendedKeyModifier;
  206621. const int KeyPress::numberPadSubtract = VK_SUBTRACT | extendedKeyModifier;
  206622. const int KeyPress::numberPadMultiply = VK_MULTIPLY | extendedKeyModifier;
  206623. const int KeyPress::numberPadDivide = VK_DIVIDE | extendedKeyModifier;
  206624. const int KeyPress::numberPadSeparator = VK_SEPARATOR | extendedKeyModifier;
  206625. const int KeyPress::numberPadDecimalPoint = VK_DECIMAL | extendedKeyModifier;
  206626. const int KeyPress::numberPadEquals = 0x92 /*VK_OEM_NEC_EQUAL*/ | extendedKeyModifier;
  206627. const int KeyPress::numberPadDelete = VK_DELETE | extendedKeyModifier;
  206628. const int KeyPress::playKey = 0x30000;
  206629. const int KeyPress::stopKey = 0x30001;
  206630. const int KeyPress::fastForwardKey = 0x30002;
  206631. const int KeyPress::rewindKey = 0x30003;
  206632. class WindowsBitmapImage : public Image::SharedImage
  206633. {
  206634. public:
  206635. HBITMAP hBitmap;
  206636. BITMAPV4HEADER bitmapInfo;
  206637. HDC hdc;
  206638. unsigned char* bitmapData;
  206639. WindowsBitmapImage (const Image::PixelFormat format_,
  206640. const int w, const int h, const bool clearImage)
  206641. : Image::SharedImage (format_, w, h)
  206642. {
  206643. jassert (format_ == Image::RGB || format_ == Image::ARGB);
  206644. pixelStride = (format_ == Image::RGB) ? 3 : 4;
  206645. zerostruct (bitmapInfo);
  206646. bitmapInfo.bV4Size = sizeof (BITMAPV4HEADER);
  206647. bitmapInfo.bV4Width = w;
  206648. bitmapInfo.bV4Height = h;
  206649. bitmapInfo.bV4Planes = 1;
  206650. bitmapInfo.bV4CSType = 1;
  206651. bitmapInfo.bV4BitCount = (unsigned short) (pixelStride * 8);
  206652. if (format_ == Image::ARGB)
  206653. {
  206654. bitmapInfo.bV4AlphaMask = 0xff000000;
  206655. bitmapInfo.bV4RedMask = 0xff0000;
  206656. bitmapInfo.bV4GreenMask = 0xff00;
  206657. bitmapInfo.bV4BlueMask = 0xff;
  206658. bitmapInfo.bV4V4Compression = BI_BITFIELDS;
  206659. }
  206660. else
  206661. {
  206662. bitmapInfo.bV4V4Compression = BI_RGB;
  206663. }
  206664. lineStride = -((w * pixelStride + 3) & ~3);
  206665. HDC dc = GetDC (0);
  206666. hdc = CreateCompatibleDC (dc);
  206667. ReleaseDC (0, dc);
  206668. SetMapMode (hdc, MM_TEXT);
  206669. hBitmap = CreateDIBSection (hdc,
  206670. (BITMAPINFO*) &(bitmapInfo),
  206671. DIB_RGB_COLORS,
  206672. (void**) &bitmapData,
  206673. 0, 0);
  206674. SelectObject (hdc, hBitmap);
  206675. if (format_ == Image::ARGB && clearImage)
  206676. zeromem (bitmapData, abs (h * lineStride));
  206677. imageData = bitmapData - (lineStride * (h - 1));
  206678. }
  206679. ~WindowsBitmapImage()
  206680. {
  206681. DeleteDC (hdc);
  206682. DeleteObject (hBitmap);
  206683. }
  206684. Image::ImageType getType() const { return Image::NativeImage; }
  206685. LowLevelGraphicsContext* createLowLevelContext()
  206686. {
  206687. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  206688. }
  206689. SharedImage* clone()
  206690. {
  206691. WindowsBitmapImage* im = new WindowsBitmapImage (format, width, height, false);
  206692. for (int i = 0; i < height; ++i)
  206693. memcpy (im->imageData + i * lineStride, imageData + i * lineStride, lineStride);
  206694. return im;
  206695. }
  206696. void blitToWindow (HWND hwnd, HDC dc, const bool transparent,
  206697. const int x, const int y,
  206698. const RectangleList& maskedRegion) throw()
  206699. {
  206700. static HDRAWDIB hdd = 0;
  206701. static bool needToCreateDrawDib = true;
  206702. if (needToCreateDrawDib)
  206703. {
  206704. needToCreateDrawDib = false;
  206705. HDC dc = GetDC (0);
  206706. const int n = GetDeviceCaps (dc, BITSPIXEL);
  206707. ReleaseDC (0, dc);
  206708. // only open if we're not palettised
  206709. if (n > 8)
  206710. hdd = DrawDibOpen();
  206711. }
  206712. if (createPaletteIfNeeded)
  206713. {
  206714. HDC dc = GetDC (0);
  206715. const int n = GetDeviceCaps (dc, BITSPIXEL);
  206716. ReleaseDC (0, dc);
  206717. if (n <= 8)
  206718. palette = CreateHalftonePalette (dc);
  206719. createPaletteIfNeeded = false;
  206720. }
  206721. if (palette != 0)
  206722. {
  206723. SelectPalette (dc, palette, FALSE);
  206724. RealizePalette (dc);
  206725. SetStretchBltMode (dc, HALFTONE);
  206726. }
  206727. SetMapMode (dc, MM_TEXT);
  206728. if (transparent)
  206729. {
  206730. POINT p, pos;
  206731. SIZE size;
  206732. RECT windowBounds;
  206733. GetWindowRect (hwnd, &windowBounds);
  206734. p.x = -x;
  206735. p.y = -y;
  206736. pos.x = windowBounds.left;
  206737. pos.y = windowBounds.top;
  206738. size.cx = windowBounds.right - windowBounds.left;
  206739. size.cy = windowBounds.bottom - windowBounds.top;
  206740. BLENDFUNCTION bf;
  206741. bf.AlphaFormat = AC_SRC_ALPHA;
  206742. bf.BlendFlags = 0;
  206743. bf.BlendOp = AC_SRC_OVER;
  206744. bf.SourceConstantAlpha = 0xff;
  206745. if (! maskedRegion.isEmpty())
  206746. {
  206747. for (RectangleList::Iterator i (maskedRegion); i.next();)
  206748. {
  206749. const Rectangle<int>& r = *i.getRectangle();
  206750. ExcludeClipRect (hdc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  206751. }
  206752. }
  206753. updateLayeredWindow (hwnd, 0, &pos, &size, hdc, &p, 0, &bf, ULW_ALPHA);
  206754. }
  206755. else
  206756. {
  206757. int savedDC = 0;
  206758. if (! maskedRegion.isEmpty())
  206759. {
  206760. savedDC = SaveDC (dc);
  206761. for (RectangleList::Iterator i (maskedRegion); i.next();)
  206762. {
  206763. const Rectangle<int>& r = *i.getRectangle();
  206764. ExcludeClipRect (dc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  206765. }
  206766. }
  206767. if (hdd == 0)
  206768. {
  206769. StretchDIBits (dc,
  206770. x, y, width, height,
  206771. 0, 0, width, height,
  206772. bitmapData, (const BITMAPINFO*) &bitmapInfo,
  206773. DIB_RGB_COLORS, SRCCOPY);
  206774. }
  206775. else
  206776. {
  206777. DrawDibDraw (hdd, dc, x, y, -1, -1,
  206778. (BITMAPINFOHEADER*) &bitmapInfo, bitmapData,
  206779. 0, 0, width, height, 0);
  206780. }
  206781. if (! maskedRegion.isEmpty())
  206782. RestoreDC (dc, savedDC);
  206783. }
  206784. }
  206785. juce_UseDebuggingNewOperator
  206786. private:
  206787. WindowsBitmapImage (const WindowsBitmapImage&);
  206788. WindowsBitmapImage& operator= (const WindowsBitmapImage&);
  206789. };
  206790. long improbableWindowNumber = 0xf965aa01; // also referenced by messaging.cpp
  206791. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  206792. {
  206793. SHORT k = (SHORT) keyCode;
  206794. if ((keyCode & extendedKeyModifier) == 0
  206795. && (k >= (SHORT) 'a' && k <= (SHORT) 'z'))
  206796. k += (SHORT) 'A' - (SHORT) 'a';
  206797. const SHORT translatedValues[] = { (SHORT) ',', VK_OEM_COMMA,
  206798. (SHORT) '+', VK_OEM_PLUS,
  206799. (SHORT) '-', VK_OEM_MINUS,
  206800. (SHORT) '.', VK_OEM_PERIOD,
  206801. (SHORT) ';', VK_OEM_1,
  206802. (SHORT) ':', VK_OEM_1,
  206803. (SHORT) '/', VK_OEM_2,
  206804. (SHORT) '?', VK_OEM_2,
  206805. (SHORT) '[', VK_OEM_4,
  206806. (SHORT) ']', VK_OEM_6 };
  206807. for (int i = 0; i < numElementsInArray (translatedValues); i += 2)
  206808. if (k == translatedValues [i])
  206809. k = translatedValues [i + 1];
  206810. return (GetKeyState (k) & 0x8000) != 0;
  206811. }
  206812. static void* callFunctionIfNotLocked (MessageCallbackFunction* callback, void* userData)
  206813. {
  206814. if (MessageManager::getInstance()->currentThreadHasLockedMessageManager())
  206815. return callback (userData);
  206816. else
  206817. return MessageManager::getInstance()->callFunctionOnMessageThread (callback, userData);
  206818. }
  206819. class Win32ComponentPeer : public ComponentPeer
  206820. {
  206821. public:
  206822. enum RenderingEngineType
  206823. {
  206824. softwareRenderingEngine = 0,
  206825. direct2DRenderingEngine
  206826. };
  206827. Win32ComponentPeer (Component* const component,
  206828. const int windowStyleFlags,
  206829. HWND parentToAddTo_)
  206830. : ComponentPeer (component, windowStyleFlags),
  206831. dontRepaint (false),
  206832. #if JUCE_DIRECT2D
  206833. currentRenderingEngine (direct2DRenderingEngine),
  206834. #else
  206835. currentRenderingEngine (softwareRenderingEngine),
  206836. #endif
  206837. fullScreen (false),
  206838. isDragging (false),
  206839. isMouseOver (false),
  206840. hasCreatedCaret (false),
  206841. currentWindowIcon (0),
  206842. dropTarget (0),
  206843. parentToAddTo (parentToAddTo_)
  206844. {
  206845. callFunctionIfNotLocked (&createWindowCallback, this);
  206846. setTitle (component->getName());
  206847. if ((windowStyleFlags & windowHasDropShadow) != 0
  206848. && Desktop::canUseSemiTransparentWindows())
  206849. {
  206850. shadower = component->getLookAndFeel().createDropShadowerForComponent (component);
  206851. if (shadower != 0)
  206852. shadower->setOwner (component);
  206853. }
  206854. }
  206855. ~Win32ComponentPeer()
  206856. {
  206857. setTaskBarIcon (Image());
  206858. shadower = 0;
  206859. // do this before the next bit to avoid messages arriving for this window
  206860. // before it's destroyed
  206861. SetWindowLongPtr (hwnd, GWLP_USERDATA, 0);
  206862. callFunctionIfNotLocked (&destroyWindowCallback, (void*) hwnd);
  206863. if (currentWindowIcon != 0)
  206864. DestroyIcon (currentWindowIcon);
  206865. if (dropTarget != 0)
  206866. {
  206867. dropTarget->Release();
  206868. dropTarget = 0;
  206869. }
  206870. #if JUCE_DIRECT2D
  206871. direct2DContext = 0;
  206872. #endif
  206873. }
  206874. void* getNativeHandle() const
  206875. {
  206876. return hwnd;
  206877. }
  206878. void setVisible (bool shouldBeVisible)
  206879. {
  206880. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  206881. if (shouldBeVisible)
  206882. InvalidateRect (hwnd, 0, 0);
  206883. else
  206884. lastPaintTime = 0;
  206885. }
  206886. void setTitle (const String& title)
  206887. {
  206888. SetWindowText (hwnd, title);
  206889. }
  206890. void setPosition (int x, int y)
  206891. {
  206892. offsetWithinParent (x, y);
  206893. SetWindowPos (hwnd, 0,
  206894. x - windowBorder.getLeft(),
  206895. y - windowBorder.getTop(),
  206896. 0, 0,
  206897. SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  206898. }
  206899. void repaintNowIfTransparent()
  206900. {
  206901. if (isTransparent() && lastPaintTime > 0 && Time::getMillisecondCounter() > lastPaintTime + 30)
  206902. handlePaintMessage();
  206903. }
  206904. void updateBorderSize()
  206905. {
  206906. WINDOWINFO info;
  206907. info.cbSize = sizeof (info);
  206908. if (GetWindowInfo (hwnd, &info))
  206909. {
  206910. windowBorder = BorderSize (info.rcClient.top - info.rcWindow.top,
  206911. info.rcClient.left - info.rcWindow.left,
  206912. info.rcWindow.bottom - info.rcClient.bottom,
  206913. info.rcWindow.right - info.rcClient.right);
  206914. }
  206915. #if JUCE_DIRECT2D
  206916. if (direct2DContext != 0)
  206917. direct2DContext->resized();
  206918. #endif
  206919. }
  206920. void setSize (int w, int h)
  206921. {
  206922. SetWindowPos (hwnd, 0, 0, 0,
  206923. w + windowBorder.getLeftAndRight(),
  206924. h + windowBorder.getTopAndBottom(),
  206925. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  206926. updateBorderSize();
  206927. repaintNowIfTransparent();
  206928. }
  206929. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  206930. {
  206931. fullScreen = isNowFullScreen;
  206932. offsetWithinParent (x, y);
  206933. SetWindowPos (hwnd, 0,
  206934. x - windowBorder.getLeft(),
  206935. y - windowBorder.getTop(),
  206936. w + windowBorder.getLeftAndRight(),
  206937. h + windowBorder.getTopAndBottom(),
  206938. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  206939. updateBorderSize();
  206940. repaintNowIfTransparent();
  206941. }
  206942. const Rectangle<int> getBounds() const
  206943. {
  206944. RECT r;
  206945. GetWindowRect (hwnd, &r);
  206946. Rectangle<int> bounds (r.left, r.top, r.right - r.left, r.bottom - r.top);
  206947. HWND parentH = GetParent (hwnd);
  206948. if (parentH != 0)
  206949. {
  206950. GetWindowRect (parentH, &r);
  206951. bounds.translate (-r.left, -r.top);
  206952. }
  206953. return windowBorder.subtractedFrom (bounds);
  206954. }
  206955. const Point<int> getScreenPosition() const
  206956. {
  206957. RECT r;
  206958. GetWindowRect (hwnd, &r);
  206959. return Point<int> (r.left + windowBorder.getLeft(),
  206960. r.top + windowBorder.getTop());
  206961. }
  206962. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  206963. {
  206964. return relativePosition + getScreenPosition();
  206965. }
  206966. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  206967. {
  206968. return screenPosition - getScreenPosition();
  206969. }
  206970. void setMinimised (bool shouldBeMinimised)
  206971. {
  206972. if (shouldBeMinimised != isMinimised())
  206973. ShowWindow (hwnd, shouldBeMinimised ? SW_MINIMIZE : SW_SHOWNORMAL);
  206974. }
  206975. bool isMinimised() const
  206976. {
  206977. WINDOWPLACEMENT wp;
  206978. wp.length = sizeof (WINDOWPLACEMENT);
  206979. GetWindowPlacement (hwnd, &wp);
  206980. return wp.showCmd == SW_SHOWMINIMIZED;
  206981. }
  206982. void setFullScreen (bool shouldBeFullScreen)
  206983. {
  206984. setMinimised (false);
  206985. if (fullScreen != shouldBeFullScreen)
  206986. {
  206987. fullScreen = shouldBeFullScreen;
  206988. const Component::SafePointer<Component> deletionChecker (component);
  206989. if (! fullScreen)
  206990. {
  206991. const Rectangle<int> boundsCopy (lastNonFullscreenBounds);
  206992. if (hasTitleBar())
  206993. ShowWindow (hwnd, SW_SHOWNORMAL);
  206994. if (! boundsCopy.isEmpty())
  206995. {
  206996. setBounds (boundsCopy.getX(),
  206997. boundsCopy.getY(),
  206998. boundsCopy.getWidth(),
  206999. boundsCopy.getHeight(),
  207000. false);
  207001. }
  207002. }
  207003. else
  207004. {
  207005. if (hasTitleBar())
  207006. ShowWindow (hwnd, SW_SHOWMAXIMIZED);
  207007. else
  207008. SendMessageW (hwnd, WM_SETTINGCHANGE, 0, 0);
  207009. }
  207010. if (deletionChecker != 0)
  207011. handleMovedOrResized();
  207012. }
  207013. }
  207014. bool isFullScreen() const
  207015. {
  207016. if (! hasTitleBar())
  207017. return fullScreen;
  207018. WINDOWPLACEMENT wp;
  207019. wp.length = sizeof (wp);
  207020. GetWindowPlacement (hwnd, &wp);
  207021. return wp.showCmd == SW_SHOWMAXIMIZED;
  207022. }
  207023. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  207024. {
  207025. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  207026. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  207027. return false;
  207028. RECT r;
  207029. GetWindowRect (hwnd, &r);
  207030. POINT p;
  207031. p.x = position.getX() + r.left + windowBorder.getLeft();
  207032. p.y = position.getY() + r.top + windowBorder.getTop();
  207033. HWND w = WindowFromPoint (p);
  207034. return w == hwnd || (trueIfInAChildWindow && (IsChild (hwnd, w) != 0));
  207035. }
  207036. const BorderSize getFrameSize() const
  207037. {
  207038. return windowBorder;
  207039. }
  207040. bool setAlwaysOnTop (bool alwaysOnTop)
  207041. {
  207042. const bool oldDeactivate = shouldDeactivateTitleBar;
  207043. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  207044. SetWindowPos (hwnd, alwaysOnTop ? HWND_TOPMOST : HWND_NOTOPMOST,
  207045. 0, 0, 0, 0,
  207046. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207047. shouldDeactivateTitleBar = oldDeactivate;
  207048. if (shadower != 0)
  207049. shadower->componentBroughtToFront (*component);
  207050. return true;
  207051. }
  207052. void toFront (bool makeActive)
  207053. {
  207054. setMinimised (false);
  207055. const bool oldDeactivate = shouldDeactivateTitleBar;
  207056. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  207057. callFunctionIfNotLocked (makeActive ? &toFrontCallback1 : &toFrontCallback2, hwnd);
  207058. shouldDeactivateTitleBar = oldDeactivate;
  207059. if (! makeActive)
  207060. {
  207061. // in this case a broughttofront call won't have occured, so do it now..
  207062. handleBroughtToFront();
  207063. }
  207064. }
  207065. void toBehind (ComponentPeer* other)
  207066. {
  207067. Win32ComponentPeer* const otherPeer = dynamic_cast <Win32ComponentPeer*> (other);
  207068. jassert (otherPeer != 0); // wrong type of window?
  207069. if (otherPeer != 0)
  207070. {
  207071. setMinimised (false);
  207072. // must be careful not to try to put a topmost window behind a normal one, or win32
  207073. // promotes the normal one to be topmost!
  207074. if (getComponent()->isAlwaysOnTop() == otherPeer->getComponent()->isAlwaysOnTop())
  207075. SetWindowPos (hwnd, otherPeer->hwnd, 0, 0, 0, 0,
  207076. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207077. else if (otherPeer->getComponent()->isAlwaysOnTop())
  207078. SetWindowPos (hwnd, HWND_TOP, 0, 0, 0, 0,
  207079. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207080. }
  207081. }
  207082. bool isFocused() const
  207083. {
  207084. return callFunctionIfNotLocked (&getFocusCallback, 0) == (void*) hwnd;
  207085. }
  207086. void grabFocus()
  207087. {
  207088. const bool oldDeactivate = shouldDeactivateTitleBar;
  207089. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  207090. callFunctionIfNotLocked (&setFocusCallback, hwnd);
  207091. shouldDeactivateTitleBar = oldDeactivate;
  207092. }
  207093. void textInputRequired (const Point<int>&)
  207094. {
  207095. if (! hasCreatedCaret)
  207096. {
  207097. hasCreatedCaret = true;
  207098. CreateCaret (hwnd, (HBITMAP) 1, 0, 0);
  207099. }
  207100. ShowCaret (hwnd);
  207101. SetCaretPos (0, 0);
  207102. }
  207103. void repaint (const Rectangle<int>& area)
  207104. {
  207105. const RECT r = { area.getX(), area.getY(), area.getRight(), area.getBottom() };
  207106. InvalidateRect (hwnd, &r, FALSE);
  207107. }
  207108. void performAnyPendingRepaintsNow()
  207109. {
  207110. MSG m;
  207111. if (component->isVisible() && PeekMessage (&m, hwnd, WM_PAINT, WM_PAINT, PM_REMOVE))
  207112. DispatchMessage (&m);
  207113. }
  207114. static Win32ComponentPeer* getOwnerOfWindow (HWND h) throw()
  207115. {
  207116. if (h != 0 && GetWindowLongPtr (h, GWLP_USERDATA) == improbableWindowNumber)
  207117. return (Win32ComponentPeer*) (pointer_sized_int) GetWindowLongPtr (h, 8);
  207118. return 0;
  207119. }
  207120. void setTaskBarIcon (const Image& image)
  207121. {
  207122. if (image.isValid())
  207123. {
  207124. HICON hicon = createHICONFromImage (image, TRUE, 0, 0);
  207125. if (taskBarIcon == 0)
  207126. {
  207127. taskBarIcon = new NOTIFYICONDATA();
  207128. taskBarIcon->cbSize = sizeof (NOTIFYICONDATA);
  207129. taskBarIcon->hWnd = (HWND) hwnd;
  207130. taskBarIcon->uID = (int) (pointer_sized_int) hwnd;
  207131. taskBarIcon->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  207132. taskBarIcon->uCallbackMessage = WM_TRAYNOTIFY;
  207133. taskBarIcon->hIcon = hicon;
  207134. taskBarIcon->szTip[0] = 0;
  207135. Shell_NotifyIcon (NIM_ADD, taskBarIcon);
  207136. }
  207137. else
  207138. {
  207139. HICON oldIcon = taskBarIcon->hIcon;
  207140. taskBarIcon->hIcon = hicon;
  207141. taskBarIcon->uFlags = NIF_ICON;
  207142. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  207143. DestroyIcon (oldIcon);
  207144. }
  207145. DestroyIcon (hicon);
  207146. }
  207147. else if (taskBarIcon != 0)
  207148. {
  207149. taskBarIcon->uFlags = 0;
  207150. Shell_NotifyIcon (NIM_DELETE, taskBarIcon);
  207151. DestroyIcon (taskBarIcon->hIcon);
  207152. taskBarIcon = 0;
  207153. }
  207154. }
  207155. void setTaskBarIconToolTip (const String& toolTip) const
  207156. {
  207157. if (taskBarIcon != 0)
  207158. {
  207159. taskBarIcon->uFlags = NIF_TIP;
  207160. toolTip.copyToUnicode (taskBarIcon->szTip, sizeof (taskBarIcon->szTip) - 1);
  207161. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  207162. }
  207163. }
  207164. bool isInside (HWND h) const
  207165. {
  207166. return GetAncestor (hwnd, GA_ROOT) == h;
  207167. }
  207168. static void updateKeyModifiers() throw()
  207169. {
  207170. int keyMods = 0;
  207171. if (GetKeyState (VK_SHIFT) & 0x8000) keyMods |= ModifierKeys::shiftModifier;
  207172. if (GetKeyState (VK_CONTROL) & 0x8000) keyMods |= ModifierKeys::ctrlModifier;
  207173. if (GetKeyState (VK_MENU) & 0x8000) keyMods |= ModifierKeys::altModifier;
  207174. if (GetKeyState (VK_RMENU) & 0x8000) keyMods &= ~(ModifierKeys::ctrlModifier | ModifierKeys::altModifier);
  207175. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  207176. }
  207177. static void updateModifiersFromWParam (const WPARAM wParam)
  207178. {
  207179. int mouseMods = 0;
  207180. if (wParam & MK_LBUTTON) mouseMods |= ModifierKeys::leftButtonModifier;
  207181. if (wParam & MK_RBUTTON) mouseMods |= ModifierKeys::rightButtonModifier;
  207182. if (wParam & MK_MBUTTON) mouseMods |= ModifierKeys::middleButtonModifier;
  207183. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  207184. updateKeyModifiers();
  207185. }
  207186. static int64 getMouseEventTime()
  207187. {
  207188. static int64 eventTimeOffset = 0;
  207189. static DWORD lastMessageTime = 0;
  207190. const DWORD thisMessageTime = GetMessageTime();
  207191. if (thisMessageTime < lastMessageTime || lastMessageTime == 0)
  207192. {
  207193. lastMessageTime = thisMessageTime;
  207194. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  207195. }
  207196. return eventTimeOffset + thisMessageTime;
  207197. }
  207198. juce_UseDebuggingNewOperator
  207199. bool dontRepaint;
  207200. static ModifierKeys currentModifiers;
  207201. static ModifierKeys modifiersAtLastCallback;
  207202. private:
  207203. HWND hwnd, parentToAddTo;
  207204. ScopedPointer<DropShadower> shadower;
  207205. RenderingEngineType currentRenderingEngine;
  207206. #if JUCE_DIRECT2D
  207207. ScopedPointer<Direct2DLowLevelGraphicsContext> direct2DContext;
  207208. #endif
  207209. bool fullScreen, isDragging, isMouseOver, hasCreatedCaret;
  207210. BorderSize windowBorder;
  207211. HICON currentWindowIcon;
  207212. ScopedPointer<NOTIFYICONDATA> taskBarIcon;
  207213. IDropTarget* dropTarget;
  207214. class TemporaryImage : public Timer
  207215. {
  207216. public:
  207217. TemporaryImage() {}
  207218. ~TemporaryImage() {}
  207219. const Image& getImage (const bool transparent, const int w, const int h)
  207220. {
  207221. const Image::PixelFormat format = transparent ? Image::ARGB : Image::RGB;
  207222. if ((! image.isValid()) || image.getWidth() < w || image.getHeight() < h || image.getFormat() != format)
  207223. image = Image (new WindowsBitmapImage (format, (w + 31) & ~31, (h + 31) & ~31, false));
  207224. startTimer (3000);
  207225. return image;
  207226. }
  207227. void timerCallback()
  207228. {
  207229. stopTimer();
  207230. image = Image::null;
  207231. }
  207232. private:
  207233. Image image;
  207234. TemporaryImage (const TemporaryImage&);
  207235. TemporaryImage& operator= (const TemporaryImage&);
  207236. };
  207237. TemporaryImage offscreenImageGenerator;
  207238. class WindowClassHolder : public DeletedAtShutdown
  207239. {
  207240. public:
  207241. WindowClassHolder()
  207242. : windowClassName ("JUCE_")
  207243. {
  207244. // this name has to be different for each app/dll instance because otherwise
  207245. // poor old Win32 can get a bit confused (even despite it not being a process-global
  207246. // window class).
  207247. windowClassName << (int) (Time::currentTimeMillis() & 0x7fffffff);
  207248. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  207249. TCHAR moduleFile [1024];
  207250. moduleFile[0] = 0;
  207251. GetModuleFileName (moduleHandle, moduleFile, 1024);
  207252. WORD iconNum = 0;
  207253. WNDCLASSEX wcex;
  207254. wcex.cbSize = sizeof (wcex);
  207255. wcex.style = CS_OWNDC;
  207256. wcex.lpfnWndProc = (WNDPROC) windowProc;
  207257. wcex.lpszClassName = windowClassName;
  207258. wcex.cbClsExtra = 0;
  207259. wcex.cbWndExtra = 32;
  207260. wcex.hInstance = moduleHandle;
  207261. wcex.hIcon = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  207262. iconNum = 1;
  207263. wcex.hIconSm = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  207264. wcex.hCursor = 0;
  207265. wcex.hbrBackground = 0;
  207266. wcex.lpszMenuName = 0;
  207267. RegisterClassEx (&wcex);
  207268. }
  207269. ~WindowClassHolder()
  207270. {
  207271. if (ComponentPeer::getNumPeers() == 0)
  207272. UnregisterClass (windowClassName, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle());
  207273. clearSingletonInstance();
  207274. }
  207275. String windowClassName;
  207276. juce_DeclareSingleton_SingleThreaded_Minimal (WindowClassHolder);
  207277. };
  207278. static void* createWindowCallback (void* userData)
  207279. {
  207280. static_cast <Win32ComponentPeer*> (userData)->createWindow();
  207281. return 0;
  207282. }
  207283. void createWindow()
  207284. {
  207285. DWORD exstyle = WS_EX_ACCEPTFILES;
  207286. DWORD type = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
  207287. if (hasTitleBar())
  207288. {
  207289. type |= WS_OVERLAPPED;
  207290. if ((styleFlags & windowHasCloseButton) != 0)
  207291. {
  207292. type |= WS_SYSMENU;
  207293. }
  207294. else
  207295. {
  207296. // annoyingly, windows won't let you have a min/max button without a close button
  207297. jassert ((styleFlags & (windowHasMinimiseButton | windowHasMaximiseButton)) == 0);
  207298. }
  207299. if ((styleFlags & windowIsResizable) != 0)
  207300. type |= WS_THICKFRAME;
  207301. }
  207302. else if (parentToAddTo != 0)
  207303. {
  207304. type |= WS_CHILD;
  207305. }
  207306. else
  207307. {
  207308. type |= WS_POPUP | WS_SYSMENU;
  207309. }
  207310. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  207311. exstyle |= WS_EX_TOOLWINDOW;
  207312. else
  207313. exstyle |= WS_EX_APPWINDOW;
  207314. if ((styleFlags & windowHasMinimiseButton) != 0)
  207315. type |= WS_MINIMIZEBOX;
  207316. if ((styleFlags & windowHasMaximiseButton) != 0)
  207317. type |= WS_MAXIMIZEBOX;
  207318. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  207319. exstyle |= WS_EX_TRANSPARENT;
  207320. if ((styleFlags & windowIsSemiTransparent) != 0
  207321. && Desktop::canUseSemiTransparentWindows())
  207322. exstyle |= WS_EX_LAYERED;
  207323. hwnd = CreateWindowEx (exstyle, WindowClassHolder::getInstance()->windowClassName, L"", type, 0, 0, 0, 0,
  207324. parentToAddTo, 0, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(), 0);
  207325. #if JUCE_DIRECT2D
  207326. updateDirect2DContext();
  207327. #endif
  207328. if (hwnd != 0)
  207329. {
  207330. SetWindowLongPtr (hwnd, 0, 0);
  207331. SetWindowLongPtr (hwnd, 8, (LONG_PTR) this);
  207332. SetWindowLongPtr (hwnd, GWLP_USERDATA, improbableWindowNumber);
  207333. if (dropTarget == 0)
  207334. dropTarget = new JuceDropTarget (this);
  207335. RegisterDragDrop (hwnd, dropTarget);
  207336. updateBorderSize();
  207337. // Calling this function here is (for some reason) necessary to make Windows
  207338. // correctly enable the menu items that we specify in the wm_initmenu message.
  207339. GetSystemMenu (hwnd, false);
  207340. }
  207341. else
  207342. {
  207343. jassertfalse;
  207344. }
  207345. }
  207346. static void* destroyWindowCallback (void* handle)
  207347. {
  207348. RevokeDragDrop ((HWND) handle);
  207349. DestroyWindow ((HWND) handle);
  207350. return 0;
  207351. }
  207352. static void* toFrontCallback1 (void* h)
  207353. {
  207354. SetForegroundWindow ((HWND) h);
  207355. return 0;
  207356. }
  207357. static void* toFrontCallback2 (void* h)
  207358. {
  207359. SetWindowPos ((HWND) h, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207360. return 0;
  207361. }
  207362. static void* setFocusCallback (void* h)
  207363. {
  207364. SetFocus ((HWND) h);
  207365. return 0;
  207366. }
  207367. static void* getFocusCallback (void*)
  207368. {
  207369. return GetFocus();
  207370. }
  207371. void offsetWithinParent (int& x, int& y) const
  207372. {
  207373. if (isTransparent())
  207374. {
  207375. HWND parentHwnd = GetParent (hwnd);
  207376. if (parentHwnd != 0)
  207377. {
  207378. RECT parentRect;
  207379. GetWindowRect (parentHwnd, &parentRect);
  207380. x += parentRect.left;
  207381. y += parentRect.top;
  207382. }
  207383. }
  207384. }
  207385. bool isTransparent() const
  207386. {
  207387. return (GetWindowLong (hwnd, GWL_EXSTYLE) & WS_EX_LAYERED) != 0;
  207388. }
  207389. inline bool hasTitleBar() const throw() { return (styleFlags & windowHasTitleBar) != 0; }
  207390. void setIcon (const Image& newIcon)
  207391. {
  207392. HICON hicon = createHICONFromImage (newIcon, TRUE, 0, 0);
  207393. if (hicon != 0)
  207394. {
  207395. SendMessage (hwnd, WM_SETICON, ICON_BIG, (LPARAM) hicon);
  207396. SendMessage (hwnd, WM_SETICON, ICON_SMALL, (LPARAM) hicon);
  207397. if (currentWindowIcon != 0)
  207398. DestroyIcon (currentWindowIcon);
  207399. currentWindowIcon = hicon;
  207400. }
  207401. }
  207402. void handlePaintMessage()
  207403. {
  207404. #if JUCE_DIRECT2D
  207405. if (direct2DContext != 0)
  207406. {
  207407. RECT r;
  207408. if (GetUpdateRect (hwnd, &r, false))
  207409. {
  207410. direct2DContext->start();
  207411. direct2DContext->clipToRectangle (Rectangle<int> (r.left, r.top, r.right - r.left, r.bottom - r.top));
  207412. handlePaint (*direct2DContext);
  207413. direct2DContext->end();
  207414. }
  207415. }
  207416. else
  207417. #endif
  207418. {
  207419. HRGN rgn = CreateRectRgn (0, 0, 0, 0);
  207420. const int regionType = GetUpdateRgn (hwnd, rgn, false);
  207421. PAINTSTRUCT paintStruct;
  207422. HDC dc = BeginPaint (hwnd, &paintStruct); // Note this can immediately generate a WM_NCPAINT
  207423. // message and become re-entrant, but that's OK
  207424. // if something in a paint handler calls, e.g. a message box, this can become reentrant and
  207425. // corrupt the image it's using to paint into, so do a check here.
  207426. static bool reentrant = false;
  207427. if (reentrant)
  207428. {
  207429. DeleteObject (rgn);
  207430. EndPaint (hwnd, &paintStruct);
  207431. return;
  207432. }
  207433. reentrant = true;
  207434. // this is the rectangle to update..
  207435. int x = paintStruct.rcPaint.left;
  207436. int y = paintStruct.rcPaint.top;
  207437. int w = paintStruct.rcPaint.right - x;
  207438. int h = paintStruct.rcPaint.bottom - y;
  207439. const bool transparent = isTransparent();
  207440. if (transparent)
  207441. {
  207442. // it's not possible to have a transparent window with a title bar at the moment!
  207443. jassert (! hasTitleBar());
  207444. RECT r;
  207445. GetWindowRect (hwnd, &r);
  207446. x = y = 0;
  207447. w = r.right - r.left;
  207448. h = r.bottom - r.top;
  207449. }
  207450. if (w > 0 && h > 0)
  207451. {
  207452. clearMaskedRegion();
  207453. Image offscreenImage (offscreenImageGenerator.getImage (transparent, w, h));
  207454. RectangleList contextClip;
  207455. const Rectangle<int> clipBounds (0, 0, w, h);
  207456. bool needToPaintAll = true;
  207457. if (regionType == COMPLEXREGION && ! transparent)
  207458. {
  207459. HRGN clipRgn = CreateRectRgnIndirect (&paintStruct.rcPaint);
  207460. CombineRgn (rgn, rgn, clipRgn, RGN_AND);
  207461. DeleteObject (clipRgn);
  207462. char rgnData [8192];
  207463. const DWORD res = GetRegionData (rgn, sizeof (rgnData), (RGNDATA*) rgnData);
  207464. if (res > 0 && res <= sizeof (rgnData))
  207465. {
  207466. const RGNDATAHEADER* const hdr = &(((const RGNDATA*) rgnData)->rdh);
  207467. if (hdr->iType == RDH_RECTANGLES
  207468. && hdr->rcBound.right - hdr->rcBound.left >= w
  207469. && hdr->rcBound.bottom - hdr->rcBound.top >= h)
  207470. {
  207471. needToPaintAll = false;
  207472. const RECT* rects = (const RECT*) (rgnData + sizeof (RGNDATAHEADER));
  207473. int num = ((RGNDATA*) rgnData)->rdh.nCount;
  207474. while (--num >= 0)
  207475. {
  207476. if (rects->right <= x + w && rects->bottom <= y + h)
  207477. {
  207478. const int cx = jmax (x, (int) rects->left);
  207479. contextClip.addWithoutMerging (Rectangle<int> (cx - x, rects->top - y, rects->right - cx, rects->bottom - rects->top)
  207480. .getIntersection (clipBounds));
  207481. }
  207482. else
  207483. {
  207484. needToPaintAll = true;
  207485. break;
  207486. }
  207487. ++rects;
  207488. }
  207489. }
  207490. }
  207491. }
  207492. if (needToPaintAll)
  207493. {
  207494. contextClip.clear();
  207495. contextClip.addWithoutMerging (Rectangle<int> (w, h));
  207496. }
  207497. if (transparent)
  207498. {
  207499. RectangleList::Iterator i (contextClip);
  207500. while (i.next())
  207501. offscreenImage.clear (*i.getRectangle());
  207502. }
  207503. // if the component's not opaque, this won't draw properly unless the platform can support this
  207504. jassert (Desktop::canUseSemiTransparentWindows() || component->isOpaque());
  207505. updateCurrentModifiers();
  207506. LowLevelGraphicsSoftwareRenderer context (offscreenImage, -x, -y, contextClip);
  207507. handlePaint (context);
  207508. if (! dontRepaint)
  207509. static_cast <WindowsBitmapImage*> (offscreenImage.getSharedImage())
  207510. ->blitToWindow (hwnd, dc, transparent, x, y, maskedRegion);
  207511. }
  207512. DeleteObject (rgn);
  207513. EndPaint (hwnd, &paintStruct);
  207514. reentrant = false;
  207515. }
  207516. #ifndef JUCE_GCC //xxx should add this fn for gcc..
  207517. _fpreset(); // because some graphics cards can unmask FP exceptions
  207518. #endif
  207519. lastPaintTime = Time::getMillisecondCounter();
  207520. }
  207521. void doMouseEvent (const Point<int>& position)
  207522. {
  207523. handleMouseEvent (0, position, currentModifiers, getMouseEventTime());
  207524. }
  207525. const StringArray getAvailableRenderingEngines()
  207526. {
  207527. StringArray s (ComponentPeer::getAvailableRenderingEngines());
  207528. #if JUCE_DIRECT2D
  207529. // xxx is this correct? Seems to enable it on Vista too??
  207530. OSVERSIONINFO info;
  207531. zerostruct (info);
  207532. info.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
  207533. GetVersionEx (&info);
  207534. if (info.dwMajorVersion >= 6)
  207535. s.add ("Direct2D");
  207536. #endif
  207537. return s;
  207538. }
  207539. int getCurrentRenderingEngine() throw()
  207540. {
  207541. return currentRenderingEngine;
  207542. }
  207543. #if JUCE_DIRECT2D
  207544. void updateDirect2DContext()
  207545. {
  207546. if (currentRenderingEngine != direct2DRenderingEngine)
  207547. direct2DContext = 0;
  207548. else if (direct2DContext == 0)
  207549. direct2DContext = new Direct2DLowLevelGraphicsContext (hwnd);
  207550. }
  207551. #endif
  207552. void setCurrentRenderingEngine (int index)
  207553. {
  207554. (void) index;
  207555. #if JUCE_DIRECT2D
  207556. currentRenderingEngine = index == 1 ? direct2DRenderingEngine : softwareRenderingEngine;
  207557. updateDirect2DContext();
  207558. repaint (component->getLocalBounds());
  207559. #endif
  207560. }
  207561. void doMouseMove (const Point<int>& position)
  207562. {
  207563. if (! isMouseOver)
  207564. {
  207565. isMouseOver = true;
  207566. updateKeyModifiers();
  207567. TRACKMOUSEEVENT tme;
  207568. tme.cbSize = sizeof (tme);
  207569. tme.dwFlags = TME_LEAVE;
  207570. tme.hwndTrack = hwnd;
  207571. tme.dwHoverTime = 0;
  207572. if (! TrackMouseEvent (&tme))
  207573. jassertfalse;
  207574. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  207575. }
  207576. else if (! isDragging)
  207577. {
  207578. if (! contains (position, false))
  207579. return;
  207580. }
  207581. // (Throttling the incoming queue of mouse-events seems to still be required in XP..)
  207582. static uint32 lastMouseTime = 0;
  207583. const uint32 now = Time::getMillisecondCounter();
  207584. const int maxMouseMovesPerSecond = 60;
  207585. if (now > lastMouseTime + 1000 / maxMouseMovesPerSecond)
  207586. {
  207587. lastMouseTime = now;
  207588. doMouseEvent (position);
  207589. }
  207590. }
  207591. void doMouseDown (const Point<int>& position, const WPARAM wParam)
  207592. {
  207593. if (GetCapture() != hwnd)
  207594. SetCapture (hwnd);
  207595. doMouseMove (position);
  207596. updateModifiersFromWParam (wParam);
  207597. isDragging = true;
  207598. doMouseEvent (position);
  207599. }
  207600. void doMouseUp (const Point<int>& position, const WPARAM wParam)
  207601. {
  207602. updateModifiersFromWParam (wParam);
  207603. isDragging = false;
  207604. // release the mouse capture if the user has released all buttons
  207605. if ((wParam & (MK_LBUTTON | MK_RBUTTON | MK_MBUTTON)) == 0 && hwnd == GetCapture())
  207606. ReleaseCapture();
  207607. doMouseEvent (position);
  207608. }
  207609. void doCaptureChanged()
  207610. {
  207611. if (isDragging)
  207612. doMouseUp (getCurrentMousePos(), (WPARAM) 0);
  207613. }
  207614. void doMouseExit()
  207615. {
  207616. isMouseOver = false;
  207617. doMouseEvent (getCurrentMousePos());
  207618. }
  207619. void doMouseWheel (const Point<int>& position, const WPARAM wParam, const bool isVertical)
  207620. {
  207621. updateKeyModifiers();
  207622. const float amount = jlimit (-1000.0f, 1000.0f, 0.75f * (short) HIWORD (wParam));
  207623. handleMouseWheel (0, position, getMouseEventTime(),
  207624. isVertical ? 0.0f : amount,
  207625. isVertical ? amount : 0.0f);
  207626. }
  207627. void sendModifierKeyChangeIfNeeded()
  207628. {
  207629. if (modifiersAtLastCallback != currentModifiers)
  207630. {
  207631. modifiersAtLastCallback = currentModifiers;
  207632. handleModifierKeysChange();
  207633. }
  207634. }
  207635. bool doKeyUp (const WPARAM key)
  207636. {
  207637. updateKeyModifiers();
  207638. switch (key)
  207639. {
  207640. case VK_SHIFT:
  207641. case VK_CONTROL:
  207642. case VK_MENU:
  207643. case VK_CAPITAL:
  207644. case VK_LWIN:
  207645. case VK_RWIN:
  207646. case VK_APPS:
  207647. case VK_NUMLOCK:
  207648. case VK_SCROLL:
  207649. case VK_LSHIFT:
  207650. case VK_RSHIFT:
  207651. case VK_LCONTROL:
  207652. case VK_LMENU:
  207653. case VK_RCONTROL:
  207654. case VK_RMENU:
  207655. sendModifierKeyChangeIfNeeded();
  207656. }
  207657. return handleKeyUpOrDown (false)
  207658. || Component::getCurrentlyModalComponent() != 0;
  207659. }
  207660. bool doKeyDown (const WPARAM key)
  207661. {
  207662. updateKeyModifiers();
  207663. bool used = false;
  207664. switch (key)
  207665. {
  207666. case VK_SHIFT:
  207667. case VK_LSHIFT:
  207668. case VK_RSHIFT:
  207669. case VK_CONTROL:
  207670. case VK_LCONTROL:
  207671. case VK_RCONTROL:
  207672. case VK_MENU:
  207673. case VK_LMENU:
  207674. case VK_RMENU:
  207675. case VK_LWIN:
  207676. case VK_RWIN:
  207677. case VK_CAPITAL:
  207678. case VK_NUMLOCK:
  207679. case VK_SCROLL:
  207680. case VK_APPS:
  207681. sendModifierKeyChangeIfNeeded();
  207682. break;
  207683. case VK_LEFT:
  207684. case VK_RIGHT:
  207685. case VK_UP:
  207686. case VK_DOWN:
  207687. case VK_PRIOR:
  207688. case VK_NEXT:
  207689. case VK_HOME:
  207690. case VK_END:
  207691. case VK_DELETE:
  207692. case VK_INSERT:
  207693. case VK_F1:
  207694. case VK_F2:
  207695. case VK_F3:
  207696. case VK_F4:
  207697. case VK_F5:
  207698. case VK_F6:
  207699. case VK_F7:
  207700. case VK_F8:
  207701. case VK_F9:
  207702. case VK_F10:
  207703. case VK_F11:
  207704. case VK_F12:
  207705. case VK_F13:
  207706. case VK_F14:
  207707. case VK_F15:
  207708. case VK_F16:
  207709. used = handleKeyUpOrDown (true);
  207710. used = handleKeyPress (extendedKeyModifier | (int) key, 0) || used;
  207711. break;
  207712. case VK_ADD:
  207713. case VK_SUBTRACT:
  207714. case VK_MULTIPLY:
  207715. case VK_DIVIDE:
  207716. case VK_SEPARATOR:
  207717. case VK_DECIMAL:
  207718. used = handleKeyUpOrDown (true);
  207719. break;
  207720. default:
  207721. used = handleKeyUpOrDown (true);
  207722. {
  207723. MSG msg;
  207724. if (! PeekMessage (&msg, hwnd, WM_CHAR, WM_DEADCHAR, PM_NOREMOVE))
  207725. {
  207726. // if there isn't a WM_CHAR or WM_DEADCHAR message pending, we need to
  207727. // manually generate the key-press event that matches this key-down.
  207728. const UINT keyChar = MapVirtualKey (key, 2);
  207729. used = handleKeyPress ((int) LOWORD (keyChar), 0) || used;
  207730. }
  207731. }
  207732. break;
  207733. }
  207734. if (Component::getCurrentlyModalComponent() != 0)
  207735. used = true;
  207736. return used;
  207737. }
  207738. bool doKeyChar (int key, const LPARAM flags)
  207739. {
  207740. updateKeyModifiers();
  207741. juce_wchar textChar = (juce_wchar) key;
  207742. const int virtualScanCode = (flags >> 16) & 0xff;
  207743. if (key >= '0' && key <= '9')
  207744. {
  207745. switch (virtualScanCode) // check for a numeric keypad scan-code
  207746. {
  207747. case 0x52:
  207748. case 0x4f:
  207749. case 0x50:
  207750. case 0x51:
  207751. case 0x4b:
  207752. case 0x4c:
  207753. case 0x4d:
  207754. case 0x47:
  207755. case 0x48:
  207756. case 0x49:
  207757. key = (key - '0') + KeyPress::numberPad0;
  207758. break;
  207759. default:
  207760. break;
  207761. }
  207762. }
  207763. else
  207764. {
  207765. // convert the scan code to an unmodified character code..
  207766. const UINT virtualKey = MapVirtualKey (virtualScanCode, 1);
  207767. UINT keyChar = MapVirtualKey (virtualKey, 2);
  207768. keyChar = LOWORD (keyChar);
  207769. if (keyChar != 0)
  207770. key = (int) keyChar;
  207771. // avoid sending junk text characters for some control-key combinations
  207772. if (textChar < ' ' && currentModifiers.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::altModifier))
  207773. textChar = 0;
  207774. }
  207775. return handleKeyPress (key, textChar);
  207776. }
  207777. bool doAppCommand (const LPARAM lParam)
  207778. {
  207779. int key = 0;
  207780. switch (GET_APPCOMMAND_LPARAM (lParam))
  207781. {
  207782. case APPCOMMAND_MEDIA_PLAY_PAUSE:
  207783. key = KeyPress::playKey;
  207784. break;
  207785. case APPCOMMAND_MEDIA_STOP:
  207786. key = KeyPress::stopKey;
  207787. break;
  207788. case APPCOMMAND_MEDIA_NEXTTRACK:
  207789. key = KeyPress::fastForwardKey;
  207790. break;
  207791. case APPCOMMAND_MEDIA_PREVIOUSTRACK:
  207792. key = KeyPress::rewindKey;
  207793. break;
  207794. }
  207795. if (key != 0)
  207796. {
  207797. updateKeyModifiers();
  207798. if (hwnd == GetActiveWindow())
  207799. {
  207800. handleKeyPress (key, 0);
  207801. return true;
  207802. }
  207803. }
  207804. return false;
  207805. }
  207806. class JuceDropTarget : public ComBaseClassHelper <IDropTarget>
  207807. {
  207808. public:
  207809. JuceDropTarget (Win32ComponentPeer* const owner_)
  207810. : owner (owner_)
  207811. {
  207812. }
  207813. ~JuceDropTarget() {}
  207814. HRESULT __stdcall DragEnter (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  207815. {
  207816. updateFileList (pDataObject);
  207817. owner->handleFileDragMove (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  207818. *pdwEffect = DROPEFFECT_COPY;
  207819. return S_OK;
  207820. }
  207821. HRESULT __stdcall DragLeave()
  207822. {
  207823. owner->handleFileDragExit (files);
  207824. return S_OK;
  207825. }
  207826. HRESULT __stdcall DragOver (DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  207827. {
  207828. owner->handleFileDragMove (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  207829. *pdwEffect = DROPEFFECT_COPY;
  207830. return S_OK;
  207831. }
  207832. HRESULT __stdcall Drop (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  207833. {
  207834. updateFileList (pDataObject);
  207835. owner->handleFileDragDrop (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  207836. *pdwEffect = DROPEFFECT_COPY;
  207837. return S_OK;
  207838. }
  207839. private:
  207840. Win32ComponentPeer* const owner;
  207841. StringArray files;
  207842. void updateFileList (IDataObject* const pDataObject)
  207843. {
  207844. files.clear();
  207845. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  207846. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  207847. if (pDataObject->GetData (&format, &medium) == S_OK)
  207848. {
  207849. const SIZE_T totalLen = GlobalSize (medium.hGlobal);
  207850. const LPDROPFILES pDropFiles = (const LPDROPFILES) GlobalLock (medium.hGlobal);
  207851. unsigned int i = 0;
  207852. if (pDropFiles->fWide)
  207853. {
  207854. const WCHAR* const fname = (WCHAR*) (((const char*) pDropFiles) + sizeof (DROPFILES));
  207855. for (;;)
  207856. {
  207857. unsigned int len = 0;
  207858. while (i + len < totalLen && fname [i + len] != 0)
  207859. ++len;
  207860. if (len == 0)
  207861. break;
  207862. files.add (String (fname + i, len));
  207863. i += len + 1;
  207864. }
  207865. }
  207866. else
  207867. {
  207868. const char* const fname = ((const char*) pDropFiles) + sizeof (DROPFILES);
  207869. for (;;)
  207870. {
  207871. unsigned int len = 0;
  207872. while (i + len < totalLen && fname [i + len] != 0)
  207873. ++len;
  207874. if (len == 0)
  207875. break;
  207876. files.add (String (fname + i, len));
  207877. i += len + 1;
  207878. }
  207879. }
  207880. GlobalUnlock (medium.hGlobal);
  207881. }
  207882. }
  207883. JuceDropTarget (const JuceDropTarget&);
  207884. JuceDropTarget& operator= (const JuceDropTarget&);
  207885. };
  207886. void doSettingChange()
  207887. {
  207888. Desktop::getInstance().refreshMonitorSizes();
  207889. if (fullScreen && ! isMinimised())
  207890. {
  207891. const Rectangle<int> r (component->getParentMonitorArea());
  207892. SetWindowPos (hwnd, 0,
  207893. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  207894. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOSENDCHANGING);
  207895. }
  207896. }
  207897. public:
  207898. static LRESULT CALLBACK windowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  207899. {
  207900. Win32ComponentPeer* const peer = getOwnerOfWindow (h);
  207901. if (peer != 0)
  207902. return peer->peerWindowProc (h, message, wParam, lParam);
  207903. return DefWindowProcW (h, message, wParam, lParam);
  207904. }
  207905. private:
  207906. static const Point<int> getPointFromLParam (LPARAM lParam) throw()
  207907. {
  207908. return Point<int> (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam));
  207909. }
  207910. const Point<int> getCurrentMousePos() throw()
  207911. {
  207912. RECT wr;
  207913. GetWindowRect (hwnd, &wr);
  207914. const DWORD mp = GetMessagePos();
  207915. return Point<int> (GET_X_LPARAM (mp) - wr.left - windowBorder.getLeft(),
  207916. GET_Y_LPARAM (mp) - wr.top - windowBorder.getTop());
  207917. }
  207918. LRESULT peerWindowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  207919. {
  207920. if (isValidPeer (this))
  207921. {
  207922. switch (message)
  207923. {
  207924. case WM_NCHITTEST:
  207925. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  207926. return HTTRANSPARENT;
  207927. if (hasTitleBar())
  207928. break;
  207929. return HTCLIENT;
  207930. case WM_PAINT:
  207931. handlePaintMessage();
  207932. return 0;
  207933. case WM_NCPAINT:
  207934. if (wParam != 1)
  207935. handlePaintMessage();
  207936. if (hasTitleBar())
  207937. break;
  207938. return 0;
  207939. case WM_ERASEBKGND:
  207940. case WM_NCCALCSIZE:
  207941. if (hasTitleBar())
  207942. break;
  207943. return 1;
  207944. case WM_MOUSEMOVE:
  207945. doMouseMove (getPointFromLParam (lParam));
  207946. return 0;
  207947. case WM_MOUSELEAVE:
  207948. doMouseExit();
  207949. return 0;
  207950. case WM_LBUTTONDOWN:
  207951. case WM_MBUTTONDOWN:
  207952. case WM_RBUTTONDOWN:
  207953. doMouseDown (getPointFromLParam (lParam), wParam);
  207954. return 0;
  207955. case WM_LBUTTONUP:
  207956. case WM_MBUTTONUP:
  207957. case WM_RBUTTONUP:
  207958. doMouseUp (getPointFromLParam (lParam), wParam);
  207959. return 0;
  207960. case WM_CAPTURECHANGED:
  207961. doCaptureChanged();
  207962. return 0;
  207963. case WM_NCMOUSEMOVE:
  207964. if (hasTitleBar())
  207965. break;
  207966. return 0;
  207967. case 0x020A: /* WM_MOUSEWHEEL */
  207968. doMouseWheel (getCurrentMousePos(), wParam, true);
  207969. return 0;
  207970. case 0x020E: /* WM_MOUSEHWHEEL */
  207971. doMouseWheel (getCurrentMousePos(), wParam, false);
  207972. return 0;
  207973. case WM_WINDOWPOSCHANGING:
  207974. if ((styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable))
  207975. {
  207976. WINDOWPOS* const wp = (WINDOWPOS*) lParam;
  207977. if ((wp->flags & (SWP_NOMOVE | SWP_NOSIZE)) != (SWP_NOMOVE | SWP_NOSIZE))
  207978. {
  207979. if (constrainer != 0)
  207980. {
  207981. const Rectangle<int> current (component->getX() - windowBorder.getLeft(),
  207982. component->getY() - windowBorder.getTop(),
  207983. component->getWidth() + windowBorder.getLeftAndRight(),
  207984. component->getHeight() + windowBorder.getTopAndBottom());
  207985. Rectangle<int> pos (wp->x, wp->y, wp->cx, wp->cy);
  207986. constrainer->checkBounds (pos, current,
  207987. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  207988. pos.getY() != current.getY() && pos.getBottom() == current.getBottom(),
  207989. pos.getX() != current.getX() && pos.getRight() == current.getRight(),
  207990. pos.getY() == current.getY() && pos.getBottom() != current.getBottom(),
  207991. pos.getX() == current.getX() && pos.getRight() != current.getRight());
  207992. wp->x = pos.getX();
  207993. wp->y = pos.getY();
  207994. wp->cx = pos.getWidth();
  207995. wp->cy = pos.getHeight();
  207996. }
  207997. }
  207998. }
  207999. return 0;
  208000. case WM_WINDOWPOSCHANGED:
  208001. doMouseEvent (getCurrentMousePos());
  208002. handleMovedOrResized();
  208003. if (dontRepaint)
  208004. break; // needed for non-accelerated openGL windows to draw themselves correctly..
  208005. return 0;
  208006. case WM_KEYDOWN:
  208007. case WM_SYSKEYDOWN:
  208008. if (doKeyDown (wParam))
  208009. return 0;
  208010. break;
  208011. case WM_KEYUP:
  208012. case WM_SYSKEYUP:
  208013. if (doKeyUp (wParam))
  208014. return 0;
  208015. break;
  208016. case WM_CHAR:
  208017. if (doKeyChar ((int) wParam, lParam))
  208018. return 0;
  208019. break;
  208020. case WM_APPCOMMAND:
  208021. if (doAppCommand (lParam))
  208022. return TRUE;
  208023. break;
  208024. case WM_SETFOCUS:
  208025. updateKeyModifiers();
  208026. handleFocusGain();
  208027. break;
  208028. case WM_KILLFOCUS:
  208029. if (hasCreatedCaret)
  208030. {
  208031. hasCreatedCaret = false;
  208032. DestroyCaret();
  208033. }
  208034. handleFocusLoss();
  208035. break;
  208036. case WM_ACTIVATEAPP:
  208037. // Windows does weird things to process priority when you swap apps,
  208038. // so this forces an update when the app is brought to the front
  208039. if (wParam != FALSE)
  208040. juce_repeatLastProcessPriority();
  208041. else
  208042. Desktop::getInstance().setKioskModeComponent (0); // turn kiosk mode off if we lose focus
  208043. juce_CheckCurrentlyFocusedTopLevelWindow();
  208044. modifiersAtLastCallback = -1;
  208045. return 0;
  208046. case WM_ACTIVATE:
  208047. if (LOWORD (wParam) == WA_ACTIVE || LOWORD (wParam) == WA_CLICKACTIVE)
  208048. {
  208049. modifiersAtLastCallback = -1;
  208050. updateKeyModifiers();
  208051. if (isMinimised())
  208052. {
  208053. component->repaint();
  208054. handleMovedOrResized();
  208055. if (! ComponentPeer::isValidPeer (this))
  208056. return 0;
  208057. }
  208058. if (LOWORD (wParam) == WA_CLICKACTIVE
  208059. && component->isCurrentlyBlockedByAnotherModalComponent())
  208060. {
  208061. const Point<int> mousePos (component->getMouseXYRelative());
  208062. Component* const underMouse = component->getComponentAt (mousePos.getX(), mousePos.getY());
  208063. if (underMouse != 0 && underMouse->isCurrentlyBlockedByAnotherModalComponent())
  208064. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  208065. return 0;
  208066. }
  208067. handleBroughtToFront();
  208068. if (component->isCurrentlyBlockedByAnotherModalComponent())
  208069. Component::getCurrentlyModalComponent()->toFront (true);
  208070. return 0;
  208071. }
  208072. break;
  208073. case WM_NCACTIVATE:
  208074. // while a temporary window is being shown, prevent Windows from deactivating the
  208075. // title bars of our main windows.
  208076. if (wParam == 0 && ! shouldDeactivateTitleBar)
  208077. wParam = TRUE; // change this and let it get passed to the DefWindowProc.
  208078. break;
  208079. case WM_MOUSEACTIVATE:
  208080. if (! component->getMouseClickGrabsKeyboardFocus())
  208081. return MA_NOACTIVATE;
  208082. break;
  208083. case WM_SHOWWINDOW:
  208084. if (wParam != 0)
  208085. handleBroughtToFront();
  208086. break;
  208087. case WM_CLOSE:
  208088. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  208089. handleUserClosingWindow();
  208090. return 0;
  208091. case WM_QUERYENDSESSION:
  208092. if (JUCEApplication::getInstance() != 0)
  208093. {
  208094. JUCEApplication::getInstance()->systemRequestedQuit();
  208095. return MessageManager::getInstance()->hasStopMessageBeenSent();
  208096. }
  208097. return TRUE;
  208098. case WM_TRAYNOTIFY:
  208099. if (component->isCurrentlyBlockedByAnotherModalComponent())
  208100. {
  208101. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN
  208102. || lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  208103. {
  208104. Component* const current = Component::getCurrentlyModalComponent();
  208105. if (current != 0)
  208106. current->inputAttemptWhenModal();
  208107. }
  208108. }
  208109. else
  208110. {
  208111. ModifierKeys eventMods (ModifierKeys::getCurrentModifiersRealtime());
  208112. if (lParam == WM_LBUTTONDOWN || lParam == WM_LBUTTONDBLCLK)
  208113. eventMods = eventMods.withFlags (ModifierKeys::leftButtonModifier);
  208114. else if (lParam == WM_RBUTTONDOWN || lParam == WM_RBUTTONDBLCLK)
  208115. eventMods = eventMods.withFlags (ModifierKeys::rightButtonModifier);
  208116. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  208117. eventMods = eventMods.withoutMouseButtons();
  208118. const MouseEvent e (Desktop::getInstance().getMainMouseSource(),
  208119. Point<int>(), eventMods, component, component, getMouseEventTime(),
  208120. Point<int>(), getMouseEventTime(), 1, false);
  208121. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN)
  208122. {
  208123. SetFocus (hwnd);
  208124. SetForegroundWindow (hwnd);
  208125. component->mouseDown (e);
  208126. }
  208127. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  208128. {
  208129. component->mouseUp (e);
  208130. }
  208131. else if (lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  208132. {
  208133. component->mouseDoubleClick (e);
  208134. }
  208135. else if (lParam == WM_MOUSEMOVE)
  208136. {
  208137. component->mouseMove (e);
  208138. }
  208139. }
  208140. break;
  208141. case WM_SYNCPAINT:
  208142. return 0;
  208143. case WM_PALETTECHANGED:
  208144. InvalidateRect (h, 0, 0);
  208145. break;
  208146. case WM_DISPLAYCHANGE:
  208147. InvalidateRect (h, 0, 0);
  208148. createPaletteIfNeeded = true;
  208149. // intentional fall-through...
  208150. case WM_SETTINGCHANGE: // note the fall-through in the previous case!
  208151. doSettingChange();
  208152. break;
  208153. case WM_INITMENU:
  208154. if (! hasTitleBar())
  208155. {
  208156. if (isFullScreen())
  208157. {
  208158. EnableMenuItem ((HMENU) wParam, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  208159. EnableMenuItem ((HMENU) wParam, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  208160. }
  208161. else if (! isMinimised())
  208162. {
  208163. EnableMenuItem ((HMENU) wParam, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
  208164. }
  208165. }
  208166. break;
  208167. case WM_SYSCOMMAND:
  208168. switch (wParam & 0xfff0)
  208169. {
  208170. case SC_CLOSE:
  208171. if (sendInputAttemptWhenModalMessage())
  208172. return 0;
  208173. if (hasTitleBar())
  208174. {
  208175. PostMessage (h, WM_CLOSE, 0, 0);
  208176. return 0;
  208177. }
  208178. break;
  208179. case SC_KEYMENU:
  208180. // (NB mustn't call sendInputAttemptWhenModalMessage() here because of very
  208181. // obscure situations that can arise if a modal loop is started from an alt-key
  208182. // keypress).
  208183. if (hasTitleBar() && h == GetCapture())
  208184. ReleaseCapture();
  208185. break;
  208186. case SC_MAXIMIZE:
  208187. if (sendInputAttemptWhenModalMessage())
  208188. return 0;
  208189. setFullScreen (true);
  208190. return 0;
  208191. case SC_MINIMIZE:
  208192. if (sendInputAttemptWhenModalMessage())
  208193. return 0;
  208194. if (! hasTitleBar())
  208195. {
  208196. setMinimised (true);
  208197. return 0;
  208198. }
  208199. break;
  208200. case SC_RESTORE:
  208201. if (sendInputAttemptWhenModalMessage())
  208202. return 0;
  208203. if (hasTitleBar())
  208204. {
  208205. if (isFullScreen())
  208206. {
  208207. setFullScreen (false);
  208208. return 0;
  208209. }
  208210. }
  208211. else
  208212. {
  208213. if (isMinimised())
  208214. setMinimised (false);
  208215. else if (isFullScreen())
  208216. setFullScreen (false);
  208217. return 0;
  208218. }
  208219. break;
  208220. }
  208221. break;
  208222. case WM_NCLBUTTONDOWN:
  208223. case WM_NCRBUTTONDOWN:
  208224. case WM_NCMBUTTONDOWN:
  208225. sendInputAttemptWhenModalMessage();
  208226. break;
  208227. //case WM_IME_STARTCOMPOSITION;
  208228. // return 0;
  208229. case WM_GETDLGCODE:
  208230. return DLGC_WANTALLKEYS;
  208231. default:
  208232. break;
  208233. }
  208234. }
  208235. return DefWindowProcW (h, message, wParam, lParam);
  208236. }
  208237. bool sendInputAttemptWhenModalMessage()
  208238. {
  208239. if (component->isCurrentlyBlockedByAnotherModalComponent())
  208240. {
  208241. Component* const current = Component::getCurrentlyModalComponent();
  208242. if (current != 0)
  208243. current->inputAttemptWhenModal();
  208244. return true;
  208245. }
  208246. return false;
  208247. }
  208248. Win32ComponentPeer (const Win32ComponentPeer&);
  208249. Win32ComponentPeer& operator= (const Win32ComponentPeer&);
  208250. };
  208251. ModifierKeys Win32ComponentPeer::currentModifiers;
  208252. ModifierKeys Win32ComponentPeer::modifiersAtLastCallback;
  208253. ComponentPeer* Component::createNewPeer (int styleFlags, void* nativeWindowToAttachTo)
  208254. {
  208255. return new Win32ComponentPeer (this, styleFlags, (HWND) nativeWindowToAttachTo);
  208256. }
  208257. juce_ImplementSingleton_SingleThreaded (Win32ComponentPeer::WindowClassHolder);
  208258. void ModifierKeys::updateCurrentModifiers() throw()
  208259. {
  208260. currentModifiers = Win32ComponentPeer::currentModifiers;
  208261. }
  208262. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  208263. {
  208264. Win32ComponentPeer::updateKeyModifiers();
  208265. int keyMods = 0;
  208266. if ((GetKeyState (VK_LBUTTON) & 0x8000) != 0) keyMods |= ModifierKeys::leftButtonModifier;
  208267. if ((GetKeyState (VK_RBUTTON) & 0x8000) != 0) keyMods |= ModifierKeys::rightButtonModifier;
  208268. if ((GetKeyState (VK_MBUTTON) & 0x8000) != 0) keyMods |= ModifierKeys::middleButtonModifier;
  208269. Win32ComponentPeer::currentModifiers
  208270. = Win32ComponentPeer::currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  208271. return Win32ComponentPeer::currentModifiers;
  208272. }
  208273. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  208274. {
  208275. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  208276. if (wp != 0)
  208277. wp->setTaskBarIcon (newImage);
  208278. }
  208279. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  208280. {
  208281. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  208282. if (wp != 0)
  208283. wp->setTaskBarIconToolTip (tooltip);
  208284. }
  208285. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw()
  208286. {
  208287. DWORD val = GetWindowLong (h, styleType);
  208288. if (bitIsSet)
  208289. val |= feature;
  208290. else
  208291. val &= ~feature;
  208292. SetWindowLongPtr (h, styleType, val);
  208293. SetWindowPos (h, 0, 0, 0, 0, 0,
  208294. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER
  208295. | SWP_NOOWNERZORDER | SWP_FRAMECHANGED | SWP_NOSENDCHANGING);
  208296. }
  208297. bool Process::isForegroundProcess()
  208298. {
  208299. HWND fg = GetForegroundWindow();
  208300. if (fg == 0)
  208301. return true;
  208302. // when running as a plugin in IE8, the browser UI runs in a different process to the plugin, so
  208303. // process ID isn't a reliable way to check if the foreground window belongs to us - instead, we
  208304. // have to see if any of our windows are children of the foreground window
  208305. fg = GetAncestor (fg, GA_ROOT);
  208306. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  208307. {
  208308. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (ComponentPeer::getPeer (i));
  208309. if (wp != 0 && wp->isInside (fg))
  208310. return true;
  208311. }
  208312. return false;
  208313. }
  208314. bool AlertWindow::showNativeDialogBox (const String& title,
  208315. const String& bodyText,
  208316. bool isOkCancel)
  208317. {
  208318. return MessageBox (0, bodyText, title,
  208319. MB_SETFOREGROUND | (isOkCancel ? MB_OKCANCEL
  208320. : MB_OK)) == IDOK;
  208321. }
  208322. void Desktop::createMouseInputSources()
  208323. {
  208324. mouseSources.add (new MouseInputSource (0, true));
  208325. }
  208326. const Point<int> Desktop::getMousePosition()
  208327. {
  208328. POINT mousePos;
  208329. GetCursorPos (&mousePos);
  208330. return Point<int> (mousePos.x, mousePos.y);
  208331. }
  208332. void Desktop::setMousePosition (const Point<int>& newPosition)
  208333. {
  208334. SetCursorPos (newPosition.getX(), newPosition.getY());
  208335. }
  208336. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  208337. {
  208338. return createSoftwareImage (format, width, height, clearImage);
  208339. }
  208340. class ScreenSaverDefeater : public Timer,
  208341. public DeletedAtShutdown
  208342. {
  208343. public:
  208344. ScreenSaverDefeater()
  208345. {
  208346. startTimer (10000);
  208347. timerCallback();
  208348. }
  208349. ~ScreenSaverDefeater() {}
  208350. void timerCallback()
  208351. {
  208352. if (Process::isForegroundProcess())
  208353. {
  208354. // simulate a shift key getting pressed..
  208355. INPUT input[2];
  208356. input[0].type = INPUT_KEYBOARD;
  208357. input[0].ki.wVk = VK_SHIFT;
  208358. input[0].ki.dwFlags = 0;
  208359. input[0].ki.dwExtraInfo = 0;
  208360. input[1].type = INPUT_KEYBOARD;
  208361. input[1].ki.wVk = VK_SHIFT;
  208362. input[1].ki.dwFlags = KEYEVENTF_KEYUP;
  208363. input[1].ki.dwExtraInfo = 0;
  208364. SendInput (2, input, sizeof (INPUT));
  208365. }
  208366. }
  208367. };
  208368. static ScreenSaverDefeater* screenSaverDefeater = 0;
  208369. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  208370. {
  208371. if (isEnabled)
  208372. deleteAndZero (screenSaverDefeater);
  208373. else if (screenSaverDefeater == 0)
  208374. screenSaverDefeater = new ScreenSaverDefeater();
  208375. }
  208376. bool Desktop::isScreenSaverEnabled()
  208377. {
  208378. return screenSaverDefeater == 0;
  208379. }
  208380. /* (The code below is the "correct" way to disable the screen saver, but it
  208381. completely fails on winXP when the saver is password-protected...)
  208382. static bool juce_screenSaverEnabled = true;
  208383. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  208384. {
  208385. juce_screenSaverEnabled = isEnabled;
  208386. SetThreadExecutionState (isEnabled ? ES_CONTINUOUS
  208387. : (ES_DISPLAY_REQUIRED | ES_CONTINUOUS));
  208388. }
  208389. bool Desktop::isScreenSaverEnabled() throw()
  208390. {
  208391. return juce_screenSaverEnabled;
  208392. }
  208393. */
  208394. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool /*allowMenusAndBars*/)
  208395. {
  208396. if (enableOrDisable)
  208397. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  208398. }
  208399. static BOOL CALLBACK enumMonitorsProc (HMONITOR, HDC, LPRECT r, LPARAM userInfo)
  208400. {
  208401. Array <Rectangle<int> >* const monitorCoords = (Array <Rectangle<int> >*) userInfo;
  208402. monitorCoords->add (Rectangle<int> (r->left, r->top, r->right - r->left, r->bottom - r->top));
  208403. return TRUE;
  208404. }
  208405. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  208406. {
  208407. EnumDisplayMonitors (0, 0, &enumMonitorsProc, (LPARAM) &monitorCoords);
  208408. // make sure the first in the list is the main monitor
  208409. for (int i = 1; i < monitorCoords.size(); ++i)
  208410. if (monitorCoords[i].getX() == 0 && monitorCoords[i].getY() == 0)
  208411. monitorCoords.swap (i, 0);
  208412. if (monitorCoords.size() == 0)
  208413. {
  208414. RECT r;
  208415. GetWindowRect (GetDesktopWindow(), &r);
  208416. monitorCoords.add (Rectangle<int> (r.left, r.top, r.right - r.left, r.bottom - r.top));
  208417. }
  208418. if (clipToWorkArea)
  208419. {
  208420. // clip the main monitor to the active non-taskbar area
  208421. RECT r;
  208422. SystemParametersInfo (SPI_GETWORKAREA, 0, &r, 0);
  208423. Rectangle<int>& screen = monitorCoords.getReference (0);
  208424. screen.setPosition (jmax (screen.getX(), (int) r.left),
  208425. jmax (screen.getY(), (int) r.top));
  208426. screen.setSize (jmin (screen.getRight(), (int) r.right) - screen.getX(),
  208427. jmin (screen.getBottom(), (int) r.bottom) - screen.getY());
  208428. }
  208429. }
  208430. static const Image createImageFromHBITMAP (HBITMAP bitmap)
  208431. {
  208432. Image im;
  208433. if (bitmap != 0)
  208434. {
  208435. BITMAP bm;
  208436. if (GetObject (bitmap, sizeof (BITMAP), &bm)
  208437. && bm.bmWidth > 0 && bm.bmHeight > 0)
  208438. {
  208439. HDC tempDC = GetDC (0);
  208440. HDC dc = CreateCompatibleDC (tempDC);
  208441. ReleaseDC (0, tempDC);
  208442. SelectObject (dc, bitmap);
  208443. im = Image (Image::ARGB, bm.bmWidth, bm.bmHeight, true);
  208444. Image::BitmapData imageData (im, true);
  208445. for (int y = bm.bmHeight; --y >= 0;)
  208446. {
  208447. for (int x = bm.bmWidth; --x >= 0;)
  208448. {
  208449. COLORREF col = GetPixel (dc, x, y);
  208450. imageData.setPixelColour (x, y, Colour ((uint8) GetRValue (col),
  208451. (uint8) GetGValue (col),
  208452. (uint8) GetBValue (col)));
  208453. }
  208454. }
  208455. DeleteDC (dc);
  208456. }
  208457. }
  208458. return im;
  208459. }
  208460. static const Image createImageFromHICON (HICON icon)
  208461. {
  208462. ICONINFO info;
  208463. if (GetIconInfo (icon, &info))
  208464. {
  208465. Image mask (createImageFromHBITMAP (info.hbmMask));
  208466. Image image (createImageFromHBITMAP (info.hbmColor));
  208467. if (mask.isValid() && image.isValid())
  208468. {
  208469. for (int y = image.getHeight(); --y >= 0;)
  208470. {
  208471. for (int x = image.getWidth(); --x >= 0;)
  208472. {
  208473. const float brightness = mask.getPixelAt (x, y).getBrightness();
  208474. if (brightness > 0.0f)
  208475. image.multiplyAlphaAt (x, y, 1.0f - brightness);
  208476. }
  208477. }
  208478. return image;
  208479. }
  208480. }
  208481. return Image::null;
  208482. }
  208483. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY)
  208484. {
  208485. WindowsBitmapImage* nativeBitmap = new WindowsBitmapImage (Image::ARGB, image.getWidth(), image.getHeight(), true);
  208486. Image bitmap (nativeBitmap);
  208487. {
  208488. Graphics g (bitmap);
  208489. g.drawImageAt (image, 0, 0);
  208490. }
  208491. HBITMAP mask = CreateBitmap (image.getWidth(), image.getHeight(), 1, 1, 0);
  208492. ICONINFO info;
  208493. info.fIcon = isIcon;
  208494. info.xHotspot = hotspotX;
  208495. info.yHotspot = hotspotY;
  208496. info.hbmMask = mask;
  208497. info.hbmColor = nativeBitmap->hBitmap;
  208498. HICON hi = CreateIconIndirect (&info);
  208499. DeleteObject (mask);
  208500. return hi;
  208501. }
  208502. const Image juce_createIconForFile (const File& file)
  208503. {
  208504. Image image;
  208505. WCHAR filename [1024];
  208506. file.getFullPathName().copyToUnicode (filename, 1023);
  208507. WORD iconNum = 0;
  208508. HICON icon = ExtractAssociatedIcon ((HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(),
  208509. filename, &iconNum);
  208510. if (icon != 0)
  208511. {
  208512. image = createImageFromHICON (icon);
  208513. DestroyIcon (icon);
  208514. }
  208515. return image;
  208516. }
  208517. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  208518. {
  208519. const int maxW = GetSystemMetrics (SM_CXCURSOR);
  208520. const int maxH = GetSystemMetrics (SM_CYCURSOR);
  208521. Image im (image);
  208522. if (im.getWidth() > maxW || im.getHeight() > maxH)
  208523. {
  208524. im = im.rescaled (maxW, maxH);
  208525. hotspotX = (hotspotX * maxW) / image.getWidth();
  208526. hotspotY = (hotspotY * maxH) / image.getHeight();
  208527. }
  208528. return createHICONFromImage (im, FALSE, hotspotX, hotspotY);
  208529. }
  208530. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard)
  208531. {
  208532. if (cursorHandle != 0 && ! isStandard)
  208533. DestroyCursor ((HCURSOR) cursorHandle);
  208534. }
  208535. void* MouseCursor::createStandardMouseCursor (const MouseCursor::StandardCursorType type)
  208536. {
  208537. LPCTSTR cursorName = IDC_ARROW;
  208538. switch (type)
  208539. {
  208540. case NormalCursor: break;
  208541. case NoCursor: return 0;
  208542. case WaitCursor: cursorName = IDC_WAIT; break;
  208543. case IBeamCursor: cursorName = IDC_IBEAM; break;
  208544. case PointingHandCursor: cursorName = MAKEINTRESOURCE(32649); break;
  208545. case CrosshairCursor: cursorName = IDC_CROSS; break;
  208546. case CopyingCursor: break; // can't seem to find one of these in the win32 list..
  208547. case LeftRightResizeCursor:
  208548. case LeftEdgeResizeCursor:
  208549. case RightEdgeResizeCursor: cursorName = IDC_SIZEWE; break;
  208550. case UpDownResizeCursor:
  208551. case TopEdgeResizeCursor:
  208552. case BottomEdgeResizeCursor: cursorName = IDC_SIZENS; break;
  208553. case TopLeftCornerResizeCursor:
  208554. case BottomRightCornerResizeCursor: cursorName = IDC_SIZENWSE; break;
  208555. case TopRightCornerResizeCursor:
  208556. case BottomLeftCornerResizeCursor: cursorName = IDC_SIZENESW; break;
  208557. case UpDownLeftRightResizeCursor: cursorName = IDC_SIZEALL; break;
  208558. case DraggingHandCursor:
  208559. {
  208560. static void* dragHandCursor = 0;
  208561. if (dragHandCursor == 0)
  208562. {
  208563. static const unsigned char dragHandData[] =
  208564. { 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,
  208565. 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,
  208566. 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 };
  208567. dragHandCursor = createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, sizeof (dragHandData)), 8, 7);
  208568. }
  208569. return dragHandCursor;
  208570. }
  208571. default:
  208572. jassertfalse; break;
  208573. }
  208574. HCURSOR cursorH = LoadCursor (0, cursorName);
  208575. if (cursorH == 0)
  208576. cursorH = LoadCursor (0, IDC_ARROW);
  208577. return cursorH;
  208578. }
  208579. void MouseCursor::showInWindow (ComponentPeer*) const
  208580. {
  208581. SetCursor ((HCURSOR) getHandle());
  208582. }
  208583. void MouseCursor::showInAllWindows() const
  208584. {
  208585. showInWindow (0);
  208586. }
  208587. class JuceDropSource : public ComBaseClassHelper <IDropSource>
  208588. {
  208589. public:
  208590. JuceDropSource() {}
  208591. ~JuceDropSource() {}
  208592. HRESULT __stdcall QueryContinueDrag (BOOL escapePressed, DWORD keys)
  208593. {
  208594. if (escapePressed)
  208595. return DRAGDROP_S_CANCEL;
  208596. if ((keys & (MK_LBUTTON | MK_RBUTTON)) == 0)
  208597. return DRAGDROP_S_DROP;
  208598. return S_OK;
  208599. }
  208600. HRESULT __stdcall GiveFeedback (DWORD)
  208601. {
  208602. return DRAGDROP_S_USEDEFAULTCURSORS;
  208603. }
  208604. };
  208605. class JuceEnumFormatEtc : public ComBaseClassHelper <IEnumFORMATETC>
  208606. {
  208607. public:
  208608. JuceEnumFormatEtc (const FORMATETC* const format_)
  208609. : format (format_),
  208610. index (0)
  208611. {
  208612. }
  208613. ~JuceEnumFormatEtc() {}
  208614. HRESULT __stdcall Clone (IEnumFORMATETC** result)
  208615. {
  208616. if (result == 0)
  208617. return E_POINTER;
  208618. JuceEnumFormatEtc* const newOne = new JuceEnumFormatEtc (format);
  208619. newOne->index = index;
  208620. *result = newOne;
  208621. return S_OK;
  208622. }
  208623. HRESULT __stdcall Next (ULONG celt, LPFORMATETC lpFormatEtc, ULONG* pceltFetched)
  208624. {
  208625. if (pceltFetched != 0)
  208626. *pceltFetched = 0;
  208627. else if (celt != 1)
  208628. return S_FALSE;
  208629. if (index == 0 && celt > 0 && lpFormatEtc != 0)
  208630. {
  208631. copyFormatEtc (lpFormatEtc [0], *format);
  208632. ++index;
  208633. if (pceltFetched != 0)
  208634. *pceltFetched = 1;
  208635. return S_OK;
  208636. }
  208637. return S_FALSE;
  208638. }
  208639. HRESULT __stdcall Skip (ULONG celt)
  208640. {
  208641. if (index + (int) celt >= 1)
  208642. return S_FALSE;
  208643. index += celt;
  208644. return S_OK;
  208645. }
  208646. HRESULT __stdcall Reset()
  208647. {
  208648. index = 0;
  208649. return S_OK;
  208650. }
  208651. private:
  208652. const FORMATETC* const format;
  208653. int index;
  208654. static void copyFormatEtc (FORMATETC& dest, const FORMATETC& source)
  208655. {
  208656. dest = source;
  208657. if (source.ptd != 0)
  208658. {
  208659. dest.ptd = (DVTARGETDEVICE*) CoTaskMemAlloc (sizeof (DVTARGETDEVICE));
  208660. *(dest.ptd) = *(source.ptd);
  208661. }
  208662. }
  208663. JuceEnumFormatEtc (const JuceEnumFormatEtc&);
  208664. JuceEnumFormatEtc& operator= (const JuceEnumFormatEtc&);
  208665. };
  208666. class JuceDataObject : public ComBaseClassHelper <IDataObject>
  208667. {
  208668. public:
  208669. JuceDataObject (JuceDropSource* const dropSource_,
  208670. const FORMATETC* const format_,
  208671. const STGMEDIUM* const medium_)
  208672. : dropSource (dropSource_),
  208673. format (format_),
  208674. medium (medium_)
  208675. {
  208676. }
  208677. virtual ~JuceDataObject()
  208678. {
  208679. jassert (refCount == 0);
  208680. }
  208681. HRESULT __stdcall GetData (FORMATETC __RPC_FAR* pFormatEtc, STGMEDIUM __RPC_FAR* pMedium)
  208682. {
  208683. if ((pFormatEtc->tymed & format->tymed) != 0
  208684. && pFormatEtc->cfFormat == format->cfFormat
  208685. && pFormatEtc->dwAspect == format->dwAspect)
  208686. {
  208687. pMedium->tymed = format->tymed;
  208688. pMedium->pUnkForRelease = 0;
  208689. if (format->tymed == TYMED_HGLOBAL)
  208690. {
  208691. const SIZE_T len = GlobalSize (medium->hGlobal);
  208692. void* const src = GlobalLock (medium->hGlobal);
  208693. void* const dst = GlobalAlloc (GMEM_FIXED, len);
  208694. memcpy (dst, src, len);
  208695. GlobalUnlock (medium->hGlobal);
  208696. pMedium->hGlobal = dst;
  208697. return S_OK;
  208698. }
  208699. }
  208700. return DV_E_FORMATETC;
  208701. }
  208702. HRESULT __stdcall QueryGetData (FORMATETC __RPC_FAR* f)
  208703. {
  208704. if (f == 0)
  208705. return E_INVALIDARG;
  208706. if (f->tymed == format->tymed
  208707. && f->cfFormat == format->cfFormat
  208708. && f->dwAspect == format->dwAspect)
  208709. return S_OK;
  208710. return DV_E_FORMATETC;
  208711. }
  208712. HRESULT __stdcall GetCanonicalFormatEtc (FORMATETC __RPC_FAR*, FORMATETC __RPC_FAR* pFormatEtcOut)
  208713. {
  208714. pFormatEtcOut->ptd = 0;
  208715. return E_NOTIMPL;
  208716. }
  208717. HRESULT __stdcall EnumFormatEtc (DWORD direction, IEnumFORMATETC __RPC_FAR *__RPC_FAR *result)
  208718. {
  208719. if (result == 0)
  208720. return E_POINTER;
  208721. if (direction == DATADIR_GET)
  208722. {
  208723. *result = new JuceEnumFormatEtc (format);
  208724. return S_OK;
  208725. }
  208726. *result = 0;
  208727. return E_NOTIMPL;
  208728. }
  208729. HRESULT __stdcall GetDataHere (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*) { return DATA_E_FORMATETC; }
  208730. HRESULT __stdcall SetData (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*, BOOL) { return E_NOTIMPL; }
  208731. HRESULT __stdcall DAdvise (FORMATETC __RPC_FAR*, DWORD, IAdviseSink __RPC_FAR*, DWORD __RPC_FAR*) { return OLE_E_ADVISENOTSUPPORTED; }
  208732. HRESULT __stdcall DUnadvise (DWORD) { return E_NOTIMPL; }
  208733. HRESULT __stdcall EnumDAdvise (IEnumSTATDATA __RPC_FAR *__RPC_FAR *) { return OLE_E_ADVISENOTSUPPORTED; }
  208734. private:
  208735. JuceDropSource* const dropSource;
  208736. const FORMATETC* const format;
  208737. const STGMEDIUM* const medium;
  208738. JuceDataObject (const JuceDataObject&);
  208739. JuceDataObject& operator= (const JuceDataObject&);
  208740. };
  208741. static HDROP createHDrop (const StringArray& fileNames)
  208742. {
  208743. int totalChars = 0;
  208744. for (int i = fileNames.size(); --i >= 0;)
  208745. totalChars += fileNames[i].length() + 1;
  208746. HDROP hDrop = (HDROP) GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT,
  208747. sizeof (DROPFILES) + sizeof (WCHAR) * (totalChars + 2));
  208748. if (hDrop != 0)
  208749. {
  208750. LPDROPFILES pDropFiles = (LPDROPFILES) GlobalLock (hDrop);
  208751. pDropFiles->pFiles = sizeof (DROPFILES);
  208752. pDropFiles->fWide = true;
  208753. WCHAR* fname = reinterpret_cast<WCHAR*> (addBytesToPointer (pDropFiles, sizeof (DROPFILES)));
  208754. for (int i = 0; i < fileNames.size(); ++i)
  208755. {
  208756. fileNames[i].copyToUnicode (fname, 2048);
  208757. fname += fileNames[i].length() + 1;
  208758. }
  208759. *fname = 0;
  208760. GlobalUnlock (hDrop);
  208761. }
  208762. return hDrop;
  208763. }
  208764. static bool performDragDrop (FORMATETC* const format, STGMEDIUM* const medium, const DWORD whatToDo)
  208765. {
  208766. JuceDropSource* const source = new JuceDropSource();
  208767. JuceDataObject* const data = new JuceDataObject (source, format, medium);
  208768. DWORD effect;
  208769. const HRESULT res = DoDragDrop (data, source, whatToDo, &effect);
  208770. data->Release();
  208771. source->Release();
  208772. return res == DRAGDROP_S_DROP;
  208773. }
  208774. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMove)
  208775. {
  208776. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  208777. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  208778. medium.hGlobal = createHDrop (files);
  208779. return performDragDrop (&format, &medium, canMove ? (DROPEFFECT_COPY | DROPEFFECT_MOVE)
  208780. : DROPEFFECT_COPY);
  208781. }
  208782. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  208783. {
  208784. FORMATETC format = { CF_TEXT, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  208785. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  208786. const int numChars = text.length();
  208787. medium.hGlobal = GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT, (numChars + 2) * sizeof (WCHAR));
  208788. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (medium.hGlobal));
  208789. text.copyToUnicode (data, numChars + 1);
  208790. format.cfFormat = CF_UNICODETEXT;
  208791. GlobalUnlock (medium.hGlobal);
  208792. return performDragDrop (&format, &medium, DROPEFFECT_COPY | DROPEFFECT_MOVE);
  208793. }
  208794. #endif
  208795. /*** End of inlined file: juce_win32_Windowing.cpp ***/
  208796. /*** Start of inlined file: juce_win32_FileChooser.cpp ***/
  208797. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208798. // compiled on its own).
  208799. #if JUCE_INCLUDED_FILE
  208800. namespace FileChooserHelpers
  208801. {
  208802. static bool areThereAnyAlwaysOnTopWindows()
  208803. {
  208804. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  208805. {
  208806. Component* c = Desktop::getInstance().getComponent (i);
  208807. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  208808. return true;
  208809. }
  208810. return false;
  208811. }
  208812. struct FileChooserCallbackInfo
  208813. {
  208814. String initialPath;
  208815. String returnedString; // need this to get non-existent pathnames from the directory chooser
  208816. ScopedPointer<Component> customComponent;
  208817. };
  208818. static int CALLBACK browseCallbackProc (HWND hWnd, UINT msg, LPARAM lParam, LPARAM lpData)
  208819. {
  208820. FileChooserCallbackInfo* info = (FileChooserCallbackInfo*) lpData;
  208821. if (msg == BFFM_INITIALIZED)
  208822. SendMessage (hWnd, BFFM_SETSELECTIONW, TRUE, (LPARAM) static_cast <const WCHAR*> (info->initialPath));
  208823. else if (msg == BFFM_VALIDATEFAILEDW)
  208824. info->returnedString = (LPCWSTR) lParam;
  208825. else if (msg == BFFM_VALIDATEFAILEDA)
  208826. info->returnedString = (const char*) lParam;
  208827. return 0;
  208828. }
  208829. static UINT_PTR CALLBACK openCallback (HWND hdlg, UINT uiMsg, WPARAM /*wParam*/, LPARAM lParam)
  208830. {
  208831. if (uiMsg == WM_INITDIALOG)
  208832. {
  208833. Component* customComp = ((FileChooserCallbackInfo*) (((OPENFILENAMEW*) lParam)->lCustData))->customComponent;
  208834. HWND dialogH = GetParent (hdlg);
  208835. jassert (dialogH != 0);
  208836. if (dialogH == 0)
  208837. dialogH = hdlg;
  208838. RECT r, cr;
  208839. GetWindowRect (dialogH, &r);
  208840. GetClientRect (dialogH, &cr);
  208841. SetWindowPos (dialogH, 0,
  208842. r.left, r.top,
  208843. customComp->getWidth() + jmax (150, (int) (r.right - r.left)),
  208844. jmax (150, (int) (r.bottom - r.top)),
  208845. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  208846. customComp->setBounds (cr.right, cr.top, customComp->getWidth(), cr.bottom - cr.top);
  208847. customComp->addToDesktop (0, dialogH);
  208848. }
  208849. else if (uiMsg == WM_NOTIFY)
  208850. {
  208851. LPOFNOTIFY ofn = (LPOFNOTIFY) lParam;
  208852. if (ofn->hdr.code == CDN_SELCHANGE)
  208853. {
  208854. FileChooserCallbackInfo* info = (FileChooserCallbackInfo*) ofn->lpOFN->lCustData;
  208855. FilePreviewComponent* comp = static_cast<FilePreviewComponent*> (info->customComponent->getChildComponent(0));
  208856. if (comp != 0)
  208857. {
  208858. WCHAR path [MAX_PATH * 2];
  208859. zerostruct (path);
  208860. CommDlg_OpenSave_GetFilePath (GetParent (hdlg), (LPARAM) &path, MAX_PATH);
  208861. comp->selectedFileChanged (File (path));
  208862. }
  208863. }
  208864. }
  208865. return 0;
  208866. }
  208867. class CustomComponentHolder : public Component
  208868. {
  208869. public:
  208870. CustomComponentHolder (Component* customComp)
  208871. {
  208872. setVisible (true);
  208873. setOpaque (true);
  208874. addAndMakeVisible (customComp);
  208875. setSize (jlimit (20, 800, customComp->getWidth()), customComp->getHeight());
  208876. }
  208877. void paint (Graphics& g)
  208878. {
  208879. g.fillAll (Colours::lightgrey);
  208880. }
  208881. void resized()
  208882. {
  208883. if (getNumChildComponents() > 0)
  208884. getChildComponent(0)->setBounds (getLocalBounds());
  208885. }
  208886. juce_UseDebuggingNewOperator
  208887. private:
  208888. CustomComponentHolder (const CustomComponentHolder&);
  208889. CustomComponentHolder& operator= (const CustomComponentHolder&);
  208890. };
  208891. }
  208892. void FileChooser::showPlatformDialog (Array<File>& results, const String& title, const File& currentFileOrDirectory,
  208893. const String& filter, bool selectsDirectory, bool /*selectsFiles*/,
  208894. bool isSaveDialogue, bool warnAboutOverwritingExistingFiles,
  208895. bool selectMultipleFiles, FilePreviewComponent* extraInfoComponent)
  208896. {
  208897. using namespace FileChooserHelpers;
  208898. HeapBlock<WCHAR> files;
  208899. const int charsAvailableForResult = 32768;
  208900. files.calloc (charsAvailableForResult + 1);
  208901. int filenameOffset = 0;
  208902. FileChooserCallbackInfo info;
  208903. // use a modal window as the parent for this dialog box
  208904. // to block input from other app windows
  208905. Component parentWindow (String::empty);
  208906. const Rectangle<int> mainMon (Desktop::getInstance().getMainMonitorArea());
  208907. parentWindow.setBounds (mainMon.getX() + mainMon.getWidth() / 4,
  208908. mainMon.getY() + mainMon.getHeight() / 4,
  208909. 0, 0);
  208910. parentWindow.setOpaque (true);
  208911. parentWindow.setAlwaysOnTop (areThereAnyAlwaysOnTopWindows());
  208912. parentWindow.addToDesktop (0);
  208913. if (extraInfoComponent == 0)
  208914. parentWindow.enterModalState();
  208915. if (currentFileOrDirectory.isDirectory())
  208916. {
  208917. info.initialPath = currentFileOrDirectory.getFullPathName();
  208918. }
  208919. else
  208920. {
  208921. currentFileOrDirectory.getFileName().copyToUnicode (files, charsAvailableForResult);
  208922. info.initialPath = currentFileOrDirectory.getParentDirectory().getFullPathName();
  208923. }
  208924. if (selectsDirectory)
  208925. {
  208926. BROWSEINFO bi;
  208927. zerostruct (bi);
  208928. bi.hwndOwner = (HWND) parentWindow.getWindowHandle();
  208929. bi.pszDisplayName = files;
  208930. bi.lpszTitle = title;
  208931. bi.lParam = (LPARAM) &info;
  208932. bi.lpfn = browseCallbackProc;
  208933. #ifdef BIF_USENEWUI
  208934. bi.ulFlags = BIF_USENEWUI | BIF_VALIDATE;
  208935. #else
  208936. bi.ulFlags = 0x50;
  208937. #endif
  208938. LPITEMIDLIST list = SHBrowseForFolder (&bi);
  208939. if (! SHGetPathFromIDListW (list, files))
  208940. {
  208941. files[0] = 0;
  208942. info.returnedString = String::empty;
  208943. }
  208944. LPMALLOC al;
  208945. if (list != 0 && SUCCEEDED (SHGetMalloc (&al)))
  208946. al->Free (list);
  208947. if (info.returnedString.isNotEmpty())
  208948. {
  208949. results.add (File (String (files)).getSiblingFile (info.returnedString));
  208950. return;
  208951. }
  208952. }
  208953. else
  208954. {
  208955. DWORD flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
  208956. if (warnAboutOverwritingExistingFiles)
  208957. flags |= OFN_OVERWRITEPROMPT;
  208958. if (selectMultipleFiles)
  208959. flags |= OFN_ALLOWMULTISELECT;
  208960. if (extraInfoComponent != 0)
  208961. {
  208962. flags |= OFN_ENABLEHOOK;
  208963. info.customComponent = new CustomComponentHolder (extraInfoComponent);
  208964. info.customComponent->enterModalState();
  208965. }
  208966. WCHAR filters [1024];
  208967. zerostruct (filters);
  208968. filter.copyToUnicode (filters, 1024);
  208969. filter.copyToUnicode (filters + filter.length() + 1, 1022 - filter.length());
  208970. OPENFILENAMEW of;
  208971. zerostruct (of);
  208972. #ifdef OPENFILENAME_SIZE_VERSION_400W
  208973. of.lStructSize = OPENFILENAME_SIZE_VERSION_400W;
  208974. #else
  208975. of.lStructSize = sizeof (of);
  208976. #endif
  208977. of.hwndOwner = (HWND) parentWindow.getWindowHandle();
  208978. of.lpstrFilter = filters;
  208979. of.nFilterIndex = 1;
  208980. of.lpstrFile = files;
  208981. of.nMaxFile = charsAvailableForResult;
  208982. of.lpstrInitialDir = info.initialPath;
  208983. of.lpstrTitle = title;
  208984. of.Flags = flags;
  208985. of.lCustData = (LPARAM) &info;
  208986. if (extraInfoComponent != 0)
  208987. of.lpfnHook = &openCallback;
  208988. if (! (isSaveDialogue ? GetSaveFileName (&of)
  208989. : GetOpenFileName (&of)))
  208990. return;
  208991. filenameOffset = of.nFileOffset;
  208992. }
  208993. if (selectMultipleFiles && filenameOffset > 0 && files [filenameOffset - 1] == 0)
  208994. {
  208995. const WCHAR* filename = files + filenameOffset;
  208996. while (*filename != 0)
  208997. {
  208998. results.add (File (String (files) + "\\" + String (filename)));
  208999. filename += CharacterFunctions::length (filename) + 1;
  209000. }
  209001. }
  209002. else if (files[0] != 0)
  209003. {
  209004. results.add (File (String (files)));
  209005. }
  209006. }
  209007. #endif
  209008. /*** End of inlined file: juce_win32_FileChooser.cpp ***/
  209009. /*** Start of inlined file: juce_win32_Misc.cpp ***/
  209010. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209011. // compiled on its own).
  209012. #if JUCE_INCLUDED_FILE
  209013. void SystemClipboard::copyTextToClipboard (const String& text)
  209014. {
  209015. if (OpenClipboard (0) != 0)
  209016. {
  209017. if (EmptyClipboard() != 0)
  209018. {
  209019. const int len = text.length();
  209020. if (len > 0)
  209021. {
  209022. HGLOBAL bufH = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE,
  209023. (len + 1) * sizeof (wchar_t));
  209024. if (bufH != 0)
  209025. {
  209026. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (bufH));
  209027. text.copyToUnicode (data, len);
  209028. GlobalUnlock (bufH);
  209029. SetClipboardData (CF_UNICODETEXT, bufH);
  209030. }
  209031. }
  209032. }
  209033. CloseClipboard();
  209034. }
  209035. }
  209036. const String SystemClipboard::getTextFromClipboard()
  209037. {
  209038. String result;
  209039. if (OpenClipboard (0) != 0)
  209040. {
  209041. HANDLE bufH = GetClipboardData (CF_UNICODETEXT);
  209042. if (bufH != 0)
  209043. {
  209044. const wchar_t* const data = (const wchar_t*) GlobalLock (bufH);
  209045. if (data != 0)
  209046. {
  209047. result = String (data, (int) (GlobalSize (bufH) / sizeof (wchar_t)));
  209048. GlobalUnlock (bufH);
  209049. }
  209050. }
  209051. CloseClipboard();
  209052. }
  209053. return result;
  209054. }
  209055. #endif
  209056. /*** End of inlined file: juce_win32_Misc.cpp ***/
  209057. /*** Start of inlined file: juce_win32_ActiveXComponent.cpp ***/
  209058. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209059. // compiled on its own).
  209060. #if JUCE_INCLUDED_FILE
  209061. namespace ActiveXHelpers
  209062. {
  209063. class JuceIStorage : public ComBaseClassHelper <IStorage>
  209064. {
  209065. public:
  209066. JuceIStorage() {}
  209067. ~JuceIStorage() {}
  209068. HRESULT __stdcall CreateStream (const WCHAR*, DWORD, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  209069. HRESULT __stdcall OpenStream (const WCHAR*, void*, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  209070. HRESULT __stdcall CreateStorage (const WCHAR*, DWORD, DWORD, DWORD, IStorage**) { return E_NOTIMPL; }
  209071. HRESULT __stdcall OpenStorage (const WCHAR*, IStorage*, DWORD, SNB, DWORD, IStorage**) { return E_NOTIMPL; }
  209072. HRESULT __stdcall CopyTo (DWORD, IID const*, SNB, IStorage*) { return E_NOTIMPL; }
  209073. HRESULT __stdcall MoveElementTo (const OLECHAR*,IStorage*, const OLECHAR*, DWORD) { return E_NOTIMPL; }
  209074. HRESULT __stdcall Commit (DWORD) { return E_NOTIMPL; }
  209075. HRESULT __stdcall Revert() { return E_NOTIMPL; }
  209076. HRESULT __stdcall EnumElements (DWORD, void*, DWORD, IEnumSTATSTG**) { return E_NOTIMPL; }
  209077. HRESULT __stdcall DestroyElement (const OLECHAR*) { return E_NOTIMPL; }
  209078. HRESULT __stdcall RenameElement (const WCHAR*, const WCHAR*) { return E_NOTIMPL; }
  209079. HRESULT __stdcall SetElementTimes (const WCHAR*, FILETIME const*, FILETIME const*, FILETIME const*) { return E_NOTIMPL; }
  209080. HRESULT __stdcall SetClass (REFCLSID) { return S_OK; }
  209081. HRESULT __stdcall SetStateBits (DWORD, DWORD) { return E_NOTIMPL; }
  209082. HRESULT __stdcall Stat (STATSTG*, DWORD) { return E_NOTIMPL; }
  209083. juce_UseDebuggingNewOperator
  209084. };
  209085. class JuceOleInPlaceFrame : public ComBaseClassHelper <IOleInPlaceFrame>
  209086. {
  209087. HWND window;
  209088. public:
  209089. JuceOleInPlaceFrame (HWND window_) : window (window_) {}
  209090. ~JuceOleInPlaceFrame() {}
  209091. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  209092. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  209093. HRESULT __stdcall GetBorder (LPRECT) { return E_NOTIMPL; }
  209094. HRESULT __stdcall RequestBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  209095. HRESULT __stdcall SetBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  209096. HRESULT __stdcall SetActiveObject (IOleInPlaceActiveObject*, LPCOLESTR) { return S_OK; }
  209097. HRESULT __stdcall InsertMenus (HMENU, LPOLEMENUGROUPWIDTHS) { return E_NOTIMPL; }
  209098. HRESULT __stdcall SetMenu (HMENU, HOLEMENU, HWND) { return S_OK; }
  209099. HRESULT __stdcall RemoveMenus (HMENU) { return E_NOTIMPL; }
  209100. HRESULT __stdcall SetStatusText (LPCOLESTR) { return S_OK; }
  209101. HRESULT __stdcall EnableModeless (BOOL) { return S_OK; }
  209102. HRESULT __stdcall TranslateAccelerator(LPMSG, WORD) { return E_NOTIMPL; }
  209103. juce_UseDebuggingNewOperator
  209104. };
  209105. class JuceIOleInPlaceSite : public ComBaseClassHelper <IOleInPlaceSite>
  209106. {
  209107. HWND window;
  209108. JuceOleInPlaceFrame* frame;
  209109. public:
  209110. JuceIOleInPlaceSite (HWND window_)
  209111. : window (window_),
  209112. frame (new JuceOleInPlaceFrame (window))
  209113. {}
  209114. ~JuceIOleInPlaceSite()
  209115. {
  209116. frame->Release();
  209117. }
  209118. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  209119. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  209120. HRESULT __stdcall CanInPlaceActivate() { return S_OK; }
  209121. HRESULT __stdcall OnInPlaceActivate() { return S_OK; }
  209122. HRESULT __stdcall OnUIActivate() { return S_OK; }
  209123. HRESULT __stdcall GetWindowContext (LPOLEINPLACEFRAME* lplpFrame, LPOLEINPLACEUIWINDOW* lplpDoc, LPRECT, LPRECT, LPOLEINPLACEFRAMEINFO lpFrameInfo)
  209124. {
  209125. /* Note: if you call AddRef on the frame here, then some types of object (e.g. web browser control) cause leaks..
  209126. If you don't call AddRef then others crash (e.g. QuickTime).. Bit of a catch-22, so letting it leak is probably preferable.
  209127. */
  209128. if (lplpFrame != 0) { frame->AddRef(); *lplpFrame = frame; }
  209129. if (lplpDoc != 0) *lplpDoc = 0;
  209130. lpFrameInfo->fMDIApp = FALSE;
  209131. lpFrameInfo->hwndFrame = window;
  209132. lpFrameInfo->haccel = 0;
  209133. lpFrameInfo->cAccelEntries = 0;
  209134. return S_OK;
  209135. }
  209136. HRESULT __stdcall Scroll (SIZE) { return E_NOTIMPL; }
  209137. HRESULT __stdcall OnUIDeactivate (BOOL) { return S_OK; }
  209138. HRESULT __stdcall OnInPlaceDeactivate() { return S_OK; }
  209139. HRESULT __stdcall DiscardUndoState() { return E_NOTIMPL; }
  209140. HRESULT __stdcall DeactivateAndUndo() { return E_NOTIMPL; }
  209141. HRESULT __stdcall OnPosRectChange (LPCRECT) { return S_OK; }
  209142. juce_UseDebuggingNewOperator
  209143. };
  209144. class JuceIOleClientSite : public ComBaseClassHelper <IOleClientSite>
  209145. {
  209146. JuceIOleInPlaceSite* inplaceSite;
  209147. public:
  209148. JuceIOleClientSite (HWND window)
  209149. : inplaceSite (new JuceIOleInPlaceSite (window))
  209150. {}
  209151. ~JuceIOleClientSite()
  209152. {
  209153. inplaceSite->Release();
  209154. }
  209155. HRESULT __stdcall QueryInterface (REFIID type, void __RPC_FAR* __RPC_FAR* result)
  209156. {
  209157. if (type == IID_IOleInPlaceSite)
  209158. {
  209159. inplaceSite->AddRef();
  209160. *result = static_cast <IOleInPlaceSite*> (inplaceSite);
  209161. return S_OK;
  209162. }
  209163. return ComBaseClassHelper <IOleClientSite>::QueryInterface (type, result);
  209164. }
  209165. HRESULT __stdcall SaveObject() { return E_NOTIMPL; }
  209166. HRESULT __stdcall GetMoniker (DWORD, DWORD, IMoniker**) { return E_NOTIMPL; }
  209167. HRESULT __stdcall GetContainer (LPOLECONTAINER* ppContainer) { *ppContainer = 0; return E_NOINTERFACE; }
  209168. HRESULT __stdcall ShowObject() { return S_OK; }
  209169. HRESULT __stdcall OnShowWindow (BOOL) { return E_NOTIMPL; }
  209170. HRESULT __stdcall RequestNewObjectLayout() { return E_NOTIMPL; }
  209171. juce_UseDebuggingNewOperator
  209172. };
  209173. static Array<ActiveXControlComponent*> activeXComps;
  209174. static HWND getHWND (const ActiveXControlComponent* const component)
  209175. {
  209176. HWND hwnd = 0;
  209177. const IID iid = IID_IOleWindow;
  209178. IOleWindow* const window = (IOleWindow*) component->queryInterface (&iid);
  209179. if (window != 0)
  209180. {
  209181. window->GetWindow (&hwnd);
  209182. window->Release();
  209183. }
  209184. return hwnd;
  209185. }
  209186. static void offerActiveXMouseEventToPeer (ComponentPeer* const peer, HWND hwnd, UINT message, LPARAM lParam)
  209187. {
  209188. RECT activeXRect, peerRect;
  209189. GetWindowRect (hwnd, &activeXRect);
  209190. GetWindowRect ((HWND) peer->getNativeHandle(), &peerRect);
  209191. const Point<int> mousePos (GET_X_LPARAM (lParam) + activeXRect.left - peerRect.left,
  209192. GET_Y_LPARAM (lParam) + activeXRect.top - peerRect.top);
  209193. const int64 mouseEventTime = Win32ComponentPeer::getMouseEventTime();
  209194. ModifierKeys::getCurrentModifiersRealtime(); // to update the mouse button flags
  209195. switch (message)
  209196. {
  209197. case WM_MOUSEMOVE:
  209198. case WM_LBUTTONDOWN:
  209199. case WM_MBUTTONDOWN:
  209200. case WM_RBUTTONDOWN:
  209201. case WM_LBUTTONUP:
  209202. case WM_MBUTTONUP:
  209203. case WM_RBUTTONUP:
  209204. peer->handleMouseEvent (0, mousePos, Win32ComponentPeer::currentModifiers, mouseEventTime);
  209205. break;
  209206. default:
  209207. break;
  209208. }
  209209. }
  209210. }
  209211. class ActiveXControlComponent::Pimpl : public ComponentMovementWatcher
  209212. {
  209213. ActiveXControlComponent& owner;
  209214. bool wasShowing;
  209215. public:
  209216. HWND controlHWND;
  209217. IStorage* storage;
  209218. IOleClientSite* clientSite;
  209219. IOleObject* control;
  209220. Pimpl (HWND hwnd, ActiveXControlComponent& owner_)
  209221. : ComponentMovementWatcher (&owner_),
  209222. owner (owner_),
  209223. wasShowing (owner_.isShowing()),
  209224. controlHWND (0),
  209225. storage (new ActiveXHelpers::JuceIStorage()),
  209226. clientSite (new ActiveXHelpers::JuceIOleClientSite (hwnd)),
  209227. control (0)
  209228. {
  209229. }
  209230. ~Pimpl()
  209231. {
  209232. if (control != 0)
  209233. {
  209234. control->Close (OLECLOSE_NOSAVE);
  209235. control->Release();
  209236. }
  209237. clientSite->Release();
  209238. storage->Release();
  209239. }
  209240. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  209241. {
  209242. Component* const topComp = owner.getTopLevelComponent();
  209243. if (topComp->getPeer() != 0)
  209244. {
  209245. const Point<int> pos (owner.relativePositionToOtherComponent (topComp, Point<int>()));
  209246. owner.setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), owner.getWidth(), owner.getHeight()));
  209247. }
  209248. }
  209249. void componentPeerChanged()
  209250. {
  209251. const bool isShowingNow = owner.isShowing();
  209252. if (wasShowing != isShowingNow)
  209253. {
  209254. wasShowing = isShowingNow;
  209255. owner.setControlVisible (isShowingNow);
  209256. }
  209257. componentMovedOrResized (true, true);
  209258. }
  209259. void componentVisibilityChanged (Component&)
  209260. {
  209261. componentPeerChanged();
  209262. }
  209263. // intercepts events going to an activeX control, so we can sneakily use the mouse events
  209264. static LRESULT CALLBACK activeXHookWndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
  209265. {
  209266. for (int i = ActiveXHelpers::activeXComps.size(); --i >= 0;)
  209267. {
  209268. const ActiveXControlComponent* const ax = ActiveXHelpers::activeXComps.getUnchecked(i);
  209269. if (ax->control != 0 && ax->control->controlHWND == hwnd)
  209270. {
  209271. switch (message)
  209272. {
  209273. case WM_MOUSEMOVE:
  209274. case WM_LBUTTONDOWN:
  209275. case WM_MBUTTONDOWN:
  209276. case WM_RBUTTONDOWN:
  209277. case WM_LBUTTONUP:
  209278. case WM_MBUTTONUP:
  209279. case WM_RBUTTONUP:
  209280. case WM_LBUTTONDBLCLK:
  209281. case WM_MBUTTONDBLCLK:
  209282. case WM_RBUTTONDBLCLK:
  209283. if (ax->isShowing())
  209284. {
  209285. ComponentPeer* const peer = ax->getPeer();
  209286. if (peer != 0)
  209287. {
  209288. ActiveXHelpers::offerActiveXMouseEventToPeer (peer, hwnd, message, lParam);
  209289. if (! ax->areMouseEventsAllowed())
  209290. return 0;
  209291. }
  209292. }
  209293. break;
  209294. default:
  209295. break;
  209296. }
  209297. return CallWindowProc ((WNDPROC) ax->originalWndProc, hwnd, message, wParam, lParam);
  209298. }
  209299. }
  209300. return DefWindowProc (hwnd, message, wParam, lParam);
  209301. }
  209302. };
  209303. ActiveXControlComponent::ActiveXControlComponent()
  209304. : originalWndProc (0),
  209305. mouseEventsAllowed (true)
  209306. {
  209307. ActiveXHelpers::activeXComps.add (this);
  209308. }
  209309. ActiveXControlComponent::~ActiveXControlComponent()
  209310. {
  209311. deleteControl();
  209312. ActiveXHelpers::activeXComps.removeValue (this);
  209313. }
  209314. void ActiveXControlComponent::paint (Graphics& g)
  209315. {
  209316. if (control == 0)
  209317. g.fillAll (Colours::lightgrey);
  209318. }
  209319. bool ActiveXControlComponent::createControl (const void* controlIID)
  209320. {
  209321. deleteControl();
  209322. ComponentPeer* const peer = getPeer();
  209323. // the component must have already been added to a real window when you call this!
  209324. jassert (dynamic_cast <Win32ComponentPeer*> (peer) != 0);
  209325. if (dynamic_cast <Win32ComponentPeer*> (peer) != 0)
  209326. {
  209327. const Point<int> pos (relativePositionToOtherComponent (getTopLevelComponent(), Point<int>()));
  209328. HWND hwnd = (HWND) peer->getNativeHandle();
  209329. ScopedPointer<Pimpl> newControl (new Pimpl (hwnd, *this));
  209330. HRESULT hr;
  209331. if ((hr = OleCreate (*(const IID*) controlIID, IID_IOleObject, 1 /*OLERENDER_DRAW*/, 0,
  209332. newControl->clientSite, newControl->storage,
  209333. (void**) &(newControl->control))) == S_OK)
  209334. {
  209335. newControl->control->SetHostNames (L"Juce", 0);
  209336. if (OleSetContainedObject (newControl->control, TRUE) == S_OK)
  209337. {
  209338. RECT rect;
  209339. rect.left = pos.getX();
  209340. rect.top = pos.getY();
  209341. rect.right = pos.getX() + getWidth();
  209342. rect.bottom = pos.getY() + getHeight();
  209343. if (newControl->control->DoVerb (OLEIVERB_SHOW, 0, newControl->clientSite, 0, hwnd, &rect) == S_OK)
  209344. {
  209345. control = newControl;
  209346. setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), getWidth(), getHeight()));
  209347. control->controlHWND = ActiveXHelpers::getHWND (this);
  209348. if (control->controlHWND != 0)
  209349. {
  209350. originalWndProc = (void*) (pointer_sized_int) GetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC);
  209351. SetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC, (LONG_PTR) Pimpl::activeXHookWndProc);
  209352. }
  209353. return true;
  209354. }
  209355. }
  209356. }
  209357. }
  209358. return false;
  209359. }
  209360. void ActiveXControlComponent::deleteControl()
  209361. {
  209362. control = 0;
  209363. originalWndProc = 0;
  209364. }
  209365. void* ActiveXControlComponent::queryInterface (const void* iid) const
  209366. {
  209367. void* result = 0;
  209368. if (control != 0 && control->control != 0
  209369. && SUCCEEDED (control->control->QueryInterface (*(const IID*) iid, &result)))
  209370. return result;
  209371. return 0;
  209372. }
  209373. void ActiveXControlComponent::setControlBounds (const Rectangle<int>& newBounds) const
  209374. {
  209375. if (control->controlHWND != 0)
  209376. MoveWindow (control->controlHWND, newBounds.getX(), newBounds.getY(), newBounds.getWidth(), newBounds.getHeight(), TRUE);
  209377. }
  209378. void ActiveXControlComponent::setControlVisible (const bool shouldBeVisible) const
  209379. {
  209380. if (control->controlHWND != 0)
  209381. ShowWindow (control->controlHWND, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  209382. }
  209383. void ActiveXControlComponent::setMouseEventsAllowed (const bool eventsCanReachControl)
  209384. {
  209385. mouseEventsAllowed = eventsCanReachControl;
  209386. }
  209387. #endif
  209388. /*** End of inlined file: juce_win32_ActiveXComponent.cpp ***/
  209389. /*** Start of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  209390. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209391. // compiled on its own).
  209392. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  209393. using namespace QTOLibrary;
  209394. using namespace QTOControlLib;
  209395. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  209396. static bool isQTAvailable = false;
  209397. class QuickTimeMovieComponent::Pimpl
  209398. {
  209399. public:
  209400. Pimpl() : dataHandle (0)
  209401. {
  209402. }
  209403. ~Pimpl()
  209404. {
  209405. clearHandle();
  209406. }
  209407. void clearHandle()
  209408. {
  209409. if (dataHandle != 0)
  209410. {
  209411. DisposeHandle (dataHandle);
  209412. dataHandle = 0;
  209413. }
  209414. }
  209415. IQTControlPtr qtControl;
  209416. IQTMoviePtr qtMovie;
  209417. Handle dataHandle;
  209418. };
  209419. QuickTimeMovieComponent::QuickTimeMovieComponent()
  209420. : movieLoaded (false),
  209421. controllerVisible (true)
  209422. {
  209423. pimpl = new Pimpl();
  209424. setMouseEventsAllowed (false);
  209425. }
  209426. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  209427. {
  209428. closeMovie();
  209429. pimpl->qtControl = 0;
  209430. deleteControl();
  209431. pimpl = 0;
  209432. }
  209433. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  209434. {
  209435. if (! isQTAvailable)
  209436. isQTAvailable = (InitializeQTML (0) == noErr) && (EnterMovies() == noErr);
  209437. return isQTAvailable;
  209438. }
  209439. void QuickTimeMovieComponent::createControlIfNeeded()
  209440. {
  209441. if (isShowing() && ! isControlCreated())
  209442. {
  209443. const IID qtIID = __uuidof (QTControl);
  209444. if (createControl (&qtIID))
  209445. {
  209446. const IID qtInterfaceIID = __uuidof (IQTControl);
  209447. pimpl->qtControl = (IQTControl*) queryInterface (&qtInterfaceIID);
  209448. if (pimpl->qtControl != 0)
  209449. {
  209450. pimpl->qtControl->Release(); // it has one ref too many at this point
  209451. pimpl->qtControl->QuickTimeInitialize();
  209452. pimpl->qtControl->PutSizing (qtMovieFitsControl);
  209453. if (movieFile != File::nonexistent)
  209454. loadMovie (movieFile, controllerVisible);
  209455. }
  209456. }
  209457. }
  209458. }
  209459. bool QuickTimeMovieComponent::isControlCreated() const
  209460. {
  209461. return isControlOpen();
  209462. }
  209463. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  209464. const bool isControllerVisible)
  209465. {
  209466. const ScopedPointer<InputStream> movieStreamDeleter (movieStream);
  209467. movieFile = File::nonexistent;
  209468. movieLoaded = false;
  209469. pimpl->qtMovie = 0;
  209470. controllerVisible = isControllerVisible;
  209471. createControlIfNeeded();
  209472. if (isControlCreated())
  209473. {
  209474. if (pimpl->qtControl != 0)
  209475. {
  209476. pimpl->qtControl->Put_MovieHandle (0);
  209477. pimpl->clearHandle();
  209478. Movie movie;
  209479. if (juce_OpenQuickTimeMovieFromStream (movieStream, movie, pimpl->dataHandle))
  209480. {
  209481. pimpl->qtControl->Put_MovieHandle ((long) (pointer_sized_int) movie);
  209482. pimpl->qtMovie = pimpl->qtControl->GetMovie();
  209483. if (pimpl->qtMovie != 0)
  209484. pimpl->qtMovie->PutMovieControllerType (isControllerVisible ? qtMovieControllerTypeStandard
  209485. : qtMovieControllerTypeNone);
  209486. }
  209487. if (movie == 0)
  209488. pimpl->clearHandle();
  209489. }
  209490. movieLoaded = (pimpl->qtMovie != 0);
  209491. }
  209492. else
  209493. {
  209494. // You're trying to open a movie when the control hasn't yet been created, probably because
  209495. // you've not yet added this component to a Window and made the whole component hierarchy visible.
  209496. jassertfalse;
  209497. }
  209498. return movieLoaded;
  209499. }
  209500. void QuickTimeMovieComponent::closeMovie()
  209501. {
  209502. stop();
  209503. movieFile = File::nonexistent;
  209504. movieLoaded = false;
  209505. pimpl->qtMovie = 0;
  209506. if (pimpl->qtControl != 0)
  209507. pimpl->qtControl->Put_MovieHandle (0);
  209508. pimpl->clearHandle();
  209509. }
  209510. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  209511. {
  209512. return movieFile;
  209513. }
  209514. bool QuickTimeMovieComponent::isMovieOpen() const
  209515. {
  209516. return movieLoaded;
  209517. }
  209518. double QuickTimeMovieComponent::getMovieDuration() const
  209519. {
  209520. if (pimpl->qtMovie != 0)
  209521. return pimpl->qtMovie->GetDuration() / (double) pimpl->qtMovie->GetTimeScale();
  209522. return 0.0;
  209523. }
  209524. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  209525. {
  209526. if (pimpl->qtMovie != 0)
  209527. {
  209528. struct QTRECT r = pimpl->qtMovie->GetNaturalRect();
  209529. width = r.right - r.left;
  209530. height = r.bottom - r.top;
  209531. }
  209532. else
  209533. {
  209534. width = height = 0;
  209535. }
  209536. }
  209537. void QuickTimeMovieComponent::play()
  209538. {
  209539. if (pimpl->qtMovie != 0)
  209540. pimpl->qtMovie->Play();
  209541. }
  209542. void QuickTimeMovieComponent::stop()
  209543. {
  209544. if (pimpl->qtMovie != 0)
  209545. pimpl->qtMovie->Stop();
  209546. }
  209547. bool QuickTimeMovieComponent::isPlaying() const
  209548. {
  209549. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetRate() != 0.0f;
  209550. }
  209551. void QuickTimeMovieComponent::setPosition (const double seconds)
  209552. {
  209553. if (pimpl->qtMovie != 0)
  209554. pimpl->qtMovie->PutTime ((long) (seconds * pimpl->qtMovie->GetTimeScale()));
  209555. }
  209556. double QuickTimeMovieComponent::getPosition() const
  209557. {
  209558. if (pimpl->qtMovie != 0)
  209559. return pimpl->qtMovie->GetTime() / (double) pimpl->qtMovie->GetTimeScale();
  209560. return 0.0;
  209561. }
  209562. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  209563. {
  209564. if (pimpl->qtMovie != 0)
  209565. pimpl->qtMovie->PutRate (newSpeed);
  209566. }
  209567. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  209568. {
  209569. if (pimpl->qtMovie != 0)
  209570. {
  209571. pimpl->qtMovie->PutAudioVolume (newVolume);
  209572. pimpl->qtMovie->PutAudioMute (newVolume <= 0);
  209573. }
  209574. }
  209575. float QuickTimeMovieComponent::getMovieVolume() const
  209576. {
  209577. if (pimpl->qtMovie != 0)
  209578. return pimpl->qtMovie->GetAudioVolume();
  209579. return 0.0f;
  209580. }
  209581. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  209582. {
  209583. if (pimpl->qtMovie != 0)
  209584. pimpl->qtMovie->PutLoop (shouldLoop);
  209585. }
  209586. bool QuickTimeMovieComponent::isLooping() const
  209587. {
  209588. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetLoop();
  209589. }
  209590. bool QuickTimeMovieComponent::isControllerVisible() const
  209591. {
  209592. return controllerVisible;
  209593. }
  209594. void QuickTimeMovieComponent::parentHierarchyChanged()
  209595. {
  209596. createControlIfNeeded();
  209597. QTCompBaseClass::parentHierarchyChanged();
  209598. }
  209599. void QuickTimeMovieComponent::visibilityChanged()
  209600. {
  209601. createControlIfNeeded();
  209602. QTCompBaseClass::visibilityChanged();
  209603. }
  209604. void QuickTimeMovieComponent::paint (Graphics& g)
  209605. {
  209606. if (! isControlCreated())
  209607. g.fillAll (Colours::black);
  209608. }
  209609. static Handle createHandleDataRef (Handle dataHandle, const char* fileName)
  209610. {
  209611. Handle dataRef = 0;
  209612. OSStatus err = PtrToHand (&dataHandle, &dataRef, sizeof (Handle));
  209613. if (err == noErr)
  209614. {
  209615. Str255 suffix;
  209616. CharacterFunctions::copy ((char*) suffix, fileName, 128);
  209617. StringPtr name = suffix;
  209618. err = PtrAndHand (name, dataRef, name[0] + 1);
  209619. if (err == noErr)
  209620. {
  209621. long atoms[3];
  209622. atoms[0] = EndianU32_NtoB (3 * sizeof (long));
  209623. atoms[1] = EndianU32_NtoB (kDataRefExtensionMacOSFileType);
  209624. atoms[2] = EndianU32_NtoB (MovieFileType);
  209625. err = PtrAndHand (atoms, dataRef, 3 * sizeof (long));
  209626. if (err == noErr)
  209627. return dataRef;
  209628. }
  209629. DisposeHandle (dataRef);
  209630. }
  209631. return 0;
  209632. }
  209633. static CFStringRef juceStringToCFString (const String& s)
  209634. {
  209635. const int len = s.length();
  209636. const juce_wchar* const t = s;
  209637. HeapBlock <UniChar> temp (len + 2);
  209638. for (int i = 0; i <= len; ++i)
  209639. temp[i] = t[i];
  209640. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  209641. }
  209642. static bool openMovie (QTNewMoviePropertyElement* props, int prop, Movie& movie)
  209643. {
  209644. Boolean trueBool = true;
  209645. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  209646. props[prop].propID = kQTMovieInstantiationPropertyID_DontResolveDataRefs;
  209647. props[prop].propValueSize = sizeof (trueBool);
  209648. props[prop].propValueAddress = &trueBool;
  209649. ++prop;
  209650. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  209651. props[prop].propID = kQTMovieInstantiationPropertyID_AsyncOK;
  209652. props[prop].propValueSize = sizeof (trueBool);
  209653. props[prop].propValueAddress = &trueBool;
  209654. ++prop;
  209655. Boolean isActive = true;
  209656. props[prop].propClass = kQTPropertyClass_NewMovieProperty;
  209657. props[prop].propID = kQTNewMoviePropertyID_Active;
  209658. props[prop].propValueSize = sizeof (isActive);
  209659. props[prop].propValueAddress = &isActive;
  209660. ++prop;
  209661. MacSetPort (0);
  209662. jassert (prop <= 5);
  209663. OSStatus err = NewMovieFromProperties (prop, props, 0, 0, &movie);
  209664. return err == noErr;
  209665. }
  209666. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle)
  209667. {
  209668. if (input == 0)
  209669. return false;
  209670. dataHandle = 0;
  209671. bool ok = false;
  209672. QTNewMoviePropertyElement props[5];
  209673. zeromem (props, sizeof (props));
  209674. int prop = 0;
  209675. DataReferenceRecord dr;
  209676. props[prop].propClass = kQTPropertyClass_DataLocation;
  209677. props[prop].propID = kQTDataLocationPropertyID_DataReference;
  209678. props[prop].propValueSize = sizeof (dr);
  209679. props[prop].propValueAddress = &dr;
  209680. ++prop;
  209681. FileInputStream* const fin = dynamic_cast <FileInputStream*> (input);
  209682. if (fin != 0)
  209683. {
  209684. CFStringRef filePath = juceStringToCFString (fin->getFile().getFullPathName());
  209685. QTNewDataReferenceFromFullPathCFString (filePath, (QTPathStyle) kQTNativeDefaultPathStyle, 0,
  209686. &dr.dataRef, &dr.dataRefType);
  209687. ok = openMovie (props, prop, movie);
  209688. DisposeHandle (dr.dataRef);
  209689. CFRelease (filePath);
  209690. }
  209691. else
  209692. {
  209693. // sanity-check because this currently needs to load the whole stream into memory..
  209694. jassert (input->getTotalLength() < 50 * 1024 * 1024);
  209695. dataHandle = NewHandle ((Size) input->getTotalLength());
  209696. HLock (dataHandle);
  209697. // read the entire stream into memory - this is a pain, but can't get it to work
  209698. // properly using a custom callback to supply the data.
  209699. input->read (*dataHandle, (int) input->getTotalLength());
  209700. HUnlock (dataHandle);
  209701. // different types to get QT to try. (We should really be a bit smarter here by
  209702. // working out in advance which one the stream contains, rather than just trying
  209703. // each one)
  209704. const char* const suffixesToTry[] = { "\04.mov", "\04.mp3",
  209705. "\04.avi", "\04.m4a" };
  209706. for (int i = 0; i < numElementsInArray (suffixesToTry) && ! ok; ++i)
  209707. {
  209708. /* // this fails for some bizarre reason - it can be bodged to work with
  209709. // movies, but can't seem to do it for other file types..
  209710. QTNewMovieUserProcRecord procInfo;
  209711. procInfo.getMovieUserProc = NewGetMovieUPP (readMovieStreamProc);
  209712. procInfo.getMovieUserProcRefcon = this;
  209713. procInfo.defaultDataRef.dataRef = dataRef;
  209714. procInfo.defaultDataRef.dataRefType = HandleDataHandlerSubType;
  209715. props[prop].propClass = kQTPropertyClass_DataLocation;
  209716. props[prop].propID = kQTDataLocationPropertyID_MovieUserProc;
  209717. props[prop].propValueSize = sizeof (procInfo);
  209718. props[prop].propValueAddress = (void*) &procInfo;
  209719. ++prop; */
  209720. dr.dataRef = createHandleDataRef (dataHandle, suffixesToTry [i]);
  209721. dr.dataRefType = HandleDataHandlerSubType;
  209722. ok = openMovie (props, prop, movie);
  209723. DisposeHandle (dr.dataRef);
  209724. }
  209725. }
  209726. return ok;
  209727. }
  209728. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  209729. const bool isControllerVisible)
  209730. {
  209731. const bool ok = loadMovie (static_cast <InputStream*> (movieFile_.createInputStream()), isControllerVisible);
  209732. movieFile = movieFile_;
  209733. return ok;
  209734. }
  209735. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  209736. const bool isControllerVisible)
  209737. {
  209738. return loadMovie (static_cast <InputStream*> (movieURL.createInputStream (false)), isControllerVisible);
  209739. }
  209740. void QuickTimeMovieComponent::goToStart()
  209741. {
  209742. setPosition (0.0);
  209743. }
  209744. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  209745. const RectanglePlacement& placement)
  209746. {
  209747. int normalWidth, normalHeight;
  209748. getMovieNormalSize (normalWidth, normalHeight);
  209749. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  209750. {
  209751. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  209752. placement.applyTo (x, y, w, h,
  209753. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  209754. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  209755. if (w > 0 && h > 0)
  209756. {
  209757. setBounds (roundToInt (x), roundToInt (y),
  209758. roundToInt (w), roundToInt (h));
  209759. }
  209760. }
  209761. else
  209762. {
  209763. setBounds (spaceToFitWithin);
  209764. }
  209765. }
  209766. #endif
  209767. /*** End of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  209768. /*** Start of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  209769. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209770. // compiled on its own).
  209771. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  209772. class WebBrowserComponentInternal : public ActiveXControlComponent
  209773. {
  209774. public:
  209775. WebBrowserComponentInternal()
  209776. : browser (0),
  209777. connectionPoint (0),
  209778. adviseCookie (0)
  209779. {
  209780. }
  209781. ~WebBrowserComponentInternal()
  209782. {
  209783. if (connectionPoint != 0)
  209784. connectionPoint->Unadvise (adviseCookie);
  209785. if (browser != 0)
  209786. browser->Release();
  209787. }
  209788. void createBrowser()
  209789. {
  209790. createControl (&CLSID_WebBrowser);
  209791. browser = (IWebBrowser2*) queryInterface (&IID_IWebBrowser2);
  209792. IConnectionPointContainer* connectionPointContainer = (IConnectionPointContainer*) queryInterface (&IID_IConnectionPointContainer);
  209793. if (connectionPointContainer != 0)
  209794. {
  209795. connectionPointContainer->FindConnectionPoint (DIID_DWebBrowserEvents2,
  209796. &connectionPoint);
  209797. if (connectionPoint != 0)
  209798. {
  209799. WebBrowserComponent* const owner = dynamic_cast <WebBrowserComponent*> (getParentComponent());
  209800. jassert (owner != 0);
  209801. EventHandler* handler = new EventHandler (owner);
  209802. connectionPoint->Advise (handler, &adviseCookie);
  209803. handler->Release();
  209804. }
  209805. }
  209806. }
  209807. void goToURL (const String& url,
  209808. const StringArray* headers,
  209809. const MemoryBlock* postData)
  209810. {
  209811. if (browser != 0)
  209812. {
  209813. LPSAFEARRAY sa = 0;
  209814. VARIANT flags, frame, postDataVar, headersVar; // (_variant_t isn't available in all compilers)
  209815. VariantInit (&flags);
  209816. VariantInit (&frame);
  209817. VariantInit (&postDataVar);
  209818. VariantInit (&headersVar);
  209819. if (headers != 0)
  209820. {
  209821. V_VT (&headersVar) = VT_BSTR;
  209822. V_BSTR (&headersVar) = SysAllocString ((const OLECHAR*) headers->joinIntoString ("\r\n"));
  209823. }
  209824. if (postData != 0 && postData->getSize() > 0)
  209825. {
  209826. LPSAFEARRAY sa = SafeArrayCreateVector (VT_UI1, 0, postData->getSize());
  209827. if (sa != 0)
  209828. {
  209829. void* data = 0;
  209830. SafeArrayAccessData (sa, &data);
  209831. jassert (data != 0);
  209832. if (data != 0)
  209833. {
  209834. postData->copyTo (data, 0, postData->getSize());
  209835. SafeArrayUnaccessData (sa);
  209836. VARIANT postDataVar2;
  209837. VariantInit (&postDataVar2);
  209838. V_VT (&postDataVar2) = VT_ARRAY | VT_UI1;
  209839. V_ARRAY (&postDataVar2) = sa;
  209840. postDataVar = postDataVar2;
  209841. }
  209842. }
  209843. }
  209844. browser->Navigate ((BSTR) (const OLECHAR*) url,
  209845. &flags, &frame,
  209846. &postDataVar, &headersVar);
  209847. if (sa != 0)
  209848. SafeArrayDestroy (sa);
  209849. VariantClear (&flags);
  209850. VariantClear (&frame);
  209851. VariantClear (&postDataVar);
  209852. VariantClear (&headersVar);
  209853. }
  209854. }
  209855. IWebBrowser2* browser;
  209856. juce_UseDebuggingNewOperator
  209857. private:
  209858. IConnectionPoint* connectionPoint;
  209859. DWORD adviseCookie;
  209860. class EventHandler : public ComBaseClassHelper <IDispatch>,
  209861. public ComponentMovementWatcher
  209862. {
  209863. public:
  209864. EventHandler (WebBrowserComponent* owner_)
  209865. : ComponentMovementWatcher (owner_),
  209866. owner (owner_)
  209867. {
  209868. }
  209869. ~EventHandler()
  209870. {
  209871. }
  209872. HRESULT __stdcall GetTypeInfoCount (UINT __RPC_FAR*) { return E_NOTIMPL; }
  209873. HRESULT __stdcall GetTypeInfo (UINT, LCID, ITypeInfo __RPC_FAR *__RPC_FAR*) { return E_NOTIMPL; }
  209874. HRESULT __stdcall GetIDsOfNames (REFIID, LPOLESTR __RPC_FAR*, UINT, LCID, DISPID __RPC_FAR*) { return E_NOTIMPL; }
  209875. HRESULT __stdcall Invoke (DISPID dispIdMember, REFIID /*riid*/, LCID /*lcid*/,
  209876. WORD /*wFlags*/, DISPPARAMS __RPC_FAR* pDispParams,
  209877. VARIANT __RPC_FAR* /*pVarResult*/, EXCEPINFO __RPC_FAR* /*pExcepInfo*/,
  209878. UINT __RPC_FAR* /*puArgErr*/)
  209879. {
  209880. switch (dispIdMember)
  209881. {
  209882. case DISPID_BEFORENAVIGATE2:
  209883. {
  209884. VARIANT* const vurl = pDispParams->rgvarg[5].pvarVal;
  209885. String url;
  209886. if ((vurl->vt & VT_BYREF) != 0)
  209887. url = *vurl->pbstrVal;
  209888. else
  209889. url = vurl->bstrVal;
  209890. *pDispParams->rgvarg->pboolVal
  209891. = owner->pageAboutToLoad (url) ? VARIANT_FALSE
  209892. : VARIANT_TRUE;
  209893. return S_OK;
  209894. }
  209895. default:
  209896. break;
  209897. }
  209898. return E_NOTIMPL;
  209899. }
  209900. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/) {}
  209901. void componentPeerChanged() {}
  209902. void componentVisibilityChanged (Component&)
  209903. {
  209904. owner->visibilityChanged();
  209905. }
  209906. juce_UseDebuggingNewOperator
  209907. private:
  209908. WebBrowserComponent* const owner;
  209909. EventHandler (const EventHandler&);
  209910. EventHandler& operator= (const EventHandler&);
  209911. };
  209912. };
  209913. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  209914. : browser (0),
  209915. blankPageShown (false),
  209916. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  209917. {
  209918. setOpaque (true);
  209919. addAndMakeVisible (browser = new WebBrowserComponentInternal());
  209920. }
  209921. WebBrowserComponent::~WebBrowserComponent()
  209922. {
  209923. delete browser;
  209924. }
  209925. void WebBrowserComponent::goToURL (const String& url,
  209926. const StringArray* headers,
  209927. const MemoryBlock* postData)
  209928. {
  209929. lastURL = url;
  209930. lastHeaders.clear();
  209931. if (headers != 0)
  209932. lastHeaders = *headers;
  209933. lastPostData.setSize (0);
  209934. if (postData != 0)
  209935. lastPostData = *postData;
  209936. blankPageShown = false;
  209937. browser->goToURL (url, headers, postData);
  209938. }
  209939. void WebBrowserComponent::stop()
  209940. {
  209941. if (browser->browser != 0)
  209942. browser->browser->Stop();
  209943. }
  209944. void WebBrowserComponent::goBack()
  209945. {
  209946. lastURL = String::empty;
  209947. blankPageShown = false;
  209948. if (browser->browser != 0)
  209949. browser->browser->GoBack();
  209950. }
  209951. void WebBrowserComponent::goForward()
  209952. {
  209953. lastURL = String::empty;
  209954. if (browser->browser != 0)
  209955. browser->browser->GoForward();
  209956. }
  209957. void WebBrowserComponent::refresh()
  209958. {
  209959. if (browser->browser != 0)
  209960. browser->browser->Refresh();
  209961. }
  209962. void WebBrowserComponent::paint (Graphics& g)
  209963. {
  209964. if (browser->browser == 0)
  209965. g.fillAll (Colours::white);
  209966. }
  209967. void WebBrowserComponent::checkWindowAssociation()
  209968. {
  209969. if (isShowing())
  209970. {
  209971. if (browser->browser == 0 && getPeer() != 0)
  209972. {
  209973. browser->createBrowser();
  209974. reloadLastURL();
  209975. }
  209976. else
  209977. {
  209978. if (blankPageShown)
  209979. goBack();
  209980. }
  209981. }
  209982. else
  209983. {
  209984. if (browser != 0 && unloadPageWhenBrowserIsHidden && ! blankPageShown)
  209985. {
  209986. // when the component becomes invisible, some stuff like flash
  209987. // carries on playing audio, so we need to force it onto a blank
  209988. // page to avoid this..
  209989. blankPageShown = true;
  209990. browser->goToURL ("about:blank", 0, 0);
  209991. }
  209992. }
  209993. }
  209994. void WebBrowserComponent::reloadLastURL()
  209995. {
  209996. if (lastURL.isNotEmpty())
  209997. {
  209998. goToURL (lastURL, &lastHeaders, &lastPostData);
  209999. lastURL = String::empty;
  210000. }
  210001. }
  210002. void WebBrowserComponent::parentHierarchyChanged()
  210003. {
  210004. checkWindowAssociation();
  210005. }
  210006. void WebBrowserComponent::resized()
  210007. {
  210008. browser->setSize (getWidth(), getHeight());
  210009. }
  210010. void WebBrowserComponent::visibilityChanged()
  210011. {
  210012. checkWindowAssociation();
  210013. }
  210014. bool WebBrowserComponent::pageAboutToLoad (const String&)
  210015. {
  210016. return true;
  210017. }
  210018. #endif
  210019. /*** End of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  210020. /*** Start of inlined file: juce_win32_OpenGLComponent.cpp ***/
  210021. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  210022. // compiled on its own).
  210023. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  210024. #define WGL_EXT_FUNCTION_INIT(extType, extFunc) \
  210025. ((extFunc = (extType) wglGetProcAddress (#extFunc)) != 0)
  210026. typedef const char* (WINAPI* PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
  210027. typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
  210028. typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int* piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
  210029. typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC) (int interval);
  210030. typedef int (WINAPI * PFNWGLGETSWAPINTERVALEXTPROC) (void);
  210031. #define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
  210032. #define WGL_DRAW_TO_WINDOW_ARB 0x2001
  210033. #define WGL_ACCELERATION_ARB 0x2003
  210034. #define WGL_SWAP_METHOD_ARB 0x2007
  210035. #define WGL_SUPPORT_OPENGL_ARB 0x2010
  210036. #define WGL_PIXEL_TYPE_ARB 0x2013
  210037. #define WGL_DOUBLE_BUFFER_ARB 0x2011
  210038. #define WGL_COLOR_BITS_ARB 0x2014
  210039. #define WGL_RED_BITS_ARB 0x2015
  210040. #define WGL_GREEN_BITS_ARB 0x2017
  210041. #define WGL_BLUE_BITS_ARB 0x2019
  210042. #define WGL_ALPHA_BITS_ARB 0x201B
  210043. #define WGL_DEPTH_BITS_ARB 0x2022
  210044. #define WGL_STENCIL_BITS_ARB 0x2023
  210045. #define WGL_FULL_ACCELERATION_ARB 0x2027
  210046. #define WGL_ACCUM_RED_BITS_ARB 0x201E
  210047. #define WGL_ACCUM_GREEN_BITS_ARB 0x201F
  210048. #define WGL_ACCUM_BLUE_BITS_ARB 0x2020
  210049. #define WGL_ACCUM_ALPHA_BITS_ARB 0x2021
  210050. #define WGL_STEREO_ARB 0x2012
  210051. #define WGL_SAMPLE_BUFFERS_ARB 0x2041
  210052. #define WGL_SAMPLES_ARB 0x2042
  210053. #define WGL_TYPE_RGBA_ARB 0x202B
  210054. static void getWglExtensions (HDC dc, StringArray& result) throw()
  210055. {
  210056. PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB = 0;
  210057. if (WGL_EXT_FUNCTION_INIT (PFNWGLGETEXTENSIONSSTRINGARBPROC, wglGetExtensionsStringARB))
  210058. result.addTokens (String (wglGetExtensionsStringARB (dc)), false);
  210059. else
  210060. jassertfalse; // If this fails, it may be because you didn't activate the openGL context
  210061. }
  210062. class WindowedGLContext : public OpenGLContext
  210063. {
  210064. public:
  210065. WindowedGLContext (Component* const component_,
  210066. HGLRC contextToShareWith,
  210067. const OpenGLPixelFormat& pixelFormat)
  210068. : renderContext (0),
  210069. dc (0),
  210070. component (component_)
  210071. {
  210072. jassert (component != 0);
  210073. createNativeWindow();
  210074. // Use a default pixel format that should be supported everywhere
  210075. PIXELFORMATDESCRIPTOR pfd;
  210076. zerostruct (pfd);
  210077. pfd.nSize = sizeof (pfd);
  210078. pfd.nVersion = 1;
  210079. pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
  210080. pfd.iPixelType = PFD_TYPE_RGBA;
  210081. pfd.cColorBits = 24;
  210082. pfd.cDepthBits = 16;
  210083. const int format = ChoosePixelFormat (dc, &pfd);
  210084. if (format != 0)
  210085. SetPixelFormat (dc, format, &pfd);
  210086. renderContext = wglCreateContext (dc);
  210087. makeActive();
  210088. setPixelFormat (pixelFormat);
  210089. if (contextToShareWith != 0 && renderContext != 0)
  210090. wglShareLists (contextToShareWith, renderContext);
  210091. }
  210092. ~WindowedGLContext()
  210093. {
  210094. deleteContext();
  210095. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  210096. nativeWindow = 0;
  210097. }
  210098. void deleteContext()
  210099. {
  210100. makeInactive();
  210101. if (renderContext != 0)
  210102. {
  210103. wglDeleteContext (renderContext);
  210104. renderContext = 0;
  210105. }
  210106. }
  210107. bool makeActive() const throw()
  210108. {
  210109. jassert (renderContext != 0);
  210110. return wglMakeCurrent (dc, renderContext) != 0;
  210111. }
  210112. bool makeInactive() const throw()
  210113. {
  210114. return (! isActive()) || (wglMakeCurrent (0, 0) != 0);
  210115. }
  210116. bool isActive() const throw()
  210117. {
  210118. return wglGetCurrentContext() == renderContext;
  210119. }
  210120. const OpenGLPixelFormat getPixelFormat() const
  210121. {
  210122. OpenGLPixelFormat pf;
  210123. makeActive();
  210124. StringArray availableExtensions;
  210125. getWglExtensions (dc, availableExtensions);
  210126. fillInPixelFormatDetails (GetPixelFormat (dc), pf, availableExtensions);
  210127. return pf;
  210128. }
  210129. void* getRawContext() const throw()
  210130. {
  210131. return renderContext;
  210132. }
  210133. bool setPixelFormat (const OpenGLPixelFormat& pixelFormat)
  210134. {
  210135. makeActive();
  210136. PIXELFORMATDESCRIPTOR pfd;
  210137. zerostruct (pfd);
  210138. pfd.nSize = sizeof (pfd);
  210139. pfd.nVersion = 1;
  210140. pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER;
  210141. pfd.iPixelType = PFD_TYPE_RGBA;
  210142. pfd.iLayerType = PFD_MAIN_PLANE;
  210143. pfd.cColorBits = (BYTE) (pixelFormat.redBits + pixelFormat.greenBits + pixelFormat.blueBits);
  210144. pfd.cRedBits = (BYTE) pixelFormat.redBits;
  210145. pfd.cGreenBits = (BYTE) pixelFormat.greenBits;
  210146. pfd.cBlueBits = (BYTE) pixelFormat.blueBits;
  210147. pfd.cAlphaBits = (BYTE) pixelFormat.alphaBits;
  210148. pfd.cDepthBits = (BYTE) pixelFormat.depthBufferBits;
  210149. pfd.cStencilBits = (BYTE) pixelFormat.stencilBufferBits;
  210150. pfd.cAccumBits = (BYTE) (pixelFormat.accumulationBufferRedBits + pixelFormat.accumulationBufferGreenBits
  210151. + pixelFormat.accumulationBufferBlueBits + pixelFormat.accumulationBufferAlphaBits);
  210152. pfd.cAccumRedBits = (BYTE) pixelFormat.accumulationBufferRedBits;
  210153. pfd.cAccumGreenBits = (BYTE) pixelFormat.accumulationBufferGreenBits;
  210154. pfd.cAccumBlueBits = (BYTE) pixelFormat.accumulationBufferBlueBits;
  210155. pfd.cAccumAlphaBits = (BYTE) pixelFormat.accumulationBufferAlphaBits;
  210156. int format = 0;
  210157. PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = 0;
  210158. StringArray availableExtensions;
  210159. getWglExtensions (dc, availableExtensions);
  210160. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  210161. && WGL_EXT_FUNCTION_INIT (PFNWGLCHOOSEPIXELFORMATARBPROC, wglChoosePixelFormatARB))
  210162. {
  210163. int attributes[64];
  210164. int n = 0;
  210165. attributes[n++] = WGL_DRAW_TO_WINDOW_ARB;
  210166. attributes[n++] = GL_TRUE;
  210167. attributes[n++] = WGL_SUPPORT_OPENGL_ARB;
  210168. attributes[n++] = GL_TRUE;
  210169. attributes[n++] = WGL_ACCELERATION_ARB;
  210170. attributes[n++] = WGL_FULL_ACCELERATION_ARB;
  210171. attributes[n++] = WGL_DOUBLE_BUFFER_ARB;
  210172. attributes[n++] = GL_TRUE;
  210173. attributes[n++] = WGL_PIXEL_TYPE_ARB;
  210174. attributes[n++] = WGL_TYPE_RGBA_ARB;
  210175. attributes[n++] = WGL_COLOR_BITS_ARB;
  210176. attributes[n++] = pfd.cColorBits;
  210177. attributes[n++] = WGL_RED_BITS_ARB;
  210178. attributes[n++] = pixelFormat.redBits;
  210179. attributes[n++] = WGL_GREEN_BITS_ARB;
  210180. attributes[n++] = pixelFormat.greenBits;
  210181. attributes[n++] = WGL_BLUE_BITS_ARB;
  210182. attributes[n++] = pixelFormat.blueBits;
  210183. attributes[n++] = WGL_ALPHA_BITS_ARB;
  210184. attributes[n++] = pixelFormat.alphaBits;
  210185. attributes[n++] = WGL_DEPTH_BITS_ARB;
  210186. attributes[n++] = pixelFormat.depthBufferBits;
  210187. if (pixelFormat.stencilBufferBits > 0)
  210188. {
  210189. attributes[n++] = WGL_STENCIL_BITS_ARB;
  210190. attributes[n++] = pixelFormat.stencilBufferBits;
  210191. }
  210192. attributes[n++] = WGL_ACCUM_RED_BITS_ARB;
  210193. attributes[n++] = pixelFormat.accumulationBufferRedBits;
  210194. attributes[n++] = WGL_ACCUM_GREEN_BITS_ARB;
  210195. attributes[n++] = pixelFormat.accumulationBufferGreenBits;
  210196. attributes[n++] = WGL_ACCUM_BLUE_BITS_ARB;
  210197. attributes[n++] = pixelFormat.accumulationBufferBlueBits;
  210198. attributes[n++] = WGL_ACCUM_ALPHA_BITS_ARB;
  210199. attributes[n++] = pixelFormat.accumulationBufferAlphaBits;
  210200. if (availableExtensions.contains ("WGL_ARB_multisample")
  210201. && pixelFormat.fullSceneAntiAliasingNumSamples > 0)
  210202. {
  210203. attributes[n++] = WGL_SAMPLE_BUFFERS_ARB;
  210204. attributes[n++] = 1;
  210205. attributes[n++] = WGL_SAMPLES_ARB;
  210206. attributes[n++] = pixelFormat.fullSceneAntiAliasingNumSamples;
  210207. }
  210208. attributes[n++] = 0;
  210209. UINT formatsCount;
  210210. const BOOL ok = wglChoosePixelFormatARB (dc, attributes, 0, 1, &format, &formatsCount);
  210211. (void) ok;
  210212. jassert (ok);
  210213. }
  210214. else
  210215. {
  210216. format = ChoosePixelFormat (dc, &pfd);
  210217. }
  210218. if (format != 0)
  210219. {
  210220. makeInactive();
  210221. // win32 can't change the pixel format of a window, so need to delete the
  210222. // old one and create a new one..
  210223. jassert (nativeWindow != 0);
  210224. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  210225. nativeWindow = 0;
  210226. createNativeWindow();
  210227. if (SetPixelFormat (dc, format, &pfd))
  210228. {
  210229. wglDeleteContext (renderContext);
  210230. renderContext = wglCreateContext (dc);
  210231. jassert (renderContext != 0);
  210232. return renderContext != 0;
  210233. }
  210234. }
  210235. return false;
  210236. }
  210237. void updateWindowPosition (int x, int y, int w, int h, int)
  210238. {
  210239. SetWindowPos ((HWND) nativeWindow->getNativeHandle(), 0,
  210240. x, y, w, h,
  210241. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  210242. }
  210243. void repaint()
  210244. {
  210245. nativeWindow->repaint (nativeWindow->getBounds().withPosition (Point<int>()));
  210246. }
  210247. void swapBuffers()
  210248. {
  210249. SwapBuffers (dc);
  210250. }
  210251. bool setSwapInterval (int numFramesPerSwap)
  210252. {
  210253. makeActive();
  210254. StringArray availableExtensions;
  210255. getWglExtensions (dc, availableExtensions);
  210256. PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = 0;
  210257. return availableExtensions.contains ("WGL_EXT_swap_control")
  210258. && WGL_EXT_FUNCTION_INIT (PFNWGLSWAPINTERVALEXTPROC, wglSwapIntervalEXT)
  210259. && wglSwapIntervalEXT (numFramesPerSwap) != FALSE;
  210260. }
  210261. int getSwapInterval() const
  210262. {
  210263. makeActive();
  210264. StringArray availableExtensions;
  210265. getWglExtensions (dc, availableExtensions);
  210266. PFNWGLGETSWAPINTERVALEXTPROC wglGetSwapIntervalEXT = 0;
  210267. if (availableExtensions.contains ("WGL_EXT_swap_control")
  210268. && WGL_EXT_FUNCTION_INIT (PFNWGLGETSWAPINTERVALEXTPROC, wglGetSwapIntervalEXT))
  210269. return wglGetSwapIntervalEXT();
  210270. return 0;
  210271. }
  210272. void findAlternativeOpenGLPixelFormats (OwnedArray <OpenGLPixelFormat>& results)
  210273. {
  210274. jassert (isActive());
  210275. StringArray availableExtensions;
  210276. getWglExtensions (dc, availableExtensions);
  210277. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  210278. int numTypes = 0;
  210279. if (availableExtensions.contains("WGL_ARB_pixel_format")
  210280. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  210281. {
  210282. int attributes = WGL_NUMBER_PIXEL_FORMATS_ARB;
  210283. if (! wglGetPixelFormatAttribivARB (dc, 1, 0, 1, &attributes, &numTypes))
  210284. jassertfalse;
  210285. }
  210286. else
  210287. {
  210288. numTypes = DescribePixelFormat (dc, 0, 0, 0);
  210289. }
  210290. OpenGLPixelFormat pf;
  210291. for (int i = 0; i < numTypes; ++i)
  210292. {
  210293. if (fillInPixelFormatDetails (i + 1, pf, availableExtensions))
  210294. {
  210295. bool alreadyListed = false;
  210296. for (int j = results.size(); --j >= 0;)
  210297. if (pf == *results.getUnchecked(j))
  210298. alreadyListed = true;
  210299. if (! alreadyListed)
  210300. results.add (new OpenGLPixelFormat (pf));
  210301. }
  210302. }
  210303. }
  210304. void* getNativeWindowHandle() const
  210305. {
  210306. return nativeWindow != 0 ? nativeWindow->getNativeHandle() : 0;
  210307. }
  210308. juce_UseDebuggingNewOperator
  210309. HGLRC renderContext;
  210310. private:
  210311. ScopedPointer<Win32ComponentPeer> nativeWindow;
  210312. Component* const component;
  210313. HDC dc;
  210314. void createNativeWindow()
  210315. {
  210316. Win32ComponentPeer* topLevelPeer = dynamic_cast <Win32ComponentPeer*> (component->getTopLevelComponent()->getPeer());
  210317. nativeWindow = new Win32ComponentPeer (component, ComponentPeer::windowIgnoresMouseClicks,
  210318. topLevelPeer == 0 ? 0 : (HWND) topLevelPeer->getNativeHandle());
  210319. nativeWindow->dontRepaint = true;
  210320. nativeWindow->setVisible (true);
  210321. dc = GetDC ((HWND) nativeWindow->getNativeHandle());
  210322. }
  210323. bool fillInPixelFormatDetails (const int pixelFormatIndex,
  210324. OpenGLPixelFormat& result,
  210325. const StringArray& availableExtensions) const throw()
  210326. {
  210327. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  210328. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  210329. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  210330. {
  210331. int attributes[32];
  210332. int numAttributes = 0;
  210333. attributes[numAttributes++] = WGL_DRAW_TO_WINDOW_ARB;
  210334. attributes[numAttributes++] = WGL_SUPPORT_OPENGL_ARB;
  210335. attributes[numAttributes++] = WGL_ACCELERATION_ARB;
  210336. attributes[numAttributes++] = WGL_DOUBLE_BUFFER_ARB;
  210337. attributes[numAttributes++] = WGL_PIXEL_TYPE_ARB;
  210338. attributes[numAttributes++] = WGL_RED_BITS_ARB;
  210339. attributes[numAttributes++] = WGL_GREEN_BITS_ARB;
  210340. attributes[numAttributes++] = WGL_BLUE_BITS_ARB;
  210341. attributes[numAttributes++] = WGL_ALPHA_BITS_ARB;
  210342. attributes[numAttributes++] = WGL_DEPTH_BITS_ARB;
  210343. attributes[numAttributes++] = WGL_STENCIL_BITS_ARB;
  210344. attributes[numAttributes++] = WGL_ACCUM_RED_BITS_ARB;
  210345. attributes[numAttributes++] = WGL_ACCUM_GREEN_BITS_ARB;
  210346. attributes[numAttributes++] = WGL_ACCUM_BLUE_BITS_ARB;
  210347. attributes[numAttributes++] = WGL_ACCUM_ALPHA_BITS_ARB;
  210348. if (availableExtensions.contains ("WGL_ARB_multisample"))
  210349. attributes[numAttributes++] = WGL_SAMPLES_ARB;
  210350. int values[32];
  210351. zeromem (values, sizeof (values));
  210352. if (wglGetPixelFormatAttribivARB (dc, pixelFormatIndex, 0, numAttributes, attributes, values))
  210353. {
  210354. int n = 0;
  210355. bool isValidFormat = (values[n++] == GL_TRUE); // WGL_DRAW_TO_WINDOW_ARB
  210356. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_SUPPORT_OPENGL_ARB
  210357. isValidFormat = (values[n++] == WGL_FULL_ACCELERATION_ARB) && isValidFormat; // WGL_ACCELERATION_ARB
  210358. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_DOUBLE_BUFFER_ARB:
  210359. isValidFormat = (values[n++] == WGL_TYPE_RGBA_ARB) && isValidFormat; // WGL_PIXEL_TYPE_ARB
  210360. result.redBits = values[n++]; // WGL_RED_BITS_ARB
  210361. result.greenBits = values[n++]; // WGL_GREEN_BITS_ARB
  210362. result.blueBits = values[n++]; // WGL_BLUE_BITS_ARB
  210363. result.alphaBits = values[n++]; // WGL_ALPHA_BITS_ARB
  210364. result.depthBufferBits = values[n++]; // WGL_DEPTH_BITS_ARB
  210365. result.stencilBufferBits = values[n++]; // WGL_STENCIL_BITS_ARB
  210366. result.accumulationBufferRedBits = values[n++]; // WGL_ACCUM_RED_BITS_ARB
  210367. result.accumulationBufferGreenBits = values[n++]; // WGL_ACCUM_GREEN_BITS_ARB
  210368. result.accumulationBufferBlueBits = values[n++]; // WGL_ACCUM_BLUE_BITS_ARB
  210369. result.accumulationBufferAlphaBits = values[n++]; // WGL_ACCUM_ALPHA_BITS_ARB
  210370. result.fullSceneAntiAliasingNumSamples = (uint8) values[n++]; // WGL_SAMPLES_ARB
  210371. return isValidFormat;
  210372. }
  210373. else
  210374. {
  210375. jassertfalse;
  210376. }
  210377. }
  210378. else
  210379. {
  210380. PIXELFORMATDESCRIPTOR pfd;
  210381. if (DescribePixelFormat (dc, pixelFormatIndex, sizeof (pfd), &pfd))
  210382. {
  210383. result.redBits = pfd.cRedBits;
  210384. result.greenBits = pfd.cGreenBits;
  210385. result.blueBits = pfd.cBlueBits;
  210386. result.alphaBits = pfd.cAlphaBits;
  210387. result.depthBufferBits = pfd.cDepthBits;
  210388. result.stencilBufferBits = pfd.cStencilBits;
  210389. result.accumulationBufferRedBits = pfd.cAccumRedBits;
  210390. result.accumulationBufferGreenBits = pfd.cAccumGreenBits;
  210391. result.accumulationBufferBlueBits = pfd.cAccumBlueBits;
  210392. result.accumulationBufferAlphaBits = pfd.cAccumAlphaBits;
  210393. result.fullSceneAntiAliasingNumSamples = 0;
  210394. return true;
  210395. }
  210396. else
  210397. {
  210398. jassertfalse;
  210399. }
  210400. }
  210401. return false;
  210402. }
  210403. WindowedGLContext (const WindowedGLContext&);
  210404. WindowedGLContext& operator= (const WindowedGLContext&);
  210405. };
  210406. OpenGLContext* OpenGLComponent::createContext()
  210407. {
  210408. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this,
  210409. contextToShareListsWith != 0 ? (HGLRC) contextToShareListsWith->getRawContext() : 0,
  210410. preferredPixelFormat));
  210411. return (c->renderContext != 0) ? c.release() : 0;
  210412. }
  210413. void* OpenGLComponent::getNativeWindowHandle() const
  210414. {
  210415. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle() : 0;
  210416. }
  210417. void juce_glViewport (const int w, const int h)
  210418. {
  210419. glViewport (0, 0, w, h);
  210420. }
  210421. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  210422. OwnedArray <OpenGLPixelFormat>& results)
  210423. {
  210424. Component tempComp;
  210425. {
  210426. WindowedGLContext wc (component, 0, OpenGLPixelFormat (8, 8, 16, 0));
  210427. wc.makeActive();
  210428. wc.findAlternativeOpenGLPixelFormats (results);
  210429. }
  210430. }
  210431. #endif
  210432. /*** End of inlined file: juce_win32_OpenGLComponent.cpp ***/
  210433. /*** Start of inlined file: juce_win32_AudioCDReader.cpp ***/
  210434. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  210435. // compiled on its own).
  210436. #if JUCE_INCLUDED_FILE
  210437. #if JUCE_USE_CDREADER
  210438. namespace CDReaderHelpers
  210439. {
  210440. //***************************************************************************
  210441. // %%% TARGET STATUS VALUES %%%
  210442. //***************************************************************************
  210443. #define STATUS_GOOD 0x00 // Status Good
  210444. #define STATUS_CHKCOND 0x02 // Check Condition
  210445. #define STATUS_CONDMET 0x04 // Condition Met
  210446. #define STATUS_BUSY 0x08 // Busy
  210447. #define STATUS_INTERM 0x10 // Intermediate
  210448. #define STATUS_INTCDMET 0x14 // Intermediate-condition met
  210449. #define STATUS_RESCONF 0x18 // Reservation conflict
  210450. #define STATUS_COMTERM 0x22 // Command Terminated
  210451. #define STATUS_QFULL 0x28 // Queue full
  210452. //***************************************************************************
  210453. // %%% SCSI MISCELLANEOUS EQUATES %%%
  210454. //***************************************************************************
  210455. #define MAXLUN 7 // Maximum Logical Unit Id
  210456. #define MAXTARG 7 // Maximum Target Id
  210457. #define MAX_SCSI_LUNS 64 // Maximum Number of SCSI LUNs
  210458. #define MAX_NUM_HA 8 // Maximum Number of SCSI HA's
  210459. //***************************************************************************
  210460. // %%% Commands for all Device Types %%%
  210461. //***************************************************************************
  210462. #define SCSI_CHANGE_DEF 0x40 // Change Definition (Optional)
  210463. #define SCSI_COMPARE 0x39 // Compare (O)
  210464. #define SCSI_COPY 0x18 // Copy (O)
  210465. #define SCSI_COP_VERIFY 0x3A // Copy and Verify (O)
  210466. #define SCSI_INQUIRY 0x12 // Inquiry (MANDATORY)
  210467. #define SCSI_LOG_SELECT 0x4C // Log Select (O)
  210468. #define SCSI_LOG_SENSE 0x4D // Log Sense (O)
  210469. #define SCSI_MODE_SEL6 0x15 // Mode Select 6-byte (Device Specific)
  210470. #define SCSI_MODE_SEL10 0x55 // Mode Select 10-byte (Device Specific)
  210471. #define SCSI_MODE_SEN6 0x1A // Mode Sense 6-byte (Device Specific)
  210472. #define SCSI_MODE_SEN10 0x5A // Mode Sense 10-byte (Device Specific)
  210473. #define SCSI_READ_BUFF 0x3C // Read Buffer (O)
  210474. #define SCSI_REQ_SENSE 0x03 // Request Sense (MANDATORY)
  210475. #define SCSI_SEND_DIAG 0x1D // Send Diagnostic (O)
  210476. #define SCSI_TST_U_RDY 0x00 // Test Unit Ready (MANDATORY)
  210477. #define SCSI_WRITE_BUFF 0x3B // Write Buffer (O)
  210478. //***************************************************************************
  210479. // %%% Commands Unique to Direct Access Devices %%%
  210480. //***************************************************************************
  210481. #define SCSI_COMPARE 0x39 // Compare (O)
  210482. #define SCSI_FORMAT 0x04 // Format Unit (MANDATORY)
  210483. #define SCSI_LCK_UN_CAC 0x36 // Lock Unlock Cache (O)
  210484. #define SCSI_PREFETCH 0x34 // Prefetch (O)
  210485. #define SCSI_MED_REMOVL 0x1E // Prevent/Allow medium Removal (O)
  210486. #define SCSI_READ6 0x08 // Read 6-byte (MANDATORY)
  210487. #define SCSI_READ10 0x28 // Read 10-byte (MANDATORY)
  210488. #define SCSI_RD_CAPAC 0x25 // Read Capacity (MANDATORY)
  210489. #define SCSI_RD_DEFECT 0x37 // Read Defect Data (O)
  210490. #define SCSI_READ_LONG 0x3E // Read Long (O)
  210491. #define SCSI_REASS_BLK 0x07 // Reassign Blocks (O)
  210492. #define SCSI_RCV_DIAG 0x1C // Receive Diagnostic Results (O)
  210493. #define SCSI_RELEASE 0x17 // Release Unit (MANDATORY)
  210494. #define SCSI_REZERO 0x01 // Rezero Unit (O)
  210495. #define SCSI_SRCH_DAT_E 0x31 // Search Data Equal (O)
  210496. #define SCSI_SRCH_DAT_H 0x30 // Search Data High (O)
  210497. #define SCSI_SRCH_DAT_L 0x32 // Search Data Low (O)
  210498. #define SCSI_SEEK6 0x0B // Seek 6-Byte (O)
  210499. #define SCSI_SEEK10 0x2B // Seek 10-Byte (O)
  210500. #define SCSI_SEND_DIAG 0x1D // Send Diagnostics (MANDATORY)
  210501. #define SCSI_SET_LIMIT 0x33 // Set Limits (O)
  210502. #define SCSI_START_STP 0x1B // Start/Stop Unit (O)
  210503. #define SCSI_SYNC_CACHE 0x35 // Synchronize Cache (O)
  210504. #define SCSI_VERIFY 0x2F // Verify (O)
  210505. #define SCSI_WRITE6 0x0A // Write 6-Byte (MANDATORY)
  210506. #define SCSI_WRITE10 0x2A // Write 10-Byte (MANDATORY)
  210507. #define SCSI_WRT_VERIFY 0x2E // Write and Verify (O)
  210508. #define SCSI_WRITE_LONG 0x3F // Write Long (O)
  210509. #define SCSI_WRITE_SAME 0x41 // Write Same (O)
  210510. //***************************************************************************
  210511. // %%% Commands Unique to Sequential Access Devices %%%
  210512. //***************************************************************************
  210513. #define SCSI_ERASE 0x19 // Erase (MANDATORY)
  210514. #define SCSI_LOAD_UN 0x1b // Load/Unload (O)
  210515. #define SCSI_LOCATE 0x2B // Locate (O)
  210516. #define SCSI_RD_BLK_LIM 0x05 // Read Block Limits (MANDATORY)
  210517. #define SCSI_READ_POS 0x34 // Read Position (O)
  210518. #define SCSI_READ_REV 0x0F // Read Reverse (O)
  210519. #define SCSI_REC_BF_DAT 0x14 // Recover Buffer Data (O)
  210520. #define SCSI_RESERVE 0x16 // Reserve Unit (MANDATORY)
  210521. #define SCSI_REWIND 0x01 // Rewind (MANDATORY)
  210522. #define SCSI_SPACE 0x11 // Space (MANDATORY)
  210523. #define SCSI_VERIFY_T 0x13 // Verify (Tape) (O)
  210524. #define SCSI_WRT_FILE 0x10 // Write Filemarks (MANDATORY)
  210525. //***************************************************************************
  210526. // %%% Commands Unique to Printer Devices %%%
  210527. //***************************************************************************
  210528. #define SCSI_PRINT 0x0A // Print (MANDATORY)
  210529. #define SCSI_SLEW_PNT 0x0B // Slew and Print (O)
  210530. #define SCSI_STOP_PNT 0x1B // Stop Print (O)
  210531. #define SCSI_SYNC_BUFF 0x10 // Synchronize Buffer (O)
  210532. //***************************************************************************
  210533. // %%% Commands Unique to Processor Devices %%%
  210534. //***************************************************************************
  210535. #define SCSI_RECEIVE 0x08 // Receive (O)
  210536. #define SCSI_SEND 0x0A // Send (O)
  210537. //***************************************************************************
  210538. // %%% Commands Unique to Write-Once Devices %%%
  210539. //***************************************************************************
  210540. #define SCSI_MEDIUM_SCN 0x38 // Medium Scan (O)
  210541. #define SCSI_SRCHDATE10 0x31 // Search Data Equal 10-Byte (O)
  210542. #define SCSI_SRCHDATE12 0xB1 // Search Data Equal 12-Byte (O)
  210543. #define SCSI_SRCHDATH10 0x30 // Search Data High 10-Byte (O)
  210544. #define SCSI_SRCHDATH12 0xB0 // Search Data High 12-Byte (O)
  210545. #define SCSI_SRCHDATL10 0x32 // Search Data Low 10-Byte (O)
  210546. #define SCSI_SRCHDATL12 0xB2 // Search Data Low 12-Byte (O)
  210547. #define SCSI_SET_LIM_10 0x33 // Set Limits 10-Byte (O)
  210548. #define SCSI_SET_LIM_12 0xB3 // Set Limits 10-Byte (O)
  210549. #define SCSI_VERIFY10 0x2F // Verify 10-Byte (O)
  210550. #define SCSI_VERIFY12 0xAF // Verify 12-Byte (O)
  210551. #define SCSI_WRITE12 0xAA // Write 12-Byte (O)
  210552. #define SCSI_WRT_VER10 0x2E // Write and Verify 10-Byte (O)
  210553. #define SCSI_WRT_VER12 0xAE // Write and Verify 12-Byte (O)
  210554. //***************************************************************************
  210555. // %%% Commands Unique to CD-ROM Devices %%%
  210556. //***************************************************************************
  210557. #define SCSI_PLAYAUD_10 0x45 // Play Audio 10-Byte (O)
  210558. #define SCSI_PLAYAUD_12 0xA5 // Play Audio 12-Byte 12-Byte (O)
  210559. #define SCSI_PLAYAUDMSF 0x47 // Play Audio MSF (O)
  210560. #define SCSI_PLAYA_TKIN 0x48 // Play Audio Track/Index (O)
  210561. #define SCSI_PLYTKREL10 0x49 // Play Track Relative 10-Byte (O)
  210562. #define SCSI_PLYTKREL12 0xA9 // Play Track Relative 12-Byte (O)
  210563. #define SCSI_READCDCAP 0x25 // Read CD-ROM Capacity (MANDATORY)
  210564. #define SCSI_READHEADER 0x44 // Read Header (O)
  210565. #define SCSI_SUBCHANNEL 0x42 // Read Subchannel (O)
  210566. #define SCSI_READ_TOC 0x43 // Read TOC (O)
  210567. //***************************************************************************
  210568. // %%% Commands Unique to Scanner Devices %%%
  210569. //***************************************************************************
  210570. #define SCSI_GETDBSTAT 0x34 // Get Data Buffer Status (O)
  210571. #define SCSI_GETWINDOW 0x25 // Get Window (O)
  210572. #define SCSI_OBJECTPOS 0x31 // Object Postion (O)
  210573. #define SCSI_SCAN 0x1B // Scan (O)
  210574. #define SCSI_SETWINDOW 0x24 // Set Window (MANDATORY)
  210575. //***************************************************************************
  210576. // %%% Commands Unique to Optical Memory Devices %%%
  210577. //***************************************************************************
  210578. #define SCSI_UpdateBlk 0x3D // Update Block (O)
  210579. //***************************************************************************
  210580. // %%% Commands Unique to Medium Changer Devices %%%
  210581. //***************************************************************************
  210582. #define SCSI_EXCHMEDIUM 0xA6 // Exchange Medium (O)
  210583. #define SCSI_INITELSTAT 0x07 // Initialize Element Status (O)
  210584. #define SCSI_POSTOELEM 0x2B // Position to Element (O)
  210585. #define SCSI_REQ_VE_ADD 0xB5 // Request Volume Element Address (O)
  210586. #define SCSI_SENDVOLTAG 0xB6 // Send Volume Tag (O)
  210587. //***************************************************************************
  210588. // %%% Commands Unique to Communication Devices %%%
  210589. //***************************************************************************
  210590. #define SCSI_GET_MSG_6 0x08 // Get Message 6-Byte (MANDATORY)
  210591. #define SCSI_GET_MSG_10 0x28 // Get Message 10-Byte (O)
  210592. #define SCSI_GET_MSG_12 0xA8 // Get Message 12-Byte (O)
  210593. #define SCSI_SND_MSG_6 0x0A // Send Message 6-Byte (MANDATORY)
  210594. #define SCSI_SND_MSG_10 0x2A // Send Message 10-Byte (O)
  210595. #define SCSI_SND_MSG_12 0xAA // Send Message 12-Byte (O)
  210596. //***************************************************************************
  210597. // %%% Request Sense Data Format %%%
  210598. //***************************************************************************
  210599. typedef struct {
  210600. BYTE ErrorCode; // Error Code (70H or 71H)
  210601. BYTE SegmentNum; // Number of current segment descriptor
  210602. BYTE SenseKey; // Sense Key(See bit definitions too)
  210603. BYTE InfoByte0; // Information MSB
  210604. BYTE InfoByte1; // Information MID
  210605. BYTE InfoByte2; // Information MID
  210606. BYTE InfoByte3; // Information LSB
  210607. BYTE AddSenLen; // Additional Sense Length
  210608. BYTE ComSpecInf0; // Command Specific Information MSB
  210609. BYTE ComSpecInf1; // Command Specific Information MID
  210610. BYTE ComSpecInf2; // Command Specific Information MID
  210611. BYTE ComSpecInf3; // Command Specific Information LSB
  210612. BYTE AddSenseCode; // Additional Sense Code
  210613. BYTE AddSenQual; // Additional Sense Code Qualifier
  210614. BYTE FieldRepUCode; // Field Replaceable Unit Code
  210615. BYTE SenKeySpec15; // Sense Key Specific 15th byte
  210616. BYTE SenKeySpec16; // Sense Key Specific 16th byte
  210617. BYTE SenKeySpec17; // Sense Key Specific 17th byte
  210618. BYTE AddSenseBytes; // Additional Sense Bytes
  210619. } SENSE_DATA_FMT;
  210620. //***************************************************************************
  210621. // %%% REQUEST SENSE ERROR CODE %%%
  210622. //***************************************************************************
  210623. #define SERROR_CURRENT 0x70 // Current Errors
  210624. #define SERROR_DEFERED 0x71 // Deferred Errors
  210625. //***************************************************************************
  210626. // %%% REQUEST SENSE BIT DEFINITIONS %%%
  210627. //***************************************************************************
  210628. #define SENSE_VALID 0x80 // Byte 0 Bit 7
  210629. #define SENSE_FILEMRK 0x80 // Byte 2 Bit 7
  210630. #define SENSE_EOM 0x40 // Byte 2 Bit 6
  210631. #define SENSE_ILI 0x20 // Byte 2 Bit 5
  210632. //***************************************************************************
  210633. // %%% REQUEST SENSE SENSE KEY DEFINITIONS %%%
  210634. //***************************************************************************
  210635. #define KEY_NOSENSE 0x00 // No Sense
  210636. #define KEY_RECERROR 0x01 // Recovered Error
  210637. #define KEY_NOTREADY 0x02 // Not Ready
  210638. #define KEY_MEDIUMERR 0x03 // Medium Error
  210639. #define KEY_HARDERROR 0x04 // Hardware Error
  210640. #define KEY_ILLGLREQ 0x05 // Illegal Request
  210641. #define KEY_UNITATT 0x06 // Unit Attention
  210642. #define KEY_DATAPROT 0x07 // Data Protect
  210643. #define KEY_BLANKCHK 0x08 // Blank Check
  210644. #define KEY_VENDSPEC 0x09 // Vendor Specific
  210645. #define KEY_COPYABORT 0x0A // Copy Abort
  210646. #define KEY_EQUAL 0x0C // Equal (Search)
  210647. #define KEY_VOLOVRFLW 0x0D // Volume Overflow
  210648. #define KEY_MISCOMP 0x0E // Miscompare (Search)
  210649. #define KEY_RESERVED 0x0F // Reserved
  210650. //***************************************************************************
  210651. // %%% PERIPHERAL DEVICE TYPE DEFINITIONS %%%
  210652. //***************************************************************************
  210653. #define DTYPE_DASD 0x00 // Disk Device
  210654. #define DTYPE_SEQD 0x01 // Tape Device
  210655. #define DTYPE_PRNT 0x02 // Printer
  210656. #define DTYPE_PROC 0x03 // Processor
  210657. #define DTYPE_WORM 0x04 // Write-once read-multiple
  210658. #define DTYPE_CROM 0x05 // CD-ROM device
  210659. #define DTYPE_SCAN 0x06 // Scanner device
  210660. #define DTYPE_OPTI 0x07 // Optical memory device
  210661. #define DTYPE_JUKE 0x08 // Medium Changer device
  210662. #define DTYPE_COMM 0x09 // Communications device
  210663. #define DTYPE_RESL 0x0A // Reserved (low)
  210664. #define DTYPE_RESH 0x1E // Reserved (high)
  210665. #define DTYPE_UNKNOWN 0x1F // Unknown or no device type
  210666. //***************************************************************************
  210667. // %%% ANSI APPROVED VERSION DEFINITIONS %%%
  210668. //***************************************************************************
  210669. #define ANSI_MAYBE 0x0 // Device may or may not be ANSI approved stand
  210670. #define ANSI_SCSI1 0x1 // Device complies to ANSI X3.131-1986 (SCSI-1)
  210671. #define ANSI_SCSI2 0x2 // Device complies to SCSI-2
  210672. #define ANSI_RESLO 0x3 // Reserved (low)
  210673. #define ANSI_RESHI 0x7 // Reserved (high)
  210674. typedef struct
  210675. {
  210676. USHORT Length;
  210677. UCHAR ScsiStatus;
  210678. UCHAR PathId;
  210679. UCHAR TargetId;
  210680. UCHAR Lun;
  210681. UCHAR CdbLength;
  210682. UCHAR SenseInfoLength;
  210683. UCHAR DataIn;
  210684. ULONG DataTransferLength;
  210685. ULONG TimeOutValue;
  210686. ULONG DataBufferOffset;
  210687. ULONG SenseInfoOffset;
  210688. UCHAR Cdb[16];
  210689. } SCSI_PASS_THROUGH, *PSCSI_PASS_THROUGH;
  210690. typedef struct
  210691. {
  210692. USHORT Length;
  210693. UCHAR ScsiStatus;
  210694. UCHAR PathId;
  210695. UCHAR TargetId;
  210696. UCHAR Lun;
  210697. UCHAR CdbLength;
  210698. UCHAR SenseInfoLength;
  210699. UCHAR DataIn;
  210700. ULONG DataTransferLength;
  210701. ULONG TimeOutValue;
  210702. PVOID DataBuffer;
  210703. ULONG SenseInfoOffset;
  210704. UCHAR Cdb[16];
  210705. } SCSI_PASS_THROUGH_DIRECT, *PSCSI_PASS_THROUGH_DIRECT;
  210706. typedef struct
  210707. {
  210708. SCSI_PASS_THROUGH_DIRECT spt;
  210709. ULONG Filler;
  210710. UCHAR ucSenseBuf[32];
  210711. } SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, *PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER;
  210712. typedef struct
  210713. {
  210714. ULONG Length;
  210715. UCHAR PortNumber;
  210716. UCHAR PathId;
  210717. UCHAR TargetId;
  210718. UCHAR Lun;
  210719. } SCSI_ADDRESS, *PSCSI_ADDRESS;
  210720. #define METHOD_BUFFERED 0
  210721. #define METHOD_IN_DIRECT 1
  210722. #define METHOD_OUT_DIRECT 2
  210723. #define METHOD_NEITHER 3
  210724. #define FILE_ANY_ACCESS 0
  210725. #ifndef FILE_READ_ACCESS
  210726. #define FILE_READ_ACCESS (0x0001)
  210727. #endif
  210728. #ifndef FILE_WRITE_ACCESS
  210729. #define FILE_WRITE_ACCESS (0x0002)
  210730. #endif
  210731. #define IOCTL_SCSI_BASE 0x00000004
  210732. #define SCSI_IOCTL_DATA_OUT 0
  210733. #define SCSI_IOCTL_DATA_IN 1
  210734. #define SCSI_IOCTL_DATA_UNSPECIFIED 2
  210735. #define CTL_CODE2( DevType, Function, Method, Access ) ( \
  210736. ((DevType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method) \
  210737. )
  210738. #define IOCTL_SCSI_PASS_THROUGH CTL_CODE2( IOCTL_SCSI_BASE, 0x0401, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  210739. #define IOCTL_SCSI_GET_CAPABILITIES CTL_CODE2( IOCTL_SCSI_BASE, 0x0404, METHOD_BUFFERED, FILE_ANY_ACCESS)
  210740. #define IOCTL_SCSI_PASS_THROUGH_DIRECT CTL_CODE2( IOCTL_SCSI_BASE, 0x0405, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  210741. #define IOCTL_SCSI_GET_ADDRESS CTL_CODE2( IOCTL_SCSI_BASE, 0x0406, METHOD_BUFFERED, FILE_ANY_ACCESS )
  210742. #define SENSE_LEN 14
  210743. #define SRB_DIR_SCSI 0x00
  210744. #define SRB_POSTING 0x01
  210745. #define SRB_ENABLE_RESIDUAL_COUNT 0x04
  210746. #define SRB_DIR_IN 0x08
  210747. #define SRB_DIR_OUT 0x10
  210748. #define SRB_EVENT_NOTIFY 0x40
  210749. #define RESIDUAL_COUNT_SUPPORTED 0x02
  210750. #define MAX_SRB_TIMEOUT 1080001u
  210751. #define DEFAULT_SRB_TIMEOUT 1080001u
  210752. #define SC_HA_INQUIRY 0x00
  210753. #define SC_GET_DEV_TYPE 0x01
  210754. #define SC_EXEC_SCSI_CMD 0x02
  210755. #define SC_ABORT_SRB 0x03
  210756. #define SC_RESET_DEV 0x04
  210757. #define SC_SET_HA_PARMS 0x05
  210758. #define SC_GET_DISK_INFO 0x06
  210759. #define SC_RESCAN_SCSI_BUS 0x07
  210760. #define SC_GETSET_TIMEOUTS 0x08
  210761. #define SS_PENDING 0x00
  210762. #define SS_COMP 0x01
  210763. #define SS_ABORTED 0x02
  210764. #define SS_ABORT_FAIL 0x03
  210765. #define SS_ERR 0x04
  210766. #define SS_INVALID_CMD 0x80
  210767. #define SS_INVALID_HA 0x81
  210768. #define SS_NO_DEVICE 0x82
  210769. #define SS_INVALID_SRB 0xE0
  210770. #define SS_OLD_MANAGER 0xE1
  210771. #define SS_BUFFER_ALIGN 0xE1
  210772. #define SS_ILLEGAL_MODE 0xE2
  210773. #define SS_NO_ASPI 0xE3
  210774. #define SS_FAILED_INIT 0xE4
  210775. #define SS_ASPI_IS_BUSY 0xE5
  210776. #define SS_BUFFER_TO_BIG 0xE6
  210777. #define SS_BUFFER_TOO_BIG 0xE6
  210778. #define SS_MISMATCHED_COMPONENTS 0xE7
  210779. #define SS_NO_ADAPTERS 0xE8
  210780. #define SS_INSUFFICIENT_RESOURCES 0xE9
  210781. #define SS_ASPI_IS_SHUTDOWN 0xEA
  210782. #define SS_BAD_INSTALL 0xEB
  210783. #define HASTAT_OK 0x00
  210784. #define HASTAT_SEL_TO 0x11
  210785. #define HASTAT_DO_DU 0x12
  210786. #define HASTAT_BUS_FREE 0x13
  210787. #define HASTAT_PHASE_ERR 0x14
  210788. #define HASTAT_TIMEOUT 0x09
  210789. #define HASTAT_COMMAND_TIMEOUT 0x0B
  210790. #define HASTAT_MESSAGE_REJECT 0x0D
  210791. #define HASTAT_BUS_RESET 0x0E
  210792. #define HASTAT_PARITY_ERROR 0x0F
  210793. #define HASTAT_REQUEST_SENSE_FAILED 0x10
  210794. #define PACKED
  210795. #pragma pack(1)
  210796. typedef struct
  210797. {
  210798. BYTE SRB_Cmd;
  210799. BYTE SRB_Status;
  210800. BYTE SRB_HaID;
  210801. BYTE SRB_Flags;
  210802. DWORD SRB_Hdr_Rsvd;
  210803. BYTE HA_Count;
  210804. BYTE HA_SCSI_ID;
  210805. BYTE HA_ManagerId[16];
  210806. BYTE HA_Identifier[16];
  210807. BYTE HA_Unique[16];
  210808. WORD HA_Rsvd1;
  210809. BYTE pad[20];
  210810. } PACKED SRB_HAInquiry, *PSRB_HAInquiry, FAR *LPSRB_HAInquiry;
  210811. typedef struct
  210812. {
  210813. BYTE SRB_Cmd;
  210814. BYTE SRB_Status;
  210815. BYTE SRB_HaID;
  210816. BYTE SRB_Flags;
  210817. DWORD SRB_Hdr_Rsvd;
  210818. BYTE SRB_Target;
  210819. BYTE SRB_Lun;
  210820. BYTE SRB_DeviceType;
  210821. BYTE SRB_Rsvd1;
  210822. BYTE pad[68];
  210823. } PACKED SRB_GDEVBlock, *PSRB_GDEVBlock, FAR *LPSRB_GDEVBlock;
  210824. typedef struct
  210825. {
  210826. BYTE SRB_Cmd;
  210827. BYTE SRB_Status;
  210828. BYTE SRB_HaID;
  210829. BYTE SRB_Flags;
  210830. DWORD SRB_Hdr_Rsvd;
  210831. BYTE SRB_Target;
  210832. BYTE SRB_Lun;
  210833. WORD SRB_Rsvd1;
  210834. DWORD SRB_BufLen;
  210835. BYTE FAR *SRB_BufPointer;
  210836. BYTE SRB_SenseLen;
  210837. BYTE SRB_CDBLen;
  210838. BYTE SRB_HaStat;
  210839. BYTE SRB_TargStat;
  210840. VOID FAR *SRB_PostProc;
  210841. BYTE SRB_Rsvd2[20];
  210842. BYTE CDBByte[16];
  210843. BYTE SenseArea[SENSE_LEN+2];
  210844. } PACKED SRB_ExecSCSICmd, *PSRB_ExecSCSICmd, FAR *LPSRB_ExecSCSICmd;
  210845. typedef struct
  210846. {
  210847. BYTE SRB_Cmd;
  210848. BYTE SRB_Status;
  210849. BYTE SRB_HaId;
  210850. BYTE SRB_Flags;
  210851. DWORD SRB_Hdr_Rsvd;
  210852. } PACKED SRB, *PSRB, FAR *LPSRB;
  210853. #pragma pack()
  210854. struct CDDeviceInfo
  210855. {
  210856. char vendor[9];
  210857. char productId[17];
  210858. char rev[5];
  210859. char vendorSpec[21];
  210860. BYTE ha;
  210861. BYTE tgt;
  210862. BYTE lun;
  210863. char scsiDriveLetter; // will be 0 if not using scsi
  210864. };
  210865. class CDReadBuffer
  210866. {
  210867. public:
  210868. int startFrame;
  210869. int numFrames;
  210870. int dataStartOffset;
  210871. int dataLength;
  210872. int bufferSize;
  210873. HeapBlock<BYTE> buffer;
  210874. int index;
  210875. bool wantsIndex;
  210876. CDReadBuffer (const int numberOfFrames)
  210877. : startFrame (0),
  210878. numFrames (0),
  210879. dataStartOffset (0),
  210880. dataLength (0),
  210881. bufferSize (2352 * numberOfFrames),
  210882. buffer (bufferSize),
  210883. index (0),
  210884. wantsIndex (false)
  210885. {
  210886. }
  210887. bool isZero() const throw()
  210888. {
  210889. BYTE* p = buffer + dataStartOffset;
  210890. for (int i = dataLength; --i >= 0;)
  210891. if (*p++ != 0)
  210892. return false;
  210893. return true;
  210894. }
  210895. };
  210896. class CDDeviceHandle;
  210897. class CDController
  210898. {
  210899. public:
  210900. CDController();
  210901. virtual ~CDController();
  210902. virtual bool read (CDReadBuffer* t) = 0;
  210903. virtual void shutDown();
  210904. bool readAudio (CDReadBuffer* t, CDReadBuffer* overlapBuffer = 0);
  210905. int getLastIndex();
  210906. public:
  210907. bool initialised;
  210908. CDDeviceHandle* deviceInfo;
  210909. int framesToCheck, framesOverlap;
  210910. void prepare (SRB_ExecSCSICmd& s);
  210911. void perform (SRB_ExecSCSICmd& s);
  210912. void setPaused (bool paused);
  210913. };
  210914. #pragma pack(1)
  210915. struct TOCTRACK
  210916. {
  210917. BYTE rsvd;
  210918. BYTE ADR;
  210919. BYTE trackNumber;
  210920. BYTE rsvd2;
  210921. BYTE addr[4];
  210922. };
  210923. struct TOC
  210924. {
  210925. WORD tocLen;
  210926. BYTE firstTrack;
  210927. BYTE lastTrack;
  210928. TOCTRACK tracks[100];
  210929. };
  210930. #pragma pack()
  210931. enum
  210932. {
  210933. READTYPE_ANY = 0,
  210934. READTYPE_ATAPI1 = 1,
  210935. READTYPE_ATAPI2 = 2,
  210936. READTYPE_READ6 = 3,
  210937. READTYPE_READ10 = 4,
  210938. READTYPE_READ_D8 = 5,
  210939. READTYPE_READ_D4 = 6,
  210940. READTYPE_READ_D4_1 = 7,
  210941. READTYPE_READ10_2 = 8
  210942. };
  210943. class CDDeviceHandle
  210944. {
  210945. public:
  210946. CDDeviceHandle (const CDDeviceInfo* const device)
  210947. : scsiHandle (0),
  210948. readType (READTYPE_ANY),
  210949. controller (0)
  210950. {
  210951. memcpy (&info, device, sizeof (info));
  210952. }
  210953. ~CDDeviceHandle()
  210954. {
  210955. if (controller != 0)
  210956. {
  210957. controller->shutDown();
  210958. controller = 0;
  210959. }
  210960. if (scsiHandle != 0)
  210961. CloseHandle (scsiHandle);
  210962. }
  210963. bool readTOC (TOC* lpToc);
  210964. bool readAudio (CDReadBuffer* buffer, CDReadBuffer* overlapBuffer = 0);
  210965. void openDrawer (bool shouldBeOpen);
  210966. CDDeviceInfo info;
  210967. HANDLE scsiHandle;
  210968. BYTE readType;
  210969. private:
  210970. ScopedPointer<CDController> controller;
  210971. bool testController (const int readType,
  210972. CDController* const newController,
  210973. CDReadBuffer* const bufferToUse);
  210974. };
  210975. DWORD (*fGetASPI32SupportInfo)(void);
  210976. DWORD (*fSendASPI32Command)(LPSRB);
  210977. static HINSTANCE winAspiLib = 0;
  210978. static bool usingScsi = false;
  210979. static bool initialised = false;
  210980. static bool InitialiseCDRipper()
  210981. {
  210982. if (! initialised)
  210983. {
  210984. initialised = true;
  210985. OSVERSIONINFO info;
  210986. info.dwOSVersionInfoSize = sizeof (info);
  210987. GetVersionEx (&info);
  210988. usingScsi = (info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4);
  210989. if (! usingScsi)
  210990. {
  210991. fGetASPI32SupportInfo = 0;
  210992. fSendASPI32Command = 0;
  210993. winAspiLib = LoadLibrary (_T("WNASPI32.DLL"));
  210994. if (winAspiLib != 0)
  210995. {
  210996. fGetASPI32SupportInfo = (DWORD(*)(void)) GetProcAddress (winAspiLib, "GetASPI32SupportInfo");
  210997. fSendASPI32Command = (DWORD(*)(LPSRB)) GetProcAddress (winAspiLib, "SendASPI32Command");
  210998. if (fGetASPI32SupportInfo == 0 || fSendASPI32Command == 0)
  210999. return false;
  211000. }
  211001. else
  211002. {
  211003. usingScsi = true;
  211004. }
  211005. }
  211006. }
  211007. return true;
  211008. }
  211009. static void DeinitialiseCDRipper()
  211010. {
  211011. if (winAspiLib != 0)
  211012. {
  211013. fGetASPI32SupportInfo = 0;
  211014. fSendASPI32Command = 0;
  211015. FreeLibrary (winAspiLib);
  211016. winAspiLib = 0;
  211017. }
  211018. initialised = false;
  211019. }
  211020. static HANDLE CreateSCSIDeviceHandle (char driveLetter)
  211021. {
  211022. TCHAR devicePath[] = { '\\', '\\', '.', '\\', driveLetter, ':', 0, 0 };
  211023. OSVERSIONINFO info;
  211024. info.dwOSVersionInfoSize = sizeof (info);
  211025. GetVersionEx (&info);
  211026. DWORD flags = GENERIC_READ;
  211027. if ((info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4))
  211028. flags = GENERIC_READ | GENERIC_WRITE;
  211029. HANDLE h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  211030. if (h == INVALID_HANDLE_VALUE)
  211031. {
  211032. flags ^= GENERIC_WRITE;
  211033. h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  211034. }
  211035. return h;
  211036. }
  211037. static DWORD performScsiPassThroughCommand (const LPSRB_ExecSCSICmd srb,
  211038. const char driveLetter,
  211039. HANDLE& deviceHandle,
  211040. const bool retryOnFailure = true)
  211041. {
  211042. SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER s;
  211043. zerostruct (s);
  211044. s.spt.Length = sizeof (SCSI_PASS_THROUGH);
  211045. s.spt.CdbLength = srb->SRB_CDBLen;
  211046. s.spt.DataIn = (BYTE) ((srb->SRB_Flags & SRB_DIR_IN)
  211047. ? SCSI_IOCTL_DATA_IN
  211048. : ((srb->SRB_Flags & SRB_DIR_OUT)
  211049. ? SCSI_IOCTL_DATA_OUT
  211050. : SCSI_IOCTL_DATA_UNSPECIFIED));
  211051. s.spt.DataTransferLength = srb->SRB_BufLen;
  211052. s.spt.TimeOutValue = 5;
  211053. s.spt.DataBuffer = srb->SRB_BufPointer;
  211054. s.spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  211055. memcpy (s.spt.Cdb, srb->CDBByte, srb->SRB_CDBLen);
  211056. srb->SRB_Status = SS_ERR;
  211057. srb->SRB_TargStat = 0x0004;
  211058. DWORD bytesReturned = 0;
  211059. if (DeviceIoControl (deviceHandle, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  211060. &s, sizeof (s),
  211061. &s, sizeof (s),
  211062. &bytesReturned, 0) != 0)
  211063. {
  211064. srb->SRB_Status = SS_COMP;
  211065. }
  211066. else if (retryOnFailure)
  211067. {
  211068. const DWORD error = GetLastError();
  211069. if ((error == ERROR_MEDIA_CHANGED) || (error == ERROR_INVALID_HANDLE))
  211070. {
  211071. if (error != ERROR_INVALID_HANDLE)
  211072. CloseHandle (deviceHandle);
  211073. deviceHandle = CreateSCSIDeviceHandle (driveLetter);
  211074. return performScsiPassThroughCommand (srb, driveLetter, deviceHandle, false);
  211075. }
  211076. }
  211077. return srb->SRB_Status;
  211078. }
  211079. // Controller types..
  211080. class ControllerType1 : public CDController
  211081. {
  211082. public:
  211083. ControllerType1() {}
  211084. ~ControllerType1() {}
  211085. bool read (CDReadBuffer* rb)
  211086. {
  211087. if (rb->numFrames * 2352 > rb->bufferSize)
  211088. return false;
  211089. SRB_ExecSCSICmd s;
  211090. prepare (s);
  211091. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211092. s.SRB_BufLen = rb->bufferSize;
  211093. s.SRB_BufPointer = rb->buffer;
  211094. s.SRB_CDBLen = 12;
  211095. s.CDBByte[0] = 0xBE;
  211096. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  211097. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  211098. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  211099. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  211100. s.CDBByte[9] = (BYTE)((deviceInfo->readType == READTYPE_ATAPI1) ? 0x10 : 0xF0);
  211101. perform (s);
  211102. if (s.SRB_Status != SS_COMP)
  211103. return false;
  211104. rb->dataLength = rb->numFrames * 2352;
  211105. rb->dataStartOffset = 0;
  211106. return true;
  211107. }
  211108. };
  211109. class ControllerType2 : public CDController
  211110. {
  211111. public:
  211112. ControllerType2() {}
  211113. ~ControllerType2() {}
  211114. void shutDown()
  211115. {
  211116. if (initialised)
  211117. {
  211118. BYTE bufPointer[] = { 0, 0, 0, 8, 83, 0, 0, 0, 0, 0, 8, 0 };
  211119. SRB_ExecSCSICmd s;
  211120. prepare (s);
  211121. s.SRB_Flags = SRB_EVENT_NOTIFY | SRB_ENABLE_RESIDUAL_COUNT;
  211122. s.SRB_BufLen = 0x0C;
  211123. s.SRB_BufPointer = bufPointer;
  211124. s.SRB_CDBLen = 6;
  211125. s.CDBByte[0] = 0x15;
  211126. s.CDBByte[4] = 0x0C;
  211127. perform (s);
  211128. }
  211129. }
  211130. bool init()
  211131. {
  211132. SRB_ExecSCSICmd s;
  211133. s.SRB_Status = SS_ERR;
  211134. if (deviceInfo->readType == READTYPE_READ10_2)
  211135. {
  211136. BYTE bufPointer1[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 35, 6, 0, 0, 0, 0, 0, 128 };
  211137. BYTE bufPointer2[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 1, 6, 32, 7, 0, 0, 0, 0 };
  211138. for (int i = 0; i < 2; ++i)
  211139. {
  211140. prepare (s);
  211141. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211142. s.SRB_BufLen = 0x14;
  211143. s.SRB_BufPointer = (i == 0) ? bufPointer1 : bufPointer2;
  211144. s.SRB_CDBLen = 6;
  211145. s.CDBByte[0] = 0x15;
  211146. s.CDBByte[1] = 0x10;
  211147. s.CDBByte[4] = 0x14;
  211148. perform (s);
  211149. if (s.SRB_Status != SS_COMP)
  211150. return false;
  211151. }
  211152. }
  211153. else
  211154. {
  211155. BYTE bufPointer[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48 };
  211156. prepare (s);
  211157. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211158. s.SRB_BufLen = 0x0C;
  211159. s.SRB_BufPointer = bufPointer;
  211160. s.SRB_CDBLen = 6;
  211161. s.CDBByte[0] = 0x15;
  211162. s.CDBByte[4] = 0x0C;
  211163. perform (s);
  211164. }
  211165. return s.SRB_Status == SS_COMP;
  211166. }
  211167. bool read (CDReadBuffer* rb)
  211168. {
  211169. if (rb->numFrames * 2352 > rb->bufferSize)
  211170. return false;
  211171. if (!initialised)
  211172. {
  211173. initialised = init();
  211174. if (!initialised)
  211175. return false;
  211176. }
  211177. SRB_ExecSCSICmd s;
  211178. prepare (s);
  211179. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211180. s.SRB_BufLen = rb->bufferSize;
  211181. s.SRB_BufPointer = rb->buffer;
  211182. s.SRB_CDBLen = 10;
  211183. s.CDBByte[0] = 0x28;
  211184. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  211185. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  211186. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  211187. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  211188. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  211189. perform (s);
  211190. if (s.SRB_Status != SS_COMP)
  211191. return false;
  211192. rb->dataLength = rb->numFrames * 2352;
  211193. rb->dataStartOffset = 0;
  211194. return true;
  211195. }
  211196. };
  211197. class ControllerType3 : public CDController
  211198. {
  211199. public:
  211200. ControllerType3() {}
  211201. ~ControllerType3() {}
  211202. bool read (CDReadBuffer* rb)
  211203. {
  211204. if (rb->numFrames * 2352 > rb->bufferSize)
  211205. return false;
  211206. if (!initialised)
  211207. {
  211208. setPaused (false);
  211209. initialised = true;
  211210. }
  211211. SRB_ExecSCSICmd s;
  211212. prepare (s);
  211213. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211214. s.SRB_BufLen = rb->numFrames * 2352;
  211215. s.SRB_BufPointer = rb->buffer;
  211216. s.SRB_CDBLen = 12;
  211217. s.CDBByte[0] = 0xD8;
  211218. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  211219. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  211220. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  211221. s.CDBByte[9] = (BYTE)(rb->numFrames & 0xFF);
  211222. perform (s);
  211223. if (s.SRB_Status != SS_COMP)
  211224. return false;
  211225. rb->dataLength = rb->numFrames * 2352;
  211226. rb->dataStartOffset = 0;
  211227. return true;
  211228. }
  211229. };
  211230. class ControllerType4 : public CDController
  211231. {
  211232. public:
  211233. ControllerType4() {}
  211234. ~ControllerType4() {}
  211235. bool selectD4Mode()
  211236. {
  211237. BYTE bufPointer[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 48 };
  211238. SRB_ExecSCSICmd s;
  211239. prepare (s);
  211240. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211241. s.SRB_CDBLen = 6;
  211242. s.SRB_BufLen = 12;
  211243. s.SRB_BufPointer = bufPointer;
  211244. s.CDBByte[0] = 0x15;
  211245. s.CDBByte[1] = 0x10;
  211246. s.CDBByte[4] = 0x08;
  211247. perform (s);
  211248. return s.SRB_Status == SS_COMP;
  211249. }
  211250. bool read (CDReadBuffer* rb)
  211251. {
  211252. if (rb->numFrames * 2352 > rb->bufferSize)
  211253. return false;
  211254. if (!initialised)
  211255. {
  211256. setPaused (true);
  211257. if (deviceInfo->readType == READTYPE_READ_D4_1)
  211258. selectD4Mode();
  211259. initialised = true;
  211260. }
  211261. SRB_ExecSCSICmd s;
  211262. prepare (s);
  211263. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211264. s.SRB_BufLen = rb->bufferSize;
  211265. s.SRB_BufPointer = rb->buffer;
  211266. s.SRB_CDBLen = 10;
  211267. s.CDBByte[0] = 0xD4;
  211268. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  211269. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  211270. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  211271. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  211272. perform (s);
  211273. if (s.SRB_Status != SS_COMP)
  211274. return false;
  211275. rb->dataLength = rb->numFrames * 2352;
  211276. rb->dataStartOffset = 0;
  211277. return true;
  211278. }
  211279. };
  211280. CDController::CDController() : initialised (false)
  211281. {
  211282. }
  211283. CDController::~CDController()
  211284. {
  211285. }
  211286. void CDController::prepare (SRB_ExecSCSICmd& s)
  211287. {
  211288. zerostruct (s);
  211289. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211290. s.SRB_HaID = deviceInfo->info.ha;
  211291. s.SRB_Target = deviceInfo->info.tgt;
  211292. s.SRB_Lun = deviceInfo->info.lun;
  211293. s.SRB_SenseLen = SENSE_LEN;
  211294. }
  211295. void CDController::perform (SRB_ExecSCSICmd& s)
  211296. {
  211297. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  211298. s.SRB_PostProc = event;
  211299. ResetEvent (event);
  211300. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s,
  211301. deviceInfo->info.scsiDriveLetter,
  211302. deviceInfo->scsiHandle)
  211303. : fSendASPI32Command ((LPSRB)&s);
  211304. if (status == SS_PENDING)
  211305. WaitForSingleObject (event, 4000);
  211306. CloseHandle (event);
  211307. }
  211308. void CDController::setPaused (bool paused)
  211309. {
  211310. SRB_ExecSCSICmd s;
  211311. prepare (s);
  211312. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211313. s.SRB_CDBLen = 10;
  211314. s.CDBByte[0] = 0x4B;
  211315. s.CDBByte[8] = (BYTE) (paused ? 0 : 1);
  211316. perform (s);
  211317. }
  211318. void CDController::shutDown()
  211319. {
  211320. }
  211321. bool CDController::readAudio (CDReadBuffer* rb, CDReadBuffer* overlapBuffer)
  211322. {
  211323. if (overlapBuffer != 0)
  211324. {
  211325. const bool canDoJitter = (overlapBuffer->bufferSize >= 2352 * framesToCheck);
  211326. const bool doJitter = canDoJitter && ! overlapBuffer->isZero();
  211327. if (doJitter
  211328. && overlapBuffer->startFrame > 0
  211329. && overlapBuffer->numFrames > 0
  211330. && overlapBuffer->dataLength > 0)
  211331. {
  211332. const int numFrames = rb->numFrames;
  211333. if (overlapBuffer->startFrame == (rb->startFrame - framesToCheck))
  211334. {
  211335. rb->startFrame -= framesOverlap;
  211336. if (framesToCheck < framesOverlap
  211337. && numFrames + framesOverlap <= rb->bufferSize / 2352)
  211338. rb->numFrames += framesOverlap;
  211339. }
  211340. else
  211341. {
  211342. overlapBuffer->dataLength = 0;
  211343. overlapBuffer->startFrame = 0;
  211344. overlapBuffer->numFrames = 0;
  211345. }
  211346. }
  211347. if (! read (rb))
  211348. return false;
  211349. if (doJitter)
  211350. {
  211351. const int checkLen = framesToCheck * 2352;
  211352. const int maxToCheck = rb->dataLength - checkLen;
  211353. if (overlapBuffer->dataLength == 0 || overlapBuffer->isZero())
  211354. return true;
  211355. BYTE* const p = overlapBuffer->buffer + overlapBuffer->dataStartOffset;
  211356. bool found = false;
  211357. for (int i = 0; i < maxToCheck; ++i)
  211358. {
  211359. if (memcmp (p, rb->buffer + i, checkLen) == 0)
  211360. {
  211361. i += checkLen;
  211362. rb->dataStartOffset = i;
  211363. rb->dataLength -= i;
  211364. rb->startFrame = overlapBuffer->startFrame + framesToCheck;
  211365. found = true;
  211366. break;
  211367. }
  211368. }
  211369. rb->numFrames = rb->dataLength / 2352;
  211370. rb->dataLength = 2352 * rb->numFrames;
  211371. if (!found)
  211372. return false;
  211373. }
  211374. if (canDoJitter)
  211375. {
  211376. memcpy (overlapBuffer->buffer,
  211377. rb->buffer + rb->dataStartOffset + 2352 * (rb->numFrames - framesToCheck),
  211378. 2352 * framesToCheck);
  211379. overlapBuffer->startFrame = rb->startFrame + rb->numFrames - framesToCheck;
  211380. overlapBuffer->numFrames = framesToCheck;
  211381. overlapBuffer->dataLength = 2352 * framesToCheck;
  211382. overlapBuffer->dataStartOffset = 0;
  211383. }
  211384. else
  211385. {
  211386. overlapBuffer->startFrame = 0;
  211387. overlapBuffer->numFrames = 0;
  211388. overlapBuffer->dataLength = 0;
  211389. }
  211390. return true;
  211391. }
  211392. else
  211393. {
  211394. return read (rb);
  211395. }
  211396. }
  211397. int CDController::getLastIndex()
  211398. {
  211399. char qdata[100];
  211400. SRB_ExecSCSICmd s;
  211401. prepare (s);
  211402. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211403. s.SRB_BufLen = sizeof (qdata);
  211404. s.SRB_BufPointer = (BYTE*)qdata;
  211405. s.SRB_CDBLen = 12;
  211406. s.CDBByte[0] = 0x42;
  211407. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  211408. s.CDBByte[2] = 64;
  211409. s.CDBByte[3] = 1; // get current position
  211410. s.CDBByte[7] = 0;
  211411. s.CDBByte[8] = (BYTE)sizeof (qdata);
  211412. perform (s);
  211413. if (s.SRB_Status == SS_COMP)
  211414. return qdata[7];
  211415. return 0;
  211416. }
  211417. bool CDDeviceHandle::readTOC (TOC* lpToc)
  211418. {
  211419. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  211420. SRB_ExecSCSICmd s;
  211421. zerostruct (s);
  211422. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211423. s.SRB_HaID = info.ha;
  211424. s.SRB_Target = info.tgt;
  211425. s.SRB_Lun = info.lun;
  211426. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211427. s.SRB_BufLen = 0x324;
  211428. s.SRB_BufPointer = (BYTE*)lpToc;
  211429. s.SRB_SenseLen = 0x0E;
  211430. s.SRB_CDBLen = 0x0A;
  211431. s.SRB_PostProc = event;
  211432. s.CDBByte[0] = 0x43;
  211433. s.CDBByte[1] = 0x00;
  211434. s.CDBByte[7] = 0x03;
  211435. s.CDBByte[8] = 0x24;
  211436. ResetEvent (event);
  211437. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  211438. : fSendASPI32Command ((LPSRB)&s);
  211439. if (status == SS_PENDING)
  211440. WaitForSingleObject (event, 4000);
  211441. CloseHandle (event);
  211442. return (s.SRB_Status == SS_COMP);
  211443. }
  211444. bool CDDeviceHandle::readAudio (CDReadBuffer* const buffer,
  211445. CDReadBuffer* const overlapBuffer)
  211446. {
  211447. if (controller == 0)
  211448. {
  211449. testController (READTYPE_ATAPI2, new ControllerType1(), buffer)
  211450. || testController (READTYPE_ATAPI1, new ControllerType1(), buffer)
  211451. || testController (READTYPE_READ10_2, new ControllerType2(), buffer)
  211452. || testController (READTYPE_READ10, new ControllerType2(), buffer)
  211453. || testController (READTYPE_READ_D8, new ControllerType3(), buffer)
  211454. || testController (READTYPE_READ_D4, new ControllerType4(), buffer)
  211455. || testController (READTYPE_READ_D4_1, new ControllerType4(), buffer);
  211456. }
  211457. buffer->index = 0;
  211458. if ((controller != 0)
  211459. && controller->readAudio (buffer, overlapBuffer))
  211460. {
  211461. if (buffer->wantsIndex)
  211462. buffer->index = controller->getLastIndex();
  211463. return true;
  211464. }
  211465. return false;
  211466. }
  211467. void CDDeviceHandle::openDrawer (bool shouldBeOpen)
  211468. {
  211469. if (shouldBeOpen)
  211470. {
  211471. if (controller != 0)
  211472. {
  211473. controller->shutDown();
  211474. controller = 0;
  211475. }
  211476. if (scsiHandle != 0)
  211477. {
  211478. CloseHandle (scsiHandle);
  211479. scsiHandle = 0;
  211480. }
  211481. }
  211482. SRB_ExecSCSICmd s;
  211483. zerostruct (s);
  211484. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211485. s.SRB_HaID = info.ha;
  211486. s.SRB_Target = info.tgt;
  211487. s.SRB_Lun = info.lun;
  211488. s.SRB_SenseLen = SENSE_LEN;
  211489. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211490. s.SRB_BufLen = 0;
  211491. s.SRB_BufPointer = 0;
  211492. s.SRB_CDBLen = 12;
  211493. s.CDBByte[0] = 0x1b;
  211494. s.CDBByte[1] = (BYTE)(info.lun << 5);
  211495. s.CDBByte[4] = (BYTE)((shouldBeOpen) ? 2 : 3);
  211496. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  211497. s.SRB_PostProc = event;
  211498. ResetEvent (event);
  211499. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  211500. : fSendASPI32Command ((LPSRB)&s);
  211501. if (status == SS_PENDING)
  211502. WaitForSingleObject (event, 4000);
  211503. CloseHandle (event);
  211504. }
  211505. bool CDDeviceHandle::testController (const int type,
  211506. CDController* const newController,
  211507. CDReadBuffer* const rb)
  211508. {
  211509. controller = newController;
  211510. readType = (BYTE)type;
  211511. controller->deviceInfo = this;
  211512. controller->framesToCheck = 1;
  211513. controller->framesOverlap = 3;
  211514. bool passed = false;
  211515. memset (rb->buffer, 0xcd, rb->bufferSize);
  211516. if (controller->read (rb))
  211517. {
  211518. passed = true;
  211519. int* p = (int*) (rb->buffer + rb->dataStartOffset);
  211520. int wrong = 0;
  211521. for (int i = rb->dataLength / 4; --i >= 0;)
  211522. {
  211523. if (*p++ == (int) 0xcdcdcdcd)
  211524. {
  211525. if (++wrong == 4)
  211526. {
  211527. passed = false;
  211528. break;
  211529. }
  211530. }
  211531. else
  211532. {
  211533. wrong = 0;
  211534. }
  211535. }
  211536. }
  211537. if (! passed)
  211538. {
  211539. controller->shutDown();
  211540. controller = 0;
  211541. }
  211542. return passed;
  211543. }
  211544. static void GetAspiDeviceInfo (CDDeviceInfo* dev, BYTE ha, BYTE tgt, BYTE lun)
  211545. {
  211546. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  211547. const int bufSize = 128;
  211548. BYTE buffer[bufSize];
  211549. zeromem (buffer, bufSize);
  211550. SRB_ExecSCSICmd s;
  211551. zerostruct (s);
  211552. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211553. s.SRB_HaID = ha;
  211554. s.SRB_Target = tgt;
  211555. s.SRB_Lun = lun;
  211556. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211557. s.SRB_BufLen = bufSize;
  211558. s.SRB_BufPointer = buffer;
  211559. s.SRB_SenseLen = SENSE_LEN;
  211560. s.SRB_CDBLen = 6;
  211561. s.SRB_PostProc = event;
  211562. s.CDBByte[0] = SCSI_INQUIRY;
  211563. s.CDBByte[4] = 100;
  211564. ResetEvent (event);
  211565. if (fSendASPI32Command ((LPSRB)&s) == SS_PENDING)
  211566. WaitForSingleObject (event, 4000);
  211567. CloseHandle (event);
  211568. if (s.SRB_Status == SS_COMP)
  211569. {
  211570. memcpy (dev->vendor, &buffer[8], 8);
  211571. memcpy (dev->productId, &buffer[16], 16);
  211572. memcpy (dev->rev, &buffer[32], 4);
  211573. memcpy (dev->vendorSpec, &buffer[36], 20);
  211574. }
  211575. }
  211576. static int FindCDDevices (CDDeviceInfo* const list,
  211577. int maxItems)
  211578. {
  211579. int count = 0;
  211580. if (usingScsi)
  211581. {
  211582. for (char driveLetter = 'b'; driveLetter <= 'z'; ++driveLetter)
  211583. {
  211584. TCHAR drivePath[8];
  211585. drivePath[0] = driveLetter;
  211586. drivePath[1] = ':';
  211587. drivePath[2] = '\\';
  211588. drivePath[3] = 0;
  211589. if (GetDriveType (drivePath) == DRIVE_CDROM)
  211590. {
  211591. HANDLE h = CreateSCSIDeviceHandle (driveLetter);
  211592. if (h != INVALID_HANDLE_VALUE)
  211593. {
  211594. BYTE buffer[100], passThroughStruct[1024];
  211595. zeromem (buffer, sizeof (buffer));
  211596. zeromem (passThroughStruct, sizeof (passThroughStruct));
  211597. PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER p = (PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER)passThroughStruct;
  211598. p->spt.Length = sizeof (SCSI_PASS_THROUGH);
  211599. p->spt.CdbLength = 6;
  211600. p->spt.SenseInfoLength = 24;
  211601. p->spt.DataIn = SCSI_IOCTL_DATA_IN;
  211602. p->spt.DataTransferLength = 100;
  211603. p->spt.TimeOutValue = 2;
  211604. p->spt.DataBuffer = buffer;
  211605. p->spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  211606. p->spt.Cdb[0] = 0x12;
  211607. p->spt.Cdb[4] = 100;
  211608. DWORD bytesReturned = 0;
  211609. if (DeviceIoControl (h, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  211610. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  211611. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  211612. &bytesReturned, 0) != 0)
  211613. {
  211614. zeromem (&list[count], sizeof (CDDeviceInfo));
  211615. list[count].scsiDriveLetter = driveLetter;
  211616. memcpy (list[count].vendor, &buffer[8], 8);
  211617. memcpy (list[count].productId, &buffer[16], 16);
  211618. memcpy (list[count].rev, &buffer[32], 4);
  211619. memcpy (list[count].vendorSpec, &buffer[36], 20);
  211620. zeromem (passThroughStruct, sizeof (passThroughStruct));
  211621. PSCSI_ADDRESS scsiAddr = (PSCSI_ADDRESS)passThroughStruct;
  211622. scsiAddr->Length = sizeof (SCSI_ADDRESS);
  211623. if (DeviceIoControl (h, IOCTL_SCSI_GET_ADDRESS,
  211624. 0, 0, scsiAddr, sizeof (SCSI_ADDRESS),
  211625. &bytesReturned, 0) != 0)
  211626. {
  211627. list[count].ha = scsiAddr->PortNumber;
  211628. list[count].tgt = scsiAddr->TargetId;
  211629. list[count].lun = scsiAddr->Lun;
  211630. ++count;
  211631. }
  211632. }
  211633. CloseHandle (h);
  211634. }
  211635. }
  211636. }
  211637. }
  211638. else
  211639. {
  211640. const DWORD d = fGetASPI32SupportInfo();
  211641. BYTE status = HIBYTE (LOWORD (d));
  211642. if (status != SS_COMP || status == SS_NO_ADAPTERS)
  211643. return 0;
  211644. const int numAdapters = LOBYTE (LOWORD (d));
  211645. for (BYTE ha = 0; ha < numAdapters; ++ha)
  211646. {
  211647. SRB_HAInquiry s;
  211648. zerostruct (s);
  211649. s.SRB_Cmd = SC_HA_INQUIRY;
  211650. s.SRB_HaID = ha;
  211651. fSendASPI32Command ((LPSRB)&s);
  211652. if (s.SRB_Status == SS_COMP)
  211653. {
  211654. maxItems = (int)s.HA_Unique[3];
  211655. if (maxItems == 0)
  211656. maxItems = 8;
  211657. for (BYTE tgt = 0; tgt < maxItems; ++tgt)
  211658. {
  211659. for (BYTE lun = 0; lun < 8; ++lun)
  211660. {
  211661. SRB_GDEVBlock sb;
  211662. zerostruct (sb);
  211663. sb.SRB_Cmd = SC_GET_DEV_TYPE;
  211664. sb.SRB_HaID = ha;
  211665. sb.SRB_Target = tgt;
  211666. sb.SRB_Lun = lun;
  211667. fSendASPI32Command ((LPSRB) &sb);
  211668. if (sb.SRB_Status == SS_COMP
  211669. && sb.SRB_DeviceType == DTYPE_CROM)
  211670. {
  211671. zeromem (&list[count], sizeof (CDDeviceInfo));
  211672. list[count].ha = ha;
  211673. list[count].tgt = tgt;
  211674. list[count].lun = lun;
  211675. GetAspiDeviceInfo (&(list[count]), ha, tgt, lun);
  211676. ++count;
  211677. }
  211678. }
  211679. }
  211680. }
  211681. }
  211682. }
  211683. return count;
  211684. }
  211685. static int ripperUsers = 0;
  211686. static bool initialisedOk = false;
  211687. class DeinitialiseTimer : private Timer,
  211688. private DeletedAtShutdown
  211689. {
  211690. DeinitialiseTimer (const DeinitialiseTimer&);
  211691. DeinitialiseTimer& operator= (const DeinitialiseTimer&);
  211692. public:
  211693. DeinitialiseTimer()
  211694. {
  211695. startTimer (4000);
  211696. }
  211697. ~DeinitialiseTimer()
  211698. {
  211699. if (--ripperUsers == 0)
  211700. DeinitialiseCDRipper();
  211701. }
  211702. void timerCallback()
  211703. {
  211704. delete this;
  211705. }
  211706. juce_UseDebuggingNewOperator
  211707. };
  211708. static void incUserCount()
  211709. {
  211710. if (ripperUsers++ == 0)
  211711. initialisedOk = InitialiseCDRipper();
  211712. }
  211713. static void decUserCount()
  211714. {
  211715. new DeinitialiseTimer();
  211716. }
  211717. struct CDDeviceWrapper
  211718. {
  211719. ScopedPointer<CDDeviceHandle> cdH;
  211720. ScopedPointer<CDReadBuffer> overlapBuffer;
  211721. bool jitter;
  211722. };
  211723. static int getAddressOf (const TOCTRACK* const t)
  211724. {
  211725. return (((DWORD)t->addr[0]) << 24) + (((DWORD)t->addr[1]) << 16) +
  211726. (((DWORD)t->addr[2]) << 8) + ((DWORD)t->addr[3]);
  211727. }
  211728. static const int samplesPerFrame = 44100 / 75;
  211729. static const int bytesPerFrame = samplesPerFrame * 4;
  211730. static CDDeviceHandle* openHandle (const CDDeviceInfo* const device)
  211731. {
  211732. SRB_GDEVBlock s;
  211733. zerostruct (s);
  211734. s.SRB_Cmd = SC_GET_DEV_TYPE;
  211735. s.SRB_HaID = device->ha;
  211736. s.SRB_Target = device->tgt;
  211737. s.SRB_Lun = device->lun;
  211738. if (usingScsi)
  211739. {
  211740. HANDLE h = CreateSCSIDeviceHandle (device->scsiDriveLetter);
  211741. if (h != INVALID_HANDLE_VALUE)
  211742. {
  211743. CDDeviceHandle* cdh = new CDDeviceHandle (device);
  211744. cdh->scsiHandle = h;
  211745. return cdh;
  211746. }
  211747. }
  211748. else
  211749. {
  211750. if (fSendASPI32Command ((LPSRB)&s) == SS_COMP
  211751. && s.SRB_DeviceType == DTYPE_CROM)
  211752. {
  211753. return new CDDeviceHandle (device);
  211754. }
  211755. }
  211756. return 0;
  211757. }
  211758. }
  211759. const StringArray AudioCDReader::getAvailableCDNames()
  211760. {
  211761. using namespace CDReaderHelpers;
  211762. StringArray results;
  211763. incUserCount();
  211764. if (initialisedOk)
  211765. {
  211766. CDDeviceInfo list[8];
  211767. const int num = FindCDDevices (list, 8);
  211768. decUserCount();
  211769. for (int i = 0; i < num; ++i)
  211770. {
  211771. String s;
  211772. if (list[i].scsiDriveLetter > 0)
  211773. s << String::charToString (list[i].scsiDriveLetter).toUpperCase() << ": ";
  211774. s << String (list[i].vendor).trim()
  211775. << ' ' << String (list[i].productId).trim()
  211776. << ' ' << String (list[i].rev).trim();
  211777. results.add (s);
  211778. }
  211779. }
  211780. return results;
  211781. }
  211782. AudioCDReader* AudioCDReader::createReaderForCD (const int deviceIndex)
  211783. {
  211784. using namespace CDReaderHelpers;
  211785. incUserCount();
  211786. if (initialisedOk)
  211787. {
  211788. CDDeviceInfo list[8];
  211789. const int num = FindCDDevices (list, 8);
  211790. if (((unsigned int) deviceIndex) < (unsigned int) num)
  211791. {
  211792. CDDeviceHandle* const handle = openHandle (&(list[deviceIndex]));
  211793. if (handle != 0)
  211794. {
  211795. CDDeviceWrapper* const d = new CDDeviceWrapper();
  211796. d->cdH = handle;
  211797. d->overlapBuffer = new CDReadBuffer(3);
  211798. return new AudioCDReader (d);
  211799. }
  211800. }
  211801. }
  211802. decUserCount();
  211803. return 0;
  211804. }
  211805. AudioCDReader::AudioCDReader (void* handle_)
  211806. : AudioFormatReader (0, "CD Audio"),
  211807. handle (handle_),
  211808. indexingEnabled (false),
  211809. lastIndex (0),
  211810. firstFrameInBuffer (0),
  211811. samplesInBuffer (0)
  211812. {
  211813. using namespace CDReaderHelpers;
  211814. jassert (handle_ != 0);
  211815. refreshTrackLengths();
  211816. sampleRate = 44100.0;
  211817. bitsPerSample = 16;
  211818. numChannels = 2;
  211819. usesFloatingPointData = false;
  211820. buffer.setSize (4 * bytesPerFrame, true);
  211821. }
  211822. AudioCDReader::~AudioCDReader()
  211823. {
  211824. using namespace CDReaderHelpers;
  211825. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  211826. delete device;
  211827. decUserCount();
  211828. }
  211829. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  211830. int64 startSampleInFile, int numSamples)
  211831. {
  211832. using namespace CDReaderHelpers;
  211833. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  211834. bool ok = true;
  211835. while (numSamples > 0)
  211836. {
  211837. const int bufferStartSample = firstFrameInBuffer * samplesPerFrame;
  211838. const int bufferEndSample = bufferStartSample + samplesInBuffer;
  211839. if (startSampleInFile >= bufferStartSample
  211840. && startSampleInFile < bufferEndSample)
  211841. {
  211842. const int toDo = (int) jmin ((int64) numSamples, bufferEndSample - startSampleInFile);
  211843. int* const l = destSamples[0] + startOffsetInDestBuffer;
  211844. int* const r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  211845. const short* src = (const short*) buffer.getData();
  211846. src += 2 * (startSampleInFile - bufferStartSample);
  211847. for (int i = 0; i < toDo; ++i)
  211848. {
  211849. l[i] = src [i << 1] << 16;
  211850. if (r != 0)
  211851. r[i] = src [(i << 1) + 1] << 16;
  211852. }
  211853. startOffsetInDestBuffer += toDo;
  211854. startSampleInFile += toDo;
  211855. numSamples -= toDo;
  211856. }
  211857. else
  211858. {
  211859. const int framesInBuffer = buffer.getSize() / bytesPerFrame;
  211860. const int frameNeeded = (int) (startSampleInFile / samplesPerFrame);
  211861. if (firstFrameInBuffer + framesInBuffer != frameNeeded)
  211862. {
  211863. device->overlapBuffer->dataLength = 0;
  211864. device->overlapBuffer->startFrame = 0;
  211865. device->overlapBuffer->numFrames = 0;
  211866. device->jitter = false;
  211867. }
  211868. firstFrameInBuffer = frameNeeded;
  211869. lastIndex = 0;
  211870. CDReadBuffer readBuffer (framesInBuffer + 4);
  211871. readBuffer.wantsIndex = indexingEnabled;
  211872. int i;
  211873. for (i = 5; --i >= 0;)
  211874. {
  211875. readBuffer.startFrame = frameNeeded;
  211876. readBuffer.numFrames = framesInBuffer;
  211877. if (device->cdH->readAudio (&readBuffer, (device->jitter) ? device->overlapBuffer : 0))
  211878. break;
  211879. else
  211880. device->overlapBuffer->dataLength = 0;
  211881. }
  211882. if (i >= 0)
  211883. {
  211884. memcpy ((char*) buffer.getData(),
  211885. readBuffer.buffer + readBuffer.dataStartOffset,
  211886. readBuffer.dataLength);
  211887. samplesInBuffer = readBuffer.dataLength >> 2;
  211888. lastIndex = readBuffer.index;
  211889. }
  211890. else
  211891. {
  211892. int* l = destSamples[0] + startOffsetInDestBuffer;
  211893. int* r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  211894. while (--numSamples >= 0)
  211895. {
  211896. *l++ = 0;
  211897. if (r != 0)
  211898. *r++ = 0;
  211899. }
  211900. // sometimes the read fails for just the very last couple of blocks, so
  211901. // we'll ignore and errors in the last half-second of the disk..
  211902. ok = startSampleInFile > (trackStartSamples [getNumTracks()] - 20000);
  211903. break;
  211904. }
  211905. }
  211906. }
  211907. return ok;
  211908. }
  211909. bool AudioCDReader::isCDStillPresent() const
  211910. {
  211911. using namespace CDReaderHelpers;
  211912. TOC toc;
  211913. zerostruct (toc);
  211914. return ((CDDeviceWrapper*) handle)->cdH->readTOC (&toc);
  211915. }
  211916. void AudioCDReader::refreshTrackLengths()
  211917. {
  211918. using namespace CDReaderHelpers;
  211919. trackStartSamples.clear();
  211920. zeromem (audioTracks, sizeof (audioTracks));
  211921. TOC toc;
  211922. zerostruct (toc);
  211923. if (((CDDeviceWrapper*)handle)->cdH->readTOC (&toc))
  211924. {
  211925. int numTracks = 1 + toc.lastTrack - toc.firstTrack;
  211926. for (int i = 0; i <= numTracks; ++i)
  211927. {
  211928. trackStartSamples.add (samplesPerFrame * getAddressOf (&toc.tracks [i]));
  211929. audioTracks [i] = ((toc.tracks[i].ADR & 4) == 0);
  211930. }
  211931. }
  211932. lengthInSamples = getPositionOfTrackStart (getNumTracks());
  211933. }
  211934. bool AudioCDReader::isTrackAudio (int trackNum) const
  211935. {
  211936. return trackNum >= 0 && trackNum < getNumTracks() && audioTracks [trackNum];
  211937. }
  211938. void AudioCDReader::enableIndexScanning (bool b)
  211939. {
  211940. indexingEnabled = b;
  211941. }
  211942. int AudioCDReader::getLastIndex() const
  211943. {
  211944. return lastIndex;
  211945. }
  211946. const int framesPerIndexRead = 4;
  211947. int AudioCDReader::getIndexAt (int samplePos)
  211948. {
  211949. using namespace CDReaderHelpers;
  211950. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  211951. const int frameNeeded = samplePos / samplesPerFrame;
  211952. device->overlapBuffer->dataLength = 0;
  211953. device->overlapBuffer->startFrame = 0;
  211954. device->overlapBuffer->numFrames = 0;
  211955. device->jitter = false;
  211956. firstFrameInBuffer = 0;
  211957. lastIndex = 0;
  211958. CDReadBuffer readBuffer (4 + framesPerIndexRead);
  211959. readBuffer.wantsIndex = true;
  211960. int i;
  211961. for (i = 5; --i >= 0;)
  211962. {
  211963. readBuffer.startFrame = frameNeeded;
  211964. readBuffer.numFrames = framesPerIndexRead;
  211965. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  211966. break;
  211967. }
  211968. if (i >= 0)
  211969. return readBuffer.index;
  211970. return -1;
  211971. }
  211972. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  211973. {
  211974. using namespace CDReaderHelpers;
  211975. Array <int> indexes;
  211976. const int trackStart = getPositionOfTrackStart (trackNumber);
  211977. const int trackEnd = getPositionOfTrackStart (trackNumber + 1);
  211978. bool needToScan = true;
  211979. if (trackEnd - trackStart > 20 * 44100)
  211980. {
  211981. // check the end of the track for indexes before scanning the whole thing
  211982. needToScan = false;
  211983. int pos = jmax (trackStart, trackEnd - 44100 * 5);
  211984. bool seenAnIndex = false;
  211985. while (pos <= trackEnd - samplesPerFrame)
  211986. {
  211987. const int index = getIndexAt (pos);
  211988. if (index == 0)
  211989. {
  211990. // lead-out, so skip back a bit if we've not found any indexes yet..
  211991. if (seenAnIndex)
  211992. break;
  211993. pos -= 44100 * 5;
  211994. if (pos < trackStart)
  211995. break;
  211996. }
  211997. else
  211998. {
  211999. if (index > 0)
  212000. seenAnIndex = true;
  212001. if (index > 1)
  212002. {
  212003. needToScan = true;
  212004. break;
  212005. }
  212006. pos += samplesPerFrame * framesPerIndexRead;
  212007. }
  212008. }
  212009. }
  212010. if (needToScan)
  212011. {
  212012. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  212013. int pos = trackStart;
  212014. int last = -1;
  212015. while (pos < trackEnd - samplesPerFrame * 10)
  212016. {
  212017. const int frameNeeded = pos / samplesPerFrame;
  212018. device->overlapBuffer->dataLength = 0;
  212019. device->overlapBuffer->startFrame = 0;
  212020. device->overlapBuffer->numFrames = 0;
  212021. device->jitter = false;
  212022. firstFrameInBuffer = 0;
  212023. CDReadBuffer readBuffer (4);
  212024. readBuffer.wantsIndex = true;
  212025. int i;
  212026. for (i = 5; --i >= 0;)
  212027. {
  212028. readBuffer.startFrame = frameNeeded;
  212029. readBuffer.numFrames = framesPerIndexRead;
  212030. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  212031. break;
  212032. }
  212033. if (i < 0)
  212034. break;
  212035. if (readBuffer.index > last && readBuffer.index > 1)
  212036. {
  212037. last = readBuffer.index;
  212038. indexes.add (pos);
  212039. }
  212040. pos += samplesPerFrame * framesPerIndexRead;
  212041. }
  212042. indexes.removeValue (trackStart);
  212043. }
  212044. return indexes;
  212045. }
  212046. void AudioCDReader::ejectDisk()
  212047. {
  212048. using namespace CDReaderHelpers;
  212049. ((CDDeviceWrapper*) handle)->cdH->openDrawer (true);
  212050. }
  212051. #endif
  212052. #if JUCE_USE_CDBURNER
  212053. static IDiscRecorder* enumCDBurners (StringArray* list, int indexToOpen, IDiscMaster** master)
  212054. {
  212055. CoInitialize (0);
  212056. IDiscMaster* dm;
  212057. IDiscRecorder* result = 0;
  212058. if (SUCCEEDED (CoCreateInstance (CLSID_MSDiscMasterObj, 0,
  212059. CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER,
  212060. IID_IDiscMaster,
  212061. (void**) &dm)))
  212062. {
  212063. if (SUCCEEDED (dm->Open()))
  212064. {
  212065. IEnumDiscRecorders* drEnum = 0;
  212066. if (SUCCEEDED (dm->EnumDiscRecorders (&drEnum)))
  212067. {
  212068. IDiscRecorder* dr = 0;
  212069. DWORD dummy;
  212070. int index = 0;
  212071. while (drEnum->Next (1, &dr, &dummy) == S_OK)
  212072. {
  212073. if (indexToOpen == index)
  212074. {
  212075. result = dr;
  212076. break;
  212077. }
  212078. else if (list != 0)
  212079. {
  212080. BSTR path;
  212081. if (SUCCEEDED (dr->GetPath (&path)))
  212082. list->add ((const WCHAR*) path);
  212083. }
  212084. ++index;
  212085. dr->Release();
  212086. }
  212087. drEnum->Release();
  212088. }
  212089. if (master == 0)
  212090. dm->Close();
  212091. }
  212092. if (master != 0)
  212093. *master = dm;
  212094. else
  212095. dm->Release();
  212096. }
  212097. return result;
  212098. }
  212099. class AudioCDBurner::Pimpl : public ComBaseClassHelper <IDiscMasterProgressEvents>,
  212100. public Timer
  212101. {
  212102. public:
  212103. Pimpl (AudioCDBurner& owner_, IDiscMaster* discMaster_, IDiscRecorder* discRecorder_)
  212104. : owner (owner_), discMaster (discMaster_), discRecorder (discRecorder_), redbook (0),
  212105. listener (0), progress (0), shouldCancel (false)
  212106. {
  212107. HRESULT hr = discMaster->SetActiveDiscMasterFormat (IID_IRedbookDiscMaster, (void**) &redbook);
  212108. jassert (SUCCEEDED (hr));
  212109. hr = discMaster->SetActiveDiscRecorder (discRecorder);
  212110. //jassert (SUCCEEDED (hr));
  212111. lastState = getDiskState();
  212112. startTimer (2000);
  212113. }
  212114. ~Pimpl() {}
  212115. void releaseObjects()
  212116. {
  212117. discRecorder->Close();
  212118. if (redbook != 0)
  212119. redbook->Release();
  212120. discRecorder->Release();
  212121. discMaster->Release();
  212122. Release();
  212123. }
  212124. HRESULT __stdcall QueryCancel (boolean* pbCancel)
  212125. {
  212126. if (listener != 0 && ! shouldCancel)
  212127. shouldCancel = listener->audioCDBurnProgress (progress);
  212128. *pbCancel = shouldCancel;
  212129. return S_OK;
  212130. }
  212131. HRESULT __stdcall NotifyBlockProgress (long nCompleted, long nTotal)
  212132. {
  212133. progress = nCompleted / (float) nTotal;
  212134. shouldCancel = listener != 0 && listener->audioCDBurnProgress (progress);
  212135. return E_NOTIMPL;
  212136. }
  212137. HRESULT __stdcall NotifyPnPActivity (void) { return E_NOTIMPL; }
  212138. HRESULT __stdcall NotifyAddProgress (long /*nCompletedSteps*/, long /*nTotalSteps*/) { return E_NOTIMPL; }
  212139. HRESULT __stdcall NotifyTrackProgress (long /*nCurrentTrack*/, long /*nTotalTracks*/) { return E_NOTIMPL; }
  212140. HRESULT __stdcall NotifyPreparingBurn (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  212141. HRESULT __stdcall NotifyClosingDisc (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  212142. HRESULT __stdcall NotifyBurnComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  212143. HRESULT __stdcall NotifyEraseComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  212144. class ScopedDiscOpener
  212145. {
  212146. public:
  212147. ScopedDiscOpener (Pimpl& p) : pimpl (p) { pimpl.discRecorder->OpenExclusive(); }
  212148. ~ScopedDiscOpener() { pimpl.discRecorder->Close(); }
  212149. private:
  212150. Pimpl& pimpl;
  212151. ScopedDiscOpener (const ScopedDiscOpener&);
  212152. ScopedDiscOpener& operator= (const ScopedDiscOpener&);
  212153. };
  212154. DiskState getDiskState()
  212155. {
  212156. const ScopedDiscOpener opener (*this);
  212157. long type, flags;
  212158. HRESULT hr = discRecorder->QueryMediaType (&type, &flags);
  212159. if (FAILED (hr))
  212160. return unknown;
  212161. if (type != 0 && (flags & MEDIA_WRITABLE) != 0)
  212162. return writableDiskPresent;
  212163. if (type == 0)
  212164. return noDisc;
  212165. else
  212166. return readOnlyDiskPresent;
  212167. }
  212168. int getIntProperty (const LPOLESTR name, const int defaultReturn) const
  212169. {
  212170. ComSmartPtr<IPropertyStorage> prop;
  212171. if (FAILED (discRecorder->GetRecorderProperties (prop.resetAndGetPointerAddress())))
  212172. return defaultReturn;
  212173. PROPSPEC iPropSpec;
  212174. iPropSpec.ulKind = PRSPEC_LPWSTR;
  212175. iPropSpec.lpwstr = name;
  212176. PROPVARIANT iPropVariant;
  212177. return FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant))
  212178. ? defaultReturn : (int) iPropVariant.lVal;
  212179. }
  212180. bool setIntProperty (const LPOLESTR name, const int value) const
  212181. {
  212182. ComSmartPtr<IPropertyStorage> prop;
  212183. if (FAILED (discRecorder->GetRecorderProperties (prop.resetAndGetPointerAddress())))
  212184. return false;
  212185. PROPSPEC iPropSpec;
  212186. iPropSpec.ulKind = PRSPEC_LPWSTR;
  212187. iPropSpec.lpwstr = name;
  212188. PROPVARIANT iPropVariant;
  212189. if (FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant)))
  212190. return false;
  212191. iPropVariant.lVal = (long) value;
  212192. return SUCCEEDED (prop->WriteMultiple (1, &iPropSpec, &iPropVariant, iPropVariant.vt))
  212193. && SUCCEEDED (discRecorder->SetRecorderProperties (prop));
  212194. }
  212195. void timerCallback()
  212196. {
  212197. const DiskState state = getDiskState();
  212198. if (state != lastState)
  212199. {
  212200. lastState = state;
  212201. owner.sendChangeMessage (&owner);
  212202. }
  212203. }
  212204. AudioCDBurner& owner;
  212205. DiskState lastState;
  212206. IDiscMaster* discMaster;
  212207. IDiscRecorder* discRecorder;
  212208. IRedbookDiscMaster* redbook;
  212209. AudioCDBurner::BurnProgressListener* listener;
  212210. float progress;
  212211. bool shouldCancel;
  212212. };
  212213. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  212214. {
  212215. IDiscMaster* discMaster = 0;
  212216. IDiscRecorder* discRecorder = enumCDBurners (0, deviceIndex, &discMaster);
  212217. if (discRecorder != 0)
  212218. pimpl = new Pimpl (*this, discMaster, discRecorder);
  212219. }
  212220. AudioCDBurner::~AudioCDBurner()
  212221. {
  212222. if (pimpl != 0)
  212223. pimpl.release()->releaseObjects();
  212224. }
  212225. const StringArray AudioCDBurner::findAvailableDevices()
  212226. {
  212227. StringArray devs;
  212228. enumCDBurners (&devs, -1, 0);
  212229. return devs;
  212230. }
  212231. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  212232. {
  212233. ScopedPointer<AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  212234. if (b->pimpl == 0)
  212235. b = 0;
  212236. return b.release();
  212237. }
  212238. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  212239. {
  212240. return pimpl->getDiskState();
  212241. }
  212242. bool AudioCDBurner::isDiskPresent() const
  212243. {
  212244. return getDiskState() == writableDiskPresent;
  212245. }
  212246. bool AudioCDBurner::openTray()
  212247. {
  212248. const Pimpl::ScopedDiscOpener opener (*pimpl);
  212249. return SUCCEEDED (pimpl->discRecorder->Eject());
  212250. }
  212251. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  212252. {
  212253. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  212254. DiskState oldState = getDiskState();
  212255. DiskState newState = oldState;
  212256. while (newState == oldState && Time::currentTimeMillis() < timeout)
  212257. {
  212258. newState = getDiskState();
  212259. Thread::sleep (jmin (250, (int) (timeout - Time::currentTimeMillis())));
  212260. }
  212261. return newState;
  212262. }
  212263. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  212264. {
  212265. Array<int> results;
  212266. const int maxSpeed = pimpl->getIntProperty (L"MaxWriteSpeed", 1);
  212267. const int speeds[] = { 1, 2, 4, 8, 12, 16, 20, 24, 32, 40, 64, 80 };
  212268. for (int i = 0; i < numElementsInArray (speeds); ++i)
  212269. if (speeds[i] <= maxSpeed)
  212270. results.add (speeds[i]);
  212271. results.addIfNotAlreadyThere (maxSpeed);
  212272. return results;
  212273. }
  212274. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  212275. {
  212276. if (pimpl->getIntProperty (L"BufferUnderrunFreeCapable", 0) == 0)
  212277. return false;
  212278. pimpl->setIntProperty (L"EnableBufferUnderrunFree", shouldBeEnabled ? -1 : 0);
  212279. return pimpl->getIntProperty (L"EnableBufferUnderrunFree", 0) != 0;
  212280. }
  212281. int AudioCDBurner::getNumAvailableAudioBlocks() const
  212282. {
  212283. long blocksFree = 0;
  212284. pimpl->redbook->GetAvailableAudioTrackBlocks (&blocksFree);
  212285. return blocksFree;
  212286. }
  212287. const String AudioCDBurner::burn (AudioCDBurner::BurnProgressListener* listener, bool ejectDiscAfterwards,
  212288. bool performFakeBurnForTesting, int writeSpeed)
  212289. {
  212290. pimpl->setIntProperty (L"WriteSpeed", writeSpeed > 0 ? writeSpeed : -1);
  212291. pimpl->listener = listener;
  212292. pimpl->progress = 0;
  212293. pimpl->shouldCancel = false;
  212294. UINT_PTR cookie;
  212295. HRESULT hr = pimpl->discMaster->ProgressAdvise ((AudioCDBurner::Pimpl*) pimpl, &cookie);
  212296. hr = pimpl->discMaster->RecordDisc (performFakeBurnForTesting,
  212297. ejectDiscAfterwards);
  212298. String error;
  212299. if (hr != S_OK)
  212300. {
  212301. const char* e = "Couldn't open or write to the CD device";
  212302. if (hr == IMAPI_E_USERABORT)
  212303. e = "User cancelled the write operation";
  212304. else if (hr == IMAPI_E_MEDIUM_NOTPRESENT || hr == IMAPI_E_TRACKOPEN)
  212305. e = "No Disk present";
  212306. error = e;
  212307. }
  212308. pimpl->discMaster->ProgressUnadvise (cookie);
  212309. pimpl->listener = 0;
  212310. return error;
  212311. }
  212312. bool AudioCDBurner::addAudioTrack (AudioSource* audioSource, int numSamples)
  212313. {
  212314. if (audioSource == 0)
  212315. return false;
  212316. ScopedPointer<AudioSource> source (audioSource);
  212317. long bytesPerBlock;
  212318. HRESULT hr = pimpl->redbook->GetAudioBlockSize (&bytesPerBlock);
  212319. const int samplesPerBlock = bytesPerBlock / 4;
  212320. bool ok = true;
  212321. hr = pimpl->redbook->CreateAudioTrack ((long) numSamples / (bytesPerBlock * 4));
  212322. HeapBlock <byte> buffer (bytesPerBlock);
  212323. AudioSampleBuffer sourceBuffer (2, samplesPerBlock);
  212324. int samplesDone = 0;
  212325. source->prepareToPlay (samplesPerBlock, 44100.0);
  212326. while (ok)
  212327. {
  212328. {
  212329. AudioSourceChannelInfo info;
  212330. info.buffer = &sourceBuffer;
  212331. info.numSamples = samplesPerBlock;
  212332. info.startSample = 0;
  212333. sourceBuffer.clear();
  212334. source->getNextAudioBlock (info);
  212335. }
  212336. zeromem (buffer, bytesPerBlock);
  212337. typedef AudioData::Pointer <AudioData::Int16, AudioData::LittleEndian,
  212338. AudioData::Interleaved, AudioData::NonConst> CDSampleFormat;
  212339. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian,
  212340. AudioData::NonInterleaved, AudioData::Const> SourceSampleFormat;
  212341. CDSampleFormat left (buffer, 2);
  212342. left.convertSamples (SourceSampleFormat (sourceBuffer.getSampleData (0)), samplesPerBlock);
  212343. CDSampleFormat right (buffer + 2, 2);
  212344. right.convertSamples (SourceSampleFormat (sourceBuffer.getSampleData (1)), samplesPerBlock);
  212345. hr = pimpl->redbook->AddAudioTrackBlocks (buffer, bytesPerBlock);
  212346. if (FAILED (hr))
  212347. ok = false;
  212348. samplesDone += samplesPerBlock;
  212349. if (samplesDone >= numSamples)
  212350. break;
  212351. }
  212352. hr = pimpl->redbook->CloseAudioTrack();
  212353. return ok && hr == S_OK;
  212354. }
  212355. #endif
  212356. #endif
  212357. /*** End of inlined file: juce_win32_AudioCDReader.cpp ***/
  212358. /*** Start of inlined file: juce_win32_Midi.cpp ***/
  212359. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  212360. // compiled on its own).
  212361. #if JUCE_INCLUDED_FILE
  212362. class MidiInCollector
  212363. {
  212364. public:
  212365. MidiInCollector (MidiInput* const input_,
  212366. MidiInputCallback& callback_)
  212367. : deviceHandle (0),
  212368. input (input_),
  212369. callback (callback_),
  212370. concatenator (4096),
  212371. isStarted (false),
  212372. startTime (0)
  212373. {
  212374. }
  212375. ~MidiInCollector()
  212376. {
  212377. stop();
  212378. if (deviceHandle != 0)
  212379. {
  212380. int count = 5;
  212381. while (--count >= 0)
  212382. {
  212383. if (midiInClose (deviceHandle) == MMSYSERR_NOERROR)
  212384. break;
  212385. Sleep (20);
  212386. }
  212387. }
  212388. }
  212389. void handleMessage (const uint32 message, const uint32 timeStamp)
  212390. {
  212391. if ((message & 0xff) >= 0x80 && isStarted)
  212392. {
  212393. concatenator.pushMidiData (&message, 3, convertTimeStamp (timeStamp), input, callback);
  212394. writeFinishedBlocks();
  212395. }
  212396. }
  212397. void handleSysEx (MIDIHDR* const hdr, const uint32 timeStamp)
  212398. {
  212399. if (isStarted)
  212400. {
  212401. concatenator.pushMidiData (hdr->lpData, hdr->dwBytesRecorded, convertTimeStamp (timeStamp), input, callback);
  212402. writeFinishedBlocks();
  212403. }
  212404. }
  212405. void start()
  212406. {
  212407. jassert (deviceHandle != 0);
  212408. if (deviceHandle != 0 && ! isStarted)
  212409. {
  212410. activeMidiCollectors.addIfNotAlreadyThere (this);
  212411. for (int i = 0; i < (int) numHeaders; ++i)
  212412. headers[i].write (deviceHandle);
  212413. startTime = Time::getMillisecondCounter();
  212414. MMRESULT res = midiInStart (deviceHandle);
  212415. if (res == MMSYSERR_NOERROR)
  212416. {
  212417. concatenator.reset();
  212418. isStarted = true;
  212419. }
  212420. else
  212421. {
  212422. unprepareAllHeaders();
  212423. }
  212424. }
  212425. }
  212426. void stop()
  212427. {
  212428. if (isStarted)
  212429. {
  212430. isStarted = false;
  212431. midiInReset (deviceHandle);
  212432. midiInStop (deviceHandle);
  212433. activeMidiCollectors.removeValue (this);
  212434. unprepareAllHeaders();
  212435. concatenator.reset();
  212436. }
  212437. }
  212438. static void CALLBACK midiInCallback (HMIDIIN, UINT uMsg, DWORD_PTR dwInstance, DWORD_PTR midiMessage, DWORD_PTR timeStamp)
  212439. {
  212440. MidiInCollector* const collector = reinterpret_cast <MidiInCollector*> (dwInstance);
  212441. if (activeMidiCollectors.contains (collector))
  212442. {
  212443. if (uMsg == MIM_DATA)
  212444. collector->handleMessage ((uint32) midiMessage, (uint32) timeStamp);
  212445. else if (uMsg == MIM_LONGDATA)
  212446. collector->handleSysEx ((MIDIHDR*) midiMessage, (uint32) timeStamp);
  212447. }
  212448. }
  212449. juce_UseDebuggingNewOperator
  212450. HMIDIIN deviceHandle;
  212451. private:
  212452. static Array <MidiInCollector*, CriticalSection> activeMidiCollectors;
  212453. MidiInput* input;
  212454. MidiInputCallback& callback;
  212455. MidiDataConcatenator concatenator;
  212456. bool volatile isStarted;
  212457. uint32 startTime;
  212458. class MidiHeader
  212459. {
  212460. public:
  212461. MidiHeader()
  212462. {
  212463. zerostruct (hdr);
  212464. hdr.lpData = data;
  212465. hdr.dwBufferLength = numElementsInArray (data);
  212466. }
  212467. void write (HMIDIIN deviceHandle)
  212468. {
  212469. hdr.dwBytesRecorded = 0;
  212470. MMRESULT res = midiInPrepareHeader (deviceHandle, &hdr, sizeof (hdr));
  212471. res = midiInAddBuffer (deviceHandle, &hdr, sizeof (hdr));
  212472. }
  212473. void writeIfFinished (HMIDIIN deviceHandle)
  212474. {
  212475. if ((hdr.dwFlags & WHDR_DONE) != 0)
  212476. {
  212477. MMRESULT res = midiInUnprepareHeader (deviceHandle, &hdr, sizeof (hdr));
  212478. (void) res;
  212479. write (deviceHandle);
  212480. }
  212481. }
  212482. void unprepare (HMIDIIN deviceHandle)
  212483. {
  212484. if ((hdr.dwFlags & WHDR_DONE) != 0)
  212485. {
  212486. int c = 10;
  212487. while (--c >= 0 && midiInUnprepareHeader (deviceHandle, &hdr, sizeof (hdr)) == MIDIERR_STILLPLAYING)
  212488. Thread::sleep (20);
  212489. jassert (c >= 0);
  212490. }
  212491. }
  212492. private:
  212493. MIDIHDR hdr;
  212494. char data [256];
  212495. MidiHeader (const MidiHeader&);
  212496. MidiHeader& operator= (const MidiHeader&);
  212497. };
  212498. enum { numHeaders = 32 };
  212499. MidiHeader headers [numHeaders];
  212500. void writeFinishedBlocks()
  212501. {
  212502. for (int i = 0; i < (int) numHeaders; ++i)
  212503. headers[i].writeIfFinished (deviceHandle);
  212504. }
  212505. void unprepareAllHeaders()
  212506. {
  212507. for (int i = 0; i < (int) numHeaders; ++i)
  212508. headers[i].unprepare (deviceHandle);
  212509. }
  212510. double convertTimeStamp (uint32 timeStamp)
  212511. {
  212512. timeStamp += startTime;
  212513. const uint32 now = Time::getMillisecondCounter();
  212514. if (timeStamp > now)
  212515. {
  212516. if (timeStamp > now + 2)
  212517. --startTime;
  212518. timeStamp = now;
  212519. }
  212520. return timeStamp * 0.001;
  212521. }
  212522. MidiInCollector (const MidiInCollector&);
  212523. MidiInCollector& operator= (const MidiInCollector&);
  212524. };
  212525. Array <MidiInCollector*, CriticalSection> MidiInCollector::activeMidiCollectors;
  212526. const StringArray MidiInput::getDevices()
  212527. {
  212528. StringArray s;
  212529. const int num = midiInGetNumDevs();
  212530. for (int i = 0; i < num; ++i)
  212531. {
  212532. MIDIINCAPS mc;
  212533. zerostruct (mc);
  212534. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212535. s.add (String (mc.szPname, sizeof (mc.szPname)));
  212536. }
  212537. return s;
  212538. }
  212539. int MidiInput::getDefaultDeviceIndex()
  212540. {
  212541. return 0;
  212542. }
  212543. MidiInput* MidiInput::openDevice (const int index, MidiInputCallback* const callback)
  212544. {
  212545. if (callback == 0)
  212546. return 0;
  212547. UINT deviceId = MIDI_MAPPER;
  212548. int n = 0;
  212549. String name;
  212550. const int num = midiInGetNumDevs();
  212551. for (int i = 0; i < num; ++i)
  212552. {
  212553. MIDIINCAPS mc;
  212554. zerostruct (mc);
  212555. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212556. {
  212557. if (index == n)
  212558. {
  212559. deviceId = i;
  212560. name = String (mc.szPname, numElementsInArray (mc.szPname));
  212561. break;
  212562. }
  212563. ++n;
  212564. }
  212565. }
  212566. ScopedPointer <MidiInput> in (new MidiInput (name));
  212567. ScopedPointer <MidiInCollector> collector (new MidiInCollector (in, *callback));
  212568. HMIDIIN h;
  212569. HRESULT err = midiInOpen (&h, deviceId,
  212570. (DWORD_PTR) &MidiInCollector::midiInCallback,
  212571. (DWORD_PTR) (MidiInCollector*) collector,
  212572. CALLBACK_FUNCTION);
  212573. if (err == MMSYSERR_NOERROR)
  212574. {
  212575. collector->deviceHandle = h;
  212576. in->internal = collector.release();
  212577. return in.release();
  212578. }
  212579. return 0;
  212580. }
  212581. MidiInput::MidiInput (const String& name_)
  212582. : name (name_),
  212583. internal (0)
  212584. {
  212585. }
  212586. MidiInput::~MidiInput()
  212587. {
  212588. delete static_cast <MidiInCollector*> (internal);
  212589. }
  212590. void MidiInput::start()
  212591. {
  212592. static_cast <MidiInCollector*> (internal)->start();
  212593. }
  212594. void MidiInput::stop()
  212595. {
  212596. static_cast <MidiInCollector*> (internal)->stop();
  212597. }
  212598. struct MidiOutHandle
  212599. {
  212600. int refCount;
  212601. UINT deviceId;
  212602. HMIDIOUT handle;
  212603. static Array<MidiOutHandle*> activeHandles;
  212604. juce_UseDebuggingNewOperator
  212605. };
  212606. Array<MidiOutHandle*> MidiOutHandle::activeHandles;
  212607. const StringArray MidiOutput::getDevices()
  212608. {
  212609. StringArray s;
  212610. const int num = midiOutGetNumDevs();
  212611. for (int i = 0; i < num; ++i)
  212612. {
  212613. MIDIOUTCAPS mc;
  212614. zerostruct (mc);
  212615. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212616. s.add (String (mc.szPname, sizeof (mc.szPname)));
  212617. }
  212618. return s;
  212619. }
  212620. int MidiOutput::getDefaultDeviceIndex()
  212621. {
  212622. const int num = midiOutGetNumDevs();
  212623. int n = 0;
  212624. for (int i = 0; i < num; ++i)
  212625. {
  212626. MIDIOUTCAPS mc;
  212627. zerostruct (mc);
  212628. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212629. {
  212630. if ((mc.wTechnology & MOD_MAPPER) != 0)
  212631. return n;
  212632. ++n;
  212633. }
  212634. }
  212635. return 0;
  212636. }
  212637. MidiOutput* MidiOutput::openDevice (int index)
  212638. {
  212639. UINT deviceId = MIDI_MAPPER;
  212640. const int num = midiOutGetNumDevs();
  212641. int i, n = 0;
  212642. for (i = 0; i < num; ++i)
  212643. {
  212644. MIDIOUTCAPS mc;
  212645. zerostruct (mc);
  212646. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212647. {
  212648. // use the microsoft sw synth as a default - best not to allow deviceId
  212649. // to be MIDI_MAPPER, or else device sharing breaks
  212650. if (String (mc.szPname, sizeof (mc.szPname)).containsIgnoreCase ("microsoft"))
  212651. deviceId = i;
  212652. if (index == n)
  212653. {
  212654. deviceId = i;
  212655. break;
  212656. }
  212657. ++n;
  212658. }
  212659. }
  212660. for (i = MidiOutHandle::activeHandles.size(); --i >= 0;)
  212661. {
  212662. MidiOutHandle* const han = MidiOutHandle::activeHandles.getUnchecked(i);
  212663. if (han != 0 && han->deviceId == deviceId)
  212664. {
  212665. han->refCount++;
  212666. MidiOutput* const out = new MidiOutput();
  212667. out->internal = han;
  212668. return out;
  212669. }
  212670. }
  212671. for (i = 4; --i >= 0;)
  212672. {
  212673. HMIDIOUT h = 0;
  212674. MMRESULT res = midiOutOpen (&h, deviceId, 0, 0, CALLBACK_NULL);
  212675. if (res == MMSYSERR_NOERROR)
  212676. {
  212677. MidiOutHandle* const han = new MidiOutHandle();
  212678. han->deviceId = deviceId;
  212679. han->refCount = 1;
  212680. han->handle = h;
  212681. MidiOutHandle::activeHandles.add (han);
  212682. MidiOutput* const out = new MidiOutput();
  212683. out->internal = han;
  212684. return out;
  212685. }
  212686. else if (res == MMSYSERR_ALLOCATED)
  212687. {
  212688. Sleep (100);
  212689. }
  212690. else
  212691. {
  212692. break;
  212693. }
  212694. }
  212695. return 0;
  212696. }
  212697. MidiOutput::~MidiOutput()
  212698. {
  212699. MidiOutHandle* const h = static_cast <MidiOutHandle*> (internal);
  212700. if (MidiOutHandle::activeHandles.contains (h) && --(h->refCount) == 0)
  212701. {
  212702. midiOutClose (h->handle);
  212703. MidiOutHandle::activeHandles.removeValue (h);
  212704. delete h;
  212705. }
  212706. }
  212707. void MidiOutput::reset()
  212708. {
  212709. const MidiOutHandle* const h = static_cast <const MidiOutHandle*> (internal);
  212710. midiOutReset (h->handle);
  212711. }
  212712. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  212713. {
  212714. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  212715. DWORD n;
  212716. if (midiOutGetVolume (handle->handle, &n) == MMSYSERR_NOERROR)
  212717. {
  212718. const unsigned short* const nn = reinterpret_cast<const unsigned short*> (&n);
  212719. rightVol = nn[0] / (float) 0xffff;
  212720. leftVol = nn[1] / (float) 0xffff;
  212721. return true;
  212722. }
  212723. else
  212724. {
  212725. rightVol = leftVol = 1.0f;
  212726. return false;
  212727. }
  212728. }
  212729. void MidiOutput::setVolume (float leftVol, float rightVol)
  212730. {
  212731. const MidiOutHandle* const handle = static_cast <MidiOutHandle*> (internal);
  212732. DWORD n;
  212733. unsigned short* const nn = reinterpret_cast<unsigned short*> (&n);
  212734. nn[0] = (unsigned short) jlimit (0, 0xffff, (int) (rightVol * 0xffff));
  212735. nn[1] = (unsigned short) jlimit (0, 0xffff, (int) (leftVol * 0xffff));
  212736. midiOutSetVolume (handle->handle, n);
  212737. }
  212738. void MidiOutput::sendMessageNow (const MidiMessage& message)
  212739. {
  212740. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  212741. if (message.getRawDataSize() > 3
  212742. || message.isSysEx())
  212743. {
  212744. MIDIHDR h;
  212745. zerostruct (h);
  212746. h.lpData = (char*) message.getRawData();
  212747. h.dwBufferLength = message.getRawDataSize();
  212748. h.dwBytesRecorded = message.getRawDataSize();
  212749. if (midiOutPrepareHeader (handle->handle, &h, sizeof (MIDIHDR)) == MMSYSERR_NOERROR)
  212750. {
  212751. MMRESULT res = midiOutLongMsg (handle->handle, &h, sizeof (MIDIHDR));
  212752. if (res == MMSYSERR_NOERROR)
  212753. {
  212754. while ((h.dwFlags & MHDR_DONE) == 0)
  212755. Sleep (1);
  212756. int count = 500; // 1 sec timeout
  212757. while (--count >= 0)
  212758. {
  212759. res = midiOutUnprepareHeader (handle->handle, &h, sizeof (MIDIHDR));
  212760. if (res == MIDIERR_STILLPLAYING)
  212761. Sleep (2);
  212762. else
  212763. break;
  212764. }
  212765. }
  212766. }
  212767. }
  212768. else
  212769. {
  212770. midiOutShortMsg (handle->handle,
  212771. *(unsigned int*) message.getRawData());
  212772. }
  212773. }
  212774. #endif
  212775. /*** End of inlined file: juce_win32_Midi.cpp ***/
  212776. /*** Start of inlined file: juce_win32_ASIO.cpp ***/
  212777. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  212778. // compiled on its own).
  212779. #if JUCE_INCLUDED_FILE && JUCE_ASIO
  212780. #undef WINDOWS
  212781. // #define ASIO_DEBUGGING 1
  212782. #if ASIO_DEBUGGING
  212783. #define log(a) { Logger::writeToLog (a); DBG (a) }
  212784. #else
  212785. #define log(a) {}
  212786. #endif
  212787. #define JUCE_ASIOCALLBACK __cdecl
  212788. #if ASIO_DEBUGGING
  212789. static void logError (const String& context, long error)
  212790. {
  212791. String err ("unknown error");
  212792. if (error == ASE_NotPresent) err = "Not Present";
  212793. else if (error == ASE_HWMalfunction) err = "Hardware Malfunction";
  212794. else if (error == ASE_InvalidParameter) err = "Invalid Parameter";
  212795. else if (error == ASE_InvalidMode) err = "Invalid Mode";
  212796. else if (error == ASE_SPNotAdvancing) err = "Sample position not advancing";
  212797. else if (error == ASE_NoClock) err = "No Clock";
  212798. else if (error == ASE_NoMemory) err = "Out of memory";
  212799. log ("!!error: " + context + " - " + err);
  212800. }
  212801. #else
  212802. #define logError(a, b) {}
  212803. #endif
  212804. class ASIOAudioIODevice;
  212805. static ASIOAudioIODevice* volatile currentASIODev[3] = { 0, 0, 0 };
  212806. static const int maxASIOChannels = 160;
  212807. class JUCE_API ASIOAudioIODevice : public AudioIODevice,
  212808. private Timer
  212809. {
  212810. public:
  212811. Component ourWindow;
  212812. ASIOAudioIODevice (const String& name_, const CLSID classId_, const int slotNumber,
  212813. const String& optionalDllForDirectLoading_)
  212814. : AudioIODevice (name_, "ASIO"),
  212815. asioObject (0),
  212816. classId (classId_),
  212817. optionalDllForDirectLoading (optionalDllForDirectLoading_),
  212818. currentBitDepth (16),
  212819. currentSampleRate (0),
  212820. isOpen_ (false),
  212821. isStarted (false),
  212822. postOutput (true),
  212823. insideControlPanelModalLoop (false),
  212824. shouldUsePreferredSize (false)
  212825. {
  212826. name = name_;
  212827. ourWindow.addToDesktop (0);
  212828. windowHandle = ourWindow.getWindowHandle();
  212829. jassert (currentASIODev [slotNumber] == 0);
  212830. currentASIODev [slotNumber] = this;
  212831. openDevice();
  212832. }
  212833. ~ASIOAudioIODevice()
  212834. {
  212835. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  212836. if (currentASIODev[i] == this)
  212837. currentASIODev[i] = 0;
  212838. close();
  212839. log ("ASIO - exiting");
  212840. removeCurrentDriver();
  212841. }
  212842. void updateSampleRates()
  212843. {
  212844. // find a list of sample rates..
  212845. const double possibleSampleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  212846. sampleRates.clear();
  212847. if (asioObject != 0)
  212848. {
  212849. for (int index = 0; index < numElementsInArray (possibleSampleRates); ++index)
  212850. {
  212851. const long err = asioObject->canSampleRate (possibleSampleRates[index]);
  212852. if (err == 0)
  212853. {
  212854. sampleRates.add ((int) possibleSampleRates[index]);
  212855. log ("rate: " + String ((int) possibleSampleRates[index]));
  212856. }
  212857. else if (err != ASE_NoClock)
  212858. {
  212859. logError ("CanSampleRate", err);
  212860. }
  212861. }
  212862. if (sampleRates.size() == 0)
  212863. {
  212864. double cr = 0;
  212865. const long err = asioObject->getSampleRate (&cr);
  212866. log ("No sample rates supported - current rate: " + String ((int) cr));
  212867. if (err == 0)
  212868. sampleRates.add ((int) cr);
  212869. }
  212870. }
  212871. }
  212872. const StringArray getOutputChannelNames() { return outputChannelNames; }
  212873. const StringArray getInputChannelNames() { return inputChannelNames; }
  212874. int getNumSampleRates() { return sampleRates.size(); }
  212875. double getSampleRate (int index) { return sampleRates [index]; }
  212876. int getNumBufferSizesAvailable() { return bufferSizes.size(); }
  212877. int getBufferSizeSamples (int index) { return bufferSizes [index]; }
  212878. int getDefaultBufferSize() { return preferredSize; }
  212879. const String open (const BigInteger& inputChannels,
  212880. const BigInteger& outputChannels,
  212881. double sr,
  212882. int bufferSizeSamples)
  212883. {
  212884. close();
  212885. currentCallback = 0;
  212886. if (bufferSizeSamples <= 0)
  212887. shouldUsePreferredSize = true;
  212888. if (asioObject == 0 || ! isASIOOpen)
  212889. {
  212890. log ("Warning: device not open");
  212891. const String err (openDevice());
  212892. if (asioObject == 0 || ! isASIOOpen)
  212893. return err;
  212894. }
  212895. isStarted = false;
  212896. bufferIndex = -1;
  212897. long err = 0;
  212898. long newPreferredSize = 0;
  212899. // if the preferred size has just changed, assume it's a control panel thing and use it as the new value.
  212900. minSize = 0;
  212901. maxSize = 0;
  212902. newPreferredSize = 0;
  212903. granularity = 0;
  212904. if (asioObject->getBufferSize (&minSize, &maxSize, &newPreferredSize, &granularity) == 0)
  212905. {
  212906. if (preferredSize != 0 && newPreferredSize != 0 && newPreferredSize != preferredSize)
  212907. shouldUsePreferredSize = true;
  212908. preferredSize = newPreferredSize;
  212909. }
  212910. // unfortunate workaround for certain manufacturers whose drivers crash horribly if you make
  212911. // dynamic changes to the buffer size...
  212912. shouldUsePreferredSize = shouldUsePreferredSize
  212913. || getName().containsIgnoreCase ("Digidesign");
  212914. if (shouldUsePreferredSize)
  212915. {
  212916. log ("Using preferred size for buffer..");
  212917. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  212918. {
  212919. bufferSizeSamples = preferredSize;
  212920. }
  212921. else
  212922. {
  212923. bufferSizeSamples = 1024;
  212924. logError ("GetBufferSize1", err);
  212925. }
  212926. shouldUsePreferredSize = false;
  212927. }
  212928. int sampleRate = roundDoubleToInt (sr);
  212929. currentSampleRate = sampleRate;
  212930. currentBlockSizeSamples = bufferSizeSamples;
  212931. currentChansOut.clear();
  212932. currentChansIn.clear();
  212933. zeromem (inBuffers, sizeof (inBuffers));
  212934. zeromem (outBuffers, sizeof (outBuffers));
  212935. updateSampleRates();
  212936. if (sampleRate == 0 || (sampleRates.size() > 0 && ! sampleRates.contains (sampleRate)))
  212937. sampleRate = sampleRates[0];
  212938. jassert (sampleRate != 0);
  212939. if (sampleRate == 0)
  212940. sampleRate = 44100;
  212941. long numSources = 32;
  212942. ASIOClockSource clocks[32];
  212943. zeromem (clocks, sizeof (clocks));
  212944. asioObject->getClockSources (clocks, &numSources);
  212945. bool isSourceSet = false;
  212946. // careful not to remove this loop because it does more than just logging!
  212947. int i;
  212948. for (i = 0; i < numSources; ++i)
  212949. {
  212950. String s ("clock: ");
  212951. s += clocks[i].name;
  212952. if (clocks[i].isCurrentSource)
  212953. {
  212954. isSourceSet = true;
  212955. s << " (cur)";
  212956. }
  212957. log (s);
  212958. }
  212959. if (numSources > 1 && ! isSourceSet)
  212960. {
  212961. log ("setting clock source");
  212962. asioObject->setClockSource (clocks[0].index);
  212963. Thread::sleep (20);
  212964. }
  212965. else
  212966. {
  212967. if (numSources == 0)
  212968. {
  212969. log ("ASIO - no clock sources!");
  212970. }
  212971. }
  212972. double cr = 0;
  212973. err = asioObject->getSampleRate (&cr);
  212974. if (err == 0)
  212975. {
  212976. currentSampleRate = cr;
  212977. }
  212978. else
  212979. {
  212980. logError ("GetSampleRate", err);
  212981. currentSampleRate = 0;
  212982. }
  212983. error = String::empty;
  212984. needToReset = false;
  212985. isReSync = false;
  212986. err = 0;
  212987. bool buffersCreated = false;
  212988. if (currentSampleRate != sampleRate)
  212989. {
  212990. log ("ASIO samplerate: " + String (currentSampleRate) + " to " + String (sampleRate));
  212991. err = asioObject->setSampleRate (sampleRate);
  212992. if (err == ASE_NoClock && numSources > 0)
  212993. {
  212994. log ("trying to set a clock source..");
  212995. Thread::sleep (10);
  212996. err = asioObject->setClockSource (clocks[0].index);
  212997. if (err != 0)
  212998. {
  212999. logError ("SetClock", err);
  213000. }
  213001. Thread::sleep (10);
  213002. err = asioObject->setSampleRate (sampleRate);
  213003. }
  213004. }
  213005. if (err == 0)
  213006. {
  213007. currentSampleRate = sampleRate;
  213008. if (needToReset)
  213009. {
  213010. if (isReSync)
  213011. {
  213012. log ("Resync request");
  213013. }
  213014. log ("! Resetting ASIO after sample rate change");
  213015. removeCurrentDriver();
  213016. loadDriver();
  213017. const String error (initDriver());
  213018. if (error.isNotEmpty())
  213019. {
  213020. log ("ASIOInit: " + error);
  213021. }
  213022. needToReset = false;
  213023. isReSync = false;
  213024. }
  213025. numActiveInputChans = 0;
  213026. numActiveOutputChans = 0;
  213027. ASIOBufferInfo* info = bufferInfos;
  213028. int i;
  213029. for (i = 0; i < totalNumInputChans; ++i)
  213030. {
  213031. if (inputChannels[i])
  213032. {
  213033. currentChansIn.setBit (i);
  213034. info->isInput = 1;
  213035. info->channelNum = i;
  213036. info->buffers[0] = info->buffers[1] = 0;
  213037. ++info;
  213038. ++numActiveInputChans;
  213039. }
  213040. }
  213041. for (i = 0; i < totalNumOutputChans; ++i)
  213042. {
  213043. if (outputChannels[i])
  213044. {
  213045. currentChansOut.setBit (i);
  213046. info->isInput = 0;
  213047. info->channelNum = i;
  213048. info->buffers[0] = info->buffers[1] = 0;
  213049. ++info;
  213050. ++numActiveOutputChans;
  213051. }
  213052. }
  213053. const int totalBuffers = numActiveInputChans + numActiveOutputChans;
  213054. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  213055. if (currentASIODev[0] == this)
  213056. {
  213057. callbacks.bufferSwitch = &bufferSwitchCallback0;
  213058. callbacks.asioMessage = &asioMessagesCallback0;
  213059. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  213060. }
  213061. else if (currentASIODev[1] == this)
  213062. {
  213063. callbacks.bufferSwitch = &bufferSwitchCallback1;
  213064. callbacks.asioMessage = &asioMessagesCallback1;
  213065. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  213066. }
  213067. else if (currentASIODev[2] == this)
  213068. {
  213069. callbacks.bufferSwitch = &bufferSwitchCallback2;
  213070. callbacks.asioMessage = &asioMessagesCallback2;
  213071. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  213072. }
  213073. else
  213074. {
  213075. jassertfalse;
  213076. }
  213077. log ("disposing buffers");
  213078. err = asioObject->disposeBuffers();
  213079. log ("creating buffers: " + String (totalBuffers) + ", " + String (currentBlockSizeSamples));
  213080. err = asioObject->createBuffers (bufferInfos,
  213081. totalBuffers,
  213082. currentBlockSizeSamples,
  213083. &callbacks);
  213084. if (err != 0)
  213085. {
  213086. currentBlockSizeSamples = preferredSize;
  213087. logError ("create buffers 2", err);
  213088. asioObject->disposeBuffers();
  213089. err = asioObject->createBuffers (bufferInfos,
  213090. totalBuffers,
  213091. currentBlockSizeSamples,
  213092. &callbacks);
  213093. }
  213094. if (err == 0)
  213095. {
  213096. buffersCreated = true;
  213097. tempBuffer.calloc (totalBuffers * currentBlockSizeSamples + 32);
  213098. int n = 0;
  213099. Array <int> types;
  213100. currentBitDepth = 16;
  213101. for (i = 0; i < jmin ((int) totalNumInputChans, maxASIOChannels); ++i)
  213102. {
  213103. if (inputChannels[i])
  213104. {
  213105. inBuffers[n] = tempBuffer + (currentBlockSizeSamples * n);
  213106. ASIOChannelInfo channelInfo;
  213107. zerostruct (channelInfo);
  213108. channelInfo.channel = i;
  213109. channelInfo.isInput = 1;
  213110. asioObject->getChannelInfo (&channelInfo);
  213111. types.addIfNotAlreadyThere (channelInfo.type);
  213112. typeToFormatParameters (channelInfo.type,
  213113. inputChannelBitDepths[n],
  213114. inputChannelBytesPerSample[n],
  213115. inputChannelIsFloat[n],
  213116. inputChannelLittleEndian[n]);
  213117. currentBitDepth = jmax (currentBitDepth, inputChannelBitDepths[n]);
  213118. ++n;
  213119. }
  213120. }
  213121. jassert (numActiveInputChans == n);
  213122. n = 0;
  213123. for (i = 0; i < jmin ((int) totalNumOutputChans, maxASIOChannels); ++i)
  213124. {
  213125. if (outputChannels[i])
  213126. {
  213127. outBuffers[n] = tempBuffer + (currentBlockSizeSamples * (numActiveInputChans + n));
  213128. ASIOChannelInfo channelInfo;
  213129. zerostruct (channelInfo);
  213130. channelInfo.channel = i;
  213131. channelInfo.isInput = 0;
  213132. asioObject->getChannelInfo (&channelInfo);
  213133. types.addIfNotAlreadyThere (channelInfo.type);
  213134. typeToFormatParameters (channelInfo.type,
  213135. outputChannelBitDepths[n],
  213136. outputChannelBytesPerSample[n],
  213137. outputChannelIsFloat[n],
  213138. outputChannelLittleEndian[n]);
  213139. currentBitDepth = jmax (currentBitDepth, outputChannelBitDepths[n]);
  213140. ++n;
  213141. }
  213142. }
  213143. jassert (numActiveOutputChans == n);
  213144. for (i = types.size(); --i >= 0;)
  213145. {
  213146. log ("channel format: " + String (types[i]));
  213147. }
  213148. jassert (n <= totalBuffers);
  213149. for (i = 0; i < numActiveOutputChans; ++i)
  213150. {
  213151. const int size = currentBlockSizeSamples * (outputChannelBitDepths[i] >> 3);
  213152. if (bufferInfos [numActiveInputChans + i].buffers[0] == 0
  213153. || bufferInfos [numActiveInputChans + i].buffers[1] == 0)
  213154. {
  213155. log ("!! Null buffers");
  213156. }
  213157. else
  213158. {
  213159. zeromem (bufferInfos[numActiveInputChans + i].buffers[0], size);
  213160. zeromem (bufferInfos[numActiveInputChans + i].buffers[1], size);
  213161. }
  213162. }
  213163. inputLatency = outputLatency = 0;
  213164. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  213165. {
  213166. log ("ASIO - no latencies");
  213167. }
  213168. else
  213169. {
  213170. log ("ASIO latencies: " + String ((int) outputLatency) + ", " + String ((int) inputLatency));
  213171. }
  213172. isOpen_ = true;
  213173. log ("starting ASIO");
  213174. calledback = false;
  213175. err = asioObject->start();
  213176. if (err != 0)
  213177. {
  213178. isOpen_ = false;
  213179. log ("ASIO - stop on failure");
  213180. Thread::sleep (10);
  213181. asioObject->stop();
  213182. error = "Can't start device";
  213183. Thread::sleep (10);
  213184. }
  213185. else
  213186. {
  213187. int count = 300;
  213188. while (--count > 0 && ! calledback)
  213189. Thread::sleep (10);
  213190. isStarted = true;
  213191. if (! calledback)
  213192. {
  213193. error = "Device didn't start correctly";
  213194. log ("ASIO didn't callback - stopping..");
  213195. asioObject->stop();
  213196. }
  213197. }
  213198. }
  213199. else
  213200. {
  213201. error = "Can't create i/o buffers";
  213202. }
  213203. }
  213204. else
  213205. {
  213206. error = "Can't set sample rate: ";
  213207. error << sampleRate;
  213208. }
  213209. if (error.isNotEmpty())
  213210. {
  213211. logError (error, err);
  213212. if (asioObject != 0 && buffersCreated)
  213213. asioObject->disposeBuffers();
  213214. Thread::sleep (20);
  213215. isStarted = false;
  213216. isOpen_ = false;
  213217. const String errorCopy (error);
  213218. close(); // (this resets the error string)
  213219. error = errorCopy;
  213220. }
  213221. needToReset = false;
  213222. isReSync = false;
  213223. return error;
  213224. }
  213225. void close()
  213226. {
  213227. error = String::empty;
  213228. stopTimer();
  213229. stop();
  213230. if (isASIOOpen && isOpen_)
  213231. {
  213232. const ScopedLock sl (callbackLock);
  213233. isOpen_ = false;
  213234. isStarted = false;
  213235. needToReset = false;
  213236. isReSync = false;
  213237. log ("ASIO - stopping");
  213238. if (asioObject != 0)
  213239. {
  213240. Thread::sleep (20);
  213241. asioObject->stop();
  213242. Thread::sleep (10);
  213243. asioObject->disposeBuffers();
  213244. }
  213245. Thread::sleep (10);
  213246. }
  213247. }
  213248. bool isOpen() { return isOpen_ || insideControlPanelModalLoop; }
  213249. bool isPlaying() { return isASIOOpen && (currentCallback != 0); }
  213250. int getCurrentBufferSizeSamples() { return currentBlockSizeSamples; }
  213251. double getCurrentSampleRate() { return currentSampleRate; }
  213252. int getCurrentBitDepth() { return currentBitDepth; }
  213253. const BigInteger getActiveOutputChannels() const { return currentChansOut; }
  213254. const BigInteger getActiveInputChannels() const { return currentChansIn; }
  213255. int getOutputLatencyInSamples() { return outputLatency + currentBlockSizeSamples / 4; }
  213256. int getInputLatencyInSamples() { return inputLatency + currentBlockSizeSamples / 4; }
  213257. void start (AudioIODeviceCallback* callback)
  213258. {
  213259. if (callback != 0)
  213260. {
  213261. callback->audioDeviceAboutToStart (this);
  213262. const ScopedLock sl (callbackLock);
  213263. currentCallback = callback;
  213264. }
  213265. }
  213266. void stop()
  213267. {
  213268. AudioIODeviceCallback* const lastCallback = currentCallback;
  213269. {
  213270. const ScopedLock sl (callbackLock);
  213271. currentCallback = 0;
  213272. }
  213273. if (lastCallback != 0)
  213274. lastCallback->audioDeviceStopped();
  213275. }
  213276. const String getLastError() { return error; }
  213277. bool hasControlPanel() const { return true; }
  213278. bool showControlPanel()
  213279. {
  213280. log ("ASIO - showing control panel");
  213281. Component modalWindow (String::empty);
  213282. modalWindow.setOpaque (true);
  213283. modalWindow.addToDesktop (0);
  213284. modalWindow.enterModalState();
  213285. bool done = false;
  213286. JUCE_TRY
  213287. {
  213288. // are there are devices that need to be closed before showing their control panel?
  213289. // close();
  213290. insideControlPanelModalLoop = true;
  213291. const uint32 started = Time::getMillisecondCounter();
  213292. if (asioObject != 0)
  213293. {
  213294. asioObject->controlPanel();
  213295. const int spent = (int) Time::getMillisecondCounter() - (int) started;
  213296. log ("spent: " + String (spent));
  213297. if (spent > 300)
  213298. {
  213299. shouldUsePreferredSize = true;
  213300. done = true;
  213301. }
  213302. }
  213303. }
  213304. JUCE_CATCH_ALL
  213305. insideControlPanelModalLoop = false;
  213306. return done;
  213307. }
  213308. void resetRequest() throw()
  213309. {
  213310. needToReset = true;
  213311. }
  213312. void resyncRequest() throw()
  213313. {
  213314. needToReset = true;
  213315. isReSync = true;
  213316. }
  213317. void timerCallback()
  213318. {
  213319. if (! insideControlPanelModalLoop)
  213320. {
  213321. stopTimer();
  213322. // used to cause a reset
  213323. log ("! ASIO restart request!");
  213324. if (isOpen_)
  213325. {
  213326. AudioIODeviceCallback* const oldCallback = currentCallback;
  213327. close();
  213328. open (BigInteger (currentChansIn), BigInteger (currentChansOut),
  213329. currentSampleRate, currentBlockSizeSamples);
  213330. if (oldCallback != 0)
  213331. start (oldCallback);
  213332. }
  213333. }
  213334. else
  213335. {
  213336. startTimer (100);
  213337. }
  213338. }
  213339. juce_UseDebuggingNewOperator
  213340. private:
  213341. IASIO* volatile asioObject;
  213342. ASIOCallbacks callbacks;
  213343. void* windowHandle;
  213344. CLSID classId;
  213345. const String optionalDllForDirectLoading;
  213346. String error;
  213347. long totalNumInputChans, totalNumOutputChans;
  213348. StringArray inputChannelNames, outputChannelNames;
  213349. Array<int> sampleRates, bufferSizes;
  213350. long inputLatency, outputLatency;
  213351. long minSize, maxSize, preferredSize, granularity;
  213352. int volatile currentBlockSizeSamples;
  213353. int volatile currentBitDepth;
  213354. double volatile currentSampleRate;
  213355. BigInteger currentChansOut, currentChansIn;
  213356. AudioIODeviceCallback* volatile currentCallback;
  213357. CriticalSection callbackLock;
  213358. ASIOBufferInfo bufferInfos [maxASIOChannels];
  213359. float* inBuffers [maxASIOChannels];
  213360. float* outBuffers [maxASIOChannels];
  213361. int inputChannelBitDepths [maxASIOChannels];
  213362. int outputChannelBitDepths [maxASIOChannels];
  213363. int inputChannelBytesPerSample [maxASIOChannels];
  213364. int outputChannelBytesPerSample [maxASIOChannels];
  213365. bool inputChannelIsFloat [maxASIOChannels];
  213366. bool outputChannelIsFloat [maxASIOChannels];
  213367. bool inputChannelLittleEndian [maxASIOChannels];
  213368. bool outputChannelLittleEndian [maxASIOChannels];
  213369. WaitableEvent event1;
  213370. HeapBlock <float> tempBuffer;
  213371. int volatile bufferIndex, numActiveInputChans, numActiveOutputChans;
  213372. bool isOpen_, isStarted;
  213373. bool volatile isASIOOpen;
  213374. bool volatile calledback;
  213375. bool volatile littleEndian, postOutput, needToReset, isReSync;
  213376. bool volatile insideControlPanelModalLoop;
  213377. bool volatile shouldUsePreferredSize;
  213378. void removeCurrentDriver()
  213379. {
  213380. if (asioObject != 0)
  213381. {
  213382. asioObject->Release();
  213383. asioObject = 0;
  213384. }
  213385. }
  213386. bool loadDriver()
  213387. {
  213388. removeCurrentDriver();
  213389. JUCE_TRY
  213390. {
  213391. if (CoCreateInstance (classId, 0, CLSCTX_INPROC_SERVER,
  213392. classId, (void**) &asioObject) == S_OK)
  213393. {
  213394. return true;
  213395. }
  213396. // If a class isn't registered but we have a path for it, we can fallback to
  213397. // doing a direct load of the COM object (only available via the juce_createASIOAudioIODeviceForGUID function).
  213398. if (optionalDllForDirectLoading.isNotEmpty())
  213399. {
  213400. HMODULE h = LoadLibrary (optionalDllForDirectLoading);
  213401. if (h != 0)
  213402. {
  213403. typedef HRESULT (CALLBACK* DllGetClassObjectFunc) (REFCLSID clsid, REFIID iid, LPVOID* ppv);
  213404. DllGetClassObjectFunc dllGetClassObject = (DllGetClassObjectFunc) GetProcAddress (h, "DllGetClassObject");
  213405. if (dllGetClassObject != 0)
  213406. {
  213407. IClassFactory* classFactory = 0;
  213408. HRESULT hr = dllGetClassObject (classId, IID_IClassFactory, (void**) &classFactory);
  213409. if (classFactory != 0)
  213410. {
  213411. hr = classFactory->CreateInstance (0, classId, (void**) &asioObject);
  213412. classFactory->Release();
  213413. }
  213414. return asioObject != 0;
  213415. }
  213416. }
  213417. }
  213418. }
  213419. JUCE_CATCH_ALL
  213420. asioObject = 0;
  213421. return false;
  213422. }
  213423. const String initDriver()
  213424. {
  213425. if (asioObject != 0)
  213426. {
  213427. char buffer [256];
  213428. zeromem (buffer, sizeof (buffer));
  213429. if (! asioObject->init (windowHandle))
  213430. {
  213431. asioObject->getErrorMessage (buffer);
  213432. return String (buffer, sizeof (buffer) - 1);
  213433. }
  213434. // just in case any daft drivers expect this to be called..
  213435. asioObject->getDriverName (buffer);
  213436. return String::empty;
  213437. }
  213438. return "No Driver";
  213439. }
  213440. const String openDevice()
  213441. {
  213442. // use this in case the driver starts opening dialog boxes..
  213443. Component modalWindow (String::empty);
  213444. modalWindow.setOpaque (true);
  213445. modalWindow.addToDesktop (0);
  213446. modalWindow.enterModalState();
  213447. // open the device and get its info..
  213448. log ("opening ASIO device: " + getName());
  213449. needToReset = false;
  213450. isReSync = false;
  213451. outputChannelNames.clear();
  213452. inputChannelNames.clear();
  213453. bufferSizes.clear();
  213454. sampleRates.clear();
  213455. isASIOOpen = false;
  213456. isOpen_ = false;
  213457. totalNumInputChans = 0;
  213458. totalNumOutputChans = 0;
  213459. numActiveInputChans = 0;
  213460. numActiveOutputChans = 0;
  213461. currentCallback = 0;
  213462. error = String::empty;
  213463. if (getName().isEmpty())
  213464. return error;
  213465. long err = 0;
  213466. if (loadDriver())
  213467. {
  213468. if ((error = initDriver()).isEmpty())
  213469. {
  213470. numActiveInputChans = 0;
  213471. numActiveOutputChans = 0;
  213472. totalNumInputChans = 0;
  213473. totalNumOutputChans = 0;
  213474. if (asioObject != 0
  213475. && (err = asioObject->getChannels (&totalNumInputChans, &totalNumOutputChans)) == 0)
  213476. {
  213477. log (String ((int) totalNumInputChans) + " in, " + String ((int) totalNumOutputChans) + " out");
  213478. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  213479. {
  213480. // find a list of buffer sizes..
  213481. log (String ((int) minSize) + " " + String ((int) maxSize) + " " + String ((int) preferredSize) + " " + String ((int) granularity));
  213482. if (granularity >= 0)
  213483. {
  213484. granularity = jmax (1, (int) granularity);
  213485. for (int i = jmax ((int) minSize, (int) granularity); i < jmin (6400, (int) maxSize); i += granularity)
  213486. bufferSizes.addIfNotAlreadyThere (granularity * (i / granularity));
  213487. }
  213488. else if (granularity < 0)
  213489. {
  213490. for (int i = 0; i < 18; ++i)
  213491. {
  213492. const int s = (1 << i);
  213493. if (s >= minSize && s <= maxSize)
  213494. bufferSizes.add (s);
  213495. }
  213496. }
  213497. if (! bufferSizes.contains (preferredSize))
  213498. bufferSizes.insert (0, preferredSize);
  213499. double currentRate = 0;
  213500. asioObject->getSampleRate (&currentRate);
  213501. if (currentRate <= 0.0 || currentRate > 192001.0)
  213502. {
  213503. log ("setting sample rate");
  213504. err = asioObject->setSampleRate (44100.0);
  213505. if (err != 0)
  213506. {
  213507. logError ("setting sample rate", err);
  213508. }
  213509. asioObject->getSampleRate (&currentRate);
  213510. }
  213511. currentSampleRate = currentRate;
  213512. postOutput = (asioObject->outputReady() == 0);
  213513. if (postOutput)
  213514. {
  213515. log ("ASIO outputReady = ok");
  213516. }
  213517. updateSampleRates();
  213518. // ..because cubase does it at this point
  213519. inputLatency = outputLatency = 0;
  213520. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  213521. {
  213522. log ("ASIO - no latencies");
  213523. }
  213524. log ("latencies: " + String ((int) inputLatency) + ", " + String ((int) outputLatency));
  213525. // create some dummy buffers now.. because cubase does..
  213526. numActiveInputChans = 0;
  213527. numActiveOutputChans = 0;
  213528. ASIOBufferInfo* info = bufferInfos;
  213529. int i, numChans = 0;
  213530. for (i = 0; i < jmin (2, (int) totalNumInputChans); ++i)
  213531. {
  213532. info->isInput = 1;
  213533. info->channelNum = i;
  213534. info->buffers[0] = info->buffers[1] = 0;
  213535. ++info;
  213536. ++numChans;
  213537. }
  213538. const int outputBufferIndex = numChans;
  213539. for (i = 0; i < jmin (2, (int) totalNumOutputChans); ++i)
  213540. {
  213541. info->isInput = 0;
  213542. info->channelNum = i;
  213543. info->buffers[0] = info->buffers[1] = 0;
  213544. ++info;
  213545. ++numChans;
  213546. }
  213547. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  213548. if (currentASIODev[0] == this)
  213549. {
  213550. callbacks.bufferSwitch = &bufferSwitchCallback0;
  213551. callbacks.asioMessage = &asioMessagesCallback0;
  213552. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  213553. }
  213554. else if (currentASIODev[1] == this)
  213555. {
  213556. callbacks.bufferSwitch = &bufferSwitchCallback1;
  213557. callbacks.asioMessage = &asioMessagesCallback1;
  213558. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  213559. }
  213560. else if (currentASIODev[2] == this)
  213561. {
  213562. callbacks.bufferSwitch = &bufferSwitchCallback2;
  213563. callbacks.asioMessage = &asioMessagesCallback2;
  213564. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  213565. }
  213566. else
  213567. {
  213568. jassertfalse;
  213569. }
  213570. log ("creating buffers (dummy): " + String (numChans) + ", " + String ((int) preferredSize));
  213571. if (preferredSize > 0)
  213572. {
  213573. err = asioObject->createBuffers (bufferInfos, numChans, preferredSize, &callbacks);
  213574. if (err != 0)
  213575. {
  213576. logError ("dummy buffers", err);
  213577. }
  213578. }
  213579. long newInps = 0, newOuts = 0;
  213580. asioObject->getChannels (&newInps, &newOuts);
  213581. if (totalNumInputChans != newInps || totalNumOutputChans != newOuts)
  213582. {
  213583. totalNumInputChans = newInps;
  213584. totalNumOutputChans = newOuts;
  213585. log (String ((int) totalNumInputChans) + " in; " + String ((int) totalNumOutputChans) + " out");
  213586. }
  213587. updateSampleRates();
  213588. ASIOChannelInfo channelInfo;
  213589. channelInfo.type = 0;
  213590. for (i = 0; i < totalNumInputChans; ++i)
  213591. {
  213592. zerostruct (channelInfo);
  213593. channelInfo.channel = i;
  213594. channelInfo.isInput = 1;
  213595. asioObject->getChannelInfo (&channelInfo);
  213596. inputChannelNames.add (String (channelInfo.name));
  213597. }
  213598. for (i = 0; i < totalNumOutputChans; ++i)
  213599. {
  213600. zerostruct (channelInfo);
  213601. channelInfo.channel = i;
  213602. channelInfo.isInput = 0;
  213603. asioObject->getChannelInfo (&channelInfo);
  213604. outputChannelNames.add (String (channelInfo.name));
  213605. typeToFormatParameters (channelInfo.type,
  213606. outputChannelBitDepths[i],
  213607. outputChannelBytesPerSample[i],
  213608. outputChannelIsFloat[i],
  213609. outputChannelLittleEndian[i]);
  213610. if (i < 2)
  213611. {
  213612. // clear the channels that are used with the dummy stuff
  213613. const int bytesPerBuffer = preferredSize * (outputChannelBitDepths[i] >> 3);
  213614. zeromem (bufferInfos [outputBufferIndex + i].buffers[0], bytesPerBuffer);
  213615. zeromem (bufferInfos [outputBufferIndex + i].buffers[1], bytesPerBuffer);
  213616. }
  213617. }
  213618. outputChannelNames.trim();
  213619. inputChannelNames.trim();
  213620. outputChannelNames.appendNumbersToDuplicates (false, true);
  213621. inputChannelNames.appendNumbersToDuplicates (false, true);
  213622. // start and stop because cubase does it..
  213623. asioObject->getLatencies (&inputLatency, &outputLatency);
  213624. if ((err = asioObject->start()) != 0)
  213625. {
  213626. // ignore an error here, as it might start later after setting other stuff up
  213627. logError ("ASIO start", err);
  213628. }
  213629. Thread::sleep (100);
  213630. asioObject->stop();
  213631. }
  213632. else
  213633. {
  213634. error = "Can't detect buffer sizes";
  213635. }
  213636. }
  213637. else
  213638. {
  213639. error = "Can't detect asio channels";
  213640. }
  213641. }
  213642. }
  213643. else
  213644. {
  213645. error = "No such device";
  213646. }
  213647. if (error.isNotEmpty())
  213648. {
  213649. logError (error, err);
  213650. if (asioObject != 0)
  213651. asioObject->disposeBuffers();
  213652. removeCurrentDriver();
  213653. isASIOOpen = false;
  213654. }
  213655. else
  213656. {
  213657. isASIOOpen = true;
  213658. log ("ASIO device open");
  213659. }
  213660. isOpen_ = false;
  213661. needToReset = false;
  213662. isReSync = false;
  213663. return error;
  213664. }
  213665. void JUCE_ASIOCALLBACK callback (const long index)
  213666. {
  213667. if (isStarted)
  213668. {
  213669. bufferIndex = index;
  213670. processBuffer();
  213671. }
  213672. else
  213673. {
  213674. if (postOutput && (asioObject != 0))
  213675. asioObject->outputReady();
  213676. }
  213677. calledback = true;
  213678. }
  213679. void processBuffer()
  213680. {
  213681. const ASIOBufferInfo* const infos = bufferInfos;
  213682. const int bi = bufferIndex;
  213683. const ScopedLock sl (callbackLock);
  213684. if (needToReset)
  213685. {
  213686. needToReset = false;
  213687. if (isReSync)
  213688. {
  213689. log ("! ASIO resync");
  213690. isReSync = false;
  213691. }
  213692. else
  213693. {
  213694. startTimer (20);
  213695. }
  213696. }
  213697. if (bi >= 0)
  213698. {
  213699. const int samps = currentBlockSizeSamples;
  213700. if (currentCallback != 0)
  213701. {
  213702. int i;
  213703. for (i = 0; i < numActiveInputChans; ++i)
  213704. {
  213705. float* const dst = inBuffers[i];
  213706. jassert (dst != 0);
  213707. const char* const src = (const char*) (infos[i].buffers[bi]);
  213708. if (inputChannelIsFloat[i])
  213709. {
  213710. memcpy (dst, src, samps * sizeof (float));
  213711. }
  213712. else
  213713. {
  213714. jassert (dst == tempBuffer + (samps * i));
  213715. switch (inputChannelBitDepths[i])
  213716. {
  213717. case 16:
  213718. convertInt16ToFloat (src, dst, inputChannelBytesPerSample[i],
  213719. samps, inputChannelLittleEndian[i]);
  213720. break;
  213721. case 24:
  213722. convertInt24ToFloat (src, dst, inputChannelBytesPerSample[i],
  213723. samps, inputChannelLittleEndian[i]);
  213724. break;
  213725. case 32:
  213726. convertInt32ToFloat (src, dst, inputChannelBytesPerSample[i],
  213727. samps, inputChannelLittleEndian[i]);
  213728. break;
  213729. case 64:
  213730. jassertfalse;
  213731. break;
  213732. }
  213733. }
  213734. }
  213735. currentCallback->audioDeviceIOCallback ((const float**) inBuffers, numActiveInputChans,
  213736. outBuffers, numActiveOutputChans, samps);
  213737. for (i = 0; i < numActiveOutputChans; ++i)
  213738. {
  213739. float* const src = outBuffers[i];
  213740. jassert (src != 0);
  213741. char* const dst = (char*) (infos [numActiveInputChans + i].buffers[bi]);
  213742. if (outputChannelIsFloat[i])
  213743. {
  213744. memcpy (dst, src, samps * sizeof (float));
  213745. }
  213746. else
  213747. {
  213748. jassert (src == tempBuffer + (samps * (numActiveInputChans + i)));
  213749. switch (outputChannelBitDepths[i])
  213750. {
  213751. case 16:
  213752. convertFloatToInt16 (src, dst, outputChannelBytesPerSample[i],
  213753. samps, outputChannelLittleEndian[i]);
  213754. break;
  213755. case 24:
  213756. convertFloatToInt24 (src, dst, outputChannelBytesPerSample[i],
  213757. samps, outputChannelLittleEndian[i]);
  213758. break;
  213759. case 32:
  213760. convertFloatToInt32 (src, dst, outputChannelBytesPerSample[i],
  213761. samps, outputChannelLittleEndian[i]);
  213762. break;
  213763. case 64:
  213764. jassertfalse;
  213765. break;
  213766. }
  213767. }
  213768. }
  213769. }
  213770. else
  213771. {
  213772. for (int i = 0; i < numActiveOutputChans; ++i)
  213773. {
  213774. const int bytesPerBuffer = samps * (outputChannelBitDepths[i] >> 3);
  213775. zeromem (infos[numActiveInputChans + i].buffers[bi], bytesPerBuffer);
  213776. }
  213777. }
  213778. }
  213779. if (postOutput)
  213780. asioObject->outputReady();
  213781. }
  213782. static ASIOTime* JUCE_ASIOCALLBACK bufferSwitchTimeInfoCallback0 (ASIOTime*, long index, long)
  213783. {
  213784. if (currentASIODev[0] != 0)
  213785. currentASIODev[0]->callback (index);
  213786. return 0;
  213787. }
  213788. static ASIOTime* JUCE_ASIOCALLBACK bufferSwitchTimeInfoCallback1 (ASIOTime*, long index, long)
  213789. {
  213790. if (currentASIODev[1] != 0)
  213791. currentASIODev[1]->callback (index);
  213792. return 0;
  213793. }
  213794. static ASIOTime* JUCE_ASIOCALLBACK bufferSwitchTimeInfoCallback2 (ASIOTime*, long index, long)
  213795. {
  213796. if (currentASIODev[2] != 0)
  213797. currentASIODev[2]->callback (index);
  213798. return 0;
  213799. }
  213800. static void JUCE_ASIOCALLBACK bufferSwitchCallback0 (long index, long)
  213801. {
  213802. if (currentASIODev[0] != 0)
  213803. currentASIODev[0]->callback (index);
  213804. }
  213805. static void JUCE_ASIOCALLBACK bufferSwitchCallback1 (long index, long)
  213806. {
  213807. if (currentASIODev[1] != 0)
  213808. currentASIODev[1]->callback (index);
  213809. }
  213810. static void JUCE_ASIOCALLBACK bufferSwitchCallback2 (long index, long)
  213811. {
  213812. if (currentASIODev[2] != 0)
  213813. currentASIODev[2]->callback (index);
  213814. }
  213815. static long JUCE_ASIOCALLBACK asioMessagesCallback0 (long selector, long value, void*, double*)
  213816. {
  213817. return asioMessagesCallback (selector, value, 0);
  213818. }
  213819. static long JUCE_ASIOCALLBACK asioMessagesCallback1 (long selector, long value, void*, double*)
  213820. {
  213821. return asioMessagesCallback (selector, value, 1);
  213822. }
  213823. static long JUCE_ASIOCALLBACK asioMessagesCallback2 (long selector, long value, void*, double*)
  213824. {
  213825. return asioMessagesCallback (selector, value, 2);
  213826. }
  213827. static long JUCE_ASIOCALLBACK asioMessagesCallback (long selector, long value, const int deviceIndex)
  213828. {
  213829. switch (selector)
  213830. {
  213831. case kAsioSelectorSupported:
  213832. if (value == kAsioResetRequest
  213833. || value == kAsioEngineVersion
  213834. || value == kAsioResyncRequest
  213835. || value == kAsioLatenciesChanged
  213836. || value == kAsioSupportsInputMonitor)
  213837. return 1;
  213838. break;
  213839. case kAsioBufferSizeChange:
  213840. break;
  213841. case kAsioResetRequest:
  213842. if (currentASIODev[deviceIndex] != 0)
  213843. currentASIODev[deviceIndex]->resetRequest();
  213844. return 1;
  213845. case kAsioResyncRequest:
  213846. if (currentASIODev[deviceIndex] != 0)
  213847. currentASIODev[deviceIndex]->resyncRequest();
  213848. return 1;
  213849. case kAsioLatenciesChanged:
  213850. return 1;
  213851. case kAsioEngineVersion:
  213852. return 2;
  213853. case kAsioSupportsTimeInfo:
  213854. case kAsioSupportsTimeCode:
  213855. return 0;
  213856. }
  213857. return 0;
  213858. }
  213859. static void JUCE_ASIOCALLBACK sampleRateChangedCallback (ASIOSampleRate)
  213860. {
  213861. }
  213862. static void convertInt16ToFloat (const char* src,
  213863. float* dest,
  213864. const int srcStrideBytes,
  213865. int numSamples,
  213866. const bool littleEndian) throw()
  213867. {
  213868. const double g = 1.0 / 32768.0;
  213869. if (littleEndian)
  213870. {
  213871. while (--numSamples >= 0)
  213872. {
  213873. *dest++ = (float) (g * (short) ByteOrder::littleEndianShort (src));
  213874. src += srcStrideBytes;
  213875. }
  213876. }
  213877. else
  213878. {
  213879. while (--numSamples >= 0)
  213880. {
  213881. *dest++ = (float) (g * (short) ByteOrder::bigEndianShort (src));
  213882. src += srcStrideBytes;
  213883. }
  213884. }
  213885. }
  213886. static void convertFloatToInt16 (const float* src,
  213887. char* dest,
  213888. const int dstStrideBytes,
  213889. int numSamples,
  213890. const bool littleEndian) throw()
  213891. {
  213892. const double maxVal = (double) 0x7fff;
  213893. if (littleEndian)
  213894. {
  213895. while (--numSamples >= 0)
  213896. {
  213897. *(uint16*) dest = ByteOrder::swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213898. dest += dstStrideBytes;
  213899. }
  213900. }
  213901. else
  213902. {
  213903. while (--numSamples >= 0)
  213904. {
  213905. *(uint16*) dest = ByteOrder::swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213906. dest += dstStrideBytes;
  213907. }
  213908. }
  213909. }
  213910. static void convertInt24ToFloat (const char* src,
  213911. float* dest,
  213912. const int srcStrideBytes,
  213913. int numSamples,
  213914. const bool littleEndian) throw()
  213915. {
  213916. const double g = 1.0 / 0x7fffff;
  213917. if (littleEndian)
  213918. {
  213919. while (--numSamples >= 0)
  213920. {
  213921. *dest++ = (float) (g * ByteOrder::littleEndian24Bit (src));
  213922. src += srcStrideBytes;
  213923. }
  213924. }
  213925. else
  213926. {
  213927. while (--numSamples >= 0)
  213928. {
  213929. *dest++ = (float) (g * ByteOrder::bigEndian24Bit (src));
  213930. src += srcStrideBytes;
  213931. }
  213932. }
  213933. }
  213934. static void convertFloatToInt24 (const float* src,
  213935. char* dest,
  213936. const int dstStrideBytes,
  213937. int numSamples,
  213938. const bool littleEndian) throw()
  213939. {
  213940. const double maxVal = (double) 0x7fffff;
  213941. if (littleEndian)
  213942. {
  213943. while (--numSamples >= 0)
  213944. {
  213945. ByteOrder::littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  213946. dest += dstStrideBytes;
  213947. }
  213948. }
  213949. else
  213950. {
  213951. while (--numSamples >= 0)
  213952. {
  213953. ByteOrder::bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  213954. dest += dstStrideBytes;
  213955. }
  213956. }
  213957. }
  213958. static void convertInt32ToFloat (const char* src,
  213959. float* dest,
  213960. const int srcStrideBytes,
  213961. int numSamples,
  213962. const bool littleEndian) throw()
  213963. {
  213964. const double g = 1.0 / 0x7fffffff;
  213965. if (littleEndian)
  213966. {
  213967. while (--numSamples >= 0)
  213968. {
  213969. *dest++ = (float) (g * (int) ByteOrder::littleEndianInt (src));
  213970. src += srcStrideBytes;
  213971. }
  213972. }
  213973. else
  213974. {
  213975. while (--numSamples >= 0)
  213976. {
  213977. *dest++ = (float) (g * (int) ByteOrder::bigEndianInt (src));
  213978. src += srcStrideBytes;
  213979. }
  213980. }
  213981. }
  213982. static void convertFloatToInt32 (const float* src,
  213983. char* dest,
  213984. const int dstStrideBytes,
  213985. int numSamples,
  213986. const bool littleEndian) throw()
  213987. {
  213988. const double maxVal = (double) 0x7fffffff;
  213989. if (littleEndian)
  213990. {
  213991. while (--numSamples >= 0)
  213992. {
  213993. *(uint32*) dest = ByteOrder::swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213994. dest += dstStrideBytes;
  213995. }
  213996. }
  213997. else
  213998. {
  213999. while (--numSamples >= 0)
  214000. {
  214001. *(uint32*) dest = ByteOrder::swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  214002. dest += dstStrideBytes;
  214003. }
  214004. }
  214005. }
  214006. static void typeToFormatParameters (const long type,
  214007. int& bitDepth,
  214008. int& byteStride,
  214009. bool& formatIsFloat,
  214010. bool& littleEndian) throw()
  214011. {
  214012. bitDepth = 0;
  214013. littleEndian = false;
  214014. formatIsFloat = false;
  214015. switch (type)
  214016. {
  214017. case ASIOSTInt16MSB:
  214018. case ASIOSTInt16LSB:
  214019. case ASIOSTInt32MSB16:
  214020. case ASIOSTInt32LSB16:
  214021. bitDepth = 16; break;
  214022. case ASIOSTFloat32MSB:
  214023. case ASIOSTFloat32LSB:
  214024. formatIsFloat = true;
  214025. bitDepth = 32; break;
  214026. case ASIOSTInt32MSB:
  214027. case ASIOSTInt32LSB:
  214028. bitDepth = 32; break;
  214029. case ASIOSTInt24MSB:
  214030. case ASIOSTInt24LSB:
  214031. case ASIOSTInt32MSB24:
  214032. case ASIOSTInt32LSB24:
  214033. case ASIOSTInt32MSB18:
  214034. case ASIOSTInt32MSB20:
  214035. case ASIOSTInt32LSB18:
  214036. case ASIOSTInt32LSB20:
  214037. bitDepth = 24; break;
  214038. case ASIOSTFloat64MSB:
  214039. case ASIOSTFloat64LSB:
  214040. default:
  214041. bitDepth = 64;
  214042. break;
  214043. }
  214044. switch (type)
  214045. {
  214046. case ASIOSTInt16MSB:
  214047. case ASIOSTInt32MSB16:
  214048. case ASIOSTFloat32MSB:
  214049. case ASIOSTFloat64MSB:
  214050. case ASIOSTInt32MSB:
  214051. case ASIOSTInt32MSB18:
  214052. case ASIOSTInt32MSB20:
  214053. case ASIOSTInt32MSB24:
  214054. case ASIOSTInt24MSB:
  214055. littleEndian = false; break;
  214056. case ASIOSTInt16LSB:
  214057. case ASIOSTInt32LSB16:
  214058. case ASIOSTFloat32LSB:
  214059. case ASIOSTFloat64LSB:
  214060. case ASIOSTInt32LSB:
  214061. case ASIOSTInt32LSB18:
  214062. case ASIOSTInt32LSB20:
  214063. case ASIOSTInt32LSB24:
  214064. case ASIOSTInt24LSB:
  214065. littleEndian = true; break;
  214066. default:
  214067. break;
  214068. }
  214069. switch (type)
  214070. {
  214071. case ASIOSTInt16LSB:
  214072. case ASIOSTInt16MSB:
  214073. byteStride = 2; break;
  214074. case ASIOSTInt24LSB:
  214075. case ASIOSTInt24MSB:
  214076. byteStride = 3; break;
  214077. case ASIOSTInt32MSB16:
  214078. case ASIOSTInt32LSB16:
  214079. case ASIOSTInt32MSB:
  214080. case ASIOSTInt32MSB18:
  214081. case ASIOSTInt32MSB20:
  214082. case ASIOSTInt32MSB24:
  214083. case ASIOSTInt32LSB:
  214084. case ASIOSTInt32LSB18:
  214085. case ASIOSTInt32LSB20:
  214086. case ASIOSTInt32LSB24:
  214087. case ASIOSTFloat32LSB:
  214088. case ASIOSTFloat32MSB:
  214089. byteStride = 4; break;
  214090. case ASIOSTFloat64MSB:
  214091. case ASIOSTFloat64LSB:
  214092. byteStride = 8; break;
  214093. default:
  214094. break;
  214095. }
  214096. }
  214097. };
  214098. class ASIOAudioIODeviceType : public AudioIODeviceType
  214099. {
  214100. public:
  214101. ASIOAudioIODeviceType()
  214102. : AudioIODeviceType ("ASIO"),
  214103. hasScanned (false)
  214104. {
  214105. CoInitialize (0);
  214106. }
  214107. ~ASIOAudioIODeviceType()
  214108. {
  214109. }
  214110. void scanForDevices()
  214111. {
  214112. hasScanned = true;
  214113. deviceNames.clear();
  214114. classIds.clear();
  214115. HKEY hk = 0;
  214116. int index = 0;
  214117. if (RegOpenKeyA (HKEY_LOCAL_MACHINE, "software\\asio", &hk) == ERROR_SUCCESS)
  214118. {
  214119. for (;;)
  214120. {
  214121. char name [256];
  214122. if (RegEnumKeyA (hk, index++, name, 256) == ERROR_SUCCESS)
  214123. {
  214124. addDriverInfo (name, hk);
  214125. }
  214126. else
  214127. {
  214128. break;
  214129. }
  214130. }
  214131. RegCloseKey (hk);
  214132. }
  214133. }
  214134. const StringArray getDeviceNames (bool /*wantInputNames*/) const
  214135. {
  214136. jassert (hasScanned); // need to call scanForDevices() before doing this
  214137. return deviceNames;
  214138. }
  214139. int getDefaultDeviceIndex (bool) const
  214140. {
  214141. jassert (hasScanned); // need to call scanForDevices() before doing this
  214142. for (int i = deviceNames.size(); --i >= 0;)
  214143. if (deviceNames[i].containsIgnoreCase ("asio4all"))
  214144. return i; // asio4all is a safe choice for a default..
  214145. #if JUCE_DEBUG
  214146. if (deviceNames.size() > 1 && deviceNames[0].containsIgnoreCase ("digidesign"))
  214147. return 1; // (the digi m-box driver crashes the app when you run
  214148. // it in the debugger, which can be a bit annoying)
  214149. #endif
  214150. return 0;
  214151. }
  214152. static int findFreeSlot()
  214153. {
  214154. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  214155. if (currentASIODev[i] == 0)
  214156. return i;
  214157. jassertfalse; // unfortunately you can only have a finite number
  214158. // of ASIO devices open at the same time..
  214159. return -1;
  214160. }
  214161. int getIndexOfDevice (AudioIODevice* d, bool /*asInput*/) const
  214162. {
  214163. jassert (hasScanned); // need to call scanForDevices() before doing this
  214164. return d == 0 ? -1 : deviceNames.indexOf (d->getName());
  214165. }
  214166. bool hasSeparateInputsAndOutputs() const { return false; }
  214167. AudioIODevice* createDevice (const String& outputDeviceName,
  214168. const String& inputDeviceName)
  214169. {
  214170. // ASIO can't open two different devices for input and output - they must be the same one.
  214171. jassert (inputDeviceName == outputDeviceName || outputDeviceName.isEmpty() || inputDeviceName.isEmpty());
  214172. jassert (hasScanned); // need to call scanForDevices() before doing this
  214173. const int index = deviceNames.indexOf (outputDeviceName.isNotEmpty() ? outputDeviceName
  214174. : inputDeviceName);
  214175. if (index >= 0)
  214176. {
  214177. const int freeSlot = findFreeSlot();
  214178. if (freeSlot >= 0)
  214179. return new ASIOAudioIODevice (outputDeviceName, *(classIds [index]), freeSlot, String::empty);
  214180. }
  214181. return 0;
  214182. }
  214183. juce_UseDebuggingNewOperator
  214184. private:
  214185. StringArray deviceNames;
  214186. OwnedArray <CLSID> classIds;
  214187. bool hasScanned;
  214188. static bool checkClassIsOk (const String& classId)
  214189. {
  214190. HKEY hk = 0;
  214191. bool ok = false;
  214192. if (RegOpenKey (HKEY_CLASSES_ROOT, _T("clsid"), &hk) == ERROR_SUCCESS)
  214193. {
  214194. int index = 0;
  214195. for (;;)
  214196. {
  214197. WCHAR buf [512];
  214198. if (RegEnumKey (hk, index++, buf, 512) == ERROR_SUCCESS)
  214199. {
  214200. if (classId.equalsIgnoreCase (buf))
  214201. {
  214202. HKEY subKey, pathKey;
  214203. if (RegOpenKeyEx (hk, buf, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  214204. {
  214205. if (RegOpenKeyEx (subKey, _T("InprocServer32"), 0, KEY_READ, &pathKey) == ERROR_SUCCESS)
  214206. {
  214207. WCHAR pathName [1024];
  214208. DWORD dtype = REG_SZ;
  214209. DWORD dsize = sizeof (pathName);
  214210. if (RegQueryValueEx (pathKey, 0, 0, &dtype, (LPBYTE) pathName, &dsize) == ERROR_SUCCESS)
  214211. ok = File (pathName).exists();
  214212. RegCloseKey (pathKey);
  214213. }
  214214. RegCloseKey (subKey);
  214215. }
  214216. break;
  214217. }
  214218. }
  214219. else
  214220. {
  214221. break;
  214222. }
  214223. }
  214224. RegCloseKey (hk);
  214225. }
  214226. return ok;
  214227. }
  214228. void addDriverInfo (const String& keyName, HKEY hk)
  214229. {
  214230. HKEY subKey;
  214231. if (RegOpenKeyEx (hk, keyName, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  214232. {
  214233. WCHAR buf [256];
  214234. zerostruct (buf);
  214235. DWORD dtype = REG_SZ;
  214236. DWORD dsize = sizeof (buf);
  214237. if (RegQueryValueEx (subKey, _T("clsid"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  214238. {
  214239. if (dsize > 0 && checkClassIsOk (buf))
  214240. {
  214241. CLSID classId;
  214242. if (CLSIDFromString ((LPOLESTR) buf, &classId) == S_OK)
  214243. {
  214244. dtype = REG_SZ;
  214245. dsize = sizeof (buf);
  214246. String deviceName;
  214247. if (RegQueryValueEx (subKey, _T("description"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  214248. deviceName = buf;
  214249. else
  214250. deviceName = keyName;
  214251. log ("found " + deviceName);
  214252. deviceNames.add (deviceName);
  214253. classIds.add (new CLSID (classId));
  214254. }
  214255. }
  214256. RegCloseKey (subKey);
  214257. }
  214258. }
  214259. }
  214260. ASIOAudioIODeviceType (const ASIOAudioIODeviceType&);
  214261. ASIOAudioIODeviceType& operator= (const ASIOAudioIODeviceType&);
  214262. };
  214263. AudioIODeviceType* juce_createAudioIODeviceType_ASIO()
  214264. {
  214265. return new ASIOAudioIODeviceType();
  214266. }
  214267. AudioIODevice* juce_createASIOAudioIODeviceForGUID (const String& name,
  214268. void* guid,
  214269. const String& optionalDllForDirectLoading)
  214270. {
  214271. const int freeSlot = ASIOAudioIODeviceType::findFreeSlot();
  214272. if (freeSlot < 0)
  214273. return 0;
  214274. return new ASIOAudioIODevice (name, *(CLSID*) guid, freeSlot, optionalDllForDirectLoading);
  214275. }
  214276. #undef log
  214277. #endif
  214278. /*** End of inlined file: juce_win32_ASIO.cpp ***/
  214279. /*** Start of inlined file: juce_win32_DirectSound.cpp ***/
  214280. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  214281. // compiled on its own).
  214282. #if JUCE_INCLUDED_FILE && JUCE_DIRECTSOUND
  214283. END_JUCE_NAMESPACE
  214284. extern "C"
  214285. {
  214286. // Declare just the minimum number of interfaces for the DSound objects that we need..
  214287. typedef struct typeDSBUFFERDESC
  214288. {
  214289. DWORD dwSize;
  214290. DWORD dwFlags;
  214291. DWORD dwBufferBytes;
  214292. DWORD dwReserved;
  214293. LPWAVEFORMATEX lpwfxFormat;
  214294. GUID guid3DAlgorithm;
  214295. } DSBUFFERDESC;
  214296. struct IDirectSoundBuffer;
  214297. #undef INTERFACE
  214298. #define INTERFACE IDirectSound
  214299. DECLARE_INTERFACE_(IDirectSound, IUnknown)
  214300. {
  214301. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214302. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214303. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214304. STDMETHOD(CreateSoundBuffer) (THIS_ DSBUFFERDESC*, IDirectSoundBuffer**, LPUNKNOWN) PURE;
  214305. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214306. STDMETHOD(DuplicateSoundBuffer) (THIS_ IDirectSoundBuffer*, IDirectSoundBuffer**) PURE;
  214307. STDMETHOD(SetCooperativeLevel) (THIS_ HWND, DWORD) PURE;
  214308. STDMETHOD(Compact) (THIS) PURE;
  214309. STDMETHOD(GetSpeakerConfig) (THIS_ LPDWORD) PURE;
  214310. STDMETHOD(SetSpeakerConfig) (THIS_ DWORD) PURE;
  214311. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  214312. };
  214313. #undef INTERFACE
  214314. #define INTERFACE IDirectSoundBuffer
  214315. DECLARE_INTERFACE_(IDirectSoundBuffer, IUnknown)
  214316. {
  214317. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214318. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214319. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214320. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214321. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  214322. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  214323. STDMETHOD(GetVolume) (THIS_ LPLONG) PURE;
  214324. STDMETHOD(GetPan) (THIS_ LPLONG) PURE;
  214325. STDMETHOD(GetFrequency) (THIS_ LPDWORD) PURE;
  214326. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  214327. STDMETHOD(Initialize) (THIS_ IDirectSound*, DSBUFFERDESC*) PURE;
  214328. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  214329. STDMETHOD(Play) (THIS_ DWORD, DWORD, DWORD) PURE;
  214330. STDMETHOD(SetCurrentPosition) (THIS_ DWORD) PURE;
  214331. STDMETHOD(SetFormat) (THIS_ const WAVEFORMATEX*) PURE;
  214332. STDMETHOD(SetVolume) (THIS_ LONG) PURE;
  214333. STDMETHOD(SetPan) (THIS_ LONG) PURE;
  214334. STDMETHOD(SetFrequency) (THIS_ DWORD) PURE;
  214335. STDMETHOD(Stop) (THIS) PURE;
  214336. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  214337. STDMETHOD(Restore) (THIS) PURE;
  214338. };
  214339. typedef struct typeDSCBUFFERDESC
  214340. {
  214341. DWORD dwSize;
  214342. DWORD dwFlags;
  214343. DWORD dwBufferBytes;
  214344. DWORD dwReserved;
  214345. LPWAVEFORMATEX lpwfxFormat;
  214346. } DSCBUFFERDESC;
  214347. struct IDirectSoundCaptureBuffer;
  214348. #undef INTERFACE
  214349. #define INTERFACE IDirectSoundCapture
  214350. DECLARE_INTERFACE_(IDirectSoundCapture, IUnknown)
  214351. {
  214352. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214353. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214354. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214355. STDMETHOD(CreateCaptureBuffer) (THIS_ DSCBUFFERDESC*, IDirectSoundCaptureBuffer**, LPUNKNOWN) PURE;
  214356. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214357. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  214358. };
  214359. #undef INTERFACE
  214360. #define INTERFACE IDirectSoundCaptureBuffer
  214361. DECLARE_INTERFACE_(IDirectSoundCaptureBuffer, IUnknown)
  214362. {
  214363. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214364. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214365. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214366. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214367. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  214368. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  214369. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  214370. STDMETHOD(Initialize) (THIS_ IDirectSoundCapture*, DSCBUFFERDESC*) PURE;
  214371. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  214372. STDMETHOD(Start) (THIS_ DWORD) PURE;
  214373. STDMETHOD(Stop) (THIS) PURE;
  214374. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  214375. };
  214376. };
  214377. BEGIN_JUCE_NAMESPACE
  214378. static const String getDSErrorMessage (HRESULT hr)
  214379. {
  214380. const char* result = 0;
  214381. switch (hr)
  214382. {
  214383. case MAKE_HRESULT(1, 0x878, 10): result = "Device already allocated"; break;
  214384. case MAKE_HRESULT(1, 0x878, 30): result = "Control unavailable"; break;
  214385. case E_INVALIDARG: result = "Invalid parameter"; break;
  214386. case MAKE_HRESULT(1, 0x878, 50): result = "Invalid call"; break;
  214387. case E_FAIL: result = "Generic error"; break;
  214388. case MAKE_HRESULT(1, 0x878, 70): result = "Priority level error"; break;
  214389. case E_OUTOFMEMORY: result = "Out of memory"; break;
  214390. case MAKE_HRESULT(1, 0x878, 100): result = "Bad format"; break;
  214391. case E_NOTIMPL: result = "Unsupported function"; break;
  214392. case MAKE_HRESULT(1, 0x878, 120): result = "No driver"; break;
  214393. case MAKE_HRESULT(1, 0x878, 130): result = "Already initialised"; break;
  214394. case CLASS_E_NOAGGREGATION: result = "No aggregation"; break;
  214395. case MAKE_HRESULT(1, 0x878, 150): result = "Buffer lost"; break;
  214396. case MAKE_HRESULT(1, 0x878, 160): result = "Another app has priority"; break;
  214397. case MAKE_HRESULT(1, 0x878, 170): result = "Uninitialised"; break;
  214398. case E_NOINTERFACE: result = "No interface"; break;
  214399. case S_OK: result = "No error"; break;
  214400. default: return "Unknown error: " + String ((int) hr);
  214401. }
  214402. return result;
  214403. }
  214404. #define DS_DEBUGGING 1
  214405. #ifdef DS_DEBUGGING
  214406. #define CATCH JUCE_CATCH_EXCEPTION
  214407. #undef log
  214408. #define log(a) Logger::writeToLog(a);
  214409. #undef logError
  214410. #define logError(a) logDSError(a, __LINE__);
  214411. static void logDSError (HRESULT hr, int lineNum)
  214412. {
  214413. if (hr != S_OK)
  214414. {
  214415. String error ("DS error at line ");
  214416. error << lineNum << " - " << getDSErrorMessage (hr);
  214417. log (error);
  214418. }
  214419. }
  214420. #else
  214421. #define CATCH JUCE_CATCH_ALL
  214422. #define log(a)
  214423. #define logError(a)
  214424. #endif
  214425. #define DSOUND_FUNCTION(functionName, params) \
  214426. typedef HRESULT (WINAPI *type##functionName) params; \
  214427. static type##functionName ds##functionName = 0;
  214428. #define DSOUND_FUNCTION_LOAD(functionName) \
  214429. ds##functionName = (type##functionName) GetProcAddress (h, #functionName); \
  214430. jassert (ds##functionName != 0);
  214431. typedef BOOL (CALLBACK *LPDSENUMCALLBACKW) (LPGUID, LPCWSTR, LPCWSTR, LPVOID);
  214432. typedef BOOL (CALLBACK *LPDSENUMCALLBACKA) (LPGUID, LPCSTR, LPCSTR, LPVOID);
  214433. DSOUND_FUNCTION (DirectSoundCreate, (const GUID*, IDirectSound**, LPUNKNOWN))
  214434. DSOUND_FUNCTION (DirectSoundCaptureCreate, (const GUID*, IDirectSoundCapture**, LPUNKNOWN))
  214435. DSOUND_FUNCTION (DirectSoundEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  214436. DSOUND_FUNCTION (DirectSoundCaptureEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  214437. static void initialiseDSoundFunctions()
  214438. {
  214439. if (dsDirectSoundCreate == 0)
  214440. {
  214441. HMODULE h = LoadLibraryA ("dsound.dll");
  214442. DSOUND_FUNCTION_LOAD (DirectSoundCreate)
  214443. DSOUND_FUNCTION_LOAD (DirectSoundCaptureCreate)
  214444. DSOUND_FUNCTION_LOAD (DirectSoundEnumerateW)
  214445. DSOUND_FUNCTION_LOAD (DirectSoundCaptureEnumerateW)
  214446. }
  214447. }
  214448. class DSoundInternalOutChannel
  214449. {
  214450. String name;
  214451. LPGUID guid;
  214452. int sampleRate, bufferSizeSamples;
  214453. float* leftBuffer;
  214454. float* rightBuffer;
  214455. IDirectSound* pDirectSound;
  214456. IDirectSoundBuffer* pOutputBuffer;
  214457. DWORD writeOffset;
  214458. int totalBytesPerBuffer;
  214459. int bytesPerBuffer;
  214460. unsigned int lastPlayCursor;
  214461. public:
  214462. int bitDepth;
  214463. bool doneFlag;
  214464. DSoundInternalOutChannel (const String& name_,
  214465. LPGUID guid_,
  214466. int rate,
  214467. int bufferSize,
  214468. float* left,
  214469. float* right)
  214470. : name (name_),
  214471. guid (guid_),
  214472. sampleRate (rate),
  214473. bufferSizeSamples (bufferSize),
  214474. leftBuffer (left),
  214475. rightBuffer (right),
  214476. pDirectSound (0),
  214477. pOutputBuffer (0),
  214478. bitDepth (16)
  214479. {
  214480. }
  214481. ~DSoundInternalOutChannel()
  214482. {
  214483. close();
  214484. }
  214485. void close()
  214486. {
  214487. HRESULT hr;
  214488. if (pOutputBuffer != 0)
  214489. {
  214490. JUCE_TRY
  214491. {
  214492. log ("closing dsound out: " + name);
  214493. hr = pOutputBuffer->Stop();
  214494. logError (hr);
  214495. }
  214496. CATCH
  214497. JUCE_TRY
  214498. {
  214499. hr = pOutputBuffer->Release();
  214500. logError (hr);
  214501. }
  214502. CATCH
  214503. pOutputBuffer = 0;
  214504. }
  214505. if (pDirectSound != 0)
  214506. {
  214507. JUCE_TRY
  214508. {
  214509. hr = pDirectSound->Release();
  214510. logError (hr);
  214511. }
  214512. CATCH
  214513. pDirectSound = 0;
  214514. }
  214515. }
  214516. const String open()
  214517. {
  214518. log ("opening dsound out device: " + name + " rate=" + String (sampleRate)
  214519. + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  214520. pDirectSound = 0;
  214521. pOutputBuffer = 0;
  214522. writeOffset = 0;
  214523. String error;
  214524. HRESULT hr = E_NOINTERFACE;
  214525. if (dsDirectSoundCreate != 0)
  214526. hr = dsDirectSoundCreate (guid, &pDirectSound, 0);
  214527. if (hr == S_OK)
  214528. {
  214529. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  214530. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  214531. const int numChannels = 2;
  214532. hr = pDirectSound->SetCooperativeLevel (GetDesktopWindow(), 2 /* DSSCL_PRIORITY */);
  214533. logError (hr);
  214534. if (hr == S_OK)
  214535. {
  214536. IDirectSoundBuffer* pPrimaryBuffer;
  214537. DSBUFFERDESC primaryDesc;
  214538. zerostruct (primaryDesc);
  214539. primaryDesc.dwSize = sizeof (DSBUFFERDESC);
  214540. primaryDesc.dwFlags = 1 /* DSBCAPS_PRIMARYBUFFER */;
  214541. primaryDesc.dwBufferBytes = 0;
  214542. primaryDesc.lpwfxFormat = 0;
  214543. log ("opening dsound out step 2");
  214544. hr = pDirectSound->CreateSoundBuffer (&primaryDesc, &pPrimaryBuffer, 0);
  214545. logError (hr);
  214546. if (hr == S_OK)
  214547. {
  214548. WAVEFORMATEX wfFormat;
  214549. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  214550. wfFormat.nChannels = (unsigned short) numChannels;
  214551. wfFormat.nSamplesPerSec = sampleRate;
  214552. wfFormat.wBitsPerSample = (unsigned short) bitDepth;
  214553. wfFormat.nBlockAlign = (unsigned short) (wfFormat.nChannels * wfFormat.wBitsPerSample / 8);
  214554. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  214555. wfFormat.cbSize = 0;
  214556. hr = pPrimaryBuffer->SetFormat (&wfFormat);
  214557. logError (hr);
  214558. if (hr == S_OK)
  214559. {
  214560. DSBUFFERDESC secondaryDesc;
  214561. zerostruct (secondaryDesc);
  214562. secondaryDesc.dwSize = sizeof (DSBUFFERDESC);
  214563. secondaryDesc.dwFlags = 0x8000 /* DSBCAPS_GLOBALFOCUS */
  214564. | 0x10000 /* DSBCAPS_GETCURRENTPOSITION2 */;
  214565. secondaryDesc.dwBufferBytes = totalBytesPerBuffer;
  214566. secondaryDesc.lpwfxFormat = &wfFormat;
  214567. hr = pDirectSound->CreateSoundBuffer (&secondaryDesc, &pOutputBuffer, 0);
  214568. logError (hr);
  214569. if (hr == S_OK)
  214570. {
  214571. log ("opening dsound out step 3");
  214572. DWORD dwDataLen;
  214573. unsigned char* pDSBuffData;
  214574. hr = pOutputBuffer->Lock (0, totalBytesPerBuffer,
  214575. (LPVOID*) &pDSBuffData, &dwDataLen, 0, 0, 0);
  214576. logError (hr);
  214577. if (hr == S_OK)
  214578. {
  214579. zeromem (pDSBuffData, dwDataLen);
  214580. hr = pOutputBuffer->Unlock (pDSBuffData, dwDataLen, 0, 0);
  214581. if (hr == S_OK)
  214582. {
  214583. hr = pOutputBuffer->SetCurrentPosition (0);
  214584. if (hr == S_OK)
  214585. {
  214586. hr = pOutputBuffer->Play (0, 0, 1 /* DSBPLAY_LOOPING */);
  214587. if (hr == S_OK)
  214588. return String::empty;
  214589. }
  214590. }
  214591. }
  214592. }
  214593. }
  214594. }
  214595. }
  214596. }
  214597. error = getDSErrorMessage (hr);
  214598. close();
  214599. return error;
  214600. }
  214601. void synchronisePosition()
  214602. {
  214603. if (pOutputBuffer != 0)
  214604. {
  214605. DWORD playCursor;
  214606. pOutputBuffer->GetCurrentPosition (&playCursor, &writeOffset);
  214607. }
  214608. }
  214609. bool service()
  214610. {
  214611. if (pOutputBuffer == 0)
  214612. return true;
  214613. DWORD playCursor, writeCursor;
  214614. for (;;)
  214615. {
  214616. HRESULT hr = pOutputBuffer->GetCurrentPosition (&playCursor, &writeCursor);
  214617. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  214618. {
  214619. pOutputBuffer->Restore();
  214620. continue;
  214621. }
  214622. if (hr == S_OK)
  214623. break;
  214624. logError (hr);
  214625. jassertfalse;
  214626. return true;
  214627. }
  214628. int playWriteGap = writeCursor - playCursor;
  214629. if (playWriteGap < 0)
  214630. playWriteGap += totalBytesPerBuffer;
  214631. int bytesEmpty = playCursor - writeOffset;
  214632. if (bytesEmpty < 0)
  214633. bytesEmpty += totalBytesPerBuffer;
  214634. if (bytesEmpty > (totalBytesPerBuffer - playWriteGap))
  214635. {
  214636. writeOffset = writeCursor;
  214637. bytesEmpty = totalBytesPerBuffer - playWriteGap;
  214638. }
  214639. if (bytesEmpty >= bytesPerBuffer)
  214640. {
  214641. void* lpbuf1 = 0;
  214642. void* lpbuf2 = 0;
  214643. DWORD dwSize1 = 0;
  214644. DWORD dwSize2 = 0;
  214645. HRESULT hr = pOutputBuffer->Lock (writeOffset,
  214646. bytesPerBuffer,
  214647. &lpbuf1, &dwSize1,
  214648. &lpbuf2, &dwSize2, 0);
  214649. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  214650. {
  214651. pOutputBuffer->Restore();
  214652. hr = pOutputBuffer->Lock (writeOffset,
  214653. bytesPerBuffer,
  214654. &lpbuf1, &dwSize1,
  214655. &lpbuf2, &dwSize2, 0);
  214656. }
  214657. if (hr == S_OK)
  214658. {
  214659. if (bitDepth == 16)
  214660. {
  214661. const float gainL = 32767.0f;
  214662. const float gainR = 32767.0f;
  214663. int* dest = static_cast<int*> (lpbuf1);
  214664. const float* left = leftBuffer;
  214665. const float* right = rightBuffer;
  214666. int samples1 = dwSize1 >> 2;
  214667. int samples2 = dwSize2 >> 2;
  214668. if (left == 0)
  214669. {
  214670. while (--samples1 >= 0)
  214671. {
  214672. int r = roundToInt (gainR * *right++);
  214673. if (r < -32768)
  214674. r = -32768;
  214675. else if (r > 32767)
  214676. r = 32767;
  214677. *dest++ = (r << 16);
  214678. }
  214679. dest = static_cast<int*> (lpbuf2);
  214680. while (--samples2 >= 0)
  214681. {
  214682. int r = roundToInt (gainR * *right++);
  214683. if (r < -32768)
  214684. r = -32768;
  214685. else if (r > 32767)
  214686. r = 32767;
  214687. *dest++ = (r << 16);
  214688. }
  214689. }
  214690. else if (right == 0)
  214691. {
  214692. while (--samples1 >= 0)
  214693. {
  214694. int l = roundToInt (gainL * *left++);
  214695. if (l < -32768)
  214696. l = -32768;
  214697. else if (l > 32767)
  214698. l = 32767;
  214699. l &= 0xffff;
  214700. *dest++ = l;
  214701. }
  214702. dest = static_cast<int*> (lpbuf2);
  214703. while (--samples2 >= 0)
  214704. {
  214705. int l = roundToInt (gainL * *left++);
  214706. if (l < -32768)
  214707. l = -32768;
  214708. else if (l > 32767)
  214709. l = 32767;
  214710. l &= 0xffff;
  214711. *dest++ = l;
  214712. }
  214713. }
  214714. else
  214715. {
  214716. while (--samples1 >= 0)
  214717. {
  214718. int l = roundToInt (gainL * *left++);
  214719. if (l < -32768)
  214720. l = -32768;
  214721. else if (l > 32767)
  214722. l = 32767;
  214723. l &= 0xffff;
  214724. int r = roundToInt (gainR * *right++);
  214725. if (r < -32768)
  214726. r = -32768;
  214727. else if (r > 32767)
  214728. r = 32767;
  214729. *dest++ = (r << 16) | l;
  214730. }
  214731. dest = static_cast<int*> (lpbuf2);
  214732. while (--samples2 >= 0)
  214733. {
  214734. int l = roundToInt (gainL * *left++);
  214735. if (l < -32768)
  214736. l = -32768;
  214737. else if (l > 32767)
  214738. l = 32767;
  214739. l &= 0xffff;
  214740. int r = roundToInt (gainR * *right++);
  214741. if (r < -32768)
  214742. r = -32768;
  214743. else if (r > 32767)
  214744. r = 32767;
  214745. *dest++ = (r << 16) | l;
  214746. }
  214747. }
  214748. }
  214749. else
  214750. {
  214751. jassertfalse;
  214752. }
  214753. writeOffset = (writeOffset + dwSize1 + dwSize2) % totalBytesPerBuffer;
  214754. pOutputBuffer->Unlock (lpbuf1, dwSize1, lpbuf2, dwSize2);
  214755. }
  214756. else
  214757. {
  214758. jassertfalse;
  214759. logError (hr);
  214760. }
  214761. bytesEmpty -= bytesPerBuffer;
  214762. return true;
  214763. }
  214764. else
  214765. {
  214766. return false;
  214767. }
  214768. }
  214769. };
  214770. struct DSoundInternalInChannel
  214771. {
  214772. String name;
  214773. LPGUID guid;
  214774. int sampleRate, bufferSizeSamples;
  214775. float* leftBuffer;
  214776. float* rightBuffer;
  214777. IDirectSound* pDirectSound;
  214778. IDirectSoundCapture* pDirectSoundCapture;
  214779. IDirectSoundCaptureBuffer* pInputBuffer;
  214780. public:
  214781. unsigned int readOffset;
  214782. int bytesPerBuffer, totalBytesPerBuffer;
  214783. int bitDepth;
  214784. bool doneFlag;
  214785. DSoundInternalInChannel (const String& name_,
  214786. LPGUID guid_,
  214787. int rate,
  214788. int bufferSize,
  214789. float* left,
  214790. float* right)
  214791. : name (name_),
  214792. guid (guid_),
  214793. sampleRate (rate),
  214794. bufferSizeSamples (bufferSize),
  214795. leftBuffer (left),
  214796. rightBuffer (right),
  214797. pDirectSound (0),
  214798. pDirectSoundCapture (0),
  214799. pInputBuffer (0),
  214800. bitDepth (16)
  214801. {
  214802. }
  214803. ~DSoundInternalInChannel()
  214804. {
  214805. close();
  214806. }
  214807. void close()
  214808. {
  214809. HRESULT hr;
  214810. if (pInputBuffer != 0)
  214811. {
  214812. JUCE_TRY
  214813. {
  214814. log ("closing dsound in: " + name);
  214815. hr = pInputBuffer->Stop();
  214816. logError (hr);
  214817. }
  214818. CATCH
  214819. JUCE_TRY
  214820. {
  214821. hr = pInputBuffer->Release();
  214822. logError (hr);
  214823. }
  214824. CATCH
  214825. pInputBuffer = 0;
  214826. }
  214827. if (pDirectSoundCapture != 0)
  214828. {
  214829. JUCE_TRY
  214830. {
  214831. hr = pDirectSoundCapture->Release();
  214832. logError (hr);
  214833. }
  214834. CATCH
  214835. pDirectSoundCapture = 0;
  214836. }
  214837. if (pDirectSound != 0)
  214838. {
  214839. JUCE_TRY
  214840. {
  214841. hr = pDirectSound->Release();
  214842. logError (hr);
  214843. }
  214844. CATCH
  214845. pDirectSound = 0;
  214846. }
  214847. }
  214848. const String open()
  214849. {
  214850. log ("opening dsound in device: " + name
  214851. + " rate=" + String (sampleRate) + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  214852. pDirectSound = 0;
  214853. pDirectSoundCapture = 0;
  214854. pInputBuffer = 0;
  214855. readOffset = 0;
  214856. totalBytesPerBuffer = 0;
  214857. String error;
  214858. HRESULT hr = E_NOINTERFACE;
  214859. if (dsDirectSoundCaptureCreate != 0)
  214860. hr = dsDirectSoundCaptureCreate (guid, &pDirectSoundCapture, 0);
  214861. logError (hr);
  214862. if (hr == S_OK)
  214863. {
  214864. const int numChannels = 2;
  214865. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  214866. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  214867. WAVEFORMATEX wfFormat;
  214868. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  214869. wfFormat.nChannels = (unsigned short)numChannels;
  214870. wfFormat.nSamplesPerSec = sampleRate;
  214871. wfFormat.wBitsPerSample = (unsigned short)bitDepth;
  214872. wfFormat.nBlockAlign = (unsigned short)(wfFormat.nChannels * (wfFormat.wBitsPerSample / 8));
  214873. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  214874. wfFormat.cbSize = 0;
  214875. DSCBUFFERDESC captureDesc;
  214876. zerostruct (captureDesc);
  214877. captureDesc.dwSize = sizeof (DSCBUFFERDESC);
  214878. captureDesc.dwFlags = 0;
  214879. captureDesc.dwBufferBytes = totalBytesPerBuffer;
  214880. captureDesc.lpwfxFormat = &wfFormat;
  214881. log ("opening dsound in step 2");
  214882. hr = pDirectSoundCapture->CreateCaptureBuffer (&captureDesc, &pInputBuffer, 0);
  214883. logError (hr);
  214884. if (hr == S_OK)
  214885. {
  214886. hr = pInputBuffer->Start (1 /* DSCBSTART_LOOPING */);
  214887. logError (hr);
  214888. if (hr == S_OK)
  214889. return String::empty;
  214890. }
  214891. }
  214892. error = getDSErrorMessage (hr);
  214893. close();
  214894. return error;
  214895. }
  214896. void synchronisePosition()
  214897. {
  214898. if (pInputBuffer != 0)
  214899. {
  214900. DWORD capturePos;
  214901. pInputBuffer->GetCurrentPosition (&capturePos, (DWORD*)&readOffset);
  214902. }
  214903. }
  214904. bool service()
  214905. {
  214906. if (pInputBuffer == 0)
  214907. return true;
  214908. DWORD capturePos, readPos;
  214909. HRESULT hr = pInputBuffer->GetCurrentPosition (&capturePos, &readPos);
  214910. logError (hr);
  214911. if (hr != S_OK)
  214912. return true;
  214913. int bytesFilled = readPos - readOffset;
  214914. if (bytesFilled < 0)
  214915. bytesFilled += totalBytesPerBuffer;
  214916. if (bytesFilled >= bytesPerBuffer)
  214917. {
  214918. LPBYTE lpbuf1 = 0;
  214919. LPBYTE lpbuf2 = 0;
  214920. DWORD dwsize1 = 0;
  214921. DWORD dwsize2 = 0;
  214922. HRESULT hr = pInputBuffer->Lock (readOffset,
  214923. bytesPerBuffer,
  214924. (void**) &lpbuf1, &dwsize1,
  214925. (void**) &lpbuf2, &dwsize2, 0);
  214926. if (hr == S_OK)
  214927. {
  214928. if (bitDepth == 16)
  214929. {
  214930. const float g = 1.0f / 32768.0f;
  214931. float* destL = leftBuffer;
  214932. float* destR = rightBuffer;
  214933. int samples1 = dwsize1 >> 2;
  214934. int samples2 = dwsize2 >> 2;
  214935. const short* src = (const short*)lpbuf1;
  214936. if (destL == 0)
  214937. {
  214938. while (--samples1 >= 0)
  214939. {
  214940. ++src;
  214941. *destR++ = *src++ * g;
  214942. }
  214943. src = (const short*)lpbuf2;
  214944. while (--samples2 >= 0)
  214945. {
  214946. ++src;
  214947. *destR++ = *src++ * g;
  214948. }
  214949. }
  214950. else if (destR == 0)
  214951. {
  214952. while (--samples1 >= 0)
  214953. {
  214954. *destL++ = *src++ * g;
  214955. ++src;
  214956. }
  214957. src = (const short*)lpbuf2;
  214958. while (--samples2 >= 0)
  214959. {
  214960. *destL++ = *src++ * g;
  214961. ++src;
  214962. }
  214963. }
  214964. else
  214965. {
  214966. while (--samples1 >= 0)
  214967. {
  214968. *destL++ = *src++ * g;
  214969. *destR++ = *src++ * g;
  214970. }
  214971. src = (const short*)lpbuf2;
  214972. while (--samples2 >= 0)
  214973. {
  214974. *destL++ = *src++ * g;
  214975. *destR++ = *src++ * g;
  214976. }
  214977. }
  214978. }
  214979. else
  214980. {
  214981. jassertfalse;
  214982. }
  214983. readOffset = (readOffset + dwsize1 + dwsize2) % totalBytesPerBuffer;
  214984. pInputBuffer->Unlock (lpbuf1, dwsize1, lpbuf2, dwsize2);
  214985. }
  214986. else
  214987. {
  214988. logError (hr);
  214989. jassertfalse;
  214990. }
  214991. bytesFilled -= bytesPerBuffer;
  214992. return true;
  214993. }
  214994. else
  214995. {
  214996. return false;
  214997. }
  214998. }
  214999. };
  215000. class DSoundAudioIODevice : public AudioIODevice,
  215001. public Thread
  215002. {
  215003. public:
  215004. DSoundAudioIODevice (const String& deviceName,
  215005. const int outputDeviceIndex_,
  215006. const int inputDeviceIndex_)
  215007. : AudioIODevice (deviceName, "DirectSound"),
  215008. Thread ("Juce DSound"),
  215009. isOpen_ (false),
  215010. isStarted (false),
  215011. outputDeviceIndex (outputDeviceIndex_),
  215012. inputDeviceIndex (inputDeviceIndex_),
  215013. totalSamplesOut (0),
  215014. sampleRate (0.0),
  215015. inputBuffers (1, 1),
  215016. outputBuffers (1, 1),
  215017. callback (0),
  215018. bufferSizeSamples (0)
  215019. {
  215020. if (outputDeviceIndex_ >= 0)
  215021. {
  215022. outChannels.add (TRANS("Left"));
  215023. outChannels.add (TRANS("Right"));
  215024. }
  215025. if (inputDeviceIndex_ >= 0)
  215026. {
  215027. inChannels.add (TRANS("Left"));
  215028. inChannels.add (TRANS("Right"));
  215029. }
  215030. }
  215031. ~DSoundAudioIODevice()
  215032. {
  215033. close();
  215034. }
  215035. const StringArray getOutputChannelNames()
  215036. {
  215037. return outChannels;
  215038. }
  215039. const StringArray getInputChannelNames()
  215040. {
  215041. return inChannels;
  215042. }
  215043. int getNumSampleRates()
  215044. {
  215045. return 4;
  215046. }
  215047. double getSampleRate (int index)
  215048. {
  215049. const double samps[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  215050. return samps [jlimit (0, 3, index)];
  215051. }
  215052. int getNumBufferSizesAvailable()
  215053. {
  215054. return 50;
  215055. }
  215056. int getBufferSizeSamples (int index)
  215057. {
  215058. int n = 64;
  215059. for (int i = 0; i < index; ++i)
  215060. n += (n < 512) ? 32
  215061. : ((n < 1024) ? 64
  215062. : ((n < 2048) ? 128 : 256));
  215063. return n;
  215064. }
  215065. int getDefaultBufferSize()
  215066. {
  215067. return 2560;
  215068. }
  215069. const String open (const BigInteger& inputChannels,
  215070. const BigInteger& outputChannels,
  215071. double sampleRate,
  215072. int bufferSizeSamples)
  215073. {
  215074. lastError = openDevice (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  215075. isOpen_ = lastError.isEmpty();
  215076. return lastError;
  215077. }
  215078. void close()
  215079. {
  215080. stop();
  215081. if (isOpen_)
  215082. {
  215083. closeDevice();
  215084. isOpen_ = false;
  215085. }
  215086. }
  215087. bool isOpen()
  215088. {
  215089. return isOpen_ && isThreadRunning();
  215090. }
  215091. int getCurrentBufferSizeSamples()
  215092. {
  215093. return bufferSizeSamples;
  215094. }
  215095. double getCurrentSampleRate()
  215096. {
  215097. return sampleRate;
  215098. }
  215099. int getCurrentBitDepth()
  215100. {
  215101. int i, bits = 256;
  215102. for (i = inChans.size(); --i >= 0;)
  215103. bits = jmin (bits, inChans[i]->bitDepth);
  215104. for (i = outChans.size(); --i >= 0;)
  215105. bits = jmin (bits, outChans[i]->bitDepth);
  215106. if (bits > 32)
  215107. bits = 16;
  215108. return bits;
  215109. }
  215110. const BigInteger getActiveOutputChannels() const
  215111. {
  215112. return enabledOutputs;
  215113. }
  215114. const BigInteger getActiveInputChannels() const
  215115. {
  215116. return enabledInputs;
  215117. }
  215118. int getOutputLatencyInSamples()
  215119. {
  215120. return (int) (getCurrentBufferSizeSamples() * 1.5);
  215121. }
  215122. int getInputLatencyInSamples()
  215123. {
  215124. return getOutputLatencyInSamples();
  215125. }
  215126. void start (AudioIODeviceCallback* call)
  215127. {
  215128. if (isOpen_ && call != 0 && ! isStarted)
  215129. {
  215130. if (! isThreadRunning())
  215131. {
  215132. // something gone wrong and the thread's stopped..
  215133. isOpen_ = false;
  215134. return;
  215135. }
  215136. call->audioDeviceAboutToStart (this);
  215137. const ScopedLock sl (startStopLock);
  215138. callback = call;
  215139. isStarted = true;
  215140. }
  215141. }
  215142. void stop()
  215143. {
  215144. if (isStarted)
  215145. {
  215146. AudioIODeviceCallback* const callbackLocal = callback;
  215147. {
  215148. const ScopedLock sl (startStopLock);
  215149. isStarted = false;
  215150. }
  215151. if (callbackLocal != 0)
  215152. callbackLocal->audioDeviceStopped();
  215153. }
  215154. }
  215155. bool isPlaying()
  215156. {
  215157. return isStarted && isOpen_ && isThreadRunning();
  215158. }
  215159. const String getLastError()
  215160. {
  215161. return lastError;
  215162. }
  215163. juce_UseDebuggingNewOperator
  215164. StringArray inChannels, outChannels;
  215165. int outputDeviceIndex, inputDeviceIndex;
  215166. private:
  215167. bool isOpen_;
  215168. bool isStarted;
  215169. String lastError;
  215170. OwnedArray <DSoundInternalInChannel> inChans;
  215171. OwnedArray <DSoundInternalOutChannel> outChans;
  215172. WaitableEvent startEvent;
  215173. int bufferSizeSamples;
  215174. int volatile totalSamplesOut;
  215175. int64 volatile lastBlockTime;
  215176. double sampleRate;
  215177. BigInteger enabledInputs, enabledOutputs;
  215178. AudioSampleBuffer inputBuffers, outputBuffers;
  215179. AudioIODeviceCallback* callback;
  215180. CriticalSection startStopLock;
  215181. DSoundAudioIODevice (const DSoundAudioIODevice&);
  215182. DSoundAudioIODevice& operator= (const DSoundAudioIODevice&);
  215183. const String openDevice (const BigInteger& inputChannels,
  215184. const BigInteger& outputChannels,
  215185. double sampleRate_,
  215186. int bufferSizeSamples_);
  215187. void closeDevice()
  215188. {
  215189. isStarted = false;
  215190. stopThread (5000);
  215191. inChans.clear();
  215192. outChans.clear();
  215193. inputBuffers.setSize (1, 1);
  215194. outputBuffers.setSize (1, 1);
  215195. }
  215196. void resync()
  215197. {
  215198. if (! threadShouldExit())
  215199. {
  215200. sleep (5);
  215201. int i;
  215202. for (i = 0; i < outChans.size(); ++i)
  215203. outChans.getUnchecked(i)->synchronisePosition();
  215204. for (i = 0; i < inChans.size(); ++i)
  215205. inChans.getUnchecked(i)->synchronisePosition();
  215206. }
  215207. }
  215208. public:
  215209. void run()
  215210. {
  215211. while (! threadShouldExit())
  215212. {
  215213. if (wait (100))
  215214. break;
  215215. }
  215216. const int latencyMs = (int) (bufferSizeSamples * 1000.0 / sampleRate);
  215217. const int maxTimeMS = jmax (5, 3 * latencyMs);
  215218. while (! threadShouldExit())
  215219. {
  215220. int numToDo = 0;
  215221. uint32 startTime = Time::getMillisecondCounter();
  215222. int i;
  215223. for (i = inChans.size(); --i >= 0;)
  215224. {
  215225. inChans.getUnchecked(i)->doneFlag = false;
  215226. ++numToDo;
  215227. }
  215228. for (i = outChans.size(); --i >= 0;)
  215229. {
  215230. outChans.getUnchecked(i)->doneFlag = false;
  215231. ++numToDo;
  215232. }
  215233. if (numToDo > 0)
  215234. {
  215235. const int maxCount = 3;
  215236. int count = maxCount;
  215237. for (;;)
  215238. {
  215239. for (i = inChans.size(); --i >= 0;)
  215240. {
  215241. DSoundInternalInChannel* const in = inChans.getUnchecked(i);
  215242. if ((! in->doneFlag) && in->service())
  215243. {
  215244. in->doneFlag = true;
  215245. --numToDo;
  215246. }
  215247. }
  215248. for (i = outChans.size(); --i >= 0;)
  215249. {
  215250. DSoundInternalOutChannel* const out = outChans.getUnchecked(i);
  215251. if ((! out->doneFlag) && out->service())
  215252. {
  215253. out->doneFlag = true;
  215254. --numToDo;
  215255. }
  215256. }
  215257. if (numToDo <= 0)
  215258. break;
  215259. if (Time::getMillisecondCounter() > startTime + maxTimeMS)
  215260. {
  215261. resync();
  215262. break;
  215263. }
  215264. if (--count <= 0)
  215265. {
  215266. Sleep (1);
  215267. count = maxCount;
  215268. }
  215269. if (threadShouldExit())
  215270. return;
  215271. }
  215272. }
  215273. else
  215274. {
  215275. sleep (1);
  215276. }
  215277. const ScopedLock sl (startStopLock);
  215278. if (isStarted)
  215279. {
  215280. JUCE_TRY
  215281. {
  215282. callback->audioDeviceIOCallback (const_cast <const float**> (inputBuffers.getArrayOfChannels()),
  215283. inputBuffers.getNumChannels(),
  215284. outputBuffers.getArrayOfChannels(),
  215285. outputBuffers.getNumChannels(),
  215286. bufferSizeSamples);
  215287. }
  215288. JUCE_CATCH_EXCEPTION
  215289. totalSamplesOut += bufferSizeSamples;
  215290. }
  215291. else
  215292. {
  215293. outputBuffers.clear();
  215294. totalSamplesOut = 0;
  215295. sleep (1);
  215296. }
  215297. }
  215298. }
  215299. };
  215300. class DSoundAudioIODeviceType : public AudioIODeviceType
  215301. {
  215302. public:
  215303. DSoundAudioIODeviceType()
  215304. : AudioIODeviceType ("DirectSound"),
  215305. hasScanned (false)
  215306. {
  215307. initialiseDSoundFunctions();
  215308. }
  215309. ~DSoundAudioIODeviceType()
  215310. {
  215311. }
  215312. void scanForDevices()
  215313. {
  215314. hasScanned = true;
  215315. outputDeviceNames.clear();
  215316. outputGuids.clear();
  215317. inputDeviceNames.clear();
  215318. inputGuids.clear();
  215319. if (dsDirectSoundEnumerateW != 0)
  215320. {
  215321. dsDirectSoundEnumerateW (outputEnumProcW, this);
  215322. dsDirectSoundCaptureEnumerateW (inputEnumProcW, this);
  215323. }
  215324. }
  215325. const StringArray getDeviceNames (bool wantInputNames) const
  215326. {
  215327. jassert (hasScanned); // need to call scanForDevices() before doing this
  215328. return wantInputNames ? inputDeviceNames
  215329. : outputDeviceNames;
  215330. }
  215331. int getDefaultDeviceIndex (bool /*forInput*/) const
  215332. {
  215333. jassert (hasScanned); // need to call scanForDevices() before doing this
  215334. return 0;
  215335. }
  215336. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  215337. {
  215338. jassert (hasScanned); // need to call scanForDevices() before doing this
  215339. DSoundAudioIODevice* const d = dynamic_cast <DSoundAudioIODevice*> (device);
  215340. if (d == 0)
  215341. return -1;
  215342. return asInput ? d->inputDeviceIndex
  215343. : d->outputDeviceIndex;
  215344. }
  215345. bool hasSeparateInputsAndOutputs() const { return true; }
  215346. AudioIODevice* createDevice (const String& outputDeviceName,
  215347. const String& inputDeviceName)
  215348. {
  215349. jassert (hasScanned); // need to call scanForDevices() before doing this
  215350. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  215351. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  215352. if (outputIndex >= 0 || inputIndex >= 0)
  215353. return new DSoundAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  215354. : inputDeviceName,
  215355. outputIndex, inputIndex);
  215356. return 0;
  215357. }
  215358. juce_UseDebuggingNewOperator
  215359. StringArray outputDeviceNames;
  215360. OwnedArray <GUID> outputGuids;
  215361. StringArray inputDeviceNames;
  215362. OwnedArray <GUID> inputGuids;
  215363. private:
  215364. bool hasScanned;
  215365. BOOL outputEnumProc (LPGUID lpGUID, String desc)
  215366. {
  215367. desc = desc.trim();
  215368. if (desc.isNotEmpty())
  215369. {
  215370. const String origDesc (desc);
  215371. int n = 2;
  215372. while (outputDeviceNames.contains (desc))
  215373. desc = origDesc + " (" + String (n++) + ")";
  215374. outputDeviceNames.add (desc);
  215375. if (lpGUID != 0)
  215376. outputGuids.add (new GUID (*lpGUID));
  215377. else
  215378. outputGuids.add (0);
  215379. }
  215380. return TRUE;
  215381. }
  215382. static BOOL CALLBACK outputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  215383. {
  215384. return ((DSoundAudioIODeviceType*) object)
  215385. ->outputEnumProc (lpGUID, String (description));
  215386. }
  215387. static BOOL CALLBACK outputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  215388. {
  215389. return ((DSoundAudioIODeviceType*) object)
  215390. ->outputEnumProc (lpGUID, String (description));
  215391. }
  215392. BOOL CALLBACK inputEnumProc (LPGUID lpGUID, String desc)
  215393. {
  215394. desc = desc.trim();
  215395. if (desc.isNotEmpty())
  215396. {
  215397. const String origDesc (desc);
  215398. int n = 2;
  215399. while (inputDeviceNames.contains (desc))
  215400. desc = origDesc + " (" + String (n++) + ")";
  215401. inputDeviceNames.add (desc);
  215402. if (lpGUID != 0)
  215403. inputGuids.add (new GUID (*lpGUID));
  215404. else
  215405. inputGuids.add (0);
  215406. }
  215407. return TRUE;
  215408. }
  215409. static BOOL CALLBACK inputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  215410. {
  215411. return ((DSoundAudioIODeviceType*) object)
  215412. ->inputEnumProc (lpGUID, String (description));
  215413. }
  215414. static BOOL CALLBACK inputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  215415. {
  215416. return ((DSoundAudioIODeviceType*) object)
  215417. ->inputEnumProc (lpGUID, String (description));
  215418. }
  215419. DSoundAudioIODeviceType (const DSoundAudioIODeviceType&);
  215420. DSoundAudioIODeviceType& operator= (const DSoundAudioIODeviceType&);
  215421. };
  215422. const String DSoundAudioIODevice::openDevice (const BigInteger& inputChannels,
  215423. const BigInteger& outputChannels,
  215424. double sampleRate_,
  215425. int bufferSizeSamples_)
  215426. {
  215427. closeDevice();
  215428. totalSamplesOut = 0;
  215429. sampleRate = sampleRate_;
  215430. if (bufferSizeSamples_ <= 0)
  215431. bufferSizeSamples_ = 960; // use as a default size if none is set.
  215432. bufferSizeSamples = bufferSizeSamples_ & ~7;
  215433. DSoundAudioIODeviceType dlh;
  215434. dlh.scanForDevices();
  215435. enabledInputs = inputChannels;
  215436. enabledInputs.setRange (inChannels.size(),
  215437. enabledInputs.getHighestBit() + 1 - inChannels.size(),
  215438. false);
  215439. inputBuffers.setSize (jmax (1, enabledInputs.countNumberOfSetBits()), bufferSizeSamples);
  215440. inputBuffers.clear();
  215441. int i, numIns = 0;
  215442. for (i = 0; i <= enabledInputs.getHighestBit(); i += 2)
  215443. {
  215444. float* left = 0;
  215445. if (enabledInputs[i])
  215446. left = inputBuffers.getSampleData (numIns++);
  215447. float* right = 0;
  215448. if (enabledInputs[i + 1])
  215449. right = inputBuffers.getSampleData (numIns++);
  215450. if (left != 0 || right != 0)
  215451. inChans.add (new DSoundInternalInChannel (dlh.inputDeviceNames [inputDeviceIndex],
  215452. dlh.inputGuids [inputDeviceIndex],
  215453. (int) sampleRate, bufferSizeSamples,
  215454. left, right));
  215455. }
  215456. enabledOutputs = outputChannels;
  215457. enabledOutputs.setRange (outChannels.size(),
  215458. enabledOutputs.getHighestBit() + 1 - outChannels.size(),
  215459. false);
  215460. outputBuffers.setSize (jmax (1, enabledOutputs.countNumberOfSetBits()), bufferSizeSamples);
  215461. outputBuffers.clear();
  215462. int numOuts = 0;
  215463. for (i = 0; i <= enabledOutputs.getHighestBit(); i += 2)
  215464. {
  215465. float* left = 0;
  215466. if (enabledOutputs[i])
  215467. left = outputBuffers.getSampleData (numOuts++);
  215468. float* right = 0;
  215469. if (enabledOutputs[i + 1])
  215470. right = outputBuffers.getSampleData (numOuts++);
  215471. if (left != 0 || right != 0)
  215472. outChans.add (new DSoundInternalOutChannel (dlh.outputDeviceNames[outputDeviceIndex],
  215473. dlh.outputGuids [outputDeviceIndex],
  215474. (int) sampleRate, bufferSizeSamples,
  215475. left, right));
  215476. }
  215477. String error;
  215478. // boost our priority while opening the devices to try to get better sync between them
  215479. const int oldThreadPri = GetThreadPriority (GetCurrentThread());
  215480. const int oldProcPri = GetPriorityClass (GetCurrentProcess());
  215481. SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  215482. SetPriorityClass (GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
  215483. for (i = 0; i < outChans.size(); ++i)
  215484. {
  215485. error = outChans[i]->open();
  215486. if (error.isNotEmpty())
  215487. {
  215488. error = "Error opening " + dlh.outputDeviceNames[i] + ": \"" + error + "\"";
  215489. break;
  215490. }
  215491. }
  215492. if (error.isEmpty())
  215493. {
  215494. for (i = 0; i < inChans.size(); ++i)
  215495. {
  215496. error = inChans[i]->open();
  215497. if (error.isNotEmpty())
  215498. {
  215499. error = "Error opening " + dlh.inputDeviceNames[i] + ": \"" + error + "\"";
  215500. break;
  215501. }
  215502. }
  215503. }
  215504. if (error.isEmpty())
  215505. {
  215506. totalSamplesOut = 0;
  215507. for (i = 0; i < outChans.size(); ++i)
  215508. outChans.getUnchecked(i)->synchronisePosition();
  215509. for (i = 0; i < inChans.size(); ++i)
  215510. inChans.getUnchecked(i)->synchronisePosition();
  215511. startThread (9);
  215512. sleep (10);
  215513. notify();
  215514. }
  215515. else
  215516. {
  215517. log (error);
  215518. }
  215519. SetThreadPriority (GetCurrentThread(), oldThreadPri);
  215520. SetPriorityClass (GetCurrentProcess(), oldProcPri);
  215521. return error;
  215522. }
  215523. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound()
  215524. {
  215525. return new DSoundAudioIODeviceType();
  215526. }
  215527. #undef log
  215528. #endif
  215529. /*** End of inlined file: juce_win32_DirectSound.cpp ***/
  215530. /*** Start of inlined file: juce_win32_WASAPI.cpp ***/
  215531. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  215532. // compiled on its own).
  215533. #if JUCE_INCLUDED_FILE && JUCE_WASAPI
  215534. #ifndef WASAPI_ENABLE_LOGGING
  215535. #define WASAPI_ENABLE_LOGGING 1
  215536. #endif
  215537. namespace WasapiClasses
  215538. {
  215539. static void logFailure (HRESULT hr)
  215540. {
  215541. (void) hr;
  215542. #if WASAPI_ENABLE_LOGGING
  215543. if (FAILED (hr))
  215544. {
  215545. String e;
  215546. e << Time::getCurrentTime().toString (true, true, true, true)
  215547. << " -- WASAPI error: ";
  215548. switch (hr)
  215549. {
  215550. case E_POINTER: e << "E_POINTER"; break;
  215551. case E_INVALIDARG: e << "E_INVALIDARG"; break;
  215552. case AUDCLNT_E_NOT_INITIALIZED: e << "AUDCLNT_E_NOT_INITIALIZED"; break;
  215553. case AUDCLNT_E_ALREADY_INITIALIZED: e << "AUDCLNT_E_ALREADY_INITIALIZED"; break;
  215554. case AUDCLNT_E_WRONG_ENDPOINT_TYPE: e << "AUDCLNT_E_WRONG_ENDPOINT_TYPE"; break;
  215555. case AUDCLNT_E_DEVICE_INVALIDATED: e << "AUDCLNT_E_DEVICE_INVALIDATED"; break;
  215556. case AUDCLNT_E_NOT_STOPPED: e << "AUDCLNT_E_NOT_STOPPED"; break;
  215557. case AUDCLNT_E_BUFFER_TOO_LARGE: e << "AUDCLNT_E_BUFFER_TOO_LARGE"; break;
  215558. case AUDCLNT_E_OUT_OF_ORDER: e << "AUDCLNT_E_OUT_OF_ORDER"; break;
  215559. case AUDCLNT_E_UNSUPPORTED_FORMAT: e << "AUDCLNT_E_UNSUPPORTED_FORMAT"; break;
  215560. case AUDCLNT_E_INVALID_SIZE: e << "AUDCLNT_E_INVALID_SIZE"; break;
  215561. case AUDCLNT_E_DEVICE_IN_USE: e << "AUDCLNT_E_DEVICE_IN_USE"; break;
  215562. case AUDCLNT_E_BUFFER_OPERATION_PENDING: e << "AUDCLNT_E_BUFFER_OPERATION_PENDING"; break;
  215563. case AUDCLNT_E_THREAD_NOT_REGISTERED: e << "AUDCLNT_E_THREAD_NOT_REGISTERED"; break;
  215564. case AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED: e << "AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED"; break;
  215565. case AUDCLNT_E_ENDPOINT_CREATE_FAILED: e << "AUDCLNT_E_ENDPOINT_CREATE_FAILED"; break;
  215566. case AUDCLNT_E_SERVICE_NOT_RUNNING: e << "AUDCLNT_E_SERVICE_NOT_RUNNING"; break;
  215567. case AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED: e << "AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED"; break;
  215568. case AUDCLNT_E_EXCLUSIVE_MODE_ONLY: e << "AUDCLNT_E_EXCLUSIVE_MODE_ONLY"; break;
  215569. case AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL: e << "AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL"; break;
  215570. case AUDCLNT_E_EVENTHANDLE_NOT_SET: e << "AUDCLNT_E_EVENTHANDLE_NOT_SET"; break;
  215571. case AUDCLNT_E_INCORRECT_BUFFER_SIZE: e << "AUDCLNT_E_INCORRECT_BUFFER_SIZE"; break;
  215572. case AUDCLNT_E_BUFFER_SIZE_ERROR: e << "AUDCLNT_E_BUFFER_SIZE_ERROR"; break;
  215573. case AUDCLNT_S_BUFFER_EMPTY: e << "AUDCLNT_S_BUFFER_EMPTY"; break;
  215574. case AUDCLNT_S_THREAD_ALREADY_REGISTERED: e << "AUDCLNT_S_THREAD_ALREADY_REGISTERED"; break;
  215575. default: e << String::toHexString ((int) hr); break;
  215576. }
  215577. DBG (e);
  215578. jassertfalse;
  215579. }
  215580. #endif
  215581. }
  215582. #undef check
  215583. static bool check (HRESULT hr)
  215584. {
  215585. logFailure (hr);
  215586. return SUCCEEDED (hr);
  215587. }
  215588. static const String getDeviceID (IMMDevice* const device)
  215589. {
  215590. String s;
  215591. WCHAR* deviceId = 0;
  215592. if (check (device->GetId (&deviceId)))
  215593. {
  215594. s = String (deviceId);
  215595. CoTaskMemFree (deviceId);
  215596. }
  215597. return s;
  215598. }
  215599. static EDataFlow getDataFlow (const ComSmartPtr<IMMDevice>& device)
  215600. {
  215601. EDataFlow flow = eRender;
  215602. ComSmartPtr <IMMEndpoint> endPoint;
  215603. if (check (device.QueryInterface (__uuidof (IMMEndpoint), endPoint)))
  215604. (void) check (endPoint->GetDataFlow (&flow));
  215605. return flow;
  215606. }
  215607. static int refTimeToSamples (const REFERENCE_TIME& t, const double sampleRate) throw()
  215608. {
  215609. return roundDoubleToInt (sampleRate * ((double) t) * 0.0000001);
  215610. }
  215611. static void copyWavFormat (WAVEFORMATEXTENSIBLE& dest, const WAVEFORMATEX* const src) throw()
  215612. {
  215613. memcpy (&dest, src, src->wFormatTag == WAVE_FORMAT_EXTENSIBLE ? sizeof (WAVEFORMATEXTENSIBLE)
  215614. : sizeof (WAVEFORMATEX));
  215615. }
  215616. class WASAPIDeviceBase
  215617. {
  215618. public:
  215619. WASAPIDeviceBase (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  215620. : device (device_),
  215621. sampleRate (0),
  215622. numChannels (0),
  215623. actualNumChannels (0),
  215624. defaultSampleRate (0),
  215625. minBufferSize (0),
  215626. defaultBufferSize (0),
  215627. latencySamples (0),
  215628. useExclusiveMode (useExclusiveMode_)
  215629. {
  215630. clientEvent = CreateEvent (0, false, false, _T("JuceWASAPI"));
  215631. ComSmartPtr <IAudioClient> tempClient (createClient());
  215632. if (tempClient == 0)
  215633. return;
  215634. REFERENCE_TIME defaultPeriod, minPeriod;
  215635. if (! check (tempClient->GetDevicePeriod (&defaultPeriod, &minPeriod)))
  215636. return;
  215637. WAVEFORMATEX* mixFormat = 0;
  215638. if (! check (tempClient->GetMixFormat (&mixFormat)))
  215639. return;
  215640. WAVEFORMATEXTENSIBLE format;
  215641. copyWavFormat (format, mixFormat);
  215642. CoTaskMemFree (mixFormat);
  215643. actualNumChannels = numChannels = format.Format.nChannels;
  215644. defaultSampleRate = format.Format.nSamplesPerSec;
  215645. minBufferSize = refTimeToSamples (minPeriod, defaultSampleRate);
  215646. defaultBufferSize = refTimeToSamples (defaultPeriod, defaultSampleRate);
  215647. rates.addUsingDefaultSort (defaultSampleRate);
  215648. static const double ratesToTest[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  215649. for (int i = 0; i < numElementsInArray (ratesToTest); ++i)
  215650. {
  215651. if (ratesToTest[i] == defaultSampleRate)
  215652. continue;
  215653. format.Format.nSamplesPerSec = roundDoubleToInt (ratesToTest[i]);
  215654. if (SUCCEEDED (tempClient->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  215655. (WAVEFORMATEX*) &format, 0)))
  215656. if (! rates.contains (ratesToTest[i]))
  215657. rates.addUsingDefaultSort (ratesToTest[i]);
  215658. }
  215659. }
  215660. ~WASAPIDeviceBase()
  215661. {
  215662. device = 0;
  215663. CloseHandle (clientEvent);
  215664. }
  215665. bool isOk() const throw() { return defaultBufferSize > 0 && defaultSampleRate > 0; }
  215666. bool openClient (const double newSampleRate, const BigInteger& newChannels)
  215667. {
  215668. sampleRate = newSampleRate;
  215669. channels = newChannels;
  215670. channels.setRange (actualNumChannels, channels.getHighestBit() + 1 - actualNumChannels, false);
  215671. numChannels = channels.getHighestBit() + 1;
  215672. if (numChannels == 0)
  215673. return true;
  215674. client = createClient();
  215675. if (client != 0
  215676. && (tryInitialisingWithFormat (true, 4) || tryInitialisingWithFormat (false, 4)
  215677. || tryInitialisingWithFormat (false, 3) || tryInitialisingWithFormat (false, 2)))
  215678. {
  215679. channelMaps.clear();
  215680. for (int i = 0; i <= channels.getHighestBit(); ++i)
  215681. if (channels[i])
  215682. channelMaps.add (i);
  215683. REFERENCE_TIME latency;
  215684. if (check (client->GetStreamLatency (&latency)))
  215685. latencySamples = refTimeToSamples (latency, sampleRate);
  215686. (void) check (client->GetBufferSize (&actualBufferSize));
  215687. return check (client->SetEventHandle (clientEvent));
  215688. }
  215689. return false;
  215690. }
  215691. void closeClient()
  215692. {
  215693. if (client != 0)
  215694. client->Stop();
  215695. client = 0;
  215696. ResetEvent (clientEvent);
  215697. }
  215698. ComSmartPtr <IMMDevice> device;
  215699. ComSmartPtr <IAudioClient> client;
  215700. double sampleRate, defaultSampleRate;
  215701. int numChannels, actualNumChannels;
  215702. int minBufferSize, defaultBufferSize, latencySamples;
  215703. const bool useExclusiveMode;
  215704. Array <double> rates;
  215705. HANDLE clientEvent;
  215706. BigInteger channels;
  215707. Array <int> channelMaps;
  215708. UINT32 actualBufferSize;
  215709. int bytesPerSample;
  215710. virtual void updateFormat (bool isFloat) = 0;
  215711. private:
  215712. const ComSmartPtr <IAudioClient> createClient()
  215713. {
  215714. ComSmartPtr <IAudioClient> client;
  215715. if (device != 0)
  215716. {
  215717. HRESULT hr = device->Activate (__uuidof (IAudioClient), CLSCTX_INPROC_SERVER, 0, (void**) client.resetAndGetPointerAddress());
  215718. logFailure (hr);
  215719. }
  215720. return client;
  215721. }
  215722. bool tryInitialisingWithFormat (const bool useFloat, const int bytesPerSampleToTry)
  215723. {
  215724. WAVEFORMATEXTENSIBLE format;
  215725. zerostruct (format);
  215726. if (numChannels <= 2 && bytesPerSampleToTry <= 2)
  215727. {
  215728. format.Format.wFormatTag = WAVE_FORMAT_PCM;
  215729. }
  215730. else
  215731. {
  215732. format.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
  215733. format.Format.cbSize = sizeof (WAVEFORMATEXTENSIBLE) - sizeof (WAVEFORMATEX);
  215734. }
  215735. format.Format.nSamplesPerSec = roundDoubleToInt (sampleRate);
  215736. format.Format.nChannels = (WORD) numChannels;
  215737. format.Format.wBitsPerSample = (WORD) (8 * bytesPerSampleToTry);
  215738. format.Format.nAvgBytesPerSec = (DWORD) (format.Format.nSamplesPerSec * numChannels * bytesPerSampleToTry);
  215739. format.Format.nBlockAlign = (WORD) (numChannels * bytesPerSampleToTry);
  215740. format.SubFormat = useFloat ? KSDATAFORMAT_SUBTYPE_IEEE_FLOAT : KSDATAFORMAT_SUBTYPE_PCM;
  215741. format.Samples.wValidBitsPerSample = format.Format.wBitsPerSample;
  215742. switch (numChannels)
  215743. {
  215744. case 1: format.dwChannelMask = SPEAKER_FRONT_CENTER; break;
  215745. case 2: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; break;
  215746. case 4: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  215747. case 6: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  215748. 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;
  215749. default: break;
  215750. }
  215751. WAVEFORMATEXTENSIBLE* nearestFormat = 0;
  215752. HRESULT hr = client->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  215753. (WAVEFORMATEX*) &format, useExclusiveMode ? 0 : (WAVEFORMATEX**) &nearestFormat);
  215754. logFailure (hr);
  215755. if (hr == S_FALSE && format.Format.nSamplesPerSec == nearestFormat->Format.nSamplesPerSec)
  215756. {
  215757. copyWavFormat (format, (WAVEFORMATEX*) nearestFormat);
  215758. hr = S_OK;
  215759. }
  215760. CoTaskMemFree (nearestFormat);
  215761. REFERENCE_TIME defaultPeriod = 0, minPeriod = 0;
  215762. if (useExclusiveMode)
  215763. check (client->GetDevicePeriod (&defaultPeriod, &minPeriod));
  215764. GUID session;
  215765. if (hr == S_OK
  215766. && check (client->Initialize (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  215767. AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
  215768. defaultPeriod, defaultPeriod, (WAVEFORMATEX*) &format, &session)))
  215769. {
  215770. actualNumChannels = format.Format.nChannels;
  215771. const bool isFloat = format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE && format.SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
  215772. bytesPerSample = format.Format.wBitsPerSample / 8;
  215773. updateFormat (isFloat);
  215774. return true;
  215775. }
  215776. return false;
  215777. }
  215778. WASAPIDeviceBase (const WASAPIDeviceBase&);
  215779. WASAPIDeviceBase& operator= (const WASAPIDeviceBase&);
  215780. };
  215781. class WASAPIInputDevice : public WASAPIDeviceBase
  215782. {
  215783. public:
  215784. WASAPIInputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  215785. : WASAPIDeviceBase (device_, useExclusiveMode_),
  215786. reservoir (1, 1)
  215787. {
  215788. }
  215789. ~WASAPIInputDevice()
  215790. {
  215791. close();
  215792. }
  215793. bool open (const double newSampleRate, const BigInteger& newChannels)
  215794. {
  215795. reservoirSize = 0;
  215796. reservoirCapacity = 16384;
  215797. reservoir.setSize (actualNumChannels * reservoirCapacity * sizeof (float));
  215798. return openClient (newSampleRate, newChannels)
  215799. && (numChannels == 0 || check (client->GetService (__uuidof (IAudioCaptureClient), (void**) captureClient.resetAndGetPointerAddress())));
  215800. }
  215801. void close()
  215802. {
  215803. closeClient();
  215804. captureClient = 0;
  215805. reservoir.setSize (0);
  215806. }
  215807. void updateFormat (bool isFloat)
  215808. {
  215809. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> NativeType;
  215810. if (isFloat)
  215811. converter = new AudioData::ConverterInstance <AudioData::Pointer <AudioData::Float32, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, NativeType> (actualNumChannels, 1);
  215812. else if (bytesPerSample == 4)
  215813. converter = new AudioData::ConverterInstance <AudioData::Pointer <AudioData::Int32, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, NativeType> (actualNumChannels, 1);
  215814. else if (bytesPerSample == 3)
  215815. converter = new AudioData::ConverterInstance <AudioData::Pointer <AudioData::Int24, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, NativeType> (actualNumChannels, 1);
  215816. else
  215817. converter = new AudioData::ConverterInstance <AudioData::Pointer <AudioData::Int16, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, NativeType> (actualNumChannels, 1);
  215818. }
  215819. void copyBuffers (float** destBuffers, int numDestBuffers, int bufferSize, Thread& thread)
  215820. {
  215821. if (numChannels <= 0)
  215822. return;
  215823. int offset = 0;
  215824. while (bufferSize > 0)
  215825. {
  215826. if (reservoirSize > 0) // There's stuff in the reservoir, so use that...
  215827. {
  215828. const int samplesToDo = jmin (bufferSize, (int) reservoirSize);
  215829. for (int i = 0; i < numDestBuffers; ++i)
  215830. converter->convertSamples (destBuffers[i], offset, reservoir.getData(), channelMaps.getUnchecked(i), samplesToDo);
  215831. bufferSize -= samplesToDo;
  215832. offset += samplesToDo;
  215833. reservoirSize -= samplesToDo;
  215834. }
  215835. else
  215836. {
  215837. UINT32 packetLength = 0;
  215838. if (! check (captureClient->GetNextPacketSize (&packetLength)))
  215839. break;
  215840. if (packetLength == 0)
  215841. {
  215842. if (thread.threadShouldExit())
  215843. break;
  215844. Thread::sleep (1);
  215845. continue;
  215846. }
  215847. uint8* inputData = 0;
  215848. UINT32 numSamplesAvailable;
  215849. DWORD flags;
  215850. if (check (captureClient->GetBuffer (&inputData, &numSamplesAvailable, &flags, 0, 0)))
  215851. {
  215852. const int samplesToDo = jmin (bufferSize, (int) numSamplesAvailable);
  215853. for (int i = 0; i < numDestBuffers; ++i)
  215854. converter->convertSamples (destBuffers[i], offset, inputData, channelMaps.getUnchecked(i), samplesToDo);
  215855. bufferSize -= samplesToDo;
  215856. offset += samplesToDo;
  215857. if (samplesToDo < (int) numSamplesAvailable)
  215858. {
  215859. reservoirSize = jmin ((int) (numSamplesAvailable - samplesToDo), reservoirCapacity);
  215860. memcpy ((uint8*) reservoir.getData(), inputData + bytesPerSample * actualNumChannels * samplesToDo,
  215861. bytesPerSample * actualNumChannels * reservoirSize);
  215862. }
  215863. captureClient->ReleaseBuffer (numSamplesAvailable);
  215864. }
  215865. }
  215866. }
  215867. }
  215868. ComSmartPtr <IAudioCaptureClient> captureClient;
  215869. MemoryBlock reservoir;
  215870. int reservoirSize, reservoirCapacity;
  215871. ScopedPointer <AudioData::Converter> converter;
  215872. private:
  215873. WASAPIInputDevice (const WASAPIInputDevice&);
  215874. WASAPIInputDevice& operator= (const WASAPIInputDevice&);
  215875. };
  215876. class WASAPIOutputDevice : public WASAPIDeviceBase
  215877. {
  215878. public:
  215879. WASAPIOutputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  215880. : WASAPIDeviceBase (device_, useExclusiveMode_)
  215881. {
  215882. }
  215883. ~WASAPIOutputDevice()
  215884. {
  215885. close();
  215886. }
  215887. bool open (const double newSampleRate, const BigInteger& newChannels)
  215888. {
  215889. return openClient (newSampleRate, newChannels)
  215890. && (numChannels == 0 || check (client->GetService (__uuidof (IAudioRenderClient), (void**) renderClient.resetAndGetPointerAddress())));
  215891. }
  215892. void close()
  215893. {
  215894. closeClient();
  215895. renderClient = 0;
  215896. }
  215897. void updateFormat (bool isFloat)
  215898. {
  215899. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> NativeType;
  215900. if (isFloat)
  215901. converter = new AudioData::ConverterInstance <NativeType, AudioData::Pointer <AudioData::Float32, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, actualNumChannels);
  215902. else if (bytesPerSample == 4)
  215903. converter = new AudioData::ConverterInstance <NativeType, AudioData::Pointer <AudioData::Int32, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, actualNumChannels);
  215904. else if (bytesPerSample == 3)
  215905. converter = new AudioData::ConverterInstance <NativeType, AudioData::Pointer <AudioData::Int24, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, actualNumChannels);
  215906. else
  215907. converter = new AudioData::ConverterInstance <NativeType, AudioData::Pointer <AudioData::Int16, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, actualNumChannels);
  215908. }
  215909. void copyBuffers (const float** const srcBuffers, const int numSrcBuffers, int bufferSize, Thread& thread)
  215910. {
  215911. if (numChannels <= 0)
  215912. return;
  215913. int offset = 0;
  215914. while (bufferSize > 0)
  215915. {
  215916. UINT32 padding = 0;
  215917. if (! check (client->GetCurrentPadding (&padding)))
  215918. return;
  215919. int samplesToDo = useExclusiveMode ? bufferSize
  215920. : jmin ((int) (actualBufferSize - padding), bufferSize);
  215921. if (samplesToDo <= 0)
  215922. {
  215923. if (thread.threadShouldExit())
  215924. break;
  215925. Thread::sleep (0);
  215926. continue;
  215927. }
  215928. uint8* outputData = 0;
  215929. if (check (renderClient->GetBuffer (samplesToDo, &outputData)))
  215930. {
  215931. for (int i = 0; i < numSrcBuffers; ++i)
  215932. converter->convertSamples (outputData, channelMaps.getUnchecked(i), srcBuffers[i], offset, samplesToDo);
  215933. renderClient->ReleaseBuffer (samplesToDo, 0);
  215934. offset += samplesToDo;
  215935. bufferSize -= samplesToDo;
  215936. }
  215937. }
  215938. }
  215939. ComSmartPtr <IAudioRenderClient> renderClient;
  215940. ScopedPointer <AudioData::Converter> converter;
  215941. private:
  215942. WASAPIOutputDevice (const WASAPIOutputDevice&);
  215943. WASAPIOutputDevice& operator= (const WASAPIOutputDevice&);
  215944. };
  215945. class WASAPIAudioIODevice : public AudioIODevice,
  215946. public Thread
  215947. {
  215948. public:
  215949. WASAPIAudioIODevice (const String& deviceName,
  215950. const String& outputDeviceId_,
  215951. const String& inputDeviceId_,
  215952. const bool useExclusiveMode_)
  215953. : AudioIODevice (deviceName, "Windows Audio"),
  215954. Thread ("Juce WASAPI"),
  215955. isOpen_ (false),
  215956. isStarted (false),
  215957. outputDeviceId (outputDeviceId_),
  215958. inputDeviceId (inputDeviceId_),
  215959. useExclusiveMode (useExclusiveMode_),
  215960. currentBufferSizeSamples (0),
  215961. currentSampleRate (0),
  215962. callback (0)
  215963. {
  215964. }
  215965. ~WASAPIAudioIODevice()
  215966. {
  215967. close();
  215968. }
  215969. bool initialise()
  215970. {
  215971. double defaultSampleRateIn = 0, defaultSampleRateOut = 0;
  215972. int minBufferSizeIn = 0, defaultBufferSizeIn = 0, minBufferSizeOut = 0, defaultBufferSizeOut = 0;
  215973. latencyIn = latencyOut = 0;
  215974. Array <double> ratesIn, ratesOut;
  215975. if (createDevices())
  215976. {
  215977. jassert (inputDevice != 0 || outputDevice != 0);
  215978. if (inputDevice != 0 && outputDevice != 0)
  215979. {
  215980. defaultSampleRate = jmin (inputDevice->defaultSampleRate, outputDevice->defaultSampleRate);
  215981. minBufferSize = jmin (inputDevice->minBufferSize, outputDevice->minBufferSize);
  215982. defaultBufferSize = jmax (inputDevice->defaultBufferSize, outputDevice->defaultBufferSize);
  215983. sampleRates = inputDevice->rates;
  215984. sampleRates.removeValuesNotIn (outputDevice->rates);
  215985. }
  215986. else
  215987. {
  215988. WASAPIDeviceBase* d = inputDevice != 0 ? static_cast<WASAPIDeviceBase*> (inputDevice)
  215989. : static_cast<WASAPIDeviceBase*> (outputDevice);
  215990. defaultSampleRate = d->defaultSampleRate;
  215991. minBufferSize = d->minBufferSize;
  215992. defaultBufferSize = d->defaultBufferSize;
  215993. sampleRates = d->rates;
  215994. }
  215995. bufferSizes.addUsingDefaultSort (defaultBufferSize);
  215996. if (minBufferSize != defaultBufferSize)
  215997. bufferSizes.addUsingDefaultSort (minBufferSize);
  215998. int n = 64;
  215999. for (int i = 0; i < 40; ++i)
  216000. {
  216001. if (n >= minBufferSize && n <= 2048 && ! bufferSizes.contains (n))
  216002. bufferSizes.addUsingDefaultSort (n);
  216003. n += (n < 512) ? 32 : (n < 1024 ? 64 : 128);
  216004. }
  216005. return true;
  216006. }
  216007. return false;
  216008. }
  216009. const StringArray getOutputChannelNames()
  216010. {
  216011. StringArray outChannels;
  216012. if (outputDevice != 0)
  216013. for (int i = 1; i <= outputDevice->actualNumChannels; ++i)
  216014. outChannels.add ("Output channel " + String (i));
  216015. return outChannels;
  216016. }
  216017. const StringArray getInputChannelNames()
  216018. {
  216019. StringArray inChannels;
  216020. if (inputDevice != 0)
  216021. for (int i = 1; i <= inputDevice->actualNumChannels; ++i)
  216022. inChannels.add ("Input channel " + String (i));
  216023. return inChannels;
  216024. }
  216025. int getNumSampleRates() { return sampleRates.size(); }
  216026. double getSampleRate (int index) { return sampleRates [index]; }
  216027. int getNumBufferSizesAvailable() { return bufferSizes.size(); }
  216028. int getBufferSizeSamples (int index) { return bufferSizes [index]; }
  216029. int getDefaultBufferSize() { return defaultBufferSize; }
  216030. int getCurrentBufferSizeSamples() { return currentBufferSizeSamples; }
  216031. double getCurrentSampleRate() { return currentSampleRate; }
  216032. int getCurrentBitDepth() { return 32; }
  216033. int getOutputLatencyInSamples() { return latencyOut; }
  216034. int getInputLatencyInSamples() { return latencyIn; }
  216035. const BigInteger getActiveOutputChannels() const { return outputDevice != 0 ? outputDevice->channels : BigInteger(); }
  216036. const BigInteger getActiveInputChannels() const { return inputDevice != 0 ? inputDevice->channels : BigInteger(); }
  216037. const String getLastError() { return lastError; }
  216038. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  216039. double sampleRate, int bufferSizeSamples)
  216040. {
  216041. close();
  216042. lastError = String::empty;
  216043. if (sampleRates.size() == 0 && inputDevice != 0 && outputDevice != 0)
  216044. {
  216045. lastError = "The input and output devices don't share a common sample rate!";
  216046. return lastError;
  216047. }
  216048. currentBufferSizeSamples = bufferSizeSamples <= 0 ? defaultBufferSize : jmax (bufferSizeSamples, minBufferSize);
  216049. currentSampleRate = sampleRate > 0 ? sampleRate : defaultSampleRate;
  216050. if (inputDevice != 0 && ! inputDevice->open (currentSampleRate, inputChannels))
  216051. {
  216052. lastError = "Couldn't open the input device!";
  216053. return lastError;
  216054. }
  216055. if (outputDevice != 0 && ! outputDevice->open (currentSampleRate, outputChannels))
  216056. {
  216057. close();
  216058. lastError = "Couldn't open the output device!";
  216059. return lastError;
  216060. }
  216061. if (inputDevice != 0)
  216062. ResetEvent (inputDevice->clientEvent);
  216063. if (outputDevice != 0)
  216064. ResetEvent (outputDevice->clientEvent);
  216065. startThread (8);
  216066. Thread::sleep (5);
  216067. if (inputDevice != 0 && inputDevice->client != 0)
  216068. {
  216069. latencyIn = inputDevice->latencySamples + inputDevice->actualBufferSize + inputDevice->minBufferSize;
  216070. HRESULT hr = inputDevice->client->Start();
  216071. logFailure (hr); //xxx handle this
  216072. }
  216073. if (outputDevice != 0 && outputDevice->client != 0)
  216074. {
  216075. latencyOut = outputDevice->latencySamples + outputDevice->actualBufferSize + outputDevice->minBufferSize;
  216076. HRESULT hr = outputDevice->client->Start();
  216077. logFailure (hr); //xxx handle this
  216078. }
  216079. isOpen_ = true;
  216080. return lastError;
  216081. }
  216082. void close()
  216083. {
  216084. stop();
  216085. if (inputDevice != 0)
  216086. SetEvent (inputDevice->clientEvent);
  216087. if (outputDevice != 0)
  216088. SetEvent (outputDevice->clientEvent);
  216089. stopThread (5000);
  216090. if (inputDevice != 0)
  216091. inputDevice->close();
  216092. if (outputDevice != 0)
  216093. outputDevice->close();
  216094. isOpen_ = false;
  216095. }
  216096. bool isOpen() { return isOpen_ && isThreadRunning(); }
  216097. bool isPlaying() { return isStarted && isOpen_ && isThreadRunning(); }
  216098. void start (AudioIODeviceCallback* call)
  216099. {
  216100. if (isOpen_ && call != 0 && ! isStarted)
  216101. {
  216102. if (! isThreadRunning())
  216103. {
  216104. // something's gone wrong and the thread's stopped..
  216105. isOpen_ = false;
  216106. return;
  216107. }
  216108. call->audioDeviceAboutToStart (this);
  216109. const ScopedLock sl (startStopLock);
  216110. callback = call;
  216111. isStarted = true;
  216112. }
  216113. }
  216114. void stop()
  216115. {
  216116. if (isStarted)
  216117. {
  216118. AudioIODeviceCallback* const callbackLocal = callback;
  216119. {
  216120. const ScopedLock sl (startStopLock);
  216121. isStarted = false;
  216122. }
  216123. if (callbackLocal != 0)
  216124. callbackLocal->audioDeviceStopped();
  216125. }
  216126. }
  216127. void setMMThreadPriority()
  216128. {
  216129. DynamicLibraryLoader dll ("avrt.dll");
  216130. DynamicLibraryImport (AvSetMmThreadCharacteristics, avSetMmThreadCharacteristics, HANDLE, dll, (LPCTSTR, LPDWORD))
  216131. DynamicLibraryImport (AvSetMmThreadPriority, avSetMmThreadPriority, HANDLE, dll, (HANDLE, AVRT_PRIORITY))
  216132. if (avSetMmThreadCharacteristics != 0 && avSetMmThreadPriority != 0)
  216133. {
  216134. DWORD dummy = 0;
  216135. HANDLE h = avSetMmThreadCharacteristics (_T("Pro Audio"), &dummy);
  216136. if (h != 0)
  216137. avSetMmThreadPriority (h, AVRT_PRIORITY_NORMAL);
  216138. }
  216139. }
  216140. void run()
  216141. {
  216142. setMMThreadPriority();
  216143. const int bufferSize = currentBufferSizeSamples;
  216144. HANDLE events[2];
  216145. int numEvents = 0;
  216146. if (inputDevice != 0)
  216147. events [numEvents++] = inputDevice->clientEvent;
  216148. if (outputDevice != 0)
  216149. events [numEvents++] = outputDevice->clientEvent;
  216150. const int numInputBuffers = getActiveInputChannels().countNumberOfSetBits();
  216151. const int numOutputBuffers = getActiveOutputChannels().countNumberOfSetBits();
  216152. AudioSampleBuffer ins (jmax (1, numInputBuffers), bufferSize + 32);
  216153. AudioSampleBuffer outs (jmax (1, numOutputBuffers), bufferSize + 32);
  216154. float** const inputBuffers = ins.getArrayOfChannels();
  216155. float** const outputBuffers = outs.getArrayOfChannels();
  216156. ins.clear();
  216157. while (! threadShouldExit())
  216158. {
  216159. const DWORD result = useExclusiveMode ? (inputDevice != 0 ? WaitForSingleObject (inputDevice->clientEvent, 1000) : S_OK)
  216160. : WaitForMultipleObjects (numEvents, events, true, 1000);
  216161. if (result == WAIT_TIMEOUT)
  216162. continue;
  216163. if (threadShouldExit())
  216164. break;
  216165. if (inputDevice != 0)
  216166. inputDevice->copyBuffers (inputBuffers, numInputBuffers, bufferSize, *this);
  216167. // Make the callback..
  216168. {
  216169. const ScopedLock sl (startStopLock);
  216170. if (isStarted)
  216171. {
  216172. JUCE_TRY
  216173. {
  216174. callback->audioDeviceIOCallback ((const float**) inputBuffers,
  216175. numInputBuffers,
  216176. outputBuffers,
  216177. numOutputBuffers,
  216178. bufferSize);
  216179. }
  216180. JUCE_CATCH_EXCEPTION
  216181. }
  216182. else
  216183. {
  216184. outs.clear();
  216185. }
  216186. }
  216187. if (useExclusiveMode && WaitForSingleObject (outputDevice->clientEvent, 1000) == WAIT_TIMEOUT)
  216188. continue;
  216189. if (outputDevice != 0)
  216190. outputDevice->copyBuffers ((const float**) outputBuffers, numOutputBuffers, bufferSize, *this);
  216191. }
  216192. }
  216193. juce_UseDebuggingNewOperator
  216194. String outputDeviceId, inputDeviceId;
  216195. String lastError;
  216196. private:
  216197. // Device stats...
  216198. ScopedPointer<WASAPIInputDevice> inputDevice;
  216199. ScopedPointer<WASAPIOutputDevice> outputDevice;
  216200. const bool useExclusiveMode;
  216201. double defaultSampleRate;
  216202. int minBufferSize, defaultBufferSize;
  216203. int latencyIn, latencyOut;
  216204. Array <double> sampleRates;
  216205. Array <int> bufferSizes;
  216206. // Active state...
  216207. bool isOpen_, isStarted;
  216208. int currentBufferSizeSamples;
  216209. double currentSampleRate;
  216210. AudioIODeviceCallback* callback;
  216211. CriticalSection startStopLock;
  216212. bool createDevices()
  216213. {
  216214. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  216215. if (! check (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  216216. return false;
  216217. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  216218. if (! check (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, deviceCollection.resetAndGetPointerAddress())))
  216219. return false;
  216220. UINT32 numDevices = 0;
  216221. if (! check (deviceCollection->GetCount (&numDevices)))
  216222. return false;
  216223. for (UINT32 i = 0; i < numDevices; ++i)
  216224. {
  216225. ComSmartPtr <IMMDevice> device;
  216226. if (! check (deviceCollection->Item (i, device.resetAndGetPointerAddress())))
  216227. continue;
  216228. const String deviceId (getDeviceID (device));
  216229. if (deviceId.isEmpty())
  216230. continue;
  216231. const EDataFlow flow = getDataFlow (device);
  216232. if (deviceId == inputDeviceId && flow == eCapture)
  216233. inputDevice = new WASAPIInputDevice (device, useExclusiveMode);
  216234. else if (deviceId == outputDeviceId && flow == eRender)
  216235. outputDevice = new WASAPIOutputDevice (device, useExclusiveMode);
  216236. }
  216237. return (outputDeviceId.isEmpty() || (outputDevice != 0 && outputDevice->isOk()))
  216238. && (inputDeviceId.isEmpty() || (inputDevice != 0 && inputDevice->isOk()));
  216239. }
  216240. WASAPIAudioIODevice (const WASAPIAudioIODevice&);
  216241. WASAPIAudioIODevice& operator= (const WASAPIAudioIODevice&);
  216242. };
  216243. class WASAPIAudioIODeviceType : public AudioIODeviceType
  216244. {
  216245. public:
  216246. WASAPIAudioIODeviceType()
  216247. : AudioIODeviceType ("Windows Audio"),
  216248. hasScanned (false)
  216249. {
  216250. }
  216251. ~WASAPIAudioIODeviceType()
  216252. {
  216253. }
  216254. void scanForDevices()
  216255. {
  216256. hasScanned = true;
  216257. outputDeviceNames.clear();
  216258. inputDeviceNames.clear();
  216259. outputDeviceIds.clear();
  216260. inputDeviceIds.clear();
  216261. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  216262. if (! check (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  216263. return;
  216264. const String defaultRenderer = getDefaultEndpoint (enumerator, false);
  216265. const String defaultCapture = getDefaultEndpoint (enumerator, true);
  216266. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  216267. UINT32 numDevices = 0;
  216268. if (! (check (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, deviceCollection.resetAndGetPointerAddress()))
  216269. && check (deviceCollection->GetCount (&numDevices))))
  216270. return;
  216271. for (UINT32 i = 0; i < numDevices; ++i)
  216272. {
  216273. ComSmartPtr <IMMDevice> device;
  216274. if (! check (deviceCollection->Item (i, device.resetAndGetPointerAddress())))
  216275. continue;
  216276. const String deviceId (getDeviceID (device));
  216277. DWORD state = 0;
  216278. if (! check (device->GetState (&state)))
  216279. continue;
  216280. if (state != DEVICE_STATE_ACTIVE)
  216281. continue;
  216282. String name;
  216283. {
  216284. ComSmartPtr <IPropertyStore> properties;
  216285. if (! check (device->OpenPropertyStore (STGM_READ, properties.resetAndGetPointerAddress())))
  216286. continue;
  216287. PROPVARIANT value;
  216288. PropVariantInit (&value);
  216289. if (check (properties->GetValue (PKEY_Device_FriendlyName, &value)))
  216290. name = value.pwszVal;
  216291. PropVariantClear (&value);
  216292. }
  216293. const EDataFlow flow = getDataFlow (device);
  216294. if (flow == eRender)
  216295. {
  216296. const int index = (deviceId == defaultRenderer) ? 0 : -1;
  216297. outputDeviceIds.insert (index, deviceId);
  216298. outputDeviceNames.insert (index, name);
  216299. }
  216300. else if (flow == eCapture)
  216301. {
  216302. const int index = (deviceId == defaultCapture) ? 0 : -1;
  216303. inputDeviceIds.insert (index, deviceId);
  216304. inputDeviceNames.insert (index, name);
  216305. }
  216306. }
  216307. inputDeviceNames.appendNumbersToDuplicates (false, false);
  216308. outputDeviceNames.appendNumbersToDuplicates (false, false);
  216309. }
  216310. const StringArray getDeviceNames (bool wantInputNames) const
  216311. {
  216312. jassert (hasScanned); // need to call scanForDevices() before doing this
  216313. return wantInputNames ? inputDeviceNames
  216314. : outputDeviceNames;
  216315. }
  216316. int getDefaultDeviceIndex (bool /*forInput*/) const
  216317. {
  216318. jassert (hasScanned); // need to call scanForDevices() before doing this
  216319. return 0;
  216320. }
  216321. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  216322. {
  216323. jassert (hasScanned); // need to call scanForDevices() before doing this
  216324. WASAPIAudioIODevice* const d = dynamic_cast <WASAPIAudioIODevice*> (device);
  216325. return d == 0 ? -1 : (asInput ? inputDeviceIds.indexOf (d->inputDeviceId)
  216326. : outputDeviceIds.indexOf (d->outputDeviceId));
  216327. }
  216328. bool hasSeparateInputsAndOutputs() const { return true; }
  216329. AudioIODevice* createDevice (const String& outputDeviceName,
  216330. const String& inputDeviceName)
  216331. {
  216332. jassert (hasScanned); // need to call scanForDevices() before doing this
  216333. const bool useExclusiveMode = false;
  216334. ScopedPointer<WASAPIAudioIODevice> device;
  216335. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  216336. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  216337. if (outputIndex >= 0 || inputIndex >= 0)
  216338. {
  216339. device = new WASAPIAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  216340. : inputDeviceName,
  216341. outputDeviceIds [outputIndex],
  216342. inputDeviceIds [inputIndex],
  216343. useExclusiveMode);
  216344. if (! device->initialise())
  216345. device = 0;
  216346. }
  216347. return device.release();
  216348. }
  216349. juce_UseDebuggingNewOperator
  216350. StringArray outputDeviceNames, outputDeviceIds;
  216351. StringArray inputDeviceNames, inputDeviceIds;
  216352. private:
  216353. bool hasScanned;
  216354. static const String getDefaultEndpoint (IMMDeviceEnumerator* const enumerator, const bool forCapture)
  216355. {
  216356. String s;
  216357. IMMDevice* dev = 0;
  216358. if (check (enumerator->GetDefaultAudioEndpoint (forCapture ? eCapture : eRender,
  216359. eMultimedia, &dev)))
  216360. {
  216361. WCHAR* deviceId = 0;
  216362. if (check (dev->GetId (&deviceId)))
  216363. {
  216364. s = String (deviceId);
  216365. CoTaskMemFree (deviceId);
  216366. }
  216367. dev->Release();
  216368. }
  216369. return s;
  216370. }
  216371. WASAPIAudioIODeviceType (const WASAPIAudioIODeviceType&);
  216372. WASAPIAudioIODeviceType& operator= (const WASAPIAudioIODeviceType&);
  216373. };
  216374. }
  216375. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI()
  216376. {
  216377. return new WasapiClasses::WASAPIAudioIODeviceType();
  216378. }
  216379. #endif
  216380. /*** End of inlined file: juce_win32_WASAPI.cpp ***/
  216381. /*** Start of inlined file: juce_win32_CameraDevice.cpp ***/
  216382. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  216383. // compiled on its own).
  216384. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  216385. class DShowCameraDeviceInteral : public ChangeBroadcaster
  216386. {
  216387. public:
  216388. DShowCameraDeviceInteral (CameraDevice* const owner_,
  216389. const ComSmartPtr <ICaptureGraphBuilder2>& captureGraphBuilder_,
  216390. const ComSmartPtr <IBaseFilter>& filter_,
  216391. int minWidth, int minHeight,
  216392. int maxWidth, int maxHeight)
  216393. : owner (owner_),
  216394. captureGraphBuilder (captureGraphBuilder_),
  216395. filter (filter_),
  216396. ok (false),
  216397. imageNeedsFlipping (false),
  216398. width (0),
  216399. height (0),
  216400. activeUsers (0),
  216401. recordNextFrameTime (false),
  216402. previewMaxFPS (60)
  216403. {
  216404. HRESULT hr = graphBuilder.CoCreateInstance (CLSID_FilterGraph);
  216405. if (FAILED (hr))
  216406. return;
  216407. hr = captureGraphBuilder->SetFiltergraph (graphBuilder);
  216408. if (FAILED (hr))
  216409. return;
  216410. hr = graphBuilder.QueryInterface (IID_IMediaControl, mediaControl);
  216411. if (FAILED (hr))
  216412. return;
  216413. {
  216414. ComSmartPtr <IAMStreamConfig> streamConfig;
  216415. hr = captureGraphBuilder->FindInterface (&PIN_CATEGORY_CAPTURE, 0, filter,
  216416. IID_IAMStreamConfig, (void**) streamConfig.resetAndGetPointerAddress());
  216417. if (streamConfig != 0)
  216418. {
  216419. getVideoSizes (streamConfig);
  216420. if (! selectVideoSize (streamConfig, minWidth, minHeight, maxWidth, maxHeight))
  216421. return;
  216422. }
  216423. }
  216424. hr = graphBuilder->AddFilter (filter, _T("Video Capture"));
  216425. if (FAILED (hr))
  216426. return;
  216427. hr = smartTee.CoCreateInstance (CLSID_SmartTee);
  216428. if (FAILED (hr))
  216429. return;
  216430. hr = graphBuilder->AddFilter (smartTee, _T("Smart Tee"));
  216431. if (FAILED (hr))
  216432. return;
  216433. if (! connectFilters (filter, smartTee))
  216434. return;
  216435. ComSmartPtr <IBaseFilter> sampleGrabberBase;
  216436. hr = sampleGrabberBase.CoCreateInstance (CLSID_SampleGrabber);
  216437. if (FAILED (hr))
  216438. return;
  216439. hr = sampleGrabberBase.QueryInterface (IID_ISampleGrabber, sampleGrabber);
  216440. if (FAILED (hr))
  216441. return;
  216442. AM_MEDIA_TYPE mt;
  216443. zerostruct (mt);
  216444. mt.majortype = MEDIATYPE_Video;
  216445. mt.subtype = MEDIASUBTYPE_RGB24;
  216446. mt.formattype = FORMAT_VideoInfo;
  216447. sampleGrabber->SetMediaType (&mt);
  216448. callback = new GrabberCallback (*this);
  216449. hr = sampleGrabber->SetCallback (callback, 1);
  216450. hr = graphBuilder->AddFilter (sampleGrabberBase, _T("Sample Grabber"));
  216451. if (FAILED (hr))
  216452. return;
  216453. ComSmartPtr <IPin> grabberInputPin;
  216454. if (! (getPin (smartTee, PINDIR_OUTPUT, smartTeeCaptureOutputPin, "capture")
  216455. && getPin (smartTee, PINDIR_OUTPUT, smartTeePreviewOutputPin, "preview")
  216456. && getPin (sampleGrabberBase, PINDIR_INPUT, grabberInputPin)))
  216457. return;
  216458. hr = graphBuilder->Connect (smartTeePreviewOutputPin, grabberInputPin);
  216459. if (FAILED (hr))
  216460. return;
  216461. zerostruct (mt);
  216462. hr = sampleGrabber->GetConnectedMediaType (&mt);
  216463. VIDEOINFOHEADER* pVih = (VIDEOINFOHEADER*) (mt.pbFormat);
  216464. width = pVih->bmiHeader.biWidth;
  216465. height = pVih->bmiHeader.biHeight;
  216466. ComSmartPtr <IBaseFilter> nullFilter;
  216467. hr = nullFilter.CoCreateInstance (CLSID_NullRenderer);
  216468. hr = graphBuilder->AddFilter (nullFilter, _T("Null Renderer"));
  216469. if (connectFilters (sampleGrabberBase, nullFilter)
  216470. && addGraphToRot())
  216471. {
  216472. activeImage = Image (Image::RGB, width, height, true);
  216473. loadingImage = Image (Image::RGB, width, height, true);
  216474. ok = true;
  216475. }
  216476. }
  216477. ~DShowCameraDeviceInteral()
  216478. {
  216479. if (mediaControl != 0)
  216480. mediaControl->Stop();
  216481. removeGraphFromRot();
  216482. for (int i = viewerComps.size(); --i >= 0;)
  216483. viewerComps.getUnchecked(i)->ownerDeleted();
  216484. callback = 0;
  216485. graphBuilder = 0;
  216486. sampleGrabber = 0;
  216487. mediaControl = 0;
  216488. filter = 0;
  216489. captureGraphBuilder = 0;
  216490. smartTee = 0;
  216491. smartTeePreviewOutputPin = 0;
  216492. smartTeeCaptureOutputPin = 0;
  216493. asfWriter = 0;
  216494. }
  216495. void addUser()
  216496. {
  216497. if (ok && activeUsers++ == 0)
  216498. mediaControl->Run();
  216499. }
  216500. void removeUser()
  216501. {
  216502. if (ok && --activeUsers == 0)
  216503. mediaControl->Stop();
  216504. }
  216505. int getPreviewMaxFPS() const
  216506. {
  216507. return previewMaxFPS;
  216508. }
  216509. void handleFrame (double /*time*/, BYTE* buffer, long /*bufferSize*/)
  216510. {
  216511. if (recordNextFrameTime)
  216512. {
  216513. const double defaultCameraLatency = 0.1;
  216514. firstRecordedTime = Time::getCurrentTime() - RelativeTime (defaultCameraLatency);
  216515. recordNextFrameTime = false;
  216516. ComSmartPtr <IPin> pin;
  216517. if (getPin (filter, PINDIR_OUTPUT, pin))
  216518. {
  216519. ComSmartPtr <IAMPushSource> pushSource;
  216520. HRESULT hr = pin.QueryInterface (IID_IAMPushSource, pushSource);
  216521. if (pushSource != 0)
  216522. {
  216523. REFERENCE_TIME latency = 0;
  216524. hr = pushSource->GetLatency (&latency);
  216525. firstRecordedTime = firstRecordedTime - RelativeTime ((double) latency);
  216526. }
  216527. }
  216528. }
  216529. {
  216530. const int lineStride = width * 3;
  216531. const ScopedLock sl (imageSwapLock);
  216532. {
  216533. const Image::BitmapData destData (loadingImage, 0, 0, width, height, true);
  216534. for (int i = 0; i < height; ++i)
  216535. memcpy (destData.getLinePointer ((height - 1) - i),
  216536. buffer + lineStride * i,
  216537. lineStride);
  216538. }
  216539. imageNeedsFlipping = true;
  216540. }
  216541. if (listeners.size() > 0)
  216542. callListeners (loadingImage);
  216543. sendChangeMessage (this);
  216544. }
  216545. void drawCurrentImage (Graphics& g, int x, int y, int w, int h)
  216546. {
  216547. if (imageNeedsFlipping)
  216548. {
  216549. const ScopedLock sl (imageSwapLock);
  216550. swapVariables (loadingImage, activeImage);
  216551. imageNeedsFlipping = false;
  216552. }
  216553. RectanglePlacement rp (RectanglePlacement::centred);
  216554. double dx = 0, dy = 0, dw = width, dh = height;
  216555. rp.applyTo (dx, dy, dw, dh, x, y, w, h);
  216556. const int rx = roundToInt (dx), ry = roundToInt (dy);
  216557. const int rw = roundToInt (dw), rh = roundToInt (dh);
  216558. g.saveState();
  216559. g.excludeClipRegion (Rectangle<int> (rx, ry, rw, rh));
  216560. g.fillAll (Colours::black);
  216561. g.restoreState();
  216562. g.drawImage (activeImage, rx, ry, rw, rh, 0, 0, width, height);
  216563. }
  216564. bool createFileCaptureFilter (const File& file, int quality)
  216565. {
  216566. removeFileCaptureFilter();
  216567. file.deleteFile();
  216568. mediaControl->Stop();
  216569. firstRecordedTime = Time();
  216570. recordNextFrameTime = true;
  216571. previewMaxFPS = 60;
  216572. HRESULT hr = asfWriter.CoCreateInstance (CLSID_WMAsfWriter);
  216573. if (SUCCEEDED (hr))
  216574. {
  216575. ComSmartPtr <IFileSinkFilter> fileSink;
  216576. hr = asfWriter.QueryInterface (IID_IFileSinkFilter, fileSink);
  216577. if (SUCCEEDED (hr))
  216578. {
  216579. hr = fileSink->SetFileName (file.getFullPathName(), 0);
  216580. if (SUCCEEDED (hr))
  216581. {
  216582. hr = graphBuilder->AddFilter (asfWriter, _T("AsfWriter"));
  216583. if (SUCCEEDED (hr))
  216584. {
  216585. ComSmartPtr <IConfigAsfWriter> asfConfig;
  216586. hr = asfWriter.QueryInterface (IID_IConfigAsfWriter, asfConfig);
  216587. asfConfig->SetIndexMode (true);
  216588. ComSmartPtr <IWMProfileManager> profileManager;
  216589. hr = WMCreateProfileManager (profileManager.resetAndGetPointerAddress());
  216590. // This gibberish is the DirectShow profile for a video-only wmv file.
  216591. String prof ("<profile version=\"589824\" storageformat=\"1\" name=\"Quality\" description=\"Quality type for output.\">"
  216592. " <streamconfig majortype=\"{73646976-0000-0010-8000-00AA00389B71}\" streamnumber=\"1\""
  216593. " streamname=\"Video Stream\" inputname=\"Video409\" bitrate=\"894960\""
  216594. " bufferwindow=\"0\" reliabletransport=\"1\" decodercomplexity=\"AU\" rfc1766langid=\"en-us\">"
  216595. " <videomediaprops maxkeyframespacing=\"50000000\" quality=\"90\"/>"
  216596. " <wmmediatype subtype=\"{33564D57-0000-0010-8000-00AA00389B71}\" bfixedsizesamples=\"0\""
  216597. " btemporalcompression=\"1\" lsamplesize=\"0\">"
  216598. " <videoinfoheader dwbitrate=\"894960\" dwbiterrorrate=\"0\" avgtimeperframe=\"$AVGTIMEPERFRAME\">"
  216599. " <rcsource left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/>"
  216600. " <rctarget left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/>"
  216601. " <bitmapinfoheader biwidth=\"$WIDTH\" biheight=\"$HEIGHT\" biplanes=\"1\" bibitcount=\"24\""
  216602. " bicompression=\"WMV3\" bisizeimage=\"0\" bixpelspermeter=\"0\" biypelspermeter=\"0\""
  216603. " biclrused=\"0\" biclrimportant=\"0\"/>"
  216604. " </videoinfoheader>"
  216605. " </wmmediatype>"
  216606. " </streamconfig>"
  216607. "</profile>");
  216608. const int fps[] = { 10, 15, 30 };
  216609. const int maxFramesPerSecond = fps [quality % numElementsInArray (fps)];
  216610. prof = prof.replace ("$WIDTH", String (width))
  216611. .replace ("$HEIGHT", String (height))
  216612. .replace ("$AVGTIMEPERFRAME", String (10000000 / maxFramesPerSecond));
  216613. ComSmartPtr <IWMProfile> currentProfile;
  216614. hr = profileManager->LoadProfileByData ((const WCHAR*) prof, currentProfile.resetAndGetPointerAddress());
  216615. hr = asfConfig->ConfigureFilterUsingProfile (currentProfile);
  216616. if (SUCCEEDED (hr))
  216617. {
  216618. ComSmartPtr <IPin> asfWriterInputPin;
  216619. if (getPin (asfWriter, PINDIR_INPUT, asfWriterInputPin, "Video Input 01"))
  216620. {
  216621. hr = graphBuilder->Connect (smartTeeCaptureOutputPin, asfWriterInputPin);
  216622. if (SUCCEEDED (hr)
  216623. && ok && activeUsers > 0
  216624. && SUCCEEDED (mediaControl->Run()))
  216625. {
  216626. previewMaxFPS = (quality < 2) ? 15 : 25; // throttle back the preview comps to try to leave the cpu free for encoding
  216627. return true;
  216628. }
  216629. }
  216630. }
  216631. }
  216632. }
  216633. }
  216634. }
  216635. removeFileCaptureFilter();
  216636. if (ok && activeUsers > 0)
  216637. mediaControl->Run();
  216638. return false;
  216639. }
  216640. void removeFileCaptureFilter()
  216641. {
  216642. mediaControl->Stop();
  216643. if (asfWriter != 0)
  216644. {
  216645. graphBuilder->RemoveFilter (asfWriter);
  216646. asfWriter = 0;
  216647. }
  216648. if (ok && activeUsers > 0)
  216649. mediaControl->Run();
  216650. previewMaxFPS = 60;
  216651. }
  216652. void addListener (CameraDevice::Listener* listenerToAdd)
  216653. {
  216654. const ScopedLock sl (listenerLock);
  216655. if (listeners.size() == 0)
  216656. addUser();
  216657. listeners.addIfNotAlreadyThere (listenerToAdd);
  216658. }
  216659. void removeListener (CameraDevice::Listener* listenerToRemove)
  216660. {
  216661. const ScopedLock sl (listenerLock);
  216662. listeners.removeValue (listenerToRemove);
  216663. if (listeners.size() == 0)
  216664. removeUser();
  216665. }
  216666. void callListeners (const Image& image)
  216667. {
  216668. const ScopedLock sl (listenerLock);
  216669. for (int i = listeners.size(); --i >= 0;)
  216670. {
  216671. CameraDevice::Listener* const l = listeners[i];
  216672. if (l != 0)
  216673. l->imageReceived (image);
  216674. }
  216675. }
  216676. class DShowCaptureViewerComp : public Component,
  216677. public ChangeListener
  216678. {
  216679. public:
  216680. DShowCaptureViewerComp (DShowCameraDeviceInteral* const owner_)
  216681. : owner (owner_), maxFPS (15), lastRepaintTime (0)
  216682. {
  216683. setOpaque (true);
  216684. owner->addChangeListener (this);
  216685. owner->addUser();
  216686. owner->viewerComps.add (this);
  216687. setSize (owner->width, owner->height);
  216688. }
  216689. ~DShowCaptureViewerComp()
  216690. {
  216691. if (owner != 0)
  216692. {
  216693. owner->viewerComps.removeValue (this);
  216694. owner->removeUser();
  216695. owner->removeChangeListener (this);
  216696. }
  216697. }
  216698. void ownerDeleted()
  216699. {
  216700. owner = 0;
  216701. }
  216702. void paint (Graphics& g)
  216703. {
  216704. g.setColour (Colours::black);
  216705. g.setImageResamplingQuality (Graphics::lowResamplingQuality);
  216706. if (owner != 0)
  216707. owner->drawCurrentImage (g, 0, 0, getWidth(), getHeight());
  216708. else
  216709. g.fillAll (Colours::black);
  216710. }
  216711. void changeListenerCallback (void*)
  216712. {
  216713. const int64 now = Time::currentTimeMillis();
  216714. if (now >= lastRepaintTime + (1000 / maxFPS))
  216715. {
  216716. lastRepaintTime = now;
  216717. repaint();
  216718. if (owner != 0)
  216719. maxFPS = owner->getPreviewMaxFPS();
  216720. }
  216721. }
  216722. private:
  216723. DShowCameraDeviceInteral* owner;
  216724. int maxFPS;
  216725. int64 lastRepaintTime;
  216726. };
  216727. bool ok;
  216728. int width, height;
  216729. Time firstRecordedTime;
  216730. Array <DShowCaptureViewerComp*> viewerComps;
  216731. private:
  216732. CameraDevice* const owner;
  216733. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  216734. ComSmartPtr <IBaseFilter> filter;
  216735. ComSmartPtr <IBaseFilter> smartTee;
  216736. ComSmartPtr <IGraphBuilder> graphBuilder;
  216737. ComSmartPtr <ISampleGrabber> sampleGrabber;
  216738. ComSmartPtr <IMediaControl> mediaControl;
  216739. ComSmartPtr <IPin> smartTeePreviewOutputPin;
  216740. ComSmartPtr <IPin> smartTeeCaptureOutputPin;
  216741. ComSmartPtr <IBaseFilter> asfWriter;
  216742. int activeUsers;
  216743. Array <int> widths, heights;
  216744. DWORD graphRegistrationID;
  216745. CriticalSection imageSwapLock;
  216746. bool imageNeedsFlipping;
  216747. Image loadingImage;
  216748. Image activeImage;
  216749. bool recordNextFrameTime;
  216750. int previewMaxFPS;
  216751. void getVideoSizes (IAMStreamConfig* const streamConfig)
  216752. {
  216753. widths.clear();
  216754. heights.clear();
  216755. int count = 0, size = 0;
  216756. streamConfig->GetNumberOfCapabilities (&count, &size);
  216757. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  216758. {
  216759. for (int i = 0; i < count; ++i)
  216760. {
  216761. VIDEO_STREAM_CONFIG_CAPS scc;
  216762. AM_MEDIA_TYPE* config;
  216763. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  216764. if (SUCCEEDED (hr))
  216765. {
  216766. const int w = scc.InputSize.cx;
  216767. const int h = scc.InputSize.cy;
  216768. bool duplicate = false;
  216769. for (int j = widths.size(); --j >= 0;)
  216770. {
  216771. if (w == widths.getUnchecked (j) && h == heights.getUnchecked (j))
  216772. {
  216773. duplicate = true;
  216774. break;
  216775. }
  216776. }
  216777. if (! duplicate)
  216778. {
  216779. DBG ("Camera capture size: " + String (w) + ", " + String (h));
  216780. widths.add (w);
  216781. heights.add (h);
  216782. }
  216783. deleteMediaType (config);
  216784. }
  216785. }
  216786. }
  216787. }
  216788. bool selectVideoSize (IAMStreamConfig* const streamConfig,
  216789. const int minWidth, const int minHeight,
  216790. const int maxWidth, const int maxHeight)
  216791. {
  216792. int count = 0, size = 0, bestArea = 0, bestIndex = -1;
  216793. streamConfig->GetNumberOfCapabilities (&count, &size);
  216794. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  216795. {
  216796. AM_MEDIA_TYPE* config;
  216797. VIDEO_STREAM_CONFIG_CAPS scc;
  216798. for (int i = 0; i < count; ++i)
  216799. {
  216800. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  216801. if (SUCCEEDED (hr))
  216802. {
  216803. if (scc.InputSize.cx >= minWidth
  216804. && scc.InputSize.cy >= minHeight
  216805. && scc.InputSize.cx <= maxWidth
  216806. && scc.InputSize.cy <= maxHeight)
  216807. {
  216808. int area = scc.InputSize.cx * scc.InputSize.cy;
  216809. if (area > bestArea)
  216810. {
  216811. bestIndex = i;
  216812. bestArea = area;
  216813. }
  216814. }
  216815. deleteMediaType (config);
  216816. }
  216817. }
  216818. if (bestIndex >= 0)
  216819. {
  216820. HRESULT hr = streamConfig->GetStreamCaps (bestIndex, &config, (BYTE*) &scc);
  216821. hr = streamConfig->SetFormat (config);
  216822. deleteMediaType (config);
  216823. return SUCCEEDED (hr);
  216824. }
  216825. }
  216826. return false;
  216827. }
  216828. static bool getPin (IBaseFilter* filter, const PIN_DIRECTION wantedDirection, ComSmartPtr<IPin>& result, const char* pinName = 0)
  216829. {
  216830. ComSmartPtr <IEnumPins> enumerator;
  216831. ComSmartPtr <IPin> pin;
  216832. filter->EnumPins (enumerator.resetAndGetPointerAddress());
  216833. while (enumerator->Next (1, pin.resetAndGetPointerAddress(), 0) == S_OK)
  216834. {
  216835. PIN_DIRECTION dir;
  216836. pin->QueryDirection (&dir);
  216837. if (wantedDirection == dir)
  216838. {
  216839. PIN_INFO info;
  216840. zerostruct (info);
  216841. pin->QueryPinInfo (&info);
  216842. if (pinName == 0 || String (pinName).equalsIgnoreCase (String (info.achName)))
  216843. {
  216844. result = pin;
  216845. return true;
  216846. }
  216847. }
  216848. }
  216849. return false;
  216850. }
  216851. bool connectFilters (IBaseFilter* const first, IBaseFilter* const second) const
  216852. {
  216853. ComSmartPtr <IPin> in, out;
  216854. return getPin (first, PINDIR_OUTPUT, out)
  216855. && getPin (second, PINDIR_INPUT, in)
  216856. && SUCCEEDED (graphBuilder->Connect (out, in));
  216857. }
  216858. bool addGraphToRot()
  216859. {
  216860. ComSmartPtr <IRunningObjectTable> rot;
  216861. if (FAILED (GetRunningObjectTable (0, rot.resetAndGetPointerAddress())))
  216862. return false;
  216863. ComSmartPtr <IMoniker> moniker;
  216864. WCHAR buffer[128];
  216865. HRESULT hr = CreateItemMoniker (_T("!"), buffer, moniker.resetAndGetPointerAddress());
  216866. if (FAILED (hr))
  216867. return false;
  216868. graphRegistrationID = 0;
  216869. return SUCCEEDED (rot->Register (0, graphBuilder, moniker, &graphRegistrationID));
  216870. }
  216871. void removeGraphFromRot()
  216872. {
  216873. ComSmartPtr <IRunningObjectTable> rot;
  216874. if (SUCCEEDED (GetRunningObjectTable (0, rot.resetAndGetPointerAddress())))
  216875. rot->Revoke (graphRegistrationID);
  216876. }
  216877. static void deleteMediaType (AM_MEDIA_TYPE* const pmt)
  216878. {
  216879. if (pmt->cbFormat != 0)
  216880. CoTaskMemFree ((PVOID) pmt->pbFormat);
  216881. if (pmt->pUnk != 0)
  216882. pmt->pUnk->Release();
  216883. CoTaskMemFree (pmt);
  216884. }
  216885. class GrabberCallback : public ComBaseClassHelper <ISampleGrabberCB>
  216886. {
  216887. public:
  216888. GrabberCallback (DShowCameraDeviceInteral& owner_)
  216889. : owner (owner_)
  216890. {
  216891. }
  216892. STDMETHODIMP SampleCB (double /*SampleTime*/, IMediaSample* /*pSample*/)
  216893. {
  216894. return E_FAIL;
  216895. }
  216896. STDMETHODIMP BufferCB (double time, BYTE* buffer, long bufferSize)
  216897. {
  216898. owner.handleFrame (time, buffer, bufferSize);
  216899. return S_OK;
  216900. }
  216901. private:
  216902. DShowCameraDeviceInteral& owner;
  216903. GrabberCallback (const GrabberCallback&);
  216904. GrabberCallback& operator= (const GrabberCallback&);
  216905. };
  216906. ComSmartPtr <GrabberCallback> callback;
  216907. Array <CameraDevice::Listener*> listeners;
  216908. CriticalSection listenerLock;
  216909. DShowCameraDeviceInteral (const DShowCameraDeviceInteral&);
  216910. DShowCameraDeviceInteral& operator= (const DShowCameraDeviceInteral&);
  216911. };
  216912. CameraDevice::CameraDevice (const String& name_, int /*index*/)
  216913. : name (name_)
  216914. {
  216915. isRecording = false;
  216916. }
  216917. CameraDevice::~CameraDevice()
  216918. {
  216919. stopRecording();
  216920. delete static_cast <DShowCameraDeviceInteral*> (internal);
  216921. internal = 0;
  216922. }
  216923. Component* CameraDevice::createViewerComponent()
  216924. {
  216925. return new DShowCameraDeviceInteral::DShowCaptureViewerComp (static_cast <DShowCameraDeviceInteral*> (internal));
  216926. }
  216927. const String CameraDevice::getFileExtension()
  216928. {
  216929. return ".wmv";
  216930. }
  216931. void CameraDevice::startRecordingToFile (const File& file, int quality)
  216932. {
  216933. jassert (quality >= 0 && quality <= 2);
  216934. stopRecording();
  216935. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216936. d->addUser();
  216937. isRecording = d->createFileCaptureFilter (file, quality);
  216938. }
  216939. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  216940. {
  216941. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216942. return d->firstRecordedTime;
  216943. }
  216944. void CameraDevice::stopRecording()
  216945. {
  216946. if (isRecording)
  216947. {
  216948. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216949. d->removeFileCaptureFilter();
  216950. d->removeUser();
  216951. isRecording = false;
  216952. }
  216953. }
  216954. void CameraDevice::addListener (Listener* listenerToAdd)
  216955. {
  216956. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216957. if (listenerToAdd != 0)
  216958. d->addListener (listenerToAdd);
  216959. }
  216960. void CameraDevice::removeListener (Listener* listenerToRemove)
  216961. {
  216962. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216963. if (listenerToRemove != 0)
  216964. d->removeListener (listenerToRemove);
  216965. }
  216966. static ComSmartPtr <IBaseFilter> enumerateCameras (StringArray* const names,
  216967. const int deviceIndexToOpen,
  216968. String& name)
  216969. {
  216970. int index = 0;
  216971. ComSmartPtr <IBaseFilter> result;
  216972. ComSmartPtr <ICreateDevEnum> pDevEnum;
  216973. HRESULT hr = pDevEnum.CoCreateInstance (CLSID_SystemDeviceEnum);
  216974. if (SUCCEEDED (hr))
  216975. {
  216976. ComSmartPtr <IEnumMoniker> enumerator;
  216977. hr = pDevEnum->CreateClassEnumerator (CLSID_VideoInputDeviceCategory, enumerator.resetAndGetPointerAddress(), 0);
  216978. if (SUCCEEDED (hr) && enumerator != 0)
  216979. {
  216980. ComSmartPtr <IMoniker> moniker;
  216981. ULONG fetched;
  216982. while (enumerator->Next (1, moniker.resetAndGetPointerAddress(), &fetched) == S_OK)
  216983. {
  216984. ComSmartPtr <IBaseFilter> captureFilter;
  216985. hr = moniker->BindToObject (0, 0, IID_IBaseFilter, (void**) captureFilter.resetAndGetPointerAddress());
  216986. if (SUCCEEDED (hr))
  216987. {
  216988. ComSmartPtr <IPropertyBag> propertyBag;
  216989. hr = moniker->BindToStorage (0, 0, IID_IPropertyBag, (void**) propertyBag.resetAndGetPointerAddress());
  216990. if (SUCCEEDED (hr))
  216991. {
  216992. VARIANT var;
  216993. var.vt = VT_BSTR;
  216994. hr = propertyBag->Read (_T("FriendlyName"), &var, 0);
  216995. propertyBag = 0;
  216996. if (SUCCEEDED (hr))
  216997. {
  216998. if (names != 0)
  216999. names->add (var.bstrVal);
  217000. if (index == deviceIndexToOpen)
  217001. {
  217002. name = var.bstrVal;
  217003. result = captureFilter;
  217004. break;
  217005. }
  217006. ++index;
  217007. }
  217008. }
  217009. }
  217010. }
  217011. }
  217012. }
  217013. return result;
  217014. }
  217015. const StringArray CameraDevice::getAvailableDevices()
  217016. {
  217017. StringArray devs;
  217018. String dummy;
  217019. enumerateCameras (&devs, -1, dummy);
  217020. return devs;
  217021. }
  217022. CameraDevice* CameraDevice::openDevice (int index,
  217023. int minWidth, int minHeight,
  217024. int maxWidth, int maxHeight)
  217025. {
  217026. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  217027. HRESULT hr = captureGraphBuilder.CoCreateInstance (CLSID_CaptureGraphBuilder2);
  217028. if (SUCCEEDED (hr))
  217029. {
  217030. String name;
  217031. const ComSmartPtr <IBaseFilter> filter (enumerateCameras (0, index, name));
  217032. if (filter != 0)
  217033. {
  217034. ScopedPointer <CameraDevice> cam (new CameraDevice (name, index));
  217035. DShowCameraDeviceInteral* const intern
  217036. = new DShowCameraDeviceInteral (cam, captureGraphBuilder, filter,
  217037. minWidth, minHeight, maxWidth, maxHeight);
  217038. cam->internal = intern;
  217039. if (intern->ok)
  217040. return cam.release();
  217041. }
  217042. }
  217043. return 0;
  217044. }
  217045. #endif
  217046. /*** End of inlined file: juce_win32_CameraDevice.cpp ***/
  217047. #endif
  217048. // Auto-link the other win32 libs that are needed by library calls..
  217049. #if (JUCE_AMALGAMATED_TEMPLATE || defined (JUCE_DLL_BUILD)) && JUCE_MSVC && ! DONT_AUTOLINK_TO_WIN32_LIBRARIES
  217050. /*** Start of inlined file: juce_win32_AutoLinkLibraries.h ***/
  217051. // Auto-links to various win32 libs that are needed by library calls..
  217052. #pragma comment(lib, "kernel32.lib")
  217053. #pragma comment(lib, "user32.lib")
  217054. #pragma comment(lib, "shell32.lib")
  217055. #pragma comment(lib, "gdi32.lib")
  217056. #pragma comment(lib, "vfw32.lib")
  217057. #pragma comment(lib, "comdlg32.lib")
  217058. #pragma comment(lib, "winmm.lib")
  217059. #pragma comment(lib, "wininet.lib")
  217060. #pragma comment(lib, "ole32.lib")
  217061. #pragma comment(lib, "oleaut32.lib")
  217062. #pragma comment(lib, "advapi32.lib")
  217063. #pragma comment(lib, "ws2_32.lib")
  217064. #pragma comment(lib, "version.lib")
  217065. #ifdef _NATIVE_WCHAR_T_DEFINED
  217066. #ifdef _DEBUG
  217067. #pragma comment(lib, "comsuppwd.lib")
  217068. #else
  217069. #pragma comment(lib, "comsuppw.lib")
  217070. #endif
  217071. #else
  217072. #ifdef _DEBUG
  217073. #pragma comment(lib, "comsuppd.lib")
  217074. #else
  217075. #pragma comment(lib, "comsupp.lib")
  217076. #endif
  217077. #endif
  217078. #if JUCE_OPENGL
  217079. #pragma comment(lib, "OpenGL32.Lib")
  217080. #pragma comment(lib, "GlU32.Lib")
  217081. #endif
  217082. #if JUCE_QUICKTIME
  217083. #pragma comment (lib, "QTMLClient.lib")
  217084. #endif
  217085. #if JUCE_USE_CAMERA
  217086. #pragma comment (lib, "Strmiids.lib")
  217087. #pragma comment (lib, "wmvcore.lib")
  217088. #endif
  217089. #if JUCE_DIRECT2D
  217090. #pragma comment (lib, "Dwrite.lib")
  217091. #pragma comment (lib, "D2d1.lib")
  217092. #endif
  217093. /*** End of inlined file: juce_win32_AutoLinkLibraries.h ***/
  217094. #endif
  217095. END_JUCE_NAMESPACE
  217096. #endif
  217097. /*** End of inlined file: juce_win32_NativeCode.cpp ***/
  217098. #endif
  217099. #if JUCE_LINUX
  217100. /*** Start of inlined file: juce_linux_NativeCode.cpp ***/
  217101. /*
  217102. This file wraps together all the mac-specific code, so that
  217103. we can include all the native headers just once, and compile all our
  217104. platform-specific stuff in one big lump, keeping it out of the way of
  217105. the rest of the codebase.
  217106. */
  217107. #if JUCE_LINUX
  217108. BEGIN_JUCE_NAMESPACE
  217109. #define JUCE_INCLUDED_FILE 1
  217110. // Now include the actual code files..
  217111. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  217112. /*
  217113. This file contains posix routines that are common to both the Linux and Mac builds.
  217114. It gets included directly in the cpp files for these platforms.
  217115. */
  217116. CriticalSection::CriticalSection() throw()
  217117. {
  217118. pthread_mutexattr_t atts;
  217119. pthread_mutexattr_init (&atts);
  217120. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  217121. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  217122. pthread_mutex_init (&internal, &atts);
  217123. }
  217124. CriticalSection::~CriticalSection() throw()
  217125. {
  217126. pthread_mutex_destroy (&internal);
  217127. }
  217128. void CriticalSection::enter() const throw()
  217129. {
  217130. pthread_mutex_lock (&internal);
  217131. }
  217132. bool CriticalSection::tryEnter() const throw()
  217133. {
  217134. return pthread_mutex_trylock (&internal) == 0;
  217135. }
  217136. void CriticalSection::exit() const throw()
  217137. {
  217138. pthread_mutex_unlock (&internal);
  217139. }
  217140. class WaitableEventImpl
  217141. {
  217142. public:
  217143. WaitableEventImpl (const bool manualReset_)
  217144. : triggered (false),
  217145. manualReset (manualReset_)
  217146. {
  217147. pthread_cond_init (&condition, 0);
  217148. pthread_mutexattr_t atts;
  217149. pthread_mutexattr_init (&atts);
  217150. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  217151. pthread_mutex_init (&mutex, &atts);
  217152. }
  217153. ~WaitableEventImpl()
  217154. {
  217155. pthread_cond_destroy (&condition);
  217156. pthread_mutex_destroy (&mutex);
  217157. }
  217158. bool wait (const int timeOutMillisecs) throw()
  217159. {
  217160. pthread_mutex_lock (&mutex);
  217161. if (! triggered)
  217162. {
  217163. if (timeOutMillisecs < 0)
  217164. {
  217165. do
  217166. {
  217167. pthread_cond_wait (&condition, &mutex);
  217168. }
  217169. while (! triggered);
  217170. }
  217171. else
  217172. {
  217173. struct timeval now;
  217174. gettimeofday (&now, 0);
  217175. struct timespec time;
  217176. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  217177. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  217178. if (time.tv_nsec >= 1000000000)
  217179. {
  217180. time.tv_nsec -= 1000000000;
  217181. time.tv_sec++;
  217182. }
  217183. do
  217184. {
  217185. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  217186. {
  217187. pthread_mutex_unlock (&mutex);
  217188. return false;
  217189. }
  217190. }
  217191. while (! triggered);
  217192. }
  217193. }
  217194. if (! manualReset)
  217195. triggered = false;
  217196. pthread_mutex_unlock (&mutex);
  217197. return true;
  217198. }
  217199. void signal() throw()
  217200. {
  217201. pthread_mutex_lock (&mutex);
  217202. triggered = true;
  217203. pthread_cond_broadcast (&condition);
  217204. pthread_mutex_unlock (&mutex);
  217205. }
  217206. void reset() throw()
  217207. {
  217208. pthread_mutex_lock (&mutex);
  217209. triggered = false;
  217210. pthread_mutex_unlock (&mutex);
  217211. }
  217212. private:
  217213. pthread_cond_t condition;
  217214. pthread_mutex_t mutex;
  217215. bool triggered;
  217216. const bool manualReset;
  217217. WaitableEventImpl (const WaitableEventImpl&);
  217218. WaitableEventImpl& operator= (const WaitableEventImpl&);
  217219. };
  217220. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  217221. : internal (new WaitableEventImpl (manualReset))
  217222. {
  217223. }
  217224. WaitableEvent::~WaitableEvent() throw()
  217225. {
  217226. delete static_cast <WaitableEventImpl*> (internal);
  217227. }
  217228. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  217229. {
  217230. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  217231. }
  217232. void WaitableEvent::signal() const throw()
  217233. {
  217234. static_cast <WaitableEventImpl*> (internal)->signal();
  217235. }
  217236. void WaitableEvent::reset() const throw()
  217237. {
  217238. static_cast <WaitableEventImpl*> (internal)->reset();
  217239. }
  217240. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  217241. {
  217242. struct timespec time;
  217243. time.tv_sec = millisecs / 1000;
  217244. time.tv_nsec = (millisecs % 1000) * 1000000;
  217245. nanosleep (&time, 0);
  217246. }
  217247. const juce_wchar File::separator = '/';
  217248. const String File::separatorString ("/");
  217249. const File File::getCurrentWorkingDirectory()
  217250. {
  217251. HeapBlock<char> heapBuffer;
  217252. char localBuffer [1024];
  217253. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  217254. int bufferSize = 4096;
  217255. while (cwd == 0 && errno == ERANGE)
  217256. {
  217257. heapBuffer.malloc (bufferSize);
  217258. cwd = getcwd (heapBuffer, bufferSize - 1);
  217259. bufferSize += 1024;
  217260. }
  217261. return File (String::fromUTF8 (cwd));
  217262. }
  217263. bool File::setAsCurrentWorkingDirectory() const
  217264. {
  217265. return chdir (getFullPathName().toUTF8()) == 0;
  217266. }
  217267. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  217268. typedef struct stat64 juce_statStruct; // (need to use the 64-bit version to work around a simulator bug)
  217269. #else
  217270. typedef struct stat juce_statStruct;
  217271. #endif
  217272. static bool juce_stat (const String& fileName, juce_statStruct& info)
  217273. {
  217274. return fileName.isNotEmpty()
  217275. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  217276. && (stat64 (fileName.toUTF8(), &info) == 0);
  217277. #else
  217278. && (stat (fileName.toUTF8(), &info) == 0);
  217279. #endif
  217280. }
  217281. bool File::isDirectory() const
  217282. {
  217283. juce_statStruct info;
  217284. return fullPath.isEmpty()
  217285. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  217286. }
  217287. bool File::exists() const
  217288. {
  217289. juce_statStruct info;
  217290. return fullPath.isNotEmpty()
  217291. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  217292. && (lstat64 (fullPath.toUTF8(), &info) == 0);
  217293. #else
  217294. && (lstat (fullPath.toUTF8(), &info) == 0);
  217295. #endif
  217296. }
  217297. bool File::existsAsFile() const
  217298. {
  217299. return exists() && ! isDirectory();
  217300. }
  217301. int64 File::getSize() const
  217302. {
  217303. juce_statStruct info;
  217304. return juce_stat (fullPath, info) ? info.st_size : 0;
  217305. }
  217306. bool File::hasWriteAccess() const
  217307. {
  217308. if (exists())
  217309. return access (fullPath.toUTF8(), W_OK) == 0;
  217310. if ((! isDirectory()) && fullPath.containsChar (separator))
  217311. return getParentDirectory().hasWriteAccess();
  217312. return false;
  217313. }
  217314. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  217315. {
  217316. juce_statStruct info;
  217317. if (! juce_stat (fullPath, info))
  217318. return false;
  217319. info.st_mode &= 0777; // Just permissions
  217320. if (shouldBeReadOnly)
  217321. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  217322. else
  217323. // Give everybody write permission?
  217324. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  217325. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  217326. }
  217327. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  217328. {
  217329. modificationTime = 0;
  217330. accessTime = 0;
  217331. creationTime = 0;
  217332. juce_statStruct info;
  217333. if (juce_stat (fullPath, info))
  217334. {
  217335. modificationTime = (int64) info.st_mtime * 1000;
  217336. accessTime = (int64) info.st_atime * 1000;
  217337. creationTime = (int64) info.st_ctime * 1000;
  217338. }
  217339. }
  217340. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  217341. {
  217342. struct utimbuf times;
  217343. times.actime = (time_t) (accessTime / 1000);
  217344. times.modtime = (time_t) (modificationTime / 1000);
  217345. return utime (fullPath.toUTF8(), &times) == 0;
  217346. }
  217347. bool File::deleteFile() const
  217348. {
  217349. if (! exists())
  217350. return true;
  217351. else if (isDirectory())
  217352. return rmdir (fullPath.toUTF8()) == 0;
  217353. else
  217354. return remove (fullPath.toUTF8()) == 0;
  217355. }
  217356. bool File::moveInternal (const File& dest) const
  217357. {
  217358. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  217359. return true;
  217360. if (hasWriteAccess() && copyInternal (dest))
  217361. {
  217362. if (deleteFile())
  217363. return true;
  217364. dest.deleteFile();
  217365. }
  217366. return false;
  217367. }
  217368. void File::createDirectoryInternal (const String& fileName) const
  217369. {
  217370. mkdir (fileName.toUTF8(), 0777);
  217371. }
  217372. int64 juce_fileSetPosition (void* handle, int64 pos)
  217373. {
  217374. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  217375. return pos;
  217376. return -1;
  217377. }
  217378. void FileInputStream::openHandle()
  217379. {
  217380. totalSize = file.getSize();
  217381. const int f = open (file.getFullPathName().toUTF8(), O_RDONLY, 00644);
  217382. if (f != -1)
  217383. fileHandle = (void*) f;
  217384. }
  217385. void FileInputStream::closeHandle()
  217386. {
  217387. if (fileHandle != 0)
  217388. {
  217389. close ((int) (pointer_sized_int) fileHandle);
  217390. fileHandle = 0;
  217391. }
  217392. }
  217393. size_t FileInputStream::readInternal (void* const buffer, const size_t numBytes)
  217394. {
  217395. if (fileHandle != 0)
  217396. return jmax ((ssize_t) 0, ::read ((int) (pointer_sized_int) fileHandle, buffer, numBytes));
  217397. return 0;
  217398. }
  217399. void FileOutputStream::openHandle()
  217400. {
  217401. if (file.exists())
  217402. {
  217403. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  217404. if (f != -1)
  217405. {
  217406. currentPosition = lseek (f, 0, SEEK_END);
  217407. if (currentPosition >= 0)
  217408. fileHandle = (void*) f;
  217409. else
  217410. close (f);
  217411. }
  217412. }
  217413. else
  217414. {
  217415. const int f = open (file.getFullPathName().toUTF8(), O_RDWR + O_CREAT, 00644);
  217416. if (f != -1)
  217417. fileHandle = (void*) f;
  217418. }
  217419. }
  217420. void FileOutputStream::closeHandle()
  217421. {
  217422. if (fileHandle != 0)
  217423. {
  217424. close ((int) (pointer_sized_int) fileHandle);
  217425. fileHandle = 0;
  217426. }
  217427. }
  217428. int FileOutputStream::writeInternal (const void* const data, const int numBytes)
  217429. {
  217430. if (fileHandle != 0)
  217431. return (int) ::write ((int) (pointer_sized_int) fileHandle, data, numBytes);
  217432. return 0;
  217433. }
  217434. void FileOutputStream::flushInternal()
  217435. {
  217436. if (fileHandle != 0)
  217437. fsync ((int) (pointer_sized_int) fileHandle);
  217438. }
  217439. const File juce_getExecutableFile()
  217440. {
  217441. Dl_info exeInfo;
  217442. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  217443. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  217444. }
  217445. // if this file doesn't exist, find a parent of it that does..
  217446. static bool juce_doStatFS (File f, struct statfs& result)
  217447. {
  217448. for (int i = 5; --i >= 0;)
  217449. {
  217450. if (f.exists())
  217451. break;
  217452. f = f.getParentDirectory();
  217453. }
  217454. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  217455. }
  217456. int64 File::getBytesFreeOnVolume() const
  217457. {
  217458. struct statfs buf;
  217459. if (juce_doStatFS (*this, buf))
  217460. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  217461. return 0;
  217462. }
  217463. int64 File::getVolumeTotalSize() const
  217464. {
  217465. struct statfs buf;
  217466. if (juce_doStatFS (*this, buf))
  217467. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  217468. return 0;
  217469. }
  217470. const String File::getVolumeLabel() const
  217471. {
  217472. #if JUCE_MAC
  217473. struct VolAttrBuf
  217474. {
  217475. u_int32_t length;
  217476. attrreference_t mountPointRef;
  217477. char mountPointSpace [MAXPATHLEN];
  217478. } attrBuf;
  217479. struct attrlist attrList;
  217480. zerostruct (attrList);
  217481. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  217482. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  217483. File f (*this);
  217484. for (;;)
  217485. {
  217486. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  217487. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  217488. (int) attrBuf.mountPointRef.attr_length);
  217489. const File parent (f.getParentDirectory());
  217490. if (f == parent)
  217491. break;
  217492. f = parent;
  217493. }
  217494. #endif
  217495. return String::empty;
  217496. }
  217497. int File::getVolumeSerialNumber() const
  217498. {
  217499. return 0; // xxx
  217500. }
  217501. void juce_runSystemCommand (const String& command)
  217502. {
  217503. int result = system (command.toUTF8());
  217504. (void) result;
  217505. }
  217506. const String juce_getOutputFromCommand (const String& command)
  217507. {
  217508. // slight bodge here, as we just pipe the output into a temp file and read it...
  217509. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  217510. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  217511. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  217512. String result (tempFile.loadFileAsString());
  217513. tempFile.deleteFile();
  217514. return result;
  217515. }
  217516. class InterProcessLock::Pimpl
  217517. {
  217518. public:
  217519. Pimpl (const String& name, const int timeOutMillisecs)
  217520. : handle (0), refCount (1)
  217521. {
  217522. #if JUCE_MAC
  217523. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  217524. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  217525. #else
  217526. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  217527. #endif
  217528. temp.create();
  217529. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  217530. if (handle != 0)
  217531. {
  217532. struct flock fl;
  217533. zerostruct (fl);
  217534. fl.l_whence = SEEK_SET;
  217535. fl.l_type = F_WRLCK;
  217536. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  217537. for (;;)
  217538. {
  217539. const int result = fcntl (handle, F_SETLK, &fl);
  217540. if (result >= 0)
  217541. return;
  217542. if (errno != EINTR)
  217543. {
  217544. if (timeOutMillisecs == 0
  217545. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  217546. break;
  217547. Thread::sleep (10);
  217548. }
  217549. }
  217550. }
  217551. closeFile();
  217552. }
  217553. ~Pimpl()
  217554. {
  217555. closeFile();
  217556. }
  217557. void closeFile()
  217558. {
  217559. if (handle != 0)
  217560. {
  217561. struct flock fl;
  217562. zerostruct (fl);
  217563. fl.l_whence = SEEK_SET;
  217564. fl.l_type = F_UNLCK;
  217565. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  217566. {}
  217567. close (handle);
  217568. handle = 0;
  217569. }
  217570. }
  217571. int handle, refCount;
  217572. };
  217573. InterProcessLock::InterProcessLock (const String& name_)
  217574. : name (name_)
  217575. {
  217576. }
  217577. InterProcessLock::~InterProcessLock()
  217578. {
  217579. }
  217580. bool InterProcessLock::enter (const int timeOutMillisecs)
  217581. {
  217582. const ScopedLock sl (lock);
  217583. if (pimpl == 0)
  217584. {
  217585. pimpl = new Pimpl (name, timeOutMillisecs);
  217586. if (pimpl->handle == 0)
  217587. pimpl = 0;
  217588. }
  217589. else
  217590. {
  217591. pimpl->refCount++;
  217592. }
  217593. return pimpl != 0;
  217594. }
  217595. void InterProcessLock::exit()
  217596. {
  217597. const ScopedLock sl (lock);
  217598. // Trying to release the lock too many times!
  217599. jassert (pimpl != 0);
  217600. if (pimpl != 0 && --(pimpl->refCount) == 0)
  217601. pimpl = 0;
  217602. }
  217603. void JUCE_API juce_threadEntryPoint (void*);
  217604. void* threadEntryProc (void* userData)
  217605. {
  217606. JUCE_AUTORELEASEPOOL
  217607. juce_threadEntryPoint (userData);
  217608. return 0;
  217609. }
  217610. void* juce_createThread (void* userData)
  217611. {
  217612. pthread_t handle = 0;
  217613. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  217614. {
  217615. pthread_detach (handle);
  217616. return (void*) handle;
  217617. }
  217618. return 0;
  217619. }
  217620. void juce_killThread (void* handle)
  217621. {
  217622. if (handle != 0)
  217623. pthread_cancel ((pthread_t) handle);
  217624. }
  217625. void juce_setCurrentThreadName (const String& /*name*/)
  217626. {
  217627. }
  217628. bool juce_setThreadPriority (void* handle, int priority)
  217629. {
  217630. struct sched_param param;
  217631. int policy;
  217632. priority = jlimit (0, 10, priority);
  217633. if (handle == 0)
  217634. handle = (void*) pthread_self();
  217635. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) != 0)
  217636. return false;
  217637. policy = priority == 0 ? SCHED_OTHER : SCHED_RR;
  217638. const int minPriority = sched_get_priority_min (policy);
  217639. const int maxPriority = sched_get_priority_max (policy);
  217640. param.sched_priority = ((maxPriority - minPriority) * priority) / 10 + minPriority;
  217641. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  217642. }
  217643. Thread::ThreadID Thread::getCurrentThreadId()
  217644. {
  217645. return (ThreadID) pthread_self();
  217646. }
  217647. void Thread::yield()
  217648. {
  217649. sched_yield();
  217650. }
  217651. /* Remove this macro if you're having problems compiling the cpu affinity
  217652. calls (the API for these has changed about quite a bit in various Linux
  217653. versions, and a lot of distros seem to ship with obsolete versions)
  217654. */
  217655. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  217656. #define SUPPORT_AFFINITIES 1
  217657. #endif
  217658. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  217659. {
  217660. #if SUPPORT_AFFINITIES
  217661. cpu_set_t affinity;
  217662. CPU_ZERO (&affinity);
  217663. for (int i = 0; i < 32; ++i)
  217664. if ((affinityMask & (1 << i)) != 0)
  217665. CPU_SET (i, &affinity);
  217666. /*
  217667. N.B. If this line causes a compile error, then you've probably not got the latest
  217668. version of glibc installed.
  217669. If you don't want to update your copy of glibc and don't care about cpu affinities,
  217670. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  217671. */
  217672. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  217673. sched_yield();
  217674. #else
  217675. /* affinities aren't supported because either the appropriate header files weren't found,
  217676. or the SUPPORT_AFFINITIES macro was turned off
  217677. */
  217678. jassertfalse;
  217679. #endif
  217680. }
  217681. /*** End of inlined file: juce_posix_SharedCode.h ***/
  217682. /*** Start of inlined file: juce_linux_Files.cpp ***/
  217683. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217684. // compiled on its own).
  217685. #if JUCE_INCLUDED_FILE
  217686. static const short U_ISOFS_SUPER_MAGIC = 0x9660; // linux/iso_fs.h
  217687. static const short U_MSDOS_SUPER_MAGIC = 0x4d44; // linux/msdos_fs.h
  217688. static const short U_NFS_SUPER_MAGIC = 0x6969; // linux/nfs_fs.h
  217689. static const short U_SMB_SUPER_MAGIC = 0x517B; // linux/smb_fs.h
  217690. bool File::copyInternal (const File& dest) const
  217691. {
  217692. FileInputStream in (*this);
  217693. if (dest.deleteFile())
  217694. {
  217695. {
  217696. FileOutputStream out (dest);
  217697. if (out.failedToOpen())
  217698. return false;
  217699. if (out.writeFromInputStream (in, -1) == getSize())
  217700. return true;
  217701. }
  217702. dest.deleteFile();
  217703. }
  217704. return false;
  217705. }
  217706. void File::findFileSystemRoots (Array<File>& destArray)
  217707. {
  217708. destArray.add (File ("/"));
  217709. }
  217710. bool File::isOnCDRomDrive() const
  217711. {
  217712. struct statfs buf;
  217713. return statfs (getFullPathName().toUTF8(), &buf) == 0
  217714. && buf.f_type == U_ISOFS_SUPER_MAGIC;
  217715. }
  217716. bool File::isOnHardDisk() const
  217717. {
  217718. struct statfs buf;
  217719. if (statfs (getFullPathName().toUTF8(), &buf) == 0)
  217720. {
  217721. switch (buf.f_type)
  217722. {
  217723. case U_ISOFS_SUPER_MAGIC: // CD-ROM
  217724. case U_MSDOS_SUPER_MAGIC: // Probably floppy (but could be mounted FAT filesystem)
  217725. case U_NFS_SUPER_MAGIC: // Network NFS
  217726. case U_SMB_SUPER_MAGIC: // Network Samba
  217727. return false;
  217728. default:
  217729. // Assume anything else is a hard-disk (but note it could
  217730. // be a RAM disk. There isn't a good way of determining
  217731. // this for sure)
  217732. return true;
  217733. }
  217734. }
  217735. // Assume so if this fails for some reason
  217736. return true;
  217737. }
  217738. bool File::isOnRemovableDrive() const
  217739. {
  217740. jassertfalse; // xxx not implemented for linux!
  217741. return false;
  217742. }
  217743. bool File::isHidden() const
  217744. {
  217745. return getFileName().startsWithChar ('.');
  217746. }
  217747. static const File juce_readlink (const String& file, const File& defaultFile)
  217748. {
  217749. const int size = 8192;
  217750. HeapBlock<char> buffer;
  217751. buffer.malloc (size + 4);
  217752. const size_t numBytes = readlink (file.toUTF8(), buffer, size);
  217753. if (numBytes > 0 && numBytes <= size)
  217754. return File (file).getSiblingFile (String::fromUTF8 (buffer, (int) numBytes));
  217755. return defaultFile;
  217756. }
  217757. const File File::getLinkedTarget() const
  217758. {
  217759. return juce_readlink (getFullPathName().toUTF8(), *this);
  217760. }
  217761. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  217762. const File File::getSpecialLocation (const SpecialLocationType type)
  217763. {
  217764. switch (type)
  217765. {
  217766. case userHomeDirectory:
  217767. {
  217768. const char* homeDir = getenv ("HOME");
  217769. if (homeDir == 0)
  217770. {
  217771. struct passwd* const pw = getpwuid (getuid());
  217772. if (pw != 0)
  217773. homeDir = pw->pw_dir;
  217774. }
  217775. return File (String::fromUTF8 (homeDir));
  217776. }
  217777. case userDocumentsDirectory:
  217778. case userMusicDirectory:
  217779. case userMoviesDirectory:
  217780. case userApplicationDataDirectory:
  217781. return File ("~");
  217782. case userDesktopDirectory:
  217783. return File ("~/Desktop");
  217784. case commonApplicationDataDirectory:
  217785. return File ("/var");
  217786. case globalApplicationsDirectory:
  217787. return File ("/usr");
  217788. case tempDirectory:
  217789. {
  217790. File tmp ("/var/tmp");
  217791. if (! tmp.isDirectory())
  217792. {
  217793. tmp = "/tmp";
  217794. if (! tmp.isDirectory())
  217795. tmp = File::getCurrentWorkingDirectory();
  217796. }
  217797. return tmp;
  217798. }
  217799. case invokedExecutableFile:
  217800. if (juce_Argv0 != 0)
  217801. return File (String::fromUTF8 (juce_Argv0));
  217802. // deliberate fall-through...
  217803. case currentExecutableFile:
  217804. case currentApplicationFile:
  217805. return juce_getExecutableFile();
  217806. case hostApplicationPath:
  217807. return juce_readlink ("/proc/self/exe", juce_getExecutableFile());
  217808. default:
  217809. jassertfalse; // unknown type?
  217810. break;
  217811. }
  217812. return File::nonexistent;
  217813. }
  217814. const String File::getVersion() const
  217815. {
  217816. return String::empty; // xxx not yet implemented
  217817. }
  217818. bool File::moveToTrash() const
  217819. {
  217820. if (! exists())
  217821. return true;
  217822. File trashCan ("~/.Trash");
  217823. if (! trashCan.isDirectory())
  217824. trashCan = "~/.local/share/Trash/files";
  217825. if (! trashCan.isDirectory())
  217826. return false;
  217827. return moveFileTo (trashCan.getNonexistentChildFile (getFileNameWithoutExtension(),
  217828. getFileExtension()));
  217829. }
  217830. class DirectoryIterator::NativeIterator::Pimpl
  217831. {
  217832. public:
  217833. Pimpl (const File& directory, const String& wildCard_)
  217834. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  217835. wildCard (wildCard_),
  217836. dir (opendir (directory.getFullPathName().toUTF8()))
  217837. {
  217838. if (wildCard == "*.*")
  217839. wildCard = "*";
  217840. wildcardUTF8 = wildCard.toUTF8();
  217841. }
  217842. ~Pimpl()
  217843. {
  217844. if (dir != 0)
  217845. closedir (dir);
  217846. }
  217847. bool next (String& filenameFound,
  217848. bool* const isDir, bool* const isHidden, int64* const fileSize,
  217849. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  217850. {
  217851. if (dir == 0)
  217852. return false;
  217853. for (;;)
  217854. {
  217855. struct dirent* const de = readdir (dir);
  217856. if (de == 0)
  217857. return false;
  217858. if (fnmatch (wildcardUTF8, de->d_name, FNM_CASEFOLD) == 0)
  217859. {
  217860. filenameFound = String::fromUTF8 (de->d_name);
  217861. const String path (parentDir + filenameFound);
  217862. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  217863. {
  217864. struct stat info;
  217865. const bool statOk = juce_stat (path, info);
  217866. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  217867. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  217868. if (modTime != 0) *modTime = statOk ? (int64) info.st_mtime * 1000 : 0;
  217869. if (creationTime != 0) *creationTime = statOk ? (int64) info.st_ctime * 1000 : 0;
  217870. }
  217871. if (isHidden != 0)
  217872. *isHidden = filenameFound.startsWithChar ('.');
  217873. if (isReadOnly != 0)
  217874. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  217875. return true;
  217876. }
  217877. }
  217878. }
  217879. private:
  217880. String parentDir, wildCard;
  217881. const char* wildcardUTF8;
  217882. DIR* dir;
  217883. Pimpl (const Pimpl&);
  217884. Pimpl& operator= (const Pimpl&);
  217885. };
  217886. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  217887. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  217888. {
  217889. }
  217890. DirectoryIterator::NativeIterator::~NativeIterator()
  217891. {
  217892. }
  217893. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  217894. bool* const isDir, bool* const isHidden, int64* const fileSize,
  217895. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  217896. {
  217897. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  217898. }
  217899. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  217900. {
  217901. String cmdString (fileName.replace (" ", "\\ ",false));
  217902. cmdString << " " << parameters;
  217903. if (URL::isProbablyAWebsiteURL (fileName)
  217904. || cmdString.startsWithIgnoreCase ("file:")
  217905. || URL::isProbablyAnEmailAddress (fileName))
  217906. {
  217907. // create a command that tries to launch a bunch of likely browsers
  217908. const char* const browserNames[] = { "xdg-open", "/etc/alternatives/x-www-browser", "firefox", "mozilla", "konqueror", "opera" };
  217909. StringArray cmdLines;
  217910. for (int i = 0; i < numElementsInArray (browserNames); ++i)
  217911. cmdLines.add (String (browserNames[i]) + " " + cmdString.trim().quoted());
  217912. cmdString = cmdLines.joinIntoString (" || ");
  217913. }
  217914. const char* const argv[4] = { "/bin/sh", "-c", cmdString.toUTF8(), 0 };
  217915. const int cpid = fork();
  217916. if (cpid == 0)
  217917. {
  217918. setsid();
  217919. // Child process
  217920. execve (argv[0], (char**) argv, environ);
  217921. exit (0);
  217922. }
  217923. return cpid >= 0;
  217924. }
  217925. void File::revealToUser() const
  217926. {
  217927. if (isDirectory())
  217928. startAsProcess();
  217929. else if (getParentDirectory().exists())
  217930. getParentDirectory().startAsProcess();
  217931. }
  217932. #endif
  217933. /*** End of inlined file: juce_linux_Files.cpp ***/
  217934. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  217935. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  217936. // compiled on its own).
  217937. #if JUCE_INCLUDED_FILE
  217938. struct NamedPipeInternal
  217939. {
  217940. String pipeInName, pipeOutName;
  217941. int pipeIn, pipeOut;
  217942. bool volatile createdPipe, blocked, stopReadOperation;
  217943. static void signalHandler (int) {}
  217944. };
  217945. void NamedPipe::cancelPendingReads()
  217946. {
  217947. while (internal != 0 && static_cast <NamedPipeInternal*> (internal)->blocked)
  217948. {
  217949. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  217950. intern->stopReadOperation = true;
  217951. char buffer [1] = { 0 };
  217952. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  217953. (void) bytesWritten;
  217954. int timeout = 2000;
  217955. while (intern->blocked && --timeout >= 0)
  217956. Thread::sleep (2);
  217957. intern->stopReadOperation = false;
  217958. }
  217959. }
  217960. void NamedPipe::close()
  217961. {
  217962. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  217963. if (intern != 0)
  217964. {
  217965. internal = 0;
  217966. if (intern->pipeIn != -1)
  217967. ::close (intern->pipeIn);
  217968. if (intern->pipeOut != -1)
  217969. ::close (intern->pipeOut);
  217970. if (intern->createdPipe)
  217971. {
  217972. unlink (intern->pipeInName.toUTF8());
  217973. unlink (intern->pipeOutName.toUTF8());
  217974. }
  217975. delete intern;
  217976. }
  217977. }
  217978. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  217979. {
  217980. close();
  217981. NamedPipeInternal* const intern = new NamedPipeInternal();
  217982. internal = intern;
  217983. intern->createdPipe = createPipe;
  217984. intern->blocked = false;
  217985. intern->stopReadOperation = false;
  217986. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  217987. siginterrupt (SIGPIPE, 1);
  217988. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  217989. intern->pipeInName = pipePath + "_in";
  217990. intern->pipeOutName = pipePath + "_out";
  217991. intern->pipeIn = -1;
  217992. intern->pipeOut = -1;
  217993. if (createPipe)
  217994. {
  217995. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  217996. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  217997. {
  217998. delete intern;
  217999. internal = 0;
  218000. return false;
  218001. }
  218002. }
  218003. return true;
  218004. }
  218005. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  218006. {
  218007. int bytesRead = -1;
  218008. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  218009. if (intern != 0)
  218010. {
  218011. intern->blocked = true;
  218012. if (intern->pipeIn == -1)
  218013. {
  218014. if (intern->createdPipe)
  218015. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  218016. else
  218017. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  218018. if (intern->pipeIn == -1)
  218019. {
  218020. intern->blocked = false;
  218021. return -1;
  218022. }
  218023. }
  218024. bytesRead = 0;
  218025. char* p = static_cast<char*> (destBuffer);
  218026. while (bytesRead < maxBytesToRead)
  218027. {
  218028. const int bytesThisTime = maxBytesToRead - bytesRead;
  218029. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  218030. if (numRead <= 0 || intern->stopReadOperation)
  218031. {
  218032. bytesRead = -1;
  218033. break;
  218034. }
  218035. bytesRead += numRead;
  218036. p += bytesRead;
  218037. }
  218038. intern->blocked = false;
  218039. }
  218040. return bytesRead;
  218041. }
  218042. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  218043. {
  218044. int bytesWritten = -1;
  218045. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  218046. if (intern != 0)
  218047. {
  218048. if (intern->pipeOut == -1)
  218049. {
  218050. if (intern->createdPipe)
  218051. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  218052. else
  218053. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  218054. if (intern->pipeOut == -1)
  218055. {
  218056. return -1;
  218057. }
  218058. }
  218059. const char* p = static_cast<const char*> (sourceBuffer);
  218060. bytesWritten = 0;
  218061. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  218062. while (bytesWritten < numBytesToWrite
  218063. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  218064. {
  218065. const int bytesThisTime = numBytesToWrite - bytesWritten;
  218066. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  218067. if (numWritten <= 0)
  218068. {
  218069. bytesWritten = -1;
  218070. break;
  218071. }
  218072. bytesWritten += numWritten;
  218073. p += bytesWritten;
  218074. }
  218075. }
  218076. return bytesWritten;
  218077. }
  218078. #endif
  218079. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  218080. /*** Start of inlined file: juce_linux_Network.cpp ***/
  218081. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218082. // compiled on its own).
  218083. #if JUCE_INCLUDED_FILE
  218084. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  218085. {
  218086. int numResults = 0;
  218087. const int s = socket (AF_INET, SOCK_DGRAM, 0);
  218088. if (s != -1)
  218089. {
  218090. char buf [1024];
  218091. struct ifconf ifc;
  218092. ifc.ifc_len = sizeof (buf);
  218093. ifc.ifc_buf = buf;
  218094. ioctl (s, SIOCGIFCONF, &ifc);
  218095. for (unsigned int i = 0; i < ifc.ifc_len / sizeof (struct ifreq); ++i)
  218096. {
  218097. struct ifreq ifr;
  218098. strcpy (ifr.ifr_name, ifc.ifc_req[i].ifr_name);
  218099. if (ioctl (s, SIOCGIFFLAGS, &ifr) == 0
  218100. && (ifr.ifr_flags & IFF_LOOPBACK) == 0
  218101. && ioctl (s, SIOCGIFHWADDR, &ifr) == 0
  218102. && numResults < maxNum)
  218103. {
  218104. int64 a = 0;
  218105. for (int j = 6; --j >= 0;)
  218106. a = (a << 8) | (uint8) ifr.ifr_hwaddr.sa_data [littleEndian ? j : (5 - j)];
  218107. *addresses++ = a;
  218108. ++numResults;
  218109. }
  218110. }
  218111. close (s);
  218112. }
  218113. return numResults;
  218114. }
  218115. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  218116. const String& emailSubject,
  218117. const String& bodyText,
  218118. const StringArray& filesToAttach)
  218119. {
  218120. jassertfalse; // xxx todo
  218121. return false;
  218122. }
  218123. /** A HTTP input stream that uses sockets.
  218124. */
  218125. class JUCE_HTTPSocketStream
  218126. {
  218127. public:
  218128. JUCE_HTTPSocketStream()
  218129. : readPosition (0),
  218130. socketHandle (-1),
  218131. levelsOfRedirection (0),
  218132. timeoutSeconds (15)
  218133. {
  218134. }
  218135. ~JUCE_HTTPSocketStream()
  218136. {
  218137. closeSocket();
  218138. }
  218139. bool open (const String& url,
  218140. const String& headers,
  218141. const MemoryBlock& postData,
  218142. const bool isPost,
  218143. URL::OpenStreamProgressCallback* callback,
  218144. void* callbackContext,
  218145. int timeOutMs)
  218146. {
  218147. closeSocket();
  218148. uint32 timeOutTime = Time::getMillisecondCounter();
  218149. if (timeOutMs == 0)
  218150. timeOutTime += 60000;
  218151. else if (timeOutMs < 0)
  218152. timeOutTime = 0xffffffff;
  218153. else
  218154. timeOutTime += timeOutMs;
  218155. String hostName, hostPath;
  218156. int hostPort;
  218157. if (! decomposeURL (url, hostName, hostPath, hostPort))
  218158. return false;
  218159. const struct hostent* host = 0;
  218160. int port = 0;
  218161. String proxyName, proxyPath;
  218162. int proxyPort = 0;
  218163. String proxyURL (getenv ("http_proxy"));
  218164. if (proxyURL.startsWithIgnoreCase ("http://"))
  218165. {
  218166. if (! decomposeURL (proxyURL, proxyName, proxyPath, proxyPort))
  218167. return false;
  218168. host = gethostbyname (proxyName.toUTF8());
  218169. port = proxyPort;
  218170. }
  218171. else
  218172. {
  218173. host = gethostbyname (hostName.toUTF8());
  218174. port = hostPort;
  218175. }
  218176. if (host == 0)
  218177. return false;
  218178. struct sockaddr_in address;
  218179. zerostruct (address);
  218180. memcpy (&address.sin_addr, host->h_addr, host->h_length);
  218181. address.sin_family = host->h_addrtype;
  218182. address.sin_port = htons (port);
  218183. socketHandle = socket (host->h_addrtype, SOCK_STREAM, 0);
  218184. if (socketHandle == -1)
  218185. return false;
  218186. int receiveBufferSize = 16384;
  218187. setsockopt (socketHandle, SOL_SOCKET, SO_RCVBUF, (char*) &receiveBufferSize, sizeof (receiveBufferSize));
  218188. setsockopt (socketHandle, SOL_SOCKET, SO_KEEPALIVE, 0, 0);
  218189. #if JUCE_MAC
  218190. setsockopt (socketHandle, SOL_SOCKET, SO_NOSIGPIPE, 0, 0);
  218191. #endif
  218192. if (connect (socketHandle, (struct sockaddr*) &address, sizeof (address)) == -1)
  218193. {
  218194. closeSocket();
  218195. return false;
  218196. }
  218197. const MemoryBlock requestHeader (createRequestHeader (hostName, hostPort,
  218198. proxyName, proxyPort,
  218199. hostPath, url,
  218200. headers, postData,
  218201. isPost));
  218202. size_t totalHeaderSent = 0;
  218203. while (totalHeaderSent < requestHeader.getSize())
  218204. {
  218205. if (Time::getMillisecondCounter() > timeOutTime)
  218206. {
  218207. closeSocket();
  218208. return false;
  218209. }
  218210. const int numToSend = jmin (1024, (int) (requestHeader.getSize() - totalHeaderSent));
  218211. if (send (socketHandle,
  218212. ((const char*) requestHeader.getData()) + totalHeaderSent,
  218213. numToSend, 0)
  218214. != numToSend)
  218215. {
  218216. closeSocket();
  218217. return false;
  218218. }
  218219. totalHeaderSent += numToSend;
  218220. if (callback != 0 && ! callback (callbackContext, totalHeaderSent, requestHeader.getSize()))
  218221. {
  218222. closeSocket();
  218223. return false;
  218224. }
  218225. }
  218226. const String responseHeader (readResponse (timeOutTime));
  218227. if (responseHeader.isNotEmpty())
  218228. {
  218229. //DBG (responseHeader);
  218230. headerLines.clear();
  218231. headerLines.addLines (responseHeader);
  218232. const int statusCode = responseHeader.fromFirstOccurrenceOf (" ", false, false)
  218233. .substring (0, 3).getIntValue();
  218234. //int contentLength = findHeaderItem (lines, "Content-Length:").getIntValue();
  218235. //bool isChunked = findHeaderItem (lines, "Transfer-Encoding:").equalsIgnoreCase ("chunked");
  218236. String location (findHeaderItem (headerLines, "Location:"));
  218237. if (statusCode >= 300 && statusCode < 400
  218238. && location.isNotEmpty())
  218239. {
  218240. if (! location.startsWithIgnoreCase ("http://"))
  218241. location = "http://" + location;
  218242. if (levelsOfRedirection++ < 3)
  218243. return open (location, headers, postData, isPost, callback, callbackContext, timeOutMs);
  218244. }
  218245. else
  218246. {
  218247. levelsOfRedirection = 0;
  218248. return true;
  218249. }
  218250. }
  218251. closeSocket();
  218252. return false;
  218253. }
  218254. int read (void* buffer, int bytesToRead)
  218255. {
  218256. fd_set readbits;
  218257. FD_ZERO (&readbits);
  218258. FD_SET (socketHandle, &readbits);
  218259. struct timeval tv;
  218260. tv.tv_sec = timeoutSeconds;
  218261. tv.tv_usec = 0;
  218262. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  218263. return 0; // (timeout)
  218264. const int bytesRead = jmax (0, (int) recv (socketHandle, buffer, bytesToRead, MSG_WAITALL));
  218265. readPosition += bytesRead;
  218266. return bytesRead;
  218267. }
  218268. int readPosition;
  218269. StringArray headerLines;
  218270. juce_UseDebuggingNewOperator
  218271. private:
  218272. int socketHandle, levelsOfRedirection;
  218273. const int timeoutSeconds;
  218274. void closeSocket()
  218275. {
  218276. if (socketHandle >= 0)
  218277. close (socketHandle);
  218278. socketHandle = -1;
  218279. }
  218280. const MemoryBlock createRequestHeader (const String& hostName,
  218281. const int hostPort,
  218282. const String& proxyName,
  218283. const int proxyPort,
  218284. const String& hostPath,
  218285. const String& originalURL,
  218286. const String& headers,
  218287. const MemoryBlock& postData,
  218288. const bool isPost)
  218289. {
  218290. String header (isPost ? "POST " : "GET ");
  218291. if (proxyName.isEmpty())
  218292. {
  218293. header << hostPath << " HTTP/1.0\r\nHost: "
  218294. << hostName << ':' << hostPort;
  218295. }
  218296. else
  218297. {
  218298. header << originalURL << " HTTP/1.0\r\nHost: "
  218299. << proxyName << ':' << proxyPort;
  218300. }
  218301. header << "\r\nUser-Agent: JUCE/"
  218302. << JUCE_MAJOR_VERSION << '.' << JUCE_MINOR_VERSION
  218303. << "\r\nConnection: Close\r\nContent-Length: "
  218304. << postData.getSize() << "\r\n"
  218305. << headers << "\r\n";
  218306. MemoryBlock mb;
  218307. mb.append (header.toUTF8(), (int) strlen (header.toUTF8()));
  218308. mb.append (postData.getData(), postData.getSize());
  218309. return mb;
  218310. }
  218311. const String readResponse (const uint32 timeOutTime)
  218312. {
  218313. int bytesRead = 0, numConsecutiveLFs = 0;
  218314. MemoryBlock buffer (1024, true);
  218315. while (numConsecutiveLFs < 2 && bytesRead < 32768
  218316. && Time::getMillisecondCounter() <= timeOutTime)
  218317. {
  218318. fd_set readbits;
  218319. FD_ZERO (&readbits);
  218320. FD_SET (socketHandle, &readbits);
  218321. struct timeval tv;
  218322. tv.tv_sec = timeoutSeconds;
  218323. tv.tv_usec = 0;
  218324. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  218325. return String::empty; // (timeout)
  218326. buffer.ensureSize (bytesRead + 8, true);
  218327. char* const dest = (char*) buffer.getData() + bytesRead;
  218328. if (recv (socketHandle, dest, 1, 0) == -1)
  218329. return String::empty;
  218330. const char lastByte = *dest;
  218331. ++bytesRead;
  218332. if (lastByte == '\n')
  218333. ++numConsecutiveLFs;
  218334. else if (lastByte != '\r')
  218335. numConsecutiveLFs = 0;
  218336. }
  218337. const String header (String::fromUTF8 ((const char*) buffer.getData()));
  218338. if (header.startsWithIgnoreCase ("HTTP/"))
  218339. return header.trimEnd();
  218340. return String::empty;
  218341. }
  218342. static bool decomposeURL (const String& url,
  218343. String& host, String& path, int& port)
  218344. {
  218345. if (! url.startsWithIgnoreCase ("http://"))
  218346. return false;
  218347. const int nextSlash = url.indexOfChar (7, '/');
  218348. int nextColon = url.indexOfChar (7, ':');
  218349. if (nextColon > nextSlash && nextSlash > 0)
  218350. nextColon = -1;
  218351. if (nextColon >= 0)
  218352. {
  218353. host = url.substring (7, nextColon);
  218354. if (nextSlash >= 0)
  218355. port = url.substring (nextColon + 1, nextSlash).getIntValue();
  218356. else
  218357. port = url.substring (nextColon + 1).getIntValue();
  218358. }
  218359. else
  218360. {
  218361. port = 80;
  218362. if (nextSlash >= 0)
  218363. host = url.substring (7, nextSlash);
  218364. else
  218365. host = url.substring (7);
  218366. }
  218367. if (nextSlash >= 0)
  218368. path = url.substring (nextSlash);
  218369. else
  218370. path = "/";
  218371. return true;
  218372. }
  218373. static const String findHeaderItem (const StringArray& lines, const String& itemName)
  218374. {
  218375. for (int i = 0; i < lines.size(); ++i)
  218376. if (lines[i].startsWithIgnoreCase (itemName))
  218377. return lines[i].substring (itemName.length()).trim();
  218378. return String::empty;
  218379. }
  218380. };
  218381. void* juce_openInternetFile (const String& url,
  218382. const String& headers,
  218383. const MemoryBlock& postData,
  218384. const bool isPost,
  218385. URL::OpenStreamProgressCallback* callback,
  218386. void* callbackContext,
  218387. int timeOutMs)
  218388. {
  218389. ScopedPointer<JUCE_HTTPSocketStream> s (new JUCE_HTTPSocketStream());
  218390. if (s->open (url, headers, postData, isPost, callback, callbackContext, timeOutMs))
  218391. return s.release();
  218392. return 0;
  218393. }
  218394. void juce_closeInternetFile (void* handle)
  218395. {
  218396. delete static_cast <JUCE_HTTPSocketStream*> (handle);
  218397. }
  218398. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  218399. {
  218400. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  218401. return s != 0 ? s->read (buffer, bytesToRead) : 0;
  218402. }
  218403. int64 juce_getInternetFileContentLength (void* handle)
  218404. {
  218405. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  218406. if (s != 0)
  218407. {
  218408. //xxx todo
  218409. jassertfalse
  218410. }
  218411. return -1;
  218412. }
  218413. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers)
  218414. {
  218415. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  218416. if (s != 0)
  218417. {
  218418. for (int i = 0; i < s->headerLines.size(); ++i)
  218419. {
  218420. const String& headersEntry = s->headerLines[i];
  218421. const String key (headersEntry.upToFirstOccurrenceOf (": ", false, false));
  218422. const String value (headersEntry.fromFirstOccurrenceOf (": ", false, false));
  218423. const String previousValue (headers [key]);
  218424. headers.set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
  218425. }
  218426. }
  218427. }
  218428. int juce_seekInInternetFile (void* handle, int newPosition)
  218429. {
  218430. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  218431. return s != 0 ? s->readPosition : 0;
  218432. }
  218433. #endif
  218434. /*** End of inlined file: juce_linux_Network.cpp ***/
  218435. /*** Start of inlined file: juce_linux_SystemStats.cpp ***/
  218436. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218437. // compiled on its own).
  218438. #if JUCE_INCLUDED_FILE
  218439. void Logger::outputDebugString (const String& text)
  218440. {
  218441. std::cerr << text << std::endl;
  218442. }
  218443. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  218444. {
  218445. return Linux;
  218446. }
  218447. const String SystemStats::getOperatingSystemName()
  218448. {
  218449. return "Linux";
  218450. }
  218451. bool SystemStats::isOperatingSystem64Bit()
  218452. {
  218453. #if JUCE_64BIT
  218454. return true;
  218455. #else
  218456. //xxx not sure how to find this out?..
  218457. return false;
  218458. #endif
  218459. }
  218460. static const String juce_getCpuInfo (const char* const key)
  218461. {
  218462. StringArray lines;
  218463. lines.addLines (File ("/proc/cpuinfo").loadFileAsString());
  218464. for (int i = lines.size(); --i >= 0;) // (NB - it's important that this runs in reverse order)
  218465. if (lines[i].startsWithIgnoreCase (key))
  218466. return lines[i].fromFirstOccurrenceOf (":", false, false).trim();
  218467. return String::empty;
  218468. }
  218469. const String SystemStats::getCpuVendor()
  218470. {
  218471. return juce_getCpuInfo ("vendor_id");
  218472. }
  218473. int SystemStats::getCpuSpeedInMegaherz()
  218474. {
  218475. return roundToInt (juce_getCpuInfo ("cpu MHz").getFloatValue());
  218476. }
  218477. int SystemStats::getMemorySizeInMegabytes()
  218478. {
  218479. struct sysinfo sysi;
  218480. if (sysinfo (&sysi) == 0)
  218481. return (sysi.totalram * sysi.mem_unit / (1024 * 1024));
  218482. return 0;
  218483. }
  218484. int SystemStats::getPageSize()
  218485. {
  218486. return sysconf (_SC_PAGESIZE);
  218487. }
  218488. const String SystemStats::getLogonName()
  218489. {
  218490. const char* user = getenv ("USER");
  218491. if (user == 0)
  218492. {
  218493. struct passwd* const pw = getpwuid (getuid());
  218494. if (pw != 0)
  218495. user = pw->pw_name;
  218496. }
  218497. return String::fromUTF8 (user);
  218498. }
  218499. const String SystemStats::getFullUserName()
  218500. {
  218501. return getLogonName();
  218502. }
  218503. void SystemStats::initialiseStats()
  218504. {
  218505. const String flags (juce_getCpuInfo ("flags"));
  218506. cpuFlags.hasMMX = flags.contains ("mmx");
  218507. cpuFlags.hasSSE = flags.contains ("sse");
  218508. cpuFlags.hasSSE2 = flags.contains ("sse2");
  218509. cpuFlags.has3DNow = flags.contains ("3dnow");
  218510. cpuFlags.numCpus = juce_getCpuInfo ("processor").getIntValue() + 1;
  218511. }
  218512. void PlatformUtilities::fpuReset()
  218513. {
  218514. }
  218515. static bool juce_getTimeSinceStartup (timeval* const t) throw()
  218516. {
  218517. if (gettimeofday (t, 0) != 0)
  218518. return false;
  218519. static unsigned int calibrate = 0;
  218520. static bool calibrated = false;
  218521. if (! calibrated)
  218522. {
  218523. calibrated = true;
  218524. struct sysinfo sysi;
  218525. if (sysinfo (&sysi) == 0)
  218526. calibrate = t->tv_sec - sysi.uptime; // Safe to assume system was not brought up earlier than 1970!
  218527. }
  218528. t->tv_sec -= calibrate;
  218529. return true;
  218530. }
  218531. uint32 juce_millisecondsSinceStartup() throw()
  218532. {
  218533. timeval t;
  218534. if (juce_getTimeSinceStartup (&t))
  218535. return (uint32) (t.tv_sec * 1000 + (t.tv_usec / 1000));
  218536. return 0;
  218537. }
  218538. int64 Time::getHighResolutionTicks() throw()
  218539. {
  218540. timeval t;
  218541. if (juce_getTimeSinceStartup (&t))
  218542. return ((int64) t.tv_sec * (int64) 1000000) + (int64) t.tv_usec;
  218543. return 0;
  218544. }
  218545. int64 Time::getHighResolutionTicksPerSecond() throw()
  218546. {
  218547. return 1000000; // (microseconds)
  218548. }
  218549. double Time::getMillisecondCounterHiRes() throw()
  218550. {
  218551. return getHighResolutionTicks() * 0.001;
  218552. }
  218553. bool Time::setSystemTimeToThisTime() const
  218554. {
  218555. timeval t;
  218556. t.tv_sec = millisSinceEpoch % 1000000;
  218557. t.tv_usec = millisSinceEpoch - t.tv_sec;
  218558. return settimeofday (&t, 0) ? false : true;
  218559. }
  218560. #endif
  218561. /*** End of inlined file: juce_linux_SystemStats.cpp ***/
  218562. /*** Start of inlined file: juce_linux_Threads.cpp ***/
  218563. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218564. // compiled on its own).
  218565. #if JUCE_INCLUDED_FILE
  218566. /*
  218567. Note that a lot of methods that you'd expect to find in this file actually
  218568. live in juce_posix_SharedCode.h!
  218569. */
  218570. // sets the process to 0=low priority, 1=normal, 2=high, 3=realtime
  218571. void Process::setPriority (ProcessPriority prior)
  218572. {
  218573. struct sched_param param;
  218574. int policy, maxp, minp;
  218575. const int p = (int) prior;
  218576. if (p <= 1)
  218577. policy = SCHED_OTHER;
  218578. else
  218579. policy = SCHED_RR;
  218580. minp = sched_get_priority_min (policy);
  218581. maxp = sched_get_priority_max (policy);
  218582. if (p < 2)
  218583. param.sched_priority = 0;
  218584. else if (p == 2 )
  218585. // Set to middle of lower realtime priority range
  218586. param.sched_priority = minp + (maxp - minp) / 4;
  218587. else
  218588. // Set to middle of higher realtime priority range
  218589. param.sched_priority = minp + (3 * (maxp - minp) / 4);
  218590. pthread_setschedparam (pthread_self(), policy, &param);
  218591. }
  218592. void Process::terminate()
  218593. {
  218594. exit (0);
  218595. }
  218596. bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger()
  218597. {
  218598. static char testResult = 0;
  218599. if (testResult == 0)
  218600. {
  218601. testResult = (char) ptrace (PT_TRACE_ME, 0, 0, 0);
  218602. if (testResult >= 0)
  218603. {
  218604. ptrace (PT_DETACH, 0, (caddr_t) 1, 0);
  218605. testResult = 1;
  218606. }
  218607. }
  218608. return testResult < 0;
  218609. }
  218610. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  218611. {
  218612. return juce_isRunningUnderDebugger();
  218613. }
  218614. void Process::raisePrivilege()
  218615. {
  218616. // If running suid root, change effective user
  218617. // to root
  218618. if (geteuid() != 0 && getuid() == 0)
  218619. {
  218620. setreuid (geteuid(), getuid());
  218621. setregid (getegid(), getgid());
  218622. }
  218623. }
  218624. void Process::lowerPrivilege()
  218625. {
  218626. // If runing suid root, change effective user
  218627. // back to real user
  218628. if (geteuid() == 0 && getuid() != 0)
  218629. {
  218630. setreuid (geteuid(), getuid());
  218631. setregid (getegid(), getgid());
  218632. }
  218633. }
  218634. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  218635. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  218636. {
  218637. return dlopen (name.toUTF8(), RTLD_LOCAL | RTLD_NOW);
  218638. }
  218639. void PlatformUtilities::freeDynamicLibrary (void* handle)
  218640. {
  218641. dlclose(handle);
  218642. }
  218643. void* PlatformUtilities::getProcedureEntryPoint (void* libraryHandle, const String& procedureName)
  218644. {
  218645. return dlsym (libraryHandle, procedureName.toCString());
  218646. }
  218647. #endif
  218648. #endif
  218649. /*** End of inlined file: juce_linux_Threads.cpp ***/
  218650. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  218651. /*** Start of inlined file: juce_linux_Clipboard.cpp ***/
  218652. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218653. // compiled on its own).
  218654. #if JUCE_INCLUDED_FILE
  218655. extern Display* display;
  218656. extern Window juce_messageWindowHandle;
  218657. namespace ClipboardHelpers
  218658. {
  218659. static String localClipboardContent;
  218660. static Atom atom_UTF8_STRING;
  218661. static Atom atom_CLIPBOARD;
  218662. static Atom atom_TARGETS;
  218663. static void initSelectionAtoms()
  218664. {
  218665. static bool isInitialised = false;
  218666. if (! isInitialised)
  218667. {
  218668. atom_UTF8_STRING = XInternAtom (display, "UTF8_STRING", False);
  218669. atom_CLIPBOARD = XInternAtom (display, "CLIPBOARD", False);
  218670. atom_TARGETS = XInternAtom (display, "TARGETS", False);
  218671. }
  218672. }
  218673. // Read the content of a window property as either a locale-dependent string or an utf8 string
  218674. // works only for strings shorter than 1000000 bytes
  218675. static String readWindowProperty (Window window, Atom prop, Atom fmt)
  218676. {
  218677. String returnData;
  218678. char* clipData;
  218679. Atom actualType;
  218680. int actualFormat;
  218681. unsigned long numItems, bytesLeft;
  218682. if (XGetWindowProperty (display, window, prop,
  218683. 0L /* offset */, 1000000 /* length (max) */, False,
  218684. AnyPropertyType /* format */,
  218685. &actualType, &actualFormat, &numItems, &bytesLeft,
  218686. (unsigned char**) &clipData) == Success)
  218687. {
  218688. if (actualType == atom_UTF8_STRING && actualFormat == 8)
  218689. returnData = String::fromUTF8 (clipData, numItems);
  218690. else if (actualType == XA_STRING && actualFormat == 8)
  218691. returnData = String (clipData, numItems);
  218692. if (clipData != 0)
  218693. XFree (clipData);
  218694. jassert (bytesLeft == 0 || numItems == 1000000);
  218695. }
  218696. XDeleteProperty (display, window, prop);
  218697. return returnData;
  218698. }
  218699. // Send a SelectionRequest to the window owning the selection and waits for its answer (with a timeout) */
  218700. static bool requestSelectionContent (String& selectionContent, Atom selection, Atom requestedFormat)
  218701. {
  218702. Atom property_name = XInternAtom (display, "JUCE_SEL", false);
  218703. // The selection owner will be asked to set the JUCE_SEL property on the
  218704. // juce_messageWindowHandle with the selection content
  218705. XConvertSelection (display, selection, requestedFormat, property_name,
  218706. juce_messageWindowHandle, CurrentTime);
  218707. int count = 50; // will wait at most for 200 ms
  218708. while (--count >= 0)
  218709. {
  218710. XEvent event;
  218711. if (XCheckTypedWindowEvent (display, juce_messageWindowHandle, SelectionNotify, &event))
  218712. {
  218713. if (event.xselection.property == property_name)
  218714. {
  218715. jassert (event.xselection.requestor == juce_messageWindowHandle);
  218716. selectionContent = readWindowProperty (event.xselection.requestor,
  218717. event.xselection.property,
  218718. requestedFormat);
  218719. return true;
  218720. }
  218721. else
  218722. {
  218723. return false; // the format we asked for was denied.. (event.xselection.property == None)
  218724. }
  218725. }
  218726. // not very elegant.. we could do a select() or something like that...
  218727. // however clipboard content requesting is inherently slow on x11, it
  218728. // often takes 50ms or more so...
  218729. Thread::sleep (4);
  218730. }
  218731. return false;
  218732. }
  218733. }
  218734. // Called from the event loop in juce_linux_Messaging in response to SelectionRequest events
  218735. void juce_handleSelectionRequest (XSelectionRequestEvent &evt)
  218736. {
  218737. ClipboardHelpers::initSelectionAtoms();
  218738. // the selection content is sent to the target window as a window property
  218739. XSelectionEvent reply;
  218740. reply.type = SelectionNotify;
  218741. reply.display = evt.display;
  218742. reply.requestor = evt.requestor;
  218743. reply.selection = evt.selection;
  218744. reply.target = evt.target;
  218745. reply.property = None; // == "fail"
  218746. reply.time = evt.time;
  218747. HeapBlock <char> data;
  218748. int propertyFormat = 0, numDataItems = 0;
  218749. if (evt.selection == XA_PRIMARY || evt.selection == ClipboardHelpers::atom_CLIPBOARD)
  218750. {
  218751. if (evt.target == XA_STRING)
  218752. {
  218753. // format data according to system locale
  218754. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsCString() + 1;
  218755. data.calloc (numDataItems + 1);
  218756. ClipboardHelpers::localClipboardContent.copyToCString (data, numDataItems);
  218757. propertyFormat = 8; // bits/item
  218758. }
  218759. else if (evt.target == ClipboardHelpers::atom_UTF8_STRING)
  218760. {
  218761. // translate to utf8
  218762. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsUTF8() + 1;
  218763. data.calloc (numDataItems + 1);
  218764. ClipboardHelpers::localClipboardContent.copyToUTF8 (data, numDataItems);
  218765. propertyFormat = 8; // bits/item
  218766. }
  218767. else if (evt.target == ClipboardHelpers::atom_TARGETS)
  218768. {
  218769. // another application wants to know what we are able to send
  218770. numDataItems = 2;
  218771. propertyFormat = 32; // atoms are 32-bit
  218772. data.calloc (numDataItems * 4);
  218773. Atom* atoms = reinterpret_cast<Atom*> (data.getData());
  218774. atoms[0] = ClipboardHelpers::atom_UTF8_STRING;
  218775. atoms[1] = XA_STRING;
  218776. }
  218777. }
  218778. else
  218779. {
  218780. DBG ("requested unsupported clipboard");
  218781. }
  218782. if (data != 0)
  218783. {
  218784. const int maxReasonableSelectionSize = 1000000;
  218785. // for very big chunks of data, we should use the "INCR" protocol , which is a pain in the *ss
  218786. if (evt.property != None && numDataItems < maxReasonableSelectionSize)
  218787. {
  218788. XChangeProperty (evt.display, evt.requestor,
  218789. evt.property, evt.target,
  218790. propertyFormat /* 8 or 32 */, PropModeReplace,
  218791. reinterpret_cast<const unsigned char*> (data.getData()), numDataItems);
  218792. reply.property = evt.property; // " == success"
  218793. }
  218794. }
  218795. XSendEvent (evt.display, evt.requestor, 0, NoEventMask, (XEvent*) &reply);
  218796. }
  218797. void SystemClipboard::copyTextToClipboard (const String& clipText)
  218798. {
  218799. ClipboardHelpers::initSelectionAtoms();
  218800. ClipboardHelpers::localClipboardContent = clipText;
  218801. XSetSelectionOwner (display, XA_PRIMARY, juce_messageWindowHandle, CurrentTime);
  218802. XSetSelectionOwner (display, ClipboardHelpers::atom_CLIPBOARD, juce_messageWindowHandle, CurrentTime);
  218803. }
  218804. const String SystemClipboard::getTextFromClipboard()
  218805. {
  218806. ClipboardHelpers::initSelectionAtoms();
  218807. /* 1) try to read from the "CLIPBOARD" selection first (the "high
  218808. level" clipboard that is supposed to be filled by ctrl-C
  218809. etc). When a clipboard manager is running, the content of this
  218810. selection is preserved even when the original selection owner
  218811. exits.
  218812. 2) and then try to read from "PRIMARY" selection (the "legacy" selection
  218813. filled by good old x11 apps such as xterm)
  218814. */
  218815. String content;
  218816. Atom selection = XA_PRIMARY;
  218817. Window selectionOwner = None;
  218818. if ((selectionOwner = XGetSelectionOwner (display, selection)) == None)
  218819. {
  218820. selection = ClipboardHelpers::atom_CLIPBOARD;
  218821. selectionOwner = XGetSelectionOwner (display, selection);
  218822. }
  218823. if (selectionOwner != None)
  218824. {
  218825. if (selectionOwner == juce_messageWindowHandle)
  218826. {
  218827. content = ClipboardHelpers::localClipboardContent;
  218828. }
  218829. else
  218830. {
  218831. // first try: we want an utf8 string
  218832. bool ok = ClipboardHelpers::requestSelectionContent (content, selection, ClipboardHelpers::atom_UTF8_STRING);
  218833. if (! ok)
  218834. {
  218835. // second chance, ask for a good old locale-dependent string ..
  218836. ok = ClipboardHelpers::requestSelectionContent (content, selection, XA_STRING);
  218837. }
  218838. }
  218839. }
  218840. return content;
  218841. }
  218842. #endif
  218843. /*** End of inlined file: juce_linux_Clipboard.cpp ***/
  218844. /*** Start of inlined file: juce_linux_Messaging.cpp ***/
  218845. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218846. // compiled on its own).
  218847. #if JUCE_INCLUDED_FILE
  218848. #if JUCE_DEBUG && ! defined (JUCE_DEBUG_XERRORS)
  218849. #define JUCE_DEBUG_XERRORS 1
  218850. #endif
  218851. Display* display = 0;
  218852. Window juce_messageWindowHandle = None;
  218853. XContext windowHandleXContext; // This is referenced from Windowing.cpp
  218854. extern void juce_windowMessageReceive (XEvent* event); // Defined in Windowing.cpp
  218855. extern void juce_handleSelectionRequest (XSelectionRequestEvent &evt); // Defined in Clipboard.cpp
  218856. ScopedXLock::ScopedXLock() { XLockDisplay (display); }
  218857. ScopedXLock::~ScopedXLock() { XUnlockDisplay (display); }
  218858. class InternalMessageQueue
  218859. {
  218860. public:
  218861. InternalMessageQueue()
  218862. : bytesInSocket (0),
  218863. totalEventCount (0)
  218864. {
  218865. int ret = ::socketpair (AF_LOCAL, SOCK_STREAM, 0, fd);
  218866. (void) ret; jassert (ret == 0);
  218867. //setNonBlocking (fd[0]);
  218868. //setNonBlocking (fd[1]);
  218869. }
  218870. ~InternalMessageQueue()
  218871. {
  218872. close (fd[0]);
  218873. close (fd[1]);
  218874. clearSingletonInstance();
  218875. }
  218876. void postMessage (Message* msg)
  218877. {
  218878. const int maxBytesInSocketQueue = 128;
  218879. ScopedLock sl (lock);
  218880. queue.add (msg);
  218881. if (bytesInSocket < maxBytesInSocketQueue)
  218882. {
  218883. ++bytesInSocket;
  218884. ScopedUnlock ul (lock);
  218885. const unsigned char x = 0xff;
  218886. size_t bytesWritten = write (fd[0], &x, 1);
  218887. (void) bytesWritten;
  218888. }
  218889. }
  218890. bool isEmpty() const
  218891. {
  218892. ScopedLock sl (lock);
  218893. return queue.size() == 0;
  218894. }
  218895. bool dispatchNextEvent()
  218896. {
  218897. // This alternates between giving priority to XEvents or internal messages,
  218898. // to keep everything running smoothly..
  218899. if ((++totalEventCount & 1) != 0)
  218900. return dispatchNextXEvent() || dispatchNextInternalMessage();
  218901. else
  218902. return dispatchNextInternalMessage() || dispatchNextXEvent();
  218903. }
  218904. // Wait for an event (either XEvent, or an internal Message)
  218905. bool sleepUntilEvent (const int timeoutMs)
  218906. {
  218907. if (! isEmpty())
  218908. return true;
  218909. if (display != 0)
  218910. {
  218911. ScopedXLock xlock;
  218912. if (XPending (display))
  218913. return true;
  218914. }
  218915. struct timeval tv;
  218916. tv.tv_sec = 0;
  218917. tv.tv_usec = timeoutMs * 1000;
  218918. int fd0 = getWaitHandle();
  218919. int fdmax = fd0;
  218920. fd_set readset;
  218921. FD_ZERO (&readset);
  218922. FD_SET (fd0, &readset);
  218923. if (display != 0)
  218924. {
  218925. ScopedXLock xlock;
  218926. int fd1 = XConnectionNumber (display);
  218927. FD_SET (fd1, &readset);
  218928. fdmax = jmax (fd0, fd1);
  218929. }
  218930. const int ret = select (fdmax + 1, &readset, 0, 0, &tv);
  218931. return (ret > 0); // ret <= 0 if error or timeout
  218932. }
  218933. struct MessageThreadFuncCall
  218934. {
  218935. enum { uniqueID = 0x73774623 };
  218936. MessageCallbackFunction* func;
  218937. void* parameter;
  218938. void* result;
  218939. CriticalSection lock;
  218940. WaitableEvent event;
  218941. };
  218942. juce_DeclareSingleton_SingleThreaded_Minimal (InternalMessageQueue);
  218943. private:
  218944. CriticalSection lock;
  218945. OwnedArray <Message> queue;
  218946. int fd[2];
  218947. int bytesInSocket;
  218948. int totalEventCount;
  218949. int getWaitHandle() const throw() { return fd[1]; }
  218950. static bool setNonBlocking (int handle)
  218951. {
  218952. int socketFlags = fcntl (handle, F_GETFL, 0);
  218953. if (socketFlags == -1)
  218954. return false;
  218955. socketFlags |= O_NONBLOCK;
  218956. return fcntl (handle, F_SETFL, socketFlags) == 0;
  218957. }
  218958. static bool dispatchNextXEvent()
  218959. {
  218960. if (display == 0)
  218961. return false;
  218962. XEvent evt;
  218963. {
  218964. ScopedXLock xlock;
  218965. if (! XPending (display))
  218966. return false;
  218967. XNextEvent (display, &evt);
  218968. }
  218969. if (evt.type == SelectionRequest && evt.xany.window == juce_messageWindowHandle)
  218970. juce_handleSelectionRequest (evt.xselectionrequest);
  218971. else if (evt.xany.window != juce_messageWindowHandle)
  218972. juce_windowMessageReceive (&evt);
  218973. return true;
  218974. }
  218975. Message* popNextMessage()
  218976. {
  218977. ScopedLock sl (lock);
  218978. if (bytesInSocket > 0)
  218979. {
  218980. --bytesInSocket;
  218981. ScopedUnlock ul (lock);
  218982. unsigned char x;
  218983. size_t numBytes = read (fd[1], &x, 1);
  218984. (void) numBytes;
  218985. }
  218986. return queue.removeAndReturn (0);
  218987. }
  218988. bool dispatchNextInternalMessage()
  218989. {
  218990. ScopedPointer <Message> msg (popNextMessage());
  218991. if (msg == 0)
  218992. return false;
  218993. if (msg->intParameter1 == MessageThreadFuncCall::uniqueID)
  218994. {
  218995. // Handle callback message
  218996. MessageThreadFuncCall* const call = (MessageThreadFuncCall*) msg->pointerParameter;
  218997. call->result = (*(call->func)) (call->parameter);
  218998. call->event.signal();
  218999. }
  219000. else
  219001. {
  219002. // Handle "normal" messages
  219003. MessageManager::getInstance()->deliverMessage (msg.release());
  219004. }
  219005. return true;
  219006. }
  219007. };
  219008. juce_ImplementSingleton_SingleThreaded (InternalMessageQueue);
  219009. namespace LinuxErrorHandling
  219010. {
  219011. static bool errorOccurred = false;
  219012. static bool keyboardBreakOccurred = false;
  219013. static XErrorHandler oldErrorHandler = (XErrorHandler) 0;
  219014. static XIOErrorHandler oldIOErrorHandler = (XIOErrorHandler) 0;
  219015. // Usually happens when client-server connection is broken
  219016. static int ioErrorHandler (Display* display)
  219017. {
  219018. DBG ("ERROR: connection to X server broken.. terminating.");
  219019. if (JUCEApplication::isStandaloneApp())
  219020. MessageManager::getInstance()->stopDispatchLoop();
  219021. errorOccurred = true;
  219022. return 0;
  219023. }
  219024. // A protocol error has occurred
  219025. static int juce_XErrorHandler (Display* display, XErrorEvent* event)
  219026. {
  219027. #if JUCE_DEBUG_XERRORS
  219028. char errorStr[64] = { 0 };
  219029. char requestStr[64] = { 0 };
  219030. XGetErrorText (display, event->error_code, errorStr, 64);
  219031. XGetErrorDatabaseText (display, "XRequest", String (event->request_code).toCString(), "Unknown", requestStr, 64);
  219032. DBG ("ERROR: X returned " + String (errorStr) + " for operation " + String (requestStr));
  219033. #endif
  219034. return 0;
  219035. }
  219036. static void installXErrorHandlers()
  219037. {
  219038. oldIOErrorHandler = XSetIOErrorHandler (ioErrorHandler);
  219039. oldErrorHandler = XSetErrorHandler (juce_XErrorHandler);
  219040. }
  219041. static void removeXErrorHandlers()
  219042. {
  219043. XSetIOErrorHandler (oldIOErrorHandler);
  219044. oldIOErrorHandler = 0;
  219045. XSetErrorHandler (oldErrorHandler);
  219046. oldErrorHandler = 0;
  219047. }
  219048. static void keyboardBreakSignalHandler (int sig)
  219049. {
  219050. if (sig == SIGINT)
  219051. keyboardBreakOccurred = true;
  219052. }
  219053. static void installKeyboardBreakHandler()
  219054. {
  219055. struct sigaction saction;
  219056. sigset_t maskSet;
  219057. sigemptyset (&maskSet);
  219058. saction.sa_handler = keyboardBreakSignalHandler;
  219059. saction.sa_mask = maskSet;
  219060. saction.sa_flags = 0;
  219061. sigaction (SIGINT, &saction, 0);
  219062. }
  219063. }
  219064. void MessageManager::doPlatformSpecificInitialisation()
  219065. {
  219066. // Initialise xlib for multiple thread support
  219067. static bool initThreadCalled = false;
  219068. if (! initThreadCalled)
  219069. {
  219070. if (! XInitThreads())
  219071. {
  219072. // This is fatal! Print error and closedown
  219073. Logger::outputDebugString ("Failed to initialise xlib thread support.");
  219074. if (JUCEApplication::isStandaloneApp())
  219075. Process::terminate();
  219076. return;
  219077. }
  219078. initThreadCalled = true;
  219079. }
  219080. LinuxErrorHandling::installXErrorHandlers();
  219081. LinuxErrorHandling::installKeyboardBreakHandler();
  219082. // Create the internal message queue
  219083. InternalMessageQueue::getInstance();
  219084. // Try to connect to a display
  219085. String displayName (getenv ("DISPLAY"));
  219086. if (displayName.isEmpty())
  219087. displayName = ":0.0";
  219088. display = XOpenDisplay (displayName.toCString());
  219089. if (display != 0) // This is not fatal! we can run headless.
  219090. {
  219091. // Create a context to store user data associated with Windows we create in WindowDriver
  219092. windowHandleXContext = XUniqueContext();
  219093. // We're only interested in client messages for this window, which are always sent
  219094. XSetWindowAttributes swa;
  219095. swa.event_mask = NoEventMask;
  219096. // Create our message window (this will never be mapped)
  219097. const int screen = DefaultScreen (display);
  219098. juce_messageWindowHandle = XCreateWindow (display, RootWindow (display, screen),
  219099. 0, 0, 1, 1, 0, 0, InputOnly,
  219100. DefaultVisual (display, screen),
  219101. CWEventMask, &swa);
  219102. }
  219103. }
  219104. void MessageManager::doPlatformSpecificShutdown()
  219105. {
  219106. InternalMessageQueue::deleteInstance();
  219107. if (display != 0 && ! LinuxErrorHandling::errorOccurred)
  219108. {
  219109. XDestroyWindow (display, juce_messageWindowHandle);
  219110. XCloseDisplay (display);
  219111. juce_messageWindowHandle = 0;
  219112. display = 0;
  219113. LinuxErrorHandling::removeXErrorHandlers();
  219114. }
  219115. }
  219116. bool juce_postMessageToSystemQueue (Message* message)
  219117. {
  219118. if (LinuxErrorHandling::errorOccurred)
  219119. return false;
  219120. InternalMessageQueue::getInstanceWithoutCreating()->postMessage (message);
  219121. return true;
  219122. }
  219123. void MessageManager::broadcastMessage (const String& value)
  219124. {
  219125. /* TODO */
  219126. }
  219127. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* func, void* parameter)
  219128. {
  219129. if (LinuxErrorHandling::errorOccurred)
  219130. return 0;
  219131. if (isThisTheMessageThread())
  219132. return func (parameter);
  219133. InternalMessageQueue::MessageThreadFuncCall messageCallContext;
  219134. messageCallContext.func = func;
  219135. messageCallContext.parameter = parameter;
  219136. InternalMessageQueue::getInstanceWithoutCreating()
  219137. ->postMessage (new Message (InternalMessageQueue::MessageThreadFuncCall::uniqueID,
  219138. 0, 0, &messageCallContext));
  219139. // Wait for it to complete before continuing
  219140. messageCallContext.event.wait();
  219141. return messageCallContext.result;
  219142. }
  219143. // this function expects that it will NEVER be called simultaneously for two concurrent threads
  219144. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages)
  219145. {
  219146. while (! LinuxErrorHandling::errorOccurred)
  219147. {
  219148. if (LinuxErrorHandling::keyboardBreakOccurred)
  219149. {
  219150. LinuxErrorHandling::errorOccurred = true;
  219151. if (JUCEApplication::isStandaloneApp())
  219152. Process::terminate();
  219153. break;
  219154. }
  219155. if (InternalMessageQueue::getInstanceWithoutCreating()->dispatchNextEvent())
  219156. return true;
  219157. if (returnIfNoPendingMessages)
  219158. break;
  219159. InternalMessageQueue::getInstanceWithoutCreating()->sleepUntilEvent (2000);
  219160. }
  219161. return false;
  219162. }
  219163. #endif
  219164. /*** End of inlined file: juce_linux_Messaging.cpp ***/
  219165. /*** Start of inlined file: juce_linux_Fonts.cpp ***/
  219166. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  219167. // compiled on its own).
  219168. #if JUCE_INCLUDED_FILE
  219169. class FreeTypeFontFace
  219170. {
  219171. public:
  219172. enum FontStyle
  219173. {
  219174. Plain = 0,
  219175. Bold = 1,
  219176. Italic = 2
  219177. };
  219178. FreeTypeFontFace (const String& familyName)
  219179. : hasSerif (false),
  219180. monospaced (false)
  219181. {
  219182. family = familyName;
  219183. }
  219184. void setFileName (const String& name, const int faceIndex, FontStyle style)
  219185. {
  219186. if (names [(int) style].fileName.isEmpty())
  219187. {
  219188. names [(int) style].fileName = name;
  219189. names [(int) style].faceIndex = faceIndex;
  219190. }
  219191. }
  219192. const String& getFamilyName() const throw() { return family; }
  219193. const String& getFileName (const int style, int& faceIndex) const throw()
  219194. {
  219195. faceIndex = names[style].faceIndex;
  219196. return names[style].fileName;
  219197. }
  219198. void setMonospaced (bool mono) throw() { monospaced = mono; }
  219199. bool getMonospaced() const throw() { return monospaced; }
  219200. void setSerif (const bool serif) throw() { hasSerif = serif; }
  219201. bool getSerif() const throw() { return hasSerif; }
  219202. private:
  219203. String family;
  219204. struct FontNameIndex
  219205. {
  219206. String fileName;
  219207. int faceIndex;
  219208. };
  219209. FontNameIndex names[4];
  219210. bool hasSerif, monospaced;
  219211. };
  219212. class FreeTypeInterface : public DeletedAtShutdown
  219213. {
  219214. public:
  219215. FreeTypeInterface()
  219216. : ftLib (0),
  219217. lastFace (0),
  219218. lastBold (false),
  219219. lastItalic (false)
  219220. {
  219221. if (FT_Init_FreeType (&ftLib) != 0)
  219222. {
  219223. ftLib = 0;
  219224. DBG ("Failed to initialize FreeType");
  219225. }
  219226. StringArray fontDirs;
  219227. fontDirs.addTokens (String::fromUTF8 (getenv ("JUCE_FONT_PATH")), ";,", String::empty);
  219228. fontDirs.removeEmptyStrings (true);
  219229. if (fontDirs.size() == 0)
  219230. {
  219231. XmlDocument fontsConfig (File ("/etc/fonts/fonts.conf"));
  219232. const ScopedPointer<XmlElement> fontsInfo (fontsConfig.getDocumentElement());
  219233. if (fontsInfo != 0)
  219234. {
  219235. forEachXmlChildElementWithTagName (*fontsInfo, e, "dir")
  219236. {
  219237. fontDirs.add (e->getAllSubText().trim());
  219238. }
  219239. }
  219240. }
  219241. if (fontDirs.size() == 0)
  219242. fontDirs.add ("/usr/X11R6/lib/X11/fonts");
  219243. for (int i = 0; i < fontDirs.size(); ++i)
  219244. enumerateFaces (fontDirs[i]);
  219245. }
  219246. ~FreeTypeInterface()
  219247. {
  219248. if (lastFace != 0)
  219249. FT_Done_Face (lastFace);
  219250. if (ftLib != 0)
  219251. FT_Done_FreeType (ftLib);
  219252. clearSingletonInstance();
  219253. }
  219254. FreeTypeFontFace* findOrCreate (const String& familyName, const bool create = false)
  219255. {
  219256. for (int i = 0; i < faces.size(); i++)
  219257. if (faces[i]->getFamilyName() == familyName)
  219258. return faces[i];
  219259. if (! create)
  219260. return 0;
  219261. FreeTypeFontFace* newFace = new FreeTypeFontFace (familyName);
  219262. faces.add (newFace);
  219263. return newFace;
  219264. }
  219265. // Enumerate all font faces available in a given directory
  219266. void enumerateFaces (const String& path)
  219267. {
  219268. File dirPath (path);
  219269. if (path.isEmpty() || ! dirPath.isDirectory())
  219270. return;
  219271. DirectoryIterator di (dirPath, true);
  219272. while (di.next())
  219273. {
  219274. File possible (di.getFile());
  219275. if (possible.hasFileExtension ("ttf")
  219276. || possible.hasFileExtension ("pfb")
  219277. || possible.hasFileExtension ("pcf"))
  219278. {
  219279. FT_Face face;
  219280. int faceIndex = 0;
  219281. int numFaces = 0;
  219282. do
  219283. {
  219284. if (FT_New_Face (ftLib, possible.getFullPathName().toUTF8(),
  219285. faceIndex, &face) == 0)
  219286. {
  219287. if (faceIndex == 0)
  219288. numFaces = face->num_faces;
  219289. if ((face->face_flags & FT_FACE_FLAG_SCALABLE) != 0)
  219290. {
  219291. FreeTypeFontFace* const newFace = findOrCreate (face->family_name, true);
  219292. int style = (int) FreeTypeFontFace::Plain;
  219293. if ((face->style_flags & FT_STYLE_FLAG_BOLD) != 0)
  219294. style |= (int) FreeTypeFontFace::Bold;
  219295. if ((face->style_flags & FT_STYLE_FLAG_ITALIC) != 0)
  219296. style |= (int) FreeTypeFontFace::Italic;
  219297. newFace->setFileName (possible.getFullPathName(), faceIndex, (FreeTypeFontFace::FontStyle) style);
  219298. newFace->setMonospaced ((face->face_flags & FT_FACE_FLAG_FIXED_WIDTH) != 0);
  219299. // Surely there must be a better way to do this?
  219300. const String name (face->family_name);
  219301. newFace->setSerif (! (name.containsIgnoreCase ("Sans")
  219302. || name.containsIgnoreCase ("Verdana")
  219303. || name.containsIgnoreCase ("Arial")));
  219304. }
  219305. FT_Done_Face (face);
  219306. }
  219307. ++faceIndex;
  219308. }
  219309. while (faceIndex < numFaces);
  219310. }
  219311. }
  219312. }
  219313. // Create a FreeType face object for a given font
  219314. FT_Face createFT_Face (const String& fontName, const bool bold, const bool italic)
  219315. {
  219316. FT_Face face = 0;
  219317. if (fontName == lastFontName && bold == lastBold && italic == lastItalic)
  219318. {
  219319. face = lastFace;
  219320. }
  219321. else
  219322. {
  219323. if (lastFace != 0)
  219324. {
  219325. FT_Done_Face (lastFace);
  219326. lastFace = 0;
  219327. }
  219328. lastFontName = fontName;
  219329. lastBold = bold;
  219330. lastItalic = italic;
  219331. FreeTypeFontFace* const ftFace = findOrCreate (fontName);
  219332. if (ftFace != 0)
  219333. {
  219334. int style = (int) FreeTypeFontFace::Plain;
  219335. if (bold)
  219336. style |= (int) FreeTypeFontFace::Bold;
  219337. if (italic)
  219338. style |= (int) FreeTypeFontFace::Italic;
  219339. int faceIndex;
  219340. String fileName (ftFace->getFileName (style, faceIndex));
  219341. if (fileName.isEmpty())
  219342. {
  219343. style ^= (int) FreeTypeFontFace::Bold;
  219344. fileName = ftFace->getFileName (style, faceIndex);
  219345. if (fileName.isEmpty())
  219346. {
  219347. style ^= (int) FreeTypeFontFace::Bold;
  219348. style ^= (int) FreeTypeFontFace::Italic;
  219349. fileName = ftFace->getFileName (style, faceIndex);
  219350. if (! fileName.length())
  219351. {
  219352. style ^= (int) FreeTypeFontFace::Bold;
  219353. fileName = ftFace->getFileName (style, faceIndex);
  219354. }
  219355. }
  219356. }
  219357. if (! FT_New_Face (ftLib, fileName.toUTF8(), faceIndex, &lastFace))
  219358. {
  219359. face = lastFace;
  219360. // If there isn't a unicode charmap then select the first one.
  219361. if (FT_Select_Charmap (face, ft_encoding_unicode))
  219362. FT_Set_Charmap (face, face->charmaps[0]);
  219363. }
  219364. }
  219365. }
  219366. return face;
  219367. }
  219368. bool addGlyph (FT_Face face, CustomTypeface& dest, uint32 character)
  219369. {
  219370. const unsigned int glyphIndex = FT_Get_Char_Index (face, character);
  219371. const float height = (float) (face->ascender - face->descender);
  219372. const float scaleX = 1.0f / height;
  219373. const float scaleY = -1.0f / height;
  219374. Path destShape;
  219375. if (FT_Load_Glyph (face, glyphIndex, FT_LOAD_NO_SCALE | FT_LOAD_NO_BITMAP | FT_LOAD_IGNORE_TRANSFORM) != 0
  219376. || face->glyph->format != ft_glyph_format_outline)
  219377. {
  219378. return false;
  219379. }
  219380. const FT_Outline* const outline = &face->glyph->outline;
  219381. const short* const contours = outline->contours;
  219382. const char* const tags = outline->tags;
  219383. FT_Vector* const points = outline->points;
  219384. for (int c = 0; c < outline->n_contours; c++)
  219385. {
  219386. const int startPoint = (c == 0) ? 0 : contours [c - 1] + 1;
  219387. const int endPoint = contours[c];
  219388. for (int p = startPoint; p <= endPoint; p++)
  219389. {
  219390. const float x = scaleX * points[p].x;
  219391. const float y = scaleY * points[p].y;
  219392. if (p == startPoint)
  219393. {
  219394. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  219395. {
  219396. float x2 = scaleX * points [endPoint].x;
  219397. float y2 = scaleY * points [endPoint].y;
  219398. if (FT_CURVE_TAG (tags[endPoint]) != FT_Curve_Tag_On)
  219399. {
  219400. x2 = (x + x2) * 0.5f;
  219401. y2 = (y + y2) * 0.5f;
  219402. }
  219403. destShape.startNewSubPath (x2, y2);
  219404. }
  219405. else
  219406. {
  219407. destShape.startNewSubPath (x, y);
  219408. }
  219409. }
  219410. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_On)
  219411. {
  219412. if (p != startPoint)
  219413. destShape.lineTo (x, y);
  219414. }
  219415. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  219416. {
  219417. const int nextIndex = (p == endPoint) ? startPoint : p + 1;
  219418. float x2 = scaleX * points [nextIndex].x;
  219419. float y2 = scaleY * points [nextIndex].y;
  219420. if (FT_CURVE_TAG (tags [nextIndex]) == FT_Curve_Tag_Conic)
  219421. {
  219422. x2 = (x + x2) * 0.5f;
  219423. y2 = (y + y2) * 0.5f;
  219424. }
  219425. else
  219426. {
  219427. ++p;
  219428. }
  219429. destShape.quadraticTo (x, y, x2, y2);
  219430. }
  219431. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Cubic)
  219432. {
  219433. if (p >= endPoint)
  219434. return false;
  219435. const int next1 = p + 1;
  219436. const int next2 = (p == (endPoint - 1)) ? startPoint : p + 2;
  219437. const float x2 = scaleX * points [next1].x;
  219438. const float y2 = scaleY * points [next1].y;
  219439. const float x3 = scaleX * points [next2].x;
  219440. const float y3 = scaleY * points [next2].y;
  219441. if (FT_CURVE_TAG (tags[next1]) != FT_Curve_Tag_Cubic
  219442. || FT_CURVE_TAG (tags[next2]) != FT_Curve_Tag_On)
  219443. return false;
  219444. destShape.cubicTo (x, y, x2, y2, x3, y3);
  219445. p += 2;
  219446. }
  219447. }
  219448. destShape.closeSubPath();
  219449. }
  219450. dest.addGlyph (character, destShape, face->glyph->metrics.horiAdvance / height);
  219451. if ((face->face_flags & FT_FACE_FLAG_KERNING) != 0)
  219452. addKerning (face, dest, character, glyphIndex);
  219453. return true;
  219454. }
  219455. void addKerning (FT_Face face, CustomTypeface& dest, const uint32 character, const uint32 glyphIndex)
  219456. {
  219457. const float height = (float) (face->ascender - face->descender);
  219458. uint32 rightGlyphIndex;
  219459. uint32 rightCharCode = FT_Get_First_Char (face, &rightGlyphIndex);
  219460. while (rightGlyphIndex != 0)
  219461. {
  219462. FT_Vector kerning;
  219463. if (FT_Get_Kerning (face, glyphIndex, rightGlyphIndex, ft_kerning_unscaled, &kerning) == 0)
  219464. {
  219465. if (kerning.x != 0)
  219466. dest.addKerningPair (character, rightCharCode, kerning.x / height);
  219467. }
  219468. rightCharCode = FT_Get_Next_Char (face, rightCharCode, &rightGlyphIndex);
  219469. }
  219470. }
  219471. // Add a glyph to a font
  219472. bool addGlyphToFont (const uint32 character, const String& fontName,
  219473. bool bold, bool italic, CustomTypeface& dest)
  219474. {
  219475. FT_Face face = createFT_Face (fontName, bold, italic);
  219476. return face != 0 && addGlyph (face, dest, character);
  219477. }
  219478. void getFamilyNames (StringArray& familyNames) const
  219479. {
  219480. for (int i = 0; i < faces.size(); i++)
  219481. familyNames.add (faces[i]->getFamilyName());
  219482. }
  219483. void getMonospacedNames (StringArray& monoSpaced) const
  219484. {
  219485. for (int i = 0; i < faces.size(); i++)
  219486. if (faces[i]->getMonospaced())
  219487. monoSpaced.add (faces[i]->getFamilyName());
  219488. }
  219489. void getSerifNames (StringArray& serif) const
  219490. {
  219491. for (int i = 0; i < faces.size(); i++)
  219492. if (faces[i]->getSerif())
  219493. serif.add (faces[i]->getFamilyName());
  219494. }
  219495. void getSansSerifNames (StringArray& sansSerif) const
  219496. {
  219497. for (int i = 0; i < faces.size(); i++)
  219498. if (! faces[i]->getSerif())
  219499. sansSerif.add (faces[i]->getFamilyName());
  219500. }
  219501. juce_DeclareSingleton_SingleThreaded_Minimal (FreeTypeInterface)
  219502. private:
  219503. FT_Library ftLib;
  219504. FT_Face lastFace;
  219505. String lastFontName;
  219506. bool lastBold, lastItalic;
  219507. OwnedArray<FreeTypeFontFace> faces;
  219508. };
  219509. juce_ImplementSingleton_SingleThreaded (FreeTypeInterface)
  219510. class FreetypeTypeface : public CustomTypeface
  219511. {
  219512. public:
  219513. FreetypeTypeface (const Font& font)
  219514. {
  219515. FT_Face face = FreeTypeInterface::getInstance()
  219516. ->createFT_Face (font.getTypefaceName(), font.isBold(), font.isItalic());
  219517. if (face == 0)
  219518. {
  219519. #if JUCE_DEBUG
  219520. String msg ("Failed to create typeface: ");
  219521. msg << font.getTypefaceName() << " " << (font.isBold() ? 'B' : ' ') << (font.isItalic() ? 'I' : ' ');
  219522. DBG (msg);
  219523. #endif
  219524. }
  219525. else
  219526. {
  219527. setCharacteristics (font.getTypefaceName(),
  219528. face->ascender / (float) (face->ascender - face->descender),
  219529. font.isBold(), font.isItalic(),
  219530. L' ');
  219531. }
  219532. }
  219533. bool loadGlyphIfPossible (juce_wchar character)
  219534. {
  219535. return FreeTypeInterface::getInstance()
  219536. ->addGlyphToFont (character, name, isBold, isItalic, *this);
  219537. }
  219538. };
  219539. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  219540. {
  219541. return new FreetypeTypeface (font);
  219542. }
  219543. const StringArray Font::findAllTypefaceNames()
  219544. {
  219545. StringArray s;
  219546. FreeTypeInterface::getInstance()->getFamilyNames (s);
  219547. s.sort (true);
  219548. return s;
  219549. }
  219550. static const String pickBestFont (const StringArray& names,
  219551. const char* const choicesString)
  219552. {
  219553. StringArray choices;
  219554. choices.addTokens (String (choicesString), ",", String::empty);
  219555. choices.trim();
  219556. choices.removeEmptyStrings();
  219557. int i, j;
  219558. for (j = 0; j < choices.size(); ++j)
  219559. if (names.contains (choices[j], true))
  219560. return choices[j];
  219561. for (j = 0; j < choices.size(); ++j)
  219562. for (i = 0; i < names.size(); i++)
  219563. if (names[i].startsWithIgnoreCase (choices[j]))
  219564. return names[i];
  219565. for (j = 0; j < choices.size(); ++j)
  219566. for (i = 0; i < names.size(); i++)
  219567. if (names[i].containsIgnoreCase (choices[j]))
  219568. return names[i];
  219569. return names[0];
  219570. }
  219571. static const String linux_getDefaultSansSerifFontName()
  219572. {
  219573. StringArray allFonts;
  219574. FreeTypeInterface::getInstance()->getSansSerifNames (allFonts);
  219575. return pickBestFont (allFonts, "Verdana, Bitstream Vera Sans, Luxi Sans, Sans");
  219576. }
  219577. static const String linux_getDefaultSerifFontName()
  219578. {
  219579. StringArray allFonts;
  219580. FreeTypeInterface::getInstance()->getSerifNames (allFonts);
  219581. return pickBestFont (allFonts, "Bitstream Vera Serif, Times, Nimbus Roman, Serif");
  219582. }
  219583. static const String linux_getDefaultMonospacedFontName()
  219584. {
  219585. StringArray allFonts;
  219586. FreeTypeInterface::getInstance()->getMonospacedNames (allFonts);
  219587. return pickBestFont (allFonts, "Bitstream Vera Sans Mono, Courier, Sans Mono, Mono");
  219588. }
  219589. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  219590. {
  219591. defaultSans = linux_getDefaultSansSerifFontName();
  219592. defaultSerif = linux_getDefaultSerifFontName();
  219593. defaultFixed = linux_getDefaultMonospacedFontName();
  219594. }
  219595. #endif
  219596. /*** End of inlined file: juce_linux_Fonts.cpp ***/
  219597. /*** Start of inlined file: juce_linux_Windowing.cpp ***/
  219598. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  219599. // compiled on its own).
  219600. #if JUCE_INCLUDED_FILE
  219601. // These are defined in juce_linux_Messaging.cpp
  219602. extern Display* display;
  219603. extern XContext windowHandleXContext;
  219604. namespace Atoms
  219605. {
  219606. enum ProtocolItems
  219607. {
  219608. TAKE_FOCUS = 0,
  219609. DELETE_WINDOW = 1,
  219610. PING = 2
  219611. };
  219612. static Atom Protocols, ProtocolList[3], ChangeState, State,
  219613. ActiveWin, Pid, WindowType, WindowState,
  219614. XdndAware, XdndEnter, XdndLeave, XdndPosition, XdndStatus,
  219615. XdndDrop, XdndFinished, XdndSelection, XdndTypeList, XdndActionList,
  219616. XdndActionDescription, XdndActionCopy,
  219617. allowedActions[5],
  219618. allowedMimeTypes[2];
  219619. const unsigned long DndVersion = 3;
  219620. static void initialiseAtoms()
  219621. {
  219622. static bool atomsInitialised = false;
  219623. if (! atomsInitialised)
  219624. {
  219625. atomsInitialised = true;
  219626. Protocols = XInternAtom (display, "WM_PROTOCOLS", True);
  219627. ProtocolList [TAKE_FOCUS] = XInternAtom (display, "WM_TAKE_FOCUS", True);
  219628. ProtocolList [DELETE_WINDOW] = XInternAtom (display, "WM_DELETE_WINDOW", True);
  219629. ProtocolList [PING] = XInternAtom (display, "_NET_WM_PING", True);
  219630. ChangeState = XInternAtom (display, "WM_CHANGE_STATE", True);
  219631. State = XInternAtom (display, "WM_STATE", True);
  219632. ActiveWin = XInternAtom (display, "_NET_ACTIVE_WINDOW", False);
  219633. Pid = XInternAtom (display, "_NET_WM_PID", False);
  219634. WindowType = XInternAtom (display, "_NET_WM_WINDOW_TYPE", True);
  219635. WindowState = XInternAtom (display, "_NET_WM_STATE", True);
  219636. XdndAware = XInternAtom (display, "XdndAware", False);
  219637. XdndEnter = XInternAtom (display, "XdndEnter", False);
  219638. XdndLeave = XInternAtom (display, "XdndLeave", False);
  219639. XdndPosition = XInternAtom (display, "XdndPosition", False);
  219640. XdndStatus = XInternAtom (display, "XdndStatus", False);
  219641. XdndDrop = XInternAtom (display, "XdndDrop", False);
  219642. XdndFinished = XInternAtom (display, "XdndFinished", False);
  219643. XdndSelection = XInternAtom (display, "XdndSelection", False);
  219644. XdndTypeList = XInternAtom (display, "XdndTypeList", False);
  219645. XdndActionList = XInternAtom (display, "XdndActionList", False);
  219646. XdndActionCopy = XInternAtom (display, "XdndActionCopy", False);
  219647. XdndActionDescription = XInternAtom (display, "XdndActionDescription", False);
  219648. allowedMimeTypes[0] = XInternAtom (display, "text/plain", False);
  219649. allowedMimeTypes[1] = XInternAtom (display, "text/uri-list", False);
  219650. allowedActions[0] = XInternAtom (display, "XdndActionMove", False);
  219651. allowedActions[1] = XdndActionCopy;
  219652. allowedActions[2] = XInternAtom (display, "XdndActionLink", False);
  219653. allowedActions[3] = XInternAtom (display, "XdndActionAsk", False);
  219654. allowedActions[4] = XInternAtom (display, "XdndActionPrivate", False);
  219655. }
  219656. }
  219657. }
  219658. namespace Keys
  219659. {
  219660. enum MouseButtons
  219661. {
  219662. NoButton = 0,
  219663. LeftButton = 1,
  219664. MiddleButton = 2,
  219665. RightButton = 3,
  219666. WheelUp = 4,
  219667. WheelDown = 5
  219668. };
  219669. static int AltMask = 0;
  219670. static int NumLockMask = 0;
  219671. static bool numLock = false;
  219672. static bool capsLock = false;
  219673. static char keyStates [32];
  219674. static const int extendedKeyModifier = 0x10000000;
  219675. }
  219676. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  219677. {
  219678. int keysym;
  219679. if (keyCode & Keys::extendedKeyModifier)
  219680. {
  219681. keysym = 0xff00 | (keyCode & 0xff);
  219682. }
  219683. else
  219684. {
  219685. keysym = keyCode;
  219686. if (keysym == (XK_Tab & 0xff)
  219687. || keysym == (XK_Return & 0xff)
  219688. || keysym == (XK_Escape & 0xff)
  219689. || keysym == (XK_BackSpace & 0xff))
  219690. {
  219691. keysym |= 0xff00;
  219692. }
  219693. }
  219694. ScopedXLock xlock;
  219695. const int keycode = XKeysymToKeycode (display, keysym);
  219696. const int keybyte = keycode >> 3;
  219697. const int keybit = (1 << (keycode & 7));
  219698. return (Keys::keyStates [keybyte] & keybit) != 0;
  219699. }
  219700. #if JUCE_USE_XSHM
  219701. namespace XSHMHelpers
  219702. {
  219703. static int trappedErrorCode = 0;
  219704. extern "C" int errorTrapHandler (Display*, XErrorEvent* err)
  219705. {
  219706. trappedErrorCode = err->error_code;
  219707. return 0;
  219708. }
  219709. static bool isShmAvailable() throw()
  219710. {
  219711. static bool isChecked = false;
  219712. static bool isAvailable = false;
  219713. if (! isChecked)
  219714. {
  219715. isChecked = true;
  219716. int major, minor;
  219717. Bool pixmaps;
  219718. ScopedXLock xlock;
  219719. if (XShmQueryVersion (display, &major, &minor, &pixmaps))
  219720. {
  219721. trappedErrorCode = 0;
  219722. XErrorHandler oldHandler = XSetErrorHandler (errorTrapHandler);
  219723. XShmSegmentInfo segmentInfo;
  219724. zerostruct (segmentInfo);
  219725. XImage* xImage = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  219726. 24, ZPixmap, 0, &segmentInfo, 50, 50);
  219727. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  219728. xImage->bytes_per_line * xImage->height,
  219729. IPC_CREAT | 0777)) >= 0)
  219730. {
  219731. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  219732. if (segmentInfo.shmaddr != (void*) -1)
  219733. {
  219734. segmentInfo.readOnly = False;
  219735. xImage->data = segmentInfo.shmaddr;
  219736. XSync (display, False);
  219737. if (XShmAttach (display, &segmentInfo) != 0)
  219738. {
  219739. XSync (display, False);
  219740. XShmDetach (display, &segmentInfo);
  219741. isAvailable = true;
  219742. }
  219743. }
  219744. XFlush (display);
  219745. XDestroyImage (xImage);
  219746. shmdt (segmentInfo.shmaddr);
  219747. }
  219748. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  219749. XSetErrorHandler (oldHandler);
  219750. if (trappedErrorCode != 0)
  219751. isAvailable = false;
  219752. }
  219753. }
  219754. return isAvailable;
  219755. }
  219756. }
  219757. #endif
  219758. #if JUCE_USE_XRENDER
  219759. namespace XRender
  219760. {
  219761. typedef Status (*tXRenderQueryVersion) (Display*, int*, int*);
  219762. typedef XRenderPictFormat* (*tXrenderFindStandardFormat) (Display*, int);
  219763. typedef XRenderPictFormat* (*tXRenderFindFormat) (Display*, unsigned long, XRenderPictFormat*, int);
  219764. typedef XRenderPictFormat* (*tXRenderFindVisualFormat) (Display*, Visual*);
  219765. static tXRenderQueryVersion xRenderQueryVersion = 0;
  219766. static tXrenderFindStandardFormat xRenderFindStandardFormat = 0;
  219767. static tXRenderFindFormat xRenderFindFormat = 0;
  219768. static tXRenderFindVisualFormat xRenderFindVisualFormat = 0;
  219769. static bool isAvailable()
  219770. {
  219771. static bool hasLoaded = false;
  219772. if (! hasLoaded)
  219773. {
  219774. ScopedXLock xlock;
  219775. hasLoaded = true;
  219776. void* h = dlopen ("libXrender.so", RTLD_GLOBAL | RTLD_NOW);
  219777. if (h != 0)
  219778. {
  219779. xRenderQueryVersion = (tXRenderQueryVersion) dlsym (h, "XRenderQueryVersion");
  219780. xRenderFindStandardFormat = (tXrenderFindStandardFormat) dlsym (h, "XrenderFindStandardFormat");
  219781. xRenderFindFormat = (tXRenderFindFormat) dlsym (h, "XRenderFindFormat");
  219782. xRenderFindVisualFormat = (tXRenderFindVisualFormat) dlsym (h, "XRenderFindVisualFormat");
  219783. }
  219784. if (xRenderQueryVersion != 0
  219785. && xRenderFindStandardFormat != 0
  219786. && xRenderFindFormat != 0
  219787. && xRenderFindVisualFormat != 0)
  219788. {
  219789. int major, minor;
  219790. if (xRenderQueryVersion (display, &major, &minor))
  219791. return true;
  219792. }
  219793. xRenderQueryVersion = 0;
  219794. }
  219795. return xRenderQueryVersion != 0;
  219796. }
  219797. static XRenderPictFormat* findPictureFormat()
  219798. {
  219799. ScopedXLock xlock;
  219800. XRenderPictFormat* pictFormat = 0;
  219801. if (isAvailable())
  219802. {
  219803. pictFormat = xRenderFindStandardFormat (display, PictStandardARGB32);
  219804. if (pictFormat == 0)
  219805. {
  219806. XRenderPictFormat desiredFormat;
  219807. desiredFormat.type = PictTypeDirect;
  219808. desiredFormat.depth = 32;
  219809. desiredFormat.direct.alphaMask = 0xff;
  219810. desiredFormat.direct.redMask = 0xff;
  219811. desiredFormat.direct.greenMask = 0xff;
  219812. desiredFormat.direct.blueMask = 0xff;
  219813. desiredFormat.direct.alpha = 24;
  219814. desiredFormat.direct.red = 16;
  219815. desiredFormat.direct.green = 8;
  219816. desiredFormat.direct.blue = 0;
  219817. pictFormat = xRenderFindFormat (display,
  219818. PictFormatType | PictFormatDepth
  219819. | PictFormatRedMask | PictFormatRed
  219820. | PictFormatGreenMask | PictFormatGreen
  219821. | PictFormatBlueMask | PictFormatBlue
  219822. | PictFormatAlphaMask | PictFormatAlpha,
  219823. &desiredFormat,
  219824. 0);
  219825. }
  219826. }
  219827. return pictFormat;
  219828. }
  219829. }
  219830. #endif
  219831. namespace Visuals
  219832. {
  219833. static Visual* findVisualWithDepth (const int desiredDepth) throw()
  219834. {
  219835. ScopedXLock xlock;
  219836. Visual* visual = 0;
  219837. int numVisuals = 0;
  219838. long desiredMask = VisualNoMask;
  219839. XVisualInfo desiredVisual;
  219840. desiredVisual.screen = DefaultScreen (display);
  219841. desiredVisual.depth = desiredDepth;
  219842. desiredMask = VisualScreenMask | VisualDepthMask;
  219843. if (desiredDepth == 32)
  219844. {
  219845. desiredVisual.c_class = TrueColor;
  219846. desiredVisual.red_mask = 0x00FF0000;
  219847. desiredVisual.green_mask = 0x0000FF00;
  219848. desiredVisual.blue_mask = 0x000000FF;
  219849. desiredVisual.bits_per_rgb = 8;
  219850. desiredMask |= VisualClassMask;
  219851. desiredMask |= VisualRedMaskMask;
  219852. desiredMask |= VisualGreenMaskMask;
  219853. desiredMask |= VisualBlueMaskMask;
  219854. desiredMask |= VisualBitsPerRGBMask;
  219855. }
  219856. XVisualInfo* xvinfos = XGetVisualInfo (display,
  219857. desiredMask,
  219858. &desiredVisual,
  219859. &numVisuals);
  219860. if (xvinfos != 0)
  219861. {
  219862. for (int i = 0; i < numVisuals; i++)
  219863. {
  219864. if (xvinfos[i].depth == desiredDepth)
  219865. {
  219866. visual = xvinfos[i].visual;
  219867. break;
  219868. }
  219869. }
  219870. XFree (xvinfos);
  219871. }
  219872. return visual;
  219873. }
  219874. static Visual* findVisualFormat (const int desiredDepth, int& matchedDepth) throw()
  219875. {
  219876. Visual* visual = 0;
  219877. if (desiredDepth == 32)
  219878. {
  219879. #if JUCE_USE_XSHM
  219880. if (XSHMHelpers::isShmAvailable())
  219881. {
  219882. #if JUCE_USE_XRENDER
  219883. if (XRender::isAvailable())
  219884. {
  219885. XRenderPictFormat* pictFormat = XRender::findPictureFormat();
  219886. if (pictFormat != 0)
  219887. {
  219888. int numVisuals = 0;
  219889. XVisualInfo desiredVisual;
  219890. desiredVisual.screen = DefaultScreen (display);
  219891. desiredVisual.depth = 32;
  219892. desiredVisual.bits_per_rgb = 8;
  219893. XVisualInfo* xvinfos = XGetVisualInfo (display,
  219894. VisualScreenMask | VisualDepthMask | VisualBitsPerRGBMask,
  219895. &desiredVisual, &numVisuals);
  219896. if (xvinfos != 0)
  219897. {
  219898. for (int i = 0; i < numVisuals; ++i)
  219899. {
  219900. XRenderPictFormat* pictVisualFormat = XRender::xRenderFindVisualFormat (display, xvinfos[i].visual);
  219901. if (pictVisualFormat != 0
  219902. && pictVisualFormat->type == PictTypeDirect
  219903. && pictVisualFormat->direct.alphaMask)
  219904. {
  219905. visual = xvinfos[i].visual;
  219906. matchedDepth = 32;
  219907. break;
  219908. }
  219909. }
  219910. XFree (xvinfos);
  219911. }
  219912. }
  219913. }
  219914. #endif
  219915. if (visual == 0)
  219916. {
  219917. visual = findVisualWithDepth (32);
  219918. if (visual != 0)
  219919. matchedDepth = 32;
  219920. }
  219921. }
  219922. #endif
  219923. }
  219924. if (visual == 0 && desiredDepth >= 24)
  219925. {
  219926. visual = findVisualWithDepth (24);
  219927. if (visual != 0)
  219928. matchedDepth = 24;
  219929. }
  219930. if (visual == 0 && desiredDepth >= 16)
  219931. {
  219932. visual = findVisualWithDepth (16);
  219933. if (visual != 0)
  219934. matchedDepth = 16;
  219935. }
  219936. return visual;
  219937. }
  219938. }
  219939. class XBitmapImage : public Image::SharedImage
  219940. {
  219941. public:
  219942. XBitmapImage (const Image::PixelFormat format_, const int w, const int h,
  219943. const bool clearImage, const int imageDepth_, Visual* visual)
  219944. : Image::SharedImage (format_, w, h),
  219945. imageDepth (imageDepth_),
  219946. gc (None)
  219947. {
  219948. jassert (format_ == Image::RGB || format_ == Image::ARGB);
  219949. pixelStride = (format_ == Image::RGB) ? 3 : 4;
  219950. lineStride = ((w * pixelStride + 3) & ~3);
  219951. ScopedXLock xlock;
  219952. #if JUCE_USE_XSHM
  219953. usingXShm = false;
  219954. if ((imageDepth > 16) && XSHMHelpers::isShmAvailable())
  219955. {
  219956. zerostruct (segmentInfo);
  219957. segmentInfo.shmid = -1;
  219958. segmentInfo.shmaddr = (char *) -1;
  219959. segmentInfo.readOnly = False;
  219960. xImage = XShmCreateImage (display, visual, imageDepth, ZPixmap, 0, &segmentInfo, w, h);
  219961. if (xImage != 0)
  219962. {
  219963. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  219964. xImage->bytes_per_line * xImage->height,
  219965. IPC_CREAT | 0777)) >= 0)
  219966. {
  219967. if (segmentInfo.shmid != -1)
  219968. {
  219969. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  219970. if (segmentInfo.shmaddr != (void*) -1)
  219971. {
  219972. segmentInfo.readOnly = False;
  219973. xImage->data = segmentInfo.shmaddr;
  219974. imageData = (uint8*) segmentInfo.shmaddr;
  219975. if (XShmAttach (display, &segmentInfo) != 0)
  219976. usingXShm = true;
  219977. else
  219978. jassertfalse;
  219979. }
  219980. else
  219981. {
  219982. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  219983. }
  219984. }
  219985. }
  219986. }
  219987. }
  219988. if (! usingXShm)
  219989. #endif
  219990. {
  219991. imageDataAllocated.malloc (lineStride * h);
  219992. imageData = imageDataAllocated;
  219993. if (format_ == Image::ARGB && clearImage)
  219994. zeromem (imageData, h * lineStride);
  219995. xImage = (XImage*) juce_calloc (sizeof (XImage));
  219996. xImage->width = w;
  219997. xImage->height = h;
  219998. xImage->xoffset = 0;
  219999. xImage->format = ZPixmap;
  220000. xImage->data = (char*) imageData;
  220001. xImage->byte_order = ImageByteOrder (display);
  220002. xImage->bitmap_unit = BitmapUnit (display);
  220003. xImage->bitmap_bit_order = BitmapBitOrder (display);
  220004. xImage->bitmap_pad = 32;
  220005. xImage->depth = pixelStride * 8;
  220006. xImage->bytes_per_line = lineStride;
  220007. xImage->bits_per_pixel = pixelStride * 8;
  220008. xImage->red_mask = 0x00FF0000;
  220009. xImage->green_mask = 0x0000FF00;
  220010. xImage->blue_mask = 0x000000FF;
  220011. if (imageDepth == 16)
  220012. {
  220013. const int pixelStride = 2;
  220014. const int lineStride = ((w * pixelStride + 3) & ~3);
  220015. imageData16Bit.malloc (lineStride * h);
  220016. xImage->data = imageData16Bit;
  220017. xImage->bitmap_pad = 16;
  220018. xImage->depth = pixelStride * 8;
  220019. xImage->bytes_per_line = lineStride;
  220020. xImage->bits_per_pixel = pixelStride * 8;
  220021. xImage->red_mask = visual->red_mask;
  220022. xImage->green_mask = visual->green_mask;
  220023. xImage->blue_mask = visual->blue_mask;
  220024. }
  220025. if (! XInitImage (xImage))
  220026. jassertfalse;
  220027. }
  220028. }
  220029. ~XBitmapImage()
  220030. {
  220031. ScopedXLock xlock;
  220032. if (gc != None)
  220033. XFreeGC (display, gc);
  220034. #if JUCE_USE_XSHM
  220035. if (usingXShm)
  220036. {
  220037. XShmDetach (display, &segmentInfo);
  220038. XFlush (display);
  220039. XDestroyImage (xImage);
  220040. shmdt (segmentInfo.shmaddr);
  220041. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  220042. }
  220043. else
  220044. #endif
  220045. {
  220046. xImage->data = 0;
  220047. XDestroyImage (xImage);
  220048. }
  220049. }
  220050. Image::ImageType getType() const { return Image::NativeImage; }
  220051. LowLevelGraphicsContext* createLowLevelContext()
  220052. {
  220053. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  220054. }
  220055. SharedImage* clone()
  220056. {
  220057. jassertfalse;
  220058. return 0;
  220059. }
  220060. void blitToWindow (Window window, int dx, int dy, int dw, int dh, int sx, int sy)
  220061. {
  220062. ScopedXLock xlock;
  220063. if (gc == None)
  220064. {
  220065. XGCValues gcvalues;
  220066. gcvalues.foreground = None;
  220067. gcvalues.background = None;
  220068. gcvalues.function = GXcopy;
  220069. gcvalues.plane_mask = AllPlanes;
  220070. gcvalues.clip_mask = None;
  220071. gcvalues.graphics_exposures = False;
  220072. gc = XCreateGC (display, window,
  220073. GCBackground | GCForeground | GCFunction | GCPlaneMask | GCClipMask | GCGraphicsExposures,
  220074. &gcvalues);
  220075. }
  220076. if (imageDepth == 16)
  220077. {
  220078. const uint32 rMask = xImage->red_mask;
  220079. const uint32 rShiftL = jmax (0, getShiftNeeded (rMask));
  220080. const uint32 rShiftR = jmax (0, -getShiftNeeded (rMask));
  220081. const uint32 gMask = xImage->green_mask;
  220082. const uint32 gShiftL = jmax (0, getShiftNeeded (gMask));
  220083. const uint32 gShiftR = jmax (0, -getShiftNeeded (gMask));
  220084. const uint32 bMask = xImage->blue_mask;
  220085. const uint32 bShiftL = jmax (0, getShiftNeeded (bMask));
  220086. const uint32 bShiftR = jmax (0, -getShiftNeeded (bMask));
  220087. const Image::BitmapData srcData (Image (this), false);
  220088. for (int y = sy; y < sy + dh; ++y)
  220089. {
  220090. const uint8* p = srcData.getPixelPointer (sx, y);
  220091. for (int x = sx; x < sx + dw; ++x)
  220092. {
  220093. const PixelRGB* const pixel = (const PixelRGB*) p;
  220094. p += srcData.pixelStride;
  220095. XPutPixel (xImage, x, y,
  220096. (((((uint32) pixel->getRed()) << rShiftL) >> rShiftR) & rMask)
  220097. | (((((uint32) pixel->getGreen()) << gShiftL) >> gShiftR) & gMask)
  220098. | (((((uint32) pixel->getBlue()) << bShiftL) >> bShiftR) & bMask));
  220099. }
  220100. }
  220101. }
  220102. // blit results to screen.
  220103. #if JUCE_USE_XSHM
  220104. if (usingXShm)
  220105. XShmPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh, True);
  220106. else
  220107. #endif
  220108. XPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh);
  220109. }
  220110. juce_UseDebuggingNewOperator
  220111. private:
  220112. XImage* xImage;
  220113. const int imageDepth;
  220114. HeapBlock <uint8> imageDataAllocated;
  220115. HeapBlock <char> imageData16Bit;
  220116. GC gc;
  220117. #if JUCE_USE_XSHM
  220118. XShmSegmentInfo segmentInfo;
  220119. bool usingXShm;
  220120. #endif
  220121. static int getShiftNeeded (const uint32 mask) throw()
  220122. {
  220123. for (int i = 32; --i >= 0;)
  220124. if (((mask >> i) & 1) != 0)
  220125. return i - 7;
  220126. jassertfalse;
  220127. return 0;
  220128. }
  220129. };
  220130. class LinuxComponentPeer : public ComponentPeer
  220131. {
  220132. public:
  220133. LinuxComponentPeer (Component* const component, const int windowStyleFlags)
  220134. : ComponentPeer (component, windowStyleFlags),
  220135. windowH (0),
  220136. parentWindow (0),
  220137. wx (0),
  220138. wy (0),
  220139. ww (0),
  220140. wh (0),
  220141. fullScreen (false),
  220142. mapped (false),
  220143. visual (0),
  220144. depth (0)
  220145. {
  220146. // it's dangerous to create a window on a thread other than the message thread..
  220147. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  220148. repainter = new LinuxRepaintManager (this);
  220149. createWindow();
  220150. setTitle (component->getName());
  220151. }
  220152. ~LinuxComponentPeer()
  220153. {
  220154. // it's dangerous to delete a window on a thread other than the message thread..
  220155. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  220156. deleteIconPixmaps();
  220157. destroyWindow();
  220158. windowH = 0;
  220159. }
  220160. void* getNativeHandle() const
  220161. {
  220162. return (void*) windowH;
  220163. }
  220164. static LinuxComponentPeer* getPeerFor (Window windowHandle) throw()
  220165. {
  220166. XPointer peer = 0;
  220167. ScopedXLock xlock;
  220168. if (! XFindContext (display, (XID) windowHandle, windowHandleXContext, &peer))
  220169. {
  220170. if (peer != 0 && ! ComponentPeer::isValidPeer ((LinuxComponentPeer*) peer))
  220171. peer = 0;
  220172. }
  220173. return (LinuxComponentPeer*) peer;
  220174. }
  220175. void setVisible (bool shouldBeVisible)
  220176. {
  220177. ScopedXLock xlock;
  220178. if (shouldBeVisible)
  220179. XMapWindow (display, windowH);
  220180. else
  220181. XUnmapWindow (display, windowH);
  220182. }
  220183. void setTitle (const String& title)
  220184. {
  220185. setWindowTitle (windowH, title);
  220186. }
  220187. void setPosition (int x, int y)
  220188. {
  220189. setBounds (x, y, ww, wh, false);
  220190. }
  220191. void setSize (int w, int h)
  220192. {
  220193. setBounds (wx, wy, w, h, false);
  220194. }
  220195. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  220196. {
  220197. fullScreen = isNowFullScreen;
  220198. if (windowH != 0)
  220199. {
  220200. Component::SafePointer<Component> deletionChecker (component);
  220201. wx = x;
  220202. wy = y;
  220203. ww = jmax (1, w);
  220204. wh = jmax (1, h);
  220205. ScopedXLock xlock;
  220206. // Make sure the Window manager does what we want
  220207. XSizeHints* hints = XAllocSizeHints();
  220208. hints->flags = USSize | USPosition;
  220209. hints->width = ww;
  220210. hints->height = wh;
  220211. hints->x = wx;
  220212. hints->y = wy;
  220213. if ((getStyleFlags() & (windowHasTitleBar | windowIsResizable)) == windowHasTitleBar)
  220214. {
  220215. hints->min_width = hints->max_width = hints->width;
  220216. hints->min_height = hints->max_height = hints->height;
  220217. hints->flags |= PMinSize | PMaxSize;
  220218. }
  220219. XSetWMNormalHints (display, windowH, hints);
  220220. XFree (hints);
  220221. XMoveResizeWindow (display, windowH,
  220222. wx - windowBorder.getLeft(),
  220223. wy - windowBorder.getTop(), ww, wh);
  220224. if (deletionChecker != 0)
  220225. {
  220226. updateBorderSize();
  220227. handleMovedOrResized();
  220228. }
  220229. }
  220230. }
  220231. const Rectangle<int> getBounds() const { return Rectangle<int> (wx, wy, ww, wh); }
  220232. const Point<int> getScreenPosition() const { return Point<int> (wx, wy); }
  220233. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  220234. {
  220235. return relativePosition + getScreenPosition();
  220236. }
  220237. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  220238. {
  220239. return screenPosition - getScreenPosition();
  220240. }
  220241. void setMinimised (bool shouldBeMinimised)
  220242. {
  220243. if (shouldBeMinimised)
  220244. {
  220245. Window root = RootWindow (display, DefaultScreen (display));
  220246. XClientMessageEvent clientMsg;
  220247. clientMsg.display = display;
  220248. clientMsg.window = windowH;
  220249. clientMsg.type = ClientMessage;
  220250. clientMsg.format = 32;
  220251. clientMsg.message_type = Atoms::ChangeState;
  220252. clientMsg.data.l[0] = IconicState;
  220253. ScopedXLock xlock;
  220254. XSendEvent (display, root, false, SubstructureRedirectMask | SubstructureNotifyMask, (XEvent*) &clientMsg);
  220255. }
  220256. else
  220257. {
  220258. setVisible (true);
  220259. }
  220260. }
  220261. bool isMinimised() const
  220262. {
  220263. bool minimised = false;
  220264. unsigned char* stateProp;
  220265. unsigned long nitems, bytesLeft;
  220266. Atom actualType;
  220267. int actualFormat;
  220268. ScopedXLock xlock;
  220269. if (XGetWindowProperty (display, windowH, Atoms::State, 0, 64, False,
  220270. Atoms::State, &actualType, &actualFormat, &nitems, &bytesLeft,
  220271. &stateProp) == Success
  220272. && actualType == Atoms::State
  220273. && actualFormat == 32
  220274. && nitems > 0)
  220275. {
  220276. if (((unsigned long*) stateProp)[0] == IconicState)
  220277. minimised = true;
  220278. XFree (stateProp);
  220279. }
  220280. return minimised;
  220281. }
  220282. void setFullScreen (const bool shouldBeFullScreen)
  220283. {
  220284. Rectangle<int> r (lastNonFullscreenBounds); // (get a copy of this before de-minimising)
  220285. setMinimised (false);
  220286. if (fullScreen != shouldBeFullScreen)
  220287. {
  220288. if (shouldBeFullScreen)
  220289. r = Desktop::getInstance().getMainMonitorArea();
  220290. if (! r.isEmpty())
  220291. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  220292. getComponent()->repaint();
  220293. }
  220294. }
  220295. bool isFullScreen() const
  220296. {
  220297. return fullScreen;
  220298. }
  220299. bool isChildWindowOf (Window possibleParent) const
  220300. {
  220301. Window* windowList = 0;
  220302. uint32 windowListSize = 0;
  220303. Window parent, root;
  220304. ScopedXLock xlock;
  220305. if (XQueryTree (display, windowH, &root, &parent, &windowList, &windowListSize) != 0)
  220306. {
  220307. if (windowList != 0)
  220308. XFree (windowList);
  220309. return parent == possibleParent;
  220310. }
  220311. return false;
  220312. }
  220313. bool isFrontWindow() const
  220314. {
  220315. Window* windowList = 0;
  220316. uint32 windowListSize = 0;
  220317. bool result = false;
  220318. ScopedXLock xlock;
  220319. Window parent, root = RootWindow (display, DefaultScreen (display));
  220320. if (XQueryTree (display, root, &root, &parent, &windowList, &windowListSize) != 0)
  220321. {
  220322. for (int i = windowListSize; --i >= 0;)
  220323. {
  220324. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (windowList[i]);
  220325. if (peer != 0)
  220326. {
  220327. result = (peer == this);
  220328. break;
  220329. }
  220330. }
  220331. }
  220332. if (windowList != 0)
  220333. XFree (windowList);
  220334. return result;
  220335. }
  220336. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  220337. {
  220338. int x = position.getX();
  220339. int y = position.getY();
  220340. if (((unsigned int) x) >= (unsigned int) ww
  220341. || ((unsigned int) y) >= (unsigned int) wh)
  220342. return false;
  220343. bool inFront = false;
  220344. for (int i = 0; i < Desktop::getInstance().getNumComponents(); ++i)
  220345. {
  220346. Component* const c = Desktop::getInstance().getComponent (i);
  220347. if (inFront)
  220348. {
  220349. if (c->contains (x + wx - c->getScreenX(),
  220350. y + wy - c->getScreenY()))
  220351. {
  220352. return false;
  220353. }
  220354. }
  220355. else if (c == getComponent())
  220356. {
  220357. inFront = true;
  220358. }
  220359. }
  220360. if (trueIfInAChildWindow)
  220361. return true;
  220362. ::Window root, child;
  220363. unsigned int bw, depth;
  220364. int wx, wy, w, h;
  220365. ScopedXLock xlock;
  220366. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  220367. &wx, &wy, (unsigned int*) &w, (unsigned int*) &h,
  220368. &bw, &depth))
  220369. {
  220370. return false;
  220371. }
  220372. if (! XTranslateCoordinates (display, windowH, windowH, x, y, &wx, &wy, &child))
  220373. return false;
  220374. return child == None;
  220375. }
  220376. const BorderSize getFrameSize() const
  220377. {
  220378. return BorderSize();
  220379. }
  220380. bool setAlwaysOnTop (bool alwaysOnTop)
  220381. {
  220382. return false;
  220383. }
  220384. void toFront (bool makeActive)
  220385. {
  220386. if (makeActive)
  220387. {
  220388. setVisible (true);
  220389. grabFocus();
  220390. }
  220391. XEvent ev;
  220392. ev.xclient.type = ClientMessage;
  220393. ev.xclient.serial = 0;
  220394. ev.xclient.send_event = True;
  220395. ev.xclient.message_type = Atoms::ActiveWin;
  220396. ev.xclient.window = windowH;
  220397. ev.xclient.format = 32;
  220398. ev.xclient.data.l[0] = 2;
  220399. ev.xclient.data.l[1] = CurrentTime;
  220400. ev.xclient.data.l[2] = 0;
  220401. ev.xclient.data.l[3] = 0;
  220402. ev.xclient.data.l[4] = 0;
  220403. {
  220404. ScopedXLock xlock;
  220405. XSendEvent (display, RootWindow (display, DefaultScreen (display)),
  220406. False, SubstructureRedirectMask | SubstructureNotifyMask, &ev);
  220407. XWindowAttributes attr;
  220408. XGetWindowAttributes (display, windowH, &attr);
  220409. if (component->isAlwaysOnTop())
  220410. XRaiseWindow (display, windowH);
  220411. XSync (display, False);
  220412. }
  220413. handleBroughtToFront();
  220414. }
  220415. void toBehind (ComponentPeer* other)
  220416. {
  220417. LinuxComponentPeer* const otherPeer = dynamic_cast <LinuxComponentPeer*> (other);
  220418. jassert (otherPeer != 0); // wrong type of window?
  220419. if (otherPeer != 0)
  220420. {
  220421. setMinimised (false);
  220422. Window newStack[] = { otherPeer->windowH, windowH };
  220423. ScopedXLock xlock;
  220424. XRestackWindows (display, newStack, 2);
  220425. }
  220426. }
  220427. bool isFocused() const
  220428. {
  220429. int revert = 0;
  220430. Window focusedWindow = 0;
  220431. ScopedXLock xlock;
  220432. XGetInputFocus (display, &focusedWindow, &revert);
  220433. return focusedWindow == windowH;
  220434. }
  220435. void grabFocus()
  220436. {
  220437. XWindowAttributes atts;
  220438. ScopedXLock xlock;
  220439. if (windowH != 0
  220440. && XGetWindowAttributes (display, windowH, &atts)
  220441. && atts.map_state == IsViewable
  220442. && ! isFocused())
  220443. {
  220444. XSetInputFocus (display, windowH, RevertToParent, CurrentTime);
  220445. isActiveApplication = true;
  220446. }
  220447. }
  220448. void textInputRequired (const Point<int>&)
  220449. {
  220450. }
  220451. void repaint (const Rectangle<int>& area)
  220452. {
  220453. repainter->repaint (area.getIntersection (getComponent()->getLocalBounds()));
  220454. }
  220455. void performAnyPendingRepaintsNow()
  220456. {
  220457. repainter->performAnyPendingRepaintsNow();
  220458. }
  220459. static Pixmap juce_createColourPixmapFromImage (Display* display, const Image& image)
  220460. {
  220461. ScopedXLock xlock;
  220462. const int width = image.getWidth();
  220463. const int height = image.getHeight();
  220464. HeapBlock <uint32> colour (width * height);
  220465. int index = 0;
  220466. for (int y = 0; y < height; ++y)
  220467. for (int x = 0; x < width; ++x)
  220468. colour[index++] = image.getPixelAt (x, y).getARGB();
  220469. XImage* ximage = XCreateImage (display, CopyFromParent, 24, ZPixmap,
  220470. 0, reinterpret_cast<char*> (colour.getData()),
  220471. width, height, 32, 0);
  220472. Pixmap pixmap = XCreatePixmap (display, DefaultRootWindow (display),
  220473. width, height, 24);
  220474. GC gc = XCreateGC (display, pixmap, 0, 0);
  220475. XPutImage (display, pixmap, gc, ximage, 0, 0, 0, 0, width, height);
  220476. XFreeGC (display, gc);
  220477. return pixmap;
  220478. }
  220479. static Pixmap juce_createMaskPixmapFromImage (Display* display, const Image& image)
  220480. {
  220481. ScopedXLock xlock;
  220482. const int width = image.getWidth();
  220483. const int height = image.getHeight();
  220484. const int stride = (width + 7) >> 3;
  220485. HeapBlock <char> mask;
  220486. mask.calloc (stride * height);
  220487. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  220488. for (int y = 0; y < height; ++y)
  220489. {
  220490. for (int x = 0; x < width; ++x)
  220491. {
  220492. const char bit = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  220493. const int offset = y * stride + (x >> 3);
  220494. if (image.getPixelAt (x, y).getAlpha() >= 128)
  220495. mask[offset] |= bit;
  220496. }
  220497. }
  220498. return XCreatePixmapFromBitmapData (display, DefaultRootWindow (display),
  220499. mask.getData(), width, height, 1, 0, 1);
  220500. }
  220501. void setIcon (const Image& newIcon)
  220502. {
  220503. const int dataSize = newIcon.getWidth() * newIcon.getHeight() + 2;
  220504. HeapBlock <unsigned long> data (dataSize);
  220505. int index = 0;
  220506. data[index++] = newIcon.getWidth();
  220507. data[index++] = newIcon.getHeight();
  220508. for (int y = 0; y < newIcon.getHeight(); ++y)
  220509. for (int x = 0; x < newIcon.getWidth(); ++x)
  220510. data[index++] = newIcon.getPixelAt (x, y).getARGB();
  220511. ScopedXLock xlock;
  220512. XChangeProperty (display, windowH,
  220513. XInternAtom (display, "_NET_WM_ICON", False),
  220514. XA_CARDINAL, 32, PropModeReplace,
  220515. reinterpret_cast<unsigned char*> (data.getData()), dataSize);
  220516. deleteIconPixmaps();
  220517. XWMHints* wmHints = XGetWMHints (display, windowH);
  220518. if (wmHints == 0)
  220519. wmHints = XAllocWMHints();
  220520. wmHints->flags |= IconPixmapHint | IconMaskHint;
  220521. wmHints->icon_pixmap = juce_createColourPixmapFromImage (display, newIcon);
  220522. wmHints->icon_mask = juce_createMaskPixmapFromImage (display, newIcon);
  220523. XSetWMHints (display, windowH, wmHints);
  220524. XFree (wmHints);
  220525. XSync (display, False);
  220526. }
  220527. void deleteIconPixmaps()
  220528. {
  220529. ScopedXLock xlock;
  220530. XWMHints* wmHints = XGetWMHints (display, windowH);
  220531. if (wmHints != 0)
  220532. {
  220533. if ((wmHints->flags & IconPixmapHint) != 0)
  220534. {
  220535. wmHints->flags &= ~IconPixmapHint;
  220536. XFreePixmap (display, wmHints->icon_pixmap);
  220537. }
  220538. if ((wmHints->flags & IconMaskHint) != 0)
  220539. {
  220540. wmHints->flags &= ~IconMaskHint;
  220541. XFreePixmap (display, wmHints->icon_mask);
  220542. }
  220543. XSetWMHints (display, windowH, wmHints);
  220544. XFree (wmHints);
  220545. }
  220546. }
  220547. void handleWindowMessage (XEvent* event)
  220548. {
  220549. switch (event->xany.type)
  220550. {
  220551. case 2: // 'KeyPress'
  220552. {
  220553. ScopedXLock xlock;
  220554. XKeyEvent* const keyEvent = (XKeyEvent*) &event->xkey;
  220555. updateKeyStates (keyEvent->keycode, true);
  220556. char utf8 [64];
  220557. zeromem (utf8, sizeof (utf8));
  220558. KeySym sym;
  220559. {
  220560. const char* oldLocale = ::setlocale (LC_ALL, 0);
  220561. ::setlocale (LC_ALL, "");
  220562. XLookupString (keyEvent, utf8, sizeof (utf8), &sym, 0);
  220563. ::setlocale (LC_ALL, oldLocale);
  220564. }
  220565. const juce_wchar unicodeChar = String::fromUTF8 (utf8, sizeof (utf8) - 1) [0];
  220566. int keyCode = (int) unicodeChar;
  220567. if (keyCode < 0x20)
  220568. keyCode = XKeycodeToKeysym (display, keyEvent->keycode, currentModifiers.isShiftDown() ? 1 : 0);
  220569. const ModifierKeys oldMods (currentModifiers);
  220570. bool keyPressed = false;
  220571. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, true);
  220572. if ((sym & 0xff00) == 0xff00)
  220573. {
  220574. // Translate keypad
  220575. if (sym == XK_KP_Divide)
  220576. keyCode = XK_slash;
  220577. else if (sym == XK_KP_Multiply)
  220578. keyCode = XK_asterisk;
  220579. else if (sym == XK_KP_Subtract)
  220580. keyCode = XK_hyphen;
  220581. else if (sym == XK_KP_Add)
  220582. keyCode = XK_plus;
  220583. else if (sym == XK_KP_Enter)
  220584. keyCode = XK_Return;
  220585. else if (sym == XK_KP_Decimal)
  220586. keyCode = Keys::numLock ? XK_period : XK_Delete;
  220587. else if (sym == XK_KP_0)
  220588. keyCode = Keys::numLock ? XK_0 : XK_Insert;
  220589. else if (sym == XK_KP_1)
  220590. keyCode = Keys::numLock ? XK_1 : XK_End;
  220591. else if (sym == XK_KP_2)
  220592. keyCode = Keys::numLock ? XK_2 : XK_Down;
  220593. else if (sym == XK_KP_3)
  220594. keyCode = Keys::numLock ? XK_3 : XK_Page_Down;
  220595. else if (sym == XK_KP_4)
  220596. keyCode = Keys::numLock ? XK_4 : XK_Left;
  220597. else if (sym == XK_KP_5)
  220598. keyCode = XK_5;
  220599. else if (sym == XK_KP_6)
  220600. keyCode = Keys::numLock ? XK_6 : XK_Right;
  220601. else if (sym == XK_KP_7)
  220602. keyCode = Keys::numLock ? XK_7 : XK_Home;
  220603. else if (sym == XK_KP_8)
  220604. keyCode = Keys::numLock ? XK_8 : XK_Up;
  220605. else if (sym == XK_KP_9)
  220606. keyCode = Keys::numLock ? XK_9 : XK_Page_Up;
  220607. switch (sym)
  220608. {
  220609. case XK_Left:
  220610. case XK_Right:
  220611. case XK_Up:
  220612. case XK_Down:
  220613. case XK_Page_Up:
  220614. case XK_Page_Down:
  220615. case XK_End:
  220616. case XK_Home:
  220617. case XK_Delete:
  220618. case XK_Insert:
  220619. keyPressed = true;
  220620. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  220621. break;
  220622. case XK_Tab:
  220623. case XK_Return:
  220624. case XK_Escape:
  220625. case XK_BackSpace:
  220626. keyPressed = true;
  220627. keyCode &= 0xff;
  220628. break;
  220629. default:
  220630. {
  220631. if (sym >= XK_F1 && sym <= XK_F16)
  220632. {
  220633. keyPressed = true;
  220634. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  220635. }
  220636. break;
  220637. }
  220638. }
  220639. }
  220640. if (utf8[0] != 0 || ((sym & 0xff00) == 0 && sym >= 8))
  220641. keyPressed = true;
  220642. if (oldMods != currentModifiers)
  220643. handleModifierKeysChange();
  220644. if (keyDownChange)
  220645. handleKeyUpOrDown (true);
  220646. if (keyPressed)
  220647. handleKeyPress (keyCode, unicodeChar);
  220648. break;
  220649. }
  220650. case KeyRelease:
  220651. {
  220652. const XKeyEvent* const keyEvent = (const XKeyEvent*) &event->xkey;
  220653. updateKeyStates (keyEvent->keycode, false);
  220654. KeySym sym;
  220655. {
  220656. ScopedXLock xlock;
  220657. sym = XKeycodeToKeysym (display, keyEvent->keycode, 0);
  220658. }
  220659. const ModifierKeys oldMods (currentModifiers);
  220660. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, false);
  220661. if (oldMods != currentModifiers)
  220662. handleModifierKeysChange();
  220663. if (keyDownChange)
  220664. handleKeyUpOrDown (false);
  220665. break;
  220666. }
  220667. case ButtonPress:
  220668. {
  220669. const XButtonPressedEvent* const buttonPressEvent = (const XButtonPressedEvent*) &event->xbutton;
  220670. updateKeyModifiers (buttonPressEvent->state);
  220671. bool buttonMsg = false;
  220672. const int map = pointerMap [buttonPressEvent->button - Button1];
  220673. if (map == Keys::WheelUp || map == Keys::WheelDown)
  220674. {
  220675. handleMouseWheel (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y),
  220676. getEventTime (buttonPressEvent->time), 0, map == Keys::WheelDown ? -84.0f : 84.0f);
  220677. }
  220678. if (map == Keys::LeftButton)
  220679. {
  220680. currentModifiers = currentModifiers.withFlags (ModifierKeys::leftButtonModifier);
  220681. buttonMsg = true;
  220682. }
  220683. else if (map == Keys::RightButton)
  220684. {
  220685. currentModifiers = currentModifiers.withFlags (ModifierKeys::rightButtonModifier);
  220686. buttonMsg = true;
  220687. }
  220688. else if (map == Keys::MiddleButton)
  220689. {
  220690. currentModifiers = currentModifiers.withFlags (ModifierKeys::middleButtonModifier);
  220691. buttonMsg = true;
  220692. }
  220693. if (buttonMsg)
  220694. {
  220695. toFront (true);
  220696. handleMouseEvent (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y), currentModifiers,
  220697. getEventTime (buttonPressEvent->time));
  220698. }
  220699. clearLastMousePos();
  220700. break;
  220701. }
  220702. case ButtonRelease:
  220703. {
  220704. const XButtonReleasedEvent* const buttonRelEvent = (const XButtonReleasedEvent*) &event->xbutton;
  220705. updateKeyModifiers (buttonRelEvent->state);
  220706. const int map = pointerMap [buttonRelEvent->button - Button1];
  220707. if (map == Keys::LeftButton)
  220708. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::leftButtonModifier);
  220709. else if (map == Keys::RightButton)
  220710. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::rightButtonModifier);
  220711. else if (map == Keys::MiddleButton)
  220712. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::middleButtonModifier);
  220713. handleMouseEvent (0, Point<int> (buttonRelEvent->x, buttonRelEvent->y), currentModifiers,
  220714. getEventTime (buttonRelEvent->time));
  220715. clearLastMousePos();
  220716. break;
  220717. }
  220718. case MotionNotify:
  220719. {
  220720. const XPointerMovedEvent* const movedEvent = (const XPointerMovedEvent*) &event->xmotion;
  220721. updateKeyModifiers (movedEvent->state);
  220722. const Point<int> mousePos (Desktop::getMousePosition());
  220723. if (lastMousePos != mousePos)
  220724. {
  220725. lastMousePos = mousePos;
  220726. if (parentWindow != 0 && (styleFlags & windowHasTitleBar) == 0)
  220727. {
  220728. Window wRoot = 0, wParent = 0;
  220729. {
  220730. ScopedXLock xlock;
  220731. unsigned int numChildren;
  220732. Window* wChild = 0;
  220733. XQueryTree (display, windowH, &wRoot, &wParent, &wChild, &numChildren);
  220734. }
  220735. if (wParent != 0
  220736. && wParent != windowH
  220737. && wParent != wRoot)
  220738. {
  220739. parentWindow = wParent;
  220740. updateBounds();
  220741. }
  220742. else
  220743. {
  220744. parentWindow = 0;
  220745. }
  220746. }
  220747. handleMouseEvent (0, mousePos - getScreenPosition(), currentModifiers, getEventTime (movedEvent->time));
  220748. }
  220749. break;
  220750. }
  220751. case EnterNotify:
  220752. {
  220753. clearLastMousePos();
  220754. const XEnterWindowEvent* const enterEvent = (const XEnterWindowEvent*) &event->xcrossing;
  220755. if (! currentModifiers.isAnyMouseButtonDown())
  220756. {
  220757. updateKeyModifiers (enterEvent->state);
  220758. handleMouseEvent (0, Point<int> (enterEvent->x, enterEvent->y), currentModifiers, getEventTime (enterEvent->time));
  220759. }
  220760. break;
  220761. }
  220762. case LeaveNotify:
  220763. {
  220764. const XLeaveWindowEvent* const leaveEvent = (const XLeaveWindowEvent*) &event->xcrossing;
  220765. // Suppress the normal leave if we've got a pointer grab, or if
  220766. // it's a bogus one caused by clicking a mouse button when running
  220767. // in a Window manager
  220768. if (((! currentModifiers.isAnyMouseButtonDown()) && leaveEvent->mode == NotifyNormal)
  220769. || leaveEvent->mode == NotifyUngrab)
  220770. {
  220771. updateKeyModifiers (leaveEvent->state);
  220772. handleMouseEvent (0, Point<int> (leaveEvent->x, leaveEvent->y), currentModifiers, getEventTime (leaveEvent->time));
  220773. }
  220774. break;
  220775. }
  220776. case FocusIn:
  220777. {
  220778. isActiveApplication = true;
  220779. if (isFocused())
  220780. handleFocusGain();
  220781. break;
  220782. }
  220783. case FocusOut:
  220784. {
  220785. isActiveApplication = false;
  220786. if (! isFocused())
  220787. handleFocusLoss();
  220788. break;
  220789. }
  220790. case Expose:
  220791. {
  220792. // Batch together all pending expose events
  220793. XExposeEvent* exposeEvent = (XExposeEvent*) &event->xexpose;
  220794. XEvent nextEvent;
  220795. ScopedXLock xlock;
  220796. if (exposeEvent->window != windowH)
  220797. {
  220798. Window child;
  220799. XTranslateCoordinates (display, exposeEvent->window, windowH,
  220800. exposeEvent->x, exposeEvent->y, &exposeEvent->x, &exposeEvent->y,
  220801. &child);
  220802. }
  220803. repaint (Rectangle<int> (exposeEvent->x, exposeEvent->y,
  220804. exposeEvent->width, exposeEvent->height));
  220805. while (XEventsQueued (display, QueuedAfterFlush) > 0)
  220806. {
  220807. XPeekEvent (display, (XEvent*) &nextEvent);
  220808. if (nextEvent.type != Expose || nextEvent.xany.window != event->xany.window)
  220809. break;
  220810. XNextEvent (display, (XEvent*) &nextEvent);
  220811. XExposeEvent* nextExposeEvent = (XExposeEvent*) &nextEvent.xexpose;
  220812. repaint (Rectangle<int> (nextExposeEvent->x, nextExposeEvent->y,
  220813. nextExposeEvent->width, nextExposeEvent->height));
  220814. }
  220815. break;
  220816. }
  220817. case CirculateNotify:
  220818. case CreateNotify:
  220819. case DestroyNotify:
  220820. // Think we can ignore these
  220821. break;
  220822. case ConfigureNotify:
  220823. {
  220824. updateBounds();
  220825. updateBorderSize();
  220826. handleMovedOrResized();
  220827. // if the native title bar is dragged, need to tell any active menus, etc.
  220828. if ((styleFlags & windowHasTitleBar) != 0
  220829. && component->isCurrentlyBlockedByAnotherModalComponent())
  220830. {
  220831. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  220832. if (currentModalComp != 0)
  220833. currentModalComp->inputAttemptWhenModal();
  220834. }
  220835. XConfigureEvent* const confEvent = (XConfigureEvent*) &event->xconfigure;
  220836. if (confEvent->window == windowH
  220837. && confEvent->above != 0
  220838. && isFrontWindow())
  220839. {
  220840. handleBroughtToFront();
  220841. }
  220842. break;
  220843. }
  220844. case ReparentNotify:
  220845. {
  220846. parentWindow = 0;
  220847. Window wRoot = 0;
  220848. Window* wChild = 0;
  220849. unsigned int numChildren;
  220850. {
  220851. ScopedXLock xlock;
  220852. XQueryTree (display, windowH, &wRoot, &parentWindow, &wChild, &numChildren);
  220853. }
  220854. if (parentWindow == windowH || parentWindow == wRoot)
  220855. parentWindow = 0;
  220856. updateBounds();
  220857. updateBorderSize();
  220858. handleMovedOrResized();
  220859. break;
  220860. }
  220861. case GravityNotify:
  220862. {
  220863. updateBounds();
  220864. updateBorderSize();
  220865. handleMovedOrResized();
  220866. break;
  220867. }
  220868. case MapNotify:
  220869. mapped = true;
  220870. handleBroughtToFront();
  220871. break;
  220872. case UnmapNotify:
  220873. mapped = false;
  220874. break;
  220875. case MappingNotify:
  220876. {
  220877. XMappingEvent* mappingEvent = (XMappingEvent*) &event->xmapping;
  220878. if (mappingEvent->request != MappingPointer)
  220879. {
  220880. // Deal with modifier/keyboard mapping
  220881. ScopedXLock xlock;
  220882. XRefreshKeyboardMapping (mappingEvent);
  220883. updateModifierMappings();
  220884. }
  220885. break;
  220886. }
  220887. case ClientMessage:
  220888. {
  220889. const XClientMessageEvent* const clientMsg = (const XClientMessageEvent*) &event->xclient;
  220890. if (clientMsg->message_type == Atoms::Protocols && clientMsg->format == 32)
  220891. {
  220892. const Atom atom = (Atom) clientMsg->data.l[0];
  220893. if (atom == Atoms::ProtocolList [Atoms::PING])
  220894. {
  220895. Window root = RootWindow (display, DefaultScreen (display));
  220896. event->xclient.window = root;
  220897. XSendEvent (display, root, False, NoEventMask, event);
  220898. XFlush (display);
  220899. }
  220900. else if (atom == Atoms::ProtocolList [Atoms::TAKE_FOCUS])
  220901. {
  220902. XWindowAttributes atts;
  220903. ScopedXLock xlock;
  220904. if (clientMsg->window != 0
  220905. && XGetWindowAttributes (display, clientMsg->window, &atts))
  220906. {
  220907. if (atts.map_state == IsViewable)
  220908. XSetInputFocus (display, clientMsg->window, RevertToParent, clientMsg->data.l[1]);
  220909. }
  220910. }
  220911. else if (atom == Atoms::ProtocolList [Atoms::DELETE_WINDOW])
  220912. {
  220913. handleUserClosingWindow();
  220914. }
  220915. }
  220916. else if (clientMsg->message_type == Atoms::XdndEnter)
  220917. {
  220918. handleDragAndDropEnter (clientMsg);
  220919. }
  220920. else if (clientMsg->message_type == Atoms::XdndLeave)
  220921. {
  220922. resetDragAndDrop();
  220923. }
  220924. else if (clientMsg->message_type == Atoms::XdndPosition)
  220925. {
  220926. handleDragAndDropPosition (clientMsg);
  220927. }
  220928. else if (clientMsg->message_type == Atoms::XdndDrop)
  220929. {
  220930. handleDragAndDropDrop (clientMsg);
  220931. }
  220932. else if (clientMsg->message_type == Atoms::XdndStatus)
  220933. {
  220934. handleDragAndDropStatus (clientMsg);
  220935. }
  220936. else if (clientMsg->message_type == Atoms::XdndFinished)
  220937. {
  220938. resetDragAndDrop();
  220939. }
  220940. break;
  220941. }
  220942. case SelectionNotify:
  220943. handleDragAndDropSelection (event);
  220944. break;
  220945. case SelectionClear:
  220946. case SelectionRequest:
  220947. break;
  220948. default:
  220949. #if JUCE_USE_XSHM
  220950. {
  220951. ScopedXLock xlock;
  220952. if (event->xany.type == XShmGetEventBase (display))
  220953. repainter->notifyPaintCompleted();
  220954. }
  220955. #endif
  220956. break;
  220957. }
  220958. }
  220959. void showMouseCursor (Cursor cursor) throw()
  220960. {
  220961. ScopedXLock xlock;
  220962. XDefineCursor (display, windowH, cursor);
  220963. }
  220964. void setTaskBarIcon (const Image& image)
  220965. {
  220966. ScopedXLock xlock;
  220967. taskbarImage = image;
  220968. Screen* const screen = XDefaultScreenOfDisplay (display);
  220969. const int screenNumber = XScreenNumberOfScreen (screen);
  220970. String screenAtom ("_NET_SYSTEM_TRAY_S");
  220971. screenAtom << screenNumber;
  220972. Atom selectionAtom = XInternAtom (display, screenAtom.toUTF8(), false);
  220973. XGrabServer (display);
  220974. Window managerWin = XGetSelectionOwner (display, selectionAtom);
  220975. if (managerWin != None)
  220976. XSelectInput (display, managerWin, StructureNotifyMask);
  220977. XUngrabServer (display);
  220978. XFlush (display);
  220979. if (managerWin != None)
  220980. {
  220981. XEvent ev;
  220982. zerostruct (ev);
  220983. ev.xclient.type = ClientMessage;
  220984. ev.xclient.window = managerWin;
  220985. ev.xclient.message_type = XInternAtom (display, "_NET_SYSTEM_TRAY_OPCODE", False);
  220986. ev.xclient.format = 32;
  220987. ev.xclient.data.l[0] = CurrentTime;
  220988. ev.xclient.data.l[1] = 0 /*SYSTEM_TRAY_REQUEST_DOCK*/;
  220989. ev.xclient.data.l[2] = windowH;
  220990. ev.xclient.data.l[3] = 0;
  220991. ev.xclient.data.l[4] = 0;
  220992. XSendEvent (display, managerWin, False, NoEventMask, &ev);
  220993. XSync (display, False);
  220994. }
  220995. // For older KDE's ...
  220996. long atomData = 1;
  220997. Atom trayAtom = XInternAtom (display, "KWM_DOCKWINDOW", false);
  220998. XChangeProperty (display, windowH, trayAtom, trayAtom, 32, PropModeReplace, (unsigned char*) &atomData, 1);
  220999. // For more recent KDE's...
  221000. trayAtom = XInternAtom (display, "_KDE_NET_WM_SYSTEM_TRAY_WINDOW_FOR", false);
  221001. XChangeProperty (display, windowH, trayAtom, XA_WINDOW, 32, PropModeReplace, (unsigned char*) &windowH, 1);
  221002. // a minimum size must be specified for GNOME and Xfce, otherwise the icon is displayed with a width of 1
  221003. XSizeHints* hints = XAllocSizeHints();
  221004. hints->flags = PMinSize;
  221005. hints->min_width = 22;
  221006. hints->min_height = 22;
  221007. XSetWMNormalHints (display, windowH, hints);
  221008. XFree (hints);
  221009. }
  221010. const Image& getTaskbarIcon() const throw() { return taskbarImage; }
  221011. juce_UseDebuggingNewOperator
  221012. bool dontRepaint;
  221013. static ModifierKeys currentModifiers;
  221014. static bool isActiveApplication;
  221015. private:
  221016. class LinuxRepaintManager : public Timer
  221017. {
  221018. public:
  221019. LinuxRepaintManager (LinuxComponentPeer* const peer_)
  221020. : peer (peer_),
  221021. lastTimeImageUsed (0)
  221022. {
  221023. #if JUCE_USE_XSHM
  221024. shmCompletedDrawing = true;
  221025. useARGBImagesForRendering = XSHMHelpers::isShmAvailable();
  221026. if (useARGBImagesForRendering)
  221027. {
  221028. ScopedXLock xlock;
  221029. XShmSegmentInfo segmentinfo;
  221030. XImage* const testImage
  221031. = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  221032. 24, ZPixmap, 0, &segmentinfo, 64, 64);
  221033. useARGBImagesForRendering = (testImage->bits_per_pixel == 32);
  221034. XDestroyImage (testImage);
  221035. }
  221036. #endif
  221037. }
  221038. ~LinuxRepaintManager()
  221039. {
  221040. }
  221041. void timerCallback()
  221042. {
  221043. #if JUCE_USE_XSHM
  221044. if (! shmCompletedDrawing)
  221045. return;
  221046. #endif
  221047. if (! regionsNeedingRepaint.isEmpty())
  221048. {
  221049. stopTimer();
  221050. performAnyPendingRepaintsNow();
  221051. }
  221052. else if (Time::getApproximateMillisecondCounter() > lastTimeImageUsed + 3000)
  221053. {
  221054. stopTimer();
  221055. image = Image::null;
  221056. }
  221057. }
  221058. void repaint (const Rectangle<int>& area)
  221059. {
  221060. if (! isTimerRunning())
  221061. startTimer (repaintTimerPeriod);
  221062. regionsNeedingRepaint.add (area);
  221063. }
  221064. void performAnyPendingRepaintsNow()
  221065. {
  221066. #if JUCE_USE_XSHM
  221067. if (! shmCompletedDrawing)
  221068. {
  221069. startTimer (repaintTimerPeriod);
  221070. return;
  221071. }
  221072. #endif
  221073. peer->clearMaskedRegion();
  221074. RectangleList originalRepaintRegion (regionsNeedingRepaint);
  221075. regionsNeedingRepaint.clear();
  221076. const Rectangle<int> totalArea (originalRepaintRegion.getBounds());
  221077. if (! totalArea.isEmpty())
  221078. {
  221079. if (image.isNull() || image.getWidth() < totalArea.getWidth()
  221080. || image.getHeight() < totalArea.getHeight())
  221081. {
  221082. #if JUCE_USE_XSHM
  221083. image = Image (new XBitmapImage (useARGBImagesForRendering ? Image::ARGB
  221084. : Image::RGB,
  221085. #else
  221086. image = Image (new XBitmapImage (Image::RGB,
  221087. #endif
  221088. (totalArea.getWidth() + 31) & ~31,
  221089. (totalArea.getHeight() + 31) & ~31,
  221090. false, peer->depth, peer->visual));
  221091. }
  221092. startTimer (repaintTimerPeriod);
  221093. RectangleList adjustedList (originalRepaintRegion);
  221094. adjustedList.offsetAll (-totalArea.getX(), -totalArea.getY());
  221095. LowLevelGraphicsSoftwareRenderer context (image, -totalArea.getX(), -totalArea.getY(), adjustedList);
  221096. if (peer->depth == 32)
  221097. {
  221098. RectangleList::Iterator i (originalRepaintRegion);
  221099. while (i.next())
  221100. image.clear (*i.getRectangle() - totalArea.getPosition());
  221101. }
  221102. peer->handlePaint (context);
  221103. if (! peer->maskedRegion.isEmpty())
  221104. originalRepaintRegion.subtract (peer->maskedRegion);
  221105. for (RectangleList::Iterator i (originalRepaintRegion); i.next();)
  221106. {
  221107. #if JUCE_USE_XSHM
  221108. shmCompletedDrawing = false;
  221109. #endif
  221110. const Rectangle<int>& r = *i.getRectangle();
  221111. static_cast<XBitmapImage*> (image.getSharedImage())
  221112. ->blitToWindow (peer->windowH,
  221113. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  221114. r.getX() - totalArea.getX(), r.getY() - totalArea.getY());
  221115. }
  221116. }
  221117. lastTimeImageUsed = Time::getApproximateMillisecondCounter();
  221118. startTimer (repaintTimerPeriod);
  221119. }
  221120. #if JUCE_USE_XSHM
  221121. void notifyPaintCompleted() { shmCompletedDrawing = true; }
  221122. #endif
  221123. private:
  221124. enum { repaintTimerPeriod = 1000 / 100 };
  221125. LinuxComponentPeer* const peer;
  221126. Image image;
  221127. uint32 lastTimeImageUsed;
  221128. RectangleList regionsNeedingRepaint;
  221129. #if JUCE_USE_XSHM
  221130. bool useARGBImagesForRendering, shmCompletedDrawing;
  221131. #endif
  221132. LinuxRepaintManager (const LinuxRepaintManager&);
  221133. LinuxRepaintManager& operator= (const LinuxRepaintManager&);
  221134. };
  221135. ScopedPointer <LinuxRepaintManager> repainter;
  221136. friend class LinuxRepaintManager;
  221137. Window windowH, parentWindow;
  221138. int wx, wy, ww, wh;
  221139. Image taskbarImage;
  221140. bool fullScreen, mapped;
  221141. Visual* visual;
  221142. int depth;
  221143. BorderSize windowBorder;
  221144. struct MotifWmHints
  221145. {
  221146. unsigned long flags;
  221147. unsigned long functions;
  221148. unsigned long decorations;
  221149. long input_mode;
  221150. unsigned long status;
  221151. };
  221152. static void updateKeyStates (const int keycode, const bool press) throw()
  221153. {
  221154. const int keybyte = keycode >> 3;
  221155. const int keybit = (1 << (keycode & 7));
  221156. if (press)
  221157. Keys::keyStates [keybyte] |= keybit;
  221158. else
  221159. Keys::keyStates [keybyte] &= ~keybit;
  221160. }
  221161. static void updateKeyModifiers (const int status) throw()
  221162. {
  221163. int keyMods = 0;
  221164. if (status & ShiftMask) keyMods |= ModifierKeys::shiftModifier;
  221165. if (status & ControlMask) keyMods |= ModifierKeys::ctrlModifier;
  221166. if (status & Keys::AltMask) keyMods |= ModifierKeys::altModifier;
  221167. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  221168. Keys::numLock = ((status & Keys::NumLockMask) != 0);
  221169. Keys::capsLock = ((status & LockMask) != 0);
  221170. }
  221171. static bool updateKeyModifiersFromSym (KeySym sym, const bool press) throw()
  221172. {
  221173. int modifier = 0;
  221174. bool isModifier = true;
  221175. switch (sym)
  221176. {
  221177. case XK_Shift_L:
  221178. case XK_Shift_R:
  221179. modifier = ModifierKeys::shiftModifier;
  221180. break;
  221181. case XK_Control_L:
  221182. case XK_Control_R:
  221183. modifier = ModifierKeys::ctrlModifier;
  221184. break;
  221185. case XK_Alt_L:
  221186. case XK_Alt_R:
  221187. modifier = ModifierKeys::altModifier;
  221188. break;
  221189. case XK_Num_Lock:
  221190. if (press)
  221191. Keys::numLock = ! Keys::numLock;
  221192. break;
  221193. case XK_Caps_Lock:
  221194. if (press)
  221195. Keys::capsLock = ! Keys::capsLock;
  221196. break;
  221197. case XK_Scroll_Lock:
  221198. break;
  221199. default:
  221200. isModifier = false;
  221201. break;
  221202. }
  221203. if (modifier != 0)
  221204. {
  221205. if (press)
  221206. currentModifiers = currentModifiers.withFlags (modifier);
  221207. else
  221208. currentModifiers = currentModifiers.withoutFlags (modifier);
  221209. }
  221210. return isModifier;
  221211. }
  221212. // Alt and Num lock are not defined by standard X
  221213. // modifier constants: check what they're mapped to
  221214. static void updateModifierMappings() throw()
  221215. {
  221216. ScopedXLock xlock;
  221217. const int altLeftCode = XKeysymToKeycode (display, XK_Alt_L);
  221218. const int numLockCode = XKeysymToKeycode (display, XK_Num_Lock);
  221219. Keys::AltMask = 0;
  221220. Keys::NumLockMask = 0;
  221221. XModifierKeymap* mapping = XGetModifierMapping (display);
  221222. if (mapping)
  221223. {
  221224. for (int i = 0; i < 8; i++)
  221225. {
  221226. if (mapping->modifiermap [i << 1] == altLeftCode)
  221227. Keys::AltMask = 1 << i;
  221228. else if (mapping->modifiermap [i << 1] == numLockCode)
  221229. Keys::NumLockMask = 1 << i;
  221230. }
  221231. XFreeModifiermap (mapping);
  221232. }
  221233. }
  221234. void removeWindowDecorations (Window wndH)
  221235. {
  221236. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  221237. if (hints != None)
  221238. {
  221239. MotifWmHints motifHints;
  221240. zerostruct (motifHints);
  221241. motifHints.flags = 2; /* MWM_HINTS_DECORATIONS */
  221242. motifHints.decorations = 0;
  221243. ScopedXLock xlock;
  221244. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  221245. (unsigned char*) &motifHints, 4);
  221246. }
  221247. hints = XInternAtom (display, "_WIN_HINTS", True);
  221248. if (hints != None)
  221249. {
  221250. long gnomeHints = 0;
  221251. ScopedXLock xlock;
  221252. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  221253. (unsigned char*) &gnomeHints, 1);
  221254. }
  221255. hints = XInternAtom (display, "KWM_WIN_DECORATION", True);
  221256. if (hints != None)
  221257. {
  221258. long kwmHints = 2; /*KDE_tinyDecoration*/
  221259. ScopedXLock xlock;
  221260. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  221261. (unsigned char*) &kwmHints, 1);
  221262. }
  221263. }
  221264. void addWindowButtons (Window wndH)
  221265. {
  221266. ScopedXLock xlock;
  221267. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  221268. if (hints != None)
  221269. {
  221270. MotifWmHints motifHints;
  221271. zerostruct (motifHints);
  221272. motifHints.flags = 1 | 2; /* MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS */
  221273. motifHints.decorations = 2 /* MWM_DECOR_BORDER */ | 8 /* MWM_DECOR_TITLE */ | 16; /* MWM_DECOR_MENU */
  221274. motifHints.functions = 4 /* MWM_FUNC_MOVE */;
  221275. if ((styleFlags & windowHasCloseButton) != 0)
  221276. motifHints.functions |= 32; /* MWM_FUNC_CLOSE */
  221277. if ((styleFlags & windowHasMinimiseButton) != 0)
  221278. {
  221279. motifHints.functions |= 8; /* MWM_FUNC_MINIMIZE */
  221280. motifHints.decorations |= 0x20; /* MWM_DECOR_MINIMIZE */
  221281. }
  221282. if ((styleFlags & windowHasMaximiseButton) != 0)
  221283. {
  221284. motifHints.functions |= 0x10; /* MWM_FUNC_MAXIMIZE */
  221285. motifHints.decorations |= 0x40; /* MWM_DECOR_MAXIMIZE */
  221286. }
  221287. if ((styleFlags & windowIsResizable) != 0)
  221288. {
  221289. motifHints.functions |= 2; /* MWM_FUNC_RESIZE */
  221290. motifHints.decorations |= 0x4; /* MWM_DECOR_RESIZEH */
  221291. }
  221292. XChangeProperty (display, wndH, hints, hints, 32, 0, (unsigned char*) &motifHints, 5);
  221293. }
  221294. hints = XInternAtom (display, "_NET_WM_ALLOWED_ACTIONS", True);
  221295. if (hints != None)
  221296. {
  221297. int netHints [6];
  221298. int num = 0;
  221299. if ((styleFlags & windowIsResizable) != 0)
  221300. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_RESIZE", True);
  221301. if ((styleFlags & windowHasMaximiseButton) != 0)
  221302. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_FULLSCREEN", True);
  221303. if ((styleFlags & windowHasMinimiseButton) != 0)
  221304. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_MINIMIZE", True);
  221305. if ((styleFlags & windowHasCloseButton) != 0)
  221306. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_CLOSE", True);
  221307. XChangeProperty (display, wndH, hints, XA_ATOM, 32, PropModeReplace, (unsigned char*) &netHints, num);
  221308. }
  221309. }
  221310. void setWindowType()
  221311. {
  221312. int netHints [2];
  221313. int numHints = 0;
  221314. if ((styleFlags & windowIsTemporary) != 0
  221315. || ((styleFlags & windowHasDropShadow) == 0 && Desktop::canUseSemiTransparentWindows()))
  221316. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_COMBO", True);
  221317. else
  221318. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_NORMAL", True);
  221319. netHints[numHints++] = XInternAtom (display, "_KDE_NET_WM_WINDOW_TYPE_OVERRIDE", True);
  221320. XChangeProperty (display, windowH, Atoms::WindowType, XA_ATOM, 32, PropModeReplace,
  221321. (unsigned char*) &netHints, numHints);
  221322. numHints = 0;
  221323. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  221324. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_SKIP_TASKBAR", True);
  221325. if (component->isAlwaysOnTop())
  221326. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_ABOVE", True);
  221327. if (numHints > 0)
  221328. XChangeProperty (display, windowH, Atoms::WindowState, XA_ATOM, 32, PropModeReplace,
  221329. (unsigned char*) &netHints, numHints);
  221330. }
  221331. void createWindow()
  221332. {
  221333. ScopedXLock xlock;
  221334. Atoms::initialiseAtoms();
  221335. resetDragAndDrop();
  221336. // Get defaults for various properties
  221337. const int screen = DefaultScreen (display);
  221338. Window root = RootWindow (display, screen);
  221339. // Try to obtain a 32-bit visual or fallback to 24 or 16
  221340. visual = Visuals::findVisualFormat ((styleFlags & windowIsSemiTransparent) ? 32 : 24, depth);
  221341. if (visual == 0)
  221342. {
  221343. Logger::outputDebugString ("ERROR: System doesn't support 32, 24 or 16 bit RGB display.\n");
  221344. Process::terminate();
  221345. }
  221346. // Create and install a colormap suitable fr our visual
  221347. Colormap colormap = XCreateColormap (display, root, visual, AllocNone);
  221348. XInstallColormap (display, colormap);
  221349. // Set up the window attributes
  221350. XSetWindowAttributes swa;
  221351. swa.border_pixel = 0;
  221352. swa.background_pixmap = None;
  221353. swa.colormap = colormap;
  221354. swa.event_mask = getAllEventsMask();
  221355. windowH = XCreateWindow (display, root,
  221356. 0, 0, 1, 1,
  221357. 0, depth, InputOutput, visual,
  221358. CWBorderPixel | CWColormap | CWBackPixmap | CWEventMask,
  221359. &swa);
  221360. XGrabButton (display, AnyButton, AnyModifier, windowH, False,
  221361. ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask,
  221362. GrabModeAsync, GrabModeAsync, None, None);
  221363. // Set the window context to identify the window handle object
  221364. if (XSaveContext (display, (XID) windowH, windowHandleXContext, (XPointer) this))
  221365. {
  221366. // Failed
  221367. jassertfalse;
  221368. Logger::outputDebugString ("Failed to create context information for window.\n");
  221369. XDestroyWindow (display, windowH);
  221370. windowH = 0;
  221371. return;
  221372. }
  221373. // Set window manager hints
  221374. XWMHints* wmHints = XAllocWMHints();
  221375. wmHints->flags = InputHint | StateHint;
  221376. wmHints->input = True; // Locally active input model
  221377. wmHints->initial_state = NormalState;
  221378. XSetWMHints (display, windowH, wmHints);
  221379. XFree (wmHints);
  221380. // Set the window type
  221381. setWindowType();
  221382. // Define decoration
  221383. if ((styleFlags & windowHasTitleBar) == 0)
  221384. removeWindowDecorations (windowH);
  221385. else
  221386. addWindowButtons (windowH);
  221387. // Set window name
  221388. setWindowTitle (windowH, getComponent()->getName());
  221389. // Associate the PID, allowing to be shut down when something goes wrong
  221390. unsigned long pid = getpid();
  221391. XChangeProperty (display, windowH, Atoms::Pid, XA_CARDINAL, 32, PropModeReplace,
  221392. (unsigned char*) &pid, 1);
  221393. // Set window manager protocols
  221394. XChangeProperty (display, windowH, Atoms::Protocols, XA_ATOM, 32, PropModeReplace,
  221395. (unsigned char*) Atoms::ProtocolList, 2);
  221396. // Set drag and drop flags
  221397. XChangeProperty (display, windowH, Atoms::XdndTypeList, XA_ATOM, 32, PropModeReplace,
  221398. (const unsigned char*) Atoms::allowedMimeTypes, numElementsInArray (Atoms::allowedMimeTypes));
  221399. XChangeProperty (display, windowH, Atoms::XdndActionList, XA_ATOM, 32, PropModeReplace,
  221400. (const unsigned char*) Atoms::allowedActions, numElementsInArray (Atoms::allowedActions));
  221401. XChangeProperty (display, windowH, Atoms::XdndActionDescription, XA_STRING, 8, PropModeReplace,
  221402. (const unsigned char*) "", 0);
  221403. unsigned long dndVersion = Atoms::DndVersion;
  221404. XChangeProperty (display, windowH, Atoms::XdndAware, XA_ATOM, 32, PropModeReplace,
  221405. (const unsigned char*) &dndVersion, 1);
  221406. // Initialise the pointer and keyboard mapping
  221407. // This is not the same as the logical pointer mapping the X server uses:
  221408. // we don't mess with this.
  221409. static bool mappingInitialised = false;
  221410. if (! mappingInitialised)
  221411. {
  221412. mappingInitialised = true;
  221413. const int numButtons = XGetPointerMapping (display, 0, 0);
  221414. if (numButtons == 2)
  221415. {
  221416. pointerMap[0] = Keys::LeftButton;
  221417. pointerMap[1] = Keys::RightButton;
  221418. pointerMap[2] = pointerMap[3] = pointerMap[4] = Keys::NoButton;
  221419. }
  221420. else if (numButtons >= 3)
  221421. {
  221422. pointerMap[0] = Keys::LeftButton;
  221423. pointerMap[1] = Keys::MiddleButton;
  221424. pointerMap[2] = Keys::RightButton;
  221425. if (numButtons >= 5)
  221426. {
  221427. pointerMap[3] = Keys::WheelUp;
  221428. pointerMap[4] = Keys::WheelDown;
  221429. }
  221430. }
  221431. updateModifierMappings();
  221432. }
  221433. }
  221434. void destroyWindow()
  221435. {
  221436. ScopedXLock xlock;
  221437. XPointer handlePointer;
  221438. if (! XFindContext (display, (XID) windowH, windowHandleXContext, &handlePointer))
  221439. XDeleteContext (display, (XID) windowH, windowHandleXContext);
  221440. XDestroyWindow (display, windowH);
  221441. // Wait for it to complete and then remove any events for this
  221442. // window from the event queue.
  221443. XSync (display, false);
  221444. XEvent event;
  221445. while (XCheckWindowEvent (display, windowH, getAllEventsMask(), &event) == True)
  221446. {}
  221447. }
  221448. static int getAllEventsMask() throw()
  221449. {
  221450. return NoEventMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask
  221451. | EnterWindowMask | LeaveWindowMask | PointerMotionMask | KeymapStateMask
  221452. | ExposureMask | StructureNotifyMask | FocusChangeMask;
  221453. }
  221454. static int64 getEventTime (::Time t)
  221455. {
  221456. static int64 eventTimeOffset = 0x12345678;
  221457. const int64 thisMessageTime = t;
  221458. if (eventTimeOffset == 0x12345678)
  221459. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  221460. return eventTimeOffset + thisMessageTime;
  221461. }
  221462. static void setWindowTitle (Window xwin, const String& title)
  221463. {
  221464. XTextProperty nameProperty;
  221465. char* strings[] = { const_cast <char*> (title.toUTF8()) };
  221466. ScopedXLock xlock;
  221467. if (XStringListToTextProperty (strings, 1, &nameProperty))
  221468. {
  221469. XSetWMName (display, xwin, &nameProperty);
  221470. XSetWMIconName (display, xwin, &nameProperty);
  221471. XFree (nameProperty.value);
  221472. }
  221473. }
  221474. void updateBorderSize()
  221475. {
  221476. if ((styleFlags & windowHasTitleBar) == 0)
  221477. {
  221478. windowBorder = BorderSize (0);
  221479. }
  221480. else if (windowBorder.getTopAndBottom() == 0 && windowBorder.getLeftAndRight() == 0)
  221481. {
  221482. ScopedXLock xlock;
  221483. Atom hints = XInternAtom (display, "_NET_FRAME_EXTENTS", True);
  221484. if (hints != None)
  221485. {
  221486. unsigned char* data = 0;
  221487. unsigned long nitems, bytesLeft;
  221488. Atom actualType;
  221489. int actualFormat;
  221490. if (XGetWindowProperty (display, windowH, hints, 0, 4, False,
  221491. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  221492. &data) == Success)
  221493. {
  221494. const unsigned long* const sizes = (const unsigned long*) data;
  221495. if (actualFormat == 32)
  221496. windowBorder = BorderSize ((int) sizes[2], (int) sizes[0],
  221497. (int) sizes[3], (int) sizes[1]);
  221498. XFree (data);
  221499. }
  221500. }
  221501. }
  221502. }
  221503. void updateBounds()
  221504. {
  221505. jassert (windowH != 0);
  221506. if (windowH != 0)
  221507. {
  221508. Window root, child;
  221509. unsigned int bw, depth;
  221510. ScopedXLock xlock;
  221511. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  221512. &wx, &wy, (unsigned int*) &ww, (unsigned int*) &wh,
  221513. &bw, &depth))
  221514. {
  221515. wx = wy = ww = wh = 0;
  221516. }
  221517. else if (! XTranslateCoordinates (display, windowH, root, 0, 0, &wx, &wy, &child))
  221518. {
  221519. wx = wy = 0;
  221520. }
  221521. }
  221522. }
  221523. void resetDragAndDrop()
  221524. {
  221525. dragAndDropFiles.clear();
  221526. lastDropPos = Point<int> (-1, -1);
  221527. dragAndDropCurrentMimeType = 0;
  221528. dragAndDropSourceWindow = 0;
  221529. srcMimeTypeAtomList.clear();
  221530. }
  221531. void sendDragAndDropMessage (XClientMessageEvent& msg)
  221532. {
  221533. msg.type = ClientMessage;
  221534. msg.display = display;
  221535. msg.window = dragAndDropSourceWindow;
  221536. msg.format = 32;
  221537. msg.data.l[0] = windowH;
  221538. ScopedXLock xlock;
  221539. XSendEvent (display, dragAndDropSourceWindow, False, 0, (XEvent*) &msg);
  221540. }
  221541. void sendDragAndDropStatus (const bool acceptDrop, Atom dropAction)
  221542. {
  221543. XClientMessageEvent msg;
  221544. zerostruct (msg);
  221545. msg.message_type = Atoms::XdndStatus;
  221546. msg.data.l[1] = (acceptDrop ? 1 : 0) | 2; // 2 indicates that we want to receive position messages
  221547. msg.data.l[4] = dropAction;
  221548. sendDragAndDropMessage (msg);
  221549. }
  221550. void sendDragAndDropLeave()
  221551. {
  221552. XClientMessageEvent msg;
  221553. zerostruct (msg);
  221554. msg.message_type = Atoms::XdndLeave;
  221555. sendDragAndDropMessage (msg);
  221556. }
  221557. void sendDragAndDropFinish()
  221558. {
  221559. XClientMessageEvent msg;
  221560. zerostruct (msg);
  221561. msg.message_type = Atoms::XdndFinished;
  221562. sendDragAndDropMessage (msg);
  221563. }
  221564. void handleDragAndDropStatus (const XClientMessageEvent* const clientMsg)
  221565. {
  221566. if ((clientMsg->data.l[1] & 1) == 0)
  221567. {
  221568. sendDragAndDropLeave();
  221569. if (dragAndDropFiles.size() > 0)
  221570. handleFileDragExit (dragAndDropFiles);
  221571. dragAndDropFiles.clear();
  221572. }
  221573. }
  221574. void handleDragAndDropPosition (const XClientMessageEvent* const clientMsg)
  221575. {
  221576. if (dragAndDropSourceWindow == 0)
  221577. return;
  221578. dragAndDropSourceWindow = clientMsg->data.l[0];
  221579. Point<int> dropPos ((int) clientMsg->data.l[2] >> 16,
  221580. (int) clientMsg->data.l[2] & 0xffff);
  221581. dropPos -= getScreenPosition();
  221582. if (lastDropPos != dropPos)
  221583. {
  221584. lastDropPos = dropPos;
  221585. dragAndDropTimestamp = clientMsg->data.l[3];
  221586. Atom targetAction = Atoms::XdndActionCopy;
  221587. for (int i = numElementsInArray (Atoms::allowedActions); --i >= 0;)
  221588. {
  221589. if ((Atom) clientMsg->data.l[4] == Atoms::allowedActions[i])
  221590. {
  221591. targetAction = Atoms::allowedActions[i];
  221592. break;
  221593. }
  221594. }
  221595. sendDragAndDropStatus (true, targetAction);
  221596. if (dragAndDropFiles.size() == 0)
  221597. updateDraggedFileList (clientMsg);
  221598. if (dragAndDropFiles.size() > 0)
  221599. handleFileDragMove (dragAndDropFiles, dropPos);
  221600. }
  221601. }
  221602. void handleDragAndDropDrop (const XClientMessageEvent* const clientMsg)
  221603. {
  221604. if (dragAndDropFiles.size() == 0)
  221605. updateDraggedFileList (clientMsg);
  221606. const StringArray files (dragAndDropFiles);
  221607. const Point<int> lastPos (lastDropPos);
  221608. sendDragAndDropFinish();
  221609. resetDragAndDrop();
  221610. if (files.size() > 0)
  221611. handleFileDragDrop (files, lastPos);
  221612. }
  221613. void handleDragAndDropEnter (const XClientMessageEvent* const clientMsg)
  221614. {
  221615. dragAndDropFiles.clear();
  221616. srcMimeTypeAtomList.clear();
  221617. dragAndDropCurrentMimeType = 0;
  221618. const unsigned long dndCurrentVersion = static_cast <unsigned long> (clientMsg->data.l[1] & 0xff000000) >> 24;
  221619. if (dndCurrentVersion < 3 || dndCurrentVersion > Atoms::DndVersion)
  221620. {
  221621. dragAndDropSourceWindow = 0;
  221622. return;
  221623. }
  221624. dragAndDropSourceWindow = clientMsg->data.l[0];
  221625. if ((clientMsg->data.l[1] & 1) != 0)
  221626. {
  221627. Atom actual;
  221628. int format;
  221629. unsigned long count = 0, remaining = 0;
  221630. unsigned char* data = 0;
  221631. ScopedXLock xlock;
  221632. XGetWindowProperty (display, dragAndDropSourceWindow, Atoms::XdndTypeList,
  221633. 0, 0x8000000L, False, XA_ATOM, &actual, &format,
  221634. &count, &remaining, &data);
  221635. if (data != 0)
  221636. {
  221637. if (actual == XA_ATOM && format == 32 && count != 0)
  221638. {
  221639. const unsigned long* const types = (const unsigned long*) data;
  221640. for (unsigned int i = 0; i < count; ++i)
  221641. if (types[i] != None)
  221642. srcMimeTypeAtomList.add (types[i]);
  221643. }
  221644. XFree (data);
  221645. }
  221646. }
  221647. if (srcMimeTypeAtomList.size() == 0)
  221648. {
  221649. for (int i = 2; i < 5; ++i)
  221650. if (clientMsg->data.l[i] != None)
  221651. srcMimeTypeAtomList.add (clientMsg->data.l[i]);
  221652. if (srcMimeTypeAtomList.size() == 0)
  221653. {
  221654. dragAndDropSourceWindow = 0;
  221655. return;
  221656. }
  221657. }
  221658. for (int i = 0; i < srcMimeTypeAtomList.size() && dragAndDropCurrentMimeType == 0; ++i)
  221659. for (int j = 0; j < numElementsInArray (Atoms::allowedMimeTypes); ++j)
  221660. if (srcMimeTypeAtomList[i] == Atoms::allowedMimeTypes[j])
  221661. dragAndDropCurrentMimeType = Atoms::allowedMimeTypes[j];
  221662. handleDragAndDropPosition (clientMsg);
  221663. }
  221664. void handleDragAndDropSelection (const XEvent* const evt)
  221665. {
  221666. dragAndDropFiles.clear();
  221667. if (evt->xselection.property != 0)
  221668. {
  221669. StringArray lines;
  221670. {
  221671. MemoryBlock dropData;
  221672. for (;;)
  221673. {
  221674. Atom actual;
  221675. uint8* data = 0;
  221676. unsigned long count = 0, remaining = 0;
  221677. int format = 0;
  221678. ScopedXLock xlock;
  221679. if (XGetWindowProperty (display, evt->xany.window, evt->xselection.property,
  221680. dropData.getSize() / 4, 65536, 1, AnyPropertyType, &actual,
  221681. &format, &count, &remaining, &data) == Success)
  221682. {
  221683. dropData.append (data, count * format / 8);
  221684. XFree (data);
  221685. if (remaining == 0)
  221686. break;
  221687. }
  221688. else
  221689. {
  221690. XFree (data);
  221691. break;
  221692. }
  221693. }
  221694. lines.addLines (dropData.toString());
  221695. }
  221696. for (int i = 0; i < lines.size(); ++i)
  221697. dragAndDropFiles.add (URL::removeEscapeChars (lines[i].fromFirstOccurrenceOf ("file://", false, true)));
  221698. dragAndDropFiles.trim();
  221699. dragAndDropFiles.removeEmptyStrings();
  221700. }
  221701. }
  221702. void updateDraggedFileList (const XClientMessageEvent* const clientMsg)
  221703. {
  221704. dragAndDropFiles.clear();
  221705. if (dragAndDropSourceWindow != None
  221706. && dragAndDropCurrentMimeType != 0)
  221707. {
  221708. dragAndDropTimestamp = clientMsg->data.l[2];
  221709. ScopedXLock xlock;
  221710. XConvertSelection (display,
  221711. Atoms::XdndSelection,
  221712. dragAndDropCurrentMimeType,
  221713. XInternAtom (display, "JXSelectionWindowProperty", 0),
  221714. windowH,
  221715. dragAndDropTimestamp);
  221716. }
  221717. }
  221718. StringArray dragAndDropFiles;
  221719. int dragAndDropTimestamp;
  221720. Point<int> lastDropPos;
  221721. Atom dragAndDropCurrentMimeType;
  221722. Window dragAndDropSourceWindow;
  221723. Array <Atom> srcMimeTypeAtomList;
  221724. static int pointerMap[5];
  221725. static Point<int> lastMousePos;
  221726. static void clearLastMousePos() throw()
  221727. {
  221728. lastMousePos = Point<int> (0x100000, 0x100000);
  221729. }
  221730. };
  221731. ModifierKeys LinuxComponentPeer::currentModifiers;
  221732. bool LinuxComponentPeer::isActiveApplication = false;
  221733. int LinuxComponentPeer::pointerMap[5];
  221734. Point<int> LinuxComponentPeer::lastMousePos;
  221735. bool Process::isForegroundProcess()
  221736. {
  221737. return LinuxComponentPeer::isActiveApplication;
  221738. }
  221739. void ModifierKeys::updateCurrentModifiers() throw()
  221740. {
  221741. currentModifiers = LinuxComponentPeer::currentModifiers;
  221742. }
  221743. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  221744. {
  221745. Window root, child;
  221746. int x, y, winx, winy;
  221747. unsigned int mask;
  221748. int mouseMods = 0;
  221749. ScopedXLock xlock;
  221750. if (XQueryPointer (display, RootWindow (display, DefaultScreen (display)),
  221751. &root, &child, &x, &y, &winx, &winy, &mask) != False)
  221752. {
  221753. if ((mask & Button1Mask) != 0) mouseMods |= ModifierKeys::leftButtonModifier;
  221754. if ((mask & Button2Mask) != 0) mouseMods |= ModifierKeys::middleButtonModifier;
  221755. if ((mask & Button3Mask) != 0) mouseMods |= ModifierKeys::rightButtonModifier;
  221756. }
  221757. LinuxComponentPeer::currentModifiers = LinuxComponentPeer::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  221758. return LinuxComponentPeer::currentModifiers;
  221759. }
  221760. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  221761. {
  221762. if (enableOrDisable)
  221763. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  221764. }
  221765. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  221766. {
  221767. return new LinuxComponentPeer (this, styleFlags);
  221768. }
  221769. // (this callback is hooked up in the messaging code)
  221770. void juce_windowMessageReceive (XEvent* event)
  221771. {
  221772. if (event->xany.window != None)
  221773. {
  221774. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (event->xany.window);
  221775. if (ComponentPeer::isValidPeer (peer))
  221776. peer->handleWindowMessage (event);
  221777. }
  221778. else
  221779. {
  221780. switch (event->xany.type)
  221781. {
  221782. case KeymapNotify:
  221783. {
  221784. const XKeymapEvent* const keymapEvent = (const XKeymapEvent*) &event->xkeymap;
  221785. memcpy (Keys::keyStates, keymapEvent->key_vector, 32);
  221786. break;
  221787. }
  221788. default:
  221789. break;
  221790. }
  221791. }
  221792. }
  221793. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool /*clipToWorkArea*/)
  221794. {
  221795. if (display == 0)
  221796. return;
  221797. #if JUCE_USE_XINERAMA
  221798. int major_opcode, first_event, first_error;
  221799. ScopedXLock xlock;
  221800. if (XQueryExtension (display, "XINERAMA", &major_opcode, &first_event, &first_error))
  221801. {
  221802. typedef Bool (*tXineramaIsActive) (Display*);
  221803. typedef XineramaScreenInfo* (*tXineramaQueryScreens) (Display*, int*);
  221804. static tXineramaIsActive xXineramaIsActive = 0;
  221805. static tXineramaQueryScreens xXineramaQueryScreens = 0;
  221806. if (xXineramaIsActive == 0 || xXineramaQueryScreens == 0)
  221807. {
  221808. void* h = dlopen ("libXinerama.so", RTLD_GLOBAL | RTLD_NOW);
  221809. if (h == 0)
  221810. h = dlopen ("libXinerama.so.1", RTLD_GLOBAL | RTLD_NOW);
  221811. if (h != 0)
  221812. {
  221813. xXineramaIsActive = (tXineramaIsActive) dlsym (h, "XineramaIsActive");
  221814. xXineramaQueryScreens = (tXineramaQueryScreens) dlsym (h, "XineramaQueryScreens");
  221815. }
  221816. }
  221817. if (xXineramaIsActive != 0
  221818. && xXineramaQueryScreens != 0
  221819. && xXineramaIsActive (display))
  221820. {
  221821. int numMonitors = 0;
  221822. XineramaScreenInfo* const screens = xXineramaQueryScreens (display, &numMonitors);
  221823. if (screens != 0)
  221824. {
  221825. for (int i = numMonitors; --i >= 0;)
  221826. {
  221827. int index = screens[i].screen_number;
  221828. if (index >= 0)
  221829. {
  221830. while (monitorCoords.size() < index)
  221831. monitorCoords.add (Rectangle<int>());
  221832. monitorCoords.set (index, Rectangle<int> (screens[i].x_org,
  221833. screens[i].y_org,
  221834. screens[i].width,
  221835. screens[i].height));
  221836. }
  221837. }
  221838. XFree (screens);
  221839. }
  221840. }
  221841. }
  221842. if (monitorCoords.size() == 0)
  221843. #endif
  221844. {
  221845. Atom hints = XInternAtom (display, "_NET_WORKAREA", True);
  221846. if (hints != None)
  221847. {
  221848. const int numMonitors = ScreenCount (display);
  221849. for (int i = 0; i < numMonitors; ++i)
  221850. {
  221851. Window root = RootWindow (display, i);
  221852. unsigned long nitems, bytesLeft;
  221853. Atom actualType;
  221854. int actualFormat;
  221855. unsigned char* data = 0;
  221856. if (XGetWindowProperty (display, root, hints, 0, 4, False,
  221857. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  221858. &data) == Success)
  221859. {
  221860. const long* const position = (const long*) data;
  221861. if (actualType == XA_CARDINAL && actualFormat == 32 && nitems == 4)
  221862. monitorCoords.add (Rectangle<int> (position[0], position[1],
  221863. position[2], position[3]));
  221864. XFree (data);
  221865. }
  221866. }
  221867. }
  221868. if (monitorCoords.size() == 0)
  221869. {
  221870. monitorCoords.add (Rectangle<int> (DisplayWidth (display, DefaultScreen (display)),
  221871. DisplayHeight (display, DefaultScreen (display))));
  221872. }
  221873. }
  221874. }
  221875. void Desktop::createMouseInputSources()
  221876. {
  221877. mouseSources.add (new MouseInputSource (0, true));
  221878. }
  221879. bool Desktop::canUseSemiTransparentWindows() throw()
  221880. {
  221881. int matchedDepth = 0;
  221882. const int desiredDepth = 32;
  221883. return Visuals::findVisualFormat (desiredDepth, matchedDepth) != 0
  221884. && (matchedDepth == desiredDepth);
  221885. }
  221886. const Point<int> Desktop::getMousePosition()
  221887. {
  221888. Window root, child;
  221889. int x, y, winx, winy;
  221890. unsigned int mask;
  221891. ScopedXLock xlock;
  221892. if (XQueryPointer (display,
  221893. RootWindow (display, DefaultScreen (display)),
  221894. &root, &child,
  221895. &x, &y, &winx, &winy, &mask) == False)
  221896. {
  221897. // Pointer not on the default screen
  221898. x = y = -1;
  221899. }
  221900. return Point<int> (x, y);
  221901. }
  221902. void Desktop::setMousePosition (const Point<int>& newPosition)
  221903. {
  221904. ScopedXLock xlock;
  221905. Window root = RootWindow (display, DefaultScreen (display));
  221906. XWarpPointer (display, None, root, 0, 0, 0, 0, newPosition.getX(), newPosition.getY());
  221907. }
  221908. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  221909. {
  221910. return upright;
  221911. }
  221912. static bool screenSaverAllowed = true;
  221913. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  221914. {
  221915. if (screenSaverAllowed != isEnabled)
  221916. {
  221917. screenSaverAllowed = isEnabled;
  221918. typedef void (*tXScreenSaverSuspend) (Display*, Bool);
  221919. static tXScreenSaverSuspend xScreenSaverSuspend = 0;
  221920. if (xScreenSaverSuspend == 0)
  221921. {
  221922. void* h = dlopen ("libXss.so", RTLD_GLOBAL | RTLD_NOW);
  221923. if (h != 0)
  221924. xScreenSaverSuspend = (tXScreenSaverSuspend) dlsym (h, "XScreenSaverSuspend");
  221925. }
  221926. ScopedXLock xlock;
  221927. if (xScreenSaverSuspend != 0)
  221928. xScreenSaverSuspend (display, ! isEnabled);
  221929. }
  221930. }
  221931. bool Desktop::isScreenSaverEnabled()
  221932. {
  221933. return screenSaverAllowed;
  221934. }
  221935. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  221936. {
  221937. ScopedXLock xlock;
  221938. const unsigned int imageW = image.getWidth();
  221939. const unsigned int imageH = image.getHeight();
  221940. #if JUCE_USE_XCURSOR
  221941. {
  221942. typedef XcursorBool (*tXcursorSupportsARGB) (Display*);
  221943. typedef XcursorImage* (*tXcursorImageCreate) (int, int);
  221944. typedef void (*tXcursorImageDestroy) (XcursorImage*);
  221945. typedef Cursor (*tXcursorImageLoadCursor) (Display*, const XcursorImage*);
  221946. static tXcursorSupportsARGB xXcursorSupportsARGB = 0;
  221947. static tXcursorImageCreate xXcursorImageCreate = 0;
  221948. static tXcursorImageDestroy xXcursorImageDestroy = 0;
  221949. static tXcursorImageLoadCursor xXcursorImageLoadCursor = 0;
  221950. static bool hasBeenLoaded = false;
  221951. if (! hasBeenLoaded)
  221952. {
  221953. hasBeenLoaded = true;
  221954. void* h = dlopen ("libXcursor.so", RTLD_GLOBAL | RTLD_NOW);
  221955. if (h != 0)
  221956. {
  221957. xXcursorSupportsARGB = (tXcursorSupportsARGB) dlsym (h, "XcursorSupportsARGB");
  221958. xXcursorImageCreate = (tXcursorImageCreate) dlsym (h, "XcursorImageCreate");
  221959. xXcursorImageLoadCursor = (tXcursorImageLoadCursor) dlsym (h, "XcursorImageLoadCursor");
  221960. xXcursorImageDestroy = (tXcursorImageDestroy) dlsym (h, "XcursorImageDestroy");
  221961. if (xXcursorSupportsARGB == 0 || xXcursorImageCreate == 0
  221962. || xXcursorImageLoadCursor == 0 || xXcursorImageDestroy == 0
  221963. || ! xXcursorSupportsARGB (display))
  221964. xXcursorSupportsARGB = 0;
  221965. }
  221966. }
  221967. if (xXcursorSupportsARGB != 0)
  221968. {
  221969. XcursorImage* xcImage = xXcursorImageCreate (imageW, imageH);
  221970. if (xcImage != 0)
  221971. {
  221972. xcImage->xhot = hotspotX;
  221973. xcImage->yhot = hotspotY;
  221974. XcursorPixel* dest = xcImage->pixels;
  221975. for (int y = 0; y < (int) imageH; ++y)
  221976. for (int x = 0; x < (int) imageW; ++x)
  221977. *dest++ = image.getPixelAt (x, y).getARGB();
  221978. void* result = (void*) xXcursorImageLoadCursor (display, xcImage);
  221979. xXcursorImageDestroy (xcImage);
  221980. if (result != 0)
  221981. return result;
  221982. }
  221983. }
  221984. }
  221985. #endif
  221986. Window root = RootWindow (display, DefaultScreen (display));
  221987. unsigned int cursorW, cursorH;
  221988. if (! XQueryBestCursor (display, root, imageW, imageH, &cursorW, &cursorH))
  221989. return 0;
  221990. Image im (Image::ARGB, cursorW, cursorH, true);
  221991. {
  221992. Graphics g (im);
  221993. if (imageW > cursorW || imageH > cursorH)
  221994. {
  221995. hotspotX = (hotspotX * cursorW) / imageW;
  221996. hotspotY = (hotspotY * cursorH) / imageH;
  221997. g.drawImageWithin (image, 0, 0, imageW, imageH,
  221998. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  221999. false);
  222000. }
  222001. else
  222002. {
  222003. g.drawImageAt (image, 0, 0);
  222004. }
  222005. }
  222006. const int stride = (cursorW + 7) >> 3;
  222007. HeapBlock <char> maskPlane, sourcePlane;
  222008. maskPlane.calloc (stride * cursorH);
  222009. sourcePlane.calloc (stride * cursorH);
  222010. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  222011. for (int y = cursorH; --y >= 0;)
  222012. {
  222013. for (int x = cursorW; --x >= 0;)
  222014. {
  222015. const char mask = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  222016. const int offset = y * stride + (x >> 3);
  222017. const Colour c (im.getPixelAt (x, y));
  222018. if (c.getAlpha() >= 128)
  222019. maskPlane[offset] |= mask;
  222020. if (c.getBrightness() >= 0.5f)
  222021. sourcePlane[offset] |= mask;
  222022. }
  222023. }
  222024. Pixmap sourcePixmap = XCreatePixmapFromBitmapData (display, root, sourcePlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  222025. Pixmap maskPixmap = XCreatePixmapFromBitmapData (display, root, maskPlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  222026. XColor white, black;
  222027. black.red = black.green = black.blue = 0;
  222028. white.red = white.green = white.blue = 0xffff;
  222029. void* result = (void*) XCreatePixmapCursor (display, sourcePixmap, maskPixmap, &white, &black, hotspotX, hotspotY);
  222030. XFreePixmap (display, sourcePixmap);
  222031. XFreePixmap (display, maskPixmap);
  222032. return result;
  222033. }
  222034. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool)
  222035. {
  222036. ScopedXLock xlock;
  222037. if (cursorHandle != 0)
  222038. XFreeCursor (display, (Cursor) cursorHandle);
  222039. }
  222040. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  222041. {
  222042. unsigned int shape;
  222043. switch (type)
  222044. {
  222045. case NormalCursor: return None; // Use parent cursor
  222046. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 16, 16, true), 0, 0);
  222047. case WaitCursor: shape = XC_watch; break;
  222048. case IBeamCursor: shape = XC_xterm; break;
  222049. case PointingHandCursor: shape = XC_hand2; break;
  222050. case LeftRightResizeCursor: shape = XC_sb_h_double_arrow; break;
  222051. case UpDownResizeCursor: shape = XC_sb_v_double_arrow; break;
  222052. case UpDownLeftRightResizeCursor: shape = XC_fleur; break;
  222053. case TopEdgeResizeCursor: shape = XC_top_side; break;
  222054. case BottomEdgeResizeCursor: shape = XC_bottom_side; break;
  222055. case LeftEdgeResizeCursor: shape = XC_left_side; break;
  222056. case RightEdgeResizeCursor: shape = XC_right_side; break;
  222057. case TopLeftCornerResizeCursor: shape = XC_top_left_corner; break;
  222058. case TopRightCornerResizeCursor: shape = XC_top_right_corner; break;
  222059. case BottomLeftCornerResizeCursor: shape = XC_bottom_left_corner; break;
  222060. case BottomRightCornerResizeCursor: shape = XC_bottom_right_corner; break;
  222061. case CrosshairCursor: shape = XC_crosshair; break;
  222062. case DraggingHandCursor:
  222063. {
  222064. static unsigned char dragHandData[] = { 71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,
  222065. 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,
  222066. 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 };
  222067. const int dragHandDataSize = 99;
  222068. return createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, dragHandDataSize), 8, 7);
  222069. }
  222070. case CopyingCursor:
  222071. {
  222072. static unsigned char copyCursorData[] = { 71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,
  222073. 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,
  222074. 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,
  222075. 252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  222076. const int copyCursorSize = 119;
  222077. return createMouseCursorFromImage (ImageFileFormat::loadFrom (copyCursorData, copyCursorSize), 1, 3);
  222078. }
  222079. default:
  222080. jassertfalse;
  222081. return None;
  222082. }
  222083. ScopedXLock xlock;
  222084. return (void*) XCreateFontCursor (display, shape);
  222085. }
  222086. void MouseCursor::showInWindow (ComponentPeer* peer) const
  222087. {
  222088. LinuxComponentPeer* const lp = dynamic_cast <LinuxComponentPeer*> (peer);
  222089. if (lp != 0)
  222090. lp->showMouseCursor ((Cursor) getHandle());
  222091. }
  222092. void MouseCursor::showInAllWindows() const
  222093. {
  222094. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  222095. showInWindow (ComponentPeer::getPeer (i));
  222096. }
  222097. const Image juce_createIconForFile (const File& file)
  222098. {
  222099. return Image::null;
  222100. }
  222101. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  222102. {
  222103. return createSoftwareImage (format, width, height, clearImage);
  222104. }
  222105. #if JUCE_OPENGL
  222106. class WindowedGLContext : public OpenGLContext
  222107. {
  222108. public:
  222109. WindowedGLContext (Component* const component,
  222110. const OpenGLPixelFormat& pixelFormat_,
  222111. GLXContext sharedContext)
  222112. : renderContext (0),
  222113. embeddedWindow (0),
  222114. pixelFormat (pixelFormat_),
  222115. swapInterval (0)
  222116. {
  222117. jassert (component != 0);
  222118. LinuxComponentPeer* const peer = dynamic_cast <LinuxComponentPeer*> (component->getTopLevelComponent()->getPeer());
  222119. if (peer == 0)
  222120. return;
  222121. ScopedXLock xlock;
  222122. XSync (display, False);
  222123. GLint attribs [64];
  222124. int n = 0;
  222125. attribs[n++] = GLX_RGBA;
  222126. attribs[n++] = GLX_DOUBLEBUFFER;
  222127. attribs[n++] = GLX_RED_SIZE;
  222128. attribs[n++] = pixelFormat.redBits;
  222129. attribs[n++] = GLX_GREEN_SIZE;
  222130. attribs[n++] = pixelFormat.greenBits;
  222131. attribs[n++] = GLX_BLUE_SIZE;
  222132. attribs[n++] = pixelFormat.blueBits;
  222133. attribs[n++] = GLX_ALPHA_SIZE;
  222134. attribs[n++] = pixelFormat.alphaBits;
  222135. attribs[n++] = GLX_DEPTH_SIZE;
  222136. attribs[n++] = pixelFormat.depthBufferBits;
  222137. attribs[n++] = GLX_STENCIL_SIZE;
  222138. attribs[n++] = pixelFormat.stencilBufferBits;
  222139. attribs[n++] = GLX_ACCUM_RED_SIZE;
  222140. attribs[n++] = pixelFormat.accumulationBufferRedBits;
  222141. attribs[n++] = GLX_ACCUM_GREEN_SIZE;
  222142. attribs[n++] = pixelFormat.accumulationBufferGreenBits;
  222143. attribs[n++] = GLX_ACCUM_BLUE_SIZE;
  222144. attribs[n++] = pixelFormat.accumulationBufferBlueBits;
  222145. attribs[n++] = GLX_ACCUM_ALPHA_SIZE;
  222146. attribs[n++] = pixelFormat.accumulationBufferAlphaBits;
  222147. // xxx not sure how to do fullSceneAntiAliasingNumSamples on linux..
  222148. attribs[n++] = None;
  222149. XVisualInfo* const bestVisual = glXChooseVisual (display, DefaultScreen (display), attribs);
  222150. if (bestVisual == 0)
  222151. return;
  222152. renderContext = glXCreateContext (display, bestVisual, sharedContext, GL_TRUE);
  222153. Window windowH = (Window) peer->getNativeHandle();
  222154. Colormap colourMap = XCreateColormap (display, windowH, bestVisual->visual, AllocNone);
  222155. XSetWindowAttributes swa;
  222156. swa.colormap = colourMap;
  222157. swa.border_pixel = 0;
  222158. swa.event_mask = ExposureMask | StructureNotifyMask;
  222159. embeddedWindow = XCreateWindow (display, windowH,
  222160. 0, 0, 1, 1, 0,
  222161. bestVisual->depth,
  222162. InputOutput,
  222163. bestVisual->visual,
  222164. CWBorderPixel | CWColormap | CWEventMask,
  222165. &swa);
  222166. XSaveContext (display, (XID) embeddedWindow, windowHandleXContext, (XPointer) peer);
  222167. XMapWindow (display, embeddedWindow);
  222168. XFreeColormap (display, colourMap);
  222169. XFree (bestVisual);
  222170. XSync (display, False);
  222171. }
  222172. ~WindowedGLContext()
  222173. {
  222174. ScopedXLock xlock;
  222175. deleteContext();
  222176. XUnmapWindow (display, embeddedWindow);
  222177. XDestroyWindow (display, embeddedWindow);
  222178. }
  222179. void deleteContext()
  222180. {
  222181. makeInactive();
  222182. if (renderContext != 0)
  222183. {
  222184. ScopedXLock xlock;
  222185. glXDestroyContext (display, renderContext);
  222186. renderContext = 0;
  222187. }
  222188. }
  222189. bool makeActive() const throw()
  222190. {
  222191. jassert (renderContext != 0);
  222192. ScopedXLock xlock;
  222193. return glXMakeCurrent (display, embeddedWindow, renderContext)
  222194. && XSync (display, False);
  222195. }
  222196. bool makeInactive() const throw()
  222197. {
  222198. ScopedXLock xlock;
  222199. return (! isActive()) || glXMakeCurrent (display, None, 0);
  222200. }
  222201. bool isActive() const throw()
  222202. {
  222203. ScopedXLock xlock;
  222204. return glXGetCurrentContext() == renderContext;
  222205. }
  222206. const OpenGLPixelFormat getPixelFormat() const
  222207. {
  222208. return pixelFormat;
  222209. }
  222210. void* getRawContext() const throw()
  222211. {
  222212. return renderContext;
  222213. }
  222214. void updateWindowPosition (int x, int y, int w, int h, int)
  222215. {
  222216. ScopedXLock xlock;
  222217. XMoveResizeWindow (display, embeddedWindow,
  222218. x, y, jmax (1, w), jmax (1, h));
  222219. }
  222220. void swapBuffers()
  222221. {
  222222. ScopedXLock xlock;
  222223. glXSwapBuffers (display, embeddedWindow);
  222224. }
  222225. bool setSwapInterval (const int numFramesPerSwap)
  222226. {
  222227. static PFNGLXSWAPINTERVALSGIPROC GLXSwapIntervalSGI = (PFNGLXSWAPINTERVALSGIPROC) glXGetProcAddress ((const GLubyte*) "glXSwapIntervalSGI");
  222228. if (GLXSwapIntervalSGI != 0)
  222229. {
  222230. swapInterval = numFramesPerSwap;
  222231. GLXSwapIntervalSGI (numFramesPerSwap);
  222232. return true;
  222233. }
  222234. return false;
  222235. }
  222236. int getSwapInterval() const
  222237. {
  222238. return swapInterval;
  222239. }
  222240. void repaint()
  222241. {
  222242. }
  222243. juce_UseDebuggingNewOperator
  222244. GLXContext renderContext;
  222245. private:
  222246. Window embeddedWindow;
  222247. OpenGLPixelFormat pixelFormat;
  222248. int swapInterval;
  222249. WindowedGLContext (const WindowedGLContext&);
  222250. WindowedGLContext& operator= (const WindowedGLContext&);
  222251. };
  222252. OpenGLContext* OpenGLComponent::createContext()
  222253. {
  222254. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  222255. contextToShareListsWith != 0 ? (GLXContext) contextToShareListsWith->getRawContext() : 0));
  222256. return (c->renderContext != 0) ? c.release() : 0;
  222257. }
  222258. void juce_glViewport (const int w, const int h)
  222259. {
  222260. glViewport (0, 0, w, h);
  222261. }
  222262. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  222263. OwnedArray <OpenGLPixelFormat>& results)
  222264. {
  222265. results.add (new OpenGLPixelFormat()); // xxx
  222266. }
  222267. #endif
  222268. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  222269. {
  222270. jassertfalse; // not implemented!
  222271. return false;
  222272. }
  222273. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  222274. {
  222275. jassertfalse; // not implemented!
  222276. return false;
  222277. }
  222278. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  222279. {
  222280. if (! isOnDesktop ())
  222281. addToDesktop (0);
  222282. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  222283. if (wp != 0)
  222284. {
  222285. wp->setTaskBarIcon (newImage);
  222286. setVisible (true);
  222287. toFront (false);
  222288. repaint();
  222289. }
  222290. }
  222291. void SystemTrayIconComponent::paint (Graphics& g)
  222292. {
  222293. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  222294. if (wp != 0)
  222295. {
  222296. g.drawImageWithin (wp->getTaskbarIcon(), 0, 0, getWidth(), getHeight(),
  222297. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  222298. false);
  222299. }
  222300. }
  222301. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  222302. {
  222303. // xxx not yet implemented!
  222304. }
  222305. void PlatformUtilities::beep()
  222306. {
  222307. std::cout << "\a" << std::flush;
  222308. }
  222309. bool AlertWindow::showNativeDialogBox (const String& title,
  222310. const String& bodyText,
  222311. bool isOkCancel)
  222312. {
  222313. // use a non-native one for the time being..
  222314. if (isOkCancel)
  222315. return AlertWindow::showOkCancelBox (AlertWindow::NoIcon, title, bodyText);
  222316. else
  222317. AlertWindow::showMessageBox (AlertWindow::NoIcon, title, bodyText);
  222318. return true;
  222319. }
  222320. const int KeyPress::spaceKey = XK_space & 0xff;
  222321. const int KeyPress::returnKey = XK_Return & 0xff;
  222322. const int KeyPress::escapeKey = XK_Escape & 0xff;
  222323. const int KeyPress::backspaceKey = XK_BackSpace & 0xff;
  222324. const int KeyPress::leftKey = (XK_Left & 0xff) | Keys::extendedKeyModifier;
  222325. const int KeyPress::rightKey = (XK_Right & 0xff) | Keys::extendedKeyModifier;
  222326. const int KeyPress::upKey = (XK_Up & 0xff) | Keys::extendedKeyModifier;
  222327. const int KeyPress::downKey = (XK_Down & 0xff) | Keys::extendedKeyModifier;
  222328. const int KeyPress::pageUpKey = (XK_Page_Up & 0xff) | Keys::extendedKeyModifier;
  222329. const int KeyPress::pageDownKey = (XK_Page_Down & 0xff) | Keys::extendedKeyModifier;
  222330. const int KeyPress::endKey = (XK_End & 0xff) | Keys::extendedKeyModifier;
  222331. const int KeyPress::homeKey = (XK_Home & 0xff) | Keys::extendedKeyModifier;
  222332. const int KeyPress::insertKey = (XK_Insert & 0xff) | Keys::extendedKeyModifier;
  222333. const int KeyPress::deleteKey = (XK_Delete & 0xff) | Keys::extendedKeyModifier;
  222334. const int KeyPress::tabKey = XK_Tab & 0xff;
  222335. const int KeyPress::F1Key = (XK_F1 & 0xff) | Keys::extendedKeyModifier;
  222336. const int KeyPress::F2Key = (XK_F2 & 0xff) | Keys::extendedKeyModifier;
  222337. const int KeyPress::F3Key = (XK_F3 & 0xff) | Keys::extendedKeyModifier;
  222338. const int KeyPress::F4Key = (XK_F4 & 0xff) | Keys::extendedKeyModifier;
  222339. const int KeyPress::F5Key = (XK_F5 & 0xff) | Keys::extendedKeyModifier;
  222340. const int KeyPress::F6Key = (XK_F6 & 0xff) | Keys::extendedKeyModifier;
  222341. const int KeyPress::F7Key = (XK_F7 & 0xff) | Keys::extendedKeyModifier;
  222342. const int KeyPress::F8Key = (XK_F8 & 0xff) | Keys::extendedKeyModifier;
  222343. const int KeyPress::F9Key = (XK_F9 & 0xff) | Keys::extendedKeyModifier;
  222344. const int KeyPress::F10Key = (XK_F10 & 0xff) | Keys::extendedKeyModifier;
  222345. const int KeyPress::F11Key = (XK_F11 & 0xff) | Keys::extendedKeyModifier;
  222346. const int KeyPress::F12Key = (XK_F12 & 0xff) | Keys::extendedKeyModifier;
  222347. const int KeyPress::F13Key = (XK_F13 & 0xff) | Keys::extendedKeyModifier;
  222348. const int KeyPress::F14Key = (XK_F14 & 0xff) | Keys::extendedKeyModifier;
  222349. const int KeyPress::F15Key = (XK_F15 & 0xff) | Keys::extendedKeyModifier;
  222350. const int KeyPress::F16Key = (XK_F16 & 0xff) | Keys::extendedKeyModifier;
  222351. const int KeyPress::numberPad0 = (XK_KP_0 & 0xff) | Keys::extendedKeyModifier;
  222352. const int KeyPress::numberPad1 = (XK_KP_1 & 0xff) | Keys::extendedKeyModifier;
  222353. const int KeyPress::numberPad2 = (XK_KP_2 & 0xff) | Keys::extendedKeyModifier;
  222354. const int KeyPress::numberPad3 = (XK_KP_3 & 0xff) | Keys::extendedKeyModifier;
  222355. const int KeyPress::numberPad4 = (XK_KP_4 & 0xff) | Keys::extendedKeyModifier;
  222356. const int KeyPress::numberPad5 = (XK_KP_5 & 0xff) | Keys::extendedKeyModifier;
  222357. const int KeyPress::numberPad6 = (XK_KP_6 & 0xff) | Keys::extendedKeyModifier;
  222358. const int KeyPress::numberPad7 = (XK_KP_7 & 0xff)| Keys::extendedKeyModifier;
  222359. const int KeyPress::numberPad8 = (XK_KP_8 & 0xff)| Keys::extendedKeyModifier;
  222360. const int KeyPress::numberPad9 = (XK_KP_9 & 0xff)| Keys::extendedKeyModifier;
  222361. const int KeyPress::numberPadAdd = (XK_KP_Add & 0xff)| Keys::extendedKeyModifier;
  222362. const int KeyPress::numberPadSubtract = (XK_KP_Subtract & 0xff)| Keys::extendedKeyModifier;
  222363. const int KeyPress::numberPadMultiply = (XK_KP_Multiply & 0xff)| Keys::extendedKeyModifier;
  222364. const int KeyPress::numberPadDivide = (XK_KP_Divide & 0xff)| Keys::extendedKeyModifier;
  222365. const int KeyPress::numberPadSeparator = (XK_KP_Separator & 0xff)| Keys::extendedKeyModifier;
  222366. const int KeyPress::numberPadDecimalPoint = (XK_KP_Decimal & 0xff)| Keys::extendedKeyModifier;
  222367. const int KeyPress::numberPadEquals = (XK_KP_Equal & 0xff)| Keys::extendedKeyModifier;
  222368. const int KeyPress::numberPadDelete = (XK_KP_Delete & 0xff)| Keys::extendedKeyModifier;
  222369. const int KeyPress::playKey = (0xffeeff00) | Keys::extendedKeyModifier;
  222370. const int KeyPress::stopKey = (0xffeeff01) | Keys::extendedKeyModifier;
  222371. const int KeyPress::fastForwardKey = (0xffeeff02) | Keys::extendedKeyModifier;
  222372. const int KeyPress::rewindKey = (0xffeeff03) | Keys::extendedKeyModifier;
  222373. #endif
  222374. /*** End of inlined file: juce_linux_Windowing.cpp ***/
  222375. /*** Start of inlined file: juce_linux_Audio.cpp ***/
  222376. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222377. // compiled on its own).
  222378. #if JUCE_INCLUDED_FILE && JUCE_ALSA
  222379. static void getDeviceSampleRates (snd_pcm_t* handle, Array <int>& rates)
  222380. {
  222381. const int ratesToTry[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  222382. snd_pcm_hw_params_t* hwParams;
  222383. snd_pcm_hw_params_alloca (&hwParams);
  222384. for (int i = 0; ratesToTry[i] != 0; ++i)
  222385. {
  222386. if (snd_pcm_hw_params_any (handle, hwParams) >= 0
  222387. && snd_pcm_hw_params_test_rate (handle, hwParams, ratesToTry[i], 0) == 0)
  222388. {
  222389. rates.addIfNotAlreadyThere (ratesToTry[i]);
  222390. }
  222391. }
  222392. }
  222393. static void getDeviceNumChannels (snd_pcm_t* handle, unsigned int* minChans, unsigned int* maxChans)
  222394. {
  222395. snd_pcm_hw_params_t *params;
  222396. snd_pcm_hw_params_alloca (&params);
  222397. if (snd_pcm_hw_params_any (handle, params) >= 0)
  222398. {
  222399. snd_pcm_hw_params_get_channels_min (params, minChans);
  222400. snd_pcm_hw_params_get_channels_max (params, maxChans);
  222401. }
  222402. }
  222403. static void getDeviceProperties (const String& deviceID,
  222404. unsigned int& minChansOut,
  222405. unsigned int& maxChansOut,
  222406. unsigned int& minChansIn,
  222407. unsigned int& maxChansIn,
  222408. Array <int>& rates)
  222409. {
  222410. if (deviceID.isEmpty())
  222411. return;
  222412. snd_ctl_t* handle;
  222413. if (snd_ctl_open (&handle, deviceID.upToLastOccurrenceOf (",", false, false).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  222414. {
  222415. snd_pcm_info_t* info;
  222416. snd_pcm_info_alloca (&info);
  222417. snd_pcm_info_set_stream (info, SND_PCM_STREAM_PLAYBACK);
  222418. snd_pcm_info_set_device (info, deviceID.fromLastOccurrenceOf (",", false, false).getIntValue());
  222419. snd_pcm_info_set_subdevice (info, 0);
  222420. if (snd_ctl_pcm_info (handle, info) >= 0)
  222421. {
  222422. snd_pcm_t* pcmHandle;
  222423. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_PLAYBACK, SND_PCM_ASYNC | SND_PCM_NONBLOCK) >= 0)
  222424. {
  222425. getDeviceNumChannels (pcmHandle, &minChansOut, &maxChansOut);
  222426. getDeviceSampleRates (pcmHandle, rates);
  222427. snd_pcm_close (pcmHandle);
  222428. }
  222429. }
  222430. snd_pcm_info_set_stream (info, SND_PCM_STREAM_CAPTURE);
  222431. if (snd_ctl_pcm_info (handle, info) >= 0)
  222432. {
  222433. snd_pcm_t* pcmHandle;
  222434. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_CAPTURE, SND_PCM_ASYNC | SND_PCM_NONBLOCK) >= 0)
  222435. {
  222436. getDeviceNumChannels (pcmHandle, &minChansIn, &maxChansIn);
  222437. if (rates.size() == 0)
  222438. getDeviceSampleRates (pcmHandle, rates);
  222439. snd_pcm_close (pcmHandle);
  222440. }
  222441. }
  222442. snd_ctl_close (handle);
  222443. }
  222444. }
  222445. class ALSADevice
  222446. {
  222447. public:
  222448. ALSADevice (const String& deviceID, bool forInput)
  222449. : handle (0),
  222450. bitDepth (16),
  222451. numChannelsRunning (0),
  222452. latency (0),
  222453. isInput (forInput)
  222454. {
  222455. failed (snd_pcm_open (&handle, deviceID.toUTF8(),
  222456. forInput ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK,
  222457. SND_PCM_ASYNC));
  222458. }
  222459. ~ALSADevice()
  222460. {
  222461. if (handle != 0)
  222462. snd_pcm_close (handle);
  222463. }
  222464. bool setParameters (unsigned int sampleRate, int numChannels, int bufferSize)
  222465. {
  222466. if (handle == 0)
  222467. return false;
  222468. snd_pcm_hw_params_t* hwParams;
  222469. snd_pcm_hw_params_alloca (&hwParams);
  222470. if (failed (snd_pcm_hw_params_any (handle, hwParams)))
  222471. return false;
  222472. if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_NONINTERLEAVED) >= 0)
  222473. isInterleaved = false;
  222474. else if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_INTERLEAVED) >= 0)
  222475. isInterleaved = true;
  222476. else
  222477. {
  222478. jassertfalse;
  222479. return false;
  222480. }
  222481. enum { isFloatBit = 1 << 16, isLittleEndianBit = 1 << 17 };
  222482. const int formatsToTry[] = { SND_PCM_FORMAT_FLOAT_LE, 32 | isFloatBit | isLittleEndianBit,
  222483. SND_PCM_FORMAT_FLOAT_BE, 32 | isFloatBit,
  222484. SND_PCM_FORMAT_S32_LE, 32 | isLittleEndianBit,
  222485. SND_PCM_FORMAT_S32_BE, 32,
  222486. SND_PCM_FORMAT_S24_3LE, 24 | isLittleEndianBit,
  222487. SND_PCM_FORMAT_S24_3BE, 24,
  222488. SND_PCM_FORMAT_S16_LE, 16 | isLittleEndianBit,
  222489. SND_PCM_FORMAT_S16_BE, 16 };
  222490. bitDepth = 0;
  222491. for (int i = 0; i < numElementsInArray (formatsToTry); i += 2)
  222492. {
  222493. if (snd_pcm_hw_params_set_format (handle, hwParams, (_snd_pcm_format) formatsToTry [i]) >= 0)
  222494. {
  222495. bitDepth = formatsToTry [i + 1] & 255;
  222496. const bool isFloat = (formatsToTry [i + 1] & isFloatBit) != 0;
  222497. const bool isLittleEndian = (formatsToTry [i + 1] & isLittleEndianBit) != 0;
  222498. converter = createConverter (isInput, bitDepth, isFloat, isLittleEndian, numChannels);
  222499. break;
  222500. }
  222501. }
  222502. if (bitDepth == 0)
  222503. {
  222504. error = "device doesn't support a compatible PCM format";
  222505. DBG ("ALSA error: " + error + "\n");
  222506. return false;
  222507. }
  222508. int dir = 0;
  222509. unsigned int periods = 4;
  222510. snd_pcm_uframes_t samplesPerPeriod = bufferSize;
  222511. if (failed (snd_pcm_hw_params_set_rate_near (handle, hwParams, &sampleRate, 0))
  222512. || failed (snd_pcm_hw_params_set_channels (handle, hwParams, numChannels))
  222513. || failed (snd_pcm_hw_params_set_periods_near (handle, hwParams, &periods, &dir))
  222514. || failed (snd_pcm_hw_params_set_period_size_near (handle, hwParams, &samplesPerPeriod, &dir))
  222515. || failed (snd_pcm_hw_params (handle, hwParams)))
  222516. {
  222517. return false;
  222518. }
  222519. snd_pcm_uframes_t frames = 0;
  222520. if (failed (snd_pcm_hw_params_get_period_size (hwParams, &frames, &dir))
  222521. || failed (snd_pcm_hw_params_get_periods (hwParams, &periods, &dir)))
  222522. latency = 0;
  222523. else
  222524. latency = frames * (periods - 1); // (this is the method JACK uses to guess the latency..)
  222525. snd_pcm_sw_params_t* swParams;
  222526. snd_pcm_sw_params_alloca (&swParams);
  222527. snd_pcm_uframes_t boundary;
  222528. if (failed (snd_pcm_sw_params_current (handle, swParams))
  222529. || failed (snd_pcm_sw_params_get_boundary (swParams, &boundary))
  222530. || failed (snd_pcm_sw_params_set_silence_threshold (handle, swParams, 0))
  222531. || failed (snd_pcm_sw_params_set_silence_size (handle, swParams, boundary))
  222532. || failed (snd_pcm_sw_params_set_start_threshold (handle, swParams, samplesPerPeriod))
  222533. || failed (snd_pcm_sw_params_set_stop_threshold (handle, swParams, boundary))
  222534. || failed (snd_pcm_sw_params (handle, swParams)))
  222535. {
  222536. return false;
  222537. }
  222538. /*
  222539. #if JUCE_DEBUG
  222540. // enable this to dump the config of the devices that get opened
  222541. snd_output_t* out;
  222542. snd_output_stdio_attach (&out, stderr, 0);
  222543. snd_pcm_hw_params_dump (hwParams, out);
  222544. snd_pcm_sw_params_dump (swParams, out);
  222545. #endif
  222546. */
  222547. numChannelsRunning = numChannels;
  222548. return true;
  222549. }
  222550. bool writeToOutputDevice (AudioSampleBuffer& outputChannelBuffer, const int numSamples)
  222551. {
  222552. jassert (numChannelsRunning <= outputChannelBuffer.getNumChannels());
  222553. float** const data = outputChannelBuffer.getArrayOfChannels();
  222554. snd_pcm_sframes_t numDone = 0;
  222555. if (isInterleaved)
  222556. {
  222557. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  222558. for (int i = 0; i < numChannelsRunning; ++i)
  222559. converter->convertSamples (scratch.getData(), i, data[i], 0, numSamples);
  222560. numDone = snd_pcm_writei (handle, scratch.getData(), numSamples);
  222561. }
  222562. else
  222563. {
  222564. for (int i = 0; i < numChannelsRunning; ++i)
  222565. converter->convertSamples (data[i], data[i], numSamples);
  222566. numDone = snd_pcm_writen (handle, (void**) data, numSamples);
  222567. }
  222568. if (failed (numDone))
  222569. {
  222570. if (numDone == -EPIPE)
  222571. {
  222572. if (failed (snd_pcm_prepare (handle)))
  222573. return false;
  222574. }
  222575. else if (numDone != -ESTRPIPE)
  222576. return false;
  222577. }
  222578. return true;
  222579. }
  222580. bool readFromInputDevice (AudioSampleBuffer& inputChannelBuffer, const int numSamples)
  222581. {
  222582. jassert (numChannelsRunning <= inputChannelBuffer.getNumChannels());
  222583. float** const data = inputChannelBuffer.getArrayOfChannels();
  222584. if (isInterleaved)
  222585. {
  222586. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  222587. snd_pcm_sframes_t num = snd_pcm_readi (handle, scratch.getData(), numSamples);
  222588. if (failed (num))
  222589. {
  222590. if (num == -EPIPE)
  222591. {
  222592. if (failed (snd_pcm_prepare (handle)))
  222593. return false;
  222594. }
  222595. else if (num != -ESTRPIPE)
  222596. return false;
  222597. }
  222598. for (int i = 0; i < numChannelsRunning; ++i)
  222599. converter->convertSamples (data[i], 0, scratch.getData(), i, numSamples);
  222600. }
  222601. else
  222602. {
  222603. snd_pcm_sframes_t num = snd_pcm_readn (handle, (void**) data, numSamples);
  222604. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  222605. return false;
  222606. for (int i = 0; i < numChannelsRunning; ++i)
  222607. converter->convertSamples (data[i], data[i], numSamples);
  222608. }
  222609. return true;
  222610. }
  222611. juce_UseDebuggingNewOperator
  222612. snd_pcm_t* handle;
  222613. String error;
  222614. int bitDepth, numChannelsRunning, latency;
  222615. private:
  222616. const bool isInput;
  222617. bool isInterleaved;
  222618. MemoryBlock scratch;
  222619. ScopedPointer<AudioData::Converter> converter;
  222620. template <class SampleType>
  222621. struct ConverterHelper
  222622. {
  222623. static AudioData::Converter* createConverter (const bool forInput, const bool isLittleEndian, const int numInterleavedChannels)
  222624. {
  222625. if (forInput)
  222626. {
  222627. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> DestType;
  222628. if (isLittleEndian)
  222629. return new AudioData::ConverterInstance <AudioData::Pointer <SampleType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, DestType> (numInterleavedChannels, 1);
  222630. else
  222631. return new AudioData::ConverterInstance <AudioData::Pointer <SampleType, AudioData::BigEndian, AudioData::Interleaved, AudioData::Const>, DestType> (numInterleavedChannels, 1);
  222632. }
  222633. else
  222634. {
  222635. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> SourceType;
  222636. if (isLittleEndian)
  222637. return new AudioData::ConverterInstance <SourceType, AudioData::Pointer <SampleType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, numInterleavedChannels);
  222638. else
  222639. return new AudioData::ConverterInstance <SourceType, AudioData::Pointer <SampleType, AudioData::BigEndian, AudioData::Interleaved, AudioData::NonConst> > (1, numInterleavedChannels);
  222640. }
  222641. }
  222642. };
  222643. static AudioData::Converter* createConverter (const bool forInput, const int bitDepth, const bool isFloat, const bool isLittleEndian, const int numInterleavedChannels)
  222644. {
  222645. switch (bitDepth)
  222646. {
  222647. case 16: return ConverterHelper <AudioData::Int16>::createConverter (forInput, isLittleEndian, numInterleavedChannels);
  222648. case 24: return ConverterHelper <AudioData::Int24>::createConverter (forInput, isLittleEndian, numInterleavedChannels);
  222649. case 32: return isFloat ? ConverterHelper <AudioData::Float32>::createConverter (forInput, isLittleEndian, numInterleavedChannels)
  222650. : ConverterHelper <AudioData::Int32>::createConverter (forInput, isLittleEndian, numInterleavedChannels);
  222651. default: jassertfalse; break; // unsupported format!
  222652. }
  222653. return 0;
  222654. }
  222655. bool failed (const int errorNum)
  222656. {
  222657. if (errorNum >= 0)
  222658. return false;
  222659. error = snd_strerror (errorNum);
  222660. DBG ("ALSA error: " + error + "\n");
  222661. return true;
  222662. }
  222663. };
  222664. class ALSAThread : public Thread
  222665. {
  222666. public:
  222667. ALSAThread (const String& inputId_,
  222668. const String& outputId_)
  222669. : Thread ("Juce ALSA"),
  222670. sampleRate (0),
  222671. bufferSize (0),
  222672. outputLatency (0),
  222673. inputLatency (0),
  222674. callback (0),
  222675. inputId (inputId_),
  222676. outputId (outputId_),
  222677. numCallbacks (0),
  222678. inputChannelBuffer (1, 1),
  222679. outputChannelBuffer (1, 1)
  222680. {
  222681. initialiseRatesAndChannels();
  222682. }
  222683. ~ALSAThread()
  222684. {
  222685. close();
  222686. }
  222687. void open (BigInteger inputChannels,
  222688. BigInteger outputChannels,
  222689. const double sampleRate_,
  222690. const int bufferSize_)
  222691. {
  222692. close();
  222693. error = String::empty;
  222694. sampleRate = sampleRate_;
  222695. bufferSize = bufferSize_;
  222696. inputChannelBuffer.setSize (jmax ((int) minChansIn, inputChannels.getHighestBit()) + 1, bufferSize);
  222697. inputChannelBuffer.clear();
  222698. inputChannelDataForCallback.clear();
  222699. currentInputChans.clear();
  222700. if (inputChannels.getHighestBit() >= 0)
  222701. {
  222702. for (int i = 0; i <= jmax (inputChannels.getHighestBit(), (int) minChansIn); ++i)
  222703. {
  222704. if (inputChannels[i])
  222705. {
  222706. inputChannelDataForCallback.add (inputChannelBuffer.getSampleData (i));
  222707. currentInputChans.setBit (i);
  222708. }
  222709. }
  222710. }
  222711. outputChannelBuffer.setSize (jmax ((int) minChansOut, outputChannels.getHighestBit()) + 1, bufferSize);
  222712. outputChannelBuffer.clear();
  222713. outputChannelDataForCallback.clear();
  222714. currentOutputChans.clear();
  222715. if (outputChannels.getHighestBit() >= 0)
  222716. {
  222717. for (int i = 0; i <= jmax (outputChannels.getHighestBit(), (int) minChansOut); ++i)
  222718. {
  222719. if (outputChannels[i])
  222720. {
  222721. outputChannelDataForCallback.add (outputChannelBuffer.getSampleData (i));
  222722. currentOutputChans.setBit (i);
  222723. }
  222724. }
  222725. }
  222726. if (outputChannelDataForCallback.size() > 0 && outputId.isNotEmpty())
  222727. {
  222728. outputDevice = new ALSADevice (outputId, false);
  222729. if (outputDevice->error.isNotEmpty())
  222730. {
  222731. error = outputDevice->error;
  222732. outputDevice = 0;
  222733. return;
  222734. }
  222735. currentOutputChans.setRange (0, minChansOut, true);
  222736. if (! outputDevice->setParameters ((unsigned int) sampleRate,
  222737. jlimit ((int) minChansOut, (int) maxChansOut, currentOutputChans.getHighestBit() + 1),
  222738. bufferSize))
  222739. {
  222740. error = outputDevice->error;
  222741. outputDevice = 0;
  222742. return;
  222743. }
  222744. outputLatency = outputDevice->latency;
  222745. }
  222746. if (inputChannelDataForCallback.size() > 0 && inputId.isNotEmpty())
  222747. {
  222748. inputDevice = new ALSADevice (inputId, true);
  222749. if (inputDevice->error.isNotEmpty())
  222750. {
  222751. error = inputDevice->error;
  222752. inputDevice = 0;
  222753. return;
  222754. }
  222755. currentInputChans.setRange (0, minChansIn, true);
  222756. if (! inputDevice->setParameters ((unsigned int) sampleRate,
  222757. jlimit ((int) minChansIn, (int) maxChansIn, currentInputChans.getHighestBit() + 1),
  222758. bufferSize))
  222759. {
  222760. error = inputDevice->error;
  222761. inputDevice = 0;
  222762. return;
  222763. }
  222764. inputLatency = inputDevice->latency;
  222765. }
  222766. if (outputDevice == 0 && inputDevice == 0)
  222767. {
  222768. error = "no channels";
  222769. return;
  222770. }
  222771. if (outputDevice != 0 && inputDevice != 0)
  222772. {
  222773. snd_pcm_link (outputDevice->handle, inputDevice->handle);
  222774. }
  222775. if (inputDevice != 0 && failed (snd_pcm_prepare (inputDevice->handle)))
  222776. return;
  222777. if (outputDevice != 0 && failed (snd_pcm_prepare (outputDevice->handle)))
  222778. return;
  222779. startThread (9);
  222780. int count = 1000;
  222781. while (numCallbacks == 0)
  222782. {
  222783. sleep (5);
  222784. if (--count < 0 || ! isThreadRunning())
  222785. {
  222786. error = "device didn't start";
  222787. break;
  222788. }
  222789. }
  222790. }
  222791. void close()
  222792. {
  222793. stopThread (6000);
  222794. inputDevice = 0;
  222795. outputDevice = 0;
  222796. inputChannelBuffer.setSize (1, 1);
  222797. outputChannelBuffer.setSize (1, 1);
  222798. numCallbacks = 0;
  222799. }
  222800. void setCallback (AudioIODeviceCallback* const newCallback) throw()
  222801. {
  222802. const ScopedLock sl (callbackLock);
  222803. callback = newCallback;
  222804. }
  222805. void run()
  222806. {
  222807. while (! threadShouldExit())
  222808. {
  222809. if (inputDevice != 0)
  222810. {
  222811. if (! inputDevice->readFromInputDevice (inputChannelBuffer, bufferSize))
  222812. {
  222813. DBG ("ALSA: read failure");
  222814. break;
  222815. }
  222816. }
  222817. if (threadShouldExit())
  222818. break;
  222819. {
  222820. const ScopedLock sl (callbackLock);
  222821. ++numCallbacks;
  222822. if (callback != 0)
  222823. {
  222824. callback->audioDeviceIOCallback ((const float**) inputChannelDataForCallback.getRawDataPointer(),
  222825. inputChannelDataForCallback.size(),
  222826. outputChannelDataForCallback.getRawDataPointer(),
  222827. outputChannelDataForCallback.size(),
  222828. bufferSize);
  222829. }
  222830. else
  222831. {
  222832. for (int i = 0; i < outputChannelDataForCallback.size(); ++i)
  222833. zeromem (outputChannelDataForCallback[i], sizeof (float) * bufferSize);
  222834. }
  222835. }
  222836. if (outputDevice != 0)
  222837. {
  222838. failed (snd_pcm_wait (outputDevice->handle, 2000));
  222839. if (threadShouldExit())
  222840. break;
  222841. failed (snd_pcm_avail_update (outputDevice->handle));
  222842. if (! outputDevice->writeToOutputDevice (outputChannelBuffer, bufferSize))
  222843. {
  222844. DBG ("ALSA: write failure");
  222845. break;
  222846. }
  222847. }
  222848. }
  222849. }
  222850. int getBitDepth() const throw()
  222851. {
  222852. if (outputDevice != 0)
  222853. return outputDevice->bitDepth;
  222854. if (inputDevice != 0)
  222855. return inputDevice->bitDepth;
  222856. return 16;
  222857. }
  222858. juce_UseDebuggingNewOperator
  222859. String error;
  222860. double sampleRate;
  222861. int bufferSize, outputLatency, inputLatency;
  222862. BigInteger currentInputChans, currentOutputChans;
  222863. Array <int> sampleRates;
  222864. StringArray channelNamesOut, channelNamesIn;
  222865. AudioIODeviceCallback* callback;
  222866. private:
  222867. const String inputId, outputId;
  222868. ScopedPointer<ALSADevice> outputDevice, inputDevice;
  222869. int numCallbacks;
  222870. CriticalSection callbackLock;
  222871. AudioSampleBuffer inputChannelBuffer, outputChannelBuffer;
  222872. Array<float*> inputChannelDataForCallback, outputChannelDataForCallback;
  222873. unsigned int minChansOut, maxChansOut;
  222874. unsigned int minChansIn, maxChansIn;
  222875. bool failed (const int errorNum)
  222876. {
  222877. if (errorNum >= 0)
  222878. return false;
  222879. error = snd_strerror (errorNum);
  222880. DBG ("ALSA error: " + error + "\n");
  222881. return true;
  222882. }
  222883. void initialiseRatesAndChannels()
  222884. {
  222885. sampleRates.clear();
  222886. channelNamesOut.clear();
  222887. channelNamesIn.clear();
  222888. minChansOut = 0;
  222889. maxChansOut = 0;
  222890. minChansIn = 0;
  222891. maxChansIn = 0;
  222892. unsigned int dummy = 0;
  222893. getDeviceProperties (inputId, dummy, dummy, minChansIn, maxChansIn, sampleRates);
  222894. getDeviceProperties (outputId, minChansOut, maxChansOut, dummy, dummy, sampleRates);
  222895. unsigned int i;
  222896. for (i = 0; i < maxChansOut; ++i)
  222897. channelNamesOut.add ("channel " + String ((int) i + 1));
  222898. for (i = 0; i < maxChansIn; ++i)
  222899. channelNamesIn.add ("channel " + String ((int) i + 1));
  222900. }
  222901. };
  222902. class ALSAAudioIODevice : public AudioIODevice
  222903. {
  222904. public:
  222905. ALSAAudioIODevice (const String& deviceName,
  222906. const String& inputId_,
  222907. const String& outputId_)
  222908. : AudioIODevice (deviceName, "ALSA"),
  222909. inputId (inputId_),
  222910. outputId (outputId_),
  222911. isOpen_ (false),
  222912. isStarted (false),
  222913. internal (inputId_, outputId_)
  222914. {
  222915. }
  222916. ~ALSAAudioIODevice()
  222917. {
  222918. }
  222919. const StringArray getOutputChannelNames() { return internal.channelNamesOut; }
  222920. const StringArray getInputChannelNames() { return internal.channelNamesIn; }
  222921. int getNumSampleRates() { return internal.sampleRates.size(); }
  222922. double getSampleRate (int index) { return internal.sampleRates [index]; }
  222923. int getDefaultBufferSize() { return 512; }
  222924. int getNumBufferSizesAvailable() { return 50; }
  222925. int getBufferSizeSamples (int index)
  222926. {
  222927. int n = 16;
  222928. for (int i = 0; i < index; ++i)
  222929. n += n < 64 ? 16
  222930. : (n < 512 ? 32
  222931. : (n < 1024 ? 64
  222932. : (n < 2048 ? 128 : 256)));
  222933. return n;
  222934. }
  222935. const String open (const BigInteger& inputChannels,
  222936. const BigInteger& outputChannels,
  222937. double sampleRate,
  222938. int bufferSizeSamples)
  222939. {
  222940. close();
  222941. if (bufferSizeSamples <= 0)
  222942. bufferSizeSamples = getDefaultBufferSize();
  222943. if (sampleRate <= 0)
  222944. {
  222945. for (int i = 0; i < getNumSampleRates(); ++i)
  222946. {
  222947. if (getSampleRate (i) >= 44100)
  222948. {
  222949. sampleRate = getSampleRate (i);
  222950. break;
  222951. }
  222952. }
  222953. }
  222954. internal.open (inputChannels, outputChannels,
  222955. sampleRate, bufferSizeSamples);
  222956. isOpen_ = internal.error.isEmpty();
  222957. return internal.error;
  222958. }
  222959. void close()
  222960. {
  222961. stop();
  222962. internal.close();
  222963. isOpen_ = false;
  222964. }
  222965. bool isOpen() { return isOpen_; }
  222966. bool isPlaying() { return isStarted && internal.error.isEmpty(); }
  222967. const String getLastError() { return internal.error; }
  222968. int getCurrentBufferSizeSamples() { return internal.bufferSize; }
  222969. double getCurrentSampleRate() { return internal.sampleRate; }
  222970. int getCurrentBitDepth() { return internal.getBitDepth(); }
  222971. const BigInteger getActiveOutputChannels() const { return internal.currentOutputChans; }
  222972. const BigInteger getActiveInputChannels() const { return internal.currentInputChans; }
  222973. int getOutputLatencyInSamples() { return internal.outputLatency; }
  222974. int getInputLatencyInSamples() { return internal.inputLatency; }
  222975. void start (AudioIODeviceCallback* callback)
  222976. {
  222977. if (! isOpen_)
  222978. callback = 0;
  222979. if (callback != 0)
  222980. callback->audioDeviceAboutToStart (this);
  222981. internal.setCallback (callback);
  222982. isStarted = (callback != 0);
  222983. }
  222984. void stop()
  222985. {
  222986. AudioIODeviceCallback* const oldCallback = internal.callback;
  222987. start (0);
  222988. if (oldCallback != 0)
  222989. oldCallback->audioDeviceStopped();
  222990. }
  222991. String inputId, outputId;
  222992. private:
  222993. bool isOpen_, isStarted;
  222994. ALSAThread internal;
  222995. };
  222996. class ALSAAudioIODeviceType : public AudioIODeviceType
  222997. {
  222998. public:
  222999. ALSAAudioIODeviceType()
  223000. : AudioIODeviceType ("ALSA"),
  223001. hasScanned (false)
  223002. {
  223003. }
  223004. ~ALSAAudioIODeviceType()
  223005. {
  223006. }
  223007. void scanForDevices()
  223008. {
  223009. if (hasScanned)
  223010. return;
  223011. hasScanned = true;
  223012. inputNames.clear();
  223013. inputIds.clear();
  223014. outputNames.clear();
  223015. outputIds.clear();
  223016. /* void** hints = 0;
  223017. if (snd_device_name_hint (-1, "pcm", &hints) >= 0)
  223018. {
  223019. for (void** hint = hints; *hint != 0; ++hint)
  223020. {
  223021. const String name (getHint (*hint, "NAME"));
  223022. if (name.isNotEmpty())
  223023. {
  223024. const String ioid (getHint (*hint, "IOID"));
  223025. String desc (getHint (*hint, "DESC"));
  223026. if (desc.isEmpty())
  223027. desc = name;
  223028. desc = desc.replaceCharacters ("\n\r", " ");
  223029. DBG ("name: " << name << "\ndesc: " << desc << "\nIO: " << ioid);
  223030. if (ioid.isEmpty() || ioid == "Input")
  223031. {
  223032. inputNames.add (desc);
  223033. inputIds.add (name);
  223034. }
  223035. if (ioid.isEmpty() || ioid == "Output")
  223036. {
  223037. outputNames.add (desc);
  223038. outputIds.add (name);
  223039. }
  223040. }
  223041. }
  223042. snd_device_name_free_hint (hints);
  223043. }
  223044. */
  223045. snd_ctl_t* handle = 0;
  223046. snd_ctl_card_info_t* info = 0;
  223047. snd_ctl_card_info_alloca (&info);
  223048. int cardNum = -1;
  223049. while (outputIds.size() + inputIds.size() <= 32)
  223050. {
  223051. snd_card_next (&cardNum);
  223052. if (cardNum < 0)
  223053. break;
  223054. if (snd_ctl_open (&handle, ("hw:" + String (cardNum)).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  223055. {
  223056. if (snd_ctl_card_info (handle, info) >= 0)
  223057. {
  223058. String cardId (snd_ctl_card_info_get_id (info));
  223059. if (cardId.removeCharacters ("0123456789").isEmpty())
  223060. cardId = String (cardNum);
  223061. int device = -1;
  223062. for (;;)
  223063. {
  223064. if (snd_ctl_pcm_next_device (handle, &device) < 0 || device < 0)
  223065. break;
  223066. String id, name;
  223067. id << "hw:" << cardId << ',' << device;
  223068. bool isInput, isOutput;
  223069. if (testDevice (id, isInput, isOutput))
  223070. {
  223071. name << snd_ctl_card_info_get_name (info);
  223072. if (name.isEmpty())
  223073. name = id;
  223074. if (isInput)
  223075. {
  223076. inputNames.add (name);
  223077. inputIds.add (id);
  223078. }
  223079. if (isOutput)
  223080. {
  223081. outputNames.add (name);
  223082. outputIds.add (id);
  223083. }
  223084. }
  223085. }
  223086. }
  223087. snd_ctl_close (handle);
  223088. }
  223089. }
  223090. inputNames.appendNumbersToDuplicates (false, true);
  223091. outputNames.appendNumbersToDuplicates (false, true);
  223092. }
  223093. const StringArray getDeviceNames (bool wantInputNames) const
  223094. {
  223095. jassert (hasScanned); // need to call scanForDevices() before doing this
  223096. return wantInputNames ? inputNames : outputNames;
  223097. }
  223098. int getDefaultDeviceIndex (bool forInput) const
  223099. {
  223100. jassert (hasScanned); // need to call scanForDevices() before doing this
  223101. return 0;
  223102. }
  223103. bool hasSeparateInputsAndOutputs() const { return true; }
  223104. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  223105. {
  223106. jassert (hasScanned); // need to call scanForDevices() before doing this
  223107. ALSAAudioIODevice* d = dynamic_cast <ALSAAudioIODevice*> (device);
  223108. if (d == 0)
  223109. return -1;
  223110. return asInput ? inputIds.indexOf (d->inputId)
  223111. : outputIds.indexOf (d->outputId);
  223112. }
  223113. AudioIODevice* createDevice (const String& outputDeviceName,
  223114. const String& inputDeviceName)
  223115. {
  223116. jassert (hasScanned); // need to call scanForDevices() before doing this
  223117. const int inputIndex = inputNames.indexOf (inputDeviceName);
  223118. const int outputIndex = outputNames.indexOf (outputDeviceName);
  223119. String deviceName (outputIndex >= 0 ? outputDeviceName
  223120. : inputDeviceName);
  223121. if (inputIndex >= 0 || outputIndex >= 0)
  223122. return new ALSAAudioIODevice (deviceName,
  223123. inputIds [inputIndex],
  223124. outputIds [outputIndex]);
  223125. return 0;
  223126. }
  223127. juce_UseDebuggingNewOperator
  223128. private:
  223129. StringArray inputNames, outputNames, inputIds, outputIds;
  223130. bool hasScanned;
  223131. static bool testDevice (const String& id, bool& isInput, bool& isOutput)
  223132. {
  223133. unsigned int minChansOut = 0, maxChansOut = 0;
  223134. unsigned int minChansIn = 0, maxChansIn = 0;
  223135. Array <int> rates;
  223136. getDeviceProperties (id, minChansOut, maxChansOut, minChansIn, maxChansIn, rates);
  223137. DBG ("ALSA device: " + id
  223138. + " outs=" + String ((int) minChansOut) + "-" + String ((int) maxChansOut)
  223139. + " ins=" + String ((int) minChansIn) + "-" + String ((int) maxChansIn)
  223140. + " rates=" + String (rates.size()));
  223141. isInput = maxChansIn > 0;
  223142. isOutput = maxChansOut > 0;
  223143. return (isInput || isOutput) && rates.size() > 0;
  223144. }
  223145. /*static const String getHint (void* hint, const char* type)
  223146. {
  223147. char* const n = snd_device_name_get_hint (hint, type);
  223148. const String s ((const char*) n);
  223149. free (n);
  223150. return s;
  223151. }*/
  223152. ALSAAudioIODeviceType (const ALSAAudioIODeviceType&);
  223153. ALSAAudioIODeviceType& operator= (const ALSAAudioIODeviceType&);
  223154. };
  223155. AudioIODeviceType* juce_createAudioIODeviceType_ALSA()
  223156. {
  223157. return new ALSAAudioIODeviceType();
  223158. }
  223159. #endif
  223160. /*** End of inlined file: juce_linux_Audio.cpp ***/
  223161. /*** Start of inlined file: juce_linux_JackAudio.cpp ***/
  223162. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223163. // compiled on its own).
  223164. #ifdef JUCE_INCLUDED_FILE
  223165. #if JUCE_JACK
  223166. static void* juce_libjack_handle = 0;
  223167. void* juce_load_jack_function (const char* const name)
  223168. {
  223169. if (juce_libjack_handle == 0)
  223170. return 0;
  223171. return dlsym (juce_libjack_handle, name);
  223172. }
  223173. #define JUCE_DECL_JACK_FUNCTION(return_type, fn_name, argument_types, arguments) \
  223174. typedef return_type (*fn_name##_ptr_t)argument_types; \
  223175. return_type fn_name argument_types { \
  223176. static fn_name##_ptr_t fn = 0; \
  223177. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  223178. if (fn) return (*fn)arguments; \
  223179. else return 0; \
  223180. }
  223181. #define JUCE_DECL_VOID_JACK_FUNCTION(fn_name, argument_types, arguments) \
  223182. typedef void (*fn_name##_ptr_t)argument_types; \
  223183. void fn_name argument_types { \
  223184. static fn_name##_ptr_t fn = 0; \
  223185. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  223186. if (fn) (*fn)arguments; \
  223187. }
  223188. 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));
  223189. JUCE_DECL_JACK_FUNCTION (int, jack_client_close, (jack_client_t *client), (client));
  223190. JUCE_DECL_JACK_FUNCTION (int, jack_activate, (jack_client_t* client), (client));
  223191. JUCE_DECL_JACK_FUNCTION (int, jack_deactivate, (jack_client_t* client), (client));
  223192. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_buffer_size, (jack_client_t* client), (client));
  223193. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_sample_rate, (jack_client_t* client), (client));
  223194. JUCE_DECL_VOID_JACK_FUNCTION (jack_on_shutdown, (jack_client_t* client, void (*function)(void* arg), void* arg), (client, function, arg));
  223195. JUCE_DECL_JACK_FUNCTION (void* , jack_port_get_buffer, (jack_port_t* port, jack_nframes_t nframes), (port, nframes));
  223196. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_port_get_total_latency, (jack_client_t* client, jack_port_t* port), (client, port));
  223197. 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));
  223198. JUCE_DECL_VOID_JACK_FUNCTION (jack_set_error_function, (void (*func)(const char*)), (func));
  223199. JUCE_DECL_JACK_FUNCTION (int, jack_set_process_callback, (jack_client_t* client, JackProcessCallback process_callback, void* arg), (client, process_callback, arg));
  223200. 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));
  223201. JUCE_DECL_JACK_FUNCTION (int, jack_connect, (jack_client_t* client, const char* source_port, const char* destination_port), (client, source_port, destination_port));
  223202. JUCE_DECL_JACK_FUNCTION (const char*, jack_port_name, (const jack_port_t* port), (port));
  223203. JUCE_DECL_JACK_FUNCTION (int, jack_set_port_connect_callback, (jack_client_t* client, JackPortConnectCallback connect_callback, void* arg), (client, connect_callback, arg));
  223204. JUCE_DECL_JACK_FUNCTION (jack_port_t* , jack_port_by_id, (jack_client_t* client, jack_port_id_t port_id), (client, port_id));
  223205. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected, (const jack_port_t* port), (port));
  223206. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected_to, (const jack_port_t* port, const char* port_name), (port, port_name));
  223207. #if JUCE_DEBUG
  223208. #define JACK_LOGGING_ENABLED 1
  223209. #endif
  223210. #if JACK_LOGGING_ENABLED
  223211. static void jack_Log (const String& s)
  223212. {
  223213. std::cerr << s << std::endl;
  223214. }
  223215. static void dumpJackErrorMessage (const jack_status_t status)
  223216. {
  223217. if (status & JackServerFailed || status & JackServerError) jack_Log ("Unable to connect to JACK server");
  223218. if (status & JackVersionError) jack_Log ("Client's protocol version does not match");
  223219. if (status & JackInvalidOption) jack_Log ("The operation contained an invalid or unsupported option");
  223220. if (status & JackNameNotUnique) jack_Log ("The desired client name was not unique");
  223221. if (status & JackNoSuchClient) jack_Log ("Requested client does not exist");
  223222. if (status & JackInitFailure) jack_Log ("Unable to initialize client");
  223223. }
  223224. #else
  223225. #define dumpJackErrorMessage(a) {}
  223226. #define jack_Log(...) {}
  223227. #endif
  223228. #ifndef JUCE_JACK_CLIENT_NAME
  223229. #define JUCE_JACK_CLIENT_NAME "JuceJack"
  223230. #endif
  223231. class JackAudioIODevice : public AudioIODevice
  223232. {
  223233. public:
  223234. JackAudioIODevice (const String& deviceName,
  223235. const String& inputId_,
  223236. const String& outputId_)
  223237. : AudioIODevice (deviceName, "JACK"),
  223238. inputId (inputId_),
  223239. outputId (outputId_),
  223240. isOpen_ (false),
  223241. callback (0),
  223242. totalNumberOfInputChannels (0),
  223243. totalNumberOfOutputChannels (0)
  223244. {
  223245. jassert (deviceName.isNotEmpty());
  223246. jack_status_t status;
  223247. client = JUCE_NAMESPACE::jack_client_open (JUCE_JACK_CLIENT_NAME, JackNoStartServer, &status);
  223248. if (client == 0)
  223249. {
  223250. dumpJackErrorMessage (status);
  223251. }
  223252. else
  223253. {
  223254. JUCE_NAMESPACE::jack_set_error_function (errorCallback);
  223255. // open input ports
  223256. const StringArray inputChannels (getInputChannelNames());
  223257. for (int i = 0; i < inputChannels.size(); i++)
  223258. {
  223259. String inputName;
  223260. inputName << "in_" << ++totalNumberOfInputChannels;
  223261. inputPorts.add (JUCE_NAMESPACE::jack_port_register (client, inputName.toUTF8(),
  223262. JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0));
  223263. }
  223264. // open output ports
  223265. const StringArray outputChannels (getOutputChannelNames());
  223266. for (int i = 0; i < outputChannels.size (); i++)
  223267. {
  223268. String outputName;
  223269. outputName << "out_" << ++totalNumberOfOutputChannels;
  223270. outputPorts.add (JUCE_NAMESPACE::jack_port_register (client, outputName.toUTF8(),
  223271. JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0));
  223272. }
  223273. inChans.calloc (totalNumberOfInputChannels + 2);
  223274. outChans.calloc (totalNumberOfOutputChannels + 2);
  223275. }
  223276. }
  223277. ~JackAudioIODevice()
  223278. {
  223279. close();
  223280. if (client != 0)
  223281. {
  223282. JUCE_NAMESPACE::jack_client_close (client);
  223283. client = 0;
  223284. }
  223285. }
  223286. const StringArray getChannelNames (bool forInput) const
  223287. {
  223288. StringArray names;
  223289. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */
  223290. forInput ? JackPortIsInput : JackPortIsOutput);
  223291. if (ports != 0)
  223292. {
  223293. int j = 0;
  223294. while (ports[j] != 0)
  223295. {
  223296. const String portName (ports [j++]);
  223297. if (portName.upToFirstOccurrenceOf (":", false, false) == getName())
  223298. names.add (portName.fromFirstOccurrenceOf (":", false, false));
  223299. }
  223300. free (ports);
  223301. }
  223302. return names;
  223303. }
  223304. const StringArray getOutputChannelNames() { return getChannelNames (false); }
  223305. const StringArray getInputChannelNames() { return getChannelNames (true); }
  223306. int getNumSampleRates() { return client != 0 ? 1 : 0; }
  223307. double getSampleRate (int index) { return client != 0 ? JUCE_NAMESPACE::jack_get_sample_rate (client) : 0; }
  223308. int getNumBufferSizesAvailable() { return client != 0 ? 1 : 0; }
  223309. int getBufferSizeSamples (int index) { return getDefaultBufferSize(); }
  223310. int getDefaultBufferSize() { return client != 0 ? JUCE_NAMESPACE::jack_get_buffer_size (client) : 0; }
  223311. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  223312. double sampleRate, int bufferSizeSamples)
  223313. {
  223314. if (client == 0)
  223315. {
  223316. lastError = "No JACK client running";
  223317. return lastError;
  223318. }
  223319. lastError = String::empty;
  223320. close();
  223321. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, this);
  223322. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, this);
  223323. JUCE_NAMESPACE::jack_activate (client);
  223324. isOpen_ = true;
  223325. if (! inputChannels.isZero())
  223326. {
  223327. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  223328. if (ports != 0)
  223329. {
  223330. const int numInputChannels = inputChannels.getHighestBit() + 1;
  223331. for (int i = 0; i < numInputChannels; ++i)
  223332. {
  223333. const String portName (ports[i]);
  223334. if (inputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  223335. {
  223336. int error = JUCE_NAMESPACE::jack_connect (client, ports[i], JUCE_NAMESPACE::jack_port_name ((jack_port_t*) inputPorts[i]));
  223337. if (error != 0)
  223338. jack_Log ("Cannot connect input port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  223339. }
  223340. }
  223341. free (ports);
  223342. }
  223343. }
  223344. if (! outputChannels.isZero())
  223345. {
  223346. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  223347. if (ports != 0)
  223348. {
  223349. const int numOutputChannels = outputChannels.getHighestBit() + 1;
  223350. for (int i = 0; i < numOutputChannels; ++i)
  223351. {
  223352. const String portName (ports[i]);
  223353. if (outputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  223354. {
  223355. int error = JUCE_NAMESPACE::jack_connect (client, JUCE_NAMESPACE::jack_port_name ((jack_port_t*) outputPorts[i]), ports[i]);
  223356. if (error != 0)
  223357. jack_Log ("Cannot connect output port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  223358. }
  223359. }
  223360. free (ports);
  223361. }
  223362. }
  223363. return lastError;
  223364. }
  223365. void close()
  223366. {
  223367. stop();
  223368. if (client != 0)
  223369. {
  223370. JUCE_NAMESPACE::jack_deactivate (client);
  223371. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, 0);
  223372. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, 0);
  223373. }
  223374. isOpen_ = false;
  223375. }
  223376. void start (AudioIODeviceCallback* newCallback)
  223377. {
  223378. if (isOpen_ && newCallback != callback)
  223379. {
  223380. if (newCallback != 0)
  223381. newCallback->audioDeviceAboutToStart (this);
  223382. AudioIODeviceCallback* const oldCallback = callback;
  223383. {
  223384. const ScopedLock sl (callbackLock);
  223385. callback = newCallback;
  223386. }
  223387. if (oldCallback != 0)
  223388. oldCallback->audioDeviceStopped();
  223389. }
  223390. }
  223391. void stop()
  223392. {
  223393. start (0);
  223394. }
  223395. bool isOpen() { return isOpen_; }
  223396. bool isPlaying() { return callback != 0; }
  223397. int getCurrentBufferSizeSamples() { return getBufferSizeSamples (0); }
  223398. double getCurrentSampleRate() { return getSampleRate (0); }
  223399. int getCurrentBitDepth() { return 32; }
  223400. const String getLastError() { return lastError; }
  223401. const BigInteger getActiveOutputChannels() const
  223402. {
  223403. BigInteger outputBits;
  223404. for (int i = 0; i < outputPorts.size(); i++)
  223405. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) outputPorts [i]))
  223406. outputBits.setBit (i);
  223407. return outputBits;
  223408. }
  223409. const BigInteger getActiveInputChannels() const
  223410. {
  223411. BigInteger inputBits;
  223412. for (int i = 0; i < inputPorts.size(); i++)
  223413. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) inputPorts [i]))
  223414. inputBits.setBit (i);
  223415. return inputBits;
  223416. }
  223417. int getOutputLatencyInSamples()
  223418. {
  223419. int latency = 0;
  223420. for (int i = 0; i < outputPorts.size(); i++)
  223421. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) outputPorts [i]));
  223422. return latency;
  223423. }
  223424. int getInputLatencyInSamples()
  223425. {
  223426. int latency = 0;
  223427. for (int i = 0; i < inputPorts.size(); i++)
  223428. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) inputPorts [i]));
  223429. return latency;
  223430. }
  223431. String inputId, outputId;
  223432. private:
  223433. void process (const int numSamples)
  223434. {
  223435. int i, numActiveInChans = 0, numActiveOutChans = 0;
  223436. for (i = 0; i < totalNumberOfInputChannels; ++i)
  223437. {
  223438. jack_default_audio_sample_t* in
  223439. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) inputPorts.getUnchecked(i), numSamples);
  223440. if (in != 0)
  223441. inChans [numActiveInChans++] = (float*) in;
  223442. }
  223443. for (i = 0; i < totalNumberOfOutputChannels; ++i)
  223444. {
  223445. jack_default_audio_sample_t* out
  223446. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) outputPorts.getUnchecked(i), numSamples);
  223447. if (out != 0)
  223448. outChans [numActiveOutChans++] = (float*) out;
  223449. }
  223450. const ScopedLock sl (callbackLock);
  223451. if (callback != 0)
  223452. {
  223453. callback->audioDeviceIOCallback (const_cast<const float**> (inChans.getData()), numActiveInChans,
  223454. outChans, numActiveOutChans, numSamples);
  223455. }
  223456. else
  223457. {
  223458. for (i = 0; i < numActiveOutChans; ++i)
  223459. zeromem (outChans[i], sizeof (float) * numSamples);
  223460. }
  223461. }
  223462. static int processCallback (jack_nframes_t nframes, void* callbackArgument)
  223463. {
  223464. if (callbackArgument != 0)
  223465. ((JackAudioIODevice*) callbackArgument)->process (nframes);
  223466. return 0;
  223467. }
  223468. static void threadInitCallback (void* callbackArgument)
  223469. {
  223470. jack_Log ("JackAudioIODevice::initialise");
  223471. }
  223472. static void shutdownCallback (void* callbackArgument)
  223473. {
  223474. jack_Log ("JackAudioIODevice::shutdown");
  223475. JackAudioIODevice* device = (JackAudioIODevice*) callbackArgument;
  223476. if (device != 0)
  223477. {
  223478. device->client = 0;
  223479. device->close();
  223480. }
  223481. }
  223482. static void errorCallback (const char* msg)
  223483. {
  223484. jack_Log ("JackAudioIODevice::errorCallback " + String (msg));
  223485. }
  223486. bool isOpen_;
  223487. jack_client_t* client;
  223488. String lastError;
  223489. AudioIODeviceCallback* callback;
  223490. CriticalSection callbackLock;
  223491. HeapBlock <float*> inChans, outChans;
  223492. int totalNumberOfInputChannels;
  223493. int totalNumberOfOutputChannels;
  223494. Array<void*> inputPorts, outputPorts;
  223495. };
  223496. class JackAudioIODeviceType : public AudioIODeviceType
  223497. {
  223498. public:
  223499. JackAudioIODeviceType()
  223500. : AudioIODeviceType ("JACK"),
  223501. hasScanned (false)
  223502. {
  223503. }
  223504. ~JackAudioIODeviceType()
  223505. {
  223506. }
  223507. void scanForDevices()
  223508. {
  223509. hasScanned = true;
  223510. inputNames.clear();
  223511. inputIds.clear();
  223512. outputNames.clear();
  223513. outputIds.clear();
  223514. if (juce_libjack_handle == 0)
  223515. {
  223516. juce_libjack_handle = dlopen ("libjack.so", RTLD_LAZY);
  223517. if (juce_libjack_handle == 0)
  223518. return;
  223519. }
  223520. // open a dummy client
  223521. jack_status_t status;
  223522. jack_client_t* client = JUCE_NAMESPACE::jack_client_open ("JuceJackDummy", JackNoStartServer, &status);
  223523. if (client == 0)
  223524. {
  223525. dumpJackErrorMessage (status);
  223526. }
  223527. else
  223528. {
  223529. // scan for output devices
  223530. const char** ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  223531. if (ports != 0)
  223532. {
  223533. int j = 0;
  223534. while (ports[j] != 0)
  223535. {
  223536. String clientName (ports[j]);
  223537. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  223538. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  223539. && ! inputNames.contains (clientName))
  223540. {
  223541. inputNames.add (clientName);
  223542. inputIds.add (ports [j]);
  223543. }
  223544. ++j;
  223545. }
  223546. free (ports);
  223547. }
  223548. // scan for input devices
  223549. ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  223550. if (ports != 0)
  223551. {
  223552. int j = 0;
  223553. while (ports[j] != 0)
  223554. {
  223555. String clientName (ports[j]);
  223556. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  223557. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  223558. && ! outputNames.contains (clientName))
  223559. {
  223560. outputNames.add (clientName);
  223561. outputIds.add (ports [j]);
  223562. }
  223563. ++j;
  223564. }
  223565. free (ports);
  223566. }
  223567. JUCE_NAMESPACE::jack_client_close (client);
  223568. }
  223569. }
  223570. const StringArray getDeviceNames (bool wantInputNames) const
  223571. {
  223572. jassert (hasScanned); // need to call scanForDevices() before doing this
  223573. return wantInputNames ? inputNames : outputNames;
  223574. }
  223575. int getDefaultDeviceIndex (bool forInput) const
  223576. {
  223577. jassert (hasScanned); // need to call scanForDevices() before doing this
  223578. return 0;
  223579. }
  223580. bool hasSeparateInputsAndOutputs() const { return true; }
  223581. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  223582. {
  223583. jassert (hasScanned); // need to call scanForDevices() before doing this
  223584. JackAudioIODevice* d = dynamic_cast <JackAudioIODevice*> (device);
  223585. if (d == 0)
  223586. return -1;
  223587. return asInput ? inputIds.indexOf (d->inputId)
  223588. : outputIds.indexOf (d->outputId);
  223589. }
  223590. AudioIODevice* createDevice (const String& outputDeviceName,
  223591. const String& inputDeviceName)
  223592. {
  223593. jassert (hasScanned); // need to call scanForDevices() before doing this
  223594. const int inputIndex = inputNames.indexOf (inputDeviceName);
  223595. const int outputIndex = outputNames.indexOf (outputDeviceName);
  223596. if (inputIndex >= 0 || outputIndex >= 0)
  223597. return new JackAudioIODevice (outputIndex >= 0 ? outputDeviceName
  223598. : inputDeviceName,
  223599. inputIds [inputIndex],
  223600. outputIds [outputIndex]);
  223601. return 0;
  223602. }
  223603. juce_UseDebuggingNewOperator
  223604. private:
  223605. StringArray inputNames, outputNames, inputIds, outputIds;
  223606. bool hasScanned;
  223607. JackAudioIODeviceType (const JackAudioIODeviceType&);
  223608. JackAudioIODeviceType& operator= (const JackAudioIODeviceType&);
  223609. };
  223610. AudioIODeviceType* juce_createAudioIODeviceType_JACK()
  223611. {
  223612. return new JackAudioIODeviceType();
  223613. }
  223614. #else // if JACK is turned off..
  223615. AudioIODeviceType* juce_createAudioIODeviceType_JACK() { return 0; }
  223616. #endif
  223617. #endif
  223618. /*** End of inlined file: juce_linux_JackAudio.cpp ***/
  223619. /*** Start of inlined file: juce_linux_Midi.cpp ***/
  223620. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223621. // compiled on its own).
  223622. #if JUCE_INCLUDED_FILE
  223623. #if JUCE_ALSA
  223624. static snd_seq_t* iterateMidiDevices (const bool forInput,
  223625. StringArray& deviceNamesFound,
  223626. const int deviceIndexToOpen)
  223627. {
  223628. snd_seq_t* returnedHandle = 0;
  223629. snd_seq_t* seqHandle;
  223630. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  223631. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  223632. {
  223633. snd_seq_system_info_t* systemInfo;
  223634. snd_seq_client_info_t* clientInfo;
  223635. if (snd_seq_system_info_malloc (&systemInfo) == 0)
  223636. {
  223637. if (snd_seq_system_info (seqHandle, systemInfo) == 0
  223638. && snd_seq_client_info_malloc (&clientInfo) == 0)
  223639. {
  223640. int numClients = snd_seq_system_info_get_cur_clients (systemInfo);
  223641. while (--numClients >= 0 && returnedHandle == 0)
  223642. {
  223643. if (snd_seq_query_next_client (seqHandle, clientInfo) == 0)
  223644. {
  223645. snd_seq_port_info_t* portInfo;
  223646. if (snd_seq_port_info_malloc (&portInfo) == 0)
  223647. {
  223648. int numPorts = snd_seq_client_info_get_num_ports (clientInfo);
  223649. const int client = snd_seq_client_info_get_client (clientInfo);
  223650. snd_seq_port_info_set_client (portInfo, client);
  223651. snd_seq_port_info_set_port (portInfo, -1);
  223652. while (--numPorts >= 0)
  223653. {
  223654. if (snd_seq_query_next_port (seqHandle, portInfo) == 0
  223655. && (snd_seq_port_info_get_capability (portInfo)
  223656. & (forInput ? SND_SEQ_PORT_CAP_READ
  223657. : SND_SEQ_PORT_CAP_WRITE)) != 0)
  223658. {
  223659. deviceNamesFound.add (snd_seq_client_info_get_name (clientInfo));
  223660. if (deviceNamesFound.size() == deviceIndexToOpen + 1)
  223661. {
  223662. const int sourcePort = snd_seq_port_info_get_port (portInfo);
  223663. const int sourceClient = snd_seq_client_info_get_client (clientInfo);
  223664. if (sourcePort != -1)
  223665. {
  223666. snd_seq_set_client_name (seqHandle,
  223667. forInput ? "Juce Midi Input"
  223668. : "Juce Midi Output");
  223669. const int portId
  223670. = snd_seq_create_simple_port (seqHandle,
  223671. forInput ? "Juce Midi In Port"
  223672. : "Juce Midi Out Port",
  223673. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  223674. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  223675. SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  223676. snd_seq_connect_from (seqHandle, portId, sourceClient, sourcePort);
  223677. returnedHandle = seqHandle;
  223678. }
  223679. }
  223680. }
  223681. }
  223682. snd_seq_port_info_free (portInfo);
  223683. }
  223684. }
  223685. }
  223686. snd_seq_client_info_free (clientInfo);
  223687. }
  223688. snd_seq_system_info_free (systemInfo);
  223689. }
  223690. if (returnedHandle == 0)
  223691. snd_seq_close (seqHandle);
  223692. }
  223693. deviceNamesFound.appendNumbersToDuplicates (true, true);
  223694. return returnedHandle;
  223695. }
  223696. static snd_seq_t* createMidiDevice (const bool forInput,
  223697. const String& deviceNameToOpen)
  223698. {
  223699. snd_seq_t* seqHandle = 0;
  223700. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  223701. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  223702. {
  223703. snd_seq_set_client_name (seqHandle,
  223704. (deviceNameToOpen + (forInput ? " Input" : " Output")).toCString());
  223705. const int portId
  223706. = snd_seq_create_simple_port (seqHandle,
  223707. forInput ? "in"
  223708. : "out",
  223709. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  223710. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  223711. forInput ? SND_SEQ_PORT_TYPE_APPLICATION
  223712. : SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  223713. if (portId < 0)
  223714. {
  223715. snd_seq_close (seqHandle);
  223716. seqHandle = 0;
  223717. }
  223718. }
  223719. return seqHandle;
  223720. }
  223721. class MidiOutputDevice
  223722. {
  223723. public:
  223724. MidiOutputDevice (MidiOutput* const midiOutput_,
  223725. snd_seq_t* const seqHandle_)
  223726. :
  223727. midiOutput (midiOutput_),
  223728. seqHandle (seqHandle_),
  223729. maxEventSize (16 * 1024)
  223730. {
  223731. jassert (seqHandle != 0 && midiOutput != 0);
  223732. snd_midi_event_new (maxEventSize, &midiParser);
  223733. }
  223734. ~MidiOutputDevice()
  223735. {
  223736. snd_midi_event_free (midiParser);
  223737. snd_seq_close (seqHandle);
  223738. }
  223739. void sendMessageNow (const MidiMessage& message)
  223740. {
  223741. if (message.getRawDataSize() > maxEventSize)
  223742. {
  223743. maxEventSize = message.getRawDataSize();
  223744. snd_midi_event_free (midiParser);
  223745. snd_midi_event_new (maxEventSize, &midiParser);
  223746. }
  223747. snd_seq_event_t event;
  223748. snd_seq_ev_clear (&event);
  223749. snd_midi_event_encode (midiParser,
  223750. message.getRawData(),
  223751. message.getRawDataSize(),
  223752. &event);
  223753. snd_midi_event_reset_encode (midiParser);
  223754. snd_seq_ev_set_source (&event, 0);
  223755. snd_seq_ev_set_subs (&event);
  223756. snd_seq_ev_set_direct (&event);
  223757. snd_seq_event_output (seqHandle, &event);
  223758. snd_seq_drain_output (seqHandle);
  223759. }
  223760. juce_UseDebuggingNewOperator
  223761. private:
  223762. MidiOutput* const midiOutput;
  223763. snd_seq_t* const seqHandle;
  223764. snd_midi_event_t* midiParser;
  223765. int maxEventSize;
  223766. };
  223767. const StringArray MidiOutput::getDevices()
  223768. {
  223769. StringArray devices;
  223770. iterateMidiDevices (false, devices, -1);
  223771. return devices;
  223772. }
  223773. int MidiOutput::getDefaultDeviceIndex()
  223774. {
  223775. return 0;
  223776. }
  223777. MidiOutput* MidiOutput::openDevice (int deviceIndex)
  223778. {
  223779. MidiOutput* newDevice = 0;
  223780. StringArray devices;
  223781. snd_seq_t* const handle = iterateMidiDevices (false, devices, deviceIndex);
  223782. if (handle != 0)
  223783. {
  223784. newDevice = new MidiOutput();
  223785. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  223786. }
  223787. return newDevice;
  223788. }
  223789. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  223790. {
  223791. MidiOutput* newDevice = 0;
  223792. snd_seq_t* const handle = createMidiDevice (false, deviceName);
  223793. if (handle != 0)
  223794. {
  223795. newDevice = new MidiOutput();
  223796. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  223797. }
  223798. return newDevice;
  223799. }
  223800. MidiOutput::~MidiOutput()
  223801. {
  223802. delete static_cast <MidiOutputDevice*> (internal);
  223803. }
  223804. void MidiOutput::reset()
  223805. {
  223806. }
  223807. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  223808. {
  223809. return false;
  223810. }
  223811. void MidiOutput::setVolume (float leftVol, float rightVol)
  223812. {
  223813. }
  223814. void MidiOutput::sendMessageNow (const MidiMessage& message)
  223815. {
  223816. static_cast <MidiOutputDevice*> (internal)->sendMessageNow (message);
  223817. }
  223818. class MidiInputThread : public Thread
  223819. {
  223820. public:
  223821. MidiInputThread (MidiInput* const midiInput_,
  223822. snd_seq_t* const seqHandle_,
  223823. MidiInputCallback* const callback_)
  223824. : Thread ("Juce MIDI Input"),
  223825. midiInput (midiInput_),
  223826. seqHandle (seqHandle_),
  223827. callback (callback_)
  223828. {
  223829. jassert (seqHandle != 0 && callback != 0 && midiInput != 0);
  223830. }
  223831. ~MidiInputThread()
  223832. {
  223833. snd_seq_close (seqHandle);
  223834. }
  223835. void run()
  223836. {
  223837. const int maxEventSize = 16 * 1024;
  223838. snd_midi_event_t* midiParser;
  223839. if (snd_midi_event_new (maxEventSize, &midiParser) >= 0)
  223840. {
  223841. HeapBlock <uint8> buffer (maxEventSize);
  223842. const int numPfds = snd_seq_poll_descriptors_count (seqHandle, POLLIN);
  223843. struct pollfd* const pfd = (struct pollfd*) alloca (numPfds * sizeof (struct pollfd));
  223844. snd_seq_poll_descriptors (seqHandle, pfd, numPfds, POLLIN);
  223845. while (! threadShouldExit())
  223846. {
  223847. if (poll (pfd, numPfds, 500) > 0)
  223848. {
  223849. snd_seq_event_t* inputEvent = 0;
  223850. snd_seq_nonblock (seqHandle, 1);
  223851. do
  223852. {
  223853. if (snd_seq_event_input (seqHandle, &inputEvent) >= 0)
  223854. {
  223855. // xxx what about SYSEXes that are too big for the buffer?
  223856. const int numBytes = snd_midi_event_decode (midiParser, buffer, maxEventSize, inputEvent);
  223857. snd_midi_event_reset_decode (midiParser);
  223858. if (numBytes > 0)
  223859. {
  223860. const MidiMessage message ((const uint8*) buffer,
  223861. numBytes,
  223862. Time::getMillisecondCounter() * 0.001);
  223863. callback->handleIncomingMidiMessage (midiInput, message);
  223864. }
  223865. snd_seq_free_event (inputEvent);
  223866. }
  223867. }
  223868. while (snd_seq_event_input_pending (seqHandle, 0) > 0);
  223869. snd_seq_free_event (inputEvent);
  223870. }
  223871. }
  223872. snd_midi_event_free (midiParser);
  223873. }
  223874. };
  223875. juce_UseDebuggingNewOperator
  223876. private:
  223877. MidiInput* const midiInput;
  223878. snd_seq_t* const seqHandle;
  223879. MidiInputCallback* const callback;
  223880. };
  223881. MidiInput::MidiInput (const String& name_)
  223882. : name (name_),
  223883. internal (0)
  223884. {
  223885. }
  223886. MidiInput::~MidiInput()
  223887. {
  223888. stop();
  223889. delete static_cast <MidiInputThread*> (internal);
  223890. }
  223891. void MidiInput::start()
  223892. {
  223893. static_cast <MidiInputThread*> (internal)->startThread();
  223894. }
  223895. void MidiInput::stop()
  223896. {
  223897. static_cast <MidiInputThread*> (internal)->stopThread (3000);
  223898. }
  223899. int MidiInput::getDefaultDeviceIndex()
  223900. {
  223901. return 0;
  223902. }
  223903. const StringArray MidiInput::getDevices()
  223904. {
  223905. StringArray devices;
  223906. iterateMidiDevices (true, devices, -1);
  223907. return devices;
  223908. }
  223909. MidiInput* MidiInput::openDevice (int deviceIndex, MidiInputCallback* callback)
  223910. {
  223911. MidiInput* newDevice = 0;
  223912. StringArray devices;
  223913. snd_seq_t* const handle = iterateMidiDevices (true, devices, deviceIndex);
  223914. if (handle != 0)
  223915. {
  223916. newDevice = new MidiInput (devices [deviceIndex]);
  223917. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  223918. }
  223919. return newDevice;
  223920. }
  223921. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  223922. {
  223923. MidiInput* newDevice = 0;
  223924. snd_seq_t* const handle = createMidiDevice (true, deviceName);
  223925. if (handle != 0)
  223926. {
  223927. newDevice = new MidiInput (deviceName);
  223928. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  223929. }
  223930. return newDevice;
  223931. }
  223932. #else
  223933. // (These are just stub functions if ALSA is unavailable...)
  223934. const StringArray MidiOutput::getDevices() { return StringArray(); }
  223935. int MidiOutput::getDefaultDeviceIndex() { return 0; }
  223936. MidiOutput* MidiOutput::openDevice (int) { return 0; }
  223937. MidiOutput* MidiOutput::createNewDevice (const String&) { return 0; }
  223938. MidiOutput::~MidiOutput() {}
  223939. void MidiOutput::reset() {}
  223940. bool MidiOutput::getVolume (float&, float&) { return false; }
  223941. void MidiOutput::setVolume (float, float) {}
  223942. void MidiOutput::sendMessageNow (const MidiMessage&) {}
  223943. MidiInput::MidiInput (const String& name_) : name (name_), internal (0) {}
  223944. MidiInput::~MidiInput() {}
  223945. void MidiInput::start() {}
  223946. void MidiInput::stop() {}
  223947. int MidiInput::getDefaultDeviceIndex() { return 0; }
  223948. const StringArray MidiInput::getDevices() { return StringArray(); }
  223949. MidiInput* MidiInput::openDevice (int, MidiInputCallback*) { return 0; }
  223950. MidiInput* MidiInput::createNewDevice (const String&, MidiInputCallback*) { return 0; }
  223951. #endif
  223952. #endif
  223953. /*** End of inlined file: juce_linux_Midi.cpp ***/
  223954. /*** Start of inlined file: juce_linux_AudioCDReader.cpp ***/
  223955. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223956. // compiled on its own).
  223957. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  223958. AudioCDReader::AudioCDReader()
  223959. : AudioFormatReader (0, "CD Audio")
  223960. {
  223961. }
  223962. const StringArray AudioCDReader::getAvailableCDNames()
  223963. {
  223964. StringArray names;
  223965. return names;
  223966. }
  223967. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  223968. {
  223969. return 0;
  223970. }
  223971. AudioCDReader::~AudioCDReader()
  223972. {
  223973. }
  223974. void AudioCDReader::refreshTrackLengths()
  223975. {
  223976. }
  223977. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  223978. int64 startSampleInFile, int numSamples)
  223979. {
  223980. return false;
  223981. }
  223982. bool AudioCDReader::isCDStillPresent() const
  223983. {
  223984. return false;
  223985. }
  223986. bool AudioCDReader::isTrackAudio (int trackNum) const
  223987. {
  223988. return false;
  223989. }
  223990. void AudioCDReader::enableIndexScanning (bool b)
  223991. {
  223992. }
  223993. int AudioCDReader::getLastIndex() const
  223994. {
  223995. return 0;
  223996. }
  223997. const Array<int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  223998. {
  223999. return Array<int>();
  224000. }
  224001. #endif
  224002. /*** End of inlined file: juce_linux_AudioCDReader.cpp ***/
  224003. /*** Start of inlined file: juce_linux_FileChooser.cpp ***/
  224004. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  224005. // compiled on its own).
  224006. #if JUCE_INCLUDED_FILE
  224007. void FileChooser::showPlatformDialog (Array<File>& results,
  224008. const String& title,
  224009. const File& file,
  224010. const String& filters,
  224011. bool isDirectory,
  224012. bool selectsFiles,
  224013. bool isSave,
  224014. bool warnAboutOverwritingExistingFiles,
  224015. bool selectMultipleFiles,
  224016. FilePreviewComponent* previewComponent)
  224017. {
  224018. const String separator (":");
  224019. String command ("zenity --file-selection");
  224020. if (title.isNotEmpty())
  224021. command << " --title=\"" << title << "\"";
  224022. if (file != File::nonexistent)
  224023. command << " --filename=\"" << file.getFullPathName () << "\"";
  224024. if (isDirectory)
  224025. command << " --directory";
  224026. if (isSave)
  224027. command << " --save";
  224028. if (selectMultipleFiles)
  224029. command << " --multiple --separator=\"" << separator << "\"";
  224030. command << " 2>&1";
  224031. MemoryOutputStream result;
  224032. int status = -1;
  224033. FILE* stream = popen (command.toUTF8(), "r");
  224034. if (stream != 0)
  224035. {
  224036. for (;;)
  224037. {
  224038. char buffer [1024];
  224039. const int bytesRead = fread (buffer, 1, sizeof (buffer), stream);
  224040. if (bytesRead <= 0)
  224041. break;
  224042. result.write (buffer, bytesRead);
  224043. }
  224044. status = pclose (stream);
  224045. }
  224046. if (status == 0)
  224047. {
  224048. StringArray tokens;
  224049. if (selectMultipleFiles)
  224050. tokens.addTokens (result.toUTF8(), separator, String::empty);
  224051. else
  224052. tokens.add (result.toUTF8());
  224053. for (int i = 0; i < tokens.size(); i++)
  224054. results.add (File (tokens[i]));
  224055. return;
  224056. }
  224057. //xxx ain't got one!
  224058. jassertfalse;
  224059. }
  224060. #endif
  224061. /*** End of inlined file: juce_linux_FileChooser.cpp ***/
  224062. /*** Start of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  224063. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  224064. // compiled on its own).
  224065. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  224066. /*
  224067. Sorry.. This class isn't implemented on Linux!
  224068. */
  224069. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  224070. : browser (0),
  224071. blankPageShown (false),
  224072. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  224073. {
  224074. setOpaque (true);
  224075. }
  224076. WebBrowserComponent::~WebBrowserComponent()
  224077. {
  224078. }
  224079. void WebBrowserComponent::goToURL (const String& url,
  224080. const StringArray* headers,
  224081. const MemoryBlock* postData)
  224082. {
  224083. lastURL = url;
  224084. lastHeaders.clear();
  224085. if (headers != 0)
  224086. lastHeaders = *headers;
  224087. lastPostData.setSize (0);
  224088. if (postData != 0)
  224089. lastPostData = *postData;
  224090. blankPageShown = false;
  224091. }
  224092. void WebBrowserComponent::stop()
  224093. {
  224094. }
  224095. void WebBrowserComponent::goBack()
  224096. {
  224097. lastURL = String::empty;
  224098. blankPageShown = false;
  224099. }
  224100. void WebBrowserComponent::goForward()
  224101. {
  224102. lastURL = String::empty;
  224103. }
  224104. void WebBrowserComponent::refresh()
  224105. {
  224106. }
  224107. void WebBrowserComponent::paint (Graphics& g)
  224108. {
  224109. g.fillAll (Colours::white);
  224110. }
  224111. void WebBrowserComponent::checkWindowAssociation()
  224112. {
  224113. }
  224114. void WebBrowserComponent::reloadLastURL()
  224115. {
  224116. if (lastURL.isNotEmpty())
  224117. {
  224118. goToURL (lastURL, &lastHeaders, &lastPostData);
  224119. lastURL = String::empty;
  224120. }
  224121. }
  224122. void WebBrowserComponent::parentHierarchyChanged()
  224123. {
  224124. checkWindowAssociation();
  224125. }
  224126. void WebBrowserComponent::resized()
  224127. {
  224128. }
  224129. void WebBrowserComponent::visibilityChanged()
  224130. {
  224131. checkWindowAssociation();
  224132. }
  224133. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  224134. {
  224135. return true;
  224136. }
  224137. #endif
  224138. /*** End of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  224139. #endif
  224140. END_JUCE_NAMESPACE
  224141. #endif
  224142. /*** End of inlined file: juce_linux_NativeCode.cpp ***/
  224143. #endif
  224144. #if JUCE_MAC || JUCE_IPHONE
  224145. /*** Start of inlined file: juce_mac_NativeCode.mm ***/
  224146. /*
  224147. This file wraps together all the mac-specific code, so that
  224148. we can include all the native headers just once, and compile all our
  224149. platform-specific stuff in one big lump, keeping it out of the way of
  224150. the rest of the codebase.
  224151. */
  224152. #if JUCE_MAC || JUCE_IOS
  224153. BEGIN_JUCE_NAMESPACE
  224154. #undef Point
  224155. template <class RectType>
  224156. static const Rectangle<int> convertToRectInt (const RectType& r)
  224157. {
  224158. return Rectangle<int> ((int) r.origin.x, (int) r.origin.y, (int) r.size.width, (int) r.size.height);
  224159. }
  224160. template <class RectType>
  224161. static const Rectangle<float> convertToRectFloat (const RectType& r)
  224162. {
  224163. return Rectangle<float> (r.origin.x, r.origin.y, r.size.width, r.size.height);
  224164. }
  224165. template <class RectType>
  224166. static CGRect convertToCGRect (const RectType& r)
  224167. {
  224168. return CGRectMake ((CGFloat) r.getX(), (CGFloat) r.getY(), (CGFloat) r.getWidth(), (CGFloat) r.getHeight());
  224169. }
  224170. #define JUCE_INCLUDED_FILE 1
  224171. // Now include the actual code files..
  224172. /*** Start of inlined file: juce_mac_ObjCSuffix.h ***/
  224173. /** This suffix is used for naming all Obj-C classes that are used inside juce.
  224174. Because of the flat naming structure used by Obj-C, you can get horrible situations where
  224175. two DLLs are loaded into a host, each of which uses classes with the same names, and these get
  224176. cross-linked so that when you make a call to a class that you thought was private, it ends up
  224177. actually calling into a similarly named class in the other module's address space.
  224178. By changing this macro to a unique value, you ensure that all the obj-C classes in your app
  224179. have unique names, and should avoid this problem.
  224180. If you're using the amalgamated version, you can just set this macro to something unique before
  224181. you include juce_amalgamated.cpp.
  224182. */
  224183. #ifndef JUCE_ObjCExtraSuffix
  224184. #define JUCE_ObjCExtraSuffix 3
  224185. #endif
  224186. #define appendMacro1(a, b, c, d, e) a ## _ ## b ## _ ## c ## _ ## d ## _ ## e
  224187. #define appendMacro2(a, b, c, d, e) appendMacro1(a, b, c, d, e)
  224188. #define MakeObjCClassName(rootName) appendMacro2 (rootName, JUCE_MAJOR_VERSION, JUCE_MINOR_VERSION, JUCE_BUILDNUMBER, JUCE_ObjCExtraSuffix)
  224189. /*** End of inlined file: juce_mac_ObjCSuffix.h ***/
  224190. /*** Start of inlined file: juce_mac_Strings.mm ***/
  224191. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224192. // compiled on its own).
  224193. #if JUCE_INCLUDED_FILE
  224194. static const String nsStringToJuce (NSString* s)
  224195. {
  224196. return String::fromUTF8 ([s UTF8String]);
  224197. }
  224198. static NSString* juceStringToNS (const String& s)
  224199. {
  224200. return [NSString stringWithUTF8String: s.toUTF8()];
  224201. }
  224202. static const String convertUTF16ToString (const UniChar* utf16)
  224203. {
  224204. String s;
  224205. while (*utf16 != 0)
  224206. s += (juce_wchar) *utf16++;
  224207. return s;
  224208. }
  224209. const String PlatformUtilities::cfStringToJuceString (CFStringRef cfString)
  224210. {
  224211. String result;
  224212. if (cfString != 0)
  224213. {
  224214. CFRange range = { 0, CFStringGetLength (cfString) };
  224215. HeapBlock <UniChar> u (range.length + 1);
  224216. CFStringGetCharacters (cfString, range, u);
  224217. u[range.length] = 0;
  224218. result = convertUTF16ToString (u);
  224219. }
  224220. return result;
  224221. }
  224222. CFStringRef PlatformUtilities::juceStringToCFString (const String& s)
  224223. {
  224224. const int len = s.length();
  224225. HeapBlock <UniChar> temp (len + 2);
  224226. for (int i = 0; i <= len; ++i)
  224227. temp[i] = s[i];
  224228. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  224229. }
  224230. const String PlatformUtilities::convertToPrecomposedUnicode (const String& s)
  224231. {
  224232. #if JUCE_IOS
  224233. const ScopedAutoReleasePool pool;
  224234. return nsStringToJuce ([juceStringToNS (s) precomposedStringWithCanonicalMapping]);
  224235. #else
  224236. UnicodeMapping map;
  224237. map.unicodeEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  224238. kUnicodeNoSubset,
  224239. kTextEncodingDefaultFormat);
  224240. map.otherEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  224241. kUnicodeCanonicalCompVariant,
  224242. kTextEncodingDefaultFormat);
  224243. map.mappingVersion = kUnicodeUseLatestMapping;
  224244. UnicodeToTextInfo conversionInfo = 0;
  224245. String result;
  224246. if (CreateUnicodeToTextInfo (&map, &conversionInfo) == noErr)
  224247. {
  224248. const int len = s.length();
  224249. HeapBlock <UniChar> tempIn, tempOut;
  224250. tempIn.calloc (len + 2);
  224251. tempOut.calloc (len + 2);
  224252. for (int i = 0; i <= len; ++i)
  224253. tempIn[i] = s[i];
  224254. ByteCount bytesRead = 0;
  224255. ByteCount outputBufferSize = 0;
  224256. if (ConvertFromUnicodeToText (conversionInfo,
  224257. len * sizeof (UniChar), tempIn,
  224258. kUnicodeDefaultDirectionMask,
  224259. 0, 0, 0, 0,
  224260. len * sizeof (UniChar), &bytesRead,
  224261. &outputBufferSize, tempOut) == noErr)
  224262. {
  224263. result.preallocateStorage (bytesRead / sizeof (UniChar) + 2);
  224264. juce_wchar* t = result;
  224265. unsigned int i;
  224266. for (i = 0; i < bytesRead / sizeof (UniChar); ++i)
  224267. t[i] = (juce_wchar) tempOut[i];
  224268. t[i] = 0;
  224269. }
  224270. DisposeUnicodeToTextInfo (&conversionInfo);
  224271. }
  224272. return result;
  224273. #endif
  224274. }
  224275. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  224276. void SystemClipboard::copyTextToClipboard (const String& text)
  224277. {
  224278. #if JUCE_IOS
  224279. [[UIPasteboard generalPasteboard] setValue: juceStringToNS (text)
  224280. forPasteboardType: @"public.text"];
  224281. #else
  224282. [[NSPasteboard generalPasteboard] declareTypes: [NSArray arrayWithObject: NSStringPboardType]
  224283. owner: nil];
  224284. [[NSPasteboard generalPasteboard] setString: juceStringToNS (text)
  224285. forType: NSStringPboardType];
  224286. #endif
  224287. }
  224288. const String SystemClipboard::getTextFromClipboard()
  224289. {
  224290. #if JUCE_IOS
  224291. NSString* text = [[UIPasteboard generalPasteboard] valueForPasteboardType: @"public.text"];
  224292. #else
  224293. NSString* text = [[NSPasteboard generalPasteboard] stringForType: NSStringPboardType];
  224294. #endif
  224295. return text == 0 ? String::empty
  224296. : nsStringToJuce (text);
  224297. }
  224298. #endif
  224299. #endif
  224300. /*** End of inlined file: juce_mac_Strings.mm ***/
  224301. /*** Start of inlined file: juce_mac_SystemStats.mm ***/
  224302. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224303. // compiled on its own).
  224304. #if JUCE_INCLUDED_FILE
  224305. namespace SystemStatsHelpers
  224306. {
  224307. static int64 highResTimerFrequency = 0;
  224308. static double highResTimerToMillisecRatio = 0;
  224309. #if JUCE_INTEL
  224310. static void juce_getCpuVendor (char* const v) throw()
  224311. {
  224312. int vendor[4];
  224313. zerostruct (vendor);
  224314. int dummy = 0;
  224315. asm ("mov %%ebx, %%esi \n\t"
  224316. "cpuid \n\t"
  224317. "xchg %%esi, %%ebx"
  224318. : "=a" (dummy), "=S" (vendor[0]), "=c" (vendor[2]), "=d" (vendor[1]) : "a" (0));
  224319. memcpy (v, vendor, 16);
  224320. }
  224321. static unsigned int getCPUIDWord (unsigned int& familyModel, unsigned int& extFeatures)
  224322. {
  224323. unsigned int cpu = 0;
  224324. unsigned int ext = 0;
  224325. unsigned int family = 0;
  224326. unsigned int dummy = 0;
  224327. asm ("mov %%ebx, %%esi \n\t"
  224328. "cpuid \n\t"
  224329. "xchg %%esi, %%ebx"
  224330. : "=a" (family), "=S" (ext), "=c" (dummy), "=d" (cpu) : "a" (1));
  224331. familyModel = family;
  224332. extFeatures = ext;
  224333. return cpu;
  224334. }
  224335. #endif
  224336. }
  224337. void SystemStats::initialiseStats()
  224338. {
  224339. using namespace SystemStatsHelpers;
  224340. static bool initialised = false;
  224341. if (! initialised)
  224342. {
  224343. initialised = true;
  224344. #if JUCE_MAC
  224345. [NSApplication sharedApplication];
  224346. #endif
  224347. #if JUCE_INTEL
  224348. unsigned int familyModel, extFeatures;
  224349. const unsigned int features = getCPUIDWord (familyModel, extFeatures);
  224350. cpuFlags.hasMMX = ((features & (1 << 23)) != 0);
  224351. cpuFlags.hasSSE = ((features & (1 << 25)) != 0);
  224352. cpuFlags.hasSSE2 = ((features & (1 << 26)) != 0);
  224353. cpuFlags.has3DNow = ((extFeatures & (1 << 31)) != 0);
  224354. #else
  224355. cpuFlags.hasMMX = false;
  224356. cpuFlags.hasSSE = false;
  224357. cpuFlags.hasSSE2 = false;
  224358. cpuFlags.has3DNow = false;
  224359. #endif
  224360. #if JUCE_IOS || (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5)
  224361. cpuFlags.numCpus = (int) [[NSProcessInfo processInfo] activeProcessorCount];
  224362. #else
  224363. cpuFlags.numCpus = (int) MPProcessors();
  224364. #endif
  224365. mach_timebase_info_data_t timebase;
  224366. (void) mach_timebase_info (&timebase);
  224367. highResTimerFrequency = (int64) (1.0e9 * timebase.denom / timebase.numer);
  224368. highResTimerToMillisecRatio = timebase.numer / (1.0e6 * timebase.denom);
  224369. String s (SystemStats::getJUCEVersion());
  224370. rlimit lim;
  224371. getrlimit (RLIMIT_NOFILE, &lim);
  224372. lim.rlim_cur = lim.rlim_max = RLIM_INFINITY;
  224373. setrlimit (RLIMIT_NOFILE, &lim);
  224374. }
  224375. }
  224376. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  224377. {
  224378. return MacOSX;
  224379. }
  224380. const String SystemStats::getOperatingSystemName()
  224381. {
  224382. return "Mac OS X";
  224383. }
  224384. #if ! JUCE_IOS
  224385. int PlatformUtilities::getOSXMinorVersionNumber()
  224386. {
  224387. SInt32 versionMinor = 0;
  224388. OSErr err = Gestalt (gestaltSystemVersionMinor, &versionMinor);
  224389. (void) err;
  224390. jassert (err == noErr);
  224391. return (int) versionMinor;
  224392. }
  224393. #endif
  224394. bool SystemStats::isOperatingSystem64Bit()
  224395. {
  224396. #if JUCE_IOS
  224397. return false;
  224398. #elif JUCE_64BIT
  224399. return true;
  224400. #else
  224401. return PlatformUtilities::getOSXMinorVersionNumber() >= 6;
  224402. #endif
  224403. }
  224404. int SystemStats::getMemorySizeInMegabytes()
  224405. {
  224406. uint64 mem = 0;
  224407. size_t memSize = sizeof (mem);
  224408. int mib[] = { CTL_HW, HW_MEMSIZE };
  224409. sysctl (mib, 2, &mem, &memSize, 0, 0);
  224410. return (int) (mem / (1024 * 1024));
  224411. }
  224412. const String SystemStats::getCpuVendor()
  224413. {
  224414. #if JUCE_INTEL
  224415. char v [16];
  224416. SystemStatsHelpers::juce_getCpuVendor (v);
  224417. return String (v, 16);
  224418. #else
  224419. return String::empty;
  224420. #endif
  224421. }
  224422. int SystemStats::getCpuSpeedInMegaherz()
  224423. {
  224424. uint64 speedHz = 0;
  224425. size_t speedSize = sizeof (speedHz);
  224426. int mib[] = { CTL_HW, HW_CPU_FREQ };
  224427. sysctl (mib, 2, &speedHz, &speedSize, 0, 0);
  224428. #if JUCE_BIG_ENDIAN
  224429. if (speedSize == 4)
  224430. speedHz >>= 32;
  224431. #endif
  224432. return (int) (speedHz / 1000000);
  224433. }
  224434. const String SystemStats::getLogonName()
  224435. {
  224436. return nsStringToJuce (NSUserName());
  224437. }
  224438. const String SystemStats::getFullUserName()
  224439. {
  224440. return nsStringToJuce (NSFullUserName());
  224441. }
  224442. uint32 juce_millisecondsSinceStartup() throw()
  224443. {
  224444. return (uint32) (mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio);
  224445. }
  224446. double Time::getMillisecondCounterHiRes() throw()
  224447. {
  224448. return mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio;
  224449. }
  224450. int64 Time::getHighResolutionTicks() throw()
  224451. {
  224452. return (int64) mach_absolute_time();
  224453. }
  224454. int64 Time::getHighResolutionTicksPerSecond() throw()
  224455. {
  224456. return SystemStatsHelpers::highResTimerFrequency;
  224457. }
  224458. bool Time::setSystemTimeToThisTime() const
  224459. {
  224460. jassertfalse;
  224461. return false;
  224462. }
  224463. int SystemStats::getPageSize()
  224464. {
  224465. return (int) NSPageSize();
  224466. }
  224467. void PlatformUtilities::fpuReset()
  224468. {
  224469. }
  224470. #endif
  224471. /*** End of inlined file: juce_mac_SystemStats.mm ***/
  224472. /*** Start of inlined file: juce_mac_Network.mm ***/
  224473. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224474. // compiled on its own).
  224475. #if JUCE_INCLUDED_FILE
  224476. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  224477. {
  224478. #ifndef IFT_ETHER
  224479. #define IFT_ETHER 6
  224480. #endif
  224481. ifaddrs* addrs = 0;
  224482. int numResults = 0;
  224483. if (getifaddrs (&addrs) == 0)
  224484. {
  224485. const ifaddrs* cursor = addrs;
  224486. while (cursor != 0 && numResults < maxNum)
  224487. {
  224488. sockaddr_storage* sto = (sockaddr_storage*) cursor->ifa_addr;
  224489. if (sto->ss_family == AF_LINK)
  224490. {
  224491. const sockaddr_dl* const sadd = (const sockaddr_dl*) cursor->ifa_addr;
  224492. if (sadd->sdl_type == IFT_ETHER)
  224493. {
  224494. const uint8* const addr = ((const uint8*) sadd->sdl_data) + sadd->sdl_nlen;
  224495. uint64 a = 0;
  224496. for (int i = 6; --i >= 0;)
  224497. a = (a << 8) | addr [littleEndian ? i : (5 - i)];
  224498. *addresses++ = (int64) a;
  224499. ++numResults;
  224500. }
  224501. }
  224502. cursor = cursor->ifa_next;
  224503. }
  224504. freeifaddrs (addrs);
  224505. }
  224506. return numResults;
  224507. }
  224508. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  224509. const String& emailSubject,
  224510. const String& bodyText,
  224511. const StringArray& filesToAttach)
  224512. {
  224513. #if JUCE_IOS
  224514. //xxx probably need to use MFMailComposeViewController
  224515. jassertfalse;
  224516. return false;
  224517. #else
  224518. const ScopedAutoReleasePool pool;
  224519. String script;
  224520. script << "tell application \"Mail\"\r\n"
  224521. "set newMessage to make new outgoing message with properties {subject:\""
  224522. << emailSubject.replace ("\"", "\\\"")
  224523. << "\", content:\""
  224524. << bodyText.replace ("\"", "\\\"")
  224525. << "\" & return & return}\r\n"
  224526. "tell newMessage\r\n"
  224527. "set visible to true\r\n"
  224528. "set sender to \"sdfsdfsdfewf\"\r\n"
  224529. "make new to recipient at end of to recipients with properties {address:\""
  224530. << targetEmailAddress
  224531. << "\"}\r\n";
  224532. for (int i = 0; i < filesToAttach.size(); ++i)
  224533. {
  224534. script << "tell content\r\n"
  224535. "make new attachment with properties {file name:\""
  224536. << filesToAttach[i].replace ("\"", "\\\"")
  224537. << "\"} at after the last paragraph\r\n"
  224538. "end tell\r\n";
  224539. }
  224540. script << "end tell\r\n"
  224541. "end tell\r\n";
  224542. NSAppleScript* s = [[NSAppleScript alloc]
  224543. initWithSource: juceStringToNS (script)];
  224544. NSDictionary* error = 0;
  224545. const bool ok = [s executeAndReturnError: &error] != nil;
  224546. [s release];
  224547. return ok;
  224548. #endif
  224549. }
  224550. END_JUCE_NAMESPACE
  224551. using namespace JUCE_NAMESPACE;
  224552. #define JuceURLConnection MakeObjCClassName(JuceURLConnection)
  224553. @interface JuceURLConnection : NSObject
  224554. {
  224555. @public
  224556. NSURLRequest* request;
  224557. NSURLConnection* connection;
  224558. NSMutableData* data;
  224559. Thread* runLoopThread;
  224560. bool initialised, hasFailed, hasFinished;
  224561. int position;
  224562. int64 contentLength;
  224563. NSDictionary* headers;
  224564. NSLock* dataLock;
  224565. }
  224566. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req withCallback: (URL::OpenStreamProgressCallback*) callback withContext: (void*) context;
  224567. - (void) dealloc;
  224568. - (void) connection: (NSURLConnection*) connection didReceiveResponse: (NSURLResponse*) response;
  224569. - (void) connection: (NSURLConnection*) connection didFailWithError: (NSError*) error;
  224570. - (void) connection: (NSURLConnection*) connection didReceiveData: (NSData*) data;
  224571. - (void) connectionDidFinishLoading: (NSURLConnection*) connection;
  224572. - (BOOL) isOpen;
  224573. - (int) read: (char*) dest numBytes: (int) num;
  224574. - (int) readPosition;
  224575. - (void) stop;
  224576. - (void) createConnection;
  224577. @end
  224578. class JuceURLConnectionMessageThread : public Thread
  224579. {
  224580. JuceURLConnection* owner;
  224581. public:
  224582. JuceURLConnectionMessageThread (JuceURLConnection* owner_)
  224583. : Thread ("http connection"),
  224584. owner (owner_)
  224585. {
  224586. }
  224587. ~JuceURLConnectionMessageThread()
  224588. {
  224589. stopThread (10000);
  224590. }
  224591. void run()
  224592. {
  224593. [owner createConnection];
  224594. while (! threadShouldExit())
  224595. {
  224596. const ScopedAutoReleasePool pool;
  224597. [[NSRunLoop currentRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  224598. }
  224599. }
  224600. };
  224601. @implementation JuceURLConnection
  224602. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req
  224603. withCallback: (URL::OpenStreamProgressCallback*) callback
  224604. withContext: (void*) context;
  224605. {
  224606. [super init];
  224607. request = req;
  224608. [request retain];
  224609. data = [[NSMutableData data] retain];
  224610. dataLock = [[NSLock alloc] init];
  224611. connection = 0;
  224612. initialised = false;
  224613. hasFailed = false;
  224614. hasFinished = false;
  224615. contentLength = -1;
  224616. headers = 0;
  224617. runLoopThread = new JuceURLConnectionMessageThread (self);
  224618. runLoopThread->startThread();
  224619. while (runLoopThread->isThreadRunning() && ! initialised)
  224620. {
  224621. if (callback != 0)
  224622. callback (context, -1, (int) [[request HTTPBody] length]);
  224623. Thread::sleep (1);
  224624. }
  224625. return self;
  224626. }
  224627. - (void) dealloc
  224628. {
  224629. [self stop];
  224630. deleteAndZero (runLoopThread);
  224631. [connection release];
  224632. [data release];
  224633. [dataLock release];
  224634. [request release];
  224635. [headers release];
  224636. [super dealloc];
  224637. }
  224638. - (void) createConnection
  224639. {
  224640. NSUInteger oldRetainCount = [self retainCount];
  224641. connection = [[NSURLConnection alloc] initWithRequest: request
  224642. delegate: self];
  224643. if (oldRetainCount == [self retainCount])
  224644. [self retain]; // newer SDK should already retain this, but there were problems in older versions..
  224645. if (connection == nil)
  224646. runLoopThread->signalThreadShouldExit();
  224647. }
  224648. - (void) connection: (NSURLConnection*) conn didReceiveResponse: (NSURLResponse*) response
  224649. {
  224650. (void) conn;
  224651. [dataLock lock];
  224652. [data setLength: 0];
  224653. [dataLock unlock];
  224654. initialised = true;
  224655. contentLength = [response expectedContentLength];
  224656. [headers release];
  224657. headers = 0;
  224658. if ([response isKindOfClass: [NSHTTPURLResponse class]])
  224659. headers = [[((NSHTTPURLResponse*) response) allHeaderFields] retain];
  224660. }
  224661. - (void) connection: (NSURLConnection*) conn didFailWithError: (NSError*) error
  224662. {
  224663. (void) conn;
  224664. DBG (nsStringToJuce ([error description]));
  224665. hasFailed = true;
  224666. initialised = true;
  224667. if (runLoopThread != 0)
  224668. runLoopThread->signalThreadShouldExit();
  224669. }
  224670. - (void) connection: (NSURLConnection*) conn didReceiveData: (NSData*) newData
  224671. {
  224672. (void) conn;
  224673. [dataLock lock];
  224674. [data appendData: newData];
  224675. [dataLock unlock];
  224676. initialised = true;
  224677. }
  224678. - (void) connectionDidFinishLoading: (NSURLConnection*) conn
  224679. {
  224680. (void) conn;
  224681. hasFinished = true;
  224682. initialised = true;
  224683. if (runLoopThread != 0)
  224684. runLoopThread->signalThreadShouldExit();
  224685. }
  224686. - (BOOL) isOpen
  224687. {
  224688. return connection != 0 && ! hasFailed;
  224689. }
  224690. - (int) readPosition
  224691. {
  224692. return position;
  224693. }
  224694. - (int) read: (char*) dest numBytes: (int) numNeeded
  224695. {
  224696. int numDone = 0;
  224697. while (numNeeded > 0)
  224698. {
  224699. int available = jmin (numNeeded, (int) [data length]);
  224700. if (available > 0)
  224701. {
  224702. [dataLock lock];
  224703. [data getBytes: dest length: available];
  224704. [data replaceBytesInRange: NSMakeRange (0, available) withBytes: nil length: 0];
  224705. [dataLock unlock];
  224706. numDone += available;
  224707. numNeeded -= available;
  224708. dest += available;
  224709. }
  224710. else
  224711. {
  224712. if (hasFailed || hasFinished)
  224713. break;
  224714. Thread::sleep (1);
  224715. }
  224716. }
  224717. position += numDone;
  224718. return numDone;
  224719. }
  224720. - (void) stop
  224721. {
  224722. [connection cancel];
  224723. if (runLoopThread != 0)
  224724. runLoopThread->stopThread (10000);
  224725. }
  224726. @end
  224727. BEGIN_JUCE_NAMESPACE
  224728. void* juce_openInternetFile (const String& url,
  224729. const String& headers,
  224730. const MemoryBlock& postData,
  224731. const bool isPost,
  224732. URL::OpenStreamProgressCallback* callback,
  224733. void* callbackContext,
  224734. int timeOutMs)
  224735. {
  224736. const ScopedAutoReleasePool pool;
  224737. NSMutableURLRequest* req = [NSMutableURLRequest
  224738. requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  224739. cachePolicy: NSURLRequestUseProtocolCachePolicy
  224740. timeoutInterval: timeOutMs <= 0 ? 60.0 : (timeOutMs / 1000.0)];
  224741. if (req == nil)
  224742. return 0;
  224743. [req setHTTPMethod: isPost ? @"POST" : @"GET"];
  224744. //[req setCachePolicy: NSURLRequestReloadIgnoringLocalAndRemoteCacheData];
  224745. StringArray headerLines;
  224746. headerLines.addLines (headers);
  224747. headerLines.removeEmptyStrings (true);
  224748. for (int i = 0; i < headerLines.size(); ++i)
  224749. {
  224750. const String key (headerLines[i].upToFirstOccurrenceOf (":", false, false).trim());
  224751. const String value (headerLines[i].fromFirstOccurrenceOf (":", false, false).trim());
  224752. if (key.isNotEmpty() && value.isNotEmpty())
  224753. [req addValue: juceStringToNS (value) forHTTPHeaderField: juceStringToNS (key)];
  224754. }
  224755. if (isPost && postData.getSize() > 0)
  224756. {
  224757. [req setHTTPBody: [NSData dataWithBytes: postData.getData()
  224758. length: postData.getSize()]];
  224759. }
  224760. JuceURLConnection* const s = [[JuceURLConnection alloc] initWithRequest: req
  224761. withCallback: callback
  224762. withContext: callbackContext];
  224763. if ([s isOpen])
  224764. return s;
  224765. [s release];
  224766. return 0;
  224767. }
  224768. void juce_closeInternetFile (void* handle)
  224769. {
  224770. JuceURLConnection* const s = (JuceURLConnection*) handle;
  224771. if (s != 0)
  224772. {
  224773. const ScopedAutoReleasePool pool;
  224774. [s stop];
  224775. [s release];
  224776. }
  224777. }
  224778. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  224779. {
  224780. JuceURLConnection* const s = (JuceURLConnection*) handle;
  224781. if (s != 0)
  224782. {
  224783. const ScopedAutoReleasePool pool;
  224784. return [s read: (char*) buffer numBytes: bytesToRead];
  224785. }
  224786. return 0;
  224787. }
  224788. int64 juce_getInternetFileContentLength (void* handle)
  224789. {
  224790. JuceURLConnection* const s = (JuceURLConnection*) handle;
  224791. if (s != 0)
  224792. return s->contentLength;
  224793. return -1;
  224794. }
  224795. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers)
  224796. {
  224797. JuceURLConnection* const s = (JuceURLConnection*) handle;
  224798. if (s != 0 && s->headers != 0)
  224799. {
  224800. NSEnumerator* enumerator = [s->headers keyEnumerator];
  224801. NSString* key;
  224802. while ((key = [enumerator nextObject]) != nil)
  224803. headers.set (nsStringToJuce (key),
  224804. nsStringToJuce ((NSString*) [s->headers objectForKey: key]));
  224805. }
  224806. }
  224807. int juce_seekInInternetFile (void* handle, int /*newPosition*/)
  224808. {
  224809. JuceURLConnection* const s = (JuceURLConnection*) handle;
  224810. if (s != 0)
  224811. return [s readPosition];
  224812. return 0;
  224813. }
  224814. #endif
  224815. /*** End of inlined file: juce_mac_Network.mm ***/
  224816. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  224817. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224818. // compiled on its own).
  224819. #if JUCE_INCLUDED_FILE
  224820. struct NamedPipeInternal
  224821. {
  224822. String pipeInName, pipeOutName;
  224823. int pipeIn, pipeOut;
  224824. bool volatile createdPipe, blocked, stopReadOperation;
  224825. static void signalHandler (int) {}
  224826. };
  224827. void NamedPipe::cancelPendingReads()
  224828. {
  224829. while (internal != 0 && static_cast <NamedPipeInternal*> (internal)->blocked)
  224830. {
  224831. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  224832. intern->stopReadOperation = true;
  224833. char buffer [1] = { 0 };
  224834. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  224835. (void) bytesWritten;
  224836. int timeout = 2000;
  224837. while (intern->blocked && --timeout >= 0)
  224838. Thread::sleep (2);
  224839. intern->stopReadOperation = false;
  224840. }
  224841. }
  224842. void NamedPipe::close()
  224843. {
  224844. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  224845. if (intern != 0)
  224846. {
  224847. internal = 0;
  224848. if (intern->pipeIn != -1)
  224849. ::close (intern->pipeIn);
  224850. if (intern->pipeOut != -1)
  224851. ::close (intern->pipeOut);
  224852. if (intern->createdPipe)
  224853. {
  224854. unlink (intern->pipeInName.toUTF8());
  224855. unlink (intern->pipeOutName.toUTF8());
  224856. }
  224857. delete intern;
  224858. }
  224859. }
  224860. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  224861. {
  224862. close();
  224863. NamedPipeInternal* const intern = new NamedPipeInternal();
  224864. internal = intern;
  224865. intern->createdPipe = createPipe;
  224866. intern->blocked = false;
  224867. intern->stopReadOperation = false;
  224868. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  224869. siginterrupt (SIGPIPE, 1);
  224870. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  224871. intern->pipeInName = pipePath + "_in";
  224872. intern->pipeOutName = pipePath + "_out";
  224873. intern->pipeIn = -1;
  224874. intern->pipeOut = -1;
  224875. if (createPipe)
  224876. {
  224877. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  224878. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  224879. {
  224880. delete intern;
  224881. internal = 0;
  224882. return false;
  224883. }
  224884. }
  224885. return true;
  224886. }
  224887. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  224888. {
  224889. int bytesRead = -1;
  224890. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  224891. if (intern != 0)
  224892. {
  224893. intern->blocked = true;
  224894. if (intern->pipeIn == -1)
  224895. {
  224896. if (intern->createdPipe)
  224897. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  224898. else
  224899. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  224900. if (intern->pipeIn == -1)
  224901. {
  224902. intern->blocked = false;
  224903. return -1;
  224904. }
  224905. }
  224906. bytesRead = 0;
  224907. char* p = static_cast<char*> (destBuffer);
  224908. while (bytesRead < maxBytesToRead)
  224909. {
  224910. const int bytesThisTime = maxBytesToRead - bytesRead;
  224911. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  224912. if (numRead <= 0 || intern->stopReadOperation)
  224913. {
  224914. bytesRead = -1;
  224915. break;
  224916. }
  224917. bytesRead += numRead;
  224918. p += bytesRead;
  224919. }
  224920. intern->blocked = false;
  224921. }
  224922. return bytesRead;
  224923. }
  224924. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  224925. {
  224926. int bytesWritten = -1;
  224927. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  224928. if (intern != 0)
  224929. {
  224930. if (intern->pipeOut == -1)
  224931. {
  224932. if (intern->createdPipe)
  224933. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  224934. else
  224935. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  224936. if (intern->pipeOut == -1)
  224937. {
  224938. return -1;
  224939. }
  224940. }
  224941. const char* p = static_cast<const char*> (sourceBuffer);
  224942. bytesWritten = 0;
  224943. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  224944. while (bytesWritten < numBytesToWrite
  224945. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  224946. {
  224947. const int bytesThisTime = numBytesToWrite - bytesWritten;
  224948. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  224949. if (numWritten <= 0)
  224950. {
  224951. bytesWritten = -1;
  224952. break;
  224953. }
  224954. bytesWritten += numWritten;
  224955. p += bytesWritten;
  224956. }
  224957. }
  224958. return bytesWritten;
  224959. }
  224960. #endif
  224961. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  224962. /*** Start of inlined file: juce_mac_Threads.mm ***/
  224963. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224964. // compiled on its own).
  224965. #if JUCE_INCLUDED_FILE
  224966. /*
  224967. Note that a lot of methods that you'd expect to find in this file actually
  224968. live in juce_posix_SharedCode.h!
  224969. */
  224970. bool Process::isForegroundProcess()
  224971. {
  224972. #if JUCE_MAC
  224973. return [NSApp isActive];
  224974. #else
  224975. return true; // xxx change this if more than one app is ever possible on the iPhone!
  224976. #endif
  224977. }
  224978. void Process::raisePrivilege()
  224979. {
  224980. jassertfalse;
  224981. }
  224982. void Process::lowerPrivilege()
  224983. {
  224984. jassertfalse;
  224985. }
  224986. void Process::terminate()
  224987. {
  224988. exit (0);
  224989. }
  224990. void Process::setPriority (ProcessPriority)
  224991. {
  224992. // xxx
  224993. }
  224994. #endif
  224995. /*** End of inlined file: juce_mac_Threads.mm ***/
  224996. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  224997. /*
  224998. This file contains posix routines that are common to both the Linux and Mac builds.
  224999. It gets included directly in the cpp files for these platforms.
  225000. */
  225001. CriticalSection::CriticalSection() throw()
  225002. {
  225003. pthread_mutexattr_t atts;
  225004. pthread_mutexattr_init (&atts);
  225005. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  225006. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  225007. pthread_mutex_init (&internal, &atts);
  225008. }
  225009. CriticalSection::~CriticalSection() throw()
  225010. {
  225011. pthread_mutex_destroy (&internal);
  225012. }
  225013. void CriticalSection::enter() const throw()
  225014. {
  225015. pthread_mutex_lock (&internal);
  225016. }
  225017. bool CriticalSection::tryEnter() const throw()
  225018. {
  225019. return pthread_mutex_trylock (&internal) == 0;
  225020. }
  225021. void CriticalSection::exit() const throw()
  225022. {
  225023. pthread_mutex_unlock (&internal);
  225024. }
  225025. class WaitableEventImpl
  225026. {
  225027. public:
  225028. WaitableEventImpl (const bool manualReset_)
  225029. : triggered (false),
  225030. manualReset (manualReset_)
  225031. {
  225032. pthread_cond_init (&condition, 0);
  225033. pthread_mutexattr_t atts;
  225034. pthread_mutexattr_init (&atts);
  225035. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  225036. pthread_mutex_init (&mutex, &atts);
  225037. }
  225038. ~WaitableEventImpl()
  225039. {
  225040. pthread_cond_destroy (&condition);
  225041. pthread_mutex_destroy (&mutex);
  225042. }
  225043. bool wait (const int timeOutMillisecs) throw()
  225044. {
  225045. pthread_mutex_lock (&mutex);
  225046. if (! triggered)
  225047. {
  225048. if (timeOutMillisecs < 0)
  225049. {
  225050. do
  225051. {
  225052. pthread_cond_wait (&condition, &mutex);
  225053. }
  225054. while (! triggered);
  225055. }
  225056. else
  225057. {
  225058. struct timeval now;
  225059. gettimeofday (&now, 0);
  225060. struct timespec time;
  225061. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  225062. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  225063. if (time.tv_nsec >= 1000000000)
  225064. {
  225065. time.tv_nsec -= 1000000000;
  225066. time.tv_sec++;
  225067. }
  225068. do
  225069. {
  225070. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  225071. {
  225072. pthread_mutex_unlock (&mutex);
  225073. return false;
  225074. }
  225075. }
  225076. while (! triggered);
  225077. }
  225078. }
  225079. if (! manualReset)
  225080. triggered = false;
  225081. pthread_mutex_unlock (&mutex);
  225082. return true;
  225083. }
  225084. void signal() throw()
  225085. {
  225086. pthread_mutex_lock (&mutex);
  225087. triggered = true;
  225088. pthread_cond_broadcast (&condition);
  225089. pthread_mutex_unlock (&mutex);
  225090. }
  225091. void reset() throw()
  225092. {
  225093. pthread_mutex_lock (&mutex);
  225094. triggered = false;
  225095. pthread_mutex_unlock (&mutex);
  225096. }
  225097. private:
  225098. pthread_cond_t condition;
  225099. pthread_mutex_t mutex;
  225100. bool triggered;
  225101. const bool manualReset;
  225102. WaitableEventImpl (const WaitableEventImpl&);
  225103. WaitableEventImpl& operator= (const WaitableEventImpl&);
  225104. };
  225105. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  225106. : internal (new WaitableEventImpl (manualReset))
  225107. {
  225108. }
  225109. WaitableEvent::~WaitableEvent() throw()
  225110. {
  225111. delete static_cast <WaitableEventImpl*> (internal);
  225112. }
  225113. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  225114. {
  225115. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  225116. }
  225117. void WaitableEvent::signal() const throw()
  225118. {
  225119. static_cast <WaitableEventImpl*> (internal)->signal();
  225120. }
  225121. void WaitableEvent::reset() const throw()
  225122. {
  225123. static_cast <WaitableEventImpl*> (internal)->reset();
  225124. }
  225125. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  225126. {
  225127. struct timespec time;
  225128. time.tv_sec = millisecs / 1000;
  225129. time.tv_nsec = (millisecs % 1000) * 1000000;
  225130. nanosleep (&time, 0);
  225131. }
  225132. const juce_wchar File::separator = '/';
  225133. const String File::separatorString ("/");
  225134. const File File::getCurrentWorkingDirectory()
  225135. {
  225136. HeapBlock<char> heapBuffer;
  225137. char localBuffer [1024];
  225138. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  225139. int bufferSize = 4096;
  225140. while (cwd == 0 && errno == ERANGE)
  225141. {
  225142. heapBuffer.malloc (bufferSize);
  225143. cwd = getcwd (heapBuffer, bufferSize - 1);
  225144. bufferSize += 1024;
  225145. }
  225146. return File (String::fromUTF8 (cwd));
  225147. }
  225148. bool File::setAsCurrentWorkingDirectory() const
  225149. {
  225150. return chdir (getFullPathName().toUTF8()) == 0;
  225151. }
  225152. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  225153. typedef struct stat64 juce_statStruct; // (need to use the 64-bit version to work around a simulator bug)
  225154. #else
  225155. typedef struct stat juce_statStruct;
  225156. #endif
  225157. static bool juce_stat (const String& fileName, juce_statStruct& info)
  225158. {
  225159. return fileName.isNotEmpty()
  225160. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  225161. && (stat64 (fileName.toUTF8(), &info) == 0);
  225162. #else
  225163. && (stat (fileName.toUTF8(), &info) == 0);
  225164. #endif
  225165. }
  225166. bool File::isDirectory() const
  225167. {
  225168. juce_statStruct info;
  225169. return fullPath.isEmpty()
  225170. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  225171. }
  225172. bool File::exists() const
  225173. {
  225174. juce_statStruct info;
  225175. return fullPath.isNotEmpty()
  225176. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  225177. && (lstat64 (fullPath.toUTF8(), &info) == 0);
  225178. #else
  225179. && (lstat (fullPath.toUTF8(), &info) == 0);
  225180. #endif
  225181. }
  225182. bool File::existsAsFile() const
  225183. {
  225184. return exists() && ! isDirectory();
  225185. }
  225186. int64 File::getSize() const
  225187. {
  225188. juce_statStruct info;
  225189. return juce_stat (fullPath, info) ? info.st_size : 0;
  225190. }
  225191. bool File::hasWriteAccess() const
  225192. {
  225193. if (exists())
  225194. return access (fullPath.toUTF8(), W_OK) == 0;
  225195. if ((! isDirectory()) && fullPath.containsChar (separator))
  225196. return getParentDirectory().hasWriteAccess();
  225197. return false;
  225198. }
  225199. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  225200. {
  225201. juce_statStruct info;
  225202. if (! juce_stat (fullPath, info))
  225203. return false;
  225204. info.st_mode &= 0777; // Just permissions
  225205. if (shouldBeReadOnly)
  225206. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  225207. else
  225208. // Give everybody write permission?
  225209. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  225210. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  225211. }
  225212. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  225213. {
  225214. modificationTime = 0;
  225215. accessTime = 0;
  225216. creationTime = 0;
  225217. juce_statStruct info;
  225218. if (juce_stat (fullPath, info))
  225219. {
  225220. modificationTime = (int64) info.st_mtime * 1000;
  225221. accessTime = (int64) info.st_atime * 1000;
  225222. creationTime = (int64) info.st_ctime * 1000;
  225223. }
  225224. }
  225225. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  225226. {
  225227. struct utimbuf times;
  225228. times.actime = (time_t) (accessTime / 1000);
  225229. times.modtime = (time_t) (modificationTime / 1000);
  225230. return utime (fullPath.toUTF8(), &times) == 0;
  225231. }
  225232. bool File::deleteFile() const
  225233. {
  225234. if (! exists())
  225235. return true;
  225236. else if (isDirectory())
  225237. return rmdir (fullPath.toUTF8()) == 0;
  225238. else
  225239. return remove (fullPath.toUTF8()) == 0;
  225240. }
  225241. bool File::moveInternal (const File& dest) const
  225242. {
  225243. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  225244. return true;
  225245. if (hasWriteAccess() && copyInternal (dest))
  225246. {
  225247. if (deleteFile())
  225248. return true;
  225249. dest.deleteFile();
  225250. }
  225251. return false;
  225252. }
  225253. void File::createDirectoryInternal (const String& fileName) const
  225254. {
  225255. mkdir (fileName.toUTF8(), 0777);
  225256. }
  225257. int64 juce_fileSetPosition (void* handle, int64 pos)
  225258. {
  225259. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  225260. return pos;
  225261. return -1;
  225262. }
  225263. void FileInputStream::openHandle()
  225264. {
  225265. totalSize = file.getSize();
  225266. const int f = open (file.getFullPathName().toUTF8(), O_RDONLY, 00644);
  225267. if (f != -1)
  225268. fileHandle = (void*) f;
  225269. }
  225270. void FileInputStream::closeHandle()
  225271. {
  225272. if (fileHandle != 0)
  225273. {
  225274. close ((int) (pointer_sized_int) fileHandle);
  225275. fileHandle = 0;
  225276. }
  225277. }
  225278. size_t FileInputStream::readInternal (void* const buffer, const size_t numBytes)
  225279. {
  225280. if (fileHandle != 0)
  225281. return jmax ((ssize_t) 0, ::read ((int) (pointer_sized_int) fileHandle, buffer, numBytes));
  225282. return 0;
  225283. }
  225284. void FileOutputStream::openHandle()
  225285. {
  225286. if (file.exists())
  225287. {
  225288. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  225289. if (f != -1)
  225290. {
  225291. currentPosition = lseek (f, 0, SEEK_END);
  225292. if (currentPosition >= 0)
  225293. fileHandle = (void*) f;
  225294. else
  225295. close (f);
  225296. }
  225297. }
  225298. else
  225299. {
  225300. const int f = open (file.getFullPathName().toUTF8(), O_RDWR + O_CREAT, 00644);
  225301. if (f != -1)
  225302. fileHandle = (void*) f;
  225303. }
  225304. }
  225305. void FileOutputStream::closeHandle()
  225306. {
  225307. if (fileHandle != 0)
  225308. {
  225309. close ((int) (pointer_sized_int) fileHandle);
  225310. fileHandle = 0;
  225311. }
  225312. }
  225313. int FileOutputStream::writeInternal (const void* const data, const int numBytes)
  225314. {
  225315. if (fileHandle != 0)
  225316. return (int) ::write ((int) (pointer_sized_int) fileHandle, data, numBytes);
  225317. return 0;
  225318. }
  225319. void FileOutputStream::flushInternal()
  225320. {
  225321. if (fileHandle != 0)
  225322. fsync ((int) (pointer_sized_int) fileHandle);
  225323. }
  225324. const File juce_getExecutableFile()
  225325. {
  225326. Dl_info exeInfo;
  225327. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  225328. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  225329. }
  225330. // if this file doesn't exist, find a parent of it that does..
  225331. static bool juce_doStatFS (File f, struct statfs& result)
  225332. {
  225333. for (int i = 5; --i >= 0;)
  225334. {
  225335. if (f.exists())
  225336. break;
  225337. f = f.getParentDirectory();
  225338. }
  225339. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  225340. }
  225341. int64 File::getBytesFreeOnVolume() const
  225342. {
  225343. struct statfs buf;
  225344. if (juce_doStatFS (*this, buf))
  225345. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  225346. return 0;
  225347. }
  225348. int64 File::getVolumeTotalSize() const
  225349. {
  225350. struct statfs buf;
  225351. if (juce_doStatFS (*this, buf))
  225352. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  225353. return 0;
  225354. }
  225355. const String File::getVolumeLabel() const
  225356. {
  225357. #if JUCE_MAC
  225358. struct VolAttrBuf
  225359. {
  225360. u_int32_t length;
  225361. attrreference_t mountPointRef;
  225362. char mountPointSpace [MAXPATHLEN];
  225363. } attrBuf;
  225364. struct attrlist attrList;
  225365. zerostruct (attrList);
  225366. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  225367. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  225368. File f (*this);
  225369. for (;;)
  225370. {
  225371. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  225372. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  225373. (int) attrBuf.mountPointRef.attr_length);
  225374. const File parent (f.getParentDirectory());
  225375. if (f == parent)
  225376. break;
  225377. f = parent;
  225378. }
  225379. #endif
  225380. return String::empty;
  225381. }
  225382. int File::getVolumeSerialNumber() const
  225383. {
  225384. return 0; // xxx
  225385. }
  225386. void juce_runSystemCommand (const String& command)
  225387. {
  225388. int result = system (command.toUTF8());
  225389. (void) result;
  225390. }
  225391. const String juce_getOutputFromCommand (const String& command)
  225392. {
  225393. // slight bodge here, as we just pipe the output into a temp file and read it...
  225394. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  225395. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  225396. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  225397. String result (tempFile.loadFileAsString());
  225398. tempFile.deleteFile();
  225399. return result;
  225400. }
  225401. class InterProcessLock::Pimpl
  225402. {
  225403. public:
  225404. Pimpl (const String& name, const int timeOutMillisecs)
  225405. : handle (0), refCount (1)
  225406. {
  225407. #if JUCE_MAC
  225408. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  225409. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  225410. #else
  225411. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  225412. #endif
  225413. temp.create();
  225414. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  225415. if (handle != 0)
  225416. {
  225417. struct flock fl;
  225418. zerostruct (fl);
  225419. fl.l_whence = SEEK_SET;
  225420. fl.l_type = F_WRLCK;
  225421. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  225422. for (;;)
  225423. {
  225424. const int result = fcntl (handle, F_SETLK, &fl);
  225425. if (result >= 0)
  225426. return;
  225427. if (errno != EINTR)
  225428. {
  225429. if (timeOutMillisecs == 0
  225430. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  225431. break;
  225432. Thread::sleep (10);
  225433. }
  225434. }
  225435. }
  225436. closeFile();
  225437. }
  225438. ~Pimpl()
  225439. {
  225440. closeFile();
  225441. }
  225442. void closeFile()
  225443. {
  225444. if (handle != 0)
  225445. {
  225446. struct flock fl;
  225447. zerostruct (fl);
  225448. fl.l_whence = SEEK_SET;
  225449. fl.l_type = F_UNLCK;
  225450. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  225451. {}
  225452. close (handle);
  225453. handle = 0;
  225454. }
  225455. }
  225456. int handle, refCount;
  225457. };
  225458. InterProcessLock::InterProcessLock (const String& name_)
  225459. : name (name_)
  225460. {
  225461. }
  225462. InterProcessLock::~InterProcessLock()
  225463. {
  225464. }
  225465. bool InterProcessLock::enter (const int timeOutMillisecs)
  225466. {
  225467. const ScopedLock sl (lock);
  225468. if (pimpl == 0)
  225469. {
  225470. pimpl = new Pimpl (name, timeOutMillisecs);
  225471. if (pimpl->handle == 0)
  225472. pimpl = 0;
  225473. }
  225474. else
  225475. {
  225476. pimpl->refCount++;
  225477. }
  225478. return pimpl != 0;
  225479. }
  225480. void InterProcessLock::exit()
  225481. {
  225482. const ScopedLock sl (lock);
  225483. // Trying to release the lock too many times!
  225484. jassert (pimpl != 0);
  225485. if (pimpl != 0 && --(pimpl->refCount) == 0)
  225486. pimpl = 0;
  225487. }
  225488. void JUCE_API juce_threadEntryPoint (void*);
  225489. void* threadEntryProc (void* userData)
  225490. {
  225491. JUCE_AUTORELEASEPOOL
  225492. juce_threadEntryPoint (userData);
  225493. return 0;
  225494. }
  225495. void* juce_createThread (void* userData)
  225496. {
  225497. pthread_t handle = 0;
  225498. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  225499. {
  225500. pthread_detach (handle);
  225501. return (void*) handle;
  225502. }
  225503. return 0;
  225504. }
  225505. void juce_killThread (void* handle)
  225506. {
  225507. if (handle != 0)
  225508. pthread_cancel ((pthread_t) handle);
  225509. }
  225510. void juce_setCurrentThreadName (const String& /*name*/)
  225511. {
  225512. }
  225513. bool juce_setThreadPriority (void* handle, int priority)
  225514. {
  225515. struct sched_param param;
  225516. int policy;
  225517. priority = jlimit (0, 10, priority);
  225518. if (handle == 0)
  225519. handle = (void*) pthread_self();
  225520. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) != 0)
  225521. return false;
  225522. policy = priority == 0 ? SCHED_OTHER : SCHED_RR;
  225523. const int minPriority = sched_get_priority_min (policy);
  225524. const int maxPriority = sched_get_priority_max (policy);
  225525. param.sched_priority = ((maxPriority - minPriority) * priority) / 10 + minPriority;
  225526. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  225527. }
  225528. Thread::ThreadID Thread::getCurrentThreadId()
  225529. {
  225530. return (ThreadID) pthread_self();
  225531. }
  225532. void Thread::yield()
  225533. {
  225534. sched_yield();
  225535. }
  225536. /* Remove this macro if you're having problems compiling the cpu affinity
  225537. calls (the API for these has changed about quite a bit in various Linux
  225538. versions, and a lot of distros seem to ship with obsolete versions)
  225539. */
  225540. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  225541. #define SUPPORT_AFFINITIES 1
  225542. #endif
  225543. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  225544. {
  225545. #if SUPPORT_AFFINITIES
  225546. cpu_set_t affinity;
  225547. CPU_ZERO (&affinity);
  225548. for (int i = 0; i < 32; ++i)
  225549. if ((affinityMask & (1 << i)) != 0)
  225550. CPU_SET (i, &affinity);
  225551. /*
  225552. N.B. If this line causes a compile error, then you've probably not got the latest
  225553. version of glibc installed.
  225554. If you don't want to update your copy of glibc and don't care about cpu affinities,
  225555. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  225556. */
  225557. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  225558. sched_yield();
  225559. #else
  225560. /* affinities aren't supported because either the appropriate header files weren't found,
  225561. or the SUPPORT_AFFINITIES macro was turned off
  225562. */
  225563. jassertfalse;
  225564. #endif
  225565. }
  225566. /*** End of inlined file: juce_posix_SharedCode.h ***/
  225567. /*** Start of inlined file: juce_mac_Files.mm ***/
  225568. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225569. // compiled on its own).
  225570. #if JUCE_INCLUDED_FILE
  225571. /*
  225572. Note that a lot of methods that you'd expect to find in this file actually
  225573. live in juce_posix_SharedCode.h!
  225574. */
  225575. bool File::copyInternal (const File& dest) const
  225576. {
  225577. const ScopedAutoReleasePool pool;
  225578. NSFileManager* fm = [NSFileManager defaultManager];
  225579. return [fm fileExistsAtPath: juceStringToNS (fullPath)]
  225580. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  225581. && [fm copyItemAtPath: juceStringToNS (fullPath)
  225582. toPath: juceStringToNS (dest.getFullPathName())
  225583. error: nil];
  225584. #else
  225585. && [fm copyPath: juceStringToNS (fullPath)
  225586. toPath: juceStringToNS (dest.getFullPathName())
  225587. handler: nil];
  225588. #endif
  225589. }
  225590. void File::findFileSystemRoots (Array<File>& destArray)
  225591. {
  225592. destArray.add (File ("/"));
  225593. }
  225594. static bool isFileOnDriveType (const File& f, const char* const* types)
  225595. {
  225596. struct statfs buf;
  225597. if (juce_doStatFS (f, buf))
  225598. {
  225599. const String type (buf.f_fstypename);
  225600. while (*types != 0)
  225601. if (type.equalsIgnoreCase (*types++))
  225602. return true;
  225603. }
  225604. return false;
  225605. }
  225606. bool File::isOnCDRomDrive() const
  225607. {
  225608. const char* const cdTypes[] = { "cd9660", "cdfs", "cddafs", "udf", 0 };
  225609. return isFileOnDriveType (*this, cdTypes);
  225610. }
  225611. bool File::isOnHardDisk() const
  225612. {
  225613. const char* const nonHDTypes[] = { "nfs", "smbfs", "ramfs", 0 };
  225614. return ! (isOnCDRomDrive() || isFileOnDriveType (*this, nonHDTypes));
  225615. }
  225616. bool File::isOnRemovableDrive() const
  225617. {
  225618. #if JUCE_IOS
  225619. return false; // xxx is this possible?
  225620. #else
  225621. const ScopedAutoReleasePool pool;
  225622. BOOL removable = false;
  225623. [[NSWorkspace sharedWorkspace]
  225624. getFileSystemInfoForPath: juceStringToNS (getFullPathName())
  225625. isRemovable: &removable
  225626. isWritable: nil
  225627. isUnmountable: nil
  225628. description: nil
  225629. type: nil];
  225630. return removable;
  225631. #endif
  225632. }
  225633. static bool juce_isHiddenFile (const String& path)
  225634. {
  225635. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6
  225636. const ScopedAutoReleasePool pool;
  225637. NSNumber* hidden = nil;
  225638. NSError* err = nil;
  225639. return [[NSURL fileURLWithPath: juceStringToNS (path)]
  225640. getResourceValue: &hidden forKey: NSURLIsHiddenKey error: &err]
  225641. && [hidden boolValue];
  225642. #else
  225643. #if JUCE_IOS
  225644. return File (path).getFileName().startsWithChar ('.');
  225645. #else
  225646. FSRef ref;
  225647. LSItemInfoRecord info;
  225648. return FSPathMakeRefWithOptions ((const UInt8*) path.toUTF8(), kFSPathMakeRefDoNotFollowLeafSymlink, &ref, 0) == noErr
  225649. && LSCopyItemInfoForRef (&ref, kLSRequestBasicFlagsOnly, &info) == noErr
  225650. && (info.flags & kLSItemInfoIsInvisible) != 0;
  225651. #endif
  225652. #endif
  225653. }
  225654. bool File::isHidden() const
  225655. {
  225656. return juce_isHiddenFile (getFullPathName());
  225657. }
  225658. #if JUCE_IOS
  225659. static const String getIOSSystemLocation (NSSearchPathDirectory type)
  225660. {
  225661. return nsStringToJuce ([NSSearchPathForDirectoriesInDomains (type, NSUserDomainMask, YES)
  225662. objectAtIndex: 0]);
  225663. }
  225664. #endif
  225665. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  225666. const File File::getSpecialLocation (const SpecialLocationType type)
  225667. {
  225668. const ScopedAutoReleasePool pool;
  225669. String resultPath;
  225670. switch (type)
  225671. {
  225672. case userHomeDirectory: resultPath = nsStringToJuce (NSHomeDirectory()); break;
  225673. #if JUCE_IOS
  225674. case userDocumentsDirectory: resultPath = getIOSSystemLocation (NSDocumentDirectory); break;
  225675. case userDesktopDirectory: resultPath = getIOSSystemLocation (NSDesktopDirectory); break;
  225676. case tempDirectory:
  225677. {
  225678. File tmp (getIOSSystemLocation (NSCachesDirectory));
  225679. tmp = tmp.getChildFile (juce_getExecutableFile().getFileNameWithoutExtension());
  225680. tmp.createDirectory();
  225681. return tmp.getFullPathName();
  225682. }
  225683. #else
  225684. case userDocumentsDirectory: resultPath = "~/Documents"; break;
  225685. case userDesktopDirectory: resultPath = "~/Desktop"; break;
  225686. case tempDirectory:
  225687. {
  225688. File tmp ("~/Library/Caches/" + juce_getExecutableFile().getFileNameWithoutExtension());
  225689. tmp.createDirectory();
  225690. return tmp.getFullPathName();
  225691. }
  225692. #endif
  225693. case userMusicDirectory: resultPath = "~/Music"; break;
  225694. case userMoviesDirectory: resultPath = "~/Movies"; break;
  225695. case userApplicationDataDirectory: resultPath = "~/Library"; break;
  225696. case commonApplicationDataDirectory: resultPath = "/Library"; break;
  225697. case globalApplicationsDirectory: resultPath = "/Applications"; break;
  225698. case invokedExecutableFile:
  225699. if (juce_Argv0 != 0)
  225700. return File (String::fromUTF8 (juce_Argv0));
  225701. // deliberate fall-through...
  225702. case currentExecutableFile:
  225703. return juce_getExecutableFile();
  225704. case currentApplicationFile:
  225705. {
  225706. const File exe (juce_getExecutableFile());
  225707. const File parent (exe.getParentDirectory());
  225708. #if JUCE_IOS
  225709. return parent;
  225710. #else
  225711. return parent.getFullPathName().endsWithIgnoreCase ("Contents/MacOS")
  225712. ? parent.getParentDirectory().getParentDirectory()
  225713. : exe;
  225714. #endif
  225715. }
  225716. case hostApplicationPath:
  225717. {
  225718. unsigned int size = 8192;
  225719. HeapBlock<char> buffer;
  225720. buffer.calloc (size + 8);
  225721. _NSGetExecutablePath (buffer.getData(), &size);
  225722. return String::fromUTF8 (buffer, size);
  225723. }
  225724. default:
  225725. jassertfalse; // unknown type?
  225726. break;
  225727. }
  225728. if (resultPath.isNotEmpty())
  225729. return File (PlatformUtilities::convertToPrecomposedUnicode (resultPath));
  225730. return File::nonexistent;
  225731. }
  225732. const String File::getVersion() const
  225733. {
  225734. const ScopedAutoReleasePool pool;
  225735. String result;
  225736. NSBundle* bundle = [NSBundle bundleWithPath: juceStringToNS (getFullPathName())];
  225737. if (bundle != 0)
  225738. {
  225739. NSDictionary* info = [bundle infoDictionary];
  225740. if (info != 0)
  225741. {
  225742. NSString* name = [info valueForKey: @"CFBundleShortVersionString"];
  225743. if (name != nil)
  225744. result = nsStringToJuce (name);
  225745. }
  225746. }
  225747. return result;
  225748. }
  225749. const File File::getLinkedTarget() const
  225750. {
  225751. #if JUCE_IOS || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MIN_ALLOWED >= MAC_OS_X_VERSION_10_5)
  225752. NSString* dest = [[NSFileManager defaultManager] destinationOfSymbolicLinkAtPath: juceStringToNS (getFullPathName()) error: nil];
  225753. #else
  225754. // (the cast here avoids a deprecation warning)
  225755. NSString* dest = [((id) [NSFileManager defaultManager]) pathContentOfSymbolicLinkAtPath: juceStringToNS (getFullPathName())];
  225756. #endif
  225757. if (dest != nil)
  225758. return File (nsStringToJuce (dest));
  225759. return *this;
  225760. }
  225761. bool File::moveToTrash() const
  225762. {
  225763. if (! exists())
  225764. return true;
  225765. #if JUCE_IOS
  225766. return deleteFile(); //xxx is there a trashcan on the iPhone?
  225767. #else
  225768. const ScopedAutoReleasePool pool;
  225769. NSString* p = juceStringToNS (getFullPathName());
  225770. return [[NSWorkspace sharedWorkspace]
  225771. performFileOperation: NSWorkspaceRecycleOperation
  225772. source: [p stringByDeletingLastPathComponent]
  225773. destination: @""
  225774. files: [NSArray arrayWithObject: [p lastPathComponent]]
  225775. tag: nil ];
  225776. #endif
  225777. }
  225778. class DirectoryIterator::NativeIterator::Pimpl
  225779. {
  225780. public:
  225781. Pimpl (const File& directory, const String& wildCard_)
  225782. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  225783. wildCard (wildCard_),
  225784. enumerator (0)
  225785. {
  225786. const ScopedAutoReleasePool pool;
  225787. enumerator = [[[NSFileManager defaultManager] enumeratorAtPath: juceStringToNS (directory.getFullPathName())] retain];
  225788. wildcardUTF8 = wildCard.toUTF8();
  225789. }
  225790. ~Pimpl()
  225791. {
  225792. [enumerator release];
  225793. }
  225794. bool next (String& filenameFound,
  225795. bool* const isDir, bool* const isHidden, int64* const fileSize,
  225796. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  225797. {
  225798. const ScopedAutoReleasePool pool;
  225799. for (;;)
  225800. {
  225801. NSString* file;
  225802. if (enumerator == 0 || (file = [enumerator nextObject]) == 0)
  225803. return false;
  225804. [enumerator skipDescendents];
  225805. filenameFound = nsStringToJuce (file);
  225806. if (fnmatch (wildcardUTF8, filenameFound.toUTF8(), FNM_CASEFOLD) != 0)
  225807. continue;
  225808. const String path (parentDir + filenameFound);
  225809. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  225810. {
  225811. juce_statStruct info;
  225812. const bool statOk = juce_stat (path, info);
  225813. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  225814. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  225815. if (modTime != 0) *modTime = statOk ? (int64) info.st_mtime * 1000 : 0;
  225816. if (creationTime != 0) *creationTime = statOk ? (int64) info.st_ctime * 1000 : 0;
  225817. }
  225818. if (isHidden != 0)
  225819. *isHidden = juce_isHiddenFile (path);
  225820. if (isReadOnly != 0)
  225821. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  225822. return true;
  225823. }
  225824. }
  225825. private:
  225826. String parentDir, wildCard;
  225827. const char* wildcardUTF8;
  225828. NSDirectoryEnumerator* enumerator;
  225829. Pimpl (const Pimpl&);
  225830. Pimpl& operator= (const Pimpl&);
  225831. };
  225832. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  225833. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  225834. {
  225835. }
  225836. DirectoryIterator::NativeIterator::~NativeIterator()
  225837. {
  225838. }
  225839. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  225840. bool* const isDir, bool* const isHidden, int64* const fileSize,
  225841. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  225842. {
  225843. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  225844. }
  225845. bool juce_launchExecutable (const String& pathAndArguments)
  225846. {
  225847. const char* const argv[4] = { "/bin/sh", "-c", pathAndArguments.toUTF8(), 0 };
  225848. const int cpid = fork();
  225849. if (cpid == 0)
  225850. {
  225851. // Child process
  225852. if (execve (argv[0], (char**) argv, 0) < 0)
  225853. exit (0);
  225854. }
  225855. else
  225856. {
  225857. if (cpid < 0)
  225858. return false;
  225859. }
  225860. return true;
  225861. }
  225862. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  225863. {
  225864. #if JUCE_IOS
  225865. return [[UIApplication sharedApplication] openURL: [NSURL fileURLWithPath: juceStringToNS (fileName)]];
  225866. #else
  225867. const ScopedAutoReleasePool pool;
  225868. if (parameters.isEmpty())
  225869. {
  225870. return [[NSWorkspace sharedWorkspace] openFile: juceStringToNS (fileName)]
  225871. || [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: juceStringToNS (fileName)]];
  225872. }
  225873. bool ok = false;
  225874. if (PlatformUtilities::isBundle (fileName))
  225875. {
  225876. NSMutableArray* urls = [NSMutableArray array];
  225877. StringArray docs;
  225878. docs.addTokens (parameters, true);
  225879. for (int i = 0; i < docs.size(); ++i)
  225880. [urls addObject: juceStringToNS (docs[i])];
  225881. ok = [[NSWorkspace sharedWorkspace] openURLs: urls
  225882. withAppBundleIdentifier: [[NSBundle bundleWithPath: juceStringToNS (fileName)] bundleIdentifier]
  225883. options: 0
  225884. additionalEventParamDescriptor: nil
  225885. launchIdentifiers: nil];
  225886. }
  225887. else if (File (fileName).exists())
  225888. {
  225889. ok = juce_launchExecutable ("\"" + fileName + "\" " + parameters);
  225890. }
  225891. return ok;
  225892. #endif
  225893. }
  225894. void File::revealToUser() const
  225895. {
  225896. #if ! JUCE_IOS
  225897. if (exists())
  225898. [[NSWorkspace sharedWorkspace] selectFile: juceStringToNS (getFullPathName()) inFileViewerRootedAtPath: @""];
  225899. else if (getParentDirectory().exists())
  225900. getParentDirectory().revealToUser();
  225901. #endif
  225902. }
  225903. #if ! JUCE_IOS
  225904. bool PlatformUtilities::makeFSRefFromPath (FSRef* destFSRef, const String& path)
  225905. {
  225906. return FSPathMakeRef ((const UInt8*) path.toUTF8(), destFSRef, 0) == noErr;
  225907. }
  225908. const String PlatformUtilities::makePathFromFSRef (FSRef* file)
  225909. {
  225910. char path [2048];
  225911. zerostruct (path);
  225912. if (FSRefMakePath (file, (UInt8*) path, sizeof (path) - 1) == noErr)
  225913. return PlatformUtilities::convertToPrecomposedUnicode (String::fromUTF8 (path));
  225914. return String::empty;
  225915. }
  225916. #endif
  225917. OSType PlatformUtilities::getTypeOfFile (const String& filename)
  225918. {
  225919. const ScopedAutoReleasePool pool;
  225920. #if JUCE_IOS || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MIN_ALLOWED >= MAC_OS_X_VERSION_10_5)
  225921. NSDictionary* fileDict = [[NSFileManager defaultManager] attributesOfItemAtPath: juceStringToNS (filename) error: nil];
  225922. #else
  225923. // (the cast here avoids a deprecation warning)
  225924. NSDictionary* fileDict = [((id) [NSFileManager defaultManager]) fileAttributesAtPath: juceStringToNS (filename) traverseLink: NO];
  225925. #endif
  225926. return [fileDict fileHFSTypeCode];
  225927. }
  225928. bool PlatformUtilities::isBundle (const String& filename)
  225929. {
  225930. #if JUCE_IOS
  225931. return false; // xxx can't find a sensible way to do this without trying to open the bundle..
  225932. #else
  225933. const ScopedAutoReleasePool pool;
  225934. return [[NSWorkspace sharedWorkspace] isFilePackageAtPath: juceStringToNS (filename)];
  225935. #endif
  225936. }
  225937. #endif
  225938. /*** End of inlined file: juce_mac_Files.mm ***/
  225939. #if JUCE_IOS
  225940. /*** Start of inlined file: juce_iphone_MiscUtilities.mm ***/
  225941. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225942. // compiled on its own).
  225943. #if JUCE_INCLUDED_FILE
  225944. END_JUCE_NAMESPACE
  225945. @interface JuceAppStartupDelegate : NSObject <UIApplicationDelegate>
  225946. {
  225947. }
  225948. - (void) applicationDidFinishLaunching: (UIApplication*) application;
  225949. - (void) applicationWillTerminate: (UIApplication*) application;
  225950. @end
  225951. @implementation JuceAppStartupDelegate
  225952. - (void) applicationDidFinishLaunching: (UIApplication*) application
  225953. {
  225954. initialiseJuce_GUI();
  225955. if (! JUCEApplication::createInstance()->initialiseApp (String::empty))
  225956. exit (0);
  225957. }
  225958. - (void) applicationWillTerminate: (UIApplication*) application
  225959. {
  225960. JUCEApplication::appWillTerminateByForce();
  225961. }
  225962. @end
  225963. BEGIN_JUCE_NAMESPACE
  225964. int juce_iOSMain (int argc, const char* argv[])
  225965. {
  225966. return UIApplicationMain (argc, const_cast<char**> (argv), nil, @"JuceAppStartupDelegate");
  225967. }
  225968. ScopedAutoReleasePool::ScopedAutoReleasePool()
  225969. {
  225970. pool = [[NSAutoreleasePool alloc] init];
  225971. }
  225972. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  225973. {
  225974. [((NSAutoreleasePool*) pool) release];
  225975. }
  225976. void PlatformUtilities::beep()
  225977. {
  225978. //xxx
  225979. //AudioServicesPlaySystemSound ();
  225980. }
  225981. void PlatformUtilities::addItemToDock (const File& file)
  225982. {
  225983. }
  225984. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  225985. END_JUCE_NAMESPACE
  225986. @interface JuceAlertBoxDelegate : NSObject
  225987. {
  225988. @public
  225989. bool clickedOk;
  225990. }
  225991. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex;
  225992. @end
  225993. @implementation JuceAlertBoxDelegate
  225994. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex
  225995. {
  225996. clickedOk = (buttonIndex == 0);
  225997. alertView.hidden = true;
  225998. }
  225999. @end
  226000. BEGIN_JUCE_NAMESPACE
  226001. // (This function is used directly by other bits of code)
  226002. bool juce_iPhoneShowModalAlert (const String& title,
  226003. const String& bodyText,
  226004. NSString* okButtonText,
  226005. NSString* cancelButtonText)
  226006. {
  226007. const ScopedAutoReleasePool pool;
  226008. JuceAlertBoxDelegate* callback = [[JuceAlertBoxDelegate alloc] init];
  226009. UIAlertView* alert = [[UIAlertView alloc] initWithTitle: juceStringToNS (title)
  226010. message: juceStringToNS (bodyText)
  226011. delegate: callback
  226012. cancelButtonTitle: okButtonText
  226013. otherButtonTitles: cancelButtonText, nil];
  226014. [alert retain];
  226015. [alert show];
  226016. while (! alert.hidden && alert.superview != nil)
  226017. [[NSRunLoop mainRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  226018. const bool result = callback->clickedOk;
  226019. [alert release];
  226020. [callback release];
  226021. return result;
  226022. }
  226023. bool AlertWindow::showNativeDialogBox (const String& title,
  226024. const String& bodyText,
  226025. bool isOkCancel)
  226026. {
  226027. return juce_iPhoneShowModalAlert (title, bodyText,
  226028. @"OK",
  226029. isOkCancel ? @"Cancel" : nil);
  226030. }
  226031. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  226032. {
  226033. jassertfalse; // no such thing on the iphone!
  226034. return false;
  226035. }
  226036. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  226037. {
  226038. jassertfalse; // no such thing on the iphone!
  226039. return false;
  226040. }
  226041. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  226042. {
  226043. [[UIApplication sharedApplication] setIdleTimerDisabled: ! isEnabled];
  226044. }
  226045. bool Desktop::isScreenSaverEnabled()
  226046. {
  226047. return ! [[UIApplication sharedApplication] isIdleTimerDisabled];
  226048. }
  226049. #endif
  226050. #endif
  226051. /*** End of inlined file: juce_iphone_MiscUtilities.mm ***/
  226052. #else
  226053. /*** Start of inlined file: juce_mac_MiscUtilities.mm ***/
  226054. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226055. // compiled on its own).
  226056. #if JUCE_INCLUDED_FILE
  226057. ScopedAutoReleasePool::ScopedAutoReleasePool()
  226058. {
  226059. pool = [[NSAutoreleasePool alloc] init];
  226060. }
  226061. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  226062. {
  226063. [((NSAutoreleasePool*) pool) release];
  226064. }
  226065. void PlatformUtilities::beep()
  226066. {
  226067. NSBeep();
  226068. }
  226069. void PlatformUtilities::addItemToDock (const File& file)
  226070. {
  226071. // check that it's not already there...
  226072. if (! juce_getOutputFromCommand ("defaults read com.apple.dock persistent-apps")
  226073. .containsIgnoreCase (file.getFullPathName()))
  226074. {
  226075. 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>"
  226076. + file.getFullPathName() + "</string><key>_CFURLStringType</key><integer>0</integer></dict></dict></dict>\"");
  226077. juce_runSystemCommand ("osascript -e \"tell application \\\"Dock\\\" to quit\"");
  226078. }
  226079. }
  226080. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  226081. bool AlertWindow::showNativeDialogBox (const String& title,
  226082. const String& bodyText,
  226083. bool isOkCancel)
  226084. {
  226085. const ScopedAutoReleasePool pool;
  226086. return NSRunAlertPanel (juceStringToNS (title),
  226087. juceStringToNS (bodyText),
  226088. @"Ok",
  226089. isOkCancel ? @"Cancel" : nil,
  226090. nil) == NSAlertDefaultReturn;
  226091. }
  226092. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool /*canMoveFiles*/)
  226093. {
  226094. if (files.size() == 0)
  226095. return false;
  226096. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource(0);
  226097. if (draggingSource == 0)
  226098. {
  226099. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  226100. return false;
  226101. }
  226102. Component* sourceComp = draggingSource->getComponentUnderMouse();
  226103. if (sourceComp == 0)
  226104. {
  226105. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  226106. return false;
  226107. }
  226108. const ScopedAutoReleasePool pool;
  226109. NSView* view = (NSView*) sourceComp->getWindowHandle();
  226110. if (view == 0)
  226111. return false;
  226112. NSPasteboard* pboard = [NSPasteboard pasteboardWithName: NSDragPboard];
  226113. [pboard declareTypes: [NSArray arrayWithObject: NSFilenamesPboardType]
  226114. owner: nil];
  226115. NSMutableArray* filesArray = [NSMutableArray arrayWithCapacity: 4];
  226116. for (int i = 0; i < files.size(); ++i)
  226117. [filesArray addObject: juceStringToNS (files[i])];
  226118. [pboard setPropertyList: filesArray
  226119. forType: NSFilenamesPboardType];
  226120. NSPoint dragPosition = [view convertPoint: [[[view window] currentEvent] locationInWindow]
  226121. fromView: nil];
  226122. dragPosition.x -= 16;
  226123. dragPosition.y -= 16;
  226124. [view dragImage: [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (files[0])]
  226125. at: dragPosition
  226126. offset: NSMakeSize (0, 0)
  226127. event: [[view window] currentEvent]
  226128. pasteboard: pboard
  226129. source: view
  226130. slideBack: YES];
  226131. return true;
  226132. }
  226133. bool DragAndDropContainer::performExternalDragDropOfText (const String& /*text*/)
  226134. {
  226135. jassertfalse; // not implemented!
  226136. return false;
  226137. }
  226138. bool Desktop::canUseSemiTransparentWindows() throw()
  226139. {
  226140. return true;
  226141. }
  226142. const Point<int> Desktop::getMousePosition()
  226143. {
  226144. const ScopedAutoReleasePool pool;
  226145. const NSPoint p ([NSEvent mouseLocation]);
  226146. return Point<int> (roundToInt (p.x), roundToInt ([[[NSScreen screens] objectAtIndex: 0] frame].size.height - p.y));
  226147. }
  226148. void Desktop::setMousePosition (const Point<int>& newPosition)
  226149. {
  226150. // this rubbish needs to be done around the warp call, to avoid causing a
  226151. // bizarre glitch..
  226152. CGAssociateMouseAndMouseCursorPosition (false);
  226153. CGWarpMouseCursorPosition (CGPointMake (newPosition.getX(), newPosition.getY()));
  226154. CGAssociateMouseAndMouseCursorPosition (true);
  226155. }
  226156. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  226157. {
  226158. return upright;
  226159. }
  226160. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  226161. class ScreenSaverDefeater : public Timer,
  226162. public DeletedAtShutdown
  226163. {
  226164. public:
  226165. ScreenSaverDefeater()
  226166. {
  226167. startTimer (10000);
  226168. timerCallback();
  226169. }
  226170. ~ScreenSaverDefeater() {}
  226171. void timerCallback()
  226172. {
  226173. if (Process::isForegroundProcess())
  226174. UpdateSystemActivity (UsrActivity);
  226175. }
  226176. };
  226177. static ScreenSaverDefeater* screenSaverDefeater = 0;
  226178. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  226179. {
  226180. if (isEnabled)
  226181. deleteAndZero (screenSaverDefeater);
  226182. else if (screenSaverDefeater == 0)
  226183. screenSaverDefeater = new ScreenSaverDefeater();
  226184. }
  226185. bool Desktop::isScreenSaverEnabled()
  226186. {
  226187. return screenSaverDefeater == 0;
  226188. }
  226189. #else
  226190. static IOPMAssertionID screenSaverDisablerID = 0;
  226191. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  226192. {
  226193. if (isEnabled)
  226194. {
  226195. if (screenSaverDisablerID != 0)
  226196. {
  226197. IOPMAssertionRelease (screenSaverDisablerID);
  226198. screenSaverDisablerID = 0;
  226199. }
  226200. }
  226201. else
  226202. {
  226203. if (screenSaverDisablerID == 0)
  226204. {
  226205. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  226206. IOPMAssertionCreateWithName (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  226207. CFSTR ("Juce"), &screenSaverDisablerID);
  226208. #else
  226209. IOPMAssertionCreate (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  226210. &screenSaverDisablerID);
  226211. #endif
  226212. }
  226213. }
  226214. }
  226215. bool Desktop::isScreenSaverEnabled()
  226216. {
  226217. return screenSaverDisablerID == 0;
  226218. }
  226219. #endif
  226220. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  226221. {
  226222. const ScopedAutoReleasePool pool;
  226223. monitorCoords.clear();
  226224. NSArray* screens = [NSScreen screens];
  226225. const CGFloat mainScreenBottom = [[[NSScreen screens] objectAtIndex: 0] frame].size.height;
  226226. for (unsigned int i = 0; i < [screens count]; ++i)
  226227. {
  226228. NSScreen* s = (NSScreen*) [screens objectAtIndex: i];
  226229. NSRect r = clipToWorkArea ? [s visibleFrame]
  226230. : [s frame];
  226231. r.origin.y = mainScreenBottom - (r.origin.y + r.size.height);
  226232. monitorCoords.add (convertToRectInt (r));
  226233. }
  226234. jassert (monitorCoords.size() > 0);
  226235. }
  226236. #endif
  226237. #endif
  226238. /*** End of inlined file: juce_mac_MiscUtilities.mm ***/
  226239. #endif
  226240. /*** Start of inlined file: juce_mac_Debugging.mm ***/
  226241. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226242. // compiled on its own).
  226243. #if JUCE_INCLUDED_FILE
  226244. void Logger::outputDebugString (const String& text)
  226245. {
  226246. std::cerr << text << std::endl;
  226247. }
  226248. bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger()
  226249. {
  226250. static char testResult = 0;
  226251. if (testResult == 0)
  226252. {
  226253. struct kinfo_proc info;
  226254. int m[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid() };
  226255. size_t sz = sizeof (info);
  226256. sysctl (m, 4, &info, &sz, 0, 0);
  226257. testResult = ((info.kp_proc.p_flag & P_TRACED) != 0) ? 1 : -1;
  226258. }
  226259. return testResult > 0;
  226260. }
  226261. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  226262. {
  226263. return juce_isRunningUnderDebugger();
  226264. }
  226265. #endif
  226266. /*** End of inlined file: juce_mac_Debugging.mm ***/
  226267. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  226268. #if JUCE_IOS
  226269. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  226270. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226271. // compiled on its own).
  226272. #if JUCE_INCLUDED_FILE
  226273. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  226274. #define SUPPORT_10_4_FONTS 1
  226275. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  226276. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  226277. #define SUPPORT_ONLY_10_4_FONTS 1
  226278. #endif
  226279. END_JUCE_NAMESPACE
  226280. @interface NSFont (PrivateHack)
  226281. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  226282. @end
  226283. BEGIN_JUCE_NAMESPACE
  226284. #endif
  226285. class MacTypeface : public Typeface
  226286. {
  226287. public:
  226288. MacTypeface (const Font& font)
  226289. : Typeface (font.getTypefaceName())
  226290. {
  226291. const ScopedAutoReleasePool pool;
  226292. renderingTransform = CGAffineTransformIdentity;
  226293. bool needsItalicTransform = false;
  226294. #if JUCE_IOS
  226295. NSString* fontName = juceStringToNS (font.getTypefaceName());
  226296. if (font.isItalic() || font.isBold())
  226297. {
  226298. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  226299. for (NSString* i in familyFonts)
  226300. {
  226301. const String fn (nsStringToJuce (i));
  226302. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  226303. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  226304. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  226305. || afterDash.containsIgnoreCase ("italic")
  226306. || fn.endsWithIgnoreCase ("oblique")
  226307. || fn.endsWithIgnoreCase ("italic");
  226308. if (probablyBold == font.isBold()
  226309. && probablyItalic == font.isItalic())
  226310. {
  226311. fontName = i;
  226312. needsItalicTransform = false;
  226313. break;
  226314. }
  226315. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  226316. {
  226317. fontName = i;
  226318. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  226319. }
  226320. }
  226321. if (needsItalicTransform)
  226322. renderingTransform.c = 0.15f;
  226323. }
  226324. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  226325. const int ascender = abs (CGFontGetAscent (fontRef));
  226326. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  226327. ascent = ascender / totalHeight;
  226328. unitsToHeightScaleFactor = 1.0f / totalHeight;
  226329. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  226330. #else
  226331. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  226332. if (font.isItalic())
  226333. {
  226334. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  226335. toHaveTrait: NSItalicFontMask];
  226336. if (newFont == nsFont)
  226337. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  226338. nsFont = newFont;
  226339. }
  226340. if (font.isBold())
  226341. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  226342. [nsFont retain];
  226343. ascent = std::abs ((float) [nsFont ascender]);
  226344. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  226345. ascent /= totalSize;
  226346. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  226347. if (needsItalicTransform)
  226348. {
  226349. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  226350. renderingTransform.c = 0.15f;
  226351. }
  226352. #if SUPPORT_ONLY_10_4_FONTS
  226353. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  226354. if (atsFont == 0)
  226355. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  226356. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  226357. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  226358. unitsToHeightScaleFactor = 1.0f / totalHeight;
  226359. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  226360. #else
  226361. #if SUPPORT_10_4_FONTS
  226362. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226363. {
  226364. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  226365. if (atsFont == 0)
  226366. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  226367. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  226368. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  226369. unitsToHeightScaleFactor = 1.0f / totalHeight;
  226370. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  226371. }
  226372. else
  226373. #endif
  226374. {
  226375. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  226376. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  226377. unitsToHeightScaleFactor = 1.0f / totalHeight;
  226378. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  226379. }
  226380. #endif
  226381. #endif
  226382. }
  226383. ~MacTypeface()
  226384. {
  226385. #if ! JUCE_IOS
  226386. [nsFont release];
  226387. #endif
  226388. if (fontRef != 0)
  226389. CGFontRelease (fontRef);
  226390. }
  226391. float getAscent() const
  226392. {
  226393. return ascent;
  226394. }
  226395. float getDescent() const
  226396. {
  226397. return 1.0f - ascent;
  226398. }
  226399. float getStringWidth (const String& text)
  226400. {
  226401. if (fontRef == 0 || text.isEmpty())
  226402. return 0;
  226403. const int length = text.length();
  226404. HeapBlock <CGGlyph> glyphs;
  226405. createGlyphsForString (text, length, glyphs);
  226406. float x = 0;
  226407. #if SUPPORT_ONLY_10_4_FONTS
  226408. HeapBlock <NSSize> advances (length);
  226409. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  226410. for (int i = 0; i < length; ++i)
  226411. x += advances[i].width;
  226412. #else
  226413. #if SUPPORT_10_4_FONTS
  226414. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226415. {
  226416. HeapBlock <NSSize> advances (length);
  226417. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  226418. for (int i = 0; i < length; ++i)
  226419. x += advances[i].width;
  226420. }
  226421. else
  226422. #endif
  226423. {
  226424. HeapBlock <int> advances (length);
  226425. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  226426. for (int i = 0; i < length; ++i)
  226427. x += advances[i];
  226428. }
  226429. #endif
  226430. return x * unitsToHeightScaleFactor;
  226431. }
  226432. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  226433. {
  226434. xOffsets.add (0);
  226435. if (fontRef == 0 || text.isEmpty())
  226436. return;
  226437. const int length = text.length();
  226438. HeapBlock <CGGlyph> glyphs;
  226439. createGlyphsForString (text, length, glyphs);
  226440. #if SUPPORT_ONLY_10_4_FONTS
  226441. HeapBlock <NSSize> advances (length);
  226442. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  226443. int x = 0;
  226444. for (int i = 0; i < length; ++i)
  226445. {
  226446. x += advances[i].width;
  226447. xOffsets.add (x * unitsToHeightScaleFactor);
  226448. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  226449. }
  226450. #else
  226451. #if SUPPORT_10_4_FONTS
  226452. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226453. {
  226454. HeapBlock <NSSize> advances (length);
  226455. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  226456. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  226457. float x = 0;
  226458. for (int i = 0; i < length; ++i)
  226459. {
  226460. x += advances[i].width;
  226461. xOffsets.add (x * unitsToHeightScaleFactor);
  226462. resultGlyphs.add (nsGlyphs[i]);
  226463. }
  226464. }
  226465. else
  226466. #endif
  226467. {
  226468. HeapBlock <int> advances (length);
  226469. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  226470. {
  226471. int x = 0;
  226472. for (int i = 0; i < length; ++i)
  226473. {
  226474. x += advances [i];
  226475. xOffsets.add (x * unitsToHeightScaleFactor);
  226476. resultGlyphs.add (glyphs[i]);
  226477. }
  226478. }
  226479. }
  226480. #endif
  226481. }
  226482. bool getOutlineForGlyph (int glyphNumber, Path& path)
  226483. {
  226484. #if JUCE_IOS
  226485. return false;
  226486. #else
  226487. if (nsFont == 0)
  226488. return false;
  226489. // we might need to apply a transform to the path, so it mustn't have anything else in it
  226490. jassert (path.isEmpty());
  226491. const ScopedAutoReleasePool pool;
  226492. NSBezierPath* bez = [NSBezierPath bezierPath];
  226493. [bez moveToPoint: NSMakePoint (0, 0)];
  226494. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  226495. inFont: nsFont];
  226496. for (int i = 0; i < [bez elementCount]; ++i)
  226497. {
  226498. NSPoint p[3];
  226499. switch ([bez elementAtIndex: i associatedPoints: p])
  226500. {
  226501. case NSMoveToBezierPathElement:
  226502. path.startNewSubPath ((float) p[0].x, (float) -p[0].y);
  226503. break;
  226504. case NSLineToBezierPathElement:
  226505. path.lineTo ((float) p[0].x, (float) -p[0].y);
  226506. break;
  226507. case NSCurveToBezierPathElement:
  226508. 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);
  226509. break;
  226510. case NSClosePathBezierPathElement:
  226511. path.closeSubPath();
  226512. break;
  226513. default:
  226514. jassertfalse;
  226515. break;
  226516. }
  226517. }
  226518. path.applyTransform (pathTransform);
  226519. return true;
  226520. #endif
  226521. }
  226522. juce_UseDebuggingNewOperator
  226523. CGFontRef fontRef;
  226524. float fontHeightToCGSizeFactor;
  226525. CGAffineTransform renderingTransform;
  226526. private:
  226527. float ascent, unitsToHeightScaleFactor;
  226528. #if JUCE_IOS
  226529. #else
  226530. NSFont* nsFont;
  226531. AffineTransform pathTransform;
  226532. #endif
  226533. void createGlyphsForString (const juce_wchar* const text, const int length, HeapBlock <CGGlyph>& glyphs)
  226534. {
  226535. #if SUPPORT_10_4_FONTS
  226536. #if ! SUPPORT_ONLY_10_4_FONTS
  226537. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226538. #endif
  226539. {
  226540. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  226541. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  226542. for (int i = 0; i < length; ++i)
  226543. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text[i]];
  226544. return;
  226545. }
  226546. #endif
  226547. #if ! SUPPORT_ONLY_10_4_FONTS
  226548. if (charToGlyphMapper == 0)
  226549. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  226550. glyphs.malloc (length);
  226551. for (int i = 0; i < length; ++i)
  226552. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text[i]);
  226553. #endif
  226554. }
  226555. #if ! SUPPORT_ONLY_10_4_FONTS
  226556. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  226557. class CharToGlyphMapper
  226558. {
  226559. public:
  226560. CharToGlyphMapper (CGFontRef fontRef)
  226561. : segCount (0), endCode (0), startCode (0), idDelta (0),
  226562. idRangeOffset (0), glyphIndexes (0)
  226563. {
  226564. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  226565. if (cmapTable != 0)
  226566. {
  226567. const int numSubtables = getValue16 (cmapTable, 2);
  226568. for (int i = 0; i < numSubtables; ++i)
  226569. {
  226570. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  226571. {
  226572. const int offset = getValue32 (cmapTable, i * 8 + 8);
  226573. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  226574. {
  226575. const int length = getValue16 (cmapTable, offset + 2);
  226576. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  226577. segCount = segCountX2 / 2;
  226578. const int endCodeOffset = offset + 14;
  226579. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  226580. const int idDeltaOffset = startCodeOffset + segCountX2;
  226581. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  226582. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  226583. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  226584. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  226585. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  226586. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  226587. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  226588. }
  226589. break;
  226590. }
  226591. }
  226592. CFRelease (cmapTable);
  226593. }
  226594. }
  226595. ~CharToGlyphMapper()
  226596. {
  226597. if (endCode != 0)
  226598. {
  226599. CFRelease (endCode);
  226600. CFRelease (startCode);
  226601. CFRelease (idDelta);
  226602. CFRelease (idRangeOffset);
  226603. CFRelease (glyphIndexes);
  226604. }
  226605. }
  226606. int getGlyphForCharacter (const juce_wchar c) const
  226607. {
  226608. for (int i = 0; i < segCount; ++i)
  226609. {
  226610. if (getValue16 (endCode, i * 2) >= c)
  226611. {
  226612. const int start = getValue16 (startCode, i * 2);
  226613. if (start > c)
  226614. break;
  226615. const int delta = getValue16 (idDelta, i * 2);
  226616. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  226617. if (rangeOffset == 0)
  226618. return delta + c;
  226619. else
  226620. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  226621. }
  226622. }
  226623. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  226624. return jmax (-1, (int) c - 29);
  226625. }
  226626. private:
  226627. int segCount;
  226628. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  226629. static uint16 getValue16 (CFDataRef data, const int index)
  226630. {
  226631. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  226632. }
  226633. static uint32 getValue32 (CFDataRef data, const int index)
  226634. {
  226635. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  226636. }
  226637. };
  226638. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  226639. #endif
  226640. MacTypeface (const MacTypeface&);
  226641. MacTypeface& operator= (const MacTypeface&);
  226642. };
  226643. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  226644. {
  226645. return new MacTypeface (font);
  226646. }
  226647. const StringArray Font::findAllTypefaceNames()
  226648. {
  226649. StringArray names;
  226650. const ScopedAutoReleasePool pool;
  226651. #if JUCE_IOS
  226652. NSArray* fonts = [UIFont familyNames];
  226653. #else
  226654. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  226655. #endif
  226656. for (unsigned int i = 0; i < [fonts count]; ++i)
  226657. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  226658. names.sort (true);
  226659. return names;
  226660. }
  226661. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  226662. {
  226663. #if JUCE_IOS
  226664. defaultSans = "Helvetica";
  226665. defaultSerif = "Times New Roman";
  226666. defaultFixed = "Courier New";
  226667. #else
  226668. defaultSans = "Lucida Grande";
  226669. defaultSerif = "Times New Roman";
  226670. defaultFixed = "Monaco";
  226671. #endif
  226672. }
  226673. #endif
  226674. /*** End of inlined file: juce_mac_Fonts.mm ***/
  226675. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  226676. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226677. // compiled on its own).
  226678. #if JUCE_INCLUDED_FILE
  226679. class CoreGraphicsImage : public Image::SharedImage
  226680. {
  226681. public:
  226682. CoreGraphicsImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  226683. : Image::SharedImage (format_, width_, height_)
  226684. {
  226685. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  226686. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  226687. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  226688. imageData = imageDataAllocated;
  226689. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  226690. : CGColorSpaceCreateDeviceRGB();
  226691. context = CGBitmapContextCreate (imageData, width, height, 8, lineStride,
  226692. colourSpace, getCGImageFlags (format_));
  226693. CGColorSpaceRelease (colourSpace);
  226694. }
  226695. ~CoreGraphicsImage()
  226696. {
  226697. CGContextRelease (context);
  226698. }
  226699. Image::ImageType getType() const { return Image::NativeImage; }
  226700. LowLevelGraphicsContext* createLowLevelContext();
  226701. SharedImage* clone()
  226702. {
  226703. CoreGraphicsImage* im = new CoreGraphicsImage (format, width, height, false);
  226704. memcpy (im->imageData, imageData, lineStride * height);
  226705. return im;
  226706. }
  226707. static CGImageRef createImage (const Image& juceImage, const bool forAlpha, CGColorSpaceRef colourSpace)
  226708. {
  226709. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (juceImage.getSharedImage());
  226710. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  226711. {
  226712. return CGBitmapContextCreateImage (nativeImage->context);
  226713. }
  226714. else
  226715. {
  226716. const Image::BitmapData srcData (juceImage, false);
  226717. CGDataProviderRef provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  226718. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  226719. 8, srcData.pixelStride * 8, srcData.lineStride,
  226720. colourSpace, getCGImageFlags (juceImage.getFormat()), provider,
  226721. 0, true, kCGRenderingIntentDefault);
  226722. CGDataProviderRelease (provider);
  226723. return imageRef;
  226724. }
  226725. }
  226726. #if JUCE_MAC
  226727. static NSImage* createNSImage (const Image& image)
  226728. {
  226729. const ScopedAutoReleasePool pool;
  226730. NSImage* im = [[NSImage alloc] init];
  226731. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  226732. [im lockFocus];
  226733. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  226734. CGImageRef imageRef = createImage (image, false, colourSpace);
  226735. CGColorSpaceRelease (colourSpace);
  226736. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  226737. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  226738. CGImageRelease (imageRef);
  226739. [im unlockFocus];
  226740. return im;
  226741. }
  226742. #endif
  226743. CGContextRef context;
  226744. HeapBlock<uint8> imageDataAllocated;
  226745. private:
  226746. static CGBitmapInfo getCGImageFlags (const Image::PixelFormat& format)
  226747. {
  226748. #if JUCE_BIG_ENDIAN
  226749. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  226750. #else
  226751. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  226752. #endif
  226753. }
  226754. };
  226755. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  226756. {
  226757. #if USE_COREGRAPHICS_RENDERING
  226758. return new CoreGraphicsImage (format == RGB ? ARGB : format, width, height, clearImage);
  226759. #else
  226760. return createSoftwareImage (format, width, height, clearImage);
  226761. #endif
  226762. }
  226763. class CoreGraphicsContext : public LowLevelGraphicsContext
  226764. {
  226765. public:
  226766. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  226767. : context (context_),
  226768. flipHeight (flipHeight_),
  226769. lastClipRectIsValid (false),
  226770. state (new SavedState()),
  226771. numGradientLookupEntries (0)
  226772. {
  226773. CGContextRetain (context);
  226774. CGContextSaveGState(context);
  226775. CGContextSetShouldSmoothFonts (context, true);
  226776. CGContextSetShouldAntialias (context, true);
  226777. CGContextSetBlendMode (context, kCGBlendModeNormal);
  226778. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  226779. greyColourSpace = CGColorSpaceCreateDeviceGray();
  226780. gradientCallbacks.version = 0;
  226781. gradientCallbacks.evaluate = gradientCallback;
  226782. gradientCallbacks.releaseInfo = 0;
  226783. setFont (Font());
  226784. }
  226785. ~CoreGraphicsContext()
  226786. {
  226787. CGContextRestoreGState (context);
  226788. CGContextRelease (context);
  226789. CGColorSpaceRelease (rgbColourSpace);
  226790. CGColorSpaceRelease (greyColourSpace);
  226791. }
  226792. bool isVectorDevice() const { return false; }
  226793. void setOrigin (int x, int y)
  226794. {
  226795. CGContextTranslateCTM (context, x, -y);
  226796. if (lastClipRectIsValid)
  226797. lastClipRect.translate (-x, -y);
  226798. }
  226799. bool clipToRectangle (const Rectangle<int>& r)
  226800. {
  226801. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  226802. if (lastClipRectIsValid)
  226803. {
  226804. // This is actually incorrect, because the actual clip region may be complex, and
  226805. // clipping its bounds to a rect may not be right... But, removing this shortcut
  226806. // doesn't actually fix anything because CoreGraphics also ignores complex regions
  226807. // when calculating the resultant clip bounds, and makes the same mistake!
  226808. lastClipRect = lastClipRect.getIntersection (r);
  226809. return ! lastClipRect.isEmpty();
  226810. }
  226811. return ! isClipEmpty();
  226812. }
  226813. bool clipToRectangleList (const RectangleList& clipRegion)
  226814. {
  226815. if (clipRegion.isEmpty())
  226816. {
  226817. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  226818. lastClipRectIsValid = true;
  226819. lastClipRect = Rectangle<int>();
  226820. return false;
  226821. }
  226822. else
  226823. {
  226824. const int numRects = clipRegion.getNumRectangles();
  226825. HeapBlock <CGRect> rects (numRects);
  226826. for (int i = 0; i < numRects; ++i)
  226827. {
  226828. const Rectangle<int>& r = clipRegion.getRectangle(i);
  226829. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  226830. }
  226831. CGContextClipToRects (context, rects, numRects);
  226832. lastClipRectIsValid = false;
  226833. return ! isClipEmpty();
  226834. }
  226835. }
  226836. void excludeClipRectangle (const Rectangle<int>& r)
  226837. {
  226838. RectangleList remaining (getClipBounds());
  226839. remaining.subtract (r);
  226840. clipToRectangleList (remaining);
  226841. lastClipRectIsValid = false;
  226842. }
  226843. void clipToPath (const Path& path, const AffineTransform& transform)
  226844. {
  226845. createPath (path, transform);
  226846. CGContextClip (context);
  226847. lastClipRectIsValid = false;
  226848. }
  226849. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  226850. {
  226851. if (! transform.isSingularity())
  226852. {
  226853. Image singleChannelImage (sourceImage);
  226854. if (sourceImage.getFormat() != Image::SingleChannel)
  226855. singleChannelImage = sourceImage.convertedToFormat (Image::SingleChannel);
  226856. CGImageRef image = CoreGraphicsImage::createImage (singleChannelImage, true, greyColourSpace);
  226857. flip();
  226858. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, sourceImage.getHeight()).followedBy (transform));
  226859. applyTransform (t);
  226860. CGRect r = CGRectMake (0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  226861. CGContextClipToMask (context, r, image);
  226862. applyTransform (t.inverted());
  226863. flip();
  226864. CGImageRelease (image);
  226865. lastClipRectIsValid = false;
  226866. }
  226867. }
  226868. bool clipRegionIntersects (const Rectangle<int>& r)
  226869. {
  226870. return getClipBounds().intersects (r);
  226871. }
  226872. const Rectangle<int> getClipBounds() const
  226873. {
  226874. if (! lastClipRectIsValid)
  226875. {
  226876. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  226877. lastClipRectIsValid = true;
  226878. lastClipRect.setBounds (roundToInt (bounds.origin.x),
  226879. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  226880. roundToInt (bounds.size.width),
  226881. roundToInt (bounds.size.height));
  226882. }
  226883. return lastClipRect;
  226884. }
  226885. bool isClipEmpty() const
  226886. {
  226887. return getClipBounds().isEmpty();
  226888. }
  226889. void saveState()
  226890. {
  226891. CGContextSaveGState (context);
  226892. stateStack.add (new SavedState (*state));
  226893. }
  226894. void restoreState()
  226895. {
  226896. CGContextRestoreGState (context);
  226897. SavedState* const top = stateStack.getLast();
  226898. if (top != 0)
  226899. {
  226900. state = top;
  226901. stateStack.removeLast (1, false);
  226902. lastClipRectIsValid = false;
  226903. }
  226904. else
  226905. {
  226906. jassertfalse; // trying to pop with an empty stack!
  226907. }
  226908. }
  226909. void setFill (const FillType& fillType)
  226910. {
  226911. state->fillType = fillType;
  226912. if (fillType.isColour())
  226913. {
  226914. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  226915. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  226916. CGContextSetAlpha (context, 1.0f);
  226917. }
  226918. }
  226919. void setOpacity (float newOpacity)
  226920. {
  226921. state->fillType.setOpacity (newOpacity);
  226922. setFill (state->fillType);
  226923. }
  226924. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  226925. {
  226926. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  226927. ? kCGInterpolationLow
  226928. : kCGInterpolationHigh);
  226929. }
  226930. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  226931. {
  226932. fillCGRect (CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()), replaceExistingContents);
  226933. }
  226934. void fillCGRect (const CGRect& cgRect, const bool replaceExistingContents)
  226935. {
  226936. if (replaceExistingContents)
  226937. {
  226938. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  226939. CGContextClearRect (context, cgRect);
  226940. #else
  226941. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  226942. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  226943. CGContextClearRect (context, cgRect);
  226944. else
  226945. #endif
  226946. CGContextSetBlendMode (context, kCGBlendModeCopy);
  226947. #endif
  226948. fillCGRect (cgRect, false);
  226949. CGContextSetBlendMode (context, kCGBlendModeNormal);
  226950. }
  226951. else
  226952. {
  226953. if (state->fillType.isColour())
  226954. {
  226955. CGContextFillRect (context, cgRect);
  226956. }
  226957. else if (state->fillType.isGradient())
  226958. {
  226959. CGContextSaveGState (context);
  226960. CGContextClipToRect (context, cgRect);
  226961. drawGradient();
  226962. CGContextRestoreGState (context);
  226963. }
  226964. else
  226965. {
  226966. CGContextSaveGState (context);
  226967. CGContextClipToRect (context, cgRect);
  226968. drawImage (state->fillType.image, state->fillType.transform, true);
  226969. CGContextRestoreGState (context);
  226970. }
  226971. }
  226972. }
  226973. void fillPath (const Path& path, const AffineTransform& transform)
  226974. {
  226975. CGContextSaveGState (context);
  226976. if (state->fillType.isColour())
  226977. {
  226978. flip();
  226979. applyTransform (transform);
  226980. createPath (path);
  226981. if (path.isUsingNonZeroWinding())
  226982. CGContextFillPath (context);
  226983. else
  226984. CGContextEOFillPath (context);
  226985. }
  226986. else
  226987. {
  226988. createPath (path, transform);
  226989. if (path.isUsingNonZeroWinding())
  226990. CGContextClip (context);
  226991. else
  226992. CGContextEOClip (context);
  226993. if (state->fillType.isGradient())
  226994. drawGradient();
  226995. else
  226996. drawImage (state->fillType.image, state->fillType.transform, true);
  226997. }
  226998. CGContextRestoreGState (context);
  226999. }
  227000. void drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  227001. {
  227002. const int iw = sourceImage.getWidth();
  227003. const int ih = sourceImage.getHeight();
  227004. CGImageRef image = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace);
  227005. CGContextSaveGState (context);
  227006. CGContextSetAlpha (context, state->fillType.getOpacity());
  227007. flip();
  227008. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, ih).followedBy (transform));
  227009. CGRect imageRect = CGRectMake (0, 0, iw, ih);
  227010. if (fillEntireClipAsTiles)
  227011. {
  227012. #if JUCE_IOS
  227013. CGContextDrawTiledImage (context, imageRect, image);
  227014. #else
  227015. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  227016. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  227017. // if it's doing a transformation - it's quicker to just draw lots of images manually
  227018. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  227019. CGContextDrawTiledImage (context, imageRect, image);
  227020. else
  227021. #endif
  227022. {
  227023. // Fallback to manually doing a tiled fill on 10.4
  227024. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  227025. int x = 0, y = 0;
  227026. while (x > clip.origin.x) x -= iw;
  227027. while (y > clip.origin.y) y -= ih;
  227028. const int right = (int) (clip.origin.x + clip.size.width);
  227029. const int bottom = (int) (clip.origin.y + clip.size.height);
  227030. while (y < bottom)
  227031. {
  227032. for (int x2 = x; x2 < right; x2 += iw)
  227033. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  227034. y += ih;
  227035. }
  227036. }
  227037. #endif
  227038. }
  227039. else
  227040. {
  227041. CGContextDrawImage (context, imageRect, image);
  227042. }
  227043. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  227044. CGContextRestoreGState (context);
  227045. }
  227046. void drawLine (const Line<float>& line)
  227047. {
  227048. if (state->fillType.isColour())
  227049. {
  227050. CGContextSetLineCap (context, kCGLineCapSquare);
  227051. CGContextSetLineWidth (context, 1.0f);
  227052. CGContextSetRGBStrokeColor (context,
  227053. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  227054. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  227055. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  227056. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  227057. CGContextStrokeLineSegments (context, cgLine, 1);
  227058. }
  227059. else
  227060. {
  227061. Path p;
  227062. p.addLineSegment (line, 1.0f);
  227063. fillPath (p, AffineTransform::identity);
  227064. }
  227065. }
  227066. void drawVerticalLine (const int x, float top, float bottom)
  227067. {
  227068. if (state->fillType.isColour())
  227069. {
  227070. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  227071. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  227072. #else
  227073. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  227074. // the x co-ord slightly to trick it..
  227075. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  227076. #endif
  227077. }
  227078. else
  227079. {
  227080. fillCGRect (CGRectMake ((float) x, flipHeight - bottom, 1.0f, bottom - top), false);
  227081. }
  227082. }
  227083. void drawHorizontalLine (const int y, float left, float right)
  227084. {
  227085. if (state->fillType.isColour())
  227086. {
  227087. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  227088. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  227089. #else
  227090. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  227091. // the x co-ord slightly to trick it..
  227092. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  227093. #endif
  227094. }
  227095. else
  227096. {
  227097. fillCGRect (CGRectMake (left, flipHeight - (y + 1), right - left, 1.0f), false);
  227098. }
  227099. }
  227100. void setFont (const Font& newFont)
  227101. {
  227102. if (state->font != newFont)
  227103. {
  227104. state->fontRef = 0;
  227105. state->font = newFont;
  227106. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  227107. if (mf != 0)
  227108. {
  227109. state->fontRef = mf->fontRef;
  227110. CGContextSetFont (context, state->fontRef);
  227111. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  227112. state->fontTransform = mf->renderingTransform;
  227113. state->fontTransform.a *= state->font.getHorizontalScale();
  227114. CGContextSetTextMatrix (context, state->fontTransform);
  227115. }
  227116. }
  227117. }
  227118. const Font getFont()
  227119. {
  227120. return state->font;
  227121. }
  227122. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  227123. {
  227124. if (state->fontRef != 0 && state->fillType.isColour())
  227125. {
  227126. if (transform.isOnlyTranslation())
  227127. {
  227128. CGContextSetTextMatrix (context, state->fontTransform); // have to set this each time, as it's not saved as part of the state
  227129. CGGlyph g = glyphNumber;
  227130. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  227131. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  227132. }
  227133. else
  227134. {
  227135. CGContextSaveGState (context);
  227136. flip();
  227137. applyTransform (transform);
  227138. CGAffineTransform t = state->fontTransform;
  227139. t.d = -t.d;
  227140. CGContextSetTextMatrix (context, t);
  227141. CGGlyph g = glyphNumber;
  227142. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  227143. CGContextRestoreGState (context);
  227144. }
  227145. }
  227146. else
  227147. {
  227148. Path p;
  227149. Font& f = state->font;
  227150. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  227151. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  227152. .followedBy (transform));
  227153. }
  227154. }
  227155. private:
  227156. CGContextRef context;
  227157. const CGFloat flipHeight;
  227158. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  227159. CGFunctionCallbacks gradientCallbacks;
  227160. mutable Rectangle<int> lastClipRect;
  227161. mutable bool lastClipRectIsValid;
  227162. struct SavedState
  227163. {
  227164. SavedState()
  227165. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  227166. {
  227167. }
  227168. SavedState (const SavedState& other)
  227169. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  227170. fontTransform (other.fontTransform)
  227171. {
  227172. }
  227173. ~SavedState()
  227174. {
  227175. }
  227176. FillType fillType;
  227177. Font font;
  227178. CGFontRef fontRef;
  227179. CGAffineTransform fontTransform;
  227180. };
  227181. ScopedPointer <SavedState> state;
  227182. OwnedArray <SavedState> stateStack;
  227183. HeapBlock <PixelARGB> gradientLookupTable;
  227184. int numGradientLookupEntries;
  227185. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  227186. {
  227187. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  227188. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  227189. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  227190. colour.unpremultiply();
  227191. outData[0] = colour.getRed() / 255.0f;
  227192. outData[1] = colour.getGreen() / 255.0f;
  227193. outData[2] = colour.getBlue() / 255.0f;
  227194. outData[3] = colour.getAlpha() / 255.0f;
  227195. }
  227196. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  227197. {
  227198. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable);
  227199. --numGradientLookupEntries;
  227200. CGShadingRef result = 0;
  227201. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  227202. CGPoint p1 (CGPointMake (gradient.point1.getX(), gradient.point1.getY()));
  227203. if (gradient.isRadial)
  227204. {
  227205. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  227206. p1, gradient.point1.getDistanceFrom (gradient.point2),
  227207. function, true, true);
  227208. }
  227209. else
  227210. {
  227211. result = CGShadingCreateAxial (rgbColourSpace, p1,
  227212. CGPointMake (gradient.point2.getX(), gradient.point2.getY()),
  227213. function, true, true);
  227214. }
  227215. CGFunctionRelease (function);
  227216. return result;
  227217. }
  227218. void drawGradient()
  227219. {
  227220. flip();
  227221. applyTransform (state->fillType.transform);
  227222. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  227223. // you draw a gradient with high quality interp enabled).
  227224. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  227225. CGContextSetAlpha (context, state->fillType.getOpacity());
  227226. CGContextDrawShading (context, shading);
  227227. CGShadingRelease (shading);
  227228. }
  227229. void createPath (const Path& path) const
  227230. {
  227231. CGContextBeginPath (context);
  227232. Path::Iterator i (path);
  227233. while (i.next())
  227234. {
  227235. switch (i.elementType)
  227236. {
  227237. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  227238. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  227239. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  227240. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  227241. case Path::Iterator::closePath: CGContextClosePath (context); break;
  227242. default: jassertfalse; break;
  227243. }
  227244. }
  227245. }
  227246. void createPath (const Path& path, const AffineTransform& transform) const
  227247. {
  227248. CGContextBeginPath (context);
  227249. Path::Iterator i (path);
  227250. while (i.next())
  227251. {
  227252. switch (i.elementType)
  227253. {
  227254. case Path::Iterator::startNewSubPath:
  227255. transform.transformPoint (i.x1, i.y1);
  227256. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  227257. break;
  227258. case Path::Iterator::lineTo:
  227259. transform.transformPoint (i.x1, i.y1);
  227260. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  227261. break;
  227262. case Path::Iterator::quadraticTo:
  227263. transform.transformPoints (i.x1, i.y1, i.x2, i.y2);
  227264. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  227265. break;
  227266. case Path::Iterator::cubicTo:
  227267. transform.transformPoints (i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  227268. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  227269. break;
  227270. case Path::Iterator::closePath:
  227271. CGContextClosePath (context); break;
  227272. default:
  227273. jassertfalse;
  227274. break;
  227275. }
  227276. }
  227277. }
  227278. void flip() const
  227279. {
  227280. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  227281. }
  227282. void applyTransform (const AffineTransform& transform) const
  227283. {
  227284. CGAffineTransform t;
  227285. t.a = transform.mat00;
  227286. t.b = transform.mat10;
  227287. t.c = transform.mat01;
  227288. t.d = transform.mat11;
  227289. t.tx = transform.mat02;
  227290. t.ty = transform.mat12;
  227291. CGContextConcatCTM (context, t);
  227292. }
  227293. CoreGraphicsContext (const CoreGraphicsContext&);
  227294. CoreGraphicsContext& operator= (const CoreGraphicsContext&);
  227295. };
  227296. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  227297. {
  227298. return new CoreGraphicsContext (context, height);
  227299. }
  227300. #if USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  227301. const Image juce_loadWithCoreImage (InputStream& input)
  227302. {
  227303. MemoryBlock data;
  227304. input.readIntoMemoryBlock (data, -1);
  227305. #if JUCE_IOS
  227306. JUCE_AUTORELEASEPOOL
  227307. UIImage* image = [UIImage imageWithData: [NSData dataWithBytesNoCopy: data.getData()
  227308. length: data.getSize()
  227309. freeWhenDone: NO]];
  227310. if (image != nil)
  227311. {
  227312. CGImageRef loadedImage = image.CGImage;
  227313. #else
  227314. CGDataProviderRef provider = CGDataProviderCreateWithData (0, data.getData(), data.getSize(), 0);
  227315. CGImageSourceRef imageSource = CGImageSourceCreateWithDataProvider (provider, 0);
  227316. CGDataProviderRelease (provider);
  227317. if (imageSource != 0)
  227318. {
  227319. CGImageRef loadedImage = CGImageSourceCreateImageAtIndex (imageSource, 0, 0);
  227320. CFRelease (imageSource);
  227321. #endif
  227322. if (loadedImage != 0)
  227323. {
  227324. const bool hasAlphaChan = CGImageGetAlphaInfo (loadedImage) != kCGImageAlphaNone;
  227325. Image image (hasAlphaChan ? Image::ARGB : Image::RGB,
  227326. (int) CGImageGetWidth (loadedImage), (int) CGImageGetHeight (loadedImage),
  227327. hasAlphaChan, Image::NativeImage);
  227328. CoreGraphicsImage* const cgImage = dynamic_cast<CoreGraphicsImage*> (image.getSharedImage());
  227329. jassert (cgImage != 0); // if USE_COREGRAPHICS_RENDERING is set, the CoreGraphicsImage class should have been used.
  227330. CGContextDrawImage (cgImage->context, CGRectMake (0, 0, image.getWidth(), image.getHeight()), loadedImage);
  227331. CGContextFlush (cgImage->context);
  227332. #if ! JUCE_IOS
  227333. CFRelease (loadedImage);
  227334. #endif
  227335. return image;
  227336. }
  227337. }
  227338. return Image::null;
  227339. }
  227340. #endif
  227341. #endif
  227342. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  227343. /*** Start of inlined file: juce_iphone_UIViewComponentPeer.mm ***/
  227344. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227345. // compiled on its own).
  227346. #if JUCE_INCLUDED_FILE
  227347. class UIViewComponentPeer;
  227348. END_JUCE_NAMESPACE
  227349. #define JuceUIView MakeObjCClassName(JuceUIView)
  227350. @interface JuceUIView : UIView <UITextViewDelegate>
  227351. {
  227352. @public
  227353. UIViewComponentPeer* owner;
  227354. UITextView* hiddenTextView;
  227355. }
  227356. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner withFrame: (CGRect) frame;
  227357. - (void) dealloc;
  227358. - (void) drawRect: (CGRect) r;
  227359. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event;
  227360. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event;
  227361. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event;
  227362. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event;
  227363. - (BOOL) becomeFirstResponder;
  227364. - (BOOL) resignFirstResponder;
  227365. - (BOOL) canBecomeFirstResponder;
  227366. - (void) asyncRepaint: (id) rect;
  227367. - (BOOL) textView: (UITextView*) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString*) text;
  227368. @end
  227369. #define JuceUIViewController MakeObjCClassName(JuceUIViewController)
  227370. @interface JuceUIViewController : UIViewController
  227371. {
  227372. }
  227373. - (BOOL) shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation) interfaceOrientation;
  227374. - (void) didRotateFromInterfaceOrientation: (UIInterfaceOrientation) fromInterfaceOrientation;
  227375. @end
  227376. #define JuceUIWindow MakeObjCClassName(JuceUIWindow)
  227377. @interface JuceUIWindow : UIWindow
  227378. {
  227379. @private
  227380. UIViewComponentPeer* owner;
  227381. bool isZooming;
  227382. }
  227383. - (void) setOwner: (UIViewComponentPeer*) owner;
  227384. - (void) becomeKeyWindow;
  227385. @end
  227386. BEGIN_JUCE_NAMESPACE
  227387. class UIViewComponentPeer : public ComponentPeer,
  227388. public FocusChangeListener
  227389. {
  227390. public:
  227391. UIViewComponentPeer (Component* const component,
  227392. const int windowStyleFlags,
  227393. UIView* viewToAttachTo);
  227394. ~UIViewComponentPeer();
  227395. void* getNativeHandle() const;
  227396. void setVisible (bool shouldBeVisible);
  227397. void setTitle (const String& title);
  227398. void setPosition (int x, int y);
  227399. void setSize (int w, int h);
  227400. void setBounds (int x, int y, int w, int h, bool isNowFullScreen);
  227401. const Rectangle<int> getBounds() const;
  227402. const Rectangle<int> getBounds (const bool global) const;
  227403. const Point<int> getScreenPosition() const;
  227404. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition);
  227405. const Point<int> globalPositionToRelative (const Point<int>& screenPosition);
  227406. void setMinimised (bool shouldBeMinimised);
  227407. bool isMinimised() const;
  227408. void setFullScreen (bool shouldBeFullScreen);
  227409. bool isFullScreen() const;
  227410. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  227411. const BorderSize getFrameSize() const;
  227412. bool setAlwaysOnTop (bool alwaysOnTop);
  227413. void toFront (bool makeActiveWindow);
  227414. void toBehind (ComponentPeer* other);
  227415. void setIcon (const Image& newIcon);
  227416. virtual void drawRect (CGRect r);
  227417. virtual bool canBecomeKeyWindow();
  227418. virtual bool windowShouldClose();
  227419. virtual void redirectMovedOrResized();
  227420. virtual CGRect constrainRect (CGRect r);
  227421. virtual void viewFocusGain();
  227422. virtual void viewFocusLoss();
  227423. bool isFocused() const;
  227424. void grabFocus();
  227425. void textInputRequired (const Point<int>& position);
  227426. virtual BOOL textViewReplaceCharacters (const Range<int>& range, const String& text);
  227427. void updateHiddenTextContent (TextInputTarget* target);
  227428. void globalFocusChanged (Component*);
  227429. virtual BOOL shouldRotate (UIInterfaceOrientation interfaceOrientation);
  227430. virtual void displayRotated();
  227431. void handleTouches (UIEvent* e, bool isDown, bool isUp, bool isCancel);
  227432. void repaint (const Rectangle<int>& area);
  227433. void performAnyPendingRepaintsNow();
  227434. juce_UseDebuggingNewOperator
  227435. UIWindow* window;
  227436. JuceUIView* view;
  227437. JuceUIViewController* controller;
  227438. bool isSharedWindow, fullScreen, insideDrawRect;
  227439. static ModifierKeys currentModifiers;
  227440. static int64 getMouseTime (UIEvent* e)
  227441. {
  227442. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  227443. + (int64) ([e timestamp] * 1000.0);
  227444. }
  227445. static const Rectangle<int> rotatedScreenPosToReal (const Rectangle<int>& r)
  227446. {
  227447. const Rectangle<int> screen (convertToRectInt ([[UIScreen mainScreen] bounds]));
  227448. switch ([[UIApplication sharedApplication] statusBarOrientation])
  227449. {
  227450. case UIInterfaceOrientationPortrait:
  227451. return r;
  227452. case UIInterfaceOrientationPortraitUpsideDown:
  227453. return Rectangle<int> (screen.getWidth() - r.getRight(), screen.getHeight() - r.getBottom(),
  227454. r.getWidth(), r.getHeight());
  227455. case UIInterfaceOrientationLandscapeLeft:
  227456. return Rectangle<int> (r.getY(), screen.getHeight() - r.getRight(),
  227457. r.getHeight(), r.getWidth());
  227458. case UIInterfaceOrientationLandscapeRight:
  227459. return Rectangle<int> (screen.getWidth() - r.getBottom(), r.getX(),
  227460. r.getHeight(), r.getWidth());
  227461. default: jassertfalse; // unknown orientation!
  227462. }
  227463. return r;
  227464. }
  227465. static const Rectangle<int> realScreenPosToRotated (const Rectangle<int>& r)
  227466. {
  227467. const Rectangle<int> screen (convertToRectInt ([[UIScreen mainScreen] bounds]));
  227468. switch ([[UIApplication sharedApplication] statusBarOrientation])
  227469. {
  227470. case UIInterfaceOrientationPortrait:
  227471. return r;
  227472. case UIInterfaceOrientationPortraitUpsideDown:
  227473. return Rectangle<int> (screen.getWidth() - r.getRight(), screen.getHeight() - r.getBottom(),
  227474. r.getWidth(), r.getHeight());
  227475. case UIInterfaceOrientationLandscapeLeft:
  227476. return Rectangle<int> (screen.getHeight() - r.getBottom(), r.getX(),
  227477. r.getHeight(), r.getWidth());
  227478. case UIInterfaceOrientationLandscapeRight:
  227479. return Rectangle<int> (r.getY(), screen.getWidth() - r.getRight(),
  227480. r.getHeight(), r.getWidth());
  227481. default: jassertfalse; // unknown orientation!
  227482. }
  227483. return r;
  227484. }
  227485. Array <UITouch*> currentTouches;
  227486. };
  227487. END_JUCE_NAMESPACE
  227488. @implementation JuceUIViewController
  227489. - (BOOL) shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation) interfaceOrientation
  227490. {
  227491. JuceUIView* juceView = (JuceUIView*) [self view];
  227492. jassert (juceView != 0 && juceView->owner != 0);
  227493. return juceView->owner->shouldRotate (interfaceOrientation);
  227494. }
  227495. - (void) didRotateFromInterfaceOrientation: (UIInterfaceOrientation) fromInterfaceOrientation
  227496. {
  227497. JuceUIView* juceView = (JuceUIView*) [self view];
  227498. jassert (juceView != 0 && juceView->owner != 0);
  227499. juceView->owner->displayRotated();
  227500. }
  227501. @end
  227502. @implementation JuceUIView
  227503. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner_
  227504. withFrame: (CGRect) frame
  227505. {
  227506. [super initWithFrame: frame];
  227507. owner = owner_;
  227508. hiddenTextView = [[UITextView alloc] initWithFrame: CGRectMake (0, 0, 0, 0)];
  227509. [self addSubview: hiddenTextView];
  227510. hiddenTextView.delegate = self;
  227511. hiddenTextView.autocapitalizationType = UITextAutocapitalizationTypeNone;
  227512. hiddenTextView.autocorrectionType = UITextAutocorrectionTypeNo;
  227513. return self;
  227514. }
  227515. - (void) dealloc
  227516. {
  227517. [hiddenTextView removeFromSuperview];
  227518. [hiddenTextView release];
  227519. [super dealloc];
  227520. }
  227521. - (void) drawRect: (CGRect) r
  227522. {
  227523. if (owner != 0)
  227524. owner->drawRect (r);
  227525. }
  227526. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  227527. {
  227528. return false;
  227529. }
  227530. ModifierKeys UIViewComponentPeer::currentModifiers;
  227531. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  227532. {
  227533. return UIViewComponentPeer::currentModifiers;
  227534. }
  227535. void ModifierKeys::updateCurrentModifiers() throw()
  227536. {
  227537. currentModifiers = UIViewComponentPeer::currentModifiers;
  227538. }
  227539. JUCE_NAMESPACE::Point<int> juce_lastMousePos;
  227540. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event
  227541. {
  227542. if (owner != 0)
  227543. owner->handleTouches (event, true, false, false);
  227544. }
  227545. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event
  227546. {
  227547. if (owner != 0)
  227548. owner->handleTouches (event, false, false, false);
  227549. }
  227550. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event
  227551. {
  227552. if (owner != 0)
  227553. owner->handleTouches (event, false, true, false);
  227554. }
  227555. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event
  227556. {
  227557. if (owner != 0)
  227558. owner->handleTouches (event, false, true, true);
  227559. [self touchesEnded: touches withEvent: event];
  227560. }
  227561. - (BOOL) becomeFirstResponder
  227562. {
  227563. if (owner != 0)
  227564. owner->viewFocusGain();
  227565. return true;
  227566. }
  227567. - (BOOL) resignFirstResponder
  227568. {
  227569. if (owner != 0)
  227570. owner->viewFocusLoss();
  227571. return true;
  227572. }
  227573. - (BOOL) canBecomeFirstResponder
  227574. {
  227575. return owner != 0 && owner->canBecomeKeyWindow();
  227576. }
  227577. - (void) asyncRepaint: (id) rect
  227578. {
  227579. CGRect* r = (CGRect*) [((NSData*) rect) bytes];
  227580. [self setNeedsDisplayInRect: *r];
  227581. }
  227582. - (BOOL) textView: (UITextView*) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString*) text
  227583. {
  227584. return owner->textViewReplaceCharacters (Range<int> (range.location, range.location + range.length),
  227585. nsStringToJuce (text));
  227586. }
  227587. @end
  227588. @implementation JuceUIWindow
  227589. - (void) setOwner: (UIViewComponentPeer*) owner_
  227590. {
  227591. owner = owner_;
  227592. isZooming = false;
  227593. }
  227594. - (void) becomeKeyWindow
  227595. {
  227596. [super becomeKeyWindow];
  227597. if (owner != 0)
  227598. owner->grabFocus();
  227599. }
  227600. @end
  227601. BEGIN_JUCE_NAMESPACE
  227602. UIViewComponentPeer::UIViewComponentPeer (Component* const component,
  227603. const int windowStyleFlags,
  227604. UIView* viewToAttachTo)
  227605. : ComponentPeer (component, windowStyleFlags),
  227606. window (0),
  227607. view (0), controller (0),
  227608. isSharedWindow (viewToAttachTo != 0),
  227609. fullScreen (false),
  227610. insideDrawRect (false)
  227611. {
  227612. CGRect r = convertToCGRect (component->getLocalBounds());
  227613. view = [[JuceUIView alloc] initWithOwner: this withFrame: r];
  227614. if (isSharedWindow)
  227615. {
  227616. window = [viewToAttachTo window];
  227617. [viewToAttachTo addSubview: view];
  227618. setVisible (component->isVisible());
  227619. }
  227620. else
  227621. {
  227622. controller = [[JuceUIViewController alloc] init];
  227623. controller.view = view;
  227624. r = convertToCGRect (rotatedScreenPosToReal (component->getBounds()));
  227625. r.origin.y = [[UIScreen mainScreen] bounds].size.height - (r.origin.y + r.size.height);
  227626. window = [[JuceUIWindow alloc] init];
  227627. window.frame = r;
  227628. window.opaque = component->isOpaque();
  227629. view.opaque = component->isOpaque();
  227630. window.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  227631. view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  227632. [((JuceUIWindow*) window) setOwner: this];
  227633. if (component->isAlwaysOnTop())
  227634. window.windowLevel = UIWindowLevelAlert;
  227635. [window addSubview: view];
  227636. view.frame = CGRectMake (0, 0, r.size.width, r.size.height);
  227637. view.hidden = ! component->isVisible();
  227638. window.hidden = ! component->isVisible();
  227639. view.multipleTouchEnabled = YES;
  227640. }
  227641. setTitle (component->getName());
  227642. Desktop::getInstance().addFocusChangeListener (this);
  227643. }
  227644. UIViewComponentPeer::~UIViewComponentPeer()
  227645. {
  227646. Desktop::getInstance().removeFocusChangeListener (this);
  227647. view->owner = 0;
  227648. [view removeFromSuperview];
  227649. [view release];
  227650. [controller release];
  227651. if (! isSharedWindow)
  227652. {
  227653. [((JuceUIWindow*) window) setOwner: 0];
  227654. [window release];
  227655. }
  227656. }
  227657. void* UIViewComponentPeer::getNativeHandle() const
  227658. {
  227659. return view;
  227660. }
  227661. void UIViewComponentPeer::setVisible (bool shouldBeVisible)
  227662. {
  227663. view.hidden = ! shouldBeVisible;
  227664. if (! isSharedWindow)
  227665. window.hidden = ! shouldBeVisible;
  227666. }
  227667. void UIViewComponentPeer::setTitle (const String& title)
  227668. {
  227669. // xxx is this possible?
  227670. }
  227671. void UIViewComponentPeer::setPosition (int x, int y)
  227672. {
  227673. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  227674. }
  227675. void UIViewComponentPeer::setSize (int w, int h)
  227676. {
  227677. setBounds (component->getX(), component->getY(), w, h, false);
  227678. }
  227679. void UIViewComponentPeer::setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  227680. {
  227681. fullScreen = isNowFullScreen;
  227682. w = jmax (0, w);
  227683. h = jmax (0, h);
  227684. if (isSharedWindow)
  227685. {
  227686. CGRect r = CGRectMake ((float) x, (float) y, (float) w, (float) h);
  227687. if ([view frame].size.width != r.size.width
  227688. || [view frame].size.height != r.size.height)
  227689. [view setNeedsDisplay];
  227690. view.frame = r;
  227691. }
  227692. else
  227693. {
  227694. const Rectangle<int> bounds (rotatedScreenPosToReal (Rectangle<int> (x, y, w, h)));
  227695. window.frame = convertToCGRect (bounds);
  227696. view.frame = CGRectMake (0, 0, (float) bounds.getWidth(), (float) bounds.getHeight());
  227697. handleMovedOrResized();
  227698. }
  227699. }
  227700. const Rectangle<int> UIViewComponentPeer::getBounds (const bool global) const
  227701. {
  227702. CGRect r = [view frame];
  227703. if (global && [view window] != 0)
  227704. {
  227705. r = [view convertRect: r toView: nil];
  227706. CGRect wr = [[view window] frame];
  227707. const Rectangle<int> windowBounds (realScreenPosToRotated (convertToRectInt (wr)));
  227708. r.origin.x = windowBounds.getX();
  227709. r.origin.y = windowBounds.getY();
  227710. }
  227711. return convertToRectInt (r);
  227712. }
  227713. const Rectangle<int> UIViewComponentPeer::getBounds() const
  227714. {
  227715. return getBounds (! isSharedWindow);
  227716. }
  227717. const Point<int> UIViewComponentPeer::getScreenPosition() const
  227718. {
  227719. return getBounds (true).getPosition();
  227720. }
  227721. const Point<int> UIViewComponentPeer::relativePositionToGlobal (const Point<int>& relativePosition)
  227722. {
  227723. return relativePosition + getScreenPosition();
  227724. }
  227725. const Point<int> UIViewComponentPeer::globalPositionToRelative (const Point<int>& screenPosition)
  227726. {
  227727. return screenPosition - getScreenPosition();
  227728. }
  227729. CGRect UIViewComponentPeer::constrainRect (CGRect r)
  227730. {
  227731. if (constrainer != 0)
  227732. {
  227733. CGRect current = [window frame];
  227734. current.origin.y = [[UIScreen mainScreen] bounds].size.height - current.origin.y - current.size.height;
  227735. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.origin.y - r.size.height;
  227736. Rectangle<int> pos (convertToRectInt (r));
  227737. Rectangle<int> original (convertToRectInt (current));
  227738. constrainer->checkBounds (pos, original,
  227739. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  227740. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  227741. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  227742. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  227743. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  227744. r.origin.x = pos.getX();
  227745. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.size.height - pos.getY();
  227746. r.size.width = pos.getWidth();
  227747. r.size.height = pos.getHeight();
  227748. }
  227749. return r;
  227750. }
  227751. void UIViewComponentPeer::setMinimised (bool shouldBeMinimised)
  227752. {
  227753. }
  227754. bool UIViewComponentPeer::isMinimised() const
  227755. {
  227756. return false;
  227757. }
  227758. void UIViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  227759. {
  227760. if (! isSharedWindow)
  227761. {
  227762. Rectangle<int> r (shouldBeFullScreen ? Desktop::getInstance().getMainMonitorArea()
  227763. : lastNonFullscreenBounds);
  227764. if ((! shouldBeFullScreen) && r.isEmpty())
  227765. r = getBounds();
  227766. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  227767. if (! r.isEmpty())
  227768. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  227769. component->repaint();
  227770. }
  227771. }
  227772. bool UIViewComponentPeer::isFullScreen() const
  227773. {
  227774. return fullScreen;
  227775. }
  227776. static Desktop::DisplayOrientation convertToJuceOrientation (UIInterfaceOrientation interfaceOrientation)
  227777. {
  227778. switch (interfaceOrientation)
  227779. {
  227780. case UIInterfaceOrientationPortrait: return Desktop::upright;
  227781. case UIInterfaceOrientationPortraitUpsideDown: return Desktop::upsideDown;
  227782. case UIInterfaceOrientationLandscapeLeft: return Desktop::rotatedClockwise;
  227783. case UIInterfaceOrientationLandscapeRight: return Desktop::rotatedAntiClockwise;
  227784. default: jassertfalse; // unknown orientation!
  227785. }
  227786. return Desktop::upright;
  227787. }
  227788. BOOL UIViewComponentPeer::shouldRotate (UIInterfaceOrientation interfaceOrientation)
  227789. {
  227790. return Desktop::getInstance().isOrientationEnabled (convertToJuceOrientation (interfaceOrientation));
  227791. }
  227792. void UIViewComponentPeer::displayRotated()
  227793. {
  227794. const Rectangle<int> oldArea (component->getBounds());
  227795. const Rectangle<int> oldDesktop (Desktop::getInstance().getMainMonitorArea());
  227796. Desktop::getInstance().refreshMonitorSizes();
  227797. if (fullScreen)
  227798. {
  227799. fullScreen = false;
  227800. setFullScreen (true);
  227801. }
  227802. else
  227803. {
  227804. const float l = oldArea.getX() / (float) oldDesktop.getWidth();
  227805. const float r = oldArea.getRight() / (float) oldDesktop.getWidth();
  227806. const float t = oldArea.getY() / (float) oldDesktop.getHeight();
  227807. const float b = oldArea.getBottom() / (float) oldDesktop.getHeight();
  227808. const Rectangle<int> newDesktop (Desktop::getInstance().getMainMonitorArea());
  227809. setBounds ((int) (l * newDesktop.getWidth()),
  227810. (int) (t * newDesktop.getHeight()),
  227811. (int) ((r - l) * newDesktop.getWidth()),
  227812. (int) ((b - t) * newDesktop.getHeight()),
  227813. false);
  227814. }
  227815. }
  227816. bool UIViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  227817. {
  227818. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  227819. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  227820. return false;
  227821. UIView* v = [view hitTest: CGPointMake ((float) position.getX(), (float) position.getY())
  227822. withEvent: nil];
  227823. if (trueIfInAChildWindow)
  227824. return v != nil;
  227825. return v == view;
  227826. }
  227827. const BorderSize UIViewComponentPeer::getFrameSize() const
  227828. {
  227829. return BorderSize();
  227830. }
  227831. bool UIViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  227832. {
  227833. if (! isSharedWindow)
  227834. window.windowLevel = alwaysOnTop ? UIWindowLevelAlert : UIWindowLevelNormal;
  227835. return true;
  227836. }
  227837. void UIViewComponentPeer::toFront (bool makeActiveWindow)
  227838. {
  227839. if (isSharedWindow)
  227840. [[view superview] bringSubviewToFront: view];
  227841. if (window != 0 && component->isVisible())
  227842. [window makeKeyAndVisible];
  227843. }
  227844. void UIViewComponentPeer::toBehind (ComponentPeer* other)
  227845. {
  227846. UIViewComponentPeer* const otherPeer = dynamic_cast <UIViewComponentPeer*> (other);
  227847. jassert (otherPeer != 0); // wrong type of window?
  227848. if (otherPeer != 0)
  227849. {
  227850. if (isSharedWindow)
  227851. {
  227852. [[view superview] insertSubview: view belowSubview: otherPeer->view];
  227853. }
  227854. else
  227855. {
  227856. jassertfalse; // don't know how to do this
  227857. }
  227858. }
  227859. }
  227860. void UIViewComponentPeer::setIcon (const Image& /*newIcon*/)
  227861. {
  227862. // to do..
  227863. }
  227864. void UIViewComponentPeer::handleTouches (UIEvent* event, const bool isDown, const bool isUp, bool isCancel)
  227865. {
  227866. NSArray* touches = [[event touchesForView: view] allObjects];
  227867. for (unsigned int i = 0; i < [touches count]; ++i)
  227868. {
  227869. UITouch* touch = [touches objectAtIndex: i];
  227870. CGPoint p = [touch locationInView: view];
  227871. const Point<int> pos ((int) p.x, (int) p.y);
  227872. juce_lastMousePos = pos + getScreenPosition();
  227873. const int64 time = getMouseTime (event);
  227874. int touchIndex = currentTouches.indexOf (touch);
  227875. if (touchIndex < 0)
  227876. {
  227877. touchIndex = currentTouches.size();
  227878. currentTouches.add (touch);
  227879. }
  227880. if (isDown)
  227881. {
  227882. currentModifiers = currentModifiers.withoutMouseButtons();
  227883. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  227884. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  227885. }
  227886. else if (isUp)
  227887. {
  227888. currentModifiers = currentModifiers.withoutMouseButtons();
  227889. currentTouches.remove (touchIndex);
  227890. }
  227891. if (isCancel)
  227892. currentTouches.clear();
  227893. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  227894. }
  227895. }
  227896. static UIViewComponentPeer* currentlyFocusedPeer = 0;
  227897. void UIViewComponentPeer::viewFocusGain()
  227898. {
  227899. if (currentlyFocusedPeer != this)
  227900. {
  227901. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  227902. currentlyFocusedPeer->handleFocusLoss();
  227903. currentlyFocusedPeer = this;
  227904. handleFocusGain();
  227905. }
  227906. }
  227907. void UIViewComponentPeer::viewFocusLoss()
  227908. {
  227909. if (currentlyFocusedPeer == this)
  227910. {
  227911. currentlyFocusedPeer = 0;
  227912. handleFocusLoss();
  227913. }
  227914. }
  227915. void juce_HandleProcessFocusChange()
  227916. {
  227917. if (UIViewComponentPeer::isValidPeer (currentlyFocusedPeer))
  227918. {
  227919. if (Process::isForegroundProcess())
  227920. {
  227921. currentlyFocusedPeer->handleFocusGain();
  227922. ComponentPeer::bringModalComponentToFront();
  227923. }
  227924. else
  227925. {
  227926. currentlyFocusedPeer->handleFocusLoss();
  227927. // turn kiosk mode off if we lose focus..
  227928. Desktop::getInstance().setKioskModeComponent (0);
  227929. }
  227930. }
  227931. }
  227932. bool UIViewComponentPeer::isFocused() const
  227933. {
  227934. return isSharedWindow ? this == currentlyFocusedPeer
  227935. : (window != 0 && [window isKeyWindow]);
  227936. }
  227937. void UIViewComponentPeer::grabFocus()
  227938. {
  227939. if (window != 0)
  227940. {
  227941. [window makeKeyWindow];
  227942. viewFocusGain();
  227943. }
  227944. }
  227945. void UIViewComponentPeer::textInputRequired (const Point<int>&)
  227946. {
  227947. }
  227948. void UIViewComponentPeer::updateHiddenTextContent (TextInputTarget* target)
  227949. {
  227950. view->hiddenTextView.text = juceStringToNS (target->getTextInRange (Range<int> (0, target->getHighlightedRegion().getStart())));
  227951. view->hiddenTextView.selectedRange = NSMakeRange (target->getHighlightedRegion().getStart(), 0);
  227952. }
  227953. BOOL UIViewComponentPeer::textViewReplaceCharacters (const Range<int>& range, const String& text)
  227954. {
  227955. TextInputTarget* const target = findCurrentTextInputTarget();
  227956. if (target != 0)
  227957. {
  227958. const Range<int> currentSelection (target->getHighlightedRegion());
  227959. if (range.getLength() == 1 && text.isEmpty()) // (detect backspace)
  227960. if (currentSelection.isEmpty())
  227961. target->setHighlightedRegion (currentSelection.withStart (currentSelection.getStart() - 1));
  227962. target->insertTextAtCaret (text);
  227963. updateHiddenTextContent (target);
  227964. }
  227965. return NO;
  227966. }
  227967. void UIViewComponentPeer::globalFocusChanged (Component*)
  227968. {
  227969. TextInputTarget* const target = findCurrentTextInputTarget();
  227970. if (target != 0)
  227971. {
  227972. Component* comp = dynamic_cast<Component*> (target);
  227973. Point<int> pos (comp->relativePositionToOtherComponent (component, Point<int>()));
  227974. view->hiddenTextView.frame = CGRectMake (pos.getX(), pos.getY(), 0, 0);
  227975. updateHiddenTextContent (target);
  227976. [view->hiddenTextView becomeFirstResponder];
  227977. }
  227978. else
  227979. {
  227980. [view->hiddenTextView resignFirstResponder];
  227981. }
  227982. }
  227983. void UIViewComponentPeer::drawRect (CGRect r)
  227984. {
  227985. if (r.size.width < 1.0f || r.size.height < 1.0f)
  227986. return;
  227987. CGContextRef cg = UIGraphicsGetCurrentContext();
  227988. if (! component->isOpaque())
  227989. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  227990. CGContextConcatCTM (cg, CGAffineTransformMake (1, 0, 0, -1, 0, view.bounds.size.height));
  227991. CoreGraphicsContext g (cg, view.bounds.size.height);
  227992. insideDrawRect = true;
  227993. handlePaint (g);
  227994. insideDrawRect = false;
  227995. }
  227996. bool UIViewComponentPeer::canBecomeKeyWindow()
  227997. {
  227998. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  227999. }
  228000. bool UIViewComponentPeer::windowShouldClose()
  228001. {
  228002. if (! isValidPeer (this))
  228003. return YES;
  228004. handleUserClosingWindow();
  228005. return NO;
  228006. }
  228007. void UIViewComponentPeer::redirectMovedOrResized()
  228008. {
  228009. handleMovedOrResized();
  228010. }
  228011. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  228012. {
  228013. }
  228014. class AsyncRepaintMessage : public CallbackMessage
  228015. {
  228016. public:
  228017. UIViewComponentPeer* const peer;
  228018. const Rectangle<int> rect;
  228019. AsyncRepaintMessage (UIViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  228020. : peer (peer_), rect (rect_)
  228021. {
  228022. }
  228023. void messageCallback()
  228024. {
  228025. if (ComponentPeer::isValidPeer (peer))
  228026. peer->repaint (rect);
  228027. }
  228028. };
  228029. void UIViewComponentPeer::repaint (const Rectangle<int>& area)
  228030. {
  228031. if (insideDrawRect || ! MessageManager::getInstance()->isThisTheMessageThread())
  228032. {
  228033. (new AsyncRepaintMessage (this, area))->post();
  228034. }
  228035. else
  228036. {
  228037. [view setNeedsDisplayInRect: convertToCGRect (area)];
  228038. }
  228039. }
  228040. void UIViewComponentPeer::performAnyPendingRepaintsNow()
  228041. {
  228042. }
  228043. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  228044. {
  228045. return new UIViewComponentPeer (this, styleFlags, (UIView*) windowToAttachTo);
  228046. }
  228047. const Image juce_createIconForFile (const File& file)
  228048. {
  228049. return Image::null;
  228050. }
  228051. void Desktop::createMouseInputSources()
  228052. {
  228053. for (int i = 0; i < 10; ++i)
  228054. mouseSources.add (new MouseInputSource (i, false));
  228055. }
  228056. bool Desktop::canUseSemiTransparentWindows() throw()
  228057. {
  228058. return true;
  228059. }
  228060. const Point<int> Desktop::getMousePosition()
  228061. {
  228062. return juce_lastMousePos;
  228063. }
  228064. void Desktop::setMousePosition (const Point<int>&)
  228065. {
  228066. }
  228067. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  228068. {
  228069. return convertToJuceOrientation ([[UIApplication sharedApplication] statusBarOrientation]);
  228070. }
  228071. void juce_updateMultiMonitorInfo (Array <Rectangle <int> >& monitorCoords, const bool clipToWorkArea)
  228072. {
  228073. const ScopedAutoReleasePool pool;
  228074. monitorCoords.clear();
  228075. CGRect r = clipToWorkArea ? [[UIScreen mainScreen] applicationFrame]
  228076. : [[UIScreen mainScreen] bounds];
  228077. monitorCoords.add (UIViewComponentPeer::realScreenPosToRotated (convertToRectInt (r)));
  228078. }
  228079. const int KeyPress::spaceKey = ' ';
  228080. const int KeyPress::returnKey = 0x0d;
  228081. const int KeyPress::escapeKey = 0x1b;
  228082. const int KeyPress::backspaceKey = 0x7f;
  228083. const int KeyPress::leftKey = 0x1000;
  228084. const int KeyPress::rightKey = 0x1001;
  228085. const int KeyPress::upKey = 0x1002;
  228086. const int KeyPress::downKey = 0x1003;
  228087. const int KeyPress::pageUpKey = 0x1004;
  228088. const int KeyPress::pageDownKey = 0x1005;
  228089. const int KeyPress::endKey = 0x1006;
  228090. const int KeyPress::homeKey = 0x1007;
  228091. const int KeyPress::deleteKey = 0x1008;
  228092. const int KeyPress::insertKey = -1;
  228093. const int KeyPress::tabKey = 9;
  228094. const int KeyPress::F1Key = 0x2001;
  228095. const int KeyPress::F2Key = 0x2002;
  228096. const int KeyPress::F3Key = 0x2003;
  228097. const int KeyPress::F4Key = 0x2004;
  228098. const int KeyPress::F5Key = 0x2005;
  228099. const int KeyPress::F6Key = 0x2006;
  228100. const int KeyPress::F7Key = 0x2007;
  228101. const int KeyPress::F8Key = 0x2008;
  228102. const int KeyPress::F9Key = 0x2009;
  228103. const int KeyPress::F10Key = 0x200a;
  228104. const int KeyPress::F11Key = 0x200b;
  228105. const int KeyPress::F12Key = 0x200c;
  228106. const int KeyPress::F13Key = 0x200d;
  228107. const int KeyPress::F14Key = 0x200e;
  228108. const int KeyPress::F15Key = 0x200f;
  228109. const int KeyPress::F16Key = 0x2010;
  228110. const int KeyPress::numberPad0 = 0x30020;
  228111. const int KeyPress::numberPad1 = 0x30021;
  228112. const int KeyPress::numberPad2 = 0x30022;
  228113. const int KeyPress::numberPad3 = 0x30023;
  228114. const int KeyPress::numberPad4 = 0x30024;
  228115. const int KeyPress::numberPad5 = 0x30025;
  228116. const int KeyPress::numberPad6 = 0x30026;
  228117. const int KeyPress::numberPad7 = 0x30027;
  228118. const int KeyPress::numberPad8 = 0x30028;
  228119. const int KeyPress::numberPad9 = 0x30029;
  228120. const int KeyPress::numberPadAdd = 0x3002a;
  228121. const int KeyPress::numberPadSubtract = 0x3002b;
  228122. const int KeyPress::numberPadMultiply = 0x3002c;
  228123. const int KeyPress::numberPadDivide = 0x3002d;
  228124. const int KeyPress::numberPadSeparator = 0x3002e;
  228125. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  228126. const int KeyPress::numberPadEquals = 0x30030;
  228127. const int KeyPress::numberPadDelete = 0x30031;
  228128. const int KeyPress::playKey = 0x30000;
  228129. const int KeyPress::stopKey = 0x30001;
  228130. const int KeyPress::fastForwardKey = 0x30002;
  228131. const int KeyPress::rewindKey = 0x30003;
  228132. #endif
  228133. /*** End of inlined file: juce_iphone_UIViewComponentPeer.mm ***/
  228134. /*** Start of inlined file: juce_iphone_MessageManager.mm ***/
  228135. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228136. // compiled on its own).
  228137. #if JUCE_INCLUDED_FILE
  228138. struct CallbackMessagePayload
  228139. {
  228140. MessageCallbackFunction* function;
  228141. void* parameter;
  228142. void* volatile result;
  228143. bool volatile hasBeenExecuted;
  228144. };
  228145. END_JUCE_NAMESPACE
  228146. @interface JuceCustomMessageHandler : NSObject
  228147. {
  228148. }
  228149. - (void) performCallback: (id) info;
  228150. @end
  228151. @implementation JuceCustomMessageHandler
  228152. - (void) performCallback: (id) info
  228153. {
  228154. if ([info isKindOfClass: [NSData class]])
  228155. {
  228156. JUCE_NAMESPACE::CallbackMessagePayload* pl = (JUCE_NAMESPACE::CallbackMessagePayload*) [((NSData*) info) bytes];
  228157. if (pl != 0)
  228158. {
  228159. pl->result = (*pl->function) (pl->parameter);
  228160. pl->hasBeenExecuted = true;
  228161. }
  228162. }
  228163. else
  228164. {
  228165. jassertfalse; // should never get here!
  228166. }
  228167. }
  228168. @end
  228169. BEGIN_JUCE_NAMESPACE
  228170. void MessageManager::runDispatchLoop()
  228171. {
  228172. jassert (isThisTheMessageThread()); // must only be called by the message thread
  228173. runDispatchLoopUntil (-1);
  228174. }
  228175. void MessageManager::stopDispatchLoop()
  228176. {
  228177. [[[UIApplication sharedApplication] delegate] applicationWillTerminate: [UIApplication sharedApplication]];
  228178. exit (0); // iPhone apps get no mercy..
  228179. }
  228180. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  228181. {
  228182. const ScopedAutoReleasePool pool;
  228183. jassert (isThisTheMessageThread()); // must only be called by the message thread
  228184. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  228185. NSDate* endDate = [NSDate dateWithTimeIntervalSinceNow: millisecondsToRunFor * 0.001];
  228186. while (! quitMessagePosted)
  228187. {
  228188. const ScopedAutoReleasePool pool;
  228189. [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode
  228190. beforeDate: endDate];
  228191. if (millisecondsToRunFor >= 0 && Time::getMillisecondCounter() >= endTime)
  228192. break;
  228193. }
  228194. return ! quitMessagePosted;
  228195. }
  228196. static CFRunLoopRef runLoop = 0;
  228197. static CFRunLoopSourceRef runLoopSource = 0;
  228198. static OwnedArray <Message, CriticalSection>* pendingMessages = 0;
  228199. static JuceCustomMessageHandler* juceCustomMessageHandler = 0;
  228200. static void runLoopSourceCallback (void*)
  228201. {
  228202. if (pendingMessages != 0)
  228203. {
  228204. int numDispatched = 0;
  228205. do
  228206. {
  228207. Message* const nextMessage = pendingMessages->removeAndReturn (0);
  228208. if (nextMessage == 0)
  228209. return;
  228210. const ScopedAutoReleasePool pool;
  228211. MessageManager::getInstance()->deliverMessage (nextMessage);
  228212. } while (++numDispatched <= 4);
  228213. CFRunLoopSourceSignal (runLoopSource);
  228214. CFRunLoopWakeUp (runLoop);
  228215. }
  228216. }
  228217. void MessageManager::doPlatformSpecificInitialisation()
  228218. {
  228219. pendingMessages = new OwnedArray <Message, CriticalSection>();
  228220. runLoop = CFRunLoopGetCurrent();
  228221. CFRunLoopSourceContext sourceContext;
  228222. zerostruct (sourceContext);
  228223. sourceContext.perform = runLoopSourceCallback;
  228224. runLoopSource = CFRunLoopSourceCreate (kCFAllocatorDefault, 1, &sourceContext);
  228225. CFRunLoopAddSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  228226. if (juceCustomMessageHandler == 0)
  228227. juceCustomMessageHandler = [[JuceCustomMessageHandler alloc] init];
  228228. }
  228229. void MessageManager::doPlatformSpecificShutdown()
  228230. {
  228231. CFRunLoopSourceInvalidate (runLoopSource);
  228232. CFRelease (runLoopSource);
  228233. runLoopSource = 0;
  228234. deleteAndZero (pendingMessages);
  228235. if (juceCustomMessageHandler != 0)
  228236. {
  228237. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceCustomMessageHandler];
  228238. [juceCustomMessageHandler release];
  228239. juceCustomMessageHandler = 0;
  228240. }
  228241. }
  228242. bool juce_postMessageToSystemQueue (Message* message)
  228243. {
  228244. if (pendingMessages != 0)
  228245. {
  228246. pendingMessages->add (message);
  228247. CFRunLoopSourceSignal (runLoopSource);
  228248. CFRunLoopWakeUp (runLoop);
  228249. }
  228250. return true;
  228251. }
  228252. void MessageManager::broadcastMessage (const String& value)
  228253. {
  228254. }
  228255. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback, void* data)
  228256. {
  228257. if (isThisTheMessageThread())
  228258. {
  228259. return (*callback) (data);
  228260. }
  228261. else
  228262. {
  228263. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  228264. // deadlock because the message manager is blocked from running, so can never
  228265. // call your function..
  228266. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  228267. const ScopedAutoReleasePool pool;
  228268. CallbackMessagePayload cmp;
  228269. cmp.function = callback;
  228270. cmp.parameter = data;
  228271. cmp.result = 0;
  228272. cmp.hasBeenExecuted = false;
  228273. [juceCustomMessageHandler performSelectorOnMainThread: @selector (performCallback:)
  228274. withObject: [NSData dataWithBytesNoCopy: &cmp
  228275. length: sizeof (cmp)
  228276. freeWhenDone: NO]
  228277. waitUntilDone: YES];
  228278. return cmp.result;
  228279. }
  228280. }
  228281. #endif
  228282. /*** End of inlined file: juce_iphone_MessageManager.mm ***/
  228283. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  228284. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228285. // compiled on its own).
  228286. #if JUCE_INCLUDED_FILE
  228287. #if JUCE_MAC
  228288. END_JUCE_NAMESPACE
  228289. using namespace JUCE_NAMESPACE;
  228290. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  228291. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  228292. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  228293. #else
  228294. @interface JuceFileChooserDelegate : NSObject
  228295. #endif
  228296. {
  228297. StringArray* filters;
  228298. }
  228299. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  228300. - (void) dealloc;
  228301. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  228302. @end
  228303. @implementation JuceFileChooserDelegate
  228304. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  228305. {
  228306. [super init];
  228307. filters = filters_;
  228308. return self;
  228309. }
  228310. - (void) dealloc
  228311. {
  228312. delete filters;
  228313. [super dealloc];
  228314. }
  228315. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  228316. {
  228317. (void) sender;
  228318. const File f (nsStringToJuce (filename));
  228319. for (int i = filters->size(); --i >= 0;)
  228320. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  228321. return true;
  228322. return f.isDirectory();
  228323. }
  228324. @end
  228325. BEGIN_JUCE_NAMESPACE
  228326. void FileChooser::showPlatformDialog (Array<File>& results,
  228327. const String& title,
  228328. const File& currentFileOrDirectory,
  228329. const String& filter,
  228330. bool selectsDirectory,
  228331. bool selectsFiles,
  228332. bool isSaveDialogue,
  228333. bool warnAboutOverwritingExistingFiles,
  228334. bool selectMultipleFiles,
  228335. FilePreviewComponent* extraInfoComponent)
  228336. {
  228337. const ScopedAutoReleasePool pool;
  228338. StringArray* filters = new StringArray();
  228339. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  228340. filters->trim();
  228341. filters->removeEmptyStrings();
  228342. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  228343. [delegate autorelease];
  228344. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  228345. : [NSOpenPanel openPanel];
  228346. [panel setTitle: juceStringToNS (title)];
  228347. if (! isSaveDialogue)
  228348. {
  228349. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  228350. [openPanel setCanChooseDirectories: selectsDirectory];
  228351. [openPanel setCanChooseFiles: selectsFiles];
  228352. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  228353. }
  228354. [panel setDelegate: delegate];
  228355. if (isSaveDialogue || selectsDirectory)
  228356. [panel setCanCreateDirectories: YES];
  228357. String directory, filename;
  228358. if (currentFileOrDirectory.isDirectory())
  228359. {
  228360. directory = currentFileOrDirectory.getFullPathName();
  228361. }
  228362. else
  228363. {
  228364. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  228365. filename = currentFileOrDirectory.getFileName();
  228366. }
  228367. if ([panel runModalForDirectory: juceStringToNS (directory)
  228368. file: juceStringToNS (filename)]
  228369. == NSOKButton)
  228370. {
  228371. if (isSaveDialogue)
  228372. {
  228373. results.add (File (nsStringToJuce ([panel filename])));
  228374. }
  228375. else
  228376. {
  228377. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  228378. NSArray* urls = [openPanel filenames];
  228379. for (unsigned int i = 0; i < [urls count]; ++i)
  228380. {
  228381. NSString* f = [urls objectAtIndex: i];
  228382. results.add (File (nsStringToJuce (f)));
  228383. }
  228384. }
  228385. }
  228386. [panel setDelegate: nil];
  228387. }
  228388. #else
  228389. void FileChooser::showPlatformDialog (Array<File>& results,
  228390. const String& title,
  228391. const File& currentFileOrDirectory,
  228392. const String& filter,
  228393. bool selectsDirectory,
  228394. bool selectsFiles,
  228395. bool isSaveDialogue,
  228396. bool warnAboutOverwritingExistingFiles,
  228397. bool selectMultipleFiles,
  228398. FilePreviewComponent* extraInfoComponent)
  228399. {
  228400. const ScopedAutoReleasePool pool;
  228401. jassertfalse; //xxx to do
  228402. }
  228403. #endif
  228404. #endif
  228405. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  228406. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  228407. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228408. // compiled on its own).
  228409. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  228410. #if JUCE_MAC
  228411. END_JUCE_NAMESPACE
  228412. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  228413. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  228414. {
  228415. CriticalSection* contextLock;
  228416. bool needsUpdate;
  228417. }
  228418. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  228419. - (bool) makeActive;
  228420. - (void) makeInactive;
  228421. - (void) reshape;
  228422. @end
  228423. @implementation ThreadSafeNSOpenGLView
  228424. - (id) initWithFrame: (NSRect) frameRect
  228425. pixelFormat: (NSOpenGLPixelFormat*) format
  228426. {
  228427. contextLock = new CriticalSection();
  228428. self = [super initWithFrame: frameRect pixelFormat: format];
  228429. if (self != nil)
  228430. [[NSNotificationCenter defaultCenter] addObserver: self
  228431. selector: @selector (_surfaceNeedsUpdate:)
  228432. name: NSViewGlobalFrameDidChangeNotification
  228433. object: self];
  228434. return self;
  228435. }
  228436. - (void) dealloc
  228437. {
  228438. [[NSNotificationCenter defaultCenter] removeObserver: self];
  228439. delete contextLock;
  228440. [super dealloc];
  228441. }
  228442. - (bool) makeActive
  228443. {
  228444. const ScopedLock sl (*contextLock);
  228445. if ([self openGLContext] == 0)
  228446. return false;
  228447. [[self openGLContext] makeCurrentContext];
  228448. if (needsUpdate)
  228449. {
  228450. [super update];
  228451. needsUpdate = false;
  228452. }
  228453. return true;
  228454. }
  228455. - (void) makeInactive
  228456. {
  228457. const ScopedLock sl (*contextLock);
  228458. [NSOpenGLContext clearCurrentContext];
  228459. }
  228460. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  228461. {
  228462. const ScopedLock sl (*contextLock);
  228463. needsUpdate = true;
  228464. }
  228465. - (void) update
  228466. {
  228467. const ScopedLock sl (*contextLock);
  228468. needsUpdate = true;
  228469. }
  228470. - (void) reshape
  228471. {
  228472. const ScopedLock sl (*contextLock);
  228473. needsUpdate = true;
  228474. }
  228475. @end
  228476. BEGIN_JUCE_NAMESPACE
  228477. class WindowedGLContext : public OpenGLContext
  228478. {
  228479. public:
  228480. WindowedGLContext (Component* const component,
  228481. const OpenGLPixelFormat& pixelFormat_,
  228482. NSOpenGLContext* sharedContext)
  228483. : renderContext (0),
  228484. pixelFormat (pixelFormat_)
  228485. {
  228486. jassert (component != 0);
  228487. NSOpenGLPixelFormatAttribute attribs [64];
  228488. int n = 0;
  228489. attribs[n++] = NSOpenGLPFADoubleBuffer;
  228490. attribs[n++] = NSOpenGLPFAAccelerated;
  228491. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  228492. attribs[n++] = NSOpenGLPFAColorSize;
  228493. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  228494. pixelFormat.greenBits,
  228495. pixelFormat.blueBits);
  228496. attribs[n++] = NSOpenGLPFAAlphaSize;
  228497. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  228498. attribs[n++] = NSOpenGLPFADepthSize;
  228499. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  228500. attribs[n++] = NSOpenGLPFAStencilSize;
  228501. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  228502. attribs[n++] = NSOpenGLPFAAccumSize;
  228503. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  228504. pixelFormat.accumulationBufferGreenBits,
  228505. pixelFormat.accumulationBufferBlueBits,
  228506. pixelFormat.accumulationBufferAlphaBits);
  228507. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  228508. attribs[n++] = NSOpenGLPFASampleBuffers;
  228509. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  228510. attribs[n++] = NSOpenGLPFAClosestPolicy;
  228511. attribs[n++] = NSOpenGLPFANoRecovery;
  228512. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  228513. NSOpenGLPixelFormat* format
  228514. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  228515. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  228516. pixelFormat: format];
  228517. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  228518. shareContext: sharedContext] autorelease];
  228519. const GLint swapInterval = 1;
  228520. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  228521. [view setOpenGLContext: renderContext];
  228522. [format release];
  228523. viewHolder = new NSViewComponentInternal (view, component);
  228524. }
  228525. ~WindowedGLContext()
  228526. {
  228527. deleteContext();
  228528. viewHolder = 0;
  228529. }
  228530. void deleteContext()
  228531. {
  228532. makeInactive();
  228533. [renderContext clearDrawable];
  228534. [renderContext setView: nil];
  228535. [view setOpenGLContext: nil];
  228536. renderContext = nil;
  228537. }
  228538. bool makeActive() const throw()
  228539. {
  228540. jassert (renderContext != 0);
  228541. if ([renderContext view] != view)
  228542. [renderContext setView: view];
  228543. [view makeActive];
  228544. return isActive();
  228545. }
  228546. bool makeInactive() const throw()
  228547. {
  228548. [view makeInactive];
  228549. return true;
  228550. }
  228551. bool isActive() const throw()
  228552. {
  228553. return [NSOpenGLContext currentContext] == renderContext;
  228554. }
  228555. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  228556. void* getRawContext() const throw() { return renderContext; }
  228557. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  228558. {
  228559. }
  228560. void swapBuffers()
  228561. {
  228562. [renderContext flushBuffer];
  228563. }
  228564. bool setSwapInterval (const int numFramesPerSwap)
  228565. {
  228566. [renderContext setValues: (const GLint*) &numFramesPerSwap
  228567. forParameter: NSOpenGLCPSwapInterval];
  228568. return true;
  228569. }
  228570. int getSwapInterval() const
  228571. {
  228572. GLint numFrames = 0;
  228573. [renderContext getValues: &numFrames
  228574. forParameter: NSOpenGLCPSwapInterval];
  228575. return numFrames;
  228576. }
  228577. void repaint()
  228578. {
  228579. // we need to invalidate the juce view that holds this gl view, to make it
  228580. // cause a repaint callback
  228581. NSView* v = (NSView*) viewHolder->view;
  228582. NSRect r = [v frame];
  228583. // bit of a bodge here.. if we only invalidate the area of the gl component,
  228584. // it's completely covered by the NSOpenGLView, so the OS throws away the
  228585. // repaint message, thus never causing our paint() callback, and never repainting
  228586. // the comp. So invalidating just a little bit around the edge helps..
  228587. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  228588. }
  228589. void* getNativeWindowHandle() const { return viewHolder->view; }
  228590. juce_UseDebuggingNewOperator
  228591. NSOpenGLContext* renderContext;
  228592. ThreadSafeNSOpenGLView* view;
  228593. private:
  228594. OpenGLPixelFormat pixelFormat;
  228595. ScopedPointer <NSViewComponentInternal> viewHolder;
  228596. WindowedGLContext (const WindowedGLContext&);
  228597. WindowedGLContext& operator= (const WindowedGLContext&);
  228598. };
  228599. OpenGLContext* OpenGLComponent::createContext()
  228600. {
  228601. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  228602. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  228603. return (c->renderContext != 0) ? c.release() : 0;
  228604. }
  228605. void* OpenGLComponent::getNativeWindowHandle() const
  228606. {
  228607. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  228608. : 0;
  228609. }
  228610. void juce_glViewport (const int w, const int h)
  228611. {
  228612. glViewport (0, 0, w, h);
  228613. }
  228614. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  228615. OwnedArray <OpenGLPixelFormat>& results)
  228616. {
  228617. /* GLint attribs [64];
  228618. int n = 0;
  228619. attribs[n++] = AGL_RGBA;
  228620. attribs[n++] = AGL_DOUBLEBUFFER;
  228621. attribs[n++] = AGL_ACCELERATED;
  228622. attribs[n++] = AGL_NO_RECOVERY;
  228623. attribs[n++] = AGL_NONE;
  228624. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  228625. while (p != 0)
  228626. {
  228627. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  228628. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  228629. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  228630. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  228631. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  228632. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  228633. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  228634. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  228635. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  228636. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  228637. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  228638. results.add (pf);
  228639. p = aglNextPixelFormat (p);
  228640. }*/
  228641. //jassertfalse // can't see how you do this in cocoa!
  228642. }
  228643. #else
  228644. END_JUCE_NAMESPACE
  228645. @interface JuceGLView : UIView
  228646. {
  228647. }
  228648. + (Class) layerClass;
  228649. @end
  228650. @implementation JuceGLView
  228651. + (Class) layerClass
  228652. {
  228653. return [CAEAGLLayer class];
  228654. }
  228655. @end
  228656. BEGIN_JUCE_NAMESPACE
  228657. class GLESContext : public OpenGLContext
  228658. {
  228659. public:
  228660. GLESContext (UIViewComponentPeer* peer,
  228661. Component* const component_,
  228662. const OpenGLPixelFormat& pixelFormat_,
  228663. const GLESContext* const sharedContext,
  228664. NSUInteger apiType)
  228665. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  228666. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  228667. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  228668. {
  228669. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  228670. view.opaque = YES;
  228671. view.hidden = NO;
  228672. view.backgroundColor = [UIColor blackColor];
  228673. view.userInteractionEnabled = NO;
  228674. glLayer = (CAEAGLLayer*) [view layer];
  228675. [peer->view addSubview: view];
  228676. if (sharedContext != 0)
  228677. context = [[EAGLContext alloc] initWithAPI: apiType
  228678. sharegroup: [sharedContext->context sharegroup]];
  228679. else
  228680. context = [[EAGLContext alloc] initWithAPI: apiType];
  228681. createGLBuffers();
  228682. }
  228683. ~GLESContext()
  228684. {
  228685. deleteContext();
  228686. [view removeFromSuperview];
  228687. [view release];
  228688. freeGLBuffers();
  228689. }
  228690. void deleteContext()
  228691. {
  228692. makeInactive();
  228693. [context release];
  228694. context = nil;
  228695. }
  228696. bool makeActive() const throw()
  228697. {
  228698. jassert (context != 0);
  228699. [EAGLContext setCurrentContext: context];
  228700. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  228701. return true;
  228702. }
  228703. void swapBuffers()
  228704. {
  228705. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  228706. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  228707. }
  228708. bool makeInactive() const throw()
  228709. {
  228710. return [EAGLContext setCurrentContext: nil];
  228711. }
  228712. bool isActive() const throw()
  228713. {
  228714. return [EAGLContext currentContext] == context;
  228715. }
  228716. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  228717. void* getRawContext() const throw() { return glLayer; }
  228718. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  228719. {
  228720. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  228721. if (lastWidth != w || lastHeight != h)
  228722. {
  228723. lastWidth = w;
  228724. lastHeight = h;
  228725. freeGLBuffers();
  228726. createGLBuffers();
  228727. }
  228728. }
  228729. bool setSwapInterval (const int numFramesPerSwap)
  228730. {
  228731. numFrames = numFramesPerSwap;
  228732. return true;
  228733. }
  228734. int getSwapInterval() const
  228735. {
  228736. return numFrames;
  228737. }
  228738. void repaint()
  228739. {
  228740. }
  228741. void createGLBuffers()
  228742. {
  228743. makeActive();
  228744. glGenFramebuffersOES (1, &frameBufferHandle);
  228745. glGenRenderbuffersOES (1, &colorBufferHandle);
  228746. glGenRenderbuffersOES (1, &depthBufferHandle);
  228747. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  228748. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  228749. GLint width, height;
  228750. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  228751. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  228752. if (useDepthBuffer)
  228753. {
  228754. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  228755. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  228756. }
  228757. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  228758. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  228759. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  228760. if (useDepthBuffer)
  228761. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  228762. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  228763. }
  228764. void freeGLBuffers()
  228765. {
  228766. if (frameBufferHandle != 0)
  228767. {
  228768. glDeleteFramebuffersOES (1, &frameBufferHandle);
  228769. frameBufferHandle = 0;
  228770. }
  228771. if (colorBufferHandle != 0)
  228772. {
  228773. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  228774. colorBufferHandle = 0;
  228775. }
  228776. if (depthBufferHandle != 0)
  228777. {
  228778. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  228779. depthBufferHandle = 0;
  228780. }
  228781. }
  228782. juce_UseDebuggingNewOperator
  228783. private:
  228784. Component::SafePointer<Component> component;
  228785. OpenGLPixelFormat pixelFormat;
  228786. JuceGLView* view;
  228787. CAEAGLLayer* glLayer;
  228788. EAGLContext* context;
  228789. bool useDepthBuffer;
  228790. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  228791. int numFrames;
  228792. int lastWidth, lastHeight;
  228793. GLESContext (const GLESContext&);
  228794. GLESContext& operator= (const GLESContext&);
  228795. };
  228796. OpenGLContext* OpenGLComponent::createContext()
  228797. {
  228798. ScopedAutoReleasePool pool;
  228799. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  228800. if (peer != 0)
  228801. return new GLESContext (peer, this, preferredPixelFormat,
  228802. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  228803. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  228804. return 0;
  228805. }
  228806. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  228807. OwnedArray <OpenGLPixelFormat>& /*results*/)
  228808. {
  228809. }
  228810. void juce_glViewport (const int w, const int h)
  228811. {
  228812. glViewport (0, 0, w, h);
  228813. }
  228814. #endif
  228815. #endif
  228816. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  228817. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  228818. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228819. // compiled on its own).
  228820. #if JUCE_INCLUDED_FILE
  228821. #if JUCE_MAC
  228822. namespace MouseCursorHelpers
  228823. {
  228824. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  228825. {
  228826. NSImage* im = CoreGraphicsImage::createNSImage (image);
  228827. NSCursor* c = [[NSCursor alloc] initWithImage: im
  228828. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  228829. [im release];
  228830. return c;
  228831. }
  228832. static void* fromWebKitFile (const char* filename, float hx, float hy)
  228833. {
  228834. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  228835. BufferedInputStream buf (&fileStream, 4096, false);
  228836. PNGImageFormat pngFormat;
  228837. Image im (pngFormat.decodeImage (buf));
  228838. if (im.isValid())
  228839. return createFromImage (im, hx * im.getWidth(), hy * im.getHeight());
  228840. jassertfalse;
  228841. return 0;
  228842. }
  228843. }
  228844. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  228845. {
  228846. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  228847. }
  228848. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  228849. {
  228850. const ScopedAutoReleasePool pool;
  228851. NSCursor* c = 0;
  228852. switch (type)
  228853. {
  228854. case NormalCursor: c = [NSCursor arrowCursor]; break;
  228855. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  228856. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  228857. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  228858. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  228859. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  228860. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  228861. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  228862. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  228863. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  228864. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  228865. case UpDownResizeCursor:
  228866. case TopEdgeResizeCursor:
  228867. case BottomEdgeResizeCursor:
  228868. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  228869. case TopLeftCornerResizeCursor:
  228870. case BottomRightCornerResizeCursor:
  228871. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  228872. case TopRightCornerResizeCursor:
  228873. case BottomLeftCornerResizeCursor:
  228874. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  228875. case UpDownLeftRightResizeCursor:
  228876. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  228877. default:
  228878. jassertfalse;
  228879. break;
  228880. }
  228881. [c retain];
  228882. return c;
  228883. }
  228884. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  228885. {
  228886. [((NSCursor*) cursorHandle) release];
  228887. }
  228888. void MouseCursor::showInAllWindows() const
  228889. {
  228890. showInWindow (0);
  228891. }
  228892. void MouseCursor::showInWindow (ComponentPeer*) const
  228893. {
  228894. [((NSCursor*) getHandle()) set];
  228895. }
  228896. #else
  228897. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  228898. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  228899. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  228900. void MouseCursor::showInAllWindows() const {}
  228901. void MouseCursor::showInWindow (ComponentPeer*) const {}
  228902. #endif
  228903. #endif
  228904. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  228905. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  228906. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228907. // compiled on its own).
  228908. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  228909. #if JUCE_MAC
  228910. END_JUCE_NAMESPACE
  228911. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  228912. @interface DownloadClickDetector : NSObject
  228913. {
  228914. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  228915. }
  228916. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  228917. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  228918. request: (NSURLRequest*) request
  228919. frame: (WebFrame*) frame
  228920. decisionListener: (id<WebPolicyDecisionListener>) listener;
  228921. @end
  228922. @implementation DownloadClickDetector
  228923. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  228924. {
  228925. [super init];
  228926. ownerComponent = ownerComponent_;
  228927. return self;
  228928. }
  228929. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  228930. request: (NSURLRequest*) request
  228931. frame: (WebFrame*) frame
  228932. decisionListener: (id <WebPolicyDecisionListener>) listener
  228933. {
  228934. (void) sender;
  228935. (void) request;
  228936. (void) frame;
  228937. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  228938. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  228939. [listener use];
  228940. else
  228941. [listener ignore];
  228942. }
  228943. @end
  228944. BEGIN_JUCE_NAMESPACE
  228945. class WebBrowserComponentInternal : public NSViewComponent
  228946. {
  228947. public:
  228948. WebBrowserComponentInternal (WebBrowserComponent* owner)
  228949. {
  228950. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  228951. frameName: @""
  228952. groupName: @""];
  228953. setView (webView);
  228954. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  228955. [webView setPolicyDelegate: clickListener];
  228956. }
  228957. ~WebBrowserComponentInternal()
  228958. {
  228959. [webView setPolicyDelegate: nil];
  228960. [clickListener release];
  228961. setView (0);
  228962. }
  228963. void goToURL (const String& url,
  228964. const StringArray* headers,
  228965. const MemoryBlock* postData)
  228966. {
  228967. NSMutableURLRequest* r
  228968. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  228969. cachePolicy: NSURLRequestUseProtocolCachePolicy
  228970. timeoutInterval: 30.0];
  228971. if (postData != 0 && postData->getSize() > 0)
  228972. {
  228973. [r setHTTPMethod: @"POST"];
  228974. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  228975. length: postData->getSize()]];
  228976. }
  228977. if (headers != 0)
  228978. {
  228979. for (int i = 0; i < headers->size(); ++i)
  228980. {
  228981. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  228982. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  228983. [r setValue: juceStringToNS (headerValue)
  228984. forHTTPHeaderField: juceStringToNS (headerName)];
  228985. }
  228986. }
  228987. stop();
  228988. [[webView mainFrame] loadRequest: r];
  228989. }
  228990. void goBack()
  228991. {
  228992. [webView goBack];
  228993. }
  228994. void goForward()
  228995. {
  228996. [webView goForward];
  228997. }
  228998. void stop()
  228999. {
  229000. [webView stopLoading: nil];
  229001. }
  229002. void refresh()
  229003. {
  229004. [webView reload: nil];
  229005. }
  229006. private:
  229007. WebView* webView;
  229008. DownloadClickDetector* clickListener;
  229009. };
  229010. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  229011. : browser (0),
  229012. blankPageShown (false),
  229013. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  229014. {
  229015. setOpaque (true);
  229016. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  229017. }
  229018. WebBrowserComponent::~WebBrowserComponent()
  229019. {
  229020. deleteAndZero (browser);
  229021. }
  229022. void WebBrowserComponent::goToURL (const String& url,
  229023. const StringArray* headers,
  229024. const MemoryBlock* postData)
  229025. {
  229026. lastURL = url;
  229027. lastHeaders.clear();
  229028. if (headers != 0)
  229029. lastHeaders = *headers;
  229030. lastPostData.setSize (0);
  229031. if (postData != 0)
  229032. lastPostData = *postData;
  229033. blankPageShown = false;
  229034. browser->goToURL (url, headers, postData);
  229035. }
  229036. void WebBrowserComponent::stop()
  229037. {
  229038. browser->stop();
  229039. }
  229040. void WebBrowserComponent::goBack()
  229041. {
  229042. lastURL = String::empty;
  229043. blankPageShown = false;
  229044. browser->goBack();
  229045. }
  229046. void WebBrowserComponent::goForward()
  229047. {
  229048. lastURL = String::empty;
  229049. browser->goForward();
  229050. }
  229051. void WebBrowserComponent::refresh()
  229052. {
  229053. browser->refresh();
  229054. }
  229055. void WebBrowserComponent::paint (Graphics&)
  229056. {
  229057. }
  229058. void WebBrowserComponent::checkWindowAssociation()
  229059. {
  229060. if (isShowing())
  229061. {
  229062. if (blankPageShown)
  229063. goBack();
  229064. }
  229065. else
  229066. {
  229067. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  229068. {
  229069. // when the component becomes invisible, some stuff like flash
  229070. // carries on playing audio, so we need to force it onto a blank
  229071. // page to avoid this, (and send it back when it's made visible again).
  229072. blankPageShown = true;
  229073. browser->goToURL ("about:blank", 0, 0);
  229074. }
  229075. }
  229076. }
  229077. void WebBrowserComponent::reloadLastURL()
  229078. {
  229079. if (lastURL.isNotEmpty())
  229080. {
  229081. goToURL (lastURL, &lastHeaders, &lastPostData);
  229082. lastURL = String::empty;
  229083. }
  229084. }
  229085. void WebBrowserComponent::parentHierarchyChanged()
  229086. {
  229087. checkWindowAssociation();
  229088. }
  229089. void WebBrowserComponent::resized()
  229090. {
  229091. browser->setSize (getWidth(), getHeight());
  229092. }
  229093. void WebBrowserComponent::visibilityChanged()
  229094. {
  229095. checkWindowAssociation();
  229096. }
  229097. bool WebBrowserComponent::pageAboutToLoad (const String&)
  229098. {
  229099. return true;
  229100. }
  229101. #else
  229102. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  229103. {
  229104. }
  229105. WebBrowserComponent::~WebBrowserComponent()
  229106. {
  229107. }
  229108. void WebBrowserComponent::goToURL (const String& url,
  229109. const StringArray* headers,
  229110. const MemoryBlock* postData)
  229111. {
  229112. }
  229113. void WebBrowserComponent::stop()
  229114. {
  229115. }
  229116. void WebBrowserComponent::goBack()
  229117. {
  229118. }
  229119. void WebBrowserComponent::goForward()
  229120. {
  229121. }
  229122. void WebBrowserComponent::refresh()
  229123. {
  229124. }
  229125. void WebBrowserComponent::paint (Graphics& g)
  229126. {
  229127. }
  229128. void WebBrowserComponent::checkWindowAssociation()
  229129. {
  229130. }
  229131. void WebBrowserComponent::reloadLastURL()
  229132. {
  229133. }
  229134. void WebBrowserComponent::parentHierarchyChanged()
  229135. {
  229136. }
  229137. void WebBrowserComponent::resized()
  229138. {
  229139. }
  229140. void WebBrowserComponent::visibilityChanged()
  229141. {
  229142. }
  229143. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  229144. {
  229145. return true;
  229146. }
  229147. #endif
  229148. #endif
  229149. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  229150. /*** Start of inlined file: juce_iphone_Audio.cpp ***/
  229151. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229152. // compiled on its own).
  229153. #if JUCE_INCLUDED_FILE
  229154. class IPhoneAudioIODevice : public AudioIODevice
  229155. {
  229156. public:
  229157. IPhoneAudioIODevice (const String& deviceName)
  229158. : AudioIODevice (deviceName, "Audio"),
  229159. actualBufferSize (0),
  229160. isRunning (false),
  229161. audioUnit (0),
  229162. callback (0),
  229163. floatData (1, 2)
  229164. {
  229165. numInputChannels = 2;
  229166. numOutputChannels = 2;
  229167. preferredBufferSize = 0;
  229168. AudioSessionInitialize (0, 0, interruptionListenerStatic, this);
  229169. updateDeviceInfo();
  229170. }
  229171. ~IPhoneAudioIODevice()
  229172. {
  229173. close();
  229174. }
  229175. const StringArray getOutputChannelNames()
  229176. {
  229177. StringArray s;
  229178. s.add ("Left");
  229179. s.add ("Right");
  229180. return s;
  229181. }
  229182. const StringArray getInputChannelNames()
  229183. {
  229184. StringArray s;
  229185. if (audioInputIsAvailable)
  229186. {
  229187. s.add ("Left");
  229188. s.add ("Right");
  229189. }
  229190. return s;
  229191. }
  229192. int getNumSampleRates()
  229193. {
  229194. return 1;
  229195. }
  229196. double getSampleRate (int index)
  229197. {
  229198. return sampleRate;
  229199. }
  229200. int getNumBufferSizesAvailable()
  229201. {
  229202. return 1;
  229203. }
  229204. int getBufferSizeSamples (int index)
  229205. {
  229206. return getDefaultBufferSize();
  229207. }
  229208. int getDefaultBufferSize()
  229209. {
  229210. return 1024;
  229211. }
  229212. const String open (const BigInteger& inputChannels,
  229213. const BigInteger& outputChannels,
  229214. double sampleRate,
  229215. int bufferSize)
  229216. {
  229217. close();
  229218. lastError = String::empty;
  229219. preferredBufferSize = (bufferSize <= 0) ? getDefaultBufferSize() : bufferSize;
  229220. // xxx set up channel mapping
  229221. activeOutputChans = outputChannels;
  229222. activeOutputChans.setRange (2, activeOutputChans.getHighestBit(), false);
  229223. numOutputChannels = activeOutputChans.countNumberOfSetBits();
  229224. monoOutputChannelNumber = activeOutputChans.findNextSetBit (0);
  229225. activeInputChans = inputChannels;
  229226. activeInputChans.setRange (2, activeInputChans.getHighestBit(), false);
  229227. numInputChannels = activeInputChans.countNumberOfSetBits();
  229228. monoInputChannelNumber = activeInputChans.findNextSetBit (0);
  229229. AudioSessionSetActive (true);
  229230. UInt32 audioCategory = audioInputIsAvailable ? kAudioSessionCategory_PlayAndRecord
  229231. : kAudioSessionCategory_MediaPlayback;
  229232. AudioSessionSetProperty (kAudioSessionProperty_AudioCategory, sizeof (audioCategory), &audioCategory);
  229233. AudioSessionAddPropertyListener (kAudioSessionProperty_AudioRouteChange, propertyChangedStatic, this);
  229234. fixAudioRouteIfSetToReceiver();
  229235. updateDeviceInfo();
  229236. Float32 bufferDuration = preferredBufferSize / sampleRate;
  229237. AudioSessionSetProperty (kAudioSessionProperty_PreferredHardwareIOBufferDuration, sizeof (bufferDuration), &bufferDuration);
  229238. actualBufferSize = preferredBufferSize;
  229239. prepareFloatBuffers();
  229240. isRunning = true;
  229241. propertyChanged (0, 0, 0); // creates and starts the AU
  229242. lastError = audioUnit != 0 ? "" : "Couldn't open the device";
  229243. return lastError;
  229244. }
  229245. void close()
  229246. {
  229247. if (isRunning)
  229248. {
  229249. isRunning = false;
  229250. AudioSessionSetActive (false);
  229251. if (audioUnit != 0)
  229252. {
  229253. AudioComponentInstanceDispose (audioUnit);
  229254. audioUnit = 0;
  229255. }
  229256. }
  229257. }
  229258. bool isOpen()
  229259. {
  229260. return isRunning;
  229261. }
  229262. int getCurrentBufferSizeSamples()
  229263. {
  229264. return actualBufferSize;
  229265. }
  229266. double getCurrentSampleRate()
  229267. {
  229268. return sampleRate;
  229269. }
  229270. int getCurrentBitDepth()
  229271. {
  229272. return 16;
  229273. }
  229274. const BigInteger getActiveOutputChannels() const
  229275. {
  229276. return activeOutputChans;
  229277. }
  229278. const BigInteger getActiveInputChannels() const
  229279. {
  229280. return activeInputChans;
  229281. }
  229282. int getOutputLatencyInSamples()
  229283. {
  229284. return 0; //xxx
  229285. }
  229286. int getInputLatencyInSamples()
  229287. {
  229288. return 0; //xxx
  229289. }
  229290. void start (AudioIODeviceCallback* callback_)
  229291. {
  229292. if (isRunning && callback != callback_)
  229293. {
  229294. if (callback_ != 0)
  229295. callback_->audioDeviceAboutToStart (this);
  229296. const ScopedLock sl (callbackLock);
  229297. callback = callback_;
  229298. }
  229299. }
  229300. void stop()
  229301. {
  229302. if (isRunning)
  229303. {
  229304. AudioIODeviceCallback* lastCallback;
  229305. {
  229306. const ScopedLock sl (callbackLock);
  229307. lastCallback = callback;
  229308. callback = 0;
  229309. }
  229310. if (lastCallback != 0)
  229311. lastCallback->audioDeviceStopped();
  229312. }
  229313. }
  229314. bool isPlaying()
  229315. {
  229316. return isRunning && callback != 0;
  229317. }
  229318. const String getLastError()
  229319. {
  229320. return lastError;
  229321. }
  229322. private:
  229323. CriticalSection callbackLock;
  229324. Float64 sampleRate;
  229325. int numInputChannels, numOutputChannels;
  229326. int preferredBufferSize;
  229327. int actualBufferSize;
  229328. bool isRunning;
  229329. String lastError;
  229330. AudioStreamBasicDescription format;
  229331. AudioUnit audioUnit;
  229332. UInt32 audioInputIsAvailable;
  229333. AudioIODeviceCallback* callback;
  229334. BigInteger activeOutputChans, activeInputChans;
  229335. AudioSampleBuffer floatData;
  229336. float* inputChannels[3];
  229337. float* outputChannels[3];
  229338. bool monoInputChannelNumber, monoOutputChannelNumber;
  229339. void prepareFloatBuffers()
  229340. {
  229341. floatData.setSize (numInputChannels + numOutputChannels, actualBufferSize);
  229342. zerostruct (inputChannels);
  229343. zerostruct (outputChannels);
  229344. for (int i = 0; i < numInputChannels; ++i)
  229345. inputChannels[i] = floatData.getSampleData (i);
  229346. for (int i = 0; i < numOutputChannels; ++i)
  229347. outputChannels[i] = floatData.getSampleData (i + numInputChannels);
  229348. }
  229349. OSStatus process (AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  229350. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  229351. {
  229352. OSStatus err = noErr;
  229353. if (audioInputIsAvailable)
  229354. err = AudioUnitRender (audioUnit, ioActionFlags, inTimeStamp, 1, inNumberFrames, ioData);
  229355. const ScopedLock sl (callbackLock);
  229356. if (callback != 0)
  229357. {
  229358. if (audioInputIsAvailable && numInputChannels > 0)
  229359. {
  229360. short* shortData = (short*) ioData->mBuffers[0].mData;
  229361. if (numInputChannels >= 2)
  229362. {
  229363. for (UInt32 i = 0; i < inNumberFrames; ++i)
  229364. {
  229365. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  229366. inputChannels[1][i] = *shortData++ * (1.0f / 32768.0f);
  229367. }
  229368. }
  229369. else
  229370. {
  229371. if (monoInputChannelNumber > 0)
  229372. ++shortData;
  229373. for (UInt32 i = 0; i < inNumberFrames; ++i)
  229374. {
  229375. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  229376. ++shortData;
  229377. }
  229378. }
  229379. }
  229380. else
  229381. {
  229382. for (int i = numInputChannels; --i >= 0;)
  229383. zeromem (inputChannels[i], sizeof (float) * inNumberFrames);
  229384. }
  229385. callback->audioDeviceIOCallback ((const float**) inputChannels, numInputChannels,
  229386. outputChannels, numOutputChannels,
  229387. (int) inNumberFrames);
  229388. short* shortData = (short*) ioData->mBuffers[0].mData;
  229389. int n = 0;
  229390. if (numOutputChannels >= 2)
  229391. {
  229392. for (UInt32 i = 0; i < inNumberFrames; ++i)
  229393. {
  229394. shortData [n++] = (short) (outputChannels[0][i] * 32767.0f);
  229395. shortData [n++] = (short) (outputChannels[1][i] * 32767.0f);
  229396. }
  229397. }
  229398. else if (numOutputChannels == 1)
  229399. {
  229400. for (UInt32 i = 0; i < inNumberFrames; ++i)
  229401. {
  229402. const short s = (short) (outputChannels[monoOutputChannelNumber][i] * 32767.0f);
  229403. shortData [n++] = s;
  229404. shortData [n++] = s;
  229405. }
  229406. }
  229407. else
  229408. {
  229409. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  229410. }
  229411. }
  229412. else
  229413. {
  229414. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  229415. }
  229416. return err;
  229417. }
  229418. void updateDeviceInfo()
  229419. {
  229420. UInt32 size = sizeof (sampleRate);
  229421. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareSampleRate, &size, &sampleRate);
  229422. size = sizeof (audioInputIsAvailable);
  229423. AudioSessionGetProperty (kAudioSessionProperty_AudioInputAvailable, &size, &audioInputIsAvailable);
  229424. }
  229425. void propertyChanged (AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  229426. {
  229427. if (! isRunning)
  229428. return;
  229429. if (inPropertyValue != 0)
  229430. {
  229431. CFDictionaryRef routeChangeDictionary = (CFDictionaryRef) inPropertyValue;
  229432. CFNumberRef routeChangeReasonRef = (CFNumberRef) CFDictionaryGetValue (routeChangeDictionary,
  229433. CFSTR (kAudioSession_AudioRouteChangeKey_Reason));
  229434. SInt32 routeChangeReason;
  229435. CFNumberGetValue (routeChangeReasonRef, kCFNumberSInt32Type, &routeChangeReason);
  229436. if (routeChangeReason == kAudioSessionRouteChangeReason_OldDeviceUnavailable)
  229437. fixAudioRouteIfSetToReceiver();
  229438. }
  229439. updateDeviceInfo();
  229440. createAudioUnit();
  229441. AudioSessionSetActive (true);
  229442. if (audioUnit != 0)
  229443. {
  229444. UInt32 formatSize = sizeof (format);
  229445. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, &formatSize);
  229446. Float32 bufferDuration = preferredBufferSize / sampleRate;
  229447. UInt32 bufferDurationSize = sizeof (bufferDuration);
  229448. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareIOBufferDuration, &bufferDurationSize, &bufferDurationSize);
  229449. actualBufferSize = (int) (sampleRate * bufferDuration + 0.5);
  229450. AudioOutputUnitStart (audioUnit);
  229451. }
  229452. }
  229453. void interruptionListener (UInt32 inInterruption)
  229454. {
  229455. /*if (inInterruption == kAudioSessionBeginInterruption)
  229456. {
  229457. isRunning = false;
  229458. AudioOutputUnitStop (audioUnit);
  229459. if (juce_iPhoneShowModalAlert ("Audio Interrupted",
  229460. "This could have been interrupted by another application or by unplugging a headset",
  229461. @"Resume",
  229462. @"Cancel"))
  229463. {
  229464. isRunning = true;
  229465. propertyChanged (0, 0, 0);
  229466. }
  229467. }*/
  229468. if (inInterruption == kAudioSessionEndInterruption)
  229469. {
  229470. isRunning = true;
  229471. AudioSessionSetActive (true);
  229472. AudioOutputUnitStart (audioUnit);
  229473. }
  229474. }
  229475. static OSStatus processStatic (void* inRefCon, AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  229476. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  229477. {
  229478. return ((IPhoneAudioIODevice*) inRefCon)->process (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  229479. }
  229480. static void propertyChangedStatic (void* inClientData, AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  229481. {
  229482. ((IPhoneAudioIODevice*) inClientData)->propertyChanged (inID, inDataSize, inPropertyValue);
  229483. }
  229484. static void interruptionListenerStatic (void* inClientData, UInt32 inInterruption)
  229485. {
  229486. ((IPhoneAudioIODevice*) inClientData)->interruptionListener (inInterruption);
  229487. }
  229488. void resetFormat (const int numChannels)
  229489. {
  229490. memset (&format, 0, sizeof (format));
  229491. format.mFormatID = kAudioFormatLinearPCM;
  229492. format.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked;
  229493. format.mBitsPerChannel = 8 * sizeof (short);
  229494. format.mChannelsPerFrame = 2;
  229495. format.mFramesPerPacket = 1;
  229496. format.mBytesPerFrame = format.mBytesPerPacket = 2 * sizeof (short);
  229497. }
  229498. bool createAudioUnit()
  229499. {
  229500. if (audioUnit != 0)
  229501. {
  229502. AudioComponentInstanceDispose (audioUnit);
  229503. audioUnit = 0;
  229504. }
  229505. resetFormat (2);
  229506. AudioComponentDescription desc;
  229507. desc.componentType = kAudioUnitType_Output;
  229508. desc.componentSubType = kAudioUnitSubType_RemoteIO;
  229509. desc.componentManufacturer = kAudioUnitManufacturer_Apple;
  229510. desc.componentFlags = 0;
  229511. desc.componentFlagsMask = 0;
  229512. AudioComponent comp = AudioComponentFindNext (0, &desc);
  229513. AudioComponentInstanceNew (comp, &audioUnit);
  229514. if (audioUnit == 0)
  229515. return false;
  229516. const UInt32 one = 1;
  229517. AudioUnitSetProperty (audioUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, &one, sizeof (one));
  229518. AudioChannelLayout layout;
  229519. layout.mChannelBitmap = 0;
  229520. layout.mNumberChannelDescriptions = 0;
  229521. layout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  229522. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Input, 0, &layout, sizeof (layout));
  229523. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Output, 0, &layout, sizeof (layout));
  229524. AURenderCallbackStruct inputProc;
  229525. inputProc.inputProc = processStatic;
  229526. inputProc.inputProcRefCon = this;
  229527. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &inputProc, sizeof (inputProc));
  229528. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &format, sizeof (format));
  229529. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, sizeof (format));
  229530. AudioUnitInitialize (audioUnit);
  229531. return true;
  229532. }
  229533. // If the routing is set to go through the receiver (i.e. the speaker, but quiet), this re-routes it
  229534. // to make it loud. Needed because by default when using an input + output, the output is kept quiet.
  229535. static void fixAudioRouteIfSetToReceiver()
  229536. {
  229537. CFStringRef audioRoute = 0;
  229538. UInt32 propertySize = sizeof (audioRoute);
  229539. if (AudioSessionGetProperty (kAudioSessionProperty_AudioRoute, &propertySize, &audioRoute) == noErr)
  229540. {
  229541. NSString* route = (NSString*) audioRoute;
  229542. //DBG ("audio route: " + nsStringToJuce (route));
  229543. if ([route hasPrefix: @"Receiver"])
  229544. {
  229545. UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
  229546. AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute, sizeof (audioRouteOverride), &audioRouteOverride);
  229547. }
  229548. CFRelease (audioRoute);
  229549. }
  229550. }
  229551. IPhoneAudioIODevice (const IPhoneAudioIODevice&);
  229552. IPhoneAudioIODevice& operator= (const IPhoneAudioIODevice&);
  229553. };
  229554. class IPhoneAudioIODeviceType : public AudioIODeviceType
  229555. {
  229556. public:
  229557. IPhoneAudioIODeviceType()
  229558. : AudioIODeviceType ("iPhone Audio")
  229559. {
  229560. }
  229561. ~IPhoneAudioIODeviceType()
  229562. {
  229563. }
  229564. void scanForDevices()
  229565. {
  229566. }
  229567. const StringArray getDeviceNames (bool wantInputNames) const
  229568. {
  229569. StringArray s;
  229570. s.add ("iPhone Audio");
  229571. return s;
  229572. }
  229573. int getDefaultDeviceIndex (bool forInput) const
  229574. {
  229575. return 0;
  229576. }
  229577. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  229578. {
  229579. return device != 0 ? 0 : -1;
  229580. }
  229581. bool hasSeparateInputsAndOutputs() const { return false; }
  229582. AudioIODevice* createDevice (const String& outputDeviceName,
  229583. const String& inputDeviceName)
  229584. {
  229585. if (outputDeviceName.isNotEmpty() || inputDeviceName.isNotEmpty())
  229586. {
  229587. return new IPhoneAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  229588. : inputDeviceName);
  229589. }
  229590. return 0;
  229591. }
  229592. juce_UseDebuggingNewOperator
  229593. private:
  229594. IPhoneAudioIODeviceType (const IPhoneAudioIODeviceType&);
  229595. IPhoneAudioIODeviceType& operator= (const IPhoneAudioIODeviceType&);
  229596. };
  229597. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio()
  229598. {
  229599. return new IPhoneAudioIODeviceType();
  229600. }
  229601. #endif
  229602. /*** End of inlined file: juce_iphone_Audio.cpp ***/
  229603. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  229604. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229605. // compiled on its own).
  229606. #if JUCE_INCLUDED_FILE
  229607. #if JUCE_MAC
  229608. namespace CoreMidiHelpers
  229609. {
  229610. static bool logError (const OSStatus err, const int lineNum)
  229611. {
  229612. if (err == noErr)
  229613. return true;
  229614. Logger::writeToLog ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  229615. jassertfalse;
  229616. return false;
  229617. }
  229618. #undef CHECK_ERROR
  229619. #define CHECK_ERROR(a) CoreMidiHelpers::logError (a, __LINE__)
  229620. static const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  229621. {
  229622. String result;
  229623. CFStringRef str = 0;
  229624. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  229625. if (str != 0)
  229626. {
  229627. result = PlatformUtilities::cfStringToJuceString (str);
  229628. CFRelease (str);
  229629. str = 0;
  229630. }
  229631. MIDIEntityRef entity = 0;
  229632. MIDIEndpointGetEntity (endpoint, &entity);
  229633. if (entity == 0)
  229634. return result; // probably virtual
  229635. if (result.isEmpty())
  229636. {
  229637. // endpoint name has zero length - try the entity
  229638. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  229639. if (str != 0)
  229640. {
  229641. result += PlatformUtilities::cfStringToJuceString (str);
  229642. CFRelease (str);
  229643. str = 0;
  229644. }
  229645. }
  229646. // now consider the device's name
  229647. MIDIDeviceRef device = 0;
  229648. MIDIEntityGetDevice (entity, &device);
  229649. if (device == 0)
  229650. return result;
  229651. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  229652. if (str != 0)
  229653. {
  229654. const String s (PlatformUtilities::cfStringToJuceString (str));
  229655. CFRelease (str);
  229656. // if an external device has only one entity, throw away
  229657. // the endpoint name and just use the device name
  229658. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  229659. {
  229660. result = s;
  229661. }
  229662. else if (! result.startsWithIgnoreCase (s))
  229663. {
  229664. // prepend the device name to the entity name
  229665. result = (s + " " + result).trimEnd();
  229666. }
  229667. }
  229668. return result;
  229669. }
  229670. static const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  229671. {
  229672. String result;
  229673. // Does the endpoint have connections?
  229674. CFDataRef connections = 0;
  229675. int numConnections = 0;
  229676. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  229677. if (connections != 0)
  229678. {
  229679. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  229680. if (numConnections > 0)
  229681. {
  229682. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  229683. for (int i = 0; i < numConnections; ++i, ++pid)
  229684. {
  229685. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  229686. MIDIObjectRef connObject;
  229687. MIDIObjectType connObjectType;
  229688. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  229689. if (err == noErr)
  229690. {
  229691. String s;
  229692. if (connObjectType == kMIDIObjectType_ExternalSource
  229693. || connObjectType == kMIDIObjectType_ExternalDestination)
  229694. {
  229695. // Connected to an external device's endpoint (10.3 and later).
  229696. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  229697. }
  229698. else
  229699. {
  229700. // Connected to an external device (10.2) (or something else, catch-all)
  229701. CFStringRef str = 0;
  229702. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  229703. if (str != 0)
  229704. {
  229705. s = PlatformUtilities::cfStringToJuceString (str);
  229706. CFRelease (str);
  229707. }
  229708. }
  229709. if (s.isNotEmpty())
  229710. {
  229711. if (result.isNotEmpty())
  229712. result += ", ";
  229713. result += s;
  229714. }
  229715. }
  229716. }
  229717. }
  229718. CFRelease (connections);
  229719. }
  229720. if (result.isNotEmpty())
  229721. return result;
  229722. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  229723. return getEndpointName (endpoint, false);
  229724. }
  229725. static MIDIClientRef getGlobalMidiClient()
  229726. {
  229727. static MIDIClientRef globalMidiClient = 0;
  229728. if (globalMidiClient == 0)
  229729. {
  229730. String name ("JUCE");
  229731. if (JUCEApplication::getInstance() != 0)
  229732. name = JUCEApplication::getInstance()->getApplicationName();
  229733. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  229734. CHECK_ERROR (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  229735. CFRelease (appName);
  229736. }
  229737. return globalMidiClient;
  229738. }
  229739. class MidiPortAndEndpoint
  229740. {
  229741. public:
  229742. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  229743. : port (port_), endPoint (endPoint_)
  229744. {
  229745. }
  229746. ~MidiPortAndEndpoint()
  229747. {
  229748. if (port != 0)
  229749. MIDIPortDispose (port);
  229750. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  229751. MIDIEndpointDispose (endPoint);
  229752. }
  229753. void send (const MIDIPacketList* const packets)
  229754. {
  229755. if (port != 0)
  229756. MIDISend (port, endPoint, packets);
  229757. else
  229758. MIDIReceived (endPoint, packets);
  229759. }
  229760. MIDIPortRef port;
  229761. MIDIEndpointRef endPoint;
  229762. };
  229763. class MidiPortAndCallback;
  229764. static CriticalSection callbackLock;
  229765. static Array<MidiPortAndCallback*> activeCallbacks;
  229766. class MidiPortAndCallback
  229767. {
  229768. public:
  229769. MidiPortAndCallback (MidiInputCallback& callback_)
  229770. : input (0), active (false), callback (callback_), concatenator (2048)
  229771. {
  229772. }
  229773. ~MidiPortAndCallback()
  229774. {
  229775. active = false;
  229776. {
  229777. const ScopedLock sl (callbackLock);
  229778. activeCallbacks.removeValue (this);
  229779. }
  229780. if (portAndEndpoint != 0 && portAndEndpoint->port != 0)
  229781. CHECK_ERROR (MIDIPortDisconnectSource (portAndEndpoint->port, portAndEndpoint->endPoint));
  229782. }
  229783. void handlePackets (const MIDIPacketList* const pktlist)
  229784. {
  229785. const double time = Time::getMillisecondCounterHiRes() * 0.001;
  229786. const ScopedLock sl (callbackLock);
  229787. if (activeCallbacks.contains (this) && active)
  229788. {
  229789. const MIDIPacket* packet = &pktlist->packet[0];
  229790. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  229791. {
  229792. concatenator.pushMidiData (packet->data, (int) packet->length, time,
  229793. input, callback);
  229794. packet = MIDIPacketNext (packet);
  229795. }
  229796. }
  229797. }
  229798. MidiInput* input;
  229799. ScopedPointer<MidiPortAndEndpoint> portAndEndpoint;
  229800. volatile bool active;
  229801. private:
  229802. MidiInputCallback& callback;
  229803. MidiDataConcatenator concatenator;
  229804. };
  229805. static void midiInputProc (const MIDIPacketList* pktlist, void* readProcRefCon, void* /*srcConnRefCon*/)
  229806. {
  229807. static_cast <MidiPortAndCallback*> (readProcRefCon)->handlePackets (pktlist);
  229808. }
  229809. }
  229810. const StringArray MidiOutput::getDevices()
  229811. {
  229812. StringArray s;
  229813. const ItemCount num = MIDIGetNumberOfDestinations();
  229814. for (ItemCount i = 0; i < num; ++i)
  229815. {
  229816. MIDIEndpointRef dest = MIDIGetDestination (i);
  229817. if (dest != 0)
  229818. {
  229819. String name (CoreMidiHelpers::getConnectedEndpointName (dest));
  229820. if (name.isEmpty())
  229821. name = "<error>";
  229822. s.add (name);
  229823. }
  229824. else
  229825. {
  229826. s.add ("<error>");
  229827. }
  229828. }
  229829. return s;
  229830. }
  229831. int MidiOutput::getDefaultDeviceIndex()
  229832. {
  229833. return 0;
  229834. }
  229835. MidiOutput* MidiOutput::openDevice (int index)
  229836. {
  229837. MidiOutput* mo = 0;
  229838. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfDestinations())
  229839. {
  229840. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  229841. CFStringRef pname;
  229842. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  229843. {
  229844. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  229845. MIDIPortRef port;
  229846. if (client != 0 && CHECK_ERROR (MIDIOutputPortCreate (client, pname, &port)))
  229847. {
  229848. mo = new MidiOutput();
  229849. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (port, endPoint);
  229850. }
  229851. CFRelease (pname);
  229852. }
  229853. }
  229854. return mo;
  229855. }
  229856. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  229857. {
  229858. MidiOutput* mo = 0;
  229859. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  229860. MIDIEndpointRef endPoint;
  229861. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  229862. if (client != 0 && CHECK_ERROR (MIDISourceCreate (client, name, &endPoint)))
  229863. {
  229864. mo = new MidiOutput();
  229865. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (0, endPoint);
  229866. }
  229867. CFRelease (name);
  229868. return mo;
  229869. }
  229870. MidiOutput::~MidiOutput()
  229871. {
  229872. delete static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  229873. }
  229874. void MidiOutput::reset()
  229875. {
  229876. }
  229877. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  229878. {
  229879. return false;
  229880. }
  229881. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  229882. {
  229883. }
  229884. void MidiOutput::sendMessageNow (const MidiMessage& message)
  229885. {
  229886. CoreMidiHelpers::MidiPortAndEndpoint* const mpe = static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  229887. if (message.isSysEx())
  229888. {
  229889. const int maxPacketSize = 256;
  229890. int pos = 0, bytesLeft = message.getRawDataSize();
  229891. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  229892. HeapBlock <MIDIPacketList> packets;
  229893. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  229894. packets->numPackets = numPackets;
  229895. MIDIPacket* p = packets->packet;
  229896. for (int i = 0; i < numPackets; ++i)
  229897. {
  229898. p->timeStamp = 0;
  229899. p->length = jmin (maxPacketSize, bytesLeft);
  229900. memcpy (p->data, message.getRawData() + pos, p->length);
  229901. pos += p->length;
  229902. bytesLeft -= p->length;
  229903. p = MIDIPacketNext (p);
  229904. }
  229905. mpe->send (packets);
  229906. }
  229907. else
  229908. {
  229909. MIDIPacketList packets;
  229910. packets.numPackets = 1;
  229911. packets.packet[0].timeStamp = 0;
  229912. packets.packet[0].length = message.getRawDataSize();
  229913. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  229914. mpe->send (&packets);
  229915. }
  229916. }
  229917. const StringArray MidiInput::getDevices()
  229918. {
  229919. StringArray s;
  229920. const ItemCount num = MIDIGetNumberOfSources();
  229921. for (ItemCount i = 0; i < num; ++i)
  229922. {
  229923. MIDIEndpointRef source = MIDIGetSource (i);
  229924. if (source != 0)
  229925. {
  229926. String name (CoreMidiHelpers::getConnectedEndpointName (source));
  229927. if (name.isEmpty())
  229928. name = "<error>";
  229929. s.add (name);
  229930. }
  229931. else
  229932. {
  229933. s.add ("<error>");
  229934. }
  229935. }
  229936. return s;
  229937. }
  229938. int MidiInput::getDefaultDeviceIndex()
  229939. {
  229940. return 0;
  229941. }
  229942. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  229943. {
  229944. jassert (callback != 0);
  229945. using namespace CoreMidiHelpers;
  229946. MidiInput* newInput = 0;
  229947. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfSources())
  229948. {
  229949. MIDIEndpointRef endPoint = MIDIGetSource (index);
  229950. if (endPoint != 0)
  229951. {
  229952. CFStringRef name;
  229953. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &name)))
  229954. {
  229955. MIDIClientRef client = getGlobalMidiClient();
  229956. if (client != 0)
  229957. {
  229958. MIDIPortRef port;
  229959. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  229960. if (CHECK_ERROR (MIDIInputPortCreate (client, name, midiInputProc, mpc, &port)))
  229961. {
  229962. if (CHECK_ERROR (MIDIPortConnectSource (port, endPoint, 0)))
  229963. {
  229964. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  229965. newInput = new MidiInput (getDevices() [index]);
  229966. mpc->input = newInput;
  229967. newInput->internal = mpc;
  229968. const ScopedLock sl (callbackLock);
  229969. activeCallbacks.add (mpc.release());
  229970. }
  229971. else
  229972. {
  229973. CHECK_ERROR (MIDIPortDispose (port));
  229974. }
  229975. }
  229976. }
  229977. }
  229978. CFRelease (name);
  229979. }
  229980. }
  229981. return newInput;
  229982. }
  229983. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  229984. {
  229985. jassert (callback != 0);
  229986. using namespace CoreMidiHelpers;
  229987. MidiInput* mi = 0;
  229988. MIDIClientRef client = getGlobalMidiClient();
  229989. if (client != 0)
  229990. {
  229991. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  229992. mpc->active = false;
  229993. MIDIEndpointRef endPoint;
  229994. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  229995. if (CHECK_ERROR (MIDIDestinationCreate (client, name, midiInputProc, mpc, &endPoint)))
  229996. {
  229997. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  229998. mi = new MidiInput (deviceName);
  229999. mpc->input = mi;
  230000. mi->internal = mpc;
  230001. const ScopedLock sl (callbackLock);
  230002. activeCallbacks.add (mpc.release());
  230003. }
  230004. CFRelease (name);
  230005. }
  230006. return mi;
  230007. }
  230008. MidiInput::MidiInput (const String& name_)
  230009. : name (name_)
  230010. {
  230011. }
  230012. MidiInput::~MidiInput()
  230013. {
  230014. delete static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal);
  230015. }
  230016. void MidiInput::start()
  230017. {
  230018. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  230019. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = true;
  230020. }
  230021. void MidiInput::stop()
  230022. {
  230023. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  230024. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = false;
  230025. }
  230026. #undef CHECK_ERROR
  230027. #else // Stubs for iOS...
  230028. MidiOutput::~MidiOutput() {}
  230029. void MidiOutput::reset() {}
  230030. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/) { return false; }
  230031. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/) {}
  230032. void MidiOutput::sendMessageNow (const MidiMessage& message) {}
  230033. const StringArray MidiOutput::getDevices() { return StringArray(); }
  230034. MidiOutput* MidiOutput::openDevice (int index) { return 0; }
  230035. const StringArray MidiInput::getDevices() { return StringArray(); }
  230036. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback) { return 0; }
  230037. #endif
  230038. #endif
  230039. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  230040. #else
  230041. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  230042. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230043. // compiled on its own).
  230044. #if JUCE_INCLUDED_FILE
  230045. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230046. #define SUPPORT_10_4_FONTS 1
  230047. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  230048. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  230049. #define SUPPORT_ONLY_10_4_FONTS 1
  230050. #endif
  230051. END_JUCE_NAMESPACE
  230052. @interface NSFont (PrivateHack)
  230053. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  230054. @end
  230055. BEGIN_JUCE_NAMESPACE
  230056. #endif
  230057. class MacTypeface : public Typeface
  230058. {
  230059. public:
  230060. MacTypeface (const Font& font)
  230061. : Typeface (font.getTypefaceName())
  230062. {
  230063. const ScopedAutoReleasePool pool;
  230064. renderingTransform = CGAffineTransformIdentity;
  230065. bool needsItalicTransform = false;
  230066. #if JUCE_IOS
  230067. NSString* fontName = juceStringToNS (font.getTypefaceName());
  230068. if (font.isItalic() || font.isBold())
  230069. {
  230070. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  230071. for (NSString* i in familyFonts)
  230072. {
  230073. const String fn (nsStringToJuce (i));
  230074. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  230075. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  230076. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  230077. || afterDash.containsIgnoreCase ("italic")
  230078. || fn.endsWithIgnoreCase ("oblique")
  230079. || fn.endsWithIgnoreCase ("italic");
  230080. if (probablyBold == font.isBold()
  230081. && probablyItalic == font.isItalic())
  230082. {
  230083. fontName = i;
  230084. needsItalicTransform = false;
  230085. break;
  230086. }
  230087. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  230088. {
  230089. fontName = i;
  230090. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  230091. }
  230092. }
  230093. if (needsItalicTransform)
  230094. renderingTransform.c = 0.15f;
  230095. }
  230096. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  230097. const int ascender = abs (CGFontGetAscent (fontRef));
  230098. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  230099. ascent = ascender / totalHeight;
  230100. unitsToHeightScaleFactor = 1.0f / totalHeight;
  230101. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  230102. #else
  230103. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  230104. if (font.isItalic())
  230105. {
  230106. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  230107. toHaveTrait: NSItalicFontMask];
  230108. if (newFont == nsFont)
  230109. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  230110. nsFont = newFont;
  230111. }
  230112. if (font.isBold())
  230113. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  230114. [nsFont retain];
  230115. ascent = std::abs ((float) [nsFont ascender]);
  230116. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  230117. ascent /= totalSize;
  230118. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  230119. if (needsItalicTransform)
  230120. {
  230121. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  230122. renderingTransform.c = 0.15f;
  230123. }
  230124. #if SUPPORT_ONLY_10_4_FONTS
  230125. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  230126. if (atsFont == 0)
  230127. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  230128. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  230129. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  230130. unitsToHeightScaleFactor = 1.0f / totalHeight;
  230131. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  230132. #else
  230133. #if SUPPORT_10_4_FONTS
  230134. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  230135. {
  230136. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  230137. if (atsFont == 0)
  230138. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  230139. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  230140. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  230141. unitsToHeightScaleFactor = 1.0f / totalHeight;
  230142. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  230143. }
  230144. else
  230145. #endif
  230146. {
  230147. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  230148. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  230149. unitsToHeightScaleFactor = 1.0f / totalHeight;
  230150. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  230151. }
  230152. #endif
  230153. #endif
  230154. }
  230155. ~MacTypeface()
  230156. {
  230157. #if ! JUCE_IOS
  230158. [nsFont release];
  230159. #endif
  230160. if (fontRef != 0)
  230161. CGFontRelease (fontRef);
  230162. }
  230163. float getAscent() const
  230164. {
  230165. return ascent;
  230166. }
  230167. float getDescent() const
  230168. {
  230169. return 1.0f - ascent;
  230170. }
  230171. float getStringWidth (const String& text)
  230172. {
  230173. if (fontRef == 0 || text.isEmpty())
  230174. return 0;
  230175. const int length = text.length();
  230176. HeapBlock <CGGlyph> glyphs;
  230177. createGlyphsForString (text, length, glyphs);
  230178. float x = 0;
  230179. #if SUPPORT_ONLY_10_4_FONTS
  230180. HeapBlock <NSSize> advances (length);
  230181. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  230182. for (int i = 0; i < length; ++i)
  230183. x += advances[i].width;
  230184. #else
  230185. #if SUPPORT_10_4_FONTS
  230186. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  230187. {
  230188. HeapBlock <NSSize> advances (length);
  230189. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  230190. for (int i = 0; i < length; ++i)
  230191. x += advances[i].width;
  230192. }
  230193. else
  230194. #endif
  230195. {
  230196. HeapBlock <int> advances (length);
  230197. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  230198. for (int i = 0; i < length; ++i)
  230199. x += advances[i];
  230200. }
  230201. #endif
  230202. return x * unitsToHeightScaleFactor;
  230203. }
  230204. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  230205. {
  230206. xOffsets.add (0);
  230207. if (fontRef == 0 || text.isEmpty())
  230208. return;
  230209. const int length = text.length();
  230210. HeapBlock <CGGlyph> glyphs;
  230211. createGlyphsForString (text, length, glyphs);
  230212. #if SUPPORT_ONLY_10_4_FONTS
  230213. HeapBlock <NSSize> advances (length);
  230214. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  230215. int x = 0;
  230216. for (int i = 0; i < length; ++i)
  230217. {
  230218. x += advances[i].width;
  230219. xOffsets.add (x * unitsToHeightScaleFactor);
  230220. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  230221. }
  230222. #else
  230223. #if SUPPORT_10_4_FONTS
  230224. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  230225. {
  230226. HeapBlock <NSSize> advances (length);
  230227. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  230228. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  230229. float x = 0;
  230230. for (int i = 0; i < length; ++i)
  230231. {
  230232. x += advances[i].width;
  230233. xOffsets.add (x * unitsToHeightScaleFactor);
  230234. resultGlyphs.add (nsGlyphs[i]);
  230235. }
  230236. }
  230237. else
  230238. #endif
  230239. {
  230240. HeapBlock <int> advances (length);
  230241. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  230242. {
  230243. int x = 0;
  230244. for (int i = 0; i < length; ++i)
  230245. {
  230246. x += advances [i];
  230247. xOffsets.add (x * unitsToHeightScaleFactor);
  230248. resultGlyphs.add (glyphs[i]);
  230249. }
  230250. }
  230251. }
  230252. #endif
  230253. }
  230254. bool getOutlineForGlyph (int glyphNumber, Path& path)
  230255. {
  230256. #if JUCE_IOS
  230257. return false;
  230258. #else
  230259. if (nsFont == 0)
  230260. return false;
  230261. // we might need to apply a transform to the path, so it mustn't have anything else in it
  230262. jassert (path.isEmpty());
  230263. const ScopedAutoReleasePool pool;
  230264. NSBezierPath* bez = [NSBezierPath bezierPath];
  230265. [bez moveToPoint: NSMakePoint (0, 0)];
  230266. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  230267. inFont: nsFont];
  230268. for (int i = 0; i < [bez elementCount]; ++i)
  230269. {
  230270. NSPoint p[3];
  230271. switch ([bez elementAtIndex: i associatedPoints: p])
  230272. {
  230273. case NSMoveToBezierPathElement:
  230274. path.startNewSubPath ((float) p[0].x, (float) -p[0].y);
  230275. break;
  230276. case NSLineToBezierPathElement:
  230277. path.lineTo ((float) p[0].x, (float) -p[0].y);
  230278. break;
  230279. case NSCurveToBezierPathElement:
  230280. 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);
  230281. break;
  230282. case NSClosePathBezierPathElement:
  230283. path.closeSubPath();
  230284. break;
  230285. default:
  230286. jassertfalse;
  230287. break;
  230288. }
  230289. }
  230290. path.applyTransform (pathTransform);
  230291. return true;
  230292. #endif
  230293. }
  230294. juce_UseDebuggingNewOperator
  230295. CGFontRef fontRef;
  230296. float fontHeightToCGSizeFactor;
  230297. CGAffineTransform renderingTransform;
  230298. private:
  230299. float ascent, unitsToHeightScaleFactor;
  230300. #if JUCE_IOS
  230301. #else
  230302. NSFont* nsFont;
  230303. AffineTransform pathTransform;
  230304. #endif
  230305. void createGlyphsForString (const juce_wchar* const text, const int length, HeapBlock <CGGlyph>& glyphs)
  230306. {
  230307. #if SUPPORT_10_4_FONTS
  230308. #if ! SUPPORT_ONLY_10_4_FONTS
  230309. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  230310. #endif
  230311. {
  230312. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  230313. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  230314. for (int i = 0; i < length; ++i)
  230315. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text[i]];
  230316. return;
  230317. }
  230318. #endif
  230319. #if ! SUPPORT_ONLY_10_4_FONTS
  230320. if (charToGlyphMapper == 0)
  230321. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  230322. glyphs.malloc (length);
  230323. for (int i = 0; i < length; ++i)
  230324. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text[i]);
  230325. #endif
  230326. }
  230327. #if ! SUPPORT_ONLY_10_4_FONTS
  230328. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  230329. class CharToGlyphMapper
  230330. {
  230331. public:
  230332. CharToGlyphMapper (CGFontRef fontRef)
  230333. : segCount (0), endCode (0), startCode (0), idDelta (0),
  230334. idRangeOffset (0), glyphIndexes (0)
  230335. {
  230336. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  230337. if (cmapTable != 0)
  230338. {
  230339. const int numSubtables = getValue16 (cmapTable, 2);
  230340. for (int i = 0; i < numSubtables; ++i)
  230341. {
  230342. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  230343. {
  230344. const int offset = getValue32 (cmapTable, i * 8 + 8);
  230345. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  230346. {
  230347. const int length = getValue16 (cmapTable, offset + 2);
  230348. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  230349. segCount = segCountX2 / 2;
  230350. const int endCodeOffset = offset + 14;
  230351. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  230352. const int idDeltaOffset = startCodeOffset + segCountX2;
  230353. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  230354. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  230355. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  230356. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  230357. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  230358. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  230359. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  230360. }
  230361. break;
  230362. }
  230363. }
  230364. CFRelease (cmapTable);
  230365. }
  230366. }
  230367. ~CharToGlyphMapper()
  230368. {
  230369. if (endCode != 0)
  230370. {
  230371. CFRelease (endCode);
  230372. CFRelease (startCode);
  230373. CFRelease (idDelta);
  230374. CFRelease (idRangeOffset);
  230375. CFRelease (glyphIndexes);
  230376. }
  230377. }
  230378. int getGlyphForCharacter (const juce_wchar c) const
  230379. {
  230380. for (int i = 0; i < segCount; ++i)
  230381. {
  230382. if (getValue16 (endCode, i * 2) >= c)
  230383. {
  230384. const int start = getValue16 (startCode, i * 2);
  230385. if (start > c)
  230386. break;
  230387. const int delta = getValue16 (idDelta, i * 2);
  230388. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  230389. if (rangeOffset == 0)
  230390. return delta + c;
  230391. else
  230392. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  230393. }
  230394. }
  230395. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  230396. return jmax (-1, (int) c - 29);
  230397. }
  230398. private:
  230399. int segCount;
  230400. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  230401. static uint16 getValue16 (CFDataRef data, const int index)
  230402. {
  230403. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  230404. }
  230405. static uint32 getValue32 (CFDataRef data, const int index)
  230406. {
  230407. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  230408. }
  230409. };
  230410. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  230411. #endif
  230412. MacTypeface (const MacTypeface&);
  230413. MacTypeface& operator= (const MacTypeface&);
  230414. };
  230415. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  230416. {
  230417. return new MacTypeface (font);
  230418. }
  230419. const StringArray Font::findAllTypefaceNames()
  230420. {
  230421. StringArray names;
  230422. const ScopedAutoReleasePool pool;
  230423. #if JUCE_IOS
  230424. NSArray* fonts = [UIFont familyNames];
  230425. #else
  230426. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  230427. #endif
  230428. for (unsigned int i = 0; i < [fonts count]; ++i)
  230429. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  230430. names.sort (true);
  230431. return names;
  230432. }
  230433. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  230434. {
  230435. #if JUCE_IOS
  230436. defaultSans = "Helvetica";
  230437. defaultSerif = "Times New Roman";
  230438. defaultFixed = "Courier New";
  230439. #else
  230440. defaultSans = "Lucida Grande";
  230441. defaultSerif = "Times New Roman";
  230442. defaultFixed = "Monaco";
  230443. #endif
  230444. }
  230445. #endif
  230446. /*** End of inlined file: juce_mac_Fonts.mm ***/
  230447. // (must go before juce_mac_CoreGraphicsContext.mm)
  230448. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  230449. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230450. // compiled on its own).
  230451. #if JUCE_INCLUDED_FILE
  230452. class CoreGraphicsImage : public Image::SharedImage
  230453. {
  230454. public:
  230455. CoreGraphicsImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  230456. : Image::SharedImage (format_, width_, height_)
  230457. {
  230458. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  230459. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  230460. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  230461. imageData = imageDataAllocated;
  230462. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  230463. : CGColorSpaceCreateDeviceRGB();
  230464. context = CGBitmapContextCreate (imageData, width, height, 8, lineStride,
  230465. colourSpace, getCGImageFlags (format_));
  230466. CGColorSpaceRelease (colourSpace);
  230467. }
  230468. ~CoreGraphicsImage()
  230469. {
  230470. CGContextRelease (context);
  230471. }
  230472. Image::ImageType getType() const { return Image::NativeImage; }
  230473. LowLevelGraphicsContext* createLowLevelContext();
  230474. SharedImage* clone()
  230475. {
  230476. CoreGraphicsImage* im = new CoreGraphicsImage (format, width, height, false);
  230477. memcpy (im->imageData, imageData, lineStride * height);
  230478. return im;
  230479. }
  230480. static CGImageRef createImage (const Image& juceImage, const bool forAlpha, CGColorSpaceRef colourSpace)
  230481. {
  230482. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (juceImage.getSharedImage());
  230483. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  230484. {
  230485. return CGBitmapContextCreateImage (nativeImage->context);
  230486. }
  230487. else
  230488. {
  230489. const Image::BitmapData srcData (juceImage, false);
  230490. CGDataProviderRef provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  230491. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  230492. 8, srcData.pixelStride * 8, srcData.lineStride,
  230493. colourSpace, getCGImageFlags (juceImage.getFormat()), provider,
  230494. 0, true, kCGRenderingIntentDefault);
  230495. CGDataProviderRelease (provider);
  230496. return imageRef;
  230497. }
  230498. }
  230499. #if JUCE_MAC
  230500. static NSImage* createNSImage (const Image& image)
  230501. {
  230502. const ScopedAutoReleasePool pool;
  230503. NSImage* im = [[NSImage alloc] init];
  230504. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  230505. [im lockFocus];
  230506. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  230507. CGImageRef imageRef = createImage (image, false, colourSpace);
  230508. CGColorSpaceRelease (colourSpace);
  230509. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  230510. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  230511. CGImageRelease (imageRef);
  230512. [im unlockFocus];
  230513. return im;
  230514. }
  230515. #endif
  230516. CGContextRef context;
  230517. HeapBlock<uint8> imageDataAllocated;
  230518. private:
  230519. static CGBitmapInfo getCGImageFlags (const Image::PixelFormat& format)
  230520. {
  230521. #if JUCE_BIG_ENDIAN
  230522. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  230523. #else
  230524. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  230525. #endif
  230526. }
  230527. };
  230528. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  230529. {
  230530. #if USE_COREGRAPHICS_RENDERING
  230531. return new CoreGraphicsImage (format == RGB ? ARGB : format, width, height, clearImage);
  230532. #else
  230533. return createSoftwareImage (format, width, height, clearImage);
  230534. #endif
  230535. }
  230536. class CoreGraphicsContext : public LowLevelGraphicsContext
  230537. {
  230538. public:
  230539. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  230540. : context (context_),
  230541. flipHeight (flipHeight_),
  230542. lastClipRectIsValid (false),
  230543. state (new SavedState()),
  230544. numGradientLookupEntries (0)
  230545. {
  230546. CGContextRetain (context);
  230547. CGContextSaveGState(context);
  230548. CGContextSetShouldSmoothFonts (context, true);
  230549. CGContextSetShouldAntialias (context, true);
  230550. CGContextSetBlendMode (context, kCGBlendModeNormal);
  230551. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  230552. greyColourSpace = CGColorSpaceCreateDeviceGray();
  230553. gradientCallbacks.version = 0;
  230554. gradientCallbacks.evaluate = gradientCallback;
  230555. gradientCallbacks.releaseInfo = 0;
  230556. setFont (Font());
  230557. }
  230558. ~CoreGraphicsContext()
  230559. {
  230560. CGContextRestoreGState (context);
  230561. CGContextRelease (context);
  230562. CGColorSpaceRelease (rgbColourSpace);
  230563. CGColorSpaceRelease (greyColourSpace);
  230564. }
  230565. bool isVectorDevice() const { return false; }
  230566. void setOrigin (int x, int y)
  230567. {
  230568. CGContextTranslateCTM (context, x, -y);
  230569. if (lastClipRectIsValid)
  230570. lastClipRect.translate (-x, -y);
  230571. }
  230572. bool clipToRectangle (const Rectangle<int>& r)
  230573. {
  230574. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  230575. if (lastClipRectIsValid)
  230576. {
  230577. // This is actually incorrect, because the actual clip region may be complex, and
  230578. // clipping its bounds to a rect may not be right... But, removing this shortcut
  230579. // doesn't actually fix anything because CoreGraphics also ignores complex regions
  230580. // when calculating the resultant clip bounds, and makes the same mistake!
  230581. lastClipRect = lastClipRect.getIntersection (r);
  230582. return ! lastClipRect.isEmpty();
  230583. }
  230584. return ! isClipEmpty();
  230585. }
  230586. bool clipToRectangleList (const RectangleList& clipRegion)
  230587. {
  230588. if (clipRegion.isEmpty())
  230589. {
  230590. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  230591. lastClipRectIsValid = true;
  230592. lastClipRect = Rectangle<int>();
  230593. return false;
  230594. }
  230595. else
  230596. {
  230597. const int numRects = clipRegion.getNumRectangles();
  230598. HeapBlock <CGRect> rects (numRects);
  230599. for (int i = 0; i < numRects; ++i)
  230600. {
  230601. const Rectangle<int>& r = clipRegion.getRectangle(i);
  230602. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  230603. }
  230604. CGContextClipToRects (context, rects, numRects);
  230605. lastClipRectIsValid = false;
  230606. return ! isClipEmpty();
  230607. }
  230608. }
  230609. void excludeClipRectangle (const Rectangle<int>& r)
  230610. {
  230611. RectangleList remaining (getClipBounds());
  230612. remaining.subtract (r);
  230613. clipToRectangleList (remaining);
  230614. lastClipRectIsValid = false;
  230615. }
  230616. void clipToPath (const Path& path, const AffineTransform& transform)
  230617. {
  230618. createPath (path, transform);
  230619. CGContextClip (context);
  230620. lastClipRectIsValid = false;
  230621. }
  230622. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  230623. {
  230624. if (! transform.isSingularity())
  230625. {
  230626. Image singleChannelImage (sourceImage);
  230627. if (sourceImage.getFormat() != Image::SingleChannel)
  230628. singleChannelImage = sourceImage.convertedToFormat (Image::SingleChannel);
  230629. CGImageRef image = CoreGraphicsImage::createImage (singleChannelImage, true, greyColourSpace);
  230630. flip();
  230631. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, sourceImage.getHeight()).followedBy (transform));
  230632. applyTransform (t);
  230633. CGRect r = CGRectMake (0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  230634. CGContextClipToMask (context, r, image);
  230635. applyTransform (t.inverted());
  230636. flip();
  230637. CGImageRelease (image);
  230638. lastClipRectIsValid = false;
  230639. }
  230640. }
  230641. bool clipRegionIntersects (const Rectangle<int>& r)
  230642. {
  230643. return getClipBounds().intersects (r);
  230644. }
  230645. const Rectangle<int> getClipBounds() const
  230646. {
  230647. if (! lastClipRectIsValid)
  230648. {
  230649. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  230650. lastClipRectIsValid = true;
  230651. lastClipRect.setBounds (roundToInt (bounds.origin.x),
  230652. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  230653. roundToInt (bounds.size.width),
  230654. roundToInt (bounds.size.height));
  230655. }
  230656. return lastClipRect;
  230657. }
  230658. bool isClipEmpty() const
  230659. {
  230660. return getClipBounds().isEmpty();
  230661. }
  230662. void saveState()
  230663. {
  230664. CGContextSaveGState (context);
  230665. stateStack.add (new SavedState (*state));
  230666. }
  230667. void restoreState()
  230668. {
  230669. CGContextRestoreGState (context);
  230670. SavedState* const top = stateStack.getLast();
  230671. if (top != 0)
  230672. {
  230673. state = top;
  230674. stateStack.removeLast (1, false);
  230675. lastClipRectIsValid = false;
  230676. }
  230677. else
  230678. {
  230679. jassertfalse; // trying to pop with an empty stack!
  230680. }
  230681. }
  230682. void setFill (const FillType& fillType)
  230683. {
  230684. state->fillType = fillType;
  230685. if (fillType.isColour())
  230686. {
  230687. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  230688. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  230689. CGContextSetAlpha (context, 1.0f);
  230690. }
  230691. }
  230692. void setOpacity (float newOpacity)
  230693. {
  230694. state->fillType.setOpacity (newOpacity);
  230695. setFill (state->fillType);
  230696. }
  230697. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  230698. {
  230699. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  230700. ? kCGInterpolationLow
  230701. : kCGInterpolationHigh);
  230702. }
  230703. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  230704. {
  230705. fillCGRect (CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()), replaceExistingContents);
  230706. }
  230707. void fillCGRect (const CGRect& cgRect, const bool replaceExistingContents)
  230708. {
  230709. if (replaceExistingContents)
  230710. {
  230711. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  230712. CGContextClearRect (context, cgRect);
  230713. #else
  230714. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230715. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  230716. CGContextClearRect (context, cgRect);
  230717. else
  230718. #endif
  230719. CGContextSetBlendMode (context, kCGBlendModeCopy);
  230720. #endif
  230721. fillCGRect (cgRect, false);
  230722. CGContextSetBlendMode (context, kCGBlendModeNormal);
  230723. }
  230724. else
  230725. {
  230726. if (state->fillType.isColour())
  230727. {
  230728. CGContextFillRect (context, cgRect);
  230729. }
  230730. else if (state->fillType.isGradient())
  230731. {
  230732. CGContextSaveGState (context);
  230733. CGContextClipToRect (context, cgRect);
  230734. drawGradient();
  230735. CGContextRestoreGState (context);
  230736. }
  230737. else
  230738. {
  230739. CGContextSaveGState (context);
  230740. CGContextClipToRect (context, cgRect);
  230741. drawImage (state->fillType.image, state->fillType.transform, true);
  230742. CGContextRestoreGState (context);
  230743. }
  230744. }
  230745. }
  230746. void fillPath (const Path& path, const AffineTransform& transform)
  230747. {
  230748. CGContextSaveGState (context);
  230749. if (state->fillType.isColour())
  230750. {
  230751. flip();
  230752. applyTransform (transform);
  230753. createPath (path);
  230754. if (path.isUsingNonZeroWinding())
  230755. CGContextFillPath (context);
  230756. else
  230757. CGContextEOFillPath (context);
  230758. }
  230759. else
  230760. {
  230761. createPath (path, transform);
  230762. if (path.isUsingNonZeroWinding())
  230763. CGContextClip (context);
  230764. else
  230765. CGContextEOClip (context);
  230766. if (state->fillType.isGradient())
  230767. drawGradient();
  230768. else
  230769. drawImage (state->fillType.image, state->fillType.transform, true);
  230770. }
  230771. CGContextRestoreGState (context);
  230772. }
  230773. void drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  230774. {
  230775. const int iw = sourceImage.getWidth();
  230776. const int ih = sourceImage.getHeight();
  230777. CGImageRef image = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace);
  230778. CGContextSaveGState (context);
  230779. CGContextSetAlpha (context, state->fillType.getOpacity());
  230780. flip();
  230781. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, ih).followedBy (transform));
  230782. CGRect imageRect = CGRectMake (0, 0, iw, ih);
  230783. if (fillEntireClipAsTiles)
  230784. {
  230785. #if JUCE_IOS
  230786. CGContextDrawTiledImage (context, imageRect, image);
  230787. #else
  230788. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  230789. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  230790. // if it's doing a transformation - it's quicker to just draw lots of images manually
  230791. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  230792. CGContextDrawTiledImage (context, imageRect, image);
  230793. else
  230794. #endif
  230795. {
  230796. // Fallback to manually doing a tiled fill on 10.4
  230797. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  230798. int x = 0, y = 0;
  230799. while (x > clip.origin.x) x -= iw;
  230800. while (y > clip.origin.y) y -= ih;
  230801. const int right = (int) (clip.origin.x + clip.size.width);
  230802. const int bottom = (int) (clip.origin.y + clip.size.height);
  230803. while (y < bottom)
  230804. {
  230805. for (int x2 = x; x2 < right; x2 += iw)
  230806. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  230807. y += ih;
  230808. }
  230809. }
  230810. #endif
  230811. }
  230812. else
  230813. {
  230814. CGContextDrawImage (context, imageRect, image);
  230815. }
  230816. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  230817. CGContextRestoreGState (context);
  230818. }
  230819. void drawLine (const Line<float>& line)
  230820. {
  230821. if (state->fillType.isColour())
  230822. {
  230823. CGContextSetLineCap (context, kCGLineCapSquare);
  230824. CGContextSetLineWidth (context, 1.0f);
  230825. CGContextSetRGBStrokeColor (context,
  230826. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  230827. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  230828. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  230829. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  230830. CGContextStrokeLineSegments (context, cgLine, 1);
  230831. }
  230832. else
  230833. {
  230834. Path p;
  230835. p.addLineSegment (line, 1.0f);
  230836. fillPath (p, AffineTransform::identity);
  230837. }
  230838. }
  230839. void drawVerticalLine (const int x, float top, float bottom)
  230840. {
  230841. if (state->fillType.isColour())
  230842. {
  230843. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  230844. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  230845. #else
  230846. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  230847. // the x co-ord slightly to trick it..
  230848. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  230849. #endif
  230850. }
  230851. else
  230852. {
  230853. fillCGRect (CGRectMake ((float) x, flipHeight - bottom, 1.0f, bottom - top), false);
  230854. }
  230855. }
  230856. void drawHorizontalLine (const int y, float left, float right)
  230857. {
  230858. if (state->fillType.isColour())
  230859. {
  230860. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  230861. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  230862. #else
  230863. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  230864. // the x co-ord slightly to trick it..
  230865. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  230866. #endif
  230867. }
  230868. else
  230869. {
  230870. fillCGRect (CGRectMake (left, flipHeight - (y + 1), right - left, 1.0f), false);
  230871. }
  230872. }
  230873. void setFont (const Font& newFont)
  230874. {
  230875. if (state->font != newFont)
  230876. {
  230877. state->fontRef = 0;
  230878. state->font = newFont;
  230879. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  230880. if (mf != 0)
  230881. {
  230882. state->fontRef = mf->fontRef;
  230883. CGContextSetFont (context, state->fontRef);
  230884. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  230885. state->fontTransform = mf->renderingTransform;
  230886. state->fontTransform.a *= state->font.getHorizontalScale();
  230887. CGContextSetTextMatrix (context, state->fontTransform);
  230888. }
  230889. }
  230890. }
  230891. const Font getFont()
  230892. {
  230893. return state->font;
  230894. }
  230895. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  230896. {
  230897. if (state->fontRef != 0 && state->fillType.isColour())
  230898. {
  230899. if (transform.isOnlyTranslation())
  230900. {
  230901. CGContextSetTextMatrix (context, state->fontTransform); // have to set this each time, as it's not saved as part of the state
  230902. CGGlyph g = glyphNumber;
  230903. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  230904. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  230905. }
  230906. else
  230907. {
  230908. CGContextSaveGState (context);
  230909. flip();
  230910. applyTransform (transform);
  230911. CGAffineTransform t = state->fontTransform;
  230912. t.d = -t.d;
  230913. CGContextSetTextMatrix (context, t);
  230914. CGGlyph g = glyphNumber;
  230915. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  230916. CGContextRestoreGState (context);
  230917. }
  230918. }
  230919. else
  230920. {
  230921. Path p;
  230922. Font& f = state->font;
  230923. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  230924. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  230925. .followedBy (transform));
  230926. }
  230927. }
  230928. private:
  230929. CGContextRef context;
  230930. const CGFloat flipHeight;
  230931. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  230932. CGFunctionCallbacks gradientCallbacks;
  230933. mutable Rectangle<int> lastClipRect;
  230934. mutable bool lastClipRectIsValid;
  230935. struct SavedState
  230936. {
  230937. SavedState()
  230938. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  230939. {
  230940. }
  230941. SavedState (const SavedState& other)
  230942. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  230943. fontTransform (other.fontTransform)
  230944. {
  230945. }
  230946. ~SavedState()
  230947. {
  230948. }
  230949. FillType fillType;
  230950. Font font;
  230951. CGFontRef fontRef;
  230952. CGAffineTransform fontTransform;
  230953. };
  230954. ScopedPointer <SavedState> state;
  230955. OwnedArray <SavedState> stateStack;
  230956. HeapBlock <PixelARGB> gradientLookupTable;
  230957. int numGradientLookupEntries;
  230958. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  230959. {
  230960. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  230961. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  230962. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  230963. colour.unpremultiply();
  230964. outData[0] = colour.getRed() / 255.0f;
  230965. outData[1] = colour.getGreen() / 255.0f;
  230966. outData[2] = colour.getBlue() / 255.0f;
  230967. outData[3] = colour.getAlpha() / 255.0f;
  230968. }
  230969. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  230970. {
  230971. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable);
  230972. --numGradientLookupEntries;
  230973. CGShadingRef result = 0;
  230974. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  230975. CGPoint p1 (CGPointMake (gradient.point1.getX(), gradient.point1.getY()));
  230976. if (gradient.isRadial)
  230977. {
  230978. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  230979. p1, gradient.point1.getDistanceFrom (gradient.point2),
  230980. function, true, true);
  230981. }
  230982. else
  230983. {
  230984. result = CGShadingCreateAxial (rgbColourSpace, p1,
  230985. CGPointMake (gradient.point2.getX(), gradient.point2.getY()),
  230986. function, true, true);
  230987. }
  230988. CGFunctionRelease (function);
  230989. return result;
  230990. }
  230991. void drawGradient()
  230992. {
  230993. flip();
  230994. applyTransform (state->fillType.transform);
  230995. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  230996. // you draw a gradient with high quality interp enabled).
  230997. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  230998. CGContextSetAlpha (context, state->fillType.getOpacity());
  230999. CGContextDrawShading (context, shading);
  231000. CGShadingRelease (shading);
  231001. }
  231002. void createPath (const Path& path) const
  231003. {
  231004. CGContextBeginPath (context);
  231005. Path::Iterator i (path);
  231006. while (i.next())
  231007. {
  231008. switch (i.elementType)
  231009. {
  231010. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  231011. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  231012. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  231013. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  231014. case Path::Iterator::closePath: CGContextClosePath (context); break;
  231015. default: jassertfalse; break;
  231016. }
  231017. }
  231018. }
  231019. void createPath (const Path& path, const AffineTransform& transform) const
  231020. {
  231021. CGContextBeginPath (context);
  231022. Path::Iterator i (path);
  231023. while (i.next())
  231024. {
  231025. switch (i.elementType)
  231026. {
  231027. case Path::Iterator::startNewSubPath:
  231028. transform.transformPoint (i.x1, i.y1);
  231029. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  231030. break;
  231031. case Path::Iterator::lineTo:
  231032. transform.transformPoint (i.x1, i.y1);
  231033. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  231034. break;
  231035. case Path::Iterator::quadraticTo:
  231036. transform.transformPoints (i.x1, i.y1, i.x2, i.y2);
  231037. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  231038. break;
  231039. case Path::Iterator::cubicTo:
  231040. transform.transformPoints (i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  231041. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  231042. break;
  231043. case Path::Iterator::closePath:
  231044. CGContextClosePath (context); break;
  231045. default:
  231046. jassertfalse;
  231047. break;
  231048. }
  231049. }
  231050. }
  231051. void flip() const
  231052. {
  231053. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  231054. }
  231055. void applyTransform (const AffineTransform& transform) const
  231056. {
  231057. CGAffineTransform t;
  231058. t.a = transform.mat00;
  231059. t.b = transform.mat10;
  231060. t.c = transform.mat01;
  231061. t.d = transform.mat11;
  231062. t.tx = transform.mat02;
  231063. t.ty = transform.mat12;
  231064. CGContextConcatCTM (context, t);
  231065. }
  231066. CoreGraphicsContext (const CoreGraphicsContext&);
  231067. CoreGraphicsContext& operator= (const CoreGraphicsContext&);
  231068. };
  231069. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  231070. {
  231071. return new CoreGraphicsContext (context, height);
  231072. }
  231073. #if USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  231074. const Image juce_loadWithCoreImage (InputStream& input)
  231075. {
  231076. MemoryBlock data;
  231077. input.readIntoMemoryBlock (data, -1);
  231078. #if JUCE_IOS
  231079. JUCE_AUTORELEASEPOOL
  231080. UIImage* image = [UIImage imageWithData: [NSData dataWithBytesNoCopy: data.getData()
  231081. length: data.getSize()
  231082. freeWhenDone: NO]];
  231083. if (image != nil)
  231084. {
  231085. CGImageRef loadedImage = image.CGImage;
  231086. #else
  231087. CGDataProviderRef provider = CGDataProviderCreateWithData (0, data.getData(), data.getSize(), 0);
  231088. CGImageSourceRef imageSource = CGImageSourceCreateWithDataProvider (provider, 0);
  231089. CGDataProviderRelease (provider);
  231090. if (imageSource != 0)
  231091. {
  231092. CGImageRef loadedImage = CGImageSourceCreateImageAtIndex (imageSource, 0, 0);
  231093. CFRelease (imageSource);
  231094. #endif
  231095. if (loadedImage != 0)
  231096. {
  231097. const bool hasAlphaChan = CGImageGetAlphaInfo (loadedImage) != kCGImageAlphaNone;
  231098. Image image (hasAlphaChan ? Image::ARGB : Image::RGB,
  231099. (int) CGImageGetWidth (loadedImage), (int) CGImageGetHeight (loadedImage),
  231100. hasAlphaChan, Image::NativeImage);
  231101. CoreGraphicsImage* const cgImage = dynamic_cast<CoreGraphicsImage*> (image.getSharedImage());
  231102. jassert (cgImage != 0); // if USE_COREGRAPHICS_RENDERING is set, the CoreGraphicsImage class should have been used.
  231103. CGContextDrawImage (cgImage->context, CGRectMake (0, 0, image.getWidth(), image.getHeight()), loadedImage);
  231104. CGContextFlush (cgImage->context);
  231105. #if ! JUCE_IOS
  231106. CFRelease (loadedImage);
  231107. #endif
  231108. return image;
  231109. }
  231110. }
  231111. return Image::null;
  231112. }
  231113. #endif
  231114. #endif
  231115. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  231116. /*** Start of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  231117. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  231118. // compiled on its own).
  231119. #if JUCE_INCLUDED_FILE
  231120. class NSViewComponentPeer;
  231121. END_JUCE_NAMESPACE
  231122. @interface NSEvent (JuceDeviceDelta)
  231123. - (float) deviceDeltaX;
  231124. - (float) deviceDeltaY;
  231125. @end
  231126. #define JuceNSView MakeObjCClassName(JuceNSView)
  231127. @interface JuceNSView : NSView<NSTextInput>
  231128. {
  231129. @public
  231130. NSViewComponentPeer* owner;
  231131. NSNotificationCenter* notificationCenter;
  231132. String* stringBeingComposed;
  231133. bool textWasInserted;
  231134. }
  231135. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner withFrame: (NSRect) frame;
  231136. - (void) dealloc;
  231137. - (BOOL) isOpaque;
  231138. - (void) drawRect: (NSRect) r;
  231139. - (void) mouseDown: (NSEvent*) ev;
  231140. - (void) asyncMouseDown: (NSEvent*) ev;
  231141. - (void) mouseUp: (NSEvent*) ev;
  231142. - (void) asyncMouseUp: (NSEvent*) ev;
  231143. - (void) mouseDragged: (NSEvent*) ev;
  231144. - (void) mouseMoved: (NSEvent*) ev;
  231145. - (void) mouseEntered: (NSEvent*) ev;
  231146. - (void) mouseExited: (NSEvent*) ev;
  231147. - (void) rightMouseDown: (NSEvent*) ev;
  231148. - (void) rightMouseDragged: (NSEvent*) ev;
  231149. - (void) rightMouseUp: (NSEvent*) ev;
  231150. - (void) otherMouseDown: (NSEvent*) ev;
  231151. - (void) otherMouseDragged: (NSEvent*) ev;
  231152. - (void) otherMouseUp: (NSEvent*) ev;
  231153. - (void) scrollWheel: (NSEvent*) ev;
  231154. - (BOOL) acceptsFirstMouse: (NSEvent*) ev;
  231155. - (void) frameChanged: (NSNotification*) n;
  231156. - (void) viewDidMoveToWindow;
  231157. - (void) keyDown: (NSEvent*) ev;
  231158. - (void) keyUp: (NSEvent*) ev;
  231159. // NSTextInput Methods
  231160. - (void) insertText: (id) aString;
  231161. - (void) doCommandBySelector: (SEL) aSelector;
  231162. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selRange;
  231163. - (void) unmarkText;
  231164. - (BOOL) hasMarkedText;
  231165. - (long) conversationIdentifier;
  231166. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange;
  231167. - (NSRange) markedRange;
  231168. - (NSRange) selectedRange;
  231169. - (NSRect) firstRectForCharacterRange: (NSRange) theRange;
  231170. - (NSUInteger) characterIndexForPoint: (NSPoint) thePoint;
  231171. - (NSArray*) validAttributesForMarkedText;
  231172. - (void) flagsChanged: (NSEvent*) ev;
  231173. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  231174. - (BOOL) performKeyEquivalent: (NSEvent*) ev;
  231175. #endif
  231176. - (BOOL) becomeFirstResponder;
  231177. - (BOOL) resignFirstResponder;
  231178. - (BOOL) acceptsFirstResponder;
  231179. - (void) asyncRepaint: (id) rect;
  231180. - (NSArray*) getSupportedDragTypes;
  231181. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender;
  231182. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender;
  231183. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender;
  231184. - (void) draggingEnded: (id <NSDraggingInfo>) sender;
  231185. - (void) draggingExited: (id <NSDraggingInfo>) sender;
  231186. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender;
  231187. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender;
  231188. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender;
  231189. @end
  231190. #define JuceNSWindow MakeObjCClassName(JuceNSWindow)
  231191. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  231192. @interface JuceNSWindow : NSWindow <NSWindowDelegate>
  231193. #else
  231194. @interface JuceNSWindow : NSWindow
  231195. #endif
  231196. {
  231197. @private
  231198. NSViewComponentPeer* owner;
  231199. bool isZooming;
  231200. }
  231201. - (void) setOwner: (NSViewComponentPeer*) owner;
  231202. - (BOOL) canBecomeKeyWindow;
  231203. - (void) becomeKeyWindow;
  231204. - (BOOL) windowShouldClose: (id) window;
  231205. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen;
  231206. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize;
  231207. - (void) zoom: (id) sender;
  231208. @end
  231209. BEGIN_JUCE_NAMESPACE
  231210. class NSViewComponentPeer : public ComponentPeer
  231211. {
  231212. public:
  231213. NSViewComponentPeer (Component* const component,
  231214. const int windowStyleFlags,
  231215. NSView* viewToAttachTo);
  231216. ~NSViewComponentPeer();
  231217. void* getNativeHandle() const;
  231218. void setVisible (bool shouldBeVisible);
  231219. void setTitle (const String& title);
  231220. void setPosition (int x, int y);
  231221. void setSize (int w, int h);
  231222. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen);
  231223. const Rectangle<int> getBounds (const bool global) const;
  231224. const Rectangle<int> getBounds() const;
  231225. const Point<int> getScreenPosition() const;
  231226. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition);
  231227. const Point<int> globalPositionToRelative (const Point<int>& screenPosition);
  231228. void setMinimised (bool shouldBeMinimised);
  231229. bool isMinimised() const;
  231230. void setFullScreen (bool shouldBeFullScreen);
  231231. bool isFullScreen() const;
  231232. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  231233. const BorderSize getFrameSize() const;
  231234. bool setAlwaysOnTop (bool alwaysOnTop);
  231235. void toFront (bool makeActiveWindow);
  231236. void toBehind (ComponentPeer* other);
  231237. void setIcon (const Image& newIcon);
  231238. const StringArray getAvailableRenderingEngines();
  231239. int getCurrentRenderingEngine() throw();
  231240. void setCurrentRenderingEngine (int index);
  231241. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  231242. for example having more than one juce plugin loaded into a host, then when a
  231243. method is called, the actual code that runs might actually be in a different module
  231244. than the one you expect... So any calls to library functions or statics that are
  231245. made inside obj-c methods will probably end up getting executed in a different DLL's
  231246. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  231247. To work around this insanity, I'm only allowing obj-c methods to make calls to
  231248. virtual methods of an object that's known to live inside the right module's space.
  231249. */
  231250. virtual void redirectMouseDown (NSEvent* ev);
  231251. virtual void redirectMouseUp (NSEvent* ev);
  231252. virtual void redirectMouseDrag (NSEvent* ev);
  231253. virtual void redirectMouseMove (NSEvent* ev);
  231254. virtual void redirectMouseEnter (NSEvent* ev);
  231255. virtual void redirectMouseExit (NSEvent* ev);
  231256. virtual void redirectMouseWheel (NSEvent* ev);
  231257. void sendMouseEvent (NSEvent* ev);
  231258. bool handleKeyEvent (NSEvent* ev, bool isKeyDown);
  231259. virtual bool redirectKeyDown (NSEvent* ev);
  231260. virtual bool redirectKeyUp (NSEvent* ev);
  231261. virtual void redirectModKeyChange (NSEvent* ev);
  231262. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  231263. virtual bool redirectPerformKeyEquivalent (NSEvent* ev);
  231264. #endif
  231265. virtual BOOL sendDragCallback (int type, id <NSDraggingInfo> sender);
  231266. virtual bool isOpaque();
  231267. virtual void drawRect (NSRect r);
  231268. virtual bool canBecomeKeyWindow();
  231269. virtual bool windowShouldClose();
  231270. virtual void redirectMovedOrResized();
  231271. virtual void viewMovedToWindow();
  231272. virtual NSRect constrainRect (NSRect r);
  231273. static void showArrowCursorIfNeeded();
  231274. static void updateModifiers (NSEvent* e);
  231275. static void updateKeysDown (NSEvent* ev, bool isKeyDown);
  231276. static int getKeyCodeFromEvent (NSEvent* ev)
  231277. {
  231278. const String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  231279. int keyCode = unmodified[0];
  231280. if (keyCode == 0x19) // (backwards-tab)
  231281. keyCode = '\t';
  231282. else if (keyCode == 0x03) // (enter)
  231283. keyCode = '\r';
  231284. else
  231285. keyCode = (int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  231286. if (([ev modifierFlags] & NSNumericPadKeyMask) != 0)
  231287. {
  231288. const int numPadConversions[] = { '0', KeyPress::numberPad0, '1', KeyPress::numberPad1,
  231289. '2', KeyPress::numberPad2, '3', KeyPress::numberPad3,
  231290. '4', KeyPress::numberPad4, '5', KeyPress::numberPad5,
  231291. '6', KeyPress::numberPad6, '7', KeyPress::numberPad7,
  231292. '8', KeyPress::numberPad8, '9', KeyPress::numberPad9,
  231293. '+', KeyPress::numberPadAdd, '-', KeyPress::numberPadSubtract,
  231294. '*', KeyPress::numberPadMultiply, '/', KeyPress::numberPadDivide,
  231295. '.', KeyPress::numberPadDecimalPoint, '=', KeyPress::numberPadEquals };
  231296. for (int i = 0; i < numElementsInArray (numPadConversions); i += 2)
  231297. if (keyCode == numPadConversions [i])
  231298. keyCode = numPadConversions [i + 1];
  231299. }
  231300. return keyCode;
  231301. }
  231302. static int64 getMouseTime (NSEvent* e)
  231303. {
  231304. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  231305. + (int64) ([e timestamp] * 1000.0);
  231306. }
  231307. static const Point<int> getMousePos (NSEvent* e, NSView* view)
  231308. {
  231309. NSPoint p = [view convertPoint: [e locationInWindow] fromView: nil];
  231310. return Point<int> (roundToInt (p.x), roundToInt ([view frame].size.height - p.y));
  231311. }
  231312. static int getModifierForButtonNumber (const NSInteger num)
  231313. {
  231314. return num == 0 ? ModifierKeys::leftButtonModifier
  231315. : (num == 1 ? ModifierKeys::rightButtonModifier
  231316. : (num == 2 ? ModifierKeys::middleButtonModifier : 0));
  231317. }
  231318. virtual void viewFocusGain();
  231319. virtual void viewFocusLoss();
  231320. bool isFocused() const;
  231321. void grabFocus();
  231322. void textInputRequired (const Point<int>& position);
  231323. void repaint (const Rectangle<int>& area);
  231324. void performAnyPendingRepaintsNow();
  231325. juce_UseDebuggingNewOperator
  231326. NSWindow* window;
  231327. JuceNSView* view;
  231328. bool isSharedWindow, fullScreen, insideDrawRect, usingCoreGraphics, recursiveToFrontCall;
  231329. static ModifierKeys currentModifiers;
  231330. static ComponentPeer* currentlyFocusedPeer;
  231331. static Array<int> keysCurrentlyDown;
  231332. };
  231333. END_JUCE_NAMESPACE
  231334. @implementation JuceNSView
  231335. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner_
  231336. withFrame: (NSRect) frame
  231337. {
  231338. [super initWithFrame: frame];
  231339. owner = owner_;
  231340. stringBeingComposed = 0;
  231341. textWasInserted = false;
  231342. notificationCenter = [NSNotificationCenter defaultCenter];
  231343. [notificationCenter addObserver: self
  231344. selector: @selector (frameChanged:)
  231345. name: NSViewFrameDidChangeNotification
  231346. object: self];
  231347. if (! owner_->isSharedWindow)
  231348. {
  231349. [notificationCenter addObserver: self
  231350. selector: @selector (frameChanged:)
  231351. name: NSWindowDidMoveNotification
  231352. object: owner_->window];
  231353. }
  231354. [self registerForDraggedTypes: [self getSupportedDragTypes]];
  231355. return self;
  231356. }
  231357. - (void) dealloc
  231358. {
  231359. [notificationCenter removeObserver: self];
  231360. delete stringBeingComposed;
  231361. [super dealloc];
  231362. }
  231363. - (void) drawRect: (NSRect) r
  231364. {
  231365. if (owner != 0)
  231366. owner->drawRect (r);
  231367. }
  231368. - (BOOL) isOpaque
  231369. {
  231370. return owner == 0 || owner->isOpaque();
  231371. }
  231372. - (void) mouseDown: (NSEvent*) ev
  231373. {
  231374. if (JUCEApplication::isStandaloneApp())
  231375. [self asyncMouseDown: ev];
  231376. else
  231377. // In some host situations, the host will stop modal loops from working
  231378. // correctly if they're called from a mouse event, so we'll trigger
  231379. // the event asynchronously..
  231380. [self performSelectorOnMainThread: @selector (asyncMouseDown:)
  231381. withObject: ev
  231382. waitUntilDone: NO];
  231383. }
  231384. - (void) asyncMouseDown: (NSEvent*) ev
  231385. {
  231386. if (owner != 0)
  231387. owner->redirectMouseDown (ev);
  231388. }
  231389. - (void) mouseUp: (NSEvent*) ev
  231390. {
  231391. if (! JUCEApplication::isStandaloneApp())
  231392. [self asyncMouseUp: ev];
  231393. else
  231394. // In some host situations, the host will stop modal loops from working
  231395. // correctly if they're called from a mouse event, so we'll trigger
  231396. // the event asynchronously..
  231397. [self performSelectorOnMainThread: @selector (asyncMouseUp:)
  231398. withObject: ev
  231399. waitUntilDone: NO];
  231400. }
  231401. - (void) asyncMouseUp: (NSEvent*) ev
  231402. {
  231403. if (owner != 0)
  231404. owner->redirectMouseUp (ev);
  231405. }
  231406. - (void) mouseDragged: (NSEvent*) ev
  231407. {
  231408. if (owner != 0)
  231409. owner->redirectMouseDrag (ev);
  231410. }
  231411. - (void) mouseMoved: (NSEvent*) ev
  231412. {
  231413. if (owner != 0)
  231414. owner->redirectMouseMove (ev);
  231415. }
  231416. - (void) mouseEntered: (NSEvent*) ev
  231417. {
  231418. if (owner != 0)
  231419. owner->redirectMouseEnter (ev);
  231420. }
  231421. - (void) mouseExited: (NSEvent*) ev
  231422. {
  231423. if (owner != 0)
  231424. owner->redirectMouseExit (ev);
  231425. }
  231426. - (void) rightMouseDown: (NSEvent*) ev
  231427. {
  231428. [self mouseDown: ev];
  231429. }
  231430. - (void) rightMouseDragged: (NSEvent*) ev
  231431. {
  231432. [self mouseDragged: ev];
  231433. }
  231434. - (void) rightMouseUp: (NSEvent*) ev
  231435. {
  231436. [self mouseUp: ev];
  231437. }
  231438. - (void) otherMouseDown: (NSEvent*) ev
  231439. {
  231440. [self mouseDown: ev];
  231441. }
  231442. - (void) otherMouseDragged: (NSEvent*) ev
  231443. {
  231444. [self mouseDragged: ev];
  231445. }
  231446. - (void) otherMouseUp: (NSEvent*) ev
  231447. {
  231448. [self mouseUp: ev];
  231449. }
  231450. - (void) scrollWheel: (NSEvent*) ev
  231451. {
  231452. if (owner != 0)
  231453. owner->redirectMouseWheel (ev);
  231454. }
  231455. - (BOOL) acceptsFirstMouse: (NSEvent*) ev
  231456. {
  231457. (void) ev;
  231458. return YES;
  231459. }
  231460. - (void) frameChanged: (NSNotification*) n
  231461. {
  231462. (void) n;
  231463. if (owner != 0)
  231464. owner->redirectMovedOrResized();
  231465. }
  231466. - (void) viewDidMoveToWindow
  231467. {
  231468. if (owner != 0)
  231469. owner->viewMovedToWindow();
  231470. }
  231471. - (void) asyncRepaint: (id) rect
  231472. {
  231473. NSRect* r = (NSRect*) [((NSData*) rect) bytes];
  231474. [self setNeedsDisplayInRect: *r];
  231475. }
  231476. - (void) keyDown: (NSEvent*) ev
  231477. {
  231478. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231479. textWasInserted = false;
  231480. if (target != 0)
  231481. [self interpretKeyEvents: [NSArray arrayWithObject: ev]];
  231482. else
  231483. deleteAndZero (stringBeingComposed);
  231484. if ((! textWasInserted) && (owner == 0 || ! owner->redirectKeyDown (ev)))
  231485. [super keyDown: ev];
  231486. }
  231487. - (void) keyUp: (NSEvent*) ev
  231488. {
  231489. if (owner == 0 || ! owner->redirectKeyUp (ev))
  231490. [super keyUp: ev];
  231491. }
  231492. - (void) insertText: (id) aString
  231493. {
  231494. // This commits multi-byte text when return is pressed, or after every keypress for western keyboards
  231495. NSString* newText = [aString isKindOfClass: [NSAttributedString class]] ? [aString string] : aString;
  231496. if ([newText length] > 0)
  231497. {
  231498. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231499. if (target != 0)
  231500. {
  231501. target->insertTextAtCaret (nsStringToJuce (newText));
  231502. textWasInserted = true;
  231503. }
  231504. }
  231505. deleteAndZero (stringBeingComposed);
  231506. }
  231507. - (void) doCommandBySelector: (SEL) aSelector
  231508. {
  231509. (void) aSelector;
  231510. }
  231511. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selectionRange
  231512. {
  231513. (void) selectionRange;
  231514. if (stringBeingComposed == 0)
  231515. stringBeingComposed = new String();
  231516. *stringBeingComposed = nsStringToJuce ([aString isKindOfClass:[NSAttributedString class]] ? [aString string] : aString);
  231517. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231518. if (target != 0)
  231519. {
  231520. const Range<int> currentHighlight (target->getHighlightedRegion());
  231521. target->insertTextAtCaret (*stringBeingComposed);
  231522. target->setHighlightedRegion (currentHighlight.withLength (stringBeingComposed->length()));
  231523. textWasInserted = true;
  231524. }
  231525. }
  231526. - (void) unmarkText
  231527. {
  231528. if (stringBeingComposed != 0)
  231529. {
  231530. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231531. if (target != 0)
  231532. {
  231533. target->insertTextAtCaret (*stringBeingComposed);
  231534. textWasInserted = true;
  231535. }
  231536. }
  231537. deleteAndZero (stringBeingComposed);
  231538. }
  231539. - (BOOL) hasMarkedText
  231540. {
  231541. return stringBeingComposed != 0;
  231542. }
  231543. - (long) conversationIdentifier
  231544. {
  231545. return (long) (pointer_sized_int) self;
  231546. }
  231547. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange
  231548. {
  231549. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231550. if (target != 0)
  231551. {
  231552. const Range<int> r ((int) theRange.location,
  231553. (int) (theRange.location + theRange.length));
  231554. return [[[NSAttributedString alloc] initWithString: juceStringToNS (target->getTextInRange (r))] autorelease];
  231555. }
  231556. return nil;
  231557. }
  231558. - (NSRange) markedRange
  231559. {
  231560. return stringBeingComposed != 0 ? NSMakeRange (0, stringBeingComposed->length())
  231561. : NSMakeRange (NSNotFound, 0);
  231562. }
  231563. - (NSRange) selectedRange
  231564. {
  231565. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231566. if (target != 0)
  231567. {
  231568. const Range<int> highlight (target->getHighlightedRegion());
  231569. if (! highlight.isEmpty())
  231570. return NSMakeRange (highlight.getStart(), highlight.getLength());
  231571. }
  231572. return NSMakeRange (NSNotFound, 0);
  231573. }
  231574. - (NSRect) firstRectForCharacterRange: (NSRange) theRange
  231575. {
  231576. (void) theRange;
  231577. JUCE_NAMESPACE::Component* const comp = dynamic_cast <JUCE_NAMESPACE::Component*> (owner->findCurrentTextInputTarget());
  231578. if (comp == 0)
  231579. return NSMakeRect (0, 0, 0, 0);
  231580. const Rectangle<int> bounds (comp->getScreenBounds());
  231581. return NSMakeRect (bounds.getX(),
  231582. [[[NSScreen screens] objectAtIndex: 0] frame].size.height - bounds.getY(),
  231583. bounds.getWidth(),
  231584. bounds.getHeight());
  231585. }
  231586. - (NSUInteger) characterIndexForPoint: (NSPoint) thePoint
  231587. {
  231588. (void) thePoint;
  231589. return NSNotFound;
  231590. }
  231591. - (NSArray*) validAttributesForMarkedText
  231592. {
  231593. return [NSArray array];
  231594. }
  231595. - (void) flagsChanged: (NSEvent*) ev
  231596. {
  231597. if (owner != 0)
  231598. owner->redirectModKeyChange (ev);
  231599. }
  231600. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  231601. - (BOOL) performKeyEquivalent: (NSEvent*) ev
  231602. {
  231603. if (owner != 0 && owner->redirectPerformKeyEquivalent (ev))
  231604. return true;
  231605. return [super performKeyEquivalent: ev];
  231606. }
  231607. #endif
  231608. - (BOOL) becomeFirstResponder
  231609. {
  231610. if (owner != 0)
  231611. owner->viewFocusGain();
  231612. return true;
  231613. }
  231614. - (BOOL) resignFirstResponder
  231615. {
  231616. if (owner != 0)
  231617. owner->viewFocusLoss();
  231618. return true;
  231619. }
  231620. - (BOOL) acceptsFirstResponder
  231621. {
  231622. return owner != 0 && owner->canBecomeKeyWindow();
  231623. }
  231624. - (NSArray*) getSupportedDragTypes
  231625. {
  231626. return [NSArray arrayWithObjects: NSFilenamesPboardType, /*NSFilesPromisePboardType, NSStringPboardType,*/ nil];
  231627. }
  231628. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender
  231629. {
  231630. return owner != 0 && owner->sendDragCallback (type, sender);
  231631. }
  231632. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender
  231633. {
  231634. if ([self sendDragCallback: 0 sender: sender])
  231635. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  231636. else
  231637. return NSDragOperationNone;
  231638. }
  231639. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender
  231640. {
  231641. if ([self sendDragCallback: 0 sender: sender])
  231642. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  231643. else
  231644. return NSDragOperationNone;
  231645. }
  231646. - (void) draggingEnded: (id <NSDraggingInfo>) sender
  231647. {
  231648. [self sendDragCallback: 1 sender: sender];
  231649. }
  231650. - (void) draggingExited: (id <NSDraggingInfo>) sender
  231651. {
  231652. [self sendDragCallback: 1 sender: sender];
  231653. }
  231654. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender
  231655. {
  231656. (void) sender;
  231657. return YES;
  231658. }
  231659. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender
  231660. {
  231661. return [self sendDragCallback: 2 sender: sender];
  231662. }
  231663. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender
  231664. {
  231665. (void) sender;
  231666. }
  231667. @end
  231668. @implementation JuceNSWindow
  231669. - (void) setOwner: (NSViewComponentPeer*) owner_
  231670. {
  231671. owner = owner_;
  231672. isZooming = false;
  231673. }
  231674. - (BOOL) canBecomeKeyWindow
  231675. {
  231676. return owner != 0 && owner->canBecomeKeyWindow();
  231677. }
  231678. - (void) becomeKeyWindow
  231679. {
  231680. [super becomeKeyWindow];
  231681. if (owner != 0)
  231682. owner->grabFocus();
  231683. }
  231684. - (BOOL) windowShouldClose: (id) window
  231685. {
  231686. (void) window;
  231687. return owner == 0 || owner->windowShouldClose();
  231688. }
  231689. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen
  231690. {
  231691. (void) screen;
  231692. if (owner != 0)
  231693. frameRect = owner->constrainRect (frameRect);
  231694. return frameRect;
  231695. }
  231696. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize
  231697. {
  231698. (void) window;
  231699. if (isZooming)
  231700. return proposedFrameSize;
  231701. NSRect frameRect = [self frame];
  231702. frameRect.origin.y -= proposedFrameSize.height - frameRect.size.height;
  231703. frameRect.size = proposedFrameSize;
  231704. if (owner != 0)
  231705. frameRect = owner->constrainRect (frameRect);
  231706. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  231707. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  231708. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  231709. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  231710. return frameRect.size;
  231711. }
  231712. - (void) zoom: (id) sender
  231713. {
  231714. isZooming = true;
  231715. [super zoom: sender];
  231716. isZooming = false;
  231717. }
  231718. - (void) windowWillMove: (NSNotification*) notification
  231719. {
  231720. (void) notification;
  231721. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  231722. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  231723. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  231724. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  231725. }
  231726. @end
  231727. BEGIN_JUCE_NAMESPACE
  231728. ModifierKeys NSViewComponentPeer::currentModifiers;
  231729. ComponentPeer* NSViewComponentPeer::currentlyFocusedPeer = 0;
  231730. Array<int> NSViewComponentPeer::keysCurrentlyDown;
  231731. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  231732. {
  231733. if (NSViewComponentPeer::keysCurrentlyDown.contains (keyCode))
  231734. return true;
  231735. if (keyCode >= 'A' && keyCode <= 'Z'
  231736. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toLowerCase ((juce_wchar) keyCode)))
  231737. return true;
  231738. if (keyCode >= 'a' && keyCode <= 'z'
  231739. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode)))
  231740. return true;
  231741. return false;
  231742. }
  231743. void NSViewComponentPeer::updateModifiers (NSEvent* e)
  231744. {
  231745. int m = 0;
  231746. if (([e modifierFlags] & NSShiftKeyMask) != 0) m |= ModifierKeys::shiftModifier;
  231747. if (([e modifierFlags] & NSControlKeyMask) != 0) m |= ModifierKeys::ctrlModifier;
  231748. if (([e modifierFlags] & NSAlternateKeyMask) != 0) m |= ModifierKeys::altModifier;
  231749. if (([e modifierFlags] & NSCommandKeyMask) != 0) m |= ModifierKeys::commandModifier;
  231750. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (m);
  231751. }
  231752. void NSViewComponentPeer::updateKeysDown (NSEvent* ev, bool isKeyDown)
  231753. {
  231754. updateModifiers (ev);
  231755. int keyCode = getKeyCodeFromEvent (ev);
  231756. if (keyCode != 0)
  231757. {
  231758. if (isKeyDown)
  231759. keysCurrentlyDown.addIfNotAlreadyThere (keyCode);
  231760. else
  231761. keysCurrentlyDown.removeValue (keyCode);
  231762. }
  231763. }
  231764. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  231765. {
  231766. return NSViewComponentPeer::currentModifiers;
  231767. }
  231768. void ModifierKeys::updateCurrentModifiers() throw()
  231769. {
  231770. currentModifiers = NSViewComponentPeer::currentModifiers;
  231771. }
  231772. NSViewComponentPeer::NSViewComponentPeer (Component* const component_,
  231773. const int windowStyleFlags,
  231774. NSView* viewToAttachTo)
  231775. : ComponentPeer (component_, windowStyleFlags),
  231776. window (0),
  231777. view (0),
  231778. isSharedWindow (viewToAttachTo != 0),
  231779. fullScreen (false),
  231780. insideDrawRect (false),
  231781. #if USE_COREGRAPHICS_RENDERING
  231782. usingCoreGraphics (true),
  231783. #else
  231784. usingCoreGraphics (false),
  231785. #endif
  231786. recursiveToFrontCall (false)
  231787. {
  231788. NSRect r = NSMakeRect (0, 0, (float) component->getWidth(),(float) component->getHeight());
  231789. view = [[JuceNSView alloc] initWithOwner: this withFrame: r];
  231790. [view setPostsFrameChangedNotifications: YES];
  231791. if (isSharedWindow)
  231792. {
  231793. window = [viewToAttachTo window];
  231794. [viewToAttachTo addSubview: view];
  231795. setVisible (component->isVisible());
  231796. }
  231797. else
  231798. {
  231799. r.origin.x = (float) component->getX();
  231800. r.origin.y = (float) component->getY();
  231801. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  231802. unsigned int style = 0;
  231803. if ((windowStyleFlags & windowHasTitleBar) == 0)
  231804. style = NSBorderlessWindowMask;
  231805. else
  231806. style = NSTitledWindowMask;
  231807. if ((windowStyleFlags & windowHasMinimiseButton) != 0)
  231808. style |= NSMiniaturizableWindowMask;
  231809. if ((windowStyleFlags & windowHasCloseButton) != 0)
  231810. style |= NSClosableWindowMask;
  231811. if ((windowStyleFlags & windowIsResizable) != 0)
  231812. style |= NSResizableWindowMask;
  231813. window = [[JuceNSWindow alloc] initWithContentRect: r
  231814. styleMask: style
  231815. backing: NSBackingStoreBuffered
  231816. defer: YES];
  231817. [((JuceNSWindow*) window) setOwner: this];
  231818. [window orderOut: nil];
  231819. [window setDelegate: (JuceNSWindow*) window];
  231820. [window setOpaque: component->isOpaque()];
  231821. [window setHasShadow: ((windowStyleFlags & windowHasDropShadow) != 0)];
  231822. if (component->isAlwaysOnTop())
  231823. [window setLevel: NSFloatingWindowLevel];
  231824. [window setContentView: view];
  231825. [window setAutodisplay: YES];
  231826. [window setAcceptsMouseMovedEvents: YES];
  231827. // We'll both retain and also release this on closing because plugin hosts can unexpectedly
  231828. // close the window for us, and also tend to get cause trouble if setReleasedWhenClosed is NO.
  231829. [window setReleasedWhenClosed: YES];
  231830. [window retain];
  231831. [window setExcludedFromWindowsMenu: (windowStyleFlags & windowIsTemporary) != 0];
  231832. [window setIgnoresMouseEvents: (windowStyleFlags & windowIgnoresMouseClicks) != 0];
  231833. }
  231834. setTitle (component->getName());
  231835. }
  231836. NSViewComponentPeer::~NSViewComponentPeer()
  231837. {
  231838. view->owner = 0;
  231839. [view removeFromSuperview];
  231840. [view release];
  231841. if (! isSharedWindow)
  231842. {
  231843. [((JuceNSWindow*) window) setOwner: 0];
  231844. [window close];
  231845. [window release];
  231846. }
  231847. }
  231848. void* NSViewComponentPeer::getNativeHandle() const
  231849. {
  231850. return view;
  231851. }
  231852. void NSViewComponentPeer::setVisible (bool shouldBeVisible)
  231853. {
  231854. if (isSharedWindow)
  231855. {
  231856. [view setHidden: ! shouldBeVisible];
  231857. }
  231858. else
  231859. {
  231860. if (shouldBeVisible)
  231861. {
  231862. [window orderFront: nil];
  231863. handleBroughtToFront();
  231864. }
  231865. else
  231866. {
  231867. [window orderOut: nil];
  231868. }
  231869. }
  231870. }
  231871. void NSViewComponentPeer::setTitle (const String& title)
  231872. {
  231873. const ScopedAutoReleasePool pool;
  231874. if (! isSharedWindow)
  231875. [window setTitle: juceStringToNS (title)];
  231876. }
  231877. void NSViewComponentPeer::setPosition (int x, int y)
  231878. {
  231879. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  231880. }
  231881. void NSViewComponentPeer::setSize (int w, int h)
  231882. {
  231883. setBounds (component->getX(), component->getY(), w, h, false);
  231884. }
  231885. void NSViewComponentPeer::setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  231886. {
  231887. fullScreen = isNowFullScreen;
  231888. NSRect r = NSMakeRect ((float) x, (float) y, (float) jmax (0, w), (float) jmax (0, h));
  231889. if (isSharedWindow)
  231890. {
  231891. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  231892. if ([view frame].size.width != r.size.width
  231893. || [view frame].size.height != r.size.height)
  231894. [view setNeedsDisplay: true];
  231895. [view setFrame: r];
  231896. }
  231897. else
  231898. {
  231899. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  231900. [window setFrame: [window frameRectForContentRect: r]
  231901. display: true];
  231902. }
  231903. }
  231904. const Rectangle<int> NSViewComponentPeer::getBounds (const bool global) const
  231905. {
  231906. NSRect r = [view frame];
  231907. if (global && [view window] != 0)
  231908. {
  231909. r = [view convertRect: r toView: nil];
  231910. NSRect wr = [[view window] frame];
  231911. r.origin.x += wr.origin.x;
  231912. r.origin.y += wr.origin.y;
  231913. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  231914. }
  231915. else
  231916. {
  231917. r.origin.y = [[view superview] frame].size.height - r.origin.y - r.size.height;
  231918. }
  231919. return Rectangle<int> (convertToRectInt (r));
  231920. }
  231921. const Rectangle<int> NSViewComponentPeer::getBounds() const
  231922. {
  231923. return getBounds (! isSharedWindow);
  231924. }
  231925. const Point<int> NSViewComponentPeer::getScreenPosition() const
  231926. {
  231927. return getBounds (true).getPosition();
  231928. }
  231929. const Point<int> NSViewComponentPeer::relativePositionToGlobal (const Point<int>& relativePosition)
  231930. {
  231931. return relativePosition + getScreenPosition();
  231932. }
  231933. const Point<int> NSViewComponentPeer::globalPositionToRelative (const Point<int>& screenPosition)
  231934. {
  231935. return screenPosition - getScreenPosition();
  231936. }
  231937. NSRect NSViewComponentPeer::constrainRect (NSRect r)
  231938. {
  231939. if (constrainer != 0)
  231940. {
  231941. NSRect current = [window frame];
  231942. current.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - current.origin.y - current.size.height;
  231943. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  231944. Rectangle<int> pos (convertToRectInt (r));
  231945. Rectangle<int> original (convertToRectInt (current));
  231946. constrainer->checkBounds (pos, original,
  231947. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  231948. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  231949. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  231950. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  231951. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  231952. r.origin.x = pos.getX();
  231953. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.size.height - pos.getY();
  231954. r.size.width = pos.getWidth();
  231955. r.size.height = pos.getHeight();
  231956. }
  231957. return r;
  231958. }
  231959. void NSViewComponentPeer::setMinimised (bool shouldBeMinimised)
  231960. {
  231961. if (! isSharedWindow)
  231962. {
  231963. if (shouldBeMinimised)
  231964. [window miniaturize: nil];
  231965. else
  231966. [window deminiaturize: nil];
  231967. }
  231968. }
  231969. bool NSViewComponentPeer::isMinimised() const
  231970. {
  231971. return window != 0 && [window isMiniaturized];
  231972. }
  231973. void NSViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  231974. {
  231975. if (! isSharedWindow)
  231976. {
  231977. Rectangle<int> r (lastNonFullscreenBounds);
  231978. setMinimised (false);
  231979. if (fullScreen != shouldBeFullScreen)
  231980. {
  231981. if (shouldBeFullScreen && (getStyleFlags() & windowHasTitleBar) != 0)
  231982. {
  231983. fullScreen = true;
  231984. [window performZoom: nil];
  231985. }
  231986. else
  231987. {
  231988. if (shouldBeFullScreen)
  231989. r = Desktop::getInstance().getMainMonitorArea();
  231990. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  231991. if (r != getComponent()->getBounds() && ! r.isEmpty())
  231992. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  231993. }
  231994. }
  231995. }
  231996. }
  231997. bool NSViewComponentPeer::isFullScreen() const
  231998. {
  231999. return fullScreen;
  232000. }
  232001. bool NSViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  232002. {
  232003. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  232004. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  232005. return false;
  232006. NSPoint p;
  232007. p.x = (float) position.getX();
  232008. p.y = (float) position.getY();
  232009. NSView* v = [view hitTest: p];
  232010. if (trueIfInAChildWindow)
  232011. return v != nil;
  232012. return v == view;
  232013. }
  232014. const BorderSize NSViewComponentPeer::getFrameSize() const
  232015. {
  232016. BorderSize b;
  232017. if (! isSharedWindow)
  232018. {
  232019. NSRect v = [view convertRect: [view frame] toView: nil];
  232020. NSRect w = [window frame];
  232021. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  232022. b.setBottom ((int) v.origin.y);
  232023. b.setLeft ((int) v.origin.x);
  232024. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  232025. }
  232026. return b;
  232027. }
  232028. bool NSViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  232029. {
  232030. if (! isSharedWindow)
  232031. {
  232032. [window setLevel: alwaysOnTop ? NSFloatingWindowLevel
  232033. : NSNormalWindowLevel];
  232034. }
  232035. return true;
  232036. }
  232037. void NSViewComponentPeer::toFront (bool makeActiveWindow)
  232038. {
  232039. if (isSharedWindow)
  232040. {
  232041. [[view superview] addSubview: view
  232042. positioned: NSWindowAbove
  232043. relativeTo: nil];
  232044. }
  232045. if (window != 0 && component->isVisible())
  232046. {
  232047. if (makeActiveWindow)
  232048. [window makeKeyAndOrderFront: nil];
  232049. else
  232050. [window orderFront: nil];
  232051. if (! recursiveToFrontCall)
  232052. {
  232053. recursiveToFrontCall = true;
  232054. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  232055. handleBroughtToFront();
  232056. recursiveToFrontCall = false;
  232057. }
  232058. }
  232059. }
  232060. void NSViewComponentPeer::toBehind (ComponentPeer* other)
  232061. {
  232062. NSViewComponentPeer* const otherPeer = dynamic_cast <NSViewComponentPeer*> (other);
  232063. jassert (otherPeer != 0); // wrong type of window?
  232064. if (otherPeer != 0)
  232065. {
  232066. if (isSharedWindow)
  232067. {
  232068. [[view superview] addSubview: view
  232069. positioned: NSWindowBelow
  232070. relativeTo: otherPeer->view];
  232071. }
  232072. else
  232073. {
  232074. [window orderWindow: NSWindowBelow
  232075. relativeTo: otherPeer->window != 0 ? [otherPeer->window windowNumber]
  232076. : nil ];
  232077. }
  232078. }
  232079. }
  232080. void NSViewComponentPeer::setIcon (const Image& /*newIcon*/)
  232081. {
  232082. // to do..
  232083. }
  232084. void NSViewComponentPeer::viewFocusGain()
  232085. {
  232086. if (currentlyFocusedPeer != this)
  232087. {
  232088. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  232089. currentlyFocusedPeer->handleFocusLoss();
  232090. currentlyFocusedPeer = this;
  232091. handleFocusGain();
  232092. }
  232093. }
  232094. void NSViewComponentPeer::viewFocusLoss()
  232095. {
  232096. if (currentlyFocusedPeer == this)
  232097. {
  232098. currentlyFocusedPeer = 0;
  232099. handleFocusLoss();
  232100. }
  232101. }
  232102. void juce_HandleProcessFocusChange()
  232103. {
  232104. NSViewComponentPeer::keysCurrentlyDown.clear();
  232105. if (NSViewComponentPeer::isValidPeer (NSViewComponentPeer::currentlyFocusedPeer))
  232106. {
  232107. if (Process::isForegroundProcess())
  232108. {
  232109. NSViewComponentPeer::currentlyFocusedPeer->handleFocusGain();
  232110. ComponentPeer::bringModalComponentToFront();
  232111. }
  232112. else
  232113. {
  232114. NSViewComponentPeer::currentlyFocusedPeer->handleFocusLoss();
  232115. // turn kiosk mode off if we lose focus..
  232116. Desktop::getInstance().setKioskModeComponent (0);
  232117. }
  232118. }
  232119. }
  232120. bool NSViewComponentPeer::isFocused() const
  232121. {
  232122. return isSharedWindow ? this == currentlyFocusedPeer
  232123. : (window != 0 && [window isKeyWindow]);
  232124. }
  232125. void NSViewComponentPeer::grabFocus()
  232126. {
  232127. if (window != 0)
  232128. {
  232129. [window makeKeyWindow];
  232130. [window makeFirstResponder: view];
  232131. viewFocusGain();
  232132. }
  232133. }
  232134. void NSViewComponentPeer::textInputRequired (const Point<int>&)
  232135. {
  232136. }
  232137. bool NSViewComponentPeer::handleKeyEvent (NSEvent* ev, bool isKeyDown)
  232138. {
  232139. String unicode (nsStringToJuce ([ev characters]));
  232140. String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  232141. int keyCode = getKeyCodeFromEvent (ev);
  232142. //DBG ("unicode: " + unicode + " " + String::toHexString ((int) unicode[0]));
  232143. //DBG ("unmodified: " + unmodified + " " + String::toHexString ((int) unmodified[0]));
  232144. if (unicode.isNotEmpty() || keyCode != 0)
  232145. {
  232146. if (isKeyDown)
  232147. {
  232148. bool used = false;
  232149. while (unicode.length() > 0)
  232150. {
  232151. juce_wchar textCharacter = unicode[0];
  232152. unicode = unicode.substring (1);
  232153. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  232154. textCharacter = 0;
  232155. used = handleKeyUpOrDown (true) || used;
  232156. used = handleKeyPress (keyCode, textCharacter) || used;
  232157. }
  232158. return used;
  232159. }
  232160. else
  232161. {
  232162. if (handleKeyUpOrDown (false))
  232163. return true;
  232164. }
  232165. }
  232166. return false;
  232167. }
  232168. bool NSViewComponentPeer::redirectKeyDown (NSEvent* ev)
  232169. {
  232170. updateKeysDown (ev, true);
  232171. bool used = handleKeyEvent (ev, true);
  232172. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  232173. {
  232174. // for command keys, the key-up event is thrown away, so simulate one..
  232175. updateKeysDown (ev, false);
  232176. used = (isValidPeer (this) && handleKeyEvent (ev, false)) || used;
  232177. }
  232178. // (If we're running modally, don't allow unused keystrokes to be passed
  232179. // along to other blocked views..)
  232180. if (Component::getCurrentlyModalComponent() != 0)
  232181. used = true;
  232182. return used;
  232183. }
  232184. bool NSViewComponentPeer::redirectKeyUp (NSEvent* ev)
  232185. {
  232186. updateKeysDown (ev, false);
  232187. return handleKeyEvent (ev, false)
  232188. || Component::getCurrentlyModalComponent() != 0;
  232189. }
  232190. void NSViewComponentPeer::redirectModKeyChange (NSEvent* ev)
  232191. {
  232192. keysCurrentlyDown.clear();
  232193. handleKeyUpOrDown (true);
  232194. updateModifiers (ev);
  232195. handleModifierKeysChange();
  232196. }
  232197. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  232198. bool NSViewComponentPeer::redirectPerformKeyEquivalent (NSEvent* ev)
  232199. {
  232200. if ([ev type] == NSKeyDown)
  232201. return redirectKeyDown (ev);
  232202. else if ([ev type] == NSKeyUp)
  232203. return redirectKeyUp (ev);
  232204. return false;
  232205. }
  232206. #endif
  232207. void NSViewComponentPeer::sendMouseEvent (NSEvent* ev)
  232208. {
  232209. updateModifiers (ev);
  232210. handleMouseEvent (0, getMousePos (ev, view), currentModifiers, getMouseTime (ev));
  232211. }
  232212. void NSViewComponentPeer::redirectMouseDown (NSEvent* ev)
  232213. {
  232214. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  232215. sendMouseEvent (ev);
  232216. }
  232217. void NSViewComponentPeer::redirectMouseUp (NSEvent* ev)
  232218. {
  232219. currentModifiers = currentModifiers.withoutFlags (getModifierForButtonNumber ([ev buttonNumber]));
  232220. sendMouseEvent (ev);
  232221. showArrowCursorIfNeeded();
  232222. }
  232223. void NSViewComponentPeer::redirectMouseDrag (NSEvent* ev)
  232224. {
  232225. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  232226. sendMouseEvent (ev);
  232227. }
  232228. void NSViewComponentPeer::redirectMouseMove (NSEvent* ev)
  232229. {
  232230. currentModifiers = currentModifiers.withoutMouseButtons();
  232231. sendMouseEvent (ev);
  232232. showArrowCursorIfNeeded();
  232233. }
  232234. void NSViewComponentPeer::redirectMouseEnter (NSEvent* ev)
  232235. {
  232236. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  232237. currentModifiers = currentModifiers.withoutMouseButtons();
  232238. sendMouseEvent (ev);
  232239. }
  232240. void NSViewComponentPeer::redirectMouseExit (NSEvent* ev)
  232241. {
  232242. currentModifiers = currentModifiers.withoutMouseButtons();
  232243. sendMouseEvent (ev);
  232244. }
  232245. void NSViewComponentPeer::redirectMouseWheel (NSEvent* ev)
  232246. {
  232247. updateModifiers (ev);
  232248. float x = 0, y = 0;
  232249. @try
  232250. {
  232251. x = [ev deviceDeltaX] * 0.5f;
  232252. y = [ev deviceDeltaY] * 0.5f;
  232253. }
  232254. @catch (...)
  232255. {}
  232256. if (x == 0 && y == 0)
  232257. {
  232258. x = [ev deltaX] * 10.0f;
  232259. y = [ev deltaY] * 10.0f;
  232260. }
  232261. handleMouseWheel (0, getMousePos (ev, view), getMouseTime (ev), x, y);
  232262. }
  232263. void NSViewComponentPeer::showArrowCursorIfNeeded()
  232264. {
  232265. MouseInputSource& mouse = Desktop::getInstance().getMainMouseSource();
  232266. if (mouse.getComponentUnderMouse() == 0
  232267. && Desktop::getInstance().findComponentAt (mouse.getScreenPosition()) == 0)
  232268. {
  232269. [[NSCursor arrowCursor] set];
  232270. }
  232271. }
  232272. BOOL NSViewComponentPeer::sendDragCallback (int type, id <NSDraggingInfo> sender)
  232273. {
  232274. NSString* bestType
  232275. = [[sender draggingPasteboard] availableTypeFromArray: [view getSupportedDragTypes]];
  232276. if (bestType == nil)
  232277. return false;
  232278. NSPoint p = [view convertPoint: [sender draggingLocation] fromView: nil];
  232279. const Point<int> pos ((int) p.x, (int) ([view frame].size.height - p.y));
  232280. StringArray files;
  232281. id list = [[sender draggingPasteboard] propertyListForType: bestType];
  232282. if (list == nil)
  232283. return false;
  232284. if ([list isKindOfClass: [NSArray class]])
  232285. {
  232286. NSArray* items = (NSArray*) list;
  232287. for (unsigned int i = 0; i < [items count]; ++i)
  232288. files.add (nsStringToJuce ((NSString*) [items objectAtIndex: i]));
  232289. }
  232290. if (files.size() == 0)
  232291. return false;
  232292. if (type == 0)
  232293. handleFileDragMove (files, pos);
  232294. else if (type == 1)
  232295. handleFileDragExit (files);
  232296. else if (type == 2)
  232297. handleFileDragDrop (files, pos);
  232298. return true;
  232299. }
  232300. bool NSViewComponentPeer::isOpaque()
  232301. {
  232302. return component == 0 || component->isOpaque();
  232303. }
  232304. void NSViewComponentPeer::drawRect (NSRect r)
  232305. {
  232306. if (r.size.width < 1.0f || r.size.height < 1.0f)
  232307. return;
  232308. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  232309. if (! component->isOpaque())
  232310. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  232311. #if USE_COREGRAPHICS_RENDERING
  232312. if (usingCoreGraphics)
  232313. {
  232314. CoreGraphicsContext context (cg, (float) [view frame].size.height);
  232315. insideDrawRect = true;
  232316. handlePaint (context);
  232317. insideDrawRect = false;
  232318. }
  232319. else
  232320. #endif
  232321. {
  232322. Image temp (getComponent()->isOpaque() ? Image::RGB : Image::ARGB,
  232323. (int) (r.size.width + 0.5f),
  232324. (int) (r.size.height + 0.5f),
  232325. ! getComponent()->isOpaque());
  232326. const int xOffset = -roundToInt (r.origin.x);
  232327. const int yOffset = -roundToInt ([view frame].size.height - (r.origin.y + r.size.height));
  232328. const NSRect* rects = 0;
  232329. NSInteger numRects = 0;
  232330. [view getRectsBeingDrawn: &rects count: &numRects];
  232331. const Rectangle<int> clipBounds (temp.getBounds());
  232332. RectangleList clip;
  232333. for (int i = 0; i < numRects; ++i)
  232334. {
  232335. clip.addWithoutMerging (clipBounds.getIntersection (Rectangle<int> (roundToInt (rects[i].origin.x) + xOffset,
  232336. roundToInt ([view frame].size.height - (rects[i].origin.y + rects[i].size.height)) + yOffset,
  232337. roundToInt (rects[i].size.width),
  232338. roundToInt (rects[i].size.height))));
  232339. }
  232340. if (! clip.isEmpty())
  232341. {
  232342. LowLevelGraphicsSoftwareRenderer context (temp, xOffset, yOffset, clip);
  232343. insideDrawRect = true;
  232344. handlePaint (context);
  232345. insideDrawRect = false;
  232346. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  232347. CGImageRef image = CoreGraphicsImage::createImage (temp, false, colourSpace);
  232348. CGColorSpaceRelease (colourSpace);
  232349. CGContextDrawImage (cg, CGRectMake (r.origin.x, r.origin.y, temp.getWidth(), temp.getHeight()), image);
  232350. CGImageRelease (image);
  232351. }
  232352. }
  232353. }
  232354. const StringArray NSViewComponentPeer::getAvailableRenderingEngines()
  232355. {
  232356. StringArray s (ComponentPeer::getAvailableRenderingEngines());
  232357. #if USE_COREGRAPHICS_RENDERING
  232358. s.add ("CoreGraphics Renderer");
  232359. #endif
  232360. return s;
  232361. }
  232362. int NSViewComponentPeer::getCurrentRenderingEngine() throw()
  232363. {
  232364. return usingCoreGraphics ? 1 : 0;
  232365. }
  232366. void NSViewComponentPeer::setCurrentRenderingEngine (int index)
  232367. {
  232368. #if USE_COREGRAPHICS_RENDERING
  232369. if (usingCoreGraphics != (index > 0))
  232370. {
  232371. usingCoreGraphics = index > 0;
  232372. [view setNeedsDisplay: true];
  232373. }
  232374. #endif
  232375. }
  232376. bool NSViewComponentPeer::canBecomeKeyWindow()
  232377. {
  232378. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  232379. }
  232380. bool NSViewComponentPeer::windowShouldClose()
  232381. {
  232382. if (! isValidPeer (this))
  232383. return YES;
  232384. handleUserClosingWindow();
  232385. return NO;
  232386. }
  232387. void NSViewComponentPeer::redirectMovedOrResized()
  232388. {
  232389. handleMovedOrResized();
  232390. }
  232391. void NSViewComponentPeer::viewMovedToWindow()
  232392. {
  232393. if (isSharedWindow)
  232394. window = [view window];
  232395. }
  232396. void Desktop::createMouseInputSources()
  232397. {
  232398. mouseSources.add (new MouseInputSource (0, true));
  232399. }
  232400. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  232401. {
  232402. // Very annoyingly, this function has to use the old SetSystemUIMode function,
  232403. // which is in Carbon.framework. But, because there's no Cocoa equivalent, it
  232404. // is apparently still available in 64-bit apps..
  232405. if (enableOrDisable)
  232406. {
  232407. SetSystemUIMode (kUIModeAllSuppressed, allowMenusAndBars ? kUIOptionAutoShowMenuBar : 0);
  232408. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  232409. }
  232410. else
  232411. {
  232412. SetSystemUIMode (kUIModeNormal, 0);
  232413. }
  232414. }
  232415. class AsyncRepaintMessage : public CallbackMessage
  232416. {
  232417. public:
  232418. NSViewComponentPeer* const peer;
  232419. const Rectangle<int> rect;
  232420. AsyncRepaintMessage (NSViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  232421. : peer (peer_), rect (rect_)
  232422. {
  232423. }
  232424. void messageCallback()
  232425. {
  232426. if (ComponentPeer::isValidPeer (peer))
  232427. peer->repaint (rect);
  232428. }
  232429. };
  232430. void NSViewComponentPeer::repaint (const Rectangle<int>& area)
  232431. {
  232432. if (insideDrawRect)
  232433. {
  232434. (new AsyncRepaintMessage (this, area))->post();
  232435. }
  232436. else
  232437. {
  232438. [view setNeedsDisplayInRect: NSMakeRect ((float) area.getX(), [view frame].size.height - (float) area.getBottom(),
  232439. (float) area.getWidth(), (float) area.getHeight())];
  232440. }
  232441. }
  232442. void NSViewComponentPeer::performAnyPendingRepaintsNow()
  232443. {
  232444. [view displayIfNeeded];
  232445. }
  232446. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  232447. {
  232448. return new NSViewComponentPeer (this, styleFlags, (NSView*) windowToAttachTo);
  232449. }
  232450. const Image juce_createIconForFile (const File& file)
  232451. {
  232452. const ScopedAutoReleasePool pool;
  232453. NSImage* image = [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (file.getFullPathName())];
  232454. CoreGraphicsImage* result = new CoreGraphicsImage (Image::ARGB, (int) [image size].width, (int) [image size].height, true);
  232455. [NSGraphicsContext saveGraphicsState];
  232456. [NSGraphicsContext setCurrentContext: [NSGraphicsContext graphicsContextWithGraphicsPort: result->context flipped: false]];
  232457. [image drawAtPoint: NSMakePoint (0, 0)
  232458. fromRect: NSMakeRect (0, 0, [image size].width, [image size].height)
  232459. operation: NSCompositeSourceOver fraction: 1.0f];
  232460. [[NSGraphicsContext currentContext] flushGraphics];
  232461. [NSGraphicsContext restoreGraphicsState];
  232462. return Image (result);
  232463. }
  232464. const int KeyPress::spaceKey = ' ';
  232465. const int KeyPress::returnKey = 0x0d;
  232466. const int KeyPress::escapeKey = 0x1b;
  232467. const int KeyPress::backspaceKey = 0x7f;
  232468. const int KeyPress::leftKey = NSLeftArrowFunctionKey;
  232469. const int KeyPress::rightKey = NSRightArrowFunctionKey;
  232470. const int KeyPress::upKey = NSUpArrowFunctionKey;
  232471. const int KeyPress::downKey = NSDownArrowFunctionKey;
  232472. const int KeyPress::pageUpKey = NSPageUpFunctionKey;
  232473. const int KeyPress::pageDownKey = NSPageDownFunctionKey;
  232474. const int KeyPress::endKey = NSEndFunctionKey;
  232475. const int KeyPress::homeKey = NSHomeFunctionKey;
  232476. const int KeyPress::deleteKey = NSDeleteFunctionKey;
  232477. const int KeyPress::insertKey = -1;
  232478. const int KeyPress::tabKey = 9;
  232479. const int KeyPress::F1Key = NSF1FunctionKey;
  232480. const int KeyPress::F2Key = NSF2FunctionKey;
  232481. const int KeyPress::F3Key = NSF3FunctionKey;
  232482. const int KeyPress::F4Key = NSF4FunctionKey;
  232483. const int KeyPress::F5Key = NSF5FunctionKey;
  232484. const int KeyPress::F6Key = NSF6FunctionKey;
  232485. const int KeyPress::F7Key = NSF7FunctionKey;
  232486. const int KeyPress::F8Key = NSF8FunctionKey;
  232487. const int KeyPress::F9Key = NSF9FunctionKey;
  232488. const int KeyPress::F10Key = NSF10FunctionKey;
  232489. const int KeyPress::F11Key = NSF1FunctionKey;
  232490. const int KeyPress::F12Key = NSF12FunctionKey;
  232491. const int KeyPress::F13Key = NSF13FunctionKey;
  232492. const int KeyPress::F14Key = NSF14FunctionKey;
  232493. const int KeyPress::F15Key = NSF15FunctionKey;
  232494. const int KeyPress::F16Key = NSF16FunctionKey;
  232495. const int KeyPress::numberPad0 = 0x30020;
  232496. const int KeyPress::numberPad1 = 0x30021;
  232497. const int KeyPress::numberPad2 = 0x30022;
  232498. const int KeyPress::numberPad3 = 0x30023;
  232499. const int KeyPress::numberPad4 = 0x30024;
  232500. const int KeyPress::numberPad5 = 0x30025;
  232501. const int KeyPress::numberPad6 = 0x30026;
  232502. const int KeyPress::numberPad7 = 0x30027;
  232503. const int KeyPress::numberPad8 = 0x30028;
  232504. const int KeyPress::numberPad9 = 0x30029;
  232505. const int KeyPress::numberPadAdd = 0x3002a;
  232506. const int KeyPress::numberPadSubtract = 0x3002b;
  232507. const int KeyPress::numberPadMultiply = 0x3002c;
  232508. const int KeyPress::numberPadDivide = 0x3002d;
  232509. const int KeyPress::numberPadSeparator = 0x3002e;
  232510. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  232511. const int KeyPress::numberPadEquals = 0x30030;
  232512. const int KeyPress::numberPadDelete = 0x30031;
  232513. const int KeyPress::playKey = 0x30000;
  232514. const int KeyPress::stopKey = 0x30001;
  232515. const int KeyPress::fastForwardKey = 0x30002;
  232516. const int KeyPress::rewindKey = 0x30003;
  232517. #endif
  232518. /*** End of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  232519. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  232520. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232521. // compiled on its own).
  232522. #if JUCE_INCLUDED_FILE
  232523. #if JUCE_MAC
  232524. namespace MouseCursorHelpers
  232525. {
  232526. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  232527. {
  232528. NSImage* im = CoreGraphicsImage::createNSImage (image);
  232529. NSCursor* c = [[NSCursor alloc] initWithImage: im
  232530. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  232531. [im release];
  232532. return c;
  232533. }
  232534. static void* fromWebKitFile (const char* filename, float hx, float hy)
  232535. {
  232536. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  232537. BufferedInputStream buf (&fileStream, 4096, false);
  232538. PNGImageFormat pngFormat;
  232539. Image im (pngFormat.decodeImage (buf));
  232540. if (im.isValid())
  232541. return createFromImage (im, hx * im.getWidth(), hy * im.getHeight());
  232542. jassertfalse;
  232543. return 0;
  232544. }
  232545. }
  232546. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  232547. {
  232548. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  232549. }
  232550. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  232551. {
  232552. const ScopedAutoReleasePool pool;
  232553. NSCursor* c = 0;
  232554. switch (type)
  232555. {
  232556. case NormalCursor: c = [NSCursor arrowCursor]; break;
  232557. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  232558. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  232559. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  232560. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  232561. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  232562. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  232563. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  232564. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  232565. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  232566. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  232567. case UpDownResizeCursor:
  232568. case TopEdgeResizeCursor:
  232569. case BottomEdgeResizeCursor:
  232570. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  232571. case TopLeftCornerResizeCursor:
  232572. case BottomRightCornerResizeCursor:
  232573. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  232574. case TopRightCornerResizeCursor:
  232575. case BottomLeftCornerResizeCursor:
  232576. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  232577. case UpDownLeftRightResizeCursor:
  232578. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  232579. default:
  232580. jassertfalse;
  232581. break;
  232582. }
  232583. [c retain];
  232584. return c;
  232585. }
  232586. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  232587. {
  232588. [((NSCursor*) cursorHandle) release];
  232589. }
  232590. void MouseCursor::showInAllWindows() const
  232591. {
  232592. showInWindow (0);
  232593. }
  232594. void MouseCursor::showInWindow (ComponentPeer*) const
  232595. {
  232596. [((NSCursor*) getHandle()) set];
  232597. }
  232598. #else
  232599. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  232600. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  232601. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  232602. void MouseCursor::showInAllWindows() const {}
  232603. void MouseCursor::showInWindow (ComponentPeer*) const {}
  232604. #endif
  232605. #endif
  232606. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  232607. /*** Start of inlined file: juce_mac_NSViewComponent.mm ***/
  232608. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232609. // compiled on its own).
  232610. #if JUCE_INCLUDED_FILE
  232611. class NSViewComponentInternal : public ComponentMovementWatcher
  232612. {
  232613. Component* const owner;
  232614. NSViewComponentPeer* currentPeer;
  232615. bool wasShowing;
  232616. public:
  232617. NSView* const view;
  232618. NSViewComponentInternal (NSView* const view_, Component* const owner_)
  232619. : ComponentMovementWatcher (owner_),
  232620. owner (owner_),
  232621. currentPeer (0),
  232622. wasShowing (false),
  232623. view (view_)
  232624. {
  232625. [view_ retain];
  232626. if (owner_->isShowing())
  232627. componentPeerChanged();
  232628. }
  232629. ~NSViewComponentInternal()
  232630. {
  232631. [view removeFromSuperview];
  232632. [view release];
  232633. }
  232634. void componentMovedOrResized (Component& comp, bool wasMoved, bool wasResized)
  232635. {
  232636. ComponentMovementWatcher::componentMovedOrResized (comp, wasMoved, wasResized);
  232637. // The ComponentMovementWatcher version of this method avoids calling
  232638. // us when the top-level comp is resized, but for an NSView we need to know this
  232639. // because with inverted co-ords, we need to update the position even if the
  232640. // top-left pos hasn't changed
  232641. if (comp.isOnDesktop() && wasResized)
  232642. componentMovedOrResized (wasMoved, wasResized);
  232643. }
  232644. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  232645. {
  232646. Component* const topComp = owner->getTopLevelComponent();
  232647. if (topComp->getPeer() != 0)
  232648. {
  232649. const Point<int> pos (owner->relativePositionToOtherComponent (topComp, Point<int>()));
  232650. NSRect r = NSMakeRect ((float) pos.getX(), (float) pos.getY(), (float) owner->getWidth(), (float) owner->getHeight());
  232651. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  232652. [view setFrame: r];
  232653. }
  232654. }
  232655. void componentPeerChanged()
  232656. {
  232657. NSViewComponentPeer* const peer = dynamic_cast <NSViewComponentPeer*> (owner->getPeer());
  232658. if (currentPeer != peer)
  232659. {
  232660. if ([view superview] != nil)
  232661. [view removeFromSuperview]; // Must be careful not to call this unless it's required - e.g. some Apple AU views
  232662. // override the call and use it as a sign that they're being deleted, which breaks everything..
  232663. currentPeer = peer;
  232664. if (peer != 0)
  232665. {
  232666. [peer->view addSubview: view];
  232667. componentMovedOrResized (false, false);
  232668. }
  232669. }
  232670. [view setHidden: ! owner->isShowing()];
  232671. }
  232672. void componentVisibilityChanged (Component&)
  232673. {
  232674. componentPeerChanged();
  232675. }
  232676. const Rectangle<int> getViewBounds() const
  232677. {
  232678. NSRect r = [view frame];
  232679. return Rectangle<int> (0, 0, (int) r.size.width, (int) r.size.height);
  232680. }
  232681. juce_UseDebuggingNewOperator
  232682. private:
  232683. NSViewComponentInternal (const NSViewComponentInternal&);
  232684. NSViewComponentInternal& operator= (const NSViewComponentInternal&);
  232685. };
  232686. NSViewComponent::NSViewComponent()
  232687. {
  232688. }
  232689. NSViewComponent::~NSViewComponent()
  232690. {
  232691. }
  232692. void NSViewComponent::setView (void* view)
  232693. {
  232694. if (view != getView())
  232695. {
  232696. if (view != 0)
  232697. info = new NSViewComponentInternal ((NSView*) view, this);
  232698. else
  232699. info = 0;
  232700. }
  232701. }
  232702. void* NSViewComponent::getView() const
  232703. {
  232704. return info == 0 ? 0 : info->view;
  232705. }
  232706. void NSViewComponent::resizeToFitView()
  232707. {
  232708. if (info != 0)
  232709. setBounds (info->getViewBounds());
  232710. }
  232711. void NSViewComponent::paint (Graphics&)
  232712. {
  232713. }
  232714. #endif
  232715. /*** End of inlined file: juce_mac_NSViewComponent.mm ***/
  232716. /*** Start of inlined file: juce_mac_AppleRemote.mm ***/
  232717. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232718. // compiled on its own).
  232719. #if JUCE_INCLUDED_FILE
  232720. AppleRemoteDevice::AppleRemoteDevice()
  232721. : device (0),
  232722. queue (0),
  232723. remoteId (0)
  232724. {
  232725. }
  232726. AppleRemoteDevice::~AppleRemoteDevice()
  232727. {
  232728. stop();
  232729. }
  232730. static io_object_t getAppleRemoteDevice()
  232731. {
  232732. CFMutableDictionaryRef dict = IOServiceMatching ("AppleIRController");
  232733. io_iterator_t iter = 0;
  232734. io_object_t iod = 0;
  232735. if (IOServiceGetMatchingServices (kIOMasterPortDefault, dict, &iter) == kIOReturnSuccess
  232736. && iter != 0)
  232737. {
  232738. iod = IOIteratorNext (iter);
  232739. }
  232740. IOObjectRelease (iter);
  232741. return iod;
  232742. }
  232743. static bool createAppleRemoteInterface (io_object_t iod, void** device)
  232744. {
  232745. jassert (*device == 0);
  232746. io_name_t classname;
  232747. if (IOObjectGetClass (iod, classname) == kIOReturnSuccess)
  232748. {
  232749. IOCFPlugInInterface** cfPlugInInterface = 0;
  232750. SInt32 score = 0;
  232751. if (IOCreatePlugInInterfaceForService (iod,
  232752. kIOHIDDeviceUserClientTypeID,
  232753. kIOCFPlugInInterfaceID,
  232754. &cfPlugInInterface,
  232755. &score) == kIOReturnSuccess)
  232756. {
  232757. HRESULT hr = (*cfPlugInInterface)->QueryInterface (cfPlugInInterface,
  232758. CFUUIDGetUUIDBytes (kIOHIDDeviceInterfaceID),
  232759. device);
  232760. (void) hr;
  232761. (*cfPlugInInterface)->Release (cfPlugInInterface);
  232762. }
  232763. }
  232764. return *device != 0;
  232765. }
  232766. bool AppleRemoteDevice::start (const bool inExclusiveMode)
  232767. {
  232768. if (queue != 0)
  232769. return true;
  232770. stop();
  232771. bool result = false;
  232772. io_object_t iod = getAppleRemoteDevice();
  232773. if (iod != 0)
  232774. {
  232775. if (createAppleRemoteInterface (iod, &device) && open (inExclusiveMode))
  232776. result = true;
  232777. else
  232778. stop();
  232779. IOObjectRelease (iod);
  232780. }
  232781. return result;
  232782. }
  232783. void AppleRemoteDevice::stop()
  232784. {
  232785. if (queue != 0)
  232786. {
  232787. (*(IOHIDQueueInterface**) queue)->stop ((IOHIDQueueInterface**) queue);
  232788. (*(IOHIDQueueInterface**) queue)->dispose ((IOHIDQueueInterface**) queue);
  232789. (*(IOHIDQueueInterface**) queue)->Release ((IOHIDQueueInterface**) queue);
  232790. queue = 0;
  232791. }
  232792. if (device != 0)
  232793. {
  232794. (*(IOHIDDeviceInterface**) device)->close ((IOHIDDeviceInterface**) device);
  232795. (*(IOHIDDeviceInterface**) device)->Release ((IOHIDDeviceInterface**) device);
  232796. device = 0;
  232797. }
  232798. }
  232799. bool AppleRemoteDevice::isActive() const
  232800. {
  232801. return queue != 0;
  232802. }
  232803. static void appleRemoteQueueCallback (void* const target, const IOReturn result, void*, void*)
  232804. {
  232805. if (result == kIOReturnSuccess)
  232806. ((AppleRemoteDevice*) target)->handleCallbackInternal();
  232807. }
  232808. bool AppleRemoteDevice::open (const bool openInExclusiveMode)
  232809. {
  232810. Array <int> cookies;
  232811. CFArrayRef elements;
  232812. IOHIDDeviceInterface122** const device122 = (IOHIDDeviceInterface122**) device;
  232813. if ((*device122)->copyMatchingElements (device122, 0, &elements) != kIOReturnSuccess)
  232814. return false;
  232815. for (int i = 0; i < CFArrayGetCount (elements); ++i)
  232816. {
  232817. CFDictionaryRef element = (CFDictionaryRef) CFArrayGetValueAtIndex (elements, i);
  232818. // get the cookie
  232819. CFTypeRef object = CFDictionaryGetValue (element, CFSTR (kIOHIDElementCookieKey));
  232820. if (object == 0 || CFGetTypeID (object) != CFNumberGetTypeID())
  232821. continue;
  232822. long number;
  232823. if (! CFNumberGetValue ((CFNumberRef) object, kCFNumberLongType, &number))
  232824. continue;
  232825. cookies.add ((int) number);
  232826. }
  232827. CFRelease (elements);
  232828. if ((*(IOHIDDeviceInterface**) device)
  232829. ->open ((IOHIDDeviceInterface**) device,
  232830. openInExclusiveMode ? kIOHIDOptionsTypeSeizeDevice
  232831. : kIOHIDOptionsTypeNone) == KERN_SUCCESS)
  232832. {
  232833. queue = (*(IOHIDDeviceInterface**) device)->allocQueue ((IOHIDDeviceInterface**) device);
  232834. if (queue != 0)
  232835. {
  232836. (*(IOHIDQueueInterface**) queue)->create ((IOHIDQueueInterface**) queue, 0, 12);
  232837. for (int i = 0; i < cookies.size(); ++i)
  232838. {
  232839. IOHIDElementCookie cookie = (IOHIDElementCookie) cookies.getUnchecked(i);
  232840. (*(IOHIDQueueInterface**) queue)->addElement ((IOHIDQueueInterface**) queue, cookie, 0);
  232841. }
  232842. CFRunLoopSourceRef eventSource;
  232843. if ((*(IOHIDQueueInterface**) queue)
  232844. ->createAsyncEventSource ((IOHIDQueueInterface**) queue, &eventSource) == KERN_SUCCESS)
  232845. {
  232846. if ((*(IOHIDQueueInterface**) queue)->setEventCallout ((IOHIDQueueInterface**) queue,
  232847. appleRemoteQueueCallback, this, 0) == KERN_SUCCESS)
  232848. {
  232849. CFRunLoopAddSource (CFRunLoopGetCurrent(), eventSource, kCFRunLoopDefaultMode);
  232850. (*(IOHIDQueueInterface**) queue)->start ((IOHIDQueueInterface**) queue);
  232851. return true;
  232852. }
  232853. }
  232854. }
  232855. }
  232856. return false;
  232857. }
  232858. void AppleRemoteDevice::handleCallbackInternal()
  232859. {
  232860. int totalValues = 0;
  232861. AbsoluteTime nullTime = { 0, 0 };
  232862. char cookies [12];
  232863. int numCookies = 0;
  232864. while (numCookies < numElementsInArray (cookies))
  232865. {
  232866. IOHIDEventStruct e;
  232867. if ((*(IOHIDQueueInterface**) queue)->getNextEvent ((IOHIDQueueInterface**) queue, &e, nullTime, 0) != kIOReturnSuccess)
  232868. break;
  232869. if ((int) e.elementCookie == 19)
  232870. {
  232871. remoteId = e.value;
  232872. buttonPressed (switched, false);
  232873. }
  232874. else
  232875. {
  232876. totalValues += e.value;
  232877. cookies [numCookies++] = (char) (pointer_sized_int) e.elementCookie;
  232878. }
  232879. }
  232880. cookies [numCookies++] = 0;
  232881. //DBG (String::toHexString ((uint8*) cookies, numCookies, 1) + " " + String (totalValues));
  232882. static const char buttonPatterns[] =
  232883. {
  232884. 0x1f, 0x14, 0x12, 0x1f, 0x14, 0x12, 0,
  232885. 0x1f, 0x15, 0x12, 0x1f, 0x15, 0x12, 0,
  232886. 0x1f, 0x1d, 0x1c, 0x12, 0,
  232887. 0x1f, 0x1e, 0x1c, 0x12, 0,
  232888. 0x1f, 0x16, 0x12, 0x1f, 0x16, 0x12, 0,
  232889. 0x1f, 0x17, 0x12, 0x1f, 0x17, 0x12, 0,
  232890. 0x1f, 0x12, 0x04, 0x02, 0,
  232891. 0x1f, 0x12, 0x03, 0x02, 0,
  232892. 0x1f, 0x12, 0x1f, 0x12, 0,
  232893. 0x23, 0x1f, 0x12, 0x23, 0x1f, 0x12, 0,
  232894. 19, 0
  232895. };
  232896. int buttonNum = (int) menuButton;
  232897. int i = 0;
  232898. while (i < numElementsInArray (buttonPatterns))
  232899. {
  232900. if (strcmp (cookies, buttonPatterns + i) == 0)
  232901. {
  232902. buttonPressed ((ButtonType) buttonNum, totalValues > 0);
  232903. break;
  232904. }
  232905. i += (int) strlen (buttonPatterns + i) + 1;
  232906. ++buttonNum;
  232907. }
  232908. }
  232909. #endif
  232910. /*** End of inlined file: juce_mac_AppleRemote.mm ***/
  232911. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  232912. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232913. // compiled on its own).
  232914. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  232915. #if JUCE_MAC
  232916. END_JUCE_NAMESPACE
  232917. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  232918. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  232919. {
  232920. CriticalSection* contextLock;
  232921. bool needsUpdate;
  232922. }
  232923. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  232924. - (bool) makeActive;
  232925. - (void) makeInactive;
  232926. - (void) reshape;
  232927. @end
  232928. @implementation ThreadSafeNSOpenGLView
  232929. - (id) initWithFrame: (NSRect) frameRect
  232930. pixelFormat: (NSOpenGLPixelFormat*) format
  232931. {
  232932. contextLock = new CriticalSection();
  232933. self = [super initWithFrame: frameRect pixelFormat: format];
  232934. if (self != nil)
  232935. [[NSNotificationCenter defaultCenter] addObserver: self
  232936. selector: @selector (_surfaceNeedsUpdate:)
  232937. name: NSViewGlobalFrameDidChangeNotification
  232938. object: self];
  232939. return self;
  232940. }
  232941. - (void) dealloc
  232942. {
  232943. [[NSNotificationCenter defaultCenter] removeObserver: self];
  232944. delete contextLock;
  232945. [super dealloc];
  232946. }
  232947. - (bool) makeActive
  232948. {
  232949. const ScopedLock sl (*contextLock);
  232950. if ([self openGLContext] == 0)
  232951. return false;
  232952. [[self openGLContext] makeCurrentContext];
  232953. if (needsUpdate)
  232954. {
  232955. [super update];
  232956. needsUpdate = false;
  232957. }
  232958. return true;
  232959. }
  232960. - (void) makeInactive
  232961. {
  232962. const ScopedLock sl (*contextLock);
  232963. [NSOpenGLContext clearCurrentContext];
  232964. }
  232965. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  232966. {
  232967. const ScopedLock sl (*contextLock);
  232968. needsUpdate = true;
  232969. }
  232970. - (void) update
  232971. {
  232972. const ScopedLock sl (*contextLock);
  232973. needsUpdate = true;
  232974. }
  232975. - (void) reshape
  232976. {
  232977. const ScopedLock sl (*contextLock);
  232978. needsUpdate = true;
  232979. }
  232980. @end
  232981. BEGIN_JUCE_NAMESPACE
  232982. class WindowedGLContext : public OpenGLContext
  232983. {
  232984. public:
  232985. WindowedGLContext (Component* const component,
  232986. const OpenGLPixelFormat& pixelFormat_,
  232987. NSOpenGLContext* sharedContext)
  232988. : renderContext (0),
  232989. pixelFormat (pixelFormat_)
  232990. {
  232991. jassert (component != 0);
  232992. NSOpenGLPixelFormatAttribute attribs [64];
  232993. int n = 0;
  232994. attribs[n++] = NSOpenGLPFADoubleBuffer;
  232995. attribs[n++] = NSOpenGLPFAAccelerated;
  232996. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  232997. attribs[n++] = NSOpenGLPFAColorSize;
  232998. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  232999. pixelFormat.greenBits,
  233000. pixelFormat.blueBits);
  233001. attribs[n++] = NSOpenGLPFAAlphaSize;
  233002. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  233003. attribs[n++] = NSOpenGLPFADepthSize;
  233004. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  233005. attribs[n++] = NSOpenGLPFAStencilSize;
  233006. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  233007. attribs[n++] = NSOpenGLPFAAccumSize;
  233008. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  233009. pixelFormat.accumulationBufferGreenBits,
  233010. pixelFormat.accumulationBufferBlueBits,
  233011. pixelFormat.accumulationBufferAlphaBits);
  233012. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  233013. attribs[n++] = NSOpenGLPFASampleBuffers;
  233014. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  233015. attribs[n++] = NSOpenGLPFAClosestPolicy;
  233016. attribs[n++] = NSOpenGLPFANoRecovery;
  233017. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  233018. NSOpenGLPixelFormat* format
  233019. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  233020. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  233021. pixelFormat: format];
  233022. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  233023. shareContext: sharedContext] autorelease];
  233024. const GLint swapInterval = 1;
  233025. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  233026. [view setOpenGLContext: renderContext];
  233027. [format release];
  233028. viewHolder = new NSViewComponentInternal (view, component);
  233029. }
  233030. ~WindowedGLContext()
  233031. {
  233032. deleteContext();
  233033. viewHolder = 0;
  233034. }
  233035. void deleteContext()
  233036. {
  233037. makeInactive();
  233038. [renderContext clearDrawable];
  233039. [renderContext setView: nil];
  233040. [view setOpenGLContext: nil];
  233041. renderContext = nil;
  233042. }
  233043. bool makeActive() const throw()
  233044. {
  233045. jassert (renderContext != 0);
  233046. if ([renderContext view] != view)
  233047. [renderContext setView: view];
  233048. [view makeActive];
  233049. return isActive();
  233050. }
  233051. bool makeInactive() const throw()
  233052. {
  233053. [view makeInactive];
  233054. return true;
  233055. }
  233056. bool isActive() const throw()
  233057. {
  233058. return [NSOpenGLContext currentContext] == renderContext;
  233059. }
  233060. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  233061. void* getRawContext() const throw() { return renderContext; }
  233062. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  233063. {
  233064. }
  233065. void swapBuffers()
  233066. {
  233067. [renderContext flushBuffer];
  233068. }
  233069. bool setSwapInterval (const int numFramesPerSwap)
  233070. {
  233071. [renderContext setValues: (const GLint*) &numFramesPerSwap
  233072. forParameter: NSOpenGLCPSwapInterval];
  233073. return true;
  233074. }
  233075. int getSwapInterval() const
  233076. {
  233077. GLint numFrames = 0;
  233078. [renderContext getValues: &numFrames
  233079. forParameter: NSOpenGLCPSwapInterval];
  233080. return numFrames;
  233081. }
  233082. void repaint()
  233083. {
  233084. // we need to invalidate the juce view that holds this gl view, to make it
  233085. // cause a repaint callback
  233086. NSView* v = (NSView*) viewHolder->view;
  233087. NSRect r = [v frame];
  233088. // bit of a bodge here.. if we only invalidate the area of the gl component,
  233089. // it's completely covered by the NSOpenGLView, so the OS throws away the
  233090. // repaint message, thus never causing our paint() callback, and never repainting
  233091. // the comp. So invalidating just a little bit around the edge helps..
  233092. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  233093. }
  233094. void* getNativeWindowHandle() const { return viewHolder->view; }
  233095. juce_UseDebuggingNewOperator
  233096. NSOpenGLContext* renderContext;
  233097. ThreadSafeNSOpenGLView* view;
  233098. private:
  233099. OpenGLPixelFormat pixelFormat;
  233100. ScopedPointer <NSViewComponentInternal> viewHolder;
  233101. WindowedGLContext (const WindowedGLContext&);
  233102. WindowedGLContext& operator= (const WindowedGLContext&);
  233103. };
  233104. OpenGLContext* OpenGLComponent::createContext()
  233105. {
  233106. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  233107. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  233108. return (c->renderContext != 0) ? c.release() : 0;
  233109. }
  233110. void* OpenGLComponent::getNativeWindowHandle() const
  233111. {
  233112. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  233113. : 0;
  233114. }
  233115. void juce_glViewport (const int w, const int h)
  233116. {
  233117. glViewport (0, 0, w, h);
  233118. }
  233119. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  233120. OwnedArray <OpenGLPixelFormat>& results)
  233121. {
  233122. /* GLint attribs [64];
  233123. int n = 0;
  233124. attribs[n++] = AGL_RGBA;
  233125. attribs[n++] = AGL_DOUBLEBUFFER;
  233126. attribs[n++] = AGL_ACCELERATED;
  233127. attribs[n++] = AGL_NO_RECOVERY;
  233128. attribs[n++] = AGL_NONE;
  233129. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  233130. while (p != 0)
  233131. {
  233132. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  233133. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  233134. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  233135. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  233136. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  233137. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  233138. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  233139. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  233140. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  233141. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  233142. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  233143. results.add (pf);
  233144. p = aglNextPixelFormat (p);
  233145. }*/
  233146. //jassertfalse // can't see how you do this in cocoa!
  233147. }
  233148. #else
  233149. END_JUCE_NAMESPACE
  233150. @interface JuceGLView : UIView
  233151. {
  233152. }
  233153. + (Class) layerClass;
  233154. @end
  233155. @implementation JuceGLView
  233156. + (Class) layerClass
  233157. {
  233158. return [CAEAGLLayer class];
  233159. }
  233160. @end
  233161. BEGIN_JUCE_NAMESPACE
  233162. class GLESContext : public OpenGLContext
  233163. {
  233164. public:
  233165. GLESContext (UIViewComponentPeer* peer,
  233166. Component* const component_,
  233167. const OpenGLPixelFormat& pixelFormat_,
  233168. const GLESContext* const sharedContext,
  233169. NSUInteger apiType)
  233170. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  233171. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  233172. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  233173. {
  233174. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  233175. view.opaque = YES;
  233176. view.hidden = NO;
  233177. view.backgroundColor = [UIColor blackColor];
  233178. view.userInteractionEnabled = NO;
  233179. glLayer = (CAEAGLLayer*) [view layer];
  233180. [peer->view addSubview: view];
  233181. if (sharedContext != 0)
  233182. context = [[EAGLContext alloc] initWithAPI: apiType
  233183. sharegroup: [sharedContext->context sharegroup]];
  233184. else
  233185. context = [[EAGLContext alloc] initWithAPI: apiType];
  233186. createGLBuffers();
  233187. }
  233188. ~GLESContext()
  233189. {
  233190. deleteContext();
  233191. [view removeFromSuperview];
  233192. [view release];
  233193. freeGLBuffers();
  233194. }
  233195. void deleteContext()
  233196. {
  233197. makeInactive();
  233198. [context release];
  233199. context = nil;
  233200. }
  233201. bool makeActive() const throw()
  233202. {
  233203. jassert (context != 0);
  233204. [EAGLContext setCurrentContext: context];
  233205. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  233206. return true;
  233207. }
  233208. void swapBuffers()
  233209. {
  233210. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  233211. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  233212. }
  233213. bool makeInactive() const throw()
  233214. {
  233215. return [EAGLContext setCurrentContext: nil];
  233216. }
  233217. bool isActive() const throw()
  233218. {
  233219. return [EAGLContext currentContext] == context;
  233220. }
  233221. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  233222. void* getRawContext() const throw() { return glLayer; }
  233223. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  233224. {
  233225. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  233226. if (lastWidth != w || lastHeight != h)
  233227. {
  233228. lastWidth = w;
  233229. lastHeight = h;
  233230. freeGLBuffers();
  233231. createGLBuffers();
  233232. }
  233233. }
  233234. bool setSwapInterval (const int numFramesPerSwap)
  233235. {
  233236. numFrames = numFramesPerSwap;
  233237. return true;
  233238. }
  233239. int getSwapInterval() const
  233240. {
  233241. return numFrames;
  233242. }
  233243. void repaint()
  233244. {
  233245. }
  233246. void createGLBuffers()
  233247. {
  233248. makeActive();
  233249. glGenFramebuffersOES (1, &frameBufferHandle);
  233250. glGenRenderbuffersOES (1, &colorBufferHandle);
  233251. glGenRenderbuffersOES (1, &depthBufferHandle);
  233252. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  233253. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  233254. GLint width, height;
  233255. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  233256. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  233257. if (useDepthBuffer)
  233258. {
  233259. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  233260. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  233261. }
  233262. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  233263. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  233264. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  233265. if (useDepthBuffer)
  233266. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  233267. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  233268. }
  233269. void freeGLBuffers()
  233270. {
  233271. if (frameBufferHandle != 0)
  233272. {
  233273. glDeleteFramebuffersOES (1, &frameBufferHandle);
  233274. frameBufferHandle = 0;
  233275. }
  233276. if (colorBufferHandle != 0)
  233277. {
  233278. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  233279. colorBufferHandle = 0;
  233280. }
  233281. if (depthBufferHandle != 0)
  233282. {
  233283. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  233284. depthBufferHandle = 0;
  233285. }
  233286. }
  233287. juce_UseDebuggingNewOperator
  233288. private:
  233289. Component::SafePointer<Component> component;
  233290. OpenGLPixelFormat pixelFormat;
  233291. JuceGLView* view;
  233292. CAEAGLLayer* glLayer;
  233293. EAGLContext* context;
  233294. bool useDepthBuffer;
  233295. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  233296. int numFrames;
  233297. int lastWidth, lastHeight;
  233298. GLESContext (const GLESContext&);
  233299. GLESContext& operator= (const GLESContext&);
  233300. };
  233301. OpenGLContext* OpenGLComponent::createContext()
  233302. {
  233303. ScopedAutoReleasePool pool;
  233304. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  233305. if (peer != 0)
  233306. return new GLESContext (peer, this, preferredPixelFormat,
  233307. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  233308. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  233309. return 0;
  233310. }
  233311. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  233312. OwnedArray <OpenGLPixelFormat>& /*results*/)
  233313. {
  233314. }
  233315. void juce_glViewport (const int w, const int h)
  233316. {
  233317. glViewport (0, 0, w, h);
  233318. }
  233319. #endif
  233320. #endif
  233321. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  233322. /*** Start of inlined file: juce_mac_MainMenu.mm ***/
  233323. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233324. // compiled on its own).
  233325. #if JUCE_INCLUDED_FILE
  233326. class JuceMainMenuHandler;
  233327. END_JUCE_NAMESPACE
  233328. using namespace JUCE_NAMESPACE;
  233329. #define JuceMenuCallback MakeObjCClassName(JuceMenuCallback)
  233330. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  233331. @interface JuceMenuCallback : NSObject <NSMenuDelegate>
  233332. #else
  233333. @interface JuceMenuCallback : NSObject
  233334. #endif
  233335. {
  233336. JuceMainMenuHandler* owner;
  233337. }
  233338. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_;
  233339. - (void) dealloc;
  233340. - (void) menuItemInvoked: (id) menu;
  233341. - (void) menuNeedsUpdate: (NSMenu*) menu;
  233342. @end
  233343. BEGIN_JUCE_NAMESPACE
  233344. class JuceMainMenuHandler : private MenuBarModel::Listener,
  233345. private DeletedAtShutdown
  233346. {
  233347. public:
  233348. static JuceMainMenuHandler* instance;
  233349. JuceMainMenuHandler()
  233350. : currentModel (0),
  233351. lastUpdateTime (0)
  233352. {
  233353. callback = [[JuceMenuCallback alloc] initWithOwner: this];
  233354. }
  233355. ~JuceMainMenuHandler()
  233356. {
  233357. setMenu (0);
  233358. jassert (instance == this);
  233359. instance = 0;
  233360. [callback release];
  233361. }
  233362. void setMenu (MenuBarModel* const newMenuBarModel)
  233363. {
  233364. if (currentModel != newMenuBarModel)
  233365. {
  233366. if (currentModel != 0)
  233367. currentModel->removeListener (this);
  233368. currentModel = newMenuBarModel;
  233369. if (currentModel != 0)
  233370. currentModel->addListener (this);
  233371. menuBarItemsChanged (0);
  233372. }
  233373. }
  233374. void addSubMenu (NSMenu* parent, const PopupMenu& child,
  233375. const String& name, const int menuId, const int tag)
  233376. {
  233377. NSMenuItem* item = [parent addItemWithTitle: juceStringToNS (name)
  233378. action: nil
  233379. keyEquivalent: @""];
  233380. [item setTag: tag];
  233381. NSMenu* sub = createMenu (child, name, menuId, tag);
  233382. [parent setSubmenu: sub forItem: item];
  233383. [sub setAutoenablesItems: false];
  233384. [sub release];
  233385. }
  233386. void updateSubMenu (NSMenuItem* parentItem, const PopupMenu& menuToCopy,
  233387. const String& name, const int menuId, const int tag)
  233388. {
  233389. [parentItem setTag: tag];
  233390. NSMenu* menu = [parentItem submenu];
  233391. [menu setTitle: juceStringToNS (name)];
  233392. while ([menu numberOfItems] > 0)
  233393. [menu removeItemAtIndex: 0];
  233394. PopupMenu::MenuItemIterator iter (menuToCopy);
  233395. while (iter.next())
  233396. addMenuItem (iter, menu, menuId, tag);
  233397. [menu setAutoenablesItems: false];
  233398. [menu update];
  233399. }
  233400. void menuBarItemsChanged (MenuBarModel*)
  233401. {
  233402. lastUpdateTime = Time::getMillisecondCounter();
  233403. StringArray menuNames;
  233404. if (currentModel != 0)
  233405. menuNames = currentModel->getMenuBarNames();
  233406. NSMenu* menuBar = [NSApp mainMenu];
  233407. while ([menuBar numberOfItems] > 1 + menuNames.size())
  233408. [menuBar removeItemAtIndex: [menuBar numberOfItems] - 1];
  233409. int menuId = 1;
  233410. for (int i = 0; i < menuNames.size(); ++i)
  233411. {
  233412. const PopupMenu menu (currentModel->getMenuForIndex (i, menuNames [i]));
  233413. if (i >= [menuBar numberOfItems] - 1)
  233414. addSubMenu (menuBar, menu, menuNames[i], menuId, i);
  233415. else
  233416. updateSubMenu ([menuBar itemAtIndex: 1 + i], menu, menuNames[i], menuId, i);
  233417. }
  233418. }
  233419. static void flashMenuBar (NSMenu* menu)
  233420. {
  233421. if ([[menu title] isEqualToString: @"Apple"])
  233422. return;
  233423. [menu retain];
  233424. const unichar f35Key = NSF35FunctionKey;
  233425. NSString* f35String = [NSString stringWithCharacters: &f35Key length: 1];
  233426. NSMenuItem* item = [[NSMenuItem alloc] initWithTitle: @"x"
  233427. action: nil
  233428. keyEquivalent: f35String];
  233429. [item setTarget: nil];
  233430. [menu insertItem: item atIndex: [menu numberOfItems]];
  233431. [item release];
  233432. if ([menu indexOfItem: item] >= 0)
  233433. {
  233434. NSEvent* f35Event = [NSEvent keyEventWithType: NSKeyDown
  233435. location: NSZeroPoint
  233436. modifierFlags: NSCommandKeyMask
  233437. timestamp: 0
  233438. windowNumber: 0
  233439. context: [NSGraphicsContext currentContext]
  233440. characters: f35String
  233441. charactersIgnoringModifiers: f35String
  233442. isARepeat: NO
  233443. keyCode: 0];
  233444. [menu performKeyEquivalent: f35Event];
  233445. if ([menu indexOfItem: item] >= 0)
  233446. [menu removeItem: item]; // (this throws if the item isn't actually in the menu)
  233447. }
  233448. [menu release];
  233449. }
  233450. static NSMenuItem* findMenuItem (NSMenu* const menu, const ApplicationCommandTarget::InvocationInfo& info)
  233451. {
  233452. for (NSInteger i = [menu numberOfItems]; --i >= 0;)
  233453. {
  233454. NSMenuItem* m = [menu itemAtIndex: i];
  233455. if ([m tag] == info.commandID)
  233456. return m;
  233457. if ([m submenu] != 0)
  233458. {
  233459. NSMenuItem* found = findMenuItem ([m submenu], info);
  233460. if (found != 0)
  233461. return found;
  233462. }
  233463. }
  233464. return 0;
  233465. }
  233466. void menuCommandInvoked (MenuBarModel*, const ApplicationCommandTarget::InvocationInfo& info)
  233467. {
  233468. NSMenuItem* item = findMenuItem ([NSApp mainMenu], info);
  233469. if (item != 0)
  233470. flashMenuBar ([item menu]);
  233471. }
  233472. void updateMenus()
  233473. {
  233474. if (Time::getMillisecondCounter() > lastUpdateTime + 500)
  233475. menuBarItemsChanged (0);
  233476. }
  233477. void invoke (const int commandId, ApplicationCommandManager* const commandManager, const int topLevelIndex) const
  233478. {
  233479. if (currentModel != 0)
  233480. {
  233481. if (commandManager != 0)
  233482. {
  233483. ApplicationCommandTarget::InvocationInfo info (commandId);
  233484. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  233485. commandManager->invoke (info, true);
  233486. }
  233487. currentModel->menuItemSelected (commandId, topLevelIndex);
  233488. }
  233489. }
  233490. MenuBarModel* currentModel;
  233491. uint32 lastUpdateTime;
  233492. void addMenuItem (PopupMenu::MenuItemIterator& iter, NSMenu* menuToAddTo,
  233493. const int topLevelMenuId, const int topLevelIndex)
  233494. {
  233495. NSString* text = juceStringToNS (iter.itemName.upToFirstOccurrenceOf ("<end>", false, true));
  233496. if (text == 0)
  233497. text = @"";
  233498. if (iter.isSeparator)
  233499. {
  233500. [menuToAddTo addItem: [NSMenuItem separatorItem]];
  233501. }
  233502. else if (iter.isSectionHeader)
  233503. {
  233504. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  233505. action: nil
  233506. keyEquivalent: @""];
  233507. [item setEnabled: false];
  233508. }
  233509. else if (iter.subMenu != 0)
  233510. {
  233511. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  233512. action: nil
  233513. keyEquivalent: @""];
  233514. [item setTag: iter.itemId];
  233515. [item setEnabled: iter.isEnabled];
  233516. NSMenu* sub = createMenu (*iter.subMenu, iter.itemName, topLevelMenuId, topLevelIndex);
  233517. [sub setDelegate: nil];
  233518. [menuToAddTo setSubmenu: sub forItem: item];
  233519. [sub release];
  233520. }
  233521. else
  233522. {
  233523. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  233524. action: @selector (menuItemInvoked:)
  233525. keyEquivalent: @""];
  233526. [item setTag: iter.itemId];
  233527. [item setEnabled: iter.isEnabled];
  233528. [item setState: iter.isTicked ? NSOnState : NSOffState];
  233529. [item setTarget: (id) callback];
  233530. NSMutableArray* info = [NSMutableArray arrayWithObject: [NSNumber numberWithUnsignedLongLong: (pointer_sized_int) (void*) iter.commandManager]];
  233531. [info addObject: [NSNumber numberWithInt: topLevelIndex]];
  233532. [item setRepresentedObject: info];
  233533. if (iter.commandManager != 0)
  233534. {
  233535. const Array <KeyPress> keyPresses (iter.commandManager->getKeyMappings()
  233536. ->getKeyPressesAssignedToCommand (iter.itemId));
  233537. if (keyPresses.size() > 0)
  233538. {
  233539. const KeyPress& kp = keyPresses.getReference(0);
  233540. if (kp.getKeyCode() != KeyPress::backspaceKey
  233541. && kp.getKeyCode() != KeyPress::deleteKey) // (adding these is annoying because it flashes the menu bar
  233542. // every time you press the key while editing text)
  233543. {
  233544. juce_wchar key = kp.getTextCharacter();
  233545. if (kp.getKeyCode() == KeyPress::backspaceKey)
  233546. key = NSBackspaceCharacter;
  233547. else if (kp.getKeyCode() == KeyPress::deleteKey)
  233548. key = NSDeleteCharacter;
  233549. else if (key == 0)
  233550. key = (juce_wchar) kp.getKeyCode();
  233551. unsigned int mods = 0;
  233552. if (kp.getModifiers().isShiftDown())
  233553. mods |= NSShiftKeyMask;
  233554. if (kp.getModifiers().isCtrlDown())
  233555. mods |= NSControlKeyMask;
  233556. if (kp.getModifiers().isAltDown())
  233557. mods |= NSAlternateKeyMask;
  233558. if (kp.getModifiers().isCommandDown())
  233559. mods |= NSCommandKeyMask;
  233560. [item setKeyEquivalent: juceStringToNS (String::charToString (key))];
  233561. [item setKeyEquivalentModifierMask: mods];
  233562. }
  233563. }
  233564. }
  233565. }
  233566. }
  233567. JuceMenuCallback* callback;
  233568. private:
  233569. NSMenu* createMenu (const PopupMenu menu,
  233570. const String& menuName,
  233571. const int topLevelMenuId,
  233572. const int topLevelIndex)
  233573. {
  233574. NSMenu* m = [[NSMenu alloc] initWithTitle: juceStringToNS (menuName)];
  233575. [m setAutoenablesItems: false];
  233576. [m setDelegate: callback];
  233577. PopupMenu::MenuItemIterator iter (menu);
  233578. while (iter.next())
  233579. addMenuItem (iter, m, topLevelMenuId, topLevelIndex);
  233580. [m update];
  233581. return m;
  233582. }
  233583. };
  233584. JuceMainMenuHandler* JuceMainMenuHandler::instance = 0;
  233585. END_JUCE_NAMESPACE
  233586. @implementation JuceMenuCallback
  233587. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_
  233588. {
  233589. [super init];
  233590. owner = owner_;
  233591. return self;
  233592. }
  233593. - (void) dealloc
  233594. {
  233595. [super dealloc];
  233596. }
  233597. - (void) menuItemInvoked: (id) menu
  233598. {
  233599. NSMenuItem* item = (NSMenuItem*) menu;
  233600. if ([[item representedObject] isKindOfClass: [NSArray class]])
  233601. {
  233602. // 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
  233603. // our own components, which may have wanted to intercept it. So, rather than dispatching directly, we'll feed it back
  233604. // into the focused component and let it trigger the menu item indirectly.
  233605. NSEvent* e = [NSApp currentEvent];
  233606. if ([e type] == NSKeyDown || [e type] == NSKeyUp)
  233607. {
  233608. if (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent() != 0)
  233609. {
  233610. JUCE_NAMESPACE::NSViewComponentPeer* peer = dynamic_cast <JUCE_NAMESPACE::NSViewComponentPeer*> (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent()->getPeer());
  233611. if (peer != 0)
  233612. {
  233613. if ([e type] == NSKeyDown)
  233614. peer->redirectKeyDown (e);
  233615. else
  233616. peer->redirectKeyUp (e);
  233617. return;
  233618. }
  233619. }
  233620. }
  233621. NSArray* info = (NSArray*) [item representedObject];
  233622. owner->invoke ((int) [item tag],
  233623. (ApplicationCommandManager*) (pointer_sized_int)
  233624. [((NSNumber*) [info objectAtIndex: 0]) unsignedLongLongValue],
  233625. (int) [((NSNumber*) [info objectAtIndex: 1]) intValue]);
  233626. }
  233627. }
  233628. - (void) menuNeedsUpdate: (NSMenu*) menu;
  233629. {
  233630. (void) menu;
  233631. if (JuceMainMenuHandler::instance != 0)
  233632. JuceMainMenuHandler::instance->updateMenus();
  233633. }
  233634. @end
  233635. BEGIN_JUCE_NAMESPACE
  233636. static NSMenu* createStandardAppMenu (NSMenu* menu, const String& appName,
  233637. const PopupMenu* extraItems)
  233638. {
  233639. if (extraItems != 0 && JuceMainMenuHandler::instance != 0 && extraItems->getNumItems() > 0)
  233640. {
  233641. PopupMenu::MenuItemIterator iter (*extraItems);
  233642. while (iter.next())
  233643. JuceMainMenuHandler::instance->addMenuItem (iter, menu, 0, -1);
  233644. [menu addItem: [NSMenuItem separatorItem]];
  233645. }
  233646. NSMenuItem* item;
  233647. // Services...
  233648. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Services", nil)
  233649. action: nil keyEquivalent: @""];
  233650. [menu addItem: item];
  233651. [item release];
  233652. NSMenu* servicesMenu = [[NSMenu alloc] initWithTitle: @"Services"];
  233653. [menu setSubmenu: servicesMenu forItem: item];
  233654. [NSApp setServicesMenu: servicesMenu];
  233655. [servicesMenu release];
  233656. [menu addItem: [NSMenuItem separatorItem]];
  233657. // Hide + Show stuff...
  233658. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Hide " + appName)
  233659. action: @selector (hide:) keyEquivalent: @"h"];
  233660. [item setTarget: NSApp];
  233661. [menu addItem: item];
  233662. [item release];
  233663. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Hide Others", nil)
  233664. action: @selector (hideOtherApplications:) keyEquivalent: @"h"];
  233665. [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
  233666. [item setTarget: NSApp];
  233667. [menu addItem: item];
  233668. [item release];
  233669. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Show All", nil)
  233670. action: @selector (unhideAllApplications:) keyEquivalent: @""];
  233671. [item setTarget: NSApp];
  233672. [menu addItem: item];
  233673. [item release];
  233674. [menu addItem: [NSMenuItem separatorItem]];
  233675. // Quit item....
  233676. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Quit " + appName)
  233677. action: @selector (terminate:) keyEquivalent: @"q"];
  233678. [item setTarget: NSApp];
  233679. [menu addItem: item];
  233680. [item release];
  233681. return menu;
  233682. }
  233683. // Since our app has no NIB, this initialises a standard app menu...
  233684. static void rebuildMainMenu (const PopupMenu* extraItems)
  233685. {
  233686. // this can't be used in a plugin!
  233687. jassert (JUCEApplication::isStandaloneApp());
  233688. if (JUCEApplication::getInstance() != 0)
  233689. {
  233690. const ScopedAutoReleasePool pool;
  233691. NSMenu* mainMenu = [[NSMenu alloc] initWithTitle: @"MainMenu"];
  233692. NSMenuItem* item = [mainMenu addItemWithTitle: @"Apple" action: nil keyEquivalent: @""];
  233693. NSMenu* appMenu = [[NSMenu alloc] initWithTitle: @"Apple"];
  233694. [NSApp performSelector: @selector (setAppleMenu:) withObject: appMenu];
  233695. [mainMenu setSubmenu: appMenu forItem: item];
  233696. [NSApp setMainMenu: mainMenu];
  233697. createStandardAppMenu (appMenu, JUCEApplication::getInstance()->getApplicationName(), extraItems);
  233698. [appMenu release];
  233699. [mainMenu release];
  233700. }
  233701. }
  233702. void MenuBarModel::setMacMainMenu (MenuBarModel* newMenuBarModel,
  233703. const PopupMenu* extraAppleMenuItems)
  233704. {
  233705. if (getMacMainMenu() != newMenuBarModel)
  233706. {
  233707. const ScopedAutoReleasePool pool;
  233708. if (newMenuBarModel == 0)
  233709. {
  233710. delete JuceMainMenuHandler::instance;
  233711. jassert (JuceMainMenuHandler::instance == 0); // should be zeroed in the destructor
  233712. jassert (extraAppleMenuItems == 0); // you can't specify some extra items without also supplying a model
  233713. extraAppleMenuItems = 0;
  233714. }
  233715. else
  233716. {
  233717. if (JuceMainMenuHandler::instance == 0)
  233718. JuceMainMenuHandler::instance = new JuceMainMenuHandler();
  233719. JuceMainMenuHandler::instance->setMenu (newMenuBarModel);
  233720. }
  233721. }
  233722. rebuildMainMenu (extraAppleMenuItems);
  233723. if (newMenuBarModel != 0)
  233724. newMenuBarModel->menuItemsChanged();
  233725. }
  233726. MenuBarModel* MenuBarModel::getMacMainMenu()
  233727. {
  233728. return JuceMainMenuHandler::instance != 0
  233729. ? JuceMainMenuHandler::instance->currentModel : 0;
  233730. }
  233731. void juce_initialiseMacMainMenu()
  233732. {
  233733. if (JuceMainMenuHandler::instance == 0)
  233734. rebuildMainMenu (0);
  233735. }
  233736. #endif
  233737. /*** End of inlined file: juce_mac_MainMenu.mm ***/
  233738. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  233739. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233740. // compiled on its own).
  233741. #if JUCE_INCLUDED_FILE
  233742. #if JUCE_MAC
  233743. END_JUCE_NAMESPACE
  233744. using namespace JUCE_NAMESPACE;
  233745. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  233746. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  233747. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  233748. #else
  233749. @interface JuceFileChooserDelegate : NSObject
  233750. #endif
  233751. {
  233752. StringArray* filters;
  233753. }
  233754. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  233755. - (void) dealloc;
  233756. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  233757. @end
  233758. @implementation JuceFileChooserDelegate
  233759. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  233760. {
  233761. [super init];
  233762. filters = filters_;
  233763. return self;
  233764. }
  233765. - (void) dealloc
  233766. {
  233767. delete filters;
  233768. [super dealloc];
  233769. }
  233770. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  233771. {
  233772. (void) sender;
  233773. const File f (nsStringToJuce (filename));
  233774. for (int i = filters->size(); --i >= 0;)
  233775. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  233776. return true;
  233777. return f.isDirectory();
  233778. }
  233779. @end
  233780. BEGIN_JUCE_NAMESPACE
  233781. void FileChooser::showPlatformDialog (Array<File>& results,
  233782. const String& title,
  233783. const File& currentFileOrDirectory,
  233784. const String& filter,
  233785. bool selectsDirectory,
  233786. bool selectsFiles,
  233787. bool isSaveDialogue,
  233788. bool warnAboutOverwritingExistingFiles,
  233789. bool selectMultipleFiles,
  233790. FilePreviewComponent* extraInfoComponent)
  233791. {
  233792. const ScopedAutoReleasePool pool;
  233793. StringArray* filters = new StringArray();
  233794. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  233795. filters->trim();
  233796. filters->removeEmptyStrings();
  233797. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  233798. [delegate autorelease];
  233799. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  233800. : [NSOpenPanel openPanel];
  233801. [panel setTitle: juceStringToNS (title)];
  233802. if (! isSaveDialogue)
  233803. {
  233804. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  233805. [openPanel setCanChooseDirectories: selectsDirectory];
  233806. [openPanel setCanChooseFiles: selectsFiles];
  233807. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  233808. }
  233809. [panel setDelegate: delegate];
  233810. if (isSaveDialogue || selectsDirectory)
  233811. [panel setCanCreateDirectories: YES];
  233812. String directory, filename;
  233813. if (currentFileOrDirectory.isDirectory())
  233814. {
  233815. directory = currentFileOrDirectory.getFullPathName();
  233816. }
  233817. else
  233818. {
  233819. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  233820. filename = currentFileOrDirectory.getFileName();
  233821. }
  233822. if ([panel runModalForDirectory: juceStringToNS (directory)
  233823. file: juceStringToNS (filename)]
  233824. == NSOKButton)
  233825. {
  233826. if (isSaveDialogue)
  233827. {
  233828. results.add (File (nsStringToJuce ([panel filename])));
  233829. }
  233830. else
  233831. {
  233832. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  233833. NSArray* urls = [openPanel filenames];
  233834. for (unsigned int i = 0; i < [urls count]; ++i)
  233835. {
  233836. NSString* f = [urls objectAtIndex: i];
  233837. results.add (File (nsStringToJuce (f)));
  233838. }
  233839. }
  233840. }
  233841. [panel setDelegate: nil];
  233842. }
  233843. #else
  233844. void FileChooser::showPlatformDialog (Array<File>& results,
  233845. const String& title,
  233846. const File& currentFileOrDirectory,
  233847. const String& filter,
  233848. bool selectsDirectory,
  233849. bool selectsFiles,
  233850. bool isSaveDialogue,
  233851. bool warnAboutOverwritingExistingFiles,
  233852. bool selectMultipleFiles,
  233853. FilePreviewComponent* extraInfoComponent)
  233854. {
  233855. const ScopedAutoReleasePool pool;
  233856. jassertfalse; //xxx to do
  233857. }
  233858. #endif
  233859. #endif
  233860. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  233861. /*** Start of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  233862. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233863. // compiled on its own).
  233864. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  233865. END_JUCE_NAMESPACE
  233866. #define NonInterceptingQTMovieView MakeObjCClassName(NonInterceptingQTMovieView)
  233867. @interface NonInterceptingQTMovieView : QTMovieView
  233868. {
  233869. }
  233870. - (id) initWithFrame: (NSRect) frame;
  233871. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent;
  233872. - (NSView*) hitTest: (NSPoint) p;
  233873. @end
  233874. @implementation NonInterceptingQTMovieView
  233875. - (id) initWithFrame: (NSRect) frame
  233876. {
  233877. self = [super initWithFrame: frame];
  233878. [self setNextResponder: [self superview]];
  233879. return self;
  233880. }
  233881. - (void) dealloc
  233882. {
  233883. [super dealloc];
  233884. }
  233885. - (NSView*) hitTest: (NSPoint) point
  233886. {
  233887. return [self isControllerVisible] ? [super hitTest: point] : nil;
  233888. }
  233889. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent
  233890. {
  233891. return YES;
  233892. }
  233893. @end
  233894. BEGIN_JUCE_NAMESPACE
  233895. #define theMovie (static_cast <QTMovie*> (movie))
  233896. QuickTimeMovieComponent::QuickTimeMovieComponent()
  233897. : movie (0)
  233898. {
  233899. setOpaque (true);
  233900. setVisible (true);
  233901. QTMovieView* view = [[NonInterceptingQTMovieView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)];
  233902. setView (view);
  233903. [view release];
  233904. }
  233905. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  233906. {
  233907. closeMovie();
  233908. setView (0);
  233909. }
  233910. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  233911. {
  233912. return true;
  233913. }
  233914. static QTMovie* openMovieFromStream (InputStream* movieStream, File& movieFile)
  233915. {
  233916. // unfortunately, QTMovie objects can only be created on the main thread..
  233917. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  233918. QTMovie* movie = 0;
  233919. FileInputStream* const fin = dynamic_cast <FileInputStream*> (movieStream);
  233920. if (fin != 0)
  233921. {
  233922. movieFile = fin->getFile();
  233923. movie = [QTMovie movieWithFile: juceStringToNS (movieFile.getFullPathName())
  233924. error: nil];
  233925. }
  233926. else
  233927. {
  233928. MemoryBlock temp;
  233929. movieStream->readIntoMemoryBlock (temp);
  233930. const char* const suffixesToTry[] = { ".mov", ".mp3", ".avi", ".m4a" };
  233931. for (int i = 0; i < numElementsInArray (suffixesToTry); ++i)
  233932. {
  233933. movie = [QTMovie movieWithDataReference: [QTDataReference dataReferenceWithReferenceToData: [NSData dataWithBytes: temp.getData()
  233934. length: temp.getSize()]
  233935. name: [NSString stringWithUTF8String: suffixesToTry[i]]
  233936. MIMEType: @""]
  233937. error: nil];
  233938. if (movie != 0)
  233939. break;
  233940. }
  233941. }
  233942. return movie;
  233943. }
  233944. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  233945. const bool isControllerVisible_)
  233946. {
  233947. return loadMovie ((InputStream*) movieFile_.createInputStream(), isControllerVisible_);
  233948. }
  233949. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  233950. const bool controllerVisible_)
  233951. {
  233952. closeMovie();
  233953. if (getPeer() == 0)
  233954. {
  233955. // To open a movie, this component must be visible inside a functioning window, so that
  233956. // the QT control can be assigned to the window.
  233957. jassertfalse;
  233958. return false;
  233959. }
  233960. movie = openMovieFromStream (movieStream, movieFile);
  233961. [theMovie retain];
  233962. QTMovieView* view = (QTMovieView*) getView();
  233963. [view setMovie: theMovie];
  233964. [view setControllerVisible: controllerVisible_];
  233965. setLooping (looping);
  233966. return movie != nil;
  233967. }
  233968. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  233969. const bool isControllerVisible_)
  233970. {
  233971. // unfortunately, QTMovie objects can only be created on the main thread..
  233972. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  233973. closeMovie();
  233974. if (getPeer() == 0)
  233975. {
  233976. // To open a movie, this component must be visible inside a functioning window, so that
  233977. // the QT control can be assigned to the window.
  233978. jassertfalse;
  233979. return false;
  233980. }
  233981. NSURL* url = [NSURL URLWithString: juceStringToNS (movieURL.toString (true))];
  233982. NSError* err;
  233983. if ([QTMovie canInitWithURL: url])
  233984. movie = [QTMovie movieWithURL: url error: &err];
  233985. [theMovie retain];
  233986. QTMovieView* view = (QTMovieView*) getView();
  233987. [view setMovie: theMovie];
  233988. [view setControllerVisible: controllerVisible];
  233989. setLooping (looping);
  233990. return movie != nil;
  233991. }
  233992. void QuickTimeMovieComponent::closeMovie()
  233993. {
  233994. stop();
  233995. QTMovieView* view = (QTMovieView*) getView();
  233996. [view setMovie: nil];
  233997. [theMovie release];
  233998. movie = 0;
  233999. movieFile = File::nonexistent;
  234000. }
  234001. bool QuickTimeMovieComponent::isMovieOpen() const
  234002. {
  234003. return movie != nil;
  234004. }
  234005. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  234006. {
  234007. return movieFile;
  234008. }
  234009. void QuickTimeMovieComponent::play()
  234010. {
  234011. [theMovie play];
  234012. }
  234013. void QuickTimeMovieComponent::stop()
  234014. {
  234015. [theMovie stop];
  234016. }
  234017. bool QuickTimeMovieComponent::isPlaying() const
  234018. {
  234019. return movie != 0 && [theMovie rate] != 0;
  234020. }
  234021. void QuickTimeMovieComponent::setPosition (const double seconds)
  234022. {
  234023. if (movie != 0)
  234024. {
  234025. QTTime t;
  234026. t.timeValue = (uint64) (100000.0 * seconds);
  234027. t.timeScale = 100000;
  234028. t.flags = 0;
  234029. [theMovie setCurrentTime: t];
  234030. }
  234031. }
  234032. double QuickTimeMovieComponent::getPosition() const
  234033. {
  234034. if (movie == 0)
  234035. return 0.0;
  234036. QTTime t = [theMovie currentTime];
  234037. return t.timeValue / (double) t.timeScale;
  234038. }
  234039. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  234040. {
  234041. [theMovie setRate: newSpeed];
  234042. }
  234043. double QuickTimeMovieComponent::getMovieDuration() const
  234044. {
  234045. if (movie == 0)
  234046. return 0.0;
  234047. QTTime t = [theMovie duration];
  234048. return t.timeValue / (double) t.timeScale;
  234049. }
  234050. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  234051. {
  234052. looping = shouldLoop;
  234053. [theMovie setAttribute: [NSNumber numberWithBool: shouldLoop]
  234054. forKey: QTMovieLoopsAttribute];
  234055. }
  234056. bool QuickTimeMovieComponent::isLooping() const
  234057. {
  234058. return looping;
  234059. }
  234060. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  234061. {
  234062. [theMovie setVolume: newVolume];
  234063. }
  234064. float QuickTimeMovieComponent::getMovieVolume() const
  234065. {
  234066. return movie != 0 ? [theMovie volume] : 0.0f;
  234067. }
  234068. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  234069. {
  234070. width = 0;
  234071. height = 0;
  234072. if (movie != 0)
  234073. {
  234074. NSSize s = [[theMovie attributeForKey: QTMovieNaturalSizeAttribute] sizeValue];
  234075. width = (int) s.width;
  234076. height = (int) s.height;
  234077. }
  234078. }
  234079. void QuickTimeMovieComponent::paint (Graphics& g)
  234080. {
  234081. if (movie == 0)
  234082. g.fillAll (Colours::black);
  234083. }
  234084. bool QuickTimeMovieComponent::isControllerVisible() const
  234085. {
  234086. return controllerVisible;
  234087. }
  234088. void QuickTimeMovieComponent::goToStart()
  234089. {
  234090. setPosition (0.0);
  234091. }
  234092. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  234093. const RectanglePlacement& placement)
  234094. {
  234095. int normalWidth, normalHeight;
  234096. getMovieNormalSize (normalWidth, normalHeight);
  234097. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  234098. {
  234099. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  234100. placement.applyTo (x, y, w, h,
  234101. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  234102. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  234103. if (w > 0 && h > 0)
  234104. {
  234105. setBounds (roundToInt (x), roundToInt (y),
  234106. roundToInt (w), roundToInt (h));
  234107. }
  234108. }
  234109. else
  234110. {
  234111. setBounds (spaceToFitWithin);
  234112. }
  234113. }
  234114. #if ! (JUCE_MAC && JUCE_64BIT)
  234115. bool juce_OpenQuickTimeMovieFromStream (InputStream* movieStream, Movie& result, Handle& dataHandle)
  234116. {
  234117. if (movieStream == 0)
  234118. return false;
  234119. File file;
  234120. QTMovie* movie = openMovieFromStream (movieStream, file);
  234121. if (movie != nil)
  234122. result = [movie quickTimeMovie];
  234123. return movie != nil;
  234124. }
  234125. #endif
  234126. #endif
  234127. /*** End of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  234128. /*** Start of inlined file: juce_mac_AudioCDBurner.mm ***/
  234129. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234130. // compiled on its own).
  234131. #if JUCE_INCLUDED_FILE && JUCE_USE_CDBURNER
  234132. const int kilobytesPerSecond1x = 176;
  234133. END_JUCE_NAMESPACE
  234134. #define OpenDiskDevice MakeObjCClassName(OpenDiskDevice)
  234135. @interface OpenDiskDevice : NSObject
  234136. {
  234137. @public
  234138. DRDevice* device;
  234139. NSMutableArray* tracks;
  234140. bool underrunProtection;
  234141. }
  234142. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device;
  234143. - (void) dealloc;
  234144. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) numSamples_;
  234145. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  234146. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed;
  234147. @end
  234148. #define AudioTrackProducer MakeObjCClassName(AudioTrackProducer)
  234149. @interface AudioTrackProducer : NSObject
  234150. {
  234151. JUCE_NAMESPACE::AudioSource* source;
  234152. int readPosition, lengthInFrames;
  234153. }
  234154. - (AudioTrackProducer*) init: (int) lengthInFrames;
  234155. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) lengthInSamples;
  234156. - (void) dealloc;
  234157. - (void) setupTrackProperties: (DRTrack*) track;
  234158. - (void) cleanupTrackAfterBurn: (DRTrack*) track;
  234159. - (BOOL) cleanupTrackAfterVerification:(DRTrack*)track;
  234160. - (uint64_t) estimateLengthOfTrack:(DRTrack*)track;
  234161. - (BOOL) prepareTrack:(DRTrack*)track forBurn:(DRBurn*)burn
  234162. toMedia:(NSDictionary*)mediaInfo;
  234163. - (BOOL) prepareTrackForVerification:(DRTrack*)track;
  234164. - (uint32_t) produceDataForTrack:(DRTrack*)track intoBuffer:(char*)buffer
  234165. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  234166. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  234167. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  234168. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  234169. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  234170. ioFlags:(uint32_t*)flags;
  234171. - (BOOL) verifyDataForTrack:(DRTrack*)track inBuffer:(const char*)buffer
  234172. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  234173. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  234174. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  234175. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  234176. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  234177. ioFlags:(uint32_t*)flags;
  234178. @end
  234179. @implementation OpenDiskDevice
  234180. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device_
  234181. {
  234182. [super init];
  234183. device = device_;
  234184. tracks = [[NSMutableArray alloc] init];
  234185. underrunProtection = true;
  234186. return self;
  234187. }
  234188. - (void) dealloc
  234189. {
  234190. [tracks release];
  234191. [super dealloc];
  234192. }
  234193. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) numSamples_
  234194. {
  234195. AudioTrackProducer* p = [[AudioTrackProducer alloc] initWithAudioSource: source_ numSamples: numSamples_];
  234196. DRTrack* t = [[DRTrack alloc] initWithProducer: p];
  234197. [p setupTrackProperties: t];
  234198. [tracks addObject: t];
  234199. [t release];
  234200. [p release];
  234201. }
  234202. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  234203. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed
  234204. {
  234205. DRBurn* burn = [DRBurn burnForDevice: device];
  234206. if (! [device acquireExclusiveAccess])
  234207. {
  234208. *error = "Couldn't open or write to the CD device";
  234209. return;
  234210. }
  234211. [device acquireMediaReservation];
  234212. NSMutableDictionary* d = [[burn properties] mutableCopy];
  234213. [d autorelease];
  234214. [d setObject: [NSNumber numberWithBool: peformFakeBurnForTesting] forKey: DRBurnTestingKey];
  234215. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnVerifyDiscKey];
  234216. [d setObject: (shouldEject ? DRBurnCompletionActionEject : DRBurnCompletionActionMount) forKey: DRBurnCompletionActionKey];
  234217. if (burnSpeed > 0)
  234218. [d setObject: [NSNumber numberWithFloat: burnSpeed * JUCE_NAMESPACE::kilobytesPerSecond1x] forKey: DRBurnRequestedSpeedKey];
  234219. if (! underrunProtection)
  234220. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnUnderrunProtectionKey];
  234221. [burn setProperties: d];
  234222. [burn writeLayout: tracks];
  234223. for (;;)
  234224. {
  234225. JUCE_NAMESPACE::Thread::sleep (300);
  234226. float progress = [[[burn status] objectForKey: DRStatusPercentCompleteKey] floatValue];
  234227. if (listener != 0 && listener->audioCDBurnProgress (progress))
  234228. {
  234229. [burn abort];
  234230. *error = "User cancelled the write operation";
  234231. break;
  234232. }
  234233. if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateFailed])
  234234. {
  234235. *error = "Write operation failed";
  234236. break;
  234237. }
  234238. else if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateDone])
  234239. {
  234240. break;
  234241. }
  234242. NSString* err = (NSString*) [[[burn status] objectForKey: DRErrorStatusKey]
  234243. objectForKey: DRErrorStatusErrorStringKey];
  234244. if ([err length] > 0)
  234245. {
  234246. *error = JUCE_NAMESPACE::String::fromUTF8 ([err UTF8String]);
  234247. break;
  234248. }
  234249. }
  234250. [device releaseMediaReservation];
  234251. [device releaseExclusiveAccess];
  234252. }
  234253. @end
  234254. @implementation AudioTrackProducer
  234255. - (AudioTrackProducer*) init: (int) lengthInFrames_
  234256. {
  234257. lengthInFrames = lengthInFrames_;
  234258. readPosition = 0;
  234259. return self;
  234260. }
  234261. - (void) setupTrackProperties: (DRTrack*) track
  234262. {
  234263. NSMutableDictionary* p = [[track properties] mutableCopy];
  234264. [p setObject:[DRMSF msfWithFrames: lengthInFrames] forKey: DRTrackLengthKey];
  234265. [p setObject:[NSNumber numberWithUnsignedShort:2352] forKey: DRBlockSizeKey];
  234266. [p setObject:[NSNumber numberWithInt:0] forKey: DRDataFormKey];
  234267. [p setObject:[NSNumber numberWithInt:0] forKey: DRBlockTypeKey];
  234268. [p setObject:[NSNumber numberWithInt:0] forKey: DRTrackModeKey];
  234269. [p setObject:[NSNumber numberWithInt:0] forKey: DRSessionFormatKey];
  234270. [track setProperties: p];
  234271. [p release];
  234272. }
  234273. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) lengthInSamples
  234274. {
  234275. AudioTrackProducer* s = [self init: (lengthInSamples + 587) / 588];
  234276. if (s != nil)
  234277. s->source = source_;
  234278. return s;
  234279. }
  234280. - (void) dealloc
  234281. {
  234282. if (source != 0)
  234283. {
  234284. source->releaseResources();
  234285. delete source;
  234286. }
  234287. [super dealloc];
  234288. }
  234289. - (void) cleanupTrackAfterBurn: (DRTrack*) track
  234290. {
  234291. }
  234292. - (BOOL) cleanupTrackAfterVerification: (DRTrack*) track
  234293. {
  234294. return true;
  234295. }
  234296. - (uint64_t) estimateLengthOfTrack: (DRTrack*) track
  234297. {
  234298. return lengthInFrames;
  234299. }
  234300. - (BOOL) prepareTrack: (DRTrack*) track forBurn: (DRBurn*) burn
  234301. toMedia: (NSDictionary*) mediaInfo
  234302. {
  234303. if (source != 0)
  234304. source->prepareToPlay (44100 / 75, 44100);
  234305. readPosition = 0;
  234306. return true;
  234307. }
  234308. - (BOOL) prepareTrackForVerification: (DRTrack*) track
  234309. {
  234310. if (source != 0)
  234311. source->prepareToPlay (44100 / 75, 44100);
  234312. return true;
  234313. }
  234314. - (uint32_t) produceDataForTrack: (DRTrack*) track intoBuffer: (char*) buffer
  234315. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  234316. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  234317. {
  234318. if (source != 0)
  234319. {
  234320. const int numSamples = JUCE_NAMESPACE::jmin ((int) bufferLength / 4, (lengthInFrames * (44100 / 75)) - readPosition);
  234321. if (numSamples > 0)
  234322. {
  234323. JUCE_NAMESPACE::AudioSampleBuffer tempBuffer (2, numSamples);
  234324. JUCE_NAMESPACE::AudioSourceChannelInfo info;
  234325. info.buffer = &tempBuffer;
  234326. info.startSample = 0;
  234327. info.numSamples = numSamples;
  234328. source->getNextAudioBlock (info);
  234329. typedef JUCE_NAMESPACE::AudioData::Pointer <JUCE_NAMESPACE::AudioData::Int16,
  234330. JUCE_NAMESPACE::AudioData::LittleEndian,
  234331. JUCE_NAMESPACE::AudioData::Interleaved,
  234332. JUCE_NAMESPACE::AudioData::NonConst> CDSampleFormat;
  234333. typedef JUCE_NAMESPACE::AudioData::Pointer <JUCE_NAMESPACE::AudioData::Float32,
  234334. JUCE_NAMESPACE::AudioData::NativeEndian,
  234335. JUCE_NAMESPACE::AudioData::NonInterleaved,
  234336. JUCE_NAMESPACE::AudioData::Const> SourceSampleFormat;
  234337. CDSampleFormat left (buffer, 2);
  234338. left.convertSamples (SourceSampleFormat (tempBuffer.getSampleData (0)), numSamples);
  234339. CDSampleFormat right (buffer + 2, 2);
  234340. right.convertSamples (SourceSampleFormat (tempBuffer.getSampleData (1)), numSamples);
  234341. readPosition += numSamples;
  234342. }
  234343. return numSamples * 4;
  234344. }
  234345. return 0;
  234346. }
  234347. - (uint32_t) producePreGapForTrack: (DRTrack*) track
  234348. intoBuffer: (char*) buffer length: (uint32_t) bufferLength
  234349. atAddress: (uint64_t) address blockSize: (uint32_t) blockSize
  234350. ioFlags: (uint32_t*) flags
  234351. {
  234352. zeromem (buffer, bufferLength);
  234353. return bufferLength;
  234354. }
  234355. - (BOOL) verifyDataForTrack: (DRTrack*) track inBuffer: (const char*) buffer
  234356. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  234357. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  234358. {
  234359. return true;
  234360. }
  234361. @end
  234362. BEGIN_JUCE_NAMESPACE
  234363. class AudioCDBurner::Pimpl : public Timer
  234364. {
  234365. public:
  234366. Pimpl (AudioCDBurner& owner_, const int deviceIndex)
  234367. : device (0), owner (owner_)
  234368. {
  234369. DRDevice* dev = [[DRDevice devices] objectAtIndex: deviceIndex];
  234370. if (dev != 0)
  234371. {
  234372. device = [[OpenDiskDevice alloc] initWithDRDevice: dev];
  234373. lastState = getDiskState();
  234374. startTimer (1000);
  234375. }
  234376. }
  234377. ~Pimpl()
  234378. {
  234379. stopTimer();
  234380. [device release];
  234381. }
  234382. void timerCallback()
  234383. {
  234384. const DiskState state = getDiskState();
  234385. if (state != lastState)
  234386. {
  234387. lastState = state;
  234388. owner.sendChangeMessage (&owner);
  234389. }
  234390. }
  234391. DiskState getDiskState() const
  234392. {
  234393. if ([device->device isValid])
  234394. {
  234395. NSDictionary* status = [device->device status];
  234396. NSString* state = [status objectForKey: DRDeviceMediaStateKey];
  234397. if ([state isEqualTo: DRDeviceMediaStateNone])
  234398. {
  234399. if ([[status objectForKey: DRDeviceIsTrayOpenKey] boolValue])
  234400. return trayOpen;
  234401. return noDisc;
  234402. }
  234403. if ([state isEqualTo: DRDeviceMediaStateMediaPresent])
  234404. {
  234405. if ([[[status objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceMediaBlocksFreeKey] intValue] > 0)
  234406. return writableDiskPresent;
  234407. else
  234408. return readOnlyDiskPresent;
  234409. }
  234410. }
  234411. return unknown;
  234412. }
  234413. bool openTray() { return [device->device isValid] && [device->device ejectMedia]; }
  234414. const Array<int> getAvailableWriteSpeeds() const
  234415. {
  234416. Array<int> results;
  234417. if ([device->device isValid])
  234418. {
  234419. NSArray* speeds = [[[device->device status] objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceBurnSpeedsKey];
  234420. for (unsigned int i = 0; i < [speeds count]; ++i)
  234421. {
  234422. const int kbPerSec = [[speeds objectAtIndex: i] intValue];
  234423. results.add (kbPerSec / kilobytesPerSecond1x);
  234424. }
  234425. }
  234426. return results;
  234427. }
  234428. bool setBufferUnderrunProtection (const bool shouldBeEnabled)
  234429. {
  234430. if ([device->device isValid])
  234431. {
  234432. device->underrunProtection = shouldBeEnabled;
  234433. return shouldBeEnabled && [[[device->device status] objectForKey: DRDeviceCanUnderrunProtectCDKey] boolValue];
  234434. }
  234435. return false;
  234436. }
  234437. int getNumAvailableAudioBlocks() const
  234438. {
  234439. return [[[[device->device status] objectForKey: DRDeviceMediaInfoKey]
  234440. objectForKey: DRDeviceMediaBlocksFreeKey] intValue];
  234441. }
  234442. OpenDiskDevice* device;
  234443. private:
  234444. DiskState lastState;
  234445. AudioCDBurner& owner;
  234446. };
  234447. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  234448. {
  234449. pimpl = new Pimpl (*this, deviceIndex);
  234450. }
  234451. AudioCDBurner::~AudioCDBurner()
  234452. {
  234453. }
  234454. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  234455. {
  234456. ScopedPointer <AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  234457. if (b->pimpl->device == 0)
  234458. b = 0;
  234459. return b.release();
  234460. }
  234461. static NSArray* findDiskBurnerDevices()
  234462. {
  234463. NSMutableArray* results = [NSMutableArray array];
  234464. NSArray* devs = [DRDevice devices];
  234465. for (int i = 0; i < [devs count]; ++i)
  234466. {
  234467. NSDictionary* dic = [[devs objectAtIndex: i] info];
  234468. NSString* name = [dic valueForKey: DRDeviceProductNameKey];
  234469. if (name != nil)
  234470. [results addObject: name];
  234471. }
  234472. return results;
  234473. }
  234474. const StringArray AudioCDBurner::findAvailableDevices()
  234475. {
  234476. NSArray* names = findDiskBurnerDevices();
  234477. StringArray s;
  234478. for (unsigned int i = 0; i < [names count]; ++i)
  234479. s.add (String::fromUTF8 ([[names objectAtIndex: i] UTF8String]));
  234480. return s;
  234481. }
  234482. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  234483. {
  234484. return pimpl->getDiskState();
  234485. }
  234486. bool AudioCDBurner::isDiskPresent() const
  234487. {
  234488. return getDiskState() == writableDiskPresent;
  234489. }
  234490. bool AudioCDBurner::openTray()
  234491. {
  234492. return pimpl->openTray();
  234493. }
  234494. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  234495. {
  234496. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  234497. DiskState oldState = getDiskState();
  234498. DiskState newState = oldState;
  234499. while (newState == oldState && Time::currentTimeMillis() < timeout)
  234500. {
  234501. newState = getDiskState();
  234502. Thread::sleep (100);
  234503. }
  234504. return newState;
  234505. }
  234506. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  234507. {
  234508. return pimpl->getAvailableWriteSpeeds();
  234509. }
  234510. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  234511. {
  234512. return pimpl->setBufferUnderrunProtection (shouldBeEnabled);
  234513. }
  234514. int AudioCDBurner::getNumAvailableAudioBlocks() const
  234515. {
  234516. return pimpl->getNumAvailableAudioBlocks();
  234517. }
  234518. bool AudioCDBurner::addAudioTrack (AudioSource* source, int numSamps)
  234519. {
  234520. if ([pimpl->device->device isValid])
  234521. {
  234522. [pimpl->device addSourceTrack: source numSamples: numSamps];
  234523. return true;
  234524. }
  234525. return false;
  234526. }
  234527. const String AudioCDBurner::burn (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener* listener,
  234528. bool ejectDiscAfterwards,
  234529. bool performFakeBurnForTesting,
  234530. int writeSpeed)
  234531. {
  234532. String error ("Couldn't open or write to the CD device");
  234533. if ([pimpl->device->device isValid])
  234534. {
  234535. error = String::empty;
  234536. [pimpl->device burn: listener
  234537. errorString: &error
  234538. ejectAfterwards: ejectDiscAfterwards
  234539. isFake: performFakeBurnForTesting
  234540. speed: writeSpeed];
  234541. }
  234542. return error;
  234543. }
  234544. #endif
  234545. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  234546. void AudioCDReader::ejectDisk()
  234547. {
  234548. const ScopedAutoReleasePool p;
  234549. [[NSWorkspace sharedWorkspace] unmountAndEjectDeviceAtPath: juceStringToNS (volumeDir.getFullPathName())];
  234550. }
  234551. #endif
  234552. /*** End of inlined file: juce_mac_AudioCDBurner.mm ***/
  234553. /*** Start of inlined file: juce_mac_AudioCDReader.mm ***/
  234554. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234555. // compiled on its own).
  234556. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  234557. namespace CDReaderHelpers
  234558. {
  234559. inline const XmlElement* getElementForKey (const XmlElement& xml, const String& key)
  234560. {
  234561. forEachXmlChildElementWithTagName (xml, child, "key")
  234562. if (child->getAllSubText().trim() == key)
  234563. return child->getNextElement();
  234564. return 0;
  234565. }
  234566. static int getIntValueForKey (const XmlElement& xml, const String& key, int defaultValue = -1)
  234567. {
  234568. const XmlElement* const block = getElementForKey (xml, key);
  234569. return block != 0 ? block->getAllSubText().trim().getIntValue() : defaultValue;
  234570. }
  234571. // Get the track offsets for a CD given an XmlElement representing its TOC.Plist.
  234572. // Returns NULL on success, otherwise a const char* representing an error.
  234573. static const char* getTrackOffsets (XmlDocument& xmlDocument, Array<int>& offsets)
  234574. {
  234575. const ScopedPointer<XmlElement> xml (xmlDocument.getDocumentElement());
  234576. if (xml == 0)
  234577. return "Couldn't parse XML in file";
  234578. const XmlElement* const dict = xml->getChildByName ("dict");
  234579. if (dict == 0)
  234580. return "Couldn't get top level dictionary";
  234581. const XmlElement* const sessions = getElementForKey (*dict, "Sessions");
  234582. if (sessions == 0)
  234583. return "Couldn't find sessions key";
  234584. const XmlElement* const session = sessions->getFirstChildElement();
  234585. if (session == 0)
  234586. return "Couldn't find first session";
  234587. const int leadOut = getIntValueForKey (*session, "Leadout Block");
  234588. if (leadOut < 0)
  234589. return "Couldn't find Leadout Block";
  234590. const XmlElement* const trackArray = getElementForKey (*session, "Track Array");
  234591. if (trackArray == 0)
  234592. return "Couldn't find Track Array";
  234593. forEachXmlChildElement (*trackArray, track)
  234594. {
  234595. const int trackValue = getIntValueForKey (*track, "Start Block");
  234596. if (trackValue < 0)
  234597. return "Couldn't find Start Block in the track";
  234598. offsets.add (trackValue * AudioCDReader::samplesPerFrame - 88200);
  234599. }
  234600. offsets.add (leadOut * AudioCDReader::samplesPerFrame - 88200);
  234601. return 0;
  234602. }
  234603. static void findDevices (Array<File>& cds)
  234604. {
  234605. File volumes ("/Volumes");
  234606. volumes.findChildFiles (cds, File::findDirectories, false);
  234607. for (int i = cds.size(); --i >= 0;)
  234608. if (! cds.getReference(i).getChildFile (".TOC.plist").exists())
  234609. cds.remove (i);
  234610. }
  234611. struct TrackSorter
  234612. {
  234613. static int getCDTrackNumber (const File& file)
  234614. {
  234615. return file.getFileName().initialSectionContainingOnly ("0123456789").getIntValue();
  234616. }
  234617. static int compareElements (const File& first, const File& second)
  234618. {
  234619. const int firstTrack = getCDTrackNumber (first);
  234620. const int secondTrack = getCDTrackNumber (second);
  234621. jassert (firstTrack > 0 && secondTrack > 0);
  234622. return firstTrack - secondTrack;
  234623. }
  234624. };
  234625. }
  234626. const StringArray AudioCDReader::getAvailableCDNames()
  234627. {
  234628. Array<File> cds;
  234629. CDReaderHelpers::findDevices (cds);
  234630. StringArray names;
  234631. for (int i = 0; i < cds.size(); ++i)
  234632. names.add (cds.getReference(i).getFileName());
  234633. return names;
  234634. }
  234635. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  234636. {
  234637. Array<File> cds;
  234638. CDReaderHelpers::findDevices (cds);
  234639. if (cds[index].exists())
  234640. return new AudioCDReader (cds[index]);
  234641. return 0;
  234642. }
  234643. AudioCDReader::AudioCDReader (const File& volume)
  234644. : AudioFormatReader (0, "CD Audio"),
  234645. volumeDir (volume),
  234646. currentReaderTrack (-1),
  234647. reader (0)
  234648. {
  234649. sampleRate = 44100.0;
  234650. bitsPerSample = 16;
  234651. numChannels = 2;
  234652. usesFloatingPointData = false;
  234653. refreshTrackLengths();
  234654. }
  234655. AudioCDReader::~AudioCDReader()
  234656. {
  234657. }
  234658. void AudioCDReader::refreshTrackLengths()
  234659. {
  234660. tracks.clear();
  234661. trackStartSamples.clear();
  234662. lengthInSamples = 0;
  234663. volumeDir.findChildFiles (tracks, File::findFiles | File::ignoreHiddenFiles, false, "*.aiff");
  234664. CDReaderHelpers::TrackSorter sorter;
  234665. tracks.sort (sorter);
  234666. const File toc (volumeDir.getChildFile (".TOC.plist"));
  234667. if (toc.exists())
  234668. {
  234669. XmlDocument doc (toc);
  234670. const char* error = CDReaderHelpers::getTrackOffsets (doc, trackStartSamples);
  234671. (void) error; // could be logged..
  234672. lengthInSamples = trackStartSamples.getLast() - trackStartSamples.getFirst();
  234673. }
  234674. }
  234675. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  234676. int64 startSampleInFile, int numSamples)
  234677. {
  234678. while (numSamples > 0)
  234679. {
  234680. int track = -1;
  234681. for (int i = 0; i < trackStartSamples.size() - 1; ++i)
  234682. {
  234683. if (startSampleInFile < trackStartSamples.getUnchecked (i + 1))
  234684. {
  234685. track = i;
  234686. break;
  234687. }
  234688. }
  234689. if (track < 0)
  234690. return false;
  234691. if (track != currentReaderTrack)
  234692. {
  234693. reader = 0;
  234694. FileInputStream* const in = tracks [track].createInputStream();
  234695. if (in != 0)
  234696. {
  234697. BufferedInputStream* const bin = new BufferedInputStream (in, 65536, true);
  234698. AiffAudioFormat format;
  234699. reader = format.createReaderFor (bin, true);
  234700. if (reader == 0)
  234701. currentReaderTrack = -1;
  234702. else
  234703. currentReaderTrack = track;
  234704. }
  234705. }
  234706. if (reader == 0)
  234707. return false;
  234708. const int startPos = (int) (startSampleInFile - trackStartSamples.getUnchecked (track));
  234709. const int numAvailable = (int) jmin ((int64) numSamples, reader->lengthInSamples - startPos);
  234710. reader->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer, startPos, numAvailable);
  234711. numSamples -= numAvailable;
  234712. startSampleInFile += numAvailable;
  234713. }
  234714. return true;
  234715. }
  234716. bool AudioCDReader::isCDStillPresent() const
  234717. {
  234718. return volumeDir.exists();
  234719. }
  234720. bool AudioCDReader::isTrackAudio (int trackNum) const
  234721. {
  234722. return tracks [trackNum].hasFileExtension (".aiff");
  234723. }
  234724. void AudioCDReader::enableIndexScanning (bool b)
  234725. {
  234726. // any way to do this on a Mac??
  234727. }
  234728. int AudioCDReader::getLastIndex() const
  234729. {
  234730. return 0;
  234731. }
  234732. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  234733. {
  234734. return Array <int>();
  234735. }
  234736. #endif
  234737. /*** End of inlined file: juce_mac_AudioCDReader.mm ***/
  234738. /*** Start of inlined file: juce_mac_MessageManager.mm ***/
  234739. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234740. // compiled on its own).
  234741. #if JUCE_INCLUDED_FILE
  234742. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  234743. for example having more than one juce plugin loaded into a host, then when a
  234744. method is called, the actual code that runs might actually be in a different module
  234745. than the one you expect... So any calls to library functions or statics that are
  234746. made inside obj-c methods will probably end up getting executed in a different DLL's
  234747. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  234748. To work around this insanity, I'm only allowing obj-c methods to make calls to
  234749. virtual methods of an object that's known to live inside the right module's space.
  234750. */
  234751. class AppDelegateRedirector
  234752. {
  234753. public:
  234754. AppDelegateRedirector()
  234755. {
  234756. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4
  234757. runLoop = CFRunLoopGetMain();
  234758. #else
  234759. runLoop = CFRunLoopGetCurrent();
  234760. #endif
  234761. CFRunLoopSourceContext sourceContext;
  234762. zerostruct (sourceContext);
  234763. sourceContext.info = this;
  234764. sourceContext.perform = runLoopSourceCallback;
  234765. runLoopSource = CFRunLoopSourceCreate (kCFAllocatorDefault, 1, &sourceContext);
  234766. CFRunLoopAddSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  234767. }
  234768. virtual ~AppDelegateRedirector()
  234769. {
  234770. CFRunLoopRemoveSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  234771. CFRunLoopSourceInvalidate (runLoopSource);
  234772. CFRelease (runLoopSource);
  234773. }
  234774. virtual NSApplicationTerminateReply shouldTerminate()
  234775. {
  234776. if (JUCEApplication::getInstance() != 0)
  234777. {
  234778. JUCEApplication::getInstance()->systemRequestedQuit();
  234779. if (! MessageManager::getInstance()->hasStopMessageBeenSent())
  234780. return NSTerminateCancel;
  234781. }
  234782. return NSTerminateNow;
  234783. }
  234784. virtual void willTerminate()
  234785. {
  234786. JUCEApplication::appWillTerminateByForce();
  234787. }
  234788. virtual BOOL openFile (NSString* filename)
  234789. {
  234790. if (JUCEApplication::getInstance() != 0)
  234791. {
  234792. JUCEApplication::getInstance()->anotherInstanceStarted (nsStringToJuce (filename));
  234793. return YES;
  234794. }
  234795. return NO;
  234796. }
  234797. virtual void openFiles (NSArray* filenames)
  234798. {
  234799. StringArray files;
  234800. for (unsigned int i = 0; i < [filenames count]; ++i)
  234801. {
  234802. String filename (nsStringToJuce ((NSString*) [filenames objectAtIndex: i]));
  234803. if (filename.containsChar (' '))
  234804. filename = filename.quoted('"');
  234805. files.add (filename);
  234806. }
  234807. if (files.size() > 0 && JUCEApplication::getInstance() != 0)
  234808. {
  234809. JUCEApplication::getInstance()->anotherInstanceStarted (files.joinIntoString (" "));
  234810. }
  234811. }
  234812. virtual void focusChanged()
  234813. {
  234814. juce_HandleProcessFocusChange();
  234815. }
  234816. struct CallbackMessagePayload
  234817. {
  234818. MessageCallbackFunction* function;
  234819. void* parameter;
  234820. void* volatile result;
  234821. bool volatile hasBeenExecuted;
  234822. };
  234823. virtual void performCallback (CallbackMessagePayload* pl)
  234824. {
  234825. pl->result = (*pl->function) (pl->parameter);
  234826. pl->hasBeenExecuted = true;
  234827. }
  234828. virtual void deleteSelf()
  234829. {
  234830. delete this;
  234831. }
  234832. void postMessage (Message* const m)
  234833. {
  234834. messages.add (m);
  234835. CFRunLoopSourceSignal (runLoopSource);
  234836. CFRunLoopWakeUp (runLoop);
  234837. }
  234838. private:
  234839. CFRunLoopRef runLoop;
  234840. CFRunLoopSourceRef runLoopSource;
  234841. OwnedArray <Message, CriticalSection> messages;
  234842. void runLoopCallback()
  234843. {
  234844. int numDispatched = 0;
  234845. do
  234846. {
  234847. Message* const nextMessage = messages.removeAndReturn (0);
  234848. if (nextMessage == 0)
  234849. return;
  234850. const ScopedAutoReleasePool pool;
  234851. MessageManager::getInstance()->deliverMessage (nextMessage);
  234852. } while (++numDispatched <= 4);
  234853. CFRunLoopSourceSignal (runLoopSource);
  234854. CFRunLoopWakeUp (runLoop);
  234855. }
  234856. static void runLoopSourceCallback (void* info)
  234857. {
  234858. static_cast <AppDelegateRedirector*> (info)->runLoopCallback();
  234859. }
  234860. };
  234861. END_JUCE_NAMESPACE
  234862. using namespace JUCE_NAMESPACE;
  234863. #define JuceAppDelegate MakeObjCClassName(JuceAppDelegate)
  234864. @interface JuceAppDelegate : NSObject
  234865. {
  234866. @private
  234867. id oldDelegate;
  234868. @public
  234869. AppDelegateRedirector* redirector;
  234870. }
  234871. - (JuceAppDelegate*) init;
  234872. - (void) dealloc;
  234873. - (BOOL) application: (NSApplication*) theApplication openFile: (NSString*) filename;
  234874. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames;
  234875. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app;
  234876. - (void) applicationWillTerminate: (NSNotification*) aNotification;
  234877. - (void) applicationDidBecomeActive: (NSNotification*) aNotification;
  234878. - (void) applicationDidResignActive: (NSNotification*) aNotification;
  234879. - (void) applicationWillUnhide: (NSNotification*) aNotification;
  234880. - (void) performCallback: (id) info;
  234881. - (void) dummyMethod;
  234882. @end
  234883. @implementation JuceAppDelegate
  234884. - (JuceAppDelegate*) init
  234885. {
  234886. [super init];
  234887. redirector = new AppDelegateRedirector();
  234888. NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
  234889. if (JUCEApplication::isStandaloneApp())
  234890. {
  234891. oldDelegate = [NSApp delegate];
  234892. [NSApp setDelegate: self];
  234893. }
  234894. else
  234895. {
  234896. oldDelegate = 0;
  234897. [center addObserver: self selector: @selector (applicationDidResignActive:)
  234898. name: NSApplicationDidResignActiveNotification object: NSApp];
  234899. [center addObserver: self selector: @selector (applicationDidBecomeActive:)
  234900. name: NSApplicationDidBecomeActiveNotification object: NSApp];
  234901. [center addObserver: self selector: @selector (applicationWillUnhide:)
  234902. name: NSApplicationWillUnhideNotification object: NSApp];
  234903. }
  234904. return self;
  234905. }
  234906. - (void) dealloc
  234907. {
  234908. if (oldDelegate != 0)
  234909. [NSApp setDelegate: oldDelegate];
  234910. redirector->deleteSelf();
  234911. [super dealloc];
  234912. }
  234913. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app
  234914. {
  234915. (void) app;
  234916. return redirector->shouldTerminate();
  234917. }
  234918. - (void) applicationWillTerminate: (NSNotification*) aNotification
  234919. {
  234920. (void) aNotification;
  234921. redirector->willTerminate();
  234922. }
  234923. - (BOOL) application: (NSApplication*) app openFile: (NSString*) filename
  234924. {
  234925. (void) app;
  234926. return redirector->openFile (filename);
  234927. }
  234928. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames
  234929. {
  234930. (void) sender;
  234931. return redirector->openFiles (filenames);
  234932. }
  234933. - (void) applicationDidBecomeActive: (NSNotification*) notification
  234934. {
  234935. (void) notification;
  234936. redirector->focusChanged();
  234937. }
  234938. - (void) applicationDidResignActive: (NSNotification*) notification
  234939. {
  234940. (void) notification;
  234941. redirector->focusChanged();
  234942. }
  234943. - (void) applicationWillUnhide: (NSNotification*) notification
  234944. {
  234945. (void) notification;
  234946. redirector->focusChanged();
  234947. }
  234948. - (void) performCallback: (id) info
  234949. {
  234950. if ([info isKindOfClass: [NSData class]])
  234951. {
  234952. AppDelegateRedirector::CallbackMessagePayload* pl
  234953. = (AppDelegateRedirector::CallbackMessagePayload*) [((NSData*) info) bytes];
  234954. if (pl != 0)
  234955. redirector->performCallback (pl);
  234956. }
  234957. else
  234958. {
  234959. jassertfalse; // should never get here!
  234960. }
  234961. }
  234962. - (void) dummyMethod {} // (used as a way of running a dummy thread)
  234963. @end
  234964. BEGIN_JUCE_NAMESPACE
  234965. static JuceAppDelegate* juceAppDelegate = 0;
  234966. void MessageManager::runDispatchLoop()
  234967. {
  234968. if (! quitMessagePosted) // check that the quit message wasn't already posted..
  234969. {
  234970. const ScopedAutoReleasePool pool;
  234971. // must only be called by the message thread!
  234972. jassert (isThisTheMessageThread());
  234973. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  234974. @try
  234975. {
  234976. [NSApp run];
  234977. }
  234978. @catch (NSException* e)
  234979. {
  234980. // An AppKit exception will kill the app, but at least this provides a chance to log it.,
  234981. std::runtime_error ex (std::string ("NSException: ") + [[e name] UTF8String] + ", Reason:" + [[e reason] UTF8String]);
  234982. JUCEApplication::sendUnhandledException (&ex, __FILE__, __LINE__);
  234983. }
  234984. @finally
  234985. {
  234986. }
  234987. #else
  234988. [NSApp run];
  234989. #endif
  234990. }
  234991. }
  234992. void MessageManager::stopDispatchLoop()
  234993. {
  234994. quitMessagePosted = true;
  234995. [NSApp stop: nil];
  234996. [NSApp activateIgnoringOtherApps: YES]; // (if the app is inactive, it sits there and ignores the quit request until the next time it gets activated)
  234997. [NSEvent startPeriodicEventsAfterDelay: 0 withPeriod: 0.1];
  234998. }
  234999. static bool isEventBlockedByModalComps (NSEvent* e)
  235000. {
  235001. if (Component::getNumCurrentlyModalComponents() == 0)
  235002. return false;
  235003. NSWindow* const w = [e window];
  235004. if (w == 0 || [w worksWhenModal])
  235005. return false;
  235006. bool isKey = false, isInputAttempt = false;
  235007. switch ([e type])
  235008. {
  235009. case NSKeyDown:
  235010. case NSKeyUp:
  235011. isKey = isInputAttempt = true;
  235012. break;
  235013. case NSLeftMouseDown:
  235014. case NSRightMouseDown:
  235015. case NSOtherMouseDown:
  235016. isInputAttempt = true;
  235017. break;
  235018. case NSLeftMouseDragged:
  235019. case NSRightMouseDragged:
  235020. case NSLeftMouseUp:
  235021. case NSRightMouseUp:
  235022. case NSOtherMouseUp:
  235023. case NSOtherMouseDragged:
  235024. if (Desktop::getInstance().getDraggingMouseSource(0) != 0)
  235025. return false;
  235026. break;
  235027. case NSMouseMoved:
  235028. case NSMouseEntered:
  235029. case NSMouseExited:
  235030. case NSCursorUpdate:
  235031. case NSScrollWheel:
  235032. case NSTabletPoint:
  235033. case NSTabletProximity:
  235034. break;
  235035. default:
  235036. return false;
  235037. }
  235038. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  235039. {
  235040. ComponentPeer* const peer = ComponentPeer::getPeer (i);
  235041. NSView* const compView = (NSView*) peer->getNativeHandle();
  235042. if ([compView window] == w)
  235043. {
  235044. if (isKey)
  235045. {
  235046. if (compView == [w firstResponder])
  235047. return false;
  235048. }
  235049. else
  235050. {
  235051. NSViewComponentPeer* nsViewPeer = dynamic_cast<NSViewComponentPeer*> (peer);
  235052. if ((nsViewPeer == 0 || ! nsViewPeer->isSharedWindow)
  235053. ? NSPointInRect ([e locationInWindow], NSMakeRect (0, 0, [w frame].size.width, [w frame].size.height))
  235054. : NSPointInRect ([compView convertPoint: [e locationInWindow] fromView: nil], [compView bounds]))
  235055. return false;
  235056. }
  235057. }
  235058. }
  235059. if (isInputAttempt)
  235060. {
  235061. if (! [NSApp isActive])
  235062. [NSApp activateIgnoringOtherApps: YES];
  235063. Component* const modal = Component::getCurrentlyModalComponent (0);
  235064. if (modal != 0)
  235065. modal->inputAttemptWhenModal();
  235066. }
  235067. return true;
  235068. }
  235069. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  235070. {
  235071. jassert (isThisTheMessageThread()); // must only be called by the message thread
  235072. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  235073. while (! quitMessagePosted)
  235074. {
  235075. const ScopedAutoReleasePool pool;
  235076. CFRunLoopRunInMode (kCFRunLoopDefaultMode, 0.001, true);
  235077. NSEvent* e = [NSApp nextEventMatchingMask: NSAnyEventMask
  235078. untilDate: [NSDate dateWithTimeIntervalSinceNow: 0.001]
  235079. inMode: NSDefaultRunLoopMode
  235080. dequeue: YES];
  235081. if (e != 0 && ! isEventBlockedByModalComps (e))
  235082. [NSApp sendEvent: e];
  235083. if (Time::getMillisecondCounter() >= endTime)
  235084. break;
  235085. }
  235086. return ! quitMessagePosted;
  235087. }
  235088. void MessageManager::doPlatformSpecificInitialisation()
  235089. {
  235090. if (juceAppDelegate == 0)
  235091. juceAppDelegate = [[JuceAppDelegate alloc] init];
  235092. // This launches a dummy thread, which forces Cocoa to initialise NSThreads
  235093. // correctly (needed prior to 10.5)
  235094. if (! [NSThread isMultiThreaded])
  235095. [NSThread detachNewThreadSelector: @selector (dummyMethod)
  235096. toTarget: juceAppDelegate
  235097. withObject: nil];
  235098. }
  235099. void MessageManager::doPlatformSpecificShutdown()
  235100. {
  235101. if (juceAppDelegate != 0)
  235102. {
  235103. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceAppDelegate];
  235104. [[NSNotificationCenter defaultCenter] removeObserver: juceAppDelegate];
  235105. [juceAppDelegate release];
  235106. juceAppDelegate = 0;
  235107. }
  235108. }
  235109. bool juce_postMessageToSystemQueue (Message* message)
  235110. {
  235111. juceAppDelegate->redirector->postMessage (message);
  235112. return true;
  235113. }
  235114. void MessageManager::broadcastMessage (const String& value)
  235115. {
  235116. }
  235117. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback, void* data)
  235118. {
  235119. if (isThisTheMessageThread())
  235120. {
  235121. return (*callback) (data);
  235122. }
  235123. else
  235124. {
  235125. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  235126. // deadlock because the message manager is blocked from running, so can never
  235127. // call your function..
  235128. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  235129. const ScopedAutoReleasePool pool;
  235130. AppDelegateRedirector::CallbackMessagePayload cmp;
  235131. cmp.function = callback;
  235132. cmp.parameter = data;
  235133. cmp.result = 0;
  235134. cmp.hasBeenExecuted = false;
  235135. [juceAppDelegate performSelectorOnMainThread: @selector (performCallback:)
  235136. withObject: [NSData dataWithBytesNoCopy: &cmp
  235137. length: sizeof (cmp)
  235138. freeWhenDone: NO]
  235139. waitUntilDone: YES];
  235140. return cmp.result;
  235141. }
  235142. }
  235143. #endif
  235144. /*** End of inlined file: juce_mac_MessageManager.mm ***/
  235145. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  235146. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  235147. // compiled on its own).
  235148. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  235149. #if JUCE_MAC
  235150. END_JUCE_NAMESPACE
  235151. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  235152. @interface DownloadClickDetector : NSObject
  235153. {
  235154. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  235155. }
  235156. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  235157. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  235158. request: (NSURLRequest*) request
  235159. frame: (WebFrame*) frame
  235160. decisionListener: (id<WebPolicyDecisionListener>) listener;
  235161. @end
  235162. @implementation DownloadClickDetector
  235163. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  235164. {
  235165. [super init];
  235166. ownerComponent = ownerComponent_;
  235167. return self;
  235168. }
  235169. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  235170. request: (NSURLRequest*) request
  235171. frame: (WebFrame*) frame
  235172. decisionListener: (id <WebPolicyDecisionListener>) listener
  235173. {
  235174. (void) sender;
  235175. (void) request;
  235176. (void) frame;
  235177. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  235178. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  235179. [listener use];
  235180. else
  235181. [listener ignore];
  235182. }
  235183. @end
  235184. BEGIN_JUCE_NAMESPACE
  235185. class WebBrowserComponentInternal : public NSViewComponent
  235186. {
  235187. public:
  235188. WebBrowserComponentInternal (WebBrowserComponent* owner)
  235189. {
  235190. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  235191. frameName: @""
  235192. groupName: @""];
  235193. setView (webView);
  235194. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  235195. [webView setPolicyDelegate: clickListener];
  235196. }
  235197. ~WebBrowserComponentInternal()
  235198. {
  235199. [webView setPolicyDelegate: nil];
  235200. [clickListener release];
  235201. setView (0);
  235202. }
  235203. void goToURL (const String& url,
  235204. const StringArray* headers,
  235205. const MemoryBlock* postData)
  235206. {
  235207. NSMutableURLRequest* r
  235208. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  235209. cachePolicy: NSURLRequestUseProtocolCachePolicy
  235210. timeoutInterval: 30.0];
  235211. if (postData != 0 && postData->getSize() > 0)
  235212. {
  235213. [r setHTTPMethod: @"POST"];
  235214. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  235215. length: postData->getSize()]];
  235216. }
  235217. if (headers != 0)
  235218. {
  235219. for (int i = 0; i < headers->size(); ++i)
  235220. {
  235221. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  235222. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  235223. [r setValue: juceStringToNS (headerValue)
  235224. forHTTPHeaderField: juceStringToNS (headerName)];
  235225. }
  235226. }
  235227. stop();
  235228. [[webView mainFrame] loadRequest: r];
  235229. }
  235230. void goBack()
  235231. {
  235232. [webView goBack];
  235233. }
  235234. void goForward()
  235235. {
  235236. [webView goForward];
  235237. }
  235238. void stop()
  235239. {
  235240. [webView stopLoading: nil];
  235241. }
  235242. void refresh()
  235243. {
  235244. [webView reload: nil];
  235245. }
  235246. private:
  235247. WebView* webView;
  235248. DownloadClickDetector* clickListener;
  235249. };
  235250. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  235251. : browser (0),
  235252. blankPageShown (false),
  235253. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  235254. {
  235255. setOpaque (true);
  235256. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  235257. }
  235258. WebBrowserComponent::~WebBrowserComponent()
  235259. {
  235260. deleteAndZero (browser);
  235261. }
  235262. void WebBrowserComponent::goToURL (const String& url,
  235263. const StringArray* headers,
  235264. const MemoryBlock* postData)
  235265. {
  235266. lastURL = url;
  235267. lastHeaders.clear();
  235268. if (headers != 0)
  235269. lastHeaders = *headers;
  235270. lastPostData.setSize (0);
  235271. if (postData != 0)
  235272. lastPostData = *postData;
  235273. blankPageShown = false;
  235274. browser->goToURL (url, headers, postData);
  235275. }
  235276. void WebBrowserComponent::stop()
  235277. {
  235278. browser->stop();
  235279. }
  235280. void WebBrowserComponent::goBack()
  235281. {
  235282. lastURL = String::empty;
  235283. blankPageShown = false;
  235284. browser->goBack();
  235285. }
  235286. void WebBrowserComponent::goForward()
  235287. {
  235288. lastURL = String::empty;
  235289. browser->goForward();
  235290. }
  235291. void WebBrowserComponent::refresh()
  235292. {
  235293. browser->refresh();
  235294. }
  235295. void WebBrowserComponent::paint (Graphics&)
  235296. {
  235297. }
  235298. void WebBrowserComponent::checkWindowAssociation()
  235299. {
  235300. if (isShowing())
  235301. {
  235302. if (blankPageShown)
  235303. goBack();
  235304. }
  235305. else
  235306. {
  235307. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  235308. {
  235309. // when the component becomes invisible, some stuff like flash
  235310. // carries on playing audio, so we need to force it onto a blank
  235311. // page to avoid this, (and send it back when it's made visible again).
  235312. blankPageShown = true;
  235313. browser->goToURL ("about:blank", 0, 0);
  235314. }
  235315. }
  235316. }
  235317. void WebBrowserComponent::reloadLastURL()
  235318. {
  235319. if (lastURL.isNotEmpty())
  235320. {
  235321. goToURL (lastURL, &lastHeaders, &lastPostData);
  235322. lastURL = String::empty;
  235323. }
  235324. }
  235325. void WebBrowserComponent::parentHierarchyChanged()
  235326. {
  235327. checkWindowAssociation();
  235328. }
  235329. void WebBrowserComponent::resized()
  235330. {
  235331. browser->setSize (getWidth(), getHeight());
  235332. }
  235333. void WebBrowserComponent::visibilityChanged()
  235334. {
  235335. checkWindowAssociation();
  235336. }
  235337. bool WebBrowserComponent::pageAboutToLoad (const String&)
  235338. {
  235339. return true;
  235340. }
  235341. #else
  235342. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  235343. {
  235344. }
  235345. WebBrowserComponent::~WebBrowserComponent()
  235346. {
  235347. }
  235348. void WebBrowserComponent::goToURL (const String& url,
  235349. const StringArray* headers,
  235350. const MemoryBlock* postData)
  235351. {
  235352. }
  235353. void WebBrowserComponent::stop()
  235354. {
  235355. }
  235356. void WebBrowserComponent::goBack()
  235357. {
  235358. }
  235359. void WebBrowserComponent::goForward()
  235360. {
  235361. }
  235362. void WebBrowserComponent::refresh()
  235363. {
  235364. }
  235365. void WebBrowserComponent::paint (Graphics& g)
  235366. {
  235367. }
  235368. void WebBrowserComponent::checkWindowAssociation()
  235369. {
  235370. }
  235371. void WebBrowserComponent::reloadLastURL()
  235372. {
  235373. }
  235374. void WebBrowserComponent::parentHierarchyChanged()
  235375. {
  235376. }
  235377. void WebBrowserComponent::resized()
  235378. {
  235379. }
  235380. void WebBrowserComponent::visibilityChanged()
  235381. {
  235382. }
  235383. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  235384. {
  235385. return true;
  235386. }
  235387. #endif
  235388. #endif
  235389. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  235390. /*** Start of inlined file: juce_mac_CoreAudio.cpp ***/
  235391. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  235392. // compiled on its own).
  235393. #if JUCE_INCLUDED_FILE
  235394. #ifndef JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  235395. #define JUCE_COREAUDIO_ERROR_LOGGING_ENABLED 1
  235396. #endif
  235397. #undef log
  235398. #if JUCE_COREAUDIO_LOGGING_ENABLED
  235399. #define log(a) Logger::writeToLog (a)
  235400. #else
  235401. #define log(a)
  235402. #endif
  235403. #undef OK
  235404. #if JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  235405. static bool logAnyErrors_CoreAudio (const OSStatus err, const int lineNum)
  235406. {
  235407. if (err == noErr)
  235408. return true;
  235409. Logger::writeToLog ("CoreAudio error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  235410. jassertfalse;
  235411. return false;
  235412. }
  235413. #define OK(a) logAnyErrors_CoreAudio (a, __LINE__)
  235414. #else
  235415. #define OK(a) (a == noErr)
  235416. #endif
  235417. class CoreAudioInternal : public Timer
  235418. {
  235419. public:
  235420. CoreAudioInternal (AudioDeviceID id)
  235421. : inputLatency (0),
  235422. outputLatency (0),
  235423. callback (0),
  235424. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  235425. audioProcID (0),
  235426. #endif
  235427. isSlaveDevice (false),
  235428. deviceID (id),
  235429. started (false),
  235430. sampleRate (0),
  235431. bufferSize (512),
  235432. numInputChans (0),
  235433. numOutputChans (0),
  235434. callbacksAllowed (true),
  235435. numInputChannelInfos (0),
  235436. numOutputChannelInfos (0)
  235437. {
  235438. jassert (deviceID != 0);
  235439. updateDetailsFromDevice();
  235440. AudioObjectPropertyAddress pa;
  235441. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235442. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235443. pa.mElement = kAudioObjectPropertyElementWildcard;
  235444. AudioObjectAddPropertyListener (deviceID, &pa, deviceListenerProc, this);
  235445. }
  235446. ~CoreAudioInternal()
  235447. {
  235448. AudioObjectPropertyAddress pa;
  235449. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235450. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235451. pa.mElement = kAudioObjectPropertyElementWildcard;
  235452. AudioObjectRemovePropertyListener (deviceID, &pa, deviceListenerProc, this);
  235453. stop (false);
  235454. }
  235455. void allocateTempBuffers()
  235456. {
  235457. const int tempBufSize = bufferSize + 4;
  235458. audioBuffer.calloc ((numInputChans + numOutputChans) * tempBufSize);
  235459. tempInputBuffers.calloc (numInputChans + 2);
  235460. tempOutputBuffers.calloc (numOutputChans + 2);
  235461. int i, count = 0;
  235462. for (i = 0; i < numInputChans; ++i)
  235463. tempInputBuffers[i] = audioBuffer + count++ * tempBufSize;
  235464. for (i = 0; i < numOutputChans; ++i)
  235465. tempOutputBuffers[i] = audioBuffer + count++ * tempBufSize;
  235466. }
  235467. // returns the number of actual available channels
  235468. void fillInChannelInfo (const bool input)
  235469. {
  235470. int chanNum = 0;
  235471. UInt32 size;
  235472. AudioObjectPropertyAddress pa;
  235473. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  235474. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235475. pa.mElement = kAudioObjectPropertyElementMaster;
  235476. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235477. {
  235478. HeapBlock <AudioBufferList> bufList;
  235479. bufList.calloc (size, 1);
  235480. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  235481. {
  235482. const int numStreams = bufList->mNumberBuffers;
  235483. for (int i = 0; i < numStreams; ++i)
  235484. {
  235485. const AudioBuffer& b = bufList->mBuffers[i];
  235486. for (unsigned int j = 0; j < b.mNumberChannels; ++j)
  235487. {
  235488. String name;
  235489. {
  235490. char channelName [256];
  235491. zerostruct (channelName);
  235492. UInt32 nameSize = sizeof (channelName);
  235493. UInt32 channelNum = chanNum + 1;
  235494. pa.mSelector = kAudioDevicePropertyChannelName;
  235495. if (AudioObjectGetPropertyData (deviceID, &pa, sizeof (channelNum), &channelNum, &nameSize, channelName) == noErr)
  235496. name = String::fromUTF8 (channelName, nameSize);
  235497. }
  235498. if (input)
  235499. {
  235500. if (activeInputChans[chanNum])
  235501. {
  235502. inputChannelInfo [numInputChannelInfos].streamNum = i;
  235503. inputChannelInfo [numInputChannelInfos].dataOffsetSamples = j;
  235504. inputChannelInfo [numInputChannelInfos].dataStrideSamples = b.mNumberChannels;
  235505. ++numInputChannelInfos;
  235506. }
  235507. if (name.isEmpty())
  235508. name << "Input " << (chanNum + 1);
  235509. inChanNames.add (name);
  235510. }
  235511. else
  235512. {
  235513. if (activeOutputChans[chanNum])
  235514. {
  235515. outputChannelInfo [numOutputChannelInfos].streamNum = i;
  235516. outputChannelInfo [numOutputChannelInfos].dataOffsetSamples = j;
  235517. outputChannelInfo [numOutputChannelInfos].dataStrideSamples = b.mNumberChannels;
  235518. ++numOutputChannelInfos;
  235519. }
  235520. if (name.isEmpty())
  235521. name << "Output " << (chanNum + 1);
  235522. outChanNames.add (name);
  235523. }
  235524. ++chanNum;
  235525. }
  235526. }
  235527. }
  235528. }
  235529. }
  235530. void updateDetailsFromDevice()
  235531. {
  235532. stopTimer();
  235533. if (deviceID == 0)
  235534. return;
  235535. const ScopedLock sl (callbackLock);
  235536. Float64 sr;
  235537. UInt32 size = sizeof (Float64);
  235538. AudioObjectPropertyAddress pa;
  235539. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  235540. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235541. pa.mElement = kAudioObjectPropertyElementMaster;
  235542. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &sr)))
  235543. sampleRate = sr;
  235544. UInt32 framesPerBuf;
  235545. size = sizeof (framesPerBuf);
  235546. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  235547. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &framesPerBuf)))
  235548. {
  235549. bufferSize = framesPerBuf;
  235550. allocateTempBuffers();
  235551. }
  235552. bufferSizes.clear();
  235553. pa.mSelector = kAudioDevicePropertyBufferFrameSizeRange;
  235554. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235555. {
  235556. HeapBlock <AudioValueRange> ranges;
  235557. ranges.calloc (size, 1);
  235558. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  235559. {
  235560. bufferSizes.add ((int) ranges[0].mMinimum);
  235561. for (int i = 32; i < 2048; i += 32)
  235562. {
  235563. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  235564. {
  235565. if (i >= ranges[j].mMinimum && i <= ranges[j].mMaximum)
  235566. {
  235567. bufferSizes.addIfNotAlreadyThere (i);
  235568. break;
  235569. }
  235570. }
  235571. }
  235572. if (bufferSize > 0)
  235573. bufferSizes.addIfNotAlreadyThere (bufferSize);
  235574. }
  235575. }
  235576. if (bufferSizes.size() == 0 && bufferSize > 0)
  235577. bufferSizes.add (bufferSize);
  235578. sampleRates.clear();
  235579. const double possibleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  235580. String rates;
  235581. pa.mSelector = kAudioDevicePropertyAvailableNominalSampleRates;
  235582. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235583. {
  235584. HeapBlock <AudioValueRange> ranges;
  235585. ranges.calloc (size, 1);
  235586. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  235587. {
  235588. for (int i = 0; i < numElementsInArray (possibleRates); ++i)
  235589. {
  235590. bool ok = false;
  235591. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  235592. if (possibleRates[i] >= ranges[j].mMinimum - 2 && possibleRates[i] <= ranges[j].mMaximum + 2)
  235593. ok = true;
  235594. if (ok)
  235595. {
  235596. sampleRates.add (possibleRates[i]);
  235597. rates << possibleRates[i] << ' ';
  235598. }
  235599. }
  235600. }
  235601. }
  235602. if (sampleRates.size() == 0 && sampleRate > 0)
  235603. {
  235604. sampleRates.add (sampleRate);
  235605. rates << sampleRate;
  235606. }
  235607. log ("sr: " + rates);
  235608. inputLatency = 0;
  235609. outputLatency = 0;
  235610. UInt32 lat;
  235611. size = sizeof (lat);
  235612. pa.mSelector = kAudioDevicePropertyLatency;
  235613. pa.mScope = kAudioDevicePropertyScopeInput;
  235614. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  235615. inputLatency = (int) lat;
  235616. pa.mScope = kAudioDevicePropertyScopeOutput;
  235617. size = sizeof (lat);
  235618. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  235619. outputLatency = (int) lat;
  235620. log ("lat: " + String (inputLatency) + " " + String (outputLatency));
  235621. inChanNames.clear();
  235622. outChanNames.clear();
  235623. inputChannelInfo.calloc (numInputChans + 2);
  235624. numInputChannelInfos = 0;
  235625. outputChannelInfo.calloc (numOutputChans + 2);
  235626. numOutputChannelInfos = 0;
  235627. fillInChannelInfo (true);
  235628. fillInChannelInfo (false);
  235629. }
  235630. const StringArray getSources (bool input)
  235631. {
  235632. StringArray s;
  235633. HeapBlock <OSType> types;
  235634. const int num = getAllDataSourcesForDevice (deviceID, types);
  235635. for (int i = 0; i < num; ++i)
  235636. {
  235637. AudioValueTranslation avt;
  235638. char buffer[256];
  235639. avt.mInputData = &(types[i]);
  235640. avt.mInputDataSize = sizeof (UInt32);
  235641. avt.mOutputData = buffer;
  235642. avt.mOutputDataSize = 256;
  235643. UInt32 transSize = sizeof (avt);
  235644. AudioObjectPropertyAddress pa;
  235645. pa.mSelector = kAudioDevicePropertyDataSourceNameForID;
  235646. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235647. pa.mElement = kAudioObjectPropertyElementMaster;
  235648. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &transSize, &avt)))
  235649. {
  235650. DBG (buffer);
  235651. s.add (buffer);
  235652. }
  235653. }
  235654. return s;
  235655. }
  235656. int getCurrentSourceIndex (bool input) const
  235657. {
  235658. OSType currentSourceID = 0;
  235659. UInt32 size = sizeof (currentSourceID);
  235660. int result = -1;
  235661. AudioObjectPropertyAddress pa;
  235662. pa.mSelector = kAudioDevicePropertyDataSource;
  235663. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235664. pa.mElement = kAudioObjectPropertyElementMaster;
  235665. if (deviceID != 0)
  235666. {
  235667. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &currentSourceID)))
  235668. {
  235669. HeapBlock <OSType> types;
  235670. const int num = getAllDataSourcesForDevice (deviceID, types);
  235671. for (int i = 0; i < num; ++i)
  235672. {
  235673. if (types[num] == currentSourceID)
  235674. {
  235675. result = i;
  235676. break;
  235677. }
  235678. }
  235679. }
  235680. }
  235681. return result;
  235682. }
  235683. void setCurrentSourceIndex (int index, bool input)
  235684. {
  235685. if (deviceID != 0)
  235686. {
  235687. HeapBlock <OSType> types;
  235688. const int num = getAllDataSourcesForDevice (deviceID, types);
  235689. if (((unsigned int) index) < (unsigned int) num)
  235690. {
  235691. AudioObjectPropertyAddress pa;
  235692. pa.mSelector = kAudioDevicePropertyDataSource;
  235693. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235694. pa.mElement = kAudioObjectPropertyElementMaster;
  235695. OSType typeId = types[index];
  235696. OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (typeId), &typeId));
  235697. }
  235698. }
  235699. }
  235700. const String reopen (const BigInteger& inputChannels,
  235701. const BigInteger& outputChannels,
  235702. double newSampleRate,
  235703. int bufferSizeSamples)
  235704. {
  235705. String error;
  235706. log ("CoreAudio reopen");
  235707. callbacksAllowed = false;
  235708. stopTimer();
  235709. stop (false);
  235710. activeInputChans = inputChannels;
  235711. activeInputChans.setRange (inChanNames.size(),
  235712. activeInputChans.getHighestBit() + 1 - inChanNames.size(),
  235713. false);
  235714. activeOutputChans = outputChannels;
  235715. activeOutputChans.setRange (outChanNames.size(),
  235716. activeOutputChans.getHighestBit() + 1 - outChanNames.size(),
  235717. false);
  235718. numInputChans = activeInputChans.countNumberOfSetBits();
  235719. numOutputChans = activeOutputChans.countNumberOfSetBits();
  235720. // set sample rate
  235721. AudioObjectPropertyAddress pa;
  235722. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  235723. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235724. pa.mElement = kAudioObjectPropertyElementMaster;
  235725. Float64 sr = newSampleRate;
  235726. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (sr), &sr)))
  235727. {
  235728. error = "Couldn't change sample rate";
  235729. }
  235730. else
  235731. {
  235732. // change buffer size
  235733. UInt32 framesPerBuf = bufferSizeSamples;
  235734. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  235735. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (framesPerBuf), &framesPerBuf)))
  235736. {
  235737. error = "Couldn't change buffer size";
  235738. }
  235739. else
  235740. {
  235741. // Annoyingly, after changing the rate and buffer size, some devices fail to
  235742. // correctly report their new settings until some random time in the future, so
  235743. // after calling updateDetailsFromDevice, we need to manually bodge these values
  235744. // to make sure we're using the correct numbers..
  235745. updateDetailsFromDevice();
  235746. sampleRate = newSampleRate;
  235747. bufferSize = bufferSizeSamples;
  235748. if (sampleRates.size() == 0)
  235749. error = "Device has no available sample-rates";
  235750. else if (bufferSizes.size() == 0)
  235751. error = "Device has no available buffer-sizes";
  235752. else if (inputDevice != 0)
  235753. error = inputDevice->reopen (inputChannels,
  235754. outputChannels,
  235755. newSampleRate,
  235756. bufferSizeSamples);
  235757. }
  235758. }
  235759. callbacksAllowed = true;
  235760. return error;
  235761. }
  235762. bool start (AudioIODeviceCallback* cb)
  235763. {
  235764. if (! started)
  235765. {
  235766. callback = 0;
  235767. if (deviceID != 0)
  235768. {
  235769. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  235770. if (OK (AudioDeviceAddIOProc (deviceID, audioIOProc, this)))
  235771. #else
  235772. if (OK (AudioDeviceCreateIOProcID (deviceID, audioIOProc, this, &audioProcID)))
  235773. #endif
  235774. {
  235775. if (OK (AudioDeviceStart (deviceID, audioIOProc)))
  235776. {
  235777. started = true;
  235778. }
  235779. else
  235780. {
  235781. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  235782. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  235783. #else
  235784. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  235785. audioProcID = 0;
  235786. #endif
  235787. }
  235788. }
  235789. }
  235790. }
  235791. if (started)
  235792. {
  235793. const ScopedLock sl (callbackLock);
  235794. callback = cb;
  235795. }
  235796. if (inputDevice != 0)
  235797. return started && inputDevice->start (cb);
  235798. else
  235799. return started;
  235800. }
  235801. void stop (bool leaveInterruptRunning)
  235802. {
  235803. {
  235804. const ScopedLock sl (callbackLock);
  235805. callback = 0;
  235806. }
  235807. if (started
  235808. && (deviceID != 0)
  235809. && ! leaveInterruptRunning)
  235810. {
  235811. OK (AudioDeviceStop (deviceID, audioIOProc));
  235812. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  235813. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  235814. #else
  235815. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  235816. audioProcID = 0;
  235817. #endif
  235818. started = false;
  235819. { const ScopedLock sl (callbackLock); }
  235820. // wait until it's definately stopped calling back..
  235821. for (int i = 40; --i >= 0;)
  235822. {
  235823. Thread::sleep (50);
  235824. UInt32 running = 0;
  235825. UInt32 size = sizeof (running);
  235826. AudioObjectPropertyAddress pa;
  235827. pa.mSelector = kAudioDevicePropertyDeviceIsRunning;
  235828. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235829. pa.mElement = kAudioObjectPropertyElementMaster;
  235830. OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &running));
  235831. if (running == 0)
  235832. break;
  235833. }
  235834. const ScopedLock sl (callbackLock);
  235835. }
  235836. if (inputDevice != 0)
  235837. inputDevice->stop (leaveInterruptRunning);
  235838. }
  235839. double getSampleRate() const
  235840. {
  235841. return sampleRate;
  235842. }
  235843. int getBufferSize() const
  235844. {
  235845. return bufferSize;
  235846. }
  235847. void audioCallback (const AudioBufferList* inInputData,
  235848. AudioBufferList* outOutputData)
  235849. {
  235850. int i;
  235851. const ScopedLock sl (callbackLock);
  235852. if (callback != 0)
  235853. {
  235854. if (inputDevice == 0)
  235855. {
  235856. for (i = numInputChans; --i >= 0;)
  235857. {
  235858. const CallbackDetailsForChannel& info = inputChannelInfo[i];
  235859. float* dest = tempInputBuffers [i];
  235860. const float* src = ((const float*) inInputData->mBuffers[info.streamNum].mData)
  235861. + info.dataOffsetSamples;
  235862. const int stride = info.dataStrideSamples;
  235863. if (stride != 0) // if this is zero, info is invalid
  235864. {
  235865. for (int j = bufferSize; --j >= 0;)
  235866. {
  235867. *dest++ = *src;
  235868. src += stride;
  235869. }
  235870. }
  235871. }
  235872. }
  235873. if (! isSlaveDevice)
  235874. {
  235875. if (inputDevice == 0)
  235876. {
  235877. callback->audioDeviceIOCallback (const_cast<const float**> (tempInputBuffers.getData()),
  235878. numInputChans,
  235879. tempOutputBuffers,
  235880. numOutputChans,
  235881. bufferSize);
  235882. }
  235883. else
  235884. {
  235885. jassert (inputDevice->bufferSize == bufferSize);
  235886. // Sometimes the two linked devices seem to get their callbacks in
  235887. // parallel, so we need to lock both devices to stop the input data being
  235888. // changed while inside our callback..
  235889. const ScopedLock sl2 (inputDevice->callbackLock);
  235890. callback->audioDeviceIOCallback (const_cast<const float**> (inputDevice->tempInputBuffers.getData()),
  235891. inputDevice->numInputChans,
  235892. tempOutputBuffers,
  235893. numOutputChans,
  235894. bufferSize);
  235895. }
  235896. for (i = numOutputChans; --i >= 0;)
  235897. {
  235898. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  235899. const float* src = tempOutputBuffers [i];
  235900. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  235901. + info.dataOffsetSamples;
  235902. const int stride = info.dataStrideSamples;
  235903. if (stride != 0) // if this is zero, info is invalid
  235904. {
  235905. for (int j = bufferSize; --j >= 0;)
  235906. {
  235907. *dest = *src++;
  235908. dest += stride;
  235909. }
  235910. }
  235911. }
  235912. }
  235913. }
  235914. else
  235915. {
  235916. for (i = jmin (numOutputChans, numOutputChannelInfos); --i >= 0;)
  235917. {
  235918. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  235919. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  235920. + info.dataOffsetSamples;
  235921. const int stride = info.dataStrideSamples;
  235922. if (stride != 0) // if this is zero, info is invalid
  235923. {
  235924. for (int j = bufferSize; --j >= 0;)
  235925. {
  235926. *dest = 0.0f;
  235927. dest += stride;
  235928. }
  235929. }
  235930. }
  235931. }
  235932. }
  235933. // called by callbacks
  235934. void deviceDetailsChanged()
  235935. {
  235936. if (callbacksAllowed)
  235937. startTimer (100);
  235938. }
  235939. void timerCallback()
  235940. {
  235941. stopTimer();
  235942. log ("CoreAudio device changed callback");
  235943. const double oldSampleRate = sampleRate;
  235944. const int oldBufferSize = bufferSize;
  235945. updateDetailsFromDevice();
  235946. if (oldBufferSize != bufferSize || oldSampleRate != sampleRate)
  235947. {
  235948. callbacksAllowed = false;
  235949. stop (false);
  235950. updateDetailsFromDevice();
  235951. callbacksAllowed = true;
  235952. }
  235953. }
  235954. CoreAudioInternal* getRelatedDevice() const
  235955. {
  235956. UInt32 size = 0;
  235957. ScopedPointer <CoreAudioInternal> result;
  235958. AudioObjectPropertyAddress pa;
  235959. pa.mSelector = kAudioDevicePropertyRelatedDevices;
  235960. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235961. pa.mElement = kAudioObjectPropertyElementMaster;
  235962. if (deviceID != 0
  235963. && AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size) == noErr
  235964. && size > 0)
  235965. {
  235966. HeapBlock <AudioDeviceID> devs;
  235967. devs.calloc (size, 1);
  235968. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, devs)))
  235969. {
  235970. for (unsigned int i = 0; i < size / sizeof (AudioDeviceID); ++i)
  235971. {
  235972. if (devs[i] != deviceID && devs[i] != 0)
  235973. {
  235974. result = new CoreAudioInternal (devs[i]);
  235975. const bool thisIsInput = inChanNames.size() > 0 && outChanNames.size() == 0;
  235976. const bool otherIsInput = result->inChanNames.size() > 0 && result->outChanNames.size() == 0;
  235977. if (thisIsInput != otherIsInput
  235978. || (inChanNames.size() + outChanNames.size() == 0)
  235979. || (result->inChanNames.size() + result->outChanNames.size()) == 0)
  235980. break;
  235981. result = 0;
  235982. }
  235983. }
  235984. }
  235985. }
  235986. return result.release();
  235987. }
  235988. juce_UseDebuggingNewOperator
  235989. int inputLatency, outputLatency;
  235990. BigInteger activeInputChans, activeOutputChans;
  235991. StringArray inChanNames, outChanNames;
  235992. Array <double> sampleRates;
  235993. Array <int> bufferSizes;
  235994. AudioIODeviceCallback* callback;
  235995. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  235996. AudioDeviceIOProcID audioProcID;
  235997. #endif
  235998. ScopedPointer<CoreAudioInternal> inputDevice;
  235999. bool isSlaveDevice;
  236000. private:
  236001. CriticalSection callbackLock;
  236002. AudioDeviceID deviceID;
  236003. bool started;
  236004. double sampleRate;
  236005. int bufferSize;
  236006. HeapBlock <float> audioBuffer;
  236007. int numInputChans, numOutputChans;
  236008. bool callbacksAllowed;
  236009. struct CallbackDetailsForChannel
  236010. {
  236011. int streamNum;
  236012. int dataOffsetSamples;
  236013. int dataStrideSamples;
  236014. };
  236015. int numInputChannelInfos, numOutputChannelInfos;
  236016. HeapBlock <CallbackDetailsForChannel> inputChannelInfo, outputChannelInfo;
  236017. HeapBlock <float*> tempInputBuffers, tempOutputBuffers;
  236018. CoreAudioInternal (const CoreAudioInternal&);
  236019. CoreAudioInternal& operator= (const CoreAudioInternal&);
  236020. static OSStatus audioIOProc (AudioDeviceID /*inDevice*/,
  236021. const AudioTimeStamp* /*inNow*/,
  236022. const AudioBufferList* inInputData,
  236023. const AudioTimeStamp* /*inInputTime*/,
  236024. AudioBufferList* outOutputData,
  236025. const AudioTimeStamp* /*inOutputTime*/,
  236026. void* device)
  236027. {
  236028. static_cast <CoreAudioInternal*> (device)->audioCallback (inInputData, outOutputData);
  236029. return noErr;
  236030. }
  236031. static OSStatus deviceListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  236032. {
  236033. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  236034. switch (pa->mSelector)
  236035. {
  236036. case kAudioDevicePropertyBufferSize:
  236037. case kAudioDevicePropertyBufferFrameSize:
  236038. case kAudioDevicePropertyNominalSampleRate:
  236039. case kAudioDevicePropertyStreamFormat:
  236040. case kAudioDevicePropertyDeviceIsAlive:
  236041. intern->deviceDetailsChanged();
  236042. break;
  236043. case kAudioDevicePropertyBufferSizeRange:
  236044. case kAudioDevicePropertyVolumeScalar:
  236045. case kAudioDevicePropertyMute:
  236046. case kAudioDevicePropertyPlayThru:
  236047. case kAudioDevicePropertyDataSource:
  236048. case kAudioDevicePropertyDeviceIsRunning:
  236049. break;
  236050. }
  236051. return noErr;
  236052. }
  236053. static int getAllDataSourcesForDevice (AudioDeviceID deviceID, HeapBlock <OSType>& types)
  236054. {
  236055. AudioObjectPropertyAddress pa;
  236056. pa.mSelector = kAudioDevicePropertyDataSources;
  236057. pa.mScope = kAudioObjectPropertyScopeWildcard;
  236058. pa.mElement = kAudioObjectPropertyElementMaster;
  236059. UInt32 size = 0;
  236060. if (deviceID != 0
  236061. && OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  236062. {
  236063. types.calloc (size, 1);
  236064. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, types)))
  236065. return size / (int) sizeof (OSType);
  236066. }
  236067. return 0;
  236068. }
  236069. };
  236070. class CoreAudioIODevice : public AudioIODevice
  236071. {
  236072. public:
  236073. CoreAudioIODevice (const String& deviceName,
  236074. AudioDeviceID inputDeviceId,
  236075. const int inputIndex_,
  236076. AudioDeviceID outputDeviceId,
  236077. const int outputIndex_)
  236078. : AudioIODevice (deviceName, "CoreAudio"),
  236079. inputIndex (inputIndex_),
  236080. outputIndex (outputIndex_),
  236081. isOpen_ (false),
  236082. isStarted (false)
  236083. {
  236084. CoreAudioInternal* device = 0;
  236085. if (outputDeviceId == 0 || outputDeviceId == inputDeviceId)
  236086. {
  236087. jassert (inputDeviceId != 0);
  236088. device = new CoreAudioInternal (inputDeviceId);
  236089. }
  236090. else
  236091. {
  236092. device = new CoreAudioInternal (outputDeviceId);
  236093. if (inputDeviceId != 0)
  236094. {
  236095. CoreAudioInternal* secondDevice = new CoreAudioInternal (inputDeviceId);
  236096. device->inputDevice = secondDevice;
  236097. secondDevice->isSlaveDevice = true;
  236098. }
  236099. }
  236100. internal = device;
  236101. AudioObjectPropertyAddress pa;
  236102. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  236103. pa.mScope = kAudioObjectPropertyScopeWildcard;
  236104. pa.mElement = kAudioObjectPropertyElementWildcard;
  236105. AudioObjectAddPropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  236106. }
  236107. ~CoreAudioIODevice()
  236108. {
  236109. AudioObjectPropertyAddress pa;
  236110. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  236111. pa.mScope = kAudioObjectPropertyScopeWildcard;
  236112. pa.mElement = kAudioObjectPropertyElementWildcard;
  236113. AudioObjectRemovePropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  236114. }
  236115. const StringArray getOutputChannelNames()
  236116. {
  236117. return internal->outChanNames;
  236118. }
  236119. const StringArray getInputChannelNames()
  236120. {
  236121. if (internal->inputDevice != 0)
  236122. return internal->inputDevice->inChanNames;
  236123. else
  236124. return internal->inChanNames;
  236125. }
  236126. int getNumSampleRates()
  236127. {
  236128. return internal->sampleRates.size();
  236129. }
  236130. double getSampleRate (int index)
  236131. {
  236132. return internal->sampleRates [index];
  236133. }
  236134. int getNumBufferSizesAvailable()
  236135. {
  236136. return internal->bufferSizes.size();
  236137. }
  236138. int getBufferSizeSamples (int index)
  236139. {
  236140. return internal->bufferSizes [index];
  236141. }
  236142. int getDefaultBufferSize()
  236143. {
  236144. for (int i = 0; i < getNumBufferSizesAvailable(); ++i)
  236145. if (getBufferSizeSamples(i) >= 512)
  236146. return getBufferSizeSamples(i);
  236147. return 512;
  236148. }
  236149. const String open (const BigInteger& inputChannels,
  236150. const BigInteger& outputChannels,
  236151. double sampleRate,
  236152. int bufferSizeSamples)
  236153. {
  236154. isOpen_ = true;
  236155. if (bufferSizeSamples <= 0)
  236156. bufferSizeSamples = getDefaultBufferSize();
  236157. lastError = internal->reopen (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  236158. isOpen_ = lastError.isEmpty();
  236159. return lastError;
  236160. }
  236161. void close()
  236162. {
  236163. isOpen_ = false;
  236164. internal->stop (false);
  236165. }
  236166. bool isOpen()
  236167. {
  236168. return isOpen_;
  236169. }
  236170. int getCurrentBufferSizeSamples()
  236171. {
  236172. return internal != 0 ? internal->getBufferSize() : 512;
  236173. }
  236174. double getCurrentSampleRate()
  236175. {
  236176. return internal != 0 ? internal->getSampleRate() : 0;
  236177. }
  236178. int getCurrentBitDepth()
  236179. {
  236180. return 32; // no way to find out, so just assume it's high..
  236181. }
  236182. const BigInteger getActiveOutputChannels() const
  236183. {
  236184. return internal != 0 ? internal->activeOutputChans : BigInteger();
  236185. }
  236186. const BigInteger getActiveInputChannels() const
  236187. {
  236188. BigInteger chans;
  236189. if (internal != 0)
  236190. {
  236191. chans = internal->activeInputChans;
  236192. if (internal->inputDevice != 0)
  236193. chans |= internal->inputDevice->activeInputChans;
  236194. }
  236195. return chans;
  236196. }
  236197. int getOutputLatencyInSamples()
  236198. {
  236199. if (internal == 0)
  236200. return 0;
  236201. // this seems like a good guess at getting the latency right - comparing
  236202. // this with a round-trip measurement, it gets it to within a few millisecs
  236203. // for the built-in mac soundcard
  236204. return internal->outputLatency + internal->getBufferSize() * 2;
  236205. }
  236206. int getInputLatencyInSamples()
  236207. {
  236208. if (internal == 0)
  236209. return 0;
  236210. return internal->inputLatency + internal->getBufferSize() * 2;
  236211. }
  236212. void start (AudioIODeviceCallback* callback)
  236213. {
  236214. if (internal != 0 && ! isStarted)
  236215. {
  236216. if (callback != 0)
  236217. callback->audioDeviceAboutToStart (this);
  236218. isStarted = true;
  236219. internal->start (callback);
  236220. }
  236221. }
  236222. void stop()
  236223. {
  236224. if (isStarted && internal != 0)
  236225. {
  236226. AudioIODeviceCallback* const lastCallback = internal->callback;
  236227. isStarted = false;
  236228. internal->stop (true);
  236229. if (lastCallback != 0)
  236230. lastCallback->audioDeviceStopped();
  236231. }
  236232. }
  236233. bool isPlaying()
  236234. {
  236235. if (internal->callback == 0)
  236236. isStarted = false;
  236237. return isStarted;
  236238. }
  236239. const String getLastError()
  236240. {
  236241. return lastError;
  236242. }
  236243. int inputIndex, outputIndex;
  236244. juce_UseDebuggingNewOperator
  236245. private:
  236246. ScopedPointer<CoreAudioInternal> internal;
  236247. bool isOpen_, isStarted;
  236248. String lastError;
  236249. static OSStatus hardwareListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  236250. {
  236251. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  236252. switch (pa->mSelector)
  236253. {
  236254. case kAudioHardwarePropertyDevices:
  236255. intern->deviceDetailsChanged();
  236256. break;
  236257. case kAudioHardwarePropertyDefaultOutputDevice:
  236258. case kAudioHardwarePropertyDefaultInputDevice:
  236259. case kAudioHardwarePropertyDefaultSystemOutputDevice:
  236260. break;
  236261. }
  236262. return noErr;
  236263. }
  236264. CoreAudioIODevice (const CoreAudioIODevice&);
  236265. CoreAudioIODevice& operator= (const CoreAudioIODevice&);
  236266. };
  236267. class CoreAudioIODeviceType : public AudioIODeviceType
  236268. {
  236269. public:
  236270. CoreAudioIODeviceType()
  236271. : AudioIODeviceType ("CoreAudio"),
  236272. hasScanned (false)
  236273. {
  236274. }
  236275. ~CoreAudioIODeviceType()
  236276. {
  236277. }
  236278. void scanForDevices()
  236279. {
  236280. hasScanned = true;
  236281. inputDeviceNames.clear();
  236282. outputDeviceNames.clear();
  236283. inputIds.clear();
  236284. outputIds.clear();
  236285. UInt32 size;
  236286. AudioObjectPropertyAddress pa;
  236287. pa.mSelector = kAudioHardwarePropertyDevices;
  236288. pa.mScope = kAudioObjectPropertyScopeWildcard;
  236289. pa.mElement = kAudioObjectPropertyElementMaster;
  236290. if (OK (AudioObjectGetPropertyDataSize (kAudioObjectSystemObject, &pa, 0, 0, &size)))
  236291. {
  236292. HeapBlock <AudioDeviceID> devs;
  236293. devs.calloc (size, 1);
  236294. if (OK (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, devs)))
  236295. {
  236296. const int num = size / (int) sizeof (AudioDeviceID);
  236297. for (int i = 0; i < num; ++i)
  236298. {
  236299. char name [1024];
  236300. size = sizeof (name);
  236301. pa.mSelector = kAudioDevicePropertyDeviceName;
  236302. if (OK (AudioObjectGetPropertyData (devs[i], &pa, 0, 0, &size, name)))
  236303. {
  236304. const String nameString (String::fromUTF8 (name, (int) strlen (name)));
  236305. const int numIns = getNumChannels (devs[i], true);
  236306. const int numOuts = getNumChannels (devs[i], false);
  236307. if (numIns > 0)
  236308. {
  236309. inputDeviceNames.add (nameString);
  236310. inputIds.add (devs[i]);
  236311. }
  236312. if (numOuts > 0)
  236313. {
  236314. outputDeviceNames.add (nameString);
  236315. outputIds.add (devs[i]);
  236316. }
  236317. }
  236318. }
  236319. }
  236320. }
  236321. inputDeviceNames.appendNumbersToDuplicates (false, true);
  236322. outputDeviceNames.appendNumbersToDuplicates (false, true);
  236323. }
  236324. const StringArray getDeviceNames (bool wantInputNames) const
  236325. {
  236326. jassert (hasScanned); // need to call scanForDevices() before doing this
  236327. if (wantInputNames)
  236328. return inputDeviceNames;
  236329. else
  236330. return outputDeviceNames;
  236331. }
  236332. int getDefaultDeviceIndex (bool forInput) const
  236333. {
  236334. jassert (hasScanned); // need to call scanForDevices() before doing this
  236335. AudioDeviceID deviceID;
  236336. UInt32 size = sizeof (deviceID);
  236337. // if they're asking for any input channels at all, use the default input, so we
  236338. // get the built-in mic rather than the built-in output with no inputs..
  236339. AudioObjectPropertyAddress pa;
  236340. pa.mSelector = forInput ? kAudioHardwarePropertyDefaultInputDevice : kAudioHardwarePropertyDefaultOutputDevice;
  236341. pa.mScope = kAudioObjectPropertyScopeWildcard;
  236342. pa.mElement = kAudioObjectPropertyElementMaster;
  236343. if (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, &deviceID) == noErr)
  236344. {
  236345. if (forInput)
  236346. {
  236347. for (int i = inputIds.size(); --i >= 0;)
  236348. if (inputIds[i] == deviceID)
  236349. return i;
  236350. }
  236351. else
  236352. {
  236353. for (int i = outputIds.size(); --i >= 0;)
  236354. if (outputIds[i] == deviceID)
  236355. return i;
  236356. }
  236357. }
  236358. return 0;
  236359. }
  236360. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  236361. {
  236362. jassert (hasScanned); // need to call scanForDevices() before doing this
  236363. CoreAudioIODevice* const d = dynamic_cast <CoreAudioIODevice*> (device);
  236364. if (d == 0)
  236365. return -1;
  236366. return asInput ? d->inputIndex
  236367. : d->outputIndex;
  236368. }
  236369. bool hasSeparateInputsAndOutputs() const { return true; }
  236370. AudioIODevice* createDevice (const String& outputDeviceName,
  236371. const String& inputDeviceName)
  236372. {
  236373. jassert (hasScanned); // need to call scanForDevices() before doing this
  236374. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  236375. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  236376. String deviceName (outputDeviceName);
  236377. if (deviceName.isEmpty())
  236378. deviceName = inputDeviceName;
  236379. if (index >= 0)
  236380. return new CoreAudioIODevice (deviceName,
  236381. inputIds [inputIndex],
  236382. inputIndex,
  236383. outputIds [outputIndex],
  236384. outputIndex);
  236385. return 0;
  236386. }
  236387. juce_UseDebuggingNewOperator
  236388. private:
  236389. StringArray inputDeviceNames, outputDeviceNames;
  236390. Array <AudioDeviceID> inputIds, outputIds;
  236391. bool hasScanned;
  236392. static int getNumChannels (AudioDeviceID deviceID, bool input)
  236393. {
  236394. int total = 0;
  236395. UInt32 size;
  236396. AudioObjectPropertyAddress pa;
  236397. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  236398. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  236399. pa.mElement = kAudioObjectPropertyElementMaster;
  236400. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  236401. {
  236402. HeapBlock <AudioBufferList> bufList;
  236403. bufList.calloc (size, 1);
  236404. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  236405. {
  236406. const int numStreams = bufList->mNumberBuffers;
  236407. for (int i = 0; i < numStreams; ++i)
  236408. {
  236409. const AudioBuffer& b = bufList->mBuffers[i];
  236410. total += b.mNumberChannels;
  236411. }
  236412. }
  236413. }
  236414. return total;
  236415. }
  236416. CoreAudioIODeviceType (const CoreAudioIODeviceType&);
  236417. CoreAudioIODeviceType& operator= (const CoreAudioIODeviceType&);
  236418. };
  236419. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio()
  236420. {
  236421. return new CoreAudioIODeviceType();
  236422. }
  236423. #undef log
  236424. #endif
  236425. /*** End of inlined file: juce_mac_CoreAudio.cpp ***/
  236426. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  236427. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  236428. // compiled on its own).
  236429. #if JUCE_INCLUDED_FILE
  236430. #if JUCE_MAC
  236431. namespace CoreMidiHelpers
  236432. {
  236433. static bool logError (const OSStatus err, const int lineNum)
  236434. {
  236435. if (err == noErr)
  236436. return true;
  236437. Logger::writeToLog ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  236438. jassertfalse;
  236439. return false;
  236440. }
  236441. #undef CHECK_ERROR
  236442. #define CHECK_ERROR(a) CoreMidiHelpers::logError (a, __LINE__)
  236443. static const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  236444. {
  236445. String result;
  236446. CFStringRef str = 0;
  236447. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  236448. if (str != 0)
  236449. {
  236450. result = PlatformUtilities::cfStringToJuceString (str);
  236451. CFRelease (str);
  236452. str = 0;
  236453. }
  236454. MIDIEntityRef entity = 0;
  236455. MIDIEndpointGetEntity (endpoint, &entity);
  236456. if (entity == 0)
  236457. return result; // probably virtual
  236458. if (result.isEmpty())
  236459. {
  236460. // endpoint name has zero length - try the entity
  236461. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  236462. if (str != 0)
  236463. {
  236464. result += PlatformUtilities::cfStringToJuceString (str);
  236465. CFRelease (str);
  236466. str = 0;
  236467. }
  236468. }
  236469. // now consider the device's name
  236470. MIDIDeviceRef device = 0;
  236471. MIDIEntityGetDevice (entity, &device);
  236472. if (device == 0)
  236473. return result;
  236474. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  236475. if (str != 0)
  236476. {
  236477. const String s (PlatformUtilities::cfStringToJuceString (str));
  236478. CFRelease (str);
  236479. // if an external device has only one entity, throw away
  236480. // the endpoint name and just use the device name
  236481. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  236482. {
  236483. result = s;
  236484. }
  236485. else if (! result.startsWithIgnoreCase (s))
  236486. {
  236487. // prepend the device name to the entity name
  236488. result = (s + " " + result).trimEnd();
  236489. }
  236490. }
  236491. return result;
  236492. }
  236493. static const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  236494. {
  236495. String result;
  236496. // Does the endpoint have connections?
  236497. CFDataRef connections = 0;
  236498. int numConnections = 0;
  236499. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  236500. if (connections != 0)
  236501. {
  236502. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  236503. if (numConnections > 0)
  236504. {
  236505. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  236506. for (int i = 0; i < numConnections; ++i, ++pid)
  236507. {
  236508. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  236509. MIDIObjectRef connObject;
  236510. MIDIObjectType connObjectType;
  236511. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  236512. if (err == noErr)
  236513. {
  236514. String s;
  236515. if (connObjectType == kMIDIObjectType_ExternalSource
  236516. || connObjectType == kMIDIObjectType_ExternalDestination)
  236517. {
  236518. // Connected to an external device's endpoint (10.3 and later).
  236519. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  236520. }
  236521. else
  236522. {
  236523. // Connected to an external device (10.2) (or something else, catch-all)
  236524. CFStringRef str = 0;
  236525. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  236526. if (str != 0)
  236527. {
  236528. s = PlatformUtilities::cfStringToJuceString (str);
  236529. CFRelease (str);
  236530. }
  236531. }
  236532. if (s.isNotEmpty())
  236533. {
  236534. if (result.isNotEmpty())
  236535. result += ", ";
  236536. result += s;
  236537. }
  236538. }
  236539. }
  236540. }
  236541. CFRelease (connections);
  236542. }
  236543. if (result.isNotEmpty())
  236544. return result;
  236545. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  236546. return getEndpointName (endpoint, false);
  236547. }
  236548. static MIDIClientRef getGlobalMidiClient()
  236549. {
  236550. static MIDIClientRef globalMidiClient = 0;
  236551. if (globalMidiClient == 0)
  236552. {
  236553. String name ("JUCE");
  236554. if (JUCEApplication::getInstance() != 0)
  236555. name = JUCEApplication::getInstance()->getApplicationName();
  236556. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  236557. CHECK_ERROR (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  236558. CFRelease (appName);
  236559. }
  236560. return globalMidiClient;
  236561. }
  236562. class MidiPortAndEndpoint
  236563. {
  236564. public:
  236565. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  236566. : port (port_), endPoint (endPoint_)
  236567. {
  236568. }
  236569. ~MidiPortAndEndpoint()
  236570. {
  236571. if (port != 0)
  236572. MIDIPortDispose (port);
  236573. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  236574. MIDIEndpointDispose (endPoint);
  236575. }
  236576. void send (const MIDIPacketList* const packets)
  236577. {
  236578. if (port != 0)
  236579. MIDISend (port, endPoint, packets);
  236580. else
  236581. MIDIReceived (endPoint, packets);
  236582. }
  236583. MIDIPortRef port;
  236584. MIDIEndpointRef endPoint;
  236585. };
  236586. class MidiPortAndCallback;
  236587. static CriticalSection callbackLock;
  236588. static Array<MidiPortAndCallback*> activeCallbacks;
  236589. class MidiPortAndCallback
  236590. {
  236591. public:
  236592. MidiPortAndCallback (MidiInputCallback& callback_)
  236593. : input (0), active (false), callback (callback_), concatenator (2048)
  236594. {
  236595. }
  236596. ~MidiPortAndCallback()
  236597. {
  236598. active = false;
  236599. {
  236600. const ScopedLock sl (callbackLock);
  236601. activeCallbacks.removeValue (this);
  236602. }
  236603. if (portAndEndpoint != 0 && portAndEndpoint->port != 0)
  236604. CHECK_ERROR (MIDIPortDisconnectSource (portAndEndpoint->port, portAndEndpoint->endPoint));
  236605. }
  236606. void handlePackets (const MIDIPacketList* const pktlist)
  236607. {
  236608. const double time = Time::getMillisecondCounterHiRes() * 0.001;
  236609. const ScopedLock sl (callbackLock);
  236610. if (activeCallbacks.contains (this) && active)
  236611. {
  236612. const MIDIPacket* packet = &pktlist->packet[0];
  236613. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  236614. {
  236615. concatenator.pushMidiData (packet->data, (int) packet->length, time,
  236616. input, callback);
  236617. packet = MIDIPacketNext (packet);
  236618. }
  236619. }
  236620. }
  236621. MidiInput* input;
  236622. ScopedPointer<MidiPortAndEndpoint> portAndEndpoint;
  236623. volatile bool active;
  236624. private:
  236625. MidiInputCallback& callback;
  236626. MidiDataConcatenator concatenator;
  236627. };
  236628. static void midiInputProc (const MIDIPacketList* pktlist, void* readProcRefCon, void* /*srcConnRefCon*/)
  236629. {
  236630. static_cast <MidiPortAndCallback*> (readProcRefCon)->handlePackets (pktlist);
  236631. }
  236632. }
  236633. const StringArray MidiOutput::getDevices()
  236634. {
  236635. StringArray s;
  236636. const ItemCount num = MIDIGetNumberOfDestinations();
  236637. for (ItemCount i = 0; i < num; ++i)
  236638. {
  236639. MIDIEndpointRef dest = MIDIGetDestination (i);
  236640. if (dest != 0)
  236641. {
  236642. String name (CoreMidiHelpers::getConnectedEndpointName (dest));
  236643. if (name.isEmpty())
  236644. name = "<error>";
  236645. s.add (name);
  236646. }
  236647. else
  236648. {
  236649. s.add ("<error>");
  236650. }
  236651. }
  236652. return s;
  236653. }
  236654. int MidiOutput::getDefaultDeviceIndex()
  236655. {
  236656. return 0;
  236657. }
  236658. MidiOutput* MidiOutput::openDevice (int index)
  236659. {
  236660. MidiOutput* mo = 0;
  236661. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfDestinations())
  236662. {
  236663. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  236664. CFStringRef pname;
  236665. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  236666. {
  236667. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  236668. MIDIPortRef port;
  236669. if (client != 0 && CHECK_ERROR (MIDIOutputPortCreate (client, pname, &port)))
  236670. {
  236671. mo = new MidiOutput();
  236672. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (port, endPoint);
  236673. }
  236674. CFRelease (pname);
  236675. }
  236676. }
  236677. return mo;
  236678. }
  236679. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  236680. {
  236681. MidiOutput* mo = 0;
  236682. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  236683. MIDIEndpointRef endPoint;
  236684. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  236685. if (client != 0 && CHECK_ERROR (MIDISourceCreate (client, name, &endPoint)))
  236686. {
  236687. mo = new MidiOutput();
  236688. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (0, endPoint);
  236689. }
  236690. CFRelease (name);
  236691. return mo;
  236692. }
  236693. MidiOutput::~MidiOutput()
  236694. {
  236695. delete static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  236696. }
  236697. void MidiOutput::reset()
  236698. {
  236699. }
  236700. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  236701. {
  236702. return false;
  236703. }
  236704. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  236705. {
  236706. }
  236707. void MidiOutput::sendMessageNow (const MidiMessage& message)
  236708. {
  236709. CoreMidiHelpers::MidiPortAndEndpoint* const mpe = static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  236710. if (message.isSysEx())
  236711. {
  236712. const int maxPacketSize = 256;
  236713. int pos = 0, bytesLeft = message.getRawDataSize();
  236714. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  236715. HeapBlock <MIDIPacketList> packets;
  236716. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  236717. packets->numPackets = numPackets;
  236718. MIDIPacket* p = packets->packet;
  236719. for (int i = 0; i < numPackets; ++i)
  236720. {
  236721. p->timeStamp = 0;
  236722. p->length = jmin (maxPacketSize, bytesLeft);
  236723. memcpy (p->data, message.getRawData() + pos, p->length);
  236724. pos += p->length;
  236725. bytesLeft -= p->length;
  236726. p = MIDIPacketNext (p);
  236727. }
  236728. mpe->send (packets);
  236729. }
  236730. else
  236731. {
  236732. MIDIPacketList packets;
  236733. packets.numPackets = 1;
  236734. packets.packet[0].timeStamp = 0;
  236735. packets.packet[0].length = message.getRawDataSize();
  236736. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  236737. mpe->send (&packets);
  236738. }
  236739. }
  236740. const StringArray MidiInput::getDevices()
  236741. {
  236742. StringArray s;
  236743. const ItemCount num = MIDIGetNumberOfSources();
  236744. for (ItemCount i = 0; i < num; ++i)
  236745. {
  236746. MIDIEndpointRef source = MIDIGetSource (i);
  236747. if (source != 0)
  236748. {
  236749. String name (CoreMidiHelpers::getConnectedEndpointName (source));
  236750. if (name.isEmpty())
  236751. name = "<error>";
  236752. s.add (name);
  236753. }
  236754. else
  236755. {
  236756. s.add ("<error>");
  236757. }
  236758. }
  236759. return s;
  236760. }
  236761. int MidiInput::getDefaultDeviceIndex()
  236762. {
  236763. return 0;
  236764. }
  236765. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  236766. {
  236767. jassert (callback != 0);
  236768. using namespace CoreMidiHelpers;
  236769. MidiInput* newInput = 0;
  236770. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfSources())
  236771. {
  236772. MIDIEndpointRef endPoint = MIDIGetSource (index);
  236773. if (endPoint != 0)
  236774. {
  236775. CFStringRef name;
  236776. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &name)))
  236777. {
  236778. MIDIClientRef client = getGlobalMidiClient();
  236779. if (client != 0)
  236780. {
  236781. MIDIPortRef port;
  236782. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  236783. if (CHECK_ERROR (MIDIInputPortCreate (client, name, midiInputProc, mpc, &port)))
  236784. {
  236785. if (CHECK_ERROR (MIDIPortConnectSource (port, endPoint, 0)))
  236786. {
  236787. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  236788. newInput = new MidiInput (getDevices() [index]);
  236789. mpc->input = newInput;
  236790. newInput->internal = mpc;
  236791. const ScopedLock sl (callbackLock);
  236792. activeCallbacks.add (mpc.release());
  236793. }
  236794. else
  236795. {
  236796. CHECK_ERROR (MIDIPortDispose (port));
  236797. }
  236798. }
  236799. }
  236800. }
  236801. CFRelease (name);
  236802. }
  236803. }
  236804. return newInput;
  236805. }
  236806. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  236807. {
  236808. jassert (callback != 0);
  236809. using namespace CoreMidiHelpers;
  236810. MidiInput* mi = 0;
  236811. MIDIClientRef client = getGlobalMidiClient();
  236812. if (client != 0)
  236813. {
  236814. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  236815. mpc->active = false;
  236816. MIDIEndpointRef endPoint;
  236817. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  236818. if (CHECK_ERROR (MIDIDestinationCreate (client, name, midiInputProc, mpc, &endPoint)))
  236819. {
  236820. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  236821. mi = new MidiInput (deviceName);
  236822. mpc->input = mi;
  236823. mi->internal = mpc;
  236824. const ScopedLock sl (callbackLock);
  236825. activeCallbacks.add (mpc.release());
  236826. }
  236827. CFRelease (name);
  236828. }
  236829. return mi;
  236830. }
  236831. MidiInput::MidiInput (const String& name_)
  236832. : name (name_)
  236833. {
  236834. }
  236835. MidiInput::~MidiInput()
  236836. {
  236837. delete static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal);
  236838. }
  236839. void MidiInput::start()
  236840. {
  236841. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  236842. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = true;
  236843. }
  236844. void MidiInput::stop()
  236845. {
  236846. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  236847. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = false;
  236848. }
  236849. #undef CHECK_ERROR
  236850. #else // Stubs for iOS...
  236851. MidiOutput::~MidiOutput() {}
  236852. void MidiOutput::reset() {}
  236853. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/) { return false; }
  236854. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/) {}
  236855. void MidiOutput::sendMessageNow (const MidiMessage& message) {}
  236856. const StringArray MidiOutput::getDevices() { return StringArray(); }
  236857. MidiOutput* MidiOutput::openDevice (int index) { return 0; }
  236858. const StringArray MidiInput::getDevices() { return StringArray(); }
  236859. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback) { return 0; }
  236860. #endif
  236861. #endif
  236862. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  236863. /*** Start of inlined file: juce_mac_CameraDevice.mm ***/
  236864. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  236865. // compiled on its own).
  236866. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  236867. #if ! JUCE_QUICKTIME
  236868. #error "On the Mac, cameras use Quicktime, so if you turn on JUCE_USE_CAMERA, you also need to enable JUCE_QUICKTIME"
  236869. #endif
  236870. #define QTCaptureCallbackDelegate MakeObjCClassName(QTCaptureCallbackDelegate)
  236871. class QTCameraDeviceInteral;
  236872. END_JUCE_NAMESPACE
  236873. @interface QTCaptureCallbackDelegate : NSObject
  236874. {
  236875. @public
  236876. CameraDevice* owner;
  236877. QTCameraDeviceInteral* internal;
  236878. int64 firstPresentationTime;
  236879. int64 averageTimeOffset;
  236880. }
  236881. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner internalDev: (QTCameraDeviceInteral*) d;
  236882. - (void) dealloc;
  236883. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  236884. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  236885. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236886. fromConnection: (QTCaptureConnection*) connection;
  236887. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  236888. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236889. fromConnection: (QTCaptureConnection*) connection;
  236890. @end
  236891. BEGIN_JUCE_NAMESPACE
  236892. class QTCameraDeviceInteral
  236893. {
  236894. public:
  236895. QTCameraDeviceInteral (CameraDevice* owner, int index)
  236896. {
  236897. const ScopedAutoReleasePool pool;
  236898. session = [[QTCaptureSession alloc] init];
  236899. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  236900. device = (QTCaptureDevice*) [devs objectAtIndex: index];
  236901. input = 0;
  236902. audioInput = 0;
  236903. audioDevice = 0;
  236904. fileOutput = 0;
  236905. imageOutput = 0;
  236906. callbackDelegate = [[QTCaptureCallbackDelegate alloc] initWithOwner: owner
  236907. internalDev: this];
  236908. NSError* err = 0;
  236909. [device retain];
  236910. [device open: &err];
  236911. if (err == 0)
  236912. {
  236913. input = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  236914. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  236915. [session addInput: input error: &err];
  236916. if (err == 0)
  236917. {
  236918. resetFile();
  236919. imageOutput = [[QTCaptureDecompressedVideoOutput alloc] init];
  236920. [imageOutput setDelegate: callbackDelegate];
  236921. if (err == 0)
  236922. {
  236923. [session startRunning];
  236924. return;
  236925. }
  236926. }
  236927. }
  236928. openingError = nsStringToJuce ([err description]);
  236929. DBG (openingError);
  236930. }
  236931. ~QTCameraDeviceInteral()
  236932. {
  236933. [session stopRunning];
  236934. [session removeOutput: imageOutput];
  236935. [session release];
  236936. [input release];
  236937. [device release];
  236938. [audioDevice release];
  236939. [audioInput release];
  236940. [fileOutput release];
  236941. [imageOutput release];
  236942. [callbackDelegate release];
  236943. }
  236944. void resetFile()
  236945. {
  236946. [fileOutput recordToOutputFileURL: nil];
  236947. [session removeOutput: fileOutput];
  236948. [fileOutput release];
  236949. fileOutput = [[QTCaptureMovieFileOutput alloc] init];
  236950. [session removeInput: audioInput];
  236951. [audioInput release];
  236952. audioInput = 0;
  236953. [audioDevice release];
  236954. audioDevice = 0;
  236955. [fileOutput setDelegate: callbackDelegate];
  236956. }
  236957. void addDefaultAudioInput()
  236958. {
  236959. NSError* err = nil;
  236960. audioDevice = [QTCaptureDevice defaultInputDeviceWithMediaType: QTMediaTypeSound];
  236961. if ([audioDevice open: &err])
  236962. [audioDevice retain];
  236963. else
  236964. audioDevice = nil;
  236965. if (audioDevice != 0)
  236966. {
  236967. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: audioDevice];
  236968. [session addInput: audioInput error: &err];
  236969. }
  236970. }
  236971. void addListener (CameraDevice::Listener* listenerToAdd)
  236972. {
  236973. const ScopedLock sl (listenerLock);
  236974. if (listeners.size() == 0)
  236975. [session addOutput: imageOutput error: nil];
  236976. listeners.addIfNotAlreadyThere (listenerToAdd);
  236977. }
  236978. void removeListener (CameraDevice::Listener* listenerToRemove)
  236979. {
  236980. const ScopedLock sl (listenerLock);
  236981. listeners.removeValue (listenerToRemove);
  236982. if (listeners.size() == 0)
  236983. [session removeOutput: imageOutput];
  236984. }
  236985. void callListeners (CIImage* frame, int w, int h)
  236986. {
  236987. CoreGraphicsImage* cgImage = new CoreGraphicsImage (Image::ARGB, w, h, false);
  236988. Image image (cgImage);
  236989. CIContext* cic = [CIContext contextWithCGContext: cgImage->context options: nil];
  236990. [cic drawImage: frame inRect: CGRectMake (0, 0, w, h) fromRect: CGRectMake (0, 0, w, h)];
  236991. CGContextFlush (cgImage->context);
  236992. const ScopedLock sl (listenerLock);
  236993. for (int i = listeners.size(); --i >= 0;)
  236994. {
  236995. CameraDevice::Listener* const l = listeners[i];
  236996. if (l != 0)
  236997. l->imageReceived (image);
  236998. }
  236999. }
  237000. QTCaptureDevice* device;
  237001. QTCaptureDeviceInput* input;
  237002. QTCaptureDevice* audioDevice;
  237003. QTCaptureDeviceInput* audioInput;
  237004. QTCaptureSession* session;
  237005. QTCaptureMovieFileOutput* fileOutput;
  237006. QTCaptureDecompressedVideoOutput* imageOutput;
  237007. QTCaptureCallbackDelegate* callbackDelegate;
  237008. String openingError;
  237009. Array<CameraDevice::Listener*> listeners;
  237010. CriticalSection listenerLock;
  237011. };
  237012. END_JUCE_NAMESPACE
  237013. @implementation QTCaptureCallbackDelegate
  237014. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner_
  237015. internalDev: (QTCameraDeviceInteral*) d
  237016. {
  237017. [super init];
  237018. owner = owner_;
  237019. internal = d;
  237020. firstPresentationTime = 0;
  237021. averageTimeOffset = 0;
  237022. return self;
  237023. }
  237024. - (void) dealloc
  237025. {
  237026. [super dealloc];
  237027. }
  237028. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  237029. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  237030. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  237031. fromConnection: (QTCaptureConnection*) connection
  237032. {
  237033. if (internal->listeners.size() > 0)
  237034. {
  237035. const ScopedAutoReleasePool pool;
  237036. internal->callListeners ([CIImage imageWithCVImageBuffer: videoFrame],
  237037. CVPixelBufferGetWidth (videoFrame),
  237038. CVPixelBufferGetHeight (videoFrame));
  237039. }
  237040. }
  237041. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  237042. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  237043. fromConnection: (QTCaptureConnection*) connection
  237044. {
  237045. const Time now (Time::getCurrentTime());
  237046. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  237047. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: QTSampleBufferHostTimeAttribute];
  237048. #else
  237049. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: @"hostTime"];
  237050. #endif
  237051. int64 presentationTime = (hosttime != nil)
  237052. ? ((int64) AudioConvertHostTimeToNanos ([hosttime unsignedLongLongValue]) / 1000000 + 40)
  237053. : (([sampleBuffer presentationTime].timeValue * 1000) / [sampleBuffer presentationTime].timeScale + 50);
  237054. const int64 timeDiff = now.toMilliseconds() - presentationTime;
  237055. if (firstPresentationTime == 0)
  237056. {
  237057. firstPresentationTime = presentationTime;
  237058. averageTimeOffset = timeDiff;
  237059. }
  237060. else
  237061. {
  237062. averageTimeOffset = (averageTimeOffset * 120 + timeDiff * 8) / 128;
  237063. }
  237064. }
  237065. @end
  237066. BEGIN_JUCE_NAMESPACE
  237067. class QTCaptureViewerComp : public NSViewComponent
  237068. {
  237069. public:
  237070. QTCaptureViewerComp (CameraDevice* const cameraDevice, QTCameraDeviceInteral* const internal)
  237071. {
  237072. const ScopedAutoReleasePool pool;
  237073. captureView = [[QTCaptureView alloc] init];
  237074. [captureView setCaptureSession: internal->session];
  237075. setSize (640, 480); // xxx need to somehow get the movie size - how?
  237076. setView (captureView);
  237077. }
  237078. ~QTCaptureViewerComp()
  237079. {
  237080. setView (0);
  237081. [captureView setCaptureSession: nil];
  237082. [captureView release];
  237083. }
  237084. QTCaptureView* captureView;
  237085. };
  237086. CameraDevice::CameraDevice (const String& name_, int index)
  237087. : name (name_)
  237088. {
  237089. isRecording = false;
  237090. internal = new QTCameraDeviceInteral (this, index);
  237091. }
  237092. CameraDevice::~CameraDevice()
  237093. {
  237094. stopRecording();
  237095. delete static_cast <QTCameraDeviceInteral*> (internal);
  237096. internal = 0;
  237097. }
  237098. Component* CameraDevice::createViewerComponent()
  237099. {
  237100. return new QTCaptureViewerComp (this, static_cast <QTCameraDeviceInteral*> (internal));
  237101. }
  237102. const String CameraDevice::getFileExtension()
  237103. {
  237104. return ".mov";
  237105. }
  237106. void CameraDevice::startRecordingToFile (const File& file, int quality)
  237107. {
  237108. stopRecording();
  237109. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  237110. d->callbackDelegate->firstPresentationTime = 0;
  237111. file.deleteFile();
  237112. // In some versions of QT (e.g. on 10.5), if you record video without audio, the speed comes
  237113. // out wrong, so we'll put some audio in there too..,
  237114. d->addDefaultAudioInput();
  237115. [d->session addOutput: d->fileOutput error: nil];
  237116. NSEnumerator* connectionEnumerator = [[d->fileOutput connections] objectEnumerator];
  237117. for (;;)
  237118. {
  237119. QTCaptureConnection* connection = [connectionEnumerator nextObject];
  237120. if (connection == 0)
  237121. break;
  237122. QTCompressionOptions* options = 0;
  237123. NSString* mediaType = [connection mediaType];
  237124. if ([mediaType isEqualToString: QTMediaTypeVideo])
  237125. options = [QTCompressionOptions compressionOptionsWithIdentifier:
  237126. quality >= 1 ? @"QTCompressionOptionsSD480SizeH264Video"
  237127. : @"QTCompressionOptions240SizeH264Video"];
  237128. else if ([mediaType isEqualToString: QTMediaTypeSound])
  237129. options = [QTCompressionOptions compressionOptionsWithIdentifier: @"QTCompressionOptionsHighQualityAACAudio"];
  237130. [d->fileOutput setCompressionOptions: options forConnection: connection];
  237131. }
  237132. [d->fileOutput recordToOutputFileURL: [NSURL fileURLWithPath: juceStringToNS (file.getFullPathName())]];
  237133. isRecording = true;
  237134. }
  237135. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  237136. {
  237137. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  237138. if (d->callbackDelegate->firstPresentationTime != 0)
  237139. return Time (d->callbackDelegate->firstPresentationTime + d->callbackDelegate->averageTimeOffset);
  237140. return Time();
  237141. }
  237142. void CameraDevice::stopRecording()
  237143. {
  237144. if (isRecording)
  237145. {
  237146. static_cast <QTCameraDeviceInteral*> (internal)->resetFile();
  237147. isRecording = false;
  237148. }
  237149. }
  237150. void CameraDevice::addListener (Listener* listenerToAdd)
  237151. {
  237152. if (listenerToAdd != 0)
  237153. static_cast <QTCameraDeviceInteral*> (internal)->addListener (listenerToAdd);
  237154. }
  237155. void CameraDevice::removeListener (Listener* listenerToRemove)
  237156. {
  237157. if (listenerToRemove != 0)
  237158. static_cast <QTCameraDeviceInteral*> (internal)->removeListener (listenerToRemove);
  237159. }
  237160. const StringArray CameraDevice::getAvailableDevices()
  237161. {
  237162. const ScopedAutoReleasePool pool;
  237163. StringArray results;
  237164. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  237165. for (int i = 0; i < (int) [devs count]; ++i)
  237166. {
  237167. QTCaptureDevice* dev = (QTCaptureDevice*) [devs objectAtIndex: i];
  237168. results.add (nsStringToJuce ([dev localizedDisplayName]));
  237169. }
  237170. return results;
  237171. }
  237172. CameraDevice* CameraDevice::openDevice (int index,
  237173. int minWidth, int minHeight,
  237174. int maxWidth, int maxHeight)
  237175. {
  237176. ScopedPointer <CameraDevice> d (new CameraDevice (getAvailableDevices() [index], index));
  237177. if (static_cast <QTCameraDeviceInteral*> (d->internal)->openingError.isEmpty())
  237178. return d.release();
  237179. return 0;
  237180. }
  237181. #endif
  237182. /*** End of inlined file: juce_mac_CameraDevice.mm ***/
  237183. #endif
  237184. #endif
  237185. END_JUCE_NAMESPACE
  237186. #endif
  237187. /*** End of inlined file: juce_mac_NativeCode.mm ***/
  237188. #endif
  237189. #endif